bytes.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package serial
  2. import (
  3. "bytes"
  4. )
  5. type Bytes interface {
  6. Bytes() []byte
  7. }
  8. type BytesLiteral []byte
  9. func (this BytesLiteral) Value() []byte {
  10. return []byte(this)
  11. }
  12. func (this BytesLiteral) Equals(another BytesLiteral) bool {
  13. return bytes.Equal(this.Value(), another.Value())
  14. }
  15. func (this BytesLiteral) Uint8Value() uint8 {
  16. return this.Value()[0]
  17. }
  18. func (this BytesLiteral) Uint16() Uint16Literal {
  19. return Uint16Literal(this.Uint16Value())
  20. }
  21. func (this BytesLiteral) Uint16Value() uint16 {
  22. value := this.Value()
  23. return uint16(value[0])<<8 + uint16(value[1])
  24. }
  25. func (this BytesLiteral) IntValue() int {
  26. value := this.Value()
  27. return int(value[0])<<24 + int(value[1])<<16 + int(value[2])<<8 + int(value[3])
  28. }
  29. func (this BytesLiteral) Uint32Value() uint32 {
  30. value := this.Value()
  31. return uint32(value[0])<<24 +
  32. uint32(value[1])<<16 +
  33. uint32(value[2])<<8 +
  34. uint32(value[3])
  35. }
  36. func (this BytesLiteral) Int64Value() int64 {
  37. value := this.Value()
  38. return int64(value[0])<<56 +
  39. int64(value[1])<<48 +
  40. int64(value[2])<<40 +
  41. int64(value[3])<<32 +
  42. int64(value[4])<<24 +
  43. int64(value[5])<<16 +
  44. int64(value[6])<<8 +
  45. int64(value[7])
  46. }
  47. // String returns a string presentation of this ByteLiteral
  48. func (this BytesLiteral) String() string {
  49. return string(this.Value())
  50. }
  51. // All returns true if all bytes in the ByteLiteral are the same as given value.
  52. func (this BytesLiteral) All(v byte) bool {
  53. for _, b := range this {
  54. if b != v {
  55. return false
  56. }
  57. }
  58. return true
  59. }