Refactor MessageReader to use bytes.Buffer

Must clearer than manipulating byte slices
pgx-vs-pq
Jack Christensen 2013-07-09 13:25:28 -05:00
parent 07c2ad1846
commit 84a9da28e2
1 changed files with 18 additions and 24 deletions

View File

@ -5,53 +5,47 @@ import (
"encoding/binary"
)
type MessageReader []byte
type MessageReader struct {
buf *bytes.Buffer
}
func newMessageReader(buf *bytes.Buffer) *MessageReader {
r := MessageReader(buf.Bytes())
return &r
return &MessageReader{buf: buf}
}
func (r *MessageReader) ReadByte() byte {
b := (*r)[0]
*r = (*r)[1:]
b, err := r.buf.ReadByte()
if err != nil {
panic("Unable to read byte")
}
return b
}
func (r *MessageReader) ReadInt16() int16 {
n := int16(binary.BigEndian.Uint16((*r)[:2]))
*r = (*r)[2:]
return n
return int16(binary.BigEndian.Uint16(r.buf.Next(2)))
}
func (r *MessageReader) ReadInt32() int32 {
n := int32(binary.BigEndian.Uint32((*r)[:4]))
*r = (*r)[4:]
return n
return int32(binary.BigEndian.Uint32(r.buf.Next(4)))
}
func (r *MessageReader) ReadInt64() int64 {
n := int64(binary.BigEndian.Uint64((*r)[:8]))
*r = (*r)[8:]
return n
return int64(binary.BigEndian.Uint64(r.buf.Next(8)))
}
func (r *MessageReader) ReadOid() oid {
n := oid(binary.BigEndian.Uint32((*r)[:4]))
*r = (*r)[4:]
return n
return oid(binary.BigEndian.Uint32(r.buf.Next(4)))
}
func (r *MessageReader) ReadString() string {
n := bytes.IndexByte(*r, 0)
s := (*r)[:n]
*r = (*r)[n+1:]
return string(s)
b, err := r.buf.ReadBytes(0)
if err != nil {
panic("Unable to read string")
}
return string(b[:len(b)-1])
}
// Read count bytes and return as string
func (r *MessageReader) ReadByteString(count int32) string {
s := (*r)[:count]
*r = (*r)[count:]
return string(s)
return string(r.buf.Next(int(count)))
}