testlib.h 193 KB

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