testlib.h 99 KB

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