tendermint/merkle/string.go

77 lines
1.7 KiB
Go
Raw Normal View History

package merkle
2014-06-03 17:03:29 -07:00
import "io"
import "bytes"
type String string
type ByteSlice []byte
2014-05-22 18:08:49 -07:00
// String
2014-05-23 17:49:28 -07:00
func (self String) Equals(other Binary) bool {
return self == other
}
2014-05-21 16:24:50 -07:00
func (self String) Less(other Key) bool {
if o, ok := other.(String); ok {
return self < o
} else {
2014-05-23 17:49:28 -07:00
panic("Cannot compare unequal types")
}
}
2014-05-22 18:08:49 -07:00
func (self String) ByteSize() int {
return len(self)+4
}
2014-06-03 17:03:29 -07:00
func (self String) WriteTo(w io.Writer) (n int64, err error) {
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-05-29 22:02:36 -07:00
// NOTE: keeps a reference to the original byte slice
func ReadString(bytes []byte, start int) (String, int) {
length := int(ReadUInt32(bytes[start:]))
2014-05-23 17:49:28 -07:00
return String(bytes[start+4:start+4+length]), start+4+length
2014-05-22 18:08:49 -07:00
}
// ByteSlice
2014-05-23 17:49:28 -07:00
func (self ByteSlice) Equals(other Binary) bool {
if o, ok := other.(ByteSlice); ok {
return bytes.Equal(self, o)
} else {
return false
}
}
2014-05-21 16:24:50 -07:00
func (self ByteSlice) Less(other Key) bool {
if o, ok := other.(ByteSlice); ok {
return bytes.Compare(self, o) < 0 // -1 if a < b
} else {
2014-05-23 17:49:28 -07:00
panic("Cannot compare unequal types")
}
}
2014-05-22 18:08:49 -07:00
func (self ByteSlice) ByteSize() int {
return len(self)+4
}
2014-06-03 17:03:29 -07:00
func (self ByteSlice) WriteTo(w io.Writer) (n int64, err error) {
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-05-22 18:08:49 -07:00
}
2014-05-29 22:02:36 -07:00
// NOTE: keeps a reference to the original byte slice
func ReadByteSlice(bytes []byte, start int) (ByteSlice, int) {
length := int(ReadUInt32(bytes[start:]))
2014-05-23 17:49:28 -07:00
return ByteSlice(bytes[start+4:start+4+length]), start+4+length
}