-
Notifications
You must be signed in to change notification settings - Fork 2
/
actionscollection.cpp
506 lines (418 loc) · 14.5 KB
/
actionscollection.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
#include "stdafx.h"
#include "actionscollection.h"
#include "binarylexeme.h"
#include "dictionary.h"
#include "dictionarykeywords.h"
#include "fileprocessing.h"
#include "jsonparser.h"
#include "bpatchfolders.h"
namespace bpatch
{
// ways to our data
namespace
{
constexpr const size_t levelBase = 1; // dictionary, todo
constexpr const size_t levelReplaceIn = 3;
constexpr const size_t levelReplaceObject = 5;
constexpr const size_t levelArray = 5;
constexpr const size_t levelTextObject = 5;
constexpr const size_t levelFileObject = 5;
///@brief check for "dictionary" or "todo"
/// with help of this function
template <const std::string_view& sv1>
bool JsonAtLevel1(TJSONObject* const pJson)
{
return (levelBase == pJson->level_ &&
0 == sv1.compare(pJson->name_));
};
///@brief check the node at level 3 under
/// "dictionary" or "todo"
/// with help of this function
template <const std::string_view& sv1, const std::string_view& sv3>
bool JsonAtLevel1_3(TJSONObject* const pJson)
{
return (3 == pJson->level_ &&
0 == sv3.compare(pJson->name_) &&
JsonAtLevel1<sv1>(pJson->parent_->parent_));
};
///@brief check the node at level 3 under
/// "dictionary"
/// with help of this function
template <const std::string_view& sv3>
bool JsonDictLevel3(TJSONObject* const pJson)
{
return (3 == pJson->level_ &&
0 == sv3.compare(pJson->name_) &&
JsonAtLevel1<dictionarySV>(pJson->parent_->parent_));
};
/// <summary>
/// check the node with decimal arrays
/// </summary>
/// <param name="pJson">node to check</param>
/// <returns>true if it is the node with decimal numbers</returns>
bool IsDecimalArray(TJSONObject* const pJson)
{
return (levelArray == pJson->level_ &&
nullptr != pJson->name_.data() && // valid name
JsonDictLevel3<decimalSV>(pJson->parent_->parent_));
}
/// <summary>
/// check the node with decimal arrays
/// </summary>
/// <param name="pJson">node to check</param>
/// <returns>true if it is the node with hexadecimal numbers</returns>
bool IsHexadecimalArray(TJSONObject* const pJson)
{
return (levelArray == pJson->level_ &&
nullptr != pJson->name_.data() && // valid name
JsonDictLevel3<hexadecimalSV>(pJson->parent_->parent_));
}
/// <summary>
/// check the node with composites
/// </summary>
/// <param name="pJson">node to check</param>
/// <returns>true if it is the node with composite data</returns>
bool IsCompositeArray(TJSONObject* const pJson)
{
return (levelArray == pJson->level_ &&
nullptr != pJson->name_.data() && // valid name
JsonDictLevel3<compositeSV>(pJson->parent_->parent_));
}
/// <summary>
/// check the node with text
/// </summary>
/// <param name="pJson">node to check</param>
/// <returns>true if it is the node with texts</returns>
bool IsTextObject(TJSONObject* const pJson)
{
return (levelTextObject == pJson->level_ &&
nullptr != pJson->name_.data() && // valid name
JsonDictLevel3<textSV>(pJson->parent_->parent_));
}
/// <summary>
/// check the node with files
/// </summary>
/// <param name="pJson">node to check</param>
/// <returns>true if it is the node with file names</returns>
bool IsFileObject(TJSONObject* const pJson)
{
return (levelFileObject == pJson->level_ &&
nullptr != pJson->name_.data() && // valid name
JsonDictLevel3<fileSV>(pJson->parent_->parent_));
}
/// <summary>
/// check the node with replace description
/// </summary>
/// <param name="pJson">node to check</param>
/// <returns>true if it is the node with decimal numbers</returns>
bool IsReplaceObject(TJSONObject* const pJson)
{
return (levelReplaceObject == pJson->level_ &&
nullptr != pJson->name_.data() && // valid name
JsonAtLevel1_3<todoSV, replaceSV>(pJson->parent_->parent_));
}
}; // nameless namespace
//--------------------------------------------------
ActionsCollection::ActionsCollection(std::vector<char>&& dataSource)
: jsondata_(std::move(dataSource))
{
std::string_view srcView(jsondata_.data(), jsondata_.size());
[[maybe_unused]] TJSONObject::PTR_JSON everything = TJSONObject::CreateJSONObject(srcView, this);
ProcessComposites();
// setup replacers chain
CreateChainOfReplacers();
}
void ActionsCollection::OnJsonObjectBegins(TJSONObject* const pJson)
{
if (0 == replaceSV.compare(pJson->name_) && pJson->level_ == levelReplaceIn)
{
replaces_.emplace_back(VectorStringviewPairs());
}
}
void ActionsCollection::OnJsonObjectParsed(TJSONObject* const pJson)
{
if (IsTextObject(pJson))
{
auto [exists, value] = pJson->JsonValue(0);
if (!exists)
{
ReportError("Expecting string value in text objects of dictionary");
}
if (const bool added = dictionary_.AddBinaryLexeme(pJson->name_,
AbstractBinaryLexeme::LexemeFromStringView(value));
!added)
{// overwritten
ReportDuplicateNameError(pJson->name_);
}
return;
}
if (IsFileObject(pJson))
{
using namespace std;
auto [exists, fileName] = pJson->JsonValue(0);
if (!exists)
{
ReportError("Expecting names in file objects of dictionary");
}
// load file
//
// set string with file name - zero terminated
// to use in logic
const_cast<char*>(fileName.data())[fileName.size()] = '\0';
// read file data
vector<char> adata;
if (!ReadFullFile(adata, fileName.data(), FolderBinaryPatterns()))
{
stringstream ss;
ss << "Failed to read file '" << fileName << "' which has been mentioned in Actions file";
throw logic_error(ss.str().c_str());
}
// create binary lexeme from readed data
if (const bool added = dictionary_.AddBinaryLexeme(pJson->name_,
AbstractBinaryLexeme::LexemeFromVector(move(adata)));
!added)
{// overwritten
ReportDuplicateNameError(pJson->name_);
}
return;
}
if (IsReplaceObject(pJson))
{
auto [exists, value] = pJson->JsonValue(0);
if (!exists)
{
ReportError("Expecting string in todo array objects of dictionary");
}
replaces_.rbegin()->emplace_back(
std::pair<std::string_view, std::string_view>(pJson->name_, value));
return;
}
}
void ActionsCollection::OnJsonArrayBegins(TJSONObject* const)
{
}
void ActionsCollection::OnJsonArrayParsed(TJSONObject* const pJson)
{
if (IsDecimalArray(pJson))
{
std::string_view value =
ParseDictionaryArray(pJson, 10,
"Expecting only values [0..255] in \"decimal\" dictionarys");
if (const bool added = dictionary_.AddBinaryLexeme(pJson->name_,
AbstractBinaryLexeme::LexemeFromStringView(value));
!added) [[unlikely]]
{// overwritten
ReportDuplicateNameError(pJson->name_);
}
return;
}
if (IsHexadecimalArray(pJson))
{
std::string_view value =
ParseDictionaryArray(pJson, 16,
"Expecting only string values [00..FF] in \"hexadecimal\" dictionarys");
if (const bool added = dictionary_.AddBinaryLexeme(pJson->name_,
AbstractBinaryLexeme::LexemeFromStringView(value));
!added) [[unlikely]]
{// overwritten
ReportDuplicateNameError(pJson->name_);
}
return;
}
if (IsCompositeArray(pJson))
{
composites_.emplace_back(pJson->name_, ParseArray(pJson, "Composite lexemes can contain only names"));
return;
}
}
void ActionsCollection::DoReplacements(const char toProcess, const bool aEod) const
{
// pass the data through inner chain of the replacers
replacersChain_->DoReplacements(toProcess, aEod);
}
//--------------------------------------------------
/// <summary>
/// stream for bytes to replace
/// </summary>
struct StreamReplacerRouter final : public StreamReplacer
{
std::unique_ptr<StreamReplacer> pToChange_; // to pick address of this pointer
virtual void DoReplacements(const char toProcess, const bool aEod) const override
{
pToChange_->DoReplacements(toProcess, aEod);
}
virtual void SetNextReplacer(std::unique_ptr<StreamReplacer>&& pNext) override
{
std::swap(pToChange_, pNext);
}
};
//
//--------------------------------------------------
void ActionsCollection::SetNextReplacer(std::unique_ptr<StreamReplacer>&& pNext)
{
// inside the last replacer
std::swap(*replacersLast_, pNext);
}
void ActionsCollection::ReportError(const char* const message)
{
throw std::runtime_error(message);
}
void ActionsCollection::ReportDuplicateNameError(const std::string_view aname)
{
std::stringstream ss;
ss << "Duplicate name '" << aname << "' has been met in Actions file";
ReportError(ss.str().c_str());
}
void ActionsCollection::ReportMissedNameError(const std::string_view aname)
{
std::stringstream ss;
ss << "Cannot find lexeme name '" << aname << "' in Actions file";
ReportError(ss.str().c_str());
}
std::string_view ActionsCollection::ParseDictionaryArray(TJSONObject* const pJson, const int base, const char* const errorMsg)
{
// here we will hold result string view
// actuallly since we are working with underlying jsondata_
// we will modify data of json text in this logic
// to form necessary string view
char* pTarget = nullptr;
size_t rezLength = 0;
const size_t sz = pJson->ChildCount();
if (sz == 0) [[unlikely]]// empty array
{
return emptySV; // empty data - can be used to remove something
}
for (size_t i = 0; i < sz; ++i)
{
auto [exists, value] = pJson->JsonValue(i);
if (!exists)
{
pTarget = nullptr;
break; // not a string received but object
}
if (0 == i)
{ // save the pointer on first element - here we will accumulate the data
pTarget = const_cast<char*>(value.data());
}
unsigned char c = 0;
std::from_chars_result rez =
std::from_chars(value.data(), value.data() + value.size(),
c, base);
if (rez.ec != std::errc())
{ // we got something which is not a number
pTarget = nullptr;
break;
}
// add a value to the result string view
pTarget[rezLength++] = *reinterpret_cast<char*>(&c);
} // for
if (nullptr == pTarget) [[unlikely]]
{
ReportError(errorMsg); // throws
return emptySV;
}
return std::string_view(pTarget, rezLength);
}
std::vector<std::string_view> ActionsCollection::ParseArray(TJSONObject* const pJson, const char* const errorMsg)
{
const size_t sz = pJson->ChildCount();
if (sz == 0) // empty array
{
ReportError(errorMsg);
}
std::vector<std::string_view> ret;
for (size_t i = 0; i < sz; ++i)
{
auto [exists, value] = pJson->JsonValue(i);
if (!exists)
{
ReportError(errorMsg);// not a string received but object
}
ret.emplace_back(std::move(value));
}
return ret;
}
void ActionsCollection::ProcessComposites()
{
for (const auto& [name, vectorData]: composites_)
{// for every composite lexeme
std::unique_ptr<AbstractBinaryLexeme> compositeLexeme;
size_t totalLength = 0;
for (const auto& subname : vectorData)
{
// get existent lexeme
auto& existantLexeme = dictionary_.Lexeme(subname);
if (existantLexeme == nullptr)
{
ReportMissedNameError(subname);
}
const size_t len = existantLexeme->access().size();
if (compositeLexeme == nullptr) // just created
{
compositeLexeme =
AbstractBinaryLexeme::LexemeFromLexeme(existantLexeme);
totalLength = len;
continue;
}
// fill data for composite lexeme
compositeLexeme->Replace(totalLength, 0, existantLexeme);
totalLength += len;
}
// now move newly created lexeme into Dictionary
if (const bool added =
dictionary_.AddBinaryLexeme(name, std::move(compositeLexeme));
!added)
{// overwritten
ReportDuplicateNameError(name);
}
}
// everything has been processd.
// free unnecessary collection
composites_.clear();
}
void ActionsCollection::CreateChainOfReplacers()
{
if (replaces_.empty())
{
ReportError("Nothing to replace in todo array of Actions file");
}
std::unique_ptr<StreamReplacerRouter> lastInstanceOfReplacers(new StreamReplacerRouter);
replacersLast_ = &lastInstanceOfReplacers.get()->pToChange_;
replacersChain_.reset(lastInstanceOfReplacers.release());
for (auto rit = replaces_.crbegin(); rit != replaces_.crend(); ++rit) // from the end
{
const VectorStringviewPairs& vPairs = *rit;
if (vPairs.empty())// check for no replace
{
// replacements not found - actually good place for warning
std::cout << coloredconsole::toconsole("Warning: empty json \"replace\" object detected.") << std::endl;
continue;
}
// multiple replacer creation place
StreamReplacerChoice sourceTargetPairs;
for (VectorStringviewPairs::const_iterator itPair = vPairs.cbegin();
itPair != vPairs.cend(); ++itPair)
{
const auto& vpair = *itPair;
auto alexemesPair = dictionary_.LexemesPair(vpair.first, vpair.second);
if (alexemesPair.first == nullptr)
{
ReportMissedNameError(vpair.first);
}
if (alexemesPair.second == nullptr)
{
ReportMissedNameError(vpair.second);
}
sourceTargetPairs.emplace_back(std::move(alexemesPair));
}
// create replacer
std::unique_ptr<StreamReplacer> replacer = StreamReplacer::CreateReplacer(sourceTargetPairs);
// `replacer` needs to hold tail of the chain
// replacersChain_ contains the tail of chain
replacer->SetNextReplacer(std::move(replacersChain_)); // now full chain is in replacer
replacersChain_ = std::move(replacer); // now full chain is in place
} // for(auto rit = replaces_.rbegin(); rit != replaces_.rend(); ++rit)
// everything has been created. free some memory
replaces_.clear();
}
};// namespace bpatch