buffer_ref.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /*
  2. * Copyright 2021 Google Inc. All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #ifndef FLATBUFFERS_BUFFER_REF_H_
  17. #define FLATBUFFERS_BUFFER_REF_H_
  18. #include "flatbuffers/base.h"
  19. #include "flatbuffers/verifier.h"
  20. namespace flatbuffers {
  21. // Convenient way to bundle a buffer and its length, to pass it around
  22. // typed by its root.
  23. // A BufferRef does not own its buffer.
  24. struct BufferRefBase {}; // for std::is_base_of
  25. template<typename T> struct BufferRef : BufferRefBase {
  26. BufferRef() : buf(nullptr), len(0), must_free(false) {}
  27. BufferRef(uint8_t *_buf, uoffset_t _len)
  28. : buf(_buf), len(_len), must_free(false) {}
  29. ~BufferRef() {
  30. if (must_free) free(buf);
  31. }
  32. const T *GetRoot() const { return flatbuffers::GetRoot<T>(buf); }
  33. bool Verify() {
  34. Verifier verifier(buf, len);
  35. return verifier.VerifyBuffer<T>(nullptr);
  36. }
  37. uint8_t *buf;
  38. uoffset_t len;
  39. bool must_free;
  40. };
  41. } // namespace flatbuffers
  42. #endif // FLATBUFFERS_BUFFER_REF_H_