github.com/hamba/avro@v1.8.0/codec_enum.go (about) 1 package avro 2 3 import ( 4 "fmt" 5 "reflect" 6 "unsafe" 7 8 "github.com/modern-go/reflect2" 9 ) 10 11 func createDecoderOfEnum(schema Schema, typ reflect2.Type) ValDecoder { 12 if typ.Kind() == reflect.String { 13 return &enumCodec{symbols: schema.(*EnumSchema).Symbols()} 14 } 15 16 return &errorDecoder{err: fmt.Errorf("avro: %s is unsupported for Avro %s", typ.String(), schema.Type())} 17 } 18 19 func createEncoderOfEnum(schema Schema, typ reflect2.Type) ValEncoder { 20 if typ.Kind() == reflect.String { 21 return &enumCodec{symbols: schema.(*EnumSchema).Symbols()} 22 } 23 24 return &errorEncoder{err: fmt.Errorf("avro: %s is unsupported for Avro %s", typ.String(), schema.Type())} 25 } 26 27 type enumCodec struct { 28 symbols []string 29 } 30 31 func (c *enumCodec) Decode(ptr unsafe.Pointer, r *Reader) { 32 i := int(r.ReadInt()) 33 34 if i < 0 || i >= len(c.symbols) { 35 r.ReportError("decode unknown enum symbol", "unknown enum symbol") 36 return 37 } 38 39 *((*string)(ptr)) = c.symbols[i] 40 } 41 42 func (c *enumCodec) Encode(ptr unsafe.Pointer, w *Writer) { 43 str := *((*string)(ptr)) 44 for i, sym := range c.symbols { 45 if str != sym { 46 continue 47 } 48 49 w.WriteInt(int32(i)) 50 return 51 } 52 53 w.Error = fmt.Errorf("avro: unknown enum symbol: %s", str) 54 }