1 /*
2 * Copyright 2018 The Android Open Source Project
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 #pragma once
18
19 #include "tuningfork/tuningfork.h"
20
21 #include <vector>
22 #include <cstdint>
23 #include <cstdlib>
24
25 namespace tuningfork {
26
27 template <typename T>
Deserialize(const std::vector<uint8_t> & ser,T & pb)28 bool Deserialize(const std::vector<uint8_t> &ser, T &pb) {
29 return pb.ParseFromArray(ser.data(), ser.size());
30 }
31 template <typename T>
Serialize(const T & pb,std::vector<uint8_t> & ser)32 bool Serialize(const T &pb, std::vector<uint8_t> &ser) {
33 ser.resize(pb.ByteSize());
34 return pb.SerializeToArray(ser.data(), ser.size());
35 }
36 template <typename T>
Serialize(const T & pb)37 std::vector<uint8_t> Serialize(const T &pb) {
38 std::vector<uint8_t> ser(pb.ByteSize());
39 pb.SerializeToArray(ser.data(), ser.size());
40 return ser;
41 }
42 // Serialize to a CProtobuf. The caller takes ownership of the returned serialization and must
43 // call CProtobufSerialization_Free to deallocate any memory.
44 template <typename T>
CProtobufSerialization_Alloc(const T & pb)45 CProtobufSerialization CProtobufSerialization_Alloc(const T &pb) {
46 CProtobufSerialization cser;
47 cser.bytes = (uint8_t*)::malloc(pb.ByteSize());
48 cser.size = pb.ByteSize();
49 cser.dealloc = ::free;
50 pb.SerializeToArray(cser.bytes, cser.size);
51 return cser;
52 }
53
54 void CProtobufSerialization_Free(CProtobufSerialization* ser);
55
56 } // namespace tuningfork {
57