-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcplib.hpp
7245 lines (5996 loc) · 219 KB
/
cplib.hpp
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
/*
* This file is part of CPLib.
*
* CPLib is free software: you can redistribute it and/or modify it under the terms of the GNU
* Lesser General Public License as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* CPLib is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with CPLib. If
* not, see <https://www.gnu.org/licenses/>.
*/
#ifndef CPLIB_HPP_
#define CPLIB_HPP_
// clang-format off
/*
* This file is part of CPLib.
*
* CPLib is free software: you can redistribute it and/or modify it under the terms of the GNU
* Lesser General Public License as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* CPLib is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with CPLib. If
* not, see <https://www.gnu.org/licenses/>.
*/
#ifndef CPLIB_MACROS_HPP_
#define CPLIB_MACROS_HPP_
#define CPLIB_VERSION "0.0.1-SNAPSHOT"
#define CPLIB_STARTUP_TEXT \
"cplib (CPLib) " CPLIB_VERSION \
"\n" \
"https://github.com/rindag-devs/cplib/ by Rindag Devs, copyright(c) 2023-2024\n"
#if (_WIN32 || __WIN32__ || __WIN32 || _WIN64 || __WIN64__ || __WIN64 || WINNT || __WINNT || \
__WINNT__ || __CYGWIN__)
#if !defined(_MSC_VER) || _MSC_VER > 1400
#define NOMINMAX 1
#include <windows.h>
#else
#include <unistd.h>
#endif
#include <fcntl.h>
#include <io.h>
#include <sys/stat.h>
#define ON_WINDOWS
#if defined(_MSC_VER) && _MSC_VER > 1400
#pragma warning(disable : 4127)
#pragma warning(disable : 4146)
#pragma warning(disable : 4458)
#endif
#else
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#if defined(__GNUC__)
#define CPLIB_PRINTF_LIKE(n, m) __attribute__((format(printf, n, m)))
#else
#define CPLIB_PRINTF_LIKE(n, m) /* If only */
#endif /* __GNUC__ */
#endif
/*
* This file is part of CPLib.
*
* CPLib is free software: you can redistribute it and/or modify it under the terms of the GNU
* Lesser General Public License as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* CPLib is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with CPLib. If
* not, see <https://www.gnu.org/licenses/>.
*/
#ifndef CPLIB_UTILS_HPP_
#define CPLIB_UTILS_HPP_
#include <cstddef>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
namespace cplib {
/**
* Panic the program with a message and exit.
*
* If the program has been registered as a CPLib program, `panic` will call the `quit` method of
* State with `INTERNAL_ERROR` status.
*
* @param message The message to print.
*/
[[noreturn]] auto panic(std::string_view message) -> void;
/**
* Format string using printf-like syntax.
*
* @param fmt The format string.
* @param ... The variadic arguments to be formatted.
* @return The formatted string.
*/
CPLIB_PRINTF_LIKE(1, 2) auto format(const char *fmt, ...) -> std::string;
/**
* Determine whether the two floating-point values are equals within the accuracy range.
*
* @tparam T The type of the values.
* @param expected The expected floating-point value.
* @param result The actual floating-point value.
* @param max_err The maximum allowable error.
* @return True if the values are equal within the accuracy range, false otherwise.
*/
template <class T>
auto float_equals(T expected, T result, T max_err) -> bool;
/**
* Calculate the minimum relative and absolute error between two floating-point values.
*
* @tparam T The type of the values.
* @param expected The expected floating-point value.
* @param result The actual floating-point value.
* @return The minimum error between the values.
*/
template <class T>
auto float_delta(T expected, T result) -> T;
/**
* Compress string to at most 64 bytes.
*
* @param s The input string.
* @return The compressed string.
*/
auto compress(std::string_view s) -> std::string;
/**
* Trim spaces at beginning and end of string.
*
* @param s The input string.
* @return The trimmed string.
*/
auto trim(std::string_view s) -> std::string;
/**
* Concatenate the values between [first,last) into a string without separator.
*
* @tparam It The type of the iterator.
* @param first Iterator to the first value.
* @param last Iterator to the last value (exclusive).
* @return The concatenated string.
*/
template <class It>
auto join(It first, It last) -> std::string;
/**
* Concatenate the values between [first,last) into a string through separator.
*
* @tparam It The type of the iterator.
* @param first Iterator to the first value.
* @param last Iterator to the last value (exclusive).
* @param separator The separator.
* @return The concatenated string.
*/
template <class It, class Sep>
auto join(It first, It last, Sep separator) -> std::string;
/**
* Splits string s by character separators returning exactly k+1 items, where k is the number of
* separator occurrences. Split the string into a list of strings using separator.
*
* @param s The input string.
* @param separator The separator character.
* @return The vector of split strings.
*/
auto split(std::string_view s, char separator) -> std::vector<std::string>;
/**
* Similar to `split`, but ignores the empty string.
*
* @param s The input string.
* @param separator The separator character.
* @return The vector of tokenized strings.
*/
auto tokenize(std::string_view s, char separator) -> std::vector<std::string>;
/**
* `UniqueFunction` is similar to `std::function`, it is a wrapper for functions.
*
* The difference between it and `std::function` is that `std::function` requires the wrapped object
* to be copy-assignable, but `UniqueFunction` only requires it to be move-assignable.
*
* In the same way, `UniqueFunction` itself cannot be copy-assignable, but can only be
* move-assignable.
*
* @tparam T The type of the stored function.
*/
template <typename T>
struct UniqueFunction;
/**
* Template specialization for Ret(Args...) type.
*
* @tparam Ret The return type of the stored function.
* @tparam Args The argument types of the stored function.
*/
template <typename Ret, typename... Args>
struct UniqueFunction<Ret(Args...)> {
public:
/**
* Creates an empty UniqueFunction.
*/
UniqueFunction() = default;
/**
* Creates an empty UniqueFunction.
*/
explicit UniqueFunction(std::nullptr_t);
/**
* Constructor.
*
* @param t The function to be stored.
* @tparam T The type of the function to be stored.
*/
template <class T>
UniqueFunction(T t); // NOLINT(google-explicit-constructor)
/**
* Function call operator.
*
* @param args The arguments to be passed to the stored function.
* @return The return value of the stored function.
*/
auto operator()(Args... args) const -> Ret;
private:
/**
* Base class for polymorphism.
*/
struct Base {
virtual ~Base() = default;
/**
* Function call operator for derived classes.
*
* @param args The arguments to be passed to the derived function.
* @return The return value of the derived function.
*/
virtual auto operator()(Args &&...args) -> Ret = 0;
};
/**
* Data class storing the actual function.
*
* @tparam T The type of the stored function.
*/
template <typename T>
struct Data : Base {
T func;
explicit Data(T &&t);
/**
* Function call operator implementation.
*
* @param args The arguments to be passed to the stored function.
* @return The return value of the stored function.
*/
auto operator()(Args &&...args) -> Ret override;
};
std::unique_ptr<Base> ptr{nullptr};
};
/**
* `WorkMode` indicates the current mode of cplib.
*/
enum struct WorkMode {
NONE,
CHECKER,
INTERACTOR,
VALIDATOR,
GENERATOR,
};
/**
* Get current work mode of cplib.
*
* @return The current work mode.
*/
auto get_work_mode() -> WorkMode;
} // namespace cplib
/*
* This file is part of CPLib.
*
* CPLib is free software: you can redistribute it and/or modify it under the terms of the GNU
* Lesser General Public License as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* CPLib is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with CPLib. If
* not, see <https://www.gnu.org/licenses/>.
*/
#if defined(CPLIB_CLANGD) || defined(CPLIB_IWYU)
#pragma once
#else
#ifndef CPLIB_UTILS_HPP_
#error "Must be included from utils.hpp"
#endif
#endif
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace cplib {
namespace detail {
inline auto has_colors() -> bool {
// https://bixense.com/clicolors/
if (std::getenv("NO_COLOR") != nullptr) return false;
if (std::getenv("CLICOLOR_FORCE") != nullptr) return true;
return isatty(fileno(stderr));
}
inline auto hex_encode(int c) -> std::string {
if (c == '\\') {
return "\\\\";
} else if (c == '\b') {
return "\\b";
} else if (c == '\f') {
return "\\f";
} else if (c == '\n') {
return "\\n";
} else if (c == '\r') {
return "\\r";
} else if (c == '\t') {
return "\\t";
} else if (!isprint(c)) {
return format("\\x%02x", static_cast<int>(c));
} else {
return {static_cast<char>(c)};
}
}
inline auto hex_encode(std::string_view s) -> std::string {
std::string result;
for (auto c : s) result += hex_encode(c);
return result;
}
} // namespace detail
// Impl panic {{{
namespace detail {
inline UniqueFunction<auto(std::string_view)->void> panic_impl = [](std::string_view s) {
std::ostream stream(std::cerr.rdbuf());
stream << "Unrecoverable error: " << s << '\n';
exit(EXIT_FAILURE);
};
} // namespace detail
inline auto panic(std::string_view message) -> void {
detail::panic_impl(message);
exit(EXIT_FAILURE); // Usually unnecessary, but in special cases to prevent problems.
}
// /Impl panic }}}
// Impl format {{{
namespace detail {
inline auto string_vsprintf(const char* format, std::va_list args) -> std::string {
std::va_list tmp_args; // unfortunately you cannot consume a va_list twice
va_copy(tmp_args, args); // so we have to copy it
const int required_len = std::vsnprintf(nullptr, 0, format, tmp_args);
va_end(tmp_args);
std::string buf(required_len, '\0');
if (std::vsnprintf(&buf[0], required_len + 1, format, args) < 0) {
panic("string_vsprintf encoding error");
return "";
}
return buf;
}
} // namespace detail
CPLIB_PRINTF_LIKE(1, 2) inline auto format(const char* fmt, ...) -> std::string {
std::va_list args;
va_start(args, fmt);
std::string str{detail::string_vsprintf(fmt, args)};
va_end(args);
return str;
}
// /Impl format }}}
template <class T>
inline auto float_equals(T expected, T result, T max_err) -> bool {
if (bool x_nan = std::isnan(expected), y_nan = std::isnan(result); x_nan || y_nan) {
return x_nan && y_nan;
}
if (bool x_inf = std::isinf(expected), y_inf = std::isinf(result); x_inf || y_inf) {
return x_inf && y_inf && (expected > 0) == (result > 0);
}
max_err += 1e-15;
if (std::abs(expected - result) <= max_err) return true;
T min_v = std::min<T>(expected * (1.0 - max_err), expected * (1.0 + max_err));
T max_v = std::max<T>(expected * (1.0 - max_err), expected * (1.0 + max_err));
return result >= min_v && result <= max_v;
}
template <class T>
inline auto float_delta(T expected, T result) -> T {
T absolute = std::abs(expected - result);
if (std::abs(expected) > 1E-9) {
double relative = std::abs(absolute / expected);
return std::min(absolute, relative);
}
return absolute;
}
inline auto compress(std::string_view s) -> std::string {
auto t = detail::hex_encode(s);
if (t.size() <= 64) {
return {t};
} else {
return static_cast<std::string>(t.substr(0, 30)) + "..." +
static_cast<std::string>(t.substr(t.size() - 31, 31));
}
}
inline auto trim(std::string_view s) -> std::string {
if (s.empty()) return std::string(s);
std::ptrdiff_t left = 0;
while (left < static_cast<std::ptrdiff_t>(s.size()) && std::isspace(s[left])) ++left;
if (left >= static_cast<std::ptrdiff_t>(s.size())) return "";
std::ptrdiff_t right = static_cast<std::ptrdiff_t>(s.size()) - 1;
while (right >= 0 && std::isspace(s[right])) --right;
if (right < 0) return "";
return std::string(s.substr(left, right - left + 1));
}
template <class It>
inline auto join(It first, It last) -> std::string {
std::ostringstream ss;
for (It i = first; i != last; ++i) {
ss << *i;
}
return ss.str();
}
template <class It, class Sep>
inline auto join(It first, It last, Sep separator) -> std::string {
std::ostringstream ss;
bool repeated = false;
for (It i = first; i != last; ++i) {
if (repeated) {
ss << separator;
} else {
repeated = true;
}
ss << *i;
}
return ss.str();
}
inline auto split(std::string_view s, char separator) -> std::vector<std::string> {
std::vector<std::string> result;
std::string item;
for (char i : s) {
if (i == separator) {
result.emplace_back(item);
item.clear();
} else {
item.push_back(i);
}
}
result.emplace_back(item);
return result;
}
inline auto tokenize(std::string_view s, char separator) -> std::vector<std::string> {
std::vector<std::string> result;
std::string item;
for (char i : s) {
if (i == separator) {
if (!item.empty()) result.emplace_back(item);
item.clear();
} else {
item.push_back(i);
}
}
if (!item.empty()) result.emplace_back(item);
return result;
}
template <typename Ret, typename... Args>
inline UniqueFunction<Ret(Args...)>::UniqueFunction(std::nullptr_t) : ptr(nullptr){};
template <typename Ret, typename... Args>
template <class T>
inline UniqueFunction<Ret(Args...)>::UniqueFunction(T t)
: ptr(std::make_unique<Data<T>>(std::move(t))){};
template <typename Ret, typename... Args>
auto UniqueFunction<Ret(Args...)>::operator()(Args... args) const -> Ret {
return (*ptr)(std::forward<Args>(args)...);
}
template <typename Ret, typename... Args>
template <class T>
UniqueFunction<Ret(Args...)>::Data<T>::Data(T&& t) : func(std::forward<T>(t)) {}
template <typename Ret, typename... Args>
template <class T>
auto UniqueFunction<Ret(Args...)>::Data<T>::operator()(Args&&... args) -> Ret {
return func(std::forward<Args>(args)...);
}
// Impl get_work_mode {{{
namespace detail {
inline WorkMode work_mode = WorkMode::NONE;
}
inline auto get_work_mode() -> WorkMode { return detail::work_mode; }
// /Impl get_work_mode }}}
} // namespace cplib
#endif
/*
* This file is part of CPLib.
*
* CPLib is free software: you can redistribute it and/or modify it under the terms of the GNU
* Lesser General Public License as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* CPLib is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with CPLib. If
* not, see <https://www.gnu.org/licenses/>.
*/
#ifndef CPLIB_NO_RAND_HPP_
#define CPLIB_NO_RAND_HPP_
#include <cstdlib>
#ifdef __GLIBC__
#define CPLIB_RAND_THROW_STATEMENT noexcept(true)
#else
#define CPLIB_RAND_THROW_STATEMENT
#endif
#if defined(__GNUC__) && !defined(__clang__)
__attribute__((error("Don not use `rand`, use `rnd.next` instead")))
#endif
#ifdef _MSC_VER
#pragma warning(disable : 4273)
#endif
inline auto
rand() CPLIB_RAND_THROW_STATEMENT -> int {
cplib::panic("Don not use `rand`, use `rnd.next` instead");
}
#if defined(__GNUC__) && !defined(__clang__)
__attribute__((error("Don not use `srand`, you should use `cplib::Random` for random generator")))
#endif
#ifdef _MSC_VER
#pragma warning(disable : 4273)
#endif
inline auto
srand(unsigned int) CPLIB_RAND_THROW_STATEMENT -> void {
cplib::panic("Don not use `srand`, you should use `cplib::Random` for random generator");
}
#endif
/*
* This file is part of CPLib.
*
* CPLib is free software: you can redistribute it and/or modify it under the terms of the GNU
* Lesser General Public License as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* CPLib is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with CPLib. If
* not, see <https://www.gnu.org/licenses/>.
*/
#ifndef CPLIB_JSON_HPP_
#define CPLIB_JSON_HPP_
#include <cstdint>
#include <map>
#include <memory>
#include <string>
#include <vector>
namespace cplib::json {
struct Value {
virtual ~Value() = 0;
[[nodiscard]] virtual auto clone() const -> std::unique_ptr<Value> = 0;
virtual auto to_string() -> std::string = 0;
};
struct String : Value {
std::string inner;
explicit String(std::string inner);
[[nodiscard]] auto clone() const -> std::unique_ptr<Value> override;
auto to_string() -> std::string override;
};
struct Int : Value {
std::int64_t inner;
explicit Int(std::int64_t inner);
[[nodiscard]] auto clone() const -> std::unique_ptr<Value> override;
auto to_string() -> std::string override;
};
struct Real : Value {
double inner;
explicit Real(double inner);
[[nodiscard]] auto clone() const -> std::unique_ptr<Value> override;
auto to_string() -> std::string override;
};
struct Bool : Value {
bool inner;
explicit Bool(bool inner);
[[nodiscard]] auto clone() const -> std::unique_ptr<Value> override;
auto to_string() -> std::string override;
};
struct List : Value {
std::vector<std::unique_ptr<Value>> inner;
explicit List(std::vector<std::unique_ptr<Value>> inner);
[[nodiscard]] auto clone() const -> std::unique_ptr<Value> override;
auto to_string() -> std::string override;
};
struct Map : Value {
std::map<std::string, std::unique_ptr<Value>> inner;
explicit Map(std::map<std::string, std::unique_ptr<Value>> inner);
[[nodiscard]] auto clone() const -> std::unique_ptr<Value> override;
auto to_string() -> std::string override;
};
} // namespace cplib::json
/*
* This file is part of CPLib.
*
* CPLib is free software: you can redistribute it and/or modify it under the terms of the GNU
* Lesser General Public License as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* CPLib is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with CPLib. If
* not, see <https://www.gnu.org/licenses/>.
*/
#if defined(CPLIB_CLANGD) || defined(CPLIB_IWYU)
#pragma once
#else
#ifndef CPLIB_JSON_HPP_
#error "Must be included from json.hpp"
#endif
#endif
#include <cstdint>
#include <ios>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
namespace cplib::json {
inline Value::~Value() = default;
inline String::String(std::string inner) : inner(std::move(inner)) {}
[[nodiscard]] inline auto String::clone() const -> std::unique_ptr<Value> {
return std::make_unique<String>(*this);
}
inline auto String::to_string() -> std::string {
std::stringbuf buf(std::ios_base::out);
buf.sputc('\"');
for (char c : inner) {
switch (c) {
case '"':
buf.sputc('\\');
buf.sputc('\"');
break;
case '\\':
buf.sputc('\\');
buf.sputc('\\');
break;
case '\b':
buf.sputc('\\');
buf.sputc('b');
break;
case '\f':
buf.sputc('\\');
buf.sputc('f');
break;
case '\n':
buf.sputc('\\');
buf.sputc('n');
break;
case '\r':
buf.sputc('\\');
buf.sputc('r');
break;
case '\t':
buf.sputc('\\');
buf.sputc('t');
break;
default:
if (('\x00' <= c && c <= '\x1f') || c == '\x7f') {
buf.sputc('\\');
buf.sputc('u');
buf.sputn(cplib::format("%04hhx", static_cast<unsigned char>(c)).c_str(), 4);
} else {
buf.sputc(c);
}
}
}
buf.sputc('\"');
return buf.str();
}
inline Int::Int(std::int64_t inner) : inner(inner) {}
[[nodiscard]] inline auto Int::clone() const -> std::unique_ptr<Value> {
return std::make_unique<Int>(*this);
}
inline auto Int::to_string() -> std::string { return std::to_string(inner); }
inline Real::Real(double inner) : inner(inner) {}
[[nodiscard]] inline auto Real::clone() const -> std::unique_ptr<Value> {
return std::make_unique<Real>(*this);
}
inline auto Real::to_string() -> std::string { return cplib::format("%.10g", inner); }
inline Bool::Bool(bool inner) : inner(inner) {}
[[nodiscard]] inline auto Bool::clone() const -> std::unique_ptr<Value> {
return std::make_unique<Bool>(*this);
}
inline auto Bool::to_string() -> std::string {
if (inner) {
return "true";
} else {
return "false";
}
}
inline List::List(std::vector<std::unique_ptr<Value>> inner) : inner(std::move(inner)) {}
[[nodiscard]] inline auto List::clone() const -> std::unique_ptr<Value> {
std::vector<std::unique_ptr<Value>> list;
list.reserve(inner.size());
for (const auto& value : inner) {
list.push_back(value->clone());
}
return std::make_unique<List>(std::move(list));
}
inline auto List::to_string() -> std::string {
std::stringbuf buf(std::ios_base::out);
buf.sputc('[');
if (!inner.empty()) {
auto it = inner.begin();
auto tmp = (*it)->to_string();
buf.sputn(tmp.c_str(), static_cast<std::streamsize>(tmp.size()));
++it;
for (; it != inner.end(); ++it) {
buf.sputc(',');
tmp = (*it)->to_string();
buf.sputn(tmp.c_str(), static_cast<std::streamsize>(tmp.size()));
}
}
buf.sputc(']');
return buf.str();
}
inline Map::Map(std::map<std::string, std::unique_ptr<Value>> inner) : inner(std::move(inner)) {}
[[nodiscard]] inline auto Map::clone() const -> std::unique_ptr<Value> {
std::map<std::string, std::unique_ptr<Value>> map;
for (const auto& [key, value] : inner) {
map.emplace(key, value->clone());
}
return std::make_unique<Map>(std::move(map));
}
inline auto Map::to_string() -> std::string {
std::stringbuf buf(std::ios_base::out);
buf.sputc('{');
if (!inner.empty()) {
auto it = inner.begin();
buf.sputc('\"');
auto tmp = it->first;
buf.sputn(tmp.c_str(), static_cast<std::streamsize>(tmp.size()));
buf.sputc('\"');
buf.sputc(':');
tmp = it->second->to_string();
buf.sputn(tmp.c_str(), static_cast<std::streamsize>(tmp.size()));
++it;
for (; it != inner.end(); ++it) {
buf.sputc(',');
buf.sputc('\"');
tmp = it->first;
buf.sputn(tmp.c_str(), static_cast<std::streamsize>(tmp.size()));
buf.sputc('\"');
buf.sputc(':');
tmp = it->second->to_string();
buf.sputn(tmp.c_str(), static_cast<std::streamsize>(tmp.size()));
}
}
buf.sputc('}');
return buf.str();
}
} // namespace cplib::json
#endif
/*
* This file is part of CPLib.
*
* CPLib is free software: you can redistribute it and/or modify it under the terms of the GNU
* Lesser General Public License as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* CPLib is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with CPLib. If
* not, see <https://www.gnu.org/licenses/>.
*/
#ifndef CPLIB_PATTERN_HPP_
#define CPLIB_PATTERN_HPP_
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include "regex.h"
namespace cplib {
/**
* Regex pattern in POSIX-Extended style. Used for matching strings.
*
* Format see
* `https://en.wikibooks.org/wiki/Regular_Expressions/POSIX-Extended_Regular_Expressions`.
*/
struct Pattern {
public:
/**
* Create pattern instance by string.
*
* @param src The source string representing the regex pattern.
*/
explicit Pattern(std::string src);
/**
* Checks if given string matches the pattern.
*
* @param s The input string to be matched against the pattern.
* @return True if the given string matches the pattern, False otherwise.
*/
[[nodiscard]] auto match(std::string_view s) const -> bool;
/**
* Returns the source string of the pattern.
*
* @return The source string representing the regex pattern.
*/
[[nodiscard]] auto src() const -> std::string_view;
private:
std::string src_;
// `re->second` represents whether regex is compiled successfully
std::shared_ptr<std::pair<regex_t, bool>> re_;
};
} // namespace cplib
/*
* This file is part of CPLib.
*