1
0

testlib.h 199 KB

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