-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataIO.cpp
More file actions
707 lines (602 loc) · 24.2 KB
/
Copy pathDataIO.cpp
File metadata and controls
707 lines (602 loc) · 24.2 KB
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
/* File: DataIO.cpp
Project: Kanabo
Purpose: Reads and writes the data found in fields of Oni game data files. Responsible for understanding every core type of data Oni uses.
Notes: This is not a class but merely a collection of utility functions. Actual disk reads/writes are performed by DiskItem. The header for
this source file is at the lowest level of the project, being included by every other source file. Thus the functions provided in this
namespace may be used by any source file that finds them helpful.
Margin Guide: |----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- -----|
Copyright 2026 Iritscen */
#include "DataIO.hpp"
#include <algorithm> // needed on Windows for ranges::reverse
#include <array> // needed on Windows for std::array
#include <chrono> // needed for std::chrono
#include <format> // needed on Windows for std::format
#include <iomanip> // needed on Windows for setw(), setfill()
#include <iostream> // for cout, cerr
#include <numeric> // for iota()
using std::array;
using std::bit_cast;
using std::cerr;
using std::chrono::seconds;
using std::chrono::system_clock;
using std::chrono::time_point;
using std::cout;
using std::format;
using std::hex;
using std::is_arithmetic;
using std::is_floating_point_v;
using std::is_same_v;
using std::map;
using std::nullopt;
using std::optional;
using std::ranges::reverse;
using std::setfill;
using std::setw;
using std::span;
using std::stoi;
using std::string;
using std::vector;
constexpr int kBaseDec = 1000;
constexpr int kBaseBin = 1024;
constexpr array<string, 4> kUnitsDec = {"bytes", "kB", "MB", "GB"};
constexpr array<string, 4> kUnitsBin = {"bytes", "KiB", "MiB", "GiB"};
namespace // enforce internal linkage
{
ByteOrder kEndianMode = ByteOrder::LE;
}
namespace DataIO
{
/************************** Public Functions **************************/
// A dispatch which takes "var", looks at what alternative is being used (see note on FieldU16's class constructor), and reads into that variant
// the data found at the given offset in "file"; if "offset" is not supplied, the file's current read position is used
bool ReadData(ValueVariant & var, DiskItem & file, optional<size_t> offset, optional<size_t> numBytes)
{
if (holds_alternative<uint8_t>(var))
return ReadNum(get<uint8_t>(var), file, offset);
else if (holds_alternative<int16_t>(var))
return ReadNum(get<int16_t>(var), file, offset);
else if (holds_alternative<uint16_t>(var))
return ReadNum(get<uint16_t>(var), file, offset);
else if (holds_alternative<int32_t>(var))
return ReadNum(get<int32_t>(var), file, offset);
else if (holds_alternative<uint32_t>(var))
return ReadNum(get<uint32_t>(var), file, offset);
else if (holds_alternative<uint64_t>(var))
return ReadNum(get<uint64_t>(var), file, offset);
else if (holds_alternative<float_t>(var))
return ReadNum(get<float_t>(var), file, offset);
else if (holds_alternative<string>(var))
return ReadString(get<string>(var), file, offset);
else if (holds_alternative<vector<char>>(var))
{
if (numBytes.has_value() && *numBytes > 0)
return ReadBytes(get<vector<char>>(var), file, *numBytes, offset);
}
// else
return false;
}
// An alternate version of the above which takes a span of data instead of a DiskItem
bool ReadData(ValueVariant & var, span<char> data, optional<size_t> offset, optional<size_t> numBytes)
{
if (holds_alternative<uint8_t>(var))
return ReadNum(get<uint8_t>(var), data, offset);
else if (holds_alternative<int16_t>(var))
return ReadNum(get<int16_t>(var), data, offset);
else if (holds_alternative<uint16_t>(var))
return ReadNum(get<uint16_t>(var), data, offset);
else if (holds_alternative<int32_t>(var))
return ReadNum(get<int32_t>(var), data, offset);
else if (holds_alternative<uint32_t>(var))
return ReadNum(get<uint32_t>(var), data, offset);
else if (holds_alternative<uint64_t>(var))
return ReadNum(get<uint64_t>(var), data, offset);
else if (holds_alternative<float_t>(var))
return ReadNum(get<float_t>(var), data, offset);
else if (holds_alternative<string>(var))
return ReadString(get<string>(var), data, offset);
else if (holds_alternative<vector<char>>(var))
{
if (numBytes.has_value() && *numBytes > 0)
return ReadBytes(get<vector<char>>(var), data, *numBytes, offset);
}
// else
return false;
}
// A dispatch which takes "var", looks at what alternative is being used, and writes that data to the buffer
bool WriteData(vector<char> & dst, const ValueVariant & var, optional<size_t> numBytes)
{
if (holds_alternative<uint8_t>(var))
return WriteNum(dst, get<uint8_t>(var));
else if (holds_alternative<int16_t>(var))
return WriteNum(dst, get<int16_t>(var));
else if (holds_alternative<uint16_t>(var))
return WriteNum(dst, get<uint16_t>(var));
else if (holds_alternative<int32_t>(var))
return WriteNum(dst, get<int32_t>(var));
else if (holds_alternative<uint32_t>(var))
return WriteNum(dst, get<uint32_t>(var));
else if (holds_alternative<uint64_t>(var))
return WriteNum(dst, get<uint64_t>(var));
else if (holds_alternative<float_t>(var))
return WriteNum(dst, get<float_t>(var));
else if (holds_alternative<string>(var))
return WriteString(dst, get<string>(var), numBytes);
else if (holds_alternative<span<char>>(var))
return WriteBytes(dst, get<span<char>>(var));
else if (holds_alternative<vector<char>>(var))
return WriteBytes(dst, get<vector<char>>(var));
// else
return false;
}
// Allows user to switch between reading data from disk as little-endian or big-endian
void SetEndianMode(ByteOrder newOrder)
{
kEndianMode = newOrder;
}
// A wrapper for HexPrintGeneric() that prints the given number in big-endian in-memory style
void HexPrintNum_Mem(uint64_t num, size_t bytes)
{
HexPrintGeneric(num, bytes, ByteFlip::Yes, DisplayStyle::Mem);
}
// A wrapper for HexPrintGeneric() that prints the given number in little-endian on-disk style
void HexPrintNum_DiskLE(uint64_t num, size_t bytes)
{
HexPrintGeneric(num, bytes, ByteFlip::No, DisplayStyle::Disk);
}
// A wrapper for HexPrintGeneric() that prints the given number in big-endian on-disk style
void HexPrintNum_DiskBE(uint64_t num, size_t bytes)
{
HexPrintGeneric(num, bytes, ByteFlip::Yes, DisplayStyle::Disk);
}
// A wrapper for HexPrintGeneric() that prints a vector of raw bytes in big-endian in-memory style
void HexPrintData_Mem(vector<char> & data)
{
HexPrintGeneric(data, ByteFlip::Yes, DisplayStyle::Mem);
}
// A wrapper for HexPrintGeneric() that prints a vector of raw bytes in little-endian on-disk style
void HexPrintData_DiskLE(vector<char> & data)
{
HexPrintGeneric(data, ByteFlip::No, DisplayStyle::Disk);
}
// A wrapper for HexPrintGeneric() that prints a vector of raw bytes in big-endian on-disk style
void HexPrintData_DiskBE(vector<char> & data)
{
HexPrintGeneric(data, ByteFlip::Yes, DisplayStyle::Disk);
}
// Print a date stored in our proprietary 24-bit format
string PrintDate24(uint32_t rawDate)
{
string s = format("20{:02}/{:02}/{:02}", uint8_t(rawDate >> (8 * 3)), uint8_t(rawDate >> (8 * 2)), uint8_t(rawDate >> (8 * 1)));
return s;
}
// Return an int that represents the supplied date in yyyy/mm/dd format
uint32_t IntFromDateStr(string & dateStr)
{
if (dateStr.length() != 10)
return 0;
for (char c : dateStr)
{
if (c != '/' && (c < '0' || c > '9'))
return 0;
}
uint8_t yy = static_cast<uint8_t>(stoi(dateStr.substr(2, 2))); // extract the "yy" in "YYyy"
uint8_t mm = static_cast<uint8_t>(stoi(dateStr.substr(5, 2)));
uint8_t dd = static_cast<uint8_t>(stoi(dateStr.substr(8, 2)));
return (uint32_t(yy) << 16) | (uint32_t(mm) << 8) | dd;
}
// Print a date stored in a standard 32-bit format: the number of seconds since 1970-01-01
string PrintDate32(uint32_t rawDate)
{
string s;
uint32_t date_rawSecs = rawDate;
time_point date_timePoint = system_clock::time_point(seconds(date_rawSecs));
time_t date_time_t = system_clock::to_time_t(date_timePoint);
char timeStr[25] = {}; // "yyyy-mm-dd hh:mm:ss a.m." + 1
tm localTime = {};
#if MAC
void * localTimePtr = localtime_r(&date_time_t, &localTime);
errno_t result = (localTimePtr == NULL);
#elif WIN
errno_t result = localtime_s(&localTime, &date_time_t);
#endif
if (result)
{
s = "Failed to obtain the local time.";
return s;
}
size_t result2 = strftime(timeStr, sizeof(timeStr), "%F %r", &localTime);
if (not result2 || not strlen(timeStr))
{
s = "Failed to convert the time.";
return s;
}
s = timeStr;
return s;
}
// Prints data sizes in a human-readable manner, using the size units under the specified system(s). Note the defaults for this function in its
// prototype. "magThreshold" is used to tell PrintSize() to not use the best-fit unit unless the number exceeds a certain magnitude, e.g. if
// "magThreshold" is 1 and the size is 2,100 bytes, it will print as "2,100 bytes" instead of "2.1 KB", but 2,100,000 bytes is 'mag 2' so, being
// over the threshold it would still print as "2.1 MB". This approach is sometimes preferable for readability. "adjective" will print "bytes" as
// "byte" so that the size string is grammatically suitable for preceding a noun, e.g. "100 byte file".
string PrintSize(uint64_t size, UnitSystem sys, int magThreshold, bool adjective)
{
double bytesDec = static_cast<double>(size), bytesBin = static_cast<double>(size);
int magDec = 0, magBin = 0;
string s = format("{} bytes", size), unitDec = "<unit not found!>", unitBin = "<unit not found!>";
// Determine magnitude of the size in base-2 units
if (sys == UnitSystem::Binary || sys == UnitSystem::Both)
{
while (bytesBin > kBaseBin)
{
bytesBin /= (double)kBaseBin;
magBin++;
}
if (magBin < 4)
unitBin = kUnitsBin[static_cast<size_t>(magBin)];
}
// Determine magnitude of the size in base-10 units
if (sys == UnitSystem::Decimal || sys == UnitSystem::Both)
{
while (bytesDec > kBaseDec)
{
bytesDec /= (double)kBaseDec;
magDec++;
}
if (magDec < 4)
unitDec = kUnitsDec[static_cast<size_t>(magDec)];
}
// If we're over the threshold, create a string in the requested unit system(s), otherwise just return "s" as it was initialized, in bytes
if (magBin > magThreshold || magDec > magThreshold)
{
switch(sys)
{
case UnitSystem::Binary:
s = format("{:.2f} {}", bytesBin, unitBin);
break;
case UnitSystem::Decimal:
s = format("{:.2f} {}", bytesDec, unitDec);
break;
case UnitSystem::Both:
s = format("{:.2f} {} ({:.2f} {})", bytesDec, unitDec, bytesBin, unitBin);
break;
}
}
if (adjective)
{
size_t pos = s.find("bytes");
if (pos != string::npos)
s.replace(pos, 5, "byte");
}
return s;
}
// Return whether "flagCode" (a value from an enum that defines flag codes) is present in "bitset", given the pointer "valuesPtr" to a map that
// relates flag codes to bit positions
bool TestFlag(MapCodeToVal * valuesPtr, uint32_t bitset, uint32_t flagCode)
{
if (valuesPtr == nullptr)
{
cout << "TestFlag() received null pointer for map.\n";
return false;
}
if ((*valuesPtr).contains(flagCode))
{
uint32_t flagBit = (*valuesPtr).at(flagCode);
return (bitset & flagBit);
}
else
return false;
}
// Perform a lookup of the name of a flag from its code, using "namesPtr" as the lookup table
string GetFlagName(MapCodeToName * namesPtr, uint32_t flagCode)
{
if (namesPtr == nullptr)
return "GetFlagName() received null pointer for map.\n";
if ((*namesPtr).contains(flagCode))
return (*namesPtr).at(flagCode);
else
return format("(lookup of bit value {} failed!)", flagCode);
}
// Construct a sentence listing the names of the flags in "bitset". "valuesPtr" is used as the lookup table from bit to flag code, and
// "namesPtr" is the lookup table from flag code to name. Pass this function "nullptr" for the first two arguments in order to deliberately
// raw-print the bitset in binary.
string ListFlags(MapCodeToVal * valuesPtr, MapCodeToName * namesPtr, uint32_t bitset)
{
if (valuesPtr == nullptr || namesPtr == nullptr)
return format("unnamed flag set ({:b})", bitset);
string s;
uint32_t flagCopy = bitset; // for recording if we failed to identify any bits
for (auto & [code, bit] : *valuesPtr)
{
if (bitset & bit)
{
s += (not s.empty() ? ", " : "") + GetFlagName(namesPtr, code);
flagCopy &= ~bit; // mark bit as handled
}
}
if (flagCopy)
s += (not s.empty() ? ", " : "") + format("unknown bits {:b}", flagCopy);
return s;
}
// Return whether "typeCode" (a value from an enum that defines type codes) is represented in "value", given the pointer "valuesPtr" to a map
// that relates type codes to bit positions
bool TestCode(MapCodeToVal * valuesPtr, uint32_t value, uint32_t typeCode)
{
if (valuesPtr == nullptr)
{
cout << "TestCode() received null pointer for map.\n";
return false;
}
if ((*valuesPtr).contains(typeCode))
return value == static_cast<uint32_t>((*valuesPtr).at(typeCode));
else
return false;
}
// Perform a lookup of the name of a type from its code, using "namesPtr" as the lookup table
string GetTypeName(MapCodeToName * namesPtr, uint32_t typeCode)
{
if (namesPtr == nullptr)
return "GetTypeName() received null pointer for map.\n";
if ((*namesPtr).contains(typeCode))
return (*namesPtr).at(typeCode);
else
return format("(lookup of type value {} failed!)", typeCode);
}
// Perform a lookup of the enum code of a type from its value on disk, using "valuesPtr" as the lookup table
uint32_t GetTypeCode(MapCodeToVal * valuesPtr, uint32_t typeVal)
{
uint32_t result = 0;
if (valuesPtr == nullptr)
return result;
for (auto & [code, val] : *valuesPtr)
{
if (val == typeVal)
result = code;
}
return result;
}
/************************** Private Functions *************************/
// Reads any integral type stored on disk in little-endian format: bool, char, intX_t, uintX_t, etc. Specializations of this function are found
// below the definition.
template <typename T> bool ReadNum(T & dst, DiskItem & src, optional<size_t> offset)
{
static_assert(is_arithmetic<T>::value, "ReadNum() was asked to read a non-arithmetic type.");
uint64_t result64 = 0;
unsigned long theSize = sizeof(T);
optional<span<char>> bytes = src.read(ReadStopCondition::FixedBytes, theSize, offset);
if (not bytes.has_value() || bytes->size() != theSize)
return false;
result64 = BuildNum(*bytes);
if constexpr (is_floating_point_v<T>)
dst = bit_cast<float>((int32_t)result64);
else
dst = static_cast<T>(result64);
return true;
}
// Specialized definitions of the above function used in other TUs, so that the compiler instantiates them and the linker is satisfied
template bool ReadNum<uint8_t>(uint8_t &, DiskItem &, optional<size_t>);
template bool ReadNum<uint16_t>(uint16_t &, DiskItem &, optional<size_t>);
template bool ReadNum<uint32_t>(uint32_t &, DiskItem &, optional<size_t>);
template bool ReadNum<uint64_t>(uint64_t &, DiskItem &, optional<size_t>);
template bool ReadNum<float_t>(float_t &, DiskItem &, optional<size_t>);
// An alternate version of the above which takes a span of data instead of a DiskItem
template <typename T> bool ReadNum(T & dst, span<char> src, optional<size_t> offset)
{
static_assert(is_arithmetic<T>::value, "ReadNum() was asked to read a non-arithmetic type.");
uint64_t result64 = 0;
unsigned long theSize = sizeof(T);
if (offset.has_value())
{
if (*offset > src.size() || src.size() - *offset < theSize)
{
cerr << "Error: ReadNum (span type) had an out of bounds error.\n";
return false;
}
result64 = BuildNum(src.subspan(*offset, theSize));
}
else
{
if (src.size() < theSize)
{
cerr << "Error: ReadNum (span type) was passed less data than the type it's supposed to read.\n";
return false;
}
result64 = BuildNum(src.subspan(0, theSize));
}
if constexpr (is_floating_point_v<T>)
dst = bit_cast<float>((int32_t)result64);
else
dst = static_cast<T>(result64);
return true;
}
// Specializations
template bool ReadNum<uint8_t>(uint8_t &, span<char>, optional<size_t>);
template bool ReadNum<uint16_t>(uint16_t &, span<char>, optional<size_t>);
template bool ReadNum<uint32_t>(uint32_t &, span<char>, optional<size_t>);
template bool ReadNum<uint64_t>(uint64_t &, span<char>, optional<size_t>);
template bool ReadNum<float_t>(float_t &, span<char>, optional<size_t>);
// Reads a string from disk
template <typename T> bool ReadString(T & dst, DiskItem & src, optional<size_t> offset)
{
static_assert(is_same_v<T, string>, "ReadString() was asked to read a non-string.");
optional<span<char>> optStr = src.read(ReadStopCondition::TillEOS, nullopt, offset);
if (optStr.has_value())
{
string str((*optStr).data(), (*optStr).size());
dst = str;
}
else
dst = "";
return true;
}
// Specializations
template bool ReadString<string>(string &, DiskItem &, optional<size_t>);
// An alternate version of the above which takes a span of data instead of a DiskItem
template <typename T> bool ReadString(T & dst, span<char> src, optional<size_t> offset)
{
static_assert(is_same_v<T, string>, "ReadString() was asked to read a non-string.");
span<char> sub = (offset.has_value() ? src.subspan(*offset) : src);
sub = ReadStringUntil(sub, ReadStopCondition::TillEOS);
string str(sub.begin(), sub.end());
dst = str;
return true;
}
// Specializations
template bool ReadString<string>(string &, span<char>, optional<size_t>);
// Reads an arbitrary number of bytes from disk into a vector<char>
template <typename T> bool ReadBytes(T & dst, DiskItem & src, size_t numBytes, optional<size_t> offset)
{
static_assert(is_same_v<T, vector<char>>, "ReadBytes() was asked to read into a non-vector<char> type.");
optional<span<char>> bytes = src.read(ReadStopCondition::FixedBytes, numBytes, offset);
if (not bytes.has_value() || bytes->size() != numBytes)
return false;
dst.clear();
dst.insert(dst.end(), bytes->begin(), bytes->end());
return true;
}
// Specializations
template bool ReadBytes<vector<char>>(vector<char> &, DiskItem &, size_t, optional<size_t>);
// An alternate version of the above which takes a span of data instead of a DiskItem
template <typename T> bool ReadBytes(T & dst, span<char> src, size_t numBytes, optional<size_t> offset)
{
static_assert(is_same_v<T, vector<char>>, "ReadBytes() was asked to read into a non-vector<char> type.");
if (offset.has_value())
{
if (*offset > src.size() || src.size() - *offset < numBytes)
return false;
dst.clear();
dst.insert(dst.end(), src.begin() + static_cast<ptrdiff_t>(*offset),
src.begin() + static_cast<ptrdiff_t>(*offset) + static_cast<ptrdiff_t>(numBytes));
}
else
{
if (src.size() < numBytes)
return false;
dst.clear();
dst.insert(dst.end(), src.begin(), src.begin() + static_cast<ptrdiff_t>(numBytes));
}
return true;
}
// Specializations
template bool ReadBytes<vector<char>>(vector<char> &, span<char>, size_t, optional<size_t>);
// Writes any integral type to the buffer in little-endian format
template <typename T> bool WriteNum(vector<char> & dst, T src)
{
static_assert(is_arithmetic<T>::value, "WriteNum() was asked to write a non-arithmetic type.");
uint64_t src64 = 0;
size_t theSize = sizeof(T);
if (is_floating_point_v<T>)
src64 = bit_cast<uint32_t>(static_cast<float>(src));
else
src64 = static_cast<uint64_t>(src);
// Build list of bytes in order we'll write them based on endianness
vector<size_t> byte_seq(theSize);
iota(byte_seq.begin(), byte_seq.end(), size_t{0});
vector<size_t> byte_mag(byte_seq);
if (kEndianMode == ByteOrder::BE)
reverse(byte_mag);
// Write the bytes
for (size_t i : byte_seq)
{
uint8_t byte = (src64 >> (byte_mag[i] * 8)) & 0xFF;
dst.push_back(static_cast<char>(byte));
}
return true;
}
// Specializations
template bool WriteNum<uint8_t>(vector<char> &, uint8_t);
template bool WriteNum<uint16_t>(vector<char> &, uint16_t);
template bool WriteNum<uint32_t>(vector<char> &, uint32_t);
template bool WriteNum<uint64_t>(vector<char> &, uint64_t);
template bool WriteNum<float_t>(vector<char> &, float_t);
// Writes a string to the buffer, including null terminator. If "numBytes" has a value, we add as much zero padding to the end of the string as
// necessary to meet that length.
bool WriteString(vector<char> & dst, const string & src, optional<size_t> numBytes)
{
dst.insert(dst.end(), src.begin(), src.end());
size_t endBytes = (numBytes.has_value() && *numBytes > src.size() ? *numBytes - src.size() : 1);
vector<char> endPadding;
endPadding.resize(endBytes, '\0');
dst.insert(dst.end(), endPadding.begin(), endPadding.end());
return true;
}
// Writes raw bytes to the buffer
bool WriteBytes(vector<char> & dst, span<char> src)
{
dst.insert(dst.end(), src.begin(), src.end());
return true;
}
bool WriteBytes(vector<char> & dst, const vector<char> & src)
{
dst.insert(dst.end(), src.begin(), src.end());
return true;
}
// Prints a number's constituent bytes in the desired order and style; "bytes" is used to specify the actual size of "num", as it doesn't have
// to be a uint64_t
void HexPrintGeneric(uint64_t num, size_t bytes, ByteFlip flip, DisplayStyle style)
{
// Determine order in which we will print the bytes of "num"
vector<int> byte_seq(bytes);
iota(byte_seq.begin(), byte_seq.end(), 0);
if (flip == ByteFlip::Yes)
reverse(byte_seq);
// Prep for desired style of printing
string spacer = " ";
if (style == DisplayStyle::Mem)
{
cout << "0x";
spacer = "";
}
// Print bytes
for (int i : byte_seq)
{
unsigned char byte = static_cast<uint8_t>((num >> (i * 8)) & 0xFF);
cout << hex << setw(2) << setfill('0') << static_cast<int>(byte) << spacer;
}
}
// Alternate version that takes a vector of raw bytes instead of a number
void HexPrintGeneric(vector<char> data, ByteFlip flip, DisplayStyle style)
{
if (flip == ByteFlip::Yes)
reverse(data);
// Prep for desired style of printing
string spacer = " ";
if (style == DisplayStyle::Mem)
{
cout << "0x";
spacer = "";
}
// Print bytes
for (char c : data)
cout << hex << setw(2) << setfill('0') << static_cast<uint8_t>(c) << spacer;
}
// Builds an int from the supplied bytes
uint64_t BuildNum(span<char> data)
{
uint64_t result = 0;
// Build a list of the bytes in the order we'll read them and the size of each one per the given endianness
vector<size_t> byte_seq(data.size());
iota(byte_seq.begin(), byte_seq.end(), size_t{0});
vector<size_t> byte_mag(byte_seq);
if (kEndianMode == ByteOrder::BE)
reverse(byte_mag);
// Build the int from the bytes
for (size_t i : byte_seq)
{
uint64_t byte = static_cast<uint8_t>(data[i]);
result |= byte << (byte_mag[i] * 8);
}
return result;
}
span<char> ReadStringUntil(span<char> data, ReadStopCondition cond)
{
size_t i = 0;
char stopChar = (cond == ReadStopCondition::TillEOL ? '\n' : '\0');
for (char c : data)
{
if (c == stopChar)
break;
i++;
}
return span<char>(data.data(), i);
}
} // end namespace