From 5debb2aa86a4453912165a90cd08b731c3d90019 Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Fri, 29 Aug 2014 08:16:10 -0700 Subject: [PATCH] Refactor error reporting to reduce duplication. --- format.cc | 23 ++++++++++++----------- format.h | 4 ++-- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/format.cc b/format.cc index 97fe136d..9e9d504b 100644 --- a/format.cc +++ b/format.cc @@ -175,13 +175,17 @@ int parse_nonnegative_int(const Char *&s) { return value; } +inline void require_numeric_argument(const Arg &arg, char spec) { + if (arg.type > Arg::LAST_NUMERIC_TYPE) { + throw fmt::FormatError( + fmt::format("format specifier '{}' requires numeric argument", spec)); + } +} + template void check_sign(const Char *&s, const Arg &arg) { char sign = static_cast(*s); - if (arg.type > Arg::LAST_NUMERIC_TYPE) { - throw fmt::FormatError(fmt::format( - "format specifier '{}' requires numeric argument", sign)); - } + require_numeric_argument(arg, sign); if (arg.type == Arg::UINT || arg.type == Arg::ULONG_LONG) { throw fmt::FormatError(fmt::format( "format specifier '{}' requires signed argument", sign)); @@ -1059,8 +1063,8 @@ const Char *fmt::BasicFormatter::format( s += 2; spec.fill_ = c; } else ++s; - if (spec.align_ == ALIGN_NUMERIC && arg.type > Arg::LAST_NUMERIC_TYPE) - throw FormatError("format specifier '=' requires numeric argument"); + if (spec.align_ == ALIGN_NUMERIC) + require_numeric_argument(arg, '='); break; } } while (--p >= s); @@ -1083,9 +1087,7 @@ const Char *fmt::BasicFormatter::format( } if (*s == '#') { - if (arg.type > Arg::LAST_NUMERIC_TYPE) - // TODO: make FormatError accept arguments - throw FormatError("format specifier '#' requires numeric argument"); + require_numeric_argument(arg, '#'); spec.flags_ |= HASH_FLAG; ++s; } @@ -1093,8 +1095,7 @@ const Char *fmt::BasicFormatter::format( // Parse width and zero flag. if ('0' <= *s && *s <= '9') { if (*s == '0') { - if (arg.type > Arg::LAST_NUMERIC_TYPE) - throw FormatError("format specifier '0' requires numeric argument"); + require_numeric_argument(arg, '0'); spec.align_ = ALIGN_NUMERIC; spec.fill_ = '0'; } diff --git a/format.h b/format.h index 0f106973..2f816292 100644 --- a/format.h +++ b/format.h @@ -215,8 +215,8 @@ typedef BasicStringRef WStringRef; */ class FormatError : public std::runtime_error { public: - explicit FormatError(const std::string &message) - : std::runtime_error(message) {} + explicit FormatError(StringRef message) + : std::runtime_error(message.c_str()) {} }; namespace internal {