package bin
import "io"
const (
maxSmallStringLength = 253
firstLongStringByte = 254
)
func encodeString (b []byte , v string ) []byte {
l := len (v )
if l <= maxSmallStringLength {
b = append (b , byte (l ))
b = append (b , v ...)
currentLen := l + 1
b = append (b , make ([]byte , nearestPaddedValueLength (currentLen )-currentLen )...)
return b
}
b = append (b , firstLongStringByte , byte (l ), byte (l >>8 ), byte (l >>16 ))
b = append (b , v ...)
currentLen := l + 4
b = append (b , make ([]byte , nearestPaddedValueLength (currentLen )-currentLen )...)
return b
}
func decodeString (b []byte ) (padding int , v string , err error ) {
if len (b ) == 0 {
return 0 , "" , io .ErrUnexpectedEOF
}
if b [0 ] == firstLongStringByte {
if len (b ) < 4 {
return 0 , "" , io .ErrUnexpectedEOF
}
strLen := uint32 (b [1 ]) | uint32 (b [2 ])<<8 | uint32 (b [3 ])<<16
if len (b ) < (int (strLen ) + 4 ) {
return 0 , "" , io .ErrUnexpectedEOF
}
return nearestPaddedValueLength (int (strLen ) + 4 ), string (b [4 : strLen +4 ]), nil
}
strLen := int (b [0 ])
if len (b ) < (strLen + 1 ) {
return 0 , "" , io .ErrUnexpectedEOF
}
if strLen > maxSmallStringLength {
return 0 , "" , &InvalidLengthError {
Length : strLen ,
Where : "string" ,
}
}
return nearestPaddedValueLength (strLen + 1 ), string (b [1 : strLen +1 ]), nil
}
The pages are generated with Golds v0.6.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds .