aboutsummaryrefslogtreecommitdiff
path: root/util/include/chre/util/flatbuffers/helpers.h
blob: 5ecb338589336dc772a70519e85fec26a080f29a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
 * Copyright 2020 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef CHRE_PLATFORM_SHARED_FLATBUFFERS_HELPERS_H_
#define CHRE_PLATFORM_SHARED_FLATBUFFERS_HELPERS_H_

#include "chre/util/container_support.h"
#include "chre/util/dynamic_vector.h"

#include "flatbuffers/flatbuffers.h"

namespace chre {

//! CHRE-specific flatbuffers allocator that routes to CHRE's alloc / free
//! functions.
class FlatBufferAllocator : public flatbuffers::Allocator {
 public:
  uint8_t *allocate(size_t size) override {
    return static_cast<uint8_t *>(memoryAlloc(size));
  }

  void deallocate(uint8_t *p, size_t) override {
    memoryFree(p);
  }
};

//! CHRE-specific FlatBufferBuilder that utilizes CHRE's allocator and adds
//! additional helper methods that make use of CHRE utilities.
class ChreFlatBufferBuilder : public flatbuffers::FlatBufferBuilder {
 public:
  explicit ChreFlatBufferBuilder(size_t initialSize = 1024)
      : flatbuffers::FlatBufferBuilder(initialSize, &mAllocator) {}

  // This is defined in flatbuffers::FlatBufferBuilder, but must be further
  // defined here since template functions aren't inherited.
  template <typename T>
  flatbuffers::Offset<flatbuffers::Vector<T>> CreateVector(const T *v,
                                                           size_t len) {
    return flatbuffers::FlatBufferBuilder::CreateVector(v, len);
  }

  /**
   * Serialize a DyanmicVector into a FlatBuffer `vector`.
   *
   * @tparam T The data type of the DynamicVector elements.
   * @param v A const reference to the DynamicVector to serialize into the
   * buffer as a `vector`.
   * @return Returns a typed `Offset` into the serialized data indicating
   * where the vector is stored.
   */
  template <typename T>
  flatbuffers::Offset<flatbuffers::Vector<T>> CreateVector(
      const DynamicVector<T> &v) {
    return flatbuffers::FlatBufferBuilder::CreateVector(v.data(), v.size());
  }

 private:
  FlatBufferAllocator mAllocator;
};

}  // namespace chre

#endif  // CHRE_PLATFORM_SHARED_FLATBUFFERS_HELPERS_H_