-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbitvector_marshal.go
More file actions
63 lines (53 loc) · 1.81 KB
/
bitvector_marshal.go
File metadata and controls
63 lines (53 loc) · 1.81 KB
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
58
59
60
61
62
63
package bbhash
import (
"encoding/binary"
"errors"
"fmt"
)
const (
uint32bytes = 4
uint64bytes = 8
)
// marshaledLength returns the number of bytes needed to marshal the bit vector.
func (b bitVector) marshaledLength() int {
// 4 bytes for the number of words in the bit vector
return uint32bytes + uint64bytes*len(b)
}
// AppendBinary implements the [encoding.BinaryAppender] interface.
func (b bitVector) AppendBinary(buf []byte) ([]byte, error) {
// append the number of words needed for this bit vector to the buffer
buf = binary.LittleEndian.AppendUint32(buf, b.words())
// append the bit vector entries to the buffer
for _, v := range b {
buf = binary.LittleEndian.AppendUint64(buf, v)
}
return buf, nil
}
// MarshalBinary implements the [encoding.BinaryMarshaler] interface.
func (b bitVector) MarshalBinary() ([]byte, error) {
return b.AppendBinary(make([]byte, 0, b.marshaledLength()))
}
// UnmarshalBinary implements the [encoding.BinaryUnmarshaler] interface.
func (b *bitVector) UnmarshalBinary(data []byte) error {
// Make a copy of data, since we will be modifying buf's slice indices
buf := data
if len(buf) < uint32bytes {
return errors.New("bitVector.UnmarshalBinary: no data")
}
// Read the number of words in the bit vector
words := binary.LittleEndian.Uint32(buf[:uint32bytes])
if words == 0 || words > (1<<32)-1 {
return fmt.Errorf("bitVector.UnmarshalBinary: invalid bit vector length %d (max %d)", words, 1<<32)
}
buf = buf[uint32bytes:] // move past header
*b = make(bitVector, words) // modify b in place
// Read the bit vector entries
for i := range words {
if len(buf) < uint64bytes {
return errors.New("bitVector.UnmarshalBinary: insufficient data for bit vector entry")
}
(*b)[i] = binary.LittleEndian.Uint64(buf[:uint64bytes])
buf = buf[uint64bytes:]
}
return nil
}