-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathvarnum.go
57 lines (52 loc) · 1.38 KB
/
varnum.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
49
50
51
52
53
54
55
56
57
// Package tlv implements NDN Type-Length-Value (TLV) encoding.
package tlv
import (
"encoding/binary"
"math"
)
// VarNum represents a number in variable size encoding for TLV-TYPE or TLV-LENGTH.
type VarNum uint64
// Size returns the wire encoding size.
func (n VarNum) Size() int {
switch {
case n < 0xFD:
return 1
case n <= math.MaxUint16:
return 3
case n <= math.MaxUint32:
return 5
default:
return 9
}
}
// Encode appends this number to a buffer.
func (n VarNum) Encode(b []byte) []byte {
switch {
case n < 0xFD:
return append(b, byte(n))
case n <= math.MaxUint16:
return binary.BigEndian.AppendUint16(append(b, 0xFD), uint16(n))
case n <= math.MaxUint32:
return binary.BigEndian.AppendUint32(append(b, 0xFE), uint32(n))
default:
return binary.BigEndian.AppendUint64(append(b, 0xFF), uint64(n))
}
}
// Decode extracts a VarNum from the buffer.
func (n *VarNum) Decode(wire []byte) (rest []byte, e error) {
switch {
case len(wire) >= 1 && wire[0] < 0xFD:
*n = VarNum(wire[0])
return wire[1:], nil
case len(wire) >= 3 && wire[0] == 0xFD:
*n = VarNum(binary.BigEndian.Uint16(wire[1:]))
return wire[3:], nil
case len(wire) >= 5 && wire[0] == 0xFE:
*n = VarNum(binary.BigEndian.Uint32(wire[1:]))
return wire[5:], nil
case len(wire) >= 9 && wire[0] == 0xFF:
*n = VarNum(binary.BigEndian.Uint64(wire[1:]))
return wire[9:], nil
}
return nil, ErrIncomplete
}