message.go 897 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package borealis
  2. import (
  3. "fmt"
  4. "github.com/fxamacker/cbor/v2"
  5. )
  6. const (
  7. V1MessageVersion = 1
  8. V1MessageMinLen = 23
  9. )
  10. type V1MessageEncoder struct{}
  11. func (encoder *V1MessageEncoder) Encode(stream string, message interface{}) ([]byte, error) {
  12. output, err := cbor.Marshal(message)
  13. if err != nil {
  14. return nil, err
  15. }
  16. return append([]byte{V1MessageVersion}, output...), nil
  17. }
  18. func (encoder *V1MessageEncoder) Decode(stream string, input []byte, messagePtr interface{}) error {
  19. if len(input) < V1MessageMinLen {
  20. return fmt.Errorf("expected message length %d+, but got %d", V1MessageMinLen, len(input))
  21. }
  22. if input[0] != V1MessageVersion {
  23. return fmt.Errorf("expected message version %d, but got %d", V1MessageVersion, input[0])
  24. }
  25. switch message := messagePtr.(type) {
  26. case *[]byte:
  27. *message = input[1:]
  28. return nil
  29. default:
  30. return cbor.Unmarshal(input[1:], message)
  31. }
  32. }