lib.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package flatbuffers
  2. // FlatBuffer is the interface that represents a flatbuffer.
  3. type FlatBuffer interface {
  4. Table() Table
  5. Init(buf []byte, i UOffsetT)
  6. }
  7. // GetRootAs is a generic helper to initialize a FlatBuffer with the provided buffer bytes and its data offset.
  8. func GetRootAs(buf []byte, offset UOffsetT, fb FlatBuffer) {
  9. n := GetUOffsetT(buf[offset:])
  10. fb.Init(buf, n+offset)
  11. }
  12. // GetSizePrefixedRootAs is a generic helper to initialize a FlatBuffer with the provided size-prefixed buffer
  13. // bytes and its data offset
  14. func GetSizePrefixedRootAs(buf []byte, offset UOffsetT, fb FlatBuffer) {
  15. n := GetUOffsetT(buf[offset+sizePrefixLength:])
  16. fb.Init(buf, n+offset+sizePrefixLength)
  17. }
  18. // GetSizePrefix reads the size from a size-prefixed flatbuffer
  19. func GetSizePrefix(buf []byte, offset UOffsetT) uint32 {
  20. return GetUint32(buf[offset:])
  21. }
  22. // GetIndirectOffset retrives the relative offset in the provided buffer stored at `offset`.
  23. func GetIndirectOffset(buf []byte, offset UOffsetT) UOffsetT {
  24. return offset + GetUOffsetT(buf[offset:])
  25. }
  26. // GetBufferIdentifier returns the file identifier as string
  27. func GetBufferIdentifier(buf []byte) string {
  28. return string(buf[SizeUOffsetT:][:fileIdentifierLength])
  29. }
  30. // GetBufferIdentifier returns the file identifier as string for a size-prefixed buffer
  31. func GetSizePrefixedBufferIdentifier(buf []byte) string {
  32. return string(buf[SizeUOffsetT+sizePrefixLength:][:fileIdentifierLength])
  33. }
  34. // BufferHasIdentifier checks if the identifier in a buffer has the expected value
  35. func BufferHasIdentifier(buf []byte, identifier string) bool {
  36. return GetBufferIdentifier(buf) == identifier
  37. }
  38. // BufferHasIdentifier checks if the identifier in a buffer has the expected value for a size-prefixed buffer
  39. func SizePrefixedBufferHasIdentifier(buf []byte, identifier string) bool {
  40. return GetSizePrefixedBufferIdentifier(buf) == identifier
  41. }