testlib.h 126 KB

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