-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencode.go
More file actions
40 lines (33 loc) · 846 Bytes
/
Copy pathencode.go
File metadata and controls
40 lines (33 loc) · 846 Bytes
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
package runlength
import (
"io"
"github.com/pkg/errors"
)
type Encoder struct {
out io.Writer
}
func (e *Encoder) Encode(data []byte) error {
if len(data) < 1 {
return nil
}
currentValue := data[0]
currentLength := byte(1)
for i := 1; i < len(data); i += 1 {
if data[i] != currentValue || currentLength == 255 {
if _, err := e.out.Write([]byte{currentLength, currentValue}); err != nil {
return errors.Wrapf(err, "failed to write data: len=%d, val=%v", currentLength, currentValue)
}
currentValue = data[i]
currentLength = 1
} else {
currentLength += 1
}
}
if _, err := e.out.Write([]byte{currentLength, currentValue}); err != nil {
return errors.Wrapf(err, "failed to write data:%d %v", currentLength, currentValue)
}
return nil
}
func NewEncoder(out io.Writer) *Encoder {
return &Encoder{out}
}