github.com/hoffie/larasync@v0.0.0-20151025221940-0384d2bddcef/helpers/bincontainer/encoder.go (about) 1 package bincontainer 2 3 import ( 4 "encoding/binary" 5 "io" 6 ) 7 8 // Encoder can write arbitrary binary chunks into a Writer in a way that they can be 9 // separated again later by a Decoder. 10 // NOTE: a maximum length of 2**32 (~4GB) is supported. 11 type Encoder struct { 12 w io.Writer 13 } 14 15 // NewEncoder returns a new encoder reference. 16 func NewEncoder(w io.Writer) *Encoder { 17 return &Encoder{w: w} 18 } 19 20 // WriteChunk forwards the given bytes to the underlying writer, prefixed by the 21 // length. 22 func (e *Encoder) WriteChunk(chunk []byte) error { 23 err := e.writeLength(len(chunk)) 24 if err != nil { 25 return err 26 } 27 _, err = e.w.Write(chunk) 28 return err 29 } 30 31 // writeLength writes the given length to the underlying writer. 32 func (e *Encoder) writeLength(length int) error { 33 binLength := make([]byte, lengthSpecSize) 34 binary.LittleEndian.PutUint32(binLength, uint32(length)) 35 36 _, err := e.w.Write(binLength) 37 return err 38 }