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 
21 using 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.
main(int,const char * [])25 int main(int /*argc*/, const char * /*argv*/[]) {
26   // load FlatBuffer schema (.fbs) and JSON from disk
27   std::string schema_file;
28   std::string json_file;
29   std::string bfbs_file;
30   bool ok =
31       flatbuffers::LoadFile("tests/monster_test.fbs", false, &schema_file) &&
32       flatbuffers::LoadFile("tests/monsterdata_test.golden", false,
33                             &json_file) &&
34       flatbuffers::LoadFile("tests/monster_test.bfbs", true, &bfbs_file);
35   if (!ok) {
36     printf("couldn't load files!\n");
37     return 1;
38   }
39 
40   const char *include_directories[] = { "samples", "tests",
41                                         "tests/include_test", nullptr };
42   // parse fbs schema
43   flatbuffers::Parser parser1;
44   ok = parser1.Parse(schema_file.c_str(), include_directories);
45   assert(ok);
46 
47   // inizialize parser by deserializing bfbs schema
48   flatbuffers::Parser parser2;
49   ok = parser2.Deserialize((uint8_t *)bfbs_file.c_str(), bfbs_file.length());
50   assert(ok);
51 
52   // parse json in parser from fbs and bfbs
53   ok = parser1.Parse(json_file.c_str(), include_directories);
54   assert(ok);
55   ok = parser2.Parse(json_file.c_str(), include_directories);
56   assert(ok);
57 
58   // to ensure it is correct, we now generate text back from the binary,
59   // and compare the two:
60   std::string jsongen1;
61   if (!GenerateText(parser1, parser1.builder_.GetBufferPointer(), &jsongen1)) {
62     printf("Couldn't serialize parsed data to JSON!\n");
63     return 1;
64   }
65 
66   std::string jsongen2;
67   if (!GenerateText(parser2, parser2.builder_.GetBufferPointer(), &jsongen2)) {
68     printf("Couldn't serialize parsed data to JSON!\n");
69     return 1;
70   }
71 
72   if (jsongen1 != jsongen2) {
73     printf("%s----------------\n%s", jsongen1.c_str(), jsongen2.c_str());
74   }
75 
76   printf("The FlatBuffer has been parsed from JSON successfully.\n");
77 }
78