github.com/mymmsc/gox@v1.3.33/encoding/binary/struc/binary.go (about) 1 package struc 2 3 import ( 4 "encoding/binary" 5 "io" 6 "reflect" 7 ) 8 9 type byteWriter struct { 10 buf []byte 11 pos int 12 } 13 14 func (b byteWriter) Write(p []byte) (int, error) { 15 capacity := len(b.buf) - b.pos 16 if capacity < len(p) { 17 p = p[:capacity] 18 } 19 if len(p) > 0 { 20 copy(b.buf[b.pos:], p) 21 b.pos += len(p) 22 } 23 return len(p), nil 24 } 25 26 type binaryFallback reflect.Value 27 28 func (b binaryFallback) String() string { 29 return b.String() 30 } 31 32 func (b binaryFallback) Sizeof(val reflect.Value, options *Options) int { 33 return binary.Size(val.Interface()) 34 } 35 36 func (b binaryFallback) Pack(buf []byte, val reflect.Value, options *Options) (int, error) { 37 tmp := byteWriter{buf: buf} 38 var order binary.ByteOrder = binary.BigEndian 39 if options.Order != nil { 40 order = options.Order 41 } 42 err := binary.Write(tmp, order, val.Interface()) 43 return tmp.pos, err 44 } 45 46 func (b binaryFallback) Unpack(r io.Reader, val reflect.Value, options *Options) error { 47 var order binary.ByteOrder = binary.BigEndian 48 if options.Order != nil { 49 order = options.Order 50 } 51 return binary.Read(r, order, val.Interface()) 52 }