1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-26 10:47:35 +00:00

AK: Add Formatter<FixedPoint<...>> without floating point

Rather than casting the FixedPoint to double, format the FixedPoint
directly. This avoids using floating point instruction, which in
turn enables this to be used even in the kernel.
This commit is contained in:
Tom 2021-12-27 18:23:04 -07:00 committed by Linus Groh
parent 77b3230c80
commit f021baf255
4 changed files with 124 additions and 15 deletions

View file

@ -12,6 +12,7 @@
#include <AK/AnyOf.h>
#include <AK/Array.h>
#include <AK/Error.h>
#include <AK/FixedPoint.h>
#include <AK/Forward.h>
#include <AK/Optional.h>
#include <AK/StringView.h>
@ -185,6 +186,19 @@ public:
char fill = ' ',
SignMode sign_mode = SignMode::OnlyIfNeeded);
ErrorOr<void> put_fixed_point(
i64 integer_value,
u64 fraction_value,
u64 fraction_one,
u8 base = 10,
bool upper_case = false,
bool zero_pad = false,
Align align = Align::Right,
size_t min_width = 0,
size_t precision = 6,
char fill = ' ',
SignMode sign_mode = SignMode::OnlyIfNeeded);
#ifndef KERNEL
ErrorOr<void> put_f80(
long double value,
@ -469,6 +483,41 @@ struct Formatter<long double> : StandardFormatter {
};
#endif
template<size_t precision, typename Underlying>
struct Formatter<FixedPoint<precision, Underlying>> : StandardFormatter {
Formatter() = default;
explicit Formatter(StandardFormatter formatter)
: StandardFormatter(formatter)
{
}
ErrorOr<void> format(FormatBuilder& builder, FixedPoint<precision, Underlying> value)
{
u8 base;
bool upper_case;
if (m_mode == Mode::Default || m_mode == Mode::Float) {
base = 10;
upper_case = false;
} else if (m_mode == Mode::Hexfloat) {
base = 16;
upper_case = false;
} else if (m_mode == Mode::HexfloatUppercase) {
base = 16;
upper_case = true;
} else {
VERIFY_NOT_REACHED();
}
m_width = m_width.value_or(0);
m_precision = m_precision.value_or(6);
i64 integer = value.ltrunk();
constexpr u64 one = static_cast<Underlying>(1) << precision;
u64 fraction_raw = value.raw() & (one - 1);
return builder.put_fixed_point(integer, fraction_raw, one, base, upper_case, m_zero_pad, m_align, m_width.value(), m_precision.value(), m_fill, m_sign_mode);
}
};
template<>
struct Formatter<std::nullptr_t> : Formatter<FlatPtr> {
ErrorOr<void> format(FormatBuilder& builder, std::nullptr_t)