testlib.h 194 KB

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