testlib.h 99 KB

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