-
Notifications
You must be signed in to change notification settings - Fork 44
/
helper.go
48 lines (35 loc) · 978 Bytes
/
helper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package packet
import (
"fmt"
bnet "github.com/bio-routing/bio-rd/net"
)
func serializePrefix(pfx bnet.Prefix) []byte {
if pfx.Pfxlen() == 0 {
return []byte{}
}
numBytes := BytesInAddr(pfx.Pfxlen())
b := make([]byte, numBytes+1)
b[0] = pfx.Pfxlen()
copy(b[1:numBytes+1], pfx.Addr().Bytes()[0:numBytes])
return b
}
func deserializePrefix(b []byte, pfxLen uint8, afi uint16) (*bnet.Prefix, error) {
numBytes := BytesInAddr(pfxLen)
if numBytes != uint8(len(b)) {
return nil, fmt.Errorf("could not parse prefix of length %d. Expected %d bytes, got %d", pfxLen, numBytes, len(b))
}
if afi == IPv4AFI {
return bnet.NewPfx(bnet.IPv4FromBytes(b), pfxLen).Dedup(), nil
}
ipBytes := make([]byte, afiAddrLenBytes[afi])
copy(ipBytes, b)
ip, err := bnet.IPFromBytes(ipBytes)
if err != nil {
return nil, err
}
pfx := bnet.NewPfx(ip, pfxLen)
if !pfx.Valid() {
return nil, fmt.Errorf("Invalid prefix: %q", pfx.String())
}
return pfx.Dedup(), nil
}