testlib.h 163 KB

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