-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoder.go
47 lines (42 loc) · 854 Bytes
/
encoder.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
package rs
import (
"github.com/klauspost/reedsolomon"
"io"
)
type encoder struct {
writers []io.Writer
enc reedsolomon.Encoder
cache []byte
}
func NewEncoder(writers []io.Writer) *encoder {
enc, _ := reedsolomon.New(DATA_SHARDS, PARITY_SHARDS)
return &encoder{writers, enc, nil}
}
func (e *encoder) Write(p []byte) (n int, err error) {
length := len(p)
current := 0
for length != 0 {
next := BLOCK_SIZE - len(e.cache)
if next > length {
next = length
}
e.cache = append(e.cache, p[current:current+next]...)
if len(e.cache) == BLOCK_SIZE {
e.Flush()
}
current += next
length -= next
}
return len(p), nil
}
func (e *encoder) Flush() {
if len(e.cache) == 0 {
return
}
shards, _ := e.enc.Split(e.cache)
e.enc.Encode(shards)
for i := range shards {
e.writers[i].Write(shards[i])
}
e.cache = []byte{}
}