testlib.h 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013
  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 http://code.google.com/p/testlib/ to get latest version or bug tracker.
  19. */
  20. #ifndef _TESTLIB_H_
  21. #define _TESTLIB_H_
  22. /*
  23. * Copyright (c) 2005-2016
  24. */
  25. #define VERSION "0.9.11"
  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. "Introduced split/tokenize functions to separate string by given char",
  61. "Introduced InStream::readUnsignedLong and InStream::readLong with unsigned long long paramerters",
  62. "Supported --testOverviewLogFileName for validator: bounds hits + features",
  63. "Fixed UB (sequence points) in random_t",
  64. "POINTS_EXIT_CODE returned back to 7 (instead of 0)",
  65. "Removed disable buffers for interactive problems, because it works unexpectedly in wine",
  66. "InStream over string: constructor of InStream from base InStream to inherit policies and std::string",
  67. "Added expectedButFound quit function, examples: expectedButFound(_wa, 10, 20), expectedButFound(_fail, ja, pa, \"[n=%d,m=%d]\", n, m)",
  68. "Fixed incorrect interval parsing in patterns",
  69. "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)",
  70. "Introduced disableFinalizeGuard() to switch off finalization checkings",
  71. "Use join() functions to format a range of items as a single string (separated by spaces or other separators)",
  72. "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",
  73. "Use -DUSE_RND_AS_BEFORE_087 to compile in compatibility mode with random behavior of versions before 0.8.7",
  74. "Fixed bug with nan in stringToDouble",
  75. "Fixed issue around overloads for size_t on x64",
  76. "Added attribute 'points' to the XML output in case of result=_points",
  77. "Exit codes can be customized via macros, e.g. -DPE_EXIT_CODE=14",
  78. "Introduced InStream function readWordTo/readTokenTo/readStringTo/readLineTo for faster reading",
  79. "Introduced global functions: format(), englishEnding(), upperCase(), lowerCase(), compress()",
  80. "Manual buffer in InStreams, some IO speed improvements",
  81. "Introduced quitif(bool, const char* pattern, ...) which delegates to quitf() in case of first argument is true",
  82. "Introduced guard against missed quitf() in checker or readEof() in validators",
  83. "Supported readStrictReal/readStrictDouble - to use in validators to check strictly float numbers",
  84. "Supported registerInteraction(argc, argv)",
  85. "Print checker message to the stderr instead of stdout",
  86. "Supported TResult _points to output calculated score, use quitp(...) functions",
  87. "Fixed to be compilable on Mac",
  88. "PC_BASE_EXIT_CODE=50 in case of defined TESTSYS",
  89. "Fixed issues 19-21, added __attribute__ format printf",
  90. "Some bug fixes",
  91. "ouf.readInt(1, 100) and similar calls return WA",
  92. "Modified random_t to avoid integer overflow",
  93. "Truncated checker output [patch by Stepan Gatilov]",
  94. "Renamed class random -> class random_t",
  95. "Supported name parameter for read-and-validation methods, like readInt(1, 2, \"n\")",
  96. "Fixed bug in readDouble()",
  97. "Improved ensuref(), fixed nextLine to work in case of EOF, added startTest()",
  98. "Supported \"partially correct\", example: quitf(_pc(13), \"result=%d\", result)",
  99. "Added shuffle(begin, end), use it instead of random_shuffle(begin, end)",
  100. "Added readLine(const string& ptrn), fixed the logic of readLine() in the validation mode",
  101. "Package extended with samples of generators and validators",
  102. "Written the documentation for classes and public methods in testlib.h",
  103. "Implemented random routine to support generators, use registerGen() to switch it on",
  104. "Implemented strict mode to validate tests, use registerValidation() to switch it on",
  105. "Now ncmp.cpp and wcmp.cpp are return WA if answer is suffix or prefix of the output",
  106. "Added InStream::readLong() and removed InStream::readLongint()",
  107. "Now no footer added to each report by default (use directive FOOTER to switch on)",
  108. "Now every checker has a name, use setName(const char* format, ...) to set it",
  109. "Now it is compatible with TTS (by Kittens Computing)",
  110. "Added \'ensure(condition, message = \"\")\' feature, it works like assert()",
  111. "Fixed compatibility with MS C++ 7.1",
  112. "Added footer with exit code information",
  113. "Added compatibility with EJUDGE (compile with EJUDGE directive)"
  114. };
  115. #ifdef _MSC_VER
  116. #define _CRT_SECURE_NO_DEPRECATE
  117. #define _CRT_SECURE_NO_WARNINGS
  118. #endif
  119. /* Overrides random() for Borland C++. */
  120. #define random __random_deprecated
  121. #include <stdlib.h>
  122. #include <cstdlib>
  123. #include <climits>
  124. #include <algorithm>
  125. #undef random
  126. #include <cstdio>
  127. #include <cctype>
  128. #include <string>
  129. #include <vector>
  130. #include <map>
  131. #include <set>
  132. #include <cmath>
  133. #include <sstream>
  134. #include <fstream>
  135. #include <cstring>
  136. #include <limits>
  137. #include <stdarg.h>
  138. #include <fcntl.h>
  139. #if ( _WIN32 || __WIN32__ || _WIN64 || __WIN64__ )
  140. # if !defined(_MSC_VER) || _MSC_VER>1400
  141. # define NOMINMAX 1
  142. # include <windows.h>
  143. # else
  144. # define WORD unsigned short
  145. # include <unistd.h>
  146. # endif
  147. # include <io.h>
  148. # define ON_WINDOWS
  149. #else
  150. # define WORD unsigned short
  151. #endif
  152. #ifndef LLONG_MIN
  153. #define LLONG_MIN (-9223372036854775807LL - 1)
  154. #endif
  155. #ifndef ULLONG_MAX
  156. #define ULLONG_MAX (18446744073709551615)
  157. #endif
  158. #define LF ((char)10)
  159. #define CR ((char)13)
  160. #define TAB ((char)9)
  161. #define SPACE ((char)' ')
  162. #define EOFC (255)
  163. #ifndef OK_EXIT_CODE
  164. # define OK_EXIT_CODE 0
  165. #endif
  166. #ifndef WA_EXIT_CODE
  167. # ifdef EJUDGE
  168. # define WA_EXIT_CODE 5
  169. # else
  170. # define WA_EXIT_CODE 1
  171. # endif
  172. #endif
  173. #ifndef PE_EXIT_CODE
  174. # ifdef EJUDGE
  175. # define PE_EXIT_CODE 4
  176. # else
  177. # define PE_EXIT_CODE 2
  178. # endif
  179. #endif
  180. #ifndef FAIL_EXIT_CODE
  181. # ifdef EJUDGE
  182. # define FAIL_EXIT_CODE 6
  183. # else
  184. # define FAIL_EXIT_CODE 3
  185. # endif
  186. #endif
  187. #ifndef DIRT_EXIT_CODE
  188. # ifdef EJUDGE
  189. # define DIRT_EXIT_CODE 6
  190. # else
  191. # define DIRT_EXIT_CODE 4
  192. # endif
  193. #endif
  194. #ifndef POINTS_EXIT_CODE
  195. # define POINTS_EXIT_CODE 7
  196. #endif
  197. #ifndef UNEXPECTED_EOF_EXIT_CODE
  198. # define UNEXPECTED_EOF_EXIT_CODE 8
  199. #endif
  200. #ifndef PC_BASE_EXIT_CODE
  201. # ifdef TESTSYS
  202. # define PC_BASE_EXIT_CODE 50
  203. # else
  204. # define PC_BASE_EXIT_CODE 0
  205. # endif
  206. #endif
  207. #ifdef __GNUC__
  208. # define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[(condition) ? 1 : -1] __attribute__((unused))
  209. #else
  210. # define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[(condition) ? 1 : -1]
  211. #endif
  212. #ifdef ON_WINDOWS
  213. #define I64 "%I64d"
  214. #define U64 "%I64u"
  215. #else
  216. #define I64 "%lld"
  217. #define U64 "%llu"
  218. #endif
  219. #ifdef _MSC_VER
  220. # define NORETURN __declspec(noreturn)
  221. #elif defined __GNUC__
  222. # define NORETURN __attribute__ ((noreturn))
  223. #else
  224. # define NORETURN
  225. #endif
  226. static char __testlib_format_buffer[16777216];
  227. static int __testlib_format_buffer_usage_count = 0;
  228. #define FMT_TO_RESULT(fmt, cstr, result) std::string result; \
  229. if (__testlib_format_buffer_usage_count != 0) \
  230. __testlib_fail("FMT_TO_RESULT::__testlib_format_buffer_usage_count != 0"); \
  231. __testlib_format_buffer_usage_count++; \
  232. va_list ap; \
  233. va_start(ap, fmt); \
  234. std::vsprintf(__testlib_format_buffer, cstr, ap); \
  235. va_end(ap); \
  236. result = std::string(__testlib_format_buffer); \
  237. __testlib_format_buffer_usage_count--; \
  238. const long long __TESTLIB_LONGLONG_MAX = 9223372036854775807LL;
  239. NORETURN static void __testlib_fail(const std::string& message);
  240. template<typename T>
  241. static inline T __testlib_abs(const T& x)
  242. {
  243. return x > 0 ? x : -x;
  244. }
  245. template<typename T>
  246. static inline T __testlib_min(const T& a, const T& b)
  247. {
  248. return a < b ? a : b;
  249. }
  250. template<typename T>
  251. static inline T __testlib_max(const T& a, const T& b)
  252. {
  253. return a > b ? a : b;
  254. }
  255. static bool __testlib_prelimIsNaN(double r)
  256. {
  257. volatile double ra = r;
  258. #ifndef __BORLANDC__
  259. return ((ra != ra) == true) && ((ra == ra) == false) && ((1.0 > ra) == false) && ((1.0 < ra) == false);
  260. #else
  261. return std::_isnan(ra);
  262. #endif
  263. }
  264. static std::string removeDoubleTrailingZeroes(std::string value)
  265. {
  266. while (!value.empty() && value[value.length() - 1] == '0' && value.find('.') != std::string::npos)
  267. value = value.substr(0, value.length() - 1);
  268. return value + '0';
  269. }
  270. #ifdef __GNUC__
  271. __attribute__ ((format (printf, 1, 2)))
  272. #endif
  273. std::string format(const char* fmt, ...)
  274. {
  275. FMT_TO_RESULT(fmt, fmt, result);
  276. return result;
  277. }
  278. std::string format(const std::string& fmt, ...)
  279. {
  280. FMT_TO_RESULT(fmt, fmt.c_str(), result);
  281. return result;
  282. }
  283. static std::string __testlib_part(const std::string& s);
  284. static bool __testlib_isNaN(double r)
  285. {
  286. __TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long));
  287. volatile double ra = r;
  288. long long llr1, llr2;
  289. std::memcpy((void*)&llr1, (void*)&ra, sizeof(double));
  290. ra = -ra;
  291. std::memcpy((void*)&llr2, (void*)&ra, sizeof(double));
  292. long long llnan = 0xFFF8000000000000;
  293. return __testlib_prelimIsNaN(r) || llnan == llr1 || llnan == llr2;
  294. }
  295. static double __testlib_nan()
  296. {
  297. __TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long));
  298. #ifndef NAN
  299. long long llnan = 0xFFF8000000000000;
  300. double nan;
  301. std::memcpy(&nan, &llnan, sizeof(double));
  302. return nan;
  303. #else
  304. return NAN;
  305. #endif
  306. }
  307. static bool __testlib_isInfinite(double r)
  308. {
  309. volatile double ra = r;
  310. return (ra > 1E300 || ra < -1E300);
  311. }
  312. #ifdef __GNUC__
  313. __attribute__((const))
  314. #endif
  315. inline bool doubleCompare(double expected, double result, double MAX_DOUBLE_ERROR)
  316. {
  317. if (__testlib_isNaN(expected))
  318. {
  319. return __testlib_isNaN(result);
  320. }
  321. else
  322. if (__testlib_isInfinite(expected))
  323. {
  324. if (expected > 0)
  325. {
  326. return result > 0 && __testlib_isInfinite(result);
  327. }
  328. else
  329. {
  330. return result < 0 && __testlib_isInfinite(result);
  331. }
  332. }
  333. else
  334. if (__testlib_isNaN(result) || __testlib_isInfinite(result))
  335. {
  336. return false;
  337. }
  338. else
  339. if (__testlib_abs(result - expected) <= MAX_DOUBLE_ERROR + 1E-15)
  340. {
  341. return true;
  342. }
  343. else
  344. {
  345. double minv = __testlib_min(expected * (1.0 - MAX_DOUBLE_ERROR),
  346. expected * (1.0 + MAX_DOUBLE_ERROR));
  347. double maxv = __testlib_max(expected * (1.0 - MAX_DOUBLE_ERROR),
  348. expected * (1.0 + MAX_DOUBLE_ERROR));
  349. return result + 1E-15 >= minv && result <= maxv + 1E-15;
  350. }
  351. }
  352. #ifdef __GNUC__
  353. __attribute__((const))
  354. #endif
  355. inline double doubleDelta(double expected, double result)
  356. {
  357. double absolute = __testlib_abs(result - expected);
  358. if (__testlib_abs(expected) > 1E-9)
  359. {
  360. double relative = __testlib_abs(absolute / expected);
  361. return __testlib_min(absolute, relative);
  362. }
  363. else
  364. return absolute;
  365. }
  366. #ifndef _fileno
  367. #define _fileno(_stream) ((_stream)->_file)
  368. #endif
  369. #ifndef O_BINARY
  370. static void __testlib_set_binary(
  371. #ifdef __GNUC__
  372. __attribute__((unused))
  373. #endif
  374. std::FILE* file
  375. )
  376. #else
  377. static void __testlib_set_binary(std::FILE* file)
  378. #endif
  379. {
  380. #ifdef O_BINARY
  381. if (NULL != file)
  382. {
  383. #ifndef __BORLANDC__
  384. _setmode(_fileno(file), O_BINARY);
  385. #else
  386. setmode(fileno(file), O_BINARY);
  387. #endif
  388. }
  389. #endif
  390. }
  391. /*
  392. * Very simple regex-like pattern.
  393. * It used for two purposes: validation and generation.
  394. *
  395. * For example, pattern("[a-z]{1,5}").next(rnd) will return
  396. * random string from lowercase latin letters with length
  397. * from 1 to 5. It is easier to call rnd.next("[a-z]{1,5}")
  398. * for the same effect.
  399. *
  400. * Another samples:
  401. * "mike|john" will generate (match) "mike" or "john";
  402. * "-?[1-9][0-9]{0,3}" will generate (match) non-zero integers from -9999 to 9999;
  403. * "id-([ac]|b{2})" will generate (match) "id-a", "id-bb", "id-c";
  404. * "[^0-9]*" will match sequences (empty or non-empty) without digits, you can't
  405. * use it for generations.
  406. *
  407. * You can't use pattern for generation if it contains meta-symbol '*'. Also it
  408. * is not recommended to use it for char-sets with meta-symbol '^' like [^a-z].
  409. *
  410. * For matching very simple greedy algorithm is used. For example, pattern
  411. * "[0-9]?1" will not match "1", because of greedy nature of matching.
  412. * Alternations (meta-symbols "|") are processed with brute-force algorithm, so
  413. * do not use many alternations in one expression.
  414. *
  415. * If you want to use one expression many times it is better to compile it into
  416. * a single pattern like "pattern p("[a-z]+")". Later you can use
  417. * "p.matches(std::string s)" or "p.next(random_t& rd)" to check matching or generate
  418. * new string by pattern.
  419. *
  420. * Simpler way to read token and check it for pattern matching is "inf.readToken("[a-z]+")".
  421. */
  422. class random_t;
  423. class pattern
  424. {
  425. public:
  426. /* Create pattern instance by string. */
  427. pattern(std::string s);
  428. /* Generate new string by pattern and given random_t. */
  429. std::string next(random_t& rnd) const;
  430. /* Checks if given string match the pattern. */
  431. bool matches(const std::string& s) const;
  432. /* Returns source string of the pattern. */
  433. std::string src() const;
  434. private:
  435. bool matches(const std::string& s, size_t pos) const;
  436. std::string s;
  437. std::vector<pattern> children;
  438. std::vector<char> chars;
  439. int from;
  440. int to;
  441. };
  442. /*
  443. * Use random_t instances to generate random values. It is preffered
  444. * way to use randoms instead of rand() function or self-written
  445. * randoms.
  446. *
  447. * Testlib defines global variable "rnd" of random_t class.
  448. * Use registerGen(argc, argv, 1) to setup random_t seed be command
  449. * line (to use latest random generator version).
  450. *
  451. * Random generates uniformly distributed values if another strategy is
  452. * not specified explicitly.
  453. */
  454. class random_t
  455. {
  456. private:
  457. unsigned long long seed;
  458. static const unsigned long long multiplier;
  459. static const unsigned long long addend;
  460. static const unsigned long long mask;
  461. static const int lim;
  462. long long nextBits(int bits)
  463. {
  464. if (bits <= 48)
  465. {
  466. seed = (seed * multiplier + addend) & mask;
  467. return (long long)(seed >> (48 - bits));
  468. }
  469. else
  470. {
  471. if (bits > 63)
  472. __testlib_fail("random_t::nextBits(int bits): n must be less than 64");
  473. int lowerBitCount = (random_t::version == 0 ? 31 : 32);
  474. long long left = (nextBits(31) << 32);
  475. long long right = nextBits(lowerBitCount);
  476. return left ^ right;
  477. }
  478. }
  479. public:
  480. static int version;
  481. /* New random_t with fixed seed. */
  482. random_t()
  483. : seed(3905348978240129619LL)
  484. {
  485. }
  486. /* Sets seed by command line. */
  487. void setSeed(int argc, char* argv[])
  488. {
  489. random_t p;
  490. seed = 3905348978240129619LL;
  491. for (int i = 1; i < argc; i++)
  492. {
  493. std::size_t le = std::strlen(argv[i]);
  494. for (std::size_t j = 0; j < le; j++)
  495. seed = seed * multiplier + (unsigned int)(argv[i][j]) + addend;
  496. seed += multiplier / addend;
  497. }
  498. seed = seed & mask;
  499. }
  500. /* Sets seed by given value. */
  501. void setSeed(long long _seed)
  502. {
  503. _seed = (_seed ^ multiplier) & mask;
  504. seed = _seed;
  505. }
  506. #ifndef __BORLANDC__
  507. /* Random string value by given pattern (see pattern documentation). */
  508. std::string next(const std::string& ptrn)
  509. {
  510. pattern p(ptrn);
  511. return p.next(*this);
  512. }
  513. #else
  514. /* Random string value by given pattern (see pattern documentation). */
  515. std::string next(std::string ptrn)
  516. {
  517. pattern p(ptrn);
  518. return p.next(*this);
  519. }
  520. #endif
  521. /* Random value in range [0, n-1]. */
  522. int next(int n)
  523. {
  524. if (n <= 0)
  525. __testlib_fail("random_t::next(int n): n must be positive");
  526. if ((n & -n) == n) // n is a power of 2
  527. return (int)((n * (long long)nextBits(31)) >> 31);
  528. const long long limit = INT_MAX / n * n;
  529. long long bits;
  530. do {
  531. bits = nextBits(31);
  532. } while (bits >= limit);
  533. return int(bits % n);
  534. }
  535. /* Random value in range [0, n-1]. */
  536. unsigned int next(unsigned int n)
  537. {
  538. if (n >= INT_MAX)
  539. __testlib_fail("random_t::next(unsigned int n): n must be less INT_MAX");
  540. return (unsigned int)next(int(n));
  541. }
  542. /* Random value in range [0, n-1]. */
  543. long long next(long long n)
  544. {
  545. if (n <= 0)
  546. __testlib_fail("random_t::next(long long n): n must be positive");
  547. const long long limit = __TESTLIB_LONGLONG_MAX / n * n;
  548. long long bits;
  549. do {
  550. bits = nextBits(63);
  551. } while (bits >= limit);
  552. return bits % n;
  553. }
  554. /* Random value in range [0, n-1]. */
  555. unsigned long long next(unsigned long long n)
  556. {
  557. if (n >= (unsigned long long)(__TESTLIB_LONGLONG_MAX))
  558. __testlib_fail("random_t::next(unsigned long long n): n must be less LONGLONG_MAX");
  559. return (unsigned long long)next((long long)(n));
  560. }
  561. /* Random value in range [0, n-1]. */
  562. long next(long n)
  563. {
  564. return (long)next((long long)(n));
  565. }
  566. /* Random value in range [0, n-1]. */
  567. unsigned long next(unsigned long n)
  568. {
  569. if (n >= (unsigned long)(LONG_MAX))
  570. __testlib_fail("random_t::next(unsigned long n): n must be less LONG_MAX");
  571. return (unsigned long)next((unsigned long long)(n));
  572. }
  573. /* Returns random value in range [from,to]. */
  574. int next(int from, int to)
  575. {
  576. return int(next((long long)to - from + 1) + from);
  577. }
  578. /* Returns random value in range [from,to]. */
  579. unsigned int next(unsigned int from, unsigned int to)
  580. {
  581. return (unsigned int)(next((long long)to - from + 1) + from);
  582. }
  583. /* Returns random value in range [from,to]. */
  584. long long next(long long from, long long to)
  585. {
  586. return next(to - from + 1) + from;
  587. }
  588. /* Returns random value in range [from,to]. */
  589. unsigned long long next(unsigned long long from, unsigned long long to)
  590. {
  591. if (from > to)
  592. __testlib_fail("random_t::next(unsigned long long from, unsigned long long to): from can't not exceed to");
  593. return next(to - from + 1) + from;
  594. }
  595. /* Returns random value in range [from,to]. */
  596. long next(long from, long to)
  597. {
  598. return next(to - from + 1) + from;
  599. }
  600. /* Returns random value in range [from,to]. */
  601. unsigned long next(unsigned long from, unsigned long to)
  602. {
  603. if (from > to)
  604. __testlib_fail("random_t::next(unsigned long from, unsigned long to): from can't not exceed to");
  605. return next(to - from + 1) + from;
  606. }
  607. /* Random double value in range [0, 1). */
  608. double next()
  609. {
  610. long long left = ((long long)(nextBits(26)) << 27);
  611. long long right = nextBits(27);
  612. return (double)(left + right) / (double)(1LL << 53);
  613. }
  614. /* Random double value in range [0, n). */
  615. double next(double n)
  616. {
  617. return n * next();
  618. }
  619. /* Random double value in range [from, to). */
  620. double next(double from, double to)
  621. {
  622. if (from > to)
  623. __testlib_fail("random_t::next(double from, double to): from can't not exceed to");
  624. return next(to - from) + from;
  625. }
  626. /* Returns random element from container. */
  627. template <typename Container>
  628. typename Container::value_type any(const Container& c)
  629. {
  630. size_t size = c.size();
  631. if (size <= 0)
  632. __testlib_fail("random_t::any(const Container& c): c.size() must be positive");
  633. return *(c.begin() + next(size));
  634. }
  635. /* Returns random element from iterator range. */
  636. template <typename Iter>
  637. typename Iter::value_type any(const Iter& begin, const Iter& end)
  638. {
  639. int size = int(end - begin);
  640. if (size <= 0)
  641. __testlib_fail("random_t::any(const Iter& begin, const Iter& end): range must have positive length");
  642. return *(begin + next(size));
  643. }
  644. /* Random string value by given pattern (see pattern documentation). */
  645. #ifdef __GNUC__
  646. __attribute__ ((format (printf, 2, 3)))
  647. #endif
  648. std::string next(const char* format, ...)
  649. {
  650. FMT_TO_RESULT(format, format, ptrn);
  651. return next(ptrn);
  652. }
  653. /*
  654. * Weighted next. If type == 0 than it is usual "next()".
  655. *
  656. * If type = 1, than it returns "max(next(), next())"
  657. * (the number of "max" functions equals to "type").
  658. *
  659. * If type < 0, than "max" function replaces with "min".
  660. */
  661. int wnext(int n, int type)
  662. {
  663. if (n <= 0)
  664. __testlib_fail("random_t::wnext(int n, int type): n must be positive");
  665. if (abs(type) < random_t::lim)
  666. {
  667. int result = next(n);
  668. for (int i = 0; i < +type; i++)
  669. result = __testlib_max(result, next(n));
  670. for (int i = 0; i < -type; i++)
  671. result = __testlib_min(result, next(n));
  672. return result;
  673. }
  674. else
  675. {
  676. double p;
  677. if (type > 0)
  678. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  679. else
  680. p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1));
  681. return int(n * p);
  682. }
  683. }
  684. /* See wnext(int, int). It uses the same algorithms. */
  685. long long wnext(long long n, int type)
  686. {
  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. {
  691. long long result = next(n);
  692. for (int i = 0; i < +type; i++)
  693. result = __testlib_max(result, next(n));
  694. for (int i = 0; i < -type; i++)
  695. result = __testlib_min(result, next(n));
  696. return result;
  697. }
  698. else
  699. {
  700. double p;
  701. if (type > 0)
  702. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  703. else
  704. p = std::pow(next() + 0.0, - type + 1);
  705. return __testlib_min(__testlib_max((long long)(double(n) * p), 0LL), n - 1LL);
  706. }
  707. }
  708. /* See wnext(int, int). It uses the same algorithms. */
  709. double wnext(int type)
  710. {
  711. if (abs(type) < random_t::lim)
  712. {
  713. double result = next();
  714. for (int i = 0; i < +type; i++)
  715. result = __testlib_max(result, next());
  716. for (int i = 0; i < -type; i++)
  717. result = __testlib_min(result, next());
  718. return result;
  719. }
  720. else
  721. {
  722. double p;
  723. if (type > 0)
  724. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  725. else
  726. p = std::pow(next() + 0.0, - type + 1);
  727. return p;
  728. }
  729. }
  730. /* See wnext(int, int). It uses the same algorithms. */
  731. double wnext(double n, int type)
  732. {
  733. if (n <= 0)
  734. __testlib_fail("random_t::wnext(double n, int type): n must be positive");
  735. if (abs(type) < random_t::lim)
  736. {
  737. double result = next();
  738. for (int i = 0; i < +type; i++)
  739. result = __testlib_max(result, next());
  740. for (int i = 0; i < -type; i++)
  741. result = __testlib_min(result, next());
  742. return n * result;
  743. }
  744. else
  745. {
  746. double p;
  747. if (type > 0)
  748. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  749. else
  750. p = std::pow(next() + 0.0, - type + 1);
  751. return n * p;
  752. }
  753. }
  754. /* See wnext(int, int). It uses the same algorithms. */
  755. unsigned int wnext(unsigned int n, int type)
  756. {
  757. if (n >= INT_MAX)
  758. __testlib_fail("random_t::wnext(unsigned int n, int type): n must be less INT_MAX");
  759. return (unsigned int)wnext(int(n), type);
  760. }
  761. /* See wnext(int, int). It uses the same algorithms. */
  762. unsigned long long wnext(unsigned long long n, int type)
  763. {
  764. if (n >= (unsigned long long)(__TESTLIB_LONGLONG_MAX))
  765. __testlib_fail("random_t::wnext(unsigned long long n, int type): n must be less LONGLONG_MAX");
  766. return (unsigned long long)wnext((long long)(n), type);
  767. }
  768. /* See wnext(int, int). It uses the same algorithms. */
  769. long wnext(long n, int type)
  770. {
  771. return (long)wnext((long long)(n), type);
  772. }
  773. /* See wnext(int, int). It uses the same algorithms. */
  774. unsigned long wnext(unsigned long n, int type)
  775. {
  776. if (n >= (unsigned long)(LONG_MAX))
  777. __testlib_fail("random_t::wnext(unsigned long n, int type): n must be less LONG_MAX");
  778. return (unsigned long)wnext((unsigned long long)(n), type);
  779. }
  780. /* Returns weighted random value in range [from, to]. */
  781. int wnext(int from, int to, int type)
  782. {
  783. if (from > to)
  784. __testlib_fail("random_t::wnext(int from, int to, int type): from can't not exceed to");
  785. return wnext(to - from + 1, type) + from;
  786. }
  787. /* Returns weighted random value in range [from, to]. */
  788. int wnext(unsigned int from, unsigned int to, int type)
  789. {
  790. if (from > to)
  791. __testlib_fail("random_t::wnext(unsigned int from, unsigned int to, int type): from can't not exceed to");
  792. return int(wnext(to - from + 1, type) + from);
  793. }
  794. /* Returns weighted random value in range [from, to]. */
  795. long long wnext(long long from, long long to, int type)
  796. {
  797. if (from > to)
  798. __testlib_fail("random_t::wnext(long long from, long long to, int type): from can't not exceed to");
  799. return wnext(to - from + 1, type) + from;
  800. }
  801. /* Returns weighted random value in range [from, to]. */
  802. unsigned long long wnext(unsigned long long from, unsigned long long to, int type)
  803. {
  804. if (from > to)
  805. __testlib_fail("random_t::wnext(unsigned long long from, unsigned long long to, int type): from can't not exceed to");
  806. return wnext(to - from + 1, type) + from;
  807. }
  808. /* Returns weighted random value in range [from, to]. */
  809. long wnext(long from, long to, int type)
  810. {
  811. if (from > to)
  812. __testlib_fail("random_t::wnext(long from, long to, int type): from can't not exceed to");
  813. return wnext(to - from + 1, type) + from;
  814. }
  815. /* Returns weighted random value in range [from, to]. */
  816. unsigned long wnext(unsigned long from, unsigned long to, int type)
  817. {
  818. if (from > to)
  819. __testlib_fail("random_t::wnext(unsigned long from, unsigned long to, int type): from can't not exceed to");
  820. return wnext(to - from + 1, type) + from;
  821. }
  822. /* Returns weighted random double value in range [from, to). */
  823. double wnext(double from, double to, int type)
  824. {
  825. if (from > to)
  826. __testlib_fail("random_t::wnext(double from, double to, int type): from can't not exceed to");
  827. return wnext(to - from, type) + from;
  828. }
  829. /* Returns weighted random element from container. */
  830. template <typename Container>
  831. typename Container::value_type wany(const Container& c, int type)
  832. {
  833. size_t size = c.size();
  834. if (size <= 0)
  835. __testlib_fail("random_t::wany(const Container& c, int type): c.size() must be positive");
  836. return *(c.begin() + wnext(size, type));
  837. }
  838. /* Returns weighted random element from iterator range. */
  839. template <typename Iter>
  840. typename Iter::value_type wany(const Iter& begin, const Iter& end, int type)
  841. {
  842. int size = int(end - begin);
  843. if (size <= 0)
  844. __testlib_fail("random_t::any(const Iter& begin, const Iter& end, int type): range must have positive length");
  845. return *(begin + wnext(size, type));
  846. }
  847. };
  848. const int random_t::lim = 25;
  849. const unsigned long long random_t::multiplier = 0x5DEECE66DLL;
  850. const unsigned long long random_t::addend = 0xBLL;
  851. const unsigned long long random_t::mask = (1LL << 48) - 1;
  852. int random_t::version = -1;
  853. /* Pattern implementation */
  854. bool pattern::matches(const std::string& s) const
  855. {
  856. return matches(s, 0);
  857. }
  858. static bool __pattern_isSlash(const std::string& s, size_t pos)
  859. {
  860. return s[pos] == '\\';
  861. }
  862. #ifdef __GNUC__
  863. __attribute__((pure))
  864. #endif
  865. static bool __pattern_isCommandChar(const std::string& s, size_t pos, char value)
  866. {
  867. if (pos >= s.length())
  868. return false;
  869. int slashes = 0;
  870. int before = int(pos) - 1;
  871. while (before >= 0 && s[before] == '\\')
  872. before--, slashes++;
  873. return slashes % 2 == 0 && s[pos] == value;
  874. }
  875. static char __pattern_getChar(const std::string& s, size_t& pos)
  876. {
  877. if (__pattern_isSlash(s, pos))
  878. pos += 2;
  879. else
  880. pos++;
  881. return s[pos - 1];
  882. }
  883. #ifdef __GNUC__
  884. __attribute__((pure))
  885. #endif
  886. static int __pattern_greedyMatch(const std::string& s, size_t pos, const std::vector<char> chars)
  887. {
  888. int result = 0;
  889. while (pos < s.length())
  890. {
  891. char c = s[pos++];
  892. if (!std::binary_search(chars.begin(), chars.end(), c))
  893. break;
  894. else
  895. result++;
  896. }
  897. return result;
  898. }
  899. std::string pattern::src() const
  900. {
  901. return s;
  902. }
  903. bool pattern::matches(const std::string& s, size_t pos) const
  904. {
  905. std::string result;
  906. if (to > 0)
  907. {
  908. int size = __pattern_greedyMatch(s, pos, chars);
  909. if (size < from)
  910. return false;
  911. if (size > to)
  912. size = to;
  913. pos += size;
  914. }
  915. if (children.size() > 0)
  916. {
  917. for (size_t child = 0; child < children.size(); child++)
  918. if (children[child].matches(s, pos))
  919. return true;
  920. return false;
  921. }
  922. else
  923. return pos == s.length();
  924. }
  925. std::string pattern::next(random_t& rnd) const
  926. {
  927. std::string result;
  928. result.reserve(20);
  929. if (to == INT_MAX)
  930. __testlib_fail("pattern::next(random_t& rnd): can't process character '*' for generation");
  931. if (to > 0)
  932. {
  933. int count = rnd.next(to - from + 1) + from;
  934. for (int i = 0; i < count; i++)
  935. result += chars[rnd.next(int(chars.size()))];
  936. }
  937. if (children.size() > 0)
  938. {
  939. int child = rnd.next(int(children.size()));
  940. result += children[child].next(rnd);
  941. }
  942. return result;
  943. }
  944. static void __pattern_scanCounts(const std::string& s, size_t& pos, int& from, int& to)
  945. {
  946. if (pos >= s.length())
  947. {
  948. from = to = 1;
  949. return;
  950. }
  951. if (__pattern_isCommandChar(s, pos, '{'))
  952. {
  953. std::vector<std::string> parts;
  954. std::string part;
  955. pos++;
  956. while (pos < s.length() && !__pattern_isCommandChar(s, pos, '}'))
  957. {
  958. if (__pattern_isCommandChar(s, pos, ','))
  959. parts.push_back(part), part = "", pos++;
  960. else
  961. part += __pattern_getChar(s, pos);
  962. }
  963. if (part != "")
  964. parts.push_back(part);
  965. if (!__pattern_isCommandChar(s, pos, '}'))
  966. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  967. pos++;
  968. if (parts.size() < 1 || parts.size() > 2)
  969. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  970. std::vector<int> numbers;
  971. for (size_t i = 0; i < parts.size(); i++)
  972. {
  973. if (parts[i].length() == 0)
  974. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  975. int number;
  976. if (std::sscanf(parts[i].c_str(), "%d", &number) != 1)
  977. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  978. numbers.push_back(number);
  979. }
  980. if (numbers.size() == 1)
  981. from = to = numbers[0];
  982. else
  983. from = numbers[0], to = numbers[1];
  984. if (from > to)
  985. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  986. }
  987. else
  988. {
  989. if (__pattern_isCommandChar(s, pos, '?'))
  990. {
  991. from = 0, to = 1, pos++;
  992. return;
  993. }
  994. if (__pattern_isCommandChar(s, pos, '*'))
  995. {
  996. from = 0, to = INT_MAX, pos++;
  997. return;
  998. }
  999. if (__pattern_isCommandChar(s, pos, '+'))
  1000. {
  1001. from = 1, to = INT_MAX, pos++;
  1002. return;
  1003. }
  1004. from = to = 1;
  1005. }
  1006. }
  1007. static std::vector<char> __pattern_scanCharSet(const std::string& s, size_t& pos)
  1008. {
  1009. if (pos >= s.length())
  1010. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  1011. std::vector<char> result;
  1012. if (__pattern_isCommandChar(s, pos, '['))
  1013. {
  1014. pos++;
  1015. bool negative = __pattern_isCommandChar(s, pos, '^');
  1016. char prev = 0;
  1017. while (pos < s.length() && !__pattern_isCommandChar(s, pos, ']'))
  1018. {
  1019. if (__pattern_isCommandChar(s, pos, '-') && prev != 0)
  1020. {
  1021. pos++;
  1022. if (pos + 1 == s.length() || __pattern_isCommandChar(s, pos, ']'))
  1023. {
  1024. result.push_back(prev);
  1025. prev = '-';
  1026. continue;
  1027. }
  1028. char next = __pattern_getChar(s, pos);
  1029. if (prev > next)
  1030. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  1031. for (char c = prev; c != next; c++)
  1032. result.push_back(c);
  1033. result.push_back(next);
  1034. prev = 0;
  1035. }
  1036. else
  1037. {
  1038. if (prev != 0)
  1039. result.push_back(prev);
  1040. prev = __pattern_getChar(s, pos);
  1041. }
  1042. }
  1043. if (prev != 0)
  1044. result.push_back(prev);
  1045. if (!__pattern_isCommandChar(s, pos, ']'))
  1046. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  1047. pos++;
  1048. if (negative)
  1049. {
  1050. std::sort(result.begin(), result.end());
  1051. std::vector<char> actuals;
  1052. for (int code = 0; code < 255; code++)
  1053. {
  1054. char c = char(code);
  1055. if (!std::binary_search(result.begin(), result.end(), c))
  1056. actuals.push_back(c);
  1057. }
  1058. result = actuals;
  1059. }
  1060. std::sort(result.begin(), result.end());
  1061. }
  1062. else
  1063. result.push_back(__pattern_getChar(s, pos));
  1064. return result;
  1065. }
  1066. pattern::pattern(std::string s): s(s), from(0), to(0)
  1067. {
  1068. std::string t;
  1069. for (size_t i = 0; i < s.length(); i++)
  1070. if (!__pattern_isCommandChar(s, i, ' '))
  1071. t += s[i];
  1072. s = t;
  1073. int opened = 0;
  1074. int firstClose = -1;
  1075. std::vector<int> seps;
  1076. for (size_t i = 0; i < s.length(); i++)
  1077. {
  1078. if (__pattern_isCommandChar(s, i, '('))
  1079. {
  1080. opened++;
  1081. continue;
  1082. }
  1083. if (__pattern_isCommandChar(s, i, ')'))
  1084. {
  1085. opened--;
  1086. if (opened == 0 && firstClose == -1)
  1087. firstClose = int(i);
  1088. continue;
  1089. }
  1090. if (opened < 0)
  1091. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  1092. if (__pattern_isCommandChar(s, i, '|') && opened == 0)
  1093. seps.push_back(int(i));
  1094. }
  1095. if (opened != 0)
  1096. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  1097. if (seps.size() == 0 && firstClose + 1 == (int)s.length()
  1098. && __pattern_isCommandChar(s, 0, '(') && __pattern_isCommandChar(s, s.length() - 1, ')'))
  1099. {
  1100. children.push_back(pattern(s.substr(1, s.length() - 2)));
  1101. }
  1102. else
  1103. {
  1104. if (seps.size() > 0)
  1105. {
  1106. seps.push_back(int(s.length()));
  1107. int last = 0;
  1108. for (size_t i = 0; i < seps.size(); i++)
  1109. {
  1110. children.push_back(pattern(s.substr(last, seps[i] - last)));
  1111. last = seps[i] + 1;
  1112. }
  1113. }
  1114. else
  1115. {
  1116. size_t pos = 0;
  1117. chars = __pattern_scanCharSet(s, pos);
  1118. __pattern_scanCounts(s, pos, from, to);
  1119. if (pos < s.length())
  1120. children.push_back(pattern(s.substr(pos)));
  1121. }
  1122. }
  1123. }
  1124. /* End of pattern implementation */
  1125. template <typename C>
  1126. inline bool isEof(C c)
  1127. {
  1128. return c == EOFC;
  1129. }
  1130. template <typename C>
  1131. inline bool isEoln(C c)
  1132. {
  1133. return (c == LF || c == CR);
  1134. }
  1135. template<typename C>
  1136. inline bool isBlanks(C c)
  1137. {
  1138. return (c == LF || c == CR || c == SPACE || c == TAB);
  1139. }
  1140. enum TMode
  1141. {
  1142. _input, _output, _answer
  1143. };
  1144. /* Outcomes 6-15 are reserved for future use. */
  1145. enum TResult
  1146. {
  1147. _ok = 0,
  1148. _wa = 1,
  1149. _pe = 2,
  1150. _fail = 3,
  1151. _dirt = 4,
  1152. _points = 5,
  1153. _unexpected_eof = 8,
  1154. _partially = 16
  1155. };
  1156. enum TTestlibMode
  1157. {
  1158. _unknown, _checker, _validator, _generator, _interactor
  1159. };
  1160. #define _pc(exitCode) (TResult(_partially + (exitCode)))
  1161. /* Outcomes 6-15 are reserved for future use. */
  1162. const std::string outcomes[] = {
  1163. "accepted",
  1164. "wrong-answer",
  1165. "presentation-error",
  1166. "fail",
  1167. "fail",
  1168. #ifndef PCMS2
  1169. "points",
  1170. #else
  1171. "relative-scoring",
  1172. #endif
  1173. "reserved",
  1174. "reserved",
  1175. "unexpected-eof",
  1176. "reserved",
  1177. "reserved",
  1178. "reserved",
  1179. "reserved",
  1180. "reserved",
  1181. "reserved",
  1182. "reserved",
  1183. "partially-correct"
  1184. };
  1185. class InputStreamReader
  1186. {
  1187. public:
  1188. virtual int curChar() = 0;
  1189. virtual int nextChar() = 0;
  1190. virtual void skipChar() = 0;
  1191. virtual void unreadChar(int c) = 0;
  1192. virtual std::string getName() = 0;
  1193. virtual bool eof() = 0;
  1194. virtual void close() = 0;
  1195. virtual ~InputStreamReader() = 0;
  1196. };
  1197. InputStreamReader::~InputStreamReader()
  1198. {
  1199. // No operations.
  1200. }
  1201. class StringInputStreamReader: public InputStreamReader
  1202. {
  1203. private:
  1204. std::string s;
  1205. size_t pos;
  1206. public:
  1207. StringInputStreamReader(const std::string& content): s(content), pos(0)
  1208. {
  1209. // No operations.
  1210. }
  1211. int curChar()
  1212. {
  1213. if (pos >= s.length())
  1214. return EOFC;
  1215. else
  1216. return s[pos];
  1217. }
  1218. int nextChar()
  1219. {
  1220. if (pos >= s.length())
  1221. {
  1222. pos++;
  1223. return EOFC;
  1224. }
  1225. else
  1226. return s[pos++];
  1227. }
  1228. void skipChar()
  1229. {
  1230. pos++;
  1231. }
  1232. void unreadChar(int c)
  1233. {
  1234. if (pos == 0)
  1235. __testlib_fail("FileFileInputStreamReader::unreadChar(int): pos == 0.");
  1236. pos--;
  1237. if (pos < s.length())
  1238. s[pos] = char(c);
  1239. }
  1240. std::string getName()
  1241. {
  1242. return __testlib_part(s);
  1243. }
  1244. bool eof()
  1245. {
  1246. return pos >= s.length();
  1247. }
  1248. void close()
  1249. {
  1250. // No operations.
  1251. }
  1252. };
  1253. class FileInputStreamReader: public InputStreamReader
  1254. {
  1255. private:
  1256. std::FILE* file;
  1257. std::string name;
  1258. inline int postprocessGetc(int getcResult)
  1259. {
  1260. if (getcResult != EOF)
  1261. return getcResult;
  1262. else
  1263. return EOFC;
  1264. }
  1265. public:
  1266. FileInputStreamReader(std::FILE* file, const std::string& name): file(file), name(name)
  1267. {
  1268. // No operations.
  1269. }
  1270. int curChar()
  1271. {
  1272. if (feof(file))
  1273. return EOFC;
  1274. else
  1275. {
  1276. int c = getc(file);
  1277. ungetc(c, file);
  1278. return postprocessGetc(c);
  1279. }
  1280. }
  1281. int nextChar()
  1282. {
  1283. if (feof(file))
  1284. return EOFC;
  1285. else
  1286. return postprocessGetc(getc(file));
  1287. }
  1288. void skipChar()
  1289. {
  1290. getc(file);
  1291. }
  1292. void unreadChar(int c)
  1293. {
  1294. ungetc(c, file);
  1295. }
  1296. std::string getName()
  1297. {
  1298. return name;
  1299. }
  1300. bool eof()
  1301. {
  1302. if (NULL == file || feof(file))
  1303. return true;
  1304. else
  1305. {
  1306. int c = nextChar();
  1307. if (c == EOFC || (c == EOF && feof(file)))
  1308. return true;
  1309. unreadChar(c);
  1310. return false;
  1311. }
  1312. }
  1313. void close()
  1314. {
  1315. if (NULL != file)
  1316. {
  1317. fclose(file);
  1318. file = NULL;
  1319. }
  1320. }
  1321. };
  1322. class BufferedFileInputStreamReader: public InputStreamReader
  1323. {
  1324. private:
  1325. static const size_t BUFFER_SIZE;
  1326. static const size_t MAX_UNREAD_COUNT;
  1327. std::FILE* file;
  1328. char* buffer;
  1329. bool* isEof;
  1330. int bufferPos;
  1331. size_t bufferSize;
  1332. std::string name;
  1333. bool refill()
  1334. {
  1335. if (NULL == file)
  1336. __testlib_fail("BufferedFileInputStreamReader: file == NULL (" + getName() + ")");
  1337. if (bufferPos >= int(bufferSize))
  1338. {
  1339. size_t readSize = fread(
  1340. buffer + MAX_UNREAD_COUNT,
  1341. 1,
  1342. BUFFER_SIZE - MAX_UNREAD_COUNT,
  1343. file
  1344. );
  1345. if (readSize < BUFFER_SIZE - MAX_UNREAD_COUNT
  1346. && ferror(file))
  1347. __testlib_fail("BufferedFileInputStreamReader: unable to read (" + getName() + ")");
  1348. bufferSize = MAX_UNREAD_COUNT + readSize;
  1349. bufferPos = int(MAX_UNREAD_COUNT);
  1350. std::memset(isEof + MAX_UNREAD_COUNT, 0, sizeof(isEof[0]) * readSize);
  1351. return readSize > 0;
  1352. }
  1353. else
  1354. return true;
  1355. }
  1356. public:
  1357. BufferedFileInputStreamReader(std::FILE* file, const std::string& name): file(file), name(name)
  1358. {
  1359. buffer = new char[BUFFER_SIZE];
  1360. isEof = new bool[BUFFER_SIZE];
  1361. bufferSize = MAX_UNREAD_COUNT;
  1362. bufferPos = int(MAX_UNREAD_COUNT);
  1363. }
  1364. ~BufferedFileInputStreamReader()
  1365. {
  1366. if (NULL != buffer)
  1367. {
  1368. delete[] buffer;
  1369. buffer = NULL;
  1370. }
  1371. if (NULL != isEof)
  1372. {
  1373. delete[] isEof;
  1374. isEof = NULL;
  1375. }
  1376. }
  1377. int curChar()
  1378. {
  1379. if (!refill())
  1380. return EOFC;
  1381. return isEof[bufferPos] ? EOFC : buffer[bufferPos];
  1382. }
  1383. int nextChar()
  1384. {
  1385. if (!refill())
  1386. return EOFC;
  1387. return isEof[bufferPos] ? EOFC : buffer[bufferPos++];
  1388. }
  1389. void skipChar()
  1390. {
  1391. bufferPos++;
  1392. }
  1393. void unreadChar(int c)
  1394. {
  1395. bufferPos--;
  1396. if (bufferPos < 0)
  1397. __testlib_fail("BufferedFileInputStreamReader::unreadChar(int): bufferPos < 0");
  1398. isEof[bufferPos] = (c == EOFC);
  1399. buffer[bufferPos] = char(c);
  1400. }
  1401. std::string getName()
  1402. {
  1403. return name;
  1404. }
  1405. bool eof()
  1406. {
  1407. return !refill() || EOFC == curChar();
  1408. }
  1409. void close()
  1410. {
  1411. if (NULL != file)
  1412. {
  1413. fclose(file);
  1414. file = NULL;
  1415. }
  1416. }
  1417. };
  1418. const size_t BufferedFileInputStreamReader::BUFFER_SIZE = 2000000;
  1419. const size_t BufferedFileInputStreamReader::MAX_UNREAD_COUNT = BufferedFileInputStreamReader::BUFFER_SIZE / 2;
  1420. /*
  1421. * Streams to be used for reading data in checkers or validators.
  1422. * Each read*() method moves pointer to the next character after the
  1423. * read value.
  1424. */
  1425. struct InStream
  1426. {
  1427. /* Do not use them. */
  1428. InStream();
  1429. ~InStream();
  1430. /* Wrap std::string with InStream. */
  1431. InStream(const InStream& baseStream, std::string content);
  1432. InputStreamReader* reader;
  1433. std::string name;
  1434. TMode mode;
  1435. bool opened;
  1436. bool stdfile;
  1437. bool strict;
  1438. int wordReserveSize;
  1439. std::string _tmpReadToken;
  1440. void init(std::string fileName, TMode mode);
  1441. void init(std::FILE* f, TMode mode);
  1442. /* Moves stream pointer to the first non-white-space character or EOF. */
  1443. void skipBlanks();
  1444. /* Returns current character in the stream. Doesn't remove it from stream. */
  1445. char curChar();
  1446. /* Moves stream pointer one character forward. */
  1447. void skipChar();
  1448. /* Returns current character and moves pointer one character forward. */
  1449. char nextChar();
  1450. /* Returns current character and moves pointer one character forward. */
  1451. char readChar();
  1452. /* As "readChar()" but ensures that the result is equal to given parameter. */
  1453. char readChar(char c);
  1454. /* As "readChar()" but ensures that the result is equal to the space (code=32). */
  1455. char readSpace();
  1456. /* Puts back the character into the stream. */
  1457. void unreadChar(char c);
  1458. /* Reopens stream, you should not use it. */
  1459. void reset(std::FILE* file = NULL);
  1460. /* Checks that current position is EOF. If not it doesn't move stream pointer. */
  1461. bool eof();
  1462. /* Moves pointer to the first non-white-space character and calls "eof()". */
  1463. bool seekEof();
  1464. /*
  1465. * Checks that current position contains EOLN.
  1466. * If not it doesn't move stream pointer.
  1467. * In strict mode expects "#13#10" for windows or "#10" for other platforms.
  1468. */
  1469. bool eoln();
  1470. /* Moves pointer to the first non-space and non-tab character and calls "eoln()". */
  1471. bool seekEoln();
  1472. /* Moves stream pointer to the first character of the next line (if exists). */
  1473. void nextLine();
  1474. /*
  1475. * Reads new token. Ignores white-spaces into the non-strict mode
  1476. * (strict mode is used in validators usually).
  1477. */
  1478. std::string readWord();
  1479. /* The same as "readWord()", it is preffered to use "readToken()". */
  1480. std::string readToken();
  1481. /* The same as "readWord()", but ensures that token matches to given pattern. */
  1482. std::string readWord(const std::string& ptrn, const std::string& variableName = "");
  1483. std::string readWord(const pattern& p, const std::string& variableName = "");
  1484. /* The same as "readToken()", but ensures that token matches to given pattern. */
  1485. std::string readToken(const std::string& ptrn, const std::string& variableName = "");
  1486. std::string readToken(const pattern& p, const std::string& variableName = "");
  1487. void readWordTo(std::string& result);
  1488. void readWordTo(std::string& result, const pattern& p, const std::string& variableName = "");
  1489. void readWordTo(std::string& result, const std::string& ptrn, const std::string& variableName = "");
  1490. void readTokenTo(std::string& result);
  1491. void readTokenTo(std::string& result, const pattern& p, const std::string& variableName = "");
  1492. void readTokenTo(std::string& result, const std::string& ptrn, const std::string& variableName = "");
  1493. /*
  1494. * Reads new long long value. Ignores white-spaces into the non-strict mode
  1495. * (strict mode is used in validators usually).
  1496. */
  1497. long long readLong();
  1498. unsigned long long readUnsignedLong();
  1499. /*
  1500. * Reads new int. Ignores white-spaces into the non-strict mode
  1501. * (strict mode is used in validators usually).
  1502. */
  1503. int readInteger();
  1504. /*
  1505. * Reads new int. Ignores white-spaces into the non-strict mode
  1506. * (strict mode is used in validators usually).
  1507. */
  1508. int readInt();
  1509. /* As "readLong()" but ensures that value in the range [minv,maxv]. */
  1510. long long readLong(long long minv, long long maxv, const std::string& variableName = "");
  1511. unsigned long long readUnsignedLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName = "");
  1512. unsigned long long readLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName = "");
  1513. /* As "readInteger()" but ensures that value in the range [minv,maxv]. */
  1514. int readInteger(int minv, int maxv, const std::string& variableName = "");
  1515. /* As "readInt()" but ensures that value in the range [minv,maxv]. */
  1516. int readInt(int minv, int maxv, const std::string& variableName = "");
  1517. /*
  1518. * Reads new double. Ignores white-spaces into the non-strict mode
  1519. * (strict mode is used in validators usually).
  1520. */
  1521. double readReal();
  1522. /*
  1523. * Reads new double. Ignores white-spaces into the non-strict mode
  1524. * (strict mode is used in validators usually).
  1525. */
  1526. double readDouble();
  1527. /* As "readReal()" but ensures that value in the range [minv,maxv]. */
  1528. double readReal(double minv, double maxv, const std::string& variableName = "");
  1529. /* As "readDouble()" but ensures that value in the range [minv,maxv]. */
  1530. double readDouble(double minv, double maxv, const std::string& variableName = "");
  1531. /*
  1532. * As "readReal()" but ensures that value in the range [minv,maxv] and
  1533. * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]
  1534. * and number is in the form "[-]digit(s)[.digit(s)]".
  1535. */
  1536. double readStrictReal(double minv, double maxv,
  1537. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  1538. const std::string& variableName = "");
  1539. /*
  1540. * As "readDouble()" but ensures that value in the range [minv,maxv] and
  1541. * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]
  1542. * and number is in the form "[-]digit(s)[.digit(s)]".
  1543. */
  1544. double readStrictDouble(double minv, double maxv,
  1545. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  1546. const std::string& variableName = "");
  1547. /* As readLine(). */
  1548. std::string readString();
  1549. /* See readLine(). */
  1550. void readStringTo(std::string& result);
  1551. /* The same as "readLine()/readString()", but ensures that line matches to the given pattern. */
  1552. std::string readString(const pattern& p, const std::string& variableName = "");
  1553. /* The same as "readLine()/readString()", but ensures that line matches to the given pattern. */
  1554. std::string readString(const std::string& ptrn, const std::string& variableName = "");
  1555. /* The same as "readLine()/readString()", but ensures that line matches to the given pattern. */
  1556. void readStringTo(std::string& result, const pattern& p, const std::string& variableName = "");
  1557. /* The same as "readLine()/readString()", but ensures that line matches to the given pattern. */
  1558. void readStringTo(std::string& result, const std::string& ptrn, const std::string& variableName = "");
  1559. /*
  1560. * Reads line from the current position to EOLN or EOF. Moves stream pointer to
  1561. * the first character of the new line (if possible).
  1562. */
  1563. std::string readLine();
  1564. /* See readLine(). */
  1565. void readLineTo(std::string& result);
  1566. /* The same as "readLine()", but ensures that line matches to the given pattern. */
  1567. std::string readLine(const pattern& p, const std::string& variableName = "");
  1568. /* The same as "readLine()", but ensures that line matches to the given pattern. */
  1569. std::string readLine(const std::string& ptrn, const std::string& variableName = "");
  1570. /* The same as "readLine()", but ensures that line matches to the given pattern. */
  1571. void readLineTo(std::string& result, const pattern& p, const std::string& variableName = "");
  1572. /* The same as "readLine()", but ensures that line matches to the given pattern. */
  1573. void readLineTo(std::string& result, const std::string& ptrn, const std::string& variableName = "");
  1574. /* Reads EOLN or fails. Use it in validators. Calls "eoln()" method internally. */
  1575. void readEoln();
  1576. /* Reads EOF or fails. Use it in validators. Calls "eof()" method internally. */
  1577. void readEof();
  1578. /*
  1579. * Quit-functions aborts program with <result> and <message>:
  1580. * input/answer streams replace any result to FAIL.
  1581. */
  1582. NORETURN void quit(TResult result, const char* msg);
  1583. /*
  1584. * Quit-functions aborts program with <result> and <message>:
  1585. * input/answer streams replace any result to FAIL.
  1586. */
  1587. NORETURN void quitf(TResult result, const char* msg, ...);
  1588. /*
  1589. * Quit-functions aborts program with <result> and <message>:
  1590. * input/answer streams replace any result to FAIL.
  1591. */
  1592. NORETURN void quits(TResult result, std::string msg);
  1593. void close();
  1594. const static WORD LightGray = 0x07;
  1595. const static WORD LightRed = 0x0c;
  1596. const static WORD LightCyan = 0x0b;
  1597. const static WORD LightGreen = 0x0a;
  1598. const static WORD LightYellow = 0x0e;
  1599. static void textColor(WORD color);
  1600. static void quitscr(WORD color, const char* msg);
  1601. static void quitscrS(WORD color, std::string msg);
  1602. void xmlSafeWrite(std::FILE * file, const char* msg);
  1603. private:
  1604. InStream(const InStream&);
  1605. InStream& operator =(const InStream&);
  1606. };
  1607. InStream inf;
  1608. InStream ouf;
  1609. InStream ans;
  1610. bool appesMode;
  1611. std::string resultName;
  1612. std::string checkerName = "untitled checker";
  1613. random_t rnd;
  1614. TTestlibMode testlibMode = _unknown;
  1615. double __testlib_points = std::numeric_limits<float>::infinity();
  1616. struct ValidatorBoundsHit
  1617. {
  1618. static const double EPS;
  1619. bool minHit;
  1620. bool maxHit;
  1621. ValidatorBoundsHit(bool minHit = false, bool maxHit = false): minHit(minHit), maxHit(maxHit)
  1622. {
  1623. };
  1624. ValidatorBoundsHit merge(const ValidatorBoundsHit& validatorBoundsHit)
  1625. {
  1626. return ValidatorBoundsHit(
  1627. __testlib_max(minHit, validatorBoundsHit.minHit),
  1628. __testlib_max(maxHit, validatorBoundsHit.maxHit)
  1629. );
  1630. }
  1631. };
  1632. const double ValidatorBoundsHit::EPS = 1E-12;
  1633. class Validator
  1634. {
  1635. private:
  1636. std::string _testset;
  1637. std::string _group;
  1638. std::string _testOverviewLogFileName;
  1639. std::map<std::string, ValidatorBoundsHit> _boundsHitByVariableName;
  1640. std::set<std::string> _features;
  1641. std::set<std::string> _hitFeatures;
  1642. bool isVariableNameBoundsAnalyzable(const std::string& variableName)
  1643. {
  1644. for (size_t i = 0; i < variableName.length(); i++)
  1645. if ((variableName[i] >= '0' && variableName[i] <= '9') || variableName[i] < ' ')
  1646. return false;
  1647. return true;
  1648. }
  1649. bool isFeatureNameAnalyzable(const std::string& featureName)
  1650. {
  1651. for (size_t i = 0; i < featureName.length(); i++)
  1652. if (featureName[i] < ' ')
  1653. return false;
  1654. return true;
  1655. }
  1656. public:
  1657. Validator(): _testset("tests"), _group()
  1658. {
  1659. }
  1660. std::string testset() const
  1661. {
  1662. return _testset;
  1663. }
  1664. std::string group() const
  1665. {
  1666. return _group;
  1667. }
  1668. std::string testOverviewLogFileName() const
  1669. {
  1670. return _testOverviewLogFileName;
  1671. }
  1672. void setTestset(const char* const testset)
  1673. {
  1674. _testset = testset;
  1675. }
  1676. void setGroup(const char* const group)
  1677. {
  1678. _group = group;
  1679. }
  1680. void setTestOverviewLogFileName(const char* const testOverviewLogFileName)
  1681. {
  1682. _testOverviewLogFileName = testOverviewLogFileName;
  1683. }
  1684. void addBoundsHit(const std::string& variableName, ValidatorBoundsHit boundsHit)
  1685. {
  1686. if (isVariableNameBoundsAnalyzable(variableName))
  1687. {
  1688. _boundsHitByVariableName[variableName]
  1689. = boundsHit.merge(_boundsHitByVariableName[variableName]);
  1690. }
  1691. }
  1692. std::string getBoundsHitLog()
  1693. {
  1694. std::string result;
  1695. for (std::map<std::string, ValidatorBoundsHit>::iterator i = _boundsHitByVariableName.begin();
  1696. i != _boundsHitByVariableName.end();
  1697. i++)
  1698. {
  1699. result += "\"" + i->first + "\":";
  1700. if (i->second.minHit)
  1701. result += " min-value-hit";
  1702. if (i->second.maxHit)
  1703. result += " max-value-hit";
  1704. result += "\n";
  1705. }
  1706. return result;
  1707. }
  1708. std::string getFeaturesLog()
  1709. {
  1710. std::string result;
  1711. for (std::set<std::string>::iterator i = _features.begin();
  1712. i != _features.end();
  1713. i++)
  1714. {
  1715. result += "feature \"" + *i + "\":";
  1716. if (_hitFeatures.count(*i))
  1717. result += " hit";
  1718. result += "\n";
  1719. }
  1720. return result;
  1721. }
  1722. void writeTestOverviewLog()
  1723. {
  1724. if (!_testOverviewLogFileName.empty())
  1725. {
  1726. std::string fileName(_testOverviewLogFileName);
  1727. _testOverviewLogFileName = "";
  1728. FILE* testOverviewLogFile = fopen(fileName.c_str(), "w");
  1729. if (NULL == testOverviewLogFile)
  1730. __testlib_fail("Validator::writeTestOverviewLog: can't test overview log to (" + fileName + ")");
  1731. fprintf(testOverviewLogFile, "%s%s", getBoundsHitLog().c_str(), getFeaturesLog().c_str());
  1732. if (fclose(testOverviewLogFile))
  1733. __testlib_fail("Validator::writeTestOverviewLog: can't close test overview log file (" + fileName + ")");
  1734. }
  1735. }
  1736. void addFeature(const std::string& feature)
  1737. {
  1738. if (_features.count(feature))
  1739. __testlib_fail("Feature " + feature + " registered twice.");
  1740. if (!isFeatureNameAnalyzable(feature))
  1741. __testlib_fail("Feature name '" + feature + "' contains restricted characters.");
  1742. _features.insert(feature);
  1743. }
  1744. void feature(const std::string& feature)
  1745. {
  1746. if (!isFeatureNameAnalyzable(feature))
  1747. __testlib_fail("Feature name '" + feature + "' contains restricted characters.");
  1748. if (!_features.count(feature))
  1749. __testlib_fail("Feature " + feature + " didn't registered via addFeature(feature).");
  1750. _hitFeatures.insert(feature);
  1751. }
  1752. } validator;
  1753. struct TestlibFinalizeGuard
  1754. {
  1755. static bool alive;
  1756. int quitCount, readEofCount;
  1757. TestlibFinalizeGuard() : quitCount(0), readEofCount(0)
  1758. {
  1759. // No operations.
  1760. }
  1761. ~TestlibFinalizeGuard()
  1762. {
  1763. bool _alive = alive;
  1764. alive = false;
  1765. if (_alive)
  1766. {
  1767. if (testlibMode == _checker && quitCount == 0)
  1768. __testlib_fail("Checker must end with quit or quitf call.");
  1769. if (testlibMode == _validator && readEofCount == 0 && quitCount == 0)
  1770. __testlib_fail("Validator must end with readEof call.");
  1771. }
  1772. validator.writeTestOverviewLog();
  1773. }
  1774. };
  1775. bool TestlibFinalizeGuard::alive = true;
  1776. TestlibFinalizeGuard testlibFinalizeGuard;
  1777. /*
  1778. * Call it to disable checks on finalization.
  1779. */
  1780. void disableFinalizeGuard()
  1781. {
  1782. TestlibFinalizeGuard::alive = false;
  1783. }
  1784. /* Interactor streams.
  1785. */
  1786. std::fstream tout;
  1787. /* implementation
  1788. */
  1789. template <typename T>
  1790. static std::string vtos(const T& t)
  1791. {
  1792. std::string s;
  1793. std::stringstream ss;
  1794. ss << t;
  1795. ss >> s;
  1796. return s;
  1797. }
  1798. template <typename T>
  1799. static std::string toString(const T& t)
  1800. {
  1801. return vtos(t);
  1802. }
  1803. InStream::InStream()
  1804. {
  1805. reader = NULL;
  1806. name = "";
  1807. mode = _input;
  1808. strict = false;
  1809. stdfile = false;
  1810. wordReserveSize = 4;
  1811. }
  1812. InStream::InStream(const InStream& baseStream, std::string content)
  1813. {
  1814. reader = new StringInputStreamReader(content);
  1815. opened = true;
  1816. strict = baseStream.strict;
  1817. mode = baseStream.mode;
  1818. name = "based on " + baseStream.name;
  1819. }
  1820. InStream::~InStream()
  1821. {
  1822. if (NULL != reader)
  1823. {
  1824. reader->close();
  1825. delete reader;
  1826. reader = NULL;
  1827. }
  1828. }
  1829. #ifdef __GNUC__
  1830. __attribute__((const))
  1831. #endif
  1832. int resultExitCode(TResult r)
  1833. {
  1834. if (r == _ok)
  1835. return OK_EXIT_CODE;
  1836. if (r == _wa)
  1837. return WA_EXIT_CODE;
  1838. if (r == _pe)
  1839. return PE_EXIT_CODE;
  1840. if (r == _fail)
  1841. return FAIL_EXIT_CODE;
  1842. if (r == _dirt)
  1843. return DIRT_EXIT_CODE;
  1844. if (r == _points)
  1845. return POINTS_EXIT_CODE;
  1846. if (r == _unexpected_eof)
  1847. #ifdef ENABLE_UNEXPECTED_EOF
  1848. return UNEXPECTED_EOF_EXIT_CODE;
  1849. #else
  1850. return PE_EXIT_CODE;
  1851. #endif
  1852. if (r >= _partially)
  1853. return PC_BASE_EXIT_CODE + (r - _partially);
  1854. return FAIL_EXIT_CODE;
  1855. }
  1856. void InStream::textColor(
  1857. #if !(defined(ON_WINDOWS) && (!defined(_MSC_VER) || _MSC_VER>1400)) && defined(__GNUC__)
  1858. __attribute__((unused))
  1859. #endif
  1860. WORD color
  1861. )
  1862. {
  1863. #if defined(ON_WINDOWS) && (!defined(_MSC_VER) || _MSC_VER>1400)
  1864. HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
  1865. SetConsoleTextAttribute(handle, color);
  1866. #endif
  1867. #if !defined(ON_WINDOWS) && defined(__CNUC__)
  1868. if (isatty(2))
  1869. {
  1870. switch (color)
  1871. {
  1872. case LightRed:
  1873. fprintf(stderr, "\033[1;31m");
  1874. break;
  1875. case LightCyan:
  1876. fprintf(stderr, "\033[1;36m");
  1877. break;
  1878. case LightGreen:
  1879. fprintf(stderr, "\033[1;32m");
  1880. break;
  1881. case LightYellow:
  1882. fprintf(stderr, "\033[1;33m");
  1883. break;
  1884. case LightGray:
  1885. default:
  1886. fprintf(stderr, "\033[0m");
  1887. }
  1888. }
  1889. #endif
  1890. }
  1891. NORETURN void halt(int exitCode)
  1892. {
  1893. #ifdef FOOTER
  1894. InStream::textColor(InStream::LightGray);
  1895. std::fprintf(stderr, "Checker: \"%s\"\n", checkerName.c_str());
  1896. std::fprintf(stderr, "Exit code: %d\n", exitCode);
  1897. InStream::textColor(InStream::LightGray);
  1898. #endif
  1899. std::exit(exitCode);
  1900. }
  1901. static bool __testlib_shouldCheckDirt(TResult result)
  1902. {
  1903. return result == _ok || result == _points || result >= _partially;
  1904. }
  1905. NORETURN void InStream::quit(TResult result, const char* msg)
  1906. {
  1907. if (TestlibFinalizeGuard::alive)
  1908. testlibFinalizeGuard.quitCount++;
  1909. #ifndef ENABLE_UNEXPECTED_EOF
  1910. if (result == _unexpected_eof)
  1911. result = _pe;
  1912. #endif
  1913. if (mode != _output && result != _fail)
  1914. quits(_fail, std::string(msg) + " (" + name + ")");
  1915. std::FILE * resultFile;
  1916. std::string errorName;
  1917. if (__testlib_shouldCheckDirt(result))
  1918. {
  1919. if (testlibMode != _interactor && !ouf.seekEof())
  1920. quit(_dirt, "Extra information in the output file");
  1921. }
  1922. int pctype = result - _partially;
  1923. bool isPartial = false;
  1924. switch (result)
  1925. {
  1926. case _ok:
  1927. errorName = "ok ";
  1928. quitscrS(LightGreen, errorName);
  1929. break;
  1930. case _wa:
  1931. errorName = "wrong answer ";
  1932. quitscrS(LightRed, errorName);
  1933. break;
  1934. case _pe:
  1935. errorName = "wrong output format ";
  1936. quitscrS(LightRed, errorName);
  1937. break;
  1938. case _fail:
  1939. errorName = "FAIL ";
  1940. quitscrS(LightRed, errorName);
  1941. break;
  1942. case _dirt:
  1943. errorName = "wrong output format ";
  1944. quitscrS(LightCyan, errorName);
  1945. result = _pe;
  1946. break;
  1947. case _points:
  1948. errorName = "points ";
  1949. quitscrS(LightYellow, errorName);
  1950. break;
  1951. case _unexpected_eof:
  1952. errorName = "unexpected eof ";
  1953. quitscrS(LightCyan, errorName);
  1954. break;
  1955. default:
  1956. if (result >= _partially)
  1957. {
  1958. errorName = format("partially correct (%d) ", pctype);
  1959. isPartial = true;
  1960. quitscrS(LightYellow, errorName);
  1961. }
  1962. else
  1963. quit(_fail, "What is the code ??? ");
  1964. }
  1965. if (resultName != "")
  1966. {
  1967. resultFile = std::fopen(resultName.c_str(), "w");
  1968. if (resultFile == NULL)
  1969. quit(_fail, "Can not write to the result file");
  1970. if (appesMode)
  1971. {
  1972. std::fprintf(resultFile, "<?xml version=\"1.0\" encoding=\"windows-1251\"?>");
  1973. if (isPartial)
  1974. std::fprintf(resultFile, "<result outcome = \"%s\" pctype = \"%d\">", outcomes[(int)_partially].c_str(), pctype);
  1975. else
  1976. {
  1977. if (result != _points)
  1978. std::fprintf(resultFile, "<result outcome = \"%s\">", outcomes[(int)result].c_str());
  1979. else
  1980. {
  1981. if (__testlib_points == std::numeric_limits<float>::infinity())
  1982. quit(_fail, "Expected points, but infinity found");
  1983. std::string stringPoints = removeDoubleTrailingZeroes(format("%.10f", __testlib_points));
  1984. std::fprintf(resultFile, "<result outcome = \"%s\" points = \"%s\">", outcomes[(int)result].c_str(), stringPoints.c_str());
  1985. }
  1986. }
  1987. xmlSafeWrite(resultFile, msg);
  1988. std::fprintf(resultFile, "</result>\n");
  1989. }
  1990. else
  1991. std::fprintf(resultFile, "%s", msg);
  1992. if (NULL == resultFile || fclose(resultFile) != 0)
  1993. quit(_fail, "Can not write to the result file");
  1994. }
  1995. quitscr(LightGray, msg);
  1996. std::fprintf(stderr, "\n");
  1997. inf.close();
  1998. ouf.close();
  1999. ans.close();
  2000. if (tout.is_open())
  2001. tout.close();
  2002. textColor(LightGray);
  2003. if (resultName != "")
  2004. std::fprintf(stderr, "See file to check exit message\n");
  2005. halt(resultExitCode(result));
  2006. }
  2007. #ifdef __GNUC__
  2008. __attribute__ ((format (printf, 3, 4)))
  2009. #endif
  2010. NORETURN void InStream::quitf(TResult result, const char* msg, ...)
  2011. {
  2012. FMT_TO_RESULT(msg, msg, message);
  2013. InStream::quit(result, message.c_str());
  2014. }
  2015. NORETURN void InStream::quits(TResult result, std::string msg)
  2016. {
  2017. InStream::quit(result, msg.c_str());
  2018. }
  2019. void InStream::xmlSafeWrite(std::FILE * file, const char* msg)
  2020. {
  2021. size_t lmsg = strlen(msg);
  2022. for (size_t i = 0; i < lmsg; i++)
  2023. {
  2024. if (msg[i] == '&')
  2025. {
  2026. std::fprintf(file, "%s", "&amp;");
  2027. continue;
  2028. }
  2029. if (msg[i] == '<')
  2030. {
  2031. std::fprintf(file, "%s", "&lt;");
  2032. continue;
  2033. }
  2034. if (msg[i] == '>')
  2035. {
  2036. std::fprintf(file, "%s", "&gt;");
  2037. continue;
  2038. }
  2039. if (msg[i] == '"')
  2040. {
  2041. std::fprintf(file, "%s", "&quot;");
  2042. continue;
  2043. }
  2044. if (0 <= msg[i] && msg[i] <= 31)
  2045. {
  2046. std::fprintf(file, "%c", '.');
  2047. continue;
  2048. }
  2049. std::fprintf(file, "%c", msg[i]);
  2050. }
  2051. }
  2052. void InStream::quitscrS(WORD color, std::string msg)
  2053. {
  2054. quitscr(color, msg.c_str());
  2055. }
  2056. void InStream::quitscr(WORD color, const char* msg)
  2057. {
  2058. if (resultName == "")
  2059. {
  2060. textColor(color);
  2061. std::fprintf(stderr, "%s", msg);
  2062. textColor(LightGray);
  2063. }
  2064. }
  2065. void InStream::reset(std::FILE* file)
  2066. {
  2067. if (opened && stdfile)
  2068. quit(_fail, "Can't reset standard handle");
  2069. if (opened)
  2070. close();
  2071. if (!stdfile)
  2072. if (NULL == (file = std::fopen(name.c_str(), "rb")))
  2073. {
  2074. if (mode == _output)
  2075. quits(_pe, std::string("Output file not found: \"") + name + "\"");
  2076. if (mode == _answer)
  2077. quits(_fail, std::string("Answer file not found: \"") + name + "\"");
  2078. }
  2079. if (NULL != file)
  2080. {
  2081. opened = true;
  2082. __testlib_set_binary(file);
  2083. if (stdfile)
  2084. reader = new FileInputStreamReader(file, name);
  2085. else
  2086. reader = new BufferedFileInputStreamReader(file, name);
  2087. }
  2088. else
  2089. {
  2090. opened = false;
  2091. reader = NULL;
  2092. }
  2093. }
  2094. void InStream::init(std::string fileName, TMode mode)
  2095. {
  2096. opened = false;
  2097. name = fileName;
  2098. stdfile = false;
  2099. this->mode = mode;
  2100. reset();
  2101. }
  2102. void InStream::init(std::FILE* f, TMode mode)
  2103. {
  2104. opened = false;
  2105. name = "untitled";
  2106. if (f == stdin)
  2107. name = "stdin", stdfile = true;
  2108. if (f == stdout)
  2109. name = "stdout", stdfile = true;
  2110. if (f == stderr)
  2111. name = "stderr", stdfile = true;
  2112. this->mode = mode;
  2113. reset(f);
  2114. }
  2115. char InStream::curChar()
  2116. {
  2117. return char(reader->curChar());
  2118. }
  2119. char InStream::nextChar()
  2120. {
  2121. return char(reader->nextChar());
  2122. }
  2123. char InStream::readChar()
  2124. {
  2125. return nextChar();
  2126. }
  2127. char InStream::readChar(char c)
  2128. {
  2129. char found = readChar();
  2130. if (c != found)
  2131. {
  2132. if (!isEoln(found))
  2133. quit(_pe, ("Unexpected character '" + std::string(1, found) + "', but '" + std::string(1, c) + "' expected").c_str());
  2134. else
  2135. quit(_pe, ("Unexpected character " + ("#" + vtos(int(found))) + ", but '" + std::string(1, c) + "' expected").c_str());
  2136. }
  2137. return found;
  2138. }
  2139. char InStream::readSpace()
  2140. {
  2141. return readChar(' ');
  2142. }
  2143. void InStream::unreadChar(char c)
  2144. {
  2145. reader->unreadChar(c);
  2146. }
  2147. void InStream::skipChar()
  2148. {
  2149. reader->skipChar();
  2150. }
  2151. void InStream::skipBlanks()
  2152. {
  2153. while (isBlanks(reader->curChar()))
  2154. reader->skipChar();
  2155. }
  2156. std::string InStream::readWord()
  2157. {
  2158. readWordTo(_tmpReadToken);
  2159. return _tmpReadToken;
  2160. }
  2161. void InStream::readWordTo(std::string& result)
  2162. {
  2163. if (!strict)
  2164. skipBlanks();
  2165. int cur = reader->nextChar();
  2166. if (cur == EOFC)
  2167. quit(_unexpected_eof, "Unexpected end of file - token expected");
  2168. if (isBlanks(cur))
  2169. quit(_pe, "Unexpected white-space - token expected");
  2170. result.clear();
  2171. while (!(isBlanks(cur) || cur == EOFC))
  2172. {
  2173. result += char(cur);
  2174. cur = reader->nextChar();
  2175. }
  2176. reader->unreadChar(cur);
  2177. if (result.length() == 0)
  2178. quit(_unexpected_eof, "Unexpected end of file or white-space - token expected");
  2179. }
  2180. std::string InStream::readToken()
  2181. {
  2182. return readWord();
  2183. }
  2184. void InStream::readTokenTo(std::string& result)
  2185. {
  2186. readWordTo(result);
  2187. }
  2188. static std::string __testlib_part(const std::string& s)
  2189. {
  2190. if (s.length() <= 64)
  2191. return s;
  2192. else
  2193. return s.substr(0, 30) + "..." + s.substr(s.length() - 31, 31);
  2194. }
  2195. std::string InStream::readWord(const pattern& p, const std::string& variableName)
  2196. {
  2197. readWordTo(_tmpReadToken);
  2198. if (!p.matches(_tmpReadToken))
  2199. {
  2200. if (variableName.empty())
  2201. quit(_wa, ("Token \"" + __testlib_part(_tmpReadToken) + "\" doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  2202. else
  2203. quit(_wa, ("Token parameter [name=" + variableName + "] equals to \"" + __testlib_part(_tmpReadToken) + "\", doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  2204. }
  2205. return _tmpReadToken;
  2206. }
  2207. std::string InStream::readWord(const std::string& ptrn, const std::string& variableName)
  2208. {
  2209. return readWord(pattern(ptrn), variableName);
  2210. }
  2211. std::string InStream::readToken(const pattern& p, const std::string& variableName)
  2212. {
  2213. return readWord(p, variableName);
  2214. }
  2215. std::string InStream::readToken(const std::string& ptrn, const std::string& variableName)
  2216. {
  2217. return readWord(ptrn, variableName);
  2218. }
  2219. void InStream::readWordTo(std::string& result, const pattern& p, const std::string& variableName)
  2220. {
  2221. readWordTo(result);
  2222. if (!p.matches(result))
  2223. {
  2224. if (variableName.empty())
  2225. quit(_wa, ("Token \"" + __testlib_part(result) + "\" doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  2226. else
  2227. quit(_wa, ("Token parameter [name=" + variableName + "] equals to \"" + __testlib_part(result) + "\", doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  2228. }
  2229. }
  2230. void InStream::readWordTo(std::string& result, const std::string& ptrn, const std::string& variableName)
  2231. {
  2232. return readWordTo(result, pattern(ptrn), variableName);
  2233. }
  2234. void InStream::readTokenTo(std::string& result, const pattern& p, const std::string& variableName)
  2235. {
  2236. return readWordTo(result, p, variableName);
  2237. }
  2238. void InStream::readTokenTo(std::string& result, const std::string& ptrn, const std::string& variableName)
  2239. {
  2240. return readWordTo(result, ptrn, variableName);
  2241. }
  2242. #ifdef __GNUC__
  2243. __attribute__((pure))
  2244. #endif
  2245. static inline bool equals(long long integer, const char* s)
  2246. {
  2247. if (integer == LLONG_MIN)
  2248. return strcmp(s, "-9223372036854775808") == 0;
  2249. if (integer == 0LL)
  2250. return strcmp(s, "0") == 0;
  2251. size_t length = strlen(s);
  2252. if (length == 0)
  2253. return false;
  2254. if (integer < 0 && s[0] != '-')
  2255. return false;
  2256. if (integer < 0)
  2257. s++, length--, integer = -integer;
  2258. if (length == 0)
  2259. return false;
  2260. while (integer > 0)
  2261. {
  2262. int digit = int(integer % 10);
  2263. if (s[length - 1] != '0' + digit)
  2264. return false;
  2265. length--;
  2266. integer /= 10;
  2267. }
  2268. return length == 0;
  2269. }
  2270. #ifdef __GNUC__
  2271. __attribute__((pure))
  2272. #endif
  2273. static inline bool equals(unsigned long long integer, const char* s)
  2274. {
  2275. if (integer == ULLONG_MAX)
  2276. return strcmp(s, "18446744073709551615") == 0;
  2277. if (integer == 0ULL)
  2278. return strcmp(s, "0") == 0;
  2279. size_t length = strlen(s);
  2280. if (length == 0)
  2281. return false;
  2282. while (integer > 0)
  2283. {
  2284. int digit = int(integer % 10);
  2285. if (s[length - 1] != '0' + digit)
  2286. return false;
  2287. length--;
  2288. integer /= 10;
  2289. }
  2290. return length == 0;
  2291. }
  2292. static inline double stringToDouble(InStream& in, const char* buffer)
  2293. {
  2294. double retval;
  2295. size_t length = strlen(buffer);
  2296. int minusCount = 0;
  2297. int plusCount = 0;
  2298. int decimalPointCount = 0;
  2299. int digitCount = 0;
  2300. int eCount = 0;
  2301. for (size_t i = 0; i < length; i++)
  2302. {
  2303. if (('0' <= buffer[i] && buffer[i] <= '9') || buffer[i] == '.'
  2304. || buffer[i] == 'e' || buffer[i] == 'E'
  2305. || buffer[i] == '-' || buffer[i] == '+')
  2306. {
  2307. if ('0' <= buffer[i] && buffer[i] <= '9')
  2308. digitCount++;
  2309. if (buffer[i] == 'e' || buffer[i] == 'E')
  2310. eCount++;
  2311. if (buffer[i] == '-')
  2312. minusCount++;
  2313. if (buffer[i] == '+')
  2314. plusCount++;
  2315. if (buffer[i] == '.')
  2316. decimalPointCount++;
  2317. }
  2318. else
  2319. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2320. }
  2321. // If for sure is not a number in standard notation or in e-notation.
  2322. if (digitCount == 0 || minusCount > 2 || plusCount > 2 || decimalPointCount > 1 || eCount > 1)
  2323. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2324. char* suffix = new char[length + 1];
  2325. int scanned = std::sscanf(buffer, "%lf%s", &retval, suffix);
  2326. bool empty = strlen(suffix) == 0;
  2327. delete[] suffix;
  2328. if (scanned == 1 || (scanned == 2 && empty))
  2329. {
  2330. if (__testlib_isNaN(retval))
  2331. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2332. return retval;
  2333. }
  2334. else
  2335. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2336. }
  2337. static inline double stringToStrictDouble(InStream& in, const char* buffer, int minAfterPointDigitCount, int maxAfterPointDigitCount)
  2338. {
  2339. if (minAfterPointDigitCount < 0)
  2340. in.quit(_fail, "stringToStrictDouble: minAfterPointDigitCount should be non-negative.");
  2341. if (minAfterPointDigitCount > maxAfterPointDigitCount)
  2342. in.quit(_fail, "stringToStrictDouble: minAfterPointDigitCount should be less or equal to maxAfterPointDigitCount.");
  2343. double retval;
  2344. size_t length = strlen(buffer);
  2345. if (length == 0 || length > 1000)
  2346. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2347. if (buffer[0] != '-' && (buffer[0] < '0' || buffer[0] > '9'))
  2348. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2349. int pointPos = -1;
  2350. for (size_t i = 1; i + 1 < length; i++)
  2351. {
  2352. if (buffer[i] == '.')
  2353. {
  2354. if (pointPos > -1)
  2355. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2356. pointPos = int(i);
  2357. }
  2358. if (buffer[i] != '.' && (buffer[i] < '0' || buffer[i] > '9'))
  2359. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2360. }
  2361. if (buffer[length - 1] < '0' || buffer[length - 1] > '9')
  2362. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2363. int afterDigitsCount = (pointPos == -1 ? 0 : int(length) - pointPos - 1);
  2364. if (afterDigitsCount < minAfterPointDigitCount || afterDigitsCount > maxAfterPointDigitCount)
  2365. in.quit(_pe, ("Expected strict double with number of digits after point in range ["
  2366. + vtos(minAfterPointDigitCount)
  2367. + ","
  2368. + vtos(maxAfterPointDigitCount)
  2369. + "], but \"" + __testlib_part(buffer) + "\" found").c_str()
  2370. );
  2371. int firstDigitPos = -1;
  2372. for (size_t i = 0; i < length; i++)
  2373. if (buffer[i] >= '0' && buffer[i] <= '9')
  2374. {
  2375. firstDigitPos = int(i);
  2376. break;
  2377. }
  2378. if (firstDigitPos > 1 || firstDigitPos == -1)
  2379. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2380. if (buffer[firstDigitPos] == '0' && firstDigitPos + 1 < int(length)
  2381. && buffer[firstDigitPos + 1] >= '0' && buffer[firstDigitPos + 1] <= '9')
  2382. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2383. char* suffix = new char[length + 1];
  2384. int scanned = std::sscanf(buffer, "%lf%s", &retval, suffix);
  2385. bool empty = strlen(suffix) == 0;
  2386. delete[] suffix;
  2387. if (scanned == 1 || (scanned == 2 && empty))
  2388. {
  2389. if (__testlib_isNaN(retval) || __testlib_isInfinite(retval))
  2390. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2391. return retval;
  2392. }
  2393. else
  2394. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2395. }
  2396. static inline long long stringToLongLong(InStream& in, const char* buffer)
  2397. {
  2398. if (strcmp(buffer, "-9223372036854775808") == 0)
  2399. return LLONG_MIN;
  2400. bool minus = false;
  2401. size_t length = strlen(buffer);
  2402. if (length > 1 && buffer[0] == '-')
  2403. minus = true;
  2404. if (length > 20)
  2405. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2406. long long retval = 0LL;
  2407. int zeroes = 0;
  2408. int processingZeroes = true;
  2409. for (int i = (minus ? 1 : 0); i < int(length); i++)
  2410. {
  2411. if (buffer[i] == '0' && processingZeroes)
  2412. zeroes++;
  2413. else
  2414. processingZeroes = false;
  2415. if (buffer[i] < '0' || buffer[i] > '9')
  2416. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2417. retval = retval * 10 + (buffer[i] - '0');
  2418. }
  2419. if (retval < 0)
  2420. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2421. if ((zeroes > 0 && (retval != 0 || minus)) || zeroes > 1)
  2422. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2423. retval = (minus ? -retval : +retval);
  2424. if (length < 19)
  2425. return retval;
  2426. if (equals(retval, buffer))
  2427. return retval;
  2428. else
  2429. in.quit(_pe, ("Expected int64, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2430. }
  2431. static inline unsigned long long stringToUnsignedLongLong(InStream& in, const char* buffer)
  2432. {
  2433. size_t length = strlen(buffer);
  2434. if (length > 20)
  2435. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2436. if (length > 1 && buffer[0] == '0')
  2437. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2438. unsigned long long retval = 0LL;
  2439. for (int i = 0; i < int(length); i++)
  2440. {
  2441. if (buffer[i] < '0' || buffer[i] > '9')
  2442. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2443. retval = retval * 10 + (buffer[i] - '0');
  2444. }
  2445. if (length < 19)
  2446. return retval;
  2447. if (length == 20 && strcmp(buffer, "18446744073709551615") == 1)
  2448. in.quit(_pe, ("Expected unsigned int64, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2449. if (equals(retval, buffer))
  2450. return retval;
  2451. else
  2452. in.quit(_pe, ("Expected unsigned int64, but \"" + __testlib_part(buffer) + "\" found").c_str());
  2453. }
  2454. int InStream::readInteger()
  2455. {
  2456. if (!strict && seekEof())
  2457. quit(_unexpected_eof, "Unexpected end of file - int32 expected");
  2458. readWordTo(_tmpReadToken);
  2459. long long value = stringToLongLong(*this, _tmpReadToken.c_str());
  2460. if (value < INT_MIN || value > INT_MAX)
  2461. quit(_pe, ("Expected int32, but \"" + __testlib_part(_tmpReadToken) + "\" found").c_str());
  2462. return int(value);
  2463. }
  2464. long long InStream::readLong()
  2465. {
  2466. if (!strict && seekEof())
  2467. quit(_unexpected_eof, "Unexpected end of file - int64 expected");
  2468. readWordTo(_tmpReadToken);
  2469. return stringToLongLong(*this, _tmpReadToken.c_str());
  2470. }
  2471. unsigned long long InStream::readUnsignedLong()
  2472. {
  2473. if (!strict && seekEof())
  2474. quit(_unexpected_eof, "Unexpected end of file - int64 expected");
  2475. readWordTo(_tmpReadToken);
  2476. return stringToUnsignedLongLong(*this, _tmpReadToken.c_str());
  2477. }
  2478. long long InStream::readLong(long long minv, long long maxv, const std::string& variableName)
  2479. {
  2480. long long result = readLong();
  2481. if (result < minv || result > maxv)
  2482. {
  2483. if (variableName.empty())
  2484. quit(_wa, ("Integer " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  2485. else
  2486. quit(_wa, ("Integer parameter [name=" + variableName + "] equals to " + vtos(result) + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  2487. }
  2488. if (strict && !variableName.empty())
  2489. validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));
  2490. return result;
  2491. }
  2492. unsigned long long InStream::readUnsignedLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName)
  2493. {
  2494. unsigned long long result = readUnsignedLong();
  2495. if (result < minv || result > maxv)
  2496. {
  2497. if (variableName.empty())
  2498. quit(_wa, ("Integer " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  2499. else
  2500. quit(_wa, ("Integer parameter [name=" + variableName + "] equals to " + vtos(result) + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  2501. }
  2502. if (strict && !variableName.empty())
  2503. validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));
  2504. return result;
  2505. }
  2506. unsigned long long InStream::readLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName)
  2507. {
  2508. return readUnsignedLong(minv, maxv, variableName);
  2509. }
  2510. int InStream::readInt()
  2511. {
  2512. return readInteger();
  2513. }
  2514. int InStream::readInt(int minv, int maxv, const std::string& variableName)
  2515. {
  2516. int result = readInt();
  2517. if (result < minv || result > maxv)
  2518. {
  2519. if (variableName.empty())
  2520. quit(_wa, ("Integer " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  2521. else
  2522. quit(_wa, ("Integer parameter [name=" + std::string(variableName) + "] equals to " + vtos(result) + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  2523. }
  2524. if (strict && !variableName.empty())
  2525. validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));
  2526. return result;
  2527. }
  2528. int InStream::readInteger(int minv, int maxv, const std::string& variableName)
  2529. {
  2530. return readInt(minv, maxv, variableName);
  2531. }
  2532. double InStream::readReal()
  2533. {
  2534. if (!strict && seekEof())
  2535. quit(_unexpected_eof, "Unexpected end of file - double expected");
  2536. return stringToDouble(*this, readWord().c_str());
  2537. }
  2538. double InStream::readDouble()
  2539. {
  2540. return readReal();
  2541. }
  2542. double InStream::readReal(double minv, double maxv, const std::string& variableName)
  2543. {
  2544. double result = readReal();
  2545. if (result < minv || result > maxv)
  2546. {
  2547. if (variableName.empty())
  2548. quit(_wa, ("Double " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  2549. else
  2550. quit(_wa, ("Double parameter [name=" + variableName + "] equals to " + vtos(result) + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  2551. }
  2552. if (strict && !variableName.empty())
  2553. validator.addBoundsHit(variableName, ValidatorBoundsHit(
  2554. doubleDelta(minv, result) < ValidatorBoundsHit::EPS,
  2555. doubleDelta(maxv, result) < ValidatorBoundsHit::EPS
  2556. ));
  2557. return result;
  2558. }
  2559. double InStream::readDouble(double minv, double maxv, const std::string& variableName)
  2560. {
  2561. return readReal(minv, maxv, variableName);
  2562. }
  2563. double InStream::readStrictReal(double minv, double maxv,
  2564. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  2565. const std::string& variableName)
  2566. {
  2567. if (!strict && seekEof())
  2568. quit(_unexpected_eof, "Unexpected end of file - strict double expected");
  2569. double result = stringToStrictDouble(*this, readWord().c_str(),
  2570. minAfterPointDigitCount, maxAfterPointDigitCount);
  2571. if (result < minv || result > maxv)
  2572. {
  2573. if (variableName.empty())
  2574. quit(_wa, ("Strict double " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  2575. else
  2576. quit(_wa, ("Strict double parameter [name=" + variableName + "] equals to " + vtos(result) + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  2577. }
  2578. if (strict && !variableName.empty())
  2579. validator.addBoundsHit(variableName, ValidatorBoundsHit(
  2580. doubleDelta(minv, result) < ValidatorBoundsHit::EPS,
  2581. doubleDelta(maxv, result) < ValidatorBoundsHit::EPS
  2582. ));
  2583. return result;
  2584. }
  2585. double InStream::readStrictDouble(double minv, double maxv,
  2586. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  2587. const std::string& variableName)
  2588. {
  2589. return readStrictReal(minv, maxv,
  2590. minAfterPointDigitCount, maxAfterPointDigitCount,
  2591. variableName);
  2592. }
  2593. bool InStream::eof()
  2594. {
  2595. if (!strict && NULL == reader)
  2596. return true;
  2597. return reader->eof();
  2598. }
  2599. bool InStream::seekEof()
  2600. {
  2601. if (!strict && NULL == reader)
  2602. return true;
  2603. skipBlanks();
  2604. return eof();
  2605. }
  2606. bool InStream::eoln()
  2607. {
  2608. if (!strict && NULL == reader)
  2609. return true;
  2610. int c = reader->nextChar();
  2611. if (!strict)
  2612. {
  2613. if (c == EOFC)
  2614. return true;
  2615. if (c == CR)
  2616. {
  2617. c = reader->nextChar();
  2618. if (c != LF)
  2619. {
  2620. reader->unreadChar(c);
  2621. reader->unreadChar(CR);
  2622. return false;
  2623. }
  2624. else
  2625. return true;
  2626. }
  2627. if (c == LF)
  2628. return true;
  2629. reader->unreadChar(c);
  2630. return false;
  2631. }
  2632. else
  2633. {
  2634. bool returnCr = false;
  2635. #ifdef ON_WINDOWS
  2636. if (c != CR)
  2637. {
  2638. reader->unreadChar(c);
  2639. return false;
  2640. }
  2641. else
  2642. {
  2643. if (!returnCr)
  2644. returnCr = true;
  2645. c = reader->nextChar();
  2646. }
  2647. #endif
  2648. if (c != LF)
  2649. {
  2650. reader->unreadChar(c);
  2651. if (returnCr)
  2652. reader->unreadChar(CR);
  2653. return false;
  2654. }
  2655. return true;
  2656. }
  2657. }
  2658. void InStream::readEoln()
  2659. {
  2660. if (!eoln())
  2661. quit(_pe, "Expected EOLN");
  2662. }
  2663. void InStream::readEof()
  2664. {
  2665. if (!eof())
  2666. quit(_pe, "Expected EOF");
  2667. if (TestlibFinalizeGuard::alive && this == &inf)
  2668. testlibFinalizeGuard.readEofCount++;
  2669. }
  2670. bool InStream::seekEoln()
  2671. {
  2672. if (!strict && NULL == reader)
  2673. return true;
  2674. int cur;
  2675. do
  2676. {
  2677. cur = reader->nextChar();
  2678. }
  2679. while (cur == SPACE || cur == TAB);
  2680. reader->unreadChar(cur);
  2681. return eoln();
  2682. }
  2683. void InStream::nextLine()
  2684. {
  2685. readLine();
  2686. }
  2687. void InStream::readStringTo(std::string& result)
  2688. {
  2689. if (NULL == reader)
  2690. quit(_pe, "Expected line");
  2691. result.clear();
  2692. int cur;
  2693. for (;;)
  2694. {
  2695. cur = reader->curChar();
  2696. if (isEoln(cur))
  2697. break;
  2698. if (cur == EOFC)
  2699. break;
  2700. result += char(reader->nextChar());
  2701. }
  2702. if (strict)
  2703. readEoln();
  2704. else
  2705. eoln();
  2706. }
  2707. std::string InStream::readString()
  2708. {
  2709. readStringTo(_tmpReadToken);
  2710. return _tmpReadToken;
  2711. }
  2712. void InStream::readStringTo(std::string& result, const pattern& p, const std::string& variableName)
  2713. {
  2714. readStringTo(result);
  2715. if (!p.matches(result))
  2716. {
  2717. if (variableName.empty())
  2718. quit(_wa, ("Line \"" + __testlib_part(result) + "\" doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  2719. else
  2720. quit(_wa, ("Line [name=" + variableName + "] equals to \"" + __testlib_part(result) + "\", doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  2721. }
  2722. }
  2723. void InStream::readStringTo(std::string& result, const std::string& ptrn, const std::string& variableName)
  2724. {
  2725. readStringTo(result, pattern(ptrn), variableName);
  2726. }
  2727. std::string InStream::readString(const pattern& p, const std::string& variableName)
  2728. {
  2729. readStringTo(_tmpReadToken, p, variableName);
  2730. return _tmpReadToken;
  2731. }
  2732. std::string InStream::readString(const std::string& ptrn, const std::string& variableName)
  2733. {
  2734. readStringTo(_tmpReadToken, ptrn, variableName);
  2735. return _tmpReadToken;
  2736. }
  2737. void InStream::readLineTo(std::string& result)
  2738. {
  2739. readStringTo(result);
  2740. }
  2741. std::string InStream::readLine()
  2742. {
  2743. return readString();
  2744. }
  2745. void InStream::readLineTo(std::string& result, const pattern& p, const std::string& variableName)
  2746. {
  2747. readStringTo(result, p, variableName);
  2748. }
  2749. void InStream::readLineTo(std::string& result, const std::string& ptrn, const std::string& variableName)
  2750. {
  2751. readStringTo(result, ptrn, variableName);
  2752. }
  2753. std::string InStream::readLine(const pattern& p, const std::string& variableName)
  2754. {
  2755. return readString(p, variableName);
  2756. }
  2757. std::string InStream::readLine(const std::string& ptrn, const std::string& variableName)
  2758. {
  2759. return readString(ptrn, variableName);
  2760. }
  2761. void InStream::close()
  2762. {
  2763. if (NULL != reader)
  2764. {
  2765. reader->close();
  2766. delete reader;
  2767. reader = NULL;
  2768. }
  2769. opened = false;
  2770. }
  2771. NORETURN void quit(TResult result, const std::string& msg)
  2772. {
  2773. ouf.quit(result, msg.c_str());
  2774. }
  2775. NORETURN void quit(TResult result, const char* msg)
  2776. {
  2777. ouf.quit(result, msg);
  2778. }
  2779. NORETURN void __testlib_quitp(double points, const char* message)
  2780. {
  2781. __testlib_points = points;
  2782. std::string stringPoints = removeDoubleTrailingZeroes(format("%.10f", points));
  2783. std::string quitMessage;
  2784. if (NULL == message || 0 == strlen(message))
  2785. quitMessage = stringPoints;
  2786. else
  2787. quitMessage = stringPoints + " " + message;
  2788. quit(_points, quitMessage.c_str());
  2789. }
  2790. NORETURN void __testlib_quitp(int points, const char* message)
  2791. {
  2792. __testlib_points = points;
  2793. std::string stringPoints = format("%d", points);
  2794. std::string quitMessage;
  2795. if (NULL == message || 0 == strlen(message))
  2796. quitMessage = stringPoints;
  2797. else
  2798. quitMessage = stringPoints + " " + message;
  2799. quit(_points, quitMessage.c_str());
  2800. }
  2801. NORETURN void quitp(float points, const std::string& message = "")
  2802. {
  2803. __testlib_quitp(double(points), message.c_str());
  2804. }
  2805. NORETURN void quitp(double points, const std::string& message = "")
  2806. {
  2807. __testlib_quitp(points, message.c_str());
  2808. }
  2809. NORETURN void quitp(long double points, const std::string& message = "")
  2810. {
  2811. __testlib_quitp(double(points), message.c_str());
  2812. }
  2813. NORETURN void quitp(int points, const std::string& message = "")
  2814. {
  2815. __testlib_quitp(points, message.c_str());
  2816. }
  2817. template<typename F>
  2818. #ifdef __GNUC__
  2819. __attribute__ ((format (printf, 2, 3)))
  2820. #endif
  2821. NORETURN void quitp(F points, const char* format, ...)
  2822. {
  2823. FMT_TO_RESULT(format, format, message);
  2824. quitp(points, message);
  2825. }
  2826. #ifdef __GNUC__
  2827. __attribute__ ((format (printf, 2, 3)))
  2828. #endif
  2829. NORETURN void quitf(TResult result, const char* format, ...)
  2830. {
  2831. FMT_TO_RESULT(format, format, message);
  2832. quit(result, message);
  2833. }
  2834. #ifdef __GNUC__
  2835. __attribute__ ((format (printf, 3, 4)))
  2836. #endif
  2837. void quitif(bool condition, TResult result, const char* format, ...)
  2838. {
  2839. if (condition)
  2840. {
  2841. FMT_TO_RESULT(format, format, message);
  2842. quit(result, message);
  2843. }
  2844. }
  2845. NORETURN void __testlib_help()
  2846. {
  2847. InStream::textColor(InStream::LightCyan);
  2848. std::fprintf(stderr, "TESTLIB %s, http://code.google.com/p/testlib/ ", VERSION);
  2849. std::fprintf(stderr, "by Mike Mirzayanov, copyright(c) 2005-2015\n");
  2850. std::fprintf(stderr, "Checker name: \"%s\"\n", checkerName.c_str());
  2851. InStream::textColor(InStream::LightGray);
  2852. std::fprintf(stderr, "\n");
  2853. std::fprintf(stderr, "Latest features: \n");
  2854. for (size_t i = 0; i < sizeof(latestFeatures) / sizeof(char*); i++)
  2855. {
  2856. std::fprintf(stderr, "*) %s\n", latestFeatures[i]);
  2857. }
  2858. std::fprintf(stderr, "\n");
  2859. std::fprintf(stderr, "Program must be run with the following arguments: \n");
  2860. std::fprintf(stderr, " <input-file> <output-file> <answer-file> [<report-file> [<-appes>]]\n\n");
  2861. std::exit(FAIL_EXIT_CODE);
  2862. }
  2863. static void __testlib_ensuresPreconditions()
  2864. {
  2865. // testlib assumes: sizeof(int) = 4.
  2866. __TESTLIB_STATIC_ASSERT(sizeof(int) == 4);
  2867. // testlib assumes: INT_MAX == 2147483647.
  2868. __TESTLIB_STATIC_ASSERT(INT_MAX == 2147483647);
  2869. // testlib assumes: sizeof(long long) = 8.
  2870. __TESTLIB_STATIC_ASSERT(sizeof(long long) == 8);
  2871. // testlib assumes: sizeof(double) = 8.
  2872. __TESTLIB_STATIC_ASSERT(sizeof(double) == 8);
  2873. // testlib assumes: no -ffast-math.
  2874. if (!__testlib_isNaN(+__testlib_nan()))
  2875. quit(_fail, "Function __testlib_isNaN is not working correctly: possible reason is '-ffast-math'");
  2876. if (!__testlib_isNaN(-__testlib_nan()))
  2877. quit(_fail, "Function __testlib_isNaN is not working correctly: possible reason is '-ffast-math'");
  2878. }
  2879. void registerGen(int argc, char* argv[], int randomGeneratorVersion)
  2880. {
  2881. if (randomGeneratorVersion < 0 || randomGeneratorVersion > 1)
  2882. quitf(_fail, "Random generator version is expected to be 0 or 1.");
  2883. random_t::version = randomGeneratorVersion;
  2884. __testlib_ensuresPreconditions();
  2885. testlibMode = _generator;
  2886. __testlib_set_binary(stdin);
  2887. rnd.setSeed(argc, argv);
  2888. }
  2889. #ifdef USE_RND_AS_BEFORE_087
  2890. void registerGen(int argc, char* argv[])
  2891. {
  2892. registerGen(argc, argv, 0);
  2893. }
  2894. #else
  2895. #ifdef __GNUC__
  2896. __attribute__ ((deprecated("Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1)."
  2897. " The third parameter stands for the random generator version."
  2898. " If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0)."
  2899. " Version 1 has been released on Spring, 2013. Use it to write new generators.")))
  2900. #endif
  2901. #ifdef _MSC_VER
  2902. __declspec(deprecated("Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1)."
  2903. " The third parameter stands for the random generator version."
  2904. " If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0)."
  2905. " Version 1 has been released on Spring, 2013. Use it to write new generators."))
  2906. #endif
  2907. void registerGen(int argc, char* argv[])
  2908. {
  2909. std::fprintf(stderr, "Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1)."
  2910. " The third parameter stands for the random generator version."
  2911. " If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0)."
  2912. " Version 1 has been released on Spring, 2013. Use it to write new generators.\n\n");
  2913. registerGen(argc, argv, 0);
  2914. }
  2915. #endif
  2916. void registerInteraction(int argc, char* argv[])
  2917. {
  2918. __testlib_ensuresPreconditions();
  2919. testlibMode = _interactor;
  2920. __testlib_set_binary(stdin);
  2921. if (argc > 1 && !strcmp("--help", argv[1]))
  2922. __testlib_help();
  2923. if (argc < 3 || argc > 6)
  2924. {
  2925. quit(_fail, std::string("Program must be run with the following arguments: ") +
  2926. std::string("<input-file> <output-file> [<answer-file> [<report-file> [<-appes>]]]") +
  2927. "\nUse \"--help\" to get help information");
  2928. }
  2929. if (argc <= 4)
  2930. {
  2931. resultName = "";
  2932. appesMode = false;
  2933. }
  2934. if (argc == 5)
  2935. {
  2936. resultName = argv[4];
  2937. appesMode = false;
  2938. }
  2939. if (argc == 6)
  2940. {
  2941. if (strcmp("-APPES", argv[5]) && strcmp("-appes", argv[5]))
  2942. {
  2943. quit(_fail, std::string("Program must be run with the following arguments: ") +
  2944. "<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]");
  2945. }
  2946. else
  2947. {
  2948. resultName = argv[4];
  2949. appesMode = true;
  2950. }
  2951. }
  2952. inf.init(argv[1], _input);
  2953. tout.open(argv[2], std::ios_base::out);
  2954. if (tout.fail() || !tout.is_open())
  2955. quit(_fail, std::string("Can not write to the test-output-file '") + argv[2] + std::string("'"));
  2956. ouf.init(stdin, _output);
  2957. if (argc >= 4)
  2958. ans.init(argv[3], _answer);
  2959. else
  2960. ans.name = "unopened answer stream";
  2961. }
  2962. void registerValidation()
  2963. {
  2964. __testlib_ensuresPreconditions();
  2965. testlibMode = _validator;
  2966. __testlib_set_binary(stdin);
  2967. inf.init(stdin, _input);
  2968. inf.strict = true;
  2969. }
  2970. void registerValidation(int argc, char* argv[])
  2971. {
  2972. registerValidation();
  2973. for (int i = 1; i < argc; i++)
  2974. {
  2975. if (!strcmp("--testset", argv[i]))
  2976. {
  2977. if (i + 1 < argc && strlen(argv[i + 1]) > 0)
  2978. validator.setTestset(argv[++i]);
  2979. else
  2980. quit(_fail, std::string("Validator must be run with the following arguments: ") +
  2981. "[--testset testset] [--group group] [--testOverviewLogFileName fileName]");
  2982. }
  2983. if (!strcmp("--group", argv[i]))
  2984. {
  2985. if (i + 1 < argc)
  2986. validator.setGroup(argv[++i]);
  2987. else
  2988. quit(_fail, std::string("Validator must be run with the following arguments: ") +
  2989. "[--testset testset] [--group group] [--testOverviewLogFileName fileName]");
  2990. }
  2991. if (!strcmp("--testOverviewLogFileName", argv[i]))
  2992. {
  2993. if (i + 1 < argc)
  2994. validator.setTestOverviewLogFileName(argv[++i]);
  2995. else
  2996. quit(_fail, std::string("Validator must be run with the following arguments: ") +
  2997. "[--testset testset] [--group group] [--testOverviewLogFileName fileName]");
  2998. }
  2999. }
  3000. }
  3001. void addFeature(const std::string& feature)
  3002. {
  3003. if (testlibMode != _validator)
  3004. quit(_fail, "Features are supported in validators only.");
  3005. validator.addFeature(feature);
  3006. }
  3007. void feature(const std::string& feature)
  3008. {
  3009. if (testlibMode != _validator)
  3010. quit(_fail, "Features are supported in validators only.");
  3011. validator.feature(feature);
  3012. }
  3013. void registerTestlibCmd(int argc, char* argv[])
  3014. {
  3015. __testlib_ensuresPreconditions();
  3016. testlibMode = _checker;
  3017. __testlib_set_binary(stdin);
  3018. if (argc > 1 && !strcmp("--help", argv[1]))
  3019. __testlib_help();
  3020. if (argc < 4 || argc > 6)
  3021. {
  3022. quit(_fail, std::string("Program must be run with the following arguments: ") +
  3023. std::string("<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]") +
  3024. "\nUse \"--help\" to get help information");
  3025. }
  3026. if (argc == 4)
  3027. {
  3028. resultName = "";
  3029. appesMode = false;
  3030. }
  3031. if (argc == 5)
  3032. {
  3033. resultName = argv[4];
  3034. appesMode = false;
  3035. }
  3036. if (argc == 6)
  3037. {
  3038. if (strcmp("-APPES", argv[5]) && strcmp("-appes", argv[5]))
  3039. {
  3040. quit(_fail, std::string("Program must be run with the following arguments: ") +
  3041. "<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]");
  3042. }
  3043. else
  3044. {
  3045. resultName = argv[4];
  3046. appesMode = true;
  3047. }
  3048. }
  3049. inf.init(argv[1], _input);
  3050. ouf.init(argv[2], _output);
  3051. ans.init(argv[3], _answer);
  3052. }
  3053. void registerTestlib(int argc, ...)
  3054. {
  3055. if (argc < 3 || argc > 5)
  3056. quit(_fail, std::string("Program must be run with the following arguments: ") +
  3057. "<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]");
  3058. char** argv = new char*[argc + 1];
  3059. va_list ap;
  3060. va_start(ap, argc);
  3061. argv[0] = NULL;
  3062. for (int i = 0; i < argc; i++)
  3063. {
  3064. argv[i + 1] = va_arg(ap, char*);
  3065. }
  3066. va_end(ap);
  3067. registerTestlibCmd(argc + 1, argv);
  3068. delete[] argv;
  3069. }
  3070. static inline void __testlib_ensure(bool cond, const std::string& msg)
  3071. {
  3072. if (!cond)
  3073. quit(_fail, msg.c_str());
  3074. }
  3075. static inline void __testlib_ensure(bool cond, const char* msg)
  3076. {
  3077. if (!cond)
  3078. quit(_fail, msg);
  3079. }
  3080. #define ensure(cond) __testlib_ensure(cond, "Condition failed: \"" #cond "\"")
  3081. #ifdef __GNUC__
  3082. __attribute__ ((format (printf, 2, 3)))
  3083. #endif
  3084. inline void ensuref(bool cond, const char* format, ...)
  3085. {
  3086. if (!cond)
  3087. {
  3088. FMT_TO_RESULT(format, format, message);
  3089. __testlib_ensure(cond, message);
  3090. }
  3091. }
  3092. NORETURN static void __testlib_fail(const std::string& message)
  3093. {
  3094. quitf(_fail, "%s", message.c_str());
  3095. }
  3096. #ifdef __GNUC__
  3097. __attribute__ ((format (printf, 1, 2)))
  3098. #endif
  3099. void setName(const char* format, ...)
  3100. {
  3101. FMT_TO_RESULT(format, format, name);
  3102. checkerName = name;
  3103. }
  3104. /*
  3105. * Do not use random_shuffle, because it will produce different result
  3106. * for different C++ compilers.
  3107. *
  3108. * This implementation uses testlib random_t to produce random numbers, so
  3109. * it is stable.
  3110. */
  3111. template<typename _RandomAccessIter>
  3112. void shuffle(_RandomAccessIter __first, _RandomAccessIter __last)
  3113. {
  3114. if (__first == __last) return;
  3115. for (_RandomAccessIter __i = __first + 1; __i != __last; ++__i)
  3116. std::iter_swap(__i, __first + rnd.next(int(__i - __first) + 1));
  3117. }
  3118. template<typename _RandomAccessIter>
  3119. #ifdef __GNUC__
  3120. __attribute__ ((error("Don't use random_shuffle(), use shuffle() instead")))
  3121. #endif
  3122. void random_shuffle(_RandomAccessIter , _RandomAccessIter )
  3123. {
  3124. quitf(_fail, "Don't use random_shuffle(), use shuffle() instead");
  3125. }
  3126. #ifdef __GLIBC__
  3127. # define RAND_THROW_STATEMENT throw()
  3128. #else
  3129. # define RAND_THROW_STATEMENT
  3130. #endif
  3131. #ifdef __GNUC__
  3132. __attribute__ ((error("Don't use rand(), use rnd.next() instead")))
  3133. #endif
  3134. #ifdef _MSC_VER
  3135. # pragma warning( disable : 4273 )
  3136. #endif
  3137. int rand() RAND_THROW_STATEMENT
  3138. {
  3139. quitf(_fail, "Don't use rand(), use rnd.next() instead");
  3140. /* This line never runs. */
  3141. //throw "Don't use rand(), use rnd.next() instead";
  3142. }
  3143. #ifdef __GNUC__
  3144. __attribute__ ((error("Don't use srand(), you should use "
  3145. "'registerGen(argc, argv, 1);' to initialize generator seed "
  3146. "by hash code of the command line params. The third parameter "
  3147. "is randomGeneratorVersion (currently the latest is 1).")))
  3148. #endif
  3149. #ifdef _MSC_VER
  3150. # pragma warning( disable : 4273 )
  3151. #endif
  3152. void srand(unsigned int seed) RAND_THROW_STATEMENT
  3153. {
  3154. quitf(_fail, "Don't use srand(), you should use "
  3155. "'registerGen(argc, argv, 1);' to initialize generator seed "
  3156. "by hash code of the command line params. The third parameter "
  3157. "is randomGeneratorVersion (currently the latest is 1) [ignored seed=%d].", seed);
  3158. }
  3159. void startTest(int test)
  3160. {
  3161. const std::string testFileName = vtos(test);
  3162. if (NULL == freopen(testFileName.c_str(), "wt", stdout))
  3163. __testlib_fail("Unable to write file '" + testFileName + "'");
  3164. }
  3165. inline std::string upperCase(std::string s)
  3166. {
  3167. for (size_t i = 0; i < s.length(); i++)
  3168. if ('a' <= s[i] && s[i] <= 'z')
  3169. s[i] = char(s[i] - 'a' + 'A');
  3170. return s;
  3171. }
  3172. inline std::string lowerCase(std::string s)
  3173. {
  3174. for (size_t i = 0; i < s.length(); i++)
  3175. if ('A' <= s[i] && s[i] <= 'Z')
  3176. s[i] = char(s[i] - 'A' + 'a');
  3177. return s;
  3178. }
  3179. inline std::string compress(const std::string& s)
  3180. {
  3181. return __testlib_part(s);
  3182. }
  3183. inline std::string englishEnding(int x)
  3184. {
  3185. x %= 100;
  3186. if (x / 10 == 1)
  3187. return "th";
  3188. if (x % 10 == 1)
  3189. return "st";
  3190. if (x % 10 == 2)
  3191. return "nd";
  3192. if (x % 10 == 3)
  3193. return "rd";
  3194. return "th";
  3195. }
  3196. inline std::string trim(const std::string& s)
  3197. {
  3198. if (s.empty())
  3199. return s;
  3200. int left = 0;
  3201. while (left < int(s.length()) && isBlanks(s[left]))
  3202. left++;
  3203. if (left >= int(s.length()))
  3204. return "";
  3205. int right = int(s.length()) - 1;
  3206. while (right >= 0 && isBlanks(s[right]))
  3207. right--;
  3208. if (right < 0)
  3209. return "";
  3210. return s.substr(left, right - left + 1);
  3211. }
  3212. template <typename _ForwardIterator, typename _Separator>
  3213. std::string join(_ForwardIterator first, _ForwardIterator last, _Separator separator)
  3214. {
  3215. std::stringstream ss;
  3216. bool repeated = false;
  3217. for (_ForwardIterator i = first; i != last; i++)
  3218. {
  3219. if (repeated)
  3220. ss << separator;
  3221. else
  3222. repeated = true;
  3223. ss << *i;
  3224. }
  3225. return ss.str();
  3226. }
  3227. template <typename _ForwardIterator>
  3228. std::string join(_ForwardIterator first, _ForwardIterator last)
  3229. {
  3230. return join(first, last, ' ');
  3231. }
  3232. template <typename _Collection, typename _Separator>
  3233. std::string join(const _Collection& collection, _Separator separator)
  3234. {
  3235. return join(collection.begin(), collection.end(), separator);
  3236. }
  3237. template <typename _Collection>
  3238. std::string join(const _Collection& collection)
  3239. {
  3240. return join(collection, ' ');
  3241. }
  3242. /**
  3243. * Splits string s by character separator returning exactly k+1 items,
  3244. * where k is the number of separator occurences.
  3245. */
  3246. std::vector<std::string> split(const std::string& s, char separator)
  3247. {
  3248. std::vector<std::string> result;
  3249. std::string item;
  3250. for (size_t i = 0; i < s.length(); i++)
  3251. if (s[i] == separator)
  3252. {
  3253. result.push_back(item);
  3254. item = "";
  3255. }
  3256. else
  3257. item += s[i];
  3258. result.push_back(item);
  3259. return result;
  3260. }
  3261. /**
  3262. * Splits string s by character separators returning exactly k+1 items,
  3263. * where k is the number of separator occurences.
  3264. */
  3265. std::vector<std::string> split(const std::string& s, const std::string& separators)
  3266. {
  3267. if (separators.empty())
  3268. return std::vector<std::string>(1, s);
  3269. std::vector<bool> isSeparator(256);
  3270. for (size_t i = 0; i < separators.size(); i++)
  3271. isSeparator[(unsigned char)(separators[i])] = true;
  3272. std::vector<std::string> result;
  3273. std::string item;
  3274. for (size_t i = 0; i < s.length(); i++)
  3275. if (isSeparator[(unsigned char)(s[i])])
  3276. {
  3277. result.push_back(item);
  3278. item = "";
  3279. }
  3280. else
  3281. item += s[i];
  3282. result.push_back(item);
  3283. return result;
  3284. }
  3285. /**
  3286. * Splits string s by character separator returning non-empty items.
  3287. */
  3288. std::vector<std::string> tokenize(const std::string& s, char separator)
  3289. {
  3290. std::vector<std::string> result;
  3291. std::string item;
  3292. for (size_t i = 0; i < s.length(); i++)
  3293. if (s[i] == separator)
  3294. {
  3295. if (!item.empty())
  3296. result.push_back(item);
  3297. item = "";
  3298. }
  3299. else
  3300. item += s[i];
  3301. if (!item.empty())
  3302. result.push_back(item);
  3303. return result;
  3304. }
  3305. /**
  3306. * Splits string s by character separators returning non-empty items.
  3307. */
  3308. std::vector<std::string> tokenize(const std::string& s, const std::string& separators)
  3309. {
  3310. if (separators.empty())
  3311. return std::vector<std::string>(1, s);
  3312. std::vector<bool> isSeparator(256);
  3313. for (size_t i = 0; i < separators.size(); i++)
  3314. isSeparator[(unsigned char)(separators[i])] = true;
  3315. std::vector<std::string> result;
  3316. std::string item;
  3317. for (size_t i = 0; i < s.length(); i++)
  3318. if (isSeparator[(unsigned char)(s[i])])
  3319. {
  3320. if (!item.empty())
  3321. result.push_back(item);
  3322. item = "";
  3323. }
  3324. else
  3325. item += s[i];
  3326. if (!item.empty())
  3327. result.push_back(item);
  3328. return result;
  3329. }
  3330. NORETURN void __testlib_expectedButFound(TResult result, std::string expected, std::string found, const char* prepend)
  3331. {
  3332. std::string message;
  3333. if (strlen(prepend) != 0)
  3334. message = format("%s: expected '%s', but found '%s'",
  3335. compress(prepend).c_str(), compress(expected).c_str(), compress(found).c_str());
  3336. else
  3337. message = format("expected '%s', but found '%s'",
  3338. compress(expected).c_str(), compress(found).c_str());
  3339. quit(result, message);
  3340. }
  3341. NORETURN void __testlib_expectedButFound(TResult result, double expected, double found, const char* prepend)
  3342. {
  3343. std::string expectedString = removeDoubleTrailingZeroes(format("%.12f", expected));
  3344. std::string foundString = removeDoubleTrailingZeroes(format("%.12f", found));
  3345. __testlib_expectedButFound(result, expectedString, foundString, prepend);
  3346. }
  3347. template <typename T>
  3348. #ifdef __GNUC__
  3349. __attribute__ ((format (printf, 4, 5)))
  3350. #endif
  3351. NORETURN void expectedButFound(TResult result, T expected, T found, const char* prependFormat = "", ...)
  3352. {
  3353. FMT_TO_RESULT(prependFormat, prependFormat, prepend);
  3354. std::string expectedString = vtos(expected);
  3355. std::string foundString = vtos(found);
  3356. __testlib_expectedButFound(result, expectedString, foundString, prepend.c_str());
  3357. }
  3358. template <>
  3359. #ifdef __GNUC__
  3360. __attribute__ ((format (printf, 4, 5)))
  3361. #endif
  3362. NORETURN void expectedButFound<std::string>(TResult result, std::string expected, std::string found, const char* prependFormat, ...)
  3363. {
  3364. FMT_TO_RESULT(prependFormat, prependFormat, prepend);
  3365. __testlib_expectedButFound(result, expected, found, prepend.c_str());
  3366. }
  3367. template <>
  3368. #ifdef __GNUC__
  3369. __attribute__ ((format (printf, 4, 5)))
  3370. #endif
  3371. NORETURN void expectedButFound<double>(TResult result, double expected, double found, const char* prependFormat, ...)
  3372. {
  3373. FMT_TO_RESULT(prependFormat, prependFormat, prepend);
  3374. std::string expectedString = removeDoubleTrailingZeroes(format("%.12f", expected));
  3375. std::string foundString = removeDoubleTrailingZeroes(format("%.12f", found));
  3376. __testlib_expectedButFound(result, expectedString, foundString, prepend.c_str());
  3377. }
  3378. template <>
  3379. #ifdef __GNUC__
  3380. __attribute__ ((format (printf, 4, 5)))
  3381. #endif
  3382. NORETURN void expectedButFound<const char*>(TResult result, const char* expected, const char* found, const char* prependFormat, ...)
  3383. {
  3384. FMT_TO_RESULT(prependFormat, prependFormat, prepend);
  3385. __testlib_expectedButFound(result, std::string(expected), std::string(found), prepend.c_str());
  3386. }
  3387. template <>
  3388. #ifdef __GNUC__
  3389. __attribute__ ((format (printf, 4, 5)))
  3390. #endif
  3391. NORETURN void expectedButFound<float>(TResult result, float expected, float found, const char* prependFormat, ...)
  3392. {
  3393. FMT_TO_RESULT(prependFormat, prependFormat, prepend);
  3394. __testlib_expectedButFound(result, double(expected), double(found), prepend.c_str());
  3395. }
  3396. template <>
  3397. #ifdef __GNUC__
  3398. __attribute__ ((format (printf, 4, 5)))
  3399. #endif
  3400. NORETURN void expectedButFound<long double>(TResult result, long double expected, long double found, const char* prependFormat, ...)
  3401. {
  3402. FMT_TO_RESULT(prependFormat, prependFormat, prepend);
  3403. __testlib_expectedButFound(result, double(expected), double(found), prepend.c_str());
  3404. }
  3405. #endif