2014-06-16 16:39:25 -07:00
|
|
|
package binary
|
|
|
|
|
|
|
|
import "io"
|
|
|
|
import "bytes"
|
|
|
|
|
|
|
|
type ByteSlice []byte
|
|
|
|
|
|
|
|
func (self ByteSlice) Equals(other Binary) bool {
|
2014-07-01 14:50:24 -07:00
|
|
|
if o, ok := other.(ByteSlice); ok {
|
|
|
|
return bytes.Equal(self, o)
|
|
|
|
} else {
|
|
|
|
return false
|
|
|
|
}
|
2014-06-16 16:39:25 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
func (self ByteSlice) Less(other Binary) bool {
|
2014-07-01 14:50:24 -07:00
|
|
|
if o, ok := other.(ByteSlice); ok {
|
|
|
|
return bytes.Compare(self, o) < 0 // -1 if a < b
|
|
|
|
} else {
|
|
|
|
panic("Cannot compare unequal types")
|
|
|
|
}
|
2014-06-16 16:39:25 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
func (self ByteSlice) ByteSize() int {
|
2014-07-01 14:50:24 -07:00
|
|
|
return len(self) + 4
|
2014-06-16 16:39:25 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
func (self ByteSlice) WriteTo(w io.Writer) (n int64, err error) {
|
2014-07-01 14:50:24 -07:00
|
|
|
var n_ int
|
|
|
|
_, err = UInt32(len(self)).WriteTo(w)
|
|
|
|
if err != nil {
|
|
|
|
return n, err
|
|
|
|
}
|
|
|
|
n_, err = w.Write([]byte(self))
|
|
|
|
return int64(n_ + 4), err
|
2014-06-16 16:39:25 -07:00
|
|
|
}
|
|
|
|
|
2014-06-24 17:28:40 -07:00
|
|
|
func ReadByteSliceSafe(r io.Reader) (ByteSlice, error) {
|
2014-07-01 14:50:24 -07:00
|
|
|
length, err := ReadUInt32Safe(r)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
bytes := make([]byte, int(length))
|
|
|
|
_, err = io.ReadFull(r, bytes)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return bytes, nil
|
2014-06-30 16:53:04 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
func ReadByteSlice(r io.Reader) ByteSlice {
|
2014-07-01 14:50:24 -07:00
|
|
|
bytes, err := ReadByteSliceSafe(r)
|
2014-07-08 15:33:26 -07:00
|
|
|
if err != nil {
|
2014-07-01 14:50:24 -07:00
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return bytes
|
2014-06-24 17:28:40 -07:00
|
|
|
}
|