You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
1.6 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. package merkle
  2. import "bytes"
  3. type String string
  4. type ByteSlice []byte
  5. // String
  6. func (self String) Equals(other Binary) bool {
  7. return self == other
  8. }
  9. func (self String) Less(other Key) bool {
  10. if o, ok := other.(String); ok {
  11. return self < o
  12. } else {
  13. panic("Cannot compare unequal types")
  14. }
  15. }
  16. func (self String) ByteSize() int {
  17. return len(self)+4
  18. }
  19. func (self String) SaveTo(buf []byte) int {
  20. if len(buf) < self.ByteSize() { panic("buf too small") }
  21. UInt32(len(self)).SaveTo(buf)
  22. copy(buf[4:], []byte(self))
  23. return len(self)+4
  24. }
  25. func LoadString(bytes []byte, start int) (String, int) {
  26. length := int(LoadUInt32(bytes[start:]))
  27. return String(bytes[start+4:start+4+length]), start+4+length
  28. }
  29. // ByteSlice
  30. func (self ByteSlice) Equals(other Binary) bool {
  31. if o, ok := other.(ByteSlice); ok {
  32. return bytes.Equal(self, o)
  33. } else {
  34. return false
  35. }
  36. }
  37. func (self ByteSlice) Less(other Key) bool {
  38. if o, ok := other.(ByteSlice); ok {
  39. return bytes.Compare(self, o) < 0 // -1 if a < b
  40. } else {
  41. panic("Cannot compare unequal types")
  42. }
  43. }
  44. func (self ByteSlice) ByteSize() int {
  45. return len(self)+4
  46. }
  47. func (self ByteSlice) SaveTo(buf []byte) int {
  48. if len(buf) < self.ByteSize() { panic("buf too small") }
  49. UInt32(len(self)).SaveTo(buf)
  50. copy(buf[4:], self)
  51. return len(self)+4
  52. }
  53. func LoadByteSlice(bytes []byte, start int) (ByteSlice, int) {
  54. length := int(LoadUInt32(bytes[start:]))
  55. return ByteSlice(bytes[start+4:start+4+length]), start+4+length
  56. }