-
Notifications
You must be signed in to change notification settings - Fork 5
/
rle.go
93 lines (76 loc) · 2.04 KB
/
rle.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package bitfield
import (
"bytes"
"encoding/binary"
)
func Encode(data []byte) ([]byte, bool) {
dataLength := len(data)
encodedData := []byte{}
if dataLength <= 1 {
return data, false
}
currentRunByte := data[0]
var currentRunLength int64 = 0
for i, b := range data {
byteMatch := b == currentRunByte
atLastByte := i == dataLength-1
// continued byte match, but end of the encoded data
if byteMatch && atLastByte {
currentRunLength++
encodedData = appendByteCount(encodedData, currentRunLength, currentRunByte)
break
}
// continued byte match, still more encoded data to iterate through
if byteMatch {
currentRunLength++
continue
}
// end of the encoded data where the last byte is different than the previous byte
if atLastByte {
encodedData = appendByteCount(encodedData, currentRunLength, currentRunByte)
currentRunByte = b
currentRunLength = 1
encodedData = appendByteCount(encodedData, currentRunLength, currentRunByte)
break
}
// different byte found with more encoded data to process
encodedData = appendByteCount(encodedData, currentRunLength, currentRunByte)
currentRunByte = b
currentRunLength = 1
}
if len(encodedData) >= len(data) {
return data, false
}
return encodedData, true
}
func Decode(encoded []byte) ([]byte, error) {
if len(encoded) == 0 {
return []byte{}, nil
}
decoded := bytes.NewBuffer([]byte{})
bufReader := bytes.NewReader(encoded)
for bufReader.Len() > 0 {
count, err := binary.ReadVarint(bufReader)
if err != nil {
return nil, err
}
charByte, err := bufReader.ReadByte()
if err != nil {
return nil, err
}
for n := int64(0); n < count; n++ {
if err := decoded.WriteByte(charByte); err != nil {
return nil, err
}
}
}
return decoded.Bytes(), nil
}
func appendByteCount(slice []byte, count int64, elem byte) []byte {
crlBuf := make([]byte, binary.MaxVarintLen64)
bytesWritten := binary.PutVarint(crlBuf, count)
crlBuf = crlBuf[:bytesWritten]
crlBuf = append(crlBuf, elem)
slice = append(slice, crlBuf...)
return slice
}