github.com/aacfactory/avro@v1.2.12/api.go (about)

     1  package avro
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/aacfactory/avro/internal/base"
     6  	"unsafe"
     7  )
     8  
     9  func Marshal(v any) (p []byte, err error) {
    10  	schema, schemaErr := base.ParseValue(v)
    11  	if schemaErr != nil {
    12  		err = schemaErr
    13  		return
    14  	}
    15  	p, err = base.Marshal(schema, v)
    16  	return
    17  }
    18  
    19  func Unmarshal(p []byte, v any) (err error) {
    20  	schema, schemaErr := base.ParseValue(v)
    21  	if schemaErr != nil {
    22  		err = schemaErr
    23  		return
    24  	}
    25  	err = base.Unmarshal(schema, p, v)
    26  	return
    27  }
    28  
    29  func Register(v any) {
    30  	base.RegisterSchemaByValue(v)
    31  }
    32  
    33  func SchemaOf(v any) (p []byte, err error) {
    34  	s, parseErr := base.ParseValue(v)
    35  	if parseErr != nil {
    36  		err = parseErr
    37  		return
    38  	}
    39  	str := s.String()
    40  	p = unsafe.Slice(unsafe.StringData(str), len(str))
    41  	return
    42  }
    43  
    44  type Marshaler interface {
    45  	MarshalAvro() ([]byte, error)
    46  }
    47  
    48  type Unmarshaler interface {
    49  	UnmarshalAvro(p []byte) error
    50  }
    51  
    52  type RawMessage []byte
    53  
    54  func (r *RawMessage) UnmarshalAvro(p []byte) error {
    55  	*r = p
    56  	return nil
    57  }
    58  
    59  func (r RawMessage) MarshalAvro() ([]byte, error) {
    60  	return r, nil
    61  }
    62  
    63  func MustMarshal(v any) (p []byte) {
    64  	b, err := Marshal(v)
    65  	if err != nil {
    66  		panic(fmt.Errorf("avro: marshal failed, %v", err))
    67  		return
    68  	}
    69  	p = b
    70  	return
    71  }
    72  
    73  func MustUnmarshal(p []byte, v any) {
    74  	err := Unmarshal(p, v)
    75  	if err != nil {
    76  		panic(fmt.Errorf("avro: unmarshal failed, %v", err))
    77  		return
    78  	}
    79  	return
    80  }