Format the code using clang-format

This commit is contained in:
Victor Zverovich 2019-01-12 18:27:38 -08:00
parent 9a777b9e1c
commit 58b6f8db48
39 changed files with 4734 additions and 5108 deletions

8
.clang-format Normal file
View File

@ -0,0 +1,8 @@
# Run manually to reformat a file:
# clang-format -i --style=file <file>
Language: Cpp
BasedOnStyle: Google
IndentPPDirectives: AfterHash
IndentCaseLabels: false
AlwaysBreakTemplateDeclarations: false
DerivePointerAlignment: false

View File

@ -28,8 +28,9 @@ enum class numeric_system {
// Parses a put_time-like format string and invokes handler actions.
template <typename Char, typename Handler>
FMT_CONSTEXPR const Char *parse_chrono_format(
const Char *begin, const Char *end, Handler &&handler) {
FMT_CONSTEXPR const Char* parse_chrono_format(const Char* begin,
const Char* end,
Handler&& handler) {
auto ptr = begin;
while (ptr != end) {
auto c = *ptr;
@ -38,11 +39,9 @@ FMT_CONSTEXPR const Char *parse_chrono_format(
++ptr;
continue;
}
if (begin != ptr)
handler.on_text(begin, ptr);
if (begin != ptr) handler.on_text(begin, ptr);
++ptr; // consume '%'
if (ptr == end)
throw format_error("invalid format");
if (ptr == end) throw format_error("invalid format");
c = *ptr++;
switch (c) {
case '%':
@ -127,8 +126,7 @@ FMT_CONSTEXPR const Char *parse_chrono_format(
break;
// Alternative representation:
case 'E': {
if (ptr == end)
throw format_error("invalid format");
if (ptr == end) throw format_error("invalid format");
c = *ptr++;
switch (c) {
case 'c':
@ -146,8 +144,7 @@ FMT_CONSTEXPR const Char *parse_chrono_format(
break;
}
case 'O':
if (ptr == end)
throw format_error("invalid format");
if (ptr == end) throw format_error("invalid format");
c = *ptr++;
switch (c) {
case 'w':
@ -177,16 +174,14 @@ FMT_CONSTEXPR const Char *parse_chrono_format(
}
begin = ptr;
}
if (begin != ptr)
handler.on_text(begin, ptr);
if (begin != ptr) handler.on_text(begin, ptr);
return ptr;
}
struct chrono_format_checker {
void report_no_date() { throw format_error("no date"); }
template <typename Char>
void on_text(const Char *, const Char *) {}
template <typename Char> void on_text(const Char*, const Char*) {}
void on_abbr_weekday() { report_no_date(); }
void on_full_weekday() { report_no_date(); }
void on_dec0_weekday(numeric_system) { report_no_date(); }
@ -210,23 +205,22 @@ struct chrono_format_checker {
void on_tz_name() { report_no_date(); }
};
template <typename Int>
inline int to_int(Int value) {
template <typename Int> inline int to_int(Int value) {
FMT_ASSERT(value >= (std::numeric_limits<int>::min)() &&
value <= (std::numeric_limits<int>::max)(), "invalid value");
value <= (std::numeric_limits<int>::max)(),
"invalid value");
return static_cast<int>(value);
}
template <typename FormatContext, typename OutputIt>
struct chrono_formatter {
FormatContext &context;
template <typename FormatContext, typename OutputIt> struct chrono_formatter {
FormatContext& context;
OutputIt out;
std::chrono::seconds s;
std::chrono::milliseconds ms;
typedef typename FormatContext::char_type char_type;
explicit chrono_formatter(FormatContext &ctx, OutputIt o)
explicit chrono_formatter(FormatContext& ctx, OutputIt o)
: context(ctx), out(o) {}
int hour() const { return to_int((s.count() / 3600) % 24); }
@ -251,14 +245,13 @@ struct chrono_formatter {
typedef typename int_traits<int>::main_type main_type;
main_type n = to_unsigned(value);
int num_digits = internal::count_digits(n);
if (width > num_digits)
out = std::fill_n(out, width - num_digits, '0');
if (width > num_digits) out = std::fill_n(out, width - num_digits, '0');
out = format_decimal<char_type>(out, n, num_digits);
}
void format_localized(const tm &time, const char *format) {
void format_localized(const tm& time, const char* format) {
auto locale = context.locale().template get<std::locale>();
auto &facet = std::use_facet<std::time_put<char_type>>(locale);
auto& facet = std::use_facet<std::time_put<char_type>>(locale);
std::basic_ostringstream<char_type> os;
os.imbue(locale);
facet.put(os, os, ' ', &time, format, format + std::strlen(format));
@ -266,7 +259,7 @@ struct chrono_formatter {
std::copy(str.begin(), str.end(), out);
}
void on_text(const char_type *begin, const char_type *end) {
void on_text(const char_type* begin, const char_type* end) {
std::copy(begin, end, out);
}
@ -286,24 +279,21 @@ struct chrono_formatter {
void on_tz_name() {}
void on_24_hour(numeric_system ns) {
if (ns == numeric_system::standard)
return write(hour(), 2);
if (ns == numeric_system::standard) return write(hour(), 2);
auto time = tm();
time.tm_hour = hour();
format_localized(time, "%OH");
}
void on_12_hour(numeric_system ns) {
if (ns == numeric_system::standard)
return write(hour12(), 2);
if (ns == numeric_system::standard) return write(hour12(), 2);
auto time = tm();
time.tm_hour = hour();
format_localized(time, "%OI");
}
void on_minute(numeric_system ns) {
if (ns == numeric_system::standard)
return write(minute(), 2);
if (ns == numeric_system::standard) return write(minute(), 2);
auto time = tm();
time.tm_min = minute();
format_localized(time, "%OM");
@ -341,30 +331,30 @@ struct chrono_formatter {
};
} // namespace internal
template <typename Period> FMT_CONSTEXPR const char *get_units() {
template <typename Period> FMT_CONSTEXPR const char* get_units() {
return FMT_NULL;
}
template <> FMT_CONSTEXPR const char *get_units<std::atto>() { return "as"; }
template <> FMT_CONSTEXPR const char *get_units<std::femto>() { return "fs"; }
template <> FMT_CONSTEXPR const char *get_units<std::pico>() { return "ps"; }
template <> FMT_CONSTEXPR const char *get_units<std::nano>() { return "ns"; }
template <> FMT_CONSTEXPR const char *get_units<std::micro>() { return "µs"; }
template <> FMT_CONSTEXPR const char *get_units<std::milli>() { return "ms"; }
template <> FMT_CONSTEXPR const char *get_units<std::centi>() { return "cs"; }
template <> FMT_CONSTEXPR const char *get_units<std::deci>() { return "ds"; }
template <> FMT_CONSTEXPR const char *get_units<std::ratio<1>>() { return "s"; }
template <> FMT_CONSTEXPR const char *get_units<std::deca>() { return "das"; }
template <> FMT_CONSTEXPR const char *get_units<std::hecto>() { return "hs"; }
template <> FMT_CONSTEXPR const char *get_units<std::kilo>() { return "ks"; }
template <> FMT_CONSTEXPR const char *get_units<std::mega>() { return "Ms"; }
template <> FMT_CONSTEXPR const char *get_units<std::giga>() { return "Gs"; }
template <> FMT_CONSTEXPR const char *get_units<std::tera>() { return "Ts"; }
template <> FMT_CONSTEXPR const char *get_units<std::peta>() { return "Ps"; }
template <> FMT_CONSTEXPR const char *get_units<std::exa>() { return "Es"; }
template <> FMT_CONSTEXPR const char *get_units<std::ratio<60>>() {
template <> FMT_CONSTEXPR const char* get_units<std::atto>() { return "as"; }
template <> FMT_CONSTEXPR const char* get_units<std::femto>() { return "fs"; }
template <> FMT_CONSTEXPR const char* get_units<std::pico>() { return "ps"; }
template <> FMT_CONSTEXPR const char* get_units<std::nano>() { return "ns"; }
template <> FMT_CONSTEXPR const char* get_units<std::micro>() { return "µs"; }
template <> FMT_CONSTEXPR const char* get_units<std::milli>() { return "ms"; }
template <> FMT_CONSTEXPR const char* get_units<std::centi>() { return "cs"; }
template <> FMT_CONSTEXPR const char* get_units<std::deci>() { return "ds"; }
template <> FMT_CONSTEXPR const char* get_units<std::ratio<1>>() { return "s"; }
template <> FMT_CONSTEXPR const char* get_units<std::deca>() { return "das"; }
template <> FMT_CONSTEXPR const char* get_units<std::hecto>() { return "hs"; }
template <> FMT_CONSTEXPR const char* get_units<std::kilo>() { return "ks"; }
template <> FMT_CONSTEXPR const char* get_units<std::mega>() { return "Ms"; }
template <> FMT_CONSTEXPR const char* get_units<std::giga>() { return "Gs"; }
template <> FMT_CONSTEXPR const char* get_units<std::tera>() { return "Ts"; }
template <> FMT_CONSTEXPR const char* get_units<std::peta>() { return "Ps"; }
template <> FMT_CONSTEXPR const char* get_units<std::exa>() { return "Es"; }
template <> FMT_CONSTEXPR const char* get_units<std::ratio<60>>() {
return "m";
}
template <> FMT_CONSTEXPR const char *get_units<std::ratio<3600>>() {
template <> FMT_CONSTEXPR const char* get_units<std::ratio<3600>>() {
return "h";
}
@ -378,12 +368,11 @@ struct formatter<std::chrono::duration<Rep, Period>, Char> {
typedef std::chrono::duration<Rep, Period> duration;
struct spec_handler {
formatter &f;
basic_parse_context<Char> &context;
formatter& f;
basic_parse_context<Char>& context;
basic_string_view<Char> format_str;
template <typename Id>
FMT_CONSTEXPR arg_ref_type make_arg_ref(Id arg_id) {
template <typename Id> FMT_CONSTEXPR arg_ref_type make_arg_ref(Id arg_id) {
context.check_arg_id(arg_id);
return arg_ref_type(arg_id);
}
@ -398,13 +387,12 @@ struct formatter<std::chrono::duration<Rep, Period>, Char> {
return arg_ref_type(context.next_arg_id());
}
void on_error(const char *msg) { throw format_error(msg); }
void on_error(const char* msg) { throw format_error(msg); }
void on_fill(Char fill) { f.spec.fill_ = fill; }
void on_align(alignment align) { f.spec.align_ = align; }
void on_width(unsigned width) { f.spec.width_ = width; }
template <typename Id>
void on_dynamic_width(Id arg_id) {
template <typename Id> void on_dynamic_width(Id arg_id) {
f.width_ref = make_arg_ref(arg_id);
}
};
@ -412,7 +400,7 @@ struct formatter<std::chrono::duration<Rep, Period>, Char> {
public:
formatter() : spec() {}
FMT_CONSTEXPR auto parse(basic_parse_context<Char> &ctx)
FMT_CONSTEXPR auto parse(basic_parse_context<Char>& ctx)
-> decltype(ctx.begin()) {
auto begin = ctx.begin(), end = ctx.end();
if (begin == end) return begin;
@ -421,14 +409,13 @@ struct formatter<std::chrono::duration<Rep, Period>, Char> {
if (begin == end) return begin;
begin = internal::parse_width(begin, end, handler);
end = parse_chrono_format(begin, end, internal::chrono_format_checker());
format_str = basic_string_view<Char>(
&*begin, internal::to_unsigned(end - begin));
format_str =
basic_string_view<Char>(&*begin, internal::to_unsigned(end - begin));
return end;
}
template <typename FormatContext>
auto format(const duration &d, FormatContext &ctx)
-> decltype(ctx.out()) {
auto format(const duration& d, FormatContext& ctx) -> decltype(ctx.out()) {
auto begin = format_str.begin(), end = format_str.end();
// As a possible future optimization, we could avoid extra copying if width
// is not specified.
@ -436,7 +423,7 @@ struct formatter<std::chrono::duration<Rep, Period>, Char> {
typedef output_range<decltype(ctx.out()), Char> range;
basic_writer<range> w(range(ctx.out()));
if (begin == end || *begin == '}') {
if (const char *unit = get_units<Period>())
if (const char* unit = get_units<Period>())
format_to(buf, "{}{}", d.count(), unit);
else if (Period::den == 1)
format_to(buf, "{}[{}]s", d.count(), Period::num);
@ -449,8 +436,8 @@ struct formatter<std::chrono::duration<Rep, Period>, Char> {
f.ms = std::chrono::duration_cast<std::chrono::milliseconds>(d - f.s);
parse_chrono_format(begin, end, f);
}
internal::handle_dynamic_spec<internal::width_checker>(
spec.width_, width_ref, ctx);
internal::handle_dynamic_spec<internal::width_checker>(spec.width_,
width_ref, ctx);
w.write(buf.data(), buf.size(), spec);
return w.out();
}

View File

@ -20,12 +20,12 @@ FMT_API void vprint_colored(color c, string_view format, format_args args);
FMT_API void vprint_colored(color c, wstring_view format, wformat_args args);
template <typename... Args>
inline void print_colored(color c, string_view format_str,
const Args & ... args) {
const Args&... args) {
vprint_colored(c, format_str, make_format_args(args...));
}
template <typename... Args>
inline void print_colored(color c, wstring_view format_str,
const Args & ... args) {
const Args&... args) {
vprint_colored(c, format_str, make_format_args<wformat_context>(args...));
}
@ -226,7 +226,8 @@ struct rgb {
FMT_CONSTEXPR rgb(uint32_t hex)
: r((hex >> 16) & 0xFF), g((hex >> 8) & 0xFF), b(hex & 0xFF) {}
FMT_CONSTEXPR rgb(color hex)
: r((uint32_t(hex) >> 16) & 0xFF), g((uint32_t(hex) >> 8) & 0xFF),
: r((uint32_t(hex) >> 16) & 0xFF),
g((uint32_t(hex) >> 8) & 0xFF),
b(uint32_t(hex) & 0xFF) {}
uint8_t r;
uint8_t g;
@ -237,19 +238,17 @@ namespace internal {
// color is a struct of either a rgb color or a terminal color.
struct color_type {
FMT_CONSTEXPR color_type() FMT_NOEXCEPT
: is_rgb(), value{} {}
FMT_CONSTEXPR color_type(color rgb_color) FMT_NOEXCEPT
: is_rgb(true), value{} {
FMT_CONSTEXPR color_type() FMT_NOEXCEPT : is_rgb(), value{} {}
FMT_CONSTEXPR color_type(color rgb_color) FMT_NOEXCEPT : is_rgb(true),
value{} {
value.rgb_color = static_cast<uint32_t>(rgb_color);
}
FMT_CONSTEXPR color_type(rgb rgb_color) FMT_NOEXCEPT
: is_rgb(true), value{} {
value.rgb_color = (static_cast<uint32_t>(rgb_color.r) << 16)
| (static_cast<uint32_t>(rgb_color.g) << 8) | rgb_color.b;
FMT_CONSTEXPR color_type(rgb rgb_color) FMT_NOEXCEPT : is_rgb(true), value{} {
value.rgb_color = (static_cast<uint32_t>(rgb_color.r) << 16) |
(static_cast<uint32_t>(rgb_color.g) << 8) | rgb_color.b;
}
FMT_CONSTEXPR color_type(terminal_color term_color) FMT_NOEXCEPT
: is_rgb(), value{} {
FMT_CONSTEXPR color_type(terminal_color term_color) FMT_NOEXCEPT : is_rgb(),
value{} {
value.term_color = static_cast<uint8_t>(term_color);
}
bool is_rgb;
@ -264,9 +263,11 @@ struct color_type {
class text_style {
public:
FMT_CONSTEXPR text_style(emphasis em = emphasis()) FMT_NOEXCEPT
: set_foreground_color(), set_background_color(), ems(em) {}
: set_foreground_color(),
set_background_color(),
ems(em) {}
FMT_CONSTEXPR text_style &operator|=(const text_style &rhs) {
FMT_CONSTEXPR text_style& operator|=(const text_style& rhs) {
if (!set_foreground_color) {
set_foreground_color = rhs.set_foreground_color;
foreground_color = rhs.foreground_color;
@ -290,12 +291,12 @@ class text_style {
return *this;
}
friend FMT_CONSTEXPR
text_style operator|(text_style lhs, const text_style &rhs) {
friend FMT_CONSTEXPR text_style operator|(text_style lhs,
const text_style& rhs) {
return lhs |= rhs;
}
FMT_CONSTEXPR text_style &operator&=(const text_style &rhs) {
FMT_CONSTEXPR text_style& operator&=(const text_style& rhs) {
if (!set_foreground_color) {
set_foreground_color = rhs.set_foreground_color;
foreground_color = rhs.foreground_color;
@ -319,8 +320,8 @@ class text_style {
return *this;
}
friend FMT_CONSTEXPR
text_style operator&(text_style lhs, const text_style &rhs) {
friend FMT_CONSTEXPR text_style operator&(text_style lhs,
const text_style& rhs) {
return lhs &= rhs;
}
@ -346,7 +347,7 @@ class text_style {
return ems;
}
private:
private:
FMT_CONSTEXPR text_style(bool is_foreground,
internal::color_type text_color) FMT_NOEXCEPT
: set_foreground_color(),
@ -387,10 +388,9 @@ FMT_CONSTEXPR text_style operator|(emphasis lhs, emphasis rhs) FMT_NOEXCEPT {
namespace internal {
template <typename Char>
struct ansi_color_escape {
template <typename Char> struct ansi_color_escape {
FMT_CONSTEXPR ansi_color_escape(internal::color_type text_color,
const char * esc) FMT_NOEXCEPT {
const char* esc) FMT_NOEXCEPT {
// If we have a terminal color, we need to output another escape code
// sequence.
if (!text_color.is_rgb) {
@ -398,8 +398,7 @@ struct ansi_color_escape {
uint32_t value = text_color.value.term_color;
// Background ASCII codes are the same as the foreground ones but with
// 10 more.
if (is_background)
value += 10u;
if (is_background) value += 10u;
std::size_t index = 0;
buffer[index++] = static_cast<Char>('\x1b');
@ -429,19 +428,15 @@ struct ansi_color_escape {
FMT_CONSTEXPR ansi_color_escape(emphasis em) FMT_NOEXCEPT {
uint8_t em_codes[4] = {};
uint8_t em_bits = static_cast<uint8_t>(em);
if (em_bits & static_cast<uint8_t>(emphasis::bold))
em_codes[0] = 1;
if (em_bits & static_cast<uint8_t>(emphasis::italic))
em_codes[1] = 3;
if (em_bits & static_cast<uint8_t>(emphasis::underline))
em_codes[2] = 4;
if (em_bits & static_cast<uint8_t>(emphasis::bold)) em_codes[0] = 1;
if (em_bits & static_cast<uint8_t>(emphasis::italic)) em_codes[1] = 3;
if (em_bits & static_cast<uint8_t>(emphasis::underline)) em_codes[2] = 4;
if (em_bits & static_cast<uint8_t>(emphasis::strikethrough))
em_codes[3] = 9;
std::size_t index = 0;
for (int i = 0; i < 4; ++i) {
if (!em_codes[i])
continue;
if (!em_codes[i]) continue;
buffer[index++] = static_cast<Char>('\x1b');
buffer[index++] = static_cast<Char>('[');
buffer[index++] = static_cast<Char>('0' + em_codes[i]);
@ -449,19 +444,17 @@ struct ansi_color_escape {
}
buffer[index++] = static_cast<Char>(0);
}
FMT_CONSTEXPR operator const Char *() const FMT_NOEXCEPT { return buffer; }
FMT_CONSTEXPR operator const Char*() const FMT_NOEXCEPT { return buffer; }
FMT_CONSTEXPR const Char * begin() const FMT_NOEXCEPT {
return buffer;
}
FMT_CONSTEXPR const Char * end() const FMT_NOEXCEPT {
FMT_CONSTEXPR const Char* begin() const FMT_NOEXCEPT { return buffer; }
FMT_CONSTEXPR const Char* end() const FMT_NOEXCEPT {
return buffer + std::strlen(buffer);
}
private:
private:
Char buffer[7u + 3u * 4u + 1u];
static FMT_CONSTEXPR void to_esc(uint8_t c, Char *out,
static FMT_CONSTEXPR void to_esc(uint8_t c, Char* out,
char delimiter) FMT_NOEXCEPT {
out[0] = static_cast<Char>('0' + c / 100);
out[1] = static_cast<Char>('0' + c / 10 % 10);
@ -471,40 +464,37 @@ private:
};
template <typename Char>
FMT_CONSTEXPR ansi_color_escape<Char>
make_foreground_color(internal::color_type foreground) FMT_NOEXCEPT {
FMT_CONSTEXPR ansi_color_escape<Char> make_foreground_color(
internal::color_type foreground) FMT_NOEXCEPT {
return ansi_color_escape<Char>(foreground, internal::data::FOREGROUND_COLOR);
}
template <typename Char>
FMT_CONSTEXPR ansi_color_escape<Char>
make_background_color(internal::color_type background) FMT_NOEXCEPT {
FMT_CONSTEXPR ansi_color_escape<Char> make_background_color(
internal::color_type background) FMT_NOEXCEPT {
return ansi_color_escape<Char>(background, internal::data::BACKGROUND_COLOR);
}
template <typename Char>
FMT_CONSTEXPR ansi_color_escape<Char>
make_emphasis(emphasis em) FMT_NOEXCEPT {
FMT_CONSTEXPR ansi_color_escape<Char> make_emphasis(emphasis em) FMT_NOEXCEPT {
return ansi_color_escape<Char>(em);
}
template <typename Char>
inline void fputs(const Char *chars, FILE *stream) FMT_NOEXCEPT {
inline void fputs(const Char* chars, FILE* stream) FMT_NOEXCEPT {
std::fputs(chars, stream);
}
template <>
inline void fputs<wchar_t>(const wchar_t *chars, FILE *stream) FMT_NOEXCEPT {
inline void fputs<wchar_t>(const wchar_t* chars, FILE* stream) FMT_NOEXCEPT {
std::fputws(chars, stream);
}
template <typename Char>
inline void reset_color(FILE *stream) FMT_NOEXCEPT {
template <typename Char> inline void reset_color(FILE* stream) FMT_NOEXCEPT {
fputs(internal::data::RESET_COLOR, stream);
}
template <>
inline void reset_color<wchar_t>(FILE *stream) FMT_NOEXCEPT {
template <> inline void reset_color<wchar_t>(FILE* stream) FMT_NOEXCEPT {
fputs(internal::data::WRESET_COLOR, stream);
}
@ -519,21 +509,18 @@ inline void reset_color(basic_memory_buffer<Char>& buffer) FMT_NOEXCEPT {
// which is needed because or else
// fmt::print(stderr, fmt::emphasis::bold, "");
// would take stderr (a std::FILE *) as the format string.
template <>
struct is_string<std::FILE *> : std::false_type {};
template <>
struct is_string<const std::FILE *> : std::false_type {};
template <> struct is_string<std::FILE*> : std::false_type {};
template <> struct is_string<const std::FILE*> : std::false_type {};
template <typename Char>
std::basic_string<Char> vformat(
const text_style &ts, basic_string_view<Char> format_str,
const text_style& ts, basic_string_view<Char> format_str,
basic_format_args<typename buffer_context<Char>::type> args) {
basic_memory_buffer<Char> buffer;
bool has_style = false;
if (ts.has_emphasis()) {
has_style = true;
ansi_color_escape<Char> escape =
make_emphasis<Char>(ts.get_emphasis());
ansi_color_escape<Char> escape = make_emphasis<Char>(ts.get_emphasis());
buffer.append(escape.begin(), escape.end());
}
if (ts.has_foreground()) {
@ -556,15 +543,13 @@ std::basic_string<Char> vformat(
}
} // namespace internal
template <
typename S, typename Char = typename internal::char_t<S>::type>
void vprint(std::FILE *f, const text_style &ts, const S &format,
template <typename S, typename Char = typename internal::char_t<S>::type>
void vprint(std::FILE* f, const text_style& ts, const S& format,
basic_format_args<typename buffer_context<Char>::type> args) {
bool has_style = false;
if (ts.has_emphasis()) {
has_style = true;
internal::fputs<Char>(
internal::make_emphasis<Char>(ts.get_emphasis()), f);
internal::fputs<Char>(internal::make_emphasis<Char>(ts.get_emphasis()), f);
}
if (ts.has_foreground()) {
has_style = true;
@ -591,8 +576,8 @@ void vprint(std::FILE *f, const text_style &ts, const S &format,
*/
template <typename String, typename... Args>
typename std::enable_if<internal::is_string<String>::value>::type print(
std::FILE *f, const text_style &ts, const String &format_str,
const Args &... args) {
std::FILE* f, const text_style& ts, const String& format_str,
const Args&... args) {
internal::check_format_string<Args...>(format_str);
typedef typename internal::char_t<String>::type char_t;
typedef typename buffer_context<char_t>::type context_t;
@ -609,16 +594,13 @@ typename std::enable_if<internal::is_string<String>::value>::type print(
*/
template <typename String, typename... Args>
typename std::enable_if<internal::is_string<String>::value>::type print(
const text_style &ts, const String &format_str,
const Args &... args) {
const text_style& ts, const String& format_str, const Args&... args) {
return print(stdout, ts, format_str, args...);
}
template <typename S, typename Char = FMT_CHAR(S)>
inline std::basic_string<Char> vformat(
const text_style &ts,
const S &format_str,
const text_style& ts, const S& format_str,
basic_format_args<typename buffer_context<Char>::type> args) {
return internal::vformat(ts, to_string_view(format_str), args);
}
@ -636,8 +618,9 @@ inline std::basic_string<Char> vformat(
\endrst
*/
template <typename S, typename... Args>
inline std::basic_string<FMT_CHAR(S)> format(
const text_style &ts, const S &format_str, const Args &... args) {
inline std::basic_string<FMT_CHAR(S)> format(const text_style& ts,
const S& format_str,
const Args&... args) {
return internal::vformat(
ts, to_string_view(format_str),
*internal::checked_args<S, Args...>(format_str, args...));

File diff suppressed because it is too large Load Diff

View File

@ -46,19 +46,19 @@
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable: 4127) // conditional expression is constant
# pragma warning(disable: 4702) // unreachable code
# pragma warning(disable : 4127) // conditional expression is constant
# pragma warning(disable : 4702) // unreachable code
// Disable deprecation warning for strerror. The latter is not called but
// MSVC fails to detect it.
# pragma warning(disable: 4996)
# pragma warning(disable : 4996)
#endif
// Dummy implementations of strerror_r and strerror_s called if corresponding
// system functions are not available.
inline fmt::internal::null<> strerror_r(int, char *, ...) {
inline fmt::internal::null<> strerror_r(int, char*, ...) {
return fmt::internal::null<>();
}
inline fmt::internal::null<> strerror_s(char *, std::size_t, ...) {
inline fmt::internal::null<> strerror_s(char*, std::size_t, ...) {
return fmt::internal::null<>();
}
@ -69,7 +69,7 @@ namespace {
#ifndef _MSC_VER
# define FMT_SNPRINTF snprintf
#else // _MSC_VER
inline int fmt_snprintf(char *buffer, size_t size, const char *format, ...) {
inline int fmt_snprintf(char* buffer, size_t size, const char* format, ...) {
va_list args;
va_start(args, format);
int result = vsnprintf_s(buffer, size, _TRUNCATE, format, args);
@ -85,7 +85,7 @@ inline int fmt_snprintf(char *buffer, size_t size, const char *format, ...) {
# define FMT_SWPRINTF swprintf
#endif // defined(_WIN32) && defined(__MINGW32__) && !defined(__NO_ISOCEXT)
typedef void (*FormatFunc)(internal::buffer &, int, string_view);
typedef void (*FormatFunc)(internal::buffer&, int, string_view);
// Portable thread-safe version of strerror.
// Sets buffer to point to a string describing the error code.
@ -96,18 +96,18 @@ typedef void (*FormatFunc)(internal::buffer &, int, string_view);
// ERANGE - buffer is not large enough to store the error message
// other - failure
// Buffer should be at least of size 1.
int safe_strerror(
int error_code, char *&buffer, std::size_t buffer_size) FMT_NOEXCEPT {
int safe_strerror(int error_code, char*& buffer,
std::size_t buffer_size) FMT_NOEXCEPT {
FMT_ASSERT(buffer != FMT_NULL && buffer_size != 0, "invalid buffer");
class dispatcher {
private:
int error_code_;
char *&buffer_;
char*& buffer_;
std::size_t buffer_size_;
// A noop assignment operator to avoid bogus warnings.
void operator=(const dispatcher &) {}
void operator=(const dispatcher&) {}
// Handle the result of XSI-compliant version of strerror_r.
int handle(int result) {
@ -116,7 +116,7 @@ int safe_strerror(
}
// Handle the result of GNU-specific version of strerror_r.
int handle(char *message) {
int handle(char* message) {
// If the buffer is full then the message is probably truncated.
if (message == buffer_ && strlen(buffer_) == buffer_size_ - 1)
return ERANGE;
@ -132,8 +132,8 @@ int safe_strerror(
// Fallback to strerror_s when strerror_r is not available.
int fallback(int result) {
// If the buffer is full then the message is probably truncated.
return result == 0 && strlen(buffer_) == buffer_size_ - 1 ?
ERANGE : result;
return result == 0 && strlen(buffer_) == buffer_size_ - 1 ? ERANGE
: result;
}
#if !FMT_MSC_VER
@ -146,17 +146,15 @@ int safe_strerror(
#endif
public:
dispatcher(int err_code, char *&buf, std::size_t buf_size)
dispatcher(int err_code, char*& buf, std::size_t buf_size)
: error_code_(err_code), buffer_(buf), buffer_size_(buf_size) {}
int run() {
return handle(strerror_r(error_code_, buffer_, buffer_size_));
}
int run() { return handle(strerror_r(error_code_, buffer_, buffer_size_)); }
};
return dispatcher(error_code, buffer, buffer_size).run();
}
void format_error_code(internal::buffer &out, int error_code,
void format_error_code(internal::buffer& out, int error_code,
string_view message) FMT_NOEXCEPT {
// Report error code making sure that the output fits into
// inline_buffer_size to avoid dynamic memory allocation and potential
@ -195,11 +193,10 @@ void report_error(FormatFunc func, int error_code,
} // namespace
FMT_FUNC size_t internal::count_code_points(basic_string_view<char8_t> s) {
const char8_t *data = s.data();
const char8_t* data = s.data();
size_t num_code_points = 0;
for (size_t i = 0, size = s.size(); i != size; ++i) {
if ((data[i] & 0xc0) != 0x80)
++num_code_points;
if ((data[i] & 0xc0) != 0x80) ++num_code_points;
}
return num_code_points;
}
@ -208,22 +205,20 @@ FMT_FUNC size_t internal::count_code_points(basic_string_view<char8_t> s) {
namespace internal {
template <typename Locale>
locale_ref::locale_ref(const Locale &loc) : locale_(&loc) {
locale_ref::locale_ref(const Locale& loc) : locale_(&loc) {
static_assert(std::is_same<Locale, std::locale>::value, "");
}
template <typename Locale>
Locale locale_ref::get() const {
template <typename Locale> Locale locale_ref::get() const {
static_assert(std::is_same<Locale, std::locale>::value, "");
return locale_ ? *static_cast<const std::locale*>(locale_) : std::locale();
}
template <typename Char>
FMT_FUNC Char thousands_sep_impl(locale_ref loc) {
return std::use_facet<std::numpunct<Char> >(
loc.get<std::locale>()).thousands_sep();
}
template <typename Char> FMT_FUNC Char thousands_sep_impl(locale_ref loc) {
return std::use_facet<std::numpunct<Char> >(loc.get<std::locale>())
.thousands_sep();
}
} // namespace internal
#else
template <typename Char>
FMT_FUNC Char internal::thousands_sep_impl(locale_ref) {
@ -231,31 +226,30 @@ FMT_FUNC Char internal::thousands_sep_impl(locale_ref) {
}
#endif
FMT_FUNC void system_error::init(
int err_code, string_view format_str, format_args args) {
FMT_FUNC void system_error::init(int err_code, string_view format_str,
format_args args) {
error_code_ = err_code;
memory_buffer buffer;
format_system_error(buffer, err_code, vformat(format_str, args));
std::runtime_error &base = *this;
std::runtime_error& base = *this;
base = std::runtime_error(to_string(buffer));
}
namespace internal {
template <typename T>
int char_traits<char>::format_float(
char *buf, std::size_t size, const char *format, int precision, T value) {
return precision < 0 ?
FMT_SNPRINTF(buf, size, format, value) :
FMT_SNPRINTF(buf, size, format, precision, value);
int char_traits<char>::format_float(char* buf, std::size_t size,
const char* format, int precision,
T value) {
return precision < 0 ? FMT_SNPRINTF(buf, size, format, value)
: FMT_SNPRINTF(buf, size, format, precision, value);
}
template <typename T>
int char_traits<wchar_t>::format_float(
wchar_t *buf, std::size_t size, const wchar_t *format, int precision,
int char_traits<wchar_t>::format_float(wchar_t* buf, std::size_t size,
const wchar_t* format, int precision,
T value) {
return precision < 0 ?
FMT_SWPRINTF(buf, size, format, value) :
FMT_SWPRINTF(buf, size, format, precision, value);
return precision < 0 ? FMT_SWPRINTF(buf, size, format, value)
: FMT_SWPRINTF(buf, size, format, precision, value);
}
template <typename T>
@ -267,33 +261,21 @@ const char basic_data<T>::DIGITS[] =
"8081828384858687888990919293949596979899";
#define FMT_POWERS_OF_10(factor) \
factor * 10, \
factor * 100, \
factor * 1000, \
factor * 10000, \
factor * 100000, \
factor * 1000000, \
factor * 10000000, \
factor * 100000000, \
factor * 10, factor * 100, factor * 1000, factor * 10000, factor * 100000, \
factor * 1000000, factor * 10000000, factor * 100000000, \
factor * 1000000000
template <typename T>
const uint32_t basic_data<T>::POWERS_OF_10_32[] = {
1, FMT_POWERS_OF_10(1)
};
const uint32_t basic_data<T>::POWERS_OF_10_32[] = {1, FMT_POWERS_OF_10(1)};
template <typename T>
const uint32_t basic_data<T>::ZERO_OR_POWERS_OF_10_32[] = {
0, FMT_POWERS_OF_10(1)
};
const uint32_t basic_data<T>::ZERO_OR_POWERS_OF_10_32[] = {0,
FMT_POWERS_OF_10(1)};
template <typename T>
const uint64_t basic_data<T>::ZERO_OR_POWERS_OF_10_64[] = {
0,
FMT_POWERS_OF_10(1),
FMT_POWERS_OF_10(1000000000ull),
10000000000000000000ull
};
0, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ull),
10000000000000000000ull};
// Normalized 64-bit significands of pow(10, k), for k = -348, -340, ..., 340.
// These are generated by support/compute-powers.py.
@ -341,11 +323,12 @@ const int16_t basic_data<T>::POW10_EXPONENTS[] = {
-50, -24, 3, 30, 56, 83, 109, 136, 162, 189, 216,
242, 269, 295, 322, 348, 375, 402, 428, 455, 481, 508,
534, 561, 588, 614, 641, 667, 694, 720, 747, 774, 800,
827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066
};
827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066};
template <typename T> const char basic_data<T>::FOREGROUND_COLOR[] = "\x1b[38;2;";
template <typename T> const char basic_data<T>::BACKGROUND_COLOR[] = "\x1b[48;2;";
template <typename T>
const char basic_data<T>::FOREGROUND_COLOR[] = "\x1b[38;2;";
template <typename T>
const char basic_data<T>::BACKGROUND_COLOR[] = "\x1b[48;2;";
template <typename T> const char basic_data<T>::RESET_COLOR[] = "\x1b[0m";
template <typename T> const wchar_t basic_data<T>::WRESET_COLOR[] = L"\x1b[0m";
@ -371,13 +354,12 @@ class fp {
static FMT_CONSTEXPR_DECL const int significand_size =
sizeof(significand_type) * char_size;
fp(): f(0), e(0) {}
fp(uint64_t f_val, int e_val): f(f_val), e(e_val) {}
fp() : f(0), e(0) {}
fp(uint64_t f_val, int e_val) : f(f_val), e(e_val) {}
// Constructs fp from an IEEE754 double. It is a template to prevent compile
// errors on platforms where double is not IEEE754.
template <typename Double>
explicit fp(Double d) {
template <typename Double> explicit fp(Double d) {
// Assume double is in the format [sign][exponent][significand].
typedef std::numeric_limits<Double> limits;
const int double_size = static_cast<int>(sizeof(Double) * char_size);
@ -397,8 +379,7 @@ class fp {
}
// Normalizes the value converted from double and multiplied by (1 << SHIFT).
template <int SHIFT = 0>
void normalize() {
template <int SHIFT = 0> void normalize() {
// Handle subnormals.
auto shifted_implicit_bit = implicit_bit << SHIFT;
while ((f & shifted_implicit_bit) == 0) {
@ -415,9 +396,9 @@ class fp {
// a boundary is a value half way between the number and its predecessor
// (lower) or successor (upper). The upper boundary is normalized and lower
// has the same exponent but may be not normalized.
void compute_boundaries(fp &lower, fp &upper) const {
lower = f == implicit_bit ?
fp((f << 2) - 1, e - 2) : fp((f << 1) - 1, e - 1);
void compute_boundaries(fp& lower, fp& upper) const {
lower =
f == implicit_bit ? fp((f << 2) - 1, e - 2) : fp((f << 1) - 1, e - 1);
upper = fp((f << 1) + 1, e - 1);
upper.normalize<1>(); // 1 is to account for the exponent shift above.
lower.f <<= lower.e - upper.e;
@ -432,12 +413,13 @@ inline fp operator-(fp x, fp y) {
}
// Computes an fp number r with r.f = x.f * y.f / pow(2, 64) rounded to nearest
// with half-up tie breaking, r.e = x.e + y.e + 64. Result may not be normalized.
// with half-up tie breaking, r.e = x.e + y.e + 64. Result may not be
// normalized.
FMT_API fp operator*(fp x, fp y);
// Returns cached power (of 10) c_k = c_k.f * pow(2, c_k.e) such that its
// (binary) exponent satisfies min_exponent <= c_k.e <= min_exponent + 3.
FMT_API fp get_cached_power(int min_exponent, int &pow10_exponent);
FMT_API fp get_cached_power(int min_exponent, int& pow10_exponent);
FMT_FUNC fp operator*(fp x, fp y) {
// Multiply 32-bit parts of significands.
@ -450,10 +432,10 @@ FMT_FUNC fp operator*(fp x, fp y) {
return fp(ac + (ad >> 32) + (bc >> 32) + (mid >> 32), x.e + y.e + 64);
}
FMT_FUNC fp get_cached_power(int min_exponent, int &pow10_exponent) {
FMT_FUNC fp get_cached_power(int min_exponent, int& pow10_exponent) {
const double one_over_log2_10 = 0.30102999566398114; // 1 / log2(10)
int index = static_cast<int>(std::ceil(
(min_exponent + fp::significand_size - 1) * one_over_log2_10));
int index = static_cast<int>(
std::ceil((min_exponent + fp::significand_size - 1) * one_over_log2_10));
// Decimal exponent of the first (smallest) cached power of 10.
const int first_dec_exp = -348;
// Difference between 2 consecutive decimal exponents in cached powers of 10.
@ -463,10 +445,11 @@ FMT_FUNC fp get_cached_power(int min_exponent, int &pow10_exponent) {
return fp(data::POW10_SIGNIFICANDS[index], data::POW10_EXPONENTS[index]);
}
FMT_FUNC bool grisu2_round(
char *buf, int &size, int max_digits, uint64_t delta,
uint64_t remainder, uint64_t exp, uint64_t diff, int &exp10) {
while (remainder < diff && delta - remainder >= exp &&
FMT_FUNC bool grisu2_round(char* buf, int& size, int max_digits, uint64_t delta,
uint64_t remainder, uint64_t exp, uint64_t diff,
int& exp10) {
while (
remainder < diff && delta - remainder >= exp &&
(remainder + exp < diff || diff - remainder > remainder + exp - diff)) {
--buf[size - 1];
remainder += exp;
@ -474,44 +457,72 @@ FMT_FUNC bool grisu2_round(
if (size > max_digits) {
--size;
++exp10;
if (buf[size] >= '5')
return false;
if (buf[size] >= '5') return false;
}
return true;
}
// Generates output using Grisu2 digit-gen algorithm.
FMT_FUNC bool grisu2_gen_digits(
char *buf, int &size, uint32_t hi, uint64_t lo, int &exp,
uint64_t delta, const fp &one, const fp &diff, int max_digits) {
FMT_FUNC bool grisu2_gen_digits(char* buf, int& size, uint32_t hi, uint64_t lo,
int& exp, uint64_t delta, const fp& one,
const fp& diff, int max_digits) {
// Generate digits for the most significant part (hi).
while (exp > 0) {
uint32_t digit = 0;
// This optimization by miloyip reduces the number of integer divisions by
// one per iteration.
switch (exp) {
case 10: digit = hi / 1000000000; hi %= 1000000000; break;
case 9: digit = hi / 100000000; hi %= 100000000; break;
case 8: digit = hi / 10000000; hi %= 10000000; break;
case 7: digit = hi / 1000000; hi %= 1000000; break;
case 6: digit = hi / 100000; hi %= 100000; break;
case 5: digit = hi / 10000; hi %= 10000; break;
case 4: digit = hi / 1000; hi %= 1000; break;
case 3: digit = hi / 100; hi %= 100; break;
case 2: digit = hi / 10; hi %= 10; break;
case 1: digit = hi; hi = 0; break;
case 10:
digit = hi / 1000000000;
hi %= 1000000000;
break;
case 9:
digit = hi / 100000000;
hi %= 100000000;
break;
case 8:
digit = hi / 10000000;
hi %= 10000000;
break;
case 7:
digit = hi / 1000000;
hi %= 1000000;
break;
case 6:
digit = hi / 100000;
hi %= 100000;
break;
case 5:
digit = hi / 10000;
hi %= 10000;
break;
case 4:
digit = hi / 1000;
hi %= 1000;
break;
case 3:
digit = hi / 100;
hi %= 100;
break;
case 2:
digit = hi / 10;
hi %= 10;
break;
case 1:
digit = hi;
hi = 0;
break;
default:
FMT_ASSERT(false, "invalid number of digits");
}
if (digit != 0 || size != 0)
buf[size++] = static_cast<char>('0' + digit);
if (digit != 0 || size != 0) buf[size++] = static_cast<char>('0' + digit);
--exp;
uint64_t remainder = (static_cast<uint64_t>(hi) << -one.e) + lo;
if (remainder <= delta || size > max_digits) {
return grisu2_round(
buf, size, max_digits, delta, remainder,
static_cast<uint64_t>(data::POWERS_OF_10_32[exp]) << -one.e,
diff.f, exp);
static_cast<uint64_t>(data::POWERS_OF_10_32[exp]) << -one.e, diff.f,
exp);
}
}
// Generate digits for the least significant part (lo).
@ -519,8 +530,7 @@ FMT_FUNC bool grisu2_gen_digits(
lo *= 10;
delta *= 10;
char digit = static_cast<char>(lo >> -one.e);
if (digit != 0 || size != 0)
buf[size++] = static_cast<char>('0' + digit);
if (digit != 0 || size != 0) buf[size++] = static_cast<char>('0' + digit);
lo &= one.f - 1;
--exp;
if (lo < delta || size > max_digits) {
@ -546,19 +556,18 @@ struct gen_digits_params {
};
struct prettify_handler {
char *data;
char* data;
ptrdiff_t size;
buffer &buf;
buffer& buf;
explicit prettify_handler(buffer &b, ptrdiff_t n)
explicit prettify_handler(buffer& b, ptrdiff_t n)
: data(b.data()), size(n), buf(b) {}
~prettify_handler() {
assert(buf.size() >= to_unsigned(size));
buf.resize(to_unsigned(size));
}
template <typename F>
void insert(ptrdiff_t pos, ptrdiff_t n, F f) {
template <typename F> void insert(ptrdiff_t pos, ptrdiff_t n, F f) {
std::memmove(data + pos + n, data + pos, to_unsigned(size - pos));
f(data + pos);
size += n;
@ -583,8 +592,7 @@ struct prettify_handler {
};
// Writes the exponent exp in the form "[+-]d{2,3}" to buffer.
template <typename Handler>
FMT_FUNC void write_exponent(int exp, Handler &&h) {
template <typename Handler> FMT_FUNC void write_exponent(int exp, Handler&& h) {
FMT_ASSERT(-1000 < exp && exp < 1000, "exponent out of range");
if (exp < 0) {
h.append('-');
@ -595,11 +603,11 @@ FMT_FUNC void write_exponent(int exp, Handler &&h) {
if (exp >= 100) {
h.append(static_cast<char>('0' + exp / 100));
exp %= 100;
const char *d = data::DIGITS + exp * 2;
const char* d = data::DIGITS + exp * 2;
h.append(d[0]);
h.append(d[1]);
} else {
const char *d = data::DIGITS + exp * 2;
const char* d = data::DIGITS + exp * 2;
h.append(d[0]);
h.append(d[1]);
}
@ -607,7 +615,7 @@ FMT_FUNC void write_exponent(int exp, Handler &&h) {
struct fill {
size_t n;
void operator()(char *buf) const {
void operator()(char* buf) const {
buf[0] = '0';
buf[1] = '.';
std::uninitialized_fill_n(buf + 2, n, '0');
@ -616,14 +624,13 @@ struct fill {
// The number is given as v = f * pow(10, exp), where f has size digits.
template <typename Handler>
FMT_FUNC void grisu2_prettify(const gen_digits_params &params,
int size, int exp, Handler &&handler) {
FMT_FUNC void grisu2_prettify(const gen_digits_params& params, int size,
int exp, Handler&& handler) {
if (!params.fixed) {
// Insert a decimal point after the first digit and add an exponent.
handler.insert(1, '.');
exp += size - 1;
if (size < params.num_digits)
handler.append(params.num_digits - size, '0');
if (size < params.num_digits) handler.append(params.num_digits - size, '0');
handler.append(params.upper ? 'E' : 'e');
write_exponent(exp, handler);
return;
@ -659,8 +666,7 @@ FMT_FUNC void grisu2_prettify(const gen_digits_params &params,
struct char_counter {
ptrdiff_t size;
template <typename F>
void insert(ptrdiff_t, ptrdiff_t n, F) { size += n; }
template <typename F> void insert(ptrdiff_t, ptrdiff_t n, F) { size += n; }
void insert(ptrdiff_t, char) { ++size; }
void append(ptrdiff_t n, char) { size += n; }
void append(char) { ++size; }
@ -670,15 +676,16 @@ struct char_counter {
// Converts format specifiers into parameters for digit generation and computes
// output buffer size for a number in the range [pow(10, exp - 1), pow(10, exp)
// or 0 if exp == 1.
FMT_FUNC gen_digits_params process_specs(const core_format_specs &specs,
int exp, buffer &buf) {
FMT_FUNC gen_digits_params process_specs(const core_format_specs& specs,
int exp, buffer& buf) {
auto params = gen_digits_params();
int num_digits = specs.precision >= 0 ? specs.precision : 6;
switch (specs.type) {
case 'G':
params.upper = true;
FMT_FALLTHROUGH
case '\0': case 'g':
case '\0':
case 'g':
params.trailing_zeros = (specs.flags & HASH_FLAG) != 0;
if (-4 <= exp && exp < num_digits + 1) {
params.fixed = true;
@ -693,8 +700,7 @@ FMT_FUNC gen_digits_params process_specs(const core_format_specs &specs,
params.fixed = true;
params.trailing_zeros = true;
int adjusted_min_digits = num_digits + exp;
if (adjusted_min_digits > 0)
num_digits = adjusted_min_digits;
if (adjusted_min_digits > 0) num_digits = adjusted_min_digits;
break;
}
case 'E':
@ -713,7 +719,7 @@ FMT_FUNC gen_digits_params process_specs(const core_format_specs &specs,
template <typename Double>
FMT_FUNC typename std::enable_if<sizeof(Double) == sizeof(uint64_t), bool>::type
grisu2_format(Double value, buffer &buf, core_format_specs specs) {
grisu2_format(Double value, buffer& buf, core_format_specs specs) {
FMT_ASSERT(value >= 0, "value is negative");
if (value == 0) {
gen_digits_params params = process_specs(specs, 1, buf);
@ -761,29 +767,27 @@ FMT_FUNC typename std::enable_if<sizeof(Double) == sizeof(uint64_t), bool>::type
}
template <typename Double>
void sprintf_format(Double value, internal::buffer &buf,
void sprintf_format(Double value, internal::buffer& buf,
core_format_specs spec) {
// Buffer capacity must be non-zero, otherwise MSVC's vsnprintf_s will fail.
FMT_ASSERT(buf.capacity() != 0, "empty buffer");
// Build format string.
enum { MAX_FORMAT_SIZE = 10}; // longest format: %#-*.*Lg
enum { MAX_FORMAT_SIZE = 10 }; // longest format: %#-*.*Lg
char format[MAX_FORMAT_SIZE];
char *format_ptr = format;
char* format_ptr = format;
*format_ptr++ = '%';
if (spec.has(HASH_FLAG))
*format_ptr++ = '#';
if (spec.has(HASH_FLAG)) *format_ptr++ = '#';
if (spec.precision >= 0) {
*format_ptr++ = '.';
*format_ptr++ = '*';
}
if (std::is_same<Double, long double>::value)
*format_ptr++ = 'L';
if (std::is_same<Double, long double>::value) *format_ptr++ = 'L';
*format_ptr++ = spec.type;
*format_ptr = '\0';
// Format using snprintf.
char *start = FMT_NULL;
char* start = FMT_NULL;
for (;;) {
std::size_t buffer_size = buf.capacity();
start = &buf[0];
@ -819,15 +823,13 @@ FMT_FUNC internal::utf8_to_utf16::utf8_to_utf16(string_view s) {
return;
}
int length = MultiByteToWideChar(
CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), s_size, FMT_NULL, 0);
if (length == 0)
FMT_THROW(windows_error(GetLastError(), ERROR_MSG));
int length = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(),
s_size, FMT_NULL, 0);
if (length == 0) FMT_THROW(windows_error(GetLastError(), ERROR_MSG));
buffer_.resize(length + 1);
length = MultiByteToWideChar(
CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), s_size, &buffer_[0], length);
if (length == 0)
FMT_THROW(windows_error(GetLastError(), ERROR_MSG));
length = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), s_size,
&buffer_[0], length);
if (length == 0) FMT_THROW(windows_error(GetLastError(), ERROR_MSG));
buffer_[length] = 0;
}
@ -839,8 +841,7 @@ FMT_FUNC internal::utf16_to_utf8::utf16_to_utf8(wstring_view s) {
}
FMT_FUNC int internal::utf16_to_utf8::convert(wstring_view s) {
if (s.size() > INT_MAX)
return ERROR_INVALID_PARAMETER;
if (s.size() > INT_MAX) return ERROR_INVALID_PARAMETER;
int s_size = static_cast<int>(s.size());
if (s_size == 0) {
// WideCharToMultiByte does not support zero length, handle separately.
@ -849,39 +850,38 @@ FMT_FUNC int internal::utf16_to_utf8::convert(wstring_view s) {
return 0;
}
int length = WideCharToMultiByte(
CP_UTF8, 0, s.data(), s_size, FMT_NULL, 0, FMT_NULL, FMT_NULL);
if (length == 0)
return GetLastError();
int length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, FMT_NULL, 0,
FMT_NULL, FMT_NULL);
if (length == 0) return GetLastError();
buffer_.resize(length + 1);
length = WideCharToMultiByte(
CP_UTF8, 0, s.data(), s_size, &buffer_[0], length, FMT_NULL, FMT_NULL);
if (length == 0)
return GetLastError();
length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, &buffer_[0],
length, FMT_NULL, FMT_NULL);
if (length == 0) return GetLastError();
buffer_[length] = 0;
return 0;
}
FMT_FUNC void windows_error::init(
int err_code, string_view format_str, format_args args) {
FMT_FUNC void windows_error::init(int err_code, string_view format_str,
format_args args) {
error_code_ = err_code;
memory_buffer buffer;
internal::format_windows_error(buffer, err_code, vformat(format_str, args));
std::runtime_error &base = *this;
std::runtime_error& base = *this;
base = std::runtime_error(to_string(buffer));
}
FMT_FUNC void internal::format_windows_error(
internal::buffer &out, int error_code, string_view message) FMT_NOEXCEPT {
FMT_FUNC void internal::format_windows_error(internal::buffer& out,
int error_code,
string_view message) FMT_NOEXCEPT {
FMT_TRY {
wmemory_buffer buf;
buf.resize(inline_buffer_size);
for (;;) {
wchar_t *system_message = &buf[0];
wchar_t* system_message = &buf[0];
int result = FormatMessageW(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
FMT_NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
system_message, static_cast<uint32_t>(buf.size()), FMT_NULL);
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, FMT_NULL,
error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), system_message,
static_cast<uint32_t>(buf.size()), FMT_NULL);
if (result != 0) {
utf16_to_utf8 utf8_message;
if (utf8_message.convert(system_message) == ERROR_SUCCESS) {
@ -897,19 +897,20 @@ FMT_FUNC void internal::format_windows_error(
break; // Can't get error message, report error code instead.
buf.resize(buf.size() * 2);
}
} FMT_CATCH(...) {}
}
FMT_CATCH(...) {}
format_error_code(out, error_code, message);
}
#endif // FMT_USE_WINDOWS_H
FMT_FUNC void format_system_error(
internal::buffer &out, int error_code, string_view message) FMT_NOEXCEPT {
FMT_FUNC void format_system_error(internal::buffer& out, int error_code,
string_view message) FMT_NOEXCEPT {
FMT_TRY {
memory_buffer buf;
buf.resize(inline_buffer_size);
for (;;) {
char *system_message = &buf[0];
char* system_message = &buf[0];
int result = safe_strerror(error_code, system_message, buf.size());
if (result == 0) {
writer w(out);
@ -922,34 +923,35 @@ FMT_FUNC void format_system_error(
break; // Can't get error message, report error code instead.
buf.resize(buf.size() * 2);
}
} FMT_CATCH(...) {}
}
FMT_CATCH(...) {}
format_error_code(out, error_code, message);
}
FMT_FUNC void internal::error_handler::on_error(const char *message) {
FMT_FUNC void internal::error_handler::on_error(const char* message) {
FMT_THROW(format_error(message));
}
FMT_FUNC void report_system_error(
int error_code, fmt::string_view message) FMT_NOEXCEPT {
FMT_FUNC void report_system_error(int error_code,
fmt::string_view message) FMT_NOEXCEPT {
report_error(format_system_error, error_code, message);
}
#if FMT_USE_WINDOWS_H
FMT_FUNC void report_windows_error(
int error_code, fmt::string_view message) FMT_NOEXCEPT {
FMT_FUNC void report_windows_error(int error_code,
fmt::string_view message) FMT_NOEXCEPT {
report_error(internal::format_windows_error, error_code, message);
}
#endif
FMT_FUNC void vprint(std::FILE *f, string_view format_str, format_args args) {
FMT_FUNC void vprint(std::FILE* f, string_view format_str, format_args args) {
memory_buffer buffer;
internal::vformat_to(buffer, format_str,
basic_format_args<buffer_context<char>::type>(args));
std::fwrite(buffer.data(), 1, buffer.size(), f);
}
FMT_FUNC void vprint(std::FILE *f, wstring_view format_str, wformat_args args) {
FMT_FUNC void vprint(std::FILE* f, wstring_view format_str, wformat_args args) {
wmemory_buffer buffer;
internal::vformat_to(buffer, format_str, args);
std::fwrite(buffer.data(), sizeof(wchar_t), buffer.size(), f);

File diff suppressed because it is too large Load Diff

View File

@ -8,42 +8,43 @@
#ifndef FMT_LOCALE_H_
#define FMT_LOCALE_H_
#include "format.h"
#include <locale>
#include "format.h"
FMT_BEGIN_NAMESPACE
namespace internal {
template <typename Char>
typename buffer_context<Char>::type::iterator vformat_to(
const std::locale &loc, basic_buffer<Char> &buf,
const std::locale& loc, basic_buffer<Char>& buf,
basic_string_view<Char> format_str,
basic_format_args<typename buffer_context<Char>::type> args) {
typedef back_insert_range<basic_buffer<Char> > range;
return vformat_to<arg_formatter<range>>(
buf, to_string_view(format_str), args, internal::locale_ref(loc));
typedef back_insert_range<basic_buffer<Char>> range;
return vformat_to<arg_formatter<range>>(buf, to_string_view(format_str), args,
internal::locale_ref(loc));
}
template <typename Char>
std::basic_string<Char> vformat(
const std::locale &loc, basic_string_view<Char> format_str,
const std::locale& loc, basic_string_view<Char> format_str,
basic_format_args<typename buffer_context<Char>::type> args) {
basic_memory_buffer<Char> buffer;
internal::vformat_to(loc, buffer, format_str, args);
return fmt::to_string(buffer);
}
}
} // namespace internal
template <typename S, typename Char = FMT_CHAR(S)>
inline std::basic_string<Char> vformat(
const std::locale &loc, const S &format_str,
const std::locale& loc, const S& format_str,
basic_format_args<typename buffer_context<Char>::type> args) {
return internal::vformat(loc, to_string_view(format_str), args);
}
template <typename S, typename... Args>
inline std::basic_string<FMT_CHAR(S)> format(
const std::locale &loc, const S &format_str, const Args &... args) {
inline std::basic_string<FMT_CHAR(S)> format(const std::locale& loc,
const S& format_str,
const Args&... args) {
return internal::vformat(
loc, to_string_view(format_str),
*internal::checked_args<S, Args...>(format_str, args...));
@ -52,7 +53,7 @@ inline std::basic_string<FMT_CHAR(S)> format(
template <typename String, typename OutputIt, typename... Args>
inline typename std::enable_if<internal::is_output_iterator<OutputIt>::value,
OutputIt>::type
vformat_to(OutputIt out, const std::locale &loc, const String &format_str,
vformat_to(OutputIt out, const std::locale& loc, const String& format_str,
typename format_args_t<OutputIt, FMT_CHAR(String)>::type args) {
typedef output_range<OutputIt, FMT_CHAR(String)> range;
return vformat_to<arg_formatter<range>>(
@ -60,11 +61,12 @@ inline typename std::enable_if<internal::is_output_iterator<OutputIt>::value,
}
template <typename OutputIt, typename S, typename... Args>
inline typename std::enable_if<
internal::is_string<S>::value &&
internal::is_output_iterator<OutputIt>::value, OutputIt>::type
format_to(OutputIt out, const std::locale &loc, const S &format_str,
const Args &... args) {
inline
typename std::enable_if<internal::is_string<S>::value &&
internal::is_output_iterator<OutputIt>::value,
OutputIt>::type
format_to(OutputIt out, const std::locale& loc, const S& format_str,
const Args&... args) {
internal::check_format_string<Args...>(format_str);
typedef typename format_context_t<OutputIt, FMT_CHAR(S)>::type context;
format_arg_store<context, Args...> as{args...};

View File

@ -8,22 +8,21 @@
#ifndef FMT_OSTREAM_H_
#define FMT_OSTREAM_H_
#include "format.h"
#include <ostream>
#include "format.h"
FMT_BEGIN_NAMESPACE
namespace internal {
template <class Char>
class formatbuf : public std::basic_streambuf<Char> {
template <class Char> class formatbuf : public std::basic_streambuf<Char> {
private:
typedef typename std::basic_streambuf<Char>::int_type int_type;
typedef typename std::basic_streambuf<Char>::traits_type traits_type;
basic_buffer<Char> &buffer_;
basic_buffer<Char>& buffer_;
public:
formatbuf(basic_buffer<Char> &buffer) : buffer_(buffer) {}
formatbuf(basic_buffer<Char>& buffer) : buffer_(buffer) {}
protected:
// The put-area is actually always empty. This makes the implementation
@ -39,31 +38,30 @@ class formatbuf : public std::basic_streambuf<Char> {
return ch;
}
std::streamsize xsputn(const Char *s, std::streamsize count) FMT_OVERRIDE {
std::streamsize xsputn(const Char* s, std::streamsize count) FMT_OVERRIDE {
buffer_.append(s, s + count);
return count;
}
};
template <typename Char>
struct test_stream : std::basic_ostream<Char> {
template <typename Char> struct test_stream : std::basic_ostream<Char> {
private:
struct null;
// Hide all operator<< from std::basic_ostream<Char>.
void operator<<(null);
};
// Checks if T has a user-defined operator<< (e.g. not a member of std::ostream).
template <typename T, typename Char>
class is_streamable {
// Checks if T has a user-defined operator<< (e.g. not a member of
// std::ostream).
template <typename T, typename Char> class is_streamable {
private:
template <typename U>
static decltype(
internal::declval<test_stream<Char>&>()
<< internal::declval<U>(), std::true_type()) test(int);
static decltype(internal::declval<test_stream<Char>&>()
<< internal::declval<U>(),
std::true_type())
test(int);
template <typename>
static std::false_type test(...);
template <typename> static std::false_type test(...);
typedef decltype(test<T>(0)) result;
@ -73,8 +71,8 @@ class is_streamable {
// Write the content of buf to os.
template <typename Char>
void write(std::basic_ostream<Char> &os, basic_buffer<Char> &buf) {
const Char *data = buf.data();
void write(std::basic_ostream<Char>& os, basic_buffer<Char>& buf) {
const Char* data = buf.data();
typedef std::make_unsigned<std::streamsize>::type UnsignedStreamSize;
UnsignedStreamSize size = buf.size();
UnsignedStreamSize max_size =
@ -88,7 +86,7 @@ void write(std::basic_ostream<Char> &os, basic_buffer<Char> &buf) {
}
template <typename Char, typename T>
void format_value(basic_buffer<Char> &buffer, const T &value) {
void format_value(basic_buffer<Char>& buffer, const T& value) {
internal::formatbuf<Char> format_buf(buffer);
std::basic_ostream<Char> output(&format_buf);
output.exceptions(std::ios_base::failbit | std::ios_base::badbit);
@ -99,10 +97,8 @@ void format_value(basic_buffer<Char> &buffer, const T &value) {
// Disable conversion to int if T has an overloaded operator<< which is a free
// function (not a member of std::ostream).
template <typename T, typename Char>
struct convert_to_int<T, Char, void> {
static const bool value =
convert_to_int<T, Char, int>::value &&
template <typename T, typename Char> struct convert_to_int<T, Char, void> {
static const bool value = convert_to_int<T, Char, int>::value &&
!internal::is_streamable<T, Char>::value;
};
@ -111,12 +107,11 @@ template <typename T, typename Char>
struct formatter<T, Char,
typename std::enable_if<
internal::is_streamable<T, Char>::value &&
!internal::format_type<
typename buffer_context<Char>::type, T>::value>::type>
!internal::format_type<typename buffer_context<Char>::type,
T>::value>::type>
: formatter<basic_string_view<Char>, Char> {
template <typename Context>
auto format(const T &value, Context &ctx) -> decltype(ctx.out()) {
auto format(const T& value, Context& ctx) -> decltype(ctx.out()) {
basic_memory_buffer<Char> buffer;
internal::format_value(buffer, value);
basic_string_view<Char> str(buffer.data(), buffer.size());
@ -125,8 +120,8 @@ struct formatter<T, Char,
};
template <typename Char>
inline void vprint(std::basic_ostream<Char> &os,
basic_string_view<Char> format_str,
inline void vprint(
std::basic_ostream<Char>& os, basic_string_view<Char> format_str,
basic_format_args<typename buffer_context<Char>::type> args) {
basic_memory_buffer<Char> buffer;
internal::vformat_to(buffer, format_str, args);
@ -142,9 +137,9 @@ inline void vprint(std::basic_ostream<Char> &os,
\endrst
*/
template <typename S, typename... Args>
inline typename std::enable_if<internal::is_string<S>::value>::type
print(std::basic_ostream<FMT_CHAR(S)> &os, const S &format_str,
const Args & ... args) {
inline typename std::enable_if<internal::is_string<S>::value>::type print(
std::basic_ostream<FMT_CHAR(S)>& os, const S& format_str,
const Args&... args) {
internal::checked_args<S, Args...> ca(format_str, args...);
vprint(os, to_string_view(format_str), *ca);
}

View File

@ -89,24 +89,23 @@ FMT_BEGIN_NAMESPACE
format(std::string("{}"), 42);
\endrst
*/
template <typename Char>
class basic_cstring_view {
template <typename Char> class basic_cstring_view {
private:
const Char *data_;
const Char* data_;
public:
/** Constructs a string reference object from a C string. */
basic_cstring_view(const Char *s) : data_(s) {}
basic_cstring_view(const Char* s) : data_(s) {}
/**
\rst
Constructs a string reference from an ``std::string`` object.
\endrst
*/
basic_cstring_view(const std::basic_string<Char> &s) : data_(s.c_str()) {}
basic_cstring_view(const std::basic_string<Char>& s) : data_(s.c_str()) {}
/** Returns the pointer to a C string. */
const Char *c_str() const { return data_; }
const Char* c_str() const { return data_; }
};
typedef basic_cstring_view<char> cstring_view;
@ -126,11 +125,11 @@ class error_code {
// A buffered file.
class buffered_file {
private:
FILE *file_;
FILE* file_;
friend class file;
explicit buffered_file(FILE *f) : file_(f) {}
explicit buffered_file(FILE* f) : file_(f) {}
public:
// Constructs a buffered_file object which doesn't represent any file.
@ -140,16 +139,15 @@ class buffered_file {
FMT_API ~buffered_file() FMT_NOEXCEPT;
private:
buffered_file(const buffered_file &) = delete;
void operator=(const buffered_file &) = delete;
buffered_file(const buffered_file&) = delete;
void operator=(const buffered_file&) = delete;
public:
buffered_file(buffered_file &&other) FMT_NOEXCEPT : file_(other.file_) {
buffered_file(buffered_file&& other) FMT_NOEXCEPT : file_(other.file_) {
other.file_ = FMT_NULL;
}
buffered_file& operator=(buffered_file &&other) {
buffered_file& operator=(buffered_file&& other) {
close();
file_ = other.file_;
other.file_ = FMT_NULL;
@ -163,18 +161,18 @@ class buffered_file {
FMT_API void close();
// Returns the pointer to a FILE object representing this file.
FILE *get() const FMT_NOEXCEPT { return file_; }
FILE* get() const FMT_NOEXCEPT { return file_; }
// We place parentheses around fileno to workaround a bug in some versions
// of MinGW that define fileno as a macro.
FMT_API int (fileno)() const;
FMT_API int(fileno)() const;
void vprint(string_view format_str, format_args args) {
fmt::vprint(file_, format_str, args);
}
template <typename... Args>
inline void print(string_view format_str, const Args & ... args) {
inline void print(string_view format_str, const Args&... args) {
vprint(format_str, make_format_args(args...));
}
};
@ -207,15 +205,13 @@ class file {
FMT_API file(cstring_view path, int oflag);
private:
file(const file &) = delete;
void operator=(const file &) = delete;
file(const file&) = delete;
void operator=(const file&) = delete;
public:
file(file &&other) FMT_NOEXCEPT : fd_(other.fd_) {
other.fd_ = -1;
}
file(file&& other) FMT_NOEXCEPT : fd_(other.fd_) { other.fd_ = -1; }
file& operator=(file &&other) {
file& operator=(file&& other) {
close();
fd_ = other.fd_;
other.fd_ = -1;
@ -236,10 +232,10 @@ class file {
FMT_API long long size() const;
// Attempts to read count bytes from the file into the specified buffer.
FMT_API std::size_t read(void *buffer, std::size_t count);
FMT_API std::size_t read(void* buffer, std::size_t count);
// Attempts to write count bytes from the specified buffer to the file.
FMT_API std::size_t write(const void *buffer, std::size_t count);
FMT_API std::size_t write(const void* buffer, std::size_t count);
// Duplicates a file descriptor with the dup function and returns
// the duplicate as a file object.
@ -251,15 +247,15 @@ class file {
// Makes fd be the copy of this file descriptor, closing fd first if
// necessary.
FMT_API void dup2(int fd, error_code &ec) FMT_NOEXCEPT;
FMT_API void dup2(int fd, error_code& ec) FMT_NOEXCEPT;
// Creates a pipe setting up read_end and write_end file objects for reading
// and writing respectively.
FMT_API static void pipe(file &read_end, file &write_end);
FMT_API static void pipe(file& read_end, file& write_end);
// Creates a buffered_file object associated with this file and detaches
// this file object from the file.
FMT_API buffered_file fdopen(const char *mode);
FMT_API buffered_file fdopen(const char* mode);
};
// Returns the memory page size.
@ -280,30 +276,27 @@ class Locale {
enum { LC_NUMERIC_MASK = LC_NUMERIC };
static locale_t newlocale(int category_mask, const char *locale, locale_t) {
static locale_t newlocale(int category_mask, const char* locale, locale_t) {
return _create_locale(category_mask, locale);
}
static void freelocale(locale_t locale) {
_free_locale(locale);
}
static void freelocale(locale_t locale) { _free_locale(locale); }
static double strtod_l(const char *nptr, char **endptr, _locale_t locale) {
static double strtod_l(const char* nptr, char** endptr, _locale_t locale) {
return _strtod_l(nptr, endptr, locale);
}
# endif
locale_t locale_;
Locale(const Locale &) = delete;
void operator=(const Locale &) = delete;
Locale(const Locale&) = delete;
void operator=(const Locale&) = delete;
public:
typedef locale_t Type;
Locale() : locale_(newlocale(LC_NUMERIC_MASK, "C", FMT_NULL)) {
if (!locale_)
FMT_THROW(system_error(errno, "cannot create locale"));
if (!locale_) FMT_THROW(system_error(errno, "cannot create locale"));
}
~Locale() { freelocale(locale_); }
@ -311,8 +304,8 @@ class Locale {
// Converts string to floating-point number and advances str past the end
// of the parsed input.
double strtod(const char *&str) const {
char *end = FMT_NULL;
double strtod(const char*& str) const {
char* end = FMT_NULL;
double result = strtod_l(str, &end, locale_);
str = end;
return result;

View File

@ -73,7 +73,8 @@ template <typename Char> struct format_part {
: which(which_value::argument_id), end_of_argument_id(0u), val(id) {}
FMT_CONSTEXPR format_part(named_argument_id arg_id)
: which(which_value::named_argument_id), end_of_argument_id(0u),
: which(which_value::named_argument_id),
end_of_argument_id(0u),
val(arg_id) {}
FMT_CONSTEXPR format_part(specification spec)
@ -99,23 +100,24 @@ template <typename Char> struct format_part {
internal::string_view_metadata named_arg_id;
internal::string_view_metadata text;
specification spec;
} val;
}
val;
};
namespace internal {
template <typename Char, typename PartsContainer>
class format_preparation_handler : public internal::error_handler {
private:
private:
typedef format_part<Char> part;
public:
public:
typedef internal::null_terminating_iterator<Char> iterator;
FMT_CONSTEXPR format_preparation_handler(basic_string_view<Char> format,
PartsContainer &parts)
PartsContainer& parts)
: parts_(parts), format_(format), parse_context_(format) {}
FMT_CONSTEXPR void on_text(const Char *begin, const Char *end) {
FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) {
if (begin == end) {
return;
}
@ -139,20 +141,19 @@ public:
parts_.add(part(arg_id));
}
FMT_CONSTEXPR void on_replacement_field(const Char *ptr) {
FMT_CONSTEXPR void on_replacement_field(const Char* ptr) {
auto last_part = parts_.last();
last_part.end_of_argument_id = ptr - format_.begin();
parts_.substitute_last(last_part);
}
FMT_CONSTEXPR const Char *on_format_specs(const Char *begin,
const Char *end) {
FMT_CONSTEXPR const Char* on_format_specs(const Char* begin,
const Char* end) {
const auto specs_offset = to_unsigned(begin - format_.begin());
typedef basic_parse_context<Char> parse_context;
internal::dynamic_format_specs<Char> parsed_specs;
dynamic_specs_handler<parse_context> handler(
parsed_specs, parse_context_);
dynamic_specs_handler<parse_context> handler(parsed_specs, parse_context_);
begin = parse_format_specs(begin, end, handler);
if (*begin != '}') {
@ -176,7 +177,7 @@ public:
}
private:
PartsContainer &parts_;
PartsContainer& parts_;
basic_string_view<Char> format_;
basic_parse_context<Char> parse_context_;
};
@ -193,7 +194,7 @@ class prepared_format {
prepared_format() = delete;
std::size_t formatted_size(const Args &... args) const {
std::size_t formatted_size(const Args&... args) const {
const auto it = this->format_to(counting_iterator<char_type>(), args...);
return it.count();
}
@ -201,7 +202,7 @@ class prepared_format {
template <typename OutputIt>
inline typename std::enable_if<internal::is_output_iterator<OutputIt>::value,
format_to_n_result<OutputIt>>::type
format_to_n(OutputIt out, unsigned n, const Args &... args) const {
format_to_n(OutputIt out, unsigned n, const Args&... args) const {
format_arg_store<typename format_to_n_context<OutputIt, char_type>::type,
Args...>
as(args...);
@ -214,7 +215,7 @@ class prepared_format {
return {it.base(), it.count()};
}
std::basic_string<char_type> format(const Args &... args) const {
std::basic_string<char_type> format(const Args&... args) const {
basic_memory_buffer<char_type> buffer;
typedef back_insert_range<internal::basic_buffer<char_type>> range;
this->vformat_to(range(buffer), *checked_args(format_, args...));
@ -225,7 +226,7 @@ class prepared_format {
inline typename std::enable_if<is_contiguous<Container>::value,
std::back_insert_iterator<Container>>::type
format_to(std::back_insert_iterator<Container> out,
const Args &... args) const {
const Args&... args) const {
internal::container_buffer<Container> buffer(internal::get_container(out));
typedef back_insert_range<internal::basic_buffer<char_type>> range;
this->vformat_to(range(buffer), *checked_args(format_, args...));
@ -233,7 +234,7 @@ class prepared_format {
}
template <typename OutputIt>
inline OutputIt format_to(OutputIt out, const Args &... args) const {
inline OutputIt format_to(OutputIt out, const Args&... args) const {
typedef typename format_context_t<OutputIt, char_type>::type context;
typedef output_range<OutputIt, char_type> range;
format_arg_store<context, Args...> as(args...);
@ -241,9 +242,8 @@ class prepared_format {
}
template <std::size_t SIZE = inline_buffer_size>
inline typename buffer_context<char_type>::type::iterator
format_to(basic_memory_buffer<char_type, SIZE> &buf,
const Args &... args) const {
inline typename buffer_context<char_type>::type::iterator format_to(
basic_memory_buffer<char_type, SIZE>& buf, const Args&... args) const {
typedef back_insert_range<internal::basic_buffer<char_type>> range;
return this->vformat_to(range(buf), *checked_args(format_, args...));
}
@ -255,16 +255,16 @@ class prepared_format {
const auto format_view = internal::to_string_view(format_);
Context ctx(out.begin(), format_view, args);
const auto &parts = parts_provider_.parts();
const auto& parts = parts_provider_.parts();
for (auto part_it = parts.begin(); part_it != parts.end(); ++part_it) {
const auto &part = *part_it;
const auto &value = part.val;
const auto& part = *part_it;
const auto& value = part.val;
switch (part.which) {
case format_part_t::which_value::text: {
const auto text = value.text.to_view(format_view);
auto out = ctx.out();
auto &&it = internal::reserve(out, text.size());
auto&& it = internal::reserve(out, text.size());
it = std::copy_n(text.begin(), text.size(), it);
ctx.advance_to(out);
} break;
@ -280,7 +280,7 @@ class prepared_format {
format_arg<Range>(ctx, named_arg_id);
} break;
case format_part_t::which_value::specification: {
const auto &arg_id_value = value.spec.arg_id.val;
const auto& arg_id_value = value.spec.arg_id.val;
const auto arg =
value.spec.arg_id.which ==
format_part_t::argument_id::which_arg_id::index
@ -306,15 +306,15 @@ class prepared_format {
}
template <typename Context>
void advance_parse_context_to_specification(Context &ctx,
const format_part_t &part) const {
void advance_parse_context_to_specification(Context& ctx,
const format_part_t& part) const {
const auto view = to_string_view(format_);
const auto specification_begin = view.data() + part.end_of_argument_id;
ctx.parse_context().advance_to(specification_begin);
}
template <typename Range, typename Context, typename Id>
void format_arg(Context &ctx, Id arg_id) const {
void format_arg(Context& ctx, Id arg_id) const {
ctx.parse_context().check_arg_id(arg_id);
const auto stopped_at =
visit_format_arg(arg_formatter<Range>(ctx), ctx.get_arg(arg_id));
@ -322,8 +322,8 @@ class prepared_format {
}
template <typename Char>
void check_prepared_specs(
const basic_format_specs<Char> &specs, internal::type arg_type) const {
void check_prepared_specs(const basic_format_specs<Char>& specs,
internal::type arg_type) const {
internal::error_handler h;
numeric_specs_checker<internal::error_handler> checker(h, arg_type);
if (specs.align_ == ALIGN_NUMERIC) {
@ -343,13 +343,13 @@ class prepared_format {
}
}
private:
private:
Format format_;
PreparedPartsProvider parts_provider_;
};
template <typename Format> class compiletime_prepared_parts_type_provider {
private:
private:
typedef FMT_CHAR(Format) char_type;
class count_handler {
@ -359,7 +359,7 @@ private:
public:
FMT_CONSTEXPR count_handler() : counter_(0u) {}
FMT_CONSTEXPR void on_text(const char_type *begin, const char_type *end) {
FMT_CONSTEXPR void on_text(const char_type* begin, const char_type* end) {
if (begin != end) {
++counter_;
}
@ -369,20 +369,20 @@ private:
FMT_CONSTEXPR void on_arg_id(unsigned) { ++counter_; }
FMT_CONSTEXPR void on_arg_id(basic_string_view<char_type>) { ++counter_; }
FMT_CONSTEXPR void on_replacement_field(const char_type *) {}
FMT_CONSTEXPR void on_replacement_field(const char_type*) {}
FMT_CONSTEXPR const char_type *on_format_specs(const char_type *begin,
const char_type *end) {
FMT_CONSTEXPR const char_type* on_format_specs(const char_type* begin,
const char_type* end) {
return find_matching_brace(begin, end);
}
FMT_CONSTEXPR void on_error(const char *) {}
FMT_CONSTEXPR void on_error(const char*) {}
FMT_CONSTEXPR unsigned result() const { return counter_; }
private:
FMT_CONSTEXPR const char_type *find_matching_brace(const char_type *begin,
const char_type *end) {
FMT_CONSTEXPR const char_type* find_matching_brace(const char_type* begin,
const char_type* end) {
FMT_CONSTEXPR_DECL const basic_string_view<char_type> text = Format{};
unsigned braces_counter{0u};
for (; begin != end; ++begin) {
@ -425,11 +425,11 @@ private:
FMT_CONSTEXPR format_parts_array() : arr{} {}
FMT_CONSTEXPR value_type &operator[](unsigned ind) { return arr[ind]; }
FMT_CONSTEXPR value_type& operator[](unsigned ind) { return arr[ind]; }
FMT_CONSTEXPR const value_type *begin() const { return arr; }
FMT_CONSTEXPR const value_type* begin() const { return arr; }
FMT_CONSTEXPR const value_type *end() const { return begin() + N; }
FMT_CONSTEXPR const value_type* end() const { return begin() + N; }
private:
value_type arr[N];
@ -450,7 +450,7 @@ template <typename Parts> class compiletime_prepared_parts_collector {
typedef typename Parts::value_type format_part;
public:
FMT_CONSTEXPR explicit compiletime_prepared_parts_collector(Parts &parts)
FMT_CONSTEXPR explicit compiletime_prepared_parts_collector(Parts& parts)
: parts_{parts}, counter_{0u} {}
FMT_CONSTEXPR void add(format_part part) { parts_[counter_++] = part; }
@ -462,7 +462,7 @@ template <typename Parts> class compiletime_prepared_parts_collector {
FMT_CONSTEXPR format_part last() { return parts_[counter_ - 1]; }
private:
Parts &parts_;
Parts& parts_;
unsigned counter_;
};
@ -493,7 +493,7 @@ template <typename PartsContainer> class runtime_parts_provider {
runtime_parts_provider(basic_string_view<Char> format)
: parts_(prepare_parts<PartsContainer>(format)) {}
const PartsContainer &parts() const { return parts_; }
const PartsContainer& parts() const { return parts_; }
private:
PartsContainer parts_;
@ -505,7 +505,7 @@ struct compiletime_parts_provider {
template <typename Char>
FMT_CONSTEXPR compiletime_parts_provider(basic_string_view<Char>) {}
const PartsContainer &parts() const {
const PartsContainer& parts() const {
static FMT_CONSTEXPR_DECL const PartsContainer prepared_parts =
prepare_compiletime_parts<PartsContainer>(
internal::to_string_view(Format{}));
@ -608,7 +608,7 @@ std::basic_string<Char> to_runtime_format(basic_string_view<Char> format) {
}
template <typename Char>
std::basic_string<Char> to_runtime_format(const Char *format) {
std::basic_string<Char> to_runtime_format(const Char* format) {
return std::basic_string<Char>(format);
}
@ -685,12 +685,12 @@ auto do_prepare(runtime_format_tag, Format format) {
}
template <typename Format, typename... Args>
FMT_CONSTEXPR auto do_prepare(compiletime_format_tag, const Format &format) {
FMT_CONSTEXPR auto do_prepare(compiletime_format_tag, const Format& format) {
return typename basic_prepared_format<Format, void, Args...>::type(format);
}
#else
template <typename Format, typename... Args>
auto do_prepare(const Format &format)
auto do_prepare(const Format& format)
-> decltype(preparator<Format, Args...>::prepare(format)) {
return preparator<Format, Args...>::prepare(format);
}
@ -757,7 +757,7 @@ auto prepare(Format format) ->
#endif
template <typename... Args, typename Char>
auto prepare(const Char *format) ->
auto prepare(const Char* format) ->
typename internal::preparator<std::basic_string<Char>,
Args...>::prepared_format_type {
return prepare<Args...>(internal::to_runtime_format(format));

View File

@ -18,86 +18,82 @@ namespace internal {
// Checks if a value fits in int - used to avoid warnings about comparing
// signed and unsigned integers.
template <bool IsSigned>
struct int_checker {
template <typename T>
static bool fits_in_int(T value) {
template <bool IsSigned> struct int_checker {
template <typename T> static bool fits_in_int(T value) {
unsigned max = std::numeric_limits<int>::max();
return value <= max;
}
static bool fits_in_int(bool) { return true; }
};
template <>
struct int_checker<true> {
template <typename T>
static bool fits_in_int(T value) {
template <> struct int_checker<true> {
template <typename T> static bool fits_in_int(T value) {
return value >= std::numeric_limits<int>::min() &&
value <= std::numeric_limits<int>::max();
}
static bool fits_in_int(int) { return true; }
};
class printf_precision_handler: public function<int> {
class printf_precision_handler : public function<int> {
public:
template <typename T>
typename std::enable_if<std::is_integral<T>::value, int>::type
operator()(T value) {
typename std::enable_if<std::is_integral<T>::value, int>::type operator()(
T value) {
if (!int_checker<std::numeric_limits<T>::is_signed>::fits_in_int(value))
FMT_THROW(format_error("number is too big"));
return static_cast<int>(value);
}
template <typename T>
typename std::enable_if<!std::is_integral<T>::value, int>::type operator()(T) {
typename std::enable_if<!std::is_integral<T>::value, int>::type operator()(
T) {
FMT_THROW(format_error("precision is not integer"));
return 0;
}
};
// An argument visitor that returns true iff arg is a zero integer.
class is_zero_int: public function<bool> {
class is_zero_int : public function<bool> {
public:
template <typename T>
typename std::enable_if<std::is_integral<T>::value, bool>::type
operator()(T value) { return value == 0; }
typename std::enable_if<std::is_integral<T>::value, bool>::type operator()(
T value) {
return value == 0;
}
template <typename T>
typename std::enable_if<!std::is_integral<T>::value, bool>::type
operator()(T) { return false; }
typename std::enable_if<!std::is_integral<T>::value, bool>::type operator()(
T) {
return false;
}
};
template <typename T>
struct make_unsigned_or_bool : std::make_unsigned<T> {};
template <typename T> struct make_unsigned_or_bool : std::make_unsigned<T> {};
template <>
struct make_unsigned_or_bool<bool> {
typedef bool type;
};
template <> struct make_unsigned_or_bool<bool> { typedef bool type; };
template <typename T, typename Context>
class arg_converter: public function<void> {
class arg_converter : public function<void> {
private:
typedef typename Context::char_type Char;
basic_format_arg<Context> &arg_;
basic_format_arg<Context>& arg_;
typename Context::char_type type_;
public:
arg_converter(basic_format_arg<Context> &arg, Char type)
arg_converter(basic_format_arg<Context>& arg, Char type)
: arg_(arg), type_(type) {}
void operator()(bool value) {
if (type_ != 's')
operator()<bool>(value);
if (type_ != 's') operator()<bool>(value);
}
template <typename U>
typename std::enable_if<std::is_integral<U>::value>::type
operator()(U value) {
typename std::enable_if<std::is_integral<U>::value>::type operator()(
U value) {
bool is_signed = type_ == 'd' || type_ == 'i';
typedef typename std::conditional<
std::is_same<T, void>::value, U, T>::type TargetType;
typedef typename std::conditional<std::is_same<T, void>::value, U, T>::type
TargetType;
if (const_check(sizeof(TargetType) <= sizeof(int))) {
// Extra casts are used to silence warnings.
if (is_signed) {
@ -132,22 +128,21 @@ class arg_converter: public function<void> {
// type depending on the type specifier: 'd' and 'i' - signed, other -
// unsigned).
template <typename T, typename Context, typename Char>
void convert_arg(basic_format_arg<Context> &arg, Char type) {
void convert_arg(basic_format_arg<Context>& arg, Char type) {
visit_format_arg(arg_converter<T, Context>(arg, type), arg);
}
// Converts an integer argument to char for printf.
template <typename Context>
class char_converter: public function<void> {
template <typename Context> class char_converter : public function<void> {
private:
basic_format_arg<Context> &arg_;
basic_format_arg<Context>& arg_;
public:
explicit char_converter(basic_format_arg<Context> &arg) : arg_(arg) {}
explicit char_converter(basic_format_arg<Context>& arg) : arg_(arg) {}
template <typename T>
typename std::enable_if<std::is_integral<T>::value>::type
operator()(T value) {
typename std::enable_if<std::is_integral<T>::value>::type operator()(
T value) {
typedef typename Context::char_type Char;
arg_ = internal::make_arg<Context>(static_cast<Char>(value));
}
@ -161,14 +156,14 @@ class char_converter: public function<void> {
// Checks if an argument is a valid printf width specifier and sets
// left alignment if it is negative.
template <typename Char>
class printf_width_handler: public function<unsigned> {
class printf_width_handler : public function<unsigned> {
private:
typedef basic_format_specs<Char> format_specs;
format_specs &spec_;
format_specs& spec_;
public:
explicit printf_width_handler(format_specs &spec) : spec_(spec) {}
explicit printf_width_handler(format_specs& spec) : spec_(spec) {}
template <typename T>
typename std::enable_if<std::is_integral<T>::value, unsigned>::type
@ -180,8 +175,7 @@ class printf_width_handler: public function<unsigned> {
width = 0 - width;
}
unsigned int_max = std::numeric_limits<int>::max();
if (width > int_max)
FMT_THROW(format_error("number is too big"));
if (width > int_max) FMT_THROW(format_error("number is too big"));
return static_cast<unsigned>(width);
}
@ -194,7 +188,7 @@ class printf_width_handler: public function<unsigned> {
};
template <typename Char, typename Context>
void printf(basic_buffer<Char> &buf, basic_string_view<Char> format,
void printf(basic_buffer<Char>& buf, basic_string_view<Char> format,
basic_format_args<Context> args) {
Context(std::back_inserter(buf), format, args).format();
}
@ -202,13 +196,11 @@ void printf(basic_buffer<Char> &buf, basic_string_view<Char> format,
using internal::printf; // For printing into memory_buffer.
template <typename Range>
class printf_arg_formatter;
template <typename Range> class printf_arg_formatter;
template <
typename OutputIt, typename Char,
typename ArgFormatter =
printf_arg_formatter<back_insert_range<internal::basic_buffer<Char>>>>
template <typename OutputIt, typename Char,
typename ArgFormatter = printf_arg_formatter<
back_insert_range<internal::basic_buffer<Char>>>>
class basic_printf_context;
/**
@ -217,8 +209,8 @@ class basic_printf_context;
\endrst
*/
template <typename Range>
class printf_arg_formatter:
public internal::function<
class printf_arg_formatter
: public internal::function<
typename internal::arg_formatter_base<Range>::iterator>,
public internal::arg_formatter_base<Range> {
private:
@ -227,7 +219,7 @@ class printf_arg_formatter:
typedef internal::arg_formatter_base<Range> base;
typedef basic_printf_context<iterator, char_type> context_type;
context_type &context_;
context_type& context_;
void write_null_pointer(char) {
this->spec()->type = 0;
@ -249,10 +241,10 @@ class printf_arg_formatter:
specifier information for standard argument types.
\endrst
*/
printf_arg_formatter(internal::basic_buffer<char_type> &buffer,
format_specs &spec, context_type &ctx)
: base(back_insert_range<internal::basic_buffer<char_type>>(buffer), &spec,
ctx.locale()),
printf_arg_formatter(internal::basic_buffer<char_type>& buffer,
format_specs& spec, context_type& ctx)
: base(back_insert_range<internal::basic_buffer<char_type>>(buffer),
&spec, ctx.locale()),
context_(ctx) {}
template <typename T>
@ -261,13 +253,12 @@ class printf_arg_formatter:
// MSVC2013 fails to compile separate overloads for bool and char_type so
// use std::is_same instead.
if (std::is_same<T, bool>::value) {
format_specs &fmt_spec = *this->spec();
if (fmt_spec.type != 's')
return base::operator()(value ? 1 : 0);
format_specs& fmt_spec = *this->spec();
if (fmt_spec.type != 's') return base::operator()(value ? 1 : 0);
fmt_spec.type = 0;
this->write(value != 0);
} else if (std::is_same<T, char_type>::value) {
format_specs &fmt_spec = *this->spec();
format_specs& fmt_spec = *this->spec();
if (fmt_spec.type && fmt_spec.type != 'c')
return (*this)(static_cast<int>(value));
fmt_spec.flags = 0;
@ -286,7 +277,7 @@ class printf_arg_formatter:
}
/** Formats a null-terminated C string. */
iterator operator()(const char *value) {
iterator operator()(const char* value) {
if (value)
base::operator()(value);
else if (this->spec()->type == 'p')
@ -297,7 +288,7 @@ class printf_arg_formatter:
}
/** Formats a null-terminated wide C string. */
iterator operator()(const wchar_t *value) {
iterator operator()(const wchar_t* value) {
if (value)
base::operator()(value);
else if (this->spec()->type == 'p')
@ -311,14 +302,11 @@ class printf_arg_formatter:
return base::operator()(value);
}
iterator operator()(monostate value) {
return base::operator()(value);
}
iterator operator()(monostate value) { return base::operator()(value); }
/** Formats a pointer. */
iterator operator()(const void *value) {
if (value)
return base::operator()(value);
iterator operator()(const void* value) {
if (value) return base::operator()(value);
this->spec()->type = 0;
write_null_pointer(char_type());
return this->out();
@ -331,13 +319,14 @@ class printf_arg_formatter:
}
};
template <typename T>
struct printf_formatter {
template <typename T> struct printf_formatter {
template <typename ParseContext>
auto parse(ParseContext &ctx) -> decltype(ctx.begin()) { return ctx.begin(); }
auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
template <typename FormatContext>
auto format(const T &value, FormatContext &ctx) -> decltype(ctx.out()) {
auto format(const T& value, FormatContext& ctx) -> decltype(ctx.out()) {
internal::format_value(internal::get_container(ctx.out()), value);
return ctx.out();
}
@ -354,22 +343,23 @@ class basic_printf_context :
/** The character type for the output. */
typedef Char char_type;
template <typename T>
struct formatter_type { typedef printf_formatter<T> type; };
template <typename T> struct formatter_type {
typedef printf_formatter<T> type;
};
private:
typedef internal::context_base<OutputIt, basic_printf_context, Char> base;
typedef typename base::format_arg format_arg;
typedef basic_format_specs<char_type> format_specs;
static void parse_flags(format_specs &spec, const Char *&it, const Char *end);
static void parse_flags(format_specs& spec, const Char*& it, const Char* end);
// Returns the argument with specified index or, if arg_index is equal
// to the maximum unsigned value, the next argument.
format_arg get_arg(unsigned arg_index = std::numeric_limits<unsigned>::max());
// Parses argument index, flags and width and returns the argument index.
unsigned parse_header(const Char *&it, const Char *end, format_specs &spec);
unsigned parse_header(const Char*& it, const Char* end, format_specs& spec);
public:
/**
@ -383,17 +373,18 @@ class basic_printf_context :
basic_format_args<basic_printf_context> args)
: base(out, format_str, args) {}
using base::parse_context;
using base::out;
using base::advance_to;
using base::out;
using base::parse_context;
/** Formats stored arguments and writes the output to the range. */
void format();
};
template <typename OutputIt, typename Char, typename AF>
void basic_printf_context<OutputIt, Char, AF>::parse_flags(
format_specs &spec, const Char *&it, const Char *end) {
void basic_printf_context<OutputIt, Char, AF>::parse_flags(format_specs& spec,
const Char*& it,
const Char* end) {
for (; it != end; ++it) {
switch (*it) {
case '-':
@ -419,7 +410,7 @@ void basic_printf_context<OutputIt, Char, AF>::parse_flags(
template <typename OutputIt, typename Char, typename AF>
typename basic_printf_context<OutputIt, Char, AF>::format_arg
basic_printf_context<OutputIt, Char, AF>::get_arg(unsigned arg_index) {
basic_printf_context<OutputIt, Char, AF>::get_arg(unsigned arg_index) {
if (arg_index == std::numeric_limits<unsigned>::max())
return this->do_get_arg(this->parse_context().next_arg_id());
return base::get_arg(arg_index - 1);
@ -427,7 +418,7 @@ typename basic_printf_context<OutputIt, Char, AF>::format_arg
template <typename OutputIt, typename Char, typename AF>
unsigned basic_printf_context<OutputIt, Char, AF>::parse_header(
const Char *&it, const Char *end, format_specs &spec) {
const Char*& it, const Char* end, format_specs& spec) {
unsigned arg_index = std::numeric_limits<unsigned>::max();
char_type c = *it;
if (c >= '0' && c <= '9') {
@ -439,8 +430,7 @@ unsigned basic_printf_context<OutputIt, Char, AF>::parse_header(
++it;
arg_index = value;
} else {
if (c == '0')
spec.fill_ = '0';
if (c == '0') spec.fill_ = '0';
if (value != 0) {
// Nonzero value means that we parsed width and don't need to
// parse it or flags again, so return now.
@ -466,10 +456,10 @@ unsigned basic_printf_context<OutputIt, Char, AF>::parse_header(
template <typename OutputIt, typename Char, typename AF>
void basic_printf_context<OutputIt, Char, AF>::format() {
auto &buffer = internal::get_container(this->out());
auto& buffer = internal::get_container(this->out());
const auto range = this->parse_context();
const Char * end = range.end();
const Char * start = range.begin();
const Char* end = range.end();
const Char* start = range.begin();
auto it = start;
while (it != end) {
char_type c = *it++;
@ -505,7 +495,8 @@ void basic_printf_context<OutputIt, Char, AF>::format() {
format_arg arg = get_arg(arg_index);
if (spec.has(HASH_FLAG) && visit_format_arg(internal::is_zero_int(), arg))
spec.flags = static_cast<uint_least8_t>(spec.flags & (~internal::to_unsigned<int>(HASH_FLAG)));
spec.flags = static_cast<uint_least8_t>(
spec.flags & (~internal::to_unsigned<int>(HASH_FLAG)));
if (spec.fill_ == '0') {
if (arg.is_arithmetic())
spec.align_ = ALIGN_NUMERIC;
@ -555,19 +546,19 @@ void basic_printf_context<OutputIt, Char, AF>::format() {
}
// Parse type.
if (it == end)
FMT_THROW(format_error("invalid format string"));
if (it == end) FMT_THROW(format_error("invalid format string"));
spec.type = static_cast<char>(*it++);
if (arg.is_integral()) {
// Normalize type.
switch (spec.type) {
case 'i': case 'u':
case 'i':
case 'u':
spec.type = 'd';
break;
case 'c':
// TODO: handle wchar_t better?
visit_format_arg(
internal::char_converter<basic_printf_context>(arg), arg);
visit_format_arg(internal::char_converter<basic_printf_context>(arg),
arg);
break;
}
}
@ -580,10 +571,10 @@ void basic_printf_context<OutputIt, Char, AF>::format() {
buffer.append(start, it);
}
template <typename Buffer>
struct basic_printf_context_t {
typedef basic_printf_context<
std::back_insert_iterator<Buffer>, typename Buffer::value_type> type;
template <typename Buffer> struct basic_printf_context_t {
typedef basic_printf_context<std::back_insert_iterator<Buffer>,
typename Buffer::value_type>
type;
};
typedef basic_printf_context_t<internal::buffer>::type printf_context;
@ -598,9 +589,11 @@ typedef basic_format_args<wprintf_context> wprintf_args;
arguments and can be implicitly converted to `~fmt::printf_args`.
\endrst
*/
template<typename... Args>
inline format_arg_store<printf_context, Args...>
make_printf_args(const Args &... args) { return {args...}; }
template <typename... Args>
inline format_arg_store<printf_context, Args...> make_printf_args(
const Args&... args) {
return {args...};
}
/**
\rst
@ -608,15 +601,18 @@ inline format_arg_store<printf_context, Args...>
arguments and can be implicitly converted to `~fmt::wprintf_args`.
\endrst
*/
template<typename... Args>
inline format_arg_store<wprintf_context, Args...>
make_wprintf_args(const Args &... args) { return {args...}; }
template <typename... Args>
inline format_arg_store<wprintf_context, Args...> make_wprintf_args(
const Args&... args) {
return {args...};
}
template <typename S, typename Char = FMT_CHAR(S)>
inline std::basic_string<Char>
vsprintf(const S &format,
basic_format_args<typename basic_printf_context_t<
internal::basic_buffer<Char>>::type> args) {
inline std::basic_string<Char> vsprintf(
const S& format,
basic_format_args<
typename basic_printf_context_t<internal::basic_buffer<Char>>::type>
args) {
basic_memory_buffer<Char> buffer;
printf(buffer, to_string_view(format), args);
return to_string(buffer);
@ -632,26 +628,28 @@ vsprintf(const S &format,
\endrst
*/
template <typename S, typename... Args>
inline FMT_ENABLE_IF_T(
internal::is_string<S>::value, std::basic_string<FMT_CHAR(S)>)
sprintf(const S &format, const Args & ... args) {
inline FMT_ENABLE_IF_T(internal::is_string<S>::value,
std::basic_string<FMT_CHAR(S)>)
sprintf(const S& format, const Args&... args) {
internal::check_format_string<Args...>(format);
typedef internal::basic_buffer<FMT_CHAR(S)> buffer;
typedef typename basic_printf_context_t<buffer>::type context;
format_arg_store<context, Args...> as{ args... };
return vsprintf(to_string_view(format),
basic_format_args<context>(as));
format_arg_store<context, Args...> as{args...};
return vsprintf(to_string_view(format), basic_format_args<context>(as));
}
template <typename S, typename Char = FMT_CHAR(S)>
inline int vfprintf(std::FILE *f, const S &format,
basic_format_args<typename basic_printf_context_t<
internal::basic_buffer<Char>>::type> args) {
inline int vfprintf(
std::FILE* f, const S& format,
basic_format_args<
typename basic_printf_context_t<internal::basic_buffer<Char>>::type>
args) {
basic_memory_buffer<Char> buffer;
printf(buffer, to_string_view(format), args);
std::size_t size = buffer.size();
return std::fwrite(
buffer.data(), sizeof(Char), size, f) < size ? -1 : static_cast<int>(size);
return std::fwrite(buffer.data(), sizeof(Char), size, f) < size
? -1
: static_cast<int>(size);
}
/**
@ -665,19 +663,20 @@ inline int vfprintf(std::FILE *f, const S &format,
*/
template <typename S, typename... Args>
inline FMT_ENABLE_IF_T(internal::is_string<S>::value, int)
fprintf(std::FILE *f, const S &format, const Args & ... args) {
fprintf(std::FILE* f, const S& format, const Args&... args) {
internal::check_format_string<Args...>(format);
typedef internal::basic_buffer<FMT_CHAR(S)> buffer;
typedef typename basic_printf_context_t<buffer>::type context;
format_arg_store<context, Args...> as{ args... };
return vfprintf(f, to_string_view(format),
basic_format_args<context>(as));
format_arg_store<context, Args...> as{args...};
return vfprintf(f, to_string_view(format), basic_format_args<context>(as));
}
template <typename S, typename Char = FMT_CHAR(S)>
inline int vprintf(const S &format,
basic_format_args<typename basic_printf_context_t<
internal::basic_buffer<Char>>::type> args) {
inline int vprintf(
const S& format,
basic_format_args<
typename basic_printf_context_t<internal::basic_buffer<Char>>::type>
args) {
return vfprintf(stdout, to_string_view(format), args);
}
@ -692,20 +691,20 @@ inline int vprintf(const S &format,
*/
template <typename S, typename... Args>
inline FMT_ENABLE_IF_T(internal::is_string<S>::value, int)
printf(const S &format_str, const Args & ... args) {
printf(const S& format_str, const Args&... args) {
internal::check_format_string<Args...>(format_str);
typedef internal::basic_buffer<FMT_CHAR(S)> buffer;
typedef typename basic_printf_context_t<buffer>::type context;
format_arg_store<context, Args...> as{ args... };
return vprintf(to_string_view(format_str),
basic_format_args<context>(as));
format_arg_store<context, Args...> as{args...};
return vprintf(to_string_view(format_str), basic_format_args<context>(as));
}
template <typename S, typename Char = FMT_CHAR(S)>
inline int vfprintf(std::basic_ostream<Char> &os,
const S &format,
basic_format_args<typename basic_printf_context_t<
internal::basic_buffer<Char>>::type> args) {
inline int vfprintf(
std::basic_ostream<Char>& os, const S& format,
basic_format_args<
typename basic_printf_context_t<internal::basic_buffer<Char>>::type>
args) {
basic_memory_buffer<Char> buffer;
printf(buffer, to_string_view(format), args);
internal::write(os, buffer);
@ -723,12 +722,12 @@ inline int vfprintf(std::basic_ostream<Char> &os,
*/
template <typename S, typename... Args>
inline FMT_ENABLE_IF_T(internal::is_string<S>::value, int)
fprintf(std::basic_ostream<FMT_CHAR(S)> &os,
const S &format_str, const Args & ... args) {
fprintf(std::basic_ostream<FMT_CHAR(S)>& os, const S& format_str,
const Args&... args) {
internal::check_format_string<Args...>(format_str);
typedef internal::basic_buffer<FMT_CHAR(S)> buffer;
typedef typename basic_printf_context_t<buffer>::type context;
format_arg_store<context, Args...> as{ args... };
format_arg_store<context, Args...> as{args...};
return vfprintf(os, to_string_view(format_str),
basic_format_args<context>(as));
}

View File

@ -12,8 +12,8 @@
#ifndef FMT_RANGES_H_
#define FMT_RANGES_H_
#include "format.h"
#include <type_traits>
#include "format.h"
// output only up to N items from the range.
#ifndef FMT_RANGE_OUTPUT_LENGTH_LIMIT
@ -22,10 +22,9 @@
FMT_BEGIN_NAMESPACE
template <typename Char>
struct formatting_base {
template <typename Char> struct formatting_base {
template <typename ParseContext>
FMT_CONSTEXPR auto parse(ParseContext &ctx) -> decltype(ctx.begin()) {
FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
};
@ -33,7 +32,8 @@ struct formatting_base {
template <typename Char, typename Enable = void>
struct formatting_range : formatting_base<Char> {
static FMT_CONSTEXPR_DECL const std::size_t range_length_limit =
FMT_RANGE_OUTPUT_LENGTH_LIMIT; // output only up to N items from the range.
FMT_RANGE_OUTPUT_LENGTH_LIMIT; // output only up to N items from the
// range.
Char prefix;
Char delimiter;
Char postfix;
@ -55,32 +55,29 @@ struct formatting_tuple : formatting_base<Char> {
namespace internal {
template <typename RangeT, typename OutputIterator>
void copy(const RangeT &range, OutputIterator out) {
void copy(const RangeT& range, OutputIterator out) {
for (auto it = range.begin(), end = range.end(); it != end; ++it)
*out++ = *it;
}
template <typename OutputIterator>
void copy(const char *str, OutputIterator out) {
const char *p_curr = str;
void copy(const char* str, OutputIterator out) {
const char* p_curr = str;
while (*p_curr) {
*out++ = *p_curr++;
}
}
template <typename OutputIterator>
void copy(char ch, OutputIterator out) {
template <typename OutputIterator> void copy(char ch, OutputIterator out) {
*out++ = ch;
}
/// Return true value if T has std::string interface, like std::string_view.
template <typename T>
class is_like_std_string {
template <typename T> class is_like_std_string {
template <typename U>
static auto check(U *p) ->
decltype(p->find('a'), p->length(), p->data(), int());
template <typename>
static void check(...);
static auto check(U* p)
-> decltype(p->find('a'), p->length(), p->data(), int());
template <typename> static void check(...);
public:
static FMT_CONSTEXPR_DECL const bool value =
@ -90,15 +87,14 @@ class is_like_std_string {
template <typename Char>
struct is_like_std_string<fmt::basic_string_view<Char>> : std::true_type {};
template <typename... Ts>
struct conditional_helper {};
template <typename... Ts> struct conditional_helper {};
template <typename T, typename _ = void>
struct is_range_ : std::false_type {};
template <typename T, typename _ = void> struct is_range_ : std::false_type {};
#if !FMT_MSC_VER || FMT_MSC_VER > 1800
template <typename T>
struct is_range_<T, typename std::conditional<
struct is_range_<
T, typename std::conditional<
false,
conditional_helper<decltype(internal::declval<T>().begin()),
decltype(internal::declval<T>().end())>,
@ -106,14 +102,13 @@ struct is_range_<T, typename std::conditional<
#endif
/// tuple_size and tuple_element check.
template <typename T>
class is_tuple_like_ {
template <typename T> class is_tuple_like_ {
template <typename U>
static auto check(U *p) ->
decltype(std::tuple_size<U>::value,
internal::declval<typename std::tuple_element<0, U>::type>(), int());
template <typename>
static void check(...);
static auto check(U* p)
-> decltype(std::tuple_size<U>::value,
internal::declval<typename std::tuple_element<0, U>::type>(),
int());
template <typename> static void check(...);
public:
static FMT_CONSTEXPR_DECL const bool value =
@ -124,18 +119,14 @@ class is_tuple_like_ {
#if defined(__cpp_lib_integer_sequence) || FMT_MSC_VER >= 1900
template <typename T, T... N>
using integer_sequence = std::integer_sequence<T, N...>;
template <std::size_t... N>
using index_sequence = std::index_sequence<N...>;
template <std::size_t... N> using index_sequence = std::index_sequence<N...>;
template <std::size_t N>
using make_index_sequence = std::make_index_sequence<N>;
#else
template <typename T, T... N>
struct integer_sequence {
template <typename T, T... N> struct integer_sequence {
typedef T value_type;
static FMT_CONSTEXPR std::size_t size() {
return sizeof...(N);
}
static FMT_CONSTEXPR std::size_t size() { return sizeof...(N); }
};
template <std::size_t... N>
@ -151,7 +142,7 @@ using make_index_sequence = make_integer_sequence<std::size_t, N>;
#endif
template <class Tuple, class F, size_t... Is>
void for_each(index_sequence<Is...>, Tuple &&tup, F &&f) FMT_NOEXCEPT {
void for_each(index_sequence<Is...>, Tuple&& tup, F&& f) FMT_NOEXCEPT {
using std::get;
// using free function get<I>(T) now.
const int _[] = {0, ((void)f(get<Is>(tup)), 0)...};
@ -159,26 +150,31 @@ void for_each(index_sequence<Is...>, Tuple &&tup, F &&f) FMT_NOEXCEPT {
}
template <class T>
FMT_CONSTEXPR make_index_sequence<std::tuple_size<T>::value>
get_indexes(T const &) { return {}; }
FMT_CONSTEXPR make_index_sequence<std::tuple_size<T>::value> get_indexes(
T const&) {
return {};
}
template <class Tuple, class F>
void for_each(Tuple &&tup, F &&f) {
template <class Tuple, class F> void for_each(Tuple&& tup, F&& f) {
const auto indexes = get_indexes(tup);
for_each(indexes, std::forward<Tuple>(tup), std::forward<F>(f));
}
template<typename Arg>
FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&,
template <typename Arg>
FMT_CONSTEXPR const char* format_str_quoted(
bool add_space, const Arg&,
typename std::enable_if<
!is_like_std_string<typename std::decay<Arg>::type>::value>::type* = nullptr) {
!is_like_std_string<typename std::decay<Arg>::type>::value>::type* =
nullptr) {
return add_space ? " {}" : "{}";
}
template<typename Arg>
FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&,
template <typename Arg>
FMT_CONSTEXPR const char* format_str_quoted(
bool add_space, const Arg&,
typename std::enable_if<
is_like_std_string<typename std::decay<Arg>::type>::value>::type* = nullptr) {
is_like_std_string<typename std::decay<Arg>::type>::value>::type* =
nullptr) {
return add_space ? " \"{}\"" : "\"{}\"";
}
@ -198,21 +194,19 @@ FMT_CONSTEXPR const wchar_t* format_str_quoted(bool add_space, const wchar_t) {
} // namespace internal
template <typename T>
struct is_tuple_like {
template <typename T> struct is_tuple_like {
static FMT_CONSTEXPR_DECL const bool value =
internal::is_tuple_like_<T>::value && !internal::is_range_<T>::value;
};
template <typename TupleT, typename Char>
struct formatter<TupleT, Char,
struct formatter<
TupleT, Char,
typename std::enable_if<fmt::is_tuple_like<TupleT>::value>::type> {
private:
private:
// C++11 generic lambda for format()
template <typename FormatContext>
struct format_each {
template <typename T>
void operator()(const T& v) {
template <typename FormatContext> struct format_each {
template <typename T> void operator()(const T& v) {
if (i > 0) {
if (formatting.add_prepostfix_space) {
*out++ = ' ';
@ -228,19 +222,20 @@ private:
formatting_tuple<Char>& formatting;
std::size_t& i;
typename std::add_lvalue_reference<decltype(std::declval<FormatContext>().out())>::type out;
typename std::add_lvalue_reference<decltype(
std::declval<FormatContext>().out())>::type out;
};
public:
public:
formatting_tuple<Char> formatting;
template <typename ParseContext>
FMT_CONSTEXPR auto parse(ParseContext &ctx) -> decltype(ctx.begin()) {
FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
return formatting.parse(ctx);
}
template <typename FormatContext = format_context>
auto format(const TupleT &values, FormatContext &ctx) -> decltype(ctx.out()) {
auto format(const TupleT& values, FormatContext& ctx) -> decltype(ctx.out()) {
auto out = ctx.out();
std::size_t i = 0;
internal::copy(formatting.prefix, out);
@ -255,8 +250,7 @@ public:
}
};
template <typename T>
struct is_range {
template <typename T> struct is_range {
static FMT_CONSTEXPR_DECL const bool value =
internal::is_range_<T>::value && !internal::is_like_std_string<T>::value;
};
@ -264,17 +258,16 @@ struct is_range {
template <typename RangeT, typename Char>
struct formatter<RangeT, Char,
typename std::enable_if<fmt::is_range<RangeT>::value>::type> {
formatting_range<Char> formatting;
template <typename ParseContext>
FMT_CONSTEXPR auto parse(ParseContext &ctx) -> decltype(ctx.begin()) {
FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
return formatting.parse(ctx);
}
template <typename FormatContext>
typename FormatContext::iterator format(
const RangeT &values, FormatContext &ctx) {
typename FormatContext::iterator format(const RangeT& values,
FormatContext& ctx) {
auto out = ctx.out();
internal::copy(formatting.prefix, out);
std::size_t i = 0;
@ -305,4 +298,3 @@ struct formatter<RangeT, Char,
FMT_END_NAMESPACE
#endif // FMT_RANGES_H_

View File

@ -8,9 +8,9 @@
#ifndef FMT_TIME_H_
#define FMT_TIME_H_
#include "format.h"
#include <ctime>
#include <locale>
#include "format.h"
FMT_BEGIN_NAMESPACE
@ -18,7 +18,7 @@ FMT_BEGIN_NAMESPACE
// Usage: f FMT_NOMACRO()
#define FMT_NOMACRO
namespace internal{
namespace internal {
inline null<> localtime_r FMT_NOMACRO(...) { return null<>(); }
inline null<> localtime_s(...) { return null<>(); }
inline null<> gmtime_r(...) { return null<>(); }
@ -31,14 +31,14 @@ inline std::tm localtime(std::time_t time) {
std::time_t time_;
std::tm tm_;
dispatcher(std::time_t t): time_(t) {}
dispatcher(std::time_t t) : time_(t) {}
bool run() {
using namespace fmt::internal;
return handle(localtime_r(&time_, &tm_));
}
bool handle(std::tm *tm) { return tm != FMT_NULL; }
bool handle(std::tm* tm) { return tm != FMT_NULL; }
bool handle(internal::null<>) {
using namespace fmt::internal;
@ -50,7 +50,7 @@ inline std::tm localtime(std::time_t time) {
#if !FMT_MSC_VER
bool fallback(internal::null<>) {
using namespace fmt::internal;
std::tm *tm = std::localtime(&time_);
std::tm* tm = std::localtime(&time_);
if (tm) tm_ = *tm;
return tm != FMT_NULL;
}
@ -58,8 +58,7 @@ inline std::tm localtime(std::time_t time) {
};
dispatcher lt(time);
// Too big time values may be unsupported.
if (!lt.run())
FMT_THROW(format_error("time_t value out of range"));
if (!lt.run()) FMT_THROW(format_error("time_t value out of range"));
return lt.tm_;
}
@ -69,14 +68,14 @@ inline std::tm gmtime(std::time_t time) {
std::time_t time_;
std::tm tm_;
dispatcher(std::time_t t): time_(t) {}
dispatcher(std::time_t t) : time_(t) {}
bool run() {
using namespace fmt::internal;
return handle(gmtime_r(&time_, &tm_));
}
bool handle(std::tm *tm) { return tm != FMT_NULL; }
bool handle(std::tm* tm) { return tm != FMT_NULL; }
bool handle(internal::null<>) {
using namespace fmt::internal;
@ -87,7 +86,7 @@ inline std::tm gmtime(std::time_t time) {
#if !FMT_MSC_VER
bool fallback(internal::null<>) {
std::tm *tm = std::gmtime(&time_);
std::tm* tm = std::gmtime(&time_);
if (tm) tm_ = *tm;
return tm != FMT_NULL;
}
@ -95,33 +94,29 @@ inline std::tm gmtime(std::time_t time) {
};
dispatcher gt(time);
// Too big time values may be unsupported.
if (!gt.run())
FMT_THROW(format_error("time_t value out of range"));
if (!gt.run()) FMT_THROW(format_error("time_t value out of range"));
return gt.tm_;
}
namespace internal {
inline std::size_t strftime(char *str, std::size_t count, const char *format,
const std::tm *time) {
inline std::size_t strftime(char* str, std::size_t count, const char* format,
const std::tm* time) {
return std::strftime(str, count, format, time);
}
inline std::size_t strftime(wchar_t *str, std::size_t count,
const wchar_t *format, const std::tm *time) {
inline std::size_t strftime(wchar_t* str, std::size_t count,
const wchar_t* format, const std::tm* time) {
return std::wcsftime(str, count, format, time);
}
}
} // namespace internal
template <typename Char>
struct formatter<std::tm, Char> {
template <typename Char> struct formatter<std::tm, Char> {
template <typename ParseContext>
auto parse(ParseContext &ctx) -> decltype(ctx.begin()) {
auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
auto it = ctx.begin();
if (it != ctx.end() && *it == ':')
++it;
if (it != ctx.end() && *it == ':') ++it;
auto end = it;
while (end != ctx.end() && *end != '}')
++end;
while (end != ctx.end() && *end != '}') ++end;
tm_format.reserve(internal::to_unsigned(end - it + 1));
tm_format.append(it, end);
tm_format.push_back('\0');
@ -129,7 +124,7 @@ struct formatter<std::tm, Char> {
}
template <typename FormatContext>
auto format(const std::tm &tm, FormatContext &ctx) -> decltype(ctx.out()) {
auto format(const std::tm& tm, FormatContext& ctx) -> decltype(ctx.out()) {
basic_memory_buffer<Char> buf;
std::size_t start = buf.size();
for (;;) {

View File

@ -9,50 +9,55 @@
FMT_BEGIN_NAMESPACE
template struct internal::basic_data<void>;
template FMT_API internal::locale_ref::locale_ref(const std::locale &loc);
template FMT_API internal::locale_ref::locale_ref(const std::locale& loc);
template FMT_API std::locale internal::locale_ref::get<std::locale>() const;
// Explicit instantiations for char.
template FMT_API char internal::thousands_sep_impl(locale_ref);
template FMT_API void internal::basic_buffer<char>::append(const char *, const char *);
template FMT_API void internal::basic_buffer<char>::append(const char*,
const char*);
template FMT_API void internal::arg_map<format_context>::init(
const basic_format_args<format_context> &args);
const basic_format_args<format_context>& args);
template FMT_API int internal::char_traits<char>::format_float(
char *, std::size_t, const char *, int, double);
template FMT_API int internal::char_traits<char>::format_float(char*,
std::size_t,
const char*, int,
double);
template FMT_API int internal::char_traits<char>::format_float(
char *, std::size_t, const char *, int, long double);
template FMT_API int internal::char_traits<char>::format_float(char*,
std::size_t,
const char*, int,
long double);
template FMT_API std::string internal::vformat<char>(
string_view, basic_format_args<format_context>);
template FMT_API format_context::iterator internal::vformat_to(
internal::buffer &, string_view, basic_format_args<format_context>);
internal::buffer&, string_view, basic_format_args<format_context>);
template FMT_API void internal::sprintf_format(
double, internal::buffer &, core_format_specs);
template FMT_API void internal::sprintf_format(
long double, internal::buffer &, core_format_specs);
template FMT_API void internal::sprintf_format(double, internal::buffer&,
core_format_specs);
template FMT_API void internal::sprintf_format(long double, internal::buffer&,
core_format_specs);
// Explicit instantiations for wchar_t.
template FMT_API wchar_t internal::thousands_sep_impl(locale_ref);
template FMT_API void internal::basic_buffer<wchar_t>::append(
const wchar_t *, const wchar_t *);
template FMT_API void internal::basic_buffer<wchar_t>::append(const wchar_t*,
const wchar_t*);
template FMT_API void internal::arg_map<wformat_context>::init(
const basic_format_args<wformat_context> &);
const basic_format_args<wformat_context>&);
template FMT_API int internal::char_traits<wchar_t>::format_float(
wchar_t *, std::size_t, const wchar_t *, int, double);
wchar_t*, std::size_t, const wchar_t*, int, double);
template FMT_API int internal::char_traits<wchar_t>::format_float(
wchar_t *, std::size_t, const wchar_t *, int, long double);
wchar_t*, std::size_t, const wchar_t*, int, long double);
template FMT_API std::wstring internal::vformat<wchar_t>(
wstring_view, basic_format_args<wformat_context>);

View File

@ -13,8 +13,8 @@
#include "fmt/posix.h"
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef _WIN32
# include <unistd.h>
@ -22,8 +22,8 @@
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# include <io.h>
# include <windows.h>
# define O_CREAT _O_CREAT
# define O_TRUNC _O_TRUNC
@ -62,7 +62,7 @@ typedef ssize_t RWResult;
inline std::size_t convert_rwcount(std::size_t count) { return count; }
#endif
}
} // namespace
FMT_BEGIN_NAMESPACE
@ -72,19 +72,17 @@ buffered_file::~buffered_file() FMT_NOEXCEPT {
}
buffered_file::buffered_file(cstring_view filename, cstring_view mode) {
FMT_RETRY_VAL(file_,
FMT_SYSTEM(fopen(filename.c_str(), mode.c_str())), FMT_NULL);
FMT_RETRY_VAL(file_, FMT_SYSTEM(fopen(filename.c_str(), mode.c_str())),
FMT_NULL);
if (!file_)
FMT_THROW(system_error(errno, "cannot open file {}", filename.c_str()));
}
void buffered_file::close() {
if (!file_)
return;
if (!file_) return;
int result = FMT_SYSTEM(fclose(file_));
file_ = FMT_NULL;
if (result != 0)
FMT_THROW(system_error(errno, "cannot close file"));
if (result != 0) FMT_THROW(system_error(errno, "cannot close file"));
}
// A macro used to prevent expansion of fileno on broken versions of MinGW.
@ -92,8 +90,7 @@ void buffered_file::close() {
int buffered_file::fileno() const {
int fd = FMT_POSIX_CALL(fileno FMT_ARGS(file_));
if (fd == -1)
FMT_THROW(system_error(errno, "cannot get file descriptor"));
if (fd == -1) FMT_THROW(system_error(errno, "cannot get file descriptor"));
return fd;
}
@ -117,14 +114,12 @@ file::~file() FMT_NOEXCEPT {
}
void file::close() {
if (fd_ == -1)
return;
if (fd_ == -1) return;
// Don't retry close in case of EINTR!
// See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
int result = FMT_POSIX_CALL(close(fd_));
fd_ = -1;
if (result != 0)
FMT_THROW(system_error(errno, "cannot close file"));
if (result != 0) FMT_THROW(system_error(errno, "cannot close file"));
}
long long file::size() const {
@ -153,19 +148,17 @@ long long file::size() const {
#endif
}
std::size_t file::read(void *buffer, std::size_t count) {
std::size_t file::read(void* buffer, std::size_t count) {
RWResult result = 0;
FMT_RETRY(result, FMT_POSIX_CALL(read(fd_, buffer, convert_rwcount(count))));
if (result < 0)
FMT_THROW(system_error(errno, "cannot read from file"));
if (result < 0) FMT_THROW(system_error(errno, "cannot read from file"));
return internal::to_unsigned(result);
}
std::size_t file::write(const void *buffer, std::size_t count) {
std::size_t file::write(const void* buffer, std::size_t count) {
RWResult result = 0;
FMT_RETRY(result, FMT_POSIX_CALL(write(fd_, buffer, convert_rwcount(count))));
if (result < 0)
FMT_THROW(system_error(errno, "cannot write to file"));
if (result < 0) FMT_THROW(system_error(errno, "cannot write to file"));
return internal::to_unsigned(result);
}
@ -182,19 +175,18 @@ void file::dup2(int fd) {
int result = 0;
FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
if (result == -1) {
FMT_THROW(system_error(errno,
"cannot duplicate file descriptor {} to {}", fd_, fd));
FMT_THROW(system_error(errno, "cannot duplicate file descriptor {} to {}",
fd_, fd));
}
}
void file::dup2(int fd, error_code &ec) FMT_NOEXCEPT {
void file::dup2(int fd, error_code& ec) FMT_NOEXCEPT {
int result = 0;
FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
if (result == -1)
ec = error_code(errno);
if (result == -1) ec = error_code(errno);
}
void file::pipe(file &read_end, file &write_end) {
void file::pipe(file& read_end, file& write_end) {
// Close the descriptors first to make sure that assignments don't throw
// and there are no leaks.
read_end.close();
@ -209,20 +201,19 @@ void file::pipe(file &read_end, file &write_end) {
// http://pubs.opengroup.org/onlinepubs/009696799/functions/pipe.html
int result = FMT_POSIX_CALL(pipe(fds));
#endif
if (result != 0)
FMT_THROW(system_error(errno, "cannot create pipe"));
if (result != 0) FMT_THROW(system_error(errno, "cannot create pipe"));
// The following assignments don't throw because read_fd and write_fd
// are closed.
read_end = file(fds[0]);
write_end = file(fds[1]);
}
buffered_file file::fdopen(const char *mode) {
buffered_file file::fdopen(const char* mode) {
// Don't retry as fdopen doesn't return EINTR.
FILE *f = FMT_POSIX_CALL(fdopen(fd_, mode));
FILE* f = FMT_POSIX_CALL(fdopen(fd_, mode));
if (!f)
FMT_THROW(system_error(errno,
"cannot associate stream with file descriptor"));
FMT_THROW(
system_error(errno, "cannot associate stream with file descriptor"));
buffered_file bf(f);
fd_ = -1;
return bf;
@ -235,10 +226,8 @@ long getpagesize() {
return si.dwPageSize;
#else
long size = FMT_POSIX_CALL(sysconf(_SC_PAGESIZE));
if (size < 0)
FMT_THROW(system_error(errno, "cannot get memory page size"));
if (size < 0) FMT_THROW(system_error(errno, "cannot get memory page size"));
return size;
#endif
}
FMT_END_NAMESPACE

View File

@ -17,6 +17,6 @@
#endif
TEST(AssertTest, Fail) {
EXPECT_DEBUG_DEATH_IF_SUPPORTED(
FMT_ASSERT(false, "don't panic!"), "don't panic!");
EXPECT_DEBUG_DEATH_IF_SUPPORTED(FMT_ASSERT(false, "don't panic!"),
"don't panic!");
}

View File

@ -34,16 +34,17 @@ std::tm make_second(int s) {
return time;
}
std::string format_tm(const std::tm &time, const char *spec,
const std::locale &loc) {
auto &facet = std::use_facet<std::time_put<char>>(loc);
std::string format_tm(const std::tm& time, const char* spec,
const std::locale& loc) {
auto& facet = std::use_facet<std::time_put<char>>(loc);
std::ostringstream os;
os.imbue(loc);
facet.put(os, os, ' ', &time, spec, spec + std::strlen(spec));
return os.str();
}
#define EXPECT_TIME(spec, time, duration) { \
#define EXPECT_TIME(spec, time, duration) \
{ \
std::locale loc("ja_JP.utf8"); \
EXPECT_EQ(format_tm(time, spec, loc), \
fmt::format(loc, "{:" spec "}", duration)); \
@ -83,12 +84,12 @@ TEST(ChronoTest, FormatDefault) {
fmt::format("{}", std::chrono::duration<int, std::exa>(42)));
EXPECT_EQ("42m", fmt::format("{}", std::chrono::minutes(42)));
EXPECT_EQ("42h", fmt::format("{}", std::chrono::hours(42)));
EXPECT_EQ("42[15]s",
fmt::format("{}",
std::chrono::duration<int, std::ratio<15, 1>>(42)));
EXPECT_EQ("42[15/4]s",
fmt::format("{}",
std::chrono::duration<int, std::ratio<15, 4>>(42)));
EXPECT_EQ(
"42[15]s",
fmt::format("{}", std::chrono::duration<int, std::ratio<15, 1>>(42)));
EXPECT_EQ(
"42[15/4]s",
fmt::format("{}", std::chrono::duration<int, std::ratio<15, 4>>(42)));
}
TEST(ChronoTest, Align) {
@ -105,7 +106,6 @@ TEST(ChronoTest, Align) {
fmt::format("{:~^12%H:%M:%S}", std::chrono::seconds(12345)));
EXPECT_EQ("03:25:45 ",
fmt::format("{:{}%H:%M:%S}", std::chrono::seconds(12345), 12));
}
TEST(ChronoTest, FormatSpecs) {
@ -162,13 +162,14 @@ TEST(ChronoTest, InvalidSpecs) {
}
TEST(ChronoTest, Locale) {
const char *loc_name = "ja_JP.utf8";
const char* loc_name = "ja_JP.utf8";
bool has_locale = false;
std::locale loc;
try {
loc = std::locale(loc_name);
has_locale = true;
} catch (const std::runtime_error &) {}
} catch (const std::runtime_error&) {
}
if (!has_locale) {
fmt::print("{} locale is missing.\n", loc_name);
return;

View File

@ -11,9 +11,9 @@
#include <functional>
#include <iterator>
#include <limits>
#include <memory>
#include <string>
#include <type_traits>
#include <memory>
#include "test-assert.h"
@ -30,9 +30,9 @@
#undef max
using fmt::basic_format_arg;
using fmt::string_view;
using fmt::internal::basic_buffer;
using fmt::internal::value;
using fmt::string_view;
using testing::_;
using testing::StrictMock;
@ -42,24 +42,23 @@ namespace {
struct test_struct {};
template <typename Context, typename T>
basic_format_arg<Context> make_arg(const T &value) {
basic_format_arg<Context> make_arg(const T& value) {
return fmt::internal::make_arg<Context>(value);
}
} // namespace
FMT_BEGIN_NAMESPACE
template <typename Char>
struct formatter<test_struct, Char> {
template <typename Char> struct formatter<test_struct, Char> {
template <typename ParseContext>
auto parse(ParseContext &ctx) -> decltype(ctx.begin()) {
auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
typedef std::back_insert_iterator<basic_buffer<Char>> iterator;
auto format(test_struct, basic_format_context<iterator, char> &ctx)
auto format(test_struct, basic_format_context<iterator, char>& ctx)
-> decltype(ctx.out()) {
const Char *test = "test";
const Char* test = "test";
return std::copy_n(test, std::strlen(test), ctx.out());
}
};
@ -67,31 +66,29 @@ FMT_END_NAMESPACE
#if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 470
TEST(BufferTest, Noncopyable) {
EXPECT_FALSE(std::is_copy_constructible<basic_buffer<char> >::value);
#if !FMT_MSC_VER
EXPECT_FALSE(std::is_copy_constructible<basic_buffer<char>>::value);
# if !FMT_MSC_VER
// std::is_copy_assignable is broken in MSVC2013.
EXPECT_FALSE(std::is_copy_assignable<basic_buffer<char> >::value);
#endif
EXPECT_FALSE(std::is_copy_assignable<basic_buffer<char>>::value);
# endif
}
TEST(BufferTest, Nonmoveable) {
EXPECT_FALSE(std::is_move_constructible<basic_buffer<char> >::value);
#if !FMT_MSC_VER
EXPECT_FALSE(std::is_move_constructible<basic_buffer<char>>::value);
# if !FMT_MSC_VER
// std::is_move_assignable is broken in MSVC2013.
EXPECT_FALSE(std::is_move_assignable<basic_buffer<char> >::value);
#endif
EXPECT_FALSE(std::is_move_assignable<basic_buffer<char>>::value);
# endif
}
#endif
// A test buffer with a dummy grow method.
template <typename T>
struct test_buffer : basic_buffer<T> {
template <typename T> struct test_buffer : basic_buffer<T> {
void grow(std::size_t capacity) { this->set(FMT_NULL, capacity); }
};
template <typename T>
struct mock_buffer : basic_buffer<T> {
MOCK_METHOD1(do_grow, void (std::size_t capacity));
template <typename T> struct mock_buffer : basic_buffer<T> {
MOCK_METHOD1(do_grow, void(std::size_t capacity));
void grow(std::size_t capacity) {
this->set(this->data(), capacity);
@ -99,8 +96,8 @@ struct mock_buffer : basic_buffer<T> {
}
mock_buffer() {}
mock_buffer(T *data) { this->set(data, 0); }
mock_buffer(T *data, std::size_t capacity) { this->set(data, capacity); }
mock_buffer(T* data) { this->set(data, 0); }
mock_buffer(T* data, std::size_t capacity) { this->set(data, capacity); }
};
TEST(BufferTest, Ctor) {
@ -134,9 +131,9 @@ struct dying_buffer : test_buffer<int> {
TEST(BufferTest, VirtualDtor) {
typedef StrictMock<dying_buffer> stict_mock_buffer;
stict_mock_buffer *mock_buffer = new stict_mock_buffer();
stict_mock_buffer* mock_buffer = new stict_mock_buffer();
EXPECT_CALL(*mock_buffer, die());
basic_buffer<int> *buffer = mock_buffer;
basic_buffer<int>* buffer = mock_buffer;
delete buffer;
}
@ -147,7 +144,7 @@ TEST(BufferTest, Access) {
EXPECT_EQ(11, buffer[0]);
buffer[3] = 42;
EXPECT_EQ(42, *(&buffer[0] + 3));
const basic_buffer<char> &const_buffer = buffer;
const basic_buffer<char>& const_buffer = buffer;
EXPECT_EQ(42, const_buffer[3]);
}
@ -182,7 +179,7 @@ TEST(BufferTest, Clear) {
TEST(BufferTest, Append) {
char data[15];
mock_buffer<char> buffer(data, 10);
const char *test = "test";
const char* test = "test";
buffer.append(test, test + 5);
EXPECT_STREQ(test, &buffer[0]);
EXPECT_EQ(5u, buffer.size());
@ -197,7 +194,7 @@ TEST(BufferTest, Append) {
TEST(BufferTest, AppendAllocatesEnoughStorage) {
char data[19];
mock_buffer<char> buffer(data, 10);
const char *test = "abcdefgh";
const char* test = "abcdefgh";
buffer.resize(10);
EXPECT_CALL(buffer, do_grow(19));
buffer.append(test, test + 9);
@ -211,15 +208,14 @@ TEST(ArgTest, FormatArgs) {
struct custom_context {
typedef char char_type;
template <typename T>
struct formatter_type {
template <typename T> struct formatter_type {
struct type {
template <typename ParseContext>
auto parse(ParseContext &ctx) -> decltype(ctx.begin()) {
auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
const char *format(const T &, custom_context& ctx) {
const char* format(const T&, custom_context& ctx) {
ctx.called = true;
return FMT_NULL;
}
@ -231,7 +227,7 @@ struct custom_context {
fmt::format_parse_context parse_context() {
return fmt::format_parse_context("");
}
void advance_to(const char *) {}
void advance_to(const char*) {}
};
TEST(ArgTest, MakeValueWithCustomContext) {
@ -249,40 +245,35 @@ template <typename Char>
bool operator==(custom_value<Char> lhs, custom_value<Char> rhs) {
return lhs.value == rhs.value;
}
}
} // namespace internal
FMT_END_NAMESPACE
// Use a unique result type to make sure that there are no undesirable
// conversions.
struct test_result {};
template <typename T>
struct mock_visitor {
template <typename U>
struct result { typedef test_result type; };
template <typename T> struct mock_visitor {
template <typename U> struct result { typedef test_result type; };
mock_visitor() {
ON_CALL(*this, visit(_)).WillByDefault(testing::Return(test_result()));
}
MOCK_METHOD1_T(visit, test_result (T value));
MOCK_METHOD0_T(unexpected, void ());
MOCK_METHOD1_T(visit, test_result(T value));
MOCK_METHOD0_T(unexpected, void());
test_result operator()(T value) { return visit(value); }
template <typename U>
test_result operator()(U) {
template <typename U> test_result operator()(U) {
unexpected();
return test_result();
}
};
template <typename T>
struct visit_type { typedef T Type; };
template <typename T> struct visit_type { typedef T Type; };
#define VISIT_TYPE(Type_, visit_type_) \
template <> \
struct visit_type<Type_> { typedef visit_type_ Type; }
template <> struct visit_type<Type_> { typedef visit_type_ Type; }
VISIT_TYPE(signed char, int);
VISIT_TYPE(unsigned char, unsigned);
@ -299,28 +290,30 @@ VISIT_TYPE(unsigned long, unsigned long long);
VISIT_TYPE(float, double);
#define CHECK_ARG_(Char, expected, value) { \
#define CHECK_ARG_(Char, expected, value) \
{ \
testing::StrictMock<mock_visitor<decltype(expected)>> visitor; \
EXPECT_CALL(visitor, visit(expected)); \
typedef std::back_insert_iterator<basic_buffer<Char>> iterator; \
fmt::visit(visitor, \
make_arg<fmt::basic_format_context<iterator, Char>>(value)); \
}
}
#define CHECK_ARG(value, typename_) { \
#define CHECK_ARG(value, typename_) \
{ \
typedef decltype(value) value_type; \
typename_ visit_type<value_type>::Type expected = value; \
CHECK_ARG_(char, expected, value) \
CHECK_ARG_(wchar_t, expected, value) \
}
}
template <typename T>
class NumericArgTest : public testing::Test {};
template <typename T> class NumericArgTest : public testing::Test {};
typedef ::testing::Types<
bool, signed char, unsigned char, signed, unsigned short,
int, unsigned, long, unsigned long, long long, unsigned long long,
float, double, long double> Types;
typedef ::testing::Types<bool, signed char, unsigned char, signed,
unsigned short, int, unsigned, long, unsigned long,
long long, unsigned long long, float, double,
long double>
Types;
TYPED_TEST_CASE(NumericArgTest, Types);
template <typename T>
@ -330,7 +323,7 @@ typename std::enable_if<std::is_integral<T>::value, T>::type test_value() {
template <typename T>
typename std::enable_if<std::is_floating_point<T>::value, T>::type
test_value() {
test_value() {
return static_cast<T>(4.2);
}
@ -348,8 +341,8 @@ TEST(ArgTest, CharArg) {
TEST(ArgTest, StringArg) {
char str_data[] = "test";
char *str = str_data;
const char *cstr = str;
char* str = str_data;
const char* cstr = str;
CHECK_ARG_(char, cstr, str);
string_view sref(str);
@ -358,8 +351,8 @@ TEST(ArgTest, StringArg) {
TEST(ArgTest, WStringArg) {
wchar_t str_data[] = L"test";
wchar_t *str = str_data;
const wchar_t *cstr = str;
wchar_t* str = str_data;
const wchar_t* cstr = str;
fmt::wstring_view sref(str);
CHECK_ARG_(wchar_t, cstr, str);
@ -369,8 +362,8 @@ TEST(ArgTest, WStringArg) {
}
TEST(ArgTest, PointerArg) {
void *p = FMT_NULL;
const void *cp = FMT_NULL;
void* p = FMT_NULL;
const void* cp = FMT_NULL;
CHECK_ARG_(char, cp, p);
CHECK_ARG_(wchar_t, cp, p);
CHECK_ARG(cp, );
@ -384,7 +377,7 @@ struct check_custom {
test_buffer() : fmt::internal::basic_buffer<char>(data, 0, 10) {}
void grow(std::size_t) {}
} buffer;
fmt::internal::basic_buffer<char> &base = buffer;
fmt::internal::basic_buffer<char>& base = buffer;
fmt::format_context ctx(std::back_inserter(base), "", fmt::format_args());
h.format(ctx);
EXPECT_EQ("test", std::string(buffer.data, buffer.size()));
@ -402,7 +395,7 @@ TEST(ArgTest, CustomArg) {
}
TEST(ArgTest, VisitInvalidArg) {
testing::StrictMock< mock_visitor<fmt::monostate> > visitor;
testing::StrictMock<mock_visitor<fmt::monostate>> visitor;
EXPECT_CALL(visitor, visit(_));
fmt::basic_format_arg<fmt::format_context> arg;
visit(visitor, arg);
@ -416,9 +409,8 @@ TEST(StringViewTest, Length) {
}
// Check string_view's comparison operator.
template <template <typename> class Op>
void check_op() {
const char *inputs[] = {"foo", "fop", "fo"};
template <template <typename> class Op> void check_op() {
const char* inputs[] = {"foo", "fop", "fo"};
std::size_t num_inputs = sizeof(inputs) / sizeof(*inputs);
for (std::size_t i = 0; i < num_inputs; ++i) {
for (std::size_t j = 0; j < num_inputs; ++j) {
@ -446,7 +438,7 @@ enum basic_enum {};
TEST(CoreTest, ConvertToInt) {
EXPECT_FALSE((fmt::convert_to_int<char, char>::value));
EXPECT_FALSE((fmt::convert_to_int<const char *, char>::value));
EXPECT_FALSE((fmt::convert_to_int<const char*, char>::value));
EXPECT_TRUE((fmt::convert_to_int<basic_enum, char>::value));
}
@ -457,31 +449,31 @@ TEST(CoreTest, IsEnumConvertibleToInt) {
}
namespace my_ns {
template <typename Char>
class my_string {
template <typename Char> class my_string {
public:
my_string(const Char *s) : s_(s) {}
const Char * data() const FMT_NOEXCEPT { return s_.data(); }
my_string(const Char* s) : s_(s) {}
const Char* data() const FMT_NOEXCEPT { return s_.data(); }
std::size_t length() const FMT_NOEXCEPT { return s_.size(); }
operator const Char*() const { return s_.c_str(); }
private:
std::basic_string<Char> s_;
};
template <typename Char>
inline fmt::basic_string_view<Char>
to_string_view(const my_string<Char> &s) FMT_NOEXCEPT {
return { s.data(), s.length() };
inline fmt::basic_string_view<Char> to_string_view(const my_string<Char>& s)
FMT_NOEXCEPT {
return {s.data(), s.length()};
}
struct non_string {};
}
} // namespace my_ns
namespace FakeQt {
class QString {
public:
QString(const wchar_t *s) : s_(std::make_shared<std::wstring>(s)) {}
const wchar_t *utf16() const FMT_NOEXCEPT { return s_->data(); }
QString(const wchar_t* s) : s_(std::make_shared<std::wstring>(s)) {}
const wchar_t* utf16() const FMT_NOEXCEPT { return s_->data(); }
int size() const FMT_NOEXCEPT { return static_cast<int>(s_->size()); }
#ifdef FMT_STRING_VIEW
operator FMT_STRING_VIEW<wchar_t>() const FMT_NOEXCEPT { return *s_; }
@ -490,15 +482,13 @@ class QString {
std::shared_ptr<std::wstring> s_;
};
inline fmt::basic_string_view<wchar_t> to_string_view(
const QString &s) FMT_NOEXCEPT {
return {s.utf16(),
static_cast<std::size_t>(s.size())};
}
inline fmt::basic_string_view<wchar_t> to_string_view(const QString& s)
FMT_NOEXCEPT {
return {s.utf16(), static_cast<std::size_t>(s.size())};
}
} // namespace FakeQt
template <typename T>
class IsStringTest : public testing::Test {};
template <typename T> class IsStringTest : public testing::Test {};
typedef ::testing::Types<char, wchar_t, char16_t, char32_t> StringCharTypes;
TYPED_TEST_CASE(IsStringTest, StringCharTypes);
@ -506,11 +496,11 @@ TYPED_TEST_CASE(IsStringTest, StringCharTypes);
namespace {
template <typename Char>
struct derived_from_string_view : fmt::basic_string_view<Char> {};
}
} // namespace
TYPED_TEST(IsStringTest, IsString) {
EXPECT_TRUE((fmt::internal::is_string<TypeParam *>::value));
EXPECT_TRUE((fmt::internal::is_string<const TypeParam *>::value));
EXPECT_TRUE((fmt::internal::is_string<TypeParam*>::value));
EXPECT_TRUE((fmt::internal::is_string<const TypeParam*>::value));
EXPECT_TRUE((fmt::internal::is_string<TypeParam[2]>::value));
EXPECT_TRUE((fmt::internal::is_string<const TypeParam[2]>::value));
EXPECT_TRUE((fmt::internal::is_string<std::basic_string<TypeParam>>::value));
@ -600,11 +590,12 @@ TEST(FormatterTest, FormatExplicitlyConvertibleToWStringView) {
}
struct explicitly_convertible_to_string_like {
template <
typename String,
typename = typename std::enable_if<
std::is_constructible<String, const char*, std::size_t>::value>::type>
FMT_EXPLICIT operator String() const { return String("foo", 3u); }
template <typename String,
typename = typename std::enable_if<std::is_constructible<
String, const char*, std::size_t>::value>::type>
FMT_EXPLICIT operator String() const {
return String("foo", 3u);
}
};
TEST(FormatterTest, FormatExplicitlyConvertibleToStringLike) {

View File

@ -13,22 +13,21 @@
// A custom argument formatter that doesn't print `-` for floating-point values
// rounded to 0.
class custom_arg_formatter :
public fmt::arg_formatter<fmt::back_insert_range<fmt::internal::buffer>> {
class custom_arg_formatter
: public fmt::arg_formatter<fmt::back_insert_range<fmt::internal::buffer>> {
public:
typedef fmt::back_insert_range<fmt::internal::buffer> range;
typedef fmt::arg_formatter<range> base;
custom_arg_formatter(
fmt::format_context &ctx, fmt::format_specs *s = FMT_NULL)
custom_arg_formatter(fmt::format_context& ctx,
fmt::format_specs* s = FMT_NULL)
: base(ctx, s) {}
using base::operator();
iterator operator()(double value) {
// Comparing a float to 0.0 is safe.
if (round(value * pow(10, spec()->precision)) == 0.0)
value = 0;
if (round(value * pow(10, spec()->precision)) == 0.0) value = 0;
return base::operator()(value);
}
};
@ -41,7 +40,7 @@ std::string custom_vformat(fmt::string_view format_str, fmt::format_args args) {
}
template <typename... Args>
std::string custom_format(const char *format_str, const Args & ... args) {
std::string custom_format(const char* format_str, const Args&... args) {
auto va = fmt::make_format_args(args...);
return custom_vformat(format_str, va);
}

View File

@ -32,13 +32,11 @@
using fmt::internal::fp;
template <bool is_iec559>
void test_construct_from_double() {
template <bool is_iec559> void test_construct_from_double() {
fmt::print("warning: double is not IEC559, skipping FP tests\n");
}
template <>
void test_construct_from_double<true>() {
template <> void test_construct_from_double<true>() {
auto v = fp(1.23);
EXPECT_EQ(v.f, 0x13ae147ae147aeu);
EXPECT_EQ(v.e, -52);
@ -107,14 +105,10 @@ TEST(FPTest, Grisu2FormatCompilesWithNonIEEEDouble) {
grisu2_format(4.2f, buf, fmt::core_format_specs());
}
template <typename T>
struct ValueExtractor: fmt::internal::function<T> {
T operator()(T value) {
return value;
}
template <typename T> struct ValueExtractor : fmt::internal::function<T> {
T operator()(T value) { return value; }
template <typename U>
FMT_NORETURN T operator()(U) {
template <typename U> FMT_NORETURN T operator()(U) {
throw std::runtime_error(fmt::format("invalid type {}", typeid(U).name()));
}
};
@ -136,7 +130,7 @@ TEST(FormatTest, FormatNegativeNaN) {
}
TEST(FormatTest, StrError) {
char *message = FMT_NULL;
char* message = FMT_NULL;
char buffer[BUFFER_SIZE];
EXPECT_ASSERT(fmt::safe_strerror(EDOM, message = FMT_NULL, 0),
"invalid buffer");
@ -178,8 +172,8 @@ TEST(FormatTest, FormatErrorCode) {
}
{
fmt::memory_buffer buffer;
std::string prefix(
fmt::inline_buffer_size - msg.size() - sep.size() + 1, 'x');
std::string prefix(fmt::inline_buffer_size - msg.size() - sep.size() + 1,
'x');
fmt::format_error_code(buffer, 42, prefix);
EXPECT_EQ(msg, to_string(buffer));
}
@ -188,8 +182,7 @@ TEST(FormatTest, FormatErrorCode) {
// Test maximum buffer size.
msg = fmt::format("error {}", codes[i]);
fmt::memory_buffer buffer;
std::string prefix(
fmt::inline_buffer_size - msg.size() - sep.size(), 'x');
std::string prefix(fmt::inline_buffer_size - msg.size() - sep.size(), 'x');
fmt::format_error_code(buffer, codes[i], prefix);
EXPECT_EQ(prefix + sep + msg, to_string(buffer));
std::size_t size = fmt::inline_buffer_size;
@ -250,17 +243,18 @@ TEST(ColorsTest, ColorsFormat) {
"\x1b[38;2;255;020;030mrgb(255,20,30)\x1b[0m");
EXPECT_EQ(fmt::format(fg(fmt::color::blue), "blue"),
"\x1b[38;2;000;000;255mblue\x1b[0m");
EXPECT_EQ(fmt::format(fg(fmt::color::blue) | bg(fmt::color::red), "two color"),
EXPECT_EQ(
fmt::format(fg(fmt::color::blue) | bg(fmt::color::red), "two color"),
"\x1b[38;2;000;000;255m\x1b[48;2;255;000;000mtwo color\x1b[0m");
EXPECT_EQ(fmt::format(fmt::emphasis::bold, "bold"),
"\x1b[1mbold\x1b[0m");
EXPECT_EQ(fmt::format(fmt::emphasis::bold, "bold"), "\x1b[1mbold\x1b[0m");
EXPECT_EQ(fmt::format(fmt::emphasis::italic, "italic"),
"\x1b[3mitalic\x1b[0m");
EXPECT_EQ(fmt::format(fmt::emphasis::underline, "underline"),
"\x1b[4munderline\x1b[0m");
EXPECT_EQ(fmt::format(fmt::emphasis::strikethrough, "strikethrough"),
"\x1b[9mstrikethrough\x1b[0m");
EXPECT_EQ(fmt::format(fg(fmt::color::blue) | fmt::emphasis::bold, "blue/bold"),
EXPECT_EQ(
fmt::format(fg(fmt::color::blue) | fmt::emphasis::bold, "blue/bold"),
"\x1b[1m\x1b[38;2;000;000;255mblue/bold\x1b[0m");
EXPECT_EQ(fmt::format(fmt::emphasis::bold, "bold error"),
"\x1b[1mbold error\x1b[0m");

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -7,11 +7,11 @@
#include "gtest-extra.h"
#include <gtest/gtest-spi.h>
#include <algorithm>
#include <cstring>
#include <memory>
#include <stdexcept>
#include <gtest/gtest-spi.h>
#if defined(_WIN32) && !defined(__MINGW32__)
# include <crtdbg.h> // for _CrtSetReportMode
@ -22,7 +22,7 @@
namespace {
// This is used to suppress coverity warnings about untrusted values.
std::string sanitize(const std::string &s) {
std::string sanitize(const std::string& s) {
std::string result;
for (std::string::const_iterator i = s.begin(), end = s.end(); i != end; ++i)
result.push_back(static_cast<char>(*i & 0xff));
@ -52,13 +52,9 @@ int SingleEvaluationTest::b_;
void do_nothing() {}
void throw_exception() {
throw std::runtime_error("test");
}
void throw_exception() { throw std::runtime_error("test"); }
void throw_system_error() {
throw fmt::system_error(EDOM, "test");
}
void throw_system_error() { throw fmt::system_error(EDOM, "test"); }
// Tests that when EXPECT_THROW_MSG fails, it evaluates its message argument
// exactly once.
@ -71,42 +67,49 @@ TEST_F(SingleEvaluationTest, FailedEXPECT_THROW_MSG) {
// Tests that when EXPECT_SYSTEM_ERROR fails, it evaluates its message argument
// exactly once.
TEST_F(SingleEvaluationTest, FailedEXPECT_SYSTEM_ERROR) {
EXPECT_NONFATAL_FAILURE(
EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, p_++), "01234");
EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, p_++),
"01234");
EXPECT_EQ(s_ + 1, p_);
}
// Tests that when EXPECT_WRITE fails, it evaluates its message argument
// exactly once.
TEST_F(SingleEvaluationTest, FailedEXPECT_WRITE) {
EXPECT_NONFATAL_FAILURE(
EXPECT_WRITE(stdout, std::printf("test"), p_++), "01234");
EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(stdout, std::printf("test"), p_++),
"01234");
EXPECT_EQ(s_ + 1, p_);
}
// Tests that assertion arguments are evaluated exactly once.
TEST_F(SingleEvaluationTest, ExceptionTests) {
// successful EXPECT_THROW_MSG
EXPECT_THROW_MSG({ // NOLINT
EXPECT_THROW_MSG(
{ // NOLINT
a_++;
throw_exception();
}, std::exception, (b_++, "test"));
},
std::exception, (b_++, "test"));
EXPECT_EQ(1, a_);
EXPECT_EQ(1, b_);
// failed EXPECT_THROW_MSG, throws different type
EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG({ // NOLINT
EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(
{ // NOLINT
a_++;
throw_exception();
}, std::logic_error, (b_++, "test")), "throws a different type");
},
std::logic_error, (b_++, "test")),
"throws a different type");
EXPECT_EQ(2, a_);
EXPECT_EQ(2, b_);
// failed EXPECT_THROW_MSG, throws an exception with different message
EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG({ // NOLINT
EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(
{ // NOLINT
a_++;
throw_exception();
}, std::exception, (b_++, "other")),
},
std::exception, (b_++, "other")),
"throws an exception with a different message");
EXPECT_EQ(3, a_);
EXPECT_EQ(3, b_);
@ -120,33 +123,40 @@ TEST_F(SingleEvaluationTest, ExceptionTests) {
TEST_F(SingleEvaluationTest, SystemErrorTests) {
// successful EXPECT_SYSTEM_ERROR
EXPECT_SYSTEM_ERROR({ // NOLINT
EXPECT_SYSTEM_ERROR(
{ // NOLINT
a_++;
throw_system_error();
}, EDOM, (b_++, "test"));
},
EDOM, (b_++, "test"));
EXPECT_EQ(1, a_);
EXPECT_EQ(1, b_);
// failed EXPECT_SYSTEM_ERROR, throws different type
EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR({ // NOLINT
EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(
{ // NOLINT
a_++;
throw_exception();
}, EDOM, (b_++, "test")), "throws a different type");
},
EDOM, (b_++, "test")),
"throws a different type");
EXPECT_EQ(2, a_);
EXPECT_EQ(2, b_);
// failed EXPECT_SYSTEM_ERROR, throws an exception with different message
EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR({ // NOLINT
EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(
{ // NOLINT
a_++;
throw_system_error();
}, EDOM, (b_++, "other")),
},
EDOM, (b_++, "other")),
"throws an exception with a different message");
EXPECT_EQ(3, a_);
EXPECT_EQ(3, b_);
// failed EXPECT_SYSTEM_ERROR, throws nothing
EXPECT_NONFATAL_FAILURE(
EXPECT_SYSTEM_ERROR(a_++, EDOM, (b_++, "test")), "throws nothing");
EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(a_++, EDOM, (b_++, "test")),
"throws nothing");
EXPECT_EQ(4, a_);
EXPECT_EQ(4, b_);
}
@ -154,18 +164,23 @@ TEST_F(SingleEvaluationTest, SystemErrorTests) {
// Tests that assertion arguments are evaluated exactly once.
TEST_F(SingleEvaluationTest, WriteTests) {
// successful EXPECT_WRITE
EXPECT_WRITE(stdout, { // NOLINT
EXPECT_WRITE(stdout,
{ // NOLINT
a_++;
std::printf("test");
}, (b_++, "test"));
},
(b_++, "test"));
EXPECT_EQ(1, a_);
EXPECT_EQ(1, b_);
// failed EXPECT_WRITE
EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(stdout, { // NOLINT
EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(stdout,
{ // NOLINT
a_++;
std::printf("test");
}, (b_++, "other")), "Actual: test");
},
(b_++, "other")),
"Actual: test");
EXPECT_EQ(2, a_);
EXPECT_EQ(2, b_);
}
@ -178,8 +193,8 @@ TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
EXPECT_THROW_MSG(throw runtime_error(""), runtime_error, "");
EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(n++, runtime_error, ""), "");
EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(throw 1, runtime_error, ""), "");
EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(
throw runtime_error("a"), runtime_error, "b"), "");
EXPECT_NONFATAL_FAILURE(
EXPECT_THROW_MSG(throw runtime_error("a"), runtime_error, "b"), "");
}
// Tests that the compiler will not complain about unreachable code in the
@ -189,8 +204,9 @@ TEST(ExpectSystemErrorTest, DoesNotGenerateUnreachableCodeWarning) {
EXPECT_SYSTEM_ERROR(throw fmt::system_error(EDOM, "test"), EDOM, "test");
EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(n++, EDOM, ""), "");
EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(throw 1, EDOM, ""), "");
EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(
throw fmt::system_error(EDOM, "aaa"), EDOM, "bbb"), "");
EXPECT_NONFATAL_FAILURE(
EXPECT_SYSTEM_ERROR(throw fmt::system_error(EDOM, "aaa"), EDOM, "bbb"),
"");
}
TEST(AssertionSyntaxTest, ExceptionAssertionBehavesLikeSingleStatement) {
@ -267,8 +283,7 @@ TEST(ExpectTest, EXPECT_WRITE) {
EXPECT_WRITE(stdout, do_nothing(), "");
EXPECT_WRITE(stdout, std::printf("test"), "test");
EXPECT_WRITE(stderr, std::fprintf(stderr, "test"), "test");
EXPECT_NONFATAL_FAILURE(
EXPECT_WRITE(stdout, std::printf("that"), "this"),
EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(stdout, std::printf("that"), "this"),
"Expected: this\n"
" Actual: that");
}
@ -278,7 +293,8 @@ TEST(StreamingAssertionsTest, EXPECT_THROW_MSG) {
<< "unexpected failure";
EXPECT_NONFATAL_FAILURE(
EXPECT_THROW_MSG(throw_exception(), std::exception, "other")
<< "expected failure", "expected failure");
<< "expected failure",
"expected failure");
}
TEST(StreamingAssertionsTest, EXPECT_SYSTEM_ERROR) {
@ -286,15 +302,15 @@ TEST(StreamingAssertionsTest, EXPECT_SYSTEM_ERROR) {
<< "unexpected failure";
EXPECT_NONFATAL_FAILURE(
EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "other")
<< "expected failure", "expected failure");
<< "expected failure",
"expected failure");
}
TEST(StreamingAssertionsTest, EXPECT_WRITE) {
EXPECT_WRITE(stdout, std::printf("test"), "test")
<< "unexpected failure";
EXPECT_NONFATAL_FAILURE(
EXPECT_WRITE(stdout, std::printf("test"), "other")
<< "expected failure", "expected failure");
EXPECT_WRITE(stdout, std::printf("test"), "test") << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(stdout, std::printf("test"), "other")
<< "expected failure",
"expected failure");
}
TEST(UtilTest, FormatSystemError) {
@ -340,8 +356,8 @@ TEST(OutputRedirectTest, FlushErrorInCtor) {
EXPECT_EQ('x', fputc('x', f.get()));
FMT_POSIX(close(write_fd));
std::unique_ptr<OutputRedirect> redir{FMT_NULL};
EXPECT_SYSTEM_ERROR_NOASSERT(redir.reset(new OutputRedirect(f.get())),
EBADF, "cannot flush stream");
EXPECT_SYSTEM_ERROR_NOASSERT(redir.reset(new OutputRedirect(f.get())), EBADF,
"cannot flush stream");
redir.reset(FMT_NULL);
write_copy.dup2(write_fd); // "undo" close or dtor will fail
}
@ -352,8 +368,9 @@ TEST(OutputRedirectTest, DupErrorInCtor) {
file copy = file::dup(fd);
FMT_POSIX(close(fd));
std::unique_ptr<OutputRedirect> redir{FMT_NULL};
EXPECT_SYSTEM_ERROR_NOASSERT(redir.reset(new OutputRedirect(f.get())),
EBADF, fmt::format("cannot duplicate file descriptor {}", fd));
EXPECT_SYSTEM_ERROR_NOASSERT(
redir.reset(new OutputRedirect(f.get())), EBADF,
fmt::format("cannot duplicate file descriptor {}", fd));
copy.dup2(fd); // "undo" close or dtor will fail
}
@ -382,8 +399,8 @@ TEST(OutputRedirectTest, FlushErrorInRestoreAndRead) {
// Put a character in a file buffer.
EXPECT_EQ('x', fputc('x', f.get()));
FMT_POSIX(close(write_fd));
EXPECT_SYSTEM_ERROR_NOASSERT(redir.restore_and_read(),
EBADF, "cannot flush stream");
EXPECT_SYSTEM_ERROR_NOASSERT(redir.restore_and_read(), EBADF,
"cannot flush stream");
write_copy.dup2(write_fd); // "undo" close or dtor will fail
}
@ -396,14 +413,16 @@ TEST(OutputRedirectTest, ErrorInDtor) {
std::unique_ptr<OutputRedirect> redir(new OutputRedirect(f.get()));
// Put a character in a file buffer.
EXPECT_EQ('x', fputc('x', f.get()));
EXPECT_WRITE(stderr, {
// The close function must be called inside EXPECT_WRITE, otherwise
// the system may recycle closed file descriptor when redirecting the
// output in EXPECT_STDERR and the second close will break output
// redirection.
EXPECT_WRITE(stderr,
{
// The close function must be called inside EXPECT_WRITE,
// otherwise the system may recycle closed file descriptor when
// redirecting the output in EXPECT_STDERR and the second close
// will break output redirection.
FMT_POSIX(close(write_fd));
SUPPRESS_ASSERT(redir.reset(FMT_NULL));
}, format_system_error(EBADF, "cannot flush stream"));
},
format_system_error(EBADF, "cannot flush stream"));
write_copy.dup2(write_fd); // "undo" close or dtor of buffered_file will fail
}

View File

@ -12,25 +12,23 @@
using fmt::file;
void OutputRedirect::flush() {
#if EOF != -1
# if EOF != -1
# error "FMT_RETRY assumes return value of -1 indicating failure"
#endif
# endif
int result = 0;
FMT_RETRY(result, fflush(file_));
if (result != 0)
throw fmt::system_error(errno, "cannot flush stream");
if (result != 0) throw fmt::system_error(errno, "cannot flush stream");
}
void OutputRedirect::restore() {
if (original_.descriptor() == -1)
return; // Already restored.
if (original_.descriptor() == -1) return; // Already restored.
flush();
// Restore the original file.
original_.dup2(FMT_POSIX(fileno(file_)));
original_.close();
}
OutputRedirect::OutputRedirect(FILE *f) : file_(f) {
OutputRedirect::OutputRedirect(FILE* f) : file_(f) {
flush();
int fd = FMT_POSIX(fileno(f));
// Create a file object referring to the original file.
@ -45,7 +43,7 @@ OutputRedirect::OutputRedirect(FILE *f) : file_(f) {
OutputRedirect::~OutputRedirect() FMT_NOEXCEPT {
try {
restore();
} catch (const std::exception &e) {
} catch (const std::exception& e) {
std::fputs(e.what(), stderr);
}
}
@ -56,8 +54,7 @@ std::string OutputRedirect::restore_and_read() {
// Read everything from the pipe.
std::string content;
if (read_end_.descriptor() == -1)
return content; // Already read.
if (read_end_.descriptor() == -1) return content; // Already read.
enum { BUFFER_SIZE = 4096 };
char buffer[BUFFER_SIZE];
std::size_t count = 0;
@ -69,7 +66,7 @@ std::string OutputRedirect::restore_and_read() {
return content;
}
std::string read(file &f, std::size_t count) {
std::string read(file& f, std::size_t count) {
std::string buffer(count, '\0');
std::size_t n = 0, offset = 0;
do {

View File

@ -28,38 +28,36 @@
bool gtest_caught_expected = false; \
try { \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
} \
catch (expected_exception const& e) { \
} catch (expected_exception const& e) { \
if (gtest_expected_message != e.what()) { \
gtest_ar \
<< #statement " throws an exception with a different message.\n" \
gtest_ar << #statement \
" throws an exception with a different message.\n" \
<< "Expected: " << gtest_expected_message << "\n" \
<< " Actual: " << e.what(); \
goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
} \
gtest_caught_expected = true; \
} \
catch (...) { \
gtest_ar << \
"Expected: " #statement " throws an exception of type " \
#expected_exception ".\n Actual: it throws a different type."; \
} catch (...) { \
gtest_ar << "Expected: " #statement \
" throws an exception of type " #expected_exception \
".\n Actual: it throws a different type."; \
goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
} \
if (!gtest_caught_expected) { \
gtest_ar << \
"Expected: " #statement " throws an exception of type " \
#expected_exception ".\n Actual: it throws nothing."; \
gtest_ar << "Expected: " #statement \
" throws an exception of type " #expected_exception \
".\n Actual: it throws nothing."; \
goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
} \
} else \
GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \
fail(gtest_ar.failure_message())
GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \
: fail(gtest_ar.failure_message())
// Tests that the statement throws the expected exception and the exception's
// what() method returns expected message.
#define EXPECT_THROW_MSG(statement, expected_exception, expected_message) \
FMT_TEST_THROW_(statement, expected_exception, \
expected_message, GTEST_NONFATAL_FAILURE_)
FMT_TEST_THROW_(statement, expected_exception, expected_message, \
GTEST_NONFATAL_FAILURE_)
std::string format_system_error(int error_code, fmt::string_view message);
@ -73,7 +71,7 @@ std::string format_system_error(int error_code, fmt::string_view message);
// The output it can handle is limited by the pipe capacity.
class OutputRedirect {
private:
FILE *file_;
FILE* file_;
fmt::file original_; // Original file passed to redirector.
fmt::file read_end_; // Read end of the pipe where the output is redirected.
@ -83,7 +81,7 @@ class OutputRedirect {
void restore();
public:
explicit OutputRedirect(FILE *file);
explicit OutputRedirect(FILE* file);
~OutputRedirect() FMT_NOEXCEPT;
// Restores the original file, reads output from the pipe into a string
@ -91,7 +89,7 @@ class OutputRedirect {
std::string restore_and_read();
};
#define FMT_TEST_WRITE_(statement, expected_output, file, fail) \
# define FMT_TEST_WRITE_(statement, expected_output, file, fail) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (::testing::AssertionResult gtest_ar = ::testing::AssertionSuccess()) { \
std::string gtest_expected_output = expected_output; \
@ -99,21 +97,20 @@ class OutputRedirect {
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
std::string gtest_output = gtest_redir.restore_and_read(); \
if (gtest_output != gtest_expected_output) { \
gtest_ar \
<< #statement " produces different output.\n" \
gtest_ar << #statement " produces different output.\n" \
<< "Expected: " << gtest_expected_output << "\n" \
<< " Actual: " << gtest_output; \
goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
} \
} else \
GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \
fail(gtest_ar.failure_message())
GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \
: fail(gtest_ar.failure_message())
// Tests that the statement writes the expected output to file.
#define EXPECT_WRITE(file, statement, expected_output) \
# define EXPECT_WRITE(file, statement, expected_output) \
FMT_TEST_WRITE_(statement, expected_output, file, GTEST_NONFATAL_FAILURE_)
#ifdef _MSC_VER
# ifdef _MSC_VER
// Suppresses Windows assertions on invalid file descriptors, making
// POSIX functions return proper error codes instead of crashing on Windows.
@ -122,38 +119,41 @@ class SuppressAssert {
_invalid_parameter_handler original_handler_;
int original_report_mode_;
static void handle_invalid_parameter(const wchar_t *,
const wchar_t *, const wchar_t *, unsigned , uintptr_t) {}
static void handle_invalid_parameter(const wchar_t*, const wchar_t*,
const wchar_t*, unsigned, uintptr_t) {}
public:
SuppressAssert()
: original_handler_(_set_invalid_parameter_handler(handle_invalid_parameter)),
original_report_mode_(_CrtSetReportMode(_CRT_ASSERT, 0)) {
}
: original_handler_(
_set_invalid_parameter_handler(handle_invalid_parameter)),
original_report_mode_(_CrtSetReportMode(_CRT_ASSERT, 0)) {}
~SuppressAssert() {
_set_invalid_parameter_handler(original_handler_);
_CrtSetReportMode(_CRT_ASSERT, original_report_mode_);
}
};
# define SUPPRESS_ASSERT(statement) { SuppressAssert sa; statement; }
#else
# define SUPPRESS_ASSERT(statement) \
{ \
SuppressAssert sa; \
statement; \
}
# else
# define SUPPRESS_ASSERT(statement) statement
#endif // _MSC_VER
# endif // _MSC_VER
#define EXPECT_SYSTEM_ERROR_NOASSERT(statement, error_code, message) \
# define EXPECT_SYSTEM_ERROR_NOASSERT(statement, error_code, message) \
EXPECT_SYSTEM_ERROR(SUPPRESS_ASSERT(statement), error_code, message)
// Attempts to read count characters from a file.
std::string read(fmt::file &f, std::size_t count);
std::string read(fmt::file& f, std::size_t count);
#define EXPECT_READ(file, expected_content) \
# define EXPECT_READ(file, expected_content) \
EXPECT_EQ(expected_content, read(file, std::strlen(expected_content)))
#endif // FMT_USE_FILE_DESCRIPTORS
template <typename Mock>
struct ScopedMock : testing::StrictMock<Mock> {
template <typename Mock> struct ScopedMock : testing::StrictMock<Mock> {
ScopedMock() { Mock::instance = this; }
~ScopedMock() { Mock::instance = FMT_NULL; }
};

View File

@ -8,8 +8,7 @@
#include "fmt/locale.h"
#include "gmock.h"
template <typename Char>
struct numpunct : std::numpunct<Char> {
template <typename Char> struct numpunct : std::numpunct<Char> {
protected:
Char do_thousands_sep() const FMT_OVERRIDE { return '~'; }
};

View File

@ -8,25 +8,23 @@
#ifndef FMT_MOCK_ALLOCATOR_H_
#define FMT_MOCK_ALLOCATOR_H_
#include "gmock.h"
#include "fmt/format.h"
#include "gmock.h"
template <typename T>
class mock_allocator {
template <typename T> class mock_allocator {
public:
mock_allocator() {}
mock_allocator(const mock_allocator &) {}
mock_allocator(const mock_allocator&) {}
typedef T value_type;
MOCK_METHOD1_T(allocate, T* (std::size_t n));
MOCK_METHOD2_T(deallocate, void (T* p, std::size_t n));
MOCK_METHOD1_T(allocate, T*(std::size_t n));
MOCK_METHOD2_T(deallocate, void(T* p, std::size_t n));
};
template <typename Allocator>
class allocator_ref {
template <typename Allocator> class allocator_ref {
private:
Allocator *alloc_;
Allocator* alloc_;
void move(allocator_ref &other) {
void move(allocator_ref& other) {
alloc_ = other.alloc_;
other.alloc_ = FMT_NULL;
}
@ -34,24 +32,24 @@ class allocator_ref {
public:
typedef typename Allocator::value_type value_type;
explicit allocator_ref(Allocator *alloc = FMT_NULL) : alloc_(alloc) {}
explicit allocator_ref(Allocator* alloc = FMT_NULL) : alloc_(alloc) {}
allocator_ref(const allocator_ref &other) : alloc_(other.alloc_) {}
allocator_ref(allocator_ref &&other) { move(other); }
allocator_ref(const allocator_ref& other) : alloc_(other.alloc_) {}
allocator_ref(allocator_ref&& other) { move(other); }
allocator_ref& operator=(allocator_ref &&other) {
allocator_ref& operator=(allocator_ref&& other) {
assert(this != &other);
move(other);
return *this;
}
allocator_ref& operator=(const allocator_ref &other) {
allocator_ref& operator=(const allocator_ref& other) {
alloc_ = other.alloc_;
return *this;
}
public:
Allocator *get() const { return alloc_; }
Allocator* get() const { return alloc_; }
value_type* allocate(std::size_t n) {
return fmt::internal::allocate(*alloc_, n);

View File

@ -16,26 +16,26 @@
using fmt::format;
using fmt::format_error;
static std::ostream &operator<<(std::ostream &os, const Date &d) {
static std::ostream& operator<<(std::ostream& os, const Date& d) {
os << d.year() << '-' << d.month() << '-' << d.day();
return os;
}
static std::wostream &operator<<(std::wostream &os, const Date &d) {
static std::wostream& operator<<(std::wostream& os, const Date& d) {
os << d.year() << L'-' << d.month() << L'-' << d.day();
return os;
}
enum TestEnum {};
static std::ostream &operator<<(std::ostream &os, TestEnum) {
static std::ostream& operator<<(std::ostream& os, TestEnum) {
return os << "TestEnum";
}
static std::wostream &operator<<(std::wostream &os, TestEnum) {
static std::wostream& operator<<(std::wostream& os, TestEnum) {
return os << L"TestEnum";
}
enum TestEnum2 {A};
enum TestEnum2 { A };
TEST(OStreamTest, Enum) {
EXPECT_FALSE((fmt::convert_to_int<TestEnum, char>::value));
@ -48,14 +48,14 @@ TEST(OStreamTest, Enum) {
typedef fmt::back_insert_range<fmt::internal::buffer> range;
struct test_arg_formatter: fmt::arg_formatter<range> {
test_arg_formatter(fmt::format_context &ctx, fmt::format_specs &s)
struct test_arg_formatter : fmt::arg_formatter<range> {
test_arg_formatter(fmt::format_context& ctx, fmt::format_specs& s)
: fmt::arg_formatter<range>(ctx, &s) {}
};
TEST(OStreamTest, CustomArg) {
fmt::memory_buffer buffer;
fmt::internal::buffer &base = buffer;
fmt::internal::buffer& base = buffer;
fmt::format_context ctx(std::back_inserter(base), "", fmt::format_args());
fmt::format_specs spec;
test_arg_formatter af(ctx, spec);
@ -75,20 +75,20 @@ TEST(OStreamTest, Format) {
TEST(OStreamTest, FormatSpecs) {
EXPECT_EQ("def ", format("{0:<5}", TestString("def")));
EXPECT_EQ(" def", format("{0:>5}", TestString("def")));
EXPECT_THROW_MSG(format("{0:=5}", TestString("def")),
format_error, "format specifier requires numeric argument");
EXPECT_THROW_MSG(format("{0:=5}", TestString("def")), format_error,
"format specifier requires numeric argument");
EXPECT_EQ(" def ", format("{0:^5}", TestString("def")));
EXPECT_EQ("def**", format("{0:*<5}", TestString("def")));
EXPECT_THROW_MSG(format("{0:+}", TestString()),
format_error, "format specifier requires numeric argument");
EXPECT_THROW_MSG(format("{0:-}", TestString()),
format_error, "format specifier requires numeric argument");
EXPECT_THROW_MSG(format("{0: }", TestString()),
format_error, "format specifier requires numeric argument");
EXPECT_THROW_MSG(format("{0:#}", TestString()),
format_error, "format specifier requires numeric argument");
EXPECT_THROW_MSG(format("{0:05}", TestString()),
format_error, "format specifier requires numeric argument");
EXPECT_THROW_MSG(format("{0:+}", TestString()), format_error,
"format specifier requires numeric argument");
EXPECT_THROW_MSG(format("{0:-}", TestString()), format_error,
"format specifier requires numeric argument");
EXPECT_THROW_MSG(format("{0: }", TestString()), format_error,
"format specifier requires numeric argument");
EXPECT_THROW_MSG(format("{0:#}", TestString()), format_error,
"format specifier requires numeric argument");
EXPECT_THROW_MSG(format("{0:05}", TestString()), format_error,
"format specifier requires numeric argument");
EXPECT_EQ("test ", format("{0:13}", TestString("test")));
EXPECT_EQ("test ", format("{0:{1}}", TestString("test"), 13));
EXPECT_EQ("te", format("{0:.2}", TestString("test")));
@ -96,7 +96,7 @@ TEST(OStreamTest, FormatSpecs) {
}
struct EmptyTest {};
static std::ostream &operator<<(std::ostream &os, EmptyTest) {
static std::ostream& operator<<(std::ostream& os, EmptyTest) {
return os << "";
}
@ -116,7 +116,7 @@ TEST(OStreamTest, Print) {
TEST(OStreamTest, WriteToOStream) {
std::ostringstream os;
fmt::memory_buffer buffer;
const char *foo = "foo";
const char* foo = "foo";
buffer.append(foo, foo + std::strlen(foo));
fmt::internal::write(os, buffer);
EXPECT_EQ("foo", os.str());
@ -125,8 +125,7 @@ TEST(OStreamTest, WriteToOStream) {
TEST(OStreamTest, WriteToOStreamMaxSize) {
std::size_t max_size = std::numeric_limits<std::size_t>::max();
std::streamsize max_streamsize = std::numeric_limits<std::streamsize>::max();
if (max_size <= fmt::internal::to_unsigned(max_streamsize))
return;
if (max_size <= fmt::internal::to_unsigned(max_streamsize)) return;
struct test_buffer : fmt::internal::buffer {
explicit test_buffer(std::size_t size) { resize(size); }
@ -134,19 +133,19 @@ TEST(OStreamTest, WriteToOStreamMaxSize) {
} buffer(max_size);
struct mock_streambuf : std::streambuf {
MOCK_METHOD2(xsputn, std::streamsize (const void *s, std::streamsize n));
std::streamsize xsputn(const char *s, std::streamsize n) {
const void *v = s;
MOCK_METHOD2(xsputn, std::streamsize(const void* s, std::streamsize n));
std::streamsize xsputn(const char* s, std::streamsize n) {
const void* v = s;
return xsputn(v, n);
}
} streambuf;
struct test_ostream : std::ostream {
explicit test_ostream(mock_streambuf &buffer) : std::ostream(&buffer) {}
explicit test_ostream(mock_streambuf& buffer) : std::ostream(&buffer) {}
} os(streambuf);
testing::InSequence sequence;
const char *data = FMT_NULL;
const char* data = FMT_NULL;
typedef std::make_unsigned<std::streamsize>::type ustreamsize;
ustreamsize size = max_size;
do {
@ -173,7 +172,7 @@ TEST(OStreamTest, ConstexprString) {
namespace fmt_test {
struct ABC {};
template <typename Output> Output &operator<<(Output &out, ABC) {
template <typename Output> Output& operator<<(Output& out, ABC) {
out << "ABC";
return out;
}

View File

@ -13,9 +13,9 @@
#include "posix-mock.h"
#include "../src/posix.cc"
#include <climits>
#include <errno.h>
#include <fcntl.h>
#include <climits>
#include <memory>
#ifdef _WIN32
@ -33,8 +33,8 @@ using fmt::error_code;
using fmt::file;
using testing::_;
using testing::StrEq;
using testing::Return;
using testing::StrEq;
namespace {
int open_count;
@ -53,7 +53,7 @@ std::size_t write_nbyte;
bool sysconf_error;
enum FStatSimulation { NONE, MAX_SIZE, ERROR } fstat_sim;
}
} // namespace
#define EMULATE_EINTR(func, error_result) \
if (func##_count != 0) { \
@ -64,13 +64,13 @@ enum FStatSimulation { NONE, MAX_SIZE, ERROR } fstat_sim;
}
#ifndef _MSC_VER
int test::open(const char *path, int oflag, int mode) {
int test::open(const char* path, int oflag, int mode) {
EMULATE_EINTR(open, -1);
return ::open(path, oflag, mode);
}
#else
errno_t test::sopen_s(
int* pfh, const char *filename, int oflag, int shflag, int pmode) {
errno_t test::sopen_s(int* pfh, const char* filename, int oflag, int shflag,
int pmode) {
EMULATE_EINTR(open, EINTR);
return _sopen_s(pfh, filename, oflag, shflag, pmode);
}
@ -80,8 +80,7 @@ errno_t test::sopen_s(
long test::sysconf(int name) {
long result = ::sysconf(name);
if (!sysconf_error)
return result;
if (!sysconf_error) return result;
// Simulate an error.
errno = EINVAL;
return -1;
@ -89,10 +88,9 @@ long test::sysconf(int name) {
static off_t max_file_size() { return std::numeric_limits<off_t>::max(); }
int test::fstat(int fd, struct stat *buf) {
int test::fstat(int fd, struct stat* buf) {
int result = ::fstat(fd, buf);
if (fstat_sim == MAX_SIZE)
buf->st_size = max_file_size();
if (fstat_sim == MAX_SIZE) buf->st_size = max_file_size();
return result;
}
@ -132,18 +130,18 @@ int test::dup2(int fildes, int fildes2) {
return ::FMT_POSIX(dup2(fildes, fildes2));
}
FILE *test::fdopen(int fildes, const char *mode) {
FILE* test::fdopen(int fildes, const char* mode) {
EMULATE_EINTR(fdopen, FMT_NULL);
return ::FMT_POSIX(fdopen(fildes, mode));
}
test::ssize_t test::read(int fildes, void *buf, test::size_t nbyte) {
test::ssize_t test::read(int fildes, void* buf, test::size_t nbyte) {
read_nbyte = nbyte;
EMULATE_EINTR(read, -1);
return ::FMT_POSIX(read(fildes, buf, nbyte));
}
test::ssize_t test::write(int fildes, const void *buf, test::size_t nbyte) {
test::ssize_t test::write(int fildes, const void* buf, test::size_t nbyte) {
write_nbyte = nbyte;
EMULATE_EINTR(write, -1);
return ::FMT_POSIX(write(fildes, buf, nbyte));
@ -155,23 +153,23 @@ int test::pipe(int fildes[2]) {
return ::pipe(fildes);
}
#else
int test::pipe(int *pfds, unsigned psize, int textmode) {
int test::pipe(int* pfds, unsigned psize, int textmode) {
EMULATE_EINTR(pipe, -1);
return _pipe(pfds, psize, textmode);
}
#endif
FILE *test::fopen(const char *filename, const char *mode) {
FILE* test::fopen(const char* filename, const char* mode) {
EMULATE_EINTR(fopen, FMT_NULL);
return ::fopen(filename, mode);
}
int test::fclose(FILE *stream) {
int test::fclose(FILE* stream) {
EMULATE_EINTR(fclose, EOF);
return ::fclose(stream);
}
int (test::fileno)(FILE *stream) {
int(test::fileno)(FILE* stream) {
EMULATE_EINTR(fileno, -1);
#ifdef fileno
return FMT_POSIX(fileno(stream));
@ -208,8 +206,8 @@ TEST(UtilTest, GetPageSize) {
#else
EXPECT_EQ(sysconf(_SC_PAGESIZE), fmt::getpagesize());
sysconf_error = true;
EXPECT_SYSTEM_ERROR(
fmt::getpagesize(), EINVAL, "cannot get memory page size");
EXPECT_SYSTEM_ERROR(fmt::getpagesize(), EINVAL,
"cannot get memory page size");
sysconf_error = false;
#endif
}
@ -217,8 +215,8 @@ TEST(UtilTest, GetPageSize) {
TEST(FileTest, OpenRetry) {
write_file("test", "there must be something here");
std::unique_ptr<file> f{FMT_NULL};
EXPECT_RETRY(f.reset(new file("test", file::RDONLY)),
open, "cannot open file test");
EXPECT_RETRY(f.reset(new file("test", file::RDONLY)), open,
"cannot open file test");
#ifndef _WIN32
char c = 0;
f->read(&c, 1);
@ -230,12 +228,14 @@ TEST(FileTest, CloseNoRetryInDtor) {
file::pipe(read_end, write_end);
std::unique_ptr<file> f(new file(std::move(read_end)));
int saved_close_count = 0;
EXPECT_WRITE(stderr, {
EXPECT_WRITE(stderr,
{
close_count = 1;
f.reset(FMT_NULL);
saved_close_count = close_count;
close_count = 0;
}, format_system_error(EINTR, "cannot close file") + "\n");
},
format_system_error(EINTR, "cannot close file") + "\n");
EXPECT_EQ(2, saved_close_count);
}
@ -256,8 +256,8 @@ TEST(FileTest, Size) {
EXPECT_EQ(content.size(), static_cast<unsigned long long>(f.size()));
#ifdef _WIN32
fmt::memory_buffer message;
fmt::internal::format_windows_error(
message, ERROR_ACCESS_DENIED, "cannot get file size");
fmt::internal::format_windows_error(message, ERROR_ACCESS_DENIED,
"cannot get file size");
fstat_sim = ERROR;
EXPECT_THROW_MSG(f.size(), fmt::windows_error, fmt::to_string(message));
fstat_sim = NONE;
@ -284,8 +284,8 @@ TEST(FileTest, ReadRetry) {
write_end.close();
char buffer[SIZE];
std::size_t count = 0;
EXPECT_RETRY(count = read_end.read(buffer, SIZE),
read, "cannot read from file");
EXPECT_RETRY(count = read_end.read(buffer, SIZE), read,
"cannot read from file");
EXPECT_EQ_POSIX(static_cast<std::streamsize>(SIZE), count);
}
@ -294,8 +294,8 @@ TEST(FileTest, WriteRetry) {
file::pipe(read_end, write_end);
enum { SIZE = 4 };
std::size_t count = 0;
EXPECT_RETRY(count = write_end.write("test", SIZE),
write, "cannot write to file");
EXPECT_RETRY(count = write_end.write("test", SIZE), write,
"cannot write to file");
write_end.close();
#ifndef _WIN32
EXPECT_EQ(static_cast<std::streamsize>(SIZE), count);
@ -312,8 +312,7 @@ TEST(FileTest, ConvertReadCount) {
file::pipe(read_end, write_end);
char c;
std::size_t size = UINT_MAX;
if (sizeof(unsigned) != sizeof(std::size_t))
++size;
if (sizeof(unsigned) != sizeof(std::size_t)) ++size;
read_count = 1;
read_nbyte = 0;
EXPECT_THROW(read_end.read(&c, size), fmt::system_error);
@ -326,8 +325,7 @@ TEST(FileTest, ConvertWriteCount) {
file::pipe(read_end, write_end);
char c;
std::size_t size = UINT_MAX;
if (sizeof(unsigned) != sizeof(std::size_t))
++size;
if (sizeof(unsigned) != sizeof(std::size_t)) ++size;
write_count = 1;
write_nbyte = 0;
EXPECT_THROW(write_end.write(&c, size), fmt::system_error);
@ -339,7 +337,8 @@ TEST(FileTest, ConvertWriteCount) {
TEST(FileTest, DupNoRetry) {
int stdout_fd = FMT_POSIX(fileno(stdout));
dup_count = 1;
EXPECT_SYSTEM_ERROR(file::dup(stdout_fd), EINTR,
EXPECT_SYSTEM_ERROR(
file::dup(stdout_fd), EINTR,
fmt::format("cannot duplicate file descriptor {}", stdout_fd));
dup_count = 0;
}
@ -369,8 +368,8 @@ TEST(FileTest, Dup2NoExceptRetry) {
TEST(FileTest, PipeNoRetry) {
file read_end, write_end;
pipe_count = 1;
EXPECT_SYSTEM_ERROR(
file::pipe(read_end, write_end), EINTR, "cannot create pipe");
EXPECT_SYSTEM_ERROR(file::pipe(read_end, write_end), EINTR,
"cannot create pipe");
pipe_count = 0;
}
@ -378,16 +377,16 @@ TEST(FileTest, FdopenNoRetry) {
file read_end, write_end;
file::pipe(read_end, write_end);
fdopen_count = 1;
EXPECT_SYSTEM_ERROR(read_end.fdopen("r"),
EINTR, "cannot associate stream with file descriptor");
EXPECT_SYSTEM_ERROR(read_end.fdopen("r"), EINTR,
"cannot associate stream with file descriptor");
fdopen_count = 0;
}
TEST(BufferedFileTest, OpenRetry) {
write_file("test", "there must be something here");
std::unique_ptr<buffered_file> f{FMT_NULL};
EXPECT_RETRY(f.reset(new buffered_file("test", "r")),
fopen, "cannot open file test");
EXPECT_RETRY(f.reset(new buffered_file("test", "r")), fopen,
"cannot open file test");
#ifndef _WIN32
char c = 0;
if (fread(&c, 1, 1, f->get()) < 1)
@ -400,12 +399,14 @@ TEST(BufferedFileTest, CloseNoRetryInDtor) {
file::pipe(read_end, write_end);
std::unique_ptr<buffered_file> f(new buffered_file(read_end.fdopen("r")));
int saved_fclose_count = 0;
EXPECT_WRITE(stderr, {
EXPECT_WRITE(stderr,
{
fclose_count = 1;
f.reset(FMT_NULL);
saved_fclose_count = fclose_count;
fclose_count = 0;
}, format_system_error(EINTR, "cannot close file") + "\n");
},
format_system_error(EINTR, "cannot close file") + "\n");
EXPECT_EQ(2, saved_fclose_count);
}
@ -430,14 +431,14 @@ TEST(BufferedFileTest, FilenoNoRetry) {
}
struct TestMock {
static TestMock *instance;
} *TestMock::instance;
static TestMock* instance;
} * TestMock::instance;
TEST(ScopedMock, Scope) {
{
ScopedMock<TestMock> mock;
EXPECT_EQ(&mock, TestMock::instance);
TestMock &copy = mock;
TestMock& copy = mock;
static_cast<void>(copy);
}
EXPECT_EQ(FMT_NULL, TestMock::instance);
@ -448,20 +449,20 @@ TEST(ScopedMock, Scope) {
typedef fmt::Locale::Type LocaleType;
struct LocaleMock {
static LocaleMock *instance;
MOCK_METHOD3(newlocale, LocaleType (int category_mask, const char *locale,
static LocaleMock* instance;
MOCK_METHOD3(newlocale, LocaleType(int category_mask, const char* locale,
LocaleType base));
MOCK_METHOD1(freelocale, void (LocaleType locale));
MOCK_METHOD1(freelocale, void(LocaleType locale));
MOCK_METHOD3(strtod_l, double (const char *nptr, char **endptr,
LocaleType locale));
} *LocaleMock::instance;
MOCK_METHOD3(strtod_l,
double(const char* nptr, char** endptr, LocaleType locale));
} * LocaleMock::instance;
#ifdef _MSC_VER
# ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable: 4273)
# pragma warning(disable : 4273)
_locale_t _create_locale(int category, const char *locale) {
_locale_t _create_locale(int category, const char* locale) {
return LocaleMock::instance->newlocale(category, locale, 0);
}
@ -469,38 +470,41 @@ void _free_locale(_locale_t locale) {
LocaleMock::instance->freelocale(locale);
}
double _strtod_l(const char *nptr, char **endptr, _locale_t locale) {
double _strtod_l(const char* nptr, char** endptr, _locale_t locale) {
return LocaleMock::instance->strtod_l(nptr, endptr, locale);
}
# pragma warning(pop)
#endif
# endif
#if defined(__THROW) && FMT_GCC_VERSION > 0 && FMT_GCC_VERSION <= 408
#define FMT_LOCALE_THROW __THROW
#else
#define FMT_LOCALE_THROW
#endif
# if defined(__THROW) && FMT_GCC_VERSION > 0 && FMT_GCC_VERSION <= 408
# define FMT_LOCALE_THROW __THROW
# else
# define FMT_LOCALE_THROW
# endif
LocaleType newlocale(int category_mask, const char *locale, LocaleType base) FMT_LOCALE_THROW {
LocaleType newlocale(int category_mask, const char* locale,
LocaleType base) FMT_LOCALE_THROW {
return LocaleMock::instance->newlocale(category_mask, locale, base);
}
#if defined(__APPLE__) || (defined(__FreeBSD__) && __FreeBSD_version < 1200002)
# if defined(__APPLE__) || \
(defined(__FreeBSD__) && __FreeBSD_version < 1200002)
typedef int FreeLocaleResult;
#else
# else
typedef void FreeLocaleResult;
#endif
# endif
FreeLocaleResult freelocale(LocaleType locale) FMT_LOCALE_THROW {
LocaleMock::instance->freelocale(locale);
return FreeLocaleResult();
}
double strtod_l(const char *nptr, char **endptr, LocaleType locale) FMT_LOCALE_THROW {
double strtod_l(const char* nptr, char** endptr,
LocaleType locale) FMT_LOCALE_THROW {
return LocaleMock::instance->strtod_l(nptr, endptr, locale);
}
#undef FMT_LOCALE_THROW
# undef FMT_LOCALE_THROW
TEST(LocaleTest, LocaleMock) {
ScopedMock<LocaleMock> mock;
@ -510,9 +514,9 @@ TEST(LocaleTest, LocaleMock) {
}
TEST(LocaleTest, Locale) {
#ifndef LC_NUMERIC_MASK
# ifndef LC_NUMERIC_MASK
enum { LC_NUMERIC_MASK = LC_NUMERIC };
#endif
# endif
ScopedMock<LocaleMock> mock;
LocaleType impl = reinterpret_cast<LocaleType>(42);
EXPECT_CALL(mock, newlocale(LC_NUMERIC_MASK, StrEq("C"), FMT_NULL))
@ -528,7 +532,7 @@ TEST(LocaleTest, Strtod) {
.WillOnce(Return(reinterpret_cast<LocaleType>(42)));
EXPECT_CALL(mock, freelocale(_));
fmt::Locale locale;
const char *str = "4.2";
const char* str = "4.2";
char end = 'x';
EXPECT_CALL(mock, strtod_l(str, _, locale.get()))
.WillOnce(testing::DoAll(testing::SetArgPointee<1>(&end), Return(777)));

View File

@ -28,13 +28,13 @@ namespace test {
// Size type for read and write.
typedef size_t size_t;
typedef ssize_t ssize_t;
int open(const char *path, int oflag, int mode);
int fstat(int fd, struct stat *buf);
int open(const char* path, int oflag, int mode);
int fstat(int fd, struct stat* buf);
#else
typedef unsigned size_t;
typedef int ssize_t;
errno_t sopen_s(
int* pfh, const char *filename, int oflag, int shflag, int pmode);
errno_t sopen_s(int* pfh, const char* filename, int oflag, int shflag,
int pmode);
#endif
#ifndef _WIN32
@ -48,20 +48,20 @@ int close(int fildes);
int dup(int fildes);
int dup2(int fildes, int fildes2);
FILE *fdopen(int fildes, const char *mode);
FILE* fdopen(int fildes, const char* mode);
ssize_t read(int fildes, void *buf, size_t nbyte);
ssize_t write(int fildes, const void *buf, size_t nbyte);
ssize_t read(int fildes, void* buf, size_t nbyte);
ssize_t write(int fildes, const void* buf, size_t nbyte);
#ifndef _WIN32
int pipe(int fildes[2]);
#else
int pipe(int *pfds, unsigned psize, int textmode);
int pipe(int* pfds, unsigned psize, int textmode);
#endif
FILE *fopen(const char *filename, const char *mode);
int fclose(FILE *stream);
int (fileno)(FILE *stream);
FILE* fopen(const char* filename, const char* mode);
int fclose(FILE* stream);
int(fileno)(FILE* stream);
} // namespace test
#define FMT_SYSTEM(call) test::call

View File

@ -44,9 +44,9 @@ static file open_file() {
}
// Attempts to write a string to a file.
static void write(file &f, fmt::string_view s) {
static void write(file& f, fmt::string_view s) {
std::size_t num_chars_left = s.size();
const char *ptr = s.data();
const char* ptr = s.data();
do {
std::size_t count = f.write(ptr, num_chars_left);
ptr += count;
@ -63,7 +63,7 @@ TEST(BufferedFileTest, DefaultCtor) {
TEST(BufferedFileTest, MoveCtor) {
buffered_file bf = open_buffered_file();
FILE *fp = bf.get();
FILE* fp = bf.get();
EXPECT_TRUE(fp != FMT_NULL);
buffered_file bf2(std::move(bf));
EXPECT_EQ(fp, bf2.get());
@ -72,7 +72,7 @@ TEST(BufferedFileTest, MoveCtor) {
TEST(BufferedFileTest, MoveAssignment) {
buffered_file bf = open_buffered_file();
FILE *fp = bf.get();
FILE* fp = bf.get();
EXPECT_TRUE(fp != FMT_NULL);
buffered_file bf2;
bf2 = std::move(bf);
@ -89,13 +89,13 @@ TEST(BufferedFileTest, MoveAssignmentClosesFile) {
}
TEST(BufferedFileTest, MoveFromTemporaryInCtor) {
FILE *fp = FMT_NULL;
FILE* fp = FMT_NULL;
buffered_file f(open_buffered_file(&fp));
EXPECT_EQ(fp, f.get());
}
TEST(BufferedFileTest, MoveFromTemporaryInAssignment) {
FILE *fp = FMT_NULL;
FILE* fp = FMT_NULL;
buffered_file f;
f = open_buffered_file(&fp);
EXPECT_EQ(fp, f.get());
@ -119,14 +119,16 @@ TEST(BufferedFileTest, CloseFileInDtor) {
TEST(BufferedFileTest, CloseErrorInDtor) {
std::unique_ptr<buffered_file> f(new buffered_file(open_buffered_file()));
EXPECT_WRITE(stderr, {
// The close function must be called inside EXPECT_WRITE, otherwise
// the system may recycle closed file descriptor when redirecting the
// output in EXPECT_STDERR and the second close will break output
// redirection.
EXPECT_WRITE(stderr,
{
// The close function must be called inside EXPECT_WRITE,
// otherwise the system may recycle closed file descriptor when
// redirecting the output in EXPECT_STDERR and the second close
// will break output redirection.
FMT_POSIX(close(f->fileno()));
SUPPRESS_ASSERT(f.reset(FMT_NULL));
}, format_system_error(EBADF, "cannot close file") + "\n");
},
format_system_error(EBADF, "cannot close file") + "\n");
}
TEST(BufferedFileTest, Close) {
@ -149,13 +151,15 @@ TEST(BufferedFileTest, Fileno) {
#ifndef __COVERITY__
// fileno on a null FILE pointer either crashes or returns an error.
// Disable Coverity because this is intentional.
EXPECT_DEATH_IF_SUPPORTED({
EXPECT_DEATH_IF_SUPPORTED(
{
try {
f.fileno();
} catch (const fmt::system_error&) {
std::exit(1);
}
}, "");
},
"");
#endif
f = open_buffered_file();
EXPECT_TRUE(f.fileno() != -1);
@ -169,7 +173,7 @@ TEST(FileTest, DefaultCtor) {
}
TEST(FileTest, OpenBufferedFileInCtor) {
FILE *fp = safe_fopen("test-file", "w");
FILE* fp = safe_fopen("test-file", "w");
std::fputs(FILE_CONTENT, fp);
std::fclose(fp);
file f("test-file", file::RDONLY);
@ -177,8 +181,8 @@ TEST(FileTest, OpenBufferedFileInCtor) {
}
TEST(FileTest, OpenBufferedFileError) {
EXPECT_SYSTEM_ERROR(file("nonexistent", file::RDONLY),
ENOENT, "cannot open file nonexistent");
EXPECT_SYSTEM_ERROR(file("nonexistent", file::RDONLY), ENOENT,
"cannot open file nonexistent");
}
TEST(FileTest, MoveCtor) {
@ -208,7 +212,7 @@ TEST(FileTest, MoveAssignmentClosesFile) {
EXPECT_TRUE(isclosed(old_fd));
}
static file OpenBufferedFile(int &fd) {
static file OpenBufferedFile(int& fd) {
file f = open_file();
fd = f.descriptor();
return f;
@ -246,14 +250,16 @@ TEST(FileTest, CloseFileInDtor) {
TEST(FileTest, CloseErrorInDtor) {
std::unique_ptr<file> f(new file(open_file()));
EXPECT_WRITE(stderr, {
// The close function must be called inside EXPECT_WRITE, otherwise
// the system may recycle closed file descriptor when redirecting the
// output in EXPECT_STDERR and the second close will break output
// redirection.
EXPECT_WRITE(stderr,
{
// The close function must be called inside EXPECT_WRITE,
// otherwise the system may recycle closed file descriptor when
// redirecting the output in EXPECT_STDERR and the second close
// will break output redirection.
FMT_POSIX(close(f->descriptor()));
SUPPRESS_ASSERT(f.reset(FMT_NULL));
}, format_system_error(EBADF, "cannot close file") + "\n");
},
format_system_error(EBADF, "cannot close file") + "\n");
}
TEST(FileTest, Close) {
@ -309,8 +315,8 @@ TEST(FileTest, Dup) {
#ifndef __COVERITY__
TEST(FileTest, DupError) {
int value = -1;
EXPECT_SYSTEM_ERROR_NOASSERT(file::dup(value),
EBADF, "cannot duplicate file descriptor -1");
EXPECT_SYSTEM_ERROR_NOASSERT(file::dup(value), EBADF,
"cannot duplicate file descriptor -1");
}
#endif
@ -324,7 +330,8 @@ TEST(FileTest, Dup2) {
TEST(FileTest, Dup2Error) {
file f = open_file();
EXPECT_SYSTEM_ERROR_NOASSERT(f.dup2(-1), EBADF,
EXPECT_SYSTEM_ERROR_NOASSERT(
f.dup2(-1), EBADF,
fmt::format("cannot duplicate file descriptor {} to -1", f.descriptor()));
}
@ -363,8 +370,8 @@ TEST(FileTest, Fdopen) {
TEST(FileTest, FdopenError) {
file f;
EXPECT_SYSTEM_ERROR_NOASSERT(
f.fdopen("r"), EBADF, "cannot associate stream with file descriptor");
EXPECT_SYSTEM_ERROR_NOASSERT(f.fdopen("r"), EBADF,
"cannot associate stream with file descriptor");
}
#ifdef FMT_LOCALE

View File

@ -5,6 +5,7 @@
//
// For the license information refer to prepare.h.
#include <stdint.h>
#include <cctype>
#include <cfloat>
#include <climits>
@ -13,12 +14,11 @@
#include <deque>
#include <list>
#include <memory>
#include <stdint.h>
#include <string>
// Check if fmt/prepare.h compiles with windows.h included before it.
#ifdef _WIN32
#include <windows.h>
# include <windows.h>
#endif
#include "fmt/prepare.h"
@ -35,24 +35,24 @@ using testing::Return;
using testing::StrictMock;
class mock_parts_collector {
public:
public:
MOCK_METHOD1(add, void(fmt::format_part<char>));
MOCK_METHOD1(substitute_last, void(fmt::format_part<char>));
MOCK_METHOD0(last, fmt::format_part<char>());
};
FMT_BEGIN_NAMESPACE
bool operator==(const internal::string_view_metadata &lhs,
const internal::string_view_metadata &rhs) {
bool operator==(const internal::string_view_metadata& lhs,
const internal::string_view_metadata& rhs) {
return std::tie(lhs.offset_, lhs.size_) == std::tie(rhs.offset_, rhs.size_);
}
bool operator!=(const internal::string_view_metadata &lhs,
const internal::string_view_metadata &rhs) {
bool operator!=(const internal::string_view_metadata& lhs,
const internal::string_view_metadata& rhs) {
return !(lhs == rhs);
}
bool operator==(const format_part<char>::specification &lhs,
const format_part<char>::specification &rhs) {
bool operator==(const format_part<char>::specification& lhs,
const format_part<char>::specification& rhs) {
if (lhs.arg_id.which != rhs.arg_id.which) {
return false;
}
@ -79,13 +79,13 @@ bool operator==(const format_part<char>::specification &lhs,
rhs.parsed_specs.flags, rhs.parsed_specs.type);
}
bool operator!=(const format_part<char>::specification &lhs,
const format_part<char>::specification &rhs) {
bool operator!=(const format_part<char>::specification& lhs,
const format_part<char>::specification& rhs) {
return !(lhs == rhs);
}
bool operator==(const format_part<char> &lhs,
const fmt::format_part<char> &rhs) {
bool operator==(const format_part<char>& lhs,
const fmt::format_part<char>& rhs) {
typedef format_part<char>::which_value which_value;
if (lhs.which != rhs.which ||
@ -114,8 +114,8 @@ bool operator==(const format_part<char> &lhs,
return false;
}
bool operator!=(const fmt::format_part<char> &lhs,
const fmt::format_part<char> &rhs) {
bool operator!=(const fmt::format_part<char>& lhs,
const fmt::format_part<char>& rhs) {
return !(lhs == rhs);
}
FMT_END_NAMESPACE
@ -303,13 +303,15 @@ TEST(PrepareTest, FormatPreparationHandler_OnArgId_AddsPartWithPassedNamedId) {
const auto expected_third_arg_id = fmt::string_view(format.data() + 6, 3);
const auto expected_third_arg_view_metadata =
fmt::internal::string_view_metadata(6, 3);
EXPECT_CALL(parts, add(format_part(
named_argument_id(expected_first_arg_view_metadata))));
EXPECT_CALL(
parts,
add(format_part(named_argument_id(expected_first_arg_view_metadata))));
EXPECT_CALL(
parts,
add(format_part(named_argument_id(expected_second_arg_view_metadata))));
EXPECT_CALL(parts, add(format_part(
named_argument_id(expected_third_arg_view_metadata))));
EXPECT_CALL(
parts,
add(format_part(named_argument_id(expected_third_arg_view_metadata))));
handler.on_arg_id(expected_first_arg_id);
handler.on_arg_id(expected_second_arg_id);
@ -500,13 +502,13 @@ TEST(PrepareTest, UserProvidedPartsContainerUnderlyingContainer) {
}
class custom_parts_container {
public:
public:
typedef fmt::format_part<char> format_part_type;
private:
private:
typedef std::deque<format_part_type> parts;
public:
public:
void add(format_part_type part) { parts_.push_back(std::move(part)); }
void substitute_last(format_part_type part) {
@ -532,7 +534,7 @@ public:
return parts_.end();
}
private:
private:
parts parts_;
};
@ -547,10 +549,10 @@ TEST(PrepareTest, UserProvidedPartsContainer) {
}
TEST(PrepareTest, PassConstCharPointerFormat) {
const char *c_format = "test {}";
const char* c_format = "test {}";
const auto prepared = fmt::prepare<int>(c_format);
EXPECT_EQ("test 42", prepared.format(42));
const wchar_t *wc_format = L"test {}";
const wchar_t* wc_format = L"test {}";
const auto wprepared = fmt::prepare<int>(wc_format);
EXPECT_EQ(L"test 42", wprepared.format(42));
}
@ -607,10 +609,10 @@ TEST(PrepareTest, PassCompileString) {
template <typename T> struct user_allocator {
typedef T value_type;
typedef value_type *pointer;
typedef const value_type *const_pointer;
typedef value_type &reference;
typedef const value_type &const_reference;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
@ -618,7 +620,7 @@ template <typename T> struct user_allocator {
user_allocator() = default;
~user_allocator() = default;
template <typename U> user_allocator(const user_allocator<U> &) {}
template <typename U> user_allocator(const user_allocator<U>&) {}
pointer allocate(size_type cnt,
typename std::allocator<void>::const_pointer = 0) {
@ -627,12 +629,12 @@ template <typename T> struct user_allocator {
void deallocate(pointer p, size_type cnt) { delete[] p; }
void construct(pointer p, const value_type &val) { new (p) value_type(val); }
void construct(pointer p, const value_type& val) { new (p) value_type(val); }
void destroy(pointer p) { (*p).~value_type(); }
bool operator==(const user_allocator &other) const { return true; }
bool operator!=(const user_allocator &other) const { return false; }
bool operator==(const user_allocator& other) const { return true; }
bool operator!=(const user_allocator& other) const { return false; }
};
TEST(PrepareTest, PassUserTypeFormat) {

View File

@ -35,11 +35,11 @@ static std::wstring make_positional(fmt::wstring_view format) {
// A wrapper around fmt::sprintf to workaround bogus warnings about invalid
// format strings in MSVC.
template <typename... Args>
std::string test_sprintf(fmt::string_view format, const Args &... args) {
std::string test_sprintf(fmt::string_view format, const Args&... args) {
return fmt::sprintf(format, args...);
}
template <typename... Args>
std::wstring test_sprintf(fmt::wstring_view format, const Args &... args) {
std::wstring test_sprintf(fmt::wstring_view format, const Args&... args) {
return fmt::sprintf(format, args...);
}
@ -69,11 +69,10 @@ TEST(PrintfTest, Escape) {
TEST(PrintfTest, PositionalArgs) {
EXPECT_EQ("42", test_sprintf("%1$d", 42));
EXPECT_EQ("before 42", test_sprintf("before %1$d", 42));
EXPECT_EQ("42 after", test_sprintf("%1$d after",42));
EXPECT_EQ("42 after", test_sprintf("%1$d after", 42));
EXPECT_EQ("before 42 after", test_sprintf("before %1$d after", 42));
EXPECT_EQ("answer = 42", test_sprintf("%1$s = %2$d", "answer", 42));
EXPECT_EQ("42 is the answer",
test_sprintf("%2$d is the %1$s", "answer", 42));
EXPECT_EQ("42 is the answer", test_sprintf("%2$d is the %1$s", "answer", 42));
EXPECT_EQ("abracadabra", test_sprintf("%1$s%2$s%1$s", "abra", "cad"));
}
@ -82,26 +81,26 @@ TEST(PrintfTest, AutomaticArgIndexing) {
}
TEST(PrintfTest, NumberIsTooBigInArgIndex) {
EXPECT_THROW_MSG(test_sprintf(format("%{}$", BIG_NUM)),
format_error, "number is too big");
EXPECT_THROW_MSG(test_sprintf(format("%{}$d", BIG_NUM)),
format_error, "number is too big");
EXPECT_THROW_MSG(test_sprintf(format("%{}$", BIG_NUM)), format_error,
"number is too big");
EXPECT_THROW_MSG(test_sprintf(format("%{}$d", BIG_NUM)), format_error,
"number is too big");
}
TEST(PrintfTest, SwitchArgIndexing) {
EXPECT_THROW_MSG(test_sprintf("%1$d%", 1, 2),
format_error, "cannot switch from manual to automatic argument indexing");
EXPECT_THROW_MSG(test_sprintf("%1$d%", 1, 2), format_error,
"cannot switch from manual to automatic argument indexing");
EXPECT_THROW_MSG(test_sprintf(format("%1$d%{}d", BIG_NUM), 1, 2),
format_error, "number is too big");
EXPECT_THROW_MSG(test_sprintf("%1$d%d", 1, 2),
format_error, "cannot switch from manual to automatic argument indexing");
EXPECT_THROW_MSG(test_sprintf("%1$d%d", 1, 2), format_error,
"cannot switch from manual to automatic argument indexing");
EXPECT_THROW_MSG(test_sprintf("%d%1$", 1, 2),
format_error, "cannot switch from automatic to manual argument indexing");
EXPECT_THROW_MSG(test_sprintf(format("%d%{}$d", BIG_NUM), 1, 2),
format_error, "number is too big");
EXPECT_THROW_MSG(test_sprintf("%d%1$d", 1, 2),
format_error, "cannot switch from automatic to manual argument indexing");
EXPECT_THROW_MSG(test_sprintf("%d%1$", 1, 2), format_error,
"cannot switch from automatic to manual argument indexing");
EXPECT_THROW_MSG(test_sprintf(format("%d%{}$d", BIG_NUM), 1, 2), format_error,
"number is too big");
EXPECT_THROW_MSG(test_sprintf("%d%1$d", 1, 2), format_error,
"cannot switch from automatic to manual argument indexing");
// Indexing errors override width errors.
EXPECT_THROW_MSG(test_sprintf(format("%d%1${}d", BIG_NUM), 1, 2),
@ -115,13 +114,13 @@ TEST(PrintfTest, InvalidArgIndex) {
"argument index out of range");
EXPECT_THROW_MSG(test_sprintf("%2$d", 42), format_error,
"argument index out of range");
EXPECT_THROW_MSG(test_sprintf(format("%{}$d", INT_MAX), 42),
format_error, "argument index out of range");
EXPECT_THROW_MSG(test_sprintf(format("%{}$d", INT_MAX), 42), format_error,
"argument index out of range");
EXPECT_THROW_MSG(test_sprintf("%2$", 42),
format_error, "argument index out of range");
EXPECT_THROW_MSG(test_sprintf(format("%{}$d", BIG_NUM), 42),
format_error, "number is too big");
EXPECT_THROW_MSG(test_sprintf("%2$", 42), format_error,
"argument index out of range");
EXPECT_THROW_MSG(test_sprintf(format("%{}$d", BIG_NUM), 42), format_error,
"number is too big");
}
TEST(PrintfTest, DefaultAlignRight) {
@ -175,8 +174,8 @@ TEST(PrintfTest, HashFlag) {
EXPECT_PRINTF("0x42", "%#x", 0x42);
EXPECT_PRINTF("0X42", "%#X", 0x42);
EXPECT_PRINTF(
fmt::format("0x{:x}", static_cast<unsigned>(-0x42)), "%#x", -0x42);
EXPECT_PRINTF(fmt::format("0x{:x}", static_cast<unsigned>(-0x42)), "%#x",
-0x42);
EXPECT_PRINTF("0", "%#x", 0);
EXPECT_PRINTF("0x0042", "%#06x", 0x42);
@ -210,10 +209,10 @@ TEST(PrintfTest, Width) {
EXPECT_THROW_MSG(test_sprintf("%5-5d", 42), format_error,
"invalid type specifier");
EXPECT_THROW_MSG(test_sprintf(format("%{}d", BIG_NUM), 42),
format_error, "number is too big");
EXPECT_THROW_MSG(test_sprintf(format("%1${}d", BIG_NUM), 42),
format_error, "number is too big");
EXPECT_THROW_MSG(test_sprintf(format("%{}d", BIG_NUM), 42), format_error,
"number is too big");
EXPECT_THROW_MSG(test_sprintf(format("%1${}d", BIG_NUM), 42), format_error,
"number is too big");
}
TEST(PrintfTest, DynamicWidth) {
@ -279,12 +278,10 @@ TEST(PrintfTest, DynamicPrecision) {
}
}
template <typename T>
struct make_signed { typedef T type; };
template <typename T> struct make_signed { typedef T type; };
#define SPECIALIZE_MAKE_SIGNED(T, S) \
template <> \
struct make_signed<T> { typedef S type; }
template <> struct make_signed<T> { typedef S type; }
SPECIALIZE_MAKE_SIGNED(char, signed char);
SPECIALIZE_MAKE_SIGNED(unsigned char, signed char);
@ -295,7 +292,7 @@ SPECIALIZE_MAKE_SIGNED(unsigned long long, long long);
// Test length format specifier ``length_spec``.
template <typename T, typename U>
void TestLength(const char *length_spec, U value) {
void TestLength(const char* length_spec, U value) {
long long signed_value = 0;
unsigned long long unsigned_value = 0;
// Apply integer promotion to the argument.
@ -335,8 +332,7 @@ void TestLength(const char *length_spec, U value) {
EXPECT_PRINTF(os.str(), fmt::format("%{}X", length_spec), value);
}
template <typename T>
void TestLength(const char *length_spec) {
template <typename T> void TestLength(const char* length_spec) {
T min = std::numeric_limits<T>::min(), max = std::numeric_limits<T>::max();
TestLength<T>(length_spec, 42);
TestLength<T>(length_spec, -42);
@ -430,32 +426,32 @@ TEST(PrintfTest, Char) {
EXPECT_PRINTF("x", "%c", 'x');
int max = std::numeric_limits<int>::max();
EXPECT_PRINTF(fmt::format("{}", static_cast<char>(max)), "%c", max);
//EXPECT_PRINTF("x", "%lc", L'x');
// EXPECT_PRINTF("x", "%lc", L'x');
EXPECT_PRINTF(L"x", L"%c", L'x');
EXPECT_PRINTF(fmt::format(L"{}", static_cast<wchar_t>(max)), L"%c", max);
}
TEST(PrintfTest, String) {
EXPECT_PRINTF("abc", "%s", "abc");
const char *null_str = FMT_NULL;
const char* null_str = FMT_NULL;
EXPECT_PRINTF("(null)", "%s", null_str);
EXPECT_PRINTF(" (null)", "%10s", null_str);
EXPECT_PRINTF(L"abc", L"%s", L"abc");
const wchar_t *null_wstr = FMT_NULL;
const wchar_t* null_wstr = FMT_NULL;
EXPECT_PRINTF(L"(null)", L"%s", null_wstr);
EXPECT_PRINTF(L" (null)", L"%10s", null_wstr);
}
TEST(PrintfTest, Pointer) {
int n;
void *p = &n;
void* p = &n;
EXPECT_PRINTF(fmt::format("{}", p), "%p", p);
p = FMT_NULL;
EXPECT_PRINTF("(nil)", "%p", p);
EXPECT_PRINTF(" (nil)", "%10p", p);
const char *s = "test";
const char* s = "test";
EXPECT_PRINTF(fmt::format("{:p}", s), "%p", s);
const char *null_str = FMT_NULL;
const char* null_str = FMT_NULL;
EXPECT_PRINTF("(nil)", "%p", null_str);
p = &n;
@ -463,9 +459,9 @@ TEST(PrintfTest, Pointer) {
p = FMT_NULL;
EXPECT_PRINTF(L"(nil)", L"%p", p);
EXPECT_PRINTF(L" (nil)", L"%10p", p);
const wchar_t *w = L"test";
const wchar_t* w = L"test";
EXPECT_PRINTF(fmt::format(L"{:p}", w), L"%p", w);
const wchar_t *null_wstr = FMT_NULL;
const wchar_t* null_wstr = FMT_NULL;
EXPECT_PRINTF(L"(nil)", L"%p", null_wstr);
}
@ -475,14 +471,12 @@ TEST(PrintfTest, Location) {
enum E { A = 42 };
TEST(PrintfTest, Enum) {
EXPECT_PRINTF("42", "%d", A);
}
TEST(PrintfTest, Enum) { EXPECT_PRINTF("42", "%d", A); }
#if FMT_USE_FILE_DESCRIPTORS
TEST(PrintfTest, Examples) {
const char *weekday = "Thursday";
const char *month = "August";
const char* weekday = "Thursday";
const char* month = "August";
int day = 21;
EXPECT_WRITE(stdout, fmt::printf("%1$s, %3$d %2$s", weekday, month, day),
"Thursday, 21 August");
@ -496,9 +490,7 @@ TEST(PrintfTest, PrintfError) {
}
#endif
TEST(PrintfTest, WideString) {
EXPECT_EQ(L"abc", fmt::sprintf(L"%s", L"abc"));
}
TEST(PrintfTest, WideString) { EXPECT_EQ(L"abc", fmt::sprintf(L"%s", L"abc")); }
TEST(PrintfTest, PrintfCustom) {
EXPECT_EQ("abc", test_sprintf("%s", TestString("abc")));
@ -520,7 +512,7 @@ TEST(PrintfTest, VPrintf) {
EXPECT_WRITE(stdout, fmt::vfprintf(std::cout, "%d", args), "42");
}
template<typename... Args>
template <typename... Args>
void check_format_string_regression(fmt::string_view s, const Args&... args) {
fmt::sprintf(s, args...);
}
@ -530,40 +522,36 @@ TEST(PrintfTest, CheckFormatStringRegression) {
}
TEST(PrintfTest, VSPrintfMakeArgsExample) {
fmt::format_arg_store<fmt::printf_context, int, const char *> as{
42, "something"};
fmt::format_arg_store<fmt::printf_context, int, const char*> as{42,
"something"};
fmt::basic_format_args<fmt::printf_context> args(as);
EXPECT_EQ(
"[42] something happened", fmt::vsprintf("[%d] %s happened", args));
EXPECT_EQ("[42] something happened", fmt::vsprintf("[%d] %s happened", args));
auto as2 = fmt::make_printf_args(42, "something");
fmt::basic_format_args<fmt::printf_context> args2(as2);
EXPECT_EQ(
"[42] something happened", fmt::vsprintf("[%d] %s happened", args2));
//the older gcc versions can't cast the return value
EXPECT_EQ("[42] something happened",
fmt::vsprintf("[%d] %s happened", args2));
// the older gcc versions can't cast the return value
#if !defined(__GNUC__) || (__GNUC__ > 4)
EXPECT_EQ(
"[42] something happened",
fmt::vsprintf(
"[%d] %s happened", fmt::make_printf_args(42, "something")));
EXPECT_EQ("[42] something happened",
fmt::vsprintf("[%d] %s happened",
fmt::make_printf_args(42, "something")));
#endif
}
TEST(PrintfTest, VSPrintfMakeWArgsExample) {
fmt::format_arg_store<fmt::wprintf_context, int, const wchar_t *> as{
fmt::format_arg_store<fmt::wprintf_context, int, const wchar_t*> as{
42, L"something"};
fmt::basic_format_args<fmt::wprintf_context> args(as);
EXPECT_EQ(
L"[42] something happened",
EXPECT_EQ(L"[42] something happened",
fmt::vsprintf(L"[%d] %s happened", args));
auto as2 = fmt::make_wprintf_args(42, L"something");
fmt::basic_format_args<fmt::wprintf_context> args2(as2);
EXPECT_EQ(
L"[42] something happened", fmt::vsprintf(L"[%d] %s happened", args2));
EXPECT_EQ(L"[42] something happened",
fmt::vsprintf(L"[%d] %s happened", args2));
// the older gcc versions can't cast the return value
#if !defined(__GNUC__) || (__GNUC__ > 4)
EXPECT_EQ(
L"[42] something happened",
fmt::vsprintf(
L"[%d] %s happened", fmt::make_wprintf_args(42, L"something")));
EXPECT_EQ(L"[42] something happened",
fmt::vsprintf(L"[%d] %s happened",
fmt::make_wprintf_args(42, L"something")));
#endif
}

View File

@ -13,13 +13,13 @@
#if (__cplusplus > 201402L) || \
(defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910)
#include "fmt/ranges.h"
#include "gtest.h"
# include "fmt/ranges.h"
# include "gtest.h"
#include <vector>
#include <array>
#include <map>
#include <string>
# include <array>
# include <map>
# include <string>
# include <vector>
TEST(RangesTest, FormatVector) {
std::vector<int32_t> iv{1, 2, 3, 5, 7, 11};
@ -52,8 +52,7 @@ TEST(RangesTest, FormatTuple) {
struct my_struct {
int32_t i;
std::string str; // can throw
template <std::size_t N>
decltype(auto) get() const noexcept {
template <std::size_t N> decltype(auto) get() const noexcept {
if constexpr (N == 0)
return i;
else if constexpr (N == 1)
@ -61,8 +60,7 @@ struct my_struct {
}
};
template <std::size_t N>
decltype(auto) get(const my_struct& s) noexcept {
template <std::size_t N> decltype(auto) get(const my_struct& s) noexcept {
return s.get<N>();
}
@ -71,8 +69,7 @@ namespace std {
template <>
struct tuple_size<my_struct> : std::integral_constant<std::size_t, 2> {};
template <std::size_t N>
struct tuple_element<N, my_struct> {
template <std::size_t N> struct tuple_element<N, my_struct> {
using type = decltype(std::declval<my_struct>().get<N>());
};

View File

@ -13,7 +13,7 @@
class assertion_failure : public std::logic_error {
public:
explicit assertion_failure(const char *message) : std::logic_error(message) {}
explicit assertion_failure(const char* message) : std::logic_error(message) {}
};
#define FMT_ASSERT(condition, message) \

View File

@ -19,7 +19,7 @@
# define _CrtSetReportMode(a, b)
#endif
int main(int argc, char **argv) {
int main(int argc, char** argv) {
#ifdef _WIN32
// Don't display any error dialogs. This also suppresses message boxes
// on assertion failures in MinGW where _set_error_mode/CrtSetReportMode

View File

@ -6,12 +6,12 @@
// For the license information refer to format.h.
#ifdef WIN32
#define _CRT_SECURE_NO_WARNINGS
# define _CRT_SECURE_NO_WARNINGS
#endif
#include "gmock.h"
#include "fmt/locale.h"
#include "fmt/time.h"
#include "fmt/locale.h"
#include "gmock.h"
TEST(TimeTest, Format) {
std::tm tm = std::tm();
@ -24,8 +24,7 @@ TEST(TimeTest, Format) {
TEST(TimeTest, GrowBuffer) {
std::string s = "{:";
for (int i = 0; i < 30; ++i)
s += "%c";
for (int i = 0; i < 30; ++i) s += "%c";
s += "}\n";
std::time_t t = std::time(FMT_NULL);
fmt::format(s, *std::localtime(&t));
@ -39,19 +38,13 @@ TEST(TimeTest, FormatToEmptyContainer) {
EXPECT_EQ(s, "42");
}
TEST(TimeTest, EmptyResult) {
EXPECT_EQ("", fmt::format("{}", std::tm()));
}
TEST(TimeTest, EmptyResult) { EXPECT_EQ("", fmt::format("{}", std::tm())); }
static bool EqualTime(const std::tm &lhs, const std::tm &rhs) {
return lhs.tm_sec == rhs.tm_sec &&
lhs.tm_min == rhs.tm_min &&
lhs.tm_hour == rhs.tm_hour &&
lhs.tm_mday == rhs.tm_mday &&
lhs.tm_mon == rhs.tm_mon &&
lhs.tm_year == rhs.tm_year &&
lhs.tm_wday == rhs.tm_wday &&
lhs.tm_yday == rhs.tm_yday &&
static bool EqualTime(const std::tm& lhs, const std::tm& rhs) {
return lhs.tm_sec == rhs.tm_sec && lhs.tm_min == rhs.tm_min &&
lhs.tm_hour == rhs.tm_hour && lhs.tm_mday == rhs.tm_mday &&
lhs.tm_mon == rhs.tm_mon && lhs.tm_year == rhs.tm_year &&
lhs.tm_wday == rhs.tm_wday && lhs.tm_yday == rhs.tm_yday &&
lhs.tm_isdst == rhs.tm_isdst;
}

View File

@ -8,7 +8,7 @@
#include "util.h"
#include <cstring>
void increment(char *s) {
void increment(char* s) {
for (int i = static_cast<int>(std::strlen(s)) - 1; i >= 0; --i) {
if (s[i] != '9') {
++s[i];
@ -30,15 +30,14 @@ std::string get_system_error(int error_code) {
#endif
}
const char *const FILE_CONTENT = "Don't panic!";
const char* const FILE_CONTENT = "Don't panic!";
fmt::buffered_file open_buffered_file(FILE **fp) {
fmt::buffered_file open_buffered_file(FILE** fp) {
fmt::file read_end, write_end;
fmt::file::pipe(read_end, write_end);
write_end.write(FILE_CONTENT, std::strlen(FILE_CONTENT));
write_end.close();
fmt::buffered_file f = read_end.fdopen("r");
if (fp)
*fp = f.get();
if (fp) *fp = f.get();
return f;
}

View File

@ -11,7 +11,7 @@
#include "fmt/posix.h"
enum {BUFFER_SIZE = 256};
enum { BUFFER_SIZE = 256 };
#ifdef _MSC_VER
# define FMT_VSNPRINTF vsprintf_s
@ -20,7 +20,7 @@ enum {BUFFER_SIZE = 256};
#endif
template <std::size_t SIZE>
void safe_sprintf(char (&buffer)[SIZE], const char *format, ...) {
void safe_sprintf(char (&buffer)[SIZE], const char* format, ...) {
std::va_list args;
va_start(args, format);
FMT_VSNPRINTF(buffer, SIZE, format, args);
@ -28,19 +28,19 @@ void safe_sprintf(char (&buffer)[SIZE], const char *format, ...) {
}
// Increment a number in a string.
void increment(char *s);
void increment(char* s);
std::string get_system_error(int error_code);
extern const char *const FILE_CONTENT;
extern const char* const FILE_CONTENT;
// Opens a buffered file for reading.
fmt::buffered_file open_buffered_file(FILE **fp = FMT_NULL);
fmt::buffered_file open_buffered_file(FILE** fp = FMT_NULL);
inline FILE *safe_fopen(const char *filename, const char *mode) {
inline FILE* safe_fopen(const char* filename, const char* mode) {
#if defined(_WIN32) && !defined(__MINGW32__)
// Fix MSVC warning about "unsafe" fopen.
FILE *f = 0;
FILE* f = 0;
errno = fopen_s(&f, filename, mode);
return f;
#else
@ -48,34 +48,33 @@ inline FILE *safe_fopen(const char *filename, const char *mode) {
#endif
}
template <typename Char>
class BasicTestString {
template <typename Char> class BasicTestString {
private:
std::basic_string<Char> value_;
static const Char EMPTY[];
public:
explicit BasicTestString(const Char *value = EMPTY) : value_(value) {}
explicit BasicTestString(const Char* value = EMPTY) : value_(value) {}
const std::basic_string<Char> &value() const { return value_; }
const std::basic_string<Char>& value() const { return value_; }
};
template <typename Char>
const Char BasicTestString<Char>::EMPTY[] = {0};
template <typename Char> const Char BasicTestString<Char>::EMPTY[] = {0};
typedef BasicTestString<char> TestString;
typedef BasicTestString<wchar_t> TestWString;
template <typename Char>
std::basic_ostream<Char> &operator<<(
std::basic_ostream<Char> &os, const BasicTestString<Char> &s) {
std::basic_ostream<Char>& operator<<(std::basic_ostream<Char>& os,
const BasicTestString<Char>& s) {
os << s.value();
return os;
}
class Date {
int year_, month_, day_;
public:
Date(int year, int month, int day) : year_(year), month_(month), day_(day) {}