2
0

Refactor MessageReader to use bytes.Buffer

Must clearer than manipulating byte slices
This commit is contained in:
Jack Christensen
2013-07-09 13:25:28 -05:00
parent 07c2ad1846
commit 84a9da28e2
+18 -24
View File
@@ -5,53 +5,47 @@ import (
"encoding/binary" "encoding/binary"
) )
type MessageReader []byte type MessageReader struct {
buf *bytes.Buffer
}
func newMessageReader(buf *bytes.Buffer) *MessageReader { func newMessageReader(buf *bytes.Buffer) *MessageReader {
r := MessageReader(buf.Bytes()) return &MessageReader{buf: buf}
return &r
} }
func (r *MessageReader) ReadByte() byte { func (r *MessageReader) ReadByte() byte {
b := (*r)[0] b, err := r.buf.ReadByte()
*r = (*r)[1:] if err != nil {
panic("Unable to read byte")
}
return b return b
} }
func (r *MessageReader) ReadInt16() int16 { func (r *MessageReader) ReadInt16() int16 {
n := int16(binary.BigEndian.Uint16((*r)[:2])) return int16(binary.BigEndian.Uint16(r.buf.Next(2)))
*r = (*r)[2:]
return n
} }
func (r *MessageReader) ReadInt32() int32 { func (r *MessageReader) ReadInt32() int32 {
n := int32(binary.BigEndian.Uint32((*r)[:4])) return int32(binary.BigEndian.Uint32(r.buf.Next(4)))
*r = (*r)[4:]
return n
} }
func (r *MessageReader) ReadInt64() int64 { func (r *MessageReader) ReadInt64() int64 {
n := int64(binary.BigEndian.Uint64((*r)[:8])) return int64(binary.BigEndian.Uint64(r.buf.Next(8)))
*r = (*r)[8:]
return n
} }
func (r *MessageReader) ReadOid() oid { func (r *MessageReader) ReadOid() oid {
n := oid(binary.BigEndian.Uint32((*r)[:4])) return oid(binary.BigEndian.Uint32(r.buf.Next(4)))
*r = (*r)[4:]
return n
} }
func (r *MessageReader) ReadString() string { func (r *MessageReader) ReadString() string {
n := bytes.IndexByte(*r, 0) b, err := r.buf.ReadBytes(0)
s := (*r)[:n] if err != nil {
*r = (*r)[n+1:] panic("Unable to read string")
return string(s) }
return string(b[:len(b)-1])
} }
// Read count bytes and return as string // Read count bytes and return as string
func (r *MessageReader) ReadByteString(count int32) string { func (r *MessageReader) ReadByteString(count int32) string {
s := (*r)[:count] return string(r.buf.Next(int(count)))
*r = (*r)[count:]
return string(s)
} }