1 /* 2 Formatting library for C++ 3 4 Copyright (c) 2012 - 2016, Victor Zverovich 5 All rights reserved. 6 7 Redistribution and use in source and binary forms, with or without 8 modification, are permitted provided that the following conditions are met: 9 10 1. Redistributions of source code must retain the above copyright notice, this 11 list of conditions and the following disclaimer. 12 2. Redistributions in binary form must reproduce the above copyright notice, 13 this list of conditions and the following disclaimer in the documentation 14 and/or other materials provided with the distribution. 15 16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 20 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 */ 27 28 #ifndef FMT_FORMAT_H_ 29 #define FMT_FORMAT_H_ 30 31 #include <cassert> 32 #include <clocale> 33 #include <cmath> 34 #include <cstdio> 35 #include <cstring> 36 #include <limits> 37 #include <memory> 38 #include <stdexcept> 39 #include <string> 40 #include <vector> 41 #include <utility> 42 43 #ifdef _SECURE_SCL 44 # define FMT_SECURE_SCL _SECURE_SCL 45 #else 46 # define FMT_SECURE_SCL 0 47 #endif 48 49 #if FMT_SECURE_SCL 50 # include <iterator> 51 #endif 52 53 #ifdef _MSC_VER 54 # define FMT_MSC_VER _MSC_VER 55 #else 56 # define FMT_MSC_VER 0 57 #endif 58 59 #if FMT_MSC_VER && FMT_MSC_VER <= 1500 60 typedef unsigned __int32 uint32_t; 61 typedef unsigned __int64 uint64_t; 62 typedef __int64 intmax_t; 63 #else 64 #include <stdint.h> 65 #endif 66 67 #if !defined(FMT_HEADER_ONLY) && defined(_WIN32) 68 # ifdef FMT_EXPORT 69 # define FMT_API __declspec(dllexport) 70 # elif defined(FMT_SHARED) 71 # define FMT_API __declspec(dllimport) 72 # endif 73 #endif 74 #ifndef FMT_API 75 # define FMT_API 76 #endif 77 78 #ifdef __GNUC__ 79 # define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) 80 # define FMT_GCC_EXTENSION __extension__ 81 # if FMT_GCC_VERSION >= 406 82 # pragma GCC diagnostic push 83 // Disable the warning about "long long" which is sometimes reported even 84 // when using __extension__. 85 # pragma GCC diagnostic ignored "-Wlong-long" 86 // Disable the warning about declaration shadowing because it affects too 87 // many valid cases. 88 # pragma GCC diagnostic ignored "-Wshadow" 89 // Disable the warning about implicit conversions that may change the sign of 90 // an integer; silencing it otherwise would require many explicit casts. 91 # pragma GCC diagnostic ignored "-Wsign-conversion" 92 # endif 93 # if __cplusplus >= 201103L || defined __GXX_EXPERIMENTAL_CXX0X__ 94 # define FMT_HAS_GXX_CXX11 1 95 # endif 96 #else 97 # define FMT_GCC_EXTENSION 98 #endif 99 100 #if defined(__INTEL_COMPILER) 101 # define FMT_ICC_VERSION __INTEL_COMPILER 102 #elif defined(__ICL) 103 # define FMT_ICC_VERSION __ICL 104 #endif 105 106 #if defined(__clang__) && !defined(FMT_ICC_VERSION) 107 # pragma clang diagnostic push 108 # pragma clang diagnostic ignored "-Wdocumentation-unknown-command" 109 # pragma clang diagnostic ignored "-Wpadded" 110 #endif 111 112 #ifdef __GNUC_LIBSTD__ 113 # define FMT_GNUC_LIBSTD_VERSION (__GNUC_LIBSTD__ * 100 + __GNUC_LIBSTD_MINOR__) 114 #endif 115 116 #ifdef __has_feature 117 # define FMT_HAS_FEATURE(x) __has_feature(x) 118 #else 119 # define FMT_HAS_FEATURE(x) 0 120 #endif 121 122 #ifdef __has_builtin 123 # define FMT_HAS_BUILTIN(x) __has_builtin(x) 124 #else 125 # define FMT_HAS_BUILTIN(x) 0 126 #endif 127 128 #ifdef __has_cpp_attribute 129 # define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) 130 #else 131 # define FMT_HAS_CPP_ATTRIBUTE(x) 0 132 #endif 133 134 #ifndef FMT_USE_VARIADIC_TEMPLATES 135 // Variadic templates are available in GCC since version 4.4 136 // (http://gcc.gnu.org/projects/cxx0x.html) and in Visual C++ 137 // since version 2013. 138 # define FMT_USE_VARIADIC_TEMPLATES \ 139 (FMT_HAS_FEATURE(cxx_variadic_templates) || \ 140 (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1800) 141 #endif 142 143 #ifndef FMT_USE_RVALUE_REFERENCES 144 // Don't use rvalue references when compiling with clang and an old libstdc++ 145 // as the latter doesn't provide std::move. 146 # if defined(FMT_GNUC_LIBSTD_VERSION) && FMT_GNUC_LIBSTD_VERSION <= 402 147 # define FMT_USE_RVALUE_REFERENCES 0 148 # else 149 # define FMT_USE_RVALUE_REFERENCES \ 150 (FMT_HAS_FEATURE(cxx_rvalue_references) || \ 151 (FMT_GCC_VERSION >= 403 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1600) 152 # endif 153 #endif 154 155 #if FMT_USE_RVALUE_REFERENCES 156 # include <utility> // for std::move 157 #endif 158 159 // Check if exceptions are disabled. 160 #if defined(__GNUC__) && !defined(__EXCEPTIONS) 161 # define FMT_EXCEPTIONS 0 162 #endif 163 #if FMT_MSC_VER && !_HAS_EXCEPTIONS 164 # define FMT_EXCEPTIONS 0 165 #endif 166 #ifndef FMT_EXCEPTIONS 167 # define FMT_EXCEPTIONS 1 168 #endif 169 170 #ifndef FMT_THROW 171 # if FMT_EXCEPTIONS 172 # define FMT_THROW(x) throw x 173 # else 174 # define FMT_THROW(x) assert(false) 175 # endif 176 #endif 177 178 // Define FMT_USE_NOEXCEPT to make fmt use noexcept (C++11 feature). 179 #ifndef FMT_USE_NOEXCEPT 180 # define FMT_USE_NOEXCEPT 0 181 #endif 182 183 #ifndef FMT_NOEXCEPT 184 # if FMT_EXCEPTIONS 185 # if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \ 186 (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || \ 187 FMT_MSC_VER >= 1900 188 # define FMT_NOEXCEPT noexcept 189 # else 190 # define FMT_NOEXCEPT throw() 191 # endif 192 # else 193 # define FMT_NOEXCEPT 194 # endif 195 #endif 196 197 #ifndef FMT_OVERRIDE 198 # if FMT_USE_OVERRIDE || FMT_HAS_FEATURE(cxx_override) || \ 199 (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || \ 200 FMT_MSC_VER >= 1900 201 # define FMT_OVERRIDE override 202 # else 203 # define FMT_OVERRIDE 204 # endif 205 #endif 206 207 208 // A macro to disallow the copy constructor and operator= functions 209 // This should be used in the private: declarations for a class 210 #ifndef FMT_USE_DELETED_FUNCTIONS 211 # define FMT_USE_DELETED_FUNCTIONS 0 212 #endif 213 214 #if FMT_USE_DELETED_FUNCTIONS || FMT_HAS_FEATURE(cxx_deleted_functions) || \ 215 (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1800 216 # define FMT_DELETED_OR_UNDEFINED = delete 217 # define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \ 218 TypeName(const TypeName&) = delete; \ 219 TypeName& operator=(const TypeName&) = delete 220 #else 221 # define FMT_DELETED_OR_UNDEFINED 222 # define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \ 223 TypeName(const TypeName&); \ 224 TypeName& operator=(const TypeName&) 225 #endif 226 227 #ifndef FMT_USE_USER_DEFINED_LITERALS 228 // All compilers which support UDLs also support variadic templates. This 229 // makes the fmt::literals implementation easier. However, an explicit check 230 // for variadic templates is added here just in case. 231 // For Intel's compiler both it and the system gcc/msc must support UDLs. 232 # define FMT_USE_USER_DEFINED_LITERALS \ 233 FMT_USE_VARIADIC_TEMPLATES && FMT_USE_RVALUE_REFERENCES && \ 234 (FMT_HAS_FEATURE(cxx_user_literals) || \ 235 (FMT_GCC_VERSION >= 407 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900) && \ 236 (!defined(FMT_ICC_VERSION) || FMT_ICC_VERSION >= 1500) 237 #endif 238 239 #ifndef FMT_ASSERT 240 # define FMT_ASSERT(condition, message) assert((condition) && message) 241 #endif 242 243 #if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clz) 244 # define FMT_BUILTIN_CLZ(n) __builtin_clz(n) 245 #endif 246 247 #if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clzll) 248 # define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n) 249 #endif 250 251 // Some compilers masquerade as both MSVC and GCC-likes or 252 // otherwise support __builtin_clz and __builtin_clzll, so 253 // only define FMT_BUILTIN_CLZ using the MSVC intrinsics 254 // if the clz and clzll builtins are not available. 255 #if FMT_MSC_VER && !defined(FMT_BUILTIN_CLZLL) 256 # include <intrin.h> // _BitScanReverse, _BitScanReverse64 257 258 namespace fmt { 259 namespace internal { 260 # pragma intrinsic(_BitScanReverse) 261 inline uint32_t clz(uint32_t x) { 262 unsigned long r = 0; 263 _BitScanReverse(&r, x); 264 265 assert(x != 0); 266 // Static analysis complains about using uninitialized data 267 // "r", but the only way that can happen is if "x" is 0, 268 // which the callers guarantee to not happen. 269 # pragma warning(suppress: 6102) 270 return 31 - r; 271 } 272 # define FMT_BUILTIN_CLZ(n) fmt::internal::clz(n) 273 274 # ifdef _WIN64 275 # pragma intrinsic(_BitScanReverse64) 276 # endif 277 278 inline uint32_t clzll(uint64_t x) { 279 unsigned long r = 0; 280 # ifdef _WIN64 281 _BitScanReverse64(&r, x); 282 # else 283 // Scan the high 32 bits. 284 if (_BitScanReverse(&r, static_cast<uint32_t>(x >> 32))) 285 return 63 - (r + 32); 286 287 // Scan the low 32 bits. 288 _BitScanReverse(&r, static_cast<uint32_t>(x)); 289 # endif 290 291 assert(x != 0); 292 // Static analysis complains about using uninitialized data 293 // "r", but the only way that can happen is if "x" is 0, 294 // which the callers guarantee to not happen. 295 # pragma warning(suppress: 6102) 296 return 63 - r; 297 } 298 # define FMT_BUILTIN_CLZLL(n) fmt::internal::clzll(n) 299 } 300 } 301 #endif 302 303 namespace fmt { 304 namespace internal { 305 struct DummyInt { 306 int data[2]; 307 operator int() const { return 0; } 308 }; 309 typedef std::numeric_limits<fmt::internal::DummyInt> FPUtil; 310 311 // Dummy implementations of system functions such as signbit and ecvt called 312 // if the latter are not available. 313 inline DummyInt signbit(...) { return DummyInt(); } 314 inline DummyInt _ecvt_s(...) { return DummyInt(); } 315 inline DummyInt isinf(...) { return DummyInt(); } 316 inline DummyInt _finite(...) { return DummyInt(); } 317 inline DummyInt isnan(...) { return DummyInt(); } 318 inline DummyInt _isnan(...) { return DummyInt(); } 319 320 // A helper function to suppress bogus "conditional expression is constant" 321 // warnings. 322 template <typename T> 323 inline T const_check(T value) { return value; } 324 } 325 } // namespace fmt 326 327 namespace std { 328 // Standard permits specialization of std::numeric_limits. This specialization 329 // is used to resolve ambiguity between isinf and std::isinf in glibc: 330 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=48891 331 // and the same for isnan and signbit. 332 template <> 333 class numeric_limits<fmt::internal::DummyInt> : 334 public std::numeric_limits<int> { 335 public: 336 // Portable version of isinf. 337 template <typename T> 338 static bool isinfinity(T x) { 339 using namespace fmt::internal; 340 // The resolution "priority" is: 341 // isinf macro > std::isinf > ::isinf > fmt::internal::isinf 342 if (const_check(sizeof(isinf(x)) == sizeof(bool) || 343 sizeof(isinf(x)) == sizeof(int))) { 344 return isinf(x) != 0; 345 } 346 return !_finite(static_cast<double>(x)); 347 } 348 349 // Portable version of isnan. 350 template <typename T> 351 static bool isnotanumber(T x) { 352 using namespace fmt::internal; 353 if (const_check(sizeof(isnan(x)) == sizeof(bool) || 354 sizeof(isnan(x)) == sizeof(int))) { 355 return isnan(x) != 0; 356 } 357 return _isnan(static_cast<double>(x)) != 0; 358 } 359 360 // Portable version of signbit. 361 static bool isnegative(double x) { 362 using namespace fmt::internal; 363 if (const_check(sizeof(signbit(x)) == sizeof(int))) 364 return signbit(x) != 0; 365 if (x < 0) return true; 366 if (!isnotanumber(x)) return false; 367 int dec = 0, sign = 0; 368 char buffer[2]; // The buffer size must be >= 2 or _ecvt_s will fail. 369 _ecvt_s(buffer, sizeof(buffer), x, 0, &dec, &sign); 370 return sign != 0; 371 } 372 }; 373 } // namespace std 374 375 namespace fmt { 376 377 // Fix the warning about long long on older versions of GCC 378 // that don't support the diagnostic pragma. 379 FMT_GCC_EXTENSION typedef long long LongLong; 380 FMT_GCC_EXTENSION typedef unsigned long long ULongLong; 381 382 #if FMT_USE_RVALUE_REFERENCES 383 using std::move; 384 #endif 385 386 template <typename Char> 387 class BasicWriter; 388 389 typedef BasicWriter<char> Writer; 390 typedef BasicWriter<wchar_t> WWriter; 391 392 template <typename Char> 393 class ArgFormatter; 394 395 template <typename CharType, 396 typename ArgFormatter = fmt::ArgFormatter<CharType> > 397 class BasicFormatter; 398 399 /** 400 \rst 401 A string reference. It can be constructed from a C string or ``std::string``. 402 403 You can use one of the following typedefs for common character types: 404 405 +------------+-------------------------+ 406 | Type | Definition | 407 +============+=========================+ 408 | StringRef | BasicStringRef<char> | 409 +------------+-------------------------+ 410 | WStringRef | BasicStringRef<wchar_t> | 411 +------------+-------------------------+ 412 413 This class is most useful as a parameter type to allow passing 414 different types of strings to a function, for example:: 415 416 template <typename... Args> 417 std::string format(StringRef format_str, const Args & ... args); 418 419 format("{}", 42); 420 format(std::string("{}"), 42); 421 \endrst 422 */ 423 template <typename Char> 424 class BasicStringRef { 425 private: 426 const Char *data_; 427 std::size_t size_; 428 429 public: 430 /** Constructs a string reference object from a C string and a size. */ 431 BasicStringRef(const Char *s, std::size_t size) : data_(s), size_(size) {} 432 433 /** 434 \rst 435 Constructs a string reference object from a C string computing 436 the size with ``std::char_traits<Char>::length``. 437 \endrst 438 */ 439 BasicStringRef(const Char *s) 440 : data_(s), size_(std::char_traits<Char>::length(s)) {} 441 442 /** 443 \rst 444 Constructs a string reference from an ``std::string`` object. 445 \endrst 446 */ 447 BasicStringRef(const std::basic_string<Char> &s) 448 : data_(s.c_str()), size_(s.size()) {} 449 450 /** 451 \rst 452 Converts a string reference to an ``std::string`` object. 453 \endrst 454 */ 455 std::basic_string<Char> to_string() const { 456 return std::basic_string<Char>(data_, size_); 457 } 458 459 /** 460 \rst 461 Automatically converts a string reference to an ``std::string`` object. 462 \endrst 463 */ 464 operator std::basic_string<Char>() const { 465 return std::basic_string<Char>(data_, size_); 466 } 467 /** Returns a pointer to the string data. */ 468 const Char *data() const { return data_; } 469 470 /** Returns the string size. */ 471 std::size_t size() const { return size_; } 472 473 // Lexicographically compare this string reference to other. 474 int compare(BasicStringRef other) const { 475 std::size_t size = size_ < other.size_ ? size_ : other.size_; 476 int result = std::char_traits<Char>::compare(data_, other.data_, size); 477 if (result == 0) 478 result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1); 479 return result; 480 } 481 482 friend bool operator==(BasicStringRef lhs, BasicStringRef rhs) { 483 return lhs.compare(rhs) == 0; 484 } 485 friend bool operator!=(BasicStringRef lhs, BasicStringRef rhs) { 486 return lhs.compare(rhs) != 0; 487 } 488 friend bool operator<(BasicStringRef lhs, BasicStringRef rhs) { 489 return lhs.compare(rhs) < 0; 490 } 491 friend bool operator<=(BasicStringRef lhs, BasicStringRef rhs) { 492 return lhs.compare(rhs) <= 0; 493 } 494 friend bool operator>(BasicStringRef lhs, BasicStringRef rhs) { 495 return lhs.compare(rhs) > 0; 496 } 497 friend bool operator>=(BasicStringRef lhs, BasicStringRef rhs) { 498 return lhs.compare(rhs) >= 0; 499 } 500 }; 501 502 typedef BasicStringRef<char> StringRef; 503 typedef BasicStringRef<wchar_t> WStringRef; 504 505 /** 506 \rst 507 A reference to a null terminated string. It can be constructed from a C 508 string or ``std::string``. 509 510 You can use one of the following typedefs for common character types: 511 512 +-------------+--------------------------+ 513 | Type | Definition | 514 +=============+==========================+ 515 | CStringRef | BasicCStringRef<char> | 516 +-------------+--------------------------+ 517 | WCStringRef | BasicCStringRef<wchar_t> | 518 +-------------+--------------------------+ 519 520 This class is most useful as a parameter type to allow passing 521 different types of strings to a function, for example:: 522 523 template <typename... Args> 524 std::string format(CStringRef format_str, const Args & ... args); 525 526 format("{}", 42); 527 format(std::string("{}"), 42); 528 \endrst 529 */ 530 template <typename Char> 531 class BasicCStringRef { 532 private: 533 const Char *data_; 534 535 public: 536 /** Constructs a string reference object from a C string. */ 537 BasicCStringRef(const Char *s) : data_(s) {} 538 539 /** 540 \rst 541 Constructs a string reference from an ``std::string`` object. 542 \endrst 543 */ 544 BasicCStringRef(const std::basic_string<Char> &s) : data_(s.c_str()) {} 545 546 /** Returns the pointer to a C string. */ 547 const Char *c_str() const { return data_; } 548 }; 549 550 typedef BasicCStringRef<char> CStringRef; 551 typedef BasicCStringRef<wchar_t> WCStringRef; 552 553 /** A formatting error such as invalid format string. */ 554 class FormatError : public std::runtime_error { 555 public: 556 explicit FormatError(CStringRef message) 557 : std::runtime_error(message.c_str()) {} 558 ~FormatError() throw(); 559 }; 560 561 namespace internal { 562 563 // MakeUnsigned<T>::Type gives an unsigned type corresponding to integer type T. 564 template <typename T> 565 struct MakeUnsigned { typedef T Type; }; 566 567 #define FMT_SPECIALIZE_MAKE_UNSIGNED(T, U) \ 568 template <> \ 569 struct MakeUnsigned<T> { typedef U Type; } 570 571 FMT_SPECIALIZE_MAKE_UNSIGNED(char, unsigned char); 572 FMT_SPECIALIZE_MAKE_UNSIGNED(signed char, unsigned char); 573 FMT_SPECIALIZE_MAKE_UNSIGNED(short, unsigned short); 574 FMT_SPECIALIZE_MAKE_UNSIGNED(int, unsigned); 575 FMT_SPECIALIZE_MAKE_UNSIGNED(long, unsigned long); 576 FMT_SPECIALIZE_MAKE_UNSIGNED(LongLong, ULongLong); 577 578 // Casts nonnegative integer to unsigned. 579 template <typename Int> 580 inline typename MakeUnsigned<Int>::Type to_unsigned(Int value) { 581 FMT_ASSERT(value >= 0, "negative value"); 582 return static_cast<typename MakeUnsigned<Int>::Type>(value); 583 } 584 585 // The number of characters to store in the MemoryBuffer object itself 586 // to avoid dynamic memory allocation. 587 enum { INLINE_BUFFER_SIZE = 500 }; 588 589 #if FMT_SECURE_SCL 590 // Use checked iterator to avoid warnings on MSVC. 591 template <typename T> 592 inline stdext::checked_array_iterator<T*> make_ptr(T *ptr, std::size_t size) { 593 return stdext::checked_array_iterator<T*>(ptr, size); 594 } 595 #else 596 template <typename T> 597 inline T *make_ptr(T *ptr, std::size_t) { return ptr; } 598 #endif 599 } // namespace internal 600 601 /** 602 \rst 603 A buffer supporting a subset of ``std::vector``'s operations. 604 \endrst 605 */ 606 template <typename T> 607 class Buffer { 608 private: 609 FMT_DISALLOW_COPY_AND_ASSIGN(Buffer); 610 611 protected: 612 T *ptr_; 613 std::size_t size_; 614 std::size_t capacity_; 615 616 Buffer(T *ptr = 0, std::size_t capacity = 0) 617 : ptr_(ptr), size_(0), capacity_(capacity) {} 618 619 /** 620 \rst 621 Increases the buffer capacity to hold at least *size* elements updating 622 ``ptr_`` and ``capacity_``. 623 \endrst 624 */ 625 virtual void grow(std::size_t size) = 0; 626 627 public: 628 virtual ~Buffer() {} 629 630 /** Returns the size of this buffer. */ 631 std::size_t size() const { return size_; } 632 633 /** Returns the capacity of this buffer. */ 634 std::size_t capacity() const { return capacity_; } 635 636 /** 637 Resizes the buffer. If T is a POD type new elements may not be initialized. 638 */ 639 void resize(std::size_t new_size) { 640 if (new_size > capacity_) 641 grow(new_size); 642 size_ = new_size; 643 } 644 645 /** 646 \rst 647 Reserves space to store at least *capacity* elements. 648 \endrst 649 */ 650 void reserve(std::size_t capacity) { 651 if (capacity > capacity_) 652 grow(capacity); 653 } 654 655 void clear() FMT_NOEXCEPT { size_ = 0; } 656 657 void push_back(const T &value) { 658 if (size_ == capacity_) 659 grow(size_ + 1); 660 ptr_[size_++] = value; 661 } 662 663 /** Appends data to the end of the buffer. */ 664 template <typename U> 665 void append(const U *begin, const U *end); 666 667 T &operator[](std::size_t index) { return ptr_[index]; } 668 const T &operator[](std::size_t index) const { return ptr_[index]; } 669 }; 670 671 template <typename T> 672 template <typename U> 673 void Buffer<T>::append(const U *begin, const U *end) { 674 std::size_t new_size = size_ + internal::to_unsigned(end - begin); 675 if (new_size > capacity_) 676 grow(new_size); 677 std::uninitialized_copy(begin, end, 678 internal::make_ptr(ptr_, capacity_) + size_); 679 size_ = new_size; 680 } 681 682 namespace internal { 683 684 // A memory buffer for trivially copyable/constructible types with the first 685 // SIZE elements stored in the object itself. 686 template <typename T, std::size_t SIZE, typename Allocator = std::allocator<T> > 687 class MemoryBuffer : private Allocator, public Buffer<T> { 688 private: 689 T data_[SIZE]; 690 691 // Deallocate memory allocated by the buffer. 692 void deallocate() { 693 if (this->ptr_ != data_) Allocator::deallocate(this->ptr_, this->capacity_); 694 } 695 696 protected: 697 void grow(std::size_t size) FMT_OVERRIDE; 698 699 public: 700 explicit MemoryBuffer(const Allocator &alloc = Allocator()) 701 : Allocator(alloc), Buffer<T>(data_, SIZE) {} 702 ~MemoryBuffer() { deallocate(); } 703 704 #if FMT_USE_RVALUE_REFERENCES 705 private: 706 // Move data from other to this buffer. 707 void move(MemoryBuffer &other) { 708 Allocator &this_alloc = *this, &other_alloc = other; 709 this_alloc = std::move(other_alloc); 710 this->size_ = other.size_; 711 this->capacity_ = other.capacity_; 712 if (other.ptr_ == other.data_) { 713 this->ptr_ = data_; 714 std::uninitialized_copy(other.data_, other.data_ + this->size_, 715 make_ptr(data_, this->capacity_)); 716 } else { 717 this->ptr_ = other.ptr_; 718 // Set pointer to the inline array so that delete is not called 719 // when deallocating. 720 other.ptr_ = other.data_; 721 } 722 } 723 724 public: 725 MemoryBuffer(MemoryBuffer &&other) { 726 move(other); 727 } 728 729 MemoryBuffer &operator=(MemoryBuffer &&other) { 730 assert(this != &other); 731 deallocate(); 732 move(other); 733 return *this; 734 } 735 #endif 736 737 // Returns a copy of the allocator associated with this buffer. 738 Allocator get_allocator() const { return *this; } 739 }; 740 741 template <typename T, std::size_t SIZE, typename Allocator> 742 void MemoryBuffer<T, SIZE, Allocator>::grow(std::size_t size) { 743 std::size_t new_capacity = this->capacity_ + this->capacity_ / 2; 744 if (size > new_capacity) 745 new_capacity = size; 746 T *new_ptr = this->allocate(new_capacity); 747 // The following code doesn't throw, so the raw pointer above doesn't leak. 748 std::uninitialized_copy(this->ptr_, this->ptr_ + this->size_, 749 make_ptr(new_ptr, new_capacity)); 750 std::size_t old_capacity = this->capacity_; 751 T *old_ptr = this->ptr_; 752 this->capacity_ = new_capacity; 753 this->ptr_ = new_ptr; 754 // deallocate may throw (at least in principle), but it doesn't matter since 755 // the buffer already uses the new storage and will deallocate it in case 756 // of exception. 757 if (old_ptr != data_) 758 Allocator::deallocate(old_ptr, old_capacity); 759 } 760 761 // A fixed-size buffer. 762 template <typename Char> 763 class FixedBuffer : public fmt::Buffer<Char> { 764 public: 765 FixedBuffer(Char *array, std::size_t size) : fmt::Buffer<Char>(array, size) {} 766 767 protected: 768 FMT_API void grow(std::size_t size); 769 }; 770 771 template <typename Char> 772 class BasicCharTraits { 773 public: 774 #if FMT_SECURE_SCL 775 typedef stdext::checked_array_iterator<Char*> CharPtr; 776 #else 777 typedef Char *CharPtr; 778 #endif 779 static Char cast(int value) { return static_cast<Char>(value); } 780 }; 781 782 template <typename Char> 783 class CharTraits; 784 785 template <> 786 class CharTraits<char> : public BasicCharTraits<char> { 787 private: 788 // Conversion from wchar_t to char is not allowed. 789 static char convert(wchar_t); 790 791 public: 792 static char convert(char value) { return value; } 793 794 // Formats a floating-point number. 795 template <typename T> 796 FMT_API static int format_float(char *buffer, std::size_t size, 797 const char *format, unsigned width, int precision, T value); 798 }; 799 800 template <> 801 class CharTraits<wchar_t> : public BasicCharTraits<wchar_t> { 802 public: 803 static wchar_t convert(char value) { return value; } 804 static wchar_t convert(wchar_t value) { return value; } 805 806 template <typename T> 807 FMT_API static int format_float(wchar_t *buffer, std::size_t size, 808 const wchar_t *format, unsigned width, int precision, T value); 809 }; 810 811 // Checks if a number is negative - used to avoid warnings. 812 template <bool IsSigned> 813 struct SignChecker { 814 template <typename T> 815 static bool is_negative(T value) { return value < 0; } 816 }; 817 818 template <> 819 struct SignChecker<false> { 820 template <typename T> 821 static bool is_negative(T) { return false; } 822 }; 823 824 // Returns true if value is negative, false otherwise. 825 // Same as (value < 0) but doesn't produce warnings if T is an unsigned type. 826 template <typename T> 827 inline bool is_negative(T value) { 828 return SignChecker<std::numeric_limits<T>::is_signed>::is_negative(value); 829 } 830 831 // Selects uint32_t if FitsIn32Bits is true, uint64_t otherwise. 832 template <bool FitsIn32Bits> 833 struct TypeSelector { typedef uint32_t Type; }; 834 835 template <> 836 struct TypeSelector<false> { typedef uint64_t Type; }; 837 838 template <typename T> 839 struct IntTraits { 840 // Smallest of uint32_t and uint64_t that is large enough to represent 841 // all values of T. 842 typedef typename 843 TypeSelector<std::numeric_limits<T>::digits <= 32>::Type MainType; 844 }; 845 846 FMT_API void report_unknown_type(char code, const char *type); 847 848 // Static data is placed in this class template to allow header-only 849 // configuration. 850 template <typename T = void> 851 struct FMT_API BasicData { 852 static const uint32_t POWERS_OF_10_32[]; 853 static const uint64_t POWERS_OF_10_64[]; 854 static const char DIGITS[]; 855 }; 856 857 #ifndef FMT_USE_EXTERN_TEMPLATES 858 // Clang doesn't have a feature check for extern templates so we check 859 // for variadic templates which were introduced in the same version. 860 # define FMT_USE_EXTERN_TEMPLATES (__clang__ && FMT_USE_VARIADIC_TEMPLATES) 861 #endif 862 863 #if FMT_USE_EXTERN_TEMPLATES && !defined(FMT_HEADER_ONLY) 864 extern template struct BasicData<void>; 865 #endif 866 867 typedef BasicData<> Data; 868 869 #ifdef FMT_BUILTIN_CLZLL 870 // Returns the number of decimal digits in n. Leading zeros are not counted 871 // except for n == 0 in which case count_digits returns 1. 872 inline unsigned count_digits(uint64_t n) { 873 // Based on http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10 874 // and the benchmark https://github.com/localvoid/cxx-benchmark-count-digits. 875 int t = (64 - FMT_BUILTIN_CLZLL(n | 1)) * 1233 >> 12; 876 return to_unsigned(t) - (n < Data::POWERS_OF_10_64[t]) + 1; 877 } 878 #else 879 // Fallback version of count_digits used when __builtin_clz is not available. 880 inline unsigned count_digits(uint64_t n) { 881 unsigned count = 1; 882 for (;;) { 883 // Integer division is slow so do it for a group of four digits instead 884 // of for every digit. The idea comes from the talk by Alexandrescu 885 // "Three Optimization Tips for C++". See speed-test for a comparison. 886 if (n < 10) return count; 887 if (n < 100) return count + 1; 888 if (n < 1000) return count + 2; 889 if (n < 10000) return count + 3; 890 n /= 10000u; 891 count += 4; 892 } 893 } 894 #endif 895 896 #ifdef FMT_BUILTIN_CLZ 897 // Optional version of count_digits for better performance on 32-bit platforms. 898 inline unsigned count_digits(uint32_t n) { 899 int t = (32 - FMT_BUILTIN_CLZ(n | 1)) * 1233 >> 12; 900 return to_unsigned(t) - (n < Data::POWERS_OF_10_32[t]) + 1; 901 } 902 #endif 903 904 // A functor that doesn't add a thousands separator. 905 struct NoThousandsSep { 906 template <typename Char> 907 void operator()(Char *) {} 908 }; 909 910 // A functor that adds a thousands separator. 911 class ThousandsSep { 912 private: 913 fmt::StringRef sep_; 914 915 // Index of a decimal digit with the least significant digit having index 0. 916 unsigned digit_index_; 917 918 public: 919 explicit ThousandsSep(fmt::StringRef sep) : sep_(sep), digit_index_(0) {} 920 921 template <typename Char> 922 void operator()(Char *&buffer) { 923 if (++digit_index_ % 3 != 0) 924 return; 925 buffer -= sep_.size(); 926 std::uninitialized_copy(sep_.data(), sep_.data() + sep_.size(), 927 internal::make_ptr(buffer, sep_.size())); 928 } 929 }; 930 931 // Formats a decimal unsigned integer value writing into buffer. 932 // thousands_sep is a functor that is called after writing each char to 933 // add a thousands separator if necessary. 934 template <typename UInt, typename Char, typename ThousandsSep> 935 inline void format_decimal(Char *buffer, UInt value, unsigned num_digits, 936 ThousandsSep thousands_sep) { 937 buffer += num_digits; 938 while (value >= 100) { 939 // Integer division is slow so do it for a group of two digits instead 940 // of for every digit. The idea comes from the talk by Alexandrescu 941 // "Three Optimization Tips for C++". See speed-test for a comparison. 942 unsigned index = static_cast<unsigned>((value % 100) * 2); 943 value /= 100; 944 *--buffer = Data::DIGITS[index + 1]; 945 thousands_sep(buffer); 946 *--buffer = Data::DIGITS[index]; 947 thousands_sep(buffer); 948 } 949 if (value < 10) { 950 *--buffer = static_cast<char>('0' + value); 951 return; 952 } 953 unsigned index = static_cast<unsigned>(value * 2); 954 *--buffer = Data::DIGITS[index + 1]; 955 thousands_sep(buffer); 956 *--buffer = Data::DIGITS[index]; 957 } 958 959 template <typename UInt, typename Char> 960 inline void format_decimal(Char *buffer, UInt value, unsigned num_digits) { 961 return format_decimal(buffer, value, num_digits, NoThousandsSep()); 962 } 963 964 #ifndef _WIN32 965 # define FMT_USE_WINDOWS_H 0 966 #elif !defined(FMT_USE_WINDOWS_H) 967 # define FMT_USE_WINDOWS_H 1 968 #endif 969 970 // Define FMT_USE_WINDOWS_H to 0 to disable use of windows.h. 971 // All the functionality that relies on it will be disabled too. 972 #if FMT_USE_WINDOWS_H 973 // A converter from UTF-8 to UTF-16. 974 // It is only provided for Windows since other systems support UTF-8 natively. 975 class UTF8ToUTF16 { 976 private: 977 MemoryBuffer<wchar_t, INLINE_BUFFER_SIZE> buffer_; 978 979 public: 980 FMT_API explicit UTF8ToUTF16(StringRef s); 981 operator WStringRef() const { return WStringRef(&buffer_[0], size()); } 982 size_t size() const { return buffer_.size() - 1; } 983 const wchar_t *c_str() const { return &buffer_[0]; } 984 std::wstring str() const { return std::wstring(&buffer_[0], size()); } 985 }; 986 987 // A converter from UTF-16 to UTF-8. 988 // It is only provided for Windows since other systems support UTF-8 natively. 989 class UTF16ToUTF8 { 990 private: 991 MemoryBuffer<char, INLINE_BUFFER_SIZE> buffer_; 992 993 public: 994 UTF16ToUTF8() {} 995 FMT_API explicit UTF16ToUTF8(WStringRef s); 996 operator StringRef() const { return StringRef(&buffer_[0], size()); } 997 size_t size() const { return buffer_.size() - 1; } 998 const char *c_str() const { return &buffer_[0]; } 999 std::string str() const { return std::string(&buffer_[0], size()); } 1000 1001 // Performs conversion returning a system error code instead of 1002 // throwing exception on conversion error. This method may still throw 1003 // in case of memory allocation error. 1004 FMT_API int convert(WStringRef s); 1005 }; 1006 1007 FMT_API void format_windows_error(fmt::Writer &out, int error_code, 1008 fmt::StringRef message) FMT_NOEXCEPT; 1009 #endif 1010 1011 FMT_API void format_system_error(fmt::Writer &out, int error_code, 1012 fmt::StringRef message) FMT_NOEXCEPT; 1013 1014 // A formatting argument value. 1015 struct Value { 1016 template <typename Char> 1017 struct StringValue { 1018 const Char *value; 1019 std::size_t size; 1020 }; 1021 1022 typedef void (*FormatFunc)( 1023 void *formatter, const void *arg, void *format_str_ptr); 1024 1025 struct CustomValue { 1026 const void *value; 1027 FormatFunc format; 1028 }; 1029 1030 union { 1031 int int_value; 1032 unsigned uint_value; 1033 LongLong long_long_value; 1034 ULongLong ulong_long_value; 1035 double double_value; 1036 long double long_double_value; 1037 const void *pointer; 1038 StringValue<char> string; 1039 StringValue<signed char> sstring; 1040 StringValue<unsigned char> ustring; 1041 StringValue<wchar_t> wstring; 1042 CustomValue custom; 1043 }; 1044 1045 enum Type { 1046 NONE, NAMED_ARG, 1047 // Integer types should go first, 1048 INT, UINT, LONG_LONG, ULONG_LONG, BOOL, CHAR, LAST_INTEGER_TYPE = CHAR, 1049 // followed by floating-point types. 1050 DOUBLE, LONG_DOUBLE, LAST_NUMERIC_TYPE = LONG_DOUBLE, 1051 CSTRING, STRING, WSTRING, POINTER, CUSTOM 1052 }; 1053 }; 1054 1055 // A formatting argument. It is a trivially copyable/constructible type to 1056 // allow storage in internal::MemoryBuffer. 1057 struct Arg : Value { 1058 Type type; 1059 }; 1060 1061 template <typename Char> 1062 struct NamedArg; 1063 1064 template <typename T = void> 1065 struct Null {}; 1066 1067 // A helper class template to enable or disable overloads taking wide 1068 // characters and strings in MakeValue. 1069 template <typename T, typename Char> 1070 struct WCharHelper { 1071 typedef Null<T> Supported; 1072 typedef T Unsupported; 1073 }; 1074 1075 template <typename T> 1076 struct WCharHelper<T, wchar_t> { 1077 typedef T Supported; 1078 typedef Null<T> Unsupported; 1079 }; 1080 1081 typedef char Yes[1]; 1082 typedef char No[2]; 1083 1084 template <typename T> 1085 T &get(); 1086 1087 // These are non-members to workaround an overload resolution bug in bcc32. 1088 Yes &convert(fmt::ULongLong); 1089 No &convert(...); 1090 1091 template<typename T, bool ENABLE_CONVERSION> 1092 struct ConvertToIntImpl { 1093 enum { value = ENABLE_CONVERSION }; 1094 }; 1095 1096 template<typename T, bool ENABLE_CONVERSION> 1097 struct ConvertToIntImpl2 { 1098 enum { value = false }; 1099 }; 1100 1101 template<typename T> 1102 struct ConvertToIntImpl2<T, true> { 1103 enum { 1104 // Don't convert numeric types. 1105 value = ConvertToIntImpl<T, !std::numeric_limits<T>::is_specialized>::value 1106 }; 1107 }; 1108 1109 template<typename T> 1110 struct ConvertToInt { 1111 enum { enable_conversion = sizeof(convert(get<T>())) == sizeof(Yes) }; 1112 enum { value = ConvertToIntImpl2<T, enable_conversion>::value }; 1113 }; 1114 1115 #define FMT_DISABLE_CONVERSION_TO_INT(Type) \ 1116 template <> \ 1117 struct ConvertToInt<Type> { enum { value = 0 }; } 1118 1119 // Silence warnings about convering float to int. 1120 FMT_DISABLE_CONVERSION_TO_INT(float); 1121 FMT_DISABLE_CONVERSION_TO_INT(double); 1122 FMT_DISABLE_CONVERSION_TO_INT(long double); 1123 1124 template<bool B, class T = void> 1125 struct EnableIf {}; 1126 1127 template<class T> 1128 struct EnableIf<true, T> { typedef T type; }; 1129 1130 template<bool B, class T, class F> 1131 struct Conditional { typedef T type; }; 1132 1133 template<class T, class F> 1134 struct Conditional<false, T, F> { typedef F type; }; 1135 1136 // For bcc32 which doesn't understand ! in template arguments. 1137 template<bool> 1138 struct Not { enum { value = 0 }; }; 1139 1140 template<> 1141 struct Not<false> { enum { value = 1 }; }; 1142 1143 template<typename T, T> struct LConvCheck { 1144 LConvCheck(int) {} 1145 }; 1146 1147 // Returns the thousands separator for the current locale. 1148 // We check if ``lconv`` contains ``thousands_sep`` because on Android 1149 // ``lconv`` is stubbed as an empty struct. 1150 template <typename LConv> 1151 inline StringRef thousands_sep( 1152 LConv *lc, LConvCheck<char *LConv::*, &LConv::thousands_sep> = 0) { 1153 return lc->thousands_sep; 1154 } 1155 1156 inline fmt::StringRef thousands_sep(...) { return ""; } 1157 1158 // Makes an Arg object from any type. 1159 template <typename Formatter> 1160 class MakeValue : public Arg { 1161 public: 1162 typedef typename Formatter::Char Char; 1163 1164 private: 1165 // The following two methods are private to disallow formatting of 1166 // arbitrary pointers. If you want to output a pointer cast it to 1167 // "void *" or "const void *". In particular, this forbids formatting 1168 // of "[const] volatile char *" which is printed as bool by iostreams. 1169 // Do not implement! 1170 template <typename T> 1171 MakeValue(const T *value); 1172 template <typename T> 1173 MakeValue(T *value); 1174 1175 // The following methods are private to disallow formatting of wide 1176 // characters and strings into narrow strings as in 1177 // fmt::format("{}", L"test"); 1178 // To fix this, use a wide format string: fmt::format(L"{}", L"test"). 1179 #if !FMT_MSC_VER || defined(_NATIVE_WCHAR_T_DEFINED) 1180 MakeValue(typename WCharHelper<wchar_t, Char>::Unsupported); 1181 #endif 1182 MakeValue(typename WCharHelper<wchar_t *, Char>::Unsupported); 1183 MakeValue(typename WCharHelper<const wchar_t *, Char>::Unsupported); 1184 MakeValue(typename WCharHelper<const std::wstring &, Char>::Unsupported); 1185 MakeValue(typename WCharHelper<WStringRef, Char>::Unsupported); 1186 1187 void set_string(StringRef str) { 1188 string.value = str.data(); 1189 string.size = str.size(); 1190 } 1191 1192 void set_string(WStringRef str) { 1193 wstring.value = str.data(); 1194 wstring.size = str.size(); 1195 } 1196 1197 // Formats an argument of a custom type, such as a user-defined class. 1198 template <typename T> 1199 static void format_custom_arg( 1200 void *formatter, const void *arg, void *format_str_ptr) { 1201 format(*static_cast<Formatter*>(formatter), 1202 *static_cast<const Char**>(format_str_ptr), 1203 *static_cast<const T*>(arg)); 1204 } 1205 1206 public: 1207 MakeValue() {} 1208 1209 #define FMT_MAKE_VALUE_(Type, field, TYPE, rhs) \ 1210 MakeValue(Type value) { field = rhs; } \ 1211 static uint64_t type(Type) { return Arg::TYPE; } 1212 1213 #define FMT_MAKE_VALUE(Type, field, TYPE) \ 1214 FMT_MAKE_VALUE_(Type, field, TYPE, value) 1215 1216 FMT_MAKE_VALUE(bool, int_value, BOOL) 1217 FMT_MAKE_VALUE(short, int_value, INT) 1218 FMT_MAKE_VALUE(unsigned short, uint_value, UINT) 1219 FMT_MAKE_VALUE(int, int_value, INT) 1220 FMT_MAKE_VALUE(unsigned, uint_value, UINT) 1221 1222 MakeValue(long value) { 1223 // To minimize the number of types we need to deal with, long is 1224 // translated either to int or to long long depending on its size. 1225 if (const_check(sizeof(long) == sizeof(int))) 1226 int_value = static_cast<int>(value); 1227 else 1228 long_long_value = value; 1229 } 1230 static uint64_t type(long) { 1231 return sizeof(long) == sizeof(int) ? Arg::INT : Arg::LONG_LONG; 1232 } 1233 1234 MakeValue(unsigned long value) { 1235 if (const_check(sizeof(unsigned long) == sizeof(unsigned))) 1236 uint_value = static_cast<unsigned>(value); 1237 else 1238 ulong_long_value = value; 1239 } 1240 static uint64_t type(unsigned long) { 1241 return sizeof(unsigned long) == sizeof(unsigned) ? 1242 Arg::UINT : Arg::ULONG_LONG; 1243 } 1244 1245 FMT_MAKE_VALUE(LongLong, long_long_value, LONG_LONG) 1246 FMT_MAKE_VALUE(ULongLong, ulong_long_value, ULONG_LONG) 1247 FMT_MAKE_VALUE(float, double_value, DOUBLE) 1248 FMT_MAKE_VALUE(double, double_value, DOUBLE) 1249 FMT_MAKE_VALUE(long double, long_double_value, LONG_DOUBLE) 1250 FMT_MAKE_VALUE(signed char, int_value, INT) 1251 FMT_MAKE_VALUE(unsigned char, uint_value, UINT) 1252 FMT_MAKE_VALUE(char, int_value, CHAR) 1253 1254 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) 1255 MakeValue(typename WCharHelper<wchar_t, Char>::Supported value) { 1256 int_value = value; 1257 } 1258 static uint64_t type(wchar_t) { return Arg::CHAR; } 1259 #endif 1260 1261 #define FMT_MAKE_STR_VALUE(Type, TYPE) \ 1262 MakeValue(Type value) { set_string(value); } \ 1263 static uint64_t type(Type) { return Arg::TYPE; } 1264 1265 FMT_MAKE_VALUE(char *, string.value, CSTRING) 1266 FMT_MAKE_VALUE(const char *, string.value, CSTRING) 1267 FMT_MAKE_VALUE(signed char *, sstring.value, CSTRING) 1268 FMT_MAKE_VALUE(const signed char *, sstring.value, CSTRING) 1269 FMT_MAKE_VALUE(unsigned char *, ustring.value, CSTRING) 1270 FMT_MAKE_VALUE(const unsigned char *, ustring.value, CSTRING) 1271 FMT_MAKE_STR_VALUE(const std::string &, STRING) 1272 FMT_MAKE_STR_VALUE(StringRef, STRING) 1273 FMT_MAKE_VALUE_(CStringRef, string.value, CSTRING, value.c_str()) 1274 1275 #define FMT_MAKE_WSTR_VALUE(Type, TYPE) \ 1276 MakeValue(typename WCharHelper<Type, Char>::Supported value) { \ 1277 set_string(value); \ 1278 } \ 1279 static uint64_t type(Type) { return Arg::TYPE; } 1280 1281 FMT_MAKE_WSTR_VALUE(wchar_t *, WSTRING) 1282 FMT_MAKE_WSTR_VALUE(const wchar_t *, WSTRING) 1283 FMT_MAKE_WSTR_VALUE(const std::wstring &, WSTRING) 1284 FMT_MAKE_WSTR_VALUE(WStringRef, WSTRING) 1285 1286 FMT_MAKE_VALUE(void *, pointer, POINTER) 1287 FMT_MAKE_VALUE(const void *, pointer, POINTER) 1288 1289 template <typename T> 1290 MakeValue(const T &value, 1291 typename EnableIf<Not< 1292 ConvertToInt<T>::value>::value, int>::type = 0) { 1293 custom.value = &value; 1294 custom.format = &format_custom_arg<T>; 1295 } 1296 1297 template <typename T> 1298 MakeValue(const T &value, 1299 typename EnableIf<ConvertToInt<T>::value, int>::type = 0) { 1300 int_value = value; 1301 } 1302 1303 template <typename T> 1304 static uint64_t type(const T &) { 1305 return ConvertToInt<T>::value ? Arg::INT : Arg::CUSTOM; 1306 } 1307 1308 // Additional template param `Char_` is needed here because make_type always 1309 // uses char. 1310 template <typename Char_> 1311 MakeValue(const NamedArg<Char_> &value) { pointer = &value; } 1312 1313 template <typename Char_> 1314 static uint64_t type(const NamedArg<Char_> &) { return Arg::NAMED_ARG; } 1315 }; 1316 1317 template <typename Formatter> 1318 class MakeArg : public Arg { 1319 public: 1320 MakeArg() { 1321 type = Arg::NONE; 1322 } 1323 1324 template <typename T> 1325 MakeArg(const T &value) 1326 : Arg(MakeValue<Formatter>(value)) { 1327 type = static_cast<Arg::Type>(MakeValue<Formatter>::type(value)); 1328 } 1329 }; 1330 1331 template <typename Char> 1332 struct NamedArg : Arg { 1333 BasicStringRef<Char> name; 1334 1335 template <typename T> 1336 NamedArg(BasicStringRef<Char> argname, const T &value) 1337 : Arg(MakeArg< BasicFormatter<Char> >(value)), name(argname) {} 1338 }; 1339 1340 class RuntimeError : public std::runtime_error { 1341 protected: 1342 RuntimeError() : std::runtime_error("") {} 1343 ~RuntimeError() throw(); 1344 }; 1345 1346 template <typename Char> 1347 class PrintfArgFormatter; 1348 1349 template <typename Char> 1350 class ArgMap; 1351 } // namespace internal 1352 1353 /** An argument list. */ 1354 class ArgList { 1355 private: 1356 // To reduce compiled code size per formatting function call, types of first 1357 // MAX_PACKED_ARGS arguments are passed in the types_ field. 1358 uint64_t types_; 1359 union { 1360 // If the number of arguments is less than MAX_PACKED_ARGS, the argument 1361 // values are stored in values_, otherwise they are stored in args_. 1362 // This is done to reduce compiled code size as storing larger objects 1363 // may require more code (at least on x86-64) even if the same amount of 1364 // data is actually copied to stack. It saves ~10% on the bloat test. 1365 const internal::Value *values_; 1366 const internal::Arg *args_; 1367 }; 1368 1369 internal::Arg::Type type(unsigned index) const { 1370 unsigned shift = index * 4; 1371 uint64_t mask = 0xf; 1372 return static_cast<internal::Arg::Type>( 1373 (types_ & (mask << shift)) >> shift); 1374 } 1375 1376 template <typename Char> 1377 friend class internal::ArgMap; 1378 1379 public: 1380 // Maximum number of arguments with packed types. 1381 enum { MAX_PACKED_ARGS = 16 }; 1382 1383 ArgList() : types_(0) {} 1384 1385 ArgList(ULongLong types, const internal::Value *values) 1386 : types_(types), values_(values) {} 1387 ArgList(ULongLong types, const internal::Arg *args) 1388 : types_(types), args_(args) {} 1389 1390 /** Returns the argument at specified index. */ 1391 internal::Arg operator[](unsigned index) const { 1392 using internal::Arg; 1393 Arg arg; 1394 bool use_values = type(MAX_PACKED_ARGS - 1) == Arg::NONE; 1395 if (index < MAX_PACKED_ARGS) { 1396 Arg::Type arg_type = type(index); 1397 internal::Value &val = arg; 1398 if (arg_type != Arg::NONE) 1399 val = use_values ? values_[index] : args_[index]; 1400 arg.type = arg_type; 1401 return arg; 1402 } 1403 if (use_values) { 1404 // The index is greater than the number of arguments that can be stored 1405 // in values, so return a "none" argument. 1406 arg.type = Arg::NONE; 1407 return arg; 1408 } 1409 for (unsigned i = MAX_PACKED_ARGS; i <= index; ++i) { 1410 if (args_[i].type == Arg::NONE) 1411 return args_[i]; 1412 } 1413 return args_[index]; 1414 } 1415 }; 1416 1417 #define FMT_DISPATCH(call) static_cast<Impl*>(this)->call 1418 1419 /** 1420 \rst 1421 An argument visitor based on the `curiously recurring template pattern 1422 <http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern>`_. 1423 1424 To use `~fmt::ArgVisitor` define a subclass that implements some or all of the 1425 visit methods with the same signatures as the methods in `~fmt::ArgVisitor`, 1426 for example, `~fmt::ArgVisitor::visit_int()`. 1427 Pass the subclass as the *Impl* template parameter. Then calling 1428 `~fmt::ArgVisitor::visit` for some argument will dispatch to a visit method 1429 specific to the argument type. For example, if the argument type is 1430 ``double`` then the `~fmt::ArgVisitor::visit_double()` method of a subclass 1431 will be called. If the subclass doesn't contain a method with this signature, 1432 then a corresponding method of `~fmt::ArgVisitor` will be called. 1433 1434 **Example**:: 1435 1436 class MyArgVisitor : public fmt::ArgVisitor<MyArgVisitor, void> { 1437 public: 1438 void visit_int(int value) { fmt::print("{}", value); } 1439 void visit_double(double value) { fmt::print("{}", value ); } 1440 }; 1441 \endrst 1442 */ 1443 template <typename Impl, typename Result> 1444 class ArgVisitor { 1445 private: 1446 typedef internal::Arg Arg; 1447 1448 public: 1449 void report_unhandled_arg() {} 1450 1451 Result visit_unhandled_arg() { 1452 FMT_DISPATCH(report_unhandled_arg()); 1453 return Result(); 1454 } 1455 1456 /** Visits an ``int`` argument. **/ 1457 Result visit_int(int value) { 1458 return FMT_DISPATCH(visit_any_int(value)); 1459 } 1460 1461 /** Visits a ``long long`` argument. **/ 1462 Result visit_long_long(LongLong value) { 1463 return FMT_DISPATCH(visit_any_int(value)); 1464 } 1465 1466 /** Visits an ``unsigned`` argument. **/ 1467 Result visit_uint(unsigned value) { 1468 return FMT_DISPATCH(visit_any_int(value)); 1469 } 1470 1471 /** Visits an ``unsigned long long`` argument. **/ 1472 Result visit_ulong_long(ULongLong value) { 1473 return FMT_DISPATCH(visit_any_int(value)); 1474 } 1475 1476 /** Visits a ``bool`` argument. **/ 1477 Result visit_bool(bool value) { 1478 return FMT_DISPATCH(visit_any_int(value)); 1479 } 1480 1481 /** Visits a ``char`` or ``wchar_t`` argument. **/ 1482 Result visit_char(int value) { 1483 return FMT_DISPATCH(visit_any_int(value)); 1484 } 1485 1486 /** Visits an argument of any integral type. **/ 1487 template <typename T> 1488 Result visit_any_int(T) { 1489 return FMT_DISPATCH(visit_unhandled_arg()); 1490 } 1491 1492 /** Visits a ``double`` argument. **/ 1493 Result visit_double(double value) { 1494 return FMT_DISPATCH(visit_any_double(value)); 1495 } 1496 1497 /** Visits a ``long double`` argument. **/ 1498 Result visit_long_double(long double value) { 1499 return FMT_DISPATCH(visit_any_double(value)); 1500 } 1501 1502 /** Visits a ``double`` or ``long double`` argument. **/ 1503 template <typename T> 1504 Result visit_any_double(T) { 1505 return FMT_DISPATCH(visit_unhandled_arg()); 1506 } 1507 1508 /** Visits a null-terminated C string (``const char *``) argument. **/ 1509 Result visit_cstring(const char *) { 1510 return FMT_DISPATCH(visit_unhandled_arg()); 1511 } 1512 1513 /** Visits a string argument. **/ 1514 Result visit_string(Arg::StringValue<char>) { 1515 return FMT_DISPATCH(visit_unhandled_arg()); 1516 } 1517 1518 /** Visits a wide string argument. **/ 1519 Result visit_wstring(Arg::StringValue<wchar_t>) { 1520 return FMT_DISPATCH(visit_unhandled_arg()); 1521 } 1522 1523 /** Visits a pointer argument. **/ 1524 Result visit_pointer(const void *) { 1525 return FMT_DISPATCH(visit_unhandled_arg()); 1526 } 1527 1528 /** Visits an argument of a custom (user-defined) type. **/ 1529 Result visit_custom(Arg::CustomValue) { 1530 return FMT_DISPATCH(visit_unhandled_arg()); 1531 } 1532 1533 /** 1534 \rst 1535 Visits an argument dispatching to the appropriate visit method based on 1536 the argument type. For example, if the argument type is ``double`` then 1537 the `~fmt::ArgVisitor::visit_double()` method of the *Impl* class will be 1538 called. 1539 \endrst 1540 */ 1541 Result visit(const Arg &arg) { 1542 switch (arg.type) { 1543 case Arg::NONE: 1544 case Arg::NAMED_ARG: 1545 FMT_ASSERT(false, "invalid argument type"); 1546 break; 1547 case Arg::INT: 1548 return FMT_DISPATCH(visit_int(arg.int_value)); 1549 case Arg::UINT: 1550 return FMT_DISPATCH(visit_uint(arg.uint_value)); 1551 case Arg::LONG_LONG: 1552 return FMT_DISPATCH(visit_long_long(arg.long_long_value)); 1553 case Arg::ULONG_LONG: 1554 return FMT_DISPATCH(visit_ulong_long(arg.ulong_long_value)); 1555 case Arg::BOOL: 1556 return FMT_DISPATCH(visit_bool(arg.int_value != 0)); 1557 case Arg::CHAR: 1558 return FMT_DISPATCH(visit_char(arg.int_value)); 1559 case Arg::DOUBLE: 1560 return FMT_DISPATCH(visit_double(arg.double_value)); 1561 case Arg::LONG_DOUBLE: 1562 return FMT_DISPATCH(visit_long_double(arg.long_double_value)); 1563 case Arg::CSTRING: 1564 return FMT_DISPATCH(visit_cstring(arg.string.value)); 1565 case Arg::STRING: 1566 return FMT_DISPATCH(visit_string(arg.string)); 1567 case Arg::WSTRING: 1568 return FMT_DISPATCH(visit_wstring(arg.wstring)); 1569 case Arg::POINTER: 1570 return FMT_DISPATCH(visit_pointer(arg.pointer)); 1571 case Arg::CUSTOM: 1572 return FMT_DISPATCH(visit_custom(arg.custom)); 1573 } 1574 return Result(); 1575 } 1576 }; 1577 1578 enum Alignment { 1579 ALIGN_DEFAULT, ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTER, ALIGN_NUMERIC 1580 }; 1581 1582 // Flags. 1583 enum { 1584 SIGN_FLAG = 1, PLUS_FLAG = 2, MINUS_FLAG = 4, HASH_FLAG = 8, 1585 CHAR_FLAG = 0x10 // Argument has char type - used in error reporting. 1586 }; 1587 1588 // An empty format specifier. 1589 struct EmptySpec {}; 1590 1591 // A type specifier. 1592 template <char TYPE> 1593 struct TypeSpec : EmptySpec { 1594 Alignment align() const { return ALIGN_DEFAULT; } 1595 unsigned width() const { return 0; } 1596 int precision() const { return -1; } 1597 bool flag(unsigned) const { return false; } 1598 char type() const { return TYPE; } 1599 char fill() const { return ' '; } 1600 }; 1601 1602 // A width specifier. 1603 struct WidthSpec { 1604 unsigned width_; 1605 // Fill is always wchar_t and cast to char if necessary to avoid having 1606 // two specialization of WidthSpec and its subclasses. 1607 wchar_t fill_; 1608 1609 WidthSpec(unsigned width, wchar_t fill) : width_(width), fill_(fill) {} 1610 1611 unsigned width() const { return width_; } 1612 wchar_t fill() const { return fill_; } 1613 }; 1614 1615 // An alignment specifier. 1616 struct AlignSpec : WidthSpec { 1617 Alignment align_; 1618 1619 AlignSpec(unsigned width, wchar_t fill, Alignment align = ALIGN_DEFAULT) 1620 : WidthSpec(width, fill), align_(align) {} 1621 1622 Alignment align() const { return align_; } 1623 1624 int precision() const { return -1; } 1625 }; 1626 1627 // An alignment and type specifier. 1628 template <char TYPE> 1629 struct AlignTypeSpec : AlignSpec { 1630 AlignTypeSpec(unsigned width, wchar_t fill) : AlignSpec(width, fill) {} 1631 1632 bool flag(unsigned) const { return false; } 1633 char type() const { return TYPE; } 1634 }; 1635 1636 // A full format specifier. 1637 struct FormatSpec : AlignSpec { 1638 unsigned flags_; 1639 int precision_; 1640 char type_; 1641 1642 FormatSpec( 1643 unsigned width = 0, char type = 0, wchar_t fill = ' ') 1644 : AlignSpec(width, fill), flags_(0), precision_(-1), type_(type) {} 1645 1646 bool flag(unsigned f) const { return (flags_ & f) != 0; } 1647 int precision() const { return precision_; } 1648 char type() const { return type_; } 1649 }; 1650 1651 // An integer format specifier. 1652 template <typename T, typename SpecT = TypeSpec<0>, typename Char = char> 1653 class IntFormatSpec : public SpecT { 1654 private: 1655 T value_; 1656 1657 public: 1658 IntFormatSpec(T val, const SpecT &spec = SpecT()) 1659 : SpecT(spec), value_(val) {} 1660 1661 T value() const { return value_; } 1662 }; 1663 1664 // A string format specifier. 1665 template <typename Char> 1666 class StrFormatSpec : public AlignSpec { 1667 private: 1668 const Char *str_; 1669 1670 public: 1671 template <typename FillChar> 1672 StrFormatSpec(const Char *str, unsigned width, FillChar fill) 1673 : AlignSpec(width, fill), str_(str) { 1674 internal::CharTraits<Char>::convert(FillChar()); 1675 } 1676 1677 const Char *str() const { return str_; } 1678 }; 1679 1680 /** 1681 Returns an integer format specifier to format the value in base 2. 1682 */ 1683 IntFormatSpec<int, TypeSpec<'b'> > bin(int value); 1684 1685 /** 1686 Returns an integer format specifier to format the value in base 8. 1687 */ 1688 IntFormatSpec<int, TypeSpec<'o'> > oct(int value); 1689 1690 /** 1691 Returns an integer format specifier to format the value in base 16 using 1692 lower-case letters for the digits above 9. 1693 */ 1694 IntFormatSpec<int, TypeSpec<'x'> > hex(int value); 1695 1696 /** 1697 Returns an integer formatter format specifier to format in base 16 using 1698 upper-case letters for the digits above 9. 1699 */ 1700 IntFormatSpec<int, TypeSpec<'X'> > hexu(int value); 1701 1702 /** 1703 \rst 1704 Returns an integer format specifier to pad the formatted argument with the 1705 fill character to the specified width using the default (right) numeric 1706 alignment. 1707 1708 **Example**:: 1709 1710 MemoryWriter out; 1711 out << pad(hex(0xcafe), 8, '0'); 1712 // out.str() == "0000cafe" 1713 1714 \endrst 1715 */ 1716 template <char TYPE_CODE, typename Char> 1717 IntFormatSpec<int, AlignTypeSpec<TYPE_CODE>, Char> pad( 1718 int value, unsigned width, Char fill = ' '); 1719 1720 #define FMT_DEFINE_INT_FORMATTERS(TYPE) \ 1721 inline IntFormatSpec<TYPE, TypeSpec<'b'> > bin(TYPE value) { \ 1722 return IntFormatSpec<TYPE, TypeSpec<'b'> >(value, TypeSpec<'b'>()); \ 1723 } \ 1724 \ 1725 inline IntFormatSpec<TYPE, TypeSpec<'o'> > oct(TYPE value) { \ 1726 return IntFormatSpec<TYPE, TypeSpec<'o'> >(value, TypeSpec<'o'>()); \ 1727 } \ 1728 \ 1729 inline IntFormatSpec<TYPE, TypeSpec<'x'> > hex(TYPE value) { \ 1730 return IntFormatSpec<TYPE, TypeSpec<'x'> >(value, TypeSpec<'x'>()); \ 1731 } \ 1732 \ 1733 inline IntFormatSpec<TYPE, TypeSpec<'X'> > hexu(TYPE value) { \ 1734 return IntFormatSpec<TYPE, TypeSpec<'X'> >(value, TypeSpec<'X'>()); \ 1735 } \ 1736 \ 1737 template <char TYPE_CODE> \ 1738 inline IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE> > pad( \ 1739 IntFormatSpec<TYPE, TypeSpec<TYPE_CODE> > f, unsigned width) { \ 1740 return IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE> >( \ 1741 f.value(), AlignTypeSpec<TYPE_CODE>(width, ' ')); \ 1742 } \ 1743 \ 1744 /* For compatibility with older compilers we provide two overloads for pad, */ \ 1745 /* one that takes a fill character and one that doesn't. In the future this */ \ 1746 /* can be replaced with one overload making the template argument Char */ \ 1747 /* default to char (C++11). */ \ 1748 template <char TYPE_CODE, typename Char> \ 1749 inline IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE>, Char> pad( \ 1750 IntFormatSpec<TYPE, TypeSpec<TYPE_CODE>, Char> f, \ 1751 unsigned width, Char fill) { \ 1752 return IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE>, Char>( \ 1753 f.value(), AlignTypeSpec<TYPE_CODE>(width, fill)); \ 1754 } \ 1755 \ 1756 inline IntFormatSpec<TYPE, AlignTypeSpec<0> > pad( \ 1757 TYPE value, unsigned width) { \ 1758 return IntFormatSpec<TYPE, AlignTypeSpec<0> >( \ 1759 value, AlignTypeSpec<0>(width, ' ')); \ 1760 } \ 1761 \ 1762 template <typename Char> \ 1763 inline IntFormatSpec<TYPE, AlignTypeSpec<0>, Char> pad( \ 1764 TYPE value, unsigned width, Char fill) { \ 1765 return IntFormatSpec<TYPE, AlignTypeSpec<0>, Char>( \ 1766 value, AlignTypeSpec<0>(width, fill)); \ 1767 } 1768 1769 FMT_DEFINE_INT_FORMATTERS(int) 1770 FMT_DEFINE_INT_FORMATTERS(long) 1771 FMT_DEFINE_INT_FORMATTERS(unsigned) 1772 FMT_DEFINE_INT_FORMATTERS(unsigned long) 1773 FMT_DEFINE_INT_FORMATTERS(LongLong) 1774 FMT_DEFINE_INT_FORMATTERS(ULongLong) 1775 1776 /** 1777 \rst 1778 Returns a string formatter that pads the formatted argument with the fill 1779 character to the specified width using the default (left) string alignment. 1780 1781 **Example**:: 1782 1783 std::string s = str(MemoryWriter() << pad("abc", 8)); 1784 // s == "abc " 1785 1786 \endrst 1787 */ 1788 template <typename Char> 1789 inline StrFormatSpec<Char> pad( 1790 const Char *str, unsigned width, Char fill = ' ') { 1791 return StrFormatSpec<Char>(str, width, fill); 1792 } 1793 1794 inline StrFormatSpec<wchar_t> pad( 1795 const wchar_t *str, unsigned width, char fill = ' ') { 1796 return StrFormatSpec<wchar_t>(str, width, fill); 1797 } 1798 1799 namespace internal { 1800 1801 template <typename Char> 1802 class ArgMap { 1803 private: 1804 typedef std::vector< 1805 std::pair<fmt::BasicStringRef<Char>, internal::Arg> > MapType; 1806 typedef typename MapType::value_type Pair; 1807 1808 MapType map_; 1809 1810 public: 1811 FMT_API void init(const ArgList &args); 1812 1813 const internal::Arg* find(const fmt::BasicStringRef<Char> &name) const { 1814 // The list is unsorted, so just return the first matching name. 1815 for (typename MapType::const_iterator it = map_.begin(), end = map_.end(); 1816 it != end; ++it) { 1817 if (it->first == name) 1818 return &it->second; 1819 } 1820 return 0; 1821 } 1822 }; 1823 1824 template <typename Impl, typename Char> 1825 class ArgFormatterBase : public ArgVisitor<Impl, void> { 1826 private: 1827 BasicWriter<Char> &writer_; 1828 FormatSpec &spec_; 1829 1830 FMT_DISALLOW_COPY_AND_ASSIGN(ArgFormatterBase); 1831 1832 void write_pointer(const void *p) { 1833 spec_.flags_ = HASH_FLAG; 1834 spec_.type_ = 'x'; 1835 writer_.write_int(reinterpret_cast<uintptr_t>(p), spec_); 1836 } 1837 1838 protected: 1839 BasicWriter<Char> &writer() { return writer_; } 1840 FormatSpec &spec() { return spec_; } 1841 1842 void write(bool value) { 1843 const char *str_value = value ? "true" : "false"; 1844 Arg::StringValue<char> str = { str_value, std::strlen(str_value) }; 1845 writer_.write_str(str, spec_); 1846 } 1847 1848 void write(const char *value) { 1849 Arg::StringValue<char> str = {value, value != 0 ? std::strlen(value) : 0}; 1850 writer_.write_str(str, spec_); 1851 } 1852 1853 public: 1854 ArgFormatterBase(BasicWriter<Char> &w, FormatSpec &s) 1855 : writer_(w), spec_(s) {} 1856 1857 template <typename T> 1858 void visit_any_int(T value) { writer_.write_int(value, spec_); } 1859 1860 template <typename T> 1861 void visit_any_double(T value) { writer_.write_double(value, spec_); } 1862 1863 void visit_bool(bool value) { 1864 if (spec_.type_) 1865 return visit_any_int(value); 1866 write(value); 1867 } 1868 1869 void visit_char(int value) { 1870 if (spec_.type_ && spec_.type_ != 'c') { 1871 spec_.flags_ |= CHAR_FLAG; 1872 writer_.write_int(value, spec_); 1873 return; 1874 } 1875 if (spec_.align_ == ALIGN_NUMERIC || spec_.flags_ != 0) 1876 FMT_THROW(FormatError("invalid format specifier for char")); 1877 typedef typename BasicWriter<Char>::CharPtr CharPtr; 1878 Char fill = internal::CharTraits<Char>::cast(spec_.fill()); 1879 CharPtr out = CharPtr(); 1880 const unsigned CHAR_SIZE = 1; 1881 if (spec_.width_ > CHAR_SIZE) { 1882 out = writer_.grow_buffer(spec_.width_); 1883 if (spec_.align_ == ALIGN_RIGHT) { 1884 std::uninitialized_fill_n(out, spec_.width_ - CHAR_SIZE, fill); 1885 out += spec_.width_ - CHAR_SIZE; 1886 } else if (spec_.align_ == ALIGN_CENTER) { 1887 out = writer_.fill_padding(out, spec_.width_, 1888 internal::const_check(CHAR_SIZE), fill); 1889 } else { 1890 std::uninitialized_fill_n(out + CHAR_SIZE, 1891 spec_.width_ - CHAR_SIZE, fill); 1892 } 1893 } else { 1894 out = writer_.grow_buffer(CHAR_SIZE); 1895 } 1896 *out = internal::CharTraits<Char>::cast(value); 1897 } 1898 1899 void visit_cstring(const char *value) { 1900 if (spec_.type_ == 'p') 1901 return write_pointer(value); 1902 write(value); 1903 } 1904 1905 void visit_string(Arg::StringValue<char> value) { 1906 writer_.write_str(value, spec_); 1907 } 1908 1909 using ArgVisitor<Impl, void>::visit_wstring; 1910 1911 void visit_wstring(Arg::StringValue<Char> value) { 1912 writer_.write_str(value, spec_); 1913 } 1914 1915 void visit_pointer(const void *value) { 1916 if (spec_.type_ && spec_.type_ != 'p') 1917 report_unknown_type(spec_.type_, "pointer"); 1918 write_pointer(value); 1919 } 1920 }; 1921 1922 class FormatterBase { 1923 private: 1924 ArgList args_; 1925 int next_arg_index_; 1926 1927 // Returns the argument with specified index. 1928 FMT_API Arg do_get_arg(unsigned arg_index, const char *&error); 1929 1930 protected: 1931 const ArgList &args() const { return args_; } 1932 1933 explicit FormatterBase(const ArgList &args) { 1934 args_ = args; 1935 next_arg_index_ = 0; 1936 } 1937 1938 // Returns the next argument. 1939 Arg next_arg(const char *&error) { 1940 if (next_arg_index_ >= 0) 1941 return do_get_arg(internal::to_unsigned(next_arg_index_++), error); 1942 error = "cannot switch from manual to automatic argument indexing"; 1943 return Arg(); 1944 } 1945 1946 // Checks if manual indexing is used and returns the argument with 1947 // specified index. 1948 Arg get_arg(unsigned arg_index, const char *&error) { 1949 return check_no_auto_index(error) ? do_get_arg(arg_index, error) : Arg(); 1950 } 1951 1952 bool check_no_auto_index(const char *&error) { 1953 if (next_arg_index_ > 0) { 1954 error = "cannot switch from automatic to manual argument indexing"; 1955 return false; 1956 } 1957 next_arg_index_ = -1; 1958 return true; 1959 } 1960 1961 template <typename Char> 1962 void write(BasicWriter<Char> &w, const Char *start, const Char *end) { 1963 if (start != end) 1964 w << BasicStringRef<Char>(start, internal::to_unsigned(end - start)); 1965 } 1966 }; 1967 1968 // A printf formatter. 1969 template <typename Char> 1970 class PrintfFormatter : private FormatterBase { 1971 private: 1972 void parse_flags(FormatSpec &spec, const Char *&s); 1973 1974 // Returns the argument with specified index or, if arg_index is equal 1975 // to the maximum unsigned value, the next argument. 1976 Arg get_arg(const Char *s, 1977 unsigned arg_index = (std::numeric_limits<unsigned>::max)()); 1978 1979 // Parses argument index, flags and width and returns the argument index. 1980 unsigned parse_header(const Char *&s, FormatSpec &spec); 1981 1982 public: 1983 explicit PrintfFormatter(const ArgList &args) : FormatterBase(args) {} 1984 FMT_API void format(BasicWriter<Char> &writer, 1985 BasicCStringRef<Char> format_str); 1986 }; 1987 } // namespace internal 1988 1989 /** 1990 \rst 1991 An argument formatter based on the `curiously recurring template pattern 1992 <http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern>`_. 1993 1994 To use `~fmt::BasicArgFormatter` define a subclass that implements some or 1995 all of the visit methods with the same signatures as the methods in 1996 `~fmt::ArgVisitor`, for example, `~fmt::ArgVisitor::visit_int()`. 1997 Pass the subclass as the *Impl* template parameter. When a formatting 1998 function processes an argument, it will dispatch to a visit method 1999 specific to the argument type. For example, if the argument type is 2000 ``double`` then the `~fmt::ArgVisitor::visit_double()` method of a subclass 2001 will be called. If the subclass doesn't contain a method with this signature, 2002 then a corresponding method of `~fmt::BasicArgFormatter` or its superclass 2003 will be called. 2004 \endrst 2005 */ 2006 template <typename Impl, typename Char> 2007 class BasicArgFormatter : public internal::ArgFormatterBase<Impl, Char> { 2008 private: 2009 BasicFormatter<Char, Impl> &formatter_; 2010 const Char *format_; 2011 2012 public: 2013 /** 2014 \rst 2015 Constructs an argument formatter object. 2016 *formatter* is a reference to the main formatter object, *spec* contains 2017 format specifier information for standard argument types, and *fmt* points 2018 to the part of the format string being parsed for custom argument types. 2019 \endrst 2020 */ 2021 BasicArgFormatter(BasicFormatter<Char, Impl> &formatter, 2022 FormatSpec &spec, const Char *fmt) 2023 : internal::ArgFormatterBase<Impl, Char>(formatter.writer(), spec), 2024 formatter_(formatter), format_(fmt) {} 2025 2026 /** Formats argument of a custom (user-defined) type. */ 2027 void visit_custom(internal::Arg::CustomValue c) { 2028 c.format(&formatter_, c.value, &format_); 2029 } 2030 }; 2031 2032 /** The default argument formatter. */ 2033 template <typename Char> 2034 class ArgFormatter : public BasicArgFormatter<ArgFormatter<Char>, Char> { 2035 public: 2036 /** Constructs an argument formatter object. */ 2037 ArgFormatter(BasicFormatter<Char> &formatter, 2038 FormatSpec &spec, const Char *fmt) 2039 : BasicArgFormatter<ArgFormatter<Char>, Char>(formatter, spec, fmt) {} 2040 }; 2041 2042 /** This template formats data and writes the output to a writer. */ 2043 template <typename CharType, typename ArgFormatter> 2044 class BasicFormatter : private internal::FormatterBase { 2045 public: 2046 /** The character type for the output. */ 2047 typedef CharType Char; 2048 2049 private: 2050 BasicWriter<Char> &writer_; 2051 internal::ArgMap<Char> map_; 2052 2053 FMT_DISALLOW_COPY_AND_ASSIGN(BasicFormatter); 2054 2055 using internal::FormatterBase::get_arg; 2056 2057 // Checks if manual indexing is used and returns the argument with 2058 // specified name. 2059 internal::Arg get_arg(BasicStringRef<Char> arg_name, const char *&error); 2060 2061 // Parses argument index and returns corresponding argument. 2062 internal::Arg parse_arg_index(const Char *&s); 2063 2064 // Parses argument name and returns corresponding argument. 2065 internal::Arg parse_arg_name(const Char *&s); 2066 2067 public: 2068 /** 2069 \rst 2070 Constructs a ``BasicFormatter`` object. References to the arguments and 2071 the writer are stored in the formatter object so make sure they have 2072 appropriate lifetimes. 2073 \endrst 2074 */ 2075 BasicFormatter(const ArgList &args, BasicWriter<Char> &w) 2076 : internal::FormatterBase(args), writer_(w) {} 2077 2078 /** Returns a reference to the writer associated with this formatter. */ 2079 BasicWriter<Char> &writer() { return writer_; } 2080 2081 /** Formats stored arguments and writes the output to the writer. */ 2082 void format(BasicCStringRef<Char> format_str); 2083 2084 // Formats a single argument and advances format_str, a format string pointer. 2085 const Char *format(const Char *&format_str, const internal::Arg &arg); 2086 }; 2087 2088 // Generates a comma-separated list with results of applying f to 2089 // numbers 0..n-1. 2090 # define FMT_GEN(n, f) FMT_GEN##n(f) 2091 # define FMT_GEN1(f) f(0) 2092 # define FMT_GEN2(f) FMT_GEN1(f), f(1) 2093 # define FMT_GEN3(f) FMT_GEN2(f), f(2) 2094 # define FMT_GEN4(f) FMT_GEN3(f), f(3) 2095 # define FMT_GEN5(f) FMT_GEN4(f), f(4) 2096 # define FMT_GEN6(f) FMT_GEN5(f), f(5) 2097 # define FMT_GEN7(f) FMT_GEN6(f), f(6) 2098 # define FMT_GEN8(f) FMT_GEN7(f), f(7) 2099 # define FMT_GEN9(f) FMT_GEN8(f), f(8) 2100 # define FMT_GEN10(f) FMT_GEN9(f), f(9) 2101 # define FMT_GEN11(f) FMT_GEN10(f), f(10) 2102 # define FMT_GEN12(f) FMT_GEN11(f), f(11) 2103 # define FMT_GEN13(f) FMT_GEN12(f), f(12) 2104 # define FMT_GEN14(f) FMT_GEN13(f), f(13) 2105 # define FMT_GEN15(f) FMT_GEN14(f), f(14) 2106 2107 namespace internal { 2108 inline uint64_t make_type() { return 0; } 2109 2110 template <typename T> 2111 inline uint64_t make_type(const T &arg) { 2112 return MakeValue< BasicFormatter<char> >::type(arg); 2113 } 2114 2115 template <unsigned N, bool/*IsPacked*/= (N < ArgList::MAX_PACKED_ARGS)> 2116 struct ArgArray; 2117 2118 template <unsigned N> 2119 struct ArgArray<N, true/*IsPacked*/> { 2120 typedef Value Type[N > 0 ? N : 1]; 2121 2122 template <typename Formatter, typename T> 2123 static Value make(const T &value) { 2124 #ifdef __clang__ 2125 Value result = MakeValue<Formatter>(value); 2126 // Workaround a bug in Apple LLVM version 4.2 (clang-425.0.28) of clang: 2127 // https://github.com/fmtlib/fmt/issues/276 2128 (void)result.custom.format; 2129 return result; 2130 #else 2131 return MakeValue<Formatter>(value); 2132 #endif 2133 } 2134 }; 2135 2136 template <unsigned N> 2137 struct ArgArray<N, false/*IsPacked*/> { 2138 typedef Arg Type[N + 1]; // +1 for the list end Arg::NONE 2139 2140 template <typename Formatter, typename T> 2141 static Arg make(const T &value) { return MakeArg<Formatter>(value); } 2142 }; 2143 2144 #if FMT_USE_VARIADIC_TEMPLATES 2145 template <typename Arg, typename... Args> 2146 inline uint64_t make_type(const Arg &first, const Args & ... tail) { 2147 return make_type(first) | (make_type(tail...) << 4); 2148 } 2149 2150 #else 2151 2152 struct ArgType { 2153 uint64_t type; 2154 2155 ArgType() : type(0) {} 2156 2157 template <typename T> 2158 ArgType(const T &arg) : type(make_type(arg)) {} 2159 }; 2160 2161 # define FMT_ARG_TYPE_DEFAULT(n) ArgType t##n = ArgType() 2162 2163 inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) { 2164 return t0.type | (t1.type << 4) | (t2.type << 8) | (t3.type << 12) | 2165 (t4.type << 16) | (t5.type << 20) | (t6.type << 24) | (t7.type << 28) | 2166 (t8.type << 32) | (t9.type << 36) | (t10.type << 40) | (t11.type << 44) | 2167 (t12.type << 48) | (t13.type << 52) | (t14.type << 56); 2168 } 2169 #endif 2170 } // namespace internal 2171 2172 # define FMT_MAKE_TEMPLATE_ARG(n) typename T##n 2173 # define FMT_MAKE_ARG_TYPE(n) T##n 2174 # define FMT_MAKE_ARG(n) const T##n &v##n 2175 # define FMT_ASSIGN_char(n) \ 2176 arr[n] = fmt::internal::MakeValue< fmt::BasicFormatter<char> >(v##n) 2177 # define FMT_ASSIGN_wchar_t(n) \ 2178 arr[n] = fmt::internal::MakeValue< fmt::BasicFormatter<wchar_t> >(v##n) 2179 2180 #if FMT_USE_VARIADIC_TEMPLATES 2181 // Defines a variadic function returning void. 2182 # define FMT_VARIADIC_VOID(func, arg_type) \ 2183 template <typename... Args> \ 2184 void func(arg_type arg0, const Args & ... args) { \ 2185 typedef fmt::internal::ArgArray<sizeof...(Args)> ArgArray; \ 2186 typename ArgArray::Type array{ \ 2187 ArgArray::template make<fmt::BasicFormatter<Char> >(args)...}; \ 2188 func(arg0, fmt::ArgList(fmt::internal::make_type(args...), array)); \ 2189 } 2190 2191 // Defines a variadic constructor. 2192 # define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \ 2193 template <typename... Args> \ 2194 ctor(arg0_type arg0, arg1_type arg1, const Args & ... args) { \ 2195 typedef fmt::internal::ArgArray<sizeof...(Args)> ArgArray; \ 2196 typename ArgArray::Type array{ \ 2197 ArgArray::template make<fmt::BasicFormatter<Char> >(args)...}; \ 2198 func(arg0, arg1, fmt::ArgList(fmt::internal::make_type(args...), array)); \ 2199 } 2200 2201 #else 2202 2203 # define FMT_MAKE_REF(n) \ 2204 fmt::internal::MakeValue< fmt::BasicFormatter<Char> >(v##n) 2205 # define FMT_MAKE_REF2(n) v##n 2206 2207 // Defines a wrapper for a function taking one argument of type arg_type 2208 // and n additional arguments of arbitrary types. 2209 # define FMT_WRAP1(func, arg_type, n) \ 2210 template <FMT_GEN(n, FMT_MAKE_TEMPLATE_ARG)> \ 2211 inline void func(arg_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \ 2212 const fmt::internal::ArgArray<n>::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \ 2213 func(arg1, fmt::ArgList( \ 2214 fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \ 2215 } 2216 2217 // Emulates a variadic function returning void on a pre-C++11 compiler. 2218 # define FMT_VARIADIC_VOID(func, arg_type) \ 2219 inline void func(arg_type arg) { func(arg, fmt::ArgList()); } \ 2220 FMT_WRAP1(func, arg_type, 1) FMT_WRAP1(func, arg_type, 2) \ 2221 FMT_WRAP1(func, arg_type, 3) FMT_WRAP1(func, arg_type, 4) \ 2222 FMT_WRAP1(func, arg_type, 5) FMT_WRAP1(func, arg_type, 6) \ 2223 FMT_WRAP1(func, arg_type, 7) FMT_WRAP1(func, arg_type, 8) \ 2224 FMT_WRAP1(func, arg_type, 9) FMT_WRAP1(func, arg_type, 10) 2225 2226 # define FMT_CTOR(ctor, func, arg0_type, arg1_type, n) \ 2227 template <FMT_GEN(n, FMT_MAKE_TEMPLATE_ARG)> \ 2228 ctor(arg0_type arg0, arg1_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \ 2229 const fmt::internal::ArgArray<n>::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \ 2230 func(arg0, arg1, fmt::ArgList( \ 2231 fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \ 2232 } 2233 2234 // Emulates a variadic constructor on a pre-C++11 compiler. 2235 # define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \ 2236 FMT_CTOR(ctor, func, arg0_type, arg1_type, 1) \ 2237 FMT_CTOR(ctor, func, arg0_type, arg1_type, 2) \ 2238 FMT_CTOR(ctor, func, arg0_type, arg1_type, 3) \ 2239 FMT_CTOR(ctor, func, arg0_type, arg1_type, 4) \ 2240 FMT_CTOR(ctor, func, arg0_type, arg1_type, 5) \ 2241 FMT_CTOR(ctor, func, arg0_type, arg1_type, 6) \ 2242 FMT_CTOR(ctor, func, arg0_type, arg1_type, 7) \ 2243 FMT_CTOR(ctor, func, arg0_type, arg1_type, 8) \ 2244 FMT_CTOR(ctor, func, arg0_type, arg1_type, 9) \ 2245 FMT_CTOR(ctor, func, arg0_type, arg1_type, 10) 2246 #endif 2247 2248 // Generates a comma-separated list with results of applying f to pairs 2249 // (argument, index). 2250 #define FMT_FOR_EACH1(f, x0) f(x0, 0) 2251 #define FMT_FOR_EACH2(f, x0, x1) \ 2252 FMT_FOR_EACH1(f, x0), f(x1, 1) 2253 #define FMT_FOR_EACH3(f, x0, x1, x2) \ 2254 FMT_FOR_EACH2(f, x0 ,x1), f(x2, 2) 2255 #define FMT_FOR_EACH4(f, x0, x1, x2, x3) \ 2256 FMT_FOR_EACH3(f, x0, x1, x2), f(x3, 3) 2257 #define FMT_FOR_EACH5(f, x0, x1, x2, x3, x4) \ 2258 FMT_FOR_EACH4(f, x0, x1, x2, x3), f(x4, 4) 2259 #define FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5) \ 2260 FMT_FOR_EACH5(f, x0, x1, x2, x3, x4), f(x5, 5) 2261 #define FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6) \ 2262 FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5), f(x6, 6) 2263 #define FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7) \ 2264 FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6), f(x7, 7) 2265 #define FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8) \ 2266 FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7), f(x8, 8) 2267 #define FMT_FOR_EACH10(f, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9) \ 2268 FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8), f(x9, 9) 2269 2270 /** 2271 An error returned by an operating system or a language runtime, 2272 for example a file opening error. 2273 */ 2274 class SystemError : public internal::RuntimeError { 2275 private: 2276 void init(int err_code, CStringRef format_str, ArgList args); 2277 2278 protected: 2279 int error_code_; 2280 2281 typedef char Char; // For FMT_VARIADIC_CTOR. 2282 2283 SystemError() {} 2284 2285 public: 2286 /** 2287 \rst 2288 Constructs a :class:`fmt::SystemError` object with the description 2289 of the form 2290 2291 .. parsed-literal:: 2292 *<message>*: *<system-message>* 2293 2294 where *<message>* is the formatted message and *<system-message>* is 2295 the system message corresponding to the error code. 2296 *error_code* is a system error code as given by ``errno``. 2297 If *error_code* is not a valid error code such as -1, the system message 2298 may look like "Unknown error -1" and is platform-dependent. 2299 2300 **Example**:: 2301 2302 // This throws a SystemError with the description 2303 // cannot open file 'madeup': No such file or directory 2304 // or similar (system message may vary). 2305 const char *filename = "madeup"; 2306 std::FILE *file = std::fopen(filename, "r"); 2307 if (!file) 2308 throw fmt::SystemError(errno, "cannot open file '{}'", filename); 2309 \endrst 2310 */ 2311 SystemError(int error_code, CStringRef message) { 2312 init(error_code, message, ArgList()); 2313 } 2314 FMT_VARIADIC_CTOR(SystemError, init, int, CStringRef) 2315 2316 ~SystemError() throw(); 2317 2318 int error_code() const { return error_code_; } 2319 }; 2320 2321 /** 2322 \rst 2323 This template provides operations for formatting and writing data into 2324 a character stream. The output is stored in a buffer provided by a subclass 2325 such as :class:`fmt::BasicMemoryWriter`. 2326 2327 You can use one of the following typedefs for common character types: 2328 2329 +---------+----------------------+ 2330 | Type | Definition | 2331 +=========+======================+ 2332 | Writer | BasicWriter<char> | 2333 +---------+----------------------+ 2334 | WWriter | BasicWriter<wchar_t> | 2335 +---------+----------------------+ 2336 2337 \endrst 2338 */ 2339 template <typename Char> 2340 class BasicWriter { 2341 private: 2342 // Output buffer. 2343 Buffer<Char> &buffer_; 2344 2345 FMT_DISALLOW_COPY_AND_ASSIGN(BasicWriter); 2346 2347 typedef typename internal::CharTraits<Char>::CharPtr CharPtr; 2348 2349 #if FMT_SECURE_SCL 2350 // Returns pointer value. 2351 static Char *get(CharPtr p) { return p.base(); } 2352 #else 2353 static Char *get(Char *p) { return p; } 2354 #endif 2355 2356 // Fills the padding around the content and returns the pointer to the 2357 // content area. 2358 static CharPtr fill_padding(CharPtr buffer, 2359 unsigned total_size, std::size_t content_size, wchar_t fill); 2360 2361 // Grows the buffer by n characters and returns a pointer to the newly 2362 // allocated area. 2363 CharPtr grow_buffer(std::size_t n) { 2364 std::size_t size = buffer_.size(); 2365 buffer_.resize(size + n); 2366 return internal::make_ptr(&buffer_[size], n); 2367 } 2368 2369 // Writes an unsigned decimal integer. 2370 template <typename UInt> 2371 Char *write_unsigned_decimal(UInt value, unsigned prefix_size = 0) { 2372 unsigned num_digits = internal::count_digits(value); 2373 Char *ptr = get(grow_buffer(prefix_size + num_digits)); 2374 internal::format_decimal(ptr + prefix_size, value, num_digits); 2375 return ptr; 2376 } 2377 2378 // Writes a decimal integer. 2379 template <typename Int> 2380 void write_decimal(Int value) { 2381 typedef typename internal::IntTraits<Int>::MainType MainType; 2382 MainType abs_value = static_cast<MainType>(value); 2383 if (internal::is_negative(value)) { 2384 abs_value = 0 - abs_value; 2385 *write_unsigned_decimal(abs_value, 1) = '-'; 2386 } else { 2387 write_unsigned_decimal(abs_value, 0); 2388 } 2389 } 2390 2391 // Prepare a buffer for integer formatting. 2392 CharPtr prepare_int_buffer(unsigned num_digits, 2393 const EmptySpec &, const char *prefix, unsigned prefix_size) { 2394 unsigned size = prefix_size + num_digits; 2395 CharPtr p = grow_buffer(size); 2396 std::uninitialized_copy(prefix, prefix + prefix_size, p); 2397 return p + size - 1; 2398 } 2399 2400 template <typename Spec> 2401 CharPtr prepare_int_buffer(unsigned num_digits, 2402 const Spec &spec, const char *prefix, unsigned prefix_size); 2403 2404 // Formats an integer. 2405 template <typename T, typename Spec> 2406 void write_int(T value, Spec spec); 2407 2408 // Formats a floating-point number (double or long double). 2409 template <typename T> 2410 void write_double(T value, const FormatSpec &spec); 2411 2412 // Writes a formatted string. 2413 template <typename StrChar> 2414 CharPtr write_str(const StrChar *s, std::size_t size, const AlignSpec &spec); 2415 2416 template <typename StrChar> 2417 void write_str(const internal::Arg::StringValue<StrChar> &str, 2418 const FormatSpec &spec); 2419 2420 // This following methods are private to disallow writing wide characters 2421 // and strings to a char stream. If you want to print a wide string as a 2422 // pointer as std::ostream does, cast it to const void*. 2423 // Do not implement! 2424 void operator<<(typename internal::WCharHelper<wchar_t, Char>::Unsupported); 2425 void operator<<( 2426 typename internal::WCharHelper<const wchar_t *, Char>::Unsupported); 2427 2428 // Appends floating-point length specifier to the format string. 2429 // The second argument is only used for overload resolution. 2430 void append_float_length(Char *&format_ptr, long double) { 2431 *format_ptr++ = 'L'; 2432 } 2433 2434 template<typename T> 2435 void append_float_length(Char *&, T) {} 2436 2437 template <typename Impl, typename Char_> 2438 friend class internal::ArgFormatterBase; 2439 2440 friend class internal::PrintfArgFormatter<Char>; 2441 2442 protected: 2443 /** 2444 Constructs a ``BasicWriter`` object. 2445 */ 2446 explicit BasicWriter(Buffer<Char> &b) : buffer_(b) {} 2447 2448 public: 2449 /** 2450 \rst 2451 Destroys a ``BasicWriter`` object. 2452 \endrst 2453 */ 2454 virtual ~BasicWriter() {} 2455 2456 /** 2457 Returns the total number of characters written. 2458 */ 2459 std::size_t size() const { return buffer_.size(); } 2460 2461 /** 2462 Returns a pointer to the output buffer content. No terminating null 2463 character is appended. 2464 */ 2465 const Char *data() const FMT_NOEXCEPT { return &buffer_[0]; } 2466 2467 /** 2468 Returns a pointer to the output buffer content with terminating null 2469 character appended. 2470 */ 2471 const Char *c_str() const { 2472 std::size_t size = buffer_.size(); 2473 buffer_.reserve(size + 1); 2474 buffer_[size] = '\0'; 2475 return &buffer_[0]; 2476 } 2477 2478 /** 2479 \rst 2480 Returns the content of the output buffer as an `std::string`. 2481 \endrst 2482 */ 2483 std::basic_string<Char> str() const { 2484 return std::basic_string<Char>(&buffer_[0], buffer_.size()); 2485 } 2486 2487 /** 2488 \rst 2489 Writes formatted data. 2490 2491 *args* is an argument list representing arbitrary arguments. 2492 2493 **Example**:: 2494 2495 MemoryWriter out; 2496 out.write("Current point:\n"); 2497 out.write("({:+f}, {:+f})", -3.14, 3.14); 2498 2499 This will write the following output to the ``out`` object: 2500 2501 .. code-block:: none 2502 2503 Current point: 2504 (-3.140000, +3.140000) 2505 2506 The output can be accessed using :func:`data()`, :func:`c_str` or 2507 :func:`str` methods. 2508 2509 See also :ref:`syntax`. 2510 \endrst 2511 */ 2512 void write(BasicCStringRef<Char> format, ArgList args) { 2513 BasicFormatter<Char>(args, *this).format(format); 2514 } 2515 FMT_VARIADIC_VOID(write, BasicCStringRef<Char>) 2516 2517 BasicWriter &operator<<(int value) { 2518 write_decimal(value); 2519 return *this; 2520 } 2521 BasicWriter &operator<<(unsigned value) { 2522 return *this << IntFormatSpec<unsigned>(value); 2523 } 2524 BasicWriter &operator<<(long value) { 2525 write_decimal(value); 2526 return *this; 2527 } 2528 BasicWriter &operator<<(unsigned long value) { 2529 return *this << IntFormatSpec<unsigned long>(value); 2530 } 2531 BasicWriter &operator<<(LongLong value) { 2532 write_decimal(value); 2533 return *this; 2534 } 2535 2536 /** 2537 \rst 2538 Formats *value* and writes it to the stream. 2539 \endrst 2540 */ 2541 BasicWriter &operator<<(ULongLong value) { 2542 return *this << IntFormatSpec<ULongLong>(value); 2543 } 2544 2545 BasicWriter &operator<<(double value) { 2546 write_double(value, FormatSpec()); 2547 return *this; 2548 } 2549 2550 /** 2551 \rst 2552 Formats *value* using the general format for floating-point numbers 2553 (``'g'``) and writes it to the stream. 2554 \endrst 2555 */ 2556 BasicWriter &operator<<(long double value) { 2557 write_double(value, FormatSpec()); 2558 return *this; 2559 } 2560 2561 /** 2562 Writes a character to the stream. 2563 */ 2564 BasicWriter &operator<<(char value) { 2565 buffer_.push_back(value); 2566 return *this; 2567 } 2568 2569 BasicWriter &operator<<( 2570 typename internal::WCharHelper<wchar_t, Char>::Supported value) { 2571 buffer_.push_back(value); 2572 return *this; 2573 } 2574 2575 /** 2576 \rst 2577 Writes *value* to the stream. 2578 \endrst 2579 */ 2580 BasicWriter &operator<<(fmt::BasicStringRef<Char> value) { 2581 const Char *str = value.data(); 2582 buffer_.append(str, str + value.size()); 2583 return *this; 2584 } 2585 2586 BasicWriter &operator<<( 2587 typename internal::WCharHelper<StringRef, Char>::Supported value) { 2588 const char *str = value.data(); 2589 buffer_.append(str, str + value.size()); 2590 return *this; 2591 } 2592 2593 template <typename T, typename Spec, typename FillChar> 2594 BasicWriter &operator<<(IntFormatSpec<T, Spec, FillChar> spec) { 2595 internal::CharTraits<Char>::convert(FillChar()); 2596 write_int(spec.value(), spec); 2597 return *this; 2598 } 2599 2600 template <typename StrChar> 2601 BasicWriter &operator<<(const StrFormatSpec<StrChar> &spec) { 2602 const StrChar *s = spec.str(); 2603 write_str(s, std::char_traits<Char>::length(s), spec); 2604 return *this; 2605 } 2606 2607 void clear() FMT_NOEXCEPT { buffer_.clear(); } 2608 2609 Buffer<Char> &buffer() FMT_NOEXCEPT { return buffer_; } 2610 }; 2611 2612 template <typename Char> 2613 template <typename StrChar> 2614 typename BasicWriter<Char>::CharPtr BasicWriter<Char>::write_str( 2615 const StrChar *s, std::size_t size, const AlignSpec &spec) { 2616 CharPtr out = CharPtr(); 2617 if (spec.width() > size) { 2618 out = grow_buffer(spec.width()); 2619 Char fill = internal::CharTraits<Char>::cast(spec.fill()); 2620 if (spec.align() == ALIGN_RIGHT) { 2621 std::uninitialized_fill_n(out, spec.width() - size, fill); 2622 out += spec.width() - size; 2623 } else if (spec.align() == ALIGN_CENTER) { 2624 out = fill_padding(out, spec.width(), size, fill); 2625 } else { 2626 std::uninitialized_fill_n(out + size, spec.width() - size, fill); 2627 } 2628 } else { 2629 out = grow_buffer(size); 2630 } 2631 std::uninitialized_copy(s, s + size, out); 2632 return out; 2633 } 2634 2635 template <typename Char> 2636 template <typename StrChar> 2637 void BasicWriter<Char>::write_str( 2638 const internal::Arg::StringValue<StrChar> &s, const FormatSpec &spec) { 2639 // Check if StrChar is convertible to Char. 2640 internal::CharTraits<Char>::convert(StrChar()); 2641 if (spec.type_ && spec.type_ != 's') 2642 internal::report_unknown_type(spec.type_, "string"); 2643 const StrChar *str_value = s.value; 2644 std::size_t str_size = s.size; 2645 if (str_size == 0) { 2646 if (!str_value) { 2647 FMT_THROW(FormatError("string pointer is null")); 2648 } 2649 } 2650 std::size_t precision = static_cast<std::size_t>(spec.precision_); 2651 if (spec.precision_ >= 0 && precision < str_size) 2652 str_size = precision; 2653 write_str(str_value, str_size, spec); 2654 } 2655 2656 template <typename Char> 2657 typename BasicWriter<Char>::CharPtr 2658 BasicWriter<Char>::fill_padding( 2659 CharPtr buffer, unsigned total_size, 2660 std::size_t content_size, wchar_t fill) { 2661 std::size_t padding = total_size - content_size; 2662 std::size_t left_padding = padding / 2; 2663 Char fill_char = internal::CharTraits<Char>::cast(fill); 2664 std::uninitialized_fill_n(buffer, left_padding, fill_char); 2665 buffer += left_padding; 2666 CharPtr content = buffer; 2667 std::uninitialized_fill_n(buffer + content_size, 2668 padding - left_padding, fill_char); 2669 return content; 2670 } 2671 2672 template <typename Char> 2673 template <typename Spec> 2674 typename BasicWriter<Char>::CharPtr 2675 BasicWriter<Char>::prepare_int_buffer( 2676 unsigned num_digits, const Spec &spec, 2677 const char *prefix, unsigned prefix_size) { 2678 unsigned width = spec.width(); 2679 Alignment align = spec.align(); 2680 Char fill = internal::CharTraits<Char>::cast(spec.fill()); 2681 if (spec.precision() > static_cast<int>(num_digits)) { 2682 // Octal prefix '0' is counted as a digit, so ignore it if precision 2683 // is specified. 2684 if (prefix_size > 0 && prefix[prefix_size - 1] == '0') 2685 --prefix_size; 2686 unsigned number_size = 2687 prefix_size + internal::to_unsigned(spec.precision()); 2688 AlignSpec subspec(number_size, '0', ALIGN_NUMERIC); 2689 if (number_size >= width) 2690 return prepare_int_buffer(num_digits, subspec, prefix, prefix_size); 2691 buffer_.reserve(width); 2692 unsigned fill_size = width - number_size; 2693 if (align != ALIGN_LEFT) { 2694 CharPtr p = grow_buffer(fill_size); 2695 std::uninitialized_fill(p, p + fill_size, fill); 2696 } 2697 CharPtr result = prepare_int_buffer( 2698 num_digits, subspec, prefix, prefix_size); 2699 if (align == ALIGN_LEFT) { 2700 CharPtr p = grow_buffer(fill_size); 2701 std::uninitialized_fill(p, p + fill_size, fill); 2702 } 2703 return result; 2704 } 2705 unsigned size = prefix_size + num_digits; 2706 if (width <= size) { 2707 CharPtr p = grow_buffer(size); 2708 std::uninitialized_copy(prefix, prefix + prefix_size, p); 2709 return p + size - 1; 2710 } 2711 CharPtr p = grow_buffer(width); 2712 CharPtr end = p + width; 2713 if (align == ALIGN_LEFT) { 2714 std::uninitialized_copy(prefix, prefix + prefix_size, p); 2715 p += size; 2716 std::uninitialized_fill(p, end, fill); 2717 } else if (align == ALIGN_CENTER) { 2718 p = fill_padding(p, width, size, fill); 2719 std::uninitialized_copy(prefix, prefix + prefix_size, p); 2720 p += size; 2721 } else { 2722 if (align == ALIGN_NUMERIC) { 2723 if (prefix_size != 0) { 2724 p = std::uninitialized_copy(prefix, prefix + prefix_size, p); 2725 size -= prefix_size; 2726 } 2727 } else { 2728 std::uninitialized_copy(prefix, prefix + prefix_size, end - size); 2729 } 2730 std::uninitialized_fill(p, end - size, fill); 2731 p = end; 2732 } 2733 return p - 1; 2734 } 2735 2736 template <typename Char> 2737 template <typename T, typename Spec> 2738 void BasicWriter<Char>::write_int(T value, Spec spec) { 2739 unsigned prefix_size = 0; 2740 typedef typename internal::IntTraits<T>::MainType UnsignedType; 2741 UnsignedType abs_value = static_cast<UnsignedType>(value); 2742 char prefix[4] = ""; 2743 if (internal::is_negative(value)) { 2744 prefix[0] = '-'; 2745 ++prefix_size; 2746 abs_value = 0 - abs_value; 2747 } else if (spec.flag(SIGN_FLAG)) { 2748 prefix[0] = spec.flag(PLUS_FLAG) ? '+' : ' '; 2749 ++prefix_size; 2750 } 2751 switch (spec.type()) { 2752 case 0: case 'd': { 2753 unsigned num_digits = internal::count_digits(abs_value); 2754 CharPtr p = prepare_int_buffer(num_digits, spec, prefix, prefix_size) + 1; 2755 internal::format_decimal(get(p), abs_value, 0); 2756 break; 2757 } 2758 case 'x': case 'X': { 2759 UnsignedType n = abs_value; 2760 if (spec.flag(HASH_FLAG)) { 2761 prefix[prefix_size++] = '0'; 2762 prefix[prefix_size++] = spec.type(); 2763 } 2764 unsigned num_digits = 0; 2765 do { 2766 ++num_digits; 2767 } while ((n >>= 4) != 0); 2768 Char *p = get(prepare_int_buffer( 2769 num_digits, spec, prefix, prefix_size)); 2770 n = abs_value; 2771 const char *digits = spec.type() == 'x' ? 2772 "0123456789abcdef" : "0123456789ABCDEF"; 2773 do { 2774 *p-- = digits[n & 0xf]; 2775 } while ((n >>= 4) != 0); 2776 break; 2777 } 2778 case 'b': case 'B': { 2779 UnsignedType n = abs_value; 2780 if (spec.flag(HASH_FLAG)) { 2781 prefix[prefix_size++] = '0'; 2782 prefix[prefix_size++] = spec.type(); 2783 } 2784 unsigned num_digits = 0; 2785 do { 2786 ++num_digits; 2787 } while ((n >>= 1) != 0); 2788 Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size)); 2789 n = abs_value; 2790 do { 2791 *p-- = static_cast<Char>('0' + (n & 1)); 2792 } while ((n >>= 1) != 0); 2793 break; 2794 } 2795 case 'o': { 2796 UnsignedType n = abs_value; 2797 if (spec.flag(HASH_FLAG)) 2798 prefix[prefix_size++] = '0'; 2799 unsigned num_digits = 0; 2800 do { 2801 ++num_digits; 2802 } while ((n >>= 3) != 0); 2803 Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size)); 2804 n = abs_value; 2805 do { 2806 *p-- = static_cast<Char>('0' + (n & 7)); 2807 } while ((n >>= 3) != 0); 2808 break; 2809 } 2810 case 'n': { 2811 unsigned num_digits = internal::count_digits(abs_value); 2812 fmt::StringRef sep = ""; 2813 #ifndef ANDROID 2814 sep = internal::thousands_sep(std::localeconv()); 2815 #endif 2816 unsigned size = static_cast<unsigned>( 2817 num_digits + sep.size() * ((num_digits - 1) / 3)); 2818 CharPtr p = prepare_int_buffer(size, spec, prefix, prefix_size) + 1; 2819 internal::format_decimal(get(p), abs_value, 0, internal::ThousandsSep(sep)); 2820 break; 2821 } 2822 default: 2823 internal::report_unknown_type( 2824 spec.type(), spec.flag(CHAR_FLAG) ? "char" : "integer"); 2825 break; 2826 } 2827 } 2828 2829 template <typename Char> 2830 template <typename T> 2831 void BasicWriter<Char>::write_double(T value, const FormatSpec &spec) { 2832 // Check type. 2833 char type = spec.type(); 2834 bool upper = false; 2835 switch (type) { 2836 case 0: 2837 type = 'g'; 2838 break; 2839 case 'e': case 'f': case 'g': case 'a': 2840 break; 2841 case 'F': 2842 #if FMT_MSC_VER 2843 // MSVC's printf doesn't support 'F'. 2844 type = 'f'; 2845 #endif 2846 // Fall through. 2847 case 'E': case 'G': case 'A': 2848 upper = true; 2849 break; 2850 default: 2851 internal::report_unknown_type(type, "double"); 2852 break; 2853 } 2854 2855 char sign = 0; 2856 // Use isnegative instead of value < 0 because the latter is always 2857 // false for NaN. 2858 if (internal::FPUtil::isnegative(static_cast<double>(value))) { 2859 sign = '-'; 2860 value = -value; 2861 } else if (spec.flag(SIGN_FLAG)) { 2862 sign = spec.flag(PLUS_FLAG) ? '+' : ' '; 2863 } 2864 2865 if (internal::FPUtil::isnotanumber(value)) { 2866 // Format NaN ourselves because sprintf's output is not consistent 2867 // across platforms. 2868 std::size_t nan_size = 4; 2869 const char *nan = upper ? " NAN" : " nan"; 2870 if (!sign) { 2871 --nan_size; 2872 ++nan; 2873 } 2874 CharPtr out = write_str(nan, nan_size, spec); 2875 if (sign) 2876 *out = sign; 2877 return; 2878 } 2879 2880 if (internal::FPUtil::isinfinity(value)) { 2881 // Format infinity ourselves because sprintf's output is not consistent 2882 // across platforms. 2883 std::size_t inf_size = 4; 2884 const char *inf = upper ? " INF" : " inf"; 2885 if (!sign) { 2886 --inf_size; 2887 ++inf; 2888 } 2889 CharPtr out = write_str(inf, inf_size, spec); 2890 if (sign) 2891 *out = sign; 2892 return; 2893 } 2894 2895 std::size_t offset = buffer_.size(); 2896 unsigned width = spec.width(); 2897 if (sign) { 2898 buffer_.reserve(buffer_.size() + (width > 1u ? width : 1u)); 2899 if (width > 0) 2900 --width; 2901 ++offset; 2902 } 2903 2904 // Build format string. 2905 enum { MAX_FORMAT_SIZE = 10}; // longest format: %#-*.*Lg 2906 Char format[MAX_FORMAT_SIZE]; 2907 Char *format_ptr = format; 2908 *format_ptr++ = '%'; 2909 unsigned width_for_sprintf = width; 2910 if (spec.flag(HASH_FLAG)) 2911 *format_ptr++ = '#'; 2912 if (spec.align() == ALIGN_CENTER) { 2913 width_for_sprintf = 0; 2914 } else { 2915 if (spec.align() == ALIGN_LEFT) 2916 *format_ptr++ = '-'; 2917 if (width != 0) 2918 *format_ptr++ = '*'; 2919 } 2920 if (spec.precision() >= 0) { 2921 *format_ptr++ = '.'; 2922 *format_ptr++ = '*'; 2923 } 2924 2925 append_float_length(format_ptr, value); 2926 *format_ptr++ = type; 2927 *format_ptr = '\0'; 2928 2929 // Format using snprintf. 2930 Char fill = internal::CharTraits<Char>::cast(spec.fill()); 2931 unsigned n = 0; 2932 Char *start = 0; 2933 for (;;) { 2934 std::size_t buffer_size = buffer_.capacity() - offset; 2935 #if FMT_MSC_VER 2936 // MSVC's vsnprintf_s doesn't work with zero size, so reserve 2937 // space for at least one extra character to make the size non-zero. 2938 // Note that the buffer's capacity will increase by more than 1. 2939 if (buffer_size == 0) { 2940 buffer_.reserve(offset + 1); 2941 buffer_size = buffer_.capacity() - offset; 2942 } 2943 #endif 2944 start = &buffer_[offset]; 2945 int result = internal::CharTraits<Char>::format_float( 2946 start, buffer_size, format, width_for_sprintf, spec.precision(), value); 2947 if (result >= 0) { 2948 n = internal::to_unsigned(result); 2949 if (offset + n < buffer_.capacity()) 2950 break; // The buffer is large enough - continue with formatting. 2951 buffer_.reserve(offset + n + 1); 2952 } else { 2953 // If result is negative we ask to increase the capacity by at least 1, 2954 // but as std::vector, the buffer grows exponentially. 2955 buffer_.reserve(buffer_.capacity() + 1); 2956 } 2957 } 2958 if (sign) { 2959 if ((spec.align() != ALIGN_RIGHT && spec.align() != ALIGN_DEFAULT) || 2960 *start != ' ') { 2961 *(start - 1) = sign; 2962 sign = 0; 2963 } else { 2964 *(start - 1) = fill; 2965 } 2966 ++n; 2967 } 2968 if (spec.align() == ALIGN_CENTER && spec.width() > n) { 2969 width = spec.width(); 2970 CharPtr p = grow_buffer(width); 2971 std::memmove(get(p) + (width - n) / 2, get(p), n * sizeof(Char)); 2972 fill_padding(p, spec.width(), n, fill); 2973 return; 2974 } 2975 if (spec.fill() != ' ' || sign) { 2976 while (*start == ' ') 2977 *start++ = fill; 2978 if (sign) 2979 *(start - 1) = sign; 2980 } 2981 grow_buffer(n); 2982 } 2983 2984 /** 2985 \rst 2986 This class template provides operations for formatting and writing data 2987 into a character stream. The output is stored in a memory buffer that grows 2988 dynamically. 2989 2990 You can use one of the following typedefs for common character types 2991 and the standard allocator: 2992 2993 +---------------+-----------------------------------------------------+ 2994 | Type | Definition | 2995 +===============+=====================================================+ 2996 | MemoryWriter | BasicMemoryWriter<char, std::allocator<char>> | 2997 +---------------+-----------------------------------------------------+ 2998 | WMemoryWriter | BasicMemoryWriter<wchar_t, std::allocator<wchar_t>> | 2999 +---------------+-----------------------------------------------------+ 3000 3001 **Example**:: 3002 3003 MemoryWriter out; 3004 out << "The answer is " << 42 << "\n"; 3005 out.write("({:+f}, {:+f})", -3.14, 3.14); 3006 3007 This will write the following output to the ``out`` object: 3008 3009 .. code-block:: none 3010 3011 The answer is 42 3012 (-3.140000, +3.140000) 3013 3014 The output can be converted to an ``std::string`` with ``out.str()`` or 3015 accessed as a C string with ``out.c_str()``. 3016 \endrst 3017 */ 3018 template <typename Char, typename Allocator = std::allocator<Char> > 3019 class BasicMemoryWriter : public BasicWriter<Char> { 3020 private: 3021 internal::MemoryBuffer<Char, internal::INLINE_BUFFER_SIZE, Allocator> buffer_; 3022 3023 public: 3024 explicit BasicMemoryWriter(const Allocator& alloc = Allocator()) 3025 : BasicWriter<Char>(buffer_), buffer_(alloc) {} 3026 3027 #if FMT_USE_RVALUE_REFERENCES 3028 /** 3029 \rst 3030 Constructs a :class:`fmt::BasicMemoryWriter` object moving the content 3031 of the other object to it. 3032 \endrst 3033 */ 3034 BasicMemoryWriter(BasicMemoryWriter &&other) 3035 : BasicWriter<Char>(buffer_), buffer_(std::move(other.buffer_)) { 3036 } 3037 3038 /** 3039 \rst 3040 Moves the content of the other ``BasicMemoryWriter`` object to this one. 3041 \endrst 3042 */ 3043 BasicMemoryWriter &operator=(BasicMemoryWriter &&other) { 3044 buffer_ = std::move(other.buffer_); 3045 return *this; 3046 } 3047 #endif 3048 }; 3049 3050 typedef BasicMemoryWriter<char> MemoryWriter; 3051 typedef BasicMemoryWriter<wchar_t> WMemoryWriter; 3052 3053 /** 3054 \rst 3055 This class template provides operations for formatting and writing data 3056 into a fixed-size array. For writing into a dynamically growing buffer 3057 use :class:`fmt::BasicMemoryWriter`. 3058 3059 Any write method will throw ``std::runtime_error`` if the output doesn't fit 3060 into the array. 3061 3062 You can use one of the following typedefs for common character types: 3063 3064 +--------------+---------------------------+ 3065 | Type | Definition | 3066 +==============+===========================+ 3067 | ArrayWriter | BasicArrayWriter<char> | 3068 +--------------+---------------------------+ 3069 | WArrayWriter | BasicArrayWriter<wchar_t> | 3070 +--------------+---------------------------+ 3071 \endrst 3072 */ 3073 template <typename Char> 3074 class BasicArrayWriter : public BasicWriter<Char> { 3075 private: 3076 internal::FixedBuffer<Char> buffer_; 3077 3078 public: 3079 /** 3080 \rst 3081 Constructs a :class:`fmt::BasicArrayWriter` object for *array* of the 3082 given size. 3083 \endrst 3084 */ 3085 BasicArrayWriter(Char *array, std::size_t size) 3086 : BasicWriter<Char>(buffer_), buffer_(array, size) {} 3087 3088 /** 3089 \rst 3090 Constructs a :class:`fmt::BasicArrayWriter` object for *array* of the 3091 size known at compile time. 3092 \endrst 3093 */ 3094 template <std::size_t SIZE> 3095 explicit BasicArrayWriter(Char (&array)[SIZE]) 3096 : BasicWriter<Char>(buffer_), buffer_(array, SIZE) {} 3097 }; 3098 3099 typedef BasicArrayWriter<char> ArrayWriter; 3100 typedef BasicArrayWriter<wchar_t> WArrayWriter; 3101 3102 // Reports a system error without throwing an exception. 3103 // Can be used to report errors from destructors. 3104 FMT_API void report_system_error(int error_code, 3105 StringRef message) FMT_NOEXCEPT; 3106 3107 #if FMT_USE_WINDOWS_H 3108 3109 /** A Windows error. */ 3110 class WindowsError : public SystemError { 3111 private: 3112 FMT_API void init(int error_code, CStringRef format_str, ArgList args); 3113 3114 public: 3115 /** 3116 \rst 3117 Constructs a :class:`fmt::WindowsError` object with the description 3118 of the form 3119 3120 .. parsed-literal:: 3121 *<message>*: *<system-message>* 3122 3123 where *<message>* is the formatted message and *<system-message>* is the 3124 system message corresponding to the error code. 3125 *error_code* is a Windows error code as given by ``GetLastError``. 3126 If *error_code* is not a valid error code such as -1, the system message 3127 will look like "error -1". 3128 3129 **Example**:: 3130 3131 // This throws a WindowsError with the description 3132 // cannot open file 'madeup': The system cannot find the file specified. 3133 // or similar (system message may vary). 3134 const char *filename = "madeup"; 3135 LPOFSTRUCT of = LPOFSTRUCT(); 3136 HFILE file = OpenFile(filename, &of, OF_READ); 3137 if (file == HFILE_ERROR) { 3138 throw fmt::WindowsError(GetLastError(), 3139 "cannot open file '{}'", filename); 3140 } 3141 \endrst 3142 */ 3143 WindowsError(int error_code, CStringRef message) { 3144 init(error_code, message, ArgList()); 3145 } 3146 FMT_VARIADIC_CTOR(WindowsError, init, int, CStringRef) 3147 }; 3148 3149 // Reports a Windows error without throwing an exception. 3150 // Can be used to report errors from destructors. 3151 FMT_API void report_windows_error(int error_code, 3152 StringRef message) FMT_NOEXCEPT; 3153 3154 #endif 3155 3156 enum Color { BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE }; 3157 3158 /** 3159 Formats a string and prints it to stdout using ANSI escape sequences 3160 to specify color (experimental). 3161 Example: 3162 print_colored(fmt::RED, "Elapsed time: {0:.2f} seconds", 1.23); 3163 */ 3164 FMT_API void print_colored(Color c, CStringRef format, ArgList args); 3165 3166 /** 3167 \rst 3168 Formats arguments and returns the result as a string. 3169 3170 **Example**:: 3171 3172 std::string message = format("The answer is {}", 42); 3173 \endrst 3174 */ 3175 inline std::string format(CStringRef format_str, ArgList args) { 3176 MemoryWriter w; 3177 w.write(format_str, args); 3178 return w.str(); 3179 } 3180 3181 inline std::wstring format(WCStringRef format_str, ArgList args) { 3182 WMemoryWriter w; 3183 w.write(format_str, args); 3184 return w.str(); 3185 } 3186 3187 /** 3188 \rst 3189 Prints formatted data to the file *f*. 3190 3191 **Example**:: 3192 3193 print(stderr, "Don't {}!", "panic"); 3194 \endrst 3195 */ 3196 FMT_API void print(std::FILE *f, CStringRef format_str, ArgList args); 3197 3198 /** 3199 \rst 3200 Prints formatted data to ``stdout``. 3201 3202 **Example**:: 3203 3204 print("Elapsed time: {0:.2f} seconds", 1.23); 3205 \endrst 3206 */ 3207 FMT_API void print(CStringRef format_str, ArgList args); 3208 3209 template <typename Char> 3210 void printf(BasicWriter<Char> &w, BasicCStringRef<Char> format, ArgList args) { 3211 internal::PrintfFormatter<Char>(args).format(w, format); 3212 } 3213 3214 /** 3215 \rst 3216 Formats arguments and returns the result as a string. 3217 3218 **Example**:: 3219 3220 std::string message = fmt::sprintf("The answer is %d", 42); 3221 \endrst 3222 */ 3223 inline std::string sprintf(CStringRef format, ArgList args) { 3224 MemoryWriter w; 3225 printf(w, format, args); 3226 return w.str(); 3227 } 3228 3229 inline std::wstring sprintf(WCStringRef format, ArgList args) { 3230 WMemoryWriter w; 3231 printf(w, format, args); 3232 return w.str(); 3233 } 3234 3235 /** 3236 \rst 3237 Prints formatted data to the file *f*. 3238 3239 **Example**:: 3240 3241 fmt::fprintf(stderr, "Don't %s!", "panic"); 3242 \endrst 3243 */ 3244 FMT_API int fprintf(std::FILE *f, CStringRef format, ArgList args); 3245 3246 /** 3247 \rst 3248 Prints formatted data to ``stdout``. 3249 3250 **Example**:: 3251 3252 fmt::printf("Elapsed time: %.2f seconds", 1.23); 3253 \endrst 3254 */ 3255 inline int printf(CStringRef format, ArgList args) { 3256 return fprintf(stdout, format, args); 3257 } 3258 3259 /** 3260 Fast integer formatter. 3261 */ 3262 class FormatInt { 3263 private: 3264 // Buffer should be large enough to hold all digits (digits10 + 1), 3265 // a sign and a null character. 3266 enum {BUFFER_SIZE = std::numeric_limits<ULongLong>::digits10 + 3}; 3267 mutable char buffer_[BUFFER_SIZE]; 3268 char *str_; 3269 3270 // Formats value in reverse and returns the number of digits. 3271 char *format_decimal(ULongLong value) { 3272 char *buffer_end = buffer_ + BUFFER_SIZE - 1; 3273 while (value >= 100) { 3274 // Integer division is slow so do it for a group of two digits instead 3275 // of for every digit. The idea comes from the talk by Alexandrescu 3276 // "Three Optimization Tips for C++". See speed-test for a comparison. 3277 unsigned index = static_cast<unsigned>((value % 100) * 2); 3278 value /= 100; 3279 *--buffer_end = internal::Data::DIGITS[index + 1]; 3280 *--buffer_end = internal::Data::DIGITS[index]; 3281 } 3282 if (value < 10) { 3283 *--buffer_end = static_cast<char>('0' + value); 3284 return buffer_end; 3285 } 3286 unsigned index = static_cast<unsigned>(value * 2); 3287 *--buffer_end = internal::Data::DIGITS[index + 1]; 3288 *--buffer_end = internal::Data::DIGITS[index]; 3289 return buffer_end; 3290 } 3291 3292 void FormatSigned(LongLong value) { 3293 ULongLong abs_value = static_cast<ULongLong>(value); 3294 bool negative = value < 0; 3295 if (negative) 3296 abs_value = 0 - abs_value; 3297 str_ = format_decimal(abs_value); 3298 if (negative) 3299 *--str_ = '-'; 3300 } 3301 3302 public: 3303 explicit FormatInt(int value) { FormatSigned(value); } 3304 explicit FormatInt(long value) { FormatSigned(value); } 3305 explicit FormatInt(LongLong value) { FormatSigned(value); } 3306 explicit FormatInt(unsigned value) : str_(format_decimal(value)) {} 3307 explicit FormatInt(unsigned long value) : str_(format_decimal(value)) {} 3308 explicit FormatInt(ULongLong value) : str_(format_decimal(value)) {} 3309 3310 /** Returns the number of characters written to the output buffer. */ 3311 std::size_t size() const { 3312 return internal::to_unsigned(buffer_ - str_ + BUFFER_SIZE - 1); 3313 } 3314 3315 /** 3316 Returns a pointer to the output buffer content. No terminating null 3317 character is appended. 3318 */ 3319 const char *data() const { return str_; } 3320 3321 /** 3322 Returns a pointer to the output buffer content with terminating null 3323 character appended. 3324 */ 3325 const char *c_str() const { 3326 buffer_[BUFFER_SIZE - 1] = '\0'; 3327 return str_; 3328 } 3329 3330 /** 3331 \rst 3332 Returns the content of the output buffer as an ``std::string``. 3333 \endrst 3334 */ 3335 std::string str() const { return std::string(str_, size()); } 3336 }; 3337 3338 // Formats a decimal integer value writing into buffer and returns 3339 // a pointer to the end of the formatted string. This function doesn't 3340 // write a terminating null character. 3341 template <typename T> 3342 inline void format_decimal(char *&buffer, T value) { 3343 typedef typename internal::IntTraits<T>::MainType MainType; 3344 MainType abs_value = static_cast<MainType>(value); 3345 if (internal::is_negative(value)) { 3346 *buffer++ = '-'; 3347 abs_value = 0 - abs_value; 3348 } 3349 if (abs_value < 100) { 3350 if (abs_value < 10) { 3351 *buffer++ = static_cast<char>('0' + abs_value); 3352 return; 3353 } 3354 unsigned index = static_cast<unsigned>(abs_value * 2); 3355 *buffer++ = internal::Data::DIGITS[index]; 3356 *buffer++ = internal::Data::DIGITS[index + 1]; 3357 return; 3358 } 3359 unsigned num_digits = internal::count_digits(abs_value); 3360 internal::format_decimal(buffer, abs_value, num_digits); 3361 buffer += num_digits; 3362 } 3363 3364 /** 3365 \rst 3366 Returns a named argument for formatting functions. 3367 3368 **Example**:: 3369 3370 print("Elapsed time: {s:.2f} seconds", arg("s", 1.23)); 3371 3372 \endrst 3373 */ 3374 template <typename T> 3375 inline internal::NamedArg<char> arg(StringRef name, const T &arg) { 3376 return internal::NamedArg<char>(name, arg); 3377 } 3378 3379 template <typename T> 3380 inline internal::NamedArg<wchar_t> arg(WStringRef name, const T &arg) { 3381 return internal::NamedArg<wchar_t>(name, arg); 3382 } 3383 3384 // The following two functions are deleted intentionally to disable 3385 // nested named arguments as in ``format("{}", arg("a", arg("b", 42)))``. 3386 template <typename Char> 3387 void arg(StringRef, const internal::NamedArg<Char>&) FMT_DELETED_OR_UNDEFINED; 3388 template <typename Char> 3389 void arg(WStringRef, const internal::NamedArg<Char>&) FMT_DELETED_OR_UNDEFINED; 3390 } 3391 3392 #if FMT_GCC_VERSION 3393 // Use the system_header pragma to suppress warnings about variadic macros 3394 // because suppressing -Wvariadic-macros with the diagnostic pragma doesn't 3395 // work. It is used at the end because we want to suppress as little warnings 3396 // as possible. 3397 # pragma GCC system_header 3398 #endif 3399 3400 // This is used to work around VC++ bugs in handling variadic macros. 3401 #define FMT_EXPAND(args) args 3402 3403 // Returns the number of arguments. 3404 // Based on https://groups.google.com/forum/#!topic/comp.std.c/d-6Mj5Lko_s. 3405 #define FMT_NARG(...) FMT_NARG_(__VA_ARGS__, FMT_RSEQ_N()) 3406 #define FMT_NARG_(...) FMT_EXPAND(FMT_ARG_N(__VA_ARGS__)) 3407 #define FMT_ARG_N(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N 3408 #define FMT_RSEQ_N() 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 3409 3410 #define FMT_CONCAT(a, b) a##b 3411 #define FMT_FOR_EACH_(N, f, ...) \ 3412 FMT_EXPAND(FMT_CONCAT(FMT_FOR_EACH, N)(f, __VA_ARGS__)) 3413 #define FMT_FOR_EACH(f, ...) \ 3414 FMT_EXPAND(FMT_FOR_EACH_(FMT_NARG(__VA_ARGS__), f, __VA_ARGS__)) 3415 3416 #define FMT_ADD_ARG_NAME(type, index) type arg##index 3417 #define FMT_GET_ARG_NAME(type, index) arg##index 3418 3419 #if FMT_USE_VARIADIC_TEMPLATES 3420 # define FMT_VARIADIC_(Char, ReturnType, func, call, ...) \ 3421 template <typename... Args> \ 3422 ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \ 3423 const Args & ... args) { \ 3424 typedef fmt::internal::ArgArray<sizeof...(Args)> ArgArray; \ 3425 typename ArgArray::Type array{ \ 3426 ArgArray::template make<fmt::BasicFormatter<Char> >(args)...}; \ 3427 call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), \ 3428 fmt::ArgList(fmt::internal::make_type(args...), array)); \ 3429 } 3430 #else 3431 // Defines a wrapper for a function taking __VA_ARGS__ arguments 3432 // and n additional arguments of arbitrary types. 3433 # define FMT_WRAP(Char, ReturnType, func, call, n, ...) \ 3434 template <FMT_GEN(n, FMT_MAKE_TEMPLATE_ARG)> \ 3435 inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \ 3436 FMT_GEN(n, FMT_MAKE_ARG)) { \ 3437 fmt::internal::ArgArray<n>::Type arr; \ 3438 FMT_GEN(n, FMT_ASSIGN_##Char); \ 3439 call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList( \ 3440 fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), arr)); \ 3441 } 3442 3443 # define FMT_VARIADIC_(Char, ReturnType, func, call, ...) \ 3444 inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__)) { \ 3445 call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList()); \ 3446 } \ 3447 FMT_WRAP(Char, ReturnType, func, call, 1, __VA_ARGS__) \ 3448 FMT_WRAP(Char, ReturnType, func, call, 2, __VA_ARGS__) \ 3449 FMT_WRAP(Char, ReturnType, func, call, 3, __VA_ARGS__) \ 3450 FMT_WRAP(Char, ReturnType, func, call, 4, __VA_ARGS__) \ 3451 FMT_WRAP(Char, ReturnType, func, call, 5, __VA_ARGS__) \ 3452 FMT_WRAP(Char, ReturnType, func, call, 6, __VA_ARGS__) \ 3453 FMT_WRAP(Char, ReturnType, func, call, 7, __VA_ARGS__) \ 3454 FMT_WRAP(Char, ReturnType, func, call, 8, __VA_ARGS__) \ 3455 FMT_WRAP(Char, ReturnType, func, call, 9, __VA_ARGS__) \ 3456 FMT_WRAP(Char, ReturnType, func, call, 10, __VA_ARGS__) \ 3457 FMT_WRAP(Char, ReturnType, func, call, 11, __VA_ARGS__) \ 3458 FMT_WRAP(Char, ReturnType, func, call, 12, __VA_ARGS__) \ 3459 FMT_WRAP(Char, ReturnType, func, call, 13, __VA_ARGS__) \ 3460 FMT_WRAP(Char, ReturnType, func, call, 14, __VA_ARGS__) \ 3461 FMT_WRAP(Char, ReturnType, func, call, 15, __VA_ARGS__) 3462 #endif // FMT_USE_VARIADIC_TEMPLATES 3463 3464 /** 3465 \rst 3466 Defines a variadic function with the specified return type, function name 3467 and argument types passed as variable arguments to this macro. 3468 3469 **Example**:: 3470 3471 void print_error(const char *file, int line, const char *format, 3472 fmt::ArgList args) { 3473 fmt::print("{}: {}: ", file, line); 3474 fmt::print(format, args); 3475 } 3476 FMT_VARIADIC(void, print_error, const char *, int, const char *) 3477 3478 ``FMT_VARIADIC`` is used for compatibility with legacy C++ compilers that 3479 don't implement variadic templates. You don't have to use this macro if 3480 you don't need legacy compiler support and can use variadic templates 3481 directly:: 3482 3483 template <typename... Args> 3484 void print_error(const char *file, int line, const char *format, 3485 const Args & ... args) { 3486 fmt::print("{}: {}: ", file, line); 3487 fmt::print(format, args...); 3488 } 3489 \endrst 3490 */ 3491 #define FMT_VARIADIC(ReturnType, func, ...) \ 3492 FMT_VARIADIC_(char, ReturnType, func, return func, __VA_ARGS__) 3493 3494 #define FMT_VARIADIC_W(ReturnType, func, ...) \ 3495 FMT_VARIADIC_(wchar_t, ReturnType, func, return func, __VA_ARGS__) 3496 3497 #define FMT_CAPTURE_ARG_(id, index) ::fmt::arg(#id, id) 3498 3499 #define FMT_CAPTURE_ARG_W_(id, index) ::fmt::arg(L###id, id) 3500 3501 /** 3502 \rst 3503 Convenient macro to capture the arguments' names and values into several 3504 ``fmt::arg(name, value)``. 3505 3506 **Example**:: 3507 3508 int x = 1, y = 2; 3509 print("point: ({x}, {y})", FMT_CAPTURE(x, y)); 3510 // same as: 3511 // print("point: ({x}, {y})", arg("x", x), arg("y", y)); 3512 3513 \endrst 3514 */ 3515 #define FMT_CAPTURE(...) FMT_FOR_EACH(FMT_CAPTURE_ARG_, __VA_ARGS__) 3516 3517 #define FMT_CAPTURE_W(...) FMT_FOR_EACH(FMT_CAPTURE_ARG_W_, __VA_ARGS__) 3518 3519 namespace fmt { 3520 FMT_VARIADIC(std::string, format, CStringRef) 3521 FMT_VARIADIC_W(std::wstring, format, WCStringRef) 3522 FMT_VARIADIC(void, print, CStringRef) 3523 FMT_VARIADIC(void, print, std::FILE *, CStringRef) 3524 3525 FMT_VARIADIC(void, print_colored, Color, CStringRef) 3526 FMT_VARIADIC(std::string, sprintf, CStringRef) 3527 FMT_VARIADIC_W(std::wstring, sprintf, WCStringRef) 3528 FMT_VARIADIC(int, printf, CStringRef) 3529 FMT_VARIADIC(int, fprintf, std::FILE *, CStringRef) 3530 3531 namespace internal { 3532 template <typename Char> 3533 inline bool is_name_start(Char c) { 3534 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c; 3535 } 3536 3537 // Parses an unsigned integer advancing s to the end of the parsed input. 3538 // This function assumes that the first character of s is a digit. 3539 template <typename Char> 3540 unsigned parse_nonnegative_int(const Char *&s) { 3541 assert('0' <= *s && *s <= '9'); 3542 unsigned value = 0; 3543 do { 3544 unsigned new_value = value * 10 + (*s++ - '0'); 3545 // Check if value wrapped around. 3546 if (new_value < value) { 3547 value = (std::numeric_limits<unsigned>::max)(); 3548 break; 3549 } 3550 value = new_value; 3551 } while ('0' <= *s && *s <= '9'); 3552 // Convert to unsigned to prevent a warning. 3553 unsigned max_int = (std::numeric_limits<int>::max)(); 3554 if (value > max_int) 3555 FMT_THROW(FormatError("number is too big")); 3556 return value; 3557 } 3558 3559 inline void require_numeric_argument(const Arg &arg, char spec) { 3560 if (arg.type > Arg::LAST_NUMERIC_TYPE) { 3561 std::string message = 3562 fmt::format("format specifier '{}' requires numeric argument", spec); 3563 FMT_THROW(fmt::FormatError(message)); 3564 } 3565 } 3566 3567 template <typename Char> 3568 void check_sign(const Char *&s, const Arg &arg) { 3569 char sign = static_cast<char>(*s); 3570 require_numeric_argument(arg, sign); 3571 if (arg.type == Arg::UINT || arg.type == Arg::ULONG_LONG) { 3572 FMT_THROW(FormatError(fmt::format( 3573 "format specifier '{}' requires signed argument", sign))); 3574 } 3575 ++s; 3576 } 3577 } // namespace internal 3578 3579 template <typename Char, typename AF> 3580 inline internal::Arg BasicFormatter<Char, AF>::get_arg( 3581 BasicStringRef<Char> arg_name, const char *&error) { 3582 if (check_no_auto_index(error)) { 3583 map_.init(args()); 3584 const internal::Arg *arg = map_.find(arg_name); 3585 if (arg) 3586 return *arg; 3587 error = "argument not found"; 3588 } 3589 return internal::Arg(); 3590 } 3591 3592 template <typename Char, typename AF> 3593 inline internal::Arg BasicFormatter<Char, AF>::parse_arg_index(const Char *&s) { 3594 const char *error = 0; 3595 internal::Arg arg = *s < '0' || *s > '9' ? 3596 next_arg(error) : get_arg(internal::parse_nonnegative_int(s), error); 3597 if (error) { 3598 FMT_THROW(FormatError( 3599 *s != '}' && *s != ':' ? "invalid format string" : error)); 3600 } 3601 return arg; 3602 } 3603 3604 template <typename Char, typename AF> 3605 inline internal::Arg BasicFormatter<Char, AF>::parse_arg_name(const Char *&s) { 3606 assert(internal::is_name_start(*s)); 3607 const Char *start = s; 3608 Char c; 3609 do { 3610 c = *++s; 3611 } while (internal::is_name_start(c) || ('0' <= c && c <= '9')); 3612 const char *error = 0; 3613 internal::Arg arg = get_arg(BasicStringRef<Char>(start, s - start), error); 3614 if (error) 3615 FMT_THROW(FormatError(error)); 3616 return arg; 3617 } 3618 3619 template <typename Char, typename ArgFormatter> 3620 const Char *BasicFormatter<Char, ArgFormatter>::format( 3621 const Char *&format_str, const internal::Arg &arg) { 3622 using internal::Arg; 3623 const Char *s = format_str; 3624 FormatSpec spec; 3625 if (*s == ':') { 3626 if (arg.type == Arg::CUSTOM) { 3627 arg.custom.format(this, arg.custom.value, &s); 3628 return s; 3629 } 3630 ++s; 3631 // Parse fill and alignment. 3632 if (Char c = *s) { 3633 const Char *p = s + 1; 3634 spec.align_ = ALIGN_DEFAULT; 3635 do { 3636 switch (*p) { 3637 case '<': 3638 spec.align_ = ALIGN_LEFT; 3639 break; 3640 case '>': 3641 spec.align_ = ALIGN_RIGHT; 3642 break; 3643 case '=': 3644 spec.align_ = ALIGN_NUMERIC; 3645 break; 3646 case '^': 3647 spec.align_ = ALIGN_CENTER; 3648 break; 3649 } 3650 if (spec.align_ != ALIGN_DEFAULT) { 3651 if (p != s) { 3652 if (c == '}') break; 3653 if (c == '{') 3654 FMT_THROW(FormatError("invalid fill character '{'")); 3655 s += 2; 3656 spec.fill_ = c; 3657 } else ++s; 3658 if (spec.align_ == ALIGN_NUMERIC) 3659 require_numeric_argument(arg, '='); 3660 break; 3661 } 3662 } while (--p >= s); 3663 } 3664 3665 // Parse sign. 3666 switch (*s) { 3667 case '+': 3668 check_sign(s, arg); 3669 spec.flags_ |= SIGN_FLAG | PLUS_FLAG; 3670 break; 3671 case '-': 3672 check_sign(s, arg); 3673 spec.flags_ |= MINUS_FLAG; 3674 break; 3675 case ' ': 3676 check_sign(s, arg); 3677 spec.flags_ |= SIGN_FLAG; 3678 break; 3679 } 3680 3681 if (*s == '#') { 3682 require_numeric_argument(arg, '#'); 3683 spec.flags_ |= HASH_FLAG; 3684 ++s; 3685 } 3686 3687 // Parse zero flag. 3688 if (*s == '0') { 3689 require_numeric_argument(arg, '0'); 3690 spec.align_ = ALIGN_NUMERIC; 3691 spec.fill_ = '0'; 3692 ++s; 3693 } 3694 3695 // Parse width. 3696 if ('0' <= *s && *s <= '9') { 3697 spec.width_ = internal::parse_nonnegative_int(s); 3698 } else if (*s == '{') { 3699 ++s; 3700 Arg width_arg = internal::is_name_start(*s) ? 3701 parse_arg_name(s) : parse_arg_index(s); 3702 if (*s++ != '}') 3703 FMT_THROW(FormatError("invalid format string")); 3704 ULongLong value = 0; 3705 switch (width_arg.type) { 3706 case Arg::INT: 3707 if (width_arg.int_value < 0) 3708 FMT_THROW(FormatError("negative width")); 3709 value = width_arg.int_value; 3710 break; 3711 case Arg::UINT: 3712 value = width_arg.uint_value; 3713 break; 3714 case Arg::LONG_LONG: 3715 if (width_arg.long_long_value < 0) 3716 FMT_THROW(FormatError("negative width")); 3717 value = width_arg.long_long_value; 3718 break; 3719 case Arg::ULONG_LONG: 3720 value = width_arg.ulong_long_value; 3721 break; 3722 default: 3723 FMT_THROW(FormatError("width is not integer")); 3724 } 3725 if (value > (std::numeric_limits<int>::max)()) 3726 FMT_THROW(FormatError("number is too big")); 3727 spec.width_ = static_cast<int>(value); 3728 } 3729 3730 // Parse precision. 3731 if (*s == '.') { 3732 ++s; 3733 spec.precision_ = 0; 3734 if ('0' <= *s && *s <= '9') { 3735 spec.precision_ = internal::parse_nonnegative_int(s); 3736 } else if (*s == '{') { 3737 ++s; 3738 Arg precision_arg = internal::is_name_start(*s) ? 3739 parse_arg_name(s) : parse_arg_index(s); 3740 if (*s++ != '}') 3741 FMT_THROW(FormatError("invalid format string")); 3742 ULongLong value = 0; 3743 switch (precision_arg.type) { 3744 case Arg::INT: 3745 if (precision_arg.int_value < 0) 3746 FMT_THROW(FormatError("negative precision")); 3747 value = precision_arg.int_value; 3748 break; 3749 case Arg::UINT: 3750 value = precision_arg.uint_value; 3751 break; 3752 case Arg::LONG_LONG: 3753 if (precision_arg.long_long_value < 0) 3754 FMT_THROW(FormatError("negative precision")); 3755 value = precision_arg.long_long_value; 3756 break; 3757 case Arg::ULONG_LONG: 3758 value = precision_arg.ulong_long_value; 3759 break; 3760 default: 3761 FMT_THROW(FormatError("precision is not integer")); 3762 } 3763 if (value > (std::numeric_limits<int>::max)()) 3764 FMT_THROW(FormatError("number is too big")); 3765 spec.precision_ = static_cast<int>(value); 3766 } else { 3767 FMT_THROW(FormatError("missing precision specifier")); 3768 } 3769 if (arg.type <= Arg::LAST_INTEGER_TYPE || arg.type == Arg::POINTER) { 3770 FMT_THROW(FormatError( 3771 fmt::format("precision not allowed in {} format specifier", 3772 arg.type == Arg::POINTER ? "pointer" : "integer"))); 3773 } 3774 } 3775 3776 // Parse type. 3777 if (*s != '}' && *s) 3778 spec.type_ = static_cast<char>(*s++); 3779 } 3780 3781 if (*s++ != '}') 3782 FMT_THROW(FormatError("missing '}' in format string")); 3783 3784 // Format argument. 3785 ArgFormatter(*this, spec, s - 1).visit(arg); 3786 return s; 3787 } 3788 3789 template <typename Char, typename AF> 3790 void BasicFormatter<Char, AF>::format(BasicCStringRef<Char> format_str) { 3791 const Char *s = format_str.c_str(); 3792 const Char *start = s; 3793 while (*s) { 3794 Char c = *s++; 3795 if (c != '{' && c != '}') continue; 3796 if (*s == c) { 3797 write(writer_, start, s); 3798 start = ++s; 3799 continue; 3800 } 3801 if (c == '}') 3802 FMT_THROW(FormatError("unmatched '}' in format string")); 3803 write(writer_, start, s - 1); 3804 internal::Arg arg = internal::is_name_start(*s) ? 3805 parse_arg_name(s) : parse_arg_index(s); 3806 start = s = format(s, arg); 3807 } 3808 write(writer_, start, s); 3809 } 3810 } // namespace fmt 3811 3812 #if FMT_USE_USER_DEFINED_LITERALS 3813 namespace fmt { 3814 namespace internal { 3815 3816 template <typename Char> 3817 struct UdlFormat { 3818 const Char *str; 3819 3820 template <typename... Args> 3821 auto operator()(Args && ... args) const 3822 -> decltype(format(str, std::forward<Args>(args)...)) { 3823 return format(str, std::forward<Args>(args)...); 3824 } 3825 }; 3826 3827 template <typename Char> 3828 struct UdlArg { 3829 const Char *str; 3830 3831 template <typename T> 3832 NamedArg<Char> operator=(T &&value) const { 3833 return {str, std::forward<T>(value)}; 3834 } 3835 }; 3836 3837 } // namespace internal 3838 3839 inline namespace literals { 3840 3841 /** 3842 \rst 3843 C++11 literal equivalent of :func:`fmt::format`. 3844 3845 **Example**:: 3846 3847 using namespace fmt::literals; 3848 std::string message = "The answer is {}"_format(42); 3849 \endrst 3850 */ 3851 inline internal::UdlFormat<char> 3852 operator"" _format(const char *s, std::size_t) { return {s}; } 3853 inline internal::UdlFormat<wchar_t> 3854 operator"" _format(const wchar_t *s, std::size_t) { return {s}; } 3855 3856 /** 3857 \rst 3858 C++11 literal equivalent of :func:`fmt::arg`. 3859 3860 **Example**:: 3861 3862 using namespace fmt::literals; 3863 print("Elapsed time: {s:.2f} seconds", "s"_a=1.23); 3864 \endrst 3865 */ 3866 inline internal::UdlArg<char> 3867 operator"" _a(const char *s, std::size_t) { return {s}; } 3868 inline internal::UdlArg<wchar_t> 3869 operator"" _a(const wchar_t *s, std::size_t) { return {s}; } 3870 3871 } // inline namespace literals 3872 } // namespace fmt 3873 #endif // FMT_USE_USER_DEFINED_LITERALS 3874 3875 // Restore warnings. 3876 #if FMT_GCC_VERSION >= 406 3877 # pragma GCC diagnostic pop 3878 #endif 3879 3880 #if defined(__clang__) && !defined(FMT_ICC_VERSION) 3881 # pragma clang diagnostic pop 3882 #endif 3883 3884 #ifdef FMT_HEADER_ONLY 3885 # define FMT_FUNC inline 3886 # include "format.cc" 3887 #else 3888 # define FMT_FUNC 3889 #endif 3890 3891 #endif // FMT_FORMAT_H_ 3892