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.

76 lines
1.7 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
11 years ago
  1. package merkle
  2. import "io"
  3. import "bytes"
  4. type String string
  5. type ByteSlice []byte
  6. // String
  7. func (self String) Equals(other Binary) bool {
  8. return self == other
  9. }
  10. func (self String) Less(other Key) bool {
  11. if o, ok := other.(String); ok {
  12. return self < o
  13. } else {
  14. panic("Cannot compare unequal types")
  15. }
  16. }
  17. func (self String) ByteSize() int {
  18. return len(self)+4
  19. }
  20. func (self String) WriteTo(w io.Writer) (n int64, err error) {
  21. var n_ int
  22. _, err = UInt32(len(self)).WriteTo(w)
  23. if err != nil { return n, err }
  24. n_, err = w.Write([]byte(self))
  25. return int64(n_+4), err
  26. }
  27. // NOTE: keeps a reference to the original byte slice
  28. func ReadString(bytes []byte, start int) (String, int) {
  29. length := int(ReadUInt32(bytes[start:]))
  30. return String(bytes[start+4:start+4+length]), start+4+length
  31. }
  32. // ByteSlice
  33. func (self ByteSlice) Equals(other Binary) bool {
  34. if o, ok := other.(ByteSlice); ok {
  35. return bytes.Equal(self, o)
  36. } else {
  37. return false
  38. }
  39. }
  40. func (self ByteSlice) Less(other Key) bool {
  41. if o, ok := other.(ByteSlice); ok {
  42. return bytes.Compare(self, o) < 0 // -1 if a < b
  43. } else {
  44. panic("Cannot compare unequal types")
  45. }
  46. }
  47. func (self ByteSlice) ByteSize() int {
  48. return len(self)+4
  49. }
  50. func (self ByteSlice) WriteTo(w io.Writer) (n int64, err error) {
  51. var n_ int
  52. _, err = UInt32(len(self)).WriteTo(w)
  53. if err != nil { return n, err }
  54. n_, err = w.Write([]byte(self))
  55. return int64(n_+4), err
  56. }
  57. // NOTE: keeps a reference to the original byte slice
  58. func ReadByteSlice(bytes []byte, start int) (ByteSlice, int) {
  59. length := int(ReadUInt32(bytes[start:]))
  60. return ByteSlice(bytes[start+4:start+4+length]), start+4+length
  61. }