-
Notifications
You must be signed in to change notification settings - Fork 26
/
encoding.go
51 lines (42 loc) · 1.2 KB
/
encoding.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
// Package slp implements "shallow length prefixed" data. Each element in a slice is prefixed by a uint16 for it's length.
package slp
import (
"encoding/binary"
"fmt"
"math"
)
// encodeUint16 encodes a uint16 with little-endian encoding,
// appends it to out returns the result.
func encodeUint16(out []byte, l uint16) []byte {
var buf [2]byte
binary.LittleEndian.PutUint16(buf[:], l)
return append(out, buf[:]...)
}
// Encode appends the SLP-encoding of a list to out
// and returns the resulting slice.
func Encode(list ...[]byte) ([]byte, error) {
var out []byte
for i, elem := range list {
elemLen := len(elem)
if elemLen > math.MaxUint16 {
return nil, fmt.Errorf("slp: element %d (%q) is too long", i, elem)
}
out = encodeUint16(out, uint16(elemLen))
out = append(out, elem...)
}
return out, nil
}
// Decode turns an SLP input into a slice of byte slices
func Decode(input []byte) [][]byte {
var out [][]byte
for len(input) > 0 {
// read the length of the current entry
entryLen := binary.LittleEndian.Uint16(input[:2])
// splice of the first two bytes
input = input[2:]
// cut of the current entry
out = append(out, input[:entryLen])
input = input[entryLen:]
}
return out
}