Documentation
¶
Overview ¶
Package codec provides a simple interface for encoding and decoding data.
It is based around the io.ReaderFrom and io.WriterTo interfaces to allow for easy transfer of data between a source and destination using arbitrary encodings.
The encoding and decoding functions are implemented as io.Writer and io.Reader, respectively. In order to support a new encoding, you must implement the Encoder and Decoder interfaces, i.e., you must provide a way to create a new io.Writer and io.Reader for the encoding.
Example:
- Define an Encoder:
type myEncoder struct { w io.Writer } func (m *myEncoder) Write(p []byte) (n int, err error) { // In practice, you would transform the input data // before writing it to the underlying writer. return m.w.Write(p) }
- Define a Decoder:
type myDecoder struct { r io.Reader } func (m *myDecoder) Read(p []byte) (n int, err error) { // Read at most len(p) data := make([]byte, len(p)) n, err = m.r.Read(data) if err != nil { return n, err } // In practice, you would transform the input data // before writing it to the underlying writer. copy(p, data[:n]) return n, nil }
- Define an Encoding struct
type myEncoding struct{} func (e *myEncoding) NewWriter(w io.Writer) (io.WriteCloser, error) { return &myEncoder{w}, nil } func (e *myEncoding) NewReader(r io.Reader) (io.ReadCloser, error) { return &myDecoder{r}, nil } // Verify that myEncoding implements the Encoding interface var ( _ Encoding = &myEncoding{} )
- Now you're good to go:
func doSomething(src io.WriterTo, dest io.ReaderFrom) { // Create a new encoding encoding := &myEncoding{} // You can encode data Encode(encoding, src, dest) // You can decode data Decode(encoding, src, dest) }
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
Click to show internal directories.
Click to hide internal directories.