github.com/segmentio/encoding@v0.4.0/proto/string.go (about) 1 package proto 2 3 import ( 4 "io" 5 "unsafe" 6 ) 7 8 var stringCodec = codec{ 9 wire: varlen, 10 size: sizeOfString, 11 encode: encodeString, 12 decode: decodeString, 13 } 14 15 func sizeOfString(p unsafe.Pointer, flags flags) int { 16 if p != nil { 17 if v := *(*string)(p); v != "" || flags.has(wantzero) { 18 return sizeOfVarlen(len(v)) 19 } 20 } 21 return 0 22 } 23 24 func encodeString(b []byte, p unsafe.Pointer, flags flags) (int, error) { 25 if p != nil { 26 if v := *(*string)(p); v != "" || flags.has(wantzero) { 27 n, err := encodeVarint(b, uint64(len(v))) 28 if err != nil { 29 return n, err 30 } 31 c := copy(b[n:], v) 32 n += c 33 if c < len(v) { 34 err = io.ErrShortBuffer 35 } 36 return n, err 37 } 38 } 39 return 0, nil 40 } 41 42 func decodeString(b []byte, p unsafe.Pointer, _ flags) (int, error) { 43 v, n, err := decodeVarlen(b) 44 *(*string)(p) = string(v) 45 return n, err 46 }