1
0

testlib.h 82 KB

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