package protocol
import (
"crypto/rand"
"errors"
"fmt"
"io"
)
var ErrInvalidConnectionIDLen = errors .New ("invalid Connection ID length" )
type ArbitraryLenConnectionID []byte
func (c ArbitraryLenConnectionID ) Len () int {
return len (c )
}
func (c ArbitraryLenConnectionID ) Bytes () []byte {
return c
}
func (c ArbitraryLenConnectionID ) String () string {
if c .Len () == 0 {
return "(empty)"
}
return fmt .Sprintf ("%x" , c .Bytes ())
}
const maxConnectionIDLen = 20
type ConnectionID struct {
b [20 ]byte
l uint8
}
func GenerateConnectionID (l int ) (ConnectionID , error ) {
var c ConnectionID
c .l = uint8 (l )
_ , err := rand .Read (c .b [:l ])
return c , err
}
func ParseConnectionID (b []byte ) ConnectionID {
if len (b ) > maxConnectionIDLen {
panic ("invalid conn id length" )
}
var c ConnectionID
c .l = uint8 (len (b ))
copy (c .b [:c .l ], b )
return c
}
func GenerateConnectionIDForInitial () (ConnectionID , error ) {
r := make ([]byte , 1 )
if _ , err := rand .Read (r ); err != nil {
return ConnectionID {}, err
}
l := MinConnectionIDLenInitial + int (r [0 ])%(maxConnectionIDLen -MinConnectionIDLenInitial +1 )
return GenerateConnectionID (l )
}
func ReadConnectionID (r io .Reader , l int ) (ConnectionID , error ) {
var c ConnectionID
if l == 0 {
return c , nil
}
if l > maxConnectionIDLen {
return c , ErrInvalidConnectionIDLen
}
c .l = uint8 (l )
_ , err := io .ReadFull (r , c .b [:l ])
if err == io .ErrUnexpectedEOF {
return c , io .EOF
}
return c , err
}
func (c ConnectionID ) Len () int {
return int (c .l )
}
func (c ConnectionID ) Bytes () []byte {
return c .b [:c .l ]
}
func (c ConnectionID ) String () string {
if c .Len () == 0 {
return "(empty)"
}
return fmt .Sprintf ("%x" , c .Bytes ())
}
type DefaultConnectionIDGenerator struct {
ConnLen int
}
func (d *DefaultConnectionIDGenerator ) GenerateConnectionID () (ConnectionID , error ) {
return GenerateConnectionID (d .ConnLen )
}
func (d *DefaultConnectionIDGenerator ) ConnectionIDLen () int {
return d .ConnLen
}
The pages are generated with Golds v0.8.2 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .