testlib.h 191 KB

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