1
0

testlib.h 86 KB

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