testlib.h 172 KB

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