1 /* 2 * Copyright 2020 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 17 #ifndef CHRE_PLATFORM_SHARED_FLATBUFFERS_HELPERS_H_ 18 #define CHRE_PLATFORM_SHARED_FLATBUFFERS_HELPERS_H_ 19 20 #include "chre/util/container_support.h" 21 #include "chre/util/dynamic_vector.h" 22 23 #include "flatbuffers/flatbuffers.h" 24 25 namespace chre { 26 27 //! CHRE-specific flatbuffers allocator that routes to CHRE's alloc / free 28 //! functions. 29 class FlatBufferAllocator : public flatbuffers::Allocator { 30 public: allocate(size_t size)31 uint8_t *allocate(size_t size) override { 32 return static_cast<uint8_t *>(memoryAlloc(size)); 33 } 34 deallocate(uint8_t * p,size_t)35 void deallocate(uint8_t *p, size_t) override { 36 memoryFree(p); 37 } 38 }; 39 40 //! CHRE-specific FlatBufferBuilder that utilizes CHRE's allocator and adds 41 //! additional helper methods that make use of CHRE utilities. 42 class ChreFlatBufferBuilder : public flatbuffers::FlatBufferBuilder { 43 public: 44 explicit ChreFlatBufferBuilder(size_t initialSize = 1024) 45 : flatbuffers::FlatBufferBuilder(initialSize, &mAllocator) {} 46 47 // This is defined in flatbuffers::FlatBufferBuilder, but must be further 48 // defined here since template functions aren't inherited. 49 template <typename T> CreateVector(const T * v,size_t len)50 flatbuffers::Offset<flatbuffers::Vector<T>> CreateVector(const T *v, 51 size_t len) { 52 return flatbuffers::FlatBufferBuilder::CreateVector(v, len); 53 } 54 55 /** 56 * Serialize a DyanmicVector into a FlatBuffer `vector`. 57 * 58 * @tparam T The data type of the DynamicVector elements. 59 * @param v A const reference to the DynamicVector to serialize into the 60 * buffer as a `vector`. 61 * @return Returns a typed `Offset` into the serialized data indicating 62 * where the vector is stored. 63 */ 64 template <typename T> CreateVector(const DynamicVector<T> & v)65 flatbuffers::Offset<flatbuffers::Vector<T>> CreateVector( 66 const DynamicVector<T> &v) { 67 return flatbuffers::FlatBufferBuilder::CreateVector(v.data(), v.size()); 68 } 69 70 private: 71 FlatBufferAllocator mAllocator; 72 }; 73 74 } // namespace chre 75 76 #endif // CHRE_PLATFORM_SHARED_FLATBUFFERS_HELPERS_H_ 77