added thread safety

This commit is contained in:
wind85 2017-07-03 03:56:27 +02:00
parent 589ccc1675
commit 49e6c114ef

View File

@ -12,6 +12,7 @@
#include <algorithm> // std::fill_n #include <algorithm> // std::fill_n
#include <limits> // std::numeric_limits #include <limits> // std::numeric_limits
#include <mutex>
#include "ostream.h" #include "ostream.h"
@ -48,7 +49,8 @@ class PrecisionHandler : public ArgVisitor<PrecisionHandler, int> {
template <typename T> template <typename T>
int visit_any_int(T value) { int visit_any_int(T value) {
if (!IntChecker<std::numeric_limits<T>::is_signed>::fits_in_int(value)) if (!IntChecker<std::numeric_limits<T>::is_signed>::fits_in_int(
value))
FMT_THROW(FormatError("number is too big")); FMT_THROW(FormatError("number is too big"));
return static_cast<int>(value); return static_cast<int>(value);
} }
@ -58,7 +60,9 @@ class PrecisionHandler : public ArgVisitor<PrecisionHandler, int> {
class IsZeroInt : public ArgVisitor<IsZeroInt, bool> { class IsZeroInt : public ArgVisitor<IsZeroInt, bool> {
public: public:
template <typename T> template <typename T>
bool visit_any_int(T value) { return value == 0; } bool visit_any_int(T value) {
return value == 0;
}
}; };
// returns the default type for format specific "%s" // returns the default type for format specific "%s"
@ -71,10 +75,14 @@ class DefaultType : public ArgVisitor<DefaultType, char> {
char visit_pointer(const void *) { return 'p'; } char visit_pointer(const void *) { return 'p'; }
template <typename T> template <typename T>
char visit_any_int(T) { return 'd'; } char visit_any_int(T) {
return 'd';
}
template <typename T> template <typename T>
char visit_any_double(T) { return 'g'; } char visit_any_double(T) {
return 'g';
}
char visit_unhandled_arg() { return 's'; } char visit_unhandled_arg() { return 's'; }
}; };
@ -106,13 +114,11 @@ class ArgConverter : public ArgVisitor<ArgConverter<T>, void> {
: arg_(arg), type_(type) {} : arg_(arg), type_(type) {}
void visit_bool(bool value) { void visit_bool(bool value) {
if (type_ != 's') if (type_ != 's') visit_any_int(value);
visit_any_int(value);
} }
void visit_char(char value) { void visit_char(char value) {
if (type_ != 's') if (type_ != 's') visit_any_int(value);
visit_any_int(value);
} }
template <typename U> template <typename U>
@ -123,29 +129,37 @@ class ArgConverter : public ArgVisitor<ArgConverter<T>, void> {
} }
using internal::Arg; using internal::Arg;
typedef typename internal::Conditional< typedef typename internal::Conditional<is_same<T, void>::value,
is_same<T, void>::value, U, T>::type TargetType; U, T>::type TargetType;
if (sizeof(TargetType) <= sizeof(int)) { if (sizeof(TargetType) <= sizeof(int)) {
// Extra casts are used to silence warnings. // Extra casts are used to silence warnings.
if (is_signed) { if (is_signed) {
arg_.type = Arg::INT; arg_.type = Arg::INT;
arg_.int_value = static_cast<int>(static_cast<TargetType>(value)); arg_.int_value = static_cast<int>(
static_cast<TargetType>(value));
} else { } else {
arg_.type = Arg::UINT; arg_.type = Arg::UINT;
typedef typename internal::MakeUnsigned<TargetType>::Type Unsigned; typedef typename internal::MakeUnsigned<
arg_.uint_value = static_cast<unsigned>(static_cast<Unsigned>(value)); TargetType>::Type Unsigned;
arg_.uint_value = static_cast<unsigned>(
static_cast<Unsigned>(value));
} }
} else { } else {
if (is_signed) { if (is_signed) {
arg_.type = Arg::LONG_LONG; arg_.type = Arg::LONG_LONG;
// glibc's printf doesn't sign extend arguments of smaller types: // glibc's printf doesn't sign extend arguments
// std::printf("%lld", -42); // prints "4294967254" // of smaller types:
// but we don't have to do the same because it's a UB. // std::printf("%lld", -42); // prints
arg_.long_long_value = static_cast<LongLong>(value); // "4294967254"
// but we don't have to do the same because it's
// a UB.
arg_.long_long_value =
static_cast<LongLong>(value);
} else { } else {
arg_.type = Arg::ULONG_LONG; arg_.type = Arg::ULONG_LONG;
arg_.ulong_long_value = arg_.ulong_long_value = static_cast<
static_cast<typename internal::MakeUnsigned<U>::Type>(value); typename internal::MakeUnsigned<U>::Type>(
value);
} }
} }
} }
@ -217,8 +231,8 @@ class WidthHandler : public ArgVisitor<WidthHandler, unsigned> {
\endrst \endrst
*/ */
template <typename Impl, typename Char, typename Spec> template <typename Impl, typename Char, typename Spec>
class BasicPrintfArgFormatter : class BasicPrintfArgFormatter
public internal::ArgFormatterBase<Impl, Char, Spec> { : public internal::ArgFormatterBase<Impl, Char, Spec> {
private: private:
void write_null_pointer() { void write_null_pointer() {
this->spec().type_ = 0; this->spec().type_ = 0;
@ -231,7 +245,8 @@ class BasicPrintfArgFormatter :
/** /**
\rst \rst
Constructs an argument formatter object. Constructs an argument formatter object.
*writer* is a reference to the output writer and *spec* contains format *writer* is a reference to the output writer and *spec* contains
format
specifier information for standard argument types. specifier information for standard argument types.
\endrst \endrst
*/ */
@ -241,8 +256,7 @@ class BasicPrintfArgFormatter :
/** Formats an argument of type ``bool``. */ /** Formats an argument of type ``bool``. */
void visit_bool(bool value) { void visit_bool(bool value) {
Spec &fmt_spec = this->spec(); Spec &fmt_spec = this->spec();
if (fmt_spec.type_ != 's') if (fmt_spec.type_ != 's') return this->visit_any_int(value);
return this->visit_any_int(value);
fmt_spec.type_ = 0; fmt_spec.type_ = 0;
this->write(value); this->write(value);
} }
@ -282,8 +296,7 @@ class BasicPrintfArgFormatter :
/** Formats a pointer. */ /** Formats a pointer. */
void visit_pointer(const void *value) { void visit_pointer(const void *value) {
if (value) if (value) return Base::visit_pointer(value);
return Base::visit_pointer(value);
this->spec().type_ = 0; this->spec().type_ = 0;
write_null_pointer(); write_null_pointer();
} }
@ -299,12 +312,14 @@ class BasicPrintfArgFormatter :
/** The default printf argument formatter. */ /** The default printf argument formatter. */
template <typename Char> template <typename Char>
class PrintfArgFormatter : class PrintfArgFormatter
public BasicPrintfArgFormatter<PrintfArgFormatter<Char>, Char, FormatSpec> { : public BasicPrintfArgFormatter<PrintfArgFormatter<Char>, Char,
FormatSpec> {
public: public:
/** Constructs an argument formatter object. */ /** Constructs an argument formatter object. */
PrintfArgFormatter(BasicWriter<Char> &w, FormatSpec &s) PrintfArgFormatter(BasicWriter<Char> &w, FormatSpec &s)
: BasicPrintfArgFormatter<PrintfArgFormatter<Char>, Char, FormatSpec>(w, s) {} : BasicPrintfArgFormatter<PrintfArgFormatter<Char>, Char,
FormatSpec>(w, s) {}
}; };
/** This template formats data and writes the output to a writer. */ /** This template formats data and writes the output to a writer. */
@ -321,13 +336,15 @@ class PrintfFormatter : private internal::FormatterBase {
const Char *s, const Char *s,
unsigned arg_index = (std::numeric_limits<unsigned>::max)()); unsigned arg_index = (std::numeric_limits<unsigned>::max)());
// Parses argument index, flags and width and returns the argument index. // Parses argument index, flags and width and returns the argument
// index.
unsigned parse_header(const Char *&s, FormatSpec &spec); unsigned parse_header(const Char *&s, FormatSpec &spec);
public: public:
/** /**
\rst \rst
Constructs a ``PrintfFormatter`` object. References to the arguments and Constructs a ``PrintfFormatter`` object. References to the arguments
and
the writer are stored in the formatter object so make sure they have the writer are stored in the formatter object so make sure they have
appropriate lifetimes. appropriate lifetimes.
\endrst \endrst
@ -370,30 +387,32 @@ internal::Arg PrintfFormatter<Char, AF>::get_arg(const Char *s,
unsigned arg_index) { unsigned arg_index) {
(void)s; (void)s;
const char *error = FMT_NULL; const char *error = FMT_NULL;
internal::Arg arg = arg_index == std::numeric_limits<unsigned>::max() ? internal::Arg arg = arg_index == std::numeric_limits<unsigned>::max()
next_arg(error) : FormatterBase::get_arg(arg_index - 1, error); ? next_arg(error)
: FormatterBase::get_arg(arg_index - 1, error);
if (error) if (error)
FMT_THROW(FormatError(!*s ? "invalid format string" : error)); FMT_THROW(FormatError(!*s ? "invalid format string" : error));
return arg; return arg;
} }
template <typename Char, typename AF> template <typename Char, typename AF>
unsigned PrintfFormatter<Char, AF>::parse_header( unsigned PrintfFormatter<Char, AF>::parse_header(const Char *&s,
const Char *&s, FormatSpec &spec) { FormatSpec &spec) {
unsigned arg_index = std::numeric_limits<unsigned>::max(); unsigned arg_index = std::numeric_limits<unsigned>::max();
Char c = *s; Char c = *s;
if (c >= '0' && c <= '9') { if (c >= '0' && c <= '9') {
// Parse an argument index (if followed by '$') or a width possibly // Parse an argument index (if followed by '$') or a width
// possibly
// preceded with '0' flag(s). // preceded with '0' flag(s).
unsigned value = internal::parse_nonnegative_int(s); unsigned value = internal::parse_nonnegative_int(s);
if (*s == '$') { // value is an argument index if (*s == '$') { // value is an argument index
++s; ++s;
arg_index = value; arg_index = value;
} else { } else {
if (c == '0') if (c == '0') spec.fill_ = '0';
spec.fill_ = '0';
if (value != 0) { if (value != 0) {
// Nonzero value means that we parsed width and don't need to // Nonzero value means that we parsed width and
// don't need to
// parse it or flags again, so return now. // parse it or flags again, so return now.
spec.width_ = value; spec.width_ = value;
return arg_index; return arg_index;
@ -435,10 +454,13 @@ void PrintfFormatter<Char, AF>::format(BasicCStringRef<Char> format_str) {
if (*s == '.') { if (*s == '.') {
++s; ++s;
if ('0' <= *s && *s <= '9') { if ('0' <= *s && *s <= '9') {
spec.precision_ = static_cast<int>(internal::parse_nonnegative_int(s)); spec.precision_ = static_cast<int>(
internal::parse_nonnegative_int(s));
} else if (*s == '*') { } else if (*s == '*') {
++s; ++s;
spec.precision_ = internal::PrecisionHandler().visit(get_arg(s)); spec.precision_ =
internal::PrecisionHandler().visit(
get_arg(s));
} else { } else {
spec.precision_ = 0; spec.precision_ = 0;
} }
@ -452,7 +474,8 @@ void PrintfFormatter<Char, AF>::format(BasicCStringRef<Char> format_str) {
if (arg.type <= Arg::LAST_NUMERIC_TYPE) if (arg.type <= Arg::LAST_NUMERIC_TYPE)
spec.align_ = ALIGN_NUMERIC; spec.align_ = ALIGN_NUMERIC;
else else
spec.fill_ = ' '; // Ignore '0' flag for non-numeric types. spec.fill_ = ' '; // Ignore '0' flag for
// non-numeric types.
} }
// Parse length and convert the argument to the required type. // Parse length and convert the argument to the required type.
@ -460,13 +483,15 @@ void PrintfFormatter<Char, AF>::format(BasicCStringRef<Char> format_str) {
switch (*s++) { switch (*s++) {
case 'h': case 'h':
if (*s == 'h') if (*s == 'h')
ArgConverter<signed char>(arg, *++s).visit(arg); ArgConverter<signed char>(arg, *++s)
.visit(arg);
else else
ArgConverter<short>(arg, *s).visit(arg); ArgConverter<short>(arg, *s).visit(arg);
break; break;
case 'l': case 'l':
if (*s == 'l') if (*s == 'l')
ArgConverter<fmt::LongLong>(arg, *++s).visit(arg); ArgConverter<fmt::LongLong>(arg, *++s)
.visit(arg);
else else
ArgConverter<long>(arg, *s).visit(arg); ArgConverter<long>(arg, *s).visit(arg);
break; break;
@ -477,10 +502,12 @@ void PrintfFormatter<Char, AF>::format(BasicCStringRef<Char> format_str) {
ArgConverter<std::size_t>(arg, *s).visit(arg); ArgConverter<std::size_t>(arg, *s).visit(arg);
break; break;
case 't': case 't':
ArgConverter<std::ptrdiff_t>(arg, *s).visit(arg); ArgConverter<std::ptrdiff_t>(arg, *s).visit(
arg);
break; break;
case 'L': case 'L':
// printf produces garbage when 'L' is omitted for long double, no // printf produces garbage when 'L' is omitted
// for long double, no
// need to do the same. // need to do the same.
break; break;
default: default:
@ -489,19 +516,20 @@ void PrintfFormatter<Char, AF>::format(BasicCStringRef<Char> format_str) {
} }
// Parse type. // Parse type.
if (!*s) if (!*s) FMT_THROW(FormatError("invalid format string"));
FMT_THROW(FormatError("invalid format string"));
spec.type_ = static_cast<char>(*s++); spec.type_ = static_cast<char>(*s++);
if (spec.type_ == 's') { if (spec.type_ == 's') {
// set the format type to the default if 's' is specified // set the format type to the default if 's' is
// specified
spec.type_ = internal::DefaultType().visit(arg); spec.type_ = internal::DefaultType().visit(arg);
} }
if (arg.type <= Arg::LAST_INTEGER_TYPE) { if (arg.type <= Arg::LAST_INTEGER_TYPE) {
// Normalize type. // Normalize type.
switch (spec.type_) { switch (spec.type_) {
case 'i': case 'u': case 'i':
case 'u':
spec.type_ = 'd'; spec.type_ = 'd';
break; break;
case 'c': case 'c':
@ -588,6 +616,8 @@ FMT_VARIADIC(int, printf, CStringRef)
\endrst \endrst
*/ */
inline int fprintf(std::ostream &os, CStringRef format_str, ArgList args) { inline int fprintf(std::ostream &os, CStringRef format_str, ArgList args) {
std::mutex mtx;
std::unique_lock<std::mutex> lck(mtx);
MemoryWriter w; MemoryWriter w;
printf(w, format_str, args); printf(w, format_str, args);
internal::write(os, w); internal::write(os, w);