testlib.h 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976
  1. /*
  2. * It is strictly recommended to include "testlib.h" before any other include
  3. * in your code. In this case testlib overrides compiler specific "random()".
  4. *
  5. * If you can't compile your code and compiler outputs something about
  6. * ambiguous call of "random_shuffle", "rand" or "srand" it means that
  7. * you shouldn't use them. Use "shuffle", and "rnd.next()" instead of them
  8. * because these calls produce stable result for any C++ compiler. Read
  9. * sample generator sources for clarification.
  10. *
  11. * Please read the documentation for class "random_t" and use "rnd" instance in
  12. * generators. Probably, these sample calls will be usefull for you:
  13. * rnd.next(); rnd.next(100); rnd.next(1, 2);
  14. * rnd.next(3.14); rnd.next("[a-z]{1,100}").
  15. *
  16. * Also read about wnext() to generate off-center random distribution.
  17. *
  18. * See http://code.google.com/p/testlib/ to get latest version or bug tracker.
  19. */
  20. #ifndef _TESTLIB_H_
  21. #define _TESTLIB_H_
  22. /*
  23. * Copyright (c) 2005-2013
  24. */
  25. #define VERSION "0.8.3-SNAPSHOT"
  26. /*
  27. * Mike Mirzayanov
  28. *
  29. * This material is provided "as is", with absolutely no warranty expressed
  30. * or implied. Any use is at your own risk.
  31. *
  32. * Permission to use or copy this software for any purpose is hereby granted
  33. * without fee, provided the above notices are retained on all copies.
  34. * Permission to modify the code and to distribute modified code is granted,
  35. * provided the above notices are retained, and a notice that the code was
  36. * modified is included with the above copyright notice.
  37. *
  38. */
  39. /* NOTE: This file contains testlib library for C++.
  40. *
  41. * Check, using testlib running format:
  42. * check.exe <Input_File> <Output_File> <Answer_File> [<Result_File> [-appes]],
  43. * If result file is specified it will contain results.
  44. *
  45. * Validator, using testlib running format:
  46. * validator.exe < input.txt,
  47. * It will return non-zero exit code and writes message to standard output.
  48. *
  49. * Generator, using testlib running format:
  50. * gen.exe [parameter-1] [parameter-2] [... paramerter-n]
  51. * You can write generated test(s) into standard output or into the file(s).
  52. *
  53. * Interactor, using testlib running format:
  54. * interactor.exe <Input_File> <Output_File> [<Answer_File> [<Result_File> [-appes]]],
  55. * Reads test from inf (mapped to args[1]), writes result to tout (mapped to argv[2],
  56. * can be judged by checker later), reads program output from ouf (mapped to stdin),
  57. * writes output to program via stdout (use cout, printf, etc).
  58. */
  59. const char* latestFeatures[] = {
  60. "Introduced InStream function readWordTo/readTokenTo/readStringTo/readLineTo for faster reading",
  61. "Introduced global functions: format(), englishEnding(), upperCase(), lowerCase(), compress()",
  62. "Manual buffer in InStreams, some IO speed improvements",
  63. "Introduced quitif(bool, const char* pattern, ...) which delegates to quitf() in case of first argument is true",
  64. "Introduced guard against missed quitf() in checker or readEof() in validators",
  65. "Supported readStrictReal/readStrictDouble - to use in validators to check strictly float numbers",
  66. "Supported registerInteraction(argc, argv)",
  67. "Print checker message to the stderr instead of stdout",
  68. "Supported TResult _points to output calculated score, use quitp(...) functions",
  69. "Fixed to be compilable on Mac",
  70. "PC_BASE_EXIT_CODE=50 in case of defined TESTSYS",
  71. "Fixed issues 19-21, added __attribute__ format printf",
  72. "Some bug fixes",
  73. "ouf.readInt(1, 100) and similar calls return WA",
  74. "Modified random_t to avoid integer overflow",
  75. "Truncated checker output [patch by Stepan Gatilov]",
  76. "Renamed class random -> class random_t",
  77. "Supported name parameter for read-and-validation methods, like readInt(1, 2, \"n\")",
  78. "Fixed bug in readDouble()",
  79. "Improved ensuref(), fixed nextLine to work in case of EOF, added startTest()",
  80. "Supported \"partially correct\", example: quitf(_pc(13), \"result=%d\", result)",
  81. "Added shuffle(begin, end), use it instead of random_shuffle(begin, end)",
  82. "Added readLine(const string& ptrn), fixed the logic of readLine() in the validation mode",
  83. "Package extended with samples of generators and validators",
  84. "Written the documentation for classes and public methods in testlib.h",
  85. "Implemented random routine to support generators, use registerGen() to switch it on",
  86. "Implemented strict mode to validate tests, use registerValidation() to switch it on",
  87. "Now ncmp.cpp and wcmp.cpp are return WA if answer is suffix or prefix of the output",
  88. "Added InStream::readLong() and removed InStream::readLongint()",
  89. "Now no footer added to each report by default (use directive FOOTER to switch on)",
  90. "Now every checker has a name, use setName(const char* format, ...) to set it",
  91. "Now it is compatible with TTS (by Kittens Computing)",
  92. "Added \'ensure(condition, message = \"\")\' feature, it works like assert()",
  93. "Fixed compatibility with MS C++ 7.1",
  94. "Added footer with exit code information",
  95. "Added compatibility with EJUDGE (compile with EJUDGE directive)"
  96. };
  97. #ifdef _MSC_VER
  98. #define _CRT_SECURE_NO_DEPRECATE
  99. #define _CRT_SECURE_NO_WARNINGS
  100. #endif
  101. /* Overrides random() for Borland C++. */
  102. #define random __random_deprecated
  103. #include <stdlib.h>
  104. #include <cstdlib>
  105. #include <climits>
  106. #include <algorithm>
  107. #undef random
  108. #include <cstdio>
  109. #include <cctype>
  110. #include <string>
  111. #include <vector>
  112. #include <cmath>
  113. #include <sstream>
  114. #include <fstream>
  115. #include <cstring>
  116. #include <stdarg.h>
  117. #include <fcntl.h>
  118. #if ( _WIN32 || __WIN32__ || _WIN64 || __WIN64__ )
  119. #include <windows.h>
  120. #include <io.h>
  121. #define ON_WINDOWS
  122. #else
  123. #define WORD unsigned short
  124. #endif
  125. #ifndef LLONG_MIN
  126. #define LLONG_MIN (-9223372036854775807LL - 1)
  127. #endif
  128. #define LF ((char)10)
  129. #define CR ((char)13)
  130. #define TAB ((char)9)
  131. #define SPACE ((char)' ')
  132. #define EOFC ((char)26)
  133. #ifndef EJUDGE
  134. #define OK_EXIT_CODE 0
  135. #define WA_EXIT_CODE 1
  136. #define PE_EXIT_CODE 2
  137. #define FAIL_EXIT_CODE 3
  138. #define DIRT_EXIT_CODE 4
  139. #define POINTS_EXIT_CODE 7
  140. #define PC_BASE_EXIT_CODE 0
  141. #else
  142. #define OK_EXIT_CODE 0
  143. #define WA_EXIT_CODE 5
  144. #define PE_EXIT_CODE 4
  145. #define FAIL_EXIT_CODE 6
  146. #define DIRT_EXIT_CODE 6
  147. #define POINTS_EXIT_CODE 7
  148. #define PC_BASE_EXIT_CODE 0
  149. #endif
  150. #ifdef TESTSYS
  151. #undef PC_BASE_EXIT_CODE
  152. #define PC_BASE_EXIT_CODE 50
  153. #endif
  154. #define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[((condition) != 0) * 2 - 1];
  155. #ifdef ON_WINDOWS
  156. #define I64 "%I64d"
  157. #define U64 "%I64u"
  158. #else
  159. #define I64 "%lld"
  160. #define U64 "%llu"
  161. #endif
  162. char __testlib_format_buffer[16777216];
  163. int __testlib_format_buffer_usage_count = 0;
  164. #define FMT_TO_RESULT(fmt, cstr, result) std::string result; \
  165. do { \
  166. if (__testlib_format_buffer_usage_count != 0) \
  167. __testlib_fail("FMT_TO_RESULT::__testlib_format_buffer_usage_count != 0"); \
  168. __testlib_format_buffer_usage_count++; \
  169. va_list ap; \
  170. va_start(ap, fmt); \
  171. std::vsprintf(__testlib_format_buffer, cstr, ap); \
  172. va_end(ap); \
  173. result = std::string(__testlib_format_buffer); \
  174. __testlib_format_buffer_usage_count--; \
  175. } while (0) \
  176. const long long __TESTLIB_LONGLONG_MAX = 9223372036854775807LL;
  177. template<typename T>
  178. static inline T __testlib_abs(const T& x)
  179. {
  180. return x > 0 ? x : -x;
  181. }
  182. template<typename T>
  183. static inline T __testlib_min(const T& a, const T& b)
  184. {
  185. return a < b ? a : b;
  186. }
  187. template<typename T>
  188. static inline T __testlib_max(const T& a, const T& b)
  189. {
  190. return a > b ? a : b;
  191. }
  192. static void __testlib_fail(const std::string& message);
  193. static void __testlib_set_binary(FILE* file)
  194. {
  195. #if !defined(unix) && !defined(__APPLE__)
  196. if (NULL != file)
  197. {
  198. #ifdef _MSC_VER
  199. _setmode(_fileno(file), O_BINARY);
  200. #else
  201. #ifdef fileno
  202. setmode(fileno(file), O_BINARY);
  203. #endif
  204. #endif
  205. }
  206. #endif
  207. }
  208. /*
  209. * Very simple regex-like pattern.
  210. * It used for two purposes: validation and generation.
  211. *
  212. * For example, pattern("[a-z]{1,5}").next(rnd) will return
  213. * random string from lowercase latin letters with length
  214. * from 1 to 5. It is easier to call rnd.next("[a-z]{1,5}")
  215. * for the same effect.
  216. *
  217. * Another samples:
  218. * "mike|john" will generate (match) "mike" or "john";
  219. * "-?[1-9][0-9]{0,3}" will generate (match) non-zero integers from -9999 to 9999;
  220. * "id-([ac]|b{2})" will generate (match) "id-a", "id-bb", "id-c";
  221. * "[^0-9]*" will match sequences (empty or non-empty) without digits, you can't
  222. * use it for generations.
  223. *
  224. * You can't use pattern for generation if it contains meta-symbol '*'. Also it
  225. * is not recommended to use it for char-sets with meta-symbol '^' like [^a-z].
  226. *
  227. * For matching very simple greedy algorithm is used. For example, pattern
  228. * "[0-9]?1" will not match "1", because of greedy nature of matching.
  229. * Alternations (meta-symbols "|") are processed with brute-force algorithm, so
  230. * do not use many alternations in one expression.
  231. *
  232. * If you want to use one expression many times it is better to compile it into
  233. * a single pattern like "pattern p("[a-z]+")". Later you can use
  234. * "p.matches(std::string s)" or "p.next(random_t& rd)" to check matching or generate
  235. * new string by pattern.
  236. *
  237. * Simpler way to read token and check it for pattern matching is "inf.readToken("[a-z]+")".
  238. */
  239. class random_t;
  240. class pattern
  241. {
  242. public:
  243. /* Create pattern instance by string. */
  244. pattern(std::string s);
  245. /* Generate new string by pattern and given random_t. */
  246. std::string next(random_t& rnd) const;
  247. /* Checks if given string match the pattern. */
  248. bool matches(const std::string& s) const;
  249. /* Returns source string of the pattern. */
  250. std::string src() const;
  251. private:
  252. bool matches(const std::string& s, size_t pos) const;
  253. std::string s;
  254. std::vector<pattern> children;
  255. std::vector<char> chars;
  256. int from;
  257. int to;
  258. };
  259. /*
  260. * Use random_t instances to generate random values. It is preffered
  261. * way to use randoms instead of rand() function or self-written
  262. * randoms.
  263. *
  264. * Testlib defines global variable "rnd" of random_t class.
  265. * Use registerGen(argc, argv) to setup random_t seed be command
  266. * line.
  267. *
  268. * Random generates uniformly distributed values if another strategy is
  269. * not specified explicitly.
  270. */
  271. class random_t
  272. {
  273. private:
  274. long long seed;
  275. static const long long multiplier;
  276. static const long long addend;
  277. static const long long mask;
  278. static const int lim;
  279. long long nextBits(int bits)
  280. {
  281. if (bits <= 48)
  282. {
  283. seed = (seed * multiplier + addend) & mask;
  284. return (long long)(seed >> (48 - bits));
  285. }
  286. else
  287. {
  288. if (bits > 63)
  289. __testlib_fail("random_t::nextBits(int bits): n must be less than 64");
  290. return ((nextBits(31) << 32) ^ nextBits(31));
  291. }
  292. }
  293. public:
  294. /* New random_t with fixed seed. */
  295. random_t()
  296. : seed(3905348978240129619LL)
  297. {
  298. }
  299. /* Sets seed by command line. */
  300. void setSeed(int argc, char* argv[])
  301. {
  302. random_t p;
  303. seed = 3905348978240129619LL;
  304. for (int i = 1; i < argc; i++)
  305. {
  306. std::size_t le = std::strlen(argv[i]);
  307. for (std::size_t j = 0; j < le; j++)
  308. seed = seed * multiplier + (unsigned int)(argv[i][j]) + addend;
  309. seed += multiplier / addend;
  310. }
  311. seed = seed & mask;
  312. }
  313. /* Sets seed by given value. */
  314. void setSeed(long long _seed)
  315. {
  316. _seed = (_seed ^ multiplier) & mask;
  317. seed = _seed;
  318. }
  319. /* Random value in range [0, n-1]. */
  320. int next(int n)
  321. {
  322. if (n <= 0)
  323. __testlib_fail("random_t::next(int n): n must be positive");
  324. if ((n & -n) == n) // n is a power of 2
  325. return (int)((n * (long long)nextBits(31)) >> 31);
  326. const long long limit = INT_MAX / n * n;
  327. long long bits;
  328. do {
  329. bits = nextBits(31);
  330. } while (bits >= limit);
  331. return int(bits % n);
  332. }
  333. /* Random value in range [0, n-1]. */
  334. template<typename T>
  335. int next(T n)
  336. {
  337. if (n >= INT_MAX)
  338. __testlib_fail("random_t::next(unsigned int n): n must be less INT_MAX");
  339. return next(int(n));
  340. }
  341. /* Random value in range [0, n-1]. */
  342. long long next(long long n)
  343. {
  344. if (n <= 0)
  345. __testlib_fail("random_t::next(long long n): n must be positive");
  346. const long long limit = __TESTLIB_LONGLONG_MAX / n * n;
  347. long long bits;
  348. do {
  349. bits = nextBits(63);
  350. } while (bits >= limit);
  351. return bits % n;
  352. }
  353. /* Random value in range [0, n-1]. */
  354. unsigned long long next(unsigned long long n)
  355. {
  356. if (n >= (unsigned long long)(__TESTLIB_LONGLONG_MAX))
  357. __testlib_fail("random_t::next(unsigned long long n): n must be less LONGLONG_MAX");
  358. return (unsigned long long)next((long long)(n));
  359. }
  360. /* Returns random value in range [from,to]. */
  361. int next(int from, int to)
  362. {
  363. return int(next((long long)to - from + 1) + from);
  364. }
  365. /* Returns random value in range [from,to]. */
  366. unsigned int next(unsigned int from, unsigned int to)
  367. {
  368. return (unsigned int)(next((long long)to - from + 1) + from);
  369. }
  370. /* Returns random value in range [from,to]. */
  371. long long next(long long from, long long to)
  372. {
  373. return next(to - from + 1) + from;
  374. }
  375. /* Random double value in range [0, 1). */
  376. double next()
  377. {
  378. return (((long long)(nextBits(26)) << 27) + nextBits(27)) / (double)(1LL << 53);
  379. }
  380. /* Random double value in range [0, n). */
  381. double next(double n)
  382. {
  383. return n * next();
  384. }
  385. /* Random double value in range [from, to). */
  386. double next(double from, double to)
  387. {
  388. return next(to - from) + from;
  389. }
  390. /* Random string value by given pattern (see pattern documentation). */
  391. std::string next(const std::string& ptrn)
  392. {
  393. pattern p(ptrn);
  394. return p.next(*this);
  395. }
  396. /* Returns random element from container. */
  397. template <typename Container>
  398. typename Container::value_type any(const Container& c)
  399. {
  400. size_t size = c.size();
  401. if (size <= 0)
  402. __testlib_fail("random_t::any(const Container& c): c.size() must be positive");
  403. return *(c.begin() + next(size));
  404. }
  405. /* Returns random element from iterator range. */
  406. template <typename Iter>
  407. typename Iter::value_type any(const Iter& begin, const Iter& end)
  408. {
  409. int size = int(end - begin);
  410. if (size <= 0)
  411. __testlib_fail("random_t::any(const Iter& begin, const Iter& end): range must have positive length");
  412. return *(begin + next(size));
  413. }
  414. /* Random string value by given pattern (see pattern documentation). */
  415. #ifdef __GNUC__
  416. __attribute__ ((format (printf, 2, 3)))
  417. #endif
  418. std::string next(const char* format, ...)
  419. {
  420. FMT_TO_RESULT(format, format, ptrn);
  421. return next(ptrn);
  422. }
  423. /*
  424. * Weighted next. If type == 0 than it is usual "next()".
  425. *
  426. * If type = 1, than it returns "max(next(), next())"
  427. * (the number of "max" functions equals to "type").
  428. *
  429. * If type < 0, than "max" function replaces with "min".
  430. */
  431. int wnext(int n, int type)
  432. {
  433. if (n <= 0)
  434. __testlib_fail("random_t::wnext(int n, int type): n must be positive");
  435. if (abs(type) < random_t::lim)
  436. {
  437. int result = next(n);
  438. for (int i = 0; i < +type; i++)
  439. result = __testlib_max(result, next(n));
  440. for (int i = 0; i < -type; i++)
  441. result = __testlib_min(result, next(n));
  442. return result;
  443. }
  444. else
  445. {
  446. double p;
  447. if (type > 0)
  448. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  449. else
  450. p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1));
  451. return int(n * p);
  452. }
  453. }
  454. /* See wnext(int, int). It uses the same algorithms. */
  455. template<typename T>
  456. int wnext(T n, int type)
  457. {
  458. if (n >= INT_MAX)
  459. __testlib_fail("random_t::wnext(unsigned int n, int type): n must be less INT_MAX");
  460. return wnext(int(n), type);
  461. }
  462. /* See wnext(int, int). It uses the same algorithms. */
  463. long long wnext(long long n, int type)
  464. {
  465. if (n <= 0)
  466. __testlib_fail("random_t::wnext(long long n, int type): n must be positive");
  467. if (abs(type) < random_t::lim)
  468. {
  469. long long result = next(n);
  470. for (int i = 0; i < +type; i++)
  471. result = __testlib_max(result, next(n));
  472. for (int i = 0; i < -type; i++)
  473. result = __testlib_min(result, next(n));
  474. return result;
  475. }
  476. else
  477. {
  478. double p;
  479. if (type > 0)
  480. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  481. else
  482. p = std::pow(next() + 0.0, - type + 1);
  483. return (long long)(n * p);
  484. }
  485. }
  486. /* See wnext(int, int). It uses the same algorithms. */
  487. double wnext(int type)
  488. {
  489. if (abs(type) < random_t::lim)
  490. {
  491. double result = next();
  492. for (int i = 0; i < +type; i++)
  493. result = __testlib_max(result, next());
  494. for (int i = 0; i < -type; i++)
  495. result = __testlib_min(result, next());
  496. return result;
  497. }
  498. else
  499. {
  500. double p;
  501. if (type > 0)
  502. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  503. else
  504. p = std::pow(next() + 0.0, - type + 1);
  505. return p;
  506. }
  507. }
  508. /* See wnext(int, int). It uses the same algorithms. */
  509. double wnext(double n, int type)
  510. {
  511. if (n <= 0)
  512. __testlib_fail("random_t::wnext(double n, int type): n must be positive");
  513. if (abs(type) < random_t::lim)
  514. {
  515. double result = next();
  516. for (int i = 0; i < +type; i++)
  517. result = __testlib_max(result, next());
  518. for (int i = 0; i < -type; i++)
  519. result = __testlib_min(result, next());
  520. return n * result;
  521. }
  522. else
  523. {
  524. double p;
  525. if (type > 0)
  526. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  527. else
  528. p = std::pow(next() + 0.0, - type + 1);
  529. return n * p;
  530. }
  531. }
  532. /* Returns weighted random value in range [from, to]. */
  533. int wnext(int from, int to, int type)
  534. {
  535. return wnext(to - from + 1, type) + from;
  536. }
  537. /* Returns weighted random value in range [from, to]. */
  538. int wnext(unsigned int from, unsigned int to, int type)
  539. {
  540. return wnext(to - from + 1, type) + from;
  541. }
  542. /* Returns weighted random value in range [from, to]. */
  543. long long wnext(long long from, long long to, int type)
  544. {
  545. return wnext(to - from + 1, type) + from;
  546. }
  547. /* Returns weighted random double value in range [from, to). */
  548. double wnext(double from, double to, int type)
  549. {
  550. return wnext(to - from, type) + from;
  551. }
  552. /* Returns weighted random element from container. */
  553. template <typename Container>
  554. typename Container::value_type wany(const Container& c, int type)
  555. {
  556. size_t size = c.size();
  557. if (size <= 0)
  558. __testlib_fail("random_t::wany(const Container& c, int type): c.size() must be positive");
  559. return *(c.begin() + wnext(size, type));
  560. }
  561. /* Returns weighted random element from iterator range. */
  562. template <typename Iter>
  563. typename Iter::value_type wany(const Iter& begin, const Iter& end, int type)
  564. {
  565. int size = int(end - begin);
  566. if (size <= 0)
  567. __testlib_fail("random_t::any(const Iter& begin, const Iter& end, int type): range must have positive length");
  568. return *(begin + wnext(size, type));
  569. }
  570. };
  571. const int random_t::lim = 25;
  572. const long long random_t::multiplier = 0x5DEECE66DLL;
  573. const long long random_t::addend = 0xBLL;
  574. const long long random_t::mask = (1LL << 48) - 1;
  575. /* Pattern implementation */
  576. bool pattern::matches(const std::string& s) const
  577. {
  578. return matches(s, 0);
  579. }
  580. static bool __pattern_isSlash(const std::string& s, size_t pos)
  581. {
  582. return s[pos] == '\\';
  583. }
  584. #ifdef __GNUC__
  585. __attribute__((pure))
  586. #endif
  587. static bool __pattern_isCommandChar(const std::string& s, size_t pos, char value)
  588. {
  589. if (pos >= s.length())
  590. return false;
  591. int slashes = 0;
  592. int before = pos - 1;
  593. while (before >= 0 && s[before] == '\\')
  594. before--, slashes++;
  595. return slashes % 2 == 0 && s[pos] == value;
  596. }
  597. static char __pattern_getChar(const std::string& s, size_t& pos)
  598. {
  599. if (__pattern_isSlash(s, pos))
  600. pos += 2;
  601. else
  602. pos++;
  603. return s[pos - 1];
  604. }
  605. #ifdef __GNUC__
  606. __attribute__((pure))
  607. #endif
  608. static int __pattern_greedyMatch(const std::string& s, size_t pos, const std::vector<char> chars)
  609. {
  610. int result = 0;
  611. while (pos < s.length())
  612. {
  613. char c = s[pos++];
  614. if (!std::binary_search(chars.begin(), chars.end(), c))
  615. break;
  616. else
  617. result++;
  618. }
  619. return result;
  620. }
  621. std::string pattern::src() const
  622. {
  623. return s;
  624. }
  625. bool pattern::matches(const std::string& s, size_t pos) const
  626. {
  627. std::string result;
  628. if (to > 0)
  629. {
  630. int size = __pattern_greedyMatch(s, pos, chars);
  631. if (size < from)
  632. return false;
  633. if (size > to)
  634. size = to;
  635. pos += size;
  636. }
  637. if (children.size() > 0)
  638. {
  639. for (size_t child = 0; child < children.size(); child++)
  640. if (children[child].matches(s, pos))
  641. return true;
  642. return false;
  643. }
  644. else
  645. return pos == s.length();
  646. }
  647. std::string pattern::next(random_t& rnd) const
  648. {
  649. std::string result;
  650. result.reserve(20);
  651. if (to == INT_MAX)
  652. __testlib_fail("pattern::next(random_t& rnd): can't process character '*' for generation");
  653. if (to > 0)
  654. {
  655. int count = rnd.next(to - from + 1) + from;
  656. for (int i = 0; i < count; i++)
  657. result += chars[rnd.next(int(chars.size()))];
  658. }
  659. if (children.size() > 0)
  660. {
  661. int child = rnd.next(int(children.size()));
  662. result += children[child].next(rnd);
  663. }
  664. return result;
  665. }
  666. static void __pattern_scanCounts(const std::string& s, size_t& pos, int& from, int& to)
  667. {
  668. if (pos >= s.length())
  669. {
  670. from = to = 1;
  671. return;
  672. }
  673. if (__pattern_isCommandChar(s, pos, '{'))
  674. {
  675. std::vector<std::string> parts;
  676. std::string part;
  677. pos++;
  678. while (pos < s.length() && !__pattern_isCommandChar(s, pos, '}'))
  679. {
  680. if (__pattern_isCommandChar(s, pos, ','))
  681. parts.push_back(part), part = "", pos++;
  682. else
  683. part += __pattern_getChar(s, pos);
  684. }
  685. if (part != "")
  686. parts.push_back(part);
  687. if (!__pattern_isCommandChar(s, pos, '}'))
  688. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  689. pos++;
  690. if (parts.size() < 1 || parts.size() > 2)
  691. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  692. std::vector<int> numbers;
  693. for (size_t i = 0; i < parts.size(); i++)
  694. {
  695. if (parts[i].length() == 0)
  696. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  697. int number;
  698. if (std::sscanf(parts[i].c_str(), "%d", &number) != 1)
  699. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  700. numbers.push_back(number);
  701. }
  702. if (numbers.size() == 1)
  703. from = to = numbers[0];
  704. else
  705. from = numbers[0], to = numbers[1];
  706. if (from > to)
  707. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  708. }
  709. else
  710. {
  711. if (__pattern_isCommandChar(s, pos, '?'))
  712. {
  713. from = 0, to = 1, pos++;
  714. return;
  715. }
  716. if (__pattern_isCommandChar(s, pos, '*'))
  717. {
  718. from = 0, to = INT_MAX, pos++;
  719. return;
  720. }
  721. if (__pattern_isCommandChar(s, pos, '+'))
  722. {
  723. from = 1, to = INT_MAX, pos++;
  724. return;
  725. }
  726. from = to = 1;
  727. }
  728. }
  729. static std::vector<char> __pattern_scanCharSet(const std::string& s, size_t& pos)
  730. {
  731. if (pos >= s.length())
  732. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  733. std::vector<char> result;
  734. if (__pattern_isCommandChar(s, pos, '['))
  735. {
  736. pos++;
  737. bool negative = __pattern_isCommandChar(s, pos, '^');
  738. char prev = 0;
  739. while (pos < s.length() && !__pattern_isCommandChar(s, pos, ']'))
  740. {
  741. if (__pattern_isCommandChar(s, pos, '-') && prev != 0)
  742. {
  743. pos++;
  744. if (pos + 1 == s.length())
  745. {
  746. result.push_back(prev);
  747. prev = '-';
  748. continue;
  749. }
  750. char next = __pattern_getChar(s, pos);
  751. if (prev > next)
  752. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  753. for (char c = prev; c != next; c++)
  754. result.push_back(c);
  755. result.push_back(next);
  756. prev = 0;
  757. }
  758. else
  759. {
  760. if (prev != 0)
  761. result.push_back(prev);
  762. prev = __pattern_getChar(s, pos);
  763. }
  764. }
  765. if (prev != 0)
  766. result.push_back(prev);
  767. if (!__pattern_isCommandChar(s, pos, ']'))
  768. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  769. pos++;
  770. if (negative)
  771. {
  772. std::sort(result.begin(), result.end());
  773. std::vector<char> actuals;
  774. for (int code = 0; code < 255; code++)
  775. {
  776. char c = char(code);
  777. if (!std::binary_search(result.begin(), result.end(), c))
  778. actuals.push_back(c);
  779. }
  780. result = actuals;
  781. }
  782. std::sort(result.begin(), result.end());
  783. }
  784. else
  785. result.push_back(__pattern_getChar(s, pos));
  786. return result;
  787. }
  788. pattern::pattern(std::string s): s(s), from(0), to(0)
  789. {
  790. std::string t;
  791. for (size_t i = 0; i < s.length(); i++)
  792. if (!__pattern_isCommandChar(s, i, ' '))
  793. t += s[i];
  794. s = t;
  795. int opened = 0;
  796. int firstClose = -1;
  797. std::vector<int> seps;
  798. for (size_t i = 0; i < s.length(); i++)
  799. {
  800. if (__pattern_isCommandChar(s, i, '('))
  801. {
  802. opened++;
  803. continue;
  804. }
  805. if (__pattern_isCommandChar(s, i, ')'))
  806. {
  807. opened--;
  808. if (opened == 0 && firstClose == -1)
  809. firstClose = i;
  810. continue;
  811. }
  812. if (opened < 0)
  813. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  814. if (__pattern_isCommandChar(s, i, '|') && opened == 0)
  815. seps.push_back(i);
  816. }
  817. if (opened != 0)
  818. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  819. if (seps.size() == 0 && firstClose + 1 == (int)s.length()
  820. && __pattern_isCommandChar(s, 0, '(') && __pattern_isCommandChar(s, s.length() - 1, ')'))
  821. {
  822. children.push_back(pattern(s.substr(1, s.length() - 2)));
  823. }
  824. else
  825. {
  826. if (seps.size() > 0)
  827. {
  828. seps.push_back(s.length());
  829. int last = 0;
  830. for (size_t i = 0; i < seps.size(); i++)
  831. {
  832. children.push_back(pattern(s.substr(last, seps[i] - last)));
  833. last = seps[i] + 1;
  834. }
  835. }
  836. else
  837. {
  838. size_t pos = 0;
  839. chars = __pattern_scanCharSet(s, pos);
  840. __pattern_scanCounts(s, pos, from, to);
  841. if (pos < s.length())
  842. children.push_back(pattern(s.substr(pos)));
  843. }
  844. }
  845. }
  846. /* End of pattern implementation */
  847. inline bool isEof(char c)
  848. {
  849. return (c == EOF || c == EOFC);
  850. }
  851. inline bool isEoln(char c)
  852. {
  853. return (c == LF || c == CR);
  854. }
  855. inline bool isBlanks(char c)
  856. {
  857. return (c == LF || c == CR || c == SPACE || c == TAB);
  858. }
  859. enum TMode
  860. {
  861. _input, _output, _answer
  862. };
  863. enum TResult
  864. {
  865. _ok, _wa, _pe, _fail, _dirt, _partially, _points
  866. };
  867. enum TTestlibMode
  868. {
  869. _unknown, _checker, _validator, _generator, _interactor
  870. };
  871. #define _pc(exitCode) (TResult(_partially + (exitCode)))
  872. const std::string outcomes[] =
  873. {"accepted", "wrong-answer", "presentation-error", "fail", "fail", "partially-correct", "points"};
  874. class InputStreamReader
  875. {
  876. public:
  877. virtual int curChar() = 0;
  878. virtual int nextChar() = 0;
  879. virtual void skipChar() = 0;
  880. virtual void unreadChar(int c) = 0;
  881. virtual std::string getName() = 0;
  882. virtual bool eof() = 0;
  883. virtual ~InputStreamReader() = 0;
  884. };
  885. InputStreamReader::~InputStreamReader()
  886. {
  887. // No operations.
  888. }
  889. class FileInputStreamReader: public InputStreamReader
  890. {
  891. private:
  892. FILE* file;
  893. std::string name;
  894. public:
  895. FileInputStreamReader(FILE* file, const std::string& name): file(file), name(name)
  896. {
  897. // No operations.
  898. }
  899. int curChar()
  900. {
  901. if (feof(file))
  902. return EOF;
  903. else
  904. {
  905. int c = getc(file);
  906. ungetc(c, file);
  907. return c;
  908. }
  909. }
  910. int nextChar()
  911. {
  912. if (feof(file))
  913. return EOF;
  914. else
  915. return getc(file);
  916. }
  917. void skipChar()
  918. {
  919. getc(file);
  920. }
  921. void unreadChar(int c)
  922. {
  923. ungetc(c, file);
  924. }
  925. std::string getName()
  926. {
  927. return name;
  928. }
  929. bool eof()
  930. {
  931. if (feof(file))
  932. return true;
  933. else
  934. {
  935. int c = getc(file);
  936. bool result = (c == EOF);
  937. ungetc(c, file);
  938. return result;
  939. }
  940. }
  941. };
  942. class BufferedFileInputStreamReader: public InputStreamReader
  943. {
  944. private:
  945. static const size_t BUFFER_SIZE;
  946. static const size_t MAX_UNREAD_COUNT;
  947. FILE* file;
  948. char* buffer;
  949. bool* isEof;
  950. int bufferPos;
  951. int bufferSize;
  952. std::string name;
  953. bool refill()
  954. {
  955. if (NULL == file)
  956. __testlib_fail("BufferedFileInputStreamReader: file == NULL (" + getName() + ")");
  957. if (bufferPos >= int(bufferSize))
  958. {
  959. size_t readSize = fread(
  960. buffer + MAX_UNREAD_COUNT,
  961. 1,
  962. BUFFER_SIZE - MAX_UNREAD_COUNT,
  963. file
  964. );
  965. if (readSize < BUFFER_SIZE - MAX_UNREAD_COUNT
  966. && ferror(file))
  967. __testlib_fail("BufferedFileInputStreamReader: unable to read (" + getName() + ")");
  968. bufferSize = MAX_UNREAD_COUNT + readSize;
  969. bufferPos = MAX_UNREAD_COUNT;
  970. std::memset(isEof + MAX_UNREAD_COUNT, 0, sizeof(isEof[0]) * readSize);
  971. return readSize > 0;
  972. }
  973. else
  974. return true;
  975. }
  976. public:
  977. BufferedFileInputStreamReader(FILE* file, const std::string& name): file(file), name(name)
  978. {
  979. buffer = new char[BUFFER_SIZE];
  980. isEof = new bool[BUFFER_SIZE];
  981. bufferSize = MAX_UNREAD_COUNT;
  982. bufferPos = MAX_UNREAD_COUNT;
  983. }
  984. ~BufferedFileInputStreamReader()
  985. {
  986. if (NULL != buffer)
  987. {
  988. delete[] buffer;
  989. buffer = NULL;
  990. }
  991. if (NULL != isEof)
  992. {
  993. delete[] isEof;
  994. isEof = NULL;
  995. }
  996. }
  997. int curChar()
  998. {
  999. if (!refill())
  1000. return EOF;
  1001. return isEof[bufferPos] ? EOF : buffer[bufferPos];
  1002. }
  1003. int nextChar()
  1004. {
  1005. if (!refill())
  1006. return EOF;
  1007. return isEof[bufferPos] ? EOF : buffer[bufferPos++];
  1008. }
  1009. void skipChar()
  1010. {
  1011. bufferPos++;
  1012. }
  1013. void unreadChar(int c)
  1014. {
  1015. bufferPos--;
  1016. if (bufferPos < 0)
  1017. __testlib_fail("BufferedFileInputStreamReader::unreadChar(int): bufferPos < 0");
  1018. isEof[bufferPos] = (c == EOF);
  1019. buffer[bufferPos] = (c == EOF ? EOFC : c);
  1020. }
  1021. std::string getName()
  1022. {
  1023. return name;
  1024. }
  1025. bool eof()
  1026. {
  1027. return !refill() || EOF == curChar();
  1028. }
  1029. };
  1030. const size_t BufferedFileInputStreamReader::BUFFER_SIZE = 1000000;
  1031. const size_t BufferedFileInputStreamReader::MAX_UNREAD_COUNT = 100;
  1032. /*
  1033. * Streams to be used for reading data in checkers or validators.
  1034. * Each read*() method moves pointer to the next character after the
  1035. * read value.
  1036. */
  1037. struct InStream
  1038. {
  1039. /* Do not use them. */
  1040. InStream();
  1041. ~InStream();
  1042. InputStreamReader* reader;
  1043. std::FILE* file;
  1044. std::string name;
  1045. TMode mode;
  1046. bool opened;
  1047. bool stdfile;
  1048. bool strict;
  1049. int wordReserveSize;
  1050. std::string _tmpReadToken;
  1051. void init(std::string fileName, TMode mode);
  1052. void init(std::FILE* f, TMode mode);
  1053. /* Moves stream pointer to the first non-white-space character or EOF. */
  1054. void skipBlanks();
  1055. /* Returns current character in the stream. Doesn't remove it from stream. */
  1056. char curChar();
  1057. /* Moves stream pointer one character forward. */
  1058. void skipChar();
  1059. /* Returns current character and moves pointer one character forward. */
  1060. char nextChar();
  1061. /* Returns current character and moves pointer one character forward. */
  1062. char readChar();
  1063. /* As "readChar()" but ensures that the result is equal to given parameter. */
  1064. char readChar(char c);
  1065. /* As "readChar()" but ensures that the result is equal to the space (code=32). */
  1066. char readSpace();
  1067. /* Puts back the character into the stream. */
  1068. void unreadChar(char c);
  1069. /* Reopens stream, you should not use it. */
  1070. void reset();
  1071. /* Checks that current position is EOF. If not it doesn't move stream pointer. */
  1072. bool eof();
  1073. /* Moves pointer to the first non-white-space character and calls "eof()". */
  1074. bool seekEof();
  1075. /*
  1076. * Checks that current position contains EOLN.
  1077. * If not it doesn't move stream pointer.
  1078. * In strict mode expects "#13#10" for windows or "#10" for other platforms.
  1079. */
  1080. bool eoln();
  1081. /* Moves pointer to the first non-space and non-tab character and calls "eoln()". */
  1082. bool seekEoln();
  1083. /* Moves stream pointer to the first character of the next line (if exists). */
  1084. void nextLine();
  1085. /*
  1086. * Reads new token. Ignores white-spaces into the non-strict mode
  1087. * (strict mode is used in validators usually).
  1088. */
  1089. std::string readWord();
  1090. /* The same as "readWord()", it is preffered to use "readToken()". */
  1091. std::string readToken();
  1092. /* The same as "readWord()", but ensures that token matches to given pattern. */
  1093. std::string readWord(const std::string& ptrn, const std::string& variableName = "");
  1094. std::string readWord(const pattern& p, const std::string& variableName = "");
  1095. /* The same as "readToken()", but ensures that token matches to given pattern. */
  1096. std::string readToken(const std::string& ptrn, const std::string& variableName = "");
  1097. std::string readToken(const pattern& p, const std::string& variableName = "");
  1098. void readWordTo(std::string& result);
  1099. void readWordTo(std::string& result, const pattern& p, const std::string& variableName = "");
  1100. void readWordTo(std::string& result, const std::string& ptrn, const std::string& variableName = "");
  1101. void readTokenTo(std::string& result);
  1102. void readTokenTo(std::string& result, const pattern& p, const std::string& variableName = "");
  1103. void readTokenTo(std::string& result, const std::string& ptrn, const std::string& variableName = "");
  1104. /*
  1105. * Reads new long long value. Ignores white-spaces into the non-strict mode
  1106. * (strict mode is used in validators usually).
  1107. */
  1108. long long readLong();
  1109. /*
  1110. * Reads new int. Ignores white-spaces into the non-strict mode
  1111. * (strict mode is used in validators usually).
  1112. */
  1113. int readInteger();
  1114. /*
  1115. * Reads new int. Ignores white-spaces into the non-strict mode
  1116. * (strict mode is used in validators usually).
  1117. */
  1118. int readInt();
  1119. /* As "readLong()" but ensures that value in the range [minv,maxv]. */
  1120. long long readLong(long long minv, long long maxv, const std::string& variableName = "");
  1121. /* As "readInteger()" but ensures that value in the range [minv,maxv]. */
  1122. int readInteger(int minv, int maxv, const std::string& variableName = "");
  1123. /* As "readInt()" but ensures that value in the range [minv,maxv]. */
  1124. int readInt(int minv, int maxv, const std::string& variableName = "");
  1125. /*
  1126. * Reads new double. Ignores white-spaces into the non-strict mode
  1127. * (strict mode is used in validators usually).
  1128. */
  1129. double readReal();
  1130. /*
  1131. * Reads new double. Ignores white-spaces into the non-strict mode
  1132. * (strict mode is used in validators usually).
  1133. */
  1134. double readDouble();
  1135. /* As "readReal()" but ensures that value in the range [minv,maxv]. */
  1136. double readReal(double minv, double maxv, const std::string& variableName = "");
  1137. /* As "readDouble()" but ensures that value in the range [minv,maxv]. */
  1138. double readDouble(double minv, double maxv, const std::string& variableName = "");
  1139. /*
  1140. * As "readReal()" but ensures that value in the range [minv,maxv] and
  1141. * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]
  1142. * and number is in the form "[-]digit(s)[.digit(s)]".
  1143. */
  1144. double readStrictReal(double minv, double maxv,
  1145. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  1146. const std::string& variableName = "");
  1147. /*
  1148. * As "readDouble()" but ensures that value in the range [minv,maxv] and
  1149. * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]
  1150. * and number is in the form "[-]digit(s)[.digit(s)]".
  1151. */
  1152. double readStrictDouble(double minv, double maxv,
  1153. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  1154. const std::string& variableName = "");
  1155. /* As readLine(). */
  1156. std::string readString();
  1157. /* See readLine(). */
  1158. void readStringTo(std::string& result);
  1159. /* The same as "readLine()/readString()", but ensures that line matches to the given pattern. */
  1160. std::string readString(const pattern& p, const std::string& variableName = "");
  1161. /* The same as "readLine()/readString()", but ensures that line matches to the given pattern. */
  1162. std::string readString(const std::string& ptrn, const std::string& variableName = "");
  1163. /* The same as "readLine()/readString()", but ensures that line matches to the given pattern. */
  1164. void readStringTo(std::string& result, const pattern& p, const std::string& variableName = "");
  1165. /* The same as "readLine()/readString()", but ensures that line matches to the given pattern. */
  1166. void readStringTo(std::string& result, const std::string& ptrn, const std::string& variableName = "");
  1167. /*
  1168. * Reads line from the current position to EOLN or EOF. Moves stream pointer to
  1169. * the first character of the new line (if possible).
  1170. */
  1171. std::string readLine();
  1172. /* See readLine(). */
  1173. void readLineTo(std::string& result);
  1174. /* The same as "readLine()", but ensures that line matches to the given pattern. */
  1175. std::string readLine(const pattern& p, const std::string& variableName = "");
  1176. /* The same as "readLine()", but ensures that line matches to the given pattern. */
  1177. std::string readLine(const std::string& ptrn, const std::string& variableName = "");
  1178. /* The same as "readLine()", but ensures that line matches to the given pattern. */
  1179. void readLineTo(std::string& result, const pattern& p, const std::string& variableName = "");
  1180. /* The same as "readLine()", but ensures that line matches to the given pattern. */
  1181. void readLineTo(std::string& result, const std::string& ptrn, const std::string& variableName = "");
  1182. /* Reads EOLN or fails. Use it in validators. Calls "eoln()" method internally. */
  1183. void readEoln();
  1184. /* Reads EOF or fails. Use it in validators. Calls "eof()" method internally. */
  1185. void readEof();
  1186. /*
  1187. * Quit-functions aborts program with <result> and <message>:
  1188. * input/answer streams replaces any result to FAIL.
  1189. */
  1190. void quit(TResult result, const char* msg);
  1191. /*
  1192. * Quit-functions aborts program with <result> and <message>:
  1193. * input/answer streams replaces any result to FAIL.
  1194. */
  1195. void quitf(TResult result, const char* msg, ...);
  1196. /*
  1197. * Quit-functions aborts program with <result> and <message>:
  1198. * input/answer streams replaces any result to FAIL.
  1199. */
  1200. void quits(TResult result, std::string msg);
  1201. void close();
  1202. const static WORD LightGray = 0x07;
  1203. const static WORD LightRed = 0x0c;
  1204. const static WORD LightCyan = 0x0b;
  1205. const static WORD LightGreen = 0x0a;
  1206. const static WORD LightYellow = 0x0e;
  1207. static void textColor(WORD color);
  1208. static void quitscr(WORD color, const char* msg);
  1209. static void quitscrS(WORD color, std::string msg);
  1210. void xmlSafeWrite(std::FILE * file, const char* msg);
  1211. };
  1212. InStream inf;
  1213. InStream ouf;
  1214. InStream ans;
  1215. bool appesMode;
  1216. std::string resultName;
  1217. std::string checkerName = "untitled checker";
  1218. random_t rnd;
  1219. TTestlibMode testlibMode = _unknown;
  1220. struct TestlibFinalizeGuard
  1221. {
  1222. static bool alive;
  1223. int quitCount, readEofCount;
  1224. TestlibFinalizeGuard() : quitCount(0), readEofCount(0)
  1225. {
  1226. // No operations.
  1227. }
  1228. ~TestlibFinalizeGuard()
  1229. {
  1230. bool _alive = alive;
  1231. alive = false;
  1232. if (_alive)
  1233. {
  1234. if (testlibMode == _checker && quitCount == 0)
  1235. __testlib_fail("Checker must end with quit or quitf call.");
  1236. if (testlibMode == _validator && readEofCount == 0 && quitCount == 0)
  1237. __testlib_fail("Validator must end with readEof call.");
  1238. }
  1239. }
  1240. };
  1241. bool TestlibFinalizeGuard::alive = true;
  1242. TestlibFinalizeGuard testlibFinalizeGuard;
  1243. /* Interactor streams.
  1244. */
  1245. std::fstream tout;
  1246. /* implementation
  1247. */
  1248. template <typename T>
  1249. static std::string vtos(const T& t)
  1250. {
  1251. std::string s;
  1252. std::stringstream ss;
  1253. ss << t;
  1254. ss >> s;
  1255. return s;
  1256. }
  1257. InStream::InStream()
  1258. {
  1259. file = NULL;
  1260. name = "";
  1261. mode = _input;
  1262. strict = false;
  1263. stdfile = false;
  1264. wordReserveSize = 4;
  1265. }
  1266. InStream::~InStream()
  1267. {
  1268. if (NULL != reader)
  1269. {
  1270. delete reader;
  1271. reader = NULL;
  1272. }
  1273. }
  1274. #ifdef __GNUC__
  1275. __attribute__((const))
  1276. #endif
  1277. int resultExitCode(TResult r)
  1278. {
  1279. if (r == _ok)
  1280. return OK_EXIT_CODE;
  1281. if (r == _wa)
  1282. return WA_EXIT_CODE;
  1283. if (r == _pe)
  1284. return PE_EXIT_CODE;
  1285. if (r == _fail)
  1286. return FAIL_EXIT_CODE;
  1287. if (r == _dirt)
  1288. return DIRT_EXIT_CODE;
  1289. if (r == _points)
  1290. return POINTS_EXIT_CODE;
  1291. if (r >= _partially)
  1292. return PC_BASE_EXIT_CODE + (r - _partially);
  1293. return FAIL_EXIT_CODE;
  1294. }
  1295. void InStream::textColor(WORD color)
  1296. {
  1297. #ifdef ON_WINDOWS
  1298. HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
  1299. SetConsoleTextAttribute(handle, color);
  1300. #endif
  1301. }
  1302. #ifdef __GNUC__
  1303. __attribute__ ((noreturn))
  1304. #endif
  1305. void halt(int exitCode)
  1306. {
  1307. #ifdef FOOTER
  1308. InStream::textColor(InStream::LightGray);
  1309. std::fprintf(stderr, "Checker: \"%s\"\n", checkerName.c_str());
  1310. std::fprintf(stderr, "Exit code: %d\n", exitCode);
  1311. InStream::textColor(InStream::LightGray);
  1312. #endif
  1313. std::exit(exitCode);
  1314. }
  1315. #ifdef __GNUC__
  1316. __attribute__ ((noreturn))
  1317. #endif
  1318. void InStream::quit(TResult result, const char* msg)
  1319. {
  1320. if (TestlibFinalizeGuard::alive)
  1321. testlibFinalizeGuard.quitCount++;
  1322. if (mode != _output && result != _fail)
  1323. quits(_fail, std::string(msg) + " (" + name + ")");
  1324. std::FILE * resultFile;
  1325. std::string errorName;
  1326. if (result == _ok)
  1327. {
  1328. if (testlibMode != _interactor && !ouf.seekEof())
  1329. quit(_dirt, "Extra information in the output file");
  1330. }
  1331. int pctype = result - _partially;
  1332. switch (result)
  1333. {
  1334. case _fail:
  1335. errorName = "FAIL ";
  1336. quitscrS(LightRed, errorName);
  1337. break;
  1338. case _dirt:
  1339. errorName = "wrong output format ";
  1340. quitscrS(LightCyan, errorName);
  1341. result = _pe;
  1342. break;
  1343. case _pe:
  1344. errorName = "wrong output format ";
  1345. quitscrS(LightRed, errorName);
  1346. break;
  1347. case _ok:
  1348. errorName = "ok ";
  1349. quitscrS(LightGreen, errorName);
  1350. break;
  1351. case _wa:
  1352. errorName = "wrong answer ";
  1353. quitscrS(LightRed, errorName);
  1354. break;
  1355. case _points:
  1356. errorName = "points ";
  1357. quitscrS(LightYellow, errorName);
  1358. break;
  1359. default:
  1360. if (result >= _partially)
  1361. {
  1362. char message[1023];
  1363. std::sprintf(message, "partially correct (%d) ", pctype);
  1364. errorName = std::string(message);
  1365. quitscrS(LightYellow, errorName);
  1366. }
  1367. else
  1368. quit(_fail, "What is the code ??? ");
  1369. }
  1370. if (resultName != "")
  1371. {
  1372. resultFile = std::fopen(resultName.c_str(), "w");
  1373. if (resultFile == NULL)
  1374. quit(_fail, "Can not write to Result file");
  1375. if (appesMode)
  1376. {
  1377. fprintf(resultFile, "<?xml version=\"1.0\" encoding=\"windows-1251\"?>");
  1378. if (result >= _partially)
  1379. fprintf(resultFile, "<result outcome = \"%s\" pctype = \"%d\">", outcomes[(int)_partially].c_str(), pctype);
  1380. else
  1381. fprintf(resultFile, "<result outcome = \"%s\">", outcomes[(int)result].c_str());
  1382. xmlSafeWrite(resultFile, msg);
  1383. fprintf(resultFile, "</result>\n");
  1384. }
  1385. else
  1386. fprintf(resultFile, "%s", msg);
  1387. if (NULL == resultFile || fclose(resultFile) != 0)
  1388. quit(_fail, "Can not write to Result file");
  1389. }
  1390. quitscr(LightGray, msg);
  1391. std::fprintf(stderr, "\n");
  1392. if (inf.file)
  1393. fclose(inf.file);
  1394. if (ouf.file)
  1395. fclose(ouf.file);
  1396. if (ans.file)
  1397. fclose(ans.file);
  1398. if (tout.is_open())
  1399. tout.close();
  1400. textColor(LightGray);
  1401. if (resultName != "")
  1402. std::fprintf(stderr, "See file to check exit message\n");
  1403. halt(resultExitCode(result));
  1404. }
  1405. #ifdef __GNUC__
  1406. __attribute__ ((format (printf, 3, 4)))
  1407. __attribute__ ((noreturn))
  1408. #endif
  1409. void InStream::quitf(TResult result, const char* msg, ...)
  1410. {
  1411. FMT_TO_RESULT(msg, msg, message);
  1412. InStream::quit(result, message.c_str());
  1413. }
  1414. #ifdef __GNUC__
  1415. __attribute__ ((noreturn))
  1416. #endif
  1417. void InStream::quits(TResult result, std::string msg)
  1418. {
  1419. InStream::quit(result, msg.c_str());
  1420. }
  1421. void InStream::xmlSafeWrite(std::FILE * file, const char* msg)
  1422. {
  1423. size_t lmsg = strlen(msg);
  1424. for (size_t i = 0; i < lmsg; i++)
  1425. {
  1426. if (msg[i] == '&')
  1427. {
  1428. fprintf(file, "%s", "&amp;");
  1429. continue;
  1430. }
  1431. if (msg[i] == '<')
  1432. {
  1433. fprintf(file, "%s", "&lt;");
  1434. continue;
  1435. }
  1436. if (msg[i] == '>')
  1437. {
  1438. fprintf(file, "%s", "&gt;");
  1439. continue;
  1440. }
  1441. if (msg[i] == '"')
  1442. {
  1443. fprintf(file, "%s", "&quot;");
  1444. continue;
  1445. }
  1446. if (0 <= msg[i] && msg[i] <= 31)
  1447. {
  1448. fprintf(file, "%c", '.');
  1449. continue;
  1450. }
  1451. fprintf(file, "%c", msg[i]);
  1452. }
  1453. }
  1454. void InStream::quitscrS(WORD color, std::string msg)
  1455. {
  1456. quitscr(color, msg.c_str());
  1457. }
  1458. void InStream::quitscr(WORD color, const char* msg)
  1459. {
  1460. if (resultName == "")
  1461. {
  1462. textColor(color);
  1463. std::fprintf(stderr, "%s", msg);
  1464. textColor(LightGray);
  1465. }
  1466. }
  1467. void InStream::reset()
  1468. {
  1469. if (opened && stdfile)
  1470. quit(_fail, "Can't reset standard handle");
  1471. if (opened)
  1472. close();
  1473. if (!stdfile)
  1474. if (NULL == (file = std::fopen(name.c_str(), "rb")))
  1475. {
  1476. if (mode == _output)
  1477. quits(_pe, std::string("File not found: \"") + name + "\"");
  1478. }
  1479. opened = true;
  1480. __testlib_set_binary(file);
  1481. if (stdfile)
  1482. reader = new FileInputStreamReader(file, name);
  1483. else
  1484. reader = new BufferedFileInputStreamReader(file, name);
  1485. }
  1486. void InStream::init(std::string fileName, TMode mode)
  1487. {
  1488. opened = false;
  1489. name = fileName;
  1490. stdfile = false;
  1491. this->mode = mode;
  1492. reset();
  1493. }
  1494. void InStream::init(std::FILE* f, TMode mode)
  1495. {
  1496. opened = false;
  1497. name = "untitled";
  1498. if (f == stdin)
  1499. name = "stdin", stdfile = true;
  1500. if (f == stdout)
  1501. name = "stdout", stdfile = true;
  1502. if (f == stderr)
  1503. name = "stderr", stdfile = true;
  1504. this->file = f;
  1505. this->mode = mode;
  1506. reset();
  1507. }
  1508. char InStream::curChar()
  1509. {
  1510. int c = reader->curChar();
  1511. return c != EOF ? c : EOFC;
  1512. }
  1513. char InStream::nextChar()
  1514. {
  1515. int c = reader->nextChar();
  1516. return c != EOF ? c : EOFC;
  1517. }
  1518. char InStream::readChar()
  1519. {
  1520. return nextChar();
  1521. }
  1522. char InStream::readChar(char c)
  1523. {
  1524. char found = readChar();
  1525. if (c != found)
  1526. {
  1527. if (!isEoln(found))
  1528. quit(_pe, ("Unexpected character '" + std::string(1, found) + "', but '" + std::string(1, c) + "' expected").c_str());
  1529. else
  1530. quit(_pe, ("Unexpected character " + ("#" + vtos(int(found))) + ", but '" + std::string(1, c) + "' expected").c_str());
  1531. }
  1532. return found;
  1533. }
  1534. char InStream::readSpace()
  1535. {
  1536. return readChar(' ');
  1537. }
  1538. void InStream::unreadChar(char c)
  1539. {
  1540. reader->unreadChar(c);
  1541. }
  1542. void InStream::skipChar()
  1543. {
  1544. reader->skipChar();
  1545. }
  1546. void InStream::skipBlanks()
  1547. {
  1548. while (isBlanks(reader->curChar()))
  1549. reader->skipChar();
  1550. }
  1551. std::string InStream::readWord()
  1552. {
  1553. readWordTo(_tmpReadToken);
  1554. return _tmpReadToken;
  1555. }
  1556. void InStream::readWordTo(std::string& result)
  1557. {
  1558. if (!strict)
  1559. skipBlanks();
  1560. int cur = reader->nextChar();
  1561. if (cur == EOF)
  1562. quit(_pe, "Unexpected end of file - token expected");
  1563. if (isBlanks(cur))
  1564. quit(_pe, "Unexpected white-space - token expected");
  1565. result.clear();
  1566. while (!(isBlanks(cur) || cur == EOF))
  1567. {
  1568. result += char(cur);
  1569. cur = reader->nextChar();
  1570. }
  1571. reader->unreadChar(cur);
  1572. if (result.length() == 0)
  1573. quit(_pe, "Unexpected end of file or white-space - token expected");
  1574. }
  1575. std::string InStream::readToken()
  1576. {
  1577. return readWord();
  1578. }
  1579. void InStream::readTokenTo(std::string& result)
  1580. {
  1581. readWordTo(result);
  1582. }
  1583. static std::string __testlib_part(const std::string& s)
  1584. {
  1585. if (s.length() <= 64)
  1586. return s;
  1587. else
  1588. return s.substr(0, 30) + "..." + s.substr(s.length() - 31, 31);
  1589. }
  1590. std::string InStream::readWord(const pattern& p, const std::string& variableName)
  1591. {
  1592. readWordTo(_tmpReadToken);
  1593. if (!p.matches(_tmpReadToken))
  1594. {
  1595. if (variableName.empty())
  1596. quit(_wa, ("Token \"" + __testlib_part(_tmpReadToken) + "\" doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  1597. else
  1598. quit(_wa, ("Token parameter [name=" + variableName + "] equals to \"" + __testlib_part(_tmpReadToken) + "\", doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  1599. }
  1600. return _tmpReadToken;
  1601. }
  1602. std::string InStream::readWord(const std::string& ptrn, const std::string& variableName)
  1603. {
  1604. return readWord(pattern(ptrn), variableName);
  1605. }
  1606. std::string InStream::readToken(const pattern& p, const std::string& variableName)
  1607. {
  1608. return readWord(p, variableName);
  1609. }
  1610. std::string InStream::readToken(const std::string& ptrn, const std::string& variableName)
  1611. {
  1612. return readWord(ptrn, variableName);
  1613. }
  1614. void InStream::readWordTo(std::string& result, const pattern& p, const std::string& variableName)
  1615. {
  1616. readWordTo(result);
  1617. if (!p.matches(result))
  1618. {
  1619. if (variableName.empty())
  1620. quit(_wa, ("Token \"" + __testlib_part(result) + "\" doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  1621. else
  1622. quit(_wa, ("Token parameter [name=" + variableName + "] equals to \"" + __testlib_part(result) + "\", doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  1623. }
  1624. }
  1625. void InStream::readWordTo(std::string& result, const std::string& ptrn, const std::string& variableName)
  1626. {
  1627. return readWordTo(result, pattern(ptrn), variableName);
  1628. }
  1629. void InStream::readTokenTo(std::string& result, const pattern& p, const std::string& variableName)
  1630. {
  1631. return readWordTo(result, p, variableName);
  1632. }
  1633. void InStream::readTokenTo(std::string& result, const std::string& ptrn, const std::string& variableName)
  1634. {
  1635. return readWordTo(result, ptrn, variableName);
  1636. }
  1637. #ifdef __GNUC__
  1638. __attribute__((pure))
  1639. #endif
  1640. static bool equals(long long integer, const char* s)
  1641. {
  1642. if (integer == LLONG_MIN)
  1643. return strcmp(s, "-9223372036854775808") == 0;
  1644. if (integer == 0LL)
  1645. return strcmp(s, "0") == 0;
  1646. size_t length = strlen(s);
  1647. if (length == 0)
  1648. return false;
  1649. if (integer < 0 && s[0] != '-')
  1650. return false;
  1651. if (integer < 0)
  1652. s++, length--, integer = -integer;
  1653. if (length == 0)
  1654. return false;
  1655. while (integer > 0)
  1656. {
  1657. int digit = int(integer % 10);
  1658. if (s[length - 1] != '0' + digit)
  1659. return false;
  1660. length--;
  1661. integer /= 10;
  1662. }
  1663. return length == 0;
  1664. }
  1665. static double stringToDouble(InStream& in, const char* buffer)
  1666. {
  1667. double retval;
  1668. size_t length = strlen(buffer);
  1669. for (size_t i = 0; i < length; i++)
  1670. if (isBlanks(buffer[i]))
  1671. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1672. char* suffix = new char[length + 1];
  1673. int scanned = std::sscanf(buffer, "%lf%s", &retval, suffix);
  1674. bool empty = strlen(suffix) == 0;
  1675. delete[] suffix;
  1676. if (scanned == 1 || (scanned == 2 && empty))
  1677. return retval;
  1678. else
  1679. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1680. __testlib_fail("Unexpected case in stringToDouble");
  1681. return retval;
  1682. }
  1683. static double stringToStrictDouble(InStream& in, const char* buffer, int minAfterPointDigitCount, int maxAfterPointDigitCount)
  1684. {
  1685. double retval;
  1686. size_t length = strlen(buffer);
  1687. if (length == 0 || length > 20)
  1688. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1689. if (buffer[0] != '-' && (buffer[0] < '0' || buffer[0] > '9'))
  1690. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1691. int pointPos = -1;
  1692. for (size_t i = 1; i + 1 < length; i++)
  1693. {
  1694. if (buffer[i] == '.')
  1695. {
  1696. if (pointPos > -1)
  1697. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1698. pointPos = i;
  1699. }
  1700. if (buffer[i] != '.' && (buffer[i] < '0' || buffer[i] > '9'))
  1701. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1702. }
  1703. if (buffer[length - 1] < '0' || buffer[length - 1] > '9')
  1704. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1705. int afterDigitsCount = (pointPos == -1 ? 0 : length - pointPos - 1);
  1706. if (afterDigitsCount < minAfterPointDigitCount || afterDigitsCount > maxAfterPointDigitCount)
  1707. in.quit(_pe, ("Expected strict double with number of digits after point in range ["
  1708. + vtos(minAfterPointDigitCount)
  1709. + ","
  1710. + vtos(maxAfterPointDigitCount)
  1711. + "], but \"" + __testlib_part(buffer) + "\" found").c_str()
  1712. );
  1713. int firstDigitPos = -1;
  1714. for (size_t i = 0; i < length; i++)
  1715. if (buffer[i] >= '0' && buffer[i] <= '9')
  1716. {
  1717. firstDigitPos = i;
  1718. break;
  1719. }
  1720. if (firstDigitPos > 1 || firstDigitPos == -1)
  1721. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1722. if (buffer[firstDigitPos] == '0' && firstDigitPos + 1 < int(length)
  1723. && buffer[firstDigitPos + 1] >= '0' && buffer[firstDigitPos + 1] <= '9')
  1724. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1725. char* suffix = new char[length + 1];
  1726. int scanned = std::sscanf(buffer, "%lf%s", &retval, suffix);
  1727. bool empty = strlen(suffix) == 0;
  1728. delete[] suffix;
  1729. if (scanned == 1 || (scanned == 2 && empty))
  1730. return retval;
  1731. else
  1732. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1733. __testlib_fail("Unexpected case in stringToStrictDouble");
  1734. return retval;
  1735. }
  1736. static long long stringToLongLong(InStream& in, const char* buffer)
  1737. {
  1738. if (strcmp(buffer, "-9223372036854775808") == 0)
  1739. return LLONG_MIN;
  1740. bool minus = false;
  1741. size_t length = strlen(buffer);
  1742. if (length > 1 && buffer[0] == '-')
  1743. minus = true;
  1744. if (length > 20)
  1745. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1746. long long retval = 0LL;
  1747. int zeroes = 0;
  1748. int processingZeroes = true;
  1749. for (size_t i = (minus ? 1 : 0); i < length; i++)
  1750. {
  1751. if (buffer[i] == '0' && processingZeroes)
  1752. zeroes++;
  1753. else
  1754. processingZeroes = false;
  1755. if (buffer[i] < '0' || buffer[i] > '9')
  1756. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1757. retval = retval * 10 + (buffer[i] - '0');
  1758. }
  1759. if (retval < 0)
  1760. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1761. if ((zeroes > 0 && (retval != 0 || minus)) || zeroes > 1)
  1762. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1763. retval = (minus ? -retval : +retval);
  1764. if (length < 19)
  1765. return retval;
  1766. if (equals(retval, buffer))
  1767. return retval;
  1768. else
  1769. in.quit(_pe, ("Expected int64, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1770. __testlib_fail("Unexpected case in stringToLongLong");
  1771. return retval;
  1772. }
  1773. int InStream::readInteger()
  1774. {
  1775. if (!strict && seekEof())
  1776. quit(_pe, "Unexpected end of file - int32 expected");
  1777. readWordTo(_tmpReadToken);
  1778. long long value = stringToLongLong(*this, _tmpReadToken.c_str());
  1779. if (value < INT_MIN || value > INT_MAX)
  1780. quit(_pe, ("Expected int32, but \"" + _tmpReadToken + "\" found").c_str());
  1781. return int(value);
  1782. }
  1783. long long InStream::readLong()
  1784. {
  1785. if (!strict && seekEof())
  1786. quit(_pe, "Unexpected end of file - int64 expected");
  1787. readWordTo(_tmpReadToken);
  1788. return stringToLongLong(*this, _tmpReadToken.c_str());
  1789. }
  1790. long long InStream::readLong(long long minv, long long maxv, const std::string& variableName)
  1791. {
  1792. long long result = readLong();
  1793. if (result < minv || result > maxv)
  1794. {
  1795. if (variableName.empty())
  1796. quit(_wa, ("Integer " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1797. else
  1798. quit(_wa, ("Integer parameter [name=" + variableName + "] equals to " + vtos(result) + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1799. }
  1800. return result;
  1801. }
  1802. int InStream::readInt()
  1803. {
  1804. return readInteger();
  1805. }
  1806. int InStream::readInt(int minv, int maxv, const std::string& variableName)
  1807. {
  1808. int result = readInt();
  1809. if (result < minv || result > maxv)
  1810. {
  1811. if (variableName.empty())
  1812. quit(_wa, ("Integer " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1813. else
  1814. quit(_wa, ("Integer parameter [name=" + std::string(variableName) + "] equals to " + vtos(result) + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1815. }
  1816. return result;
  1817. }
  1818. int InStream::readInteger(int minv, int maxv, const std::string& variableName)
  1819. {
  1820. return readInt(minv, maxv, variableName);
  1821. }
  1822. double InStream::readReal()
  1823. {
  1824. if (!strict && seekEof())
  1825. quit(_pe, "Unexpected end of file - double expected");
  1826. return stringToDouble(*this, readWord().c_str());
  1827. }
  1828. double InStream::readDouble()
  1829. {
  1830. return readReal();
  1831. }
  1832. double InStream::readReal(double minv, double maxv, const std::string& variableName)
  1833. {
  1834. double result = readReal();
  1835. if (result < minv || result > maxv)
  1836. {
  1837. if (variableName.empty())
  1838. quit(_wa, ("Double " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1839. else
  1840. quit(_wa, ("Double parameter [name=" + variableName + "] equals to " + vtos(result) + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1841. }
  1842. return result;
  1843. }
  1844. double InStream::readDouble(double minv, double maxv, const std::string& variableName)
  1845. {
  1846. return readReal(minv, maxv, variableName);
  1847. }
  1848. double InStream::readStrictReal(double minv, double maxv,
  1849. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  1850. const std::string& variableName)
  1851. {
  1852. if (!strict && seekEof())
  1853. quit(_pe, "Unexpected end of file - strict double expected");
  1854. double result = stringToStrictDouble(*this, readWord().c_str(),
  1855. minAfterPointDigitCount, maxAfterPointDigitCount);
  1856. if (result < minv || result > maxv)
  1857. {
  1858. if (variableName.empty())
  1859. quit(_wa, ("Strict double " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1860. else
  1861. quit(_wa, ("Strict double parameter [name=" + variableName + "] equals to " + vtos(result) + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1862. }
  1863. return result;
  1864. }
  1865. double InStream::readStrictDouble(double minv, double maxv,
  1866. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  1867. const std::string& variableName)
  1868. {
  1869. return readStrictReal(minv, maxv,
  1870. minAfterPointDigitCount, maxAfterPointDigitCount,
  1871. variableName);
  1872. }
  1873. bool InStream::eof()
  1874. {
  1875. if (!strict && NULL == file)
  1876. return true;
  1877. return reader->eof();
  1878. }
  1879. bool InStream::seekEof()
  1880. {
  1881. if (NULL == file)
  1882. return true;
  1883. skipBlanks();
  1884. return eof();
  1885. }
  1886. bool InStream::eoln()
  1887. {
  1888. if (!strict && NULL == file)
  1889. return true;
  1890. int c = reader->nextChar();
  1891. if (!strict)
  1892. {
  1893. if (c == EOF)
  1894. return true;
  1895. if (c == CR)
  1896. {
  1897. c = reader->nextChar();
  1898. if (c != LF)
  1899. {
  1900. reader->unreadChar(CR);
  1901. reader->unreadChar(c);
  1902. return false;
  1903. }
  1904. else
  1905. return true;
  1906. }
  1907. if (c == LF)
  1908. return true;
  1909. reader->unreadChar(c);
  1910. return false;
  1911. }
  1912. else
  1913. {
  1914. bool returnCr = false;
  1915. #ifdef ON_WINDOWS
  1916. if (c != CR)
  1917. {
  1918. reader->unreadChar(c);
  1919. return false;
  1920. }
  1921. else
  1922. {
  1923. if (!returnCr)
  1924. returnCr = true;
  1925. c = reader->nextChar();
  1926. }
  1927. #endif
  1928. if (c != LF)
  1929. {
  1930. if (returnCr)
  1931. reader->unreadChar(CR);
  1932. reader->unreadChar(LF);
  1933. return false;
  1934. }
  1935. return true;
  1936. }
  1937. }
  1938. void InStream::readEoln()
  1939. {
  1940. if (!eoln())
  1941. quit(_pe, "Expected EOLN");
  1942. }
  1943. void InStream::readEof()
  1944. {
  1945. if (!eof())
  1946. quit(_pe, "Expected EOF");
  1947. if (TestlibFinalizeGuard::alive && this == &inf)
  1948. testlibFinalizeGuard.readEofCount++;
  1949. }
  1950. bool InStream::seekEoln()
  1951. {
  1952. if (NULL == file)
  1953. return true;
  1954. int cur;
  1955. do
  1956. {
  1957. cur = reader->nextChar();
  1958. }
  1959. while (cur == SPACE || cur == TAB);
  1960. reader->unreadChar(cur);
  1961. return eoln();
  1962. }
  1963. void InStream::nextLine()
  1964. {
  1965. readLine();
  1966. }
  1967. void InStream::readStringTo(std::string& result)
  1968. {
  1969. if (NULL == file)
  1970. quit(_pe, "Expected line");
  1971. result.clear();
  1972. int cur;
  1973. for (;;)
  1974. {
  1975. cur = reader->curChar();
  1976. if (isEoln(cur))
  1977. break;
  1978. if (cur == EOF)
  1979. break;
  1980. result += char(reader->nextChar());
  1981. }
  1982. if (strict)
  1983. readEoln();
  1984. else
  1985. eoln();
  1986. }
  1987. std::string InStream::readString()
  1988. {
  1989. readStringTo(_tmpReadToken);
  1990. return _tmpReadToken;
  1991. }
  1992. void InStream::readStringTo(std::string& result, const pattern& p, const std::string& variableName)
  1993. {
  1994. readStringTo(result);
  1995. if (!p.matches(result))
  1996. {
  1997. if (variableName.empty())
  1998. quit(_wa, ("Line \"" + __testlib_part(result) + "\" doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  1999. else
  2000. quit(_wa, ("Line [name=" + variableName + "] equals to \"" + __testlib_part(result) + "\", doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  2001. }
  2002. }
  2003. void InStream::readStringTo(std::string& result, const std::string& ptrn, const std::string& variableName)
  2004. {
  2005. readStringTo(result, pattern(ptrn), variableName);
  2006. }
  2007. std::string InStream::readString(const pattern& p, const std::string& variableName)
  2008. {
  2009. readStringTo(_tmpReadToken, p, variableName);
  2010. return _tmpReadToken;
  2011. }
  2012. std::string InStream::readString(const std::string& ptrn, const std::string& variableName)
  2013. {
  2014. readStringTo(_tmpReadToken, ptrn, variableName);
  2015. return _tmpReadToken;
  2016. }
  2017. void InStream::readLineTo(std::string& result)
  2018. {
  2019. readStringTo(result);
  2020. }
  2021. std::string InStream::readLine()
  2022. {
  2023. return readString();
  2024. }
  2025. void InStream::readLineTo(std::string& result, const pattern& p, const std::string& variableName)
  2026. {
  2027. readStringTo(result, p, variableName);
  2028. }
  2029. void InStream::readLineTo(std::string& result, const std::string& ptrn, const std::string& variableName)
  2030. {
  2031. readStringTo(result, ptrn, variableName);
  2032. }
  2033. std::string InStream::readLine(const pattern& p, const std::string& variableName)
  2034. {
  2035. return readString(p, variableName);
  2036. }
  2037. std::string InStream::readLine(const std::string& ptrn, const std::string& variableName)
  2038. {
  2039. return readString(ptrn, variableName);
  2040. }
  2041. void InStream::close()
  2042. {
  2043. if (opened)
  2044. fclose(file);
  2045. if (NULL != reader)
  2046. {
  2047. delete reader;
  2048. reader = NULL;
  2049. }
  2050. opened = false;
  2051. }
  2052. #ifdef __GNUC__
  2053. __attribute__ ((noreturn))
  2054. #endif
  2055. void quit(TResult result, const std::string& msg)
  2056. {
  2057. ouf.quit(result, msg.c_str());
  2058. }
  2059. #ifdef __GNUC__
  2060. __attribute__ ((noreturn))
  2061. #endif
  2062. void quit(TResult result, const char* msg)
  2063. {
  2064. ouf.quit(result, msg);
  2065. }
  2066. #ifdef __GNUC__
  2067. __attribute__ ((noreturn))
  2068. #endif
  2069. void __testlib_quitp(double points, const char* message)
  2070. {
  2071. char buffer[512];
  2072. if (NULL == message || 0 == strlen(message))
  2073. std::sprintf(buffer, "%.10f", points);
  2074. else
  2075. std::sprintf(buffer, "%.10f %s", points, message);
  2076. quit(_points, buffer);
  2077. }
  2078. #ifdef __GNUC__
  2079. __attribute__ ((noreturn))
  2080. #endif
  2081. void quitp(float points, const std::string& message = "")
  2082. {
  2083. __testlib_quitp(double(points), message.c_str());
  2084. }
  2085. #ifdef __GNUC__
  2086. __attribute__ ((noreturn))
  2087. #endif
  2088. void quitp(double points, const std::string& message = "")
  2089. {
  2090. __testlib_quitp(points, message.c_str());
  2091. }
  2092. #ifdef __GNUC__
  2093. __attribute__ ((noreturn))
  2094. #endif
  2095. void quitp(long double points, const std::string& message = "")
  2096. {
  2097. __testlib_quitp(double(points), message.c_str());
  2098. }
  2099. template<typename F>
  2100. #ifdef __GNUC__
  2101. __attribute__ ((format (printf, 2, 3)))
  2102. __attribute__ ((noreturn))
  2103. #endif
  2104. void quitp(F points, const char* format, ...)
  2105. {
  2106. FMT_TO_RESULT(format, format, message);
  2107. quitp(points, message);
  2108. }
  2109. #ifdef __GNUC__
  2110. __attribute__ ((format (printf, 2, 3)))
  2111. __attribute__ ((noreturn))
  2112. #endif
  2113. void quitf(TResult result, const char* format, ...)
  2114. {
  2115. FMT_TO_RESULT(format, format, message);
  2116. quit(result, message);
  2117. }
  2118. #ifdef __GNUC__
  2119. __attribute__ ((format (printf, 3, 4)))
  2120. #endif
  2121. void quitif(bool condition, TResult result, const char* format, ...)
  2122. {
  2123. if (condition)
  2124. {
  2125. FMT_TO_RESULT(format, format, message);
  2126. quit(result, message);
  2127. }
  2128. }
  2129. #ifdef __GNUC__
  2130. __attribute__ ((noreturn))
  2131. #endif
  2132. void __testlib_help()
  2133. {
  2134. InStream::textColor(InStream::LightCyan);
  2135. std::fprintf(stderr, "TESTLIB %s, http://code.google.com/p/testlib/ ", VERSION);
  2136. std::fprintf(stderr, "by Mike Mirzayanov, copyright(c) 2005-2013\n");
  2137. std::fprintf(stderr, "Checker name: \"%s\"\n", checkerName.c_str());
  2138. InStream::textColor(InStream::LightGray);
  2139. std::fprintf(stderr, "\n");
  2140. std::fprintf(stderr, "Latest features: \n");
  2141. for (size_t i = 0; i < sizeof(latestFeatures) / sizeof(char*); i++)
  2142. {
  2143. std::fprintf(stderr, "*) %s\n", latestFeatures[i]);
  2144. }
  2145. std::fprintf(stderr, "\n");
  2146. std::fprintf(stderr, "Program must be run with the following arguments: \n");
  2147. std::fprintf(stderr, " <input-file> <output-file> <answer-file> [<report-file> [<-appes>]]\n\n");
  2148. std::exit(0);
  2149. }
  2150. void registerGen(int argc, char* argv[])
  2151. {
  2152. testlibMode = _generator;
  2153. __testlib_set_binary(stdin);
  2154. rnd.setSeed(argc, argv);
  2155. }
  2156. void registerInteraction(int argc, char* argv[])
  2157. {
  2158. testlibMode = _interactor;
  2159. __testlib_set_binary(stdin);
  2160. if (argc > 1 && !strcmp("--help", argv[1]))
  2161. __testlib_help();
  2162. // testlib assumes: sizeof(int) = 4.
  2163. __TESTLIB_STATIC_ASSERT(sizeof(int) == 4);
  2164. // testlib assumes: INT_MAX == 2147483647.
  2165. __TESTLIB_STATIC_ASSERT(INT_MAX == 2147483647);
  2166. // testlib assumes: sizeof(long long) = 8.
  2167. __TESTLIB_STATIC_ASSERT(sizeof(long long) == 8);
  2168. if (argc < 3 || argc > 6)
  2169. {
  2170. quit(_fail, std::string("Program must be run with the following arguments: ") +
  2171. std::string("<input-file> <output-file> [<answer-file> [<report-file> [<-appes>]]]") +
  2172. "\nUse \"--help\" to get help information");
  2173. }
  2174. if (argc <= 4)
  2175. {
  2176. resultName = "";
  2177. appesMode = false;
  2178. }
  2179. if (argc == 5)
  2180. {
  2181. resultName = argv[4];
  2182. appesMode = false;
  2183. }
  2184. if (argc == 6)
  2185. {
  2186. if (strcmp("-APPES", argv[5]) && strcmp("-appes", argv[5]))
  2187. {
  2188. quit(_fail, std::string("Program must be run with the following arguments: ") +
  2189. "<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]");
  2190. }
  2191. else
  2192. {
  2193. resultName = argv[4];
  2194. appesMode = true;
  2195. }
  2196. }
  2197. if (setvbuf(stdin, NULL, _IONBF, 0) != 0)
  2198. quit(_fail, std::string("Can not disable buffer for stdin"));
  2199. if (setvbuf(stdout, NULL, _IONBF, 0) != 0)
  2200. quit(_fail, std::string("Can not disable buffer for stdout"));
  2201. if (setvbuf(stderr, NULL, _IONBF, 0) != 0)
  2202. quit(_fail, std::string("Can not disable buffer for stderr"));
  2203. inf.init(argv[1], _input);
  2204. tout.open(argv[2], std::ios_base::out);
  2205. if (tout.fail() || !tout.is_open())
  2206. quit(_fail, std::string("Can not write to the test-output-file '") + argv[2] + std::string("'"));
  2207. ouf.init(stdin, _output);
  2208. if (argc >= 4)
  2209. ans.init(argv[3], _answer);
  2210. }
  2211. void registerValidation()
  2212. {
  2213. testlibMode = _validator;
  2214. __testlib_set_binary(stdin);
  2215. // testlib assumes: sizeof(int) = 4.
  2216. __TESTLIB_STATIC_ASSERT(sizeof(int) == 4);
  2217. // testlib assumes: INT_MAX == 2147483647.
  2218. __TESTLIB_STATIC_ASSERT(INT_MAX == 2147483647);
  2219. // testlib assumes: sizeof(long long) = 8.
  2220. __TESTLIB_STATIC_ASSERT(sizeof(long long) == 8);
  2221. inf.init(stdin, _input);
  2222. inf.strict = true;
  2223. }
  2224. void registerTestlibCmd(int argc, char* argv[])
  2225. {
  2226. testlibMode = _checker;
  2227. __testlib_set_binary(stdin);
  2228. if (argc > 1 && !strcmp("--help", argv[1]))
  2229. __testlib_help();
  2230. // testlib assumes: sizeof(int) = 4.
  2231. __TESTLIB_STATIC_ASSERT(sizeof(int) == 4);
  2232. // testlib assumes: INT_MAX == 2147483647.
  2233. __TESTLIB_STATIC_ASSERT(INT_MAX == 2147483647);
  2234. // testlib assumes: sizeof(long long) = 8.
  2235. __TESTLIB_STATIC_ASSERT(sizeof(long long) == 8);
  2236. if (argc < 4 || argc > 6)
  2237. {
  2238. quit(_fail, std::string("Program must be run with the following arguments: ") +
  2239. std::string("<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]") +
  2240. "\nUse \"--help\" to get help information");
  2241. }
  2242. if (argc == 4)
  2243. {
  2244. resultName = "";
  2245. appesMode = false;
  2246. }
  2247. if (argc == 5)
  2248. {
  2249. resultName = argv[4];
  2250. appesMode = false;
  2251. }
  2252. if (argc == 6)
  2253. {
  2254. if (strcmp("-APPES", argv[5]) && strcmp("-appes", argv[5]))
  2255. {
  2256. quit(_fail, std::string("Program must be run with the following arguments: ") +
  2257. "<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]");
  2258. }
  2259. else
  2260. {
  2261. resultName = argv[4];
  2262. appesMode = true;
  2263. }
  2264. }
  2265. inf.init(argv[1], _input);
  2266. ouf.init(argv[2], _output);
  2267. ans.init(argv[3], _answer);
  2268. }
  2269. void registerTestlib(int argc, ...)
  2270. {
  2271. if (argc < 3 || argc > 5)
  2272. quit(_fail, std::string("Program must be run with the following arguments: ") +
  2273. "<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]");
  2274. char** argv = new char*[argc + 1];
  2275. va_list ap;
  2276. va_start(ap, argc);
  2277. argv[0] = NULL;
  2278. for (int i = 0; i < argc; i++)
  2279. {
  2280. argv[i + 1] = va_arg(ap, char*);
  2281. }
  2282. va_end(ap);
  2283. registerTestlibCmd(argc + 1, argv);
  2284. delete[] argv;
  2285. }
  2286. inline bool isNaN(double r)
  2287. {
  2288. return ((r != r) == true) && ((r == r) == false) && ((1.0 > r) == false) && ((1.0 < r) == false);
  2289. }
  2290. inline bool isInfinite(double r)
  2291. {
  2292. return (r > 1E100 || r < -1E100);
  2293. }
  2294. #ifdef __GNUC__
  2295. __attribute__((const))
  2296. #endif
  2297. bool doubleCompare(double expected, double result, double MAX_DOUBLE_ERROR)
  2298. {
  2299. if (isNaN(expected))
  2300. {
  2301. return isNaN(result);
  2302. }
  2303. else
  2304. if (isInfinite(expected))
  2305. {
  2306. if (expected > 0)
  2307. {
  2308. return result > 0 && isInfinite(result);
  2309. }
  2310. else
  2311. {
  2312. return result < 0 && isInfinite(result);
  2313. }
  2314. }
  2315. else
  2316. if (isNaN(result) || isInfinite(result))
  2317. {
  2318. return false;
  2319. }
  2320. else
  2321. if (__testlib_abs(result - expected) <= MAX_DOUBLE_ERROR + 1E-15)
  2322. {
  2323. return true;
  2324. }
  2325. else
  2326. {
  2327. double minv = __testlib_min(expected * (1.0 - MAX_DOUBLE_ERROR),
  2328. expected * (1.0 + MAX_DOUBLE_ERROR));
  2329. double maxv = __testlib_max(expected * (1.0 - MAX_DOUBLE_ERROR),
  2330. expected * (1.0 + MAX_DOUBLE_ERROR));
  2331. return result + 1E-15 >= minv && result <= maxv + 1E-15;
  2332. }
  2333. }
  2334. #ifdef __GNUC__
  2335. __attribute__((const))
  2336. #endif
  2337. double doubleDelta(double expected, double result)
  2338. {
  2339. double absolute = __testlib_abs(result - expected);
  2340. if (__testlib_abs(expected) > 1E-9)
  2341. {
  2342. double relative = __testlib_abs(absolute / expected);
  2343. return __testlib_min(absolute, relative);
  2344. }
  2345. else
  2346. return absolute;
  2347. }
  2348. static void __testlib_ensure(bool cond, const std::string msg)
  2349. {
  2350. if (!cond)
  2351. quit(_fail, msg.c_str());
  2352. }
  2353. #define ensure(cond) __testlib_ensure(cond, std::string("Condition failed: \"") + #cond + "\"")
  2354. #ifdef __GNUC__
  2355. __attribute__ ((format (printf, 2, 3)))
  2356. #endif
  2357. void ensuref(bool cond, const char* format, ...)
  2358. {
  2359. if (!cond)
  2360. {
  2361. FMT_TO_RESULT(format, format, message);
  2362. __testlib_ensure(cond, message);
  2363. }
  2364. }
  2365. #ifdef __GNUC__
  2366. __attribute__((noreturn))
  2367. #endif
  2368. static void __testlib_fail(const std::string& message)
  2369. {
  2370. quitf(_fail, "%s", message.c_str());
  2371. }
  2372. #ifdef __GNUC__
  2373. __attribute__ ((format (printf, 1, 2)))
  2374. #endif
  2375. void setName(const char* format, ...)
  2376. {
  2377. FMT_TO_RESULT(format, format, name);
  2378. checkerName = name;
  2379. }
  2380. /*
  2381. * Do not use random_shuffle, because it will produce different result
  2382. * for different C++ compilers.
  2383. *
  2384. * This implementation uses testlib random_t to produce random numbers, so
  2385. * it is stable.
  2386. */
  2387. template<typename _RandomAccessIter>
  2388. void shuffle(_RandomAccessIter __first, _RandomAccessIter __last)
  2389. {
  2390. if (__first == __last) return;
  2391. for (_RandomAccessIter __i = __first + 1; __i != __last; ++__i)
  2392. std::iter_swap(__i, __first + rnd.next(int(__i - __first) + 1));
  2393. }
  2394. template<typename _RandomAccessIter>
  2395. #ifdef __GNUC__
  2396. __attribute__ ((error("Don't use random_shuffle(), use shuffle() instead")))
  2397. #endif
  2398. void random_shuffle(_RandomAccessIter , _RandomAccessIter )
  2399. {
  2400. quitf(_fail, "Don't use random_shuffle(), use shuffle() instead");
  2401. }
  2402. #ifdef __GLIBC__
  2403. # define RAND_THROW_STATEMENT throw()
  2404. #else
  2405. # define RAND_THROW_STATEMENT
  2406. #endif
  2407. #ifdef __GNUC__
  2408. __attribute__ ((error("Don't use rand(), use rnd.next() instead")))
  2409. #endif
  2410. int rand() RAND_THROW_STATEMENT
  2411. {
  2412. quitf(_fail, "Don't use rand(), use rnd.next() instead");
  2413. }
  2414. #ifdef __GNUC__
  2415. __attribute__ ((error("Don't use srand(), you should use "
  2416. "'registerGen(argc, argv);' to initialize generator seed "
  2417. "by hash code of the command line params")))
  2418. #endif
  2419. void srand(unsigned int seed) RAND_THROW_STATEMENT
  2420. {
  2421. quitf(_fail, "Don't use srand(), you should use "
  2422. "'registerGen(argc, argv);' to initialize generator seed "
  2423. "by hash code of the command line params [seed=%d ignored]", seed);
  2424. }
  2425. void startTest(int test)
  2426. {
  2427. const std::string testFileName = vtos(test);
  2428. if (NULL == freopen(testFileName.c_str(), "wt", stdout))
  2429. __testlib_fail("Unable to write file '" + testFileName + "'");
  2430. }
  2431. #ifdef __GNUC__
  2432. __attribute__ ((format (printf, 1, 2)))
  2433. #endif
  2434. std::string format(const char* fmt, ...)
  2435. {
  2436. FMT_TO_RESULT(fmt, fmt, result);
  2437. return result;
  2438. }
  2439. std::string format(const std::string& fmt, ...)
  2440. {
  2441. FMT_TO_RESULT(fmt, fmt.c_str(), result);
  2442. return result;
  2443. }
  2444. std::string upperCase(std::string s)
  2445. {
  2446. for (size_t i = 0; i < s.length(); i++)
  2447. if ('a' <= s[i] && s[i] <= 'z')
  2448. s[i] = s[i] - 'a' + 'A';
  2449. return s;
  2450. }
  2451. std::string lowerCase(std::string s)
  2452. {
  2453. for (size_t i = 0; i < s.length(); i++)
  2454. if ('A' <= s[i] && s[i] <= 'Z')
  2455. s[i] = s[i] - 'A' + 'a';
  2456. return s;
  2457. }
  2458. std::string compress(const std::string& s)
  2459. {
  2460. return __testlib_part(s);
  2461. }
  2462. std::string englishEnding(int x)
  2463. {
  2464. x %= 100;
  2465. if (x / 10 == 1)
  2466. return "th";
  2467. if (x % 10 == 1)
  2468. return "st";
  2469. if (x % 10 == 2)
  2470. return "nd";
  2471. if (x % 10 == 3)
  2472. return "rd";
  2473. return "th";
  2474. }
  2475. std::string trim(const std::string& s)
  2476. {
  2477. if (s.empty())
  2478. return s;
  2479. int left = 0;
  2480. while (left < int(s.length()) && isBlanks(s[left]))
  2481. left++;
  2482. if (left >= int(s.length()))
  2483. return "";
  2484. int right = s.length() - 1;
  2485. while (right >= 0 && isBlanks(s[right]))
  2486. right--;
  2487. if (right < 0)
  2488. return "";
  2489. return s.substr(left, right - left + 1);
  2490. }
  2491. #endif