testlib.h 190 KB

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