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.

50 lines
1.2 KiB

11 years ago
11 years ago
  1. package binary
  2. import "io"
  3. import "bytes"
  4. type ByteSlice []byte
  5. func (self ByteSlice) Equals(other Binary) bool {
  6. if o, ok := other.(ByteSlice); ok {
  7. return bytes.Equal(self, o)
  8. } else {
  9. return false
  10. }
  11. }
  12. func (self ByteSlice) Less(other Binary) bool {
  13. if o, ok := other.(ByteSlice); ok {
  14. return bytes.Compare(self, o) < 0 // -1 if a < b
  15. } else {
  16. panic("Cannot compare unequal types")
  17. }
  18. }
  19. func (self ByteSlice) ByteSize() int {
  20. return len(self)+4
  21. }
  22. func (self ByteSlice) WriteTo(w io.Writer) (n int64, err error) {
  23. var n_ int
  24. _, err = UInt32(len(self)).WriteTo(w)
  25. if err != nil { return n, err }
  26. n_, err = w.Write([]byte(self))
  27. return int64(n_+4), err
  28. }
  29. func ReadByteSlice(r io.Reader) ByteSlice {
  30. length := int(ReadUInt32(r))
  31. bytes := make([]byte, length)
  32. _, err := io.ReadFull(r, bytes)
  33. if err != nil { panic(err) }
  34. return ByteSlice(bytes)
  35. }
  36. func ReadByteSliceSafe(r io.Reader) (ByteSlice, error) {
  37. length := int(ReadUInt32(r))
  38. bytes := make([]byte, length)
  39. _, err := io.ReadFull(r, bytes)
  40. if err != nil { return nil, err }
  41. return ByteSlice(bytes), nil
  42. }