-
Notifications
You must be signed in to change notification settings - Fork 7
/
UnpackControlWords.go
46 lines (41 loc) · 1.06 KB
/
UnpackControlWords.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
package compression
import (
"bytes"
"encoding/binary"
)
// UnpackControlWords reads from an encoded string of bytes a series of packed control words.
// If all is OK, the control words are returned. If the function returns an error, something
// could not be read/decoded properly.
func UnpackControlWords(data []byte) (words []ControlWord, err error) {
if len(data) < 4 {
return nil, ErrFormat
}
var controlBytes uint32
reader := bytes.NewReader(data)
err = binary.Read(reader, binary.LittleEndian, &controlBytes)
if err != nil {
return
}
if controlBytes%bytesPerControlWord != 0 {
return nil, ErrFormat
}
wordCount := int(controlBytes / bytesPerControlWord)
unpacked := 0
words = make([]ControlWord, wordCount)
for unpacked < wordCount {
var packed PackedControlWord
err = binary.Read(reader, binary.LittleEndian, &packed)
if err != nil {
return
}
times := packed.Times()
if times > len(words)-unpacked {
return nil, ErrFormat
}
for i := 0; i < times; i++ {
words[unpacked+i] = packed.Value()
}
unpacked += times
}
return
}