-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencode.go
43 lines (36 loc) · 858 Bytes
/
encode.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
package runlength
import (
"io"
"github.com/pkg/errors"
)
type Encoder struct {
out io.Writer
}
func (e *Encoder) Encode(data []byte) error {
currentValue := data[0]
currentLength := byte(1)
for i := 1; i < len(data); i += 1 {
out := true
if currentValue == data[i] {
out = false
currentLength += 1
if 255 <= currentLength {
out = true
}
}
if out {
if _, err := e.out.Write([]byte{currentLength, currentValue}); err != nil {
return errors.Wrapf(err, "failed to write data:%d %v", currentLength, currentValue)
}
currentLength = 1
currentValue = data[i]
}
}
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}
}