#![doc(hidden)]
use core::cmp;
#[cfg(not(feature = "compact"))]
use lexical_parse_integer::algorithm;
use lexical_util::digit::char_to_valid_digit_const;
#[cfg(feature = "radix")]
use lexical_util::digit::digit_to_char_const;
use lexical_util::format::NumberFormat;
use lexical_util::iterator::{AsBytes, DigitsIter, Iter};
use lexical_util::num::{AsPrimitive, Integer};
#[cfg(feature = "radix")]
use crate::bigint::Bigfloat;
use crate::bigint::{Bigint, Limb};
use crate::float::{extended_to_float, ExtendedFloat80, RawFloat};
use crate::limits::{u32_power_limit, u64_power_limit};
use crate::number::Number;
use crate::shared;
#[must_use]
#[allow(clippy::unwrap_used)] pub fn slow_radix<F: RawFloat, const FORMAT: u128>(
num: Number,
fp: ExtendedFloat80,
) -> ExtendedFloat80 {
debug_assert!(fp.mant & (1 << 63) != 0, "number must be normalized");
let format = NumberFormat::<{ FORMAT }> {};
let sci_exp = scientific_exponent::<FORMAT>(&num);
#[cfg(feature = "radix")]
{
if let Some(max_digits) = F::max_digits(format.radix()) {
digit_comp::<F, FORMAT>(num, fp, sci_exp, max_digits)
} else {
byte_comp::<F, FORMAT>(num, fp, sci_exp)
}
}
#[cfg(not(feature = "radix"))]
{
let max_digits = F::max_digits(format.radix()).unwrap();
digit_comp::<F, FORMAT>(num, fp, sci_exp, max_digits)
}
}
#[must_use]
#[inline(always)]
#[allow(clippy::cast_possible_wrap)] pub fn digit_comp<F: RawFloat, const FORMAT: u128>(
num: Number,
fp: ExtendedFloat80,
sci_exp: i32,
max_digits: usize,
) -> ExtendedFloat80 {
let (bigmant, digits) = parse_mantissa::<FORMAT>(num, max_digits);
let exponent = sci_exp + 1 - digits as i32;
if exponent >= 0 {
positive_digit_comp::<F, FORMAT>(bigmant, exponent)
} else {
negative_digit_comp::<F, FORMAT>(bigmant, fp, exponent)
}
}
#[must_use]
#[inline(always)]
#[allow(clippy::unwrap_used)] #[allow(clippy::cast_possible_wrap)] #[allow(clippy::missing_inline_in_public_items)] pub fn positive_digit_comp<F: RawFloat, const FORMAT: u128>(
mut bigmant: Bigint,
exponent: i32,
) -> ExtendedFloat80 {
let format = NumberFormat::<{ FORMAT }> {};
bigmant.pow(format.radix(), exponent as u32).unwrap();
let (mant, is_truncated) = bigmant.hi64();
let exp = bigmant.bit_length() as i32 - 64 + F::EXPONENT_BIAS;
let mut fp = ExtendedFloat80 {
mant,
exp,
};
shared::round::<F, _>(&mut fp, |f, s| {
shared::round_nearest_tie_even(f, s, |is_odd, is_halfway, is_above| {
is_above || (is_halfway && is_truncated) || (is_odd && is_halfway)
});
});
fp
}
#[must_use]
#[inline(always)]
#[allow(clippy::match_bool)] #[allow(clippy::unwrap_used)] #[allow(clippy::comparison_chain)] #[allow(clippy::missing_inline_in_public_items)] pub fn negative_digit_comp<F: RawFloat, const FORMAT: u128>(
bigmant: Bigint,
mut fp: ExtendedFloat80,
exponent: i32,
) -> ExtendedFloat80 {
debug_assert!(fp.mant & (1 << 63) != 0, "the significant digits must be normalized");
let format = NumberFormat::<FORMAT> {};
let radix = format.radix();
let mut real_digits = bigmant;
let real_exp = exponent;
debug_assert!(real_exp < 0, "algorithm only works with negative numbers");
let mut b = fp;
shared::round::<F, _>(&mut b, shared::round_down);
let b = extended_to_float::<F>(b);
let theor = bh(b);
let mut theor_digits = Bigint::from_u64(theor.mant);
let theor_exp = theor.exp;
let (binary_exp, halfradix_exp, radix_exp) = match radix.is_even() {
true => (theor_exp - real_exp, -real_exp, 0),
false => (theor_exp, 0, -real_exp),
};
if halfradix_exp != 0 {
theor_digits.pow(radix / 2, halfradix_exp as u32).unwrap();
}
if radix_exp != 0 {
theor_digits.pow(radix, radix_exp as u32).unwrap();
}
if binary_exp > 0 {
theor_digits.pow(2, binary_exp as u32).unwrap();
} else if binary_exp < 0 {
real_digits.pow(2, (-binary_exp) as u32).unwrap();
}
let ord = real_digits.data.cmp(&theor_digits.data);
shared::round::<F, _>(&mut fp, |f, s| {
shared::round_nearest_tie_even(f, s, |is_odd, _, _| {
match ord {
cmp::Ordering::Greater => true,
cmp::Ordering::Less => false,
cmp::Ordering::Equal if is_odd => true,
cmp::Ordering::Equal => false,
}
});
});
fp
}
#[cfg(not(feature = "compact"))]
macro_rules! try_parse_8digits {
(
$format:ident,
$iter:ident,
$value:ident,
$count:ident,
$counter:ident,
$step:ident,
$max_digits:ident
) => {{
let format = NumberFormat::<$format> {};
let radix = format.radix() as Limb;
if can_try_parse_multidigit!($iter, radix) {
debug_assert!(radix < 16);
let radix8 = format.radix8() as Limb;
while $step - $counter >= 8 && $max_digits - $count >= 8 {
if let Some(v) = algorithm::try_parse_8digits::<Limb, _, FORMAT>(&mut $iter) {
$value = $value.wrapping_mul(radix8).wrapping_add(v);
$counter += 8;
$count += 8;
} else {
break;
}
}
}
}};
}
macro_rules! add_digit {
($c:ident, $radix:ident, $value:ident, $counter:ident, $count:ident) => {{
let digit = char_to_valid_digit_const($c, $radix);
$value *= $radix as Limb;
$value += digit as Limb;
$counter += 1;
$count += 1;
}};
}
macro_rules! add_temporary {
(@mul $result:ident, $power:expr, $value:expr) => {
$result.data.mul_small($power).unwrap();
$result.data.add_small($value).unwrap();
};
(@end $format:ident, $result:ident, $counter:ident, $value:ident) => {
if $counter != 0 {
let small_power = f64::int_pow_fast_path($counter, $format.radix());
add_temporary!(@mul $result, small_power as Limb, $value);
}
};
(@max $format:ident, $result:ident, $counter:ident, $value:ident, $max:ident) => {
add_temporary!(@mul $result, $max, $value);
$counter = 0;
$value = 0;
};
}
macro_rules! round_up_truncated {
($format:ident, $result:ident, $count:ident) => {{
add_temporary!(@mul $result, $format.radix() as Limb, 1);
$count += 1;
}};
}
macro_rules! round_up_nonzero {
($format:ident, $iter:expr, $result:ident, $count:ident) => {{
let mut iter = $iter;
if iter.is_contiguous() {
while let Some(value) = iter.peek_u64() {
unsafe { iter.step_by_unchecked(8) };
if value != 0x3030_3030_3030_3030 {
round_up_truncated!($format, $result, $count);
return ($result, $count);
}
}
}
for &digit in iter {
if digit != b'0' {
round_up_truncated!($format, $result, $count);
return ($result, $count);
}
}
}};
}
#[must_use]
#[allow(clippy::cognitive_complexity)] #[allow(clippy::missing_inline_in_public_items)] pub fn parse_mantissa<const FORMAT: u128>(num: Number, max_digits: usize) -> (Bigint, usize) {
let format = NumberFormat::<FORMAT> {};
let radix = format.radix();
let mut counter: usize = 0;
let mut count: usize = 0;
let mut value: Limb = 0;
let mut result = Bigint::new();
let step = if Limb::BITS == 32 {
u32_power_limit(format.radix())
} else {
u64_power_limit(format.radix())
} as usize;
let max_native = (format.radix() as Limb).pow(step as u32);
let mut integer = num.integer.bytes::<FORMAT>();
let mut integer_iter = integer.integer_iter();
integer_iter.skip_zeros();
'integer: loop {
#[cfg(not(feature = "compact"))]
try_parse_8digits!(FORMAT, integer_iter, value, count, counter, step, max_digits);
while counter < step && count < max_digits {
if let Some(&c) = integer_iter.next() {
add_digit!(c, radix, value, counter, count);
} else {
break 'integer;
}
}
if count == max_digits {
add_temporary!(@end format, result, counter, value);
round_up_nonzero!(format, integer_iter, result, count);
if let Some(fraction) = num.fraction {
let mut fraction = fraction.bytes::<FORMAT>();
round_up_nonzero!(format, fraction.fraction_iter(), result, count);
}
return (result, count);
} else {
add_temporary!(@max format, result, counter, value, max_native);
}
}
if let Some(fraction) = num.fraction {
let mut fraction = fraction.bytes::<FORMAT>();
let mut fraction_iter = fraction.integer_iter();
if count == 0 {
fraction_iter.skip_zeros();
}
'fraction: loop {
#[cfg(not(feature = "compact"))]
try_parse_8digits!(FORMAT, fraction_iter, value, count, counter, step, max_digits);
while counter < step && count < max_digits {
if let Some(&c) = fraction_iter.next() {
add_digit!(c, radix, value, counter, count);
} else {
break 'fraction;
}
}
if count == max_digits {
add_temporary!(@end format, result, counter, value);
round_up_nonzero!(format, fraction_iter, result, count);
return (result, count);
} else {
add_temporary!(@max format, result, counter, value, max_native);
}
}
}
add_temporary!(@end format, result, counter, value);
(result, count)
}
#[cfg(feature = "radix")]
macro_rules! integer_compare {
($iter:ident, $num:ident, $den:ident, $radix:ident) => {{
while !$num.data.is_empty() {
let actual = match $iter.next() {
Some(&v) => v,
_ => break,
};
let rem = $num.data.quorem(&$den.data) as u32;
let expected = digit_to_char_const(rem, $radix);
$num.data.mul_small($radix as Limb).unwrap();
if actual < expected {
return cmp::Ordering::Less;
} else if actual > expected {
return cmp::Ordering::Greater;
}
}
if $num.data.is_empty() {
for &digit in $iter {
if digit != b'0' {
return cmp::Ordering::Greater;
}
}
}
}};
}
#[cfg(feature = "radix")]
macro_rules! fraction_compare {
($iter:ident, $num:ident, $den:ident, $radix:ident) => {{
while !$num.data.is_empty() {
let actual = match $iter.next() {
Some(&v) => v,
_ => return cmp::Ordering::Less,
};
let rem = $num.data.quorem(&$den.data) as u32;
let expected = digit_to_char_const(rem, $radix);
$num.data.mul_small($radix as Limb).unwrap();
if actual < expected {
return cmp::Ordering::Less;
} else if actual > expected {
return cmp::Ordering::Greater;
}
}
for &digit in $iter {
if digit != b'0' {
return cmp::Ordering::Greater;
}
}
}};
}
#[cfg(feature = "radix")]
#[allow(clippy::unwrap_used)] #[allow(clippy::comparison_chain)] pub fn byte_comp<F: RawFloat, const FORMAT: u128>(
number: Number,
mut fp: ExtendedFloat80,
sci_exp: i32,
) -> ExtendedFloat80 {
debug_assert!(fp.mant & (1 << 63) != 0);
let format = NumberFormat::<FORMAT> {};
let mut b = fp;
shared::round::<F, _>(&mut b, shared::round_down);
let b = extended_to_float::<F>(b);
let theor = Bigfloat::from_float(bh::<F>(b));
let mut factor = Bigfloat::from_u32(1);
factor.pow(format.radix(), sci_exp.unsigned_abs()).unwrap();
let mut num: Bigfloat;
let mut den: Bigfloat;
if sci_exp < 0 {
num = factor;
num.data *= &theor.data;
den = Bigfloat::from_u32(1);
den.exp = -theor.exp;
} else {
num = theor;
den = factor;
}
let wlz = integral_binary_factor(format.radix());
let nlz = den.leading_zeros().wrapping_sub(wlz) & (32 - 1);
if nlz != 0 {
den.shl_bits(nlz as usize).unwrap();
den.exp -= nlz as i32;
}
let diff = den.exp - num.exp;
let shift = diff.unsigned_abs() as usize;
if diff < 0 {
num.shl(shift).unwrap();
num.exp -= shift as i32;
} else if diff > 0 {
let (q, r) = shift.ceil_divmod(Limb::BITS as usize);
let r = -r;
if r != 0 {
num.shl_bits(r as usize).unwrap();
num.exp -= r;
}
if q != 0 {
den.shl_limbs(q).unwrap();
den.exp -= Limb::BITS as i32 * q as i32;
}
}
let ord = compare_bytes::<FORMAT>(number, num, den);
shared::round::<F, _>(&mut fp, |f, s| {
shared::round_nearest_tie_even(f, s, |is_odd, _, _| {
match ord {
cmp::Ordering::Greater => true,
cmp::Ordering::Less => false,
cmp::Ordering::Equal if is_odd => true,
cmp::Ordering::Equal => false,
}
});
});
fp
}
#[cfg(feature = "radix")]
#[allow(clippy::unwrap_used)] pub fn compare_bytes<const FORMAT: u128>(
number: Number,
mut num: Bigfloat,
den: Bigfloat,
) -> cmp::Ordering {
let format = NumberFormat::<FORMAT> {};
let radix = format.radix();
let mut integer = number.integer.bytes::<{ FORMAT }>();
let mut integer_iter = integer.integer_iter();
integer_iter.skip_zeros();
if integer_iter.is_buffer_empty() {
let mut fraction = number.fraction.unwrap().bytes::<{ FORMAT }>();
let mut fraction_iter = fraction.fraction_iter();
fraction_iter.skip_zeros();
fraction_compare!(fraction_iter, num, den, radix);
} else {
integer_compare!(integer_iter, num, den, radix);
if let Some(fraction) = number.fraction {
let mut fraction = fraction.bytes::<{ FORMAT }>();
let mut fraction_iter = fraction.fraction_iter();
fraction_compare!(fraction_iter, num, den, radix);
} else if !num.data.is_empty() {
return cmp::Ordering::Less;
}
}
cmp::Ordering::Equal
}
#[must_use]
#[inline(always)]
pub fn scientific_exponent<const FORMAT: u128>(num: &Number) -> i32 {
let format = NumberFormat::<FORMAT> {};
let radix = format.radix() as u64;
let radix2 = radix * radix;
let radix4 = radix2 * radix2;
let mut mantissa = num.mantissa;
let mut exponent = num.exponent;
while mantissa >= radix4 {
mantissa /= radix4;
exponent += 4;
}
while mantissa >= radix2 {
mantissa /= radix2;
exponent += 2;
}
while mantissa >= radix {
mantissa /= radix;
exponent += 1;
}
exponent as i32
}
#[must_use]
#[inline(always)]
pub fn b<F: RawFloat>(float: F) -> ExtendedFloat80 {
ExtendedFloat80 {
mant: float.mantissa().as_u64(),
exp: float.exponent(),
}
}
#[must_use]
#[inline(always)]
pub fn bh<F: RawFloat>(float: F) -> ExtendedFloat80 {
let fp = b(float);
ExtendedFloat80 {
mant: (fp.mant << 1) + 1,
exp: fp.exp - 1,
}
}
#[must_use]
#[inline(always)]
#[cfg(feature = "radix")]
pub const fn integral_binary_factor(radix: u32) -> u32 {
match radix {
3 => 2,
5 => 3,
6 => 3,
7 => 3,
9 => 4,
10 => 4,
11 => 4,
12 => 4,
13 => 4,
14 => 4,
15 => 4,
17 => 5,
18 => 5,
19 => 5,
20 => 5,
21 => 5,
22 => 5,
23 => 5,
24 => 5,
25 => 5,
26 => 5,
27 => 5,
28 => 5,
29 => 5,
30 => 5,
31 => 5,
33 => 6,
34 => 6,
35 => 6,
36 => 6,
_ => 0,
}
}
#[must_use]
#[inline(always)]
#[cfg(not(feature = "radix"))]
pub const fn integral_binary_factor(radix: u32) -> u32 {
match radix {
10 => 4,
_ => 0,
}
}