1
0

testlib.h 82 KB

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