forked from MikeMirzayanov/testlib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
testlib.h
6064 lines (5127 loc) · 194 KB
/
testlib.h
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
/*
* It is strictly recommended to include "testlib.h" before any other include
* in your code. In this case testlib overrides compiler specific "random()".
*
* If you can't compile your code and compiler outputs something about
* ambiguous call of "random_shuffle", "rand" or "srand" it means that
* you shouldn't use them. Use "shuffle", and "rnd.next()" instead of them
* because these calls produce stable result for any C++ compiler. Read
* sample generator sources for clarification.
*
* Please read the documentation for class "random_t" and use "rnd" instance in
* generators. Probably, these sample calls will be useful for you:
* rnd.next(); rnd.next(100); rnd.next(1, 2);
* rnd.next(3.14); rnd.next("[a-z]{1,100}").
*
* Also read about wnext() to generate off-center random distribution.
*
* See https://github.com/MikeMirzayanov/testlib/ to get latest version or bug tracker.
*/
#ifndef _TESTLIB_H_
#define _TESTLIB_H_
/*
* Copyright (c) 2005-2023
*/
#define VERSION "0.9.41"
/*
* Mike Mirzayanov
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
/* NOTE: This file contains testlib library for C++.
*
* Check, using testlib running format:
* check.exe <Input_File> <Output_File> <Answer_File> [<Result_File> [-appes]],
* If result file is specified it will contain results.
*
* Validator, using testlib running format:
* validator.exe < input.txt,
* It will return non-zero exit code and writes message to standard output.
*
* Generator, using testlib running format:
* gen.exe [parameter-1] [parameter-2] [... paramerter-n]
* You can write generated test(s) into standard output or into the file(s).
*
* Interactor, using testlib running format:
* interactor.exe <Input_File> <Output_File> [<Answer_File> [<Result_File> [-appes]]],
* Reads test from inf (mapped to args[1]), writes result to tout (mapped to argv[2],
* can be judged by checker later), reads program output from ouf (mapped to stdin),
* writes output to program via stdout (use cout, printf, etc).
*/
const char *latestFeatures[] = {
"Use setAppesModeEncoding to change xml encoding from windows-1251 to other",
"rnd.any/wany use distance/advance instead of -/+: now they support sets/multisets",
"Use syntax `int t = inf.readInt(1, 3, \"~t\");` to skip the lower bound check. Tildes can be used on either side or both: ~t, t~, ~t~",
"Supported EJUDGE support in registerTestlibCmd",
"Supported '--testMarkupFileName fn' and '--testCase tc/--testCaseFileName fn' for validators",
"Added opt defaults via opt<T>(key/index, default_val); check unused opts when using has_opt or default opt (turn off this check with suppressEnsureNoUnusedOpt()).",
"For checker added --group and --testset command line params (like for validator), use checker.group() or checker.testset() to get values",
"Added quitpi(points_info, message) function to return with _points exit code 7 and given points_info",
"rnd.partition(size, sum[, min_part=1]) returns random (unsorted) partition which is a representation of the given `sum` as a sum of `size` positive integers (or >=min_part if specified)",
"rnd.distinct(size, n) and rnd.distinct(size, from, to)",
"opt<bool>(\"some_missing_key\") returns false now",
"has_opt(key)",
"Abort validator on validator.testset()/validator.group() if registered without using command line",
"Print integer range violations in a human readable way like `violates the range [1, 10^9]`",
"Opts supported: use them like n = opt<int>(\"n\"), in a command line you can use an exponential notation",
"Reformatted",
"Use setTestCase(i) or unsetTestCase() to support test cases (you can use it in any type of program: generator, interactor, validator or checker)",
"Fixed issue #87: readStrictDouble accepts \"-0.00\"",
"Fixed issue #83: added InStream::quitif(condition, ...)",
"Fixed issue #79: fixed missed guard against repeated header include",
"Fixed issue #80: fixed UB in case of huge quitf message",
"Fixed issue #84: added readXs(size, indexBase = 1)",
"Fixed stringstream repeated usage issue",
"Fixed compilation in g++ (for std=c++03)",
"Batch of println functions (support collections, iterator ranges)",
"Introduced rnd.perm(size, first = 0) to generate a `first`-indexed permutation",
"Allow any whitespace in readInts-like functions for non-validators",
"Ignore 4+ command line arguments ifdef EJUDGE",
"Speed up of vtos",
"Show line number in validators in case of incorrect format",
"Truncate huge checker/validator/interactor message",
"Fixed issue with readTokenTo of very long tokens, now aborts with _pe/_fail depending of a stream type",
"Introduced InStream::ensure/ensuref checking a condition, returns wa/fail depending of a stream type",
"Fixed compilation in VS 2015+",
"Introduced space-separated read functions: readWords/readTokens, multilines read functions: readStrings/readLines",
"Introduced space-separated read functions: readInts/readIntegers/readLongs/readUnsignedLongs/readDoubles/readReals/readStrictDoubles/readStrictReals",
"Introduced split/tokenize functions to separate string by given char",
"Introduced InStream::readUnsignedLong and InStream::readLong with unsigned long long parameters",
"Supported --testOverviewLogFileName for validator: bounds hits + features",
"Fixed UB (sequence points) in random_t",
"POINTS_EXIT_CODE returned back to 7 (instead of 0)",
"Removed disable buffers for interactive problems, because it works unexpectedly in wine",
"InStream over string: constructor of InStream from base InStream to inherit policies and std::string",
"Added expectedButFound quit function, examples: expectedButFound(_wa, 10, 20), expectedButFound(_fail, ja, pa, \"[n=%d,m=%d]\", n, m)",
"Fixed incorrect interval parsing in patterns",
"Use registerGen(argc, argv, 1) to develop new generator, use registerGen(argc, argv, 0) to compile old generators (originally created for testlib under 0.8.7)",
"Introduced disableFinalizeGuard() to switch off finalization checkings",
"Use join() functions to format a range of items as a single string (separated by spaces or other separators)",
"Use -DENABLE_UNEXPECTED_EOF to enable special exit code (by default, 8) in case of unexpected eof. It is good idea to use it in interactors",
"Use -DUSE_RND_AS_BEFORE_087 to compile in compatibility mode with random behavior of versions before 0.8.7",
"Fixed bug with nan in stringToDouble",
"Fixed issue around overloads for size_t on x64",
"Added attribute 'points' to the XML output in case of result=_points",
"Exit codes can be customized via macros, e.g. -DPE_EXIT_CODE=14",
"Introduced InStream function readWordTo/readTokenTo/readStringTo/readLineTo for faster reading",
"Introduced global functions: format(), englishEnding(), upperCase(), lowerCase(), compress()",
"Manual buffer in InStreams, some IO speed improvements",
"Introduced quitif(bool, const char* pattern, ...) which delegates to quitf() in case of first argument is true",
"Introduced guard against missed quitf() in checker or readEof() in validators",
"Supported readStrictReal/readStrictDouble - to use in validators to check strictly float numbers",
"Supported registerInteraction(argc, argv)",
"Print checker message to the stderr instead of stdout",
"Supported TResult _points to output calculated score, use quitp(...) functions",
"Fixed to be compilable on Mac",
"PC_BASE_EXIT_CODE=50 in case of defined TESTSYS",
"Fixed issues 19-21, added __attribute__ format printf",
"Some bug fixes",
"ouf.readInt(1, 100) and similar calls return WA",
"Modified random_t to avoid integer overflow",
"Truncated checker output [patch by Stepan Gatilov]",
"Renamed class random -> class random_t",
"Supported name parameter for read-and-validation methods, like readInt(1, 2, \"n\")",
"Fixed bug in readDouble()",
"Improved ensuref(), fixed nextLine to work in case of EOF, added startTest()",
"Supported \"partially correct\", example: quitf(_pc(13), \"result=%d\", result)",
"Added shuffle(begin, end), use it instead of random_shuffle(begin, end)",
"Added readLine(const string& ptrn), fixed the logic of readLine() in the validation mode",
"Package extended with samples of generators and validators",
"Written the documentation for classes and public methods in testlib.h",
"Implemented random routine to support generators, use registerGen() to switch it on",
"Implemented strict mode to validate tests, use registerValidation() to switch it on",
"Now ncmp.cpp and wcmp.cpp are return WA if answer is suffix or prefix of the output",
"Added InStream::readLong() and removed InStream::readLongint()",
"Now no footer added to each report by default (use directive FOOTER to switch on)",
"Now every checker has a name, use setName(const char* format, ...) to set it",
"Now it is compatible with TTS (by Kittens Computing)",
"Added \'ensure(condition, message = \"\")\' feature, it works like assert()",
"Fixed compatibility with MS C++ 7.1",
"Added footer with exit code information",
"Added compatibility with EJUDGE (compile with EJUDGE directive)",
"Added compatibility with Contester (compile with CONTESTER directive)"
};
#ifdef _MSC_VER
#define _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_NO_VA_START_VALIDATION
#endif
/* Overrides random() for Borland C++. */
#define random __random_deprecated
#include <stdlib.h>
#include <cstdlib>
#include <climits>
#include <algorithm>
#undef random
#include <cstdio>
#include <cctype>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <cmath>
#include <iterator>
#include <iostream>
#include <sstream>
#include <fstream>
#include <cstring>
#include <limits>
#include <stdarg.h>
#include <fcntl.h>
#include <functional>
#include <cstdint>
#ifdef TESTLIB_THROW_EXIT_EXCEPTION_INSTEAD_OF_EXIT
# include <exception>
#endif
#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
# define WORD unsigned short
# include <unistd.h>
# endif
# include <io.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
# define WORD unsigned short
# include <unistd.h>
#endif
#if defined(FOR_WINDOWS) && defined(FOR_LINUX)
#error Only one target system is allowed
#endif
#ifndef LLONG_MIN
#define LLONG_MIN (-9223372036854775807LL - 1)
#endif
#ifndef ULLONG_MAX
#define ULLONG_MAX (18446744073709551615)
#endif
#define LF ((char)10)
#define CR ((char)13)
#define TAB ((char)9)
#define SPACE ((char)' ')
#define EOFC (255)
#ifndef OK_EXIT_CODE
# ifdef CONTESTER
# define OK_EXIT_CODE 0xAC
# else
# define OK_EXIT_CODE 0
# endif
#endif
#ifndef WA_EXIT_CODE
# ifdef EJUDGE
# define WA_EXIT_CODE 5
# elif defined(CONTESTER)
# define WA_EXIT_CODE 0xAB
# else
# define WA_EXIT_CODE 1
# endif
#endif
#ifndef PE_EXIT_CODE
# ifdef EJUDGE
# define PE_EXIT_CODE 4
# elif defined(CONTESTER)
# define PE_EXIT_CODE 0xAA
# else
# define PE_EXIT_CODE 2
# endif
#endif
#ifndef FAIL_EXIT_CODE
# ifdef EJUDGE
# define FAIL_EXIT_CODE 6
# elif defined(CONTESTER)
# define FAIL_EXIT_CODE 0xA3
# else
# define FAIL_EXIT_CODE 3
# endif
#endif
#ifndef DIRT_EXIT_CODE
# ifdef EJUDGE
# define DIRT_EXIT_CODE 6
# else
# define DIRT_EXIT_CODE 4
# endif
#endif
#ifndef POINTS_EXIT_CODE
# define POINTS_EXIT_CODE 7
#endif
#ifndef UNEXPECTED_EOF_EXIT_CODE
# define UNEXPECTED_EOF_EXIT_CODE 8
#endif
#ifndef PC_BASE_EXIT_CODE
# ifdef TESTSYS
# define PC_BASE_EXIT_CODE 50
# else
# define PC_BASE_EXIT_CODE 0
# endif
#endif
#ifdef __GNUC__
# define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[(condition) ? 1 : -1] __attribute__((unused))
#else
# define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[(condition) ? 1 : -1]
#endif
#ifdef ON_WINDOWS
#define I64 "%I64d"
#define U64 "%I64u"
#else
#define I64 "%lld"
#define U64 "%llu"
#endif
#ifdef _MSC_VER
# define NORETURN __declspec(noreturn)
#elif defined __GNUC__
# define NORETURN __attribute__ ((noreturn))
#else
# define NORETURN
#endif
static char __testlib_format_buffer[16777216];
static int __testlib_format_buffer_usage_count = 0;
#define FMT_TO_RESULT(fmt, cstr, result) std::string result; \
if (__testlib_format_buffer_usage_count != 0) \
__testlib_fail("FMT_TO_RESULT::__testlib_format_buffer_usage_count != 0"); \
__testlib_format_buffer_usage_count++; \
va_list ap; \
va_start(ap, fmt); \
vsnprintf(__testlib_format_buffer, sizeof(__testlib_format_buffer), cstr, ap); \
va_end(ap); \
__testlib_format_buffer[sizeof(__testlib_format_buffer) - 1] = 0; \
result = std::string(__testlib_format_buffer); \
__testlib_format_buffer_usage_count--; \
const long long __TESTLIB_LONGLONG_MAX = 9223372036854775807LL;
const int __TESTLIB_MAX_TEST_CASE = 1073741823;
int __testlib_exitCode;
bool __testlib_hasTestCase;
int __testlib_testCase = -1;
void setTestCase(int testCase);
void unsetTestCase() {
__testlib_hasTestCase = false;
__testlib_testCase = -1;
}
NORETURN static void __testlib_fail(const std::string &message);
template<typename T>
#ifdef __GNUC__
__attribute__((const))
#endif
static inline T __testlib_abs(const T &x) {
return x > 0 ? x : -x;
}
template<typename T>
#ifdef __GNUC__
__attribute__((const))
#endif
static inline T __testlib_min(const T &a, const T &b) {
return a < b ? a : b;
}
template<typename T>
#ifdef __GNUC__
__attribute__((const))
#endif
static inline T __testlib_max(const T &a, const T &b) {
return a > b ? a : b;
}
template<typename T>
#ifdef __GNUC__
__attribute__((const))
#endif
static inline T __testlib_crop(T value, T a, T b) {
return __testlib_min(__testlib_max(value, a), --b);
}
#ifdef __GNUC__
__attribute__((const))
#endif
static inline double __testlib_crop(double value, double a, double b) {
value = __testlib_min(__testlib_max(value, a), b);
if (value >= b)
value = std::nexttoward(b, a);
return value;
}
static bool __testlib_prelimIsNaN(double r) {
volatile double ra = r;
#ifndef __BORLANDC__
return ((ra != ra) == true) && ((ra == ra) == false) && ((1.0 > ra) == false) && ((1.0 < ra) == false);
#else
return std::_isnan(ra);
#endif
}
#ifdef __GNUC__
__attribute__((const))
#endif
static std::string removeDoubleTrailingZeroes(std::string value) {
while (!value.empty() && value[value.length() - 1] == '0' && value.find('.') != std::string::npos)
value = value.substr(0, value.length() - 1);
if (!value.empty() && value[value.length() - 1] == '.')
return value + '0';
else
return value;
}
#ifdef __GNUC__
__attribute__((const))
#endif
inline std::string upperCase(std::string s) {
for (size_t i = 0; i < s.length(); i++)
if ('a' <= s[i] && s[i] <= 'z')
s[i] = char(s[i] - 'a' + 'A');
return s;
}
#ifdef __GNUC__
__attribute__((const))
#endif
inline std::string lowerCase(std::string s) {
for (size_t i = 0; i < s.length(); i++)
if ('A' <= s[i] && s[i] <= 'Z')
s[i] = char(s[i] - 'A' + 'a');
return s;
}
#ifdef __GNUC__
__attribute__ ((format (printf, 1, 2)))
#endif
std::string format(const char *fmt, ...) {
FMT_TO_RESULT(fmt, fmt, result);
return result;
}
std::string format(const std::string fmt, ...) {
FMT_TO_RESULT(fmt, fmt.c_str(), result);
return result;
}
#ifdef __GNUC__
__attribute__((const))
#endif
static std::string __testlib_part(const std::string &s);
static bool __testlib_isNaN(double r) {
__TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long));
volatile double ra = r;
long long llr1, llr2;
std::memcpy((void *) &llr1, (void *) &ra, sizeof(double));
ra = -ra;
std::memcpy((void *) &llr2, (void *) &ra, sizeof(double));
long long llnan = 0xFFF8000000000000LL;
return __testlib_prelimIsNaN(r) || llnan == llr1 || llnan == llr2;
}
static double __testlib_nan() {
__TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long));
#ifndef NAN
long long llnan = 0xFFF8000000000000LL;
double nan;
std::memcpy(&nan, &llnan, sizeof(double));
return nan;
#else
return NAN;
#endif
}
static bool __testlib_isInfinite(double r) {
volatile double ra = r;
return (ra > 1E300 || ra < -1E300);
}
#ifdef __GNUC__
__attribute__((const))
#endif
inline bool doubleCompare(double expected, double result, double MAX_DOUBLE_ERROR) {
MAX_DOUBLE_ERROR += 1E-15;
if (__testlib_isNaN(expected)) {
return __testlib_isNaN(result);
} else if (__testlib_isInfinite(expected)) {
if (expected > 0) {
return result > 0 && __testlib_isInfinite(result);
} else {
return result < 0 && __testlib_isInfinite(result);
}
} else if (__testlib_isNaN(result) || __testlib_isInfinite(result)) {
return false;
} else if (__testlib_abs(result - expected) <= MAX_DOUBLE_ERROR) {
return true;
} else {
double minv = __testlib_min(expected * (1.0 - MAX_DOUBLE_ERROR),
expected * (1.0 + MAX_DOUBLE_ERROR));
double maxv = __testlib_max(expected * (1.0 - MAX_DOUBLE_ERROR),
expected * (1.0 + MAX_DOUBLE_ERROR));
return result >= minv && result <= maxv;
}
}
#ifdef __GNUC__
__attribute__((const))
#endif
inline double doubleDelta(double expected, double result) {
double absolute = __testlib_abs(result - expected);
if (__testlib_abs(expected) > 1E-9) {
double relative = __testlib_abs(absolute / expected);
return __testlib_min(absolute, relative);
} else
return absolute;
}
/** It does nothing on non-windows and files differ from stdin/stdout/stderr. */
static void __testlib_set_binary(std::FILE *file) {
if (NULL != file) {
#ifdef ON_WINDOWS
# ifdef _O_BINARY
if (stdin == file)
# ifdef STDIN_FILENO
return void(_setmode(STDIN_FILENO, _O_BINARY));
# else
return void(_setmode(_fileno(stdin), _O_BINARY));
# endif
if (stdout == file)
# ifdef STDOUT_FILENO
return void(_setmode(STDOUT_FILENO, _O_BINARY));
# else
return void(_setmode(_fileno(stdout), _O_BINARY));
# endif
if (stderr == file)
# ifdef STDERR_FILENO
return void(_setmode(STDERR_FILENO, _O_BINARY));
# else
return void(_setmode(_fileno(stderr), _O_BINARY));
# endif
# elif O_BINARY
if (stdin == file)
# ifdef STDIN_FILENO
return void(setmode(STDIN_FILENO, O_BINARY));
# else
return void(setmode(fileno(stdin), O_BINARY));
# endif
if (stdout == file)
# ifdef STDOUT_FILENO
return void(setmode(STDOUT_FILENO, O_BINARY));
# else
return void(setmode(fileno(stdout), O_BINARY));
# endif
if (stderr == file)
# ifdef STDERR_FILENO
return void(setmode(STDERR_FILENO, O_BINARY));
# else
return void(setmode(fileno(stderr), O_BINARY));
# endif
# endif
#endif
}
}
#if __cplusplus > 199711L || defined(_MSC_VER)
template<typename T>
#ifdef __GNUC__
__attribute__((const))
#endif
static std::string vtos(const T &t, std::true_type) {
if (t == 0)
return "0";
else {
T n(t);
bool negative = n < 0;
std::string s;
while (n != 0) {
T digit = n % 10;
if (digit < 0)
digit = -digit;
s += char('0' + digit);
n /= 10;
}
std::reverse(s.begin(), s.end());
return negative ? "-" + s : s;
}
}
template<typename T>
static std::string vtos(const T &t, std::false_type) {
std::string s;
static std::stringstream ss;
ss.str(std::string());
ss.clear();
ss << t;
ss >> s;
return s;
}
template<typename T>
static std::string vtos(const T &t) {
return vtos(t, std::is_integral<T>());
}
/* signed case. */
template<typename T>
static std::string toHumanReadableString(const T &n, std::false_type) {
if (n == 0)
return vtos(n);
int trailingZeroCount = 0;
T n_ = n;
while (n_ % 10 == 0)
n_ /= 10, trailingZeroCount++;
if (trailingZeroCount >= 7) {
if (n_ == 1)
return "10^" + vtos(trailingZeroCount);
else if (n_ == -1)
return "-10^" + vtos(trailingZeroCount);
else
return vtos(n_) + "*10^" + vtos(trailingZeroCount);
} else
return vtos(n);
}
/* unsigned case. */
template<typename T>
static std::string toHumanReadableString(const T &n, std::true_type) {
if (n == 0)
return vtos(n);
int trailingZeroCount = 0;
T n_ = n;
while (n_ % 10 == 0)
n_ /= 10, trailingZeroCount++;
if (trailingZeroCount >= 7) {
if (n_ == 1)
return "10^" + vtos(trailingZeroCount);
else
return vtos(n_) + "*10^" + vtos(trailingZeroCount);
} else
return vtos(n);
}
template<typename T>
static std::string toHumanReadableString(const T &n) {
return toHumanReadableString(n, std::is_unsigned<T>());
}
#else
template<typename T>
static std::string vtos(const T& t)
{
std::string s;
static std::stringstream ss;
ss.str(std::string());
ss.clear();
ss << t;
ss >> s;
return s;
}
template<typename T>
static std::string toHumanReadableString(const T &n) {
return vtos(n);
}
#endif
template<typename T>
static std::string toString(const T &t) {
return vtos(t);
}
#if __cplusplus > 199711L || defined(_MSC_VER)
/* opts */
void prepareOpts(int argc, char* argv[]);
#endif
/*
* Very simple regex-like pattern.
* It used for two purposes: validation and generation.
*
* For example, pattern("[a-z]{1,5}").next(rnd) will return
* random string from lowercase latin letters with length
* from 1 to 5. It is easier to call rnd.next("[a-z]{1,5}")
* for the same effect.
*
* Another samples:
* "mike|john" will generate (match) "mike" or "john";
* "-?[1-9][0-9]{0,3}" will generate (match) non-zero integers from -9999 to 9999;
* "id-([ac]|b{2})" will generate (match) "id-a", "id-bb", "id-c";
* "[^0-9]*" will match sequences (empty or non-empty) without digits, you can't
* use it for generations.
*
* You can't use pattern for generation if it contains meta-symbol '*'. Also it
* is not recommended to use it for char-sets with meta-symbol '^' like [^a-z].
*
* For matching very simple greedy algorithm is used. For example, pattern
* "[0-9]?1" will not match "1", because of greedy nature of matching.
* Alternations (meta-symbols "|") are processed with brute-force algorithm, so
* do not use many alternations in one expression.
*
* If you want to use one expression many times it is better to compile it into
* a single pattern like "pattern p("[a-z]+")". Later you can use
* "p.matches(std::string s)" or "p.next(random_t& rd)" to check matching or generate
* new string by pattern.
*
* Simpler way to read token and check it for pattern matching is "inf.readToken("[a-z]+")".
*
* All spaces are ignored in regex, unless escaped with \. For example, ouf.readLine("NO SOLUTION")
* will expect "NOSOLUTION", the correct call should be ouf.readLine("NO\\ SOLUTION") or
* ouf.readLine(R"(NO\ SOLUTION)") if you prefer raw string literals from C++11.
*/
class random_t;
class pattern {
public:
/* Create pattern instance by string. */
pattern(std::string s);
/* Generate new string by pattern and given random_t. */
std::string next(random_t &rnd) const;
/* Checks if given string match the pattern. */
bool matches(const std::string &s) const;
/* Returns source string of the pattern. */
std::string src() const;
private:
bool matches(const std::string &s, size_t pos) const;
std::string s;
std::vector<pattern> children;
std::vector<char> chars;
int from;
int to;
};
/*
* Use random_t instances to generate random values. It is preferred
* way to use randoms instead of rand() function or self-written
* randoms.
*
* Testlib defines global variable "rnd" of random_t class.
* Use registerGen(argc, argv, 1) to setup random_t seed be command
* line (to use latest random generator version).
*
* Random generates uniformly distributed values if another strategy is
* not specified explicitly.
*/
class random_t {
private:
unsigned long long seed;
static const unsigned long long multiplier;
static const unsigned long long addend;
static const unsigned long long mask;
static const int lim;
long long nextBits(int bits) {
if (bits <= 48) {
seed = (seed * multiplier + addend) & mask;
return (long long) (seed >> (48 - bits));
} else {
if (bits > 63)
__testlib_fail("random_t::nextBits(int bits): n must be less than 64");
int lowerBitCount = (random_t::version == 0 ? 31 : 32);
long long left = (nextBits(31) << 32);
long long right = nextBits(lowerBitCount);
return left ^ right;
}
}
public:
static int version;
/* New random_t with fixed seed. */
random_t()
: seed(3905348978240129619LL) {
}
/* Sets seed by command line. */
void setSeed(int argc, char *argv[]) {
random_t p;
seed = 3905348978240129619LL;
for (int i = 1; i < argc; i++) {
std::size_t le = std::strlen(argv[i]);
for (std::size_t j = 0; j < le; j++)
seed = seed * multiplier + (unsigned int) (argv[i][j]) + addend;
seed += multiplier / addend;
}
seed = seed & mask;
}
/* Sets seed by given value. */
void setSeed(long long _seed) {
seed = (unsigned long long) _seed;
seed = (seed ^ multiplier) & mask;
}
#ifndef __BORLANDC__
/* Random string value by given pattern (see pattern documentation). */
std::string next(const std::string &ptrn) {
pattern p(ptrn);
return p.next(*this);
}
#else
/* Random string value by given pattern (see pattern documentation). */
std::string next(std::string ptrn)
{
pattern p(ptrn);
return p.next(*this);
}
#endif
/* Random value in range [0, n-1]. */
int next(int n) {
if (n <= 0)
__testlib_fail("random_t::next(int n): n must be positive");
if ((n & -n) == n) // n is a power of 2
return (int) ((n * (long long) nextBits(31)) >> 31);
const long long limit = INT_MAX / n * n;
long long bits;
do {
bits = nextBits(31);
} while (bits >= limit);
return int(bits % n);
}
/* Random value in range [0, n-1]. */
unsigned int next(unsigned int n) {
if (n >= INT_MAX)
__testlib_fail("random_t::next(unsigned int n): n must be less INT_MAX");
return (unsigned int) next(int(n));
}
/* Random value in range [0, n-1]. */
long long next(long long n) {
if (n <= 0)
__testlib_fail("random_t::next(long long n): n must be positive");
const long long limit = __TESTLIB_LONGLONG_MAX / n * n;
long long bits;
do {
bits = nextBits(63);
} while (bits >= limit);
return bits % n;
}
/* Random value in range [0, n-1]. */
unsigned long long next(unsigned long long n) {
if (n >= (unsigned long long) (__TESTLIB_LONGLONG_MAX))
__testlib_fail("random_t::next(unsigned long long n): n must be less LONGLONG_MAX");
return (unsigned long long) next((long long) (n));
}
/* Random value in range [0, n-1]. */
long next(long n) {
return (long) next((long long) (n));
}
/* Random value in range [0, n-1]. */
unsigned long next(unsigned long n) {
if (n >= (unsigned long) (LONG_MAX))
__testlib_fail("random_t::next(unsigned long n): n must be less LONG_MAX");
return (unsigned long) next((unsigned long long) (n));
}
/* Returns random value in range [from,to]. */
int next(int from, int to) {
return int(next((long long) to - from + 1) + from);
}
/* Returns random value in range [from,to]. */
unsigned int next(unsigned int from, unsigned int to) {
return (unsigned int) (next((long long) to - from + 1) + from);
}
/* Returns random value in range [from,to]. */
long long next(long long from, long long to) {
return next(to - from + 1) + from;
}
/* Returns random value in range [from,to]. */
unsigned long long next(unsigned long long from, unsigned long long to) {
if (from > to)
__testlib_fail("random_t::next(unsigned long long from, unsigned long long to): from can't not exceed to");
return next(to - from + 1) + from;
}
/* Returns random value in range [from,to]. */
long next(long from, long to) {
return next(to - from + 1) + from;
}
/* Returns random value in range [from,to]. */
unsigned long next(unsigned long from, unsigned long to) {
if (from > to)
__testlib_fail("random_t::next(unsigned long from, unsigned long to): from can't not exceed to");
return next(to - from + 1) + from;
}
/* Random double value in range [0, 1). */
double next() {
long long left = ((long long) (nextBits(26)) << 27);
long long right = nextBits(27);
return __testlib_crop((double) (left + right) / (double) (1LL << 53), 0.0, 1.0);
}
/* Random double value in range [0, n). */
double next(double n) {
if (n <= 0.0)
__testlib_fail("random_t::next(double): n should be positive");
return __testlib_crop(n * next(), 0.0, n);
}
/* Random double value in range [from, to). */
double next(double from, double to) {
if (from >= to)
__testlib_fail("random_t::next(double from, double to): from should be strictly less than to");
return next(to - from) + from;
}
/* Returns random element from container. */
template<typename Container>
typename Container::value_type any(const Container &c) {
int size = int(c.size());
if (size <= 0)
__testlib_fail("random_t::any(const Container& c): c.size() must be positive");
typename Container::const_iterator it = c.begin();
std::advance(it, next(size));
return *it;
}
/* Returns random element from iterator range. */
template<typename Iter>
typename Iter::value_type any(const Iter &begin, const Iter &end) {
int size = static_cast<int>(std::distance(begin, end));
if (size <= 0)
__testlib_fail("random_t::any(const Iter& begin, const Iter& end): range must have positive length");
Iter it = begin;
std::advance(it, next(size));
return *it;
}
/* Random string value by given pattern (see pattern documentation). */
#ifdef __GNUC__
__attribute__ ((format (printf, 2, 3)))
#endif
std::string next(const char *format, ...) {
FMT_TO_RESULT(format, format, ptrn);
return next(ptrn);
}
/*
* Weighted next. If type == 0 than it is usual "next()".
*
* If type = 1, than it returns "max(next(), next())"
* (the number of "max" functions equals to "type").
*
* If type < 0, than "max" function replaces with "min".
*/
int wnext(int n, int type) {
if (n <= 0)
__testlib_fail("random_t::wnext(int n, int type): n must be positive");
if (abs(type) < random_t::lim) {
int result = next(n);
for (int i = 0; i < +type; i++)
result = __testlib_max(result, next(n));
for (int i = 0; i < -type; i++)
result = __testlib_min(result, next(n));
return result;
} else {
double p;
if (type > 0)
p = std::pow(next() + 0.0, 1.0 / (type + 1));
else
p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1));
return __testlib_crop((int) (double(n) * p), 0, n);
}
}
/* See wnext(int, int). It uses the same algorithms. */
long long wnext(long long n, int type) {
if (n <= 0)