github.com/qri-io/qri@v0.10.1-0.20220104210721-c771715036cb/p2p/p2putil/multicodec_old/coding.go (about)

     1  package multicodec
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  )
     7  
     8  // Codec is an algorithm for coding data from one representation
     9  // to another. For convenience, we define a codec in the usual
    10  // sense: a function and its inverse, to encode and decode.
    11  type Codec interface {
    12  	// Decoder wraps given io.Reader and returns an object which
    13  	// will decode bytes into objects.
    14  	Decoder(r io.Reader) Decoder
    15  
    16  	// Encoder wraps given io.Writer and returns an Encoder
    17  	Encoder(w io.Writer) Encoder
    18  }
    19  
    20  // Encoder encodes objects into bytes and writes them to an
    21  // underlying io.Writer. Works like encoding.Marshal
    22  type Encoder interface {
    23  	Encode(n interface{}) error
    24  }
    25  
    26  // Decoder decodes objects from bytes from an underlying
    27  // io.Reader, into given object. Works like encoding.Unmarshal
    28  type Decoder interface {
    29  	Decode(n interface{}) error
    30  }
    31  
    32  // Marshal serializes an object to a []byte.
    33  func Marshal(c Codec, o interface{}) ([]byte, error) {
    34  	var buf bytes.Buffer
    35  	err := MarshalTo(c, &buf, o)
    36  	if err != nil {
    37  		return nil, err
    38  	}
    39  	return buf.Bytes(), nil
    40  }
    41  
    42  // MarshalTo serializes an object to a writer.
    43  func MarshalTo(c Codec, w io.Writer, o interface{}) error {
    44  	return c.Encoder(w).Encode(o)
    45  }
    46  
    47  // Unmarshal deserializes an object to a []byte.
    48  func Unmarshal(c Codec, buf []byte, o interface{}) error {
    49  	return UnmarshalFrom(c, bytes.NewBuffer(buf), o)
    50  }
    51  
    52  // UnmarshalFrom deserializes an objects from a reader.
    53  func UnmarshalFrom(c Codec, r io.Reader, o interface{}) error {
    54  	return c.Decoder(r).Decode(o)
    55  }