1
0

testlib.h 201 KB

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