gitlab.com/jokerrs1/Sia@v1.3.2/modules/renter/erasure.go (about) 1 package renter 2 3 import ( 4 "io" 5 6 "github.com/klauspost/reedsolomon" 7 8 "github.com/NebulousLabs/Sia/modules" 9 ) 10 11 // rsCode is a Reed-Solomon encoder/decoder. It implements the 12 // modules.ErasureCoder interface. 13 type rsCode struct { 14 enc reedsolomon.Encoder 15 16 numPieces int 17 dataPieces int 18 } 19 20 // NumPieces returns the number of pieces returned by Encode. 21 func (rs *rsCode) NumPieces() int { return rs.numPieces } 22 23 // MinPieces return the minimum number of pieces that must be present to 24 // recover the original data. 25 func (rs *rsCode) MinPieces() int { return rs.dataPieces } 26 27 // Encode splits data into equal-length pieces, some containing the original 28 // data and some containing parity data. 29 func (rs *rsCode) Encode(data []byte) ([][]byte, error) { 30 pieces, err := rs.enc.Split(data) 31 if err != nil { 32 return nil, err 33 } 34 // err should not be possible if Encode is called on the result of Split, 35 // but no harm in checking anyway. 36 err = rs.enc.Encode(pieces) 37 if err != nil { 38 return nil, err 39 } 40 return pieces, nil 41 } 42 43 // Recover recovers the original data from pieces and writes it to w. 44 // pieces should be identical to the slice returned by Encode (length and 45 // order must be preserved), but with missing elements set to nil. 46 func (rs *rsCode) Recover(pieces [][]byte, n uint64, w io.Writer) error { 47 err := rs.enc.ReconstructData(pieces) 48 if err != nil { 49 return err 50 } 51 return rs.enc.Join(w, pieces, int(n)) 52 } 53 54 // NewRSCode creates a new Reed-Solomon encoder/decoder using the supplied 55 // parameters. 56 func NewRSCode(nData, nParity int) (modules.ErasureCoder, error) { 57 enc, err := reedsolomon.New(nData, nParity) 58 if err != nil { 59 return nil, err 60 } 61 return &rsCode{ 62 enc: enc, 63 numPieces: nData + nParity, 64 dataPieces: nData, 65 }, nil 66 }