Skip to content

Instantly share code, notes, and snippets.

@qiuyuzhou
Last active September 5, 2015 07:10
Show Gist options
  • Save qiuyuzhou/d4cfc7d1aefd4e79e93d to your computer and use it in GitHub Desktop.
Save qiuyuzhou/d4cfc7d1aefd4e79e93d to your computer and use it in GitHub Desktop.
Write/Read string to io.Writer/Reader with length header
package core
import "io"
import "encoding/binary"
import "bufio"
func WriteString(writer io.Writer, s string) (err error) {
l := len(s)
if l < 128 {
err = binary.Write(writer, binary.BigEndian, byte(l))
} else {
err = binary.Write(writer, binary.BigEndian, uint32(l))
}
if err != nil {
return
}
_, err = writer.Write([]byte(s))
return
}
func ReadString(reader io.Reader) (string, error) {
var l byte
r := bufio.NewReader(reader)
if err := binary.Read(r, binary.BigEndian, &l); err != nil {
return "", err
}
if l < 128 {
var buf [128]byte
b := buf[:l]
if _, err := r.Read(b); err != nil {
return "", err
}
return string(b), nil
}
r.UnreadByte()
var ll uint32
if err := binary.Read(r, binary.BigEndian, &ll); err != nil {
return "", err
}
b := make([]byte, ll)
if _, err := r.Read(b); err != nil {
return "", err
}
return string(b), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment