| 1 |
use crate::{ |
| 2 |
constants::{BYTES_TO_OVERFLOW_U64, MAX_PRECISION, MAX_STR_BUFFER_SIZE, OVERFLOW_U96, WILL_OVERFLOW_U64}, |
| 3 |
error::{tail_error, Error}, |
| 4 |
ops::array::{add_by_internal_flattened, add_one_internal, div_by_u32, is_all_zero, mul_by_u32}, |
| 5 |
Decimal, |
| 6 |
}; |
| 7 |
|
| 8 |
use arrayvec::{ArrayString, ArrayVec}; |
| 9 |
|
| 10 |
use alloc::{string::String, vec::Vec}; |
| 11 |
use core::fmt; |
| 12 |
|
| 13 |
// impl that doesn't allocate for serialization purposes. |
| 14 |
pub(crate) fn to_str_internal( |
| 15 |
value: &Decimal, |
| 16 |
append_sign: bool, |
| 17 |
precision: Option<usize>, |
| 18 |
) -> (ArrayString<MAX_STR_BUFFER_SIZE>, Option<usize>) { |
| 19 |
// Get the scale - where we need to put the decimal point |
| 20 |
let scale = value.scale() as usize; |
| 21 |
|
| 22 |
// Convert to a string and manipulate that (neg at front, inject decimal) |
| 23 |
let mut chars = ArrayVec::<_, MAX_STR_BUFFER_SIZE>::new(); |
| 24 |
let mut working = value.mantissa_array3(); |
| 25 |
while !is_all_zero(&working) { |
| 26 |
let remainder = div_by_u32(&mut working, 10u32); |
| 27 |
chars.push(char::from(b'0' + remainder as u8)); |
| 28 |
} |
| 29 |
while scale > chars.len() { |
| 30 |
chars.push('0'); |
| 31 |
} |
| 32 |
|
| 33 |
let (prec, additional) = match precision { |
| 34 |
Some(prec) => { |
| 35 |
let max: usize = MAX_PRECISION.into(); |
| 36 |
if prec > max { |
| 37 |
(max, Some(prec - max)) |
| 38 |
} else { |
| 39 |
(prec, None) |
| 40 |
} |
| 41 |
} |
| 42 |
None => (scale, None), |
| 43 |
}; |
| 44 |
|
| 45 |
let len = chars.len(); |
| 46 |
let whole_len = len - scale; |
| 47 |
let mut rep = ArrayString::new(); |
| 48 |
// Append the negative sign if necessary while also keeping track of the length of an "empty" string representation |
| 49 |
let empty_len = if append_sign && value.is_sign_negative() { |
| 50 |
rep.push('-'); |
| 51 |
1 |
| 52 |
} else { |
| 53 |
0 |
| 54 |
}; |
| 55 |
for i in 0..whole_len + prec { |
| 56 |
if i == len - scale { |
| 57 |
if i == 0 { |
| 58 |
rep.push('0'); |
| 59 |
} |
| 60 |
rep.push('.'); |
| 61 |
} |
| 62 |
|
| 63 |
if i >= len { |
| 64 |
rep.push('0'); |
| 65 |
} else { |
| 66 |
let c = chars[len - i - 1]; |
| 67 |
rep.push(c); |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
// corner case for when we truncated everything in a low fractional |
| 72 |
if rep.len() == empty_len { |
| 73 |
rep.push('0'); |
| 74 |
} |
| 75 |
|
| 76 |
(rep, additional) |
| 77 |
} |
| 78 |
|
| 79 |
pub(crate) fn fmt_scientific_notation( |
| 80 |
value: &Decimal, |
| 81 |
exponent_symbol: &str, |
| 82 |
f: &mut fmt::Formatter<'_>, |
| 83 |
) -> fmt::Result { |
| 84 |
#[cfg(not(feature = "std"))] |
| 85 |
use alloc::string::ToString; |
| 86 |
|
| 87 |
// Get the scale - this is the e value. With multiples of 10 this may get bigger. |
| 88 |
let mut exponent = -(value.scale() as isize); |
| 89 |
|
| 90 |
// Convert the integral to a string |
| 91 |
let mut chars = Vec::new(); |
| 92 |
let mut working = value.mantissa_array3(); |
| 93 |
while !is_all_zero(&working) { |
| 94 |
let remainder = div_by_u32(&mut working, 10u32); |
| 95 |
chars.push(char::from(b'0' + remainder as u8)); |
| 96 |
} |
| 97 |
|
| 98 |
// First of all, apply scientific notation rules. That is: |
| 99 |
// 1. If non-zero digit comes first, move decimal point left so that e is a positive integer |
| 100 |
// 2. If decimal point comes first, move decimal point right until after the first non-zero digit |
| 101 |
// Since decimal notation naturally lends itself this way, we just need to inject the decimal |
| 102 |
// point in the right place and adjust the exponent accordingly. |
| 103 |
|
| 104 |
let len = chars.len(); |
| 105 |
let mut rep; |
| 106 |
// We either are operating with a precision specified, or on defaults. Defaults will perform "smart" |
| 107 |
// reduction of precision. |
| 108 |
if let Some(precision) = f.precision() { |
| 109 |
if len > 1 { |
| 110 |
// If we're zero precision AND it's trailing zeros then strip them |
| 111 |
if precision == 0 && chars.iter().take(len - 1).all(|c| *c == '0') { |
| 112 |
rep = chars.iter().skip(len - 1).collect::<String>(); |
| 113 |
} else { |
| 114 |
// We may still be zero precision, however we aren't trailing zeros |
| 115 |
if precision > 0 { |
| 116 |
chars.insert(len - 1, '.'); |
| 117 |
} |
| 118 |
rep = chars |
| 119 |
.iter() |
| 120 |
.rev() |
| 121 |
// Add on extra zeros according to the precision. At least one, since we added a decimal place. |
| 122 |
.chain(core::iter::repeat(&'0')) |
| 123 |
.take(if precision == 0 { 1 } else { 2 + precision }) |
| 124 |
.collect::<String>(); |
| 125 |
} |
| 126 |
exponent += (len - 1) as isize; |
| 127 |
} else if precision > 0 { |
| 128 |
// We have precision that we want to add |
| 129 |
chars.push('.'); |
| 130 |
rep = chars |
| 131 |
.iter() |
| 132 |
.chain(core::iter::repeat(&'0')) |
| 133 |
.take(2 + precision) |
| 134 |
.collect::<String>(); |
| 135 |
} else { |
| 136 |
rep = chars.iter().collect::<String>(); |
| 137 |
} |
| 138 |
} else if len > 1 { |
| 139 |
// If the number is just trailing zeros then we treat it like 0 precision |
| 140 |
if chars.iter().take(len - 1).all(|c| *c == '0') { |
| 141 |
rep = chars.iter().skip(len - 1).collect::<String>(); |
| 142 |
} else { |
| 143 |
// Otherwise, we need to insert a decimal place and make it a scientific number |
| 144 |
chars.insert(len - 1, '.'); |
| 145 |
rep = chars.iter().rev().collect::<String>(); |
| 146 |
} |
| 147 |
exponent += (len - 1) as isize; |
| 148 |
} else { |
| 149 |
rep = chars.iter().collect::<String>(); |
| 150 |
} |
| 151 |
|
| 152 |
rep.push_str(exponent_symbol); |
| 153 |
rep.push_str(&exponent.to_string()); |
| 154 |
f.pad_integral(value.is_sign_positive(), "", &rep) |
| 155 |
} |
| 156 |
|
| 157 |
// dedicated implementation for the most common case. |
| 158 |
#[inline] |
| 159 |
pub(crate) fn parse_str_radix_10(str: &str) -> Result<Decimal, Error> { |
| 160 |
let bytes = str.as_bytes(); |
| 161 |
if bytes.len() < BYTES_TO_OVERFLOW_U64 { |
| 162 |
parse_str_radix_10_dispatch::<false, true>(bytes) |
| 163 |
} else { |
| 164 |
parse_str_radix_10_dispatch::<true, true>(bytes) |
| 165 |
} |
| 166 |
} |
| 167 |
|
| 168 |
#[inline] |
| 169 |
pub(crate) fn parse_str_radix_10_exact(str: &str) -> Result<Decimal, Error> { |
| 170 |
let bytes = str.as_bytes(); |
| 171 |
if bytes.len() < BYTES_TO_OVERFLOW_U64 { |
| 172 |
parse_str_radix_10_dispatch::<false, false>(bytes) |
| 173 |
} else { |
| 174 |
parse_str_radix_10_dispatch::<true, false>(bytes) |
| 175 |
} |
| 176 |
} |
| 177 |
|
| 178 |
#[inline] |
| 179 |
fn parse_str_radix_10_dispatch<const BIG: bool, const ROUND: bool>(bytes: &[u8]) -> Result<Decimal, Error> { |
| 180 |
match bytes { |
| 181 |
[b, rest @ ..] => byte_dispatch_u64::<false, false, false, BIG, true, ROUND>(rest, 0, 0, *b), |
| 182 |
[] => tail_error("Invalid decimal: empty"), |
| 183 |
} |
| 184 |
} |
| 185 |
|
| 186 |
#[inline] |
| 187 |
fn overflow_64(val: u64) -> bool { |
| 188 |
val >= WILL_OVERFLOW_U64 |
| 189 |
} |
| 190 |
|
| 191 |
#[inline] |
| 192 |
pub fn overflow_128(val: u128) -> bool { |
| 193 |
val >= OVERFLOW_U96 |
| 194 |
} |
| 195 |
|
| 196 |
/// Dispatch the next byte: |
| 197 |
/// |
| 198 |
/// * POINT - a decimal point has been seen |
| 199 |
/// * NEG - we've encountered a `-` and the number is negative |
| 200 |
/// * HAS - a digit has been encountered (when HAS is false it's invalid) |
| 201 |
/// * BIG - a number that uses 96 bits instead of only 64 bits |
| 202 |
/// * FIRST - true if it is the first byte in the string |
| 203 |
#[inline] |
| 204 |
fn dispatch_next<const POINT: bool, const NEG: bool, const HAS: bool, const BIG: bool, const ROUND: bool>( |
| 205 |
bytes: &[u8], |
| 206 |
data64: u64, |
| 207 |
scale: u8, |
| 208 |
) -> Result<Decimal, Error> { |
| 209 |
if let Some((next, bytes)) = bytes.split_first() { |
| 210 |
byte_dispatch_u64::<POINT, NEG, HAS, BIG, false, ROUND>(bytes, data64, scale, *next) |
| 211 |
} else { |
| 212 |
handle_data::<NEG, HAS>(data64 as u128, scale) |
| 213 |
} |
| 214 |
} |
| 215 |
|
| 216 |
#[inline(never)] |
| 217 |
fn non_digit_dispatch_u64< |
| 218 |
const POINT: bool, |
| 219 |
const NEG: bool, |
| 220 |
const HAS: bool, |
| 221 |
const BIG: bool, |
| 222 |
const FIRST: bool, |
| 223 |
const ROUND: bool, |
| 224 |
>( |
| 225 |
bytes: &[u8], |
| 226 |
data64: u64, |
| 227 |
scale: u8, |
| 228 |
b: u8, |
| 229 |
) -> Result<Decimal, Error> { |
| 230 |
match b { |
| 231 |
b'-' if FIRST && !HAS => dispatch_next::<false, true, false, BIG, ROUND>(bytes, data64, scale), |
| 232 |
b'+' if FIRST && !HAS => dispatch_next::<false, false, false, BIG, ROUND>(bytes, data64, scale), |
| 233 |
b'_' if HAS => handle_separator::<POINT, NEG, BIG, ROUND>(bytes, data64, scale), |
| 234 |
b => tail_invalid_digit(b), |
| 235 |
} |
| 236 |
} |
| 237 |
|
| 238 |
#[inline] |
| 239 |
fn byte_dispatch_u64< |
| 240 |
const POINT: bool, |
| 241 |
const NEG: bool, |
| 242 |
const HAS: bool, |
| 243 |
const BIG: bool, |
| 244 |
const FIRST: bool, |
| 245 |
const ROUND: bool, |
| 246 |
>( |
| 247 |
bytes: &[u8], |
| 248 |
data64: u64, |
| 249 |
scale: u8, |
| 250 |
b: u8, |
| 251 |
) -> Result<Decimal, Error> { |
| 252 |
match b { |
| 253 |
b'0'..=b'9' => handle_digit_64::<POINT, NEG, BIG, ROUND>(bytes, data64, scale, b - b'0'), |
| 254 |
b'.' if !POINT => handle_point::<NEG, HAS, BIG, ROUND>(bytes, data64, scale), |
| 255 |
b => non_digit_dispatch_u64::<POINT, NEG, HAS, BIG, FIRST, ROUND>(bytes, data64, scale, b), |
| 256 |
} |
| 257 |
} |
| 258 |
|
| 259 |
#[inline(never)] |
| 260 |
fn handle_digit_64<const POINT: bool, const NEG: bool, const BIG: bool, const ROUND: bool>( |
| 261 |
bytes: &[u8], |
| 262 |
data64: u64, |
| 263 |
scale: u8, |
| 264 |
digit: u8, |
| 265 |
) -> Result<Decimal, Error> { |
| 266 |
// we have already validated that we cannot overflow |
| 267 |
let data64 = data64 * 10 + digit as u64; |
| 268 |
let scale = if POINT { scale + 1 } else { 0 }; |
| 269 |
|
| 270 |
if let Some((next, bytes)) = bytes.split_first() { |
| 271 |
let next = *next; |
| 272 |
if POINT && BIG && scale >= 28 { |
| 273 |
if ROUND { |
| 274 |
maybe_round(data64 as u128, next, scale, POINT, NEG) |
| 275 |
} else { |
| 276 |
Err(Error::Underflow) |
| 277 |
} |
| 278 |
} else if BIG && overflow_64(data64) { |
| 279 |
handle_full_128::<POINT, NEG, ROUND>(data64 as u128, bytes, scale, next) |
| 280 |
} else { |
| 281 |
byte_dispatch_u64::<POINT, NEG, true, BIG, false, ROUND>(bytes, data64, scale, next) |
| 282 |
} |
| 283 |
} else { |
| 284 |
let data: u128 = data64 as u128; |
| 285 |
|
| 286 |
handle_data::<NEG, true>(data, scale) |
| 287 |
} |
| 288 |
} |
| 289 |
|
| 290 |
#[inline(never)] |
| 291 |
fn handle_point<const NEG: bool, const HAS: bool, const BIG: bool, const ROUND: bool>( |
| 292 |
bytes: &[u8], |
| 293 |
data64: u64, |
| 294 |
scale: u8, |
| 295 |
) -> Result<Decimal, Error> { |
| 296 |
dispatch_next::<true, NEG, HAS, BIG, ROUND>(bytes, data64, scale) |
| 297 |
} |
| 298 |
|
| 299 |
#[inline(never)] |
| 300 |
fn handle_separator<const POINT: bool, const NEG: bool, const BIG: bool, const ROUND: bool>( |
| 301 |
bytes: &[u8], |
| 302 |
data64: u64, |
| 303 |
scale: u8, |
| 304 |
) -> Result<Decimal, Error> { |
| 305 |
dispatch_next::<POINT, NEG, true, BIG, ROUND>(bytes, data64, scale) |
| 306 |
} |
| 307 |
|
| 308 |
#[inline(never)] |
| 309 |
#[cold] |
| 310 |
fn tail_invalid_digit(digit: u8) -> Result<Decimal, Error> { |
| 311 |
match digit { |
| 312 |
b'.' => tail_error("Invalid decimal: two decimal points"), |
| 313 |
b'_' => tail_error("Invalid decimal: must start lead with a number"), |
| 314 |
_ => tail_error("Invalid decimal: unknown character"), |
| 315 |
} |
| 316 |
} |
| 317 |
|
| 318 |
#[inline(never)] |
| 319 |
#[cold] |
| 320 |
fn handle_full_128<const POINT: bool, const NEG: bool, const ROUND: bool>( |
| 321 |
mut data: u128, |
| 322 |
bytes: &[u8], |
| 323 |
scale: u8, |
| 324 |
next_byte: u8, |
| 325 |
) -> Result<Decimal, Error> { |
| 326 |
let b = next_byte; |
| 327 |
match b { |
| 328 |
b'0'..=b'9' => { |
| 329 |
let digit = u32::from(b - b'0'); |
| 330 |
|
| 331 |
// If the data is going to overflow then we should go into recovery mode |
| 332 |
let next = (data * 10) + digit as u128; |
| 333 |
if overflow_128(next) { |
| 334 |
if !POINT { |
| 335 |
return tail_error("Invalid decimal: overflow from too many digits"); |
| 336 |
} |
| 337 |
|
| 338 |
if ROUND { |
| 339 |
maybe_round(data, next_byte, scale, POINT, NEG) |
| 340 |
} else { |
| 341 |
Err(Error::Underflow) |
| 342 |
} |
| 343 |
} else { |
| 344 |
data = next; |
| 345 |
let scale = scale + POINT as u8; |
| 346 |
if let Some((next, bytes)) = bytes.split_first() { |
| 347 |
let next = *next; |
| 348 |
if POINT && scale >= 28 { |
| 349 |
if ROUND { |
| 350 |
maybe_round(data, next, scale, POINT, NEG) |
| 351 |
} else { |
| 352 |
Err(Error::Underflow) |
| 353 |
} |
| 354 |
} else { |
| 355 |
handle_full_128::<POINT, NEG, ROUND>(data, bytes, scale, next) |
| 356 |
} |
| 357 |
} else { |
| 358 |
handle_data::<NEG, true>(data, scale) |
| 359 |
} |
| 360 |
} |
| 361 |
} |
| 362 |
b'.' if !POINT => { |
| 363 |
// This call won't tail? |
| 364 |
if let Some((next, bytes)) = bytes.split_first() { |
| 365 |
handle_full_128::<true, NEG, ROUND>(data, bytes, scale, *next) |
| 366 |
} else { |
| 367 |
handle_data::<NEG, true>(data, scale) |
| 368 |
} |
| 369 |
} |
| 370 |
b'_' => { |
| 371 |
if let Some((next, bytes)) = bytes.split_first() { |
| 372 |
handle_full_128::<POINT, NEG, ROUND>(data, bytes, scale, *next) |
| 373 |
} else { |
| 374 |
handle_data::<NEG, true>(data, scale) |
| 375 |
} |
| 376 |
} |
| 377 |
b => tail_invalid_digit(b), |
| 378 |
} |
| 379 |
} |
| 380 |
|
| 381 |
#[inline(never)] |
| 382 |
#[cold] |
| 383 |
fn maybe_round( |
| 384 |
mut data: u128, |
| 385 |
next_byte: u8, |
| 386 |
mut scale: u8, |
| 387 |
point: bool, |
| 388 |
negative: bool, |
| 389 |
) -> Result<Decimal, crate::Error> { |
| 390 |
let digit = match next_byte { |
| 391 |
b'0'..=b'9' => u32::from(next_byte - b'0'), |
| 392 |
b'_' => 0, // this should be an invalid string? |
| 393 |
b'.' if point => 0, |
| 394 |
b => return tail_invalid_digit(b), |
| 395 |
}; |
| 396 |
|
| 397 |
// Round at midpoint |
| 398 |
if digit >= 5 { |
| 399 |
data += 1; |
| 400 |
|
| 401 |
// If the mantissa is now overflowing, round to the next |
| 402 |
// next least significant digit and discard precision |
| 403 |
if overflow_128(data) { |
| 404 |
if scale == 0 { |
| 405 |
return tail_error("Invalid decimal: overflow from mantissa after rounding"); |
| 406 |
} |
| 407 |
data += 4; |
| 408 |
data /= 10; |
| 409 |
scale -= 1; |
| 410 |
} |
| 411 |
} |
| 412 |
|
| 413 |
if negative { |
| 414 |
handle_data::<true, true>(data, scale) |
| 415 |
} else { |
| 416 |
handle_data::<false, true>(data, scale) |
| 417 |
} |
| 418 |
} |
| 419 |
|
| 420 |
#[inline(never)] |
| 421 |
fn tail_no_has() -> Result<Decimal, Error> { |
| 422 |
tail_error("Invalid decimal: no digits found") |
| 423 |
} |
| 424 |
|
| 425 |
#[inline] |
| 426 |
fn handle_data<const NEG: bool, const HAS: bool>(data: u128, scale: u8) -> Result<Decimal, Error> { |
| 427 |
debug_assert_eq!(data >> 96, 0); |
| 428 |
if !HAS { |
| 429 |
tail_no_has() |
| 430 |
} else { |
| 431 |
Ok(Decimal::from_parts( |
| 432 |
data as u32, |
| 433 |
(data >> 32) as u32, |
| 434 |
(data >> 64) as u32, |
| 435 |
NEG, |
| 436 |
scale as u32, |
| 437 |
)) |
| 438 |
} |
| 439 |
} |
| 440 |
|
| 441 |
pub(crate) fn parse_str_radix_n(str: &str, radix: u32) -> Result<Decimal, Error> { |
| 442 |
if str.is_empty() { |
| 443 |
return Err(Error::from("Invalid decimal: empty")); |
| 444 |
} |
| 445 |
if radix < 2 { |
| 446 |
return Err(Error::from("Unsupported radix < 2")); |
| 447 |
} |
| 448 |
if radix > 36 { |
| 449 |
// As per trait documentation |
| 450 |
return Err(Error::from("Unsupported radix > 36")); |
| 451 |
} |
| 452 |
|
| 453 |
let mut offset = 0; |
| 454 |
let mut len = str.len(); |
| 455 |
let bytes = str.as_bytes(); |
| 456 |
let mut negative = false; // assume positive |
| 457 |
|
| 458 |
// handle the sign |
| 459 |
if bytes[offset] == b'-' { |
| 460 |
negative = true; // leading minus means negative |
| 461 |
offset += 1; |
| 462 |
len -= 1; |
| 463 |
} else if bytes[offset] == b'+' { |
| 464 |
// leading + allowed |
| 465 |
offset += 1; |
| 466 |
len -= 1; |
| 467 |
} |
| 468 |
|
| 469 |
// should now be at numeric part of the significand |
| 470 |
let mut digits_before_dot: i32 = -1; // digits before '.', -1 if no '.' |
| 471 |
let mut coeff = ArrayVec::<_, 96>::new(); // integer significand array |
| 472 |
|
| 473 |
// Supporting different radix |
| 474 |
let (max_n, max_alpha_lower, max_alpha_upper) = if radix <= 10 { |
| 475 |
(b'0' + (radix - 1) as u8, 0, 0) |
| 476 |
} else { |
| 477 |
let adj = (radix - 11) as u8; |
| 478 |
(b'9', adj + b'a', adj + b'A') |
| 479 |
}; |
| 480 |
|
| 481 |
// Estimate the max precision. All in all, it needs to fit into 96 bits. |
| 482 |
// Rather than try to estimate, I've included the constants directly in here. We could, |
| 483 |
// perhaps, replace this with a formula if it's faster - though it does appear to be log2. |
| 484 |
let estimated_max_precision = match radix { |
| 485 |
2 => 96, |
| 486 |
3 => 61, |
| 487 |
4 => 48, |
| 488 |
5 => 42, |
| 489 |
6 => 38, |
| 490 |
7 => 35, |
| 491 |
8 => 32, |
| 492 |
9 => 31, |
| 493 |
10 => 28, |
| 494 |
11 => 28, |
| 495 |
12 => 27, |
| 496 |
13 => 26, |
| 497 |
14 => 26, |
| 498 |
15 => 25, |
| 499 |
16 => 24, |
| 500 |
17 => 24, |
| 501 |
18 => 24, |
| 502 |
19 => 23, |
| 503 |
20 => 23, |
| 504 |
21 => 22, |
| 505 |
22 => 22, |
| 506 |
23 => 22, |
| 507 |
24 => 21, |
| 508 |
25 => 21, |
| 509 |
26 => 21, |
| 510 |
27 => 21, |
| 511 |
28 => 20, |
| 512 |
29 => 20, |
| 513 |
30 => 20, |
| 514 |
31 => 20, |
| 515 |
32 => 20, |
| 516 |
33 => 20, |
| 517 |
34 => 19, |
| 518 |
35 => 19, |
| 519 |
36 => 19, |
| 520 |
_ => return Err(Error::from("Unsupported radix")), |
| 521 |
}; |
| 522 |
|
| 523 |
let mut maybe_round = false; |
| 524 |
while len > 0 { |
| 525 |
let b = bytes[offset]; |
| 526 |
match b { |
| 527 |
b'0'..=b'9' => { |
| 528 |
if b > max_n { |
| 529 |
return Err(Error::from("Invalid decimal: invalid character")); |
| 530 |
} |
| 531 |
coeff.push(u32::from(b - b'0')); |
| 532 |
offset += 1; |
| 533 |
len -= 1; |
| 534 |
|
| 535 |
// If the coefficient is longer than the max, exit early |
| 536 |
if coeff.len() as u32 > estimated_max_precision { |
| 537 |
maybe_round = true; |
| 538 |
break; |
| 539 |
} |
| 540 |
} |
| 541 |
b'a'..=b'z' => { |
| 542 |
if b > max_alpha_lower { |
| 543 |
return Err(Error::from("Invalid decimal: invalid character")); |
| 544 |
} |
| 545 |
coeff.push(u32::from(b - b'a') + 10); |
| 546 |
offset += 1; |
| 547 |
len -= 1; |
| 548 |
|
| 549 |
if coeff.len() as u32 > estimated_max_precision { |
| 550 |
maybe_round = true; |
| 551 |
break; |
| 552 |
} |
| 553 |
} |
| 554 |
b'A'..=b'Z' => { |
| 555 |
if b > max_alpha_upper { |
| 556 |
return Err(Error::from("Invalid decimal: invalid character")); |
| 557 |
} |
| 558 |
coeff.push(u32::from(b - b'A') + 10); |
| 559 |
offset += 1; |
| 560 |
len -= 1; |
| 561 |
|
| 562 |
if coeff.len() as u32 > estimated_max_precision { |
| 563 |
maybe_round = true; |
| 564 |
break; |
| 565 |
} |
| 566 |
} |
| 567 |
b'.' => { |
| 568 |
if digits_before_dot >= 0 { |
| 569 |
return Err(Error::from("Invalid decimal: two decimal points")); |
| 570 |
} |
| 571 |
digits_before_dot = coeff.len() as i32; |
| 572 |
offset += 1; |
| 573 |
len -= 1; |
| 574 |
} |
| 575 |
b'_' => { |
| 576 |
// Must start with a number... |
| 577 |
if coeff.is_empty() { |
| 578 |
return Err(Error::from("Invalid decimal: must start lead with a number")); |
| 579 |
} |
| 580 |
offset += 1; |
| 581 |
len -= 1; |
| 582 |
} |
| 583 |
_ => return Err(Error::from("Invalid decimal: unknown character")), |
| 584 |
} |
| 585 |
} |
| 586 |
|
| 587 |
// If we exited before the end of the string then do some rounding if necessary |
| 588 |
if maybe_round && offset < bytes.len() { |
| 589 |
let next_byte = bytes[offset]; |
| 590 |
let digit = match next_byte { |
| 591 |
b'0'..=b'9' => { |
| 592 |
if next_byte > max_n { |
| 593 |
return Err(Error::from("Invalid decimal: invalid character")); |
| 594 |
} |
| 595 |
u32::from(next_byte - b'0') |
| 596 |
} |
| 597 |
b'a'..=b'z' => { |
| 598 |
if next_byte > max_alpha_lower { |
| 599 |
return Err(Error::from("Invalid decimal: invalid character")); |
| 600 |
} |
| 601 |
u32::from(next_byte - b'a') + 10 |
| 602 |
} |
| 603 |
b'A'..=b'Z' => { |
| 604 |
if next_byte > max_alpha_upper { |
| 605 |
return Err(Error::from("Invalid decimal: invalid character")); |
| 606 |
} |
| 607 |
u32::from(next_byte - b'A') + 10 |
| 608 |
} |
| 609 |
b'_' => 0, |
| 610 |
b'.' => { |
| 611 |
// Still an error if we have a second dp |
| 612 |
if digits_before_dot >= 0 { |
| 613 |
return Err(Error::from("Invalid decimal: two decimal points")); |
| 614 |
} |
| 615 |
0 |
| 616 |
} |
| 617 |
_ => return Err(Error::from("Invalid decimal: unknown character")), |
| 618 |
}; |
| 619 |
|
| 620 |
// Round at midpoint |
| 621 |
let midpoint = if radix & 0x1 == 1 { radix / 2 } else { (radix + 1) / 2 }; |
| 622 |
if digit >= midpoint { |
| 623 |
let mut index = coeff.len() - 1; |
| 624 |
loop { |
| 625 |
let new_digit = coeff[index] + 1; |
| 626 |
if new_digit <= 9 { |
| 627 |
coeff[index] = new_digit; |
| 628 |
break; |
| 629 |
} else { |
| 630 |
coeff[index] = 0; |
| 631 |
if index == 0 { |
| 632 |
coeff.insert(0, 1u32); |
| 633 |
digits_before_dot += 1; |
| 634 |
coeff.pop(); |
| 635 |
break; |
| 636 |
} |
| 637 |
} |
| 638 |
index -= 1; |
| 639 |
} |
| 640 |
} |
| 641 |
} |
| 642 |
|
| 643 |
// here when no characters left |
| 644 |
if coeff.is_empty() { |
| 645 |
return Err(Error::from("Invalid decimal: no digits found")); |
| 646 |
} |
| 647 |
|
| 648 |
let mut scale = if digits_before_dot >= 0 { |
| 649 |
// we had a decimal place so set the scale |
| 650 |
(coeff.len() as u32) - (digits_before_dot as u32) |
| 651 |
} else { |
| 652 |
0 |
| 653 |
}; |
| 654 |
|
| 655 |
// Parse this using specified radix |
| 656 |
let mut data = [0u32, 0u32, 0u32]; |
| 657 |
let mut tmp = [0u32, 0u32, 0u32]; |
| 658 |
let len = coeff.len(); |
| 659 |
for (i, digit) in coeff.iter().enumerate() { |
| 660 |
// If the data is going to overflow then we should go into recovery mode |
| 661 |
tmp[0] = data[0]; |
| 662 |
tmp[1] = data[1]; |
| 663 |
tmp[2] = data[2]; |
| 664 |
let overflow = mul_by_u32(&mut tmp, radix); |
| 665 |
if overflow > 0 { |
| 666 |
// This means that we have more data to process, that we're not sure what to do with. |
| 667 |
// This may or may not be an issue - depending on whether we're past a decimal point |
| 668 |
// or not. |
| 669 |
if (i as i32) < digits_before_dot && i + 1 < len { |
| 670 |
return Err(Error::from("Invalid decimal: overflow from too many digits")); |
| 671 |
} |
| 672 |
|
| 673 |
if *digit >= 5 { |
| 674 |
let carry = add_one_internal(&mut data); |
| 675 |
if carry > 0 { |
| 676 |
// Highly unlikely scenario which is more indicative of a bug |
| 677 |
return Err(Error::from("Invalid decimal: overflow when rounding")); |
| 678 |
} |
| 679 |
} |
| 680 |
// We're also one less digit so reduce the scale |
| 681 |
let diff = (len - i) as u32; |
| 682 |
if diff > scale { |
| 683 |
return Err(Error::from("Invalid decimal: overflow from scale mismatch")); |
| 684 |
} |
| 685 |
scale -= diff; |
| 686 |
break; |
| 687 |
} else { |
| 688 |
data[0] = tmp[0]; |
| 689 |
data[1] = tmp[1]; |
| 690 |
data[2] = tmp[2]; |
| 691 |
let carry = add_by_internal_flattened(&mut data, *digit); |
| 692 |
if carry > 0 { |
| 693 |
// Highly unlikely scenario which is more indicative of a bug |
| 694 |
return Err(Error::from("Invalid decimal: overflow from carry")); |
| 695 |
} |
| 696 |
} |
| 697 |
} |
| 698 |
|
| 699 |
Ok(Decimal::from_parts(data[0], data[1], data[2], negative, scale)) |
| 700 |
} |
| 701 |
|
| 702 |
#[cfg(test)] |
| 703 |
mod test { |
| 704 |
use super::*; |
| 705 |
use crate::Decimal; |
| 706 |
use arrayvec::ArrayString; |
| 707 |
use core::{fmt::Write, str::FromStr}; |
| 708 |
|
| 709 |
#[test] |
| 710 |
fn display_does_not_overflow_max_capacity() { |
| 711 |
let num = Decimal::from_str("1.2").unwrap(); |
| 712 |
let mut buffer = ArrayString::<64>::new(); |
| 713 |
let _ = buffer.write_fmt(format_args!("{:.31}", num)).unwrap(); |
| 714 |
assert_eq!("1.2000000000000000000000000000000", buffer.as_str()); |
| 715 |
} |
| 716 |
|
| 717 |
#[test] |
| 718 |
fn from_str_rounding_0() { |
| 719 |
assert_eq!( |
| 720 |
parse_str_radix_10("1.234").unwrap().unpack(), |
| 721 |
Decimal::new(1234, 3).unpack() |
| 722 |
); |
| 723 |
} |
| 724 |
|
| 725 |
#[test] |
| 726 |
fn from_str_rounding_1() { |
| 727 |
assert_eq!( |
| 728 |
parse_str_radix_10("11111_11111_11111.11111_11111_11111") |
| 729 |
.unwrap() |
| 730 |
.unpack(), |
| 731 |
Decimal::from_i128_with_scale(11_111_111_111_111_111_111_111_111_111, 14).unpack() |
| 732 |
); |
| 733 |
} |
| 734 |
|
| 735 |
#[test] |
| 736 |
fn from_str_rounding_2() { |
| 737 |
assert_eq!( |
| 738 |
parse_str_radix_10("11111_11111_11111.11111_11111_11115") |
| 739 |
.unwrap() |
| 740 |
.unpack(), |
| 741 |
Decimal::from_i128_with_scale(11_111_111_111_111_111_111_111_111_112, 14).unpack() |
| 742 |
); |
| 743 |
} |
| 744 |
|
| 745 |
#[test] |
| 746 |
fn from_str_rounding_3() { |
| 747 |
assert_eq!( |
| 748 |
parse_str_radix_10("11111_11111_11111.11111_11111_11195") |
| 749 |
.unwrap() |
| 750 |
.unpack(), |
| 751 |
Decimal::from_i128_with_scale(1_111_111_111_111_111_111_111_111_1120, 14).unpack() // was Decimal::from_i128_with_scale(1_111_111_111_111_111_111_111_111_112, 13) |
| 752 |
); |
| 753 |
} |
| 754 |
|
| 755 |
#[test] |
| 756 |
fn from_str_rounding_4() { |
| 757 |
assert_eq!( |
| 758 |
parse_str_radix_10("99999_99999_99999.99999_99999_99995") |
| 759 |
.unwrap() |
| 760 |
.unpack(), |
| 761 |
Decimal::from_i128_with_scale(10_000_000_000_000_000_000_000_000_000, 13).unpack() // was Decimal::from_i128_with_scale(1_000_000_000_000_000_000_000_000_000, 12) |
| 762 |
); |
| 763 |
} |
| 764 |
|
| 765 |
#[test] |
| 766 |
fn from_str_no_rounding_0() { |
| 767 |
assert_eq!( |
| 768 |
parse_str_radix_10_exact("1.234").unwrap().unpack(), |
| 769 |
Decimal::new(1234, 3).unpack() |
| 770 |
); |
| 771 |
} |
| 772 |
|
| 773 |
#[test] |
| 774 |
fn from_str_no_rounding_1() { |
| 775 |
assert_eq!( |
| 776 |
parse_str_radix_10_exact("11111_11111_11111.11111_11111_11111"), |
| 777 |
Err(Error::Underflow) |
| 778 |
); |
| 779 |
} |
| 780 |
|
| 781 |
#[test] |
| 782 |
fn from_str_no_rounding_2() { |
| 783 |
assert_eq!( |
| 784 |
parse_str_radix_10_exact("11111_11111_11111.11111_11111_11115"), |
| 785 |
Err(Error::Underflow) |
| 786 |
); |
| 787 |
} |
| 788 |
|
| 789 |
#[test] |
| 790 |
fn from_str_no_rounding_3() { |
| 791 |
assert_eq!( |
| 792 |
parse_str_radix_10_exact("11111_11111_11111.11111_11111_11195"), |
| 793 |
Err(Error::Underflow) |
| 794 |
); |
| 795 |
} |
| 796 |
|
| 797 |
#[test] |
| 798 |
fn from_str_no_rounding_4() { |
| 799 |
assert_eq!( |
| 800 |
parse_str_radix_10_exact("99999_99999_99999.99999_99999_99995"), |
| 801 |
Err(Error::Underflow) |
| 802 |
); |
| 803 |
} |
| 804 |
|
| 805 |
#[test] |
| 806 |
fn from_str_many_pointless_chars() { |
| 807 |
assert_eq!( |
| 808 |
parse_str_radix_10("00________________________________________________________________001.1") |
| 809 |
.unwrap() |
| 810 |
.unpack(), |
| 811 |
Decimal::from_i128_with_scale(11, 1).unpack() |
| 812 |
); |
| 813 |
} |
| 814 |
|
| 815 |
#[test] |
| 816 |
fn from_str_leading_0s_1() { |
| 817 |
assert_eq!( |
| 818 |
parse_str_radix_10("00001.1").unwrap().unpack(), |
| 819 |
Decimal::from_i128_with_scale(11, 1).unpack() |
| 820 |
); |
| 821 |
} |
| 822 |
|
| 823 |
#[test] |
| 824 |
fn from_str_leading_0s_2() { |
| 825 |
assert_eq!( |
| 826 |
parse_str_radix_10("00000_00000_00000_00000_00001.00001") |
| 827 |
.unwrap() |
| 828 |
.unpack(), |
| 829 |
Decimal::from_i128_with_scale(100001, 5).unpack() |
| 830 |
); |
| 831 |
} |
| 832 |
|
| 833 |
#[test] |
| 834 |
fn from_str_leading_0s_3() { |
| 835 |
assert_eq!( |
| 836 |
parse_str_radix_10("0.00000_00000_00000_00000_00000_00100") |
| 837 |
.unwrap() |
| 838 |
.unpack(), |
| 839 |
Decimal::from_i128_with_scale(1, 28).unpack() |
| 840 |
); |
| 841 |
} |
| 842 |
|
| 843 |
#[test] |
| 844 |
fn from_str_trailing_0s_1() { |
| 845 |
assert_eq!( |
| 846 |
parse_str_radix_10("0.00001_00000_00000").unwrap().unpack(), |
| 847 |
Decimal::from_i128_with_scale(10_000_000_000, 15).unpack() |
| 848 |
); |
| 849 |
} |
| 850 |
|
| 851 |
#[test] |
| 852 |
fn from_str_trailing_0s_2() { |
| 853 |
assert_eq!( |
| 854 |
parse_str_radix_10("0.00001_00000_00000_00000_00000_00000") |
| 855 |
.unwrap() |
| 856 |
.unpack(), |
| 857 |
Decimal::from_i128_with_scale(100_000_000_000_000_000_000_000, 28).unpack() |
| 858 |
); |
| 859 |
} |
| 860 |
|
| 861 |
#[test] |
| 862 |
fn from_str_overflow_1() { |
| 863 |
assert_eq!( |
| 864 |
parse_str_radix_10("99999_99999_99999_99999_99999_99999.99999"), |
| 865 |
// The original implementation returned |
| 866 |
// Ok(10000_00000_00000_00000_00000_0000) |
| 867 |
// Which is a bug! |
| 868 |
Err(Error::from("Invalid decimal: overflow from too many digits")) |
| 869 |
); |
| 870 |
} |
| 871 |
|
| 872 |
#[test] |
| 873 |
fn from_str_overflow_2() { |
| 874 |
assert!( |
| 875 |
parse_str_radix_10("99999_99999_99999_99999_99999_11111.11111").is_err(), |
| 876 |
// The original implementation is 'overflow from scale mismatch' |
| 877 |
// but we got rid of that now |
| 878 |
); |
| 879 |
} |
| 880 |
|
| 881 |
#[test] |
| 882 |
fn from_str_overflow_3() { |
| 883 |
assert!( |
| 884 |
parse_str_radix_10("99999_99999_99999_99999_99999_99994").is_err() // We could not get into 'overflow when rounding' or 'overflow from carry' |
| 885 |
// in the original implementation because the rounding logic before prevented it |
| 886 |
); |
| 887 |
} |
| 888 |
|
| 889 |
#[test] |
| 890 |
fn from_str_overflow_4() { |
| 891 |
assert_eq!( |
| 892 |
// This does not overflow, moving the decimal point 1 more step would result in |
| 893 |
// 'overflow from too many digits' |
| 894 |
parse_str_radix_10("99999_99999_99999_99999_99999_999.99") |
| 895 |
.unwrap() |
| 896 |
.unpack(), |
| 897 |
Decimal::from_i128_with_scale(10_000_000_000_000_000_000_000_000_000, 0).unpack() |
| 898 |
); |
| 899 |
} |
| 900 |
|
| 901 |
#[test] |
| 902 |
fn from_str_mantissa_overflow_1() { |
| 903 |
// reminder: |
| 904 |
assert_eq!(OVERFLOW_U96, 79_228_162_514_264_337_593_543_950_336); |
| 905 |
assert_eq!( |
| 906 |
parse_str_radix_10("79_228_162_514_264_337_593_543_950_33.56") |
| 907 |
.unwrap() |
| 908 |
.unpack(), |
| 909 |
Decimal::from_i128_with_scale(79_228_162_514_264_337_593_543_950_34, 0).unpack() |
| 910 |
); |
| 911 |
// This is a mantissa of OVERFLOW_U96 - 1 just before reaching the last digit. |
| 912 |
// Previously, this would return Err("overflow from mantissa after rounding") |
| 913 |
// instead of successfully rounding. |
| 914 |
} |
| 915 |
|
| 916 |
#[test] |
| 917 |
fn from_str_mantissa_overflow_2() { |
| 918 |
assert_eq!( |
| 919 |
parse_str_radix_10("79_228_162_514_264_337_593_543_950_335.6"), |
| 920 |
Err(Error::from("Invalid decimal: overflow from mantissa after rounding")) |
| 921 |
); |
| 922 |
// this case wants to round to 79_228_162_514_264_337_593_543_950_340. |
| 923 |
// (79_228_162_514_264_337_593_543_950_336 is OVERFLOW_U96 and too large |
| 924 |
// to fit in 96 bits) which is also too large for the mantissa so fails. |
| 925 |
} |
| 926 |
|
| 927 |
#[test] |
| 928 |
fn from_str_mantissa_overflow_3() { |
| 929 |
// this hits the other avoidable overflow case in maybe_round |
| 930 |
assert_eq!( |
| 931 |
parse_str_radix_10("7.92281625142643375935439503356").unwrap().unpack(), |
| 932 |
Decimal::from_i128_with_scale(79_228_162_514_264_337_593_543_950_34, 27).unpack() |
| 933 |
); |
| 934 |
} |
| 935 |
|
| 936 |
#[ignore] |
| 937 |
#[test] |
| 938 |
fn from_str_mantissa_overflow_4() { |
| 939 |
// Same test as above, however with underscores. This causes issues. |
| 940 |
assert_eq!( |
| 941 |
parse_str_radix_10("7.9_228_162_514_264_337_593_543_950_335_6") |
| 942 |
.unwrap() |
| 943 |
.unpack(), |
| 944 |
Decimal::from_i128_with_scale(79_228_162_514_264_337_593_543_950_34, 27).unpack() |
| 945 |
); |
| 946 |
} |
| 947 |
|
| 948 |
#[test] |
| 949 |
fn from_str_edge_cases_1() { |
| 950 |
assert_eq!(parse_str_radix_10(""), Err(Error::from("Invalid decimal: empty"))); |
| 951 |
} |
| 952 |
|
| 953 |
#[test] |
| 954 |
fn from_str_edge_cases_2() { |
| 955 |
assert_eq!( |
| 956 |
parse_str_radix_10("0.1."), |
| 957 |
Err(Error::from("Invalid decimal: two decimal points")) |
| 958 |
); |
| 959 |
} |
| 960 |
|
| 961 |
#[test] |
| 962 |
fn from_str_edge_cases_3() { |
| 963 |
assert_eq!( |
| 964 |
parse_str_radix_10("_"), |
| 965 |
Err(Error::from("Invalid decimal: must start lead with a number")) |
| 966 |
); |
| 967 |
} |
| 968 |
|
| 969 |
#[test] |
| 970 |
fn from_str_edge_cases_4() { |
| 971 |
assert_eq!( |
| 972 |
parse_str_radix_10("1?2"), |
| 973 |
Err(Error::from("Invalid decimal: unknown character")) |
| 974 |
); |
| 975 |
} |
| 976 |
|
| 977 |
#[test] |
| 978 |
fn from_str_edge_cases_5() { |
| 979 |
assert_eq!( |
| 980 |
parse_str_radix_10("."), |
| 981 |
Err(Error::from("Invalid decimal: no digits found")) |
| 982 |
); |
| 983 |
} |
| 984 |
|
| 985 |
#[test] |
| 986 |
fn from_str_edge_cases_6() { |
| 987 |
// Decimal::MAX + 0.99999 |
| 988 |
assert_eq!( |
| 989 |
parse_str_radix_10("79_228_162_514_264_337_593_543_950_335.99999"), |
| 990 |
Err(Error::from("Invalid decimal: overflow from mantissa after rounding")) |
| 991 |
); |
| 992 |
} |
| 993 |
} |