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.

80 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
  1. package binary
  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 Binary) 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. func ReadString(r io.Reader) String {
  28. length := int(ReadUInt32(r))
  29. bytes := make([]byte, length)
  30. _, err := io.ReadFull(r, bytes)
  31. if err != nil { panic(err) }
  32. return String(bytes)
  33. }
  34. // ByteSlice
  35. func (self ByteSlice) Equals(other Binary) bool {
  36. if o, ok := other.(ByteSlice); ok {
  37. return bytes.Equal(self, o)
  38. } else {
  39. return false
  40. }
  41. }
  42. func (self ByteSlice) Less(other Binary) bool {
  43. if o, ok := other.(ByteSlice); ok {
  44. return bytes.Compare(self, o) < 0 // -1 if a < b
  45. } else {
  46. panic("Cannot compare unequal types")
  47. }
  48. }
  49. func (self ByteSlice) ByteSize() int {
  50. return len(self)+4
  51. }
  52. func (self ByteSlice) WriteTo(w io.Writer) (n int64, err error) {
  53. var n_ int
  54. _, err = UInt32(len(self)).WriteTo(w)
  55. if err != nil { return n, err }
  56. n_, err = w.Write([]byte(self))
  57. return int64(n_+4), err
  58. }
  59. func ReadByteSlice(r io.Reader) ByteSlice {
  60. length := int(ReadUInt32(r))
  61. bytes := make([]byte, length)
  62. _, err := io.ReadFull(r, bytes)
  63. if err != nil { panic(err) }
  64. return ByteSlice(bytes)
  65. }