github.com/philpearl/plenc@v0.0.15/marshal.go (about) 1 package plenc 2 3 import ( 4 "fmt" 5 "reflect" 6 "unsafe" 7 ) 8 9 func Marshal(data []byte, value interface{}) ([]byte, error) { 10 return defaultPlenc.Marshal(data, value) 11 } 12 13 func Unmarshal(data []byte, value interface{}) error { 14 return defaultPlenc.Unmarshal(data, value) 15 } 16 17 func (p *Plenc) Marshal(data []byte, value interface{}) ([]byte, error) { 18 typ := reflect.TypeOf(value) 19 ptr := unpackEFace(value).data 20 if typ.Kind() == reflect.Ptr { 21 typ = typ.Elem() 22 23 // When marshalling we don't want a pointer to a map as a map is a 24 // pointer-ish type itself. 25 if typ.Kind() == reflect.Map { 26 ptr = *(*unsafe.Pointer)(ptr) 27 } 28 } 29 30 c, err := p.CodecForType(typ) 31 if err != nil { 32 return nil, err 33 } 34 35 if c.Omit(ptr) { 36 return nil, nil 37 } 38 if data == nil { 39 data = make([]byte, 0, c.Size(ptr, nil)) 40 } 41 42 return c.Append(data, ptr, nil), nil 43 } 44 45 func (p *Plenc) Unmarshal(data []byte, value interface{}) error { 46 rv := reflect.ValueOf(value) 47 if rv.Kind() != reflect.Ptr || rv.IsNil() { 48 return fmt.Errorf("you must pass in a non-nil pointer") 49 } 50 51 c, err := p.CodecForType(rv.Type().Elem()) 52 if err != nil { 53 return err 54 } 55 56 _, err = c.Read(data, unsafe.Pointer(rv.Pointer()), c.WireType()) 57 return err 58 }