example of parsing text straight into a buffer, and generating text back from it:
| 571 | // example of parsing text straight into a buffer, and generating |
| 572 | // text back from it: |
| 573 | void ParseAndGenerateTextTest(bool binary) { |
| 574 | // load FlatBuffer schema (.fbs) and JSON from disk |
| 575 | std::string schemafile; |
| 576 | std::string jsonfile; |
| 577 | TEST_EQ(flatbuffers::LoadFile( |
| 578 | (test_data_path + "monster_test." + (binary ? "bfbs" : "fbs")) |
| 579 | .c_str(), |
| 580 | binary, &schemafile), |
| 581 | true); |
| 582 | TEST_EQ(flatbuffers::LoadFile( |
| 583 | (test_data_path + "monsterdata_test.golden").c_str(), false, |
| 584 | &jsonfile), |
| 585 | true); |
| 586 | |
| 587 | auto include_test_path = |
| 588 | flatbuffers::ConCatPathFileName(test_data_path, "include_test"); |
| 589 | const char *include_directories[] = { test_data_path.c_str(), |
| 590 | include_test_path.c_str(), nullptr }; |
| 591 | |
| 592 | // parse schema first, so we can use it to parse the data after |
| 593 | flatbuffers::Parser parser; |
| 594 | if (binary) { |
| 595 | flatbuffers::Verifier verifier( |
| 596 | reinterpret_cast<const uint8_t *>(schemafile.c_str()), |
| 597 | schemafile.size()); |
| 598 | TEST_EQ(reflection::VerifySchemaBuffer(verifier), true); |
| 599 | //auto schema = reflection::GetSchema(schemafile.c_str()); |
| 600 | TEST_EQ(parser.Deserialize((const uint8_t *)schemafile.c_str(), schemafile.size()), true); |
| 601 | } else { |
| 602 | TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true); |
| 603 | } |
| 604 | TEST_EQ(parser.Parse(jsonfile.c_str(), include_directories), true); |
| 605 | |
| 606 | // here, parser.builder_ contains a binary buffer that is the parsed data. |
| 607 | |
| 608 | // First, verify it, just in case: |
| 609 | flatbuffers::Verifier verifier(parser.builder_.GetBufferPointer(), |
| 610 | parser.builder_.GetSize()); |
| 611 | TEST_EQ(VerifyMonsterBuffer(verifier), true); |
| 612 | |
| 613 | AccessFlatBufferTest(parser.builder_.GetBufferPointer(), |
| 614 | parser.builder_.GetSize(), false); |
| 615 | |
| 616 | // to ensure it is correct, we now generate text back from the binary, |
| 617 | // and compare the two: |
| 618 | std::string jsongen; |
| 619 | auto result = |
| 620 | GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen); |
| 621 | TEST_EQ(result, true); |
| 622 | TEST_EQ_STR(jsongen.c_str(), jsonfile.c_str()); |
| 623 | |
| 624 | // We can also do the above using the convenient Registry that knows about |
| 625 | // a set of file_identifiers mapped to schemas. |
| 626 | flatbuffers::Registry registry; |
| 627 | // Make sure schemas can find their includes. |
| 628 | registry.AddIncludeDirectory(test_data_path.c_str()); |
| 629 | registry.AddIncludeDirectory(include_test_path.c_str()); |
| 630 | // Call this with many schemas if possible. |
no test coverage detected