blob: 74d8c833c294a5fb25571d7daa211d3fe9ab06f4 [file] [log] [blame]
Nikhil Namjoshida6e5572023-03-13 10:52:53 -07001#include "bej_dictionary.h"
2#include "bej_encoder_core.h"
3#include "bej_tree.h"
4
5#include "nlohmann/json.hpp"
6
7#include <fstream>
8#include <iostream>
9#include <optional>
10#include <span>
11
12namespace libbej
13{
14
15// Buffer size for storing a single binary file data.
16constexpr uint32_t maxBufferSize = 16 * 1024;
17
18struct BejTestInputFiles
19{
20 const char* jsonFile;
21 const char* schemaDictionaryFile;
22 const char* annotationDictionaryFile;
23 const char* errorDictionaryFile;
24 const char* encodedStreamFile;
25};
26
27struct BejTestInputs
28{
29 nlohmann::json expectedJson;
30 const uint8_t* schemaDictionary;
31 const uint8_t* annotationDictionary;
32 const uint8_t* errorDictionary;
33 std::span<const uint8_t> encodedStream;
34};
35
36std::streamsize readBinaryFile(const char* fileName, std::span<uint8_t> buffer)
37{
38 std::ifstream inputStream(fileName, std::ios::binary);
39 if (!inputStream.is_open())
40 {
41 std::cerr << "Cannot open file: " << fileName << "\n";
42 return 0;
43 }
44 auto readLength = inputStream.readsome(
45 reinterpret_cast<char*>(buffer.data()), buffer.size_bytes());
46 if (inputStream.peek() != EOF)
47 {
48 std::cerr << "Failed to read the complete file: " << fileName
49 << " read length: " << readLength << "\n";
50 return 0;
51 }
52 return readLength;
53}
54
55std::optional<BejTestInputs> loadInputs(const BejTestInputFiles& files,
56 bool readErrorDictionary = false)
57{
58 std::ifstream jsonInput(files.jsonFile);
59 if (!jsonInput.is_open())
60 {
61 std::cerr << "Cannot open file: " << files.jsonFile << "\n";
62 return std::nullopt;
63 }
64 nlohmann::json expJson;
65 jsonInput >> expJson;
66
67 static uint8_t schemaDictBuffer[maxBufferSize];
68 if (readBinaryFile(files.schemaDictionaryFile,
69 std::span(schemaDictBuffer, maxBufferSize)) == 0)
70 {
71 return std::nullopt;
72 }
73
74 static uint8_t annoDictBuffer[maxBufferSize];
75 if (readBinaryFile(files.annotationDictionaryFile,
76 std::span(annoDictBuffer, maxBufferSize)) == 0)
77 {
78 return std::nullopt;
79 }
80
81 static uint8_t encBuffer[maxBufferSize];
82 auto encLen = readBinaryFile(files.encodedStreamFile,
83 std::span(encBuffer, maxBufferSize));
84 if (encLen == 0)
85 {
86 return std::nullopt;
87 }
88
89 static uint8_t errorDict[maxBufferSize];
90 if (readErrorDictionary)
91 {
92 if (readBinaryFile(files.errorDictionaryFile,
93 std::span(errorDict, maxBufferSize)) == 0)
94 {
95 return std::nullopt;
96 }
97 }
98
99 BejTestInputs inputs = {
100 .expectedJson = expJson,
101 .schemaDictionary = schemaDictBuffer,
102 .annotationDictionary = annoDictBuffer,
103 .errorDictionary = errorDict,
104 .encodedStream = std::span(encBuffer, encLen),
105 };
106 return inputs;
107}
108
109} // namespace libbej