package codec import ( "bufio" "io" ) const DefaultFirstByte = 0xab type XorEncoder struct { wr io.Writer wb *bufio.Writer last byte } func (x *XorEncoder) Write(p []byte) (n int, err error) { var next byte for _, v := range p { next = v ^ x.last x.last = next err = x.wb.WriteByte(next) if err != nil { return } n = n + 1 } err = x.wb.Flush() return } func NewXorEncoder(wr io.Writer, first byte) *XorEncoder { return &XorEncoder{ wr: wr, wb: bufio.NewWriter(wr), last: first, } } type XorDecoder struct { rd io.Reader last byte } func (x *XorDecoder) Read(p []byte) (n int, err error) { n, err = x.rd.Read(p) if err != nil { return n, err } var next byte for idx := 0; idx < n; idx++ { next = p[idx] p[idx] ^= x.last x.last = next } return n, nil } func NewXorDecoder(rd io.Reader, first byte) *XorDecoder { return &XorDecoder{ rd: rd, last: first, } }