testlib.h 191 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970
  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-2022
  24. */
  25. #define VERSION "0.9.40-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. "Supported '--testMarkupFileName fn' and '--testCase tc/--testCaseFileName fn' for validators",
  61. "Added opt defaults via opt<T>(key/index, default_val); check unused opts when using has_opt or default opt (turn off this check with suppressEnsureNoUnusedOpt()).",
  62. "For checker added --group and --testset command line params (like for validator), use checker.group() or checker.testset() to get values",
  63. "Added quitpi(points_info, message) function to return with _points exit code 7 and given points_info",
  64. "rnd.partition(size, sum[, min_part=1]) returns random (unsorted) partition which is a representation of the given `sum` as a sum of `size` positive integers (or >=min_part if specified)",
  65. "rnd.distinct(size, n) and rnd.distinct(size, from, to)",
  66. "opt<bool>(\"some_missing_key\") returns false now",
  67. "has_opt(key)",
  68. "Abort validator on validator.testset()/validator.group() if registered without using command line",
  69. "Print integer range violations in a human readable way like `violates the range [1, 10^9]`",
  70. "Opts supported: use them like n = opt<int>(\"n\"), in a command line you can use an exponential notation",
  71. "Reformatted",
  72. "Use setTestCase(i) or unsetTestCase() to support test cases (you can use it in any type of program: generator, interactor, validator or checker)",
  73. "Fixed issue #87: readStrictDouble accepts \"-0.00\"",
  74. "Fixed issue #83: added InStream::quitif(condition, ...)",
  75. "Fixed issue #79: fixed missed guard against repeated header include",
  76. "Fixed issue #80: fixed UB in case of huge quitf message",
  77. "Fixed issue #84: added readXs(size, indexBase = 1)",
  78. "Fixed stringstream repeated usage issue",
  79. "Fixed compilation in g++ (for std=c++03)",
  80. "Batch of println functions (support collections, iterator ranges)",
  81. "Introduced rnd.perm(size, first = 0) to generate a `first`-indexed permutation",
  82. "Allow any whitespace in readInts-like functions for non-validators",
  83. "Ignore 4+ command line arguments ifdef EJUDGE",
  84. "Speed up of vtos",
  85. "Show line number in validators in case of incorrect format",
  86. "Truncate huge checker/validator/interactor message",
  87. "Fixed issue with readTokenTo of very long tokens, now aborts with _pe/_fail depending of a stream type",
  88. "Introduced InStream::ensure/ensuref checking a condition, returns wa/fail depending of a stream type",
  89. "Fixed compilation in VS 2015+",
  90. "Introduced space-separated read functions: readWords/readTokens, multilines read functions: readStrings/readLines",
  91. "Introduced space-separated read functions: readInts/readIntegers/readLongs/readUnsignedLongs/readDoubles/readReals/readStrictDoubles/readStrictReals",
  92. "Introduced split/tokenize functions to separate string by given char",
  93. "Introduced InStream::readUnsignedLong and InStream::readLong with unsigned long long parameters",
  94. "Supported --testOverviewLogFileName for validator: bounds hits + features",
  95. "Fixed UB (sequence points) in random_t",
  96. "POINTS_EXIT_CODE returned back to 7 (instead of 0)",
  97. "Removed disable buffers for interactive problems, because it works unexpectedly in wine",
  98. "InStream over string: constructor of InStream from base InStream to inherit policies and std::string",
  99. "Added expectedButFound quit function, examples: expectedButFound(_wa, 10, 20), expectedButFound(_fail, ja, pa, \"[n=%d,m=%d]\", n, m)",
  100. "Fixed incorrect interval parsing in patterns",
  101. "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)",
  102. "Introduced disableFinalizeGuard() to switch off finalization checkings",
  103. "Use join() functions to format a range of items as a single string (separated by spaces or other separators)",
  104. "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",
  105. "Use -DUSE_RND_AS_BEFORE_087 to compile in compatibility mode with random behavior of versions before 0.8.7",
  106. "Fixed bug with nan in stringToDouble",
  107. "Fixed issue around overloads for size_t on x64",
  108. "Added attribute 'points' to the XML output in case of result=_points",
  109. "Exit codes can be customized via macros, e.g. -DPE_EXIT_CODE=14",
  110. "Introduced InStream function readWordTo/readTokenTo/readStringTo/readLineTo for faster reading",
  111. "Introduced global functions: format(), englishEnding(), upperCase(), lowerCase(), compress()",
  112. "Manual buffer in InStreams, some IO speed improvements",
  113. "Introduced quitif(bool, const char* pattern, ...) which delegates to quitf() in case of first argument is true",
  114. "Introduced guard against missed quitf() in checker or readEof() in validators",
  115. "Supported readStrictReal/readStrictDouble - to use in validators to check strictly float numbers",
  116. "Supported registerInteraction(argc, argv)",
  117. "Print checker message to the stderr instead of stdout",
  118. "Supported TResult _points to output calculated score, use quitp(...) functions",
  119. "Fixed to be compilable on Mac",
  120. "PC_BASE_EXIT_CODE=50 in case of defined TESTSYS",
  121. "Fixed issues 19-21, added __attribute__ format printf",
  122. "Some bug fixes",
  123. "ouf.readInt(1, 100) and similar calls return WA",
  124. "Modified random_t to avoid integer overflow",
  125. "Truncated checker output [patch by Stepan Gatilov]",
  126. "Renamed class random -> class random_t",
  127. "Supported name parameter for read-and-validation methods, like readInt(1, 2, \"n\")",
  128. "Fixed bug in readDouble()",
  129. "Improved ensuref(), fixed nextLine to work in case of EOF, added startTest()",
  130. "Supported \"partially correct\", example: quitf(_pc(13), \"result=%d\", result)",
  131. "Added shuffle(begin, end), use it instead of random_shuffle(begin, end)",
  132. "Added readLine(const string& ptrn), fixed the logic of readLine() in the validation mode",
  133. "Package extended with samples of generators and validators",
  134. "Written the documentation for classes and public methods in testlib.h",
  135. "Implemented random routine to support generators, use registerGen() to switch it on",
  136. "Implemented strict mode to validate tests, use registerValidation() to switch it on",
  137. "Now ncmp.cpp and wcmp.cpp are return WA if answer is suffix or prefix of the output",
  138. "Added InStream::readLong() and removed InStream::readLongint()",
  139. "Now no footer added to each report by default (use directive FOOTER to switch on)",
  140. "Now every checker has a name, use setName(const char* format, ...) to set it",
  141. "Now it is compatible with TTS (by Kittens Computing)",
  142. "Added \'ensure(condition, message = \"\")\' feature, it works like assert()",
  143. "Fixed compatibility with MS C++ 7.1",
  144. "Added footer with exit code information",
  145. "Added compatibility with EJUDGE (compile with EJUDGE directive)",
  146. "Added compatibility with Contester (compile with CONTESTER directive)"
  147. };
  148. #ifdef _MSC_VER
  149. #define _CRT_SECURE_NO_DEPRECATE
  150. #define _CRT_SECURE_NO_WARNINGS
  151. #define _CRT_NO_VA_START_VALIDATION
  152. #endif
  153. /* Overrides random() for Borland C++. */
  154. #define random __random_deprecated
  155. #include <stdlib.h>
  156. #include <cstdlib>
  157. #include <climits>
  158. #include <algorithm>
  159. #undef random
  160. #include <cstdio>
  161. #include <cctype>
  162. #include <string>
  163. #include <vector>
  164. #include <map>
  165. #include <set>
  166. #include <cmath>
  167. #include <iostream>
  168. #include <sstream>
  169. #include <fstream>
  170. #include <cstring>
  171. #include <limits>
  172. #include <stdarg.h>
  173. #include <fcntl.h>
  174. #include <functional>
  175. #include <cstdint>
  176. #ifdef TESTLIB_THROW_EXIT_EXCEPTION_INSTEAD_OF_EXIT
  177. # include <exception>
  178. #endif
  179. #if (_WIN32 || __WIN32__ || __WIN32 || _WIN64 || __WIN64__ || __WIN64 || WINNT || __WINNT || __WINNT__ || __CYGWIN__)
  180. # if !defined(_MSC_VER) || _MSC_VER > 1400
  181. # define NOMINMAX 1
  182. # include <windows.h>
  183. # else
  184. # define WORD unsigned short
  185. # include <unistd.h>
  186. # endif
  187. # include <io.h>
  188. # define ON_WINDOWS
  189. # if defined(_MSC_VER) && _MSC_VER > 1400
  190. # pragma warning( disable : 4127 )
  191. # pragma warning( disable : 4146 )
  192. # pragma warning( disable : 4458 )
  193. # endif
  194. #else
  195. # define WORD unsigned short
  196. # include <unistd.h>
  197. #endif
  198. #if defined(FOR_WINDOWS) && defined(FOR_LINUX)
  199. #error Only one target system is allowed
  200. #endif
  201. #ifndef LLONG_MIN
  202. #define LLONG_MIN (-9223372036854775807LL - 1)
  203. #endif
  204. #ifndef ULLONG_MAX
  205. #define ULLONG_MAX (18446744073709551615)
  206. #endif
  207. #define LF ((char)10)
  208. #define CR ((char)13)
  209. #define TAB ((char)9)
  210. #define SPACE ((char)' ')
  211. #define EOFC (255)
  212. #ifndef OK_EXIT_CODE
  213. # ifdef CONTESTER
  214. # define OK_EXIT_CODE 0xAC
  215. # else
  216. # define OK_EXIT_CODE 0
  217. # endif
  218. #endif
  219. #ifndef WA_EXIT_CODE
  220. # ifdef EJUDGE
  221. # define WA_EXIT_CODE 5
  222. # elif defined(CONTESTER)
  223. # define WA_EXIT_CODE 0xAB
  224. # else
  225. # define WA_EXIT_CODE 1
  226. # endif
  227. #endif
  228. #ifndef PE_EXIT_CODE
  229. # ifdef EJUDGE
  230. # define PE_EXIT_CODE 4
  231. # elif defined(CONTESTER)
  232. # define PE_EXIT_CODE 0xAA
  233. # else
  234. # define PE_EXIT_CODE 2
  235. # endif
  236. #endif
  237. #ifndef FAIL_EXIT_CODE
  238. # ifdef EJUDGE
  239. # define FAIL_EXIT_CODE 6
  240. # elif defined(CONTESTER)
  241. # define FAIL_EXIT_CODE 0xA3
  242. # else
  243. # define FAIL_EXIT_CODE 3
  244. # endif
  245. #endif
  246. #ifndef DIRT_EXIT_CODE
  247. # ifdef EJUDGE
  248. # define DIRT_EXIT_CODE 6
  249. # else
  250. # define DIRT_EXIT_CODE 4
  251. # endif
  252. #endif
  253. #ifndef POINTS_EXIT_CODE
  254. # define POINTS_EXIT_CODE 7
  255. #endif
  256. #ifndef UNEXPECTED_EOF_EXIT_CODE
  257. # define UNEXPECTED_EOF_EXIT_CODE 8
  258. #endif
  259. #ifndef PC_BASE_EXIT_CODE
  260. # ifdef TESTSYS
  261. # define PC_BASE_EXIT_CODE 50
  262. # else
  263. # define PC_BASE_EXIT_CODE 0
  264. # endif
  265. #endif
  266. #ifdef __GNUC__
  267. # define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[(condition) ? 1 : -1] __attribute__((unused))
  268. #else
  269. # define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[(condition) ? 1 : -1]
  270. #endif
  271. #ifdef ON_WINDOWS
  272. #define I64 "%I64d"
  273. #define U64 "%I64u"
  274. #else
  275. #define I64 "%lld"
  276. #define U64 "%llu"
  277. #endif
  278. #ifdef _MSC_VER
  279. # define NORETURN __declspec(noreturn)
  280. #elif defined __GNUC__
  281. # define NORETURN __attribute__ ((noreturn))
  282. #else
  283. # define NORETURN
  284. #endif
  285. static char __testlib_format_buffer[16777216];
  286. static int __testlib_format_buffer_usage_count = 0;
  287. #define FMT_TO_RESULT(fmt, cstr, result) std::string result; \
  288. if (__testlib_format_buffer_usage_count != 0) \
  289. __testlib_fail("FMT_TO_RESULT::__testlib_format_buffer_usage_count != 0"); \
  290. __testlib_format_buffer_usage_count++; \
  291. va_list ap; \
  292. va_start(ap, fmt); \
  293. vsnprintf(__testlib_format_buffer, sizeof(__testlib_format_buffer), cstr, ap); \
  294. va_end(ap); \
  295. __testlib_format_buffer[sizeof(__testlib_format_buffer) - 1] = 0; \
  296. result = std::string(__testlib_format_buffer); \
  297. __testlib_format_buffer_usage_count--; \
  298. const long long __TESTLIB_LONGLONG_MAX = 9223372036854775807LL;
  299. const int __TESTLIB_MAX_TEST_CASE = 1073741823;
  300. int __testlib_exitCode;
  301. bool __testlib_hasTestCase;
  302. int __testlib_testCase = -1;
  303. void setTestCase(int testCase);
  304. void unsetTestCase() {
  305. __testlib_hasTestCase = false;
  306. __testlib_testCase = -1;
  307. }
  308. NORETURN static void __testlib_fail(const std::string &message);
  309. template<typename T>
  310. static inline T __testlib_abs(const T &x) {
  311. return x > 0 ? x : -x;
  312. }
  313. template<typename T>
  314. static inline T __testlib_min(const T &a, const T &b) {
  315. return a < b ? a : b;
  316. }
  317. template<typename T>
  318. static inline T __testlib_max(const T &a, const T &b) {
  319. return a > b ? a : b;
  320. }
  321. template<typename T>
  322. static inline T __testlib_crop(T value, T a, T b) {
  323. return __testlib_min(__testlib_max(value, a), --b);
  324. }
  325. static inline double __testlib_crop(double value, double a, double b) {
  326. value = __testlib_min(__testlib_max(value, a), b);
  327. if (value >= b)
  328. value = std::nexttoward(b, a);
  329. return value;
  330. }
  331. static bool __testlib_prelimIsNaN(double r) {
  332. volatile double ra = r;
  333. #ifndef __BORLANDC__
  334. return ((ra != ra) == true) && ((ra == ra) == false) && ((1.0 > ra) == false) && ((1.0 < ra) == false);
  335. #else
  336. return std::_isnan(ra);
  337. #endif
  338. }
  339. static std::string removeDoubleTrailingZeroes(std::string value) {
  340. while (!value.empty() && value[value.length() - 1] == '0' && value.find('.') != std::string::npos)
  341. value = value.substr(0, value.length() - 1);
  342. if (!value.empty() && value[value.length() - 1] == '.')
  343. return value + '0';
  344. else
  345. return value;
  346. }
  347. inline std::string upperCase(std::string s) {
  348. for (size_t i = 0; i < s.length(); i++)
  349. if ('a' <= s[i] && s[i] <= 'z')
  350. s[i] = char(s[i] - 'a' + 'A');
  351. return s;
  352. }
  353. inline std::string lowerCase(std::string s) {
  354. for (size_t i = 0; i < s.length(); i++)
  355. if ('A' <= s[i] && s[i] <= 'Z')
  356. s[i] = char(s[i] - 'A' + 'a');
  357. return s;
  358. }
  359. #ifdef __GNUC__
  360. __attribute__ ((format (printf, 1, 2)))
  361. #endif
  362. std::string format(const char *fmt, ...) {
  363. FMT_TO_RESULT(fmt, fmt, result);
  364. return result;
  365. }
  366. std::string format(const std::string fmt, ...) {
  367. FMT_TO_RESULT(fmt, fmt.c_str(), result);
  368. return result;
  369. }
  370. static std::string __testlib_part(const std::string &s);
  371. static bool __testlib_isNaN(double r) {
  372. __TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long));
  373. volatile double ra = r;
  374. long long llr1, llr2;
  375. std::memcpy((void *) &llr1, (void *) &ra, sizeof(double));
  376. ra = -ra;
  377. std::memcpy((void *) &llr2, (void *) &ra, sizeof(double));
  378. long long llnan = 0xFFF8000000000000LL;
  379. return __testlib_prelimIsNaN(r) || llnan == llr1 || llnan == llr2;
  380. }
  381. static double __testlib_nan() {
  382. __TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long));
  383. #ifndef NAN
  384. long long llnan = 0xFFF8000000000000LL;
  385. double nan;
  386. std::memcpy(&nan, &llnan, sizeof(double));
  387. return nan;
  388. #else
  389. return NAN;
  390. #endif
  391. }
  392. static bool __testlib_isInfinite(double r) {
  393. volatile double ra = r;
  394. return (ra > 1E300 || ra < -1E300);
  395. }
  396. #ifdef __GNUC__
  397. __attribute__((const))
  398. #endif
  399. inline bool doubleCompare(double expected, double result, double MAX_DOUBLE_ERROR) {
  400. MAX_DOUBLE_ERROR += 1E-15;
  401. if (__testlib_isNaN(expected)) {
  402. return __testlib_isNaN(result);
  403. } else if (__testlib_isInfinite(expected)) {
  404. if (expected > 0) {
  405. return result > 0 && __testlib_isInfinite(result);
  406. } else {
  407. return result < 0 && __testlib_isInfinite(result);
  408. }
  409. } else if (__testlib_isNaN(result) || __testlib_isInfinite(result)) {
  410. return false;
  411. } else if (__testlib_abs(result - expected) <= MAX_DOUBLE_ERROR) {
  412. return true;
  413. } else {
  414. double minv = __testlib_min(expected * (1.0 - MAX_DOUBLE_ERROR),
  415. expected * (1.0 + MAX_DOUBLE_ERROR));
  416. double maxv = __testlib_max(expected * (1.0 - MAX_DOUBLE_ERROR),
  417. expected * (1.0 + MAX_DOUBLE_ERROR));
  418. return result >= minv && result <= maxv;
  419. }
  420. }
  421. #ifdef __GNUC__
  422. __attribute__((const))
  423. #endif
  424. inline double doubleDelta(double expected, double result) {
  425. double absolute = __testlib_abs(result - expected);
  426. if (__testlib_abs(expected) > 1E-9) {
  427. double relative = __testlib_abs(absolute / expected);
  428. return __testlib_min(absolute, relative);
  429. } else
  430. return absolute;
  431. }
  432. /** It does nothing on non-windows and files differ from stdin/stdout/stderr. */
  433. static void __testlib_set_binary(std::FILE *file) {
  434. if (NULL != file) {
  435. #ifdef ON_WINDOWS
  436. # ifdef _O_BINARY
  437. if (stdin == file)
  438. # ifdef STDIN_FILENO
  439. return void(_setmode(STDIN_FILENO, _O_BINARY));
  440. # else
  441. return void(_setmode(_fileno(stdin), _O_BINARY));
  442. # endif
  443. if (stdout == file)
  444. # ifdef STDOUT_FILENO
  445. return void(_setmode(STDOUT_FILENO, _O_BINARY));
  446. # else
  447. return void(_setmode(_fileno(stdout), _O_BINARY));
  448. # endif
  449. if (stderr == file)
  450. # ifdef STDERR_FILENO
  451. return void(_setmode(STDERR_FILENO, _O_BINARY));
  452. # else
  453. return void(_setmode(_fileno(stderr), _O_BINARY));
  454. # endif
  455. # elif O_BINARY
  456. if (stdin == file)
  457. # ifdef STDIN_FILENO
  458. return void(setmode(STDIN_FILENO, O_BINARY));
  459. # else
  460. return void(setmode(fileno(stdin), O_BINARY));
  461. # endif
  462. if (stdout == file)
  463. # ifdef STDOUT_FILENO
  464. return void(setmode(STDOUT_FILENO, O_BINARY));
  465. # else
  466. return void(setmode(fileno(stdout), O_BINARY));
  467. # endif
  468. if (stderr == file)
  469. # ifdef STDERR_FILENO
  470. return void(setmode(STDERR_FILENO, O_BINARY));
  471. # else
  472. return void(setmode(fileno(stderr), O_BINARY));
  473. # endif
  474. # endif
  475. #endif
  476. }
  477. }
  478. #if __cplusplus > 199711L || defined(_MSC_VER)
  479. template<typename T>
  480. static std::string vtos(const T &t, std::true_type) {
  481. if (t == 0)
  482. return "0";
  483. else {
  484. T n(t);
  485. bool negative = n < 0;
  486. std::string s;
  487. while (n != 0) {
  488. T digit = n % 10;
  489. if (digit < 0)
  490. digit = -digit;
  491. s += char('0' + digit);
  492. n /= 10;
  493. }
  494. std::reverse(s.begin(), s.end());
  495. return negative ? "-" + s : s;
  496. }
  497. }
  498. template<typename T>
  499. static std::string vtos(const T &t, std::false_type) {
  500. std::string s;
  501. static std::stringstream ss;
  502. ss.str(std::string());
  503. ss.clear();
  504. ss << t;
  505. ss >> s;
  506. return s;
  507. }
  508. template<typename T>
  509. static std::string vtos(const T &t) {
  510. return vtos(t, std::is_integral<T>());
  511. }
  512. /* signed case. */
  513. template<typename T>
  514. static std::string toHumanReadableString(const T &n, std::false_type) {
  515. if (n == 0)
  516. return vtos(n);
  517. int trailingZeroCount = 0;
  518. T n_ = n;
  519. while (n_ % 10 == 0)
  520. n_ /= 10, trailingZeroCount++;
  521. if (trailingZeroCount >= 7) {
  522. if (n_ == 1)
  523. return "10^" + vtos(trailingZeroCount);
  524. else if (n_ == -1)
  525. return "-10^" + vtos(trailingZeroCount);
  526. else
  527. return vtos(n_) + "*10^" + vtos(trailingZeroCount);
  528. } else
  529. return vtos(n);
  530. }
  531. /* unsigned case. */
  532. template<typename T>
  533. static std::string toHumanReadableString(const T &n, std::true_type) {
  534. if (n == 0)
  535. return vtos(n);
  536. int trailingZeroCount = 0;
  537. T n_ = n;
  538. while (n_ % 10 == 0)
  539. n_ /= 10, trailingZeroCount++;
  540. if (trailingZeroCount >= 7) {
  541. if (n_ == 1)
  542. return "10^" + vtos(trailingZeroCount);
  543. else
  544. return vtos(n_) + "*10^" + vtos(trailingZeroCount);
  545. } else
  546. return vtos(n);
  547. }
  548. template<typename T>
  549. static std::string toHumanReadableString(const T &n) {
  550. return toHumanReadableString(n, std::is_unsigned<T>());
  551. }
  552. #else
  553. template<typename T>
  554. static std::string vtos(const T& t)
  555. {
  556. std::string s;
  557. static std::stringstream ss;
  558. ss.str(std::string());
  559. ss.clear();
  560. ss << t;
  561. ss >> s;
  562. return s;
  563. }
  564. template<typename T>
  565. static std::string toHumanReadableString(const T &n) {
  566. return vtos(n);
  567. }
  568. #endif
  569. template<typename T>
  570. static std::string toString(const T &t) {
  571. return vtos(t);
  572. }
  573. #if __cplusplus > 199711L || defined(_MSC_VER)
  574. /* opts */
  575. void prepareOpts(int argc, char* argv[]);
  576. #endif
  577. /*
  578. * Very simple regex-like pattern.
  579. * It used for two purposes: validation and generation.
  580. *
  581. * For example, pattern("[a-z]{1,5}").next(rnd) will return
  582. * random string from lowercase latin letters with length
  583. * from 1 to 5. It is easier to call rnd.next("[a-z]{1,5}")
  584. * for the same effect.
  585. *
  586. * Another samples:
  587. * "mike|john" will generate (match) "mike" or "john";
  588. * "-?[1-9][0-9]{0,3}" will generate (match) non-zero integers from -9999 to 9999;
  589. * "id-([ac]|b{2})" will generate (match) "id-a", "id-bb", "id-c";
  590. * "[^0-9]*" will match sequences (empty or non-empty) without digits, you can't
  591. * use it for generations.
  592. *
  593. * You can't use pattern for generation if it contains meta-symbol '*'. Also it
  594. * is not recommended to use it for char-sets with meta-symbol '^' like [^a-z].
  595. *
  596. * For matching very simple greedy algorithm is used. For example, pattern
  597. * "[0-9]?1" will not match "1", because of greedy nature of matching.
  598. * Alternations (meta-symbols "|") are processed with brute-force algorithm, so
  599. * do not use many alternations in one expression.
  600. *
  601. * If you want to use one expression many times it is better to compile it into
  602. * a single pattern like "pattern p("[a-z]+")". Later you can use
  603. * "p.matches(std::string s)" or "p.next(random_t& rd)" to check matching or generate
  604. * new string by pattern.
  605. *
  606. * Simpler way to read token and check it for pattern matching is "inf.readToken("[a-z]+")".
  607. *
  608. * All spaces are ignored in regex, unless escaped with \. For example, ouf.readLine("NO SOLUTION")
  609. * will expect "NOSOLUTION", the correct call should be ouf.readLine("NO\\ SOLUTION") or
  610. * ouf.readLine(R"(NO\ SOLUTION)") if you prefer raw string literals from C++11.
  611. */
  612. class random_t;
  613. class pattern {
  614. public:
  615. /* Create pattern instance by string. */
  616. pattern(std::string s);
  617. /* Generate new string by pattern and given random_t. */
  618. std::string next(random_t &rnd) const;
  619. /* Checks if given string match the pattern. */
  620. bool matches(const std::string &s) const;
  621. /* Returns source string of the pattern. */
  622. std::string src() const;
  623. private:
  624. bool matches(const std::string &s, size_t pos) const;
  625. std::string s;
  626. std::vector<pattern> children;
  627. std::vector<char> chars;
  628. int from;
  629. int to;
  630. };
  631. /*
  632. * Use random_t instances to generate random values. It is preferred
  633. * way to use randoms instead of rand() function or self-written
  634. * randoms.
  635. *
  636. * Testlib defines global variable "rnd" of random_t class.
  637. * Use registerGen(argc, argv, 1) to setup random_t seed be command
  638. * line (to use latest random generator version).
  639. *
  640. * Random generates uniformly distributed values if another strategy is
  641. * not specified explicitly.
  642. */
  643. class random_t {
  644. private:
  645. unsigned long long seed;
  646. static const unsigned long long multiplier;
  647. static const unsigned long long addend;
  648. static const unsigned long long mask;
  649. static const int lim;
  650. long long nextBits(int bits) {
  651. if (bits <= 48) {
  652. seed = (seed * multiplier + addend) & mask;
  653. return (long long) (seed >> (48 - bits));
  654. } else {
  655. if (bits > 63)
  656. __testlib_fail("random_t::nextBits(int bits): n must be less than 64");
  657. int lowerBitCount = (random_t::version == 0 ? 31 : 32);
  658. long long left = (nextBits(31) << 32);
  659. long long right = nextBits(lowerBitCount);
  660. return left ^ right;
  661. }
  662. }
  663. public:
  664. static int version;
  665. /* New random_t with fixed seed. */
  666. random_t()
  667. : seed(3905348978240129619LL) {
  668. }
  669. /* Sets seed by command line. */
  670. void setSeed(int argc, char *argv[]) {
  671. random_t p;
  672. seed = 3905348978240129619LL;
  673. for (int i = 1; i < argc; i++) {
  674. std::size_t le = std::strlen(argv[i]);
  675. for (std::size_t j = 0; j < le; j++)
  676. seed = seed * multiplier + (unsigned int) (argv[i][j]) + addend;
  677. seed += multiplier / addend;
  678. }
  679. seed = seed & mask;
  680. }
  681. /* Sets seed by given value. */
  682. void setSeed(long long _seed) {
  683. _seed = (_seed ^ multiplier) & mask;
  684. seed = _seed;
  685. }
  686. #ifndef __BORLANDC__
  687. /* Random string value by given pattern (see pattern documentation). */
  688. std::string next(const std::string &ptrn) {
  689. pattern p(ptrn);
  690. return p.next(*this);
  691. }
  692. #else
  693. /* Random string value by given pattern (see pattern documentation). */
  694. std::string next(std::string ptrn)
  695. {
  696. pattern p(ptrn);
  697. return p.next(*this);
  698. }
  699. #endif
  700. /* Random value in range [0, n-1]. */
  701. int next(int n) {
  702. if (n <= 0)
  703. __testlib_fail("random_t::next(int n): n must be positive");
  704. if ((n & -n) == n) // n is a power of 2
  705. return (int) ((n * (long long) nextBits(31)) >> 31);
  706. const long long limit = INT_MAX / n * n;
  707. long long bits;
  708. do {
  709. bits = nextBits(31);
  710. } while (bits >= limit);
  711. return int(bits % n);
  712. }
  713. /* Random value in range [0, n-1]. */
  714. unsigned int next(unsigned int n) {
  715. if (n >= INT_MAX)
  716. __testlib_fail("random_t::next(unsigned int n): n must be less INT_MAX");
  717. return (unsigned int) next(int(n));
  718. }
  719. /* Random value in range [0, n-1]. */
  720. long long next(long long n) {
  721. if (n <= 0)
  722. __testlib_fail("random_t::next(long long n): n must be positive");
  723. const long long limit = __TESTLIB_LONGLONG_MAX / n * n;
  724. long long bits;
  725. do {
  726. bits = nextBits(63);
  727. } while (bits >= limit);
  728. return bits % n;
  729. }
  730. /* Random value in range [0, n-1]. */
  731. unsigned long long next(unsigned long long n) {
  732. if (n >= (unsigned long long) (__TESTLIB_LONGLONG_MAX))
  733. __testlib_fail("random_t::next(unsigned long long n): n must be less LONGLONG_MAX");
  734. return (unsigned long long) next((long long) (n));
  735. }
  736. /* Random value in range [0, n-1]. */
  737. long next(long n) {
  738. return (long) next((long long) (n));
  739. }
  740. /* Random value in range [0, n-1]. */
  741. unsigned long next(unsigned long n) {
  742. if (n >= (unsigned long) (LONG_MAX))
  743. __testlib_fail("random_t::next(unsigned long n): n must be less LONG_MAX");
  744. return (unsigned long) next((unsigned long long) (n));
  745. }
  746. /* Returns random value in range [from,to]. */
  747. int next(int from, int to) {
  748. return int(next((long long) to - from + 1) + from);
  749. }
  750. /* Returns random value in range [from,to]. */
  751. unsigned int next(unsigned int from, unsigned int to) {
  752. return (unsigned int) (next((long long) to - from + 1) + from);
  753. }
  754. /* Returns random value in range [from,to]. */
  755. long long next(long long from, long long to) {
  756. return next(to - from + 1) + from;
  757. }
  758. /* Returns random value in range [from,to]. */
  759. unsigned long long next(unsigned long long from, unsigned long long to) {
  760. if (from > to)
  761. __testlib_fail("random_t::next(unsigned long long from, unsigned long long to): from can't not exceed to");
  762. return next(to - from + 1) + from;
  763. }
  764. /* Returns random value in range [from,to]. */
  765. long next(long from, long to) {
  766. return next(to - from + 1) + from;
  767. }
  768. /* Returns random value in range [from,to]. */
  769. unsigned long next(unsigned long from, unsigned long to) {
  770. if (from > to)
  771. __testlib_fail("random_t::next(unsigned long from, unsigned long to): from can't not exceed to");
  772. return next(to - from + 1) + from;
  773. }
  774. /* Random double value in range [0, 1). */
  775. double next() {
  776. long long left = ((long long) (nextBits(26)) << 27);
  777. long long right = nextBits(27);
  778. return __testlib_crop((double) (left + right) / (double) (1LL << 53), 0.0, 1.0);
  779. }
  780. /* Random double value in range [0, n). */
  781. double next(double n) {
  782. if (n <= 0.0)
  783. __testlib_fail("random_t::next(double): n should be positive");
  784. return __testlib_crop(n * next(), 0.0, n);
  785. }
  786. /* Random double value in range [from, to). */
  787. double next(double from, double to) {
  788. if (from >= to)
  789. __testlib_fail("random_t::next(double from, double to): from should be strictly less than to");
  790. return next(to - from) + from;
  791. }
  792. /* Returns random element from container. */
  793. template<typename Container>
  794. typename Container::value_type any(const Container &c) {
  795. int size = int(c.size());
  796. if (size <= 0)
  797. __testlib_fail("random_t::any(const Container& c): c.size() must be positive");
  798. return *(c.begin() + next(size));
  799. }
  800. /* Returns random element from iterator range. */
  801. template<typename Iter>
  802. typename Iter::value_type any(const Iter &begin, const Iter &end) {
  803. int size = int(end - begin);
  804. if (size <= 0)
  805. __testlib_fail("random_t::any(const Iter& begin, const Iter& end): range must have positive length");
  806. return *(begin + next(size));
  807. }
  808. /* Random string value by given pattern (see pattern documentation). */
  809. #ifdef __GNUC__
  810. __attribute__ ((format (printf, 2, 3)))
  811. #endif
  812. std::string next(const char *format, ...) {
  813. FMT_TO_RESULT(format, format, ptrn);
  814. return next(ptrn);
  815. }
  816. /*
  817. * Weighted next. If type == 0 than it is usual "next()".
  818. *
  819. * If type = 1, than it returns "max(next(), next())"
  820. * (the number of "max" functions equals to "type").
  821. *
  822. * If type < 0, than "max" function replaces with "min".
  823. */
  824. int wnext(int n, int type) {
  825. if (n <= 0)
  826. __testlib_fail("random_t::wnext(int n, int type): n must be positive");
  827. if (abs(type) < random_t::lim) {
  828. int result = next(n);
  829. for (int i = 0; i < +type; i++)
  830. result = __testlib_max(result, next(n));
  831. for (int i = 0; i < -type; i++)
  832. result = __testlib_min(result, next(n));
  833. return result;
  834. } else {
  835. double p;
  836. if (type > 0)
  837. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  838. else
  839. p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1));
  840. return __testlib_crop((int) (double(n) * p), 0, n);
  841. }
  842. }
  843. /* See wnext(int, int). It uses the same algorithms. */
  844. long long wnext(long long n, int type) {
  845. if (n <= 0)
  846. __testlib_fail("random_t::wnext(long long n, int type): n must be positive");
  847. if (abs(type) < random_t::lim) {
  848. long long result = next(n);
  849. for (int i = 0; i < +type; i++)
  850. result = __testlib_max(result, next(n));
  851. for (int i = 0; i < -type; i++)
  852. result = __testlib_min(result, next(n));
  853. return result;
  854. } else {
  855. double p;
  856. if (type > 0)
  857. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  858. else
  859. p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1));
  860. return __testlib_crop((long long) (double(n) * p), 0LL, n);
  861. }
  862. }
  863. /* Returns value in [0, n). See wnext(int, int). It uses the same algorithms. */
  864. double wnext(double n, int type) {
  865. if (n <= 0)
  866. __testlib_fail("random_t::wnext(double n, int type): n must be positive");
  867. if (abs(type) < random_t::lim) {
  868. double result = next();
  869. for (int i = 0; i < +type; i++)
  870. result = __testlib_max(result, next());
  871. for (int i = 0; i < -type; i++)
  872. result = __testlib_min(result, next());
  873. return n * result;
  874. } else {
  875. double p;
  876. if (type > 0)
  877. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  878. else
  879. p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1));
  880. return __testlib_crop(n * p, 0.0, n);
  881. }
  882. }
  883. /* Returns value in [0, 1). See wnext(int, int). It uses the same algorithms. */
  884. double wnext(int type) {
  885. return wnext(1.0, type);
  886. }
  887. /* See wnext(int, int). It uses the same algorithms. */
  888. unsigned int wnext(unsigned int n, int type) {
  889. if (n >= INT_MAX)
  890. __testlib_fail("random_t::wnext(unsigned int n, int type): n must be less INT_MAX");
  891. return (unsigned int) wnext(int(n), type);
  892. }
  893. /* See wnext(int, int). It uses the same algorithms. */
  894. unsigned long long wnext(unsigned long long n, int type) {
  895. if (n >= (unsigned long long) (__TESTLIB_LONGLONG_MAX))
  896. __testlib_fail("random_t::wnext(unsigned long long n, int type): n must be less LONGLONG_MAX");
  897. return (unsigned long long) wnext((long long) (n), type);
  898. }
  899. /* See wnext(int, int). It uses the same algorithms. */
  900. long wnext(long n, int type) {
  901. return (long) wnext((long long) (n), type);
  902. }
  903. /* See wnext(int, int). It uses the same algorithms. */
  904. unsigned long wnext(unsigned long n, int type) {
  905. if (n >= (unsigned long) (LONG_MAX))
  906. __testlib_fail("random_t::wnext(unsigned long n, int type): n must be less LONG_MAX");
  907. return (unsigned long) wnext((unsigned long long) (n), type);
  908. }
  909. /* Returns weighted random value in range [from, to]. */
  910. int wnext(int from, int to, int type) {
  911. if (from > to)
  912. __testlib_fail("random_t::wnext(int from, int to, int type): from can't not exceed to");
  913. return wnext(to - from + 1, type) + from;
  914. }
  915. /* Returns weighted random value in range [from, to]. */
  916. int wnext(unsigned int from, unsigned int to, int type) {
  917. if (from > to)
  918. __testlib_fail("random_t::wnext(unsigned int from, unsigned int to, int type): from can't not exceed to");
  919. return int(wnext(to - from + 1, type) + from);
  920. }
  921. /* Returns weighted random value in range [from, to]. */
  922. long long wnext(long long from, long long to, int type) {
  923. if (from > to)
  924. __testlib_fail("random_t::wnext(long long from, long long to, int type): from can't not exceed to");
  925. return wnext(to - from + 1, type) + from;
  926. }
  927. /* Returns weighted random value in range [from, to]. */
  928. unsigned long long wnext(unsigned long long from, unsigned long long to, int type) {
  929. if (from > to)
  930. __testlib_fail(
  931. "random_t::wnext(unsigned long long from, unsigned long long to, int type): from can't not exceed to");
  932. return wnext(to - from + 1, type) + from;
  933. }
  934. /* Returns weighted random value in range [from, to]. */
  935. long wnext(long from, long to, int type) {
  936. if (from > to)
  937. __testlib_fail("random_t::wnext(long from, long to, int type): from can't not exceed to");
  938. return wnext(to - from + 1, type) + from;
  939. }
  940. /* Returns weighted random value in range [from, to]. */
  941. unsigned long wnext(unsigned long from, unsigned long to, int type) {
  942. if (from > to)
  943. __testlib_fail("random_t::wnext(unsigned long from, unsigned long to, int type): from can't not exceed to");
  944. return wnext(to - from + 1, type) + from;
  945. }
  946. /* Returns weighted random double value in range [from, to). */
  947. double wnext(double from, double to, int type) {
  948. if (from >= to)
  949. __testlib_fail("random_t::wnext(double from, double to, int type): from should be strictly less than to");
  950. return wnext(to - from, type) + from;
  951. }
  952. /* Returns weighted random element from container. */
  953. template<typename Container>
  954. typename Container::value_type wany(const Container &c, int type) {
  955. size_t size = c.size();
  956. if (size <= 0)
  957. __testlib_fail("random_t::wany(const Container& c, int type): c.size() must be positive");
  958. return *(c.begin() + wnext(size, type));
  959. }
  960. /* Returns weighted random element from iterator range. */
  961. template<typename Iter>
  962. typename Iter::value_type wany(const Iter &begin, const Iter &end, int type) {
  963. int size = int(end - begin);
  964. if (size <= 0)
  965. __testlib_fail(
  966. "random_t::any(const Iter& begin, const Iter& end, int type): range must have positive length");
  967. return *(begin + wnext(size, type));
  968. }
  969. /* Returns random permutation of the given size (values are between `first` and `first`+size-1)*/
  970. template<typename T, typename E>
  971. std::vector<E> perm(T size, E first) {
  972. if (size < 0)
  973. __testlib_fail("random_t::perm(T size, E first = 0): size must non-negative");
  974. else if (size == 0)
  975. return std::vector<E>();
  976. std::vector<E> p(size);
  977. E current = first;
  978. for (T i = 0; i < size; i++)
  979. p[i] = current++;
  980. if (size > 1)
  981. for (T i = 1; i < size; i++)
  982. std::swap(p[i], p[next(i + 1)]);
  983. return p;
  984. }
  985. /* Returns random permutation of the given size (values are between 0 and size-1)*/
  986. template<typename T>
  987. std::vector<T> perm(T size) {
  988. return perm(size, T(0));
  989. }
  990. /* Returns `size` unordered (unsorted) distinct numbers between `from` and `to`. */
  991. template<typename T>
  992. std::vector<T> distinct(int size, T from, T to) {
  993. std::vector<T> result;
  994. if (size == 0)
  995. return result;
  996. if (from > to)
  997. __testlib_fail("random_t::distinct expected from <= to");
  998. if (size < 0)
  999. __testlib_fail("random_t::distinct expected size >= 0");
  1000. uint64_t n = to - from + 1;
  1001. if (uint64_t(size) > n)
  1002. __testlib_fail("random_t::distinct expected size <= to - from + 1");
  1003. double expected = 0.0;
  1004. for (int i = 1; i <= size; i++)
  1005. expected += double(n) / double(n - i + 1);
  1006. if (expected < double(n)) {
  1007. std::set<T> vals;
  1008. while (int(vals.size()) < size) {
  1009. T x = T(next(from, to));
  1010. if (vals.insert(x).second)
  1011. result.push_back(x);
  1012. }
  1013. } else {
  1014. if (n > 1000000000)
  1015. __testlib_fail("random_t::distinct here expected to - from + 1 <= 1000000000");
  1016. std::vector<T> p(perm(int(n), from));
  1017. result.insert(result.end(), p.begin(), p.begin() + size);
  1018. }
  1019. return result;
  1020. }
  1021. /* Returns `size` unordered (unsorted) distinct numbers between `0` and `upper`-1. */
  1022. template<typename T>
  1023. std::vector<T> distinct(int size, T upper) {
  1024. if (size < 0)
  1025. __testlib_fail("random_t::distinct expected size >= 0");
  1026. if (size == 0)
  1027. return std::vector<T>();
  1028. if (upper <= 0)
  1029. __testlib_fail("random_t::distinct expected upper > 0");
  1030. if (size > upper)
  1031. __testlib_fail("random_t::distinct expected size <= upper");
  1032. return distinct(size, T(0), upper - 1);
  1033. }
  1034. /* Returns random (unsorted) partition which is a representation of sum as a sum of integers not less than min_part. */
  1035. template<typename T>
  1036. std::vector<T> partition(int size, T sum, T min_part) {
  1037. if (size < 0)
  1038. __testlib_fail("random_t::partition: size < 0");
  1039. if (size == 0 && sum != 0)
  1040. __testlib_fail("random_t::partition: size == 0 && sum != 0");
  1041. if (min_part * size > sum)
  1042. __testlib_fail("random_t::partition: min_part * size > sum");
  1043. if (size == 0 && sum == 0)
  1044. return std::vector<T>();
  1045. T sum_ = sum;
  1046. sum -= min_part * size;
  1047. std::vector<T> septums(size);
  1048. std::vector<T> d = distinct(size - 1, T(1), T(sum + size - 1));
  1049. for (int i = 0; i + 1 < size; i++)
  1050. septums[i + 1] = d[i];
  1051. sort(septums.begin(), septums.end());
  1052. std::vector<T> result(size);
  1053. for (int i = 0; i + 1 < size; i++)
  1054. result[i] = septums[i + 1] - septums[i] - 1;
  1055. result[size - 1] = sum + size - 1 - septums.back();
  1056. for (std::size_t i = 0; i < result.size(); i++)
  1057. result[i] += min_part;
  1058. T result_sum = 0;
  1059. for (std::size_t i = 0; i < result.size(); i++)
  1060. result_sum += result[i];
  1061. if (result_sum != sum_)
  1062. __testlib_fail("random_t::partition: partition sum is expected to be the given sum");
  1063. if (*std::min_element(result.begin(), result.end()) < min_part)
  1064. __testlib_fail("random_t::partition: partition min is expected to be no less than the given min_part");
  1065. if (int(result.size()) != size || result.size() != (size_t) size)
  1066. __testlib_fail("random_t::partition: partition size is expected to be equal to the given size");
  1067. return result;
  1068. }
  1069. /* Returns random (unsorted) partition which is a representation of sum as a sum of positive integers. */
  1070. template<typename T>
  1071. std::vector<T> partition(int size, T sum) {
  1072. return partition(size, sum, T(1));
  1073. }
  1074. };
  1075. const int random_t::lim = 25;
  1076. const unsigned long long random_t::multiplier = 0x5DEECE66DLL;
  1077. const unsigned long long random_t::addend = 0xBLL;
  1078. const unsigned long long random_t::mask = (1LL << 48) - 1;
  1079. int random_t::version = -1;
  1080. /* Pattern implementation */
  1081. bool pattern::matches(const std::string &s) const {
  1082. return matches(s, 0);
  1083. }
  1084. static bool __pattern_isSlash(const std::string &s, size_t pos) {
  1085. return s[pos] == '\\';
  1086. }
  1087. #ifdef __GNUC__
  1088. __attribute__((pure))
  1089. #endif
  1090. static bool __pattern_isCommandChar(const std::string &s, size_t pos, char value) {
  1091. if (pos >= s.length())
  1092. return false;
  1093. int slashes = 0;
  1094. int before = int(pos) - 1;
  1095. while (before >= 0 && s[before] == '\\')
  1096. before--, slashes++;
  1097. return slashes % 2 == 0 && s[pos] == value;
  1098. }
  1099. static char __pattern_getChar(const std::string &s, size_t &pos) {
  1100. if (__pattern_isSlash(s, pos))
  1101. pos += 2;
  1102. else
  1103. pos++;
  1104. return s[pos - 1];
  1105. }
  1106. #ifdef __GNUC__
  1107. __attribute__((pure))
  1108. #endif
  1109. static int __pattern_greedyMatch(const std::string &s, size_t pos, const std::vector<char> chars) {
  1110. int result = 0;
  1111. while (pos < s.length()) {
  1112. char c = s[pos++];
  1113. if (!std::binary_search(chars.begin(), chars.end(), c))
  1114. break;
  1115. else
  1116. result++;
  1117. }
  1118. return result;
  1119. }
  1120. std::string pattern::src() const {
  1121. return s;
  1122. }
  1123. bool pattern::matches(const std::string &s, size_t pos) const {
  1124. std::string result;
  1125. if (to > 0) {
  1126. int size = __pattern_greedyMatch(s, pos, chars);
  1127. if (size < from)
  1128. return false;
  1129. if (size > to)
  1130. size = to;
  1131. pos += size;
  1132. }
  1133. if (children.size() > 0) {
  1134. for (size_t child = 0; child < children.size(); child++)
  1135. if (children[child].matches(s, pos))
  1136. return true;
  1137. return false;
  1138. } else
  1139. return pos == s.length();
  1140. }
  1141. std::string pattern::next(random_t &rnd) const {
  1142. std::string result;
  1143. result.reserve(20);
  1144. if (to == INT_MAX)
  1145. __testlib_fail("pattern::next(random_t& rnd): can't process character '*' for generation");
  1146. if (to > 0) {
  1147. int count = rnd.next(to - from + 1) + from;
  1148. for (int i = 0; i < count; i++)
  1149. result += chars[rnd.next(int(chars.size()))];
  1150. }
  1151. if (children.size() > 0) {
  1152. int child = rnd.next(int(children.size()));
  1153. result += children[child].next(rnd);
  1154. }
  1155. return result;
  1156. }
  1157. static void __pattern_scanCounts(const std::string &s, size_t &pos, int &from, int &to) {
  1158. if (pos >= s.length()) {
  1159. from = to = 1;
  1160. return;
  1161. }
  1162. if (__pattern_isCommandChar(s, pos, '{')) {
  1163. std::vector<std::string> parts;
  1164. std::string part;
  1165. pos++;
  1166. while (pos < s.length() && !__pattern_isCommandChar(s, pos, '}')) {
  1167. if (__pattern_isCommandChar(s, pos, ','))
  1168. parts.push_back(part), part = "", pos++;
  1169. else
  1170. part += __pattern_getChar(s, pos);
  1171. }
  1172. if (part != "")
  1173. parts.push_back(part);
  1174. if (!__pattern_isCommandChar(s, pos, '}'))
  1175. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  1176. pos++;
  1177. if (parts.size() < 1 || parts.size() > 2)
  1178. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  1179. std::vector<int> numbers;
  1180. for (size_t i = 0; i < parts.size(); i++) {
  1181. if (parts[i].length() == 0)
  1182. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  1183. int number;
  1184. if (std::sscanf(parts[i].c_str(), "%d", &number) != 1)
  1185. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  1186. numbers.push_back(number);
  1187. }
  1188. if (numbers.size() == 1)
  1189. from = to = numbers[0];
  1190. else
  1191. from = numbers[0], to = numbers[1];
  1192. if (from > to)
  1193. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  1194. } else {
  1195. if (__pattern_isCommandChar(s, pos, '?')) {
  1196. from = 0, to = 1, pos++;
  1197. return;
  1198. }
  1199. if (__pattern_isCommandChar(s, pos, '*')) {
  1200. from = 0, to = INT_MAX, pos++;
  1201. return;
  1202. }
  1203. if (__pattern_isCommandChar(s, pos, '+')) {
  1204. from = 1, to = INT_MAX, pos++;
  1205. return;
  1206. }
  1207. from = to = 1;
  1208. }
  1209. }
  1210. static std::vector<char> __pattern_scanCharSet(const std::string &s, size_t &pos) {
  1211. if (pos >= s.length())
  1212. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  1213. std::vector<char> result;
  1214. if (__pattern_isCommandChar(s, pos, '[')) {
  1215. pos++;
  1216. bool negative = __pattern_isCommandChar(s, pos, '^');
  1217. if (negative)
  1218. pos++;
  1219. char prev = 0;
  1220. while (pos < s.length() && !__pattern_isCommandChar(s, pos, ']')) {
  1221. if (__pattern_isCommandChar(s, pos, '-') && prev != 0) {
  1222. pos++;
  1223. if (pos + 1 == s.length() || __pattern_isCommandChar(s, pos, ']')) {
  1224. result.push_back(prev);
  1225. prev = '-';
  1226. continue;
  1227. }
  1228. char next = __pattern_getChar(s, pos);
  1229. if (prev > next)
  1230. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  1231. for (char c = prev; c != next; c++)
  1232. result.push_back(c);
  1233. result.push_back(next);
  1234. prev = 0;
  1235. } else {
  1236. if (prev != 0)
  1237. result.push_back(prev);
  1238. prev = __pattern_getChar(s, pos);
  1239. }
  1240. }
  1241. if (prev != 0)
  1242. result.push_back(prev);
  1243. if (!__pattern_isCommandChar(s, pos, ']'))
  1244. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  1245. pos++;
  1246. if (negative) {
  1247. std::sort(result.begin(), result.end());
  1248. std::vector<char> actuals;
  1249. for (int code = 0; code < 255; code++) {
  1250. char c = char(code);
  1251. if (!std::binary_search(result.begin(), result.end(), c))
  1252. actuals.push_back(c);
  1253. }
  1254. result = actuals;
  1255. }
  1256. std::sort(result.begin(), result.end());
  1257. } else
  1258. result.push_back(__pattern_getChar(s, pos));
  1259. return result;
  1260. }
  1261. pattern::pattern(std::string s) : s(s), from(0), to(0) {
  1262. std::string t;
  1263. for (size_t i = 0; i < s.length(); i++)
  1264. if (!__pattern_isCommandChar(s, i, ' '))
  1265. t += s[i];
  1266. s = t;
  1267. int opened = 0;
  1268. int firstClose = -1;
  1269. std::vector<int> seps;
  1270. for (size_t i = 0; i < s.length(); i++) {
  1271. if (__pattern_isCommandChar(s, i, '(')) {
  1272. opened++;
  1273. continue;
  1274. }
  1275. if (__pattern_isCommandChar(s, i, ')')) {
  1276. opened--;
  1277. if (opened == 0 && firstClose == -1)
  1278. firstClose = int(i);
  1279. continue;
  1280. }
  1281. if (opened < 0)
  1282. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  1283. if (__pattern_isCommandChar(s, i, '|') && opened == 0)
  1284. seps.push_back(int(i));
  1285. }
  1286. if (opened != 0)
  1287. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  1288. if (seps.size() == 0 && firstClose + 1 == (int) s.length()
  1289. && __pattern_isCommandChar(s, 0, '(') && __pattern_isCommandChar(s, s.length() - 1, ')')) {
  1290. children.push_back(pattern(s.substr(1, s.length() - 2)));
  1291. } else {
  1292. if (seps.size() > 0) {
  1293. seps.push_back(int(s.length()));
  1294. int last = 0;
  1295. for (size_t i = 0; i < seps.size(); i++) {
  1296. children.push_back(pattern(s.substr(last, seps[i] - last)));
  1297. last = seps[i] + 1;
  1298. }
  1299. } else {
  1300. size_t pos = 0;
  1301. chars = __pattern_scanCharSet(s, pos);
  1302. __pattern_scanCounts(s, pos, from, to);
  1303. if (pos < s.length())
  1304. children.push_back(pattern(s.substr(pos)));
  1305. }
  1306. }
  1307. }
  1308. /* End of pattern implementation */
  1309. template<typename C>
  1310. inline bool isEof(C c) {
  1311. return c == EOFC;
  1312. }
  1313. template<typename C>
  1314. inline bool isEoln(C c) {
  1315. return (c == LF || c == CR);
  1316. }
  1317. template<typename C>
  1318. inline bool isBlanks(C c) {
  1319. return (c == LF || c == CR || c == SPACE || c == TAB);
  1320. }
  1321. inline std::string trim(const std::string &s) {
  1322. if (s.empty())
  1323. return s;
  1324. int left = 0;
  1325. while (left < int(s.length()) && isBlanks(s[left]))
  1326. left++;
  1327. if (left >= int(s.length()))
  1328. return "";
  1329. int right = int(s.length()) - 1;
  1330. while (right >= 0 && isBlanks(s[right]))
  1331. right--;
  1332. if (right < 0)
  1333. return "";
  1334. return s.substr(left, right - left + 1);
  1335. }
  1336. enum TMode {
  1337. _input, _output, _answer
  1338. };
  1339. /* Outcomes 6-15 are reserved for future use. */
  1340. enum TResult {
  1341. _ok = 0,
  1342. _wa = 1,
  1343. _pe = 2,
  1344. _fail = 3,
  1345. _dirt = 4,
  1346. _points = 5,
  1347. _unexpected_eof = 8,
  1348. _partially = 16
  1349. };
  1350. enum TTestlibMode {
  1351. _unknown, _checker, _validator, _generator, _interactor, _scorer
  1352. };
  1353. #define _pc(exitCode) (TResult(_partially + (exitCode)))
  1354. /* Outcomes 6-15 are reserved for future use. */
  1355. const std::string outcomes[] = {
  1356. "accepted",
  1357. "wrong-answer",
  1358. "presentation-error",
  1359. "fail",
  1360. "fail",
  1361. #ifndef PCMS2
  1362. "points",
  1363. #else
  1364. "relative-scoring",
  1365. #endif
  1366. "reserved",
  1367. "reserved",
  1368. "unexpected-eof",
  1369. "reserved",
  1370. "reserved",
  1371. "reserved",
  1372. "reserved",
  1373. "reserved",
  1374. "reserved",
  1375. "reserved",
  1376. "partially-correct"
  1377. };
  1378. class InputStreamReader {
  1379. public:
  1380. virtual void setTestCase(int testCase) = 0;
  1381. virtual std::vector<int> getReadChars() = 0;
  1382. virtual int curChar() = 0;
  1383. virtual int nextChar() = 0;
  1384. virtual void skipChar() = 0;
  1385. virtual void unreadChar(int c) = 0;
  1386. virtual std::string getName() = 0;
  1387. virtual bool eof() = 0;
  1388. virtual void close() = 0;
  1389. virtual int getLine() = 0;
  1390. virtual ~InputStreamReader() = 0;
  1391. };
  1392. InputStreamReader::~InputStreamReader() {
  1393. // No operations.
  1394. }
  1395. class StringInputStreamReader : public InputStreamReader {
  1396. private:
  1397. std::string s;
  1398. size_t pos;
  1399. public:
  1400. StringInputStreamReader(const std::string &content) : s(content), pos(0) {
  1401. // No operations.
  1402. }
  1403. void setTestCase(int) {
  1404. __testlib_fail("setTestCase not implemented in StringInputStreamReader");
  1405. }
  1406. std::vector<int> getReadChars() {
  1407. __testlib_fail("getReadChars not implemented in StringInputStreamReader");
  1408. }
  1409. int curChar() {
  1410. if (pos >= s.length())
  1411. return EOFC;
  1412. else
  1413. return s[pos];
  1414. }
  1415. int nextChar() {
  1416. if (pos >= s.length()) {
  1417. pos++;
  1418. return EOFC;
  1419. } else
  1420. return s[pos++];
  1421. }
  1422. void skipChar() {
  1423. pos++;
  1424. }
  1425. void unreadChar(int c) {
  1426. if (pos == 0)
  1427. __testlib_fail("StringInputStreamReader::unreadChar(int): pos == 0.");
  1428. pos--;
  1429. if (pos < s.length())
  1430. s[pos] = char(c);
  1431. }
  1432. std::string getName() {
  1433. return __testlib_part(s);
  1434. }
  1435. int getLine() {
  1436. return -1;
  1437. }
  1438. bool eof() {
  1439. return pos >= s.length();
  1440. }
  1441. void close() {
  1442. // No operations.
  1443. }
  1444. };
  1445. class FileInputStreamReader : public InputStreamReader {
  1446. private:
  1447. std::FILE *file;
  1448. std::string name;
  1449. int line;
  1450. std::vector<int> undoChars;
  1451. std::vector<int> readChars;
  1452. std::vector<int> undoReadChars;
  1453. inline int postprocessGetc(int getcResult) {
  1454. if (getcResult != EOF)
  1455. return getcResult;
  1456. else
  1457. return EOFC;
  1458. }
  1459. int getc(FILE *file) {
  1460. int c;
  1461. int rc;
  1462. if (undoChars.empty()) {
  1463. c = rc = ::getc(file);
  1464. } else {
  1465. c = undoChars.back();
  1466. undoChars.pop_back();
  1467. rc = undoReadChars.back();
  1468. undoReadChars.pop_back();
  1469. }
  1470. if (c == LF)
  1471. line++;
  1472. readChars.push_back(rc);
  1473. return c;
  1474. }
  1475. int ungetc(int c/*, FILE* file*/) {
  1476. if (!readChars.empty()) {
  1477. undoReadChars.push_back(readChars.back());
  1478. readChars.pop_back();
  1479. }
  1480. if (c == LF)
  1481. line--;
  1482. undoChars.push_back(c);
  1483. return c;
  1484. }
  1485. public:
  1486. FileInputStreamReader(std::FILE *file, const std::string &name) : file(file), name(name), line(1) {
  1487. // No operations.
  1488. }
  1489. void setTestCase(int testCase) {
  1490. if (testCase < 0 || testCase > __TESTLIB_MAX_TEST_CASE)
  1491. __testlib_fail(format("testCase expected fit in [1,%d], but %d doesn't", __TESTLIB_MAX_TEST_CASE, testCase));
  1492. readChars.push_back(testCase + 256);
  1493. }
  1494. std::vector<int> getReadChars() {
  1495. return readChars;
  1496. }
  1497. int curChar() {
  1498. if (feof(file))
  1499. return EOFC;
  1500. else {
  1501. int c = getc(file);
  1502. ungetc(c/*, file*/);
  1503. return postprocessGetc(c);
  1504. }
  1505. }
  1506. int nextChar() {
  1507. if (feof(file))
  1508. return EOFC;
  1509. else
  1510. return postprocessGetc(getc(file));
  1511. }
  1512. void skipChar() {
  1513. getc(file);
  1514. }
  1515. void unreadChar(int c) {
  1516. ungetc(c/*, file*/);
  1517. }
  1518. std::string getName() {
  1519. return name;
  1520. }
  1521. int getLine() {
  1522. return line;
  1523. }
  1524. bool eof() {
  1525. if (NULL == file || feof(file))
  1526. return true;
  1527. else {
  1528. int c = nextChar();
  1529. if (c == EOFC || (c == EOF && feof(file)))
  1530. return true;
  1531. unreadChar(c);
  1532. return false;
  1533. }
  1534. }
  1535. void close() {
  1536. if (NULL != file) {
  1537. fclose(file);
  1538. file = NULL;
  1539. }
  1540. }
  1541. };
  1542. class BufferedFileInputStreamReader : public InputStreamReader {
  1543. private:
  1544. static const size_t BUFFER_SIZE;
  1545. static const size_t MAX_UNREAD_COUNT;
  1546. std::FILE *file;
  1547. std::string name;
  1548. int line;
  1549. char *buffer;
  1550. bool *isEof;
  1551. int bufferPos;
  1552. size_t bufferSize;
  1553. bool refill() {
  1554. if (NULL == file)
  1555. __testlib_fail("BufferedFileInputStreamReader: file == NULL (" + getName() + ")");
  1556. if (bufferPos >= int(bufferSize)) {
  1557. size_t readSize = fread(
  1558. buffer + MAX_UNREAD_COUNT,
  1559. 1,
  1560. BUFFER_SIZE - MAX_UNREAD_COUNT,
  1561. file
  1562. );
  1563. if (readSize < BUFFER_SIZE - MAX_UNREAD_COUNT
  1564. && ferror(file))
  1565. __testlib_fail("BufferedFileInputStreamReader: unable to read (" + getName() + ")");
  1566. bufferSize = MAX_UNREAD_COUNT + readSize;
  1567. bufferPos = int(MAX_UNREAD_COUNT);
  1568. std::memset(isEof + MAX_UNREAD_COUNT, 0, sizeof(isEof[0]) * readSize);
  1569. return readSize > 0;
  1570. } else
  1571. return true;
  1572. }
  1573. char increment() {
  1574. char c;
  1575. if ((c = buffer[bufferPos++]) == LF)
  1576. line++;
  1577. return c;
  1578. }
  1579. public:
  1580. BufferedFileInputStreamReader(std::FILE *file, const std::string &name) : file(file), name(name), line(1) {
  1581. buffer = new char[BUFFER_SIZE];
  1582. isEof = new bool[BUFFER_SIZE];
  1583. bufferSize = MAX_UNREAD_COUNT;
  1584. bufferPos = int(MAX_UNREAD_COUNT);
  1585. }
  1586. ~BufferedFileInputStreamReader() {
  1587. if (NULL != buffer) {
  1588. delete[] buffer;
  1589. buffer = NULL;
  1590. }
  1591. if (NULL != isEof) {
  1592. delete[] isEof;
  1593. isEof = NULL;
  1594. }
  1595. }
  1596. void setTestCase(int) {
  1597. __testlib_fail("setTestCase not implemented in BufferedFileInputStreamReader");
  1598. }
  1599. std::vector<int> getReadChars() {
  1600. __testlib_fail("getReadChars not implemented in BufferedFileInputStreamReader");
  1601. }
  1602. int curChar() {
  1603. if (!refill())
  1604. return EOFC;
  1605. return isEof[bufferPos] ? EOFC : buffer[bufferPos];
  1606. }
  1607. int nextChar() {
  1608. if (!refill())
  1609. return EOFC;
  1610. return isEof[bufferPos] ? EOFC : increment();
  1611. }
  1612. void skipChar() {
  1613. increment();
  1614. }
  1615. void unreadChar(int c) {
  1616. bufferPos--;
  1617. if (bufferPos < 0)
  1618. __testlib_fail("BufferedFileInputStreamReader::unreadChar(int): bufferPos < 0");
  1619. isEof[bufferPos] = (c == EOFC);
  1620. buffer[bufferPos] = char(c);
  1621. if (c == LF)
  1622. line--;
  1623. }
  1624. std::string getName() {
  1625. return name;
  1626. }
  1627. int getLine() {
  1628. return line;
  1629. }
  1630. bool eof() {
  1631. return !refill() || EOFC == curChar();
  1632. }
  1633. void close() {
  1634. if (NULL != file) {
  1635. fclose(file);
  1636. file = NULL;
  1637. }
  1638. }
  1639. };
  1640. const size_t BufferedFileInputStreamReader::BUFFER_SIZE = 2000000;
  1641. const size_t BufferedFileInputStreamReader::MAX_UNREAD_COUNT = BufferedFileInputStreamReader::BUFFER_SIZE / 2;
  1642. /*
  1643. * Streams to be used for reading data in checkers or validators.
  1644. * Each read*() method moves pointer to the next character after the
  1645. * read value.
  1646. */
  1647. struct InStream {
  1648. /* Do not use them. */
  1649. InStream();
  1650. ~InStream();
  1651. /* Wrap std::string with InStream. */
  1652. InStream(const InStream &baseStream, std::string content);
  1653. InputStreamReader *reader;
  1654. int lastLine;
  1655. std::string name;
  1656. TMode mode;
  1657. bool opened;
  1658. bool stdfile;
  1659. bool strict;
  1660. int wordReserveSize;
  1661. std::string _tmpReadToken;
  1662. int readManyIteration;
  1663. size_t maxFileSize;
  1664. size_t maxTokenLength;
  1665. size_t maxMessageLength;
  1666. void init(std::string fileName, TMode mode);
  1667. void init(std::FILE *f, TMode mode);
  1668. void setTestCase(int testCase);
  1669. std::vector<int> getReadChars();
  1670. /* Moves stream pointer to the first non-white-space character or EOF. */
  1671. void skipBlanks();
  1672. /* Returns current character in the stream. Doesn't remove it from stream. */
  1673. char curChar();
  1674. /* Moves stream pointer one character forward. */
  1675. void skipChar();
  1676. /* Returns current character and moves pointer one character forward. */
  1677. char nextChar();
  1678. /* Returns current character and moves pointer one character forward. */
  1679. char readChar();
  1680. /* As "readChar()" but ensures that the result is equal to given parameter. */
  1681. char readChar(char c);
  1682. /* As "readChar()" but ensures that the result is equal to the space (code=32). */
  1683. char readSpace();
  1684. /* Puts back the character into the stream. */
  1685. void unreadChar(char c);
  1686. /* Reopens stream, you should not use it. */
  1687. void reset(std::FILE *file = NULL);
  1688. /* Checks that current position is EOF. If not it doesn't move stream pointer. */
  1689. bool eof();
  1690. /* Moves pointer to the first non-white-space character and calls "eof()". */
  1691. bool seekEof();
  1692. /*
  1693. * Checks that current position contains EOLN.
  1694. * If not it doesn't move stream pointer.
  1695. * In strict mode expects "#13#10" for windows or "#10" for other platforms.
  1696. */
  1697. bool eoln();
  1698. /* Moves pointer to the first non-space and non-tab character and calls "eoln()". */
  1699. bool seekEoln();
  1700. /* Moves stream pointer to the first character of the next line (if exists). */
  1701. void nextLine();
  1702. /*
  1703. * Reads new token. Ignores white-spaces into the non-strict mode
  1704. * (strict mode is used in validators usually).
  1705. */
  1706. std::string readWord();
  1707. /* The same as "readWord()", it is preferred to use "readToken()". */
  1708. std::string readToken();
  1709. /* The same as "readWord()", but ensures that token matches to given pattern. */
  1710. std::string readWord(const std::string &ptrn, const std::string &variableName = "");
  1711. std::string readWord(const pattern &p, const std::string &variableName = "");
  1712. std::vector<std::string>
  1713. readWords(int size, const std::string &ptrn, const std::string &variablesName = "", int indexBase = 1);
  1714. std::vector<std::string>
  1715. readWords(int size, const pattern &p, const std::string &variablesName = "", int indexBase = 1);
  1716. std::vector<std::string> readWords(int size, int indexBase = 1);
  1717. /* The same as "readToken()", but ensures that token matches to given pattern. */
  1718. std::string readToken(const std::string &ptrn, const std::string &variableName = "");
  1719. std::string readToken(const pattern &p, const std::string &variableName = "");
  1720. std::vector<std::string>
  1721. readTokens(int size, const std::string &ptrn, const std::string &variablesName = "", int indexBase = 1);
  1722. std::vector<std::string>
  1723. readTokens(int size, const pattern &p, const std::string &variablesName = "", int indexBase = 1);
  1724. std::vector<std::string> readTokens(int size, int indexBase = 1);
  1725. void readWordTo(std::string &result);
  1726. void readWordTo(std::string &result, const pattern &p, const std::string &variableName = "");
  1727. void readWordTo(std::string &result, const std::string &ptrn, const std::string &variableName = "");
  1728. void readTokenTo(std::string &result);
  1729. void readTokenTo(std::string &result, const pattern &p, const std::string &variableName = "");
  1730. void readTokenTo(std::string &result, const std::string &ptrn, const std::string &variableName = "");
  1731. /*
  1732. * Reads new long long value. Ignores white-spaces into the non-strict mode
  1733. * (strict mode is used in validators usually).
  1734. */
  1735. long long readLong();
  1736. unsigned long long readUnsignedLong();
  1737. /*
  1738. * Reads new int. Ignores white-spaces into the non-strict mode
  1739. * (strict mode is used in validators usually).
  1740. */
  1741. int readInteger();
  1742. /*
  1743. * Reads new int. Ignores white-spaces into the non-strict mode
  1744. * (strict mode is used in validators usually).
  1745. */
  1746. int readInt();
  1747. /* As "readLong()" but ensures that value in the range [minv,maxv]. */
  1748. long long readLong(long long minv, long long maxv, const std::string &variableName = "");
  1749. /* Reads space-separated sequence of long longs. */
  1750. std::vector<long long>
  1751. readLongs(int size, long long minv, long long maxv, const std::string &variablesName = "", int indexBase = 1);
  1752. /* Reads space-separated sequence of long longs. */
  1753. std::vector<long long> readLongs(int size, int indexBase = 1);
  1754. unsigned long long
  1755. readUnsignedLong(unsigned long long minv, unsigned long long maxv, const std::string &variableName = "");
  1756. std::vector<unsigned long long>
  1757. readUnsignedLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string &variablesName = "",
  1758. int indexBase = 1);
  1759. std::vector<unsigned long long> readUnsignedLongs(int size, int indexBase = 1);
  1760. unsigned long long readLong(unsigned long long minv, unsigned long long maxv, const std::string &variableName = "");
  1761. std::vector<unsigned long long>
  1762. readLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string &variablesName = "",
  1763. int indexBase = 1);
  1764. /* As "readInteger()" but ensures that value in the range [minv,maxv]. */
  1765. int readInteger(int minv, int maxv, const std::string &variableName = "");
  1766. /* As "readInt()" but ensures that value in the range [minv,maxv]. */
  1767. int readInt(int minv, int maxv, const std::string &variableName = "");
  1768. /* Reads space-separated sequence of integers. */
  1769. std::vector<int>
  1770. readIntegers(int size, int minv, int maxv, const std::string &variablesName = "", int indexBase = 1);
  1771. /* Reads space-separated sequence of integers. */
  1772. std::vector<int> readIntegers(int size, int indexBase = 1);
  1773. /* Reads space-separated sequence of integers. */
  1774. std::vector<int> readInts(int size, int minv, int maxv, const std::string &variablesName = "", int indexBase = 1);
  1775. /* Reads space-separated sequence of integers. */
  1776. std::vector<int> readInts(int size, int indexBase = 1);
  1777. /*
  1778. * Reads new double. Ignores white-spaces into the non-strict mode
  1779. * (strict mode is used in validators usually).
  1780. */
  1781. double readReal();
  1782. /*
  1783. * Reads new double. Ignores white-spaces into the non-strict mode
  1784. * (strict mode is used in validators usually).
  1785. */
  1786. double readDouble();
  1787. /* As "readReal()" but ensures that value in the range [minv,maxv]. */
  1788. double readReal(double minv, double maxv, const std::string &variableName = "");
  1789. std::vector<double>
  1790. readReals(int size, double minv, double maxv, const std::string &variablesName = "", int indexBase = 1);
  1791. std::vector<double> readReals(int size, int indexBase = 1);
  1792. /* As "readDouble()" but ensures that value in the range [minv,maxv]. */
  1793. double readDouble(double minv, double maxv, const std::string &variableName = "");
  1794. std::vector<double>
  1795. readDoubles(int size, double minv, double maxv, const std::string &variablesName = "", int indexBase = 1);
  1796. std::vector<double> readDoubles(int size, int indexBase = 1);
  1797. /*
  1798. * As "readReal()" but ensures that value in the range [minv,maxv] and
  1799. * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]
  1800. * and number is in the form "[-]digit(s)[.digit(s)]".
  1801. */
  1802. double readStrictReal(double minv, double maxv,
  1803. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  1804. const std::string &variableName = "");
  1805. std::vector<double> readStrictReals(int size, double minv, double maxv,
  1806. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  1807. const std::string &variablesName = "", int indexBase = 1);
  1808. /*
  1809. * As "readDouble()" but ensures that value in the range [minv,maxv] and
  1810. * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]
  1811. * and number is in the form "[-]digit(s)[.digit(s)]".
  1812. */
  1813. double readStrictDouble(double minv, double maxv,
  1814. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  1815. const std::string &variableName = "");
  1816. std::vector<double> readStrictDoubles(int size, double minv, double maxv,
  1817. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  1818. const std::string &variablesName = "", int indexBase = 1);
  1819. /* As readLine(). */
  1820. std::string readString();
  1821. /* Read many lines. */
  1822. std::vector<std::string> readStrings(int size, int indexBase = 1);
  1823. /* See readLine(). */
  1824. void readStringTo(std::string &result);
  1825. /* The same as "readLine()/readString()", but ensures that line matches to the given pattern. */
  1826. std::string readString(const pattern &p, const std::string &variableName = "");
  1827. /* The same as "readLine()/readString()", but ensures that line matches to the given pattern. */
  1828. std::string readString(const std::string &ptrn, const std::string &variableName = "");
  1829. /* Read many lines. */
  1830. std::vector<std::string>
  1831. readStrings(int size, const pattern &p, const std::string &variableName = "", int indexBase = 1);
  1832. /* Read many lines. */
  1833. std::vector<std::string>
  1834. readStrings(int size, const std::string &ptrn, const std::string &variableName = "", int indexBase = 1);
  1835. /* The same as "readLine()/readString()", but ensures that line matches to the given pattern. */
  1836. void readStringTo(std::string &result, const pattern &p, const std::string &variableName = "");
  1837. /* The same as "readLine()/readString()", but ensures that line matches to the given pattern. */
  1838. void readStringTo(std::string &result, const std::string &ptrn, const std::string &variableName = "");
  1839. /*
  1840. * Reads line from the current position to EOLN or EOF. Moves stream pointer to
  1841. * the first character of the new line (if possible).
  1842. */
  1843. std::string readLine();
  1844. /* Read many lines. */
  1845. std::vector<std::string> readLines(int size, int indexBase = 1);
  1846. /* See readLine(). */
  1847. void readLineTo(std::string &result);
  1848. /* The same as "readLine()", but ensures that line matches to the given pattern. */
  1849. std::string readLine(const pattern &p, const std::string &variableName = "");
  1850. /* The same as "readLine()", but ensures that line matches to the given pattern. */
  1851. std::string readLine(const std::string &ptrn, const std::string &variableName = "");
  1852. /* Read many lines. */
  1853. std::vector<std::string>
  1854. readLines(int size, const pattern &p, const std::string &variableName = "", int indexBase = 1);
  1855. /* Read many lines. */
  1856. std::vector<std::string>
  1857. readLines(int size, const std::string &ptrn, const std::string &variableName = "", int indexBase = 1);
  1858. /* The same as "readLine()", but ensures that line matches to the given pattern. */
  1859. void readLineTo(std::string &result, const pattern &p, const std::string &variableName = "");
  1860. /* The same as "readLine()", but ensures that line matches to the given pattern. */
  1861. void readLineTo(std::string &result, const std::string &ptrn, const std::string &variableName = "");
  1862. /* Reads EOLN or fails. Use it in validators. Calls "eoln()" method internally. */
  1863. void readEoln();
  1864. /* Reads EOF or fails. Use it in validators. Calls "eof()" method internally. */
  1865. void readEof();
  1866. /*
  1867. * Quit-functions aborts program with <result> and <message>:
  1868. * input/answer streams replace any result to FAIL.
  1869. */
  1870. NORETURN void quit(TResult result, const char *msg);
  1871. /*
  1872. * Quit-functions aborts program with <result> and <message>:
  1873. * input/answer streams replace any result to FAIL.
  1874. */
  1875. NORETURN void quitf(TResult result, const char *msg, ...);
  1876. /*
  1877. * Quit-functions aborts program with <result> and <message>:
  1878. * input/answer streams replace any result to FAIL.
  1879. */
  1880. void quitif(bool condition, TResult result, const char *msg, ...);
  1881. /*
  1882. * Quit-functions aborts program with <result> and <message>:
  1883. * input/answer streams replace any result to FAIL.
  1884. */
  1885. NORETURN void quits(TResult result, std::string msg);
  1886. /*
  1887. * Checks condition and aborts a program if condition is false.
  1888. * Returns _wa for ouf and _fail on any other streams.
  1889. */
  1890. #ifdef __GNUC__
  1891. __attribute__ ((format (printf, 3, 4)))
  1892. #endif
  1893. void ensuref(bool cond, const char *format, ...);
  1894. void __testlib_ensure(bool cond, std::string message);
  1895. void close();
  1896. const static int NO_INDEX = INT_MAX;
  1897. const static char OPEN_BRACKET = char(11);
  1898. const static char CLOSE_BRACKET = char(17);
  1899. const static WORD LightGray = 0x07;
  1900. const static WORD LightRed = 0x0c;
  1901. const static WORD LightCyan = 0x0b;
  1902. const static WORD LightGreen = 0x0a;
  1903. const static WORD LightYellow = 0x0e;
  1904. static void textColor(WORD color);
  1905. static void quitscr(WORD color, const char *msg);
  1906. static void quitscrS(WORD color, std::string msg);
  1907. void xmlSafeWrite(std::FILE *file, const char *msg);
  1908. /* Skips UTF-8 Byte Order Mark. */
  1909. void skipBom();
  1910. private:
  1911. InStream(const InStream &);
  1912. InStream &operator=(const InStream &);
  1913. };
  1914. InStream inf;
  1915. InStream ouf;
  1916. InStream ans;
  1917. bool appesMode;
  1918. std::string appesModeEncoding = "windows-1251";
  1919. std::string resultName;
  1920. std::string checkerName = "untitled checker";
  1921. random_t rnd;
  1922. TTestlibMode testlibMode = _unknown;
  1923. double __testlib_points = std::numeric_limits<float>::infinity();
  1924. struct ValidatorBoundsHit {
  1925. static const double EPS;
  1926. bool minHit;
  1927. bool maxHit;
  1928. ValidatorBoundsHit(bool minHit = false, bool maxHit = false) : minHit(minHit), maxHit(maxHit) {
  1929. };
  1930. ValidatorBoundsHit merge(const ValidatorBoundsHit &validatorBoundsHit) {
  1931. return ValidatorBoundsHit(
  1932. __testlib_max(minHit, validatorBoundsHit.minHit),
  1933. __testlib_max(maxHit, validatorBoundsHit.maxHit)
  1934. );
  1935. }
  1936. };
  1937. const double ValidatorBoundsHit::EPS = 1E-12;
  1938. class Validator {
  1939. private:
  1940. const static std::string TEST_MARKUP_HEADER;
  1941. const static std::string TEST_CASE_OPEN_TAG;
  1942. const static std::string TEST_CASE_CLOSE_TAG;
  1943. bool _initialized;
  1944. std::string _testset;
  1945. std::string _group;
  1946. std::string _testOverviewLogFileName;
  1947. std::string _testMarkupFileName;
  1948. int _testCase = -1;
  1949. std::string _testCaseFileName;
  1950. std::map<std::string, ValidatorBoundsHit> _boundsHitByVariableName;
  1951. std::set<std::string> _features;
  1952. std::set<std::string> _hitFeatures;
  1953. bool isVariableNameBoundsAnalyzable(const std::string &variableName) {
  1954. for (size_t i = 0; i < variableName.length(); i++)
  1955. if ((variableName[i] >= '0' && variableName[i] <= '9') || variableName[i] < ' ')
  1956. return false;
  1957. return true;
  1958. }
  1959. bool isFeatureNameAnalyzable(const std::string &featureName) {
  1960. for (size_t i = 0; i < featureName.length(); i++)
  1961. if (featureName[i] < ' ')
  1962. return false;
  1963. return true;
  1964. }
  1965. public:
  1966. Validator() : _initialized(false), _testset("tests"), _group() {
  1967. }
  1968. void initialize() {
  1969. _initialized = true;
  1970. }
  1971. std::string testset() const {
  1972. if (!_initialized)
  1973. __testlib_fail("Validator should be initialized with registerValidation(argc, argv) instead of registerValidation() to support validator.testset()");
  1974. return _testset;
  1975. }
  1976. std::string group() const {
  1977. if (!_initialized)
  1978. __testlib_fail("Validator should be initialized with registerValidation(argc, argv) instead of registerValidation() to support validator.group()");
  1979. return _group;
  1980. }
  1981. std::string testOverviewLogFileName() const {
  1982. return _testOverviewLogFileName;
  1983. }
  1984. std::string testMarkupFileName() const {
  1985. return _testMarkupFileName;
  1986. }
  1987. int testCase() const {
  1988. return _testCase;
  1989. }
  1990. std::string testCaseFileName() const {
  1991. return _testCaseFileName;
  1992. }
  1993. void setTestset(const char *const testset) {
  1994. _testset = testset;
  1995. }
  1996. void setGroup(const char *const group) {
  1997. _group = group;
  1998. }
  1999. void setTestOverviewLogFileName(const char *const testOverviewLogFileName) {
  2000. _testOverviewLogFileName = testOverviewLogFileName;
  2001. }
  2002. void setTestMarkupFileName(const char *const testMarkupFileName) {
  2003. _testMarkupFileName = testMarkupFileName;
  2004. }
  2005. void setTestCase(int testCase) {
  2006. _testCase = testCase;
  2007. }
  2008. void setTestCaseFileName(const char *const testCaseFileName) {
  2009. _testCaseFileName = testCaseFileName;
  2010. }
  2011. void addBoundsHit(const std::string &variableName, ValidatorBoundsHit boundsHit) {
  2012. if (isVariableNameBoundsAnalyzable(variableName)) {
  2013. _boundsHitByVariableName[variableName]
  2014. = boundsHit.merge(_boundsHitByVariableName[variableName]);
  2015. }
  2016. }
  2017. std::string getBoundsHitLog() {
  2018. std::string result;
  2019. for (std::map<std::string, ValidatorBoundsHit>::iterator i = _boundsHitByVariableName.begin();
  2020. i != _boundsHitByVariableName.end();
  2021. i++) {
  2022. result += "\"" + i->first + "\":";
  2023. if (i->second.minHit)
  2024. result += " min-value-hit";
  2025. if (i->second.maxHit)
  2026. result += " max-value-hit";
  2027. result += "\n";
  2028. }
  2029. return result;
  2030. }
  2031. std::string getFeaturesLog() {
  2032. std::string result;
  2033. for (std::set<std::string>::iterator i = _features.begin();
  2034. i != _features.end();
  2035. i++) {
  2036. result += "feature \"" + *i + "\":";
  2037. if (_hitFeatures.count(*i))
  2038. result += " hit";
  2039. result += "\n";
  2040. }
  2041. return result;
  2042. }
  2043. void writeTestOverviewLog() {
  2044. if (!_testOverviewLogFileName.empty()) {
  2045. std::string fileName(_testOverviewLogFileName);
  2046. _testOverviewLogFileName = "";
  2047. FILE *testOverviewLogFile = fopen(fileName.c_str(), "w");
  2048. if (NULL == testOverviewLogFile)
  2049. __testlib_fail("Validator::writeTestOverviewLog: can't write test overview log to (" + fileName + ")");
  2050. fprintf(testOverviewLogFile, "%s%s", getBoundsHitLog().c_str(), getFeaturesLog().c_str());
  2051. if (fclose(testOverviewLogFile))
  2052. __testlib_fail(
  2053. "Validator::writeTestOverviewLog: can't close test overview log file (" + fileName + ")");
  2054. }
  2055. }
  2056. void writeTestMarkup() {
  2057. if (!_testMarkupFileName.empty()) {
  2058. std::vector<int> readChars = inf.getReadChars();
  2059. if (!readChars.empty()) {
  2060. std::string markup(TEST_MARKUP_HEADER);
  2061. for (size_t i = 0; i < readChars.size(); i++) {
  2062. int c = readChars[i];
  2063. if (i + 1 == readChars.size() && c == -1)
  2064. continue;
  2065. if (c <= 256) {
  2066. char cc = char(c);
  2067. if (cc == '\\' || cc == '!')
  2068. markup += '\\';
  2069. markup += cc;
  2070. } else {
  2071. markup += TEST_CASE_OPEN_TAG;
  2072. markup += toString(c - 256);
  2073. markup += TEST_CASE_CLOSE_TAG;
  2074. }
  2075. }
  2076. FILE* f;
  2077. bool standard_file = false;
  2078. if (_testMarkupFileName == "stdout")
  2079. f = stdout, standard_file = true;
  2080. else if (_testMarkupFileName == "stderr")
  2081. f = stderr, standard_file = true;
  2082. else {
  2083. f = fopen(_testMarkupFileName.c_str(), "wb");
  2084. if (NULL == f)
  2085. __testlib_fail("Validator::writeTestMarkup: can't write test markup to (" + _testMarkupFileName + ")");
  2086. }
  2087. std::fprintf(f, "%s", markup.c_str());
  2088. std::fflush(f);
  2089. if (!standard_file)
  2090. if (std::fclose(f))
  2091. __testlib_fail("Validator::writeTestMarkup: can't close test markup file (" + _testCaseFileName + ")");
  2092. }
  2093. }
  2094. }
  2095. void writeTestCase() {
  2096. if (_testCase > 0) {
  2097. std::vector<int> readChars = inf.getReadChars();
  2098. if (!readChars.empty()) {
  2099. std::string content, testCaseContent;
  2100. bool matchedTestCase = false;
  2101. for (size_t i = 0; i < readChars.size(); i++) {
  2102. int c = readChars[i];
  2103. if (i + 1 == readChars.size() && c == -1)
  2104. continue;
  2105. if (c <= 256)
  2106. content += char(c);
  2107. else {
  2108. if (matchedTestCase) {
  2109. testCaseContent = content;
  2110. matchedTestCase = false;
  2111. }
  2112. content = "";
  2113. int testCase = c - 256;
  2114. if (testCase == _testCase)
  2115. matchedTestCase = true;
  2116. }
  2117. }
  2118. if (matchedTestCase)
  2119. testCaseContent = content;
  2120. if (!testCaseContent.empty()) {
  2121. FILE* f;
  2122. bool standard_file = false;
  2123. if (_testCaseFileName.empty() || _testCaseFileName == "stdout")
  2124. f = stdout, standard_file = true;
  2125. else if (_testCaseFileName == "stderr")
  2126. f = stderr, standard_file = true;
  2127. else {
  2128. f = fopen(_testCaseFileName.c_str(), "wb");
  2129. if (NULL == f)
  2130. __testlib_fail("Validator::writeTestCase: can't write test case to (" + _testCaseFileName + ")");
  2131. }
  2132. std::fprintf(f, "%s", testCaseContent.c_str());
  2133. std::fflush(f);
  2134. if (!standard_file)
  2135. if (std::fclose(f))
  2136. __testlib_fail("Validator::writeTestCase: can't close test case file (" + _testCaseFileName + ")");
  2137. }
  2138. }
  2139. }
  2140. }
  2141. void addFeature(const std::string &feature) {
  2142. if (_features.count(feature))
  2143. __testlib_fail("Feature " + feature + " registered twice.");
  2144. if (!isFeatureNameAnalyzable(feature))
  2145. __testlib_fail("Feature name '" + feature + "' contains restricted characters.");
  2146. _features.insert(feature);
  2147. }
  2148. void feature(const std::string &feature) {
  2149. if (!isFeatureNameAnalyzable(feature))
  2150. __testlib_fail("Feature name '" + feature + "' contains restricted characters.");
  2151. if (!_features.count(feature))
  2152. __testlib_fail("Feature " + feature + " didn't registered via addFeature(feature).");
  2153. _hitFeatures.insert(feature);
  2154. }
  2155. } validator;
  2156. const std::string Validator::TEST_MARKUP_HEADER = "MU\xF3\x01";
  2157. const std::string Validator::TEST_CASE_OPEN_TAG = "!c";
  2158. const std::string Validator::TEST_CASE_CLOSE_TAG = ";";
  2159. struct TestlibFinalizeGuard {
  2160. static bool alive;
  2161. static bool registered;
  2162. int quitCount, readEofCount;
  2163. TestlibFinalizeGuard() : quitCount(0), readEofCount(0) {
  2164. // No operations.
  2165. }
  2166. ~TestlibFinalizeGuard() {
  2167. bool _alive = alive;
  2168. alive = false;
  2169. if (_alive) {
  2170. if (testlibMode == _checker && quitCount == 0)
  2171. __testlib_fail("Checker must end with quit or quitf call.");
  2172. if (testlibMode == _validator && readEofCount == 0 && quitCount == 0)
  2173. __testlib_fail("Validator must end with readEof call.");
  2174. /* opts */
  2175. autoEnsureNoUnusedOpts();
  2176. if (!registered)
  2177. __testlib_fail("Call register-function in the first line of the main (registerTestlibCmd or other similar)");
  2178. }
  2179. if (__testlib_exitCode == 0) {
  2180. validator.writeTestOverviewLog();
  2181. validator.writeTestMarkup();
  2182. validator.writeTestCase();
  2183. }
  2184. }
  2185. private:
  2186. /* opts */
  2187. void autoEnsureNoUnusedOpts();
  2188. };
  2189. bool TestlibFinalizeGuard::alive = true;
  2190. bool TestlibFinalizeGuard::registered = false;
  2191. extern TestlibFinalizeGuard testlibFinalizeGuard;
  2192. /*
  2193. * Call it to disable checks on finalization.
  2194. */
  2195. void disableFinalizeGuard() {
  2196. TestlibFinalizeGuard::alive = false;
  2197. }
  2198. /* Interactor streams.
  2199. */
  2200. std::fstream tout;
  2201. /* implementation
  2202. */
  2203. InStream::InStream() {
  2204. reader = NULL;
  2205. lastLine = -1;
  2206. opened = false;
  2207. name = "";
  2208. mode = _input;
  2209. strict = false;
  2210. stdfile = false;
  2211. wordReserveSize = 4;
  2212. readManyIteration = NO_INDEX;
  2213. maxFileSize = 128 * 1024 * 1024; // 128MB.
  2214. maxTokenLength = 32 * 1024 * 1024; // 32MB.
  2215. maxMessageLength = 32000;
  2216. }
  2217. InStream::InStream(const InStream &baseStream, std::string content) {
  2218. reader = new StringInputStreamReader(content);
  2219. lastLine = -1;
  2220. opened = true;
  2221. strict = baseStream.strict;
  2222. stdfile = false;
  2223. mode = baseStream.mode;
  2224. name = "based on " + baseStream.name;
  2225. readManyIteration = NO_INDEX;
  2226. maxFileSize = 128 * 1024 * 1024; // 128MB.
  2227. maxTokenLength = 32 * 1024 * 1024; // 32MB.
  2228. maxMessageLength = 32000;
  2229. }
  2230. InStream::~InStream() {
  2231. if (NULL != reader) {
  2232. reader->close();
  2233. delete reader;
  2234. reader = NULL;
  2235. }
  2236. }
  2237. void InStream::setTestCase(int testCase) {
  2238. if (testlibMode != _validator || mode != _input || !stdfile || this != &inf)
  2239. __testlib_fail("InStream::setTestCase can be used only for inf in validator-mode."
  2240. " Actually, prefer setTestCase function instead of InStream member");
  2241. reader->setTestCase(testCase);
  2242. }
  2243. std::vector<int> InStream::getReadChars() {
  2244. if (testlibMode != _validator || mode != _input || !stdfile || this != &inf)
  2245. __testlib_fail("InStream::getReadChars can be used only for inf in validator-mode.");
  2246. return reader == NULL ? std::vector<int>() : reader->getReadChars();
  2247. }
  2248. void setTestCase(int testCase) {
  2249. static bool first_run = true;
  2250. static bool zero_based = false;
  2251. if (first_run && testCase == 0)
  2252. zero_based = true;
  2253. if (zero_based)
  2254. testCase++;
  2255. __testlib_hasTestCase = true;
  2256. __testlib_testCase = testCase;
  2257. if (testlibMode == _validator)
  2258. inf.setTestCase(testCase);
  2259. first_run = false;
  2260. }
  2261. #ifdef __GNUC__
  2262. __attribute__((const))
  2263. #endif
  2264. int resultExitCode(TResult r) {
  2265. if (r == _ok)
  2266. return OK_EXIT_CODE;
  2267. if (r == _wa)
  2268. return WA_EXIT_CODE;
  2269. if (r == _pe)
  2270. return PE_EXIT_CODE;
  2271. if (r == _fail)
  2272. return FAIL_EXIT_CODE;
  2273. if (r == _dirt)
  2274. return DIRT_EXIT_CODE;
  2275. if (r == _points)
  2276. return POINTS_EXIT_CODE;
  2277. if (r == _unexpected_eof)
  2278. #ifdef ENABLE_UNEXPECTED_EOF
  2279. return UNEXPECTED_EOF_EXIT_CODE;
  2280. #else
  2281. return PE_EXIT_CODE;
  2282. #endif
  2283. if (r >= _partially)
  2284. return PC_BASE_EXIT_CODE + (r - _partially);
  2285. return FAIL_EXIT_CODE;
  2286. }
  2287. void InStream::textColor(
  2288. #if !(defined(ON_WINDOWS) && (!defined(_MSC_VER) || _MSC_VER > 1400)) && defined(__GNUC__)
  2289. __attribute__((unused))
  2290. #endif
  2291. WORD color
  2292. ) {
  2293. #if defined(ON_WINDOWS) && (!defined(_MSC_VER) || _MSC_VER > 1400)
  2294. HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
  2295. SetConsoleTextAttribute(handle, color);
  2296. #endif
  2297. #if !defined(ON_WINDOWS) && defined(__GNUC__)
  2298. if (isatty(2))
  2299. {
  2300. switch (color)
  2301. {
  2302. case LightRed:
  2303. fprintf(stderr, "\033[1;31m");
  2304. break;
  2305. case LightCyan:
  2306. fprintf(stderr, "\033[1;36m");
  2307. break;
  2308. case LightGreen:
  2309. fprintf(stderr, "\033[1;32m");
  2310. break;
  2311. case LightYellow:
  2312. fprintf(stderr, "\033[1;33m");
  2313. break;
  2314. case LightGray:
  2315. default:
  2316. fprintf(stderr, "\033[0m");
  2317. }
  2318. }
  2319. #endif
  2320. }
  2321. #ifdef TESTLIB_THROW_EXIT_EXCEPTION_INSTEAD_OF_EXIT
  2322. class exit_exception: public std::exception {
  2323. private:
  2324. int exitCode;
  2325. public:
  2326. exit_exception(int exitCode): exitCode(exitCode) {}
  2327. int getExitCode() { return exitCode; }
  2328. };
  2329. #endif
  2330. NORETURN void halt(int exitCode) {
  2331. #ifdef FOOTER
  2332. InStream::textColor(InStream::LightGray);
  2333. std::fprintf(stderr, "Checker: \"%s\"\n", checkerName.c_str());
  2334. std::fprintf(stderr, "Exit code: %d\n", exitCode);
  2335. InStream::textColor(InStream::LightGray);
  2336. #endif
  2337. __testlib_exitCode = exitCode;
  2338. #ifdef TESTLIB_THROW_EXIT_EXCEPTION_INSTEAD_OF_EXIT
  2339. throw exit_exception(exitCode);
  2340. #endif
  2341. std::exit(exitCode);
  2342. }
  2343. static bool __testlib_shouldCheckDirt(TResult result) {
  2344. return result == _ok || result == _points || result >= _partially;
  2345. }
  2346. static std::string __testlib_appendMessage(const std::string &message, const std::string &extra) {
  2347. int openPos = -1, closePos = -1;
  2348. for (size_t i = 0; i < message.length(); i++) {
  2349. if (message[i] == InStream::OPEN_BRACKET) {
  2350. if (openPos == -1)
  2351. openPos = int(i);
  2352. else
  2353. openPos = INT_MAX;
  2354. }
  2355. if (message[i] == InStream::CLOSE_BRACKET) {
  2356. if (closePos == -1)
  2357. closePos = int(i);
  2358. else
  2359. closePos = INT_MAX;
  2360. }
  2361. }
  2362. if (openPos != -1 && openPos != INT_MAX
  2363. && closePos != -1 && closePos != INT_MAX
  2364. && openPos < closePos) {
  2365. size_t index = message.find(extra, openPos);
  2366. if (index == std::string::npos || int(index) >= closePos) {
  2367. std::string result(message);
  2368. result.insert(closePos, ", " + extra);
  2369. return result;
  2370. }
  2371. return message;
  2372. }
  2373. return message + " " + InStream::OPEN_BRACKET + extra + InStream::CLOSE_BRACKET;
  2374. }
  2375. static std::string __testlib_toPrintableMessage(const std::string &message) {
  2376. int openPos = -1, closePos = -1;
  2377. for (size_t i = 0; i < message.length(); i++) {
  2378. if (message[i] == InStream::OPEN_BRACKET) {
  2379. if (openPos == -1)
  2380. openPos = int(i);
  2381. else
  2382. openPos = INT_MAX;
  2383. }
  2384. if (message[i] == InStream::CLOSE_BRACKET) {
  2385. if (closePos == -1)
  2386. closePos = int(i);
  2387. else
  2388. closePos = INT_MAX;
  2389. }
  2390. }
  2391. if (openPos != -1 && openPos != INT_MAX
  2392. && closePos != -1 && closePos != INT_MAX
  2393. && openPos < closePos) {
  2394. std::string result(message);
  2395. result[openPos] = '(';
  2396. result[closePos] = ')';
  2397. return result;
  2398. }
  2399. return message;
  2400. }
  2401. NORETURN void InStream::quit(TResult result, const char *msg) {
  2402. if (TestlibFinalizeGuard::alive)
  2403. testlibFinalizeGuard.quitCount++;
  2404. std::string message(msg);
  2405. message = trim(message);
  2406. if (__testlib_hasTestCase) {
  2407. if (result != _ok)
  2408. message = __testlib_appendMessage(message, "test case " + vtos(__testlib_testCase));
  2409. else {
  2410. if (__testlib_testCase == 1)
  2411. message = __testlib_appendMessage(message, vtos(__testlib_testCase) + " test case");
  2412. else
  2413. message = __testlib_appendMessage(message, vtos(__testlib_testCase) + " test cases");
  2414. }
  2415. }
  2416. // You can change maxMessageLength.
  2417. // Example: 'inf.maxMessageLength = 1024 * 1024;'.
  2418. if (message.length() > maxMessageLength) {
  2419. std::string warn = "message length exceeds " + vtos(maxMessageLength)
  2420. + ", the message is truncated: ";
  2421. message = warn + message.substr(0, maxMessageLength - warn.length());
  2422. }
  2423. #ifndef ENABLE_UNEXPECTED_EOF
  2424. if (result == _unexpected_eof)
  2425. result = _pe;
  2426. #endif
  2427. if (testlibMode == _scorer && result != _fail)
  2428. quits(_fail, "Scorer should return points only. Don't use a quit function.");
  2429. if (mode != _output && result != _fail) {
  2430. if (mode == _input && testlibMode == _validator && lastLine != -1)
  2431. quits(_fail, __testlib_appendMessage(__testlib_appendMessage(message, name), "line " + vtos(lastLine)));
  2432. else
  2433. quits(_fail, __testlib_appendMessage(message, name));
  2434. }
  2435. std::FILE *resultFile;
  2436. std::string errorName;
  2437. if (__testlib_shouldCheckDirt(result)) {
  2438. if (testlibMode != _interactor && !ouf.seekEof())
  2439. quit(_dirt, "Extra information in the output file");
  2440. }
  2441. int pctype = result - _partially;
  2442. bool isPartial = false;
  2443. switch (result) {
  2444. case _ok:
  2445. errorName = "ok ";
  2446. quitscrS(LightGreen, errorName);
  2447. break;
  2448. case _wa:
  2449. errorName = "wrong answer ";
  2450. quitscrS(LightRed, errorName);
  2451. break;
  2452. case _pe:
  2453. errorName = "wrong output format ";
  2454. quitscrS(LightRed, errorName);
  2455. break;
  2456. case _fail:
  2457. errorName = "FAIL ";
  2458. quitscrS(LightRed, errorName);
  2459. break;
  2460. case _dirt:
  2461. errorName = "wrong output format ";
  2462. quitscrS(LightCyan, errorName);
  2463. result = _pe;
  2464. break;
  2465. case _points:
  2466. errorName = "points ";
  2467. quitscrS(LightYellow, errorName);
  2468. break;
  2469. case _unexpected_eof:
  2470. errorName = "unexpected eof ";
  2471. quitscrS(LightCyan, errorName);
  2472. break;
  2473. default:
  2474. if (result >= _partially) {
  2475. errorName = format("partially correct (%d) ", pctype);
  2476. isPartial = true;
  2477. quitscrS(LightYellow, errorName);
  2478. } else
  2479. quit(_fail, "What is the code ??? ");
  2480. }
  2481. if (resultName != "") {
  2482. resultFile = std::fopen(resultName.c_str(), "w");
  2483. if (resultFile == NULL) {
  2484. resultName = "";
  2485. quit(_fail, "Can not write to the result file");
  2486. }
  2487. if (appesMode) {
  2488. std::fprintf(resultFile, "<?xml version=\"1.0\" encoding=\"%s\"?>", appesModeEncoding.c_str());
  2489. if (isPartial)
  2490. std::fprintf(resultFile, "<result outcome = \"%s\" pctype = \"%d\">",
  2491. outcomes[(int) _partially].c_str(), pctype);
  2492. else {
  2493. if (result != _points)
  2494. std::fprintf(resultFile, "<result outcome = \"%s\">", outcomes[(int) result].c_str());
  2495. else {
  2496. if (__testlib_points == std::numeric_limits<float>::infinity())
  2497. quit(_fail, "Expected points, but infinity found");
  2498. std::string stringPoints = removeDoubleTrailingZeroes(format("%.10f", __testlib_points));
  2499. std::fprintf(resultFile, "<result outcome = \"%s\" points = \"%s\">",
  2500. outcomes[(int) result].c_str(), stringPoints.c_str());
  2501. }
  2502. }
  2503. xmlSafeWrite(resultFile, __testlib_toPrintableMessage(message).c_str());
  2504. std::fprintf(resultFile, "</result>\n");
  2505. } else
  2506. std::fprintf(resultFile, "%s", __testlib_toPrintableMessage(message).c_str());
  2507. if (NULL == resultFile || fclose(resultFile) != 0) {
  2508. resultName = "";
  2509. quit(_fail, "Can not write to the result file");
  2510. }
  2511. }
  2512. quitscr(LightGray, __testlib_toPrintableMessage(message).c_str());
  2513. std::fprintf(stderr, "\n");
  2514. inf.close();
  2515. ouf.close();
  2516. ans.close();
  2517. if (tout.is_open())
  2518. tout.close();
  2519. textColor(LightGray);
  2520. if (resultName != "")
  2521. std::fprintf(stderr, "See file to check exit message\n");
  2522. halt(resultExitCode(result));
  2523. }
  2524. #ifdef __GNUC__
  2525. __attribute__ ((format (printf, 3, 4)))
  2526. #endif
  2527. NORETURN void InStream::quitf(TResult result, const char *msg, ...) {
  2528. FMT_TO_RESULT(msg, msg, message);
  2529. InStream::quit(result, message.c_str());
  2530. }
  2531. #ifdef __GNUC__
  2532. __attribute__ ((format (printf, 4, 5)))
  2533. #endif
  2534. void InStream::quitif(bool condition, TResult result, const char *msg, ...) {
  2535. if (condition) {
  2536. FMT_TO_RESULT(msg, msg, message);
  2537. InStream::quit(result, message.c_str());
  2538. }
  2539. }
  2540. NORETURN void InStream::quits(TResult result, std::string msg) {
  2541. InStream::quit(result, msg.c_str());
  2542. }
  2543. void InStream::xmlSafeWrite(std::FILE *file, const char *msg) {
  2544. size_t lmsg = strlen(msg);
  2545. for (size_t i = 0; i < lmsg; i++) {
  2546. if (msg[i] == '&') {
  2547. std::fprintf(file, "%s", "&amp;");
  2548. continue;
  2549. }
  2550. if (msg[i] == '<') {
  2551. std::fprintf(file, "%s", "&lt;");
  2552. continue;
  2553. }
  2554. if (msg[i] == '>') {
  2555. std::fprintf(file, "%s", "&gt;");
  2556. continue;
  2557. }
  2558. if (msg[i] == '"') {
  2559. std::fprintf(file, "%s", "&quot;");
  2560. continue;
  2561. }
  2562. if (0 <= msg[i] && msg[i] <= 31) {
  2563. std::fprintf(file, "%c", '.');
  2564. continue;
  2565. }
  2566. std::fprintf(file, "%c", msg[i]);
  2567. }
  2568. }
  2569. void InStream::quitscrS(WORD color, std::string msg) {
  2570. quitscr(color, msg.c_str());
  2571. }
  2572. void InStream::quitscr(WORD color, const char *msg) {
  2573. if (resultName == "") {
  2574. textColor(color);
  2575. std::fprintf(stderr, "%s", msg);
  2576. textColor(LightGray);
  2577. }
  2578. }
  2579. void InStream::reset(std::FILE *file) {
  2580. if (opened && stdfile)
  2581. quit(_fail, "Can't reset standard handle");
  2582. if (opened)
  2583. close();
  2584. if (!stdfile && NULL == file)
  2585. if (NULL == (file = std::fopen(name.c_str(), "rb"))) {
  2586. if (mode == _output)
  2587. quits(_pe, std::string("Output file not found: \"") + name + "\"");
  2588. if (mode == _answer)
  2589. quits(_fail, std::string("Answer file not found: \"") + name + "\"");
  2590. }
  2591. if (NULL != file) {
  2592. opened = true;
  2593. __testlib_set_binary(file);
  2594. if (stdfile)
  2595. reader = new FileInputStreamReader(file, name);
  2596. else
  2597. reader = new BufferedFileInputStreamReader(file, name);
  2598. } else {
  2599. opened = false;
  2600. reader = NULL;
  2601. }
  2602. }
  2603. void InStream::init(std::string fileName, TMode mode) {
  2604. opened = false;
  2605. name = fileName;
  2606. stdfile = false;
  2607. this->mode = mode;
  2608. std::ifstream stream;
  2609. stream.open(fileName.c_str(), std::ios::in);
  2610. if (stream.is_open()) {
  2611. std::streampos start = stream.tellg();
  2612. stream.seekg(0, std::ios::end);
  2613. std::streampos end = stream.tellg();
  2614. size_t fileSize = size_t(end - start);
  2615. stream.close();
  2616. // You can change maxFileSize.
  2617. // Example: 'inf.maxFileSize = 256 * 1024 * 1024;'.
  2618. if (fileSize > maxFileSize)
  2619. quitf(_pe, "File size exceeds %d bytes, size is %d", int(maxFileSize), int(fileSize));
  2620. }
  2621. reset();
  2622. skipBom();
  2623. }
  2624. void InStream::init(std::FILE *f, TMode mode) {
  2625. opened = false;
  2626. name = "untitled";
  2627. this->mode = mode;
  2628. if (f == stdin)
  2629. name = "stdin", stdfile = true;
  2630. if (f == stdout)
  2631. name = "stdout", stdfile = true;
  2632. if (f == stderr)
  2633. name = "stderr", stdfile = true;
  2634. reset(f);
  2635. skipBom();
  2636. }
  2637. void InStream::skipBom() {
  2638. const std::string utf8Bom = "\xEF\xBB\xBF";
  2639. size_t index = 0;
  2640. while (index < utf8Bom.size() && curChar() == utf8Bom[index]) {
  2641. index++;
  2642. skipChar();
  2643. }
  2644. if (index < utf8Bom.size()) {
  2645. while (index != 0) {
  2646. unreadChar(utf8Bom[index - 1]);
  2647. index--;
  2648. }
  2649. }
  2650. }
  2651. char InStream::curChar() {
  2652. return char(reader->curChar());
  2653. }
  2654. char InStream::nextChar() {
  2655. return char(reader->nextChar());
  2656. }
  2657. char InStream::readChar() {
  2658. return nextChar();
  2659. }
  2660. char InStream::readChar(char c) {
  2661. lastLine = reader->getLine();
  2662. char found = readChar();
  2663. if (c != found) {
  2664. if (!isEoln(found))
  2665. quit(_pe, ("Unexpected character '" + std::string(1, found) + "', but '" + std::string(1, c) +
  2666. "' expected").c_str());
  2667. else
  2668. quit(_pe, ("Unexpected character " + ("#" + vtos(int(found))) + ", but '" + std::string(1, c) +
  2669. "' expected").c_str());
  2670. }
  2671. return found;
  2672. }
  2673. char InStream::readSpace() {
  2674. return readChar(' ');
  2675. }
  2676. void InStream::unreadChar(char c) {
  2677. reader->unreadChar(c);
  2678. }
  2679. void InStream::skipChar() {
  2680. reader->skipChar();
  2681. }
  2682. void InStream::skipBlanks() {
  2683. while (isBlanks(reader->curChar()))
  2684. reader->skipChar();
  2685. }
  2686. std::string InStream::readWord() {
  2687. readWordTo(_tmpReadToken);
  2688. return _tmpReadToken;
  2689. }
  2690. void InStream::readWordTo(std::string &result) {
  2691. if (!strict)
  2692. skipBlanks();
  2693. lastLine = reader->getLine();
  2694. int cur = reader->nextChar();
  2695. if (cur == EOFC)
  2696. quit(_unexpected_eof, "Unexpected end of file - token expected");
  2697. if (isBlanks(cur))
  2698. quit(_pe, "Unexpected white-space - token expected");
  2699. result.clear();
  2700. while (!(isBlanks(cur) || cur == EOFC)) {
  2701. result += char(cur);
  2702. // You can change maxTokenLength.
  2703. // Example: 'inf.maxTokenLength = 128 * 1024 * 1024;'.
  2704. if (result.length() > maxTokenLength)
  2705. quitf(_pe, "Length of token exceeds %d, token is '%s...'", int(maxTokenLength),
  2706. __testlib_part(result).c_str());
  2707. cur = reader->nextChar();
  2708. }
  2709. reader->unreadChar(cur);
  2710. if (result.length() == 0)
  2711. quit(_unexpected_eof, "Unexpected end of file or white-space - token expected");
  2712. }
  2713. std::string InStream::readToken() {
  2714. return readWord();
  2715. }
  2716. void InStream::readTokenTo(std::string &result) {
  2717. readWordTo(result);
  2718. }
  2719. static std::string __testlib_part(const std::string &s) {
  2720. std::string t;
  2721. for (size_t i = 0; i < s.length(); i++)
  2722. if (s[i] != '\0')
  2723. t += s[i];
  2724. else
  2725. t += '~';
  2726. if (t.length() <= 64)
  2727. return t;
  2728. else
  2729. return t.substr(0, 30) + "..." + t.substr(s.length() - 31, 31);
  2730. }
  2731. #define __testlib_readMany(readMany, readOne, typeName, space) \
  2732. if (size < 0) \
  2733. quit(_fail, #readMany ": size should be non-negative."); \
  2734. if (size > 100000000) \
  2735. quit(_fail, #readMany ": size should be at most 100000000."); \
  2736. \
  2737. std::vector<typeName> result(size); \
  2738. readManyIteration = indexBase; \
  2739. \
  2740. for (int i = 0; i < size; i++) \
  2741. { \
  2742. result[i] = readOne; \
  2743. readManyIteration++; \
  2744. if (strict && space && i + 1 < size) \
  2745. readSpace(); \
  2746. } \
  2747. \
  2748. readManyIteration = NO_INDEX; \
  2749. return result; \
  2750. std::string InStream::readWord(const pattern &p, const std::string &variableName) {
  2751. readWordTo(_tmpReadToken);
  2752. if (!p.matches(_tmpReadToken)) {
  2753. if (readManyIteration == NO_INDEX) {
  2754. if (variableName.empty())
  2755. quit(_wa,
  2756. ("Token \"" + __testlib_part(_tmpReadToken) + "\" doesn't correspond to pattern \"" + p.src() +
  2757. "\"").c_str());
  2758. else
  2759. quit(_wa, ("Token parameter [name=" + variableName + "] equals to \"" + __testlib_part(_tmpReadToken) +
  2760. "\", doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  2761. } else {
  2762. if (variableName.empty())
  2763. quit(_wa, ("Token element [index=" + vtos(readManyIteration) + "] equals to \"" +
  2764. __testlib_part(_tmpReadToken) + "\" doesn't correspond to pattern \"" + p.src() +
  2765. "\"").c_str());
  2766. else
  2767. quit(_wa, ("Token element " + variableName + "[" + vtos(readManyIteration) + "] equals to \"" +
  2768. __testlib_part(_tmpReadToken) + "\", doesn't correspond to pattern \"" + p.src() +
  2769. "\"").c_str());
  2770. }
  2771. }
  2772. return _tmpReadToken;
  2773. }
  2774. std::vector<std::string>
  2775. InStream::readWords(int size, const pattern &p, const std::string &variablesName, int indexBase) {
  2776. __testlib_readMany(readWords, readWord(p, variablesName), std::string, true);
  2777. }
  2778. std::vector<std::string> InStream::readWords(int size, int indexBase) {
  2779. __testlib_readMany(readWords, readWord(), std::string, true);
  2780. }
  2781. std::string InStream::readWord(const std::string &ptrn, const std::string &variableName) {
  2782. return readWord(pattern(ptrn), variableName);
  2783. }
  2784. std::vector<std::string>
  2785. InStream::readWords(int size, const std::string &ptrn, const std::string &variablesName, int indexBase) {
  2786. pattern p(ptrn);
  2787. __testlib_readMany(readWords, readWord(p, variablesName), std::string, true);
  2788. }
  2789. std::string InStream::readToken(const pattern &p, const std::string &variableName) {
  2790. return readWord(p, variableName);
  2791. }
  2792. std::vector<std::string>
  2793. InStream::readTokens(int size, const pattern &p, const std::string &variablesName, int indexBase) {
  2794. __testlib_readMany(readTokens, readToken(p, variablesName), std::string, true);
  2795. }
  2796. std::vector<std::string> InStream::readTokens(int size, int indexBase) {
  2797. __testlib_readMany(readTokens, readToken(), std::string, true);
  2798. }
  2799. std::string InStream::readToken(const std::string &ptrn, const std::string &variableName) {
  2800. return readWord(ptrn, variableName);
  2801. }
  2802. std::vector<std::string>
  2803. InStream::readTokens(int size, const std::string &ptrn, const std::string &variablesName, int indexBase) {
  2804. pattern p(ptrn);
  2805. __testlib_readMany(readTokens, readWord(p, variablesName), std::string, true);
  2806. }
  2807. void InStream::readWordTo(std::string &result, const pattern &p, const std::string &variableName) {
  2808. readWordTo(result);
  2809. if (!p.matches(result)) {
  2810. if (variableName.empty())
  2811. quit(_wa, ("Token \"" + __testlib_part(result) + "\" doesn't correspond to pattern \"" + p.src() +
  2812. "\"").c_str());
  2813. else
  2814. quit(_wa, ("Token parameter [name=" + variableName + "] equals to \"" + __testlib_part(result) +
  2815. "\", doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  2816. }
  2817. }
  2818. void InStream::readWordTo(std::string &result, const std::string &ptrn, const std::string &variableName) {
  2819. return readWordTo(result, pattern(ptrn), variableName);
  2820. }
  2821. void InStream::readTokenTo(std::string &result, const pattern &p, const std::string &variableName) {
  2822. return readWordTo(result, p, variableName);
  2823. }
  2824. void InStream::readTokenTo(std::string &result, const std::string &ptrn, const std::string &variableName) {
  2825. return readWordTo(result, ptrn, variableName);
  2826. }
  2827. #ifdef __GNUC__
  2828. __attribute__((pure))
  2829. #endif
  2830. static inline bool equals(long long integer, const char *s) {
  2831. if (integer == LLONG_MIN)
  2832. return strcmp(s, "-9223372036854775808") == 0;
  2833. if (integer == 0LL)
  2834. return strcmp(s, "0") == 0;
  2835. size_t length = strlen(s);
  2836. if (length == 0)
  2837. return false;
  2838. if (integer < 0 && s[0] != '-')
  2839. return false;
  2840. if (integer < 0)
  2841. s++, length--, integer = -integer;
  2842. if (length == 0)
  2843. return false;
  2844. while (integer > 0) {
  2845. int digit = int(integer % 10);
  2846. if (s[length - 1] != '0' + digit)
  2847. return false;
  2848. length--;
  2849. integer /= 10;
  2850. }
  2851. return length == 0;
  2852. }
  2853. #ifdef __GNUC__
  2854. __attribute__((pure))
  2855. #endif
  2856. static inline bool equals(unsigned long long integer, const char *s) {
  2857. if (integer == ULLONG_MAX)
  2858. return strcmp(s, "18446744073709551615") == 0;
  2859. if (integer == 0ULL)
  2860. return strcmp(s, "0") == 0;
  2861. size_t length = strlen(s);
  2862. if (length == 0)
  2863. return false;
  2864. while (integer > 0) {
  2865. int digit = int(integer % 10);
  2866. if (s[length - 1] != '0' + digit)
  2867. return false;
  2868. length--;
  2869. integer /= 10;
  2870. }
  2871. return length == 0;
  2872. }
  2873. static inline double stringToDouble(InStream &in, const char *buffer) {
  2874. double retval;
  2875. size_t length = strlen(buffer);
  2876. int minusCount = 0;
  2877. int plusCount = 0;
  2878. int decimalPointCount = 0;
  2879. int digitCount = 0;
  2880. int eCount = 0;
  2881. for (size_t i = 0; i < length; i++) {
  2882. if (('0' <= buffer[i] && buffer[i] <= '9') || buffer[i] == '.'
  2883. || buffer[i] == 'e' || buffer[i] == 'E'
  2884. || buffer[i] == '-' || buffer[i] == '+') {
  2885. if ('0' <= buffer[i] && buffer[i] <= '9')
  2886. digitCount++;
  2887. if (buffer[i] == 'e' || buffer[i] == 'E')
  2888. eCount++;
  2889. if (buffer[i] == '-')
  2890. minusCount++;
  2891. if (buffer[i] == '+')
  2892. plusCount++;
  2893. if (buffer[i] == '.')
  2894. decimalPointCount++;
  2895. } else
  2896. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2897. }
  2898. // If for sure is not a number in standard notation or in e-notation.
  2899. if (digitCount == 0 || minusCount > 2 || plusCount > 2 || decimalPointCount > 1 || eCount > 1)
  2900. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2901. char *suffix = new char[length + 1];
  2902. std::memset(suffix, 0, length + 1);
  2903. int scanned = std::sscanf(buffer, "%lf%s", &retval, suffix);
  2904. bool empty = strlen(suffix) == 0;
  2905. delete[] suffix;
  2906. if (scanned == 1 || (scanned == 2 && empty)) {
  2907. if (__testlib_isNaN(retval))
  2908. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2909. return retval;
  2910. } else
  2911. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2912. }
  2913. static inline double stringToDouble(InStream &in, const std::string& buffer) {
  2914. for (size_t i = 0; i < buffer.length(); i++)
  2915. if (buffer[i] == '\0')
  2916. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found (it contains \\0)").c_str());
  2917. return stringToDouble(in, buffer.c_str());
  2918. }
  2919. static inline double stringToStrictDouble(InStream &in, const char *buffer,
  2920. int minAfterPointDigitCount, int maxAfterPointDigitCount) {
  2921. if (minAfterPointDigitCount < 0)
  2922. in.quit(_fail, "stringToStrictDouble: minAfterPointDigitCount should be non-negative.");
  2923. if (minAfterPointDigitCount > maxAfterPointDigitCount)
  2924. in.quit(_fail,
  2925. "stringToStrictDouble: minAfterPointDigitCount should be less or equal to maxAfterPointDigitCount.");
  2926. double retval;
  2927. size_t length = strlen(buffer);
  2928. if (length == 0 || length > 1000)
  2929. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2930. if (buffer[0] != '-' && (buffer[0] < '0' || buffer[0] > '9'))
  2931. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2932. int pointPos = -1;
  2933. for (size_t i = 1; i + 1 < length; i++) {
  2934. if (buffer[i] == '.') {
  2935. if (pointPos > -1)
  2936. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2937. pointPos = int(i);
  2938. }
  2939. if (buffer[i] != '.' && (buffer[i] < '0' || buffer[i] > '9'))
  2940. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2941. }
  2942. if (buffer[length - 1] < '0' || buffer[length - 1] > '9')
  2943. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2944. int afterDigitsCount = (pointPos == -1 ? 0 : int(length) - pointPos - 1);
  2945. if (afterDigitsCount < minAfterPointDigitCount || afterDigitsCount > maxAfterPointDigitCount)
  2946. in.quit(_pe, ("Expected strict double with number of digits after point in range ["
  2947. + vtos(minAfterPointDigitCount)
  2948. + ","
  2949. + vtos(maxAfterPointDigitCount)
  2950. + "], but \"" + __testlib_part(buffer) + "\" found").c_str()
  2951. );
  2952. int firstDigitPos = -1;
  2953. for (size_t i = 0; i < length; i++)
  2954. if (buffer[i] >= '0' && buffer[i] <= '9') {
  2955. firstDigitPos = int(i);
  2956. break;
  2957. }
  2958. if (firstDigitPos > 1 || firstDigitPos == -1)
  2959. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2960. if (buffer[firstDigitPos] == '0' && firstDigitPos + 1 < int(length)
  2961. && buffer[firstDigitPos + 1] >= '0' && buffer[firstDigitPos + 1] <= '9')
  2962. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2963. char *suffix = new char[length + 1];
  2964. std::memset(suffix, 0, length + 1);
  2965. int scanned = std::sscanf(buffer, "%lf%s", &retval, suffix);
  2966. bool empty = strlen(suffix) == 0;
  2967. delete[] suffix;
  2968. if (scanned == 1 || (scanned == 2 && empty)) {
  2969. if (__testlib_isNaN(retval) || __testlib_isInfinite(retval))
  2970. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2971. if (buffer[0] == '-' && retval >= 0)
  2972. in.quit(_pe, ("Redundant minus in \"" + __testlib_part(buffer) + "\" found").c_str());
  2973. return retval;
  2974. } else
  2975. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2976. }
  2977. static inline double stringToStrictDouble(InStream &in, const std::string& buffer,
  2978. int minAfterPointDigitCount, int maxAfterPointDigitCount) {
  2979. for (size_t i = 0; i < buffer.length(); i++)
  2980. if (buffer[i] == '\0')
  2981. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found (it contains \\0)").c_str());
  2982. return stringToStrictDouble(in, buffer.c_str(), minAfterPointDigitCount, maxAfterPointDigitCount);
  2983. }
  2984. static inline long long stringToLongLong(InStream &in, const char *buffer) {
  2985. if (strcmp(buffer, "-9223372036854775808") == 0)
  2986. return LLONG_MIN;
  2987. bool minus = false;
  2988. size_t length = strlen(buffer);
  2989. if (length > 1 && buffer[0] == '-')
  2990. minus = true;
  2991. if (length > 20)
  2992. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2993. long long retval = 0LL;
  2994. int zeroes = 0;
  2995. bool processingZeroes = true;
  2996. for (int i = (minus ? 1 : 0); i < int(length); i++) {
  2997. if (buffer[i] == '0' && processingZeroes)
  2998. zeroes++;
  2999. else
  3000. processingZeroes = false;
  3001. if (buffer[i] < '0' || buffer[i] > '9')
  3002. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  3003. retval = retval * 10 + (buffer[i] - '0');
  3004. }
  3005. if (retval < 0)
  3006. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  3007. if ((zeroes > 0 && (retval != 0 || minus)) || zeroes > 1)
  3008. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  3009. retval = (minus ? -retval : +retval);
  3010. if (length < 19)
  3011. return retval;
  3012. if (equals(retval, buffer))
  3013. return retval;
  3014. else
  3015. in.quit(_pe, ("Expected int64, but \"" + __testlib_part(buffer) + "\" found").c_str());
  3016. }
  3017. static inline long long stringToLongLong(InStream &in, const std::string& buffer) {
  3018. for (size_t i = 0; i < buffer.length(); i++)
  3019. if (buffer[i] == '\0')
  3020. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found (it contains \\0)").c_str());
  3021. return stringToLongLong(in, buffer.c_str());
  3022. }
  3023. static inline unsigned long long stringToUnsignedLongLong(InStream &in, const char *buffer) {
  3024. size_t length = strlen(buffer);
  3025. if (length > 20)
  3026. in.quit(_pe, ("Expected unsigned integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  3027. if (length > 1 && buffer[0] == '0')
  3028. in.quit(_pe, ("Expected unsigned integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  3029. unsigned long long retval = 0LL;
  3030. for (int i = 0; i < int(length); i++) {
  3031. if (buffer[i] < '0' || buffer[i] > '9')
  3032. in.quit(_pe, ("Expected unsigned integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  3033. retval = retval * 10 + (buffer[i] - '0');
  3034. }
  3035. if (length < 19)
  3036. return retval;
  3037. if (length == 20 && strcmp(buffer, "18446744073709551615") > 0)
  3038. in.quit(_pe, ("Expected unsigned int64, but \"" + __testlib_part(buffer) + "\" found").c_str());
  3039. if (equals(retval, buffer))
  3040. return retval;
  3041. else
  3042. in.quit(_pe, ("Expected unsigned int64, but \"" + __testlib_part(buffer) + "\" found").c_str());
  3043. }
  3044. static inline long long stringToUnsignedLongLong(InStream &in, const std::string& buffer) {
  3045. for (size_t i = 0; i < buffer.length(); i++)
  3046. if (buffer[i] == '\0')
  3047. in.quit(_pe, ("Expected unsigned integer, but \"" + __testlib_part(buffer) + "\" found (it contains \\0)").c_str());
  3048. return stringToUnsignedLongLong(in, buffer.c_str());
  3049. }
  3050. int InStream::readInteger() {
  3051. if (!strict && seekEof())
  3052. quit(_unexpected_eof, "Unexpected end of file - int32 expected");
  3053. readWordTo(_tmpReadToken);
  3054. long long value = stringToLongLong(*this, _tmpReadToken);
  3055. if (value < INT_MIN || value > INT_MAX)
  3056. quit(_pe, ("Expected int32, but \"" + __testlib_part(_tmpReadToken) + "\" found").c_str());
  3057. return int(value);
  3058. }
  3059. long long InStream::readLong() {
  3060. if (!strict && seekEof())
  3061. quit(_unexpected_eof, "Unexpected end of file - int64 expected");
  3062. readWordTo(_tmpReadToken);
  3063. return stringToLongLong(*this, _tmpReadToken);
  3064. }
  3065. unsigned long long InStream::readUnsignedLong() {
  3066. if (!strict && seekEof())
  3067. quit(_unexpected_eof, "Unexpected end of file - int64 expected");
  3068. readWordTo(_tmpReadToken);
  3069. return stringToUnsignedLongLong(*this, _tmpReadToken);
  3070. }
  3071. long long InStream::readLong(long long minv, long long maxv, const std::string &variableName) {
  3072. long long result = readLong();
  3073. if (result < minv || result > maxv) {
  3074. if (readManyIteration == NO_INDEX) {
  3075. if (variableName.empty())
  3076. quit(_wa, ("Integer " + vtos(result) + " violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) +
  3077. "]").c_str());
  3078. else
  3079. quit(_wa, ("Integer parameter [name=" + std::string(variableName) + "] equals to " + vtos(result) +
  3080. ", violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) + "]").c_str());
  3081. } else {
  3082. if (variableName.empty())
  3083. quit(_wa, ("Integer element [index=" + vtos(readManyIteration) + "] equals to " + vtos(result) +
  3084. ", violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) + "]").c_str());
  3085. else
  3086. quit(_wa,
  3087. ("Integer element " + std::string(variableName) + "[" + vtos(readManyIteration) + "] equals to " +
  3088. vtos(result) + ", violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) + "]").c_str());
  3089. }
  3090. }
  3091. if (strict && !variableName.empty())
  3092. validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));
  3093. return result;
  3094. }
  3095. std::vector<long long>
  3096. InStream::readLongs(int size, long long minv, long long maxv, const std::string &variablesName, int indexBase) {
  3097. __testlib_readMany(readLongs, readLong(minv, maxv, variablesName), long long, true)
  3098. }
  3099. std::vector<long long> InStream::readLongs(int size, int indexBase) {
  3100. __testlib_readMany(readLongs, readLong(), long long, true)
  3101. }
  3102. unsigned long long
  3103. InStream::readUnsignedLong(unsigned long long minv, unsigned long long maxv, const std::string &variableName) {
  3104. unsigned long long result = readUnsignedLong();
  3105. if (result < minv || result > maxv) {
  3106. if (readManyIteration == NO_INDEX) {
  3107. if (variableName.empty())
  3108. quit(_wa,
  3109. ("Unsigned integer " + vtos(result) + " violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) +
  3110. "]").c_str());
  3111. else
  3112. quit(_wa,
  3113. ("Unsigned integer parameter [name=" + std::string(variableName) + "] equals to " + vtos(result) +
  3114. ", violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) + "]").c_str());
  3115. } else {
  3116. if (variableName.empty())
  3117. quit(_wa,
  3118. ("Unsigned integer element [index=" + vtos(readManyIteration) + "] equals to " + vtos(result) +
  3119. ", violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) + "]").c_str());
  3120. else
  3121. quit(_wa, ("Unsigned integer element " + std::string(variableName) + "[" + vtos(readManyIteration) +
  3122. "] equals to " + vtos(result) + ", violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) +
  3123. "]").c_str());
  3124. }
  3125. }
  3126. if (strict && !variableName.empty())
  3127. validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));
  3128. return result;
  3129. }
  3130. std::vector<unsigned long long> InStream::readUnsignedLongs(int size, unsigned long long minv, unsigned long long maxv,
  3131. const std::string &variablesName, int indexBase) {
  3132. __testlib_readMany(readUnsignedLongs, readUnsignedLong(minv, maxv, variablesName), unsigned long long, true)
  3133. }
  3134. std::vector<unsigned long long> InStream::readUnsignedLongs(int size, int indexBase) {
  3135. __testlib_readMany(readUnsignedLongs, readUnsignedLong(), unsigned long long, true)
  3136. }
  3137. unsigned long long
  3138. InStream::readLong(unsigned long long minv, unsigned long long maxv, const std::string &variableName) {
  3139. return readUnsignedLong(minv, maxv, variableName);
  3140. }
  3141. int InStream::readInt() {
  3142. return readInteger();
  3143. }
  3144. int InStream::readInt(int minv, int maxv, const std::string &variableName) {
  3145. int result = readInt();
  3146. if (result < minv || result > maxv) {
  3147. if (readManyIteration == NO_INDEX) {
  3148. if (variableName.empty())
  3149. quit(_wa, ("Integer " + vtos(result) + " violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) +
  3150. "]").c_str());
  3151. else
  3152. quit(_wa, ("Integer parameter [name=" + std::string(variableName) + "] equals to " + vtos(result) +
  3153. ", violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) + "]").c_str());
  3154. } else {
  3155. if (variableName.empty())
  3156. quit(_wa, ("Integer element [index=" + vtos(readManyIteration) + "] equals to " + vtos(result) +
  3157. ", violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) + "]").c_str());
  3158. else
  3159. quit(_wa,
  3160. ("Integer element " + std::string(variableName) + "[" + vtos(readManyIteration) + "] equals to " +
  3161. vtos(result) + ", violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) + "]").c_str());
  3162. }
  3163. }
  3164. if (strict && !variableName.empty())
  3165. validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));
  3166. return result;
  3167. }
  3168. int InStream::readInteger(int minv, int maxv, const std::string &variableName) {
  3169. return readInt(minv, maxv, variableName);
  3170. }
  3171. std::vector<int> InStream::readInts(int size, int minv, int maxv, const std::string &variablesName, int indexBase) {
  3172. __testlib_readMany(readInts, readInt(minv, maxv, variablesName), int, true)
  3173. }
  3174. std::vector<int> InStream::readInts(int size, int indexBase) {
  3175. __testlib_readMany(readInts, readInt(), int, true)
  3176. }
  3177. std::vector<int> InStream::readIntegers(int size, int minv, int maxv, const std::string &variablesName, int indexBase) {
  3178. __testlib_readMany(readIntegers, readInt(minv, maxv, variablesName), int, true)
  3179. }
  3180. std::vector<int> InStream::readIntegers(int size, int indexBase) {
  3181. __testlib_readMany(readIntegers, readInt(), int, true)
  3182. }
  3183. double InStream::readReal() {
  3184. if (!strict && seekEof())
  3185. quit(_unexpected_eof, "Unexpected end of file - double expected");
  3186. return stringToDouble(*this, readWord());
  3187. }
  3188. double InStream::readDouble() {
  3189. return readReal();
  3190. }
  3191. double InStream::readReal(double minv, double maxv, const std::string &variableName) {
  3192. double result = readReal();
  3193. if (result < minv || result > maxv) {
  3194. if (readManyIteration == NO_INDEX) {
  3195. if (variableName.empty())
  3196. quit(_wa, ("Double " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) +
  3197. "]").c_str());
  3198. else
  3199. quit(_wa, ("Double parameter [name=" + std::string(variableName) + "] equals to " + vtos(result) +
  3200. ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  3201. } else {
  3202. if (variableName.empty())
  3203. quit(_wa, ("Double element [index=" + vtos(readManyIteration) + "] equals to " + vtos(result) +
  3204. ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  3205. else
  3206. quit(_wa,
  3207. ("Double element " + std::string(variableName) + "[" + vtos(readManyIteration) + "] equals to " +
  3208. vtos(result) + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  3209. }
  3210. }
  3211. if (strict && !variableName.empty())
  3212. validator.addBoundsHit(variableName, ValidatorBoundsHit(
  3213. doubleDelta(minv, result) < ValidatorBoundsHit::EPS,
  3214. doubleDelta(maxv, result) < ValidatorBoundsHit::EPS
  3215. ));
  3216. return result;
  3217. }
  3218. std::vector<double>
  3219. InStream::readReals(int size, double minv, double maxv, const std::string &variablesName, int indexBase) {
  3220. __testlib_readMany(readReals, readReal(minv, maxv, variablesName), double, true)
  3221. }
  3222. std::vector<double> InStream::readReals(int size, int indexBase) {
  3223. __testlib_readMany(readReals, readReal(), double, true)
  3224. }
  3225. double InStream::readDouble(double minv, double maxv, const std::string &variableName) {
  3226. return readReal(minv, maxv, variableName);
  3227. }
  3228. std::vector<double>
  3229. InStream::readDoubles(int size, double minv, double maxv, const std::string &variablesName, int indexBase) {
  3230. __testlib_readMany(readDoubles, readDouble(minv, maxv, variablesName), double, true)
  3231. }
  3232. std::vector<double> InStream::readDoubles(int size, int indexBase) {
  3233. __testlib_readMany(readDoubles, readDouble(), double, true)
  3234. }
  3235. double InStream::readStrictReal(double minv, double maxv,
  3236. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  3237. const std::string &variableName) {
  3238. if (!strict && seekEof())
  3239. quit(_unexpected_eof, "Unexpected end of file - strict double expected");
  3240. double result = stringToStrictDouble(*this, readWord(), minAfterPointDigitCount, maxAfterPointDigitCount);
  3241. if (result < minv || result > maxv) {
  3242. if (readManyIteration == NO_INDEX) {
  3243. if (variableName.empty())
  3244. quit(_wa, ("Strict double " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) +
  3245. "]").c_str());
  3246. else
  3247. quit(_wa,
  3248. ("Strict double parameter [name=" + std::string(variableName) + "] equals to " + vtos(result) +
  3249. ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  3250. } else {
  3251. if (variableName.empty())
  3252. quit(_wa, ("Strict double element [index=" + vtos(readManyIteration) + "] equals to " + vtos(result) +
  3253. ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  3254. else
  3255. quit(_wa, ("Strict double element " + std::string(variableName) + "[" + vtos(readManyIteration) +
  3256. "] equals to " + vtos(result) + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) +
  3257. "]").c_str());
  3258. }
  3259. }
  3260. if (strict && !variableName.empty())
  3261. validator.addBoundsHit(variableName, ValidatorBoundsHit(
  3262. doubleDelta(minv, result) < ValidatorBoundsHit::EPS,
  3263. doubleDelta(maxv, result) < ValidatorBoundsHit::EPS
  3264. ));
  3265. return result;
  3266. }
  3267. std::vector<double> InStream::readStrictReals(int size, double minv, double maxv,
  3268. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  3269. const std::string &variablesName, int indexBase) {
  3270. __testlib_readMany(readStrictReals,
  3271. readStrictReal(minv, maxv, minAfterPointDigitCount, maxAfterPointDigitCount, variablesName),
  3272. double, true)
  3273. }
  3274. double InStream::readStrictDouble(double minv, double maxv,
  3275. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  3276. const std::string &variableName) {
  3277. return readStrictReal(minv, maxv,
  3278. minAfterPointDigitCount, maxAfterPointDigitCount,
  3279. variableName);
  3280. }
  3281. std::vector<double> InStream::readStrictDoubles(int size, double minv, double maxv,
  3282. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  3283. const std::string &variablesName, int indexBase) {
  3284. __testlib_readMany(readStrictDoubles,
  3285. readStrictDouble(minv, maxv, minAfterPointDigitCount, maxAfterPointDigitCount, variablesName),
  3286. double, true)
  3287. }
  3288. bool InStream::eof() {
  3289. if (!strict && NULL == reader)
  3290. return true;
  3291. return reader->eof();
  3292. }
  3293. bool InStream::seekEof() {
  3294. if (!strict && NULL == reader)
  3295. return true;
  3296. skipBlanks();
  3297. return eof();
  3298. }
  3299. bool InStream::eoln() {
  3300. if (!strict && NULL == reader)
  3301. return true;
  3302. int c = reader->nextChar();
  3303. if (!strict) {
  3304. if (c == EOFC)
  3305. return true;
  3306. if (c == CR) {
  3307. c = reader->nextChar();
  3308. if (c != LF) {
  3309. reader->unreadChar(c);
  3310. reader->unreadChar(CR);
  3311. return false;
  3312. } else
  3313. return true;
  3314. }
  3315. if (c == LF)
  3316. return true;
  3317. reader->unreadChar(c);
  3318. return false;
  3319. } else {
  3320. bool returnCr = false;
  3321. #if (defined(ON_WINDOWS) && !defined(FOR_LINUX)) || defined(FOR_WINDOWS)
  3322. if (c != CR) {
  3323. reader->unreadChar(c);
  3324. return false;
  3325. } else {
  3326. if (!returnCr)
  3327. returnCr = true;
  3328. c = reader->nextChar();
  3329. }
  3330. #endif
  3331. if (c != LF) {
  3332. reader->unreadChar(c);
  3333. if (returnCr)
  3334. reader->unreadChar(CR);
  3335. return false;
  3336. }
  3337. return true;
  3338. }
  3339. }
  3340. void InStream::readEoln() {
  3341. lastLine = reader->getLine();
  3342. if (!eoln())
  3343. quit(_pe, "Expected EOLN");
  3344. }
  3345. void InStream::readEof() {
  3346. lastLine = reader->getLine();
  3347. if (!eof())
  3348. quit(_pe, "Expected EOF");
  3349. if (TestlibFinalizeGuard::alive && this == &inf)
  3350. testlibFinalizeGuard.readEofCount++;
  3351. }
  3352. bool InStream::seekEoln() {
  3353. if (!strict && NULL == reader)
  3354. return true;
  3355. int cur;
  3356. do {
  3357. cur = reader->nextChar();
  3358. } while (cur == SPACE || cur == TAB);
  3359. reader->unreadChar(cur);
  3360. return eoln();
  3361. }
  3362. void InStream::nextLine() {
  3363. readLine();
  3364. }
  3365. void InStream::readStringTo(std::string &result) {
  3366. if (NULL == reader)
  3367. quit(_pe, "Expected line");
  3368. result.clear();
  3369. for (;;) {
  3370. int cur = reader->curChar();
  3371. if (cur == LF || cur == EOFC)
  3372. break;
  3373. if (cur == CR) {
  3374. cur = reader->nextChar();
  3375. if (reader->curChar() == LF) {
  3376. reader->unreadChar(cur);
  3377. break;
  3378. }
  3379. }
  3380. lastLine = reader->getLine();
  3381. result += char(reader->nextChar());
  3382. }
  3383. if (strict)
  3384. readEoln();
  3385. else
  3386. eoln();
  3387. }
  3388. std::string InStream::readString() {
  3389. readStringTo(_tmpReadToken);
  3390. return _tmpReadToken;
  3391. }
  3392. std::vector<std::string> InStream::readStrings(int size, int indexBase) {
  3393. __testlib_readMany(readStrings, readString(), std::string, false)
  3394. }
  3395. void InStream::readStringTo(std::string &result, const pattern &p, const std::string &variableName) {
  3396. readStringTo(result);
  3397. if (!p.matches(result)) {
  3398. if (readManyIteration == NO_INDEX) {
  3399. if (variableName.empty())
  3400. quit(_wa, ("Line \"" + __testlib_part(result) + "\" doesn't correspond to pattern \"" + p.src() +
  3401. "\"").c_str());
  3402. else
  3403. quit(_wa, ("Line [name=" + variableName + "] equals to \"" + __testlib_part(result) +
  3404. "\", doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  3405. } else {
  3406. if (variableName.empty())
  3407. quit(_wa,
  3408. ("Line element [index=" + vtos(readManyIteration) + "] equals to \"" + __testlib_part(result) +
  3409. "\" doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  3410. else
  3411. quit(_wa,
  3412. ("Line element " + std::string(variableName) + "[" + vtos(readManyIteration) + "] equals to \"" +
  3413. __testlib_part(result) + "\", doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  3414. }
  3415. }
  3416. }
  3417. void InStream::readStringTo(std::string &result, const std::string &ptrn, const std::string &variableName) {
  3418. readStringTo(result, pattern(ptrn), variableName);
  3419. }
  3420. std::string InStream::readString(const pattern &p, const std::string &variableName) {
  3421. readStringTo(_tmpReadToken, p, variableName);
  3422. return _tmpReadToken;
  3423. }
  3424. std::vector<std::string>
  3425. InStream::readStrings(int size, const pattern &p, const std::string &variablesName, int indexBase) {
  3426. __testlib_readMany(readStrings, readString(p, variablesName), std::string, false)
  3427. }
  3428. std::string InStream::readString(const std::string &ptrn, const std::string &variableName) {
  3429. readStringTo(_tmpReadToken, ptrn, variableName);
  3430. return _tmpReadToken;
  3431. }
  3432. std::vector<std::string>
  3433. InStream::readStrings(int size, const std::string &ptrn, const std::string &variablesName, int indexBase) {
  3434. pattern p(ptrn);
  3435. __testlib_readMany(readStrings, readString(p, variablesName), std::string, false)
  3436. }
  3437. void InStream::readLineTo(std::string &result) {
  3438. readStringTo(result);
  3439. }
  3440. std::string InStream::readLine() {
  3441. return readString();
  3442. }
  3443. std::vector<std::string> InStream::readLines(int size, int indexBase) {
  3444. __testlib_readMany(readLines, readString(), std::string, false)
  3445. }
  3446. void InStream::readLineTo(std::string &result, const pattern &p, const std::string &variableName) {
  3447. readStringTo(result, p, variableName);
  3448. }
  3449. void InStream::readLineTo(std::string &result, const std::string &ptrn, const std::string &variableName) {
  3450. readStringTo(result, ptrn, variableName);
  3451. }
  3452. std::string InStream::readLine(const pattern &p, const std::string &variableName) {
  3453. return readString(p, variableName);
  3454. }
  3455. std::vector<std::string>
  3456. InStream::readLines(int size, const pattern &p, const std::string &variablesName, int indexBase) {
  3457. __testlib_readMany(readLines, readString(p, variablesName), std::string, false)
  3458. }
  3459. std::string InStream::readLine(const std::string &ptrn, const std::string &variableName) {
  3460. return readString(ptrn, variableName);
  3461. }
  3462. std::vector<std::string>
  3463. InStream::readLines(int size, const std::string &ptrn, const std::string &variablesName, int indexBase) {
  3464. pattern p(ptrn);
  3465. __testlib_readMany(readLines, readString(p, variablesName), std::string, false)
  3466. }
  3467. #ifdef __GNUC__
  3468. __attribute__ ((format (printf, 3, 4)))
  3469. #endif
  3470. void InStream::ensuref(bool cond, const char *format, ...) {
  3471. if (!cond) {
  3472. FMT_TO_RESULT(format, format, message);
  3473. this->__testlib_ensure(cond, message);
  3474. }
  3475. }
  3476. void InStream::__testlib_ensure(bool cond, std::string message) {
  3477. if (!cond)
  3478. this->quit(_wa, message.c_str());
  3479. }
  3480. void InStream::close() {
  3481. if (NULL != reader) {
  3482. reader->close();
  3483. delete reader;
  3484. reader = NULL;
  3485. }
  3486. opened = false;
  3487. }
  3488. NORETURN void quit(TResult result, const std::string &msg) {
  3489. ouf.quit(result, msg.c_str());
  3490. }
  3491. NORETURN void quit(TResult result, const char *msg) {
  3492. ouf.quit(result, msg);
  3493. }
  3494. NORETURN void __testlib_quitp(double points, const char *message) {
  3495. __testlib_points = points;
  3496. std::string stringPoints = removeDoubleTrailingZeroes(format("%.10f", points));
  3497. std::string quitMessage;
  3498. if (NULL == message || 0 == strlen(message))
  3499. quitMessage = stringPoints;
  3500. else
  3501. quitMessage = stringPoints + " " + message;
  3502. quit(_points, quitMessage.c_str());
  3503. }
  3504. NORETURN void __testlib_quitp(int points, const char *message) {
  3505. __testlib_points = points;
  3506. std::string stringPoints = format("%d", points);
  3507. std::string quitMessage;
  3508. if (NULL == message || 0 == strlen(message))
  3509. quitMessage = stringPoints;
  3510. else
  3511. quitMessage = stringPoints + " " + message;
  3512. quit(_points, quitMessage.c_str());
  3513. }
  3514. NORETURN void quitp(float points, const std::string &message = "") {
  3515. __testlib_quitp(double(points), message.c_str());
  3516. }
  3517. NORETURN void quitp(double points, const std::string &message = "") {
  3518. __testlib_quitp(points, message.c_str());
  3519. }
  3520. NORETURN void quitp(long double points, const std::string &message = "") {
  3521. __testlib_quitp(double(points), message.c_str());
  3522. }
  3523. NORETURN void quitp(int points, const std::string &message = "") {
  3524. __testlib_quitp(points, message.c_str());
  3525. }
  3526. NORETURN void quitpi(const std::string &points_info, const std::string &message = "") {
  3527. if (points_info.find(' ') != std::string::npos)
  3528. quit(_fail, "Parameter 'points_info' can't contain spaces");
  3529. if (message.empty())
  3530. quit(_points, ("points_info=" + points_info).c_str());
  3531. else
  3532. quit(_points, ("points_info=" + points_info + " " + message).c_str());
  3533. }
  3534. template<typename F>
  3535. #ifdef __GNUC__
  3536. __attribute__ ((format (printf, 2, 3)))
  3537. #endif
  3538. NORETURN void quitp(F points, const char *format, ...) {
  3539. FMT_TO_RESULT(format, format, message);
  3540. quitp(points, message);
  3541. }
  3542. #ifdef __GNUC__
  3543. __attribute__ ((format (printf, 2, 3)))
  3544. #endif
  3545. NORETURN void quitf(TResult result, const char *format, ...) {
  3546. FMT_TO_RESULT(format, format, message);
  3547. quit(result, message);
  3548. }
  3549. #ifdef __GNUC__
  3550. __attribute__ ((format (printf, 3, 4)))
  3551. #endif
  3552. void quitif(bool condition, TResult result, const char *format, ...) {
  3553. if (condition) {
  3554. FMT_TO_RESULT(format, format, message);
  3555. quit(result, message);
  3556. }
  3557. }
  3558. NORETURN void __testlib_help() {
  3559. InStream::textColor(InStream::LightCyan);
  3560. std::fprintf(stderr, "TESTLIB %s, https://github.com/MikeMirzayanov/testlib/ ", VERSION);
  3561. std::fprintf(stderr, "by Mike Mirzayanov, copyright(c) 2005-2020\n");
  3562. std::fprintf(stderr, "Checker name: \"%s\"\n", checkerName.c_str());
  3563. InStream::textColor(InStream::LightGray);
  3564. std::fprintf(stderr, "\n");
  3565. std::fprintf(stderr, "Latest features: \n");
  3566. for (size_t i = 0; i < sizeof(latestFeatures) / sizeof(char *); i++) {
  3567. std::fprintf(stderr, "*) %s\n", latestFeatures[i]);
  3568. }
  3569. std::fprintf(stderr, "\n");
  3570. std::fprintf(stderr, "Program must be run with the following arguments: \n");
  3571. std::fprintf(stderr, " [--testset testset] [--group group] <input-file> <output-file> <answer-file> [<report-file> [<-appes>]]\n\n");
  3572. __testlib_exitCode = FAIL_EXIT_CODE;
  3573. std::exit(FAIL_EXIT_CODE);
  3574. }
  3575. static void __testlib_ensuresPreconditions() {
  3576. // testlib assumes: sizeof(int) = 4.
  3577. __TESTLIB_STATIC_ASSERT(sizeof(int) == 4);
  3578. // testlib assumes: INT_MAX == 2147483647.
  3579. __TESTLIB_STATIC_ASSERT(INT_MAX == 2147483647);
  3580. // testlib assumes: sizeof(long long) = 8.
  3581. __TESTLIB_STATIC_ASSERT(sizeof(long long) == 8);
  3582. // testlib assumes: sizeof(double) = 8.
  3583. __TESTLIB_STATIC_ASSERT(sizeof(double) == 8);
  3584. // testlib assumes: no -ffast-math.
  3585. if (!__testlib_isNaN(+__testlib_nan()))
  3586. quit(_fail, "Function __testlib_isNaN is not working correctly: possible reason is '-ffast-math'");
  3587. if (!__testlib_isNaN(-__testlib_nan()))
  3588. quit(_fail, "Function __testlib_isNaN is not working correctly: possible reason is '-ffast-math'");
  3589. }
  3590. std::string __testlib_testset;
  3591. std::string getTestset() {
  3592. return __testlib_testset;
  3593. }
  3594. std::string __testlib_group;
  3595. std::string getGroup() {
  3596. return __testlib_group;
  3597. }
  3598. static void __testlib_set_testset_and_group(int argc, char* argv[]) {
  3599. for (int i = 1; i < argc; i++) {
  3600. if (!strcmp("--testset", argv[i])) {
  3601. if (i + 1 < argc && strlen(argv[i + 1]) > 0)
  3602. __testlib_testset = argv[++i];
  3603. else
  3604. quit(_fail, std::string("Expected non-empty testset after --testset command line parameter"));
  3605. } else if (!strcmp("--group", argv[i])) {
  3606. if (i + 1 < argc)
  3607. __testlib_group = argv[++i];
  3608. else
  3609. quit(_fail, std::string("Expected group after --group command line parameter"));
  3610. }
  3611. }
  3612. }
  3613. void registerGen(int argc, char *argv[], int randomGeneratorVersion) {
  3614. if (randomGeneratorVersion < 0 || randomGeneratorVersion > 1)
  3615. quitf(_fail, "Random generator version is expected to be 0 or 1.");
  3616. random_t::version = randomGeneratorVersion;
  3617. __testlib_ensuresPreconditions();
  3618. TestlibFinalizeGuard::registered = true;
  3619. testlibMode = _generator;
  3620. __testlib_set_binary(stdin);
  3621. rnd.setSeed(argc, argv);
  3622. #if __cplusplus > 199711L || defined(_MSC_VER)
  3623. prepareOpts(argc, argv);
  3624. #endif
  3625. }
  3626. #ifdef USE_RND_AS_BEFORE_087
  3627. void registerGen(int argc, char* argv[])
  3628. {
  3629. registerGen(argc, argv, 0);
  3630. }
  3631. #else
  3632. #ifdef __GNUC__
  3633. #if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 4))
  3634. __attribute__ ((deprecated("Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1)."
  3635. " The third parameter stands for the random generator version."
  3636. " If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0)."
  3637. " Version 1 has been released on Spring, 2013. Use it to write new generators.")))
  3638. #else
  3639. __attribute__ ((deprecated))
  3640. #endif
  3641. #endif
  3642. #ifdef _MSC_VER
  3643. __declspec(deprecated("Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1)."
  3644. " The third parameter stands for the random generator version."
  3645. " If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0)."
  3646. " Version 1 has been released on Spring, 2013. Use it to write new generators."))
  3647. #endif
  3648. void registerGen(int argc, char *argv[]) {
  3649. std::fprintf(stderr, "Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1)."
  3650. " The third parameter stands for the random generator version."
  3651. " If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0)."
  3652. " Version 1 has been released on Spring, 2013. Use it to write new generators.\n\n");
  3653. registerGen(argc, argv, 0);
  3654. }
  3655. #endif
  3656. static void setAppesModeEncoding(std::string appesModeEncoding) {
  3657. static const char* const ENCODINGS[] = {"ascii", "utf-7", "utf-8", "utf-16", "utf-16le", "utf-16be", "utf-32", "utf-32le", "utf-32be", "iso-8859-1",
  3658. "iso-8859-2", "iso-8859-3", "iso-8859-4", "iso-8859-5", "iso-8859-6", "iso-8859-7", "iso-8859-8", "iso-8859-9", "iso-8859-10", "iso-8859-11",
  3659. "iso-8859-13", "iso-8859-14", "iso-8859-15", "iso-8859-16", "windows-1250", "windows-1251", "windows-1252", "windows-1253", "windows-1254", "windows-1255",
  3660. "windows-1256", "windows-1257", "windows-1258", "gb2312", "gbk", "gb18030", "big5", "shift-jis", "euc-jp", "euc-kr",
  3661. "euc-cn", "euc-tw", "koi8-r", "koi8-u", "tis-620", "ibm437", "ibm850", "ibm852", "ibm855", "ibm857",
  3662. "ibm860", "ibm861", "ibm862", "ibm863", "ibm865", "ibm866", "ibm869", "macroman", "maccentraleurope", "maciceland",
  3663. "maccroatian", "macromania", "maccyrillic", "macukraine", "macgreek", "macturkish", "machebrew", "macarabic", "macthai", "hz-gb-2312",
  3664. "iso-2022-jp", "iso-2022-kr", "iso-2022-cn", "armscii-8", "tscii", "iscii", "viscii", "geostd8", "cp949", "cp874",
  3665. "cp1006", "cp775", "cp858", "cp737", "cp853", "cp856", "cp922", "cp1046", "cp1125", "cp1131",
  3666. "ptcp154", "koi8-t", "koi8-ru", "mulelao-1", "cp1133", "iso-ir-166", "tcvn", "iso-ir-14", "iso-ir-87", "iso-ir-159"};
  3667. appesModeEncoding = lowerCase(appesModeEncoding);
  3668. bool valid = false;
  3669. for (size_t i = 0; i < sizeof(ENCODINGS) / sizeof(ENCODINGS[0]); i++)
  3670. if (appesModeEncoding == ENCODINGS[i]) {
  3671. valid = true;
  3672. break;
  3673. }
  3674. if (!valid)
  3675. quit(_fail, "Unexpected encoding for setAppesModeEncoding(encoding)");
  3676. ::appesModeEncoding = appesModeEncoding;
  3677. }
  3678. void registerInteraction(int argc, char *argv[]) {
  3679. __testlib_ensuresPreconditions();
  3680. __testlib_set_testset_and_group(argc, argv);
  3681. TestlibFinalizeGuard::registered = true;
  3682. testlibMode = _interactor;
  3683. __testlib_set_binary(stdin);
  3684. if (argc > 1 && !strcmp("--help", argv[1]))
  3685. __testlib_help();
  3686. if (argc < 3 || argc > 6) {
  3687. quit(_fail, std::string("Program must be run with the following arguments: ") +
  3688. std::string("<input-file> <output-file> [<answer-file> [<report-file> [<-appes>]]]") +
  3689. "\nUse \"--help\" to get help information");
  3690. }
  3691. if (argc <= 4) {
  3692. resultName = "";
  3693. appesMode = false;
  3694. }
  3695. #ifndef EJUDGE
  3696. if (argc == 5) {
  3697. resultName = argv[4];
  3698. appesMode = false;
  3699. }
  3700. if (argc == 6) {
  3701. if (strcmp("-APPES", argv[5]) && strcmp("-appes", argv[5])) {
  3702. quit(_fail, std::string("Program must be run with the following arguments: ") +
  3703. "<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]");
  3704. } else {
  3705. resultName = argv[4];
  3706. appesMode = true;
  3707. }
  3708. }
  3709. #endif
  3710. inf.init(argv[1], _input);
  3711. tout.open(argv[2], std::ios_base::out);
  3712. if (tout.fail() || !tout.is_open())
  3713. quit(_fail, std::string("Can not write to the test-output-file '") + argv[2] + std::string("'"));
  3714. ouf.init(stdin, _output);
  3715. if (argc >= 4)
  3716. ans.init(argv[3], _answer);
  3717. else
  3718. ans.name = "unopened answer stream";
  3719. }
  3720. void registerValidation() {
  3721. __testlib_ensuresPreconditions();
  3722. TestlibFinalizeGuard::registered = true;
  3723. testlibMode = _validator;
  3724. __testlib_set_binary(stdin);
  3725. __testlib_set_binary(stdout);
  3726. __testlib_set_binary(stderr);
  3727. inf.init(stdin, _input);
  3728. inf.strict = true;
  3729. }
  3730. void registerValidation(int argc, char *argv[]) {
  3731. registerValidation();
  3732. __testlib_set_testset_and_group(argc, argv);
  3733. validator.initialize();
  3734. TestlibFinalizeGuard::registered = true;
  3735. std::string comment = "Validator must be run with the following arguments:"
  3736. " [--testset testset]"
  3737. " [--group group]"
  3738. " [--testOverviewLogFileName fileName]"
  3739. " [--testMarkupFileName fileName]"
  3740. " [--testCase testCase]"
  3741. " [--testCaseFileName fileName]"
  3742. ;
  3743. for (int i = 1; i < argc; i++) {
  3744. if (!strcmp("--testset", argv[i])) {
  3745. if (i + 1 < argc && strlen(argv[i + 1]) > 0)
  3746. validator.setTestset(argv[++i]);
  3747. else
  3748. quit(_fail, comment);
  3749. }
  3750. if (!strcmp("--group", argv[i])) {
  3751. if (i + 1 < argc)
  3752. validator.setGroup(argv[++i]);
  3753. else
  3754. quit(_fail, comment);
  3755. }
  3756. if (!strcmp("--testOverviewLogFileName", argv[i])) {
  3757. if (i + 1 < argc)
  3758. validator.setTestOverviewLogFileName(argv[++i]);
  3759. else
  3760. quit(_fail, comment);
  3761. }
  3762. if (!strcmp("--testMarkupFileName", argv[i])) {
  3763. if (i + 1 < argc)
  3764. validator.setTestMarkupFileName(argv[++i]);
  3765. else
  3766. quit(_fail, comment);
  3767. }
  3768. if (!strcmp("--testCase", argv[i])) {
  3769. if (i + 1 < argc) {
  3770. long long testCase = stringToLongLong(inf, argv[++i]);
  3771. if (testCase < 1 || testCase >= __TESTLIB_MAX_TEST_CASE)
  3772. quit(_fail, format("Argument testCase should be between 1 and %d, but ", __TESTLIB_MAX_TEST_CASE)
  3773. + toString(testCase) + " found");
  3774. validator.setTestCase(int(testCase));
  3775. } else
  3776. quit(_fail, comment);
  3777. }
  3778. if (!strcmp("--testCaseFileName", argv[i])) {
  3779. if (i + 1 < argc) {
  3780. validator.setTestCaseFileName(argv[++i]);
  3781. } else
  3782. quit(_fail, comment);
  3783. }
  3784. }
  3785. }
  3786. void addFeature(const std::string &feature) {
  3787. if (testlibMode != _validator)
  3788. quit(_fail, "Features are supported in validators only.");
  3789. validator.addFeature(feature);
  3790. }
  3791. void feature(const std::string &feature) {
  3792. if (testlibMode != _validator)
  3793. quit(_fail, "Features are supported in validators only.");
  3794. validator.feature(feature);
  3795. }
  3796. class Checker {
  3797. private:
  3798. bool _initialized;
  3799. std::string _testset;
  3800. std::string _group;
  3801. public:
  3802. Checker() : _initialized(false), _testset("tests"), _group() {
  3803. }
  3804. void initialize() {
  3805. _initialized = true;
  3806. }
  3807. std::string testset() const {
  3808. if (!_initialized)
  3809. __testlib_fail("Checker should be initialized with registerTestlibCmd(argc, argv) instead of registerTestlibCmd() to support checker.testset()");
  3810. return _testset;
  3811. }
  3812. std::string group() const {
  3813. if (!_initialized)
  3814. __testlib_fail("Checker should be initialized with registerTestlibCmd(argc, argv) instead of registerTestlibCmd() to support checker.group()");
  3815. return _group;
  3816. }
  3817. void setTestset(const char *const testset) {
  3818. _testset = testset;
  3819. }
  3820. void setGroup(const char *const group) {
  3821. _group = group;
  3822. }
  3823. } checker;
  3824. void registerTestlibCmd(int argc, char *argv[]) {
  3825. __testlib_ensuresPreconditions();
  3826. __testlib_set_testset_and_group(argc, argv);
  3827. TestlibFinalizeGuard::registered = true;
  3828. testlibMode = _checker;
  3829. __testlib_set_binary(stdin);
  3830. std::vector<std::string> args(1, argv[0]);
  3831. checker.initialize();
  3832. for (int i = 1; i < argc; i++) {
  3833. if (!strcmp("--testset", argv[i])) {
  3834. if (i + 1 < argc && strlen(argv[i + 1]) > 0)
  3835. checker.setTestset(argv[++i]);
  3836. else
  3837. quit(_fail, std::string("Expected testset after --testset command line parameter"));
  3838. } else if (!strcmp("--group", argv[i])) {
  3839. if (i + 1 < argc)
  3840. checker.setGroup(argv[++i]);
  3841. else
  3842. quit(_fail, std::string("Expected group after --group command line parameter"));
  3843. } else
  3844. args.push_back(argv[i]);
  3845. }
  3846. argc = int(args.size());
  3847. if (argc > 1 && "--help" == args[1])
  3848. __testlib_help();
  3849. if (argc < 4 || argc > 6) {
  3850. quit(_fail, std::string("Program must be run with the following arguments: ") +
  3851. std::string("[--testset testset] [--group group] <input-file> <output-file> <answer-file> [<report-file> [<-appes>]]") +
  3852. "\nUse \"--help\" to get help information");
  3853. }
  3854. if (argc == 4) {
  3855. resultName = "";
  3856. appesMode = false;
  3857. }
  3858. if (argc == 5) {
  3859. resultName = args[4];
  3860. appesMode = false;
  3861. }
  3862. if (argc == 6) {
  3863. if ("-APPES" != args[5] && "-appes" != args[5]) {
  3864. quit(_fail, std::string("Program must be run with the following arguments: ") +
  3865. "<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]");
  3866. } else {
  3867. resultName = args[4];
  3868. appesMode = true;
  3869. }
  3870. }
  3871. inf.init(args[1], _input);
  3872. ouf.init(args[2], _output);
  3873. ans.init(args[3], _answer);
  3874. }
  3875. void registerTestlib(int argc, ...) {
  3876. if (argc < 3 || argc > 5)
  3877. quit(_fail, std::string("Program must be run with the following arguments: ") +
  3878. "<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]");
  3879. char **argv = new char *[argc + 1];
  3880. va_list ap;
  3881. va_start(ap, argc);
  3882. argv[0] = NULL;
  3883. for (int i = 0; i < argc; i++) {
  3884. argv[i + 1] = va_arg(ap, char*);
  3885. }
  3886. va_end(ap);
  3887. registerTestlibCmd(argc + 1, argv);
  3888. delete[] argv;
  3889. }
  3890. static inline void __testlib_ensure(bool cond, const std::string &msg) {
  3891. if (!cond)
  3892. quit(_fail, msg.c_str());
  3893. }
  3894. #ifdef __GNUC__
  3895. __attribute__((unused))
  3896. #endif
  3897. static inline void __testlib_ensure(bool cond, const char *msg) {
  3898. if (!cond)
  3899. quit(_fail, msg);
  3900. }
  3901. #define ensure(cond) __testlib_ensure(cond, "Condition failed: \"" #cond "\"")
  3902. #define STRINGIZE_DETAIL(x) #x
  3903. #define STRINGIZE(x) STRINGIZE_DETAIL(x)
  3904. #define ensure_ext(cond) __testlib_ensure(cond, "Line " STRINGIZE(__LINE__) ": Condition failed: \"" #cond "\"")
  3905. #ifdef __GNUC__
  3906. __attribute__ ((format (printf, 2, 3)))
  3907. #endif
  3908. inline void ensuref(bool cond, const char *format, ...) {
  3909. if (!cond) {
  3910. FMT_TO_RESULT(format, format, message);
  3911. __testlib_ensure(cond, message);
  3912. }
  3913. }
  3914. NORETURN static void __testlib_fail(const std::string &message) {
  3915. quitf(_fail, "%s", message.c_str());
  3916. }
  3917. #ifdef __GNUC__
  3918. __attribute__ ((format (printf, 1, 2)))
  3919. #endif
  3920. void setName(const char *format, ...) {
  3921. FMT_TO_RESULT(format, format, name);
  3922. checkerName = name;
  3923. }
  3924. /*
  3925. * Do not use random_shuffle, because it will produce different result
  3926. * for different C++ compilers.
  3927. *
  3928. * This implementation uses testlib random_t to produce random numbers, so
  3929. * it is stable.
  3930. */
  3931. template<typename _RandomAccessIter>
  3932. void shuffle(_RandomAccessIter __first, _RandomAccessIter __last) {
  3933. if (__first == __last) return;
  3934. for (_RandomAccessIter __i = __first + 1; __i != __last; ++__i)
  3935. std::iter_swap(__i, __first + rnd.next(int(__i - __first) + 1));
  3936. }
  3937. template<typename _RandomAccessIter>
  3938. #if defined(__GNUC__) && !defined(__clang__)
  3939. __attribute__ ((error("Don't use random_shuffle(), use shuffle() instead")))
  3940. #endif
  3941. void random_shuffle(_RandomAccessIter, _RandomAccessIter) {
  3942. quitf(_fail, "Don't use random_shuffle(), use shuffle() instead");
  3943. }
  3944. #ifdef __GLIBC__
  3945. # define RAND_THROW_STATEMENT throw()
  3946. #else
  3947. # define RAND_THROW_STATEMENT
  3948. #endif
  3949. #if defined(__GNUC__) && !defined(__clang__)
  3950. __attribute__ ((error("Don't use rand(), use rnd.next() instead")))
  3951. #endif
  3952. #ifdef _MSC_VER
  3953. # pragma warning( disable : 4273 )
  3954. #endif
  3955. int rand() RAND_THROW_STATEMENT
  3956. {
  3957. quitf(_fail, "Don't use rand(), use rnd.next() instead");
  3958. /* This line never runs. */
  3959. //throw "Don't use rand(), use rnd.next() instead";
  3960. }
  3961. #if defined(__GNUC__) && !defined(__clang__)
  3962. __attribute__ ((error("Don't use srand(), you should use "
  3963. "'registerGen(argc, argv, 1);' to initialize generator seed "
  3964. "by hash code of the command line params. The third parameter "
  3965. "is randomGeneratorVersion (currently the latest is 1).")))
  3966. #endif
  3967. #ifdef _MSC_VER
  3968. # pragma warning( disable : 4273 )
  3969. #endif
  3970. void srand(unsigned int seed) RAND_THROW_STATEMENT
  3971. {
  3972. quitf(_fail, "Don't use srand(), you should use "
  3973. "'registerGen(argc, argv, 1);' to initialize generator seed "
  3974. "by hash code of the command line params. The third parameter "
  3975. "is randomGeneratorVersion (currently the latest is 1) [ignored seed=%u].", seed);
  3976. }
  3977. void startTest(int test) {
  3978. const std::string testFileName = vtos(test);
  3979. if (NULL == freopen(testFileName.c_str(), "wt", stdout))
  3980. __testlib_fail("Unable to write file '" + testFileName + "'");
  3981. }
  3982. inline std::string compress(const std::string &s) {
  3983. return __testlib_part(s);
  3984. }
  3985. inline std::string englishEnding(int x) {
  3986. x %= 100;
  3987. if (x / 10 == 1)
  3988. return "th";
  3989. if (x % 10 == 1)
  3990. return "st";
  3991. if (x % 10 == 2)
  3992. return "nd";
  3993. if (x % 10 == 3)
  3994. return "rd";
  3995. return "th";
  3996. }
  3997. template<typename _ForwardIterator, typename _Separator>
  3998. std::string join(_ForwardIterator first, _ForwardIterator last, _Separator separator) {
  3999. std::stringstream ss;
  4000. bool repeated = false;
  4001. for (_ForwardIterator i = first; i != last; i++) {
  4002. if (repeated)
  4003. ss << separator;
  4004. else
  4005. repeated = true;
  4006. ss << *i;
  4007. }
  4008. return ss.str();
  4009. }
  4010. template<typename _ForwardIterator>
  4011. std::string join(_ForwardIterator first, _ForwardIterator last) {
  4012. return join(first, last, ' ');
  4013. }
  4014. template<typename _Collection, typename _Separator>
  4015. std::string join(const _Collection &collection, _Separator separator) {
  4016. return join(collection.begin(), collection.end(), separator);
  4017. }
  4018. template<typename _Collection>
  4019. std::string join(const _Collection &collection) {
  4020. return join(collection, ' ');
  4021. }
  4022. /**
  4023. * Splits string s by character separator returning exactly k+1 items,
  4024. * where k is the number of separator occurrences.
  4025. */
  4026. std::vector<std::string> split(const std::string &s, char separator) {
  4027. std::vector<std::string> result;
  4028. std::string item;
  4029. for (size_t i = 0; i < s.length(); i++)
  4030. if (s[i] == separator) {
  4031. result.push_back(item);
  4032. item = "";
  4033. } else
  4034. item += s[i];
  4035. result.push_back(item);
  4036. return result;
  4037. }
  4038. /**
  4039. * Splits string s by character separators returning exactly k+1 items,
  4040. * where k is the number of separator occurrences.
  4041. */
  4042. std::vector<std::string> split(const std::string &s, const std::string &separators) {
  4043. if (separators.empty())
  4044. return std::vector<std::string>(1, s);
  4045. std::vector<bool> isSeparator(256);
  4046. for (size_t i = 0; i < separators.size(); i++)
  4047. isSeparator[(unsigned char) (separators[i])] = true;
  4048. std::vector<std::string> result;
  4049. std::string item;
  4050. for (size_t i = 0; i < s.length(); i++)
  4051. if (isSeparator[(unsigned char) (s[i])]) {
  4052. result.push_back(item);
  4053. item = "";
  4054. } else
  4055. item += s[i];
  4056. result.push_back(item);
  4057. return result;
  4058. }
  4059. /**
  4060. * Splits string s by character separator returning non-empty items.
  4061. */
  4062. std::vector<std::string> tokenize(const std::string &s, char separator) {
  4063. std::vector<std::string> result;
  4064. std::string item;
  4065. for (size_t i = 0; i < s.length(); i++)
  4066. if (s[i] == separator) {
  4067. if (!item.empty())
  4068. result.push_back(item);
  4069. item = "";
  4070. } else
  4071. item += s[i];
  4072. if (!item.empty())
  4073. result.push_back(item);
  4074. return result;
  4075. }
  4076. /**
  4077. * Splits string s by character separators returning non-empty items.
  4078. */
  4079. std::vector<std::string> tokenize(const std::string &s, const std::string &separators) {
  4080. if (separators.empty())
  4081. return std::vector<std::string>(1, s);
  4082. std::vector<bool> isSeparator(256);
  4083. for (size_t i = 0; i < separators.size(); i++)
  4084. isSeparator[(unsigned char) (separators[i])] = true;
  4085. std::vector<std::string> result;
  4086. std::string item;
  4087. for (size_t i = 0; i < s.length(); i++)
  4088. if (isSeparator[(unsigned char) (s[i])]) {
  4089. if (!item.empty())
  4090. result.push_back(item);
  4091. item = "";
  4092. } else
  4093. item += s[i];
  4094. if (!item.empty())
  4095. result.push_back(item);
  4096. return result;
  4097. }
  4098. NORETURN void __testlib_expectedButFound(TResult result, std::string expected, std::string found, const char *prepend) {
  4099. std::string message;
  4100. if (strlen(prepend) != 0)
  4101. message = format("%s: expected '%s', but found '%s'",
  4102. compress(prepend).c_str(), compress(expected).c_str(), compress(found).c_str());
  4103. else
  4104. message = format("expected '%s', but found '%s'",
  4105. compress(expected).c_str(), compress(found).c_str());
  4106. quit(result, message);
  4107. }
  4108. NORETURN void __testlib_expectedButFound(TResult result, double expected, double found, const char *prepend) {
  4109. std::string expectedString = removeDoubleTrailingZeroes(format("%.12f", expected));
  4110. std::string foundString = removeDoubleTrailingZeroes(format("%.12f", found));
  4111. __testlib_expectedButFound(result, expectedString, foundString, prepend);
  4112. }
  4113. template<typename T>
  4114. #ifdef __GNUC__
  4115. __attribute__ ((format (printf, 4, 5)))
  4116. #endif
  4117. NORETURN void expectedButFound(TResult result, T expected, T found, const char *prependFormat = "", ...) {
  4118. FMT_TO_RESULT(prependFormat, prependFormat, prepend);
  4119. std::string expectedString = vtos(expected);
  4120. std::string foundString = vtos(found);
  4121. __testlib_expectedButFound(result, expectedString, foundString, prepend.c_str());
  4122. }
  4123. template<>
  4124. #ifdef __GNUC__
  4125. __attribute__ ((format (printf, 4, 5)))
  4126. #endif
  4127. NORETURN void
  4128. expectedButFound<std::string>(TResult result, std::string expected, std::string found, const char *prependFormat, ...) {
  4129. FMT_TO_RESULT(prependFormat, prependFormat, prepend);
  4130. __testlib_expectedButFound(result, expected, found, prepend.c_str());
  4131. }
  4132. template<>
  4133. #ifdef __GNUC__
  4134. __attribute__ ((format (printf, 4, 5)))
  4135. #endif
  4136. NORETURN void expectedButFound<double>(TResult result, double expected, double found, const char *prependFormat, ...) {
  4137. FMT_TO_RESULT(prependFormat, prependFormat, prepend);
  4138. std::string expectedString = removeDoubleTrailingZeroes(format("%.12f", expected));
  4139. std::string foundString = removeDoubleTrailingZeroes(format("%.12f", found));
  4140. __testlib_expectedButFound(result, expectedString, foundString, prepend.c_str());
  4141. }
  4142. template<>
  4143. #ifdef __GNUC__
  4144. __attribute__ ((format (printf, 4, 5)))
  4145. #endif
  4146. NORETURN void
  4147. expectedButFound<const char *>(TResult result, const char *expected, const char *found, const char *prependFormat,
  4148. ...) {
  4149. FMT_TO_RESULT(prependFormat, prependFormat, prepend);
  4150. __testlib_expectedButFound(result, std::string(expected), std::string(found), prepend.c_str());
  4151. }
  4152. template<>
  4153. #ifdef __GNUC__
  4154. __attribute__ ((format (printf, 4, 5)))
  4155. #endif
  4156. NORETURN void expectedButFound<float>(TResult result, float expected, float found, const char *prependFormat, ...) {
  4157. FMT_TO_RESULT(prependFormat, prependFormat, prepend);
  4158. __testlib_expectedButFound(result, double(expected), double(found), prepend.c_str());
  4159. }
  4160. template<>
  4161. #ifdef __GNUC__
  4162. __attribute__ ((format (printf, 4, 5)))
  4163. #endif
  4164. NORETURN void
  4165. expectedButFound<long double>(TResult result, long double expected, long double found, const char *prependFormat, ...) {
  4166. FMT_TO_RESULT(prependFormat, prependFormat, prepend);
  4167. __testlib_expectedButFound(result, double(expected), double(found), prepend.c_str());
  4168. }
  4169. #if __cplusplus > 199711L || defined(_MSC_VER)
  4170. template<typename T>
  4171. struct is_iterable {
  4172. template<typename U>
  4173. static char test(typename U::iterator *x);
  4174. template<typename U>
  4175. static long test(U *x);
  4176. static const bool value = sizeof(test<T>(0)) == 1;
  4177. };
  4178. template<bool B, class T = void>
  4179. struct __testlib_enable_if {
  4180. };
  4181. template<class T>
  4182. struct __testlib_enable_if<true, T> {
  4183. typedef T type;
  4184. };
  4185. template<typename T>
  4186. typename __testlib_enable_if<!is_iterable<T>::value, void>::type __testlib_print_one(const T &t) {
  4187. std::cout << t;
  4188. }
  4189. template<typename T>
  4190. typename __testlib_enable_if<is_iterable<T>::value, void>::type __testlib_print_one(const T &t) {
  4191. bool first = true;
  4192. for (typename T::const_iterator i = t.begin(); i != t.end(); i++) {
  4193. if (first)
  4194. first = false;
  4195. else
  4196. std::cout << " ";
  4197. std::cout << *i;
  4198. }
  4199. }
  4200. template<>
  4201. typename __testlib_enable_if<is_iterable<std::string>::value, void>::type
  4202. __testlib_print_one<std::string>(const std::string &t) {
  4203. std::cout << t;
  4204. }
  4205. template<typename A, typename B>
  4206. void __println_range(A begin, B end) {
  4207. bool first = true;
  4208. for (B i = B(begin); i != end; i++) {
  4209. if (first)
  4210. first = false;
  4211. else
  4212. std::cout << " ";
  4213. __testlib_print_one(*i);
  4214. }
  4215. std::cout << std::endl;
  4216. }
  4217. template<class T, class Enable = void>
  4218. struct is_iterator {
  4219. static T makeT();
  4220. typedef void *twoptrs[2];
  4221. static twoptrs &test(...);
  4222. template<class R>
  4223. static typename R::iterator_category *test(R);
  4224. template<class R>
  4225. static void *test(R *);
  4226. static const bool value = sizeof(test(makeT())) == sizeof(void *);
  4227. };
  4228. template<class T>
  4229. struct is_iterator<T, typename __testlib_enable_if<std::is_array<T>::value>::type> {
  4230. static const bool value = false;
  4231. };
  4232. template<typename A, typename B>
  4233. typename __testlib_enable_if<!is_iterator<B>::value, void>::type println(const A &a, const B &b) {
  4234. __testlib_print_one(a);
  4235. std::cout << " ";
  4236. __testlib_print_one(b);
  4237. std::cout << std::endl;
  4238. }
  4239. template<typename A, typename B>
  4240. typename __testlib_enable_if<is_iterator<B>::value, void>::type println(const A &a, const B &b) {
  4241. __println_range(a, b);
  4242. }
  4243. template<typename A>
  4244. void println(const A *a, const A *b) {
  4245. __println_range(a, b);
  4246. }
  4247. template<>
  4248. void println<char>(const char *a, const char *b) {
  4249. __testlib_print_one(a);
  4250. std::cout << " ";
  4251. __testlib_print_one(b);
  4252. std::cout << std::endl;
  4253. }
  4254. template<typename T>
  4255. void println(const T &x) {
  4256. __testlib_print_one(x);
  4257. std::cout << std::endl;
  4258. }
  4259. template<typename A, typename B, typename C>
  4260. void println(const A &a, const B &b, const C &c) {
  4261. __testlib_print_one(a);
  4262. std::cout << " ";
  4263. __testlib_print_one(b);
  4264. std::cout << " ";
  4265. __testlib_print_one(c);
  4266. std::cout << std::endl;
  4267. }
  4268. template<typename A, typename B, typename C, typename D>
  4269. void println(const A &a, const B &b, const C &c, const D &d) {
  4270. __testlib_print_one(a);
  4271. std::cout << " ";
  4272. __testlib_print_one(b);
  4273. std::cout << " ";
  4274. __testlib_print_one(c);
  4275. std::cout << " ";
  4276. __testlib_print_one(d);
  4277. std::cout << std::endl;
  4278. }
  4279. template<typename A, typename B, typename C, typename D, typename E>
  4280. void println(const A &a, const B &b, const C &c, const D &d, const E &e) {
  4281. __testlib_print_one(a);
  4282. std::cout << " ";
  4283. __testlib_print_one(b);
  4284. std::cout << " ";
  4285. __testlib_print_one(c);
  4286. std::cout << " ";
  4287. __testlib_print_one(d);
  4288. std::cout << " ";
  4289. __testlib_print_one(e);
  4290. std::cout << std::endl;
  4291. }
  4292. template<typename A, typename B, typename C, typename D, typename E, typename F>
  4293. void println(const A &a, const B &b, const C &c, const D &d, const E &e, const F &f) {
  4294. __testlib_print_one(a);
  4295. std::cout << " ";
  4296. __testlib_print_one(b);
  4297. std::cout << " ";
  4298. __testlib_print_one(c);
  4299. std::cout << " ";
  4300. __testlib_print_one(d);
  4301. std::cout << " ";
  4302. __testlib_print_one(e);
  4303. std::cout << " ";
  4304. __testlib_print_one(f);
  4305. std::cout << std::endl;
  4306. }
  4307. template<typename A, typename B, typename C, typename D, typename E, typename F, typename G>
  4308. void println(const A &a, const B &b, const C &c, const D &d, const E &e, const F &f, const G &g) {
  4309. __testlib_print_one(a);
  4310. std::cout << " ";
  4311. __testlib_print_one(b);
  4312. std::cout << " ";
  4313. __testlib_print_one(c);
  4314. std::cout << " ";
  4315. __testlib_print_one(d);
  4316. std::cout << " ";
  4317. __testlib_print_one(e);
  4318. std::cout << " ";
  4319. __testlib_print_one(f);
  4320. std::cout << " ";
  4321. __testlib_print_one(g);
  4322. std::cout << std::endl;
  4323. }
  4324. /* opts */
  4325. /**
  4326. * A struct for a singular testlib opt, containing the raw string value,
  4327. * and a boolean value for marking whether the opt is used.
  4328. */
  4329. struct TestlibOpt {
  4330. std::string value;
  4331. bool used;
  4332. TestlibOpt() : value(), used(false) {}
  4333. };
  4334. /**
  4335. * Get the type of opt based on the number of `-` at the beginning and the
  4336. * _validity_ of the key name.
  4337. *
  4338. * A valid key name must start with an alphabetical character.
  4339. *
  4340. * Returns: 1 if s has one `-` at the beginning, that is, "-keyName".
  4341. * 2 if s has two `-` at the beginning, that is, "--keyName".
  4342. * 0 otherwise. That is, if s has no `-` at the beginning, or has more
  4343. * than 2 at the beginning ("---keyName", "----keyName", ...), or the
  4344. * keyName is invalid (the first character is not an alphabetical
  4345. * character).
  4346. */
  4347. size_t getOptType(char *s) {
  4348. if (!s || strlen(s) <= 1)
  4349. return 0;
  4350. if (s[0] == '-') {
  4351. if (isalpha(s[1]))
  4352. return 1;
  4353. else if (s[1] == '-')
  4354. return isalpha(s[2]) ? 2 : 0;
  4355. }
  4356. return 0;
  4357. }
  4358. /**
  4359. * Parse the opt at a given index, and put it into the opts maps.
  4360. *
  4361. * An opt can has the following form:
  4362. * 1) -keyName=value or --keyName=value (ex. -n=10 --test-count=20)
  4363. * 2) -keyName value or --keyName value (ex. -n 10 --test-count 20)
  4364. * 3) -kNumval or --kNumval (ex. -n10 --t20)
  4365. * 4) -boolProperty or --boolProperty (ex. -sorted --tree-only)
  4366. *
  4367. * Only the second form consumes 2 arguments. The other consumes only 1
  4368. * argument.
  4369. *
  4370. * In the third form, the key is a single character, and after the key is the
  4371. * value. The value _should_ be a number.
  4372. *
  4373. * In the forth form, the value is true.
  4374. *
  4375. * Params:
  4376. * - argc and argv: the number of command line arguments and the command line
  4377. * arguments themselves.
  4378. * - index: the starting index of the opts.
  4379. * - opts: the map containing the resulting opt.
  4380. *
  4381. * Returns: the number of consumed arguments to parse the opt.
  4382. * 0 if there is no arguments to parse.
  4383. *
  4384. * Algorithm details:
  4385. * TODO. Please refer to the implementation to see how the code handles the 3rd and 4th forms separately.
  4386. */
  4387. size_t parseOpt(size_t argc, char *argv[], size_t index, std::map<std::string, TestlibOpt> &opts) {
  4388. if (index >= argc)
  4389. return 0;
  4390. size_t type = getOptType(argv[index]), inc = 1;
  4391. if (type > 0) {
  4392. std::string key(argv[index] + type), val;
  4393. size_t sep = key.find('=');
  4394. if (sep != std::string::npos) {
  4395. val = key.substr(sep + 1);
  4396. key = key.substr(0, sep);
  4397. } else {
  4398. if (index + 1 < argc && getOptType(argv[index + 1]) == 0) {
  4399. val = argv[index + 1];
  4400. inc = 2;
  4401. } else {
  4402. if (key.length() > 1 && isdigit(key[1])) {
  4403. val = key.substr(1);
  4404. key = key.substr(0, 1);
  4405. } else {
  4406. val = "true";
  4407. }
  4408. }
  4409. }
  4410. opts[key].value = val;
  4411. } else {
  4412. return inc;
  4413. }
  4414. return inc;
  4415. }
  4416. /**
  4417. * Global list containing all the arguments in the order given in the command line.
  4418. */
  4419. std::vector<std::string> __testlib_argv;
  4420. /**
  4421. * Global dictionary containing all the parsed opts.
  4422. */
  4423. std::map<std::string, TestlibOpt> __testlib_opts;
  4424. /**
  4425. * Whether automatic no unused opts ensurement should be done. This flag will
  4426. * be turned on when `has_opt` or `opt(key, default_value)` is called.
  4427. *
  4428. * The automatic ensurement can be suppressed when
  4429. * __testlib_ensureNoUnusedOptsSuppressed is true.
  4430. */
  4431. bool __testlib_ensureNoUnusedOptsFlag = false;
  4432. /**
  4433. * Suppress no unused opts automatic ensurement. Can be set to true with
  4434. * `suppressEnsureNoUnusedOpts()`.
  4435. */
  4436. bool __testlib_ensureNoUnusedOptsSuppressed = false;
  4437. /**
  4438. * Parse command line arguments into opts.
  4439. * The results are stored into __testlib_argv and __testlib_opts.
  4440. */
  4441. void prepareOpts(int argc, char *argv[]) {
  4442. if (argc <= 0)
  4443. __testlib_fail("Opts: expected argc>=0 but found " + toString(argc));
  4444. size_t n = static_cast<size_t>(argc); // NOLINT(hicpp-use-auto,modernize-use-auto)
  4445. __testlib_opts = std::map<std::string, TestlibOpt>();
  4446. for (size_t index = 1; index < n; index += parseOpt(n, argv, index, __testlib_opts));
  4447. __testlib_argv = std::vector<std::string>(n);
  4448. for (size_t index = 0; index < n; index++)
  4449. __testlib_argv[index] = argv[index];
  4450. }
  4451. /**
  4452. * An utility function to get the argument with a given index. This function
  4453. * also print a readable message when no arguments are found.
  4454. */
  4455. std::string __testlib_indexToArgv(int index) {
  4456. if (index < 0 || index >= int(__testlib_argv.size()))
  4457. __testlib_fail("Opts: index '" + toString(index) + "' is out of range [0,"
  4458. + toString(__testlib_argv.size()) + ")");
  4459. return __testlib_argv[size_t(index)];
  4460. }
  4461. /**
  4462. * An utility function to get the opt with a given key . This function
  4463. * also print a readable message when no opts are found.
  4464. */
  4465. std::string __testlib_keyToOpts(const std::string &key) {
  4466. auto it = __testlib_opts.find(key);
  4467. if (it == __testlib_opts.end())
  4468. __testlib_fail("Opts: unknown key '" + compress(key) + "'");
  4469. it->second.used = true;
  4470. return it->second.value;
  4471. }
  4472. template<typename T>
  4473. T optValueToIntegral(const std::string &s, bool nonnegative);
  4474. long double optValueToLongDouble(const std::string &s);
  4475. std::string parseExponentialOptValue(const std::string &s) {
  4476. size_t pos = std::string::npos;
  4477. for (size_t i = 0; i < s.length(); i++)
  4478. if (s[i] == 'e' || s[i] == 'E') {
  4479. if (pos != std::string::npos)
  4480. __testlib_fail("Opts: expected typical exponential notation but '" + compress(s) + "' found");
  4481. pos = i;
  4482. }
  4483. if (pos == std::string::npos)
  4484. return s;
  4485. std::string e = s.substr(pos + 1);
  4486. if (!e.empty() && e[0] == '+')
  4487. e = e.substr(1);
  4488. if (e.empty())
  4489. __testlib_fail("Opts: expected typical exponential notation but '" + compress(s) + "' found");
  4490. if (e.length() > 20)
  4491. __testlib_fail("Opts: expected typical exponential notation but '" + compress(s) + "' found");
  4492. int ne = optValueToIntegral<int>(e, false);
  4493. std::string num = s.substr(0, pos);
  4494. if (num.length() > 20)
  4495. __testlib_fail("Opts: expected typical exponential notation but '" + compress(s) + "' found");
  4496. if (!num.empty() && num[0] == '+')
  4497. num = num.substr(1);
  4498. optValueToLongDouble(num);
  4499. bool minus = false;
  4500. if (num[0] == '-') {
  4501. minus = true;
  4502. num = num.substr(1);
  4503. }
  4504. for (int i = 0; i < +ne; i++) {
  4505. size_t sep = num.find('.');
  4506. if (sep == std::string::npos)
  4507. num += '0';
  4508. else {
  4509. if (sep + 1 == num.length())
  4510. num[sep] = '0';
  4511. else
  4512. std::swap(num[sep], num[sep + 1]);
  4513. }
  4514. }
  4515. for (int i = 0; i < -ne; i++) {
  4516. size_t sep = num.find('.');
  4517. if (sep == std::string::npos)
  4518. num.insert(num.begin() + int(num.length()) - 1, '.');
  4519. else {
  4520. if (sep == 0)
  4521. num.insert(num.begin() + 1, '0');
  4522. else
  4523. std::swap(num[sep - 1], num[sep]);
  4524. }
  4525. }
  4526. while (!num.empty() && num[0] == '0')
  4527. num = num.substr(1);
  4528. while (num.find('.') != std::string::npos && num.back() == '0')
  4529. num = num.substr(0, num.length() - 1);
  4530. if (!num.empty() && num.back() == '.')
  4531. num = num.substr(0, num.length() - 1);
  4532. if ((!num.empty() && num[0] == '.') || num.empty())
  4533. num.insert(num.begin(), '0');
  4534. return (minus ? "-" : "") + num;
  4535. }
  4536. template<typename T>
  4537. T optValueToIntegral(const std::string &s_, bool nonnegative) {
  4538. std::string s(parseExponentialOptValue(s_));
  4539. if (s.empty())
  4540. __testlib_fail("Opts: expected integer but '" + compress(s_) + "' found");
  4541. T value = 0;
  4542. long double about = 0.0;
  4543. signed char sign = +1;
  4544. size_t pos = 0;
  4545. if (s[pos] == '-') {
  4546. if (nonnegative)
  4547. __testlib_fail("Opts: expected non-negative integer but '" + compress(s_) + "' found");
  4548. sign = -1;
  4549. pos++;
  4550. }
  4551. for (size_t i = pos; i < s.length(); i++) {
  4552. if (s[i] < '0' || s[i] > '9')
  4553. __testlib_fail("Opts: expected integer but '" + compress(s_) + "' found");
  4554. value = value * 10 + s[i] - '0';
  4555. about = about * 10 + s[i] - '0';
  4556. }
  4557. value *= sign;
  4558. about *= sign;
  4559. if (fabsl(value - about) > 0.1)
  4560. __testlib_fail("Opts: integer overflow: expected integer but '" + compress(s_) + "' found");
  4561. return value;
  4562. }
  4563. long double optValueToLongDouble(const std::string &s_) {
  4564. std::string s(parseExponentialOptValue(s_));
  4565. if (s.empty())
  4566. __testlib_fail("Opts: expected float number but '" + compress(s_) + "' found");
  4567. long double value = 0.0;
  4568. signed char sign = +1;
  4569. size_t pos = 0;
  4570. if (s[pos] == '-') {
  4571. sign = -1;
  4572. pos++;
  4573. }
  4574. bool period = false;
  4575. long double mul = 1.0;
  4576. for (size_t i = pos; i < s.length(); i++) {
  4577. if (s[i] == '.') {
  4578. if (period)
  4579. __testlib_fail("Opts: expected float number but '" + compress(s_) + "' found");
  4580. else {
  4581. period = true;
  4582. continue;
  4583. }
  4584. }
  4585. if (period)
  4586. mul *= 10.0;
  4587. if (s[i] < '0' || s[i] > '9')
  4588. __testlib_fail("Opts: expected float number but '" + compress(s_) + "' found");
  4589. if (period)
  4590. value += (s[i] - '0') / mul;
  4591. else
  4592. value = value * 10 + s[i] - '0';
  4593. }
  4594. value *= sign;
  4595. return value;
  4596. }
  4597. /**
  4598. * Return true if there is an opt with a given key.
  4599. *
  4600. * By calling this function, automatic ensurement for no unused opts will be
  4601. * done when the program is finalized. Call suppressEnsureNoUnusedOpts() to
  4602. * turn it off.
  4603. */
  4604. bool has_opt(const std::string &key) {
  4605. __testlib_ensureNoUnusedOptsFlag = true;
  4606. return __testlib_opts.count(key) != 0;
  4607. }
  4608. /* About the following part for opt with 2 and 3 arguments.
  4609. *
  4610. * To parse the argv/opts correctly for a give type (integer, floating point or
  4611. * string), some meta programming must be done to determine the type of
  4612. * the type, and use the correct parsing function accordingly.
  4613. *
  4614. * The pseudo algorithm for determining the type of T and parse it accordingly
  4615. * is as follows:
  4616. *
  4617. * if (T is integral type) {
  4618. * if (T is unsigned) {
  4619. * parse the argv/opt as an **unsigned integer** of type T.
  4620. * } else {
  4621. * parse the argv/opt as an **signed integer** of type T.
  4622. * } else {
  4623. * if (T is floating point type) {
  4624. * parse the argv/opt as an **floating point** of type T.
  4625. * } else {
  4626. * // T should be std::string
  4627. * just the raw content of the argv/opts.
  4628. * }
  4629. * }
  4630. *
  4631. * To help with meta programming, some `opt` function with 2 or 3 arguments are
  4632. * defined.
  4633. *
  4634. * Opt with 3 arguments: T opt(true/false is_integral, true/false is_unsigned, index/key)
  4635. *
  4636. * + The first argument is for determining whether the type T is an integral
  4637. * type. That is, the result of std::is_integral<T>() should be passed to
  4638. * this argument. When false, the type _should_ be either floating point or a
  4639. * std::string.
  4640. *
  4641. * + The second argument is for determining whether the signedness of the type
  4642. * T (if it is unsigned or signed). That is, the result of
  4643. * std::is_unsigned<T>() should be passed to this argument. This argument can
  4644. * be ignored if the first one is false, because it only applies to integer.
  4645. *
  4646. * Opt with 2 arguments: T opt(true/false is_floating_point, index/key)
  4647. * + The first argument is for determining whether the type T is a floating
  4648. * point type. That is, the result of std::is_floating_point<T>() should be
  4649. * passed to this argument. When false, the type _should_ be a std::string.
  4650. */
  4651. template<typename T>
  4652. T opt(std::false_type is_floating_point, int index);
  4653. template<>
  4654. std::string opt(std::false_type /*is_floating_point*/, int index) {
  4655. return __testlib_indexToArgv(index);
  4656. }
  4657. template<typename T>
  4658. T opt(std::true_type /*is_floating_point*/, int index) {
  4659. return T(optValueToLongDouble(__testlib_indexToArgv(index)));
  4660. }
  4661. template<typename T, typename U>
  4662. T opt(std::false_type /*is_integral*/, U /*is_unsigned*/, int index) {
  4663. return opt<T>(std::is_floating_point<T>(), index);
  4664. }
  4665. template<typename T>
  4666. T opt(std::true_type /*is_integral*/, std::false_type /*is_unsigned*/, int index) {
  4667. return optValueToIntegral<T>(__testlib_indexToArgv(index), false);
  4668. }
  4669. template<typename T>
  4670. T opt(std::true_type /*is_integral*/, std::true_type /*is_unsigned*/, int index) {
  4671. return optValueToIntegral<T>(__testlib_indexToArgv(index), true);
  4672. }
  4673. template<>
  4674. bool opt(std::true_type /*is_integral*/, std::true_type /*is_unsigned*/, int index) {
  4675. std::string value = __testlib_indexToArgv(index);
  4676. if (value == "true" || value == "1")
  4677. return true;
  4678. if (value == "false" || value == "0")
  4679. return false;
  4680. __testlib_fail("Opts: opt by index '" + toString(index) + "': expected bool true/false or 0/1 but '"
  4681. + compress(value) + "' found");
  4682. }
  4683. /**
  4684. * Return the parsed argv by a given index.
  4685. */
  4686. template<typename T>
  4687. T opt(int index) {
  4688. return opt<T>(std::is_integral<T>(), std::is_unsigned<T>(), index);
  4689. }
  4690. /**
  4691. * Return the raw string value of an argv by a given index.
  4692. */
  4693. std::string opt(int index) {
  4694. return opt<std::string>(index);
  4695. }
  4696. /**
  4697. * Return the parsed argv by a given index. If the index is bigger than
  4698. * the number of argv, return the given default_value.
  4699. */
  4700. template<typename T>
  4701. T opt(int index, const T &default_value) {
  4702. if (index >= int(__testlib_argv.size())) {
  4703. return default_value;
  4704. }
  4705. return opt<T>(index);
  4706. }
  4707. /**
  4708. * Return the raw string value of an argv by a given index. If the index is
  4709. * bigger than the number of argv, return the given default_value.
  4710. */
  4711. std::string opt(int index, const std::string &default_value) {
  4712. return opt<std::string>(index, default_value);
  4713. }
  4714. template<typename T>
  4715. T opt(std::false_type is_floating_point, const std::string &key);
  4716. template<>
  4717. std::string opt(std::false_type /*is_floating_point*/, const std::string &key) {
  4718. return __testlib_keyToOpts(key);
  4719. }
  4720. template<typename T>
  4721. T opt(std::true_type /*is_integral*/, const std::string &key) {
  4722. return T(optValueToLongDouble(__testlib_keyToOpts(key)));
  4723. }
  4724. template<typename T, typename U>
  4725. T opt(std::false_type /*is_integral*/, U, const std::string &key) {
  4726. return opt<T>(std::is_floating_point<T>(), key);
  4727. }
  4728. template<typename T>
  4729. T opt(std::true_type /*is_integral*/, std::false_type /*is_unsigned*/, const std::string &key) {
  4730. return optValueToIntegral<T>(__testlib_keyToOpts(key), false);
  4731. }
  4732. template<typename T>
  4733. T opt(std::true_type /*is_integral*/, std::true_type /*is_unsigned*/, const std::string &key) {
  4734. return optValueToIntegral<T>(__testlib_keyToOpts(key), true);
  4735. }
  4736. template<>
  4737. bool opt(std::true_type /*is_integral*/, std::true_type /*is_unsigned*/, const std::string &key) {
  4738. if (!has_opt(key))
  4739. return false;
  4740. std::string value = __testlib_keyToOpts(key);
  4741. if (value == "true" || value == "1")
  4742. return true;
  4743. if (value == "false" || value == "0")
  4744. return false;
  4745. __testlib_fail("Opts: key '" + compress(key) + "': expected bool true/false or 0/1 but '"
  4746. + compress(value) + "' found");
  4747. }
  4748. /**
  4749. * Return the parsed opt by a given key.
  4750. */
  4751. template<typename T>
  4752. T opt(const std::string &key) {
  4753. return opt<T>(std::is_integral<T>(), std::is_unsigned<T>(), key);
  4754. }
  4755. /**
  4756. * Return the raw string value of an opt by a given key
  4757. */
  4758. std::string opt(const std::string &key) {
  4759. return opt<std::string>(key);
  4760. }
  4761. /* Scorer started. */
  4762. enum TestResultVerdict {
  4763. SKIPPED,
  4764. OK,
  4765. WRONG_ANSWER,
  4766. RUNTIME_ERROR,
  4767. TIME_LIMIT_EXCEEDED,
  4768. IDLENESS_LIMIT_EXCEEDED,
  4769. MEMORY_LIMIT_EXCEEDED,
  4770. COMPILATION_ERROR,
  4771. CRASHED,
  4772. FAILED
  4773. };
  4774. std::string serializeVerdict(TestResultVerdict verdict) {
  4775. switch (verdict) {
  4776. case SKIPPED: return "SKIPPED";
  4777. case OK: return "OK";
  4778. case WRONG_ANSWER: return "WRONG_ANSWER";
  4779. case RUNTIME_ERROR: return "RUNTIME_ERROR";
  4780. case TIME_LIMIT_EXCEEDED: return "TIME_LIMIT_EXCEEDED";
  4781. case IDLENESS_LIMIT_EXCEEDED: return "IDLENESS_LIMIT_EXCEEDED";
  4782. case MEMORY_LIMIT_EXCEEDED: return "MEMORY_LIMIT_EXCEEDED";
  4783. case COMPILATION_ERROR: return "COMPILATION_ERROR";
  4784. case CRASHED: return "CRASHED";
  4785. case FAILED: return "FAILED";
  4786. }
  4787. throw "Unexpected verdict";
  4788. }
  4789. TestResultVerdict deserializeTestResultVerdict(std::string s) {
  4790. if (s == "SKIPPED")
  4791. return SKIPPED;
  4792. else if (s == "OK")
  4793. return OK;
  4794. else if (s == "WRONG_ANSWER")
  4795. return WRONG_ANSWER;
  4796. else if (s == "RUNTIME_ERROR")
  4797. return RUNTIME_ERROR;
  4798. else if (s == "TIME_LIMIT_EXCEEDED")
  4799. return TIME_LIMIT_EXCEEDED;
  4800. else if (s == "IDLENESS_LIMIT_EXCEEDED")
  4801. return IDLENESS_LIMIT_EXCEEDED;
  4802. else if (s == "MEMORY_LIMIT_EXCEEDED")
  4803. return MEMORY_LIMIT_EXCEEDED;
  4804. else if (s == "COMPILATION_ERROR")
  4805. return COMPILATION_ERROR;
  4806. else if (s == "CRASHED")
  4807. return CRASHED;
  4808. else if (s == "FAILED")
  4809. return FAILED;
  4810. ensuref(false, "Unexpected serialized TestResultVerdict");
  4811. // No return actually.
  4812. return FAILED;
  4813. }
  4814. struct TestResult {
  4815. int testIndex;
  4816. std::string testset;
  4817. std::string group;
  4818. TestResultVerdict verdict;
  4819. double points;
  4820. long long timeConsumed;
  4821. long long memoryConsumed;
  4822. std::string input;
  4823. std::string output;
  4824. std::string answer;
  4825. int exitCode;
  4826. std::string checkerComment;
  4827. };
  4828. std::string serializePoints(double points) {
  4829. if (std::isnan(points))
  4830. return "";
  4831. else {
  4832. char c[64];
  4833. snprintf(c, 64, "%.03lf", points);
  4834. return c;
  4835. }
  4836. }
  4837. double deserializePoints(std::string s) {
  4838. if (s.empty())
  4839. return std::numeric_limits<double>::quiet_NaN();
  4840. else {
  4841. double result;
  4842. ensuref(sscanf(s.c_str(), "%lf", &result) == 1, "Invalid serialized points");
  4843. return result;
  4844. }
  4845. }
  4846. std::string escapeTestResultString(std::string s) {
  4847. std::string result;
  4848. for (size_t i = 0; i < s.length(); i++) {
  4849. if (s[i] == '\r')
  4850. continue;
  4851. if (s[i] == '\n') {
  4852. result += "\\n";
  4853. continue;
  4854. }
  4855. if (s[i] == '\\' || s[i] == ';')
  4856. result += '\\';
  4857. result += s[i];
  4858. }
  4859. return result;
  4860. }
  4861. std::string unescapeTestResultString(std::string s) {
  4862. std::string result;
  4863. for (size_t i = 0; i < s.length(); i++) {
  4864. if (s[i] == '\\' && i + 1 < s.length()) {
  4865. if (s[i + 1] == 'n') {
  4866. result += '\n';
  4867. i++;
  4868. continue;
  4869. } else if (s[i + 1] == ';' || s[i + 1] == '\\') {
  4870. result += s[i + 1];
  4871. i++;
  4872. continue;
  4873. }
  4874. }
  4875. result += s[i];
  4876. }
  4877. return result;
  4878. }
  4879. std::string serializeTestResult(TestResult tr) {
  4880. std::string result;
  4881. result += std::to_string(tr.testIndex);
  4882. result += ";";
  4883. result += escapeTestResultString(tr.testset);
  4884. result += ";";
  4885. result += escapeTestResultString(tr.group);
  4886. result += ";";
  4887. result += serializeVerdict(tr.verdict);
  4888. result += ";";
  4889. result += serializePoints(tr.points);
  4890. result += ";";
  4891. result += std::to_string(tr.timeConsumed);
  4892. result += ";";
  4893. result += std::to_string(tr.memoryConsumed);
  4894. result += ";";
  4895. result += escapeTestResultString(tr.input);
  4896. result += ";";
  4897. result += escapeTestResultString(tr.output);
  4898. result += ";";
  4899. result += escapeTestResultString(tr.answer);
  4900. result += ";";
  4901. result += std::to_string(tr.exitCode);
  4902. result += ";";
  4903. result += escapeTestResultString(tr.checkerComment);
  4904. return result;
  4905. }
  4906. TestResult deserializeTestResult(std::string s) {
  4907. std::vector<std::string> items;
  4908. std::string t;
  4909. for (size_t i = 0; i < s.length(); i++) {
  4910. if (s[i] == '\\') {
  4911. t += s[i];
  4912. if (i + 1 < s.length())
  4913. t += s[i + 1];
  4914. i++;
  4915. continue;
  4916. } else {
  4917. if (s[i] == ';') {
  4918. items.push_back(t);
  4919. t = "";
  4920. } else
  4921. t += s[i];
  4922. }
  4923. }
  4924. items.push_back(t);
  4925. ensuref(items.size() == 12, "Invalid TestResult serialization: expected exactly 12 items");
  4926. TestResult tr;
  4927. size_t pos = 0;
  4928. tr.testIndex = stoi(items[pos++]);
  4929. tr.testset = unescapeTestResultString(items[pos++]);
  4930. tr.group = unescapeTestResultString(items[pos++]);
  4931. tr.verdict = deserializeTestResultVerdict(items[pos++]);
  4932. tr.points = deserializePoints(items[pos++]);
  4933. tr.timeConsumed = stoll(items[pos++]);
  4934. tr.memoryConsumed = stoll(items[pos++]);
  4935. tr.input = unescapeTestResultString(items[pos++]);
  4936. tr.output = unescapeTestResultString(items[pos++]);
  4937. tr.answer = unescapeTestResultString(items[pos++]);
  4938. tr.exitCode = stoi(items[pos++]);
  4939. tr.checkerComment = unescapeTestResultString(items[pos++]);
  4940. return tr;
  4941. }
  4942. std::vector<TestResult> readTestResults(std::string fileName) {
  4943. std::ifstream stream;
  4944. stream.open(fileName.c_str(), std::ios::in);
  4945. ensuref(stream.is_open(), "Can't read test results file '%s'", fileName.c_str());
  4946. std::vector<TestResult> result;
  4947. std::string line;
  4948. while (getline(stream, line))
  4949. if (!line.empty())
  4950. result.push_back(deserializeTestResult(line));
  4951. stream.close();
  4952. return result;
  4953. }
  4954. std::function<double(std::vector<TestResult>)> __testlib_scorer;
  4955. struct TestlibScorerGuard {
  4956. ~TestlibScorerGuard() {
  4957. if (testlibMode == _scorer) {
  4958. std::vector<TestResult> testResults;
  4959. while (!inf.eof()) {
  4960. std::string line = inf.readLine();
  4961. if (!line.empty())
  4962. testResults.push_back(deserializeTestResult(line));
  4963. }
  4964. inf.readEof();
  4965. printf("%.3f\n", __testlib_scorer(testResults));
  4966. }
  4967. }
  4968. } __testlib_scorer_guard;
  4969. void registerScorer(int argc, char *argv[], std::function<double(std::vector<TestResult>)> scorer) {
  4970. /* Suppress unused. */
  4971. (void)(argc), (void)(argv);
  4972. __testlib_ensuresPreconditions();
  4973. testlibMode = _scorer;
  4974. __testlib_set_binary(stdin);
  4975. inf.init(stdin, _input);
  4976. inf.strict = false;
  4977. __testlib_scorer = scorer;
  4978. }
  4979. /* Scorer ended. */
  4980. /**
  4981. * Return the parsed opt by a given key. If no opts with the given key are
  4982. * found, return the given default_value.
  4983. *
  4984. * By calling this function, automatic ensurement for no unused opts will be
  4985. * done when the program is finalized. Call suppressEnsureNoUnusedOpts() to
  4986. * turn it off.
  4987. */
  4988. template<typename T>
  4989. T opt(const std::string &key, const T &default_value) {
  4990. if (!has_opt(key)) {
  4991. return default_value;
  4992. }
  4993. return opt<T>(key);
  4994. }
  4995. /**
  4996. * Return the raw string value of an opt by a given key. If no opts with the
  4997. * given key are found, return the given default_value.
  4998. *
  4999. * By calling this function, automatic ensurement for no unused opts will be
  5000. * done when the program is finalized. Call suppressEnsureNoUnusedOpts() to
  5001. * turn it off.
  5002. */
  5003. std::string opt(const std::string &key, const std::string &default_value) {
  5004. return opt<std::string>(key, default_value);
  5005. }
  5006. /**
  5007. * Check if all opts are used. If not, __testlib_fail is called.
  5008. * Should be used after calling all opt() function calls.
  5009. *
  5010. * This function is useful when opt() with default_value for checking typos
  5011. * in the opt's key.
  5012. */
  5013. void ensureNoUnusedOpts() {
  5014. for (const auto &opt: __testlib_opts) {
  5015. if (!opt.second.used) {
  5016. __testlib_fail(format("Opts: unused key '%s'", compress(opt.first).c_str()));
  5017. }
  5018. }
  5019. }
  5020. void suppressEnsureNoUnusedOpts() {
  5021. __testlib_ensureNoUnusedOptsSuppressed = true;
  5022. }
  5023. void TestlibFinalizeGuard::autoEnsureNoUnusedOpts() {
  5024. if (__testlib_ensureNoUnusedOptsFlag && !__testlib_ensureNoUnusedOptsSuppressed) {
  5025. ensureNoUnusedOpts();
  5026. }
  5027. }
  5028. TestlibFinalizeGuard testlibFinalizeGuard;
  5029. #endif
  5030. #endif