flatbuffers
78 строк · 2.7 Кб
1/*
2* Copyright 2014 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#include "flatbuffers/idl.h"
18#include "flatbuffers/util.h"
19#include "monster_generated.h" // Already includes "flatbuffers/flatbuffers.h".
20
21using namespace MyGame::Sample;
22
23// This is an example of parsing text straight into a buffer and then
24// generating flatbuffer (JSON) text from the buffer.
25int main(int /*argc*/, const char * /*argv*/[]) {
26// load FlatBuffer schema (.fbs) and JSON from disk
27std::string schema_file;
28std::string json_file;
29std::string bfbs_file;
30bool ok =
31flatbuffers::LoadFile("tests/monster_test.fbs", false, &schema_file) &&
32flatbuffers::LoadFile("tests/monsterdata_test.golden", false,
33&json_file) &&
34flatbuffers::LoadFile("tests/monster_test.bfbs", true, &bfbs_file);
35if (!ok) {
36printf("couldn't load files!\n");
37return 1;
38}
39
40const char *include_directories[] = { "samples", "tests",
41"tests/include_test", nullptr };
42// parse fbs schema
43flatbuffers::Parser parser1;
44ok = parser1.Parse(schema_file.c_str(), include_directories);
45assert(ok);
46
47// inizialize parser by deserializing bfbs schema
48flatbuffers::Parser parser2;
49ok = parser2.Deserialize(reinterpret_cast<const uint8_t *>(bfbs_file.c_str()),
50bfbs_file.length());
51assert(ok);
52
53// parse json in parser from fbs and bfbs
54ok = parser1.Parse(json_file.c_str(), include_directories);
55assert(ok);
56ok = parser2.Parse(json_file.c_str(), include_directories);
57assert(ok);
58
59// to ensure it is correct, we now generate text back from the binary,
60// and compare the two:
61std::string jsongen1;
62if (GenText(parser1, parser1.builder_.GetBufferPointer(), &jsongen1)) {
63printf("Couldn't serialize parsed data to JSON!\n");
64return 1;
65}
66
67std::string jsongen2;
68if (GenText(parser2, parser2.builder_.GetBufferPointer(), &jsongen2)) {
69printf("Couldn't serialize parsed data to JSON!\n");
70return 1;
71}
72
73if (jsongen1 != jsongen2) {
74printf("%s----------------\n%s", jsongen1.c_str(), jsongen2.c_str());
75}
76
77printf("The FlatBuffer has been parsed from JSON successfully.\n");
78}
79