-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencoder.go
54 lines (45 loc) · 940 Bytes
/
encoder.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
package klv
import (
"errors"
"io"
)
var (
ErrPartialWrite = errors.New("partial write")
ErrKeyTooLong = errors.New("key is too long")
)
type Encoder interface {
Encode(chunks Chunks) (err error)
}
type encoder struct {
w io.Writer
keyLength uint
}
func NewEncoder(w io.Writer, keyLength uint) Encoder {
return &encoder{
w: w,
keyLength: keyLength,
}
}
func (e *encoder) Encode(chunks Chunks) error {
for _, chunk := range chunks {
buf := []byte{}
delta := int(e.keyLength - uint(len(chunk.Key)))
if delta < 0 {
return ErrKeyTooLong
} else if delta > 0 {
pad := make([]byte, delta)
chunk.Key = append(chunk.Key, pad...)
}
buf = append(buf, chunk.Key...)
buf = append(buf, BerEncodeChunk(len(chunk.Value))...)
buf = append(buf, chunk.Value...)
n, err := e.w.Write(buf)
if err != nil {
return err
}
if n != len(buf) {
return ErrPartialWrite
}
}
return nil
}