From 6c6ddf936a921360bd1e5904d850d20683277366 Mon Sep 17 00:00:00 2001 From: Riyyi Date: Fri, 5 Aug 2022 00:10:38 +0200 Subject: [PATCH] Util: Add alternative form specifier option to integral types --- src/util/format/builder.cpp | 23 ++++++++++++++++++++++- src/util/format/builder.h | 2 ++ src/util/format/formatter.h | 4 ++-- 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/src/util/format/builder.cpp b/src/util/format/builder.cpp index 10ceffc..ca09511 100644 --- a/src/util/format/builder.cpp +++ b/src/util/format/builder.cpp @@ -68,6 +68,7 @@ void Builder::putU64(size_t value, char fill, Align align, Sign sign, + bool alternativeForm, bool zeroPadding, size_t width, bool isNegative) const @@ -96,6 +97,25 @@ void Builder::putU64(size_t value, string.insert(0, signCharacter); } + // Alternative form + if (alternativeForm) { + switch (base) { + case 2: + string.insert(0, (uppercase) ? "0B" : "0b"); + break; + case 8: + break; + string.insert(0, 1, '0'); + case 10: + break; + case 16: + string.insert(0, (uppercase) ? "0X" : "0x"); + break; + default: + VERIFY_NOT_REACHED(); + } + } + // Zero padding if (zeroPadding) { fill = '0'; @@ -144,12 +164,13 @@ void Builder::putI64(int64_t value, char fill, Align align, Sign sign, + bool alternativeForm, bool zeroPadding, size_t width) const { bool isNegative = value < 0; value = isNegative ? -value : value; - putU64(static_cast(value), base, uppercase, fill, align, sign, zeroPadding, width, isNegative); + putU64(static_cast(value), base, uppercase, fill, align, sign, alternativeForm, zeroPadding, width, isNegative); } void Builder::putF64(double number, uint8_t precision) const diff --git a/src/util/format/builder.h b/src/util/format/builder.h index b52a09e..a22e2a6 100644 --- a/src/util/format/builder.h +++ b/src/util/format/builder.h @@ -42,6 +42,7 @@ public: char fill = ' ', Align align = Align::Right, Sign sign = Sign::Negative, + bool alternativeForm = false, bool zeroPadding = false, size_t width = 0, bool isNegative = false) const; @@ -52,6 +53,7 @@ public: char fill = ' ', Align align = Align::Right, Sign sign = Sign::Negative, + bool alternativeForm = false, bool zeroPadding = false, size_t width = 0) const; diff --git a/src/util/format/formatter.h b/src/util/format/formatter.h index 0bf3612..20b2e10 100644 --- a/src/util/format/formatter.h +++ b/src/util/format/formatter.h @@ -127,12 +127,12 @@ struct Formatter { if constexpr (std::is_unsigned_v) { builder.putU64( value, base, uppercase, specifier.fill, specifier.align, specifier.sign, - specifier.zeroPadding, specifier.width); + specifier.alternativeForm, specifier.zeroPadding, specifier.width); } else { builder.putI64( value, base, uppercase, specifier.fill, specifier.align, specifier.sign, - specifier.zeroPadding, specifier.width); + specifier.alternativeForm, specifier.zeroPadding, specifier.width); } } };