tendermint/merkle/string.go

74 lines
1.7 KiB
Go
Raw Normal View History

package merkle
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-05-29 22:02:36 -07:00
func (self String) WriteTo(buf []byte) int {
2014-05-22 18:08:49 -07:00
if len(buf) < self.ByteSize() { panic("buf too small") }
2014-05-29 22:02:36 -07:00
UInt32(len(self)).WriteTo(buf)
2014-05-22 18:08:49 -07:00
copy(buf[4:], []byte(self))
return len(self)+4
}
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-05-29 22:02:36 -07:00
func (self ByteSlice) WriteTo(buf []byte) int {
2014-05-22 18:08:49 -07:00
if len(buf) < self.ByteSize() { panic("buf too small") }
2014-05-29 22:02:36 -07:00
UInt32(len(self)).WriteTo(buf)
2014-05-22 18:08:49 -07:00
copy(buf[4:], self)
return len(self)+4
}
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
}