syncthing/xdr/reader.go

105 lines
1.8 KiB
Go
Raw Normal View History

2014-02-15 11:08:55 +00:00
package xdr
2014-02-20 16:40:15 +00:00
import (
"errors"
"io"
)
2014-02-24 12:29:30 +00:00
var ErrElementSizeExceeded = errors.New("element size exceeded")
2014-02-15 11:08:55 +00:00
type Reader struct {
r io.Reader
2014-02-20 16:40:15 +00:00
tot int
2014-02-15 11:08:55 +00:00
err error
b [8]byte
}
func NewReader(r io.Reader) *Reader {
return &Reader{
r: r,
}
}
func (r *Reader) ReadString() string {
2014-02-20 16:40:15 +00:00
return string(r.ReadBytes())
}
func (r *Reader) ReadStringMax(max int) string {
return string(r.ReadBytesMax(max))
}
func (r *Reader) ReadBytes() []byte {
return r.ReadBytesInto(nil)
}
func (r *Reader) ReadBytesMax(max int) []byte {
return r.ReadBytesMaxInto(max, nil)
}
func (r *Reader) ReadBytesInto(dst []byte) []byte {
return r.ReadBytesMaxInto(0, dst)
2014-02-15 11:08:55 +00:00
}
2014-02-20 16:40:15 +00:00
func (r *Reader) ReadBytesMaxInto(max int, dst []byte) []byte {
2014-02-15 11:08:55 +00:00
if r.err != nil {
return nil
}
l := int(r.ReadUint32())
if r.err != nil {
return nil
}
2014-02-20 16:40:15 +00:00
if max > 0 && l > max {
r.err = ErrElementSizeExceeded
return nil
}
2014-02-15 11:08:55 +00:00
if l+pad(l) > len(dst) {
dst = make([]byte, l+pad(l))
} else {
dst = dst[:l+pad(l)]
}
_, r.err = io.ReadFull(r.r, dst)
2014-02-20 16:40:15 +00:00
r.tot += l + pad(l)
2014-02-15 11:08:55 +00:00
return dst[:l]
}
2014-02-20 16:40:15 +00:00
func (r *Reader) ReadUint16() uint16 {
if r.err != nil {
return 0
}
_, r.err = io.ReadFull(r.r, r.b[:4])
r.tot += 4
return uint16(r.b[1]) | uint16(r.b[0])<<8
}
2014-02-15 11:08:55 +00:00
func (r *Reader) ReadUint32() uint32 {
2014-05-11 22:55:43 +00:00
var n int
2014-02-15 11:08:55 +00:00
if r.err != nil {
return 0
}
2014-05-11 22:55:43 +00:00
n, r.err = io.ReadFull(r.r, r.b[:4])
if n < 4 {
return 0
}
r.tot += n
2014-02-15 11:08:55 +00:00
return uint32(r.b[3]) | uint32(r.b[2])<<8 | uint32(r.b[1])<<16 | uint32(r.b[0])<<24
}
func (r *Reader) ReadUint64() uint64 {
2014-05-11 22:55:43 +00:00
var n int
2014-02-15 11:08:55 +00:00
if r.err != nil {
return 0
}
2014-05-11 22:55:43 +00:00
n, r.err = io.ReadFull(r.r, r.b[:8])
r.tot += n
2014-02-15 11:08:55 +00:00
return uint64(r.b[7]) | uint64(r.b[6])<<8 | uint64(r.b[5])<<16 | uint64(r.b[4])<<24 |
uint64(r.b[3])<<32 | uint64(r.b[2])<<40 | uint64(r.b[1])<<48 | uint64(r.b[0])<<56
}
2014-02-20 16:40:15 +00:00
func (r *Reader) Tot() int {
2014-02-15 11:08:55 +00:00
return r.tot
}
2014-02-20 16:40:15 +00:00
func (r *Reader) Error() error {
2014-02-15 11:08:55 +00:00
return r.err
}