format-test.cc 92 KB

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