testlib.h 92 KB

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