format-test.cc 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495
  1. // Formatting library for C++ - formatting library tests
  2. //
  3. // Copyright (c) 2012 - present, Victor Zverovich
  4. // All rights reserved.
  5. //
  6. // For the license information refer to format.h.
  7. #include <stdint.h>
  8. #include <cctype>
  9. #include <cfloat>
  10. #include <climits>
  11. #include <cmath>
  12. #include <cstring>
  13. #include <list>
  14. #include <memory>
  15. #include <string>
  16. // Check if fmt/format.h compiles with windows.h included before it.
  17. #ifdef _WIN32
  18. # include <windows.h>
  19. #endif
  20. // Check if fmt/format.h compiles with the X11 index macro defined.
  21. #define index(x, y) no nice things
  22. #include "fmt/format.h"
  23. #undef index
  24. #include <gmock/gmock.h>
  25. #include "gtest-extra.h"
  26. #include "mock-allocator.h"
  27. #include "util.h"
  28. #undef ERROR
  29. using fmt::basic_memory_buffer;
  30. using fmt::format;
  31. using fmt::format_error;
  32. using fmt::memory_buffer;
  33. using fmt::string_view;
  34. using fmt::wmemory_buffer;
  35. using fmt::wstring_view;
  36. using fmt::detail::max_value;
  37. using testing::Return;
  38. using testing::StrictMock;
  39. namespace {
  40. #if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 408
  41. template <typename Char, typename T> bool check_enabled_formatter() {
  42. static_assert(std::is_default_constructible<fmt::formatter<T, Char>>::value,
  43. "");
  44. return true;
  45. }
  46. template <typename Char, typename... T> void check_enabled_formatters() {
  47. auto dummy = {check_enabled_formatter<Char, T>()...};
  48. (void)dummy;
  49. }
  50. TEST(FormatterTest, TestFormattersEnabled) {
  51. check_enabled_formatters<char, bool, char, signed char, unsigned char, short,
  52. unsigned short, int, unsigned, long, unsigned long,
  53. long long, unsigned long long, float, double,
  54. long double, void*, const void*, char*, const char*,
  55. std::string, std::nullptr_t>();
  56. check_enabled_formatters<wchar_t, bool, wchar_t, signed char, unsigned char,
  57. short, unsigned short, int, unsigned, long,
  58. unsigned long, long long, unsigned long long, float,
  59. double, long double, void*, const void*, wchar_t*,
  60. const wchar_t*, std::wstring, std::nullptr_t>();
  61. }
  62. #endif
  63. // Format value using the standard library.
  64. template <typename Char, typename T>
  65. void std_format(const T& value, std::basic_string<Char>& result) {
  66. std::basic_ostringstream<Char> os;
  67. os << value;
  68. result = os.str();
  69. }
  70. #ifdef __MINGW32__
  71. // Workaround a bug in formatting long double in MinGW.
  72. void std_format(long double value, std::string& result) {
  73. char buffer[100];
  74. safe_sprintf(buffer, "%Lg", value);
  75. result = buffer;
  76. }
  77. void std_format(long double value, std::wstring& result) {
  78. wchar_t buffer[100];
  79. swprintf(buffer, L"%Lg", value);
  80. result = buffer;
  81. }
  82. #endif
  83. } // namespace
  84. struct uint32_pair {
  85. uint32_t u[2];
  86. };
  87. TEST(UtilTest, BitCast) {
  88. auto s = fmt::detail::bit_cast<uint32_pair>(uint64_t{42});
  89. EXPECT_EQ(fmt::detail::bit_cast<uint64_t>(s), 42ull);
  90. s = fmt::detail::bit_cast<uint32_pair>(uint64_t(~0ull));
  91. EXPECT_EQ(fmt::detail::bit_cast<uint64_t>(s), ~0ull);
  92. }
  93. TEST(UtilTest, Increment) {
  94. char s[10] = "123";
  95. increment(s);
  96. EXPECT_STREQ("124", s);
  97. s[2] = '8';
  98. increment(s);
  99. EXPECT_STREQ("129", s);
  100. increment(s);
  101. EXPECT_STREQ("130", s);
  102. s[1] = s[2] = '9';
  103. increment(s);
  104. EXPECT_STREQ("200", s);
  105. }
  106. TEST(UtilTest, ParseNonnegativeInt) {
  107. if (max_value<int>() != static_cast<int>(static_cast<unsigned>(1) << 31)) {
  108. fmt::print("Skipping parse_nonnegative_int test\n");
  109. return;
  110. }
  111. fmt::string_view s = "10000000000";
  112. auto begin = s.begin(), end = s.end();
  113. EXPECT_THROW_MSG(
  114. parse_nonnegative_int(begin, end, fmt::detail::error_handler()),
  115. fmt::format_error, "number is too big");
  116. s = "2147483649";
  117. begin = s.begin();
  118. end = s.end();
  119. EXPECT_THROW_MSG(
  120. parse_nonnegative_int(begin, end, fmt::detail::error_handler()),
  121. fmt::format_error, "number is too big");
  122. }
  123. TEST(IteratorTest, CountingIterator) {
  124. fmt::detail::counting_iterator it;
  125. auto prev = it++;
  126. EXPECT_EQ(prev.count(), 0);
  127. EXPECT_EQ(it.count(), 1);
  128. EXPECT_EQ((it + 41).count(), 42);
  129. }
  130. TEST(IteratorTest, TruncatingIterator) {
  131. char* p = nullptr;
  132. fmt::detail::truncating_iterator<char*> it(p, 3);
  133. auto prev = it++;
  134. EXPECT_EQ(prev.base(), p);
  135. EXPECT_EQ(it.base(), p + 1);
  136. }
  137. TEST(IteratorTest, TruncatingBackInserter) {
  138. std::string buffer;
  139. auto bi = std::back_inserter(buffer);
  140. fmt::detail::truncating_iterator<decltype(bi)> it(bi, 2);
  141. *it++ = '4';
  142. *it++ = '2';
  143. *it++ = '1';
  144. EXPECT_EQ(buffer.size(), 2);
  145. EXPECT_EQ(buffer, "42");
  146. }
  147. TEST(IteratorTest, IsOutputIterator) {
  148. EXPECT_TRUE((fmt::detail::is_output_iterator<char*, char>::value));
  149. EXPECT_FALSE((fmt::detail::is_output_iterator<const char*, char>::value));
  150. EXPECT_FALSE((fmt::detail::is_output_iterator<std::string, char>::value));
  151. EXPECT_TRUE(
  152. (fmt::detail::is_output_iterator<std::back_insert_iterator<std::string>,
  153. char>::value));
  154. EXPECT_TRUE(
  155. (fmt::detail::is_output_iterator<std::string::iterator, char>::value));
  156. EXPECT_FALSE((fmt::detail::is_output_iterator<std::string::const_iterator,
  157. char>::value));
  158. EXPECT_FALSE((fmt::detail::is_output_iterator<std::list<char>, char>::value));
  159. EXPECT_TRUE((
  160. fmt::detail::is_output_iterator<std::list<char>::iterator, char>::value));
  161. EXPECT_FALSE((fmt::detail::is_output_iterator<std::list<char>::const_iterator,
  162. char>::value));
  163. EXPECT_FALSE((fmt::detail::is_output_iterator<uint32_pair, char>::value));
  164. }
  165. TEST(MemoryBufferTest, Ctor) {
  166. basic_memory_buffer<char, 123> buffer;
  167. EXPECT_EQ(static_cast<size_t>(0), buffer.size());
  168. EXPECT_EQ(123u, buffer.capacity());
  169. }
  170. static void check_forwarding(mock_allocator<int>& alloc,
  171. allocator_ref<mock_allocator<int>>& ref) {
  172. int mem;
  173. // Check if value_type is properly defined.
  174. allocator_ref<mock_allocator<int>>::value_type* ptr = &mem;
  175. // Check forwarding.
  176. EXPECT_CALL(alloc, allocate(42)).WillOnce(testing::Return(ptr));
  177. ref.allocate(42);
  178. EXPECT_CALL(alloc, deallocate(ptr, 42));
  179. ref.deallocate(ptr, 42);
  180. }
  181. TEST(AllocatorTest, allocator_ref) {
  182. StrictMock<mock_allocator<int>> alloc;
  183. typedef allocator_ref<mock_allocator<int>> test_allocator_ref;
  184. test_allocator_ref ref(&alloc);
  185. // Check if allocator_ref forwards to the underlying allocator.
  186. check_forwarding(alloc, ref);
  187. test_allocator_ref ref2(ref);
  188. check_forwarding(alloc, ref2);
  189. test_allocator_ref ref3;
  190. EXPECT_EQ(nullptr, ref3.get());
  191. ref3 = ref;
  192. check_forwarding(alloc, ref3);
  193. }
  194. typedef allocator_ref<std::allocator<char>> TestAllocator;
  195. static void check_move_buffer(
  196. const char* str, basic_memory_buffer<char, 5, TestAllocator>& buffer) {
  197. std::allocator<char>* alloc = buffer.get_allocator().get();
  198. basic_memory_buffer<char, 5, TestAllocator> buffer2(std::move(buffer));
  199. // Move shouldn't destroy the inline content of the first buffer.
  200. EXPECT_EQ(str, std::string(&buffer[0], buffer.size()));
  201. EXPECT_EQ(str, std::string(&buffer2[0], buffer2.size()));
  202. EXPECT_EQ(5u, buffer2.capacity());
  203. // Move should transfer allocator.
  204. EXPECT_EQ(nullptr, buffer.get_allocator().get());
  205. EXPECT_EQ(alloc, buffer2.get_allocator().get());
  206. }
  207. TEST(MemoryBufferTest, MoveCtorInlineBuffer) {
  208. std::allocator<char> alloc;
  209. basic_memory_buffer<char, 5, TestAllocator> buffer((TestAllocator(&alloc)));
  210. const char test[] = "test";
  211. buffer.append(string_view(test, 4));
  212. check_move_buffer("test", buffer);
  213. // Adding one more character fills the inline buffer, but doesn't cause
  214. // dynamic allocation.
  215. buffer.push_back('a');
  216. check_move_buffer("testa", buffer);
  217. }
  218. TEST(MemoryBufferTest, MoveCtorDynamicBuffer) {
  219. std::allocator<char> alloc;
  220. basic_memory_buffer<char, 4, TestAllocator> buffer((TestAllocator(&alloc)));
  221. const char test[] = "test";
  222. buffer.append(test, test + 4);
  223. const char* inline_buffer_ptr = &buffer[0];
  224. // Adding one more character causes the content to move from the inline to
  225. // a dynamically allocated buffer.
  226. buffer.push_back('a');
  227. basic_memory_buffer<char, 4, TestAllocator> buffer2(std::move(buffer));
  228. // Move should rip the guts of the first buffer.
  229. EXPECT_EQ(inline_buffer_ptr, &buffer[0]);
  230. EXPECT_EQ("testa", std::string(&buffer2[0], buffer2.size()));
  231. EXPECT_GT(buffer2.capacity(), 4u);
  232. }
  233. static void check_move_assign_buffer(const char* str,
  234. basic_memory_buffer<char, 5>& buffer) {
  235. basic_memory_buffer<char, 5> buffer2;
  236. buffer2 = std::move(buffer);
  237. // Move shouldn't destroy the inline content of the first buffer.
  238. EXPECT_EQ(str, std::string(&buffer[0], buffer.size()));
  239. EXPECT_EQ(str, std::string(&buffer2[0], buffer2.size()));
  240. EXPECT_EQ(5u, buffer2.capacity());
  241. }
  242. TEST(MemoryBufferTest, MoveAssignment) {
  243. basic_memory_buffer<char, 5> buffer;
  244. const char test[] = "test";
  245. buffer.append(test, test + 4);
  246. check_move_assign_buffer("test", buffer);
  247. // Adding one more character fills the inline buffer, but doesn't cause
  248. // dynamic allocation.
  249. buffer.push_back('a');
  250. check_move_assign_buffer("testa", buffer);
  251. const char* inline_buffer_ptr = &buffer[0];
  252. // Adding one more character causes the content to move from the inline to
  253. // a dynamically allocated buffer.
  254. buffer.push_back('b');
  255. basic_memory_buffer<char, 5> buffer2;
  256. buffer2 = std::move(buffer);
  257. // Move should rip the guts of the first buffer.
  258. EXPECT_EQ(inline_buffer_ptr, &buffer[0]);
  259. EXPECT_EQ("testab", std::string(&buffer2[0], buffer2.size()));
  260. EXPECT_GT(buffer2.capacity(), 5u);
  261. }
  262. TEST(MemoryBufferTest, Grow) {
  263. typedef allocator_ref<mock_allocator<int>> Allocator;
  264. mock_allocator<int> alloc;
  265. basic_memory_buffer<int, 10, Allocator> buffer((Allocator(&alloc)));
  266. buffer.resize(7);
  267. using fmt::detail::to_unsigned;
  268. for (int i = 0; i < 7; ++i) buffer[to_unsigned(i)] = i * i;
  269. EXPECT_EQ(10u, buffer.capacity());
  270. int mem[20];
  271. mem[7] = 0xdead;
  272. EXPECT_CALL(alloc, allocate(20)).WillOnce(Return(mem));
  273. buffer.try_reserve(20);
  274. EXPECT_EQ(20u, buffer.capacity());
  275. // Check if size elements have been copied
  276. for (int i = 0; i < 7; ++i) EXPECT_EQ(i * i, buffer[to_unsigned(i)]);
  277. // and no more than that.
  278. EXPECT_EQ(0xdead, buffer[7]);
  279. EXPECT_CALL(alloc, deallocate(mem, 20));
  280. }
  281. TEST(MemoryBufferTest, Allocator) {
  282. typedef allocator_ref<mock_allocator<char>> TestAllocator;
  283. basic_memory_buffer<char, 10, TestAllocator> buffer;
  284. EXPECT_EQ(nullptr, buffer.get_allocator().get());
  285. StrictMock<mock_allocator<char>> alloc;
  286. char mem;
  287. {
  288. basic_memory_buffer<char, 10, TestAllocator> buffer2(
  289. (TestAllocator(&alloc)));
  290. EXPECT_EQ(&alloc, buffer2.get_allocator().get());
  291. size_t size = 2 * fmt::inline_buffer_size;
  292. EXPECT_CALL(alloc, allocate(size)).WillOnce(Return(&mem));
  293. buffer2.reserve(size);
  294. EXPECT_CALL(alloc, deallocate(&mem, size));
  295. }
  296. }
  297. TEST(MemoryBufferTest, ExceptionInDeallocate) {
  298. typedef allocator_ref<mock_allocator<char>> TestAllocator;
  299. StrictMock<mock_allocator<char>> alloc;
  300. basic_memory_buffer<char, 10, TestAllocator> buffer((TestAllocator(&alloc)));
  301. size_t size = 2 * fmt::inline_buffer_size;
  302. std::vector<char> mem(size);
  303. {
  304. EXPECT_CALL(alloc, allocate(size)).WillOnce(Return(&mem[0]));
  305. buffer.resize(size);
  306. std::fill(&buffer[0], &buffer[0] + size, 'x');
  307. }
  308. std::vector<char> mem2(2 * size);
  309. {
  310. EXPECT_CALL(alloc, allocate(2 * size)).WillOnce(Return(&mem2[0]));
  311. std::exception e;
  312. EXPECT_CALL(alloc, deallocate(&mem[0], size)).WillOnce(testing::Throw(e));
  313. EXPECT_THROW(buffer.reserve(2 * size), std::exception);
  314. EXPECT_EQ(&mem2[0], &buffer[0]);
  315. // Check that the data has been copied.
  316. for (size_t i = 0; i < size; ++i) EXPECT_EQ('x', buffer[i]);
  317. }
  318. EXPECT_CALL(alloc, deallocate(&mem2[0], 2 * size));
  319. }
  320. TEST(UtilTest, UTF8ToUTF16) {
  321. fmt::detail::utf8_to_utf16 u("лошадка");
  322. EXPECT_EQ(L"\x043B\x043E\x0448\x0430\x0434\x043A\x0430", u.str());
  323. EXPECT_EQ(7, u.size());
  324. // U+10437 { DESERET SMALL LETTER YEE }
  325. EXPECT_EQ(L"\xD801\xDC37", fmt::detail::utf8_to_utf16("𐐷").str());
  326. EXPECT_THROW_MSG(fmt::detail::utf8_to_utf16("\xc3\x28"), std::runtime_error,
  327. "invalid utf8");
  328. EXPECT_THROW_MSG(fmt::detail::utf8_to_utf16(fmt::string_view("л", 1)),
  329. std::runtime_error, "invalid utf8");
  330. EXPECT_EQ(L"123456", fmt::detail::utf8_to_utf16("123456").str());
  331. }
  332. TEST(UtilTest, UTF8ToUTF16EmptyString) {
  333. std::string s = "";
  334. fmt::detail::utf8_to_utf16 u(s.c_str());
  335. EXPECT_EQ(L"", u.str());
  336. EXPECT_EQ(s.size(), u.size());
  337. }
  338. TEST(UtilTest, FormatSystemError) {
  339. fmt::memory_buffer message;
  340. fmt::format_system_error(message, EDOM, "test");
  341. EXPECT_EQ(fmt::format("test: {}", get_system_error(EDOM)),
  342. to_string(message));
  343. message = fmt::memory_buffer();
  344. // Check if std::allocator throws on allocating max size_t / 2 chars.
  345. size_t max_size = max_value<size_t>() / 2;
  346. bool throws_on_alloc = false;
  347. try {
  348. std::allocator<char> alloc;
  349. alloc.deallocate(alloc.allocate(max_size), max_size);
  350. } catch (const std::bad_alloc&) {
  351. throws_on_alloc = true;
  352. }
  353. if (!throws_on_alloc) {
  354. fmt::print("warning: std::allocator allocates {} chars", max_size);
  355. return;
  356. }
  357. fmt::format_system_error(message, EDOM, fmt::string_view(nullptr, max_size));
  358. EXPECT_EQ(fmt::format("error {}", EDOM), to_string(message));
  359. }
  360. TEST(UtilTest, SystemError) {
  361. fmt::system_error e(EDOM, "test");
  362. EXPECT_EQ(fmt::format("test: {}", get_system_error(EDOM)), e.what());
  363. EXPECT_EQ(EDOM, e.error_code());
  364. fmt::system_error error(0, "");
  365. try {
  366. throw fmt::system_error(EDOM, "test {}", "error");
  367. } catch (const fmt::system_error& e) {
  368. error = e;
  369. }
  370. fmt::memory_buffer message;
  371. fmt::format_system_error(message, EDOM, "test error");
  372. EXPECT_EQ(to_string(message), error.what());
  373. EXPECT_EQ(EDOM, error.error_code());
  374. }
  375. TEST(UtilTest, ReportSystemError) {
  376. fmt::memory_buffer out;
  377. fmt::format_system_error(out, EDOM, "test error");
  378. out.push_back('\n');
  379. EXPECT_WRITE(stderr, fmt::report_system_error(EDOM, "test error"),
  380. to_string(out));
  381. }
  382. TEST(StringViewTest, Ctor) {
  383. EXPECT_STREQ("abc", string_view("abc").data());
  384. EXPECT_EQ(3u, string_view("abc").size());
  385. EXPECT_STREQ("defg", string_view(std::string("defg")).data());
  386. EXPECT_EQ(4u, string_view(std::string("defg")).size());
  387. }
  388. TEST(FormatToTest, FormatWithoutArgs) {
  389. std::string s;
  390. fmt::format_to(std::back_inserter(s), "test");
  391. EXPECT_EQ("test", s);
  392. }
  393. TEST(FormatToTest, Format) {
  394. std::string s;
  395. fmt::format_to(std::back_inserter(s), "part{0}", 1);
  396. EXPECT_EQ("part1", s);
  397. fmt::format_to(std::back_inserter(s), "part{0}", 2);
  398. EXPECT_EQ("part1part2", s);
  399. }
  400. TEST(FormatToTest, WideString) {
  401. std::vector<wchar_t> buf;
  402. fmt::format_to(std::back_inserter(buf), L"{}{}", 42, L'\0');
  403. EXPECT_STREQ(buf.data(), L"42");
  404. }
  405. TEST(FormatToTest, FormatToMemoryBuffer) {
  406. fmt::basic_memory_buffer<char, 100> buffer;
  407. fmt::format_to(buffer, "{}", "foo");
  408. EXPECT_EQ("foo", to_string(buffer));
  409. fmt::wmemory_buffer wbuffer;
  410. fmt::format_to(wbuffer, L"{}", L"foo");
  411. EXPECT_EQ(L"foo", to_string(wbuffer));
  412. }
  413. TEST(FormatterTest, Escape) {
  414. EXPECT_EQ("{", format("{{"));
  415. EXPECT_EQ("before {", format("before {{"));
  416. EXPECT_EQ("{ after", format("{{ after"));
  417. EXPECT_EQ("before { after", format("before {{ after"));
  418. EXPECT_EQ("}", format("}}"));
  419. EXPECT_EQ("before }", format("before }}"));
  420. EXPECT_EQ("} after", format("}} after"));
  421. EXPECT_EQ("before } after", format("before }} after"));
  422. EXPECT_EQ("{}", format("{{}}"));
  423. EXPECT_EQ("{42}", format("{{{0}}}", 42));
  424. }
  425. TEST(FormatterTest, UnmatchedBraces) {
  426. EXPECT_THROW_MSG(format("{"), format_error, "invalid format string");
  427. EXPECT_THROW_MSG(format("}"), format_error, "unmatched '}' in format string");
  428. EXPECT_THROW_MSG(format("{0{}"), format_error, "invalid format string");
  429. }
  430. TEST(FormatterTest, NoArgs) { EXPECT_EQ("test", format("test")); }
  431. TEST(FormatterTest, ArgsInDifferentPositions) {
  432. EXPECT_EQ("42", format("{0}", 42));
  433. EXPECT_EQ("before 42", format("before {0}", 42));
  434. EXPECT_EQ("42 after", format("{0} after", 42));
  435. EXPECT_EQ("before 42 after", format("before {0} after", 42));
  436. EXPECT_EQ("answer = 42", format("{0} = {1}", "answer", 42));
  437. EXPECT_EQ("42 is the answer", format("{1} is the {0}", "answer", 42));
  438. EXPECT_EQ("abracadabra", format("{0}{1}{0}", "abra", "cad"));
  439. }
  440. TEST(FormatterTest, ArgErrors) {
  441. EXPECT_THROW_MSG(format("{"), format_error, "invalid format string");
  442. EXPECT_THROW_MSG(format("{?}"), format_error, "invalid format string");
  443. EXPECT_THROW_MSG(format("{0"), format_error, "invalid format string");
  444. EXPECT_THROW_MSG(format("{0}"), format_error, "argument not found");
  445. EXPECT_THROW_MSG(format("{00}", 42), format_error, "invalid format string");
  446. char format_str[BUFFER_SIZE];
  447. safe_sprintf(format_str, "{%u", INT_MAX);
  448. EXPECT_THROW_MSG(format(format_str), format_error, "invalid format string");
  449. safe_sprintf(format_str, "{%u}", INT_MAX);
  450. EXPECT_THROW_MSG(format(format_str), format_error, "argument not found");
  451. safe_sprintf(format_str, "{%u", INT_MAX + 1u);
  452. EXPECT_THROW_MSG(format(format_str), format_error, "number is too big");
  453. safe_sprintf(format_str, "{%u}", INT_MAX + 1u);
  454. EXPECT_THROW_MSG(format(format_str), format_error, "number is too big");
  455. }
  456. template <int N> struct TestFormat {
  457. template <typename... Args>
  458. static std::string format(fmt::string_view format_str, const Args&... args) {
  459. return TestFormat<N - 1>::format(format_str, N - 1, args...);
  460. }
  461. };
  462. template <> struct TestFormat<0> {
  463. template <typename... Args>
  464. static std::string format(fmt::string_view format_str, const Args&... args) {
  465. return fmt::format(format_str, args...);
  466. }
  467. };
  468. TEST(FormatterTest, ManyArgs) {
  469. EXPECT_EQ("19", TestFormat<20>::format("{19}"));
  470. EXPECT_THROW_MSG(TestFormat<20>::format("{20}"), format_error,
  471. "argument not found");
  472. EXPECT_THROW_MSG(TestFormat<21>::format("{21}"), format_error,
  473. "argument not found");
  474. enum { max_packed_args = fmt::detail::max_packed_args };
  475. std::string format_str = fmt::format("{{{}}}", max_packed_args + 1);
  476. EXPECT_THROW_MSG(TestFormat<max_packed_args>::format(format_str),
  477. format_error, "argument not found");
  478. }
  479. TEST(FormatterTest, NamedArg) {
  480. EXPECT_EQ("1/a/A", format("{_1}/{a_}/{A_}", fmt::arg("a_", 'a'),
  481. fmt::arg("A_", "A"), fmt::arg("_1", 1)));
  482. EXPECT_EQ(" -42", format("{0:{width}}", -42, fmt::arg("width", 4)));
  483. EXPECT_EQ("st", format("{0:.{precision}}", "str", fmt::arg("precision", 2)));
  484. EXPECT_EQ("1 2", format("{} {two}", 1, fmt::arg("two", 2)));
  485. EXPECT_EQ("42", format("{c}", fmt::arg("a", 0), fmt::arg("b", 0),
  486. fmt::arg("c", 42), fmt::arg("d", 0), fmt::arg("e", 0),
  487. fmt::arg("f", 0), fmt::arg("g", 0), fmt::arg("h", 0),
  488. fmt::arg("i", 0), fmt::arg("j", 0), fmt::arg("k", 0),
  489. fmt::arg("l", 0), fmt::arg("m", 0), fmt::arg("n", 0),
  490. fmt::arg("o", 0), fmt::arg("p", 0)));
  491. EXPECT_THROW_MSG(format("{a}"), format_error, "argument not found");
  492. EXPECT_THROW_MSG(format("{a}", 42), format_error, "argument not found");
  493. }
  494. TEST(FormatterTest, AutoArgIndex) {
  495. EXPECT_EQ("abc", format("{}{}{}", 'a', 'b', 'c'));
  496. EXPECT_THROW_MSG(format("{0}{}", 'a', 'b'), format_error,
  497. "cannot switch from manual to automatic argument indexing");
  498. EXPECT_THROW_MSG(format("{}{0}", 'a', 'b'), format_error,
  499. "cannot switch from automatic to manual argument indexing");
  500. EXPECT_EQ("1.2", format("{:.{}}", 1.2345, 2));
  501. EXPECT_THROW_MSG(format("{0}:.{}", 1.2345, 2), format_error,
  502. "cannot switch from manual to automatic argument indexing");
  503. EXPECT_THROW_MSG(format("{:.{0}}", 1.2345, 2), format_error,
  504. "cannot switch from automatic to manual argument indexing");
  505. EXPECT_THROW_MSG(format("{}"), format_error, "argument not found");
  506. }
  507. TEST(FormatterTest, EmptySpecs) { EXPECT_EQ("42", format("{0:}", 42)); }
  508. TEST(FormatterTest, LeftAlign) {
  509. EXPECT_EQ("42 ", format("{0:<4}", 42));
  510. EXPECT_EQ("42 ", format("{0:<4o}", 042));
  511. EXPECT_EQ("42 ", format("{0:<4x}", 0x42));
  512. EXPECT_EQ("-42 ", format("{0:<5}", -42));
  513. EXPECT_EQ("42 ", format("{0:<5}", 42u));
  514. EXPECT_EQ("-42 ", format("{0:<5}", -42l));
  515. EXPECT_EQ("42 ", format("{0:<5}", 42ul));
  516. EXPECT_EQ("-42 ", format("{0:<5}", -42ll));
  517. EXPECT_EQ("42 ", format("{0:<5}", 42ull));
  518. EXPECT_EQ("-42 ", format("{0:<5}", -42.0));
  519. EXPECT_EQ("-42 ", format("{0:<5}", -42.0l));
  520. EXPECT_EQ("c ", format("{0:<5}", 'c'));
  521. EXPECT_EQ("abc ", format("{0:<5}", "abc"));
  522. EXPECT_EQ("0xface ", format("{0:<8}", reinterpret_cast<void*>(0xface)));
  523. }
  524. TEST(FormatterTest, RightAlign) {
  525. EXPECT_EQ(" 42", format("{0:>4}", 42));
  526. EXPECT_EQ(" 42", format("{0:>4o}", 042));
  527. EXPECT_EQ(" 42", format("{0:>4x}", 0x42));
  528. EXPECT_EQ(" -42", format("{0:>5}", -42));
  529. EXPECT_EQ(" 42", format("{0:>5}", 42u));
  530. EXPECT_EQ(" -42", format("{0:>5}", -42l));
  531. EXPECT_EQ(" 42", format("{0:>5}", 42ul));
  532. EXPECT_EQ(" -42", format("{0:>5}", -42ll));
  533. EXPECT_EQ(" 42", format("{0:>5}", 42ull));
  534. EXPECT_EQ(" -42", format("{0:>5}", -42.0));
  535. EXPECT_EQ(" -42", format("{0:>5}", -42.0l));
  536. EXPECT_EQ(" c", format("{0:>5}", 'c'));
  537. EXPECT_EQ(" abc", format("{0:>5}", "abc"));
  538. EXPECT_EQ(" 0xface", format("{0:>8}", reinterpret_cast<void*>(0xface)));
  539. }
  540. #if FMT_DEPRECATED_NUMERIC_ALIGN
  541. TEST(FormatterTest, NumericAlign) { EXPECT_EQ("0042", format("{0:=4}", 42)); }
  542. #endif
  543. TEST(FormatterTest, CenterAlign) {
  544. EXPECT_EQ(" 42 ", format("{0:^5}", 42));
  545. EXPECT_EQ(" 42 ", format("{0:^5o}", 042));
  546. EXPECT_EQ(" 42 ", format("{0:^5x}", 0x42));
  547. EXPECT_EQ(" -42 ", format("{0:^5}", -42));
  548. EXPECT_EQ(" 42 ", format("{0:^5}", 42u));
  549. EXPECT_EQ(" -42 ", format("{0:^5}", -42l));
  550. EXPECT_EQ(" 42 ", format("{0:^5}", 42ul));
  551. EXPECT_EQ(" -42 ", format("{0:^5}", -42ll));
  552. EXPECT_EQ(" 42 ", format("{0:^5}", 42ull));
  553. EXPECT_EQ(" -42 ", format("{0:^5}", -42.0));
  554. EXPECT_EQ(" -42 ", format("{0:^5}", -42.0l));
  555. EXPECT_EQ(" c ", format("{0:^5}", 'c'));
  556. EXPECT_EQ(" abc ", format("{0:^6}", "abc"));
  557. EXPECT_EQ(" 0xface ", format("{0:^8}", reinterpret_cast<void*>(0xface)));
  558. }
  559. TEST(FormatterTest, Fill) {
  560. EXPECT_THROW_MSG(format("{0:{<5}", 'c'), format_error,
  561. "invalid fill character '{'");
  562. EXPECT_THROW_MSG(format("{0:{<5}}", 'c'), format_error,
  563. "invalid fill character '{'");
  564. EXPECT_EQ("**42", format("{0:*>4}", 42));
  565. EXPECT_EQ("**-42", format("{0:*>5}", -42));
  566. EXPECT_EQ("***42", format("{0:*>5}", 42u));
  567. EXPECT_EQ("**-42", format("{0:*>5}", -42l));
  568. EXPECT_EQ("***42", format("{0:*>5}", 42ul));
  569. EXPECT_EQ("**-42", format("{0:*>5}", -42ll));
  570. EXPECT_EQ("***42", format("{0:*>5}", 42ull));
  571. EXPECT_EQ("**-42", format("{0:*>5}", -42.0));
  572. EXPECT_EQ("**-42", format("{0:*>5}", -42.0l));
  573. EXPECT_EQ("c****", format("{0:*<5}", 'c'));
  574. EXPECT_EQ("abc**", format("{0:*<5}", "abc"));
  575. EXPECT_EQ("**0xface", format("{0:*>8}", reinterpret_cast<void*>(0xface)));
  576. EXPECT_EQ("foo=", format("{:}=", "foo"));
  577. EXPECT_EQ(std::string("\0\0\0*", 4), format(string_view("{:\0>4}", 6), '*'));
  578. EXPECT_EQ("жж42", format("{0:ж>4}", 42));
  579. EXPECT_THROW_MSG(format("{:\x80\x80\x80\x80\x80>}", 0), format_error,
  580. "missing '}' in format string");
  581. }
  582. TEST(FormatterTest, PlusSign) {
  583. EXPECT_EQ("+42", format("{0:+}", 42));
  584. EXPECT_EQ("-42", format("{0:+}", -42));
  585. EXPECT_EQ("+42", format("{0:+}", 42));
  586. EXPECT_THROW_MSG(format("{0:+}", 42u), format_error,
  587. "format specifier requires signed argument");
  588. EXPECT_EQ("+42", format("{0:+}", 42l));
  589. EXPECT_THROW_MSG(format("{0:+}", 42ul), format_error,
  590. "format specifier requires signed argument");
  591. EXPECT_EQ("+42", format("{0:+}", 42ll));
  592. EXPECT_THROW_MSG(format("{0:+}", 42ull), format_error,
  593. "format specifier requires signed argument");
  594. EXPECT_EQ("+42", format("{0:+}", 42.0));
  595. EXPECT_EQ("+42", format("{0:+}", 42.0l));
  596. EXPECT_THROW_MSG(format("{0:+", 'c'), format_error,
  597. "missing '}' in format string");
  598. EXPECT_THROW_MSG(format("{0:+}", 'c'), format_error,
  599. "invalid format specifier for char");
  600. EXPECT_THROW_MSG(format("{0:+}", "abc"), format_error,
  601. "format specifier requires numeric argument");
  602. EXPECT_THROW_MSG(format("{0:+}", reinterpret_cast<void*>(0x42)), format_error,
  603. "format specifier requires numeric argument");
  604. }
  605. TEST(FormatterTest, MinusSign) {
  606. EXPECT_EQ("42", format("{0:-}", 42));
  607. EXPECT_EQ("-42", format("{0:-}", -42));
  608. EXPECT_EQ("42", format("{0:-}", 42));
  609. EXPECT_THROW_MSG(format("{0:-}", 42u), format_error,
  610. "format specifier requires signed argument");
  611. EXPECT_EQ("42", format("{0:-}", 42l));
  612. EXPECT_THROW_MSG(format("{0:-}", 42ul), format_error,
  613. "format specifier requires signed argument");
  614. EXPECT_EQ("42", format("{0:-}", 42ll));
  615. EXPECT_THROW_MSG(format("{0:-}", 42ull), format_error,
  616. "format specifier requires signed argument");
  617. EXPECT_EQ("42", format("{0:-}", 42.0));
  618. EXPECT_EQ("42", format("{0:-}", 42.0l));
  619. EXPECT_THROW_MSG(format("{0:-", 'c'), format_error,
  620. "missing '}' in format string");
  621. EXPECT_THROW_MSG(format("{0:-}", 'c'), format_error,
  622. "invalid format specifier for char");
  623. EXPECT_THROW_MSG(format("{0:-}", "abc"), format_error,
  624. "format specifier requires numeric argument");
  625. EXPECT_THROW_MSG(format("{0:-}", reinterpret_cast<void*>(0x42)), format_error,
  626. "format specifier requires numeric argument");
  627. }
  628. TEST(FormatterTest, SpaceSign) {
  629. EXPECT_EQ(" 42", format("{0: }", 42));
  630. EXPECT_EQ("-42", format("{0: }", -42));
  631. EXPECT_EQ(" 42", format("{0: }", 42));
  632. EXPECT_THROW_MSG(format("{0: }", 42u), format_error,
  633. "format specifier requires signed argument");
  634. EXPECT_EQ(" 42", format("{0: }", 42l));
  635. EXPECT_THROW_MSG(format("{0: }", 42ul), format_error,
  636. "format specifier requires signed argument");
  637. EXPECT_EQ(" 42", format("{0: }", 42ll));
  638. EXPECT_THROW_MSG(format("{0: }", 42ull), format_error,
  639. "format specifier requires signed argument");
  640. EXPECT_EQ(" 42", format("{0: }", 42.0));
  641. EXPECT_EQ(" 42", format("{0: }", 42.0l));
  642. EXPECT_THROW_MSG(format("{0: ", 'c'), format_error,
  643. "missing '}' in format string");
  644. EXPECT_THROW_MSG(format("{0: }", 'c'), format_error,
  645. "invalid format specifier for char");
  646. EXPECT_THROW_MSG(format("{0: }", "abc"), format_error,
  647. "format specifier requires numeric argument");
  648. EXPECT_THROW_MSG(format("{0: }", reinterpret_cast<void*>(0x42)), format_error,
  649. "format specifier requires numeric argument");
  650. }
  651. TEST(FormatterTest, SignNotTruncated) {
  652. wchar_t format_str[] = {L'{', L':',
  653. '+' | (1 << fmt::detail::num_bits<char>()), L'}', 0};
  654. EXPECT_THROW(format(format_str, 42), format_error);
  655. }
  656. TEST(FormatterTest, HashFlag) {
  657. EXPECT_EQ("42", format("{0:#}", 42));
  658. EXPECT_EQ("-42", format("{0:#}", -42));
  659. EXPECT_EQ("0b101010", format("{0:#b}", 42));
  660. EXPECT_EQ("0B101010", format("{0:#B}", 42));
  661. EXPECT_EQ("-0b101010", format("{0:#b}", -42));
  662. EXPECT_EQ("0x42", format("{0:#x}", 0x42));
  663. EXPECT_EQ("0X42", format("{0:#X}", 0x42));
  664. EXPECT_EQ("-0x42", format("{0:#x}", -0x42));
  665. EXPECT_EQ("0", format("{0:#o}", 0));
  666. EXPECT_EQ("042", format("{0:#o}", 042));
  667. EXPECT_EQ("-042", format("{0:#o}", -042));
  668. EXPECT_EQ("42", format("{0:#}", 42u));
  669. EXPECT_EQ("0x42", format("{0:#x}", 0x42u));
  670. EXPECT_EQ("042", format("{0:#o}", 042u));
  671. EXPECT_EQ("-42", format("{0:#}", -42l));
  672. EXPECT_EQ("0x42", format("{0:#x}", 0x42l));
  673. EXPECT_EQ("-0x42", format("{0:#x}", -0x42l));
  674. EXPECT_EQ("042", format("{0:#o}", 042l));
  675. EXPECT_EQ("-042", format("{0:#o}", -042l));
  676. EXPECT_EQ("42", format("{0:#}", 42ul));
  677. EXPECT_EQ("0x42", format("{0:#x}", 0x42ul));
  678. EXPECT_EQ("042", format("{0:#o}", 042ul));
  679. EXPECT_EQ("-42", format("{0:#}", -42ll));
  680. EXPECT_EQ("0x42", format("{0:#x}", 0x42ll));
  681. EXPECT_EQ("-0x42", format("{0:#x}", -0x42ll));
  682. EXPECT_EQ("042", format("{0:#o}", 042ll));
  683. EXPECT_EQ("-042", format("{0:#o}", -042ll));
  684. EXPECT_EQ("42", format("{0:#}", 42ull));
  685. EXPECT_EQ("0x42", format("{0:#x}", 0x42ull));
  686. EXPECT_EQ("042", format("{0:#o}", 042ull));
  687. EXPECT_EQ("-42.0", format("{0:#}", -42.0));
  688. EXPECT_EQ("-42.0", format("{0:#}", -42.0l));
  689. EXPECT_EQ("4.e+01", format("{:#.0e}", 42.0));
  690. EXPECT_EQ("0.", format("{:#.0f}", 0.01));
  691. EXPECT_EQ("0.50", format("{:#.2g}", 0.5));
  692. EXPECT_EQ("0.", format("{:#.0f}", 0.5));
  693. EXPECT_THROW_MSG(format("{0:#", 'c'), format_error,
  694. "missing '}' in format string");
  695. EXPECT_THROW_MSG(format("{0:#}", 'c'), format_error,
  696. "invalid format specifier for char");
  697. EXPECT_THROW_MSG(format("{0:#}", "abc"), format_error,
  698. "format specifier requires numeric argument");
  699. EXPECT_THROW_MSG(format("{0:#}", reinterpret_cast<void*>(0x42)), format_error,
  700. "format specifier requires numeric argument");
  701. }
  702. TEST(FormatterTest, ZeroFlag) {
  703. EXPECT_EQ("42", format("{0:0}", 42));
  704. EXPECT_EQ("-0042", format("{0:05}", -42));
  705. EXPECT_EQ("00042", format("{0:05}", 42u));
  706. EXPECT_EQ("-0042", format("{0:05}", -42l));
  707. EXPECT_EQ("00042", format("{0:05}", 42ul));
  708. EXPECT_EQ("-0042", format("{0:05}", -42ll));
  709. EXPECT_EQ("00042", format("{0:05}", 42ull));
  710. EXPECT_EQ("-000042", format("{0:07}", -42.0));
  711. EXPECT_EQ("-000042", format("{0:07}", -42.0l));
  712. EXPECT_THROW_MSG(format("{0:0", 'c'), format_error,
  713. "missing '}' in format string");
  714. EXPECT_THROW_MSG(format("{0:05}", 'c'), format_error,
  715. "invalid format specifier for char");
  716. EXPECT_THROW_MSG(format("{0:05}", "abc"), format_error,
  717. "format specifier requires numeric argument");
  718. EXPECT_THROW_MSG(format("{0:05}", reinterpret_cast<void*>(0x42)),
  719. format_error, "format specifier requires numeric argument");
  720. }
  721. TEST(FormatterTest, Width) {
  722. char format_str[BUFFER_SIZE];
  723. safe_sprintf(format_str, "{0:%u", UINT_MAX);
  724. increment(format_str + 3);
  725. EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
  726. size_t size = std::strlen(format_str);
  727. format_str[size] = '}';
  728. format_str[size + 1] = 0;
  729. EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
  730. safe_sprintf(format_str, "{0:%u", INT_MAX + 1u);
  731. EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
  732. safe_sprintf(format_str, "{0:%u}", INT_MAX + 1u);
  733. EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
  734. EXPECT_EQ(" -42", format("{0:4}", -42));
  735. EXPECT_EQ(" 42", format("{0:5}", 42u));
  736. EXPECT_EQ(" -42", format("{0:6}", -42l));
  737. EXPECT_EQ(" 42", format("{0:7}", 42ul));
  738. EXPECT_EQ(" -42", format("{0:6}", -42ll));
  739. EXPECT_EQ(" 42", format("{0:7}", 42ull));
  740. EXPECT_EQ(" -1.23", format("{0:8}", -1.23));
  741. EXPECT_EQ(" -1.23", format("{0:9}", -1.23l));
  742. EXPECT_EQ(" 0xcafe", format("{0:10}", reinterpret_cast<void*>(0xcafe)));
  743. EXPECT_EQ("x ", format("{0:11}", 'x'));
  744. EXPECT_EQ("str ", format("{0:12}", "str"));
  745. EXPECT_EQ(fmt::format("{:*^5}", "🤡"), "**🤡**");
  746. }
  747. template <typename T> inline T const_check(T value) { return value; }
  748. TEST(FormatterTest, RuntimeWidth) {
  749. char format_str[BUFFER_SIZE];
  750. safe_sprintf(format_str, "{0:{%u", UINT_MAX);
  751. increment(format_str + 4);
  752. EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
  753. size_t size = std::strlen(format_str);
  754. format_str[size] = '}';
  755. format_str[size + 1] = 0;
  756. EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
  757. format_str[size + 1] = '}';
  758. format_str[size + 2] = 0;
  759. EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
  760. EXPECT_THROW_MSG(format("{0:{", 0), format_error, "invalid format string");
  761. EXPECT_THROW_MSG(format("{0:{}", 0), format_error,
  762. "cannot switch from manual to automatic argument indexing");
  763. EXPECT_THROW_MSG(format("{0:{?}}", 0), format_error, "invalid format string");
  764. EXPECT_THROW_MSG(format("{0:{1}}", 0), format_error, "argument not found");
  765. EXPECT_THROW_MSG(format("{0:{0:}}", 0), format_error,
  766. "invalid format string");
  767. EXPECT_THROW_MSG(format("{0:{1}}", 0, -1), format_error, "negative width");
  768. EXPECT_THROW_MSG(format("{0:{1}}", 0, (INT_MAX + 1u)), format_error,
  769. "number is too big");
  770. EXPECT_THROW_MSG(format("{0:{1}}", 0, -1l), format_error, "negative width");
  771. if (const_check(sizeof(long) > sizeof(int))) {
  772. long value = INT_MAX;
  773. EXPECT_THROW_MSG(format("{0:{1}}", 0, (value + 1)), format_error,
  774. "number is too big");
  775. }
  776. EXPECT_THROW_MSG(format("{0:{1}}", 0, (INT_MAX + 1ul)), format_error,
  777. "number is too big");
  778. EXPECT_THROW_MSG(format("{0:{1}}", 0, '0'), format_error,
  779. "width is not integer");
  780. EXPECT_THROW_MSG(format("{0:{1}}", 0, 0.0), format_error,
  781. "width is not integer");
  782. EXPECT_EQ(" -42", format("{0:{1}}", -42, 4));
  783. EXPECT_EQ(" 42", format("{0:{1}}", 42u, 5));
  784. EXPECT_EQ(" -42", format("{0:{1}}", -42l, 6));
  785. EXPECT_EQ(" 42", format("{0:{1}}", 42ul, 7));
  786. EXPECT_EQ(" -42", format("{0:{1}}", -42ll, 6));
  787. EXPECT_EQ(" 42", format("{0:{1}}", 42ull, 7));
  788. EXPECT_EQ(" -1.23", format("{0:{1}}", -1.23, 8));
  789. EXPECT_EQ(" -1.23", format("{0:{1}}", -1.23l, 9));
  790. EXPECT_EQ(" 0xcafe",
  791. format("{0:{1}}", reinterpret_cast<void*>(0xcafe), 10));
  792. EXPECT_EQ("x ", format("{0:{1}}", 'x', 11));
  793. EXPECT_EQ("str ", format("{0:{1}}", "str", 12));
  794. }
  795. TEST(FormatterTest, Precision) {
  796. char format_str[BUFFER_SIZE];
  797. safe_sprintf(format_str, "{0:.%u", UINT_MAX);
  798. increment(format_str + 4);
  799. EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
  800. size_t size = std::strlen(format_str);
  801. format_str[size] = '}';
  802. format_str[size + 1] = 0;
  803. EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
  804. safe_sprintf(format_str, "{0:.%u", INT_MAX + 1u);
  805. EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
  806. safe_sprintf(format_str, "{0:.%u}", INT_MAX + 1u);
  807. EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
  808. EXPECT_THROW_MSG(format("{0:.", 0), format_error,
  809. "missing precision specifier");
  810. EXPECT_THROW_MSG(format("{0:.}", 0), format_error,
  811. "missing precision specifier");
  812. EXPECT_THROW_MSG(format("{0:.2", 0), format_error,
  813. "precision not allowed for this argument type");
  814. EXPECT_THROW_MSG(format("{0:.2}", 42), format_error,
  815. "precision not allowed for this argument type");
  816. EXPECT_THROW_MSG(format("{0:.2f}", 42), format_error,
  817. "precision not allowed for this argument type");
  818. EXPECT_THROW_MSG(format("{0:.2}", 42u), format_error,
  819. "precision not allowed for this argument type");
  820. EXPECT_THROW_MSG(format("{0:.2f}", 42u), format_error,
  821. "precision not allowed for this argument type");
  822. EXPECT_THROW_MSG(format("{0:.2}", 42l), format_error,
  823. "precision not allowed for this argument type");
  824. EXPECT_THROW_MSG(format("{0:.2f}", 42l), format_error,
  825. "precision not allowed for this argument type");
  826. EXPECT_THROW_MSG(format("{0:.2}", 42ul), format_error,
  827. "precision not allowed for this argument type");
  828. EXPECT_THROW_MSG(format("{0:.2f}", 42ul), format_error,
  829. "precision not allowed for this argument type");
  830. EXPECT_THROW_MSG(format("{0:.2}", 42ll), format_error,
  831. "precision not allowed for this argument type");
  832. EXPECT_THROW_MSG(format("{0:.2f}", 42ll), format_error,
  833. "precision not allowed for this argument type");
  834. EXPECT_THROW_MSG(format("{0:.2}", 42ull), format_error,
  835. "precision not allowed for this argument type");
  836. EXPECT_THROW_MSG(format("{0:.2f}", 42ull), format_error,
  837. "precision not allowed for this argument type");
  838. EXPECT_THROW_MSG(format("{0:3.0}", 'x'), format_error,
  839. "precision not allowed for this argument type");
  840. EXPECT_EQ("1.2", format("{0:.2}", 1.2345));
  841. EXPECT_EQ("1.2", format("{0:.2}", 1.2345l));
  842. EXPECT_EQ("1.2e+56", format("{:.2}", 1.234e56));
  843. EXPECT_EQ("1e+00", format("{:.0e}", 1.0L));
  844. EXPECT_EQ(" 0.0e+00", format("{:9.1e}", 0.0));
  845. EXPECT_EQ(
  846. "4.9406564584124654417656879286822137236505980261432476442558568250067550"
  847. "727020875186529983636163599237979656469544571773092665671035593979639877"
  848. "479601078187812630071319031140452784581716784898210368871863605699873072"
  849. "305000638740915356498438731247339727316961514003171538539807412623856559"
  850. "117102665855668676818703956031062493194527159149245532930545654440112748"
  851. "012970999954193198940908041656332452475714786901472678015935523861155013"
  852. "480352649347201937902681071074917033322268447533357208324319361e-324",
  853. format("{:.494}", 4.9406564584124654E-324));
  854. EXPECT_EQ(
  855. "-0X1.41FE3FFE71C9E000000000000000000000000000000000000000000000000000000"
  856. "000000000000000000000000000000000000000000000000000000000000000000000000"
  857. "000000000000000000000000000000000000000000000000000000000000000000000000"
  858. "000000000000000000000000000000000000000000000000000000000000000000000000"
  859. "000000000000000000000000000000000000000000000000000000000000000000000000"
  860. "000000000000000000000000000000000000000000000000000000000000000000000000"
  861. "000000000000000000000000000000000000000000000000000000000000000000000000"
  862. "000000000000000000000000000000000000000000000000000000000000000000000000"
  863. "000000000000000000000000000000000000000000000000000000000000000000000000"
  864. "000000000000000000000000000000000000000000000000000000000000000000000000"
  865. "000000000000000000000000000000000000000000000000000000000000000000000000"
  866. "000000000000000000000000000000000000000000000000000P+127",
  867. format("{:.838A}", -2.14001164E+38));
  868. EXPECT_EQ("123.", format("{:#.0f}", 123.0));
  869. EXPECT_EQ("1.23", format("{:.02f}", 1.234));
  870. EXPECT_EQ("0.001", format("{:.1g}", 0.001));
  871. EXPECT_EQ("1019666400", format("{}", 1019666432.0f));
  872. EXPECT_EQ("1e+01", format("{:.0e}", 9.5));
  873. EXPECT_EQ("1.0e-34", fmt::format("{:.1e}", 1e-34));
  874. EXPECT_THROW_MSG(format("{0:.2}", reinterpret_cast<void*>(0xcafe)),
  875. format_error,
  876. "precision not allowed for this argument type");
  877. EXPECT_THROW_MSG(format("{0:.2f}", reinterpret_cast<void*>(0xcafe)),
  878. format_error,
  879. "precision not allowed for this argument type");
  880. EXPECT_THROW_MSG(format("{:.{}e}", 42.0, fmt::detail::max_value<int>()),
  881. format_error, "number is too big");
  882. EXPECT_EQ("st", format("{0:.2}", "str"));
  883. }
  884. TEST(FormatterTest, RuntimePrecision) {
  885. char format_str[BUFFER_SIZE];
  886. safe_sprintf(format_str, "{0:.{%u", UINT_MAX);
  887. increment(format_str + 5);
  888. EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
  889. size_t size = std::strlen(format_str);
  890. format_str[size] = '}';
  891. format_str[size + 1] = 0;
  892. EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
  893. format_str[size + 1] = '}';
  894. format_str[size + 2] = 0;
  895. EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
  896. EXPECT_THROW_MSG(format("{0:.{", 0), format_error, "invalid format string");
  897. EXPECT_THROW_MSG(format("{0:.{}", 0), format_error,
  898. "cannot switch from manual to automatic argument indexing");
  899. EXPECT_THROW_MSG(format("{0:.{?}}", 0), format_error,
  900. "invalid format string");
  901. EXPECT_THROW_MSG(format("{0:.{1}", 0, 0), format_error,
  902. "precision not allowed for this argument type");
  903. EXPECT_THROW_MSG(format("{0:.{1}}", 0), format_error, "argument not found");
  904. EXPECT_THROW_MSG(format("{0:.{0:}}", 0), format_error,
  905. "invalid format string");
  906. EXPECT_THROW_MSG(format("{0:.{1}}", 0, -1), format_error,
  907. "negative precision");
  908. EXPECT_THROW_MSG(format("{0:.{1}}", 0, (INT_MAX + 1u)), format_error,
  909. "number is too big");
  910. EXPECT_THROW_MSG(format("{0:.{1}}", 0, -1l), format_error,
  911. "negative precision");
  912. if (const_check(sizeof(long) > sizeof(int))) {
  913. long value = INT_MAX;
  914. EXPECT_THROW_MSG(format("{0:.{1}}", 0, (value + 1)), format_error,
  915. "number is too big");
  916. }
  917. EXPECT_THROW_MSG(format("{0:.{1}}", 0, (INT_MAX + 1ul)), format_error,
  918. "number is too big");
  919. EXPECT_THROW_MSG(format("{0:.{1}}", 0, '0'), format_error,
  920. "precision is not integer");
  921. EXPECT_THROW_MSG(format("{0:.{1}}", 0, 0.0), format_error,
  922. "precision is not integer");
  923. EXPECT_THROW_MSG(format("{0:.{1}}", 42, 2), format_error,
  924. "precision not allowed for this argument type");
  925. EXPECT_THROW_MSG(format("{0:.{1}f}", 42, 2), format_error,
  926. "precision not allowed for this argument type");
  927. EXPECT_THROW_MSG(format("{0:.{1}}", 42u, 2), format_error,
  928. "precision not allowed for this argument type");
  929. EXPECT_THROW_MSG(format("{0:.{1}f}", 42u, 2), format_error,
  930. "precision not allowed for this argument type");
  931. EXPECT_THROW_MSG(format("{0:.{1}}", 42l, 2), format_error,
  932. "precision not allowed for this argument type");
  933. EXPECT_THROW_MSG(format("{0:.{1}f}", 42l, 2), format_error,
  934. "precision not allowed for this argument type");
  935. EXPECT_THROW_MSG(format("{0:.{1}}", 42ul, 2), format_error,
  936. "precision not allowed for this argument type");
  937. EXPECT_THROW_MSG(format("{0:.{1}f}", 42ul, 2), format_error,
  938. "precision not allowed for this argument type");
  939. EXPECT_THROW_MSG(format("{0:.{1}}", 42ll, 2), format_error,
  940. "precision not allowed for this argument type");
  941. EXPECT_THROW_MSG(format("{0:.{1}f}", 42ll, 2), format_error,
  942. "precision not allowed for this argument type");
  943. EXPECT_THROW_MSG(format("{0:.{1}}", 42ull, 2), format_error,
  944. "precision not allowed for this argument type");
  945. EXPECT_THROW_MSG(format("{0:.{1}f}", 42ull, 2), format_error,
  946. "precision not allowed for this argument type");
  947. EXPECT_THROW_MSG(format("{0:3.{1}}", 'x', 0), format_error,
  948. "precision not allowed for this argument type");
  949. EXPECT_EQ("1.2", format("{0:.{1}}", 1.2345, 2));
  950. EXPECT_EQ("1.2", format("{1:.{0}}", 2, 1.2345l));
  951. EXPECT_THROW_MSG(format("{0:.{1}}", reinterpret_cast<void*>(0xcafe), 2),
  952. format_error,
  953. "precision not allowed for this argument type");
  954. EXPECT_THROW_MSG(format("{0:.{1}f}", reinterpret_cast<void*>(0xcafe), 2),
  955. format_error,
  956. "precision not allowed for this argument type");
  957. EXPECT_EQ("st", format("{0:.{1}}", "str", 2));
  958. }
  959. template <typename T>
  960. void check_unknown_types(const T& value, const char* types, const char*) {
  961. char format_str[BUFFER_SIZE];
  962. const char* special = ".0123456789}";
  963. for (int i = CHAR_MIN; i <= CHAR_MAX; ++i) {
  964. char c = static_cast<char>(i);
  965. if (std::strchr(types, c) || std::strchr(special, c) || !c) continue;
  966. safe_sprintf(format_str, "{0:10%c}", c);
  967. const char* message = "invalid type specifier";
  968. EXPECT_THROW_MSG(format(format_str, value), format_error, message)
  969. << format_str << " " << message;
  970. }
  971. }
  972. TEST(BoolTest, FormatBool) {
  973. EXPECT_EQ("true", format("{}", true));
  974. EXPECT_EQ("false", format("{}", false));
  975. EXPECT_EQ("1", format("{:d}", true));
  976. EXPECT_EQ("true ", format("{:5}", true));
  977. EXPECT_EQ(L"true", format(L"{}", true));
  978. }
  979. TEST(FormatterTest, FormatShort) {
  980. short s = 42;
  981. EXPECT_EQ("42", format("{0:d}", s));
  982. unsigned short us = 42;
  983. EXPECT_EQ("42", format("{0:d}", us));
  984. }
  985. TEST(FormatterTest, FormatInt) {
  986. EXPECT_THROW_MSG(format("{0:v", 42), format_error,
  987. "missing '}' in format string");
  988. check_unknown_types(42, "bBdoxXnLc", "integer");
  989. EXPECT_EQ("x", format("{:c}", static_cast<int>('x')));
  990. }
  991. TEST(FormatterTest, FormatBin) {
  992. EXPECT_EQ("0", format("{0:b}", 0));
  993. EXPECT_EQ("101010", format("{0:b}", 42));
  994. EXPECT_EQ("101010", format("{0:b}", 42u));
  995. EXPECT_EQ("-101010", format("{0:b}", -42));
  996. EXPECT_EQ("11000000111001", format("{0:b}", 12345));
  997. EXPECT_EQ("10010001101000101011001111000", format("{0:b}", 0x12345678));
  998. EXPECT_EQ("10010000101010111100110111101111", format("{0:b}", 0x90ABCDEF));
  999. EXPECT_EQ("11111111111111111111111111111111",
  1000. format("{0:b}", max_value<uint32_t>()));
  1001. }
  1002. #if FMT_USE_INT128
  1003. constexpr auto int128_max = static_cast<__int128_t>(
  1004. (static_cast<__uint128_t>(1) << ((__SIZEOF_INT128__ * CHAR_BIT) - 1)) - 1);
  1005. constexpr auto int128_min = -int128_max - 1;
  1006. constexpr auto uint128_max = ~static_cast<__uint128_t>(0);
  1007. #endif
  1008. TEST(FormatterTest, FormatDec) {
  1009. EXPECT_EQ("0", format("{0}", 0));
  1010. EXPECT_EQ("42", format("{0}", 42));
  1011. EXPECT_EQ("42", format("{0:d}", 42));
  1012. EXPECT_EQ("42", format("{0}", 42u));
  1013. EXPECT_EQ("-42", format("{0}", -42));
  1014. EXPECT_EQ("12345", format("{0}", 12345));
  1015. EXPECT_EQ("67890", format("{0}", 67890));
  1016. #if FMT_USE_INT128
  1017. EXPECT_EQ("0", format("{0}", static_cast<__int128_t>(0)));
  1018. EXPECT_EQ("0", format("{0}", static_cast<__uint128_t>(0)));
  1019. EXPECT_EQ("9223372036854775808",
  1020. format("{0}", static_cast<__int128_t>(INT64_MAX) + 1));
  1021. EXPECT_EQ("-9223372036854775809",
  1022. format("{0}", static_cast<__int128_t>(INT64_MIN) - 1));
  1023. EXPECT_EQ("18446744073709551616",
  1024. format("{0}", static_cast<__int128_t>(UINT64_MAX) + 1));
  1025. EXPECT_EQ("170141183460469231731687303715884105727",
  1026. format("{0}", int128_max));
  1027. EXPECT_EQ("-170141183460469231731687303715884105728",
  1028. format("{0}", int128_min));
  1029. EXPECT_EQ("340282366920938463463374607431768211455",
  1030. format("{0}", uint128_max));
  1031. #endif
  1032. char buffer[BUFFER_SIZE];
  1033. safe_sprintf(buffer, "%d", INT_MIN);
  1034. EXPECT_EQ(buffer, format("{0}", INT_MIN));
  1035. safe_sprintf(buffer, "%d", INT_MAX);
  1036. EXPECT_EQ(buffer, format("{0}", INT_MAX));
  1037. safe_sprintf(buffer, "%u", UINT_MAX);
  1038. EXPECT_EQ(buffer, format("{0}", UINT_MAX));
  1039. safe_sprintf(buffer, "%ld", 0 - static_cast<unsigned long>(LONG_MIN));
  1040. EXPECT_EQ(buffer, format("{0}", LONG_MIN));
  1041. safe_sprintf(buffer, "%ld", LONG_MAX);
  1042. EXPECT_EQ(buffer, format("{0}", LONG_MAX));
  1043. safe_sprintf(buffer, "%lu", ULONG_MAX);
  1044. EXPECT_EQ(buffer, format("{0}", ULONG_MAX));
  1045. }
  1046. TEST(FormatterTest, FormatHex) {
  1047. EXPECT_EQ("0", format("{0:x}", 0));
  1048. EXPECT_EQ("42", format("{0:x}", 0x42));
  1049. EXPECT_EQ("42", format("{0:x}", 0x42u));
  1050. EXPECT_EQ("-42", format("{0:x}", -0x42));
  1051. EXPECT_EQ("12345678", format("{0:x}", 0x12345678));
  1052. EXPECT_EQ("90abcdef", format("{0:x}", 0x90abcdef));
  1053. EXPECT_EQ("12345678", format("{0:X}", 0x12345678));
  1054. EXPECT_EQ("90ABCDEF", format("{0:X}", 0x90ABCDEF));
  1055. #if FMT_USE_INT128
  1056. EXPECT_EQ("0", format("{0:x}", static_cast<__int128_t>(0)));
  1057. EXPECT_EQ("0", format("{0:x}", static_cast<__uint128_t>(0)));
  1058. EXPECT_EQ("8000000000000000",
  1059. format("{0:x}", static_cast<__int128_t>(INT64_MAX) + 1));
  1060. EXPECT_EQ("-8000000000000001",
  1061. format("{0:x}", static_cast<__int128_t>(INT64_MIN) - 1));
  1062. EXPECT_EQ("10000000000000000",
  1063. format("{0:x}", static_cast<__int128_t>(UINT64_MAX) + 1));
  1064. EXPECT_EQ("7fffffffffffffffffffffffffffffff", format("{0:x}", int128_max));
  1065. EXPECT_EQ("-80000000000000000000000000000000", format("{0:x}", int128_min));
  1066. EXPECT_EQ("ffffffffffffffffffffffffffffffff", format("{0:x}", uint128_max));
  1067. #endif
  1068. char buffer[BUFFER_SIZE];
  1069. safe_sprintf(buffer, "-%x", 0 - static_cast<unsigned>(INT_MIN));
  1070. EXPECT_EQ(buffer, format("{0:x}", INT_MIN));
  1071. safe_sprintf(buffer, "%x", INT_MAX);
  1072. EXPECT_EQ(buffer, format("{0:x}", INT_MAX));
  1073. safe_sprintf(buffer, "%x", UINT_MAX);
  1074. EXPECT_EQ(buffer, format("{0:x}", UINT_MAX));
  1075. safe_sprintf(buffer, "-%lx", 0 - static_cast<unsigned long>(LONG_MIN));
  1076. EXPECT_EQ(buffer, format("{0:x}", LONG_MIN));
  1077. safe_sprintf(buffer, "%lx", LONG_MAX);
  1078. EXPECT_EQ(buffer, format("{0:x}", LONG_MAX));
  1079. safe_sprintf(buffer, "%lx", ULONG_MAX);
  1080. EXPECT_EQ(buffer, format("{0:x}", ULONG_MAX));
  1081. }
  1082. TEST(FormatterTest, FormatOct) {
  1083. EXPECT_EQ("0", format("{0:o}", 0));
  1084. EXPECT_EQ("42", format("{0:o}", 042));
  1085. EXPECT_EQ("42", format("{0:o}", 042u));
  1086. EXPECT_EQ("-42", format("{0:o}", -042));
  1087. EXPECT_EQ("12345670", format("{0:o}", 012345670));
  1088. #if FMT_USE_INT128
  1089. EXPECT_EQ("0", format("{0:o}", static_cast<__int128_t>(0)));
  1090. EXPECT_EQ("0", format("{0:o}", static_cast<__uint128_t>(0)));
  1091. EXPECT_EQ("1000000000000000000000",
  1092. format("{0:o}", static_cast<__int128_t>(INT64_MAX) + 1));
  1093. EXPECT_EQ("-1000000000000000000001",
  1094. format("{0:o}", static_cast<__int128_t>(INT64_MIN) - 1));
  1095. EXPECT_EQ("2000000000000000000000",
  1096. format("{0:o}", static_cast<__int128_t>(UINT64_MAX) + 1));
  1097. EXPECT_EQ("1777777777777777777777777777777777777777777",
  1098. format("{0:o}", int128_max));
  1099. EXPECT_EQ("-2000000000000000000000000000000000000000000",
  1100. format("{0:o}", int128_min));
  1101. EXPECT_EQ("3777777777777777777777777777777777777777777",
  1102. format("{0:o}", uint128_max));
  1103. #endif
  1104. char buffer[BUFFER_SIZE];
  1105. safe_sprintf(buffer, "-%o", 0 - static_cast<unsigned>(INT_MIN));
  1106. EXPECT_EQ(buffer, format("{0:o}", INT_MIN));
  1107. safe_sprintf(buffer, "%o", INT_MAX);
  1108. EXPECT_EQ(buffer, format("{0:o}", INT_MAX));
  1109. safe_sprintf(buffer, "%o", UINT_MAX);
  1110. EXPECT_EQ(buffer, format("{0:o}", UINT_MAX));
  1111. safe_sprintf(buffer, "-%lo", 0 - static_cast<unsigned long>(LONG_MIN));
  1112. EXPECT_EQ(buffer, format("{0:o}", LONG_MIN));
  1113. safe_sprintf(buffer, "%lo", LONG_MAX);
  1114. EXPECT_EQ(buffer, format("{0:o}", LONG_MAX));
  1115. safe_sprintf(buffer, "%lo", ULONG_MAX);
  1116. EXPECT_EQ(buffer, format("{0:o}", ULONG_MAX));
  1117. }
  1118. TEST(FormatterTest, FormatIntLocale) {
  1119. EXPECT_EQ("1234", format("{:L}", 1234));
  1120. }
  1121. struct ConvertibleToLongLong {
  1122. operator long long() const { return 1LL << 32; }
  1123. };
  1124. TEST(FormatterTest, FormatConvertibleToLongLong) {
  1125. EXPECT_EQ("100000000", format("{:x}", ConvertibleToLongLong()));
  1126. }
  1127. TEST(FormatterTest, FormatFloat) {
  1128. EXPECT_EQ("0", format("{}", 0.0f));
  1129. EXPECT_EQ("392.500000", format("{0:f}", 392.5f));
  1130. }
  1131. TEST(FormatterTest, FormatDouble) {
  1132. EXPECT_EQ("0", format("{}", 0.0));
  1133. check_unknown_types(1.2, "eEfFgGaAnL%", "double");
  1134. EXPECT_EQ("0", format("{:}", 0.0));
  1135. EXPECT_EQ("0.000000", format("{:f}", 0.0));
  1136. EXPECT_EQ("0", format("{:g}", 0.0));
  1137. EXPECT_EQ("392.65", format("{:}", 392.65));
  1138. EXPECT_EQ("392.65", format("{:g}", 392.65));
  1139. EXPECT_EQ("392.65", format("{:G}", 392.65));
  1140. EXPECT_EQ("4.9014e+06", format("{:g}", 4.9014e6));
  1141. EXPECT_EQ("392.650000", format("{:f}", 392.65));
  1142. EXPECT_EQ("392.650000", format("{:F}", 392.65));
  1143. EXPECT_EQ("42", format("{:L}", 42.0));
  1144. char buffer[BUFFER_SIZE];
  1145. safe_sprintf(buffer, "%e", 392.65);
  1146. EXPECT_EQ(buffer, format("{0:e}", 392.65));
  1147. safe_sprintf(buffer, "%E", 392.65);
  1148. EXPECT_EQ(buffer, format("{0:E}", 392.65));
  1149. EXPECT_EQ("+0000392.6", format("{0:+010.4g}", 392.65));
  1150. safe_sprintf(buffer, "%a", -42.0);
  1151. EXPECT_EQ(buffer, format("{:a}", -42.0));
  1152. safe_sprintf(buffer, "%A", -42.0);
  1153. EXPECT_EQ(buffer, format("{:A}", -42.0));
  1154. EXPECT_EQ("9223372036854775808.000000",
  1155. format("{:f}", 9223372036854775807.0));
  1156. }
  1157. TEST(FormatterTest, PrecisionRounding) {
  1158. EXPECT_EQ("0", format("{:.0f}", 0.0));
  1159. EXPECT_EQ("0", format("{:.0f}", 0.01));
  1160. EXPECT_EQ("0", format("{:.0f}", 0.1));
  1161. EXPECT_EQ("0.000", format("{:.3f}", 0.00049));
  1162. EXPECT_EQ("0.001", format("{:.3f}", 0.0005));
  1163. EXPECT_EQ("0.001", format("{:.3f}", 0.00149));
  1164. EXPECT_EQ("0.002", format("{:.3f}", 0.0015));
  1165. EXPECT_EQ("1.000", format("{:.3f}", 0.9999));
  1166. EXPECT_EQ("0.00123", format("{:.3}", 0.00123));
  1167. EXPECT_EQ("0.1", format("{:.16g}", 0.1));
  1168. EXPECT_EQ("1", fmt::format("{:.0}", 1.0));
  1169. EXPECT_EQ("225.51575035152063720",
  1170. fmt::format("{:.17f}", 225.51575035152064));
  1171. EXPECT_EQ("-761519619559038.2", fmt::format("{:.1f}", -761519619559038.2));
  1172. EXPECT_EQ("1.9156918820264798e-56",
  1173. fmt::format("{}", 1.9156918820264798e-56));
  1174. EXPECT_EQ("0.0000", fmt::format("{:.4f}", 7.2809479766055470e-15));
  1175. // Trigger a rounding error in Grisu by a specially chosen number.
  1176. EXPECT_EQ("3788512123356.985352", format("{:f}", 3788512123356.985352));
  1177. }
  1178. TEST(FormatterTest, PrettifyFloat) {
  1179. EXPECT_EQ("0.0001", fmt::format("{}", 1e-4));
  1180. EXPECT_EQ("1e-05", fmt::format("{}", 1e-5));
  1181. EXPECT_EQ("1000000000000000", fmt::format("{}", 1e15));
  1182. EXPECT_EQ("1e+16", fmt::format("{}", 1e16));
  1183. EXPECT_EQ("9.999e-05", fmt::format("{}", 9.999e-5));
  1184. EXPECT_EQ("10000000000", fmt::format("{}", 1e10));
  1185. EXPECT_EQ("100000000000", fmt::format("{}", 1e11));
  1186. EXPECT_EQ("12340000000", fmt::format("{}", 1234e7));
  1187. EXPECT_EQ("12.34", fmt::format("{}", 1234e-2));
  1188. EXPECT_EQ("0.001234", fmt::format("{}", 1234e-6));
  1189. EXPECT_EQ("0.1", fmt::format("{}", 0.1f));
  1190. EXPECT_EQ("0.10000000149011612", fmt::format("{}", double(0.1f)));
  1191. EXPECT_EQ("1.3563156e-19", fmt::format("{}", 1.35631564e-19f));
  1192. }
  1193. TEST(FormatterTest, FormatNaN) {
  1194. double nan = std::numeric_limits<double>::quiet_NaN();
  1195. EXPECT_EQ("nan", format("{}", nan));
  1196. EXPECT_EQ("+nan", format("{:+}", nan));
  1197. if (std::signbit(-nan))
  1198. EXPECT_EQ("-nan", format("{}", -nan));
  1199. else
  1200. fmt::print("Warning: compiler doesn't handle negative NaN correctly");
  1201. EXPECT_EQ(" nan", format("{: }", nan));
  1202. EXPECT_EQ("NAN", format("{:F}", nan));
  1203. EXPECT_EQ("nan ", format("{:<7}", nan));
  1204. EXPECT_EQ(" nan ", format("{:^7}", nan));
  1205. EXPECT_EQ(" nan", format("{:>7}", nan));
  1206. }
  1207. TEST(FormatterTest, FormatInfinity) {
  1208. double inf = std::numeric_limits<double>::infinity();
  1209. EXPECT_EQ("inf", format("{}", inf));
  1210. EXPECT_EQ("+inf", format("{:+}", inf));
  1211. EXPECT_EQ("-inf", format("{}", -inf));
  1212. EXPECT_EQ(" inf", format("{: }", inf));
  1213. EXPECT_EQ("INF", format("{:F}", inf));
  1214. EXPECT_EQ("inf ", format("{:<7}", inf));
  1215. EXPECT_EQ(" inf ", format("{:^7}", inf));
  1216. EXPECT_EQ(" inf", format("{:>7}", inf));
  1217. }
  1218. TEST(FormatterTest, FormatLongDouble) {
  1219. EXPECT_EQ("0", format("{0:}", 0.0l));
  1220. EXPECT_EQ("0.000000", format("{0:f}", 0.0l));
  1221. EXPECT_EQ("392.65", format("{0:}", 392.65l));
  1222. EXPECT_EQ("392.65", format("{0:g}", 392.65l));
  1223. EXPECT_EQ("392.65", format("{0:G}", 392.65l));
  1224. EXPECT_EQ("392.650000", format("{0:f}", 392.65l));
  1225. EXPECT_EQ("392.650000", format("{0:F}", 392.65l));
  1226. char buffer[BUFFER_SIZE];
  1227. safe_sprintf(buffer, "%Le", 392.65l);
  1228. EXPECT_EQ(buffer, format("{0:e}", 392.65l));
  1229. EXPECT_EQ("+0000392.6", format("{0:+010.4g}", 392.64l));
  1230. safe_sprintf(buffer, "%La", 3.31l);
  1231. EXPECT_EQ(buffer, format("{:a}", 3.31l));
  1232. }
  1233. TEST(FormatterTest, FormatChar) {
  1234. const char types[] = "cbBdoxXL";
  1235. check_unknown_types('a', types, "char");
  1236. EXPECT_EQ("a", format("{0}", 'a'));
  1237. EXPECT_EQ("z", format("{0:c}", 'z'));
  1238. EXPECT_EQ(L"a", format(L"{0}", 'a'));
  1239. int n = 'x';
  1240. for (const char* type = types + 1; *type; ++type) {
  1241. std::string format_str = fmt::format("{{:{}}}", *type);
  1242. EXPECT_EQ(fmt::format(format_str, n), fmt::format(format_str, 'x'));
  1243. }
  1244. EXPECT_EQ(fmt::format("{:02X}", n), fmt::format("{:02X}", 'x'));
  1245. }
  1246. TEST(FormatterTest, FormatVolatileChar) {
  1247. volatile char c = 'x';
  1248. EXPECT_EQ("x", format("{}", c));
  1249. }
  1250. TEST(FormatterTest, FormatUnsignedChar) {
  1251. EXPECT_EQ("42", format("{}", static_cast<unsigned char>(42)));
  1252. EXPECT_EQ("42", format("{}", static_cast<uint8_t>(42)));
  1253. }
  1254. TEST(FormatterTest, FormatWChar) {
  1255. EXPECT_EQ(L"a", format(L"{0}", L'a'));
  1256. // This shouldn't compile:
  1257. // format("{}", L'a');
  1258. }
  1259. TEST(FormatterTest, FormatCString) {
  1260. check_unknown_types("test", "sp", "string");
  1261. EXPECT_EQ("test", format("{0}", "test"));
  1262. EXPECT_EQ("test", format("{0:s}", "test"));
  1263. char nonconst[] = "nonconst";
  1264. EXPECT_EQ("nonconst", format("{0}", nonconst));
  1265. EXPECT_THROW_MSG(format("{0}", static_cast<const char*>(nullptr)),
  1266. format_error, "string pointer is null");
  1267. }
  1268. TEST(FormatterTest, FormatSCharString) {
  1269. signed char str[] = "test";
  1270. EXPECT_EQ("test", format("{0:s}", str));
  1271. const signed char* const_str = str;
  1272. EXPECT_EQ("test", format("{0:s}", const_str));
  1273. }
  1274. TEST(FormatterTest, FormatUCharString) {
  1275. unsigned char str[] = "test";
  1276. EXPECT_EQ("test", format("{0:s}", str));
  1277. const unsigned char* const_str = str;
  1278. EXPECT_EQ("test", format("{0:s}", const_str));
  1279. unsigned char* ptr = str;
  1280. EXPECT_EQ("test", format("{0:s}", ptr));
  1281. }
  1282. TEST(FormatterTest, FormatPointer) {
  1283. check_unknown_types(reinterpret_cast<void*>(0x1234), "p", "pointer");
  1284. EXPECT_EQ("0x0", format("{0}", static_cast<void*>(nullptr)));
  1285. EXPECT_EQ("0x1234", format("{0}", reinterpret_cast<void*>(0x1234)));
  1286. EXPECT_EQ("0x1234", format("{0:p}", reinterpret_cast<void*>(0x1234)));
  1287. EXPECT_EQ("0x" + std::string(sizeof(void*) * CHAR_BIT / 4, 'f'),
  1288. format("{0}", reinterpret_cast<void*>(~uintptr_t())));
  1289. EXPECT_EQ("0x1234", format("{}", fmt::ptr(reinterpret_cast<int*>(0x1234))));
  1290. std::unique_ptr<int> up(new int(1));
  1291. EXPECT_EQ(format("{}", fmt::ptr(up.get())), format("{}", fmt::ptr(up)));
  1292. std::shared_ptr<int> sp(new int(1));
  1293. EXPECT_EQ(format("{}", fmt::ptr(sp.get())), format("{}", fmt::ptr(sp)));
  1294. EXPECT_EQ("0x0", format("{}", nullptr));
  1295. }
  1296. TEST(FormatterTest, FormatString) {
  1297. EXPECT_EQ("test", format("{0}", std::string("test")));
  1298. }
  1299. TEST(FormatterTest, FormatStringView) {
  1300. EXPECT_EQ("test", format("{}", string_view("test")));
  1301. EXPECT_EQ("", format("{}", string_view()));
  1302. }
  1303. #ifdef FMT_USE_STRING_VIEW
  1304. struct string_viewable {};
  1305. FMT_BEGIN_NAMESPACE
  1306. template <> struct formatter<string_viewable> : formatter<std::string_view> {
  1307. auto format(string_viewable, format_context& ctx) -> decltype(ctx.out()) {
  1308. return formatter<std::string_view>::format("foo", ctx);
  1309. }
  1310. };
  1311. FMT_END_NAMESPACE
  1312. TEST(FormatterTest, FormatStdStringView) {
  1313. EXPECT_EQ("test", format("{}", std::string_view("test")));
  1314. EXPECT_EQ("foo", format("{}", string_viewable()));
  1315. }
  1316. struct explicitly_convertible_to_std_string_view {
  1317. explicit operator std::string_view() const { return "foo"; }
  1318. };
  1319. namespace fmt {
  1320. template <>
  1321. struct formatter<explicitly_convertible_to_std_string_view>
  1322. : formatter<std::string_view> {
  1323. auto format(const explicitly_convertible_to_std_string_view& v,
  1324. format_context& ctx) -> decltype(ctx.out()) {
  1325. return format_to(ctx.out(), "'{}'", std::string_view(v));
  1326. }
  1327. };
  1328. } // namespace fmt
  1329. TEST(FormatterTest, FormatExplicitlyConvertibleToStdStringView) {
  1330. EXPECT_EQ("'foo'",
  1331. fmt::format("{}", explicitly_convertible_to_std_string_view()));
  1332. }
  1333. #endif
  1334. // std::is_constructible is broken in MSVC until version 2015.
  1335. #if !FMT_MSC_VER || FMT_MSC_VER >= 1900
  1336. struct explicitly_convertible_to_wstring_view {
  1337. explicit operator fmt::wstring_view() const { return L"foo"; }
  1338. };
  1339. TEST(FormatTest, FormatExplicitlyConvertibleToWStringView) {
  1340. EXPECT_EQ(L"foo",
  1341. fmt::format(L"{}", explicitly_convertible_to_wstring_view()));
  1342. }
  1343. #endif
  1344. namespace fake_qt {
  1345. class QString {
  1346. public:
  1347. QString(const wchar_t* s) : s_(std::make_shared<std::wstring>(s)) {}
  1348. const wchar_t* utf16() const FMT_NOEXCEPT { return s_->data(); }
  1349. int size() const FMT_NOEXCEPT { return static_cast<int>(s_->size()); }
  1350. private:
  1351. std::shared_ptr<std::wstring> s_;
  1352. };
  1353. fmt::basic_string_view<wchar_t> to_string_view(const QString& s) FMT_NOEXCEPT {
  1354. return {s.utf16(), static_cast<size_t>(s.size())};
  1355. }
  1356. } // namespace fake_qt
  1357. TEST(FormatTest, FormatForeignStrings) {
  1358. using fake_qt::QString;
  1359. EXPECT_EQ(fmt::format(QString(L"{}"), 42), L"42");
  1360. EXPECT_EQ(fmt::format(QString(L"{}"), QString(L"42")), L"42");
  1361. }
  1362. FMT_BEGIN_NAMESPACE
  1363. template <> struct formatter<Date> {
  1364. template <typename ParseContext>
  1365. FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
  1366. auto it = ctx.begin();
  1367. if (it != ctx.end() && *it == 'd') ++it;
  1368. return it;
  1369. }
  1370. auto format(const Date& d, format_context& ctx) -> decltype(ctx.out()) {
  1371. format_to(ctx.out(), "{}-{}-{}", d.year(), d.month(), d.day());
  1372. return ctx.out();
  1373. }
  1374. };
  1375. FMT_END_NAMESPACE
  1376. TEST(FormatterTest, FormatCustom) {
  1377. Date date(2012, 12, 9);
  1378. EXPECT_THROW_MSG(fmt::format("{:s}", date), format_error,
  1379. "unknown format specifier");
  1380. }
  1381. class Answer {};
  1382. FMT_BEGIN_NAMESPACE
  1383. template <> struct formatter<Answer> : formatter<int> {
  1384. template <typename FormatContext>
  1385. auto format(Answer, FormatContext& ctx) -> decltype(ctx.out()) {
  1386. return formatter<int>::format(42, ctx);
  1387. }
  1388. };
  1389. FMT_END_NAMESPACE
  1390. TEST(FormatterTest, CustomFormat) {
  1391. EXPECT_EQ("42", format("{0}", Answer()));
  1392. EXPECT_EQ("0042", format("{:04}", Answer()));
  1393. }
  1394. TEST(FormatterTest, CustomFormatTo) {
  1395. char buf[10] = {};
  1396. auto end =
  1397. &*fmt::format_to(fmt::detail::make_checked(buf, 10), "{}", Answer());
  1398. EXPECT_EQ(end, buf + 2);
  1399. EXPECT_STREQ(buf, "42");
  1400. }
  1401. TEST(FormatterTest, WideFormatString) {
  1402. EXPECT_EQ(L"42", format(L"{}", 42));
  1403. EXPECT_EQ(L"4.2", format(L"{}", 4.2));
  1404. EXPECT_EQ(L"abc", format(L"{}", L"abc"));
  1405. EXPECT_EQ(L"z", format(L"{}", L'z'));
  1406. EXPECT_THROW(fmt::format(L"{:*\x343E}", 42), fmt::format_error);
  1407. }
  1408. TEST(FormatterTest, FormatStringFromSpeedTest) {
  1409. EXPECT_EQ("1.2340000000:0042:+3.13:str:0x3e8:X:%",
  1410. format("{0:0.10f}:{1:04}:{2:+g}:{3}:{4}:{5}:%", 1.234, 42, 3.13,
  1411. "str", reinterpret_cast<void*>(1000), 'X'));
  1412. }
  1413. TEST(FormatterTest, FormatExamples) {
  1414. std::string message = format("The answer is {}", 42);
  1415. EXPECT_EQ("The answer is 42", message);
  1416. EXPECT_EQ("42", format("{}", 42));
  1417. EXPECT_EQ("42", format(std::string("{}"), 42));
  1418. memory_buffer out;
  1419. format_to(out, "The answer is {}.", 42);
  1420. EXPECT_EQ("The answer is 42.", to_string(out));
  1421. const char* filename = "nonexistent";
  1422. FILE* ftest = safe_fopen(filename, "r");
  1423. if (ftest) fclose(ftest);
  1424. int error_code = errno;
  1425. EXPECT_TRUE(ftest == nullptr);
  1426. EXPECT_SYSTEM_ERROR(
  1427. {
  1428. FILE* f = safe_fopen(filename, "r");
  1429. if (!f)
  1430. throw fmt::system_error(errno, "Cannot open file '{}'", filename);
  1431. fclose(f);
  1432. },
  1433. error_code, "Cannot open file 'nonexistent'");
  1434. }
  1435. TEST(FormatterTest, Examples) {
  1436. EXPECT_EQ("First, thou shalt count to three",
  1437. format("First, thou shalt count to {0}", "three"));
  1438. EXPECT_EQ("Bring me a shrubbery", format("Bring me a {}", "shrubbery"));
  1439. EXPECT_EQ("From 1 to 3", format("From {} to {}", 1, 3));
  1440. char buffer[BUFFER_SIZE];
  1441. safe_sprintf(buffer, "%03.2f", -1.2);
  1442. EXPECT_EQ(buffer, format("{:03.2f}", -1.2));
  1443. EXPECT_EQ("a, b, c", format("{0}, {1}, {2}", 'a', 'b', 'c'));
  1444. EXPECT_EQ("a, b, c", format("{}, {}, {}", 'a', 'b', 'c'));
  1445. EXPECT_EQ("c, b, a", format("{2}, {1}, {0}", 'a', 'b', 'c'));
  1446. EXPECT_EQ("abracadabra", format("{0}{1}{0}", "abra", "cad"));
  1447. EXPECT_EQ("left aligned ", format("{:<30}", "left aligned"));
  1448. EXPECT_EQ(" right aligned",
  1449. format("{:>30}", "right aligned"));
  1450. EXPECT_EQ(" centered ", format("{:^30}", "centered"));
  1451. EXPECT_EQ("***********centered***********", format("{:*^30}", "centered"));
  1452. EXPECT_EQ("+3.140000; -3.140000", format("{:+f}; {:+f}", 3.14, -3.14));
  1453. EXPECT_EQ(" 3.140000; -3.140000", format("{: f}; {: f}", 3.14, -3.14));
  1454. EXPECT_EQ("3.140000; -3.140000", format("{:-f}; {:-f}", 3.14, -3.14));
  1455. EXPECT_EQ("int: 42; hex: 2a; oct: 52",
  1456. format("int: {0:d}; hex: {0:x}; oct: {0:o}", 42));
  1457. EXPECT_EQ("int: 42; hex: 0x2a; oct: 052",
  1458. format("int: {0:d}; hex: {0:#x}; oct: {0:#o}", 42));
  1459. EXPECT_EQ("The answer is 42", format("The answer is {}", 42));
  1460. EXPECT_THROW_MSG(format("The answer is {:d}", "forty-two"), format_error,
  1461. "invalid type specifier");
  1462. EXPECT_EQ(L"Cyrillic letter \x42e", format(L"Cyrillic letter {}", L'\x42e'));
  1463. EXPECT_WRITE(
  1464. stdout, fmt::print("{}", std::numeric_limits<double>::infinity()), "inf");
  1465. }
  1466. TEST(FormatIntTest, Data) {
  1467. fmt::format_int format_int(42);
  1468. EXPECT_EQ("42", std::string(format_int.data(), format_int.size()));
  1469. }
  1470. TEST(FormatIntTest, FormatInt) {
  1471. EXPECT_EQ("42", fmt::format_int(42).str());
  1472. EXPECT_EQ(2u, fmt::format_int(42).size());
  1473. EXPECT_EQ("-42", fmt::format_int(-42).str());
  1474. EXPECT_EQ(3u, fmt::format_int(-42).size());
  1475. EXPECT_EQ("42", fmt::format_int(42ul).str());
  1476. EXPECT_EQ("-42", fmt::format_int(-42l).str());
  1477. EXPECT_EQ("42", fmt::format_int(42ull).str());
  1478. EXPECT_EQ("-42", fmt::format_int(-42ll).str());
  1479. std::ostringstream os;
  1480. os << max_value<int64_t>();
  1481. EXPECT_EQ(os.str(), fmt::format_int(max_value<int64_t>()).str());
  1482. }
  1483. TEST(FormatTest, Print) {
  1484. #if FMT_USE_FCNTL
  1485. EXPECT_WRITE(stdout, fmt::print("Don't {}!", "panic"), "Don't panic!");
  1486. EXPECT_WRITE(stderr, fmt::print(stderr, "Don't {}!", "panic"),
  1487. "Don't panic!");
  1488. #endif
  1489. // Check that the wide print overload compiles.
  1490. if (fmt::detail::const_check(false)) fmt::print(L"test");
  1491. }
  1492. TEST(FormatTest, Variadic) {
  1493. EXPECT_EQ("abc1", format("{}c{}", "ab", 1));
  1494. EXPECT_EQ(L"abc1", format(L"{}c{}", L"ab", 1));
  1495. }
  1496. TEST(FormatTest, Dynamic) {
  1497. typedef fmt::format_context ctx;
  1498. std::vector<fmt::basic_format_arg<ctx>> args;
  1499. args.emplace_back(fmt::detail::make_arg<ctx>(42));
  1500. args.emplace_back(fmt::detail::make_arg<ctx>("abc1"));
  1501. args.emplace_back(fmt::detail::make_arg<ctx>(1.5f));
  1502. std::string result = fmt::vformat(
  1503. "{} and {} and {}",
  1504. fmt::basic_format_args<ctx>(args.data(), static_cast<int>(args.size())));
  1505. EXPECT_EQ("42 and abc1 and 1.5", result);
  1506. }
  1507. TEST(FormatTest, Bytes) {
  1508. auto s = fmt::format("{:10}", fmt::bytes("ёжик"));
  1509. EXPECT_EQ("ёжик ", s);
  1510. EXPECT_EQ(10, s.size());
  1511. }
  1512. TEST(FormatTest, JoinArg) {
  1513. using fmt::join;
  1514. int v1[3] = {1, 2, 3};
  1515. std::vector<float> v2;
  1516. v2.push_back(1.2f);
  1517. v2.push_back(3.4f);
  1518. void* v3[2] = {&v1[0], &v1[1]};
  1519. EXPECT_EQ("(1, 2, 3)", format("({})", join(v1, v1 + 3, ", ")));
  1520. EXPECT_EQ("(1)", format("({})", join(v1, v1 + 1, ", ")));
  1521. EXPECT_EQ("()", format("({})", join(v1, v1, ", ")));
  1522. EXPECT_EQ("(001, 002, 003)", format("({:03})", join(v1, v1 + 3, ", ")));
  1523. EXPECT_EQ("(+01.20, +03.40)",
  1524. format("({:+06.2f})", join(v2.begin(), v2.end(), ", ")));
  1525. EXPECT_EQ(L"(1, 2, 3)", format(L"({})", join(v1, v1 + 3, L", ")));
  1526. EXPECT_EQ("1, 2, 3", format("{0:{1}}", join(v1, v1 + 3, ", "), 1));
  1527. EXPECT_EQ(format("{}, {}", v3[0], v3[1]),
  1528. format("{}", join(v3, v3 + 2, ", ")));
  1529. #if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 405
  1530. EXPECT_EQ("(1, 2, 3)", format("({})", join(v1, ", ")));
  1531. EXPECT_EQ("(+01.20, +03.40)", format("({:+06.2f})", join(v2, ", ")));
  1532. #endif
  1533. }
  1534. template <typename T> std::string str(const T& value) {
  1535. return fmt::format("{}", value);
  1536. }
  1537. TEST(StrTest, Convert) {
  1538. EXPECT_EQ("42", str(42));
  1539. std::string s = str(Date(2012, 12, 9));
  1540. EXPECT_EQ("2012-12-9", s);
  1541. }
  1542. std::string vformat_message(int id, const char* format, fmt::format_args args) {
  1543. fmt::memory_buffer buffer;
  1544. format_to(buffer, "[{}] ", id);
  1545. vformat_to(buffer, format, args);
  1546. return to_string(buffer);
  1547. }
  1548. template <typename... Args>
  1549. std::string format_message(int id, const char* format, const Args&... args) {
  1550. auto va = fmt::make_format_args(args...);
  1551. return vformat_message(id, format, va);
  1552. }
  1553. TEST(FormatTest, FormatMessageExample) {
  1554. EXPECT_EQ("[42] something happened",
  1555. format_message(42, "{} happened", "something"));
  1556. }
  1557. template <typename... Args>
  1558. void print_error(const char* file, int line, const char* format,
  1559. const Args&... args) {
  1560. fmt::print("{}: {}: ", file, line);
  1561. fmt::print(format, args...);
  1562. }
  1563. TEST(FormatTest, UnpackedArgs) {
  1564. EXPECT_EQ("0123456789abcdefg",
  1565. fmt::format("{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}", 0, 1, 2, 3, 4, 5,
  1566. 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g'));
  1567. }
  1568. struct string_like {};
  1569. fmt::string_view to_string_view(string_like) { return "foo"; }
  1570. constexpr char with_null[3] = {'{', '}', '\0'};
  1571. constexpr char no_null[2] = {'{', '}'};
  1572. TEST(FormatTest, CompileTimeString) {
  1573. EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), 42));
  1574. EXPECT_EQ(L"42", fmt::format(FMT_STRING(L"{}"), 42));
  1575. EXPECT_EQ("foo", fmt::format(FMT_STRING("{}"), string_like()));
  1576. (void)with_null;
  1577. (void)no_null;
  1578. #if __cplusplus >= 201703L
  1579. EXPECT_EQ("42", fmt::format(FMT_STRING(with_null), 42));
  1580. EXPECT_EQ("42", fmt::format(FMT_STRING(no_null), 42));
  1581. #endif
  1582. #if defined(FMT_USE_STRING_VIEW) && __cplusplus >= 201703L
  1583. EXPECT_EQ("42", fmt::format(FMT_STRING(std::string_view("{}")), 42));
  1584. EXPECT_EQ(L"42", fmt::format(FMT_STRING(std::wstring_view(L"{}")), 42));
  1585. #endif
  1586. }
  1587. TEST(FormatTest, CustomFormatCompileTimeString) {
  1588. EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), Answer()));
  1589. Answer answer;
  1590. EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), answer));
  1591. char buf[10] = {};
  1592. fmt::format_to(buf, FMT_STRING("{}"), answer);
  1593. const Answer const_answer = Answer();
  1594. EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), const_answer));
  1595. }
  1596. #if FMT_USE_USER_DEFINED_LITERALS
  1597. // Passing user-defined literals directly to EXPECT_EQ causes problems
  1598. // with macro argument stringification (#) on some versions of GCC.
  1599. // Workaround: Assing the UDL result to a variable before the macro.
  1600. using namespace fmt::literals;
  1601. TEST(LiteralsTest, Format) {
  1602. auto udl_format = "{}c{}"_format("ab", 1);
  1603. EXPECT_EQ(format("{}c{}", "ab", 1), udl_format);
  1604. auto udl_format_w = L"{}c{}"_format(L"ab", 1);
  1605. EXPECT_EQ(format(L"{}c{}", L"ab", 1), udl_format_w);
  1606. }
  1607. TEST(LiteralsTest, NamedArg) {
  1608. auto udl_a = format("{first}{second}{first}{third}", "first"_a = "abra",
  1609. "second"_a = "cad", "third"_a = 99);
  1610. EXPECT_EQ(format("{first}{second}{first}{third}", fmt::arg("first", "abra"),
  1611. fmt::arg("second", "cad"), fmt::arg("third", 99)),
  1612. udl_a);
  1613. auto udl_a_w = format(L"{first}{second}{first}{third}", L"first"_a = L"abra",
  1614. L"second"_a = L"cad", L"third"_a = 99);
  1615. EXPECT_EQ(
  1616. format(L"{first}{second}{first}{third}", fmt::arg(L"first", L"abra"),
  1617. fmt::arg(L"second", L"cad"), fmt::arg(L"third", 99)),
  1618. udl_a_w);
  1619. }
  1620. TEST(FormatTest, UdlTemplate) {
  1621. EXPECT_EQ("foo", "foo"_format());
  1622. EXPECT_EQ(" 42", "{0:10}"_format(42));
  1623. }
  1624. TEST(FormatTest, UdlPassUserDefinedObjectAsLvalue) {
  1625. Date date(2015, 10, 21);
  1626. EXPECT_EQ("2015-10-21", "{}"_format(date));
  1627. }
  1628. #endif // FMT_USE_USER_DEFINED_LITERALS
  1629. enum TestEnum { A };
  1630. TEST(FormatTest, Enum) { EXPECT_EQ("0", fmt::format("{}", A)); }
  1631. TEST(FormatTest, FormatterNotSpecialized) {
  1632. static_assert(
  1633. !fmt::has_formatter<fmt::formatter<TestEnum>, fmt::format_context>::value,
  1634. "");
  1635. }
  1636. #if FMT_HAS_FEATURE(cxx_strong_enums)
  1637. enum big_enum : unsigned long long { big_enum_value = 5000000000ULL };
  1638. TEST(FormatTest, StrongEnum) {
  1639. EXPECT_EQ("5000000000", fmt::format("{}", big_enum_value));
  1640. }
  1641. #endif
  1642. TEST(FormatTest, NonNullTerminatedFormatString) {
  1643. EXPECT_EQ("42", format(string_view("{}foo", 2), 42));
  1644. }
  1645. struct variant {
  1646. enum { INT, STRING } type;
  1647. explicit variant(int) : type(INT) {}
  1648. explicit variant(const char*) : type(STRING) {}
  1649. };
  1650. FMT_BEGIN_NAMESPACE
  1651. template <> struct formatter<variant> : dynamic_formatter<> {
  1652. auto format(variant value, format_context& ctx) -> decltype(ctx.out()) {
  1653. if (value.type == variant::INT) return dynamic_formatter<>::format(42, ctx);
  1654. return dynamic_formatter<>::format("foo", ctx);
  1655. }
  1656. };
  1657. FMT_END_NAMESPACE
  1658. TEST(FormatTest, DynamicFormatter) {
  1659. auto num = variant(42);
  1660. auto str = variant("foo");
  1661. EXPECT_EQ("42", format("{:d}", num));
  1662. EXPECT_EQ("foo", format("{:s}", str));
  1663. EXPECT_EQ(" 42 foo ", format("{:{}} {:{}}", num, 3, str, 4));
  1664. EXPECT_THROW_MSG(format("{0:{}}", num), format_error,
  1665. "cannot switch from manual to automatic argument indexing");
  1666. EXPECT_THROW_MSG(format("{:{0}}", num), format_error,
  1667. "cannot switch from automatic to manual argument indexing");
  1668. #if FMT_DEPRECATED_NUMERIC_ALIGN
  1669. EXPECT_THROW_MSG(format("{:=}", str), format_error,
  1670. "format specifier requires numeric argument");
  1671. #endif
  1672. EXPECT_THROW_MSG(format("{:+}", str), format_error,
  1673. "format specifier requires numeric argument");
  1674. EXPECT_THROW_MSG(format("{:-}", str), format_error,
  1675. "format specifier requires numeric argument");
  1676. EXPECT_THROW_MSG(format("{: }", str), format_error,
  1677. "format specifier requires numeric argument");
  1678. EXPECT_THROW_MSG(format("{:#}", str), format_error,
  1679. "format specifier requires numeric argument");
  1680. EXPECT_THROW_MSG(format("{:0}", str), format_error,
  1681. "format specifier requires numeric argument");
  1682. EXPECT_THROW_MSG(format("{:.2}", num), format_error,
  1683. "precision not allowed for this argument type");
  1684. }
  1685. namespace adl_test {
  1686. namespace fmt {
  1687. namespace detail {
  1688. struct foo {};
  1689. template <typename, typename OutputIt> void write(OutputIt, foo) = delete;
  1690. } // namespace detail
  1691. } // namespace fmt
  1692. } // namespace adl_test
  1693. FMT_BEGIN_NAMESPACE
  1694. template <>
  1695. struct formatter<adl_test::fmt::detail::foo> : formatter<std::string> {
  1696. template <typename FormatContext>
  1697. auto format(adl_test::fmt::detail::foo, FormatContext& ctx)
  1698. -> decltype(ctx.out()) {
  1699. return formatter<std::string>::format("foo", ctx);
  1700. }
  1701. };
  1702. FMT_END_NAMESPACE
  1703. TEST(FormatTest, ToString) {
  1704. EXPECT_EQ("42", fmt::to_string(42));
  1705. EXPECT_EQ("0x1234", fmt::to_string(reinterpret_cast<void*>(0x1234)));
  1706. EXPECT_EQ("foo", fmt::to_string(adl_test::fmt::detail::foo()));
  1707. }
  1708. TEST(FormatTest, ToWString) { EXPECT_EQ(L"42", fmt::to_wstring(42)); }
  1709. TEST(FormatTest, OutputIterators) {
  1710. std::list<char> out;
  1711. fmt::format_to(std::back_inserter(out), "{}", 42);
  1712. EXPECT_EQ("42", std::string(out.begin(), out.end()));
  1713. std::stringstream s;
  1714. fmt::format_to(std::ostream_iterator<char>(s), "{}", 42);
  1715. EXPECT_EQ("42", s.str());
  1716. }
  1717. TEST(FormatTest, FormattedSize) {
  1718. EXPECT_EQ(2u, fmt::formatted_size("{}", 42));
  1719. }
  1720. TEST(FormatTest, FormatTo) {
  1721. std::vector<char> v;
  1722. fmt::format_to(std::back_inserter(v), "{}", "foo");
  1723. EXPECT_EQ(string_view(v.data(), v.size()), "foo");
  1724. }
  1725. TEST(FormatTest, FormatToN) {
  1726. char buffer[4];
  1727. buffer[3] = 'x';
  1728. auto result = fmt::format_to_n(buffer, 3, "{}", 12345);
  1729. EXPECT_EQ(5u, result.size);
  1730. EXPECT_EQ(buffer + 3, result.out);
  1731. EXPECT_EQ("123x", fmt::string_view(buffer, 4));
  1732. result = fmt::format_to_n(buffer, 3, "{:s}", "foobar");
  1733. EXPECT_EQ(6u, result.size);
  1734. EXPECT_EQ(buffer + 3, result.out);
  1735. EXPECT_EQ("foox", fmt::string_view(buffer, 4));
  1736. buffer[0] = 'x';
  1737. buffer[1] = 'x';
  1738. buffer[2] = 'x';
  1739. result = fmt::format_to_n(buffer, 3, "{}", 'A');
  1740. EXPECT_EQ(1u, result.size);
  1741. EXPECT_EQ(buffer + 1, result.out);
  1742. EXPECT_EQ("Axxx", fmt::string_view(buffer, 4));
  1743. result = fmt::format_to_n(buffer, 3, "{}{} ", 'B', 'C');
  1744. EXPECT_EQ(3u, result.size);
  1745. EXPECT_EQ(buffer + 3, result.out);
  1746. EXPECT_EQ("BC x", fmt::string_view(buffer, 4));
  1747. result = fmt::format_to_n(buffer, 4, "{}", "ABCDE");
  1748. EXPECT_EQ(5u, result.size);
  1749. EXPECT_EQ("ABCD", fmt::string_view(buffer, 4));
  1750. buffer[3] = 'x';
  1751. result = fmt::format_to_n(buffer, 3, "{}", std::string(1000, '*'));
  1752. EXPECT_EQ(1000u, result.size);
  1753. EXPECT_EQ("***x", fmt::string_view(buffer, 4));
  1754. }
  1755. TEST(FormatTest, WideFormatToN) {
  1756. wchar_t buffer[4];
  1757. buffer[3] = L'x';
  1758. auto result = fmt::format_to_n(buffer, 3, L"{}", 12345);
  1759. EXPECT_EQ(5u, result.size);
  1760. EXPECT_EQ(buffer + 3, result.out);
  1761. EXPECT_EQ(L"123x", fmt::wstring_view(buffer, 4));
  1762. buffer[0] = L'x';
  1763. buffer[1] = L'x';
  1764. buffer[2] = L'x';
  1765. result = fmt::format_to_n(buffer, 3, L"{}", L'A');
  1766. EXPECT_EQ(1u, result.size);
  1767. EXPECT_EQ(buffer + 1, result.out);
  1768. EXPECT_EQ(L"Axxx", fmt::wstring_view(buffer, 4));
  1769. result = fmt::format_to_n(buffer, 3, L"{}{} ", L'B', L'C');
  1770. EXPECT_EQ(3u, result.size);
  1771. EXPECT_EQ(buffer + 3, result.out);
  1772. EXPECT_EQ(L"BC x", fmt::wstring_view(buffer, 4));
  1773. }
  1774. struct test_output_iterator {
  1775. char* data;
  1776. using iterator_category = std::output_iterator_tag;
  1777. using value_type = void;
  1778. using difference_type = void;
  1779. using pointer = void;
  1780. using reference = void;
  1781. test_output_iterator& operator++() {
  1782. ++data;
  1783. return *this;
  1784. }
  1785. test_output_iterator operator++(int) {
  1786. auto tmp = *this;
  1787. ++data;
  1788. return tmp;
  1789. }
  1790. char& operator*() { return *data; }
  1791. };
  1792. TEST(FormatTest, FormatToNOutputIterator) {
  1793. char buf[10] = {};
  1794. fmt::format_to_n(test_output_iterator{buf}, 10, "{}", 42);
  1795. EXPECT_STREQ(buf, "42");
  1796. }
  1797. #if FMT_USE_CONSTEXPR
  1798. struct test_arg_id_handler {
  1799. enum result { NONE, EMPTY, INDEX, NAME, ERROR };
  1800. result res = NONE;
  1801. int index = 0;
  1802. string_view name;
  1803. FMT_CONSTEXPR void operator()() { res = EMPTY; }
  1804. FMT_CONSTEXPR void operator()(int i) {
  1805. res = INDEX;
  1806. index = i;
  1807. }
  1808. FMT_CONSTEXPR void operator()(string_view n) {
  1809. res = NAME;
  1810. name = n;
  1811. }
  1812. FMT_CONSTEXPR void on_error(const char*) { res = ERROR; }
  1813. };
  1814. template <size_t N>
  1815. FMT_CONSTEXPR test_arg_id_handler parse_arg_id(const char (&s)[N]) {
  1816. test_arg_id_handler h;
  1817. fmt::detail::parse_arg_id(s, s + N, h);
  1818. return h;
  1819. }
  1820. TEST(FormatTest, ConstexprParseArgID) {
  1821. static_assert(parse_arg_id(":").res == test_arg_id_handler::EMPTY, "");
  1822. static_assert(parse_arg_id("}").res == test_arg_id_handler::EMPTY, "");
  1823. static_assert(parse_arg_id("42:").res == test_arg_id_handler::INDEX, "");
  1824. static_assert(parse_arg_id("42:").index == 42, "");
  1825. static_assert(parse_arg_id("foo:").res == test_arg_id_handler::NAME, "");
  1826. static_assert(parse_arg_id("foo:").name.size() == 3, "");
  1827. static_assert(parse_arg_id("!").res == test_arg_id_handler::ERROR, "");
  1828. }
  1829. struct test_format_specs_handler {
  1830. enum Result { NONE, PLUS, MINUS, SPACE, HASH, ZERO, ERROR };
  1831. Result res = NONE;
  1832. fmt::align_t align = fmt::align::none;
  1833. char fill = 0;
  1834. int width = 0;
  1835. fmt::detail::arg_ref<char> width_ref;
  1836. int precision = 0;
  1837. fmt::detail::arg_ref<char> precision_ref;
  1838. char type = 0;
  1839. // Workaround for MSVC2017 bug that results in "expression did not evaluate
  1840. // to a constant" with compiler-generated copy ctor.
  1841. FMT_CONSTEXPR test_format_specs_handler() {}
  1842. FMT_CONSTEXPR test_format_specs_handler(
  1843. const test_format_specs_handler& other)
  1844. : res(other.res),
  1845. align(other.align),
  1846. fill(other.fill),
  1847. width(other.width),
  1848. width_ref(other.width_ref),
  1849. precision(other.precision),
  1850. precision_ref(other.precision_ref),
  1851. type(other.type) {}
  1852. FMT_CONSTEXPR void on_align(fmt::align_t a) { align = a; }
  1853. FMT_CONSTEXPR void on_fill(fmt::string_view f) { fill = f[0]; }
  1854. FMT_CONSTEXPR void on_plus() { res = PLUS; }
  1855. FMT_CONSTEXPR void on_minus() { res = MINUS; }
  1856. FMT_CONSTEXPR void on_space() { res = SPACE; }
  1857. FMT_CONSTEXPR void on_hash() { res = HASH; }
  1858. FMT_CONSTEXPR void on_zero() { res = ZERO; }
  1859. FMT_CONSTEXPR void on_width(int w) { width = w; }
  1860. FMT_CONSTEXPR void on_dynamic_width(fmt::detail::auto_id) {}
  1861. FMT_CONSTEXPR void on_dynamic_width(int index) { width_ref = index; }
  1862. FMT_CONSTEXPR void on_dynamic_width(string_view) {}
  1863. FMT_CONSTEXPR void on_precision(int p) { precision = p; }
  1864. FMT_CONSTEXPR void on_dynamic_precision(fmt::detail::auto_id) {}
  1865. FMT_CONSTEXPR void on_dynamic_precision(int index) { precision_ref = index; }
  1866. FMT_CONSTEXPR void on_dynamic_precision(string_view) {}
  1867. FMT_CONSTEXPR void end_precision() {}
  1868. FMT_CONSTEXPR void on_type(char t) { type = t; }
  1869. FMT_CONSTEXPR void on_error(const char*) { res = ERROR; }
  1870. };
  1871. template <size_t N>
  1872. FMT_CONSTEXPR test_format_specs_handler parse_test_specs(const char (&s)[N]) {
  1873. test_format_specs_handler h;
  1874. fmt::detail::parse_format_specs(s, s + N, h);
  1875. return h;
  1876. }
  1877. TEST(FormatTest, ConstexprParseFormatSpecs) {
  1878. typedef test_format_specs_handler handler;
  1879. static_assert(parse_test_specs("<").align == fmt::align::left, "");
  1880. static_assert(parse_test_specs("*^").fill == '*', "");
  1881. static_assert(parse_test_specs("+").res == handler::PLUS, "");
  1882. static_assert(parse_test_specs("-").res == handler::MINUS, "");
  1883. static_assert(parse_test_specs(" ").res == handler::SPACE, "");
  1884. static_assert(parse_test_specs("#").res == handler::HASH, "");
  1885. static_assert(parse_test_specs("0").res == handler::ZERO, "");
  1886. static_assert(parse_test_specs("42").width == 42, "");
  1887. static_assert(parse_test_specs("{42}").width_ref.val.index == 42, "");
  1888. static_assert(parse_test_specs(".42").precision == 42, "");
  1889. static_assert(parse_test_specs(".{42}").precision_ref.val.index == 42, "");
  1890. static_assert(parse_test_specs("d").type == 'd', "");
  1891. static_assert(parse_test_specs("{<").res == handler::ERROR, "");
  1892. }
  1893. struct test_parse_context {
  1894. typedef char char_type;
  1895. FMT_CONSTEXPR int next_arg_id() { return 11; }
  1896. template <typename Id> FMT_CONSTEXPR void check_arg_id(Id) {}
  1897. FMT_CONSTEXPR const char* begin() { return nullptr; }
  1898. FMT_CONSTEXPR const char* end() { return nullptr; }
  1899. void on_error(const char*) {}
  1900. };
  1901. struct test_context {
  1902. using char_type = char;
  1903. using format_arg = fmt::basic_format_arg<test_context>;
  1904. using parse_context_type = fmt::format_parse_context;
  1905. template <typename T> struct formatter_type {
  1906. typedef fmt::formatter<T, char_type> type;
  1907. };
  1908. template <typename Id>
  1909. FMT_CONSTEXPR fmt::basic_format_arg<test_context> arg(Id id) {
  1910. return fmt::detail::make_arg<test_context>(id);
  1911. }
  1912. void on_error(const char*) {}
  1913. FMT_CONSTEXPR test_context error_handler() { return *this; }
  1914. };
  1915. template <size_t N>
  1916. FMT_CONSTEXPR fmt::format_specs parse_specs(const char (&s)[N]) {
  1917. auto specs = fmt::format_specs();
  1918. auto parse_ctx = test_parse_context();
  1919. auto ctx = test_context();
  1920. fmt::detail::specs_handler<test_parse_context, test_context> h(
  1921. specs, parse_ctx, ctx);
  1922. parse_format_specs(s, s + N, h);
  1923. return specs;
  1924. }
  1925. TEST(FormatTest, ConstexprSpecsHandler) {
  1926. static_assert(parse_specs("<").align == fmt::align::left, "");
  1927. static_assert(parse_specs("*^").fill[0] == '*', "");
  1928. static_assert(parse_specs("+").sign == fmt::sign::plus, "");
  1929. static_assert(parse_specs("-").sign == fmt::sign::minus, "");
  1930. static_assert(parse_specs(" ").sign == fmt::sign::space, "");
  1931. static_assert(parse_specs("#").alt, "");
  1932. static_assert(parse_specs("0").align == fmt::align::numeric, "");
  1933. static_assert(parse_specs("42").width == 42, "");
  1934. static_assert(parse_specs("{}").width == 11, "");
  1935. static_assert(parse_specs("{22}").width == 22, "");
  1936. static_assert(parse_specs(".42").precision == 42, "");
  1937. static_assert(parse_specs(".{}").precision == 11, "");
  1938. static_assert(parse_specs(".{22}").precision == 22, "");
  1939. static_assert(parse_specs("d").type == 'd', "");
  1940. }
  1941. template <size_t N>
  1942. FMT_CONSTEXPR fmt::detail::dynamic_format_specs<char> parse_dynamic_specs(
  1943. const char (&s)[N]) {
  1944. fmt::detail::dynamic_format_specs<char> specs;
  1945. test_parse_context ctx{};
  1946. fmt::detail::dynamic_specs_handler<test_parse_context> h(specs, ctx);
  1947. parse_format_specs(s, s + N, h);
  1948. return specs;
  1949. }
  1950. TEST(FormatTest, ConstexprDynamicSpecsHandler) {
  1951. static_assert(parse_dynamic_specs("<").align == fmt::align::left, "");
  1952. static_assert(parse_dynamic_specs("*^").fill[0] == '*', "");
  1953. static_assert(parse_dynamic_specs("+").sign == fmt::sign::plus, "");
  1954. static_assert(parse_dynamic_specs("-").sign == fmt::sign::minus, "");
  1955. static_assert(parse_dynamic_specs(" ").sign == fmt::sign::space, "");
  1956. static_assert(parse_dynamic_specs("#").alt, "");
  1957. static_assert(parse_dynamic_specs("0").align == fmt::align::numeric, "");
  1958. static_assert(parse_dynamic_specs("42").width == 42, "");
  1959. static_assert(parse_dynamic_specs("{}").width_ref.val.index == 11, "");
  1960. static_assert(parse_dynamic_specs("{42}").width_ref.val.index == 42, "");
  1961. static_assert(parse_dynamic_specs(".42").precision == 42, "");
  1962. static_assert(parse_dynamic_specs(".{}").precision_ref.val.index == 11, "");
  1963. static_assert(parse_dynamic_specs(".{42}").precision_ref.val.index == 42, "");
  1964. static_assert(parse_dynamic_specs("d").type == 'd', "");
  1965. }
  1966. template <size_t N>
  1967. FMT_CONSTEXPR test_format_specs_handler check_specs(const char (&s)[N]) {
  1968. fmt::detail::specs_checker<test_format_specs_handler> checker(
  1969. test_format_specs_handler(), fmt::detail::type::double_type);
  1970. parse_format_specs(s, s + N, checker);
  1971. return checker;
  1972. }
  1973. TEST(FormatTest, ConstexprSpecsChecker) {
  1974. typedef test_format_specs_handler handler;
  1975. static_assert(check_specs("<").align == fmt::align::left, "");
  1976. static_assert(check_specs("*^").fill == '*', "");
  1977. static_assert(check_specs("+").res == handler::PLUS, "");
  1978. static_assert(check_specs("-").res == handler::MINUS, "");
  1979. static_assert(check_specs(" ").res == handler::SPACE, "");
  1980. static_assert(check_specs("#").res == handler::HASH, "");
  1981. static_assert(check_specs("0").res == handler::ZERO, "");
  1982. static_assert(check_specs("42").width == 42, "");
  1983. static_assert(check_specs("{42}").width_ref.val.index == 42, "");
  1984. static_assert(check_specs(".42").precision == 42, "");
  1985. static_assert(check_specs(".{42}").precision_ref.val.index == 42, "");
  1986. static_assert(check_specs("d").type == 'd', "");
  1987. static_assert(check_specs("{<").res == handler::ERROR, "");
  1988. }
  1989. struct test_format_string_handler {
  1990. FMT_CONSTEXPR void on_text(const char*, const char*) {}
  1991. FMT_CONSTEXPR int on_arg_id() { return 0; }
  1992. template <typename T> FMT_CONSTEXPR int on_arg_id(T) { return 0; }
  1993. FMT_CONSTEXPR void on_replacement_field(int, const char*) {}
  1994. FMT_CONSTEXPR const char* on_format_specs(int, const char* begin,
  1995. const char*) {
  1996. return begin;
  1997. }
  1998. FMT_CONSTEXPR void on_error(const char*) { error = true; }
  1999. bool error = false;
  2000. };
  2001. template <size_t N> FMT_CONSTEXPR bool parse_string(const char (&s)[N]) {
  2002. test_format_string_handler h;
  2003. fmt::detail::parse_format_string<true>(fmt::string_view(s, N - 1), h);
  2004. return !h.error;
  2005. }
  2006. TEST(FormatTest, ConstexprParseFormatString) {
  2007. static_assert(parse_string("foo"), "");
  2008. static_assert(!parse_string("}"), "");
  2009. static_assert(parse_string("{}"), "");
  2010. static_assert(parse_string("{42}"), "");
  2011. static_assert(parse_string("{foo}"), "");
  2012. static_assert(parse_string("{:}"), "");
  2013. }
  2014. struct test_error_handler {
  2015. const char*& error;
  2016. FMT_CONSTEXPR test_error_handler(const char*& err) : error(err) {}
  2017. FMT_CONSTEXPR test_error_handler(const test_error_handler& other)
  2018. : error(other.error) {}
  2019. FMT_CONSTEXPR void on_error(const char* message) {
  2020. if (!error) error = message;
  2021. }
  2022. };
  2023. FMT_CONSTEXPR size_t len(const char* s) {
  2024. size_t len = 0;
  2025. while (*s++) ++len;
  2026. return len;
  2027. }
  2028. FMT_CONSTEXPR bool equal(const char* s1, const char* s2) {
  2029. if (!s1 || !s2) return s1 == s2;
  2030. while (*s1 && *s1 == *s2) {
  2031. ++s1;
  2032. ++s2;
  2033. }
  2034. return *s1 == *s2;
  2035. }
  2036. template <typename... Args>
  2037. FMT_CONSTEXPR bool test_error(const char* fmt, const char* expected_error) {
  2038. const char* actual_error = nullptr;
  2039. string_view s(fmt, len(fmt));
  2040. fmt::detail::format_string_checker<char, test_error_handler, Args...> checker(
  2041. s, test_error_handler(actual_error));
  2042. fmt::detail::parse_format_string<true>(s, checker);
  2043. return equal(actual_error, expected_error);
  2044. }
  2045. # define EXPECT_ERROR_NOARGS(fmt, error) \
  2046. static_assert(test_error(fmt, error), "")
  2047. # define EXPECT_ERROR(fmt, error, ...) \
  2048. static_assert(test_error<__VA_ARGS__>(fmt, error), "")
  2049. TEST(FormatTest, FormatStringErrors) {
  2050. EXPECT_ERROR_NOARGS("foo", nullptr);
  2051. EXPECT_ERROR_NOARGS("}", "unmatched '}' in format string");
  2052. EXPECT_ERROR("{0:s", "unknown format specifier", Date);
  2053. # if !FMT_MSC_VER || FMT_MSC_VER >= 1916
  2054. // This causes an detail compiler error in MSVC2017.
  2055. EXPECT_ERROR("{:{<}", "invalid fill character '{'", int);
  2056. EXPECT_ERROR("{:10000000000}", "number is too big", int);
  2057. EXPECT_ERROR("{:.10000000000}", "number is too big", int);
  2058. EXPECT_ERROR_NOARGS("{:x}", "argument not found");
  2059. # if FMT_DEPRECATED_NUMERIC_ALIGN
  2060. EXPECT_ERROR("{0:=5", "unknown format specifier", int);
  2061. EXPECT_ERROR("{:=}", "format specifier requires numeric argument",
  2062. const char*);
  2063. # endif
  2064. EXPECT_ERROR("{:+}", "format specifier requires numeric argument",
  2065. const char*);
  2066. EXPECT_ERROR("{:-}", "format specifier requires numeric argument",
  2067. const char*);
  2068. EXPECT_ERROR("{:#}", "format specifier requires numeric argument",
  2069. const char*);
  2070. EXPECT_ERROR("{: }", "format specifier requires numeric argument",
  2071. const char*);
  2072. EXPECT_ERROR("{:0}", "format specifier requires numeric argument",
  2073. const char*);
  2074. EXPECT_ERROR("{:+}", "format specifier requires signed argument", unsigned);
  2075. EXPECT_ERROR("{:-}", "format specifier requires signed argument", unsigned);
  2076. EXPECT_ERROR("{: }", "format specifier requires signed argument", unsigned);
  2077. EXPECT_ERROR("{:{}}", "argument not found", int);
  2078. EXPECT_ERROR("{:.{}}", "argument not found", double);
  2079. EXPECT_ERROR("{:.2}", "precision not allowed for this argument type", int);
  2080. EXPECT_ERROR("{:s}", "invalid type specifier", int);
  2081. EXPECT_ERROR("{:s}", "invalid type specifier", bool);
  2082. EXPECT_ERROR("{:s}", "invalid type specifier", char);
  2083. EXPECT_ERROR("{:+}", "invalid format specifier for char", char);
  2084. EXPECT_ERROR("{:s}", "invalid type specifier", double);
  2085. EXPECT_ERROR("{:d}", "invalid type specifier", const char*);
  2086. EXPECT_ERROR("{:d}", "invalid type specifier", std::string);
  2087. EXPECT_ERROR("{:s}", "invalid type specifier", void*);
  2088. # else
  2089. fmt::print("warning: constexpr is broken in this version of MSVC\n");
  2090. # endif
  2091. EXPECT_ERROR("{foo", "compile-time checks don't support named arguments",
  2092. int);
  2093. EXPECT_ERROR_NOARGS("{10000000000}", "number is too big");
  2094. EXPECT_ERROR_NOARGS("{0x}", "invalid format string");
  2095. EXPECT_ERROR_NOARGS("{-}", "invalid format string");
  2096. EXPECT_ERROR("{:{0x}}", "invalid format string", int);
  2097. EXPECT_ERROR("{:{-}}", "invalid format string", int);
  2098. EXPECT_ERROR("{:.{0x}}", "invalid format string", int);
  2099. EXPECT_ERROR("{:.{-}}", "invalid format string", int);
  2100. EXPECT_ERROR("{:.x}", "missing precision specifier", int);
  2101. EXPECT_ERROR_NOARGS("{}", "argument not found");
  2102. EXPECT_ERROR("{1}", "argument not found", int);
  2103. EXPECT_ERROR("{1}{}",
  2104. "cannot switch from manual to automatic argument indexing", int,
  2105. int);
  2106. EXPECT_ERROR("{}{1}",
  2107. "cannot switch from automatic to manual argument indexing", int,
  2108. int);
  2109. }
  2110. TEST(FormatTest, VFormatTo) {
  2111. typedef fmt::format_context context;
  2112. fmt::basic_format_arg<context> arg = fmt::detail::make_arg<context>(42);
  2113. fmt::basic_format_args<context> args(&arg, 1);
  2114. std::string s;
  2115. fmt::vformat_to(std::back_inserter(s), "{}", args);
  2116. EXPECT_EQ("42", s);
  2117. s.clear();
  2118. fmt::vformat_to(std::back_inserter(s), FMT_STRING("{}"), args);
  2119. EXPECT_EQ("42", s);
  2120. typedef fmt::wformat_context wcontext;
  2121. fmt::basic_format_arg<wcontext> warg = fmt::detail::make_arg<wcontext>(42);
  2122. fmt::basic_format_args<wcontext> wargs(&warg, 1);
  2123. std::wstring w;
  2124. fmt::vformat_to(std::back_inserter(w), L"{}", wargs);
  2125. EXPECT_EQ(L"42", w);
  2126. w.clear();
  2127. fmt::vformat_to(std::back_inserter(w), FMT_STRING(L"{}"), wargs);
  2128. EXPECT_EQ(L"42", w);
  2129. }
  2130. template <typename T> static std::string FmtToString(const T& t) {
  2131. return fmt::format(FMT_STRING("{}"), t);
  2132. }
  2133. TEST(FormatTest, FmtStringInTemplate) {
  2134. EXPECT_EQ(FmtToString(1), "1");
  2135. EXPECT_EQ(FmtToString(0), "0");
  2136. }
  2137. #endif // FMT_USE_CONSTEXPR
  2138. TEST(FormatTest, CharTraitsIsNotAmbiguous) {
  2139. // Test that we don't inject detail names into the std namespace.
  2140. using namespace std;
  2141. char_traits<char>::char_type c;
  2142. (void)c;
  2143. #if __cplusplus >= 201103L
  2144. std::string s;
  2145. auto lval = begin(s);
  2146. (void)lval;
  2147. #endif
  2148. }
  2149. #if __cplusplus > 201103L
  2150. struct custom_char {
  2151. int value;
  2152. custom_char() = default;
  2153. template <typename T>
  2154. constexpr custom_char(T val) : value(static_cast<int>(val)) {}
  2155. operator int() const { return value; }
  2156. };
  2157. int to_ascii(custom_char c) { return c; }
  2158. FMT_BEGIN_NAMESPACE
  2159. template <> struct is_char<custom_char> : std::true_type {};
  2160. FMT_END_NAMESPACE
  2161. TEST(FormatTest, FormatCustomChar) {
  2162. const custom_char format[] = {'{', '}', 0};
  2163. auto result = fmt::format(format, custom_char('x'));
  2164. EXPECT_EQ(result.size(), 1);
  2165. EXPECT_EQ(result[0], custom_char('x'));
  2166. }
  2167. #endif
  2168. // Convert a char8_t string to std::string. Otherwise GTest will insist on
  2169. // inserting `char8_t` NTBS into a `char` stream which is disabled by P1423.
  2170. template <typename S> std::string from_u8str(const S& str) {
  2171. return std::string(str.begin(), str.end());
  2172. }
  2173. TEST(FormatTest, FormatUTF8Precision) {
  2174. using str_type = std::basic_string<fmt::detail::char8_type>;
  2175. str_type format(reinterpret_cast<const fmt::detail::char8_type*>(u8"{:.4}"));
  2176. str_type str(reinterpret_cast<const fmt::detail::char8_type*>(
  2177. u8"caf\u00e9s")); // cafés
  2178. auto result = fmt::format(format, str);
  2179. EXPECT_EQ(fmt::detail::count_code_points(result), 4);
  2180. EXPECT_EQ(result.size(), 5);
  2181. EXPECT_EQ(from_u8str(result), from_u8str(str.substr(0, 5)));
  2182. }
  2183. struct check_back_appender {};
  2184. FMT_BEGIN_NAMESPACE
  2185. template <> struct formatter<check_back_appender> {
  2186. template <typename ParseContext>
  2187. auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
  2188. return ctx.begin();
  2189. }
  2190. template <typename Context>
  2191. auto format(check_back_appender, Context& ctx) -> decltype(ctx.out()) {
  2192. auto out = ctx.out();
  2193. static_assert(std::is_same<decltype(++out), decltype(out)&>::value,
  2194. "needs to satisfy weakly_incrementable");
  2195. *out = 'y';
  2196. return ++out;
  2197. }
  2198. };
  2199. FMT_END_NAMESPACE
  2200. TEST(FormatTest, BackInsertSlicing) {
  2201. EXPECT_EQ(fmt::format("{}", check_back_appender{}), "y");
  2202. }