testlib.h 107 KB

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