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