testlib.h 132 KB

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