| 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 | #include "format.h" |
| 29 | |
| 30 | #include <string.h> |
| 31 | |
| 32 | #include <cctype> |
| 33 | #include <cerrno> |
| 34 | #include <climits> |
| 35 | #include <cmath> |
| 36 | #include <cstdarg> |
| 37 | #include <cstddef> // for std::ptrdiff_t |
| 38 | |
| 39 | #if defined(_WIN32) && defined(__MINGW32__) |
| 40 | # include <cstring> |
| 41 | #endif |
| 42 | |
| 43 | #if FMT_USE_WINDOWS_H |
| 44 | # if defined(NOMINMAX) || defined(FMT_WIN_MINMAX) |
| 45 | # include <windows.h> |
| 46 | # else |
| 47 | # define NOMINMAX |
| 48 | # include <windows.h> |
| 49 | # undef NOMINMAX |
| 50 | # endif |
| 51 | #endif |
| 52 | |
| 53 | using fmt::internal::Arg; |
| 54 | |
| 55 | #if FMT_EXCEPTIONS |
| 56 | # define FMT_TRY try |
| 57 | # define FMT_CATCH(x) catch (x) |
| 58 | #else |
| 59 | # define FMT_TRY if (true) |
| 60 | # define FMT_CATCH(x) if (false) |
| 61 | #endif |
| 62 | |
| 63 | #ifdef _MSC_VER |
| 64 | # pragma warning(push) |
| 65 | # pragma warning(disable: 4127) // conditional expression is constant |
| 66 | # pragma warning(disable: 4702) // unreachable code |
| 67 | // Disable deprecation warning for strerror. The latter is not called but |
| 68 | // MSVC fails to detect it. |
| 69 | # pragma warning(disable: 4996) |
| 70 | #endif |
| 71 | |
| 72 | // Dummy implementations of strerror_r and strerror_s called if corresponding |
| 73 | // system functions are not available. |
| 74 | static inline fmt::internal::Null<> strerror_r(int, char *, ...) { |
| 75 | return fmt::internal::Null<>(); |
| 76 | } |
| 77 | static inline fmt::internal::Null<> strerror_s(char *, std::size_t, ...) { |
| 78 | return fmt::internal::Null<>(); |
| 79 | } |
| 80 | |
| 81 | namespace fmt { |
| 82 | |
| 83 | FMT_FUNC internal::RuntimeError::~RuntimeError() throw() {} |
| 84 | FMT_FUNC FormatError::~FormatError() throw() {} |
| 85 | FMT_FUNC SystemError::~SystemError() throw() {} |
| 86 | |
| 87 | namespace { |
| 88 | |
| 89 | #ifndef _MSC_VER |
| 90 | # define FMT_SNPRINTF snprintf |
| 91 | #else // _MSC_VER |
| 92 | inline int fmt_snprintf(char *buffer, size_t size, const char *format, ...) { |
| 93 | va_list args; |
| 94 | va_start(args, format); |
| 95 | int result = vsnprintf_s(buffer, size, _TRUNCATE, format, args); |
| 96 | va_end(args); |
| 97 | return result; |
| 98 | } |
| 99 | # define FMT_SNPRINTF fmt_snprintf |
| 100 | #endif // _MSC_VER |
| 101 | |
| 102 | #if defined(_WIN32) && defined(__MINGW32__) && !defined(__NO_ISOCEXT) |
| 103 | # define FMT_SWPRINTF snwprintf |
| 104 | #else |
| 105 | # define FMT_SWPRINTF swprintf |
| 106 | #endif // defined(_WIN32) && defined(__MINGW32__) && !defined(__NO_ISOCEXT) |
| 107 | |
| 108 | // Checks if a value fits in int - used to avoid warnings about comparing |
| 109 | // signed and unsigned integers. |
| 110 | template <bool IsSigned> |
| 111 | struct IntChecker { |
| 112 | template <typename T> |
| 113 | static bool fits_in_int(T value) { |
| 114 | unsigned max = INT_MAX; |
| 115 | return value <= max; |
| 116 | } |
| 117 | static bool fits_in_int(bool) { return true; } |
| 118 | }; |
| 119 | |
| 120 | template <> |
| 121 | struct IntChecker<true> { |
| 122 | template <typename T> |
| 123 | static bool fits_in_int(T value) { |
| 124 | return value >= INT_MIN && value <= INT_MAX; |
| 125 | } |
| 126 | static bool fits_in_int(int) { return true; } |
| 127 | }; |
| 128 | |
| 129 | const char RESET_COLOR[] = "\x1b[0m"; |
| 130 | |
| 131 | typedef void(*FormatFunc)(Writer &, int, StringRef); |
| 132 | |
| 133 | // Portable thread-safe version of strerror. |
| 134 | // Sets buffer to point to a string describing the error code. |
| 135 | // This can be either a pointer to a string stored in buffer, |
| 136 | // or a pointer to some static immutable string. |
| 137 | // Returns one of the following values: |
| 138 | // 0 - success |
| 139 | // ERANGE - buffer is not large enough to store the error message |
| 140 | // other - failure |
| 141 | // Buffer should be at least of size 1. |
| 142 | int safe_strerror( |
| 143 | int error_code, char *&buffer, std::size_t buffer_size) FMT_NOEXCEPT { |
| 144 | FMT_ASSERT(buffer != 0 && buffer_size != 0, "invalid buffer"); |
| 145 | |
| 146 | class StrError { |
| 147 | private: |
| 148 | int error_code_; |
| 149 | char *&buffer_; |
| 150 | std::size_t buffer_size_; |
| 151 | |
| 152 | // A noop assignment operator to avoid bogus warnings. |
| 153 | void operator=(const StrError &) {} |
| 154 | |
| 155 | // Handle the result of XSI-compliant version of strerror_r. |
| 156 | int handle(int result) { |
| 157 | // glibc versions before 2.13 return result in errno. |
| 158 | return result == -1 ? errno : result; |
| 159 | } |
| 160 | |
| 161 | // Handle the result of GNU-specific version of strerror_r. |
| 162 | int handle(char *message) { |
| 163 | // If the buffer is full then the message is probably truncated. |
| 164 | if (message == buffer_ && strlen(buffer_) == buffer_size_ - 1) |
| 165 | return ERANGE; |
| 166 | buffer_ = message; |
| 167 | return 0; |
| 168 | } |
| 169 | |
| 170 | // Handle the case when strerror_r is not available. |
| 171 | int handle(internal::Null<>) { |
| 172 | return fallback(strerror_s(buffer_, buffer_size_, error_code_)); |
| 173 | } |
| 174 | |
| 175 | // Fallback to strerror_s when strerror_r is not available. |
| 176 | int fallback(int result) { |
| 177 | // If the buffer is full then the message is probably truncated. |
| 178 | return result == 0 && strlen(buffer_) == buffer_size_ - 1 ? |
| 179 | ERANGE : result; |
| 180 | } |
| 181 | |
| 182 | // Fallback to strerror if strerror_r and strerror_s are not available. |
| 183 | int fallback(internal::Null<>) { |
| 184 | errno = 0; |
| 185 | buffer_ = strerror(error_code_); |
| 186 | return errno; |
| 187 | } |
| 188 | |
| 189 | public: |
| 190 | StrError(int err_code, char *&buf, std::size_t buf_size) |
| 191 | : error_code_(err_code), buffer_(buf), buffer_size_(buf_size) {} |
| 192 | |
| 193 | int run() { |
| 194 | strerror_r(0, 0, ""); // Suppress a warning about unused strerror_r. |
| 195 | return handle(strerror_r(error_code_, buffer_, buffer_size_)); |
| 196 | } |
| 197 | }; |
| 198 | return StrError(error_code, buffer, buffer_size).run(); |
| 199 | } |
| 200 | |
| 201 | void format_error_code(Writer &out, int error_code, |
| 202 | StringRef message) FMT_NOEXCEPT { |
| 203 | // Report error code making sure that the output fits into |
| 204 | // INLINE_BUFFER_SIZE to avoid dynamic memory allocation and potential |
| 205 | // bad_alloc. |
| 206 | out.clear(); |
| 207 | static const char SEP[] = ": "; |
| 208 | static const char ERROR_STR[] = "error "; |
| 209 | // Subtract 2 to account for terminating null characters in SEP and ERROR_STR. |
| 210 | std::size_t error_code_size = sizeof(SEP) + sizeof(ERROR_STR) - 2; |
| 211 | typedef internal::IntTraits<int>::MainType MainType; |
| 212 | MainType abs_value = static_cast<MainType>(error_code); |
| 213 | if (internal::is_negative(error_code)) { |
| 214 | abs_value = 0 - abs_value; |
| 215 | ++error_code_size; |
| 216 | } |
| 217 | error_code_size += internal::count_digits(abs_value); |
| 218 | if (message.size() <= internal::INLINE_BUFFER_SIZE - error_code_size) |
| 219 | out << message << SEP; |
| 220 | out << ERROR_STR << error_code; |
| 221 | assert(out.size() <= internal::INLINE_BUFFER_SIZE); |
| 222 | } |
| 223 | |
| 224 | void report_error(FormatFunc func, int error_code, |
| 225 | StringRef message) FMT_NOEXCEPT { |
| 226 | MemoryWriter full_message; |
| 227 | func(full_message, error_code, message); |
| 228 | // Use Writer::data instead of Writer::c_str to avoid potential memory |
| 229 | // allocation. |
| 230 | std::fwrite(full_message.data(), full_message.size(), 1, stderr); |
| 231 | std::fputc('\n', stderr); |
| 232 | } |
| 233 | |
| 234 | // IsZeroInt::visit(arg) returns true iff arg is a zero integer. |
| 235 | class IsZeroInt : public ArgVisitor<IsZeroInt, bool> { |
| 236 | public: |
| 237 | template <typename T> |
| 238 | bool visit_any_int(T value) { return value == 0; } |
| 239 | }; |
| 240 | |
| 241 | // Checks if an argument is a valid printf width specifier and sets |
| 242 | // left alignment if it is negative. |
| 243 | class WidthHandler : public ArgVisitor<WidthHandler, unsigned> { |
| 244 | private: |
| 245 | FormatSpec &spec_; |
| 246 | |
| 247 | FMT_DISALLOW_COPY_AND_ASSIGN(WidthHandler); |
| 248 | |
| 249 | public: |
| 250 | explicit WidthHandler(FormatSpec &spec) : spec_(spec) {} |
| 251 | |
| 252 | void report_unhandled_arg() { |
| 253 | FMT_THROW(FormatError("width is not integer")); |
| 254 | } |
| 255 | |
| 256 | template <typename T> |
| 257 | unsigned visit_any_int(T value) { |
| 258 | typedef typename internal::IntTraits<T>::MainType UnsignedType; |
| 259 | UnsignedType width = static_cast<UnsignedType>(value); |
| 260 | if (internal::is_negative(value)) { |
| 261 | spec_.align_ = ALIGN_LEFT; |
| 262 | width = 0 - width; |
| 263 | } |
| 264 | if (width > INT_MAX) |
| 265 | FMT_THROW(FormatError("number is too big")); |
| 266 | return static_cast<unsigned>(width); |
| 267 | } |
| 268 | }; |
| 269 | |
| 270 | class PrecisionHandler : public ArgVisitor<PrecisionHandler, int> { |
| 271 | public: |
| 272 | void report_unhandled_arg() { |
| 273 | FMT_THROW(FormatError("precision is not integer")); |
| 274 | } |
| 275 | |
| 276 | template <typename T> |
| 277 | int visit_any_int(T value) { |
| 278 | if (!IntChecker<std::numeric_limits<T>::is_signed>::fits_in_int(value)) |
| 279 | FMT_THROW(FormatError("number is too big")); |
| 280 | return static_cast<int>(value); |
| 281 | } |
| 282 | }; |
| 283 | |
| 284 | template <typename T, typename U> |
| 285 | struct is_same { |
| 286 | enum { value = 0 }; |
| 287 | }; |
| 288 | |
| 289 | template <typename T> |
| 290 | struct is_same<T, T> { |
| 291 | enum { value = 1 }; |
| 292 | }; |
| 293 | |
| 294 | // An argument visitor that converts an integer argument to T for printf, |
| 295 | // if T is an integral type. If T is void, the argument is converted to |
| 296 | // corresponding signed or unsigned type depending on the type specifier: |
| 297 | // 'd' and 'i' - signed, other - unsigned) |
| 298 | template <typename T = void> |
| 299 | class ArgConverter : public ArgVisitor<ArgConverter<T>, void> { |
| 300 | private: |
| 301 | internal::Arg &arg_; |
| 302 | wchar_t type_; |
| 303 | |
| 304 | FMT_DISALLOW_COPY_AND_ASSIGN(ArgConverter); |
| 305 | |
| 306 | public: |
| 307 | ArgConverter(internal::Arg &arg, wchar_t type) |
| 308 | : arg_(arg), type_(type) {} |
| 309 | |
| 310 | void visit_bool(bool value) { |
| 311 | if (type_ != 's') |
| 312 | visit_any_int(value); |
| 313 | } |
| 314 | |
| 315 | template <typename U> |
| 316 | void visit_any_int(U value) { |
| 317 | bool is_signed = type_ == 'd' || type_ == 'i'; |
| 318 | using internal::Arg; |
| 319 | typedef typename internal::Conditional< |
| 320 | is_same<T, void>::value, U, T>::type TargetType; |
| 321 | if (sizeof(TargetType) <= sizeof(int)) { |
| 322 | // Extra casts are used to silence warnings. |
| 323 | if (is_signed) { |
| 324 | arg_.type = Arg::INT; |
| 325 | arg_.int_value = static_cast<int>(static_cast<TargetType>(value)); |
| 326 | } |
| 327 | else { |
| 328 | arg_.type = Arg::UINT; |
| 329 | typedef typename internal::MakeUnsigned<TargetType>::Type Unsigned; |
| 330 | arg_.uint_value = static_cast<unsigned>(static_cast<Unsigned>(value)); |
| 331 | } |
| 332 | } |
| 333 | else { |
| 334 | if (is_signed) { |
| 335 | arg_.type = Arg::LONG_LONG; |
| 336 | // glibc's printf doesn't sign extend arguments of smaller types: |
| 337 | // std::printf("%lld", -42); // prints "4294967254" |
| 338 | // but we don't have to do the same because it's a UB. |
| 339 | arg_.long_long_value = static_cast<LongLong>(value); |
| 340 | } |
| 341 | else { |
| 342 | arg_.type = Arg::ULONG_LONG; |
| 343 | arg_.ulong_long_value = |
| 344 | static_cast<typename internal::MakeUnsigned<U>::Type>(value); |
| 345 | } |
| 346 | } |
| 347 | } |
| 348 | }; |
| 349 | |
| 350 | // Converts an integer argument to char for printf. |
| 351 | class CharConverter : public ArgVisitor<CharConverter, void> { |
| 352 | private: |
| 353 | internal::Arg &arg_; |
| 354 | |
| 355 | FMT_DISALLOW_COPY_AND_ASSIGN(CharConverter); |
| 356 | |
| 357 | public: |
| 358 | explicit CharConverter(internal::Arg &arg) : arg_(arg) {} |
| 359 | |
| 360 | template <typename T> |
| 361 | void visit_any_int(T value) { |
| 362 | arg_.type = internal::Arg::CHAR; |
| 363 | arg_.int_value = static_cast<char>(value); |
| 364 | } |
| 365 | }; |
| 366 | } // namespace |
| 367 | |
| 368 | namespace internal { |
| 369 | |
| 370 | template <typename Char> |
| 371 | class PrintfArgFormatter : |
| 372 | public ArgFormatterBase<PrintfArgFormatter<Char>, Char> { |
| 373 | |
| 374 | void write_null_pointer() { |
| 375 | this->spec().type_ = 0; |
| 376 | this->write("(nil)"); |
| 377 | } |
| 378 | |
| 379 | typedef ArgFormatterBase<PrintfArgFormatter<Char>, Char> Base; |
| 380 | |
| 381 | public: |
| 382 | PrintfArgFormatter(BasicWriter<Char> &w, FormatSpec &s) |
| 383 | : ArgFormatterBase<PrintfArgFormatter<Char>, Char>(w, s) {} |
| 384 | |
| 385 | void visit_bool(bool value) { |
| 386 | FormatSpec &fmt_spec = this->spec(); |
| 387 | if (fmt_spec.type_ != 's') |
| 388 | return this->visit_any_int(value); |
| 389 | fmt_spec.type_ = 0; |
| 390 | this->write(value); |
| 391 | } |
| 392 | |
| 393 | void visit_char(int value) { |
| 394 | const FormatSpec &fmt_spec = this->spec(); |
| 395 | BasicWriter<Char> &w = this->writer(); |
| 396 | if (fmt_spec.type_ && fmt_spec.type_ != 'c') |
| 397 | w.write_int(value, fmt_spec); |
| 398 | typedef typename BasicWriter<Char>::CharPtr CharPtr; |
| 399 | CharPtr out = CharPtr(); |
| 400 | if (fmt_spec.width_ > 1) { |
| 401 | Char fill = ' '; |
| 402 | out = w.grow_buffer(fmt_spec.width_); |
| 403 | if (fmt_spec.align_ != ALIGN_LEFT) { |
| 404 | std::fill_n(out, fmt_spec.width_ - 1, fill); |
| 405 | out += fmt_spec.width_ - 1; |
| 406 | } |
| 407 | else { |
| 408 | std::fill_n(out + 1, fmt_spec.width_ - 1, fill); |
| 409 | } |
| 410 | } |
| 411 | else { |
| 412 | out = w.grow_buffer(1); |
| 413 | } |
| 414 | *out = static_cast<Char>(value); |
| 415 | } |
| 416 | |
| 417 | void visit_cstring(const char *value) { |
| 418 | if (value) |
| 419 | Base::visit_cstring(value); |
| 420 | else if (this->spec().type_ == 'p') |
| 421 | write_null_pointer(); |
| 422 | else |
| 423 | this->write("(null)"); |
| 424 | } |
| 425 | |
| 426 | void visit_pointer(const void *value) { |
| 427 | if (value) |
| 428 | return Base::visit_pointer(value); |
| 429 | this->spec().type_ = 0; |
| 430 | write_null_pointer(); |
| 431 | } |
| 432 | |
| 433 | void visit_custom(Arg::CustomValue c) { |
| 434 | BasicFormatter<Char> formatter(ArgList(), this->writer()); |
| 435 | const Char format_str[] = { '}', 0 }; |
| 436 | const Char *format = format_str; |
| 437 | c.format(&formatter, c.value, &format); |
| 438 | } |
| 439 | }; |
| 440 | } // namespace internal |
| 441 | } // namespace fmt |
| 442 | |
| 443 | FMT_FUNC void fmt::SystemError::init( |
| 444 | int err_code, CStringRef format_str, ArgList args) { |
| 445 | error_code_ = err_code; |
| 446 | MemoryWriter w; |
| 447 | internal::format_system_error(w, err_code, format(format_str, args)); |
| 448 | std::runtime_error &base = *this; |
| 449 | base = std::runtime_error(w.str()); |
| 450 | } |
| 451 | |
| 452 | template <typename T> |
| 453 | int fmt::internal::CharTraits<char>::format_float( |
| 454 | char *buffer, std::size_t size, const char *format, |
| 455 | unsigned width, int precision, T value) { |
| 456 | if (width == 0) { |
| 457 | return precision < 0 ? |
| 458 | FMT_SNPRINTF(buffer, size, format, value) : |
| 459 | FMT_SNPRINTF(buffer, size, format, precision, value); |
| 460 | } |
| 461 | return precision < 0 ? |
| 462 | FMT_SNPRINTF(buffer, size, format, width, value) : |
| 463 | FMT_SNPRINTF(buffer, size, format, width, precision, value); |
| 464 | } |
| 465 | |
| 466 | template <typename T> |
| 467 | int fmt::internal::CharTraits<wchar_t>::format_float( |
| 468 | wchar_t *buffer, std::size_t size, const wchar_t *format, |
| 469 | unsigned width, int precision, T value) { |
| 470 | if (width == 0) { |
| 471 | return precision < 0 ? |
| 472 | FMT_SWPRINTF(buffer, size, format, value) : |
| 473 | FMT_SWPRINTF(buffer, size, format, precision, value); |
| 474 | } |
| 475 | return precision < 0 ? |
| 476 | FMT_SWPRINTF(buffer, size, format, width, value) : |
| 477 | FMT_SWPRINTF(buffer, size, format, width, precision, value); |
| 478 | } |
| 479 | |
| 480 | template <typename T> |
| 481 | const char fmt::internal::BasicData<T>::DIGITS[] = |
| 482 | "0001020304050607080910111213141516171819" |
| 483 | "2021222324252627282930313233343536373839" |
| 484 | "4041424344454647484950515253545556575859" |
| 485 | "6061626364656667686970717273747576777879" |
| 486 | "8081828384858687888990919293949596979899"; |
| 487 | |
| 488 | #define FMT_POWERS_OF_10(factor) \ |
| 489 | factor * 10, \ |
| 490 | factor * 100, \ |
| 491 | factor * 1000, \ |
| 492 | factor * 10000, \ |
| 493 | factor * 100000, \ |
| 494 | factor * 1000000, \ |
| 495 | factor * 10000000, \ |
| 496 | factor * 100000000, \ |
| 497 | factor * 1000000000 |
| 498 | |
| 499 | template <typename T> |
| 500 | const uint32_t fmt::internal::BasicData<T>::POWERS_OF_10_32[] = { |
| 501 | 0, FMT_POWERS_OF_10(1) |
| 502 | }; |
| 503 | |
| 504 | template <typename T> |
| 505 | const uint64_t fmt::internal::BasicData<T>::POWERS_OF_10_64[] = { |
| 506 | 0, |
| 507 | FMT_POWERS_OF_10(1), |
| 508 | FMT_POWERS_OF_10(fmt::ULongLong(1000000000)), |
| 509 | // Multiply several constants instead of using a single long long constant |
| 510 | // to avoid warnings about C++98 not supporting long long. |
| 511 | fmt::ULongLong(1000000000) * fmt::ULongLong(1000000000) * 10 |
| 512 | }; |
| 513 | |
| 514 | FMT_FUNC void fmt::internal::report_unknown_type(char code, const char *type) { |
| 515 | (void)type; |
| 516 | if (std::isprint(static_cast<unsigned char>(code))) { |
| 517 | FMT_THROW(fmt::FormatError( |
| 518 | fmt::format("unknown format code '{}' for {}", code, type))); |
| 519 | } |
| 520 | FMT_THROW(fmt::FormatError( |
| 521 | fmt::format("unknown format code '\\x{:02x}' for {}", |
| 522 | static_cast<unsigned>(code), type))); |
| 523 | } |
| 524 | |
| 525 | #if FMT_USE_WINDOWS_H |
| 526 | |
| 527 | FMT_FUNC fmt::internal::UTF8ToUTF16::UTF8ToUTF16(fmt::StringRef s) { |
| 528 | static const char ERROR_MSG[] = "cannot convert string from UTF-8 to UTF-16"; |
| 529 | if (s.size() > INT_MAX) |
| 530 | FMT_THROW(WindowsError(ERROR_INVALID_PARAMETER, ERROR_MSG)); |
| 531 | int s_size = static_cast<int>(s.size()); |
| 532 | int length = MultiByteToWideChar( |
| 533 | CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), s_size, 0, 0); |
| 534 | if (length == 0) |
| 535 | FMT_THROW(WindowsError(GetLastError(), ERROR_MSG)); |
| 536 | buffer_.resize(length + 1); |
| 537 | length = MultiByteToWideChar( |
| 538 | CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), s_size, &buffer_[0], length); |
| 539 | if (length == 0) |
| 540 | FMT_THROW(WindowsError(GetLastError(), ERROR_MSG)); |
| 541 | buffer_[length] = 0; |
| 542 | } |
| 543 | |
| 544 | FMT_FUNC fmt::internal::UTF16ToUTF8::UTF16ToUTF8(fmt::WStringRef s) { |
| 545 | if (int error_code = convert(s)) { |
| 546 | FMT_THROW(WindowsError(error_code, |
| 547 | "cannot convert string from UTF-16 to UTF-8")); |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | FMT_FUNC int fmt::internal::UTF16ToUTF8::convert(fmt::WStringRef s) { |
| 552 | if (s.size() > INT_MAX) |
| 553 | return ERROR_INVALID_PARAMETER; |
| 554 | int s_size = static_cast<int>(s.size()); |
| 555 | int length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, 0, 0, 0, 0); |
| 556 | if (length == 0) |
| 557 | return GetLastError(); |
| 558 | buffer_.resize(length + 1); |
| 559 | length = WideCharToMultiByte( |
| 560 | CP_UTF8, 0, s.data(), s_size, &buffer_[0], length, 0, 0); |
| 561 | if (length == 0) |
| 562 | return GetLastError(); |
| 563 | buffer_[length] = 0; |
| 564 | return 0; |
| 565 | } |
| 566 | |
| 567 | FMT_FUNC void fmt::WindowsError::init( |
| 568 | int err_code, CStringRef format_str, ArgList args) { |
| 569 | error_code_ = err_code; |
| 570 | MemoryWriter w; |
| 571 | internal::format_windows_error(w, err_code, format(format_str, args)); |
| 572 | std::runtime_error &base = *this; |
| 573 | base = std::runtime_error(w.str()); |
| 574 | } |
| 575 | |
| 576 | FMT_FUNC void fmt::internal::format_windows_error( |
| 577 | fmt::Writer &out, int error_code, |
| 578 | fmt::StringRef message) FMT_NOEXCEPT { |
| 579 | FMT_TRY{ |
| 580 | MemoryBuffer<wchar_t, INLINE_BUFFER_SIZE> buffer; |
| 581 | buffer.resize(INLINE_BUFFER_SIZE); |
| 582 | for (;;) { |
| 583 | wchar_t *system_message = &buffer[0]; |
| 584 | int result = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, |
| 585 | 0, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), |
| 586 | system_message, static_cast<uint32_t>(buffer.size()), 0); |
| 587 | if (result != 0) { |
| 588 | UTF16ToUTF8 utf8_message; |
| 589 | if (utf8_message.convert(system_message) == ERROR_SUCCESS) { |
| 590 | out << message << ": " << utf8_message; |
| 591 | return; |
| 592 | } |
| 593 | break; |
| 594 | } |
| 595 | if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) |
| 596 | break; // Can't get error message, report error code instead. |
| 597 | buffer.resize(buffer.size() * 2); |
| 598 | } |
| 599 | } FMT_CATCH(...) {} |
| 600 | fmt::format_error_code(out, error_code, message); // 'fmt::' is for bcc32. |
| 601 | } |
| 602 | |
| 603 | #endif // FMT_USE_WINDOWS_H |
| 604 | |
| 605 | FMT_FUNC void fmt::internal::format_system_error( |
| 606 | fmt::Writer &out, int error_code, |
| 607 | fmt::StringRef message) FMT_NOEXCEPT { |
| 608 | FMT_TRY{ |
| 609 | MemoryBuffer<char, INLINE_BUFFER_SIZE> buffer; |
| 610 | buffer.resize(INLINE_BUFFER_SIZE); |
| 611 | for (;;) { |
| 612 | char *system_message = &buffer[0]; |
| 613 | int result = safe_strerror(error_code, system_message, buffer.size()); |
| 614 | if (result == 0) { |
| 615 | out << message << ": " << system_message; |
| 616 | return; |
| 617 | } |
| 618 | if (result != ERANGE) |
| 619 | break; // Can't get error message, report error code instead. |
| 620 | buffer.resize(buffer.size() * 2); |
| 621 | } |
| 622 | } FMT_CATCH(...) {} |
| 623 | fmt::format_error_code(out, error_code, message); // 'fmt::' is for bcc32. |
| 624 | } |
| 625 | |
| 626 | template <typename Char> |
| 627 | void fmt::internal::ArgMap<Char>::init(const ArgList &args) { |
| 628 | if (!map_.empty()) |
| 629 | return; |
| 630 | typedef internal::NamedArg<Char> NamedArg; |
| 631 | const NamedArg *named_arg = 0; |
| 632 | bool use_values = |
| 633 | args.type(ArgList::MAX_PACKED_ARGS - 1) == internal::Arg::NONE; |
| 634 | if (use_values) { |
| 635 | for (unsigned i = 0;/*nothing*/; ++i) { |
| 636 | internal::Arg::Type arg_type = args.type(i); |
| 637 | switch (arg_type) { |
| 638 | case internal::Arg::NONE: |
| 639 | return; |
| 640 | case internal::Arg::NAMED_ARG: |
| 641 | named_arg = static_cast<const NamedArg*>(args.values_[i].pointer); |
| 642 | map_.push_back(Pair(named_arg->name, *named_arg)); |
| 643 | break; |
| 644 | default: |
| 645 | /*nothing*/; |
| 646 | } |
| 647 | } |
| 648 | return; |
| 649 | } |
| 650 | for (unsigned i = 0; i != ArgList::MAX_PACKED_ARGS; ++i) { |
| 651 | internal::Arg::Type arg_type = args.type(i); |
| 652 | if (arg_type == internal::Arg::NAMED_ARG) { |
| 653 | named_arg = static_cast<const NamedArg*>(args.args_[i].pointer); |
| 654 | map_.push_back(Pair(named_arg->name, *named_arg)); |
| 655 | } |
| 656 | } |
| 657 | for (unsigned i = ArgList::MAX_PACKED_ARGS;/*nothing*/; ++i) { |
| 658 | switch (args.args_[i].type) { |
| 659 | case internal::Arg::NONE: |
| 660 | return; |
| 661 | case internal::Arg::NAMED_ARG: |
| 662 | named_arg = static_cast<const NamedArg*>(args.args_[i].pointer); |
| 663 | map_.push_back(Pair(named_arg->name, *named_arg)); |
| 664 | break; |
| 665 | default: |
| 666 | /*nothing*/; |
| 667 | } |
| 668 | } |
| 669 | } |
| 670 | |
| 671 | template <typename Char> |
| 672 | void fmt::internal::FixedBuffer<Char>::grow(std::size_t) { |
| 673 | FMT_THROW(std::runtime_error("buffer overflow")); |
| 674 | } |
| 675 | |
| 676 | FMT_FUNC Arg fmt::internal::FormatterBase::do_get_arg( |
| 677 | unsigned arg_index, const char *&error) { |
| 678 | Arg arg = args_[arg_index]; |
| 679 | switch (arg.type) { |
| 680 | case Arg::NONE: |
| 681 | error = "argument index out of range"; |
| 682 | break; |
| 683 | case Arg::NAMED_ARG: |
| 684 | arg = *static_cast<const internal::Arg*>(arg.pointer); |
| 685 | break; |
| 686 | default: |
| 687 | /*nothing*/; |
| 688 | } |
| 689 | return arg; |
| 690 | } |
| 691 | |
| 692 | template <typename Char> |
| 693 | void fmt::internal::PrintfFormatter<Char>::parse_flags( |
| 694 | FormatSpec &spec, const Char *&s) { |
| 695 | for (;;) { |
| 696 | switch (*s++) { |
| 697 | case '-': |
| 698 | spec.align_ = ALIGN_LEFT; |
| 699 | break; |
| 700 | case '+': |
| 701 | spec.flags_ |= SIGN_FLAG | PLUS_FLAG; |
| 702 | break; |
| 703 | case '0': |
| 704 | spec.fill_ = '0'; |
| 705 | break; |
| 706 | case ' ': |
| 707 | spec.flags_ |= SIGN_FLAG; |
| 708 | break; |
| 709 | case '#': |
| 710 | spec.flags_ |= HASH_FLAG; |
| 711 | break; |
| 712 | default: |
| 713 | --s; |
| 714 | return; |
| 715 | } |
| 716 | } |
| 717 | } |
| 718 | |
| 719 | template <typename Char> |
| 720 | Arg fmt::internal::PrintfFormatter<Char>::get_arg( |
| 721 | const Char *s, unsigned arg_index) { |
| 722 | (void)s; |
| 723 | const char *error = 0; |
| 724 | Arg arg = arg_index == UINT_MAX ? |
| 725 | next_arg(error) : FormatterBase::get_arg(arg_index - 1, error); |
| 726 | if (error) |
| 727 | FMT_THROW(FormatError(!*s ? "invalid format string" : error)); |
| 728 | return arg; |
| 729 | } |
| 730 | |
| 731 | template <typename Char> |
| 732 | unsigned fmt::internal::PrintfFormatter<Char>::parse_header( |
| 733 | const Char *&s, FormatSpec &spec) { |
| 734 | unsigned arg_index = UINT_MAX; |
| 735 | Char c = *s; |
| 736 | if (c >= '0' && c <= '9') { |
| 737 | // Parse an argument index (if followed by '$') or a width possibly |
| 738 | // preceded with '0' flag(s). |
| 739 | unsigned value = parse_nonnegative_int(s); |
| 740 | if (*s == '$') { // value is an argument index |
| 741 | ++s; |
| 742 | arg_index = value; |
| 743 | } |
| 744 | else { |
| 745 | if (c == '0') |
| 746 | spec.fill_ = '0'; |
| 747 | if (value != 0) { |
| 748 | // Nonzero value means that we parsed width and don't need to |
| 749 | // parse it or flags again, so return now. |
| 750 | spec.width_ = value; |
| 751 | return arg_index; |
| 752 | } |
| 753 | } |
| 754 | } |
| 755 | parse_flags(spec, s); |
| 756 | // Parse width. |
| 757 | if (*s >= '0' && *s <= '9') { |
| 758 | spec.width_ = parse_nonnegative_int(s); |
| 759 | } |
| 760 | else if (*s == '*') { |
| 761 | ++s; |
| 762 | spec.width_ = WidthHandler(spec).visit(get_arg(s)); |
| 763 | } |
| 764 | return arg_index; |
| 765 | } |
| 766 | |
| 767 | template <typename Char> |
| 768 | void fmt::internal::PrintfFormatter<Char>::format( |
| 769 | BasicWriter<Char> &writer, BasicCStringRef<Char> format_str) { |
| 770 | const Char *start = format_str.c_str(); |
| 771 | const Char *s = start; |
| 772 | while (*s) { |
| 773 | Char c = *s++; |
| 774 | if (c != '%') continue; |
| 775 | if (*s == c) { |
| 776 | write(writer, start, s); |
| 777 | start = ++s; |
| 778 | continue; |
| 779 | } |
| 780 | write(writer, start, s - 1); |
| 781 | |
| 782 | FormatSpec spec; |
| 783 | spec.align_ = ALIGN_RIGHT; |
| 784 | |
| 785 | // Parse argument index, flags and width. |
| 786 | unsigned arg_index = parse_header(s, spec); |
| 787 | |
| 788 | // Parse precision. |
| 789 | if (*s == '.') { |
| 790 | ++s; |
| 791 | if ('0' <= *s && *s <= '9') { |
| 792 | spec.precision_ = static_cast<int>(parse_nonnegative_int(s)); |
| 793 | } |
| 794 | else if (*s == '*') { |
| 795 | ++s; |
| 796 | spec.precision_ = PrecisionHandler().visit(get_arg(s)); |
| 797 | } |
| 798 | } |
| 799 | |
| 800 | Arg arg = get_arg(s, arg_index); |
| 801 | if (spec.flag(HASH_FLAG) && IsZeroInt().visit(arg)) |
| 802 | spec.flags_ &= ~to_unsigned<int>(HASH_FLAG); |
| 803 | if (spec.fill_ == '0') { |
| 804 | if (arg.type <= Arg::LAST_NUMERIC_TYPE) |
| 805 | spec.align_ = ALIGN_NUMERIC; |
| 806 | else |
| 807 | spec.fill_ = ' '; // Ignore '0' flag for non-numeric types. |
| 808 | } |
| 809 | |
| 810 | // Parse length and convert the argument to the required type. |
| 811 | switch (*s++) { |
| 812 | case 'h': |
| 813 | if (*s == 'h') |
| 814 | ArgConverter<signed char>(arg, *++s).visit(arg); |
| 815 | else |
| 816 | ArgConverter<short>(arg, *s).visit(arg); |
| 817 | break; |
| 818 | case 'l': |
| 819 | if (*s == 'l') |
| 820 | ArgConverter<fmt::LongLong>(arg, *++s).visit(arg); |
| 821 | else |
| 822 | ArgConverter<long>(arg, *s).visit(arg); |
| 823 | break; |
| 824 | case 'j': |
| 825 | ArgConverter<intmax_t>(arg, *s).visit(arg); |
| 826 | break; |
| 827 | case 'z': |
| 828 | ArgConverter<std::size_t>(arg, *s).visit(arg); |
| 829 | break; |
| 830 | case 't': |
| 831 | ArgConverter<std::ptrdiff_t>(arg, *s).visit(arg); |
| 832 | break; |
| 833 | case 'L': |
| 834 | // printf produces garbage when 'L' is omitted for long double, no |
| 835 | // need to do the same. |
| 836 | break; |
| 837 | default: |
| 838 | --s; |
| 839 | ArgConverter<void>(arg, *s).visit(arg); |
| 840 | } |
| 841 | |
| 842 | // Parse type. |
| 843 | if (!*s) |
| 844 | FMT_THROW(FormatError("invalid format string")); |
| 845 | spec.type_ = static_cast<char>(*s++); |
| 846 | if (arg.type <= Arg::LAST_INTEGER_TYPE) { |
| 847 | // Normalize type. |
| 848 | switch (spec.type_) { |
| 849 | case 'i': case 'u': |
| 850 | spec.type_ = 'd'; |
| 851 | break; |
| 852 | case 'c': |
| 853 | // TODO: handle wchar_t |
| 854 | CharConverter(arg).visit(arg); |
| 855 | break; |
| 856 | } |
| 857 | } |
| 858 | |
| 859 | start = s; |
| 860 | |
| 861 | // Format argument. |
| 862 | internal::PrintfArgFormatter<Char>(writer, spec).visit(arg); |
| 863 | } |
| 864 | write(writer, start, s); |
| 865 | } |
| 866 | |
| 867 | FMT_FUNC void fmt::report_system_error( |
| 868 | int error_code, fmt::StringRef message) FMT_NOEXCEPT { |
| 869 | // 'fmt::' is for bcc32. |
| 870 | fmt::report_error(internal::format_system_error, error_code, message); |
| 871 | } |
| 872 | |
| 873 | #if FMT_USE_WINDOWS_H |
| 874 | FMT_FUNC void fmt::report_windows_error( |
| 875 | int error_code, fmt::StringRef message) FMT_NOEXCEPT { |
| 876 | // 'fmt::' is for bcc32. |
| 877 | fmt::report_error(internal::format_windows_error, error_code, message); |
| 878 | } |
| 879 | #endif |
| 880 | |
| 881 | FMT_FUNC void fmt::print(std::FILE *f, CStringRef format_str, ArgList args) { |
| 882 | MemoryWriter w; |
| 883 | w.write(format_str, args); |
| 884 | std::fwrite(w.data(), 1, w.size(), f); |
| 885 | } |
| 886 | |
| 887 | FMT_FUNC void fmt::print(CStringRef format_str, ArgList args) { |
| 888 | print(stdout, format_str, args); |
| 889 | } |
| 890 | |
| 891 | FMT_FUNC void fmt::print_colored(Color c, CStringRef format, ArgList args) { |
| 892 | char escape[] = "\x1b[30m"; |
| 893 | escape[3] = static_cast<char>('0' + c); |
| 894 | std::fputs(escape, stdout); |
| 895 | print(format, args); |
| 896 | std::fputs(RESET_COLOR, stdout); |
| 897 | } |
| 898 | |
| 899 | FMT_FUNC int fmt::fprintf(std::FILE *f, CStringRef format, ArgList args) { |
| 900 | MemoryWriter w; |
| 901 | printf(w, format, args); |
| 902 | std::size_t size = w.size(); |
| 903 | return std::fwrite(w.data(), 1, size, f) < size ? -1 : static_cast<int>(size); |
| 904 | } |
| 905 | |
| 906 | #ifndef FMT_HEADER_ONLY |
| 907 | |
| 908 | template struct fmt::internal::BasicData<void>; |
| 909 | |
| 910 | // Explicit instantiations for char. |
| 911 | |
| 912 | template void fmt::internal::FixedBuffer<char>::grow(std::size_t); |
| 913 | |
| 914 | template void fmt::internal::ArgMap<char>::init(const fmt::ArgList &args); |
| 915 | |
| 916 | template void fmt::internal::PrintfFormatter<char>::format( |
| 917 | BasicWriter<char> &writer, CStringRef format); |
| 918 | |
| 919 | template int fmt::internal::CharTraits<char>::format_float( |
| 920 | char *buffer, std::size_t size, const char *format, |
| 921 | unsigned width, int precision, double value); |
| 922 | |
| 923 | template int fmt::internal::CharTraits<char>::format_float( |
| 924 | char *buffer, std::size_t size, const char *format, |
| 925 | unsigned width, int precision, long double value); |
| 926 | |
| 927 | // Explicit instantiations for wchar_t. |
| 928 | |
| 929 | template void fmt::internal::FixedBuffer<wchar_t>::grow(std::size_t); |
| 930 | |
| 931 | template void fmt::internal::ArgMap<wchar_t>::init(const fmt::ArgList &args); |
| 932 | |
| 933 | template void fmt::internal::PrintfFormatter<wchar_t>::format( |
| 934 | BasicWriter<wchar_t> &writer, WCStringRef format); |
| 935 | |
| 936 | template int fmt::internal::CharTraits<wchar_t>::format_float( |
| 937 | wchar_t *buffer, std::size_t size, const wchar_t *format, |
| 938 | unsigned width, int precision, double value); |
| 939 | |
| 940 | template int fmt::internal::CharTraits<wchar_t>::format_float( |
| 941 | wchar_t *buffer, std::size_t size, const wchar_t *format, |
| 942 | unsigned width, int precision, long double value); |
| 943 | |
| 944 | #endif // FMT_HEADER_ONLY |
| 945 | |
| 946 | #ifdef _MSC_VER |
| 947 | # pragma warning(pop) |
| 948 | #endif |