blob: 94b982a278042492ac958627f6e1d0b3afbf12ec [file] [log] [blame]
Austin Schuh3e95e5d2019-09-20 00:08:54 -07001#ifndef AOS_JSON_TO_FLATBUFFER_H_
2#define AOS_JSON_TO_FLATBUFFER_H_
3
4#include <cstddef>
5#include <string>
James Kuszmaul3ae42262019-11-08 12:33:41 -08006#include <string_view>
Austin Schuh3e95e5d2019-09-20 00:08:54 -07007
Austin Schuhe93d8642019-10-13 15:27:07 -07008#include "aos/flatbuffers.h"
Austin Schuh3e95e5d2019-09-20 00:08:54 -07009#include "flatbuffers/flatbuffers.h"
10
11namespace aos {
12
13// Parses the flatbuffer into the vector, or returns an empty vector.
Austin Schuhe93d8642019-10-13 15:27:07 -070014flatbuffers::DetachedBuffer JsonToFlatbuffer(
James Kuszmaul3ae42262019-11-08 12:33:41 -080015 const std::string_view data,
16 const flatbuffers::TypeTable *typetable);
Austin Schuh3e95e5d2019-09-20 00:08:54 -070017
18// Converts a flatbuffer into a Json string.
Austin Schuh3e95e5d2019-09-20 00:08:54 -070019// multi_line controls if the Json is written out on multiple lines or one.
Austin Schuhe93d8642019-10-13 15:27:07 -070020// The methods below are generally more useful than BufferFlatbufferToJson and
21// TableFlatbufferToJson.
22::std::string BufferFlatbufferToJson(const uint8_t *buffer,
23 const flatbuffers::TypeTable *typetable,
24 bool multi_line = false);
25
26::std::string TableFlatbufferToJson(const flatbuffers::Table *t,
27 const ::flatbuffers::TypeTable *typetable,
28 bool multi_line);
29
30// Converts a DetachedBuffer holding a flatbuffer to JSON.
31inline ::std::string FlatbufferToJson(const flatbuffers::DetachedBuffer &buffer,
32 const flatbuffers::TypeTable *typetable,
33 bool multi_line = false) {
34 return BufferFlatbufferToJson(buffer.data(), typetable, multi_line);
35}
36
37// Converts a Flatbuffer<T> holding a flatbuffer to JSON.
38template <typename T>
39inline ::std::string FlatbufferToJson(const Flatbuffer<T> &flatbuffer,
40 bool multi_line = false) {
41 return BufferFlatbufferToJson(
42 flatbuffer.data(), Flatbuffer<T>::MiniReflectTypeTable(), multi_line);
43}
44
45// Converts a flatbuffer::Table to JSON.
46template <typename T>
47typename std::enable_if<
48 std::is_base_of<flatbuffers::Table, T>::value,
49 std::string>::type inline FlatbufferToJson(const T *flatbuffer,
50 bool multi_line = false) {
51 return TableFlatbufferToJson(
52 reinterpret_cast<const flatbuffers::Table *>(flatbuffer),
53 Flatbuffer<T>::MiniReflectTypeTable(), multi_line);
54}
Austin Schuh3e95e5d2019-09-20 00:08:54 -070055
Austin Schuh3e95e5d2019-09-20 00:08:54 -070056} // namespace aos
57
58#endif // AOS_JSON_TO_FLATBUFFER_H_