testlib.h 90 KB

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