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

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