b1on.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package b1
  2. import "encoding/binary"
  3. import "fmt"
  4. import "io"
  5. type B1onKind int64
  6. const (
  7. B1onObjectKind B1onKind = 'O'
  8. B1onArrayKind B1onKind = 'A'
  9. B1onStringKind B1onKind = 'S'
  10. B1onIntegerKind B1onKind = 'I'
  11. B1onDoubleKind B1onKind = 'D'
  12. B1onTrueKind B1onKind = 'T'
  13. B1onFalseKind B1onKind = 'F'
  14. B1onNullKind B1onKind = 'N'
  15. )
  16. func (k B1onKind) MarshalBinary(w io.Writer) error {
  17. return binary.Write(w, binary.LittleEndian, k)
  18. }
  19. func (k *B1onKind) UnmarshalBinary(r io.Reader) error {
  20. return binary.Read(r, binary.LittleEndian, k)
  21. }
  22. type B1onValue interface {
  23. Kind() B1onKind
  24. MarshalBinary(io.Writer) error
  25. UnmarshalBinary(io.Writer) error
  26. JsonString() string
  27. }
  28. type B1onPair struct {
  29. Key string
  30. Value B1onValue
  31. }
  32. type B1onObject struct {
  33. Members []B1onPair
  34. }
  35. type B1onArray struct {
  36. Members []B1onValue
  37. }
  38. type B1onString string
  39. func (s B1onString) Kind() B1onKind {
  40. return B1onStringKind
  41. }
  42. func (s B1onString) MarshalBinary(w io.Writer) error {
  43. l := int64(len(s))
  44. err := s.Kind().MarshalBinary(w)
  45. if err != nil {
  46. return err
  47. }
  48. err = binary.Write(w, binary.LittleEndian, l)
  49. if err != nil {
  50. return err
  51. }
  52. wl, err := w.Write([]byte(s))
  53. if int64(wl) != l {
  54. return fmt.Errorf("short write")
  55. }
  56. return err
  57. }
  58. func (s B1onString) UnmarshalBinary(w io.Writer) error {
  59. l := int64(len(s))
  60. err := s.Kind().MarshalBinary(w)
  61. if err != nil {
  62. return err
  63. }
  64. err = binary.Write(w, binary.LittleEndian, l)
  65. if err != nil {
  66. return err
  67. }
  68. wl, err := w.Write([]byte(s))
  69. if int64(wl) != l {
  70. return fmt.Errorf("short write")
  71. }
  72. return err
  73. }
  74. type B1onBool bool
  75. type B1onInt int64
  76. type B1onDouble float64