format-test.cc 96 KB

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