testlib.h 152 KB

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