-
Notifications
You must be signed in to change notification settings - Fork 0
/
rs.go
65 lines (58 loc) · 1.09 KB
/
rs.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
// Package reedsolomon provides a Reed-Solomon erasure code.
package reedsolomon
import (
"errors"
"github.com/klauspost/reedsolomon"
)
type Code struct {
enc reedsolomon.Encoder
data, tot int
}
func New(data, parity int) (*Code, error) {
enc, err := reedsolomon.New(data, parity)
if err != nil {
return nil, err
}
return &Code{
enc: enc,
tot: data + parity,
data: data,
}, nil
}
func (c *Code) Encode(p []byte) ([][]byte, error) {
bs, err := c.enc.Split(p)
if err != nil {
return nil, err
}
if err := c.enc.Encode(bs); err != nil {
return nil, err
}
return bs, nil
}
func (c *Code) Decode(bs [][]byte) ([]byte, error) {
var redo bool
for i := range bs[:c.data] {
if bs[i] == nil {
redo = true
break
}
}
if redo {
if err := c.enc.Reconstruct(bs); err != nil {
return nil, err
}
ok, err := c.enc.Verify(bs)
if err != nil {
return nil, err
}
if !ok {
return nil, errors.New("dataset doesn't verify")
}
}
var b []byte
for i := range bs[:c.data] {
b = append(b, bs[i]...)
}
return b, nil
}
func (c *Code) Shards() int { return c.tot }