-
Notifications
You must be signed in to change notification settings - Fork 233
Expand file tree
/
Copy pathccapi_util_private.h
More file actions
1880 lines (1666 loc) · 61.9 KB
/
ccapi_util_private.h
File metadata and controls
1880 lines (1666 loc) · 61.9 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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef INCLUDE_CCAPI_CPP_CCAPI_UTIL_PRIVATE_H_
#define INCLUDE_CCAPI_CPP_CCAPI_UTIL_PRIVATE_H_
#ifdef _WIN32
#define timegm _mkgmtime
#endif
#include <unistd.h>
#include <algorithm>
#include <array>
#include <charconv>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <map>
#include <numeric>
#include <optional>
#include <random>
#include <regex>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "ccapi_cpp/ccapi_macro.h"
#include "ccapi_cpp/ccapi_util.h"
#include "openssl/evp.h"
#include "openssl/pem.h"
namespace ccapi {
/**
* Utilities.
*/
class UtilString {
public:
static bool startsWith(const std::string& str, const std::string& prefix) {
return str.size() >= prefix.size() && std::memcmp(str.data(), prefix.data(), prefix.size()) == 0;
}
static std::string roundInputBySignificantFigure(double input, int numSignificantFigure, int roundDirection) {
const auto& splitted = UtilString::split(UtilString::printDoubleScientific(input), 'e');
double a = std::stod(splitted.at(0)) * std::pow(10, numSignificantFigure - 1);
double b;
if (roundDirection > 0) {
b = std::ceil(a);
} else if (roundDirection < 0) {
b = std::floor(a);
} else {
b = std::round(a);
}
std::string c = std::to_string(static_cast<int>(b));
int exponent = std::stoi(splitted.at(1)) - (numSignificantFigure - 1);
std::string output;
if (exponent >= 0) {
output = c + std::string(exponent, '0');
} else if (-exponent <= c.size() - 1) {
output = c.substr(0, c.size() + exponent);
output += ".";
output += c.substr(c.size() + exponent);
} else {
// output = std::string(-exponent - c.size() + 1, '0');
// output += ".";
// output += c; // use these three code, roundInputBySignificantFigure(0.00123456, 3, 1), output is "000.124"
output = "0.";
output += std::string(-exponent - c.size(), '0');
output += c; // use these three code, roundInputBySignificantFigure(0.00123456, 3, 1), output is "0.00124"
}
return output;
}
static std::string replaceFirstOccurrence(std::string& s, const std::string& toReplace, const std::string& replaceWith) {
std::size_t pos = s.find(toReplace);
if (pos == std::string::npos) {
return s;
};
return s.replace(pos, toReplace.length(), replaceWith);
}
static bool endsWith(const std::string& mainStr, const std::string& toMatch) {
if (mainStr.size() >= toMatch.size() && mainStr.compare(mainStr.size() - toMatch.size(), toMatch.size(), toMatch) == 0) {
return true;
} else {
return false;
}
}
static std::string printDoubleScientific(double number, int precision = CCAPI_PRINT_DOUBLE_PRECISION_DEFAULT) {
std::stringstream ss;
ss << std::setprecision(precision) << std::scientific << number;
// ss << number;
return ss.str();
}
static bool isNumber(const std::string& s) {
return !s.empty() && std::find_if(s.begin(), s.end(), [](unsigned char c) { return !std::isdigit(c); }) == s.end();
}
// https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c
static std::string generateRandomString(const size_t length) {
static const auto ch_set = std::vector<char>({'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'});
static std::default_random_engine rng(std::random_device{}());
static std::uniform_int_distribution<> dist(0, ch_set.size() - 1);
static auto randchar = []() { return ch_set[dist(rng)]; };
std::string str(length, 0);
std::generate_n(str.begin(), length, randchar);
return str;
}
static std::string generateUuidV4() {
static std::random_device rd;
static std::mt19937 gen(rd());
static std::uniform_int_distribution<> dis(0, 15);
static std::uniform_int_distribution<> dis2(8, 11);
std::stringstream ss;
int i;
ss << std::hex;
for (i = 0; i < 8; i++) {
ss << dis(gen);
}
ss << "-";
for (i = 0; i < 4; i++) {
ss << dis(gen);
}
ss << "-4";
for (i = 0; i < 3; i++) {
ss << dis(gen);
}
ss << "-";
ss << dis2(gen);
for (i = 0; i < 3; i++) {
ss << dis(gen);
}
ss << "-";
for (i = 0; i < 12; i++) {
ss << dis(gen);
};
return ss.str();
}
static std::vector<std::string> split(const std::string& in, char sep) {
std::vector<std::string> r;
r.reserve(std::count(in.begin(), in.end(), sep) + 1);
for (auto p = in.begin();; ++p) {
auto q = p;
p = std::find(p, in.end(), sep);
r.emplace_back(q, p);
if (p == in.end()) {
return r;
}
}
}
static std::vector<std::string> split(const std::string& original, const std::string& delimiter) {
std::string s = original;
std::vector<std::string> output;
size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
output.emplace_back(std::move(token));
s.erase(0, pos + delimiter.length());
}
output.emplace_back(std::move(s));
return output;
}
static std::set<std::string> splitToSet(const std::string& original, const std::string& delimiter) {
std::string s = original;
std::set<std::string> output;
size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
output.insert(std::move(token));
s.erase(0, pos + delimiter.length());
}
output.insert(std::move(s));
return output;
}
static std::string join(const std::vector<std::string>& strings, const std::string& delimiter) {
switch (strings.size()) {
case 0:
return "";
case 1:
return strings.at(0);
default:
std::ostringstream joined;
std::copy(strings.begin(), strings.end() - 1, std::ostream_iterator<std::string>(joined, delimiter.c_str()));
joined << *strings.rbegin();
return joined.str();
}
}
static std::string join(const std::set<std::string>& strings, const std::string& delimiter) {
std::vector<std::string> strings_vector(strings.begin(), strings.end());
return join(strings_vector, delimiter);
}
static std::string toUpper(const std::string& input) {
std::string output(input);
std::transform(output.begin(), output.end(), output.begin(), ::toupper);
return output;
}
static std::string toLower(const std::string& input) {
std::string output(input);
std::transform(output.begin(), output.end(), output.begin(), ::tolower);
return output;
}
static std::string ltrim(const std::string& original, const std::string& chars = "\t\n\v\f\r ") {
std::string str = original;
str.erase(0, str.find_first_not_of(chars));
return str;
}
static std::string ltrim(const std::string& original, char c) {
std::string str = original;
str.erase(0, str.find_first_not_of(c));
return str;
}
static void ltrimInPlace(std::string& str, const std::string& chars = "\t\n\v\f\r ") { str.erase(0, str.find_first_not_of(chars)); }
static void ltrimInPlace(std::string& str, char c) { str.erase(0, str.find_first_not_of(c)); }
static std::string rtrim(const std::string& original, const std::string& chars = "\t\n\v\f\r ") {
std::string str = original;
str.erase(str.find_last_not_of(chars) + 1);
return str;
}
static std::string rtrim(const std::string& original, char c) {
std::string str = original;
str.erase(str.find_last_not_of(c) + 1);
return str;
}
static std::string_view rtrim(std::string_view str, char c) {
std::size_t end = str.find_last_not_of(c);
if (end == std::string_view::npos) return {}; // All characters were 'c' — return empty view
return str.substr(0, end + 1);
}
static void rtrimInPlace(std::string& str, const std::string& chars = "\t\n\v\f\r ") { str.erase(str.find_last_not_of(chars) + 1); }
static void rtrimInPlace(std::string& str, char c) { str.erase(str.find_last_not_of(c) + 1); }
static std::string trim(const std::string& original, const std::string& chars = "\t\n\v\f\r ") { return ltrim(rtrim(original, chars), chars); }
static std::string trim(const std::string& original, char c) { return ltrim(rtrim(original, c), c); }
static void trimInPlace(std::string& str, const std::string& chars = "\t\n\v\f\r ") {
rtrimInPlace(str, chars);
ltrimInPlace(str, chars);
}
static void trimInPlace(std::string& str, char c) {
rtrimInPlace(str, c);
ltrimInPlace(str, c);
}
static std::string firstNCharacter(const std::string& str, const size_t n) {
if (str.length() > n) {
return str.substr(0, n) + "...";
} else {
return str;
}
}
static std::string normalizeDecimalString(const std::string& original) {
if (original.find('.') != std::string::npos && original.find_first_of("Ee") == std::string::npos) {
std::string str(original);
rtrimInPlace(str, "0");
rtrimInPlace(str, ".");
return str;
} else {
return original;
}
}
// static std::string normalizeDecimalStringView(const char* data) {
// std::string str(data);
// if (str.find('.') != std::string::npos) {
// rtrimInPlace(str, "0");
// rtrimInPlace(str, ".");
// }
// return str;
// }
static std::string_view normalizeDecimalStringView(std::string_view input) {
// Quick check for dot
size_t dotPos = input.find('.');
if (dotPos == std::string_view::npos || input.find_first_of("Ee") != std::string::npos) return input;
size_t end = input.size();
// Remove trailing '0's
while (end > dotPos && input[end - 1] == '0') {
--end;
}
// Remove trailing '.' if all decimals were zeros
if (end > dotPos && input[end - 1] == '.') {
--end;
}
return input.substr(0, end);
}
static std::string leftPadTo(const std::string& str, const size_t padToLength, const char paddingChar) {
std::string copy = str;
if (padToLength > copy.size()) {
copy.insert(0, padToLength - copy.size(), paddingChar);
}
return copy;
}
static std::string rightPadTo(const std::string& str, const size_t padToLength, const char paddingChar) {
std::string copy = str;
if (padToLength > copy.size()) {
copy.append(padToLength - copy.size(), paddingChar);
}
return copy;
}
};
class UtilTime {
public:
static std::string convertFIXTimeToISO(const std::string& fixTime) {
// convert 20200925-15:55:28.093490622 to 2020-09-25T15:55:28.093490622Z
std::string output;
output += fixTime.substr(0, 4);
output += "-";
output += fixTime.substr(4, 2);
output += "-";
output += fixTime.substr(6, 2);
output += "T";
output += fixTime.substr(9);
output += "Z";
return output;
}
static std::string convertTimePointToFIXTime(const TimePoint& tp) {
int year, month, day, hour, minute, second, millisecond;
timePointToParts(tp, year, month, day, hour, minute, second, millisecond);
std::string output;
output += std::to_string(year);
auto monthStr = std::to_string(month);
output += std::string(2 - monthStr.length(), '0');
output += monthStr;
auto dayStr = std::to_string(day);
output += std::string(2 - dayStr.length(), '0');
output += dayStr;
output += "-";
auto hourStr = std::to_string(hour);
output += std::string(2 - hourStr.length(), '0');
output += hourStr;
output += ":";
auto minuteStr = std::to_string(minute);
output += std::string(2 - minuteStr.length(), '0');
output += minuteStr;
output += ":";
auto secondStr = std::to_string(second);
output += std::string(2 - secondStr.length(), '0');
output += secondStr;
output += ".";
auto millisecondStr = std::to_string(millisecond);
output += std::string(3 - millisecondStr.length(), '0');
output += millisecondStr;
return output;
}
template <typename T = std::chrono::milliseconds>
static void timePointToParts(TimePoint tp, int& year, int& month, int& day, int& hour, int& minute, int& second, int& fractionalSecond) {
auto epoch_sec = std::chrono::time_point_cast<std::chrono::seconds>(tp).time_since_epoch().count();
auto day_sec = epoch_sec - (epoch_sec % 86400);
auto days_since_epoch = day_sec / 86400;
// see http://howardhinnant.github.io/date_algorithms.html
days_since_epoch += 719468;
const unsigned era = (days_since_epoch >= 0 ? days_since_epoch : days_since_epoch - 146096) / 146097;
const unsigned doe = static_cast<unsigned>(days_since_epoch - era * 146097);
const unsigned yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
year = static_cast<unsigned>(yoe) + era * 400;
const unsigned doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
const unsigned mp = (5 * doy + 2) / 153;
day = doy - (153 * mp + 2) / 5 + 1;
month = mp + (mp < 10 ? 3 : -9);
year += month <= 2;
auto in_day = tp - std::chrono::duration_cast<T>(std::chrono::seconds(day_sec));
auto in_day_sec_original = std::chrono::time_point_cast<std::chrono::seconds>(in_day).time_since_epoch().count();
auto in_day_sec = in_day_sec_original;
hour = in_day_sec / 3600;
in_day_sec -= hour * 3600;
minute = in_day_sec / 60;
second = in_day_sec - minute * 60;
auto in_day_fractional_second = in_day - std::chrono::duration_cast<T>(std::chrono::seconds(in_day_sec_original));
fractionalSecond = std::chrono::time_point_cast<T>(in_day_fractional_second).time_since_epoch().count();
}
static TimePoint now() {
auto now = std::chrono::system_clock::now();
return TimePoint(now);
}
static TimePoint parse(const std::string& input) {
std::tm time{};
time.tm_year = std::strtol(&input[0], nullptr, 10) - 1900;
time.tm_mon = std::strtol(&input[5], nullptr, 10) - 1;
time.tm_mday = std::strtol(&input[8], nullptr, 10);
if (input.length() > 10) {
time.tm_hour = std::strtol(&input[11], nullptr, 10);
time.tm_min = std::strtol(&input[14], nullptr, 10);
time.tm_sec = std::strtol(&input[17], nullptr, 10);
}
time.tm_isdst = 0;
long nanoseconds = 0;
if (input.length() > 20) {
std::string trail = input.substr(20);
if (trail.back() == 'Z') {
trail.pop_back();
}
if (!trail.empty()) {
if (trail.length() > 9) {
throw std::invalid_argument("input too long");
}
nanoseconds = std::stoll(UtilString::rightPadTo(trail, 9, '0'));
}
}
return TimePoint(std::chrono::system_clock::from_time_t(timegm(&time))) + std::chrono::nanoseconds(nanoseconds);
}
static TimePoint makeTimePoint(const std::pair<long long, long long>& timePair) {
auto tp = TimePoint(std::chrono::duration<int64_t>(timePair.first));
tp += std::chrono::nanoseconds(timePair.second);
return tp;
}
static TimePoint makeTimePointMilli(const std::pair<long long, long long>& timePair) {
auto tp = TimePoint(std::chrono::milliseconds(timePair.first));
tp += std::chrono::nanoseconds(timePair.second);
return tp;
}
static std::pair<long long, long long> divide(const TimePoint& tp) {
auto then = tp.time_since_epoch();
auto s = std::chrono::duration_cast<std::chrono::seconds>(then);
then -= s;
auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(then);
return std::make_pair(s.count(), ns.count());
}
static std::pair<long long, long long> divide(const std::string& seconds) {
if (seconds.find('.') != std::string::npos) {
std::string secondsCopy = seconds;
UtilString::rtrimInPlace(secondsCopy, '0');
UtilString::rtrimInPlace(secondsCopy, '.');
auto found = secondsCopy.find('.');
return std::make_pair(std::stoll(secondsCopy.substr(0, found)),
found != std::string::npos ? std::stoll(UtilString::rightPadTo(secondsCopy.substr(found + 1), 9, '0')) : 0);
} else {
return std::make_pair(std::stoll(seconds), 0);
}
}
static std::pair<long long, long long> divideMilli(const std::string& milliseconds) {
if (milliseconds.find('.') != std::string::npos) {
std::string millisecondsCopy = milliseconds;
UtilString::rtrimInPlace(millisecondsCopy, '0');
UtilString::rtrimInPlace(millisecondsCopy, '.');
auto found = millisecondsCopy.find('.');
return std::make_pair(std::stoll(millisecondsCopy.substr(0, found)),
found != std::string::npos ? std::stoll(UtilString::rightPadTo(millisecondsCopy.substr(found + 1), 6, '0')) : 0);
} else {
return std::make_pair(std::stoll(milliseconds), 0);
}
}
static std::string convertMillisecondsStrToSecondsStr(const std::string& milliseconds) {
std::string output;
if (milliseconds.length() >= 4) {
output = milliseconds;
output.insert(milliseconds.length() - 3, 1, '.');
} else {
output = "0.";
output += std::string(3 - milliseconds.length(), '0');
output += milliseconds;
output = UtilString::normalizeDecimalString(output);
}
return output;
}
static std::pair<long long, long long> divideNanoWhole(const std::string& nanoseconds) {
return std::make_pair(std::stoll(nanoseconds.substr(0, nanoseconds.length() - 9)), std::stoll(nanoseconds.substr(nanoseconds.length() - 9)));
}
template <typename T = std::chrono::nanoseconds>
static std::string getISOTimestamp(const TimePoint& tp) {
int year, month, day, hour, minute, second, fractionalSecond;
timePointToParts<T>(tp, year, month, day, hour, minute, second, fractionalSecond);
std::string output;
output += std::to_string(year);
output += "-";
auto monthStr = std::to_string(month);
output += std::string(2 - monthStr.length(), '0');
output += monthStr;
output += "-";
auto dayStr = std::to_string(day);
output += std::string(2 - dayStr.length(), '0');
output += dayStr;
output += "T";
auto hourStr = std::to_string(hour);
output += std::string(2 - hourStr.length(), '0');
output += hourStr;
output += ":";
auto minuteStr = std::to_string(minute);
output += std::string(2 - minuteStr.length(), '0');
output += minuteStr;
output += ":";
auto secondStr = std::to_string(second);
output += std::string(2 - secondStr.length(), '0');
output += secondStr;
if (!std::is_same<T, std::chrono::seconds>::value) {
output += ".";
auto fractionalSecondStr = std::to_string(fractionalSecond);
int padToLength;
if (std::is_same<T, std::chrono::nanoseconds>::value) {
padToLength = 9;
} else if (std::is_same<T, std::chrono::microseconds>::value) {
padToLength = 6;
} else if (std::is_same<T, std::chrono::milliseconds>::value) {
padToLength = 3;
}
output += std::string(padToLength - fractionalSecondStr.length(), '0');
// UtilString::rtrimInPlace(fractionalSecondStr, '0');
output += fractionalSecondStr;
}
output += "Z";
return output;
}
static int getUnixTimestamp(const TimePoint& tp) {
auto then = tp.time_since_epoch();
auto s = std::chrono::duration_cast<std::chrono::seconds>(then);
return s.count();
}
static TimePoint makeTimePointFromMilliseconds(long long milliseconds) { return TimePoint(std::chrono::milliseconds(milliseconds)); }
static TimePoint makeTimePointFromSeconds(long seconds) { return TimePoint(std::chrono::seconds(seconds)); }
};
class UtilAlgorithm {
public:
enum class ShaVersion {
UNKNOWN,
SHA256,
SHA512,
};
public:
static std::string toBase62(size_t value) {
static constexpr char kBase62Chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
std::string result;
do {
result += kBase62Chars[value % 62];
value /= 62;
} while (value);
std::reverse(result.begin(), result.end());
return result;
}
static std::string shortBase62Hash(const std::string& input) {
std::hash<std::string> hasher;
return toBase62(hasher(input));
}
static std::string computeHash(const ShaVersion shaVersion, const std::string& unhashed, bool returnHex = false) {
EVP_MD_CTX* context = EVP_MD_CTX_new();
switch (shaVersion) {
case ShaVersion::SHA256:
EVP_DigestInit_ex(context, EVP_sha256(), NULL);
break;
case ShaVersion::SHA512:
EVP_DigestInit_ex(context, EVP_sha512(), NULL);
break;
default:
// Release the context, adding an extra line here to avoid potential memory leaks that may occur in computeHash
EVP_MD_CTX_free(context);
throw std::invalid_argument("invalid shaVersion");
}
EVP_DigestUpdate(context, unhashed.c_str(), unhashed.length());
unsigned char hash[EVP_MAX_MD_SIZE];
unsigned int lengthOfHash = 0;
EVP_DigestFinal_ex(context, hash, &lengthOfHash);
EVP_MD_CTX_free(context);
std::stringstream ss;
if (returnHex) {
for (unsigned int i = 0; i < lengthOfHash; ++i) {
ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
}
} else {
for (unsigned int i = 0; i < lengthOfHash; ++i) {
ss << (char)hash[i];
}
}
return ss.str();
}
static std::string stringToHex(const std::string& input) {
static const char hex_digits[] = "0123456789abcdef";
std::string output;
output.reserve(input.length() * 2);
for (unsigned char c : input) {
output.push_back(hex_digits[c >> 4]);
output.push_back(hex_digits[c & 15]);
}
return output;
}
static int hexValue(unsigned char hex_digit) {
static const signed char hex_values[256] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
};
int value = hex_values[hex_digit];
if (value == -1) throw std::invalid_argument("invalid hex digit");
return value;
}
static std::string hexToString(const std::string& input) {
const auto len = input.length();
if (len & 1) throw std::invalid_argument("odd length");
std::string output;
output.reserve(len / 2);
for (auto it = input.begin(); it != input.end();) {
int hi = hexValue(*it++);
int lo = hexValue(*it++);
output.push_back(hi << 4 | lo);
}
return output;
}
// https://stackoverflow.com/questions/342409/how-do-i-base64-encode-decode-in-c
static std::string base64Encode(const std::string& input) {
static const unsigned char base64_table[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const unsigned char* src = reinterpret_cast<const unsigned char*>(input.c_str());
size_t len = input.length();
unsigned char *out, *pos;
const unsigned char *end, *in;
size_t olen;
olen = 4 * ((len + 2) / 3); /* 3-byte blocks to 4-byte */
if (olen < len) return std::string(); /* integer overflow */
std::string outStr;
outStr.resize(olen);
out = (unsigned char*)&outStr[0];
end = src + len;
in = src;
pos = out;
while (end - in >= 3) {
*pos++ = base64_table[in[0] >> 2];
*pos++ = base64_table[((in[0] & 0x03) << 4) | (in[1] >> 4)];
*pos++ = base64_table[((in[1] & 0x0f) << 2) | (in[2] >> 6)];
*pos++ = base64_table[in[2] & 0x3f];
in += 3;
}
if (end - in) {
*pos++ = base64_table[in[0] >> 2];
if (end - in == 1) {
*pos++ = base64_table[(in[0] & 0x03) << 4];
*pos++ = '=';
} else {
*pos++ = base64_table[((in[0] & 0x03) << 4) | (in[1] >> 4)];
*pos++ = base64_table[(in[1] & 0x0f) << 2];
}
*pos++ = '=';
}
return outStr;
}
static std::string base64Decode(const std::string& in) {
static const int B64index[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 63, 62, 62, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0,
0, 0, 0, 0, 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, 0, 0,
0, 0, 63, 0, 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};
const void* data = in.c_str();
const size_t len = in.length();
unsigned char* p = (unsigned char*)data;
int pad = len > 0 && (len % 4 || p[len - 1] == '=');
const size_t L = ((len + 3) / 4 - pad) * 4;
std::string str(L / 4 * 3 + pad, '\0');
for (size_t i = 0, j = 0; i < L; i += 4) {
int n = B64index[p[i]] << 18 | B64index[p[i + 1]] << 12 | B64index[p[i + 2]] << 6 | B64index[p[i + 3]];
str[j++] = n >> 16;
str[j++] = n >> 8 & 0xFF;
str[j++] = n & 0xFF;
}
if (pad) {
int n = B64index[p[L]] << 18 | B64index[p[L + 1]] << 12;
str[str.size() - 1] = n >> 16;
if (len > L + 2 && p[L + 2] != '=') {
n |= B64index[p[L + 2]] << 6;
str.push_back(n >> 8 & 0xFF);
}
}
return str;
}
// https://github.com/brianloveswords/base64url
static std::string base64UrlFromBase64(const std::string& base64) {
return std::regex_replace(std::regex_replace(std::regex_replace(base64, std::regex("="), ""), std::regex("\\+"), "-"), std::regex("\\/"), "_");
}
static std::string base64FromBase64Url(const std::string& base64Url) {
auto segmentLength = 4;
auto stringLength = base64Url.size();
auto diff = stringLength % segmentLength;
if (!diff) {
return base64Url;
}
auto padLength = segmentLength - diff;
std::string paddedBase64Url(base64Url);
paddedBase64Url += std::string(padLength, '=');
return std::regex_replace(std::regex_replace(paddedBase64Url, std::regex("\\-"), "+"), std::regex("_"), "/");
}
static std::string base64UrlEncode(const std::string& in) { return base64UrlFromBase64(base64Encode(in)); }
static std::string base64UrlDecode(const std::string& in) { return base64Decode(base64FromBase64Url(in)); }
static double exponentialBackoff(double initial, double multiplier, double base, double exponent) { return initial + multiplier * (pow(base, exponent) - 1); }
template <typename InputIterator>
static uint_fast32_t crc(InputIterator first, InputIterator last);
static EVP_PKEY* loadPrivateKey(const std::string& keyPem, const std::string& password = "") {
BIO* bio = BIO_new_mem_buf(keyPem.data(), static_cast<int>(keyPem.size()));
if (!bio) return nullptr;
const EVP_PKEY_ASN1_METHOD* meth = EVP_PKEY_asn1_find_str(nullptr, "ED25519", -1);
if (!meth) {
throw std::runtime_error("ED25519 is NOT supported in this OpenSSL build.");
}
EVP_PKEY* pkey = nullptr;
if (password.empty()) {
pkey = PEM_read_bio_PrivateKey(bio, nullptr, nullptr, nullptr);
} else {
pkey = PEM_read_bio_PrivateKey(bio, nullptr, nullptr, const_cast<char*>(password.c_str()));
}
BIO_free(bio);
return pkey;
}
static std::string readFile(const std::string& path) {
std::ifstream file(path, std::ios::binary);
if (!file.is_open()) {
throw std::runtime_error("Failed to open file: " + path);
}
std::ostringstream oss;
oss << file.rdbuf();
return oss.str();
}
static std::string base64Encode(const std::vector<unsigned char>& input) {
BIO *bio, *b64;
BUF_MEM* bufferPtr;
b64 = BIO_new(BIO_f_base64());
bio = BIO_new(BIO_s_mem());
b64 = BIO_push(b64, bio);
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
BIO_write(b64, input.data(), static_cast<int>(input.size()));
BIO_flush(b64);
BIO_get_mem_ptr(b64, &bufferPtr);
std::string result(bufferPtr->data, bufferPtr->length);
BIO_free_all(b64);
return result;
}
static std::string signPayload(EVP_PKEY* pkey, const std::string& payload) {
EVP_MD_CTX* ctx = EVP_MD_CTX_new();
if (!ctx) throw std::runtime_error("Failed to create EVP_MD_CTX");
const int key_type = EVP_PKEY_base_id(pkey);
const bool is_ed25519 = key_type == EVP_PKEY_ED25519;
if (EVP_DigestSignInit(ctx, nullptr, is_ed25519 ? nullptr : EVP_sha256(), nullptr, pkey) != 1) throw std::runtime_error("EVP_DigestSignInit failed");
size_t sigLen = 0;
if (is_ed25519) {
// One-shot sign for Ed25519
if (EVP_DigestSign(ctx, nullptr, &sigLen, reinterpret_cast<const unsigned char*>(payload.data()), payload.size()) != 1)
throw std::runtime_error("EVP_DigestSign (get length) failed");
std::vector<unsigned char> signature(sigLen);
if (EVP_DigestSign(ctx, signature.data(), &sigLen, reinterpret_cast<const unsigned char*>(payload.data()), payload.size()) != 1)
throw std::runtime_error("EVP_DigestSign failed");
signature.resize(sigLen);
EVP_MD_CTX_free(ctx);
return base64Encode(signature);
} else {
// Traditional sign (e.g., RSA)
if (EVP_DigestSignUpdate(ctx, payload.data(), payload.size()) != 1) throw std::runtime_error("EVP_DigestSignUpdate failed");
if (EVP_DigestSignFinal(ctx, nullptr, &sigLen) != 1) throw std::runtime_error("EVP_DigestSignFinal (get length) failed");
std::vector<unsigned char> signature(sigLen);
if (EVP_DigestSignFinal(ctx, signature.data(), &sigLen) != 1) throw std::runtime_error("EVP_DigestSignFinal failed");
signature.resize(sigLen);
EVP_MD_CTX_free(ctx);
return base64Encode(signature);
}
}
static const EVP_MD* getDigest(const ShaVersion version) {
switch (version) {
case ShaVersion::SHA256:
return EVP_sha256();
case ShaVersion::SHA512:
return EVP_sha512();
default:
throw std::invalid_argument("Unsupported SHA version");
}
}
};
template <typename InputIterator>
inline uint_fast32_t UtilAlgorithm::crc(InputIterator first, InputIterator last) {
static auto const table = []() {
auto const reversed_polynomial = uint_fast32_t{0xEDB88320uL};
// This is a function object that calculates the checksum for a value,
// then increments the value, starting from zero.
struct byte_checksum {
uint_fast32_t operator()() noexcept {
auto checksum = static_cast<uint_fast32_t>(n++);
for (auto i = 0; i < 8; ++i) checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0);
return checksum;
}
unsigned n = 0;
};
auto table = std::array<uint_fast32_t, 256>{};
std::generate(table.begin(), table.end(), byte_checksum{});
return table;
}();
// Calculate the checksum - make sure to clip to 32 bits, for systems that don't
// have a true (fast) 32-bit type.
return uint_fast32_t{0xFFFFFFFFuL} &
~std::accumulate(first, last, ~uint_fast32_t{0} & uint_fast32_t{0xFFFFFFFFuL},
[](uint_fast32_t checksum, std::uint_fast8_t value) { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); });
}
class UtilSystem {
public:
static bool getEnvAsBool(const std::string& variableName, const bool defaultValue = false) {
const char* env_p = std::getenv(variableName.c_str());
if (env_p) {
return UtilString::toLower(env_p) == "true";
} else {
return defaultValue;
}
}
static std::string getEnvAsString(const std::string& variableName, const std::string& defaultValue = "") {
const char* env_p = std::getenv(variableName.c_str());
if (env_p) {
return std::string(env_p);
} else {
return defaultValue;
}
}
static int getEnvAsInt(const std::string& variableName, const int defaultValue = 0) {
const char* env_p = std::getenv(variableName.c_str());
if (env_p) {
return std::stoi(std::string(env_p));
} else {
return defaultValue;
}
}
static long getEnvAsLong(const std::string& variableName, const long defaultValue = 0) {
const char* env_p = std::getenv(variableName.c_str());
if (env_p) {
return std::stol(std::string(env_p));
} else {
return defaultValue;
}
}
static float getEnvAsFloat(const std::string& variableName, const float defaultValue = 0) {
const char* env_p = std::getenv(variableName.c_str());
if (env_p) {
return std::stof(std::string(env_p));
} else {
return defaultValue;
}
}
static double getEnvAsDouble(const std::string& variableName, const double defaultValue = 0) {
const char* env_p = std::getenv(variableName.c_str());
if (env_p) {
return std::stod(std::string(env_p));
} else {
return defaultValue;
}
}
static bool checkEnvExist(const std::string& variableName) {
const char* env_p = std::getenv(variableName.c_str());
if (env_p) {
return true;
} else {
return false;
}
}
};
/**
* This class provides a numeric type for representing an arbitrary precision decimal number. It is minimalistic for the purpose of high performance.
* Furthermore, unlike double, it is suitable for being used as the key of a map. boost::multiprecision::cpp_dec_float can also be used, but based on
* test it does lead to nearly 100% increase in cpu usage!
*/
class Decimal {
public:
Decimal() {}
template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
Decimal(T value) {
if (value < 0) {
this->sign = false;
this->before = -value;
} else if (value > 0) {
this->before = value;
}
}
explicit Decimal(std::string_view originalValue) {
if (originalValue.empty()) {
throw std::invalid_argument("Decimal constructor input value cannot be empty");
}
if (originalValue.at(0) == '-') {
this->sign = false;
}
auto foundE = originalValue.find('E');
if (foundE != std::string::npos || originalValue.find('e') != std::string::npos) {
if (foundE == std::string::npos) {
foundE = originalValue.find('e');
}
std::string fixedPointValue = std::string(originalValue.substr(this->sign ? 0 : 1, this->sign ? foundE : foundE - 1));
auto foundDot = fixedPointValue.find('.');
if (foundDot != std::string::npos) {
fixedPointValue.erase(fixedPointValue.find_last_not_of('0') + 1);
fixedPointValue.erase(fixedPointValue.find_last_not_of('.') + 1);
}
std::string exponent = std::string(originalValue.substr(foundE + 1));
if (exponent.at(0) == '+') {
exponent.erase(0, 1);
}
exponent.erase(0, exponent.find_first_not_of('0'));
if (exponent.empty()) {
exponent = "0";
}
if (exponent != "0") {
foundDot = fixedPointValue.find('.');
if (foundDot != std::string::npos) {
if (exponent.at(0) != '-') {
if (std::stoi(exponent) < fixedPointValue.substr(foundDot + 1).length()) {
fixedPointValue = fixedPointValue.substr(0, foundDot) + fixedPointValue.substr(foundDot + 1).substr(0, std::stoi(exponent)) + "." +
fixedPointValue.substr(foundDot + 1).substr(std::stoi(exponent));
} else {
fixedPointValue = fixedPointValue.substr(0, foundDot) + fixedPointValue.substr(foundDot + 1) +
std::string(std::stoi(exponent) - fixedPointValue.substr(foundDot + 1).length(), '0');
}
} else {
fixedPointValue = "0." + std::string(-std::stoi(exponent) - 1, '0') + fixedPointValue.substr(0, foundDot) + fixedPointValue.substr(foundDot + 1);
}