github.com/aacfactory/avro@v1.2.12/internal/base/encoder.go (about)

     1  package base
     2  
     3  import (
     4  	"io"
     5  )
     6  
     7  // Encoder writes Avro values to an output stream.
     8  type Encoder struct {
     9  	s Schema
    10  	w *Writer
    11  }
    12  
    13  // NewEncoder returns a new encoder that writes to w using schema s.
    14  func NewEncoder(s string, w io.Writer) (*Encoder, error) {
    15  	sch, err := Parse(s)
    16  	if err != nil {
    17  		return nil, err
    18  	}
    19  	return NewEncoderForSchema(sch, w), nil
    20  }
    21  
    22  // NewEncoderForSchema returns a new encoder that writes to w using schema.
    23  func NewEncoderForSchema(schema Schema, w io.Writer) *Encoder {
    24  	return DefaultConfig.NewEncoder(schema, w)
    25  }
    26  
    27  // Encode writes the Avro encoding of v to the stream.
    28  func (e *Encoder) Encode(v any) error {
    29  	e.w.WriteVal(e.s, v)
    30  	_ = e.w.Flush()
    31  	return e.w.Error
    32  }
    33  
    34  // Marshal returns the Avro encoding of v.
    35  func Marshal(schema Schema, v any) ([]byte, error) {
    36  	return DefaultConfig.Marshal(schema, v)
    37  }