Skip to content

Commit

Permalink
make format_int constexpr (#4032)
Browse files Browse the repository at this point in the history
* make format_int constexpr

* format_int can only be constexpr in C++20

* apply clang-format

* drop constexpr for str()
  • Loading branch information
dixlorenz authored Jun 23, 2024
1 parent edde973 commit 7ae102b
Showing 1 changed file with 17 additions and 11 deletions.
28 changes: 17 additions & 11 deletions include/fmt/format.h
Original file line number Diff line number Diff line change
Expand Up @@ -3918,12 +3918,14 @@ class format_int {
mutable char buffer_[buffer_size];
char* str_;

template <typename UInt> auto format_unsigned(UInt value) -> char* {
template <typename UInt>
FMT_CONSTEXPR20 auto format_unsigned(UInt value) -> char* {
auto n = static_cast<detail::uint32_or_64_or_128_t<UInt>>(value);
return detail::format_decimal(buffer_, n, buffer_size - 1).begin;
}

template <typename Int> auto format_signed(Int value) -> char* {
template <typename Int>
FMT_CONSTEXPR20 auto format_signed(Int value) -> char* {
auto abs_value = static_cast<detail::uint32_or_64_or_128_t<Int>>(value);
bool negative = value < 0;
if (negative) abs_value = 0 - abs_value;
Expand All @@ -3933,26 +3935,30 @@ class format_int {
}

public:
explicit format_int(int value) : str_(format_signed(value)) {}
explicit format_int(long value) : str_(format_signed(value)) {}
explicit format_int(long long value) : str_(format_signed(value)) {}
explicit format_int(unsigned value) : str_(format_unsigned(value)) {}
explicit format_int(unsigned long value) : str_(format_unsigned(value)) {}
explicit format_int(unsigned long long value)
explicit FMT_CONSTEXPR20 format_int(int value) : str_(format_signed(value)) {}
explicit FMT_CONSTEXPR20 format_int(long value)
: str_(format_signed(value)) {}
explicit FMT_CONSTEXPR20 format_int(long long value)
: str_(format_signed(value)) {}
explicit FMT_CONSTEXPR20 format_int(unsigned value)
: str_(format_unsigned(value)) {}
explicit FMT_CONSTEXPR20 format_int(unsigned long value)
: str_(format_unsigned(value)) {}
explicit FMT_CONSTEXPR20 format_int(unsigned long long value)
: str_(format_unsigned(value)) {}

/// Returns the number of characters written to the output buffer.
auto size() const -> size_t {
FMT_CONSTEXPR20 auto size() const -> size_t {
return detail::to_unsigned(buffer_ - str_ + buffer_size - 1);
}

/// Returns a pointer to the output buffer content. No terminating null
/// character is appended.
auto data() const -> const char* { return str_; }
FMT_CONSTEXPR20 auto data() const -> const char* { return str_; }

/// Returns a pointer to the output buffer content with terminating null
/// character appended.
auto c_str() const -> const char* {
FMT_CONSTEXPR20 auto c_str() const -> const char* {
buffer_[buffer_size - 1] = '\0';
return str_;
}
Expand Down

0 comments on commit 7ae102b

Please sign in to comment.