Skip to content

Truly independent web browser

LibCrypto: Remove unused BigFraction

Andreas Kling4a76af27a514
diff --git a/Libraries/LibCrypto/BigFraction/BigFraction.cpp b/Libraries/LibCrypto/BigFraction/BigFraction.cpp
deleted file mode 100644
index 85fd1c0fc28..00000000000
--- a/Libraries/LibCrypto/BigFraction/BigFraction.cpp
+++ /dev/null
@@ -1,309 +0,0 @@
-/*
- * Copyright (c) 2022, Lucas Chollet <[email protected]>
- * Copyright (c) 2025, Manuel Zahariev <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Math.h>
-#include <AK/StringBuilder.h>
-#include <AK/Utf16StringBuilder.h>
-#include <LibCrypto/BigFraction/BigFraction.h>
-#include <LibCrypto/BigInt/UnsignedBigInteger.h>
-
-namespace Crypto {
-
-BigFraction::BigFraction(SignedBigInteger numerator, UnsignedBigInteger denominator)
- : m_numerator(move(numerator))
- , m_denominator(move(denominator))
-{
- VERIFY(m_denominator != 0);
- reduce();
-}
-
-BigFraction::BigFraction(SignedBigInteger value)
- : BigFraction(move(value), 1)
-{
-}
-
-ErrorOr<BigFraction> BigFraction::from_string(StringView sv)
-{
- auto maybe_dot_index = sv.find('.');
-
- auto integer_part_view = sv.substring_view(0, maybe_dot_index.value_or(sv.length()));
- auto fraction_part_view = maybe_dot_index.has_value() ? sv.substring_view(1 + *maybe_dot_index) : "0"sv;
-
- auto integer_part = TRY(SignedBigInteger::from_base(10, integer_part_view));
- auto fractional_part = TRY(SignedBigInteger::from_base(10, fraction_part_view));
-
- if (!sv.is_empty() && sv[0] == '-')
- fractional_part.negate();
-
- return BigFraction(move(integer_part)) + BigFraction(move(fractional_part), "10"_bigint.pow(fraction_part_view.length()));
-}
-
-BigFraction BigFraction::operator+(BigFraction const& rhs) const
-{
- if (rhs.m_numerator == "0"_bigint)
- return *this;
-
- auto result = *this;
- result.m_numerator.set_to(m_numerator.multiplied_by(rhs.m_denominator).plus(rhs.m_numerator.multiplied_by(m_denominator)));
- result.m_denominator.set_to(m_denominator.multiplied_by(rhs.m_denominator));
-
- result.reduce();
-
- return result;
-}
-
-BigFraction BigFraction::operator-(BigFraction const& rhs) const
-{
- return *this + (-rhs);
-}
-
-BigFraction BigFraction::operator*(BigFraction const& rhs) const
-{
- auto result = *this;
- result.m_numerator.set_to(result.m_numerator.multiplied_by(rhs.m_numerator));
- result.m_denominator.set_to(result.m_denominator.multiplied_by(rhs.m_denominator));
-
- result.reduce();
-
- return result;
-}
-
-BigFraction BigFraction::operator-() const
-{
- return { m_numerator.negated_value(), m_denominator };
-}
-
-BigFraction BigFraction::invert() const
-{
- return BigFraction { 1 } / *this;
-}
-
-BigFraction BigFraction::operator/(BigFraction const& rhs) const
-{
- VERIFY(rhs.m_numerator != "0"_bigint);
-
- auto result = *this;
- result.m_numerator.set_to(m_numerator.multiplied_by(rhs.m_denominator));
- result.m_denominator.set_to(m_denominator.multiplied_by(rhs.m_numerator.unsigned_value()));
-
- if (rhs.m_numerator.is_negative())
- result.m_numerator.negate();
-
- result.reduce();
-
- return result;
-}
-
-bool BigFraction::operator<(BigFraction const& rhs) const
-{
- return (*this - rhs).m_numerator.is_negative();
-}
-
-bool BigFraction::operator==(BigFraction const& rhs) const
-{
- return m_numerator == rhs.m_numerator && m_denominator == rhs.m_denominator;
-}
-
-BigFraction::BigFraction(double d)
-{
- bool negative = false;
- if (d < 0) {
- negative = true;
- d = -d;
- }
- i8 current_pow = 0;
- while (AK::pow(10.0, (double)current_pow) <= d)
- current_pow += 1;
- current_pow -= 1;
- unsigned decimal_places = 0;
- while (d >= NumericLimits<double>::epsilon() || current_pow >= 0) {
- m_numerator.set_to(m_numerator.multiplied_by(SignedBigInteger { 10 }));
- i8 digit = (u64)(d * AK::pow(0.1, (double)current_pow)) % 10;
- m_numerator.set_to(m_numerator.plus(UnsignedBigInteger { digit }));
- d -= digit * AK::pow(10.0, (double)current_pow);
- if (current_pow < 0) {
- ++decimal_places;
- m_denominator.set_to("10"_bigint.pow(decimal_places));
- }
- current_pow -= 1;
- }
- m_numerator.set_to(negative ? (m_numerator.negated_value()) : m_numerator);
-}
-
-/*
- * Complexity O(N^2), where N = number of words in the larger of denominator, numerator.
- * - shifts: O(N); two copies
- * - division: O(N^2): Knuth's D algorithm (UnsignedBigInteger::divided_by)
- * - conversion to double: constant (64-bit quotient)
- */
-double BigFraction::to_double() const
-{
- bool const sign = m_numerator.is_negative();
- if (m_numerator.is_zero())
- return sign ? -0.0 : +0.0;
-
- UnsignedBigInteger numerator = m_numerator.unsigned_value(); // copy
- UnsignedBigInteger const& denominator = m_denominator;
-
- size_t top_bit_numerator = numerator.one_based_index_of_highest_set_bit();
- size_t top_bit_denominator = denominator.one_based_index_of_highest_set_bit();
- size_t shift_left_numerator = 0;
-
- // 1. Shift numerator so that its most significant bit is exaclty 64 bits left tha than that of the denominator.
- // NOTE: the precision of the result will be 63 bits (more than 53 bits necessary for the mantissa of a double).
- if (top_bit_numerator < (top_bit_denominator + 64)) {
- shift_left_numerator = top_bit_denominator + 64 - top_bit_numerator;
- numerator = MUST(numerator.shift_left(shift_left_numerator)); // copy
- }
- // NOTE: Do nothing if numerator already has more than 64 bits more than denominator.
-
- // 2. Divide [potentially shifted] numerator by the denominator.
- auto division_result = numerator.divided_by(denominator);
- if (!division_result.remainder.is_zero()) {
- division_result.quotient = MUST(division_result.quotient.shift_left(1)).plus(1); // Extend the quotient with a "fake 1".
- // NOTE: Since the quotient has at least 63 bits, this will only affect the mantissa
- // on rounding, and have the same effect on rounding as any fractional digits (from the remainder).
- shift_left_numerator++;
- }
-
- using Extractor = FloatExtractor<double>;
- Extractor double_extractor;
-
- // 3. Convert the quotient to_double using UnsignedBigInteger::to_double.
- double_extractor.d = division_result.quotient.to_double();
- double_extractor.sign = sign;
-
- // 4. Shift the result back by the same number of bits as the numerator.
- double_extractor.exponent -= shift_left_numerator;
-
- return double_extractor.d;
-}
-
-bool BigFraction::is_zero() const
-{
- return m_numerator.is_zero();
-}
-
-void BigFraction::set_to_0()
-{
- m_numerator.set_to_0();
- m_denominator.set_to(1);
-}
-
-BigFraction BigFraction::rounded(unsigned rounding_threshold) const
-{
- auto const get_last_digit = [](auto const& integer) {
- return integer.divided_by("10"_bigint).remainder;
- };
-
- auto res = m_numerator.divided_by(m_denominator);
- BigFraction result { move(res.quotient) };
-
- auto const needed_power = "10"_bigint.pow(rounding_threshold);
- // We get one more digit to do proper rounding
- auto const fractional_value = res.remainder.multiplied_by(needed_power.multiplied_by("10"_bigint)).divided_by(m_denominator).quotient;
-
- result.m_numerator.set_to(result.m_numerator.multiplied_by(needed_power));
- result.m_numerator.set_to(result.m_numerator.plus(fractional_value.divided_by("10"_bigint).quotient));
- if (get_last_digit(fractional_value) > "4"_bigint)
- result.m_numerator.set_to(result.m_numerator.plus("1"_bigint));
-
- result.m_denominator.set_to(result.m_denominator.multiplied_by(needed_power));
-
- return result;
-}
-
-void BigFraction::reduce()
-{
- auto const gcd = m_numerator.unsigned_value().gcd(m_denominator);
-
- if (gcd == 1)
- return;
-
- auto const numerator_divide = m_numerator.divided_by(gcd);
- VERIFY(numerator_divide.remainder == "0"_bigint);
- m_numerator = numerator_divide.quotient;
-
- auto const denominator_divide = m_denominator.divided_by(gcd);
- VERIFY(denominator_divide.remainder == "0"_bigint);
- m_denominator = denominator_divide.quotient;
-}
-
-Utf16String BigFraction::to_utf16_string(unsigned rounding_threshold) const
-{
- Utf16StringBuilder builder;
- if (m_numerator.is_negative() && m_numerator != "0"_bigint)
- builder.append_ascii('-');
-
- auto const number_of_digits = [](auto integer) {
- unsigned size = 1;
- UnsignedBigInteger const ten { 10 };
-
- auto division_result = integer.divided_by(ten);
-
- while (division_result.remainder.is_zero() && !division_result.quotient.is_zero()) {
- division_result = division_result.quotient.divided_by(ten);
- ++size;
- }
-
- return size;
- };
-
- auto const rounded_fraction = rounded(rounding_threshold);
-
- // We take the unsigned value as we already manage the '-'
- auto const full_value = MUST(rounded_fraction.m_numerator.unsigned_value().to_base_utf16(10));
- int split = full_value.length_in_code_units() - (number_of_digits(rounded_fraction.m_denominator) - 1);
-
- if (split < 0)
- split = 0;
-
- auto const remove_trailing_zeros = [](Utf16View value) -> Utf16View {
- auto n = value.length_in_code_units();
- VERIFY(n > 0);
- while (n > 0 && value.code_unit_at(n - 1) == '0')
- --n;
- return value.substring_view(0, n);
- };
-
- auto const raw_fractional_value = full_value.substring_view(split, full_value.length_in_code_units() - split);
-
- Utf16View integer_value = "0"sv;
- if (split != 0)
- integer_value = full_value.substring_view(0, split);
-
- Utf16View fractional_value = "0"sv;
- if (rounding_threshold != 0)
- fractional_value = remove_trailing_zeros(raw_fractional_value);
-
- builder.append(integer_value);
-
- bool const has_decimal_part = fractional_value.length_in_code_units() > 0 && fractional_value != "0"sv;
-
- if (has_decimal_part) {
- builder.append_ascii('.');
-
- auto number_pre_zeros = number_of_digits(rounded_fraction.m_denominator) - full_value.length_in_code_units() - 1;
- if (number_pre_zeros > rounding_threshold || fractional_value == "0"sv)
- number_pre_zeros = 0;
-
- builder.append_repeated_ascii('0', number_pre_zeros);
-
- if (fractional_value != "0"sv)
- builder.append(fractional_value);
- }
-
- return builder.to_string();
-}
-
-BigFraction BigFraction::sqrt() const
-{
- // FIXME: very naive implementation
- return BigFraction { AK::sqrt(to_double()) };
-}
-
-}
diff --git a/Libraries/LibCrypto/BigFraction/BigFraction.h b/Libraries/LibCrypto/BigFraction/BigFraction.h
deleted file mode 100644
index eb800c058fb..00000000000
--- a/Libraries/LibCrypto/BigFraction/BigFraction.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (c) 2022, Lucas Chollet <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Utf16String.h>
-#include <LibCrypto/BigInt/SignedBigInteger.h>
-
-namespace Crypto {
-
-class BigFraction {
- // FIXME: Make the whole API more error-friendly. This includes:
- // - Propagating errors from BigIntegers
- // - Returns errors from BigFraction(numerator, denominator);
- // - Duplicate fallible operators with a error-friendly version
-
-public:
- BigFraction() = default;
- explicit BigFraction(Crypto::SignedBigInteger);
- BigFraction(Crypto::SignedBigInteger numerator, Crypto::UnsignedBigInteger denominator);
-
- BigFraction(Crypto::BigFraction const&) = default;
- BigFraction(Crypto::BigFraction&&) = default;
- BigFraction& operator=(Crypto::BigFraction const&) = default;
- BigFraction& operator=(Crypto::BigFraction&&) = default;
-
- explicit BigFraction(double);
-
- static ErrorOr<BigFraction> from_string(StringView);
-
- BigFraction operator+(BigFraction const&) const;
- BigFraction operator-(BigFraction const&) const;
- BigFraction operator*(BigFraction const&) const;
- BigFraction operator/(BigFraction const&) const;
-
- BigFraction operator-() const;
-
- bool operator<(BigFraction const&) const;
- bool operator==(BigFraction const&) const;
-
- BigFraction invert() const;
- BigFraction sqrt() const;
-
- bool is_zero() const;
- void set_to_0();
-
- // Return a BigFraction in "scientific notation", as an example with:
- // - m_numerator = 2
- // - m_denominator = 3
- // - rounding_threshold = 4
- // The returned BigFraction will have:
- // - m_numerator = 6667
- // - m_denominator = 10000
- BigFraction rounded(unsigned rounding_threshold) const;
-
- Utf16String to_utf16_string(unsigned rounding_threshold) const;
- double to_double() const;
-
- Crypto::SignedBigInteger const& numerator() const& { return m_numerator; }
- Crypto::UnsignedBigInteger const& denominator() const& { return m_denominator; }
-
-private:
- void reduce();
-
- // This class uses a pair of integers to store a value. The purpose is to
- // support any rational number without any numerical errors.
- // For example, if we were to represent the value -123.55 in this format,
- // the values could be -12355 for and 100 for m_denominator. However, this
- // pair of value is not unique and the value will be reduced to -2471/20.
- // This way, most operations don't have to be performed on doubles, but can
- // be performed without loss of precision on this class.
- Crypto::SignedBigInteger m_numerator { 0 };
- Crypto::UnsignedBigInteger m_denominator { 1 };
-};
-
-}
diff --git a/Libraries/LibCrypto/CMakeLists.txt b/Libraries/LibCrypto/CMakeLists.txt
index 599f7902732..f011757acfb 100644
--- a/Libraries/LibCrypto/CMakeLists.txt
+++ b/Libraries/LibCrypto/CMakeLists.txt
@@ -7,7 +7,6 @@ set(SOURCES
ASN1/PEM.cpp
Authentication/HMAC.cpp
Authentication/KMAC.cpp
- BigFraction/BigFraction.cpp
BigInt/SignedBigInteger.cpp
BigInt/UnsignedBigInteger.cpp
Certificate/Certificate.cpp
diff --git a/Tests/LibCrypto/CMakeLists.txt b/Tests/LibCrypto/CMakeLists.txt
index 7e57eb858d6..d931b8c0b3b 100644
--- a/Tests/LibCrypto/CMakeLists.txt
+++ b/Tests/LibCrypto/CMakeLists.txt
@@ -4,7 +4,6 @@ set(TEST_SOURCES
TestAES.cpp
TestArgon2.cpp
TestASN1.cpp
- TestBigFraction.cpp
TestBigInteger.cpp
TestCurves.cpp
TestEd25519.cpp
diff --git a/Tests/LibCrypto/TestBigFraction.cpp b/Tests/LibCrypto/TestBigFraction.cpp
deleted file mode 100644
index a4a7601a6b7..00000000000
--- a/Tests/LibCrypto/TestBigFraction.cpp
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (c) 2024, Tim Ledbetter <[email protected]>
- * Copyright (c) 2025, Manuel Zahariev <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibCrypto/BigFraction/BigFraction.h>
-#include <LibTest/TestCase.h>
-
-static Crypto::UnsignedBigInteger bigint_fibonacci(size_t n)
-{
- Crypto::UnsignedBigInteger num1(0);
- Crypto::UnsignedBigInteger num2(1);
- for (size_t i = 0; i < n; ++i) {
- Crypto::UnsignedBigInteger t = num1.plus(num2);
- num2 = num1;
- num1 = t;
- }
- return num1;
-}
-
-TEST_CASE(roundtrip_from_string)
-{
- Array valid_number_strings {
- "0.1"sv,
- "-0.1"sv,
- "0.9"sv,
- "-0.9"sv,
- "1.2"sv,
- "-1.2"sv,
- "610888968122787804679.305596150292503043363"sv,
- "-610888968122787804679.305596150292503043363"sv
- };
-
- for (auto valid_number_string : valid_number_strings) {
- auto result = TRY_OR_FAIL(Crypto::BigFraction::from_string(valid_number_string));
- auto precision = valid_number_string.length() - valid_number_string.find('.').value();
- EXPECT_EQ(result.to_utf16_string(precision), Utf16String::from_utf8(valid_number_string));
- }
-}
-
-TEST_CASE(big_fraction_to_double)
-{
- // Golden ratio:
- // - limit (inf) ratio of two consecutive fibonacci numbers
- // - also ( 1 + sqrt( 5 ))/2
- Crypto::BigFraction phi(Crypto::SignedBigInteger { bigint_fibonacci(500) }, bigint_fibonacci(499));
- // Power 64 of golden ratio:
- // - limit ratio of two 64-separated fibonacci numbers
- // - also (23725150497407 + 10610209857723 * sqrt( 5 ))/2
- Crypto::BigFraction phi_64(Crypto::SignedBigInteger { bigint_fibonacci(564) }, bigint_fibonacci(500));
-
- EXPECT_EQ(phi.to_double(), 1.618033988749895); // 1.6180339887498948482045868343656381177203091798057628621... (https://oeis.org/A001622)
- EXPECT_EQ(phi_64.to_double(), 23725150497407); // 23725150497406.9999999999999578506361799772097881088769... (https://www.calculator.net/big-number-calculator.html)
-}
-
-TEST_CASE(big_fraction_temporal_duration_precision_support)
-{
- // https://github.com/tc39/test262/blob/main/test/built-ins/Temporal/Duration/prototype/total/precision-exact-mathematical-values-1.js
- // Express 4000h and 1ns in hours, as a double
- Crypto::BigFraction temporal_duration_precision_test = Crypto::BigFraction { Crypto::SignedBigInteger { "14400000000000001"_bigint }, "3600000000000"_bigint };
-
- EXPECT_EQ(temporal_duration_precision_test.to_double(), 4000.0000000000005);
-}