testlib.h 86 KB

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