1
0

testlib.h 192 KB

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