grpc.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package flatbuffers
  2. import "errors"
  3. var (
  4. // Codec implements gRPC-go Codec which is used to encode and decode messages.
  5. Codec = "flatbuffers"
  6. // ErrInsufficientData is returned when the data is too short to read the root UOffsetT.
  7. ErrInsufficientData = errors.New("insufficient data")
  8. // ErrInvalidRootOffset is returned when the root UOffsetT is out of bounds.
  9. ErrInvalidRootOffset = errors.New("invalid root offset")
  10. )
  11. // FlatbuffersCodec defines the interface gRPC uses to encode and decode messages. Note
  12. // that implementations of this interface must be thread safe; a Codec's
  13. // methods can be called from concurrent goroutines.
  14. type FlatbuffersCodec struct{}
  15. // Marshal returns the wire format of v.
  16. func (FlatbuffersCodec) Marshal(v interface{}) ([]byte, error) {
  17. return v.(*Builder).FinishedBytes(), nil
  18. }
  19. // Unmarshal parses the wire format into v.
  20. func (FlatbuffersCodec) Unmarshal(data []byte, v interface{}) error {
  21. // Need at least 4 bytes to read the root table offset (UOffsetT).
  22. // Vtable soffset_t and metadata are read later during field access.
  23. if len(data) < SizeUOffsetT {
  24. return ErrInsufficientData
  25. }
  26. off := GetUOffsetT(data)
  27. // The root UOffsetT must be within the data buffer
  28. // Compare in the unsigned domain to avoid signedness pitfalls
  29. if off > UOffsetT(len(data)-SizeUOffsetT) {
  30. return ErrInvalidRootOffset
  31. }
  32. v.(flatbuffersInit).Init(data, off)
  33. return nil
  34. }
  35. // String old gRPC Codec interface func
  36. func (FlatbuffersCodec) String() string {
  37. return Codec
  38. }
  39. // Name returns the name of the Codec implementation. The returned string
  40. // will be used as part of content type in transmission. The result must be
  41. // static; the result cannot change between calls.
  42. //
  43. // add Name() for ForceCodec interface
  44. func (FlatbuffersCodec) Name() string {
  45. return Codec
  46. }
  47. type flatbuffersInit interface {
  48. Init(data []byte, i UOffsetT)
  49. }