add more methods to the protocol.ConnectionID

This will make it easier to change the underlying type of the connection
ID (potentially an array is faster than a byte slice).
This commit is contained in:
Marten Seemann
2018-04-19 08:47:43 +09:00
parent 74ccd194f7
commit d47124d14d
8 changed files with 124 additions and 47 deletions

View File

@@ -3,6 +3,8 @@ package protocol
import (
"bytes"
"crypto/rand"
"fmt"
"io"
)
// A ConnectionID in QUIC
@@ -17,7 +19,38 @@ func GenerateConnectionID() (ConnectionID, error) {
return ConnectionID(b), nil
}
// ReadConnectionID reads a connection ID of length len from the given io.Reader.
// It returns io.EOF if there are not enough bytes to read.
func ReadConnectionID(r io.Reader, len int) (ConnectionID, error) {
if len == 0 {
return nil, nil
}
c := make(ConnectionID, len)
_, err := io.ReadFull(r, c)
if err == io.ErrUnexpectedEOF {
return nil, io.EOF
}
return c, err
}
// Equal says if two connection IDs are equal
func (c ConnectionID) Equal(other ConnectionID) bool {
return bytes.Equal(c, other)
}
// Len returns the length of the connection ID in bytes
func (c ConnectionID) Len() int {
return len(c)
}
// Bytes returns the byte representation
func (c ConnectionID) Bytes() []byte {
return []byte(c)
}
func (c ConnectionID) String() string {
if c.Len() == 0 {
return "(empty)"
}
return fmt.Sprintf("%#x", c.Bytes())
}