testlib.h 127 KB

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