Skip to content

Truly independent web browser

AK: Use zmij instead of fmt's dragonbox for decimal forms

Timothy Flynnf9e619997813
diff --git a/AK/CMakeLists.txt b/AK/CMakeLists.txt
index 081879dc5e6..2b39acc1154 100644
--- a/AK/CMakeLists.txt
+++ b/AK/CMakeLists.txt
@@ -77,7 +77,7 @@ else()
endif()
configure_file(Backtrace.h.in Backtrace.h @ONLY)
-target_link_libraries(AK PRIVATE FastFloat::fast_float fmt::fmt simdutf::simdutf)
+target_link_libraries(AK PRIVATE FastFloat::fast_float simdutf::simdutf zmij::zmij)
set(MIMALLOC_VISIBILITY PRIVATE)
if (NOT BUILD_SHARED_LIBS)
diff --git a/AK/FFIHelpers.cpp b/AK/FFIHelpers.cpp
index 075033f304b..f26f5ac414d 100644
--- a/AK/FFIHelpers.cpp
+++ b/AK/FFIHelpers.cpp
@@ -156,6 +156,14 @@ extern "C" void ladybird_convert_to_decimal_exponential_form(double value, bool*
*exponent = form.exponent;
}
+extern "C" void ladybird_convert_to_decimal_exponential_form_with_trailing_zeroes(double value, bool* sign, u64* fraction, i32* exponent)
+{
+ auto form = AK::convert_to_decimal_exponential_form<AK::RemoveTrailingZeroes::No>(value);
+ *sign = form.sign;
+ *fraction = form.fraction;
+ *exponent = form.exponent;
+}
+
extern "C" void* ladybird_alloc(size_t size, size_t alignment)
{
// NB: mimalloc only guarantees natural alignment up to the allocation size.
diff --git a/AK/FFIHelpers.h b/AK/FFIHelpers.h
index c0a71d409f5..5320fc7271d 100644
--- a/AK/FFIHelpers.h
+++ b/AK/FFIHelpers.h
@@ -48,6 +48,7 @@ u8 ladybird_decode_base64_into(void const*, size_t, bool has_ascii_storage, bool
FlatPtr ladybird_encode_base64_to_utf16(u8 const*, size_t, bool url, bool omit_padding);
void ladybird_convert_to_decimal_exponential_form(double, bool* sign, u64* fraction, i32* exponent);
+void ladybird_convert_to_decimal_exponential_form_with_trailing_zeroes(double, bool* sign, u64* fraction, i32* exponent);
}
#ifdef USING_AK_GLOBALLY
diff --git a/AK/Rust/src/lib.rs b/AK/Rust/src/lib.rs
index a8c756a9819..122fc1a1d90 100644
--- a/AK/Rust/src/lib.rs
+++ b/AK/Rust/src/lib.rs
@@ -76,6 +76,12 @@ unsafe extern "C" {
fraction: *mut u64,
exponent: *mut i32,
);
+ fn ladybird_convert_to_decimal_exponential_form_with_trailing_zeroes(
+ value: f64,
+ sign: *mut bool,
+ fraction: *mut u64,
+ exponent: *mut i32,
+ );
}
// AK string data is immutable, and its reference count and cached metadata are atomic.
@@ -460,16 +466,30 @@ pub struct DecimalExponentialForm {
pub exponent: i32,
}
-pub fn convert_to_decimal_exponential_form(value: f64) -> DecimalExponentialForm {
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum RemoveTrailingZeroes {
+ No,
+ Yes,
+}
+
+#[inline]
+pub fn convert_to_decimal_exponential_form(
+ value: f64,
+ remove_trailing_zeroes: RemoveTrailingZeroes,
+) -> DecimalExponentialForm {
assert!(value.is_finite());
let mut form = DecimalExponentialForm {
sign: false,
fraction: 0,
exponent: 0,
};
+ let convert = match remove_trailing_zeroes {
+ RemoveTrailingZeroes::Yes => ladybird_convert_to_decimal_exponential_form,
+ RemoveTrailingZeroes::No => ladybird_convert_to_decimal_exponential_form_with_trailing_zeroes,
+ };
// SAFETY: The outputs live for the duration of the call.
unsafe {
- ladybird_convert_to_decimal_exponential_form(
+ convert(
value,
&raw mut form.sign,
&raw mut form.fraction,
diff --git a/AK/StringConversions.cpp b/AK/StringConversions.cpp
index 4a5f83fbafd..fd3305455e0 100644
--- a/AK/StringConversions.cpp
+++ b/AK/StringConversions.cpp
@@ -5,14 +5,15 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/FloatingPoint.h>
+#include <AK/Array.h>
+#include <AK/BuiltinWrappers.h>
#include <AK/StringConversions.h>
#include <AK/StringView.h>
#include <AK/Utf16View.h>
#include <math.h>
#include <fast_float/fast_float.h>
-#include <fmt/format.h>
+#include <zmij.h>
namespace AK {
@@ -154,20 +155,78 @@ ENUMERATE_INTEGRAL_TYPES
ENUMERATE_INTEGRAL_TYPES
#undef __ENUMERATE_TYPE
-template<FloatingPoint T>
+static constexpr int remove_trailing_decimal_zeroes(u64& significand)
+{
+ if (significand == 0)
+ return 0;
+
+ struct DivisionByPowerOfFive {
+ u64 inverse { 0 };
+ u64 max_quotient { 0 };
+ };
+ static constexpr auto powers_of_five = [] {
+ // zmij's significand has at most 18 digits, hence at most 17 trailing zeroes.
+ Array<DivisionByPowerOfFive, 18> powers {};
+ u64 power = 1;
+ u64 inverse = 1;
+
+ for (auto& entry : powers) {
+ entry = { inverse, NumericLimits<u64>::max() / power };
+ power *= 5;
+
+ // The multiplicative inverse of 5 modulo 2^64.
+ inverse *= 0xcccccccccccccccdULL;
+ }
+
+ return powers;
+ }();
+
+ // Every decimal zero contributes a factor of both 2 and 5. Remove the factors of 2 with a shift, then divide by
+ // 5^zeroes using its modular inverse. The product is an exact quotient iff it is at most UINT64_MAX / 5^zeroes.
+ auto zeroes = min(count_trailing_zeroes(significand), 17);
+
+ auto try_remove_zeroes = [&] {
+ auto const& divisor = powers_of_five[zeroes];
+
+ auto quotient = (significand >> zeroes) * divisor.inverse;
+ if (quotient > divisor.max_quotient)
+ return false;
+
+ significand = quotient;
+ return true;
+ };
+
+ // The number of factors of 2 often matches the number of decimal zeroes, or exceeds it by one.
+ if (try_remove_zeroes())
+ return zeroes;
+ --zeroes;
+ if (try_remove_zeroes())
+ return zeroes;
+
+ zeroes = 0;
+ while (significand % 10 == 0) {
+ significand /= 10;
+ ++zeroes;
+ }
+
+ return zeroes;
+}
+
+template<RemoveTrailingZeroes remove_trailing_zeroes, FloatingPoint T>
DecimalExponentialForm convert_to_decimal_exponential_form(T value)
{
ASSERT(!isinf(value));
ASSERT(!isnan(value));
- FloatExtractor<T> extractor;
- extractor.d = value;
-
- auto [significand, exponent] = fmt::detail::dragonbox::to_decimal(value);
- return { static_cast<bool>(extractor.sign), significand, exponent };
+ auto [significand, exponent, negative] = zmij::to_decimal(value);
+ if constexpr (remove_trailing_zeroes == RemoveTrailingZeroes::Yes)
+ exponent += remove_trailing_decimal_zeroes(significand);
+ return { negative, significand, exponent };
}
-template DecimalExponentialForm convert_to_decimal_exponential_form(float);
-template DecimalExponentialForm convert_to_decimal_exponential_form(double);
+template DecimalExponentialForm convert_to_decimal_exponential_form<RemoveTrailingZeroes::No>(float);
+template DecimalExponentialForm convert_to_decimal_exponential_form<RemoveTrailingZeroes::No>(double);
+template DecimalExponentialForm convert_to_decimal_exponential_form<RemoveTrailingZeroes::Yes>(float);
+template DecimalExponentialForm convert_to_decimal_exponential_form<RemoveTrailingZeroes::Yes>(double);
}
diff --git a/AK/StringConversions.h b/AK/StringConversions.h
index 336b3e4d29d..1e62a4a156e 100644
--- a/AK/StringConversions.h
+++ b/AK/StringConversions.h
@@ -45,7 +45,11 @@ struct DecimalExponentialForm {
i32 exponent { 0 };
};
-template<FloatingPoint T>
+enum class RemoveTrailingZeroes {
+ No,
+ Yes,
+};
+template<RemoveTrailingZeroes remove_trailing_zeroes = RemoveTrailingZeroes::Yes, FloatingPoint T>
DecimalExponentialForm convert_to_decimal_exponential_form(T value);
}
diff --git a/Libraries/LibJS/Rust/src/runtime/number_prototype_algorithms.rs b/Libraries/LibJS/Rust/src/runtime/number_prototype_algorithms.rs
index 133f18a83c7..91580b0fe91 100644
--- a/Libraries/LibJS/Rust/src/runtime/number_prototype_algorithms.rs
+++ b/Libraries/LibJS/Rust/src/runtime/number_prototype_algorithms.rs
@@ -15,18 +15,11 @@ use crate::runtime::string_conversions::{BinaryDecomposition, convert_to_decimal
const DIGITS: [u8; 36] = *b"0123456789abcdefghijklmnopqrstuvwxyz";
-const fn count_digits(mut number: u64) -> u8 {
- let mut digits = 0;
-
- loop {
- number /= 10;
- digits += 1;
- if number == 0 {
- break;
- }
+const fn count_digits(number: u64) -> u8 {
+ match number.checked_ilog10() {
+ Some(exponent) => exponent as u8 + 1,
+ None => 1,
}
-
- digits
}
/// Crypto::UnsignedBigInteger::count_digits_in_base(10).
@@ -44,7 +37,7 @@ struct SignificandAndExponent {
}
fn compute_significand_and_exponent_with_precision(number: f64, precision: i32) -> SignificandAndExponent {
- let result = convert_to_decimal_exponential_form(number);
+ let result = ak::convert_to_decimal_exponential_form(number, ak::RemoveTrailingZeroes::No);
let mut exponent = result.exponent + i32::from(count_digits(result.fraction)) - 1;
// Decompose the number into its exact binary representation. An IEEE-754 double is exactly equal to:
diff --git a/Libraries/LibJS/Rust/src/runtime/string_conversions.rs b/Libraries/LibJS/Rust/src/runtime/string_conversions.rs
index 4ce63e7b158..12f8e252869 100644
--- a/Libraries/LibJS/Rust/src/runtime/string_conversions.rs
+++ b/Libraries/LibJS/Rust/src/runtime/string_conversions.rs
@@ -128,7 +128,7 @@ pub fn decompose_double(number: f64) -> BinaryDecomposition {
pub use ak::DecimalExponentialForm;
-/// AK::convert_to_decimal_exponential_form, which runs fmt's Dragonbox: the fewest significant decimal digits that
+/// AK::convert_to_decimal_exponential_form, which runs zmij: the fewest significant decimal digits that
/// round back to the value under round-to-nearest-even, and among those the candidate closest to the value, ties
/// going to the even candidate. The fraction has no trailing zeros.
pub fn convert_to_decimal_exponential_form(value: f64) -> DecimalExponentialForm {
@@ -141,5 +141,5 @@ pub fn convert_to_decimal_exponential_form(value: f64) -> DecimalExponentialForm
exponent: 0,
};
}
- ak::convert_to_decimal_exponential_form(value)
+ ak::convert_to_decimal_exponential_form(value, ak::RemoveTrailingZeroes::Yes)
}
diff --git a/Libraries/LibJS/Rust/src/runtime/value.rs b/Libraries/LibJS/Rust/src/runtime/value.rs
index 5409d234fd4..a6a9021afd5 100644
--- a/Libraries/LibJS/Rust/src/runtime/value.rs
+++ b/Libraries/LibJS/Rust/src/runtime/value.rs
@@ -2365,7 +2365,7 @@ pub fn append_number_to_string(builder: &mut impl NumberStringBuilder, value: f6
sign: is_negative,
fraction: significand,
exponent,
- } = ak::convert_to_decimal_exponential_form(value);
+ } = ak::convert_to_decimal_exponential_form(value, ak::RemoveTrailingZeroes::Yes);
let significand_digits = DecimalDigits::new(significand);
let digits = significand_digits.as_bytes();
let k = digits.len() as i32;
diff --git a/Tests/AK/TestStringConversions.cpp b/Tests/AK/TestStringConversions.cpp
index 680c2f7259d..b85fc9c21c7 100644
--- a/Tests/AK/TestStringConversions.cpp
+++ b/Tests/AK/TestStringConversions.cpp
@@ -8,6 +8,7 @@
#include <LibTest/TestCase.h>
#include <AK/Array.h>
+#include <AK/String.h>
#include <AK/StringConversions.h>
#include <AK/Utf16View.h>
@@ -743,7 +744,86 @@ TEST_CASE(float_conversion)
DOES_CONVERT_TO(float, -11754944e-45, 1, 11754944, -45);
}
-BENCHMARK_CASE(bench_float_conversion)
+TEST_CASE(decimal_conversion_trailing_zeroes)
+{
+ // Exercise short significands across zmij's range of decimal exponents, including
+ // cases with many trailing zeroes and extra factors of two in the significand.
+ for (auto exponent : to_array({ -300, -30, -7, -1, 0, 1, 7, 30, 300 })) {
+ for (u64 fraction = 1; fraction <= 100; ++fraction) {
+ auto normalized_fraction = fraction;
+ auto normalized_exponent = exponent;
+ while (normalized_fraction % 10 == 0) {
+ normalized_fraction /= 10;
+ ++normalized_exponent;
+ }
+
+ for (bool sign : { false, true }) {
+ auto text = MUST(String::formatted("{}{}e{}", sign ? "-"sv : ""sv, fraction, exponent));
+ auto expected = AK::DecimalExponentialForm { sign, normalized_fraction, normalized_exponent };
+ EXPECT_EQ(AK::convert_to_decimal_exponential_form(parse_complete_double(text.bytes_as_string_view())), expected);
+ if (exponent >= -30 && exponent <= 30)
+ EXPECT_EQ(AK::convert_to_decimal_exponential_form(parse_complete_float(text.bytes_as_string_view())), expected);
+ }
+ }
+ }
+
+ // Powers of two can have many binary trailing zeroes without any decimal ones.
+ for (int exponent = 0; exponent <= 53; ++exponent) {
+ auto fraction = 1ULL << exponent;
+ DOES_CONVERT_TO(double, fraction, false, fraction, 0);
+ if (exponent <= 23)
+ DOES_CONVERT_TO(float, fraction, false, fraction, 0);
+ }
+
+ DOES_CONVERT_TO(double, 1e23, false, 1, 23);
+ DOES_CONVERT_TO(double, bit_cast<double>(1ULL), false, 5, -324);
+ DOES_CONVERT_TO(double, bit_cast<double>(2ULL), false, 1, -323);
+ DOES_CONVERT_TO(float, bit_cast<float>(1U), false, 1, -45);
+ DOES_CONVERT_TO(float, bit_cast<float>(2U), false, 3, -45);
+ DOES_CONVERT_TO(double, 123.456789, false, 123456789, -6);
+ DOES_CONVERT_TO(double, 0.000000123456789, false, 123456789, -15);
+ DOES_CONVERT_TO(double, 9876543210123456.0, false, 9876543210123456, 0);
+ DOES_CONVERT_TO(double, 1.23e-7, false, 123, -9);
+ DOES_CONVERT_TO(double, 58.0, false, 58, 0);
+}
+
+TEST_CASE(decimal_conversion_without_removing_trailing_zeroes)
+{
+ EXPECT_EQ(AK::convert_to_decimal_exponential_form<AK::RemoveTrailingZeroes::No>(1.0),
+ (AK::DecimalExponentialForm { false, 10'000'000'000'000'000, -16 }));
+ EXPECT_EQ(AK::convert_to_decimal_exponential_form<AK::RemoveTrailingZeroes::No>(1.0f),
+ (AK::DecimalExponentialForm { false, 100'000'000, -8 }));
+
+ auto verify = [](auto value) {
+ auto normalized = AK::convert_to_decimal_exponential_form(value);
+ auto unnormalized = AK::convert_to_decimal_exponential_form<AK::RemoveTrailingZeroes::No>(value);
+
+ auto count_digits = [](u64 fraction) {
+ int count = 0;
+ do {
+ ++count;
+ fraction /= 10;
+ } while (fraction != 0);
+ return count;
+ };
+ // Precision formatting only needs this exponent, which must not depend on normalization.
+ EXPECT_EQ(unnormalized.exponent + count_digits(unnormalized.fraction), normalized.exponent + count_digits(normalized.fraction));
+
+ while (unnormalized.fraction != 0 && unnormalized.fraction % 10 == 0) {
+ unnormalized.fraction /= 10;
+ ++unnormalized.exponent;
+ }
+ EXPECT_EQ(unnormalized, normalized);
+ };
+
+ for (auto value : to_array<double>({ 0.0, -0.0, 1.0, -1.0, 0.1, 0.3, 58.0, 1e23, 1e-300, 1e300, 0x1p-1022, bit_cast<double>(1ULL), NumericLimits<double>::max() }))
+ verify(value);
+ for (auto value : to_array<float>({ 0.0f, -0.0f, 1.0f, -1.0f, 0.1f, 0.3f, 58.0f, 1e-30f, 1e30f, 0x1p-126f, bit_cast<float>(1U), NumericLimits<float>::max() }))
+ verify(value);
+}
+
+template<AK::RemoveTrailingZeroes remove_trailing_zeroes>
+static void bench_float_conversion_impl()
{
static constexpr auto numbers = to_array<double>({
123.456789,
@@ -754,7 +834,17 @@ BENCHMARK_CASE(bench_float_conversion)
});
for (size_t i = 0; i < 100'000'000; i++) {
- auto result = AK::convert_to_decimal_exponential_form(numbers[i % numbers.size()]);
+ auto result = AK::convert_to_decimal_exponential_form<remove_trailing_zeroes>(numbers[i % numbers.size()]);
AK::taint_for_optimizer(result);
}
}
+
+BENCHMARK_CASE(bench_float_conversion)
+{
+ bench_float_conversion_impl<AK::RemoveTrailingZeroes::Yes>();
+}
+
+BENCHMARK_CASE(bench_float_conversion_without_removing_trailing_zeroes)
+{
+ bench_float_conversion_impl<AK::RemoveTrailingZeroes::No>();
+}
diff --git a/Tests/LibJS/Runtime/builtins/Number/Number.prototype.toExponential.js b/Tests/LibJS/Runtime/builtins/Number/Number.prototype.toExponential.js
index c9c67b54050..7edb9867147 100644
--- a/Tests/LibJS/Runtime/builtins/Number/Number.prototype.toExponential.js
+++ b/Tests/LibJS/Runtime/builtins/Number/Number.prototype.toExponential.js
@@ -30,6 +30,22 @@ describe("errors", () => {
});
describe("correct behavior", () => {
+ test("explicit precision is independent of trailing zeroes in the significand", () => {
+ for (const [number, expected] of [
+ [1, "1.00e+0"],
+ [0.1, "1.00e-1"],
+ [0.000001, "1.00e-6"],
+ [0.0000001, "1.00e-7"],
+ [1e23, "1.00e+23"],
+ [9.999, "1.00e+1"],
+ [Number.MIN_VALUE, "4.94e-324"],
+ [Number.MAX_VALUE, "1.80e+308"],
+ ]) {
+ expect(number.toExponential(2)).toBe(expected);
+ expect((-number).toExponential(2)).toBe("-" + expected);
+ }
+ });
+
test("special values", () => {
[
[Infinity, 6, "Infinity"],
diff --git a/Tests/LibJS/Runtime/builtins/Number/Number.prototype.toPrecision.js b/Tests/LibJS/Runtime/builtins/Number/Number.prototype.toPrecision.js
index 7bbdac5a8b6..0a82b99eb7d 100644
--- a/Tests/LibJS/Runtime/builtins/Number/Number.prototype.toPrecision.js
+++ b/Tests/LibJS/Runtime/builtins/Number/Number.prototype.toPrecision.js
@@ -27,6 +27,22 @@ describe("errors", () => {
});
describe("correct behavior", () => {
+ test("decimal exponent is independent of trailing zeroes in the significand", () => {
+ for (const [number, expected] of [
+ [1, "1.00"],
+ [0.1, "0.100"],
+ [0.000001, "0.00000100"],
+ [0.0000001, "1.00e-7"],
+ [1e23, "1.00e+23"],
+ [9.999, "10.0"],
+ [Number.MIN_VALUE, "4.94e-324"],
+ [Number.MAX_VALUE, "1.80e+308"],
+ ]) {
+ expect(number.toPrecision(3)).toBe(expected);
+ expect((-number).toPrecision(3)).toBe("-" + expected);
+ }
+ });
+
test("special values", () => {
[
[Infinity, 6, "Infinity"],