github.com/hamba/avro/v2@v2.22.1-0.20240518180522-aff3955acf7d/decoder.go (about)

     1  package avro
     2  
     3  import (
     4  	"io"
     5  )
     6  
     7  // Decoder reads and decodes Avro values from an input stream.
     8  type Decoder struct {
     9  	s Schema
    10  	r *Reader
    11  }
    12  
    13  // NewDecoder returns a new decoder that reads from reader r using schema s.
    14  func NewDecoder(s string, r io.Reader) (*Decoder, error) {
    15  	sch, err := Parse(s)
    16  	if err != nil {
    17  		return nil, err
    18  	}
    19  
    20  	return NewDecoderForSchema(sch, r), nil
    21  }
    22  
    23  // NewDecoderForSchema returns a new decoder that reads from r using schema.
    24  func NewDecoderForSchema(schema Schema, reader io.Reader) *Decoder {
    25  	return DefaultConfig.NewDecoder(schema, reader)
    26  }
    27  
    28  // Decode reads the next Avro encoded value from its input and stores it in the value pointed to by v.
    29  func (d *Decoder) Decode(obj any) error {
    30  	if d.r.head == d.r.tail && d.r.reader != nil {
    31  		if !d.r.loadMore() {
    32  			return io.EOF
    33  		}
    34  	}
    35  
    36  	d.r.ReadVal(d.s, obj)
    37  
    38  	//nolint:errorlint // Only direct EOF errors should be discarded.
    39  	if d.r.Error == io.EOF {
    40  		return nil
    41  	}
    42  	return d.r.Error
    43  }
    44  
    45  // Unmarshal parses the Avro encoded data and stores the result in the value pointed to by v.
    46  // If v is nil or not a pointer, Unmarshal returns an error.
    47  func Unmarshal(schema Schema, data []byte, v any) error {
    48  	return DefaultConfig.Unmarshal(schema, data, v)
    49  }