| 1 |
//! [BSON Decimal128](https://github.com/mongodb/specifications/blob/master/source/bson-decimal128/decimal128.rst) data type representation |
| 2 |
|
| 3 |
use std::{convert::TryInto, fmt}; |
| 4 |
|
| 5 |
use bitvec::prelude::*; |
| 6 |
|
| 7 |
/// Struct representing a BSON Decimal128 type. |
| 8 |
/// |
| 9 |
/// This type supports conversion to and from human-readable strings via the [std::fmt::Display] and |
| 10 |
/// [std::str::FromStr] traits: |
| 11 |
/// |
| 12 |
/// ```rust |
| 13 |
/// # use std::str::FromStr; |
| 14 |
/// # use bson::Decimal128; |
| 15 |
/// # fn example() -> std::result::Result<(), Box<dyn std::error::Error>> { |
| 16 |
/// let value: Decimal128 = "3.14159".parse()?; |
| 17 |
/// assert_eq!("3.14159", format!("{}", value)); |
| 18 |
/// let scientific = Decimal128::from_str("1.05E+3")?; |
| 19 |
/// assert_eq!("1.05E+3", scientific.to_string()); |
| 20 |
/// # Ok(()) |
| 21 |
/// # } |
| 22 |
/// # example().unwrap() |
| 23 |
/// ``` |
| 24 |
#[derive(Copy, Clone, PartialEq)] |
| 25 |
pub struct Decimal128 { |
| 26 |
/// BSON bytes containing the decimal128. Stored for round tripping. |
| 27 |
pub(crate) bytes: [u8; 16], |
| 28 |
} |
| 29 |
|
| 30 |
impl Decimal128 { |
| 31 |
/// Constructs a new `Decimal128` from the provided raw byte representation. |
| 32 |
pub fn from_bytes(bytes: [u8; 128 / 8]) -> Self { |
| 33 |
Self { bytes } |
| 34 |
} |
| 35 |
|
| 36 |
/// Returns the raw byte representation of this `Decimal128`. |
| 37 |
pub fn bytes(&self) -> [u8; 128 / 8] { |
| 38 |
self.bytes |
| 39 |
} |
| 40 |
|
| 41 |
pub(crate) fn deserialize_from_slice<E: serde::de::Error>( |
| 42 |
bytes: &[u8], |
| 43 |
) -> std::result::Result<Self, E> { |
| 44 |
let arr: [u8; 128 / 8] = bytes.try_into().map_err(E::custom)?; |
| 45 |
Ok(Decimal128 { bytes: arr }) |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
impl fmt::Debug for Decimal128 { |
| 50 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 51 |
write!(f, "Decimal128(...)") |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
impl fmt::Display for Decimal128 { |
| 56 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 57 |
write!(f, "{}", ParsedDecimal128::new(self)) |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
impl std::str::FromStr for Decimal128 { |
| 62 |
type Err = ParseError; |
| 63 |
|
| 64 |
fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 65 |
Ok(s.parse::<ParsedDecimal128>()?.pack()) |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
#[derive(Debug, Clone, PartialEq)] |
| 70 |
struct ParsedDecimal128 { |
| 71 |
sign: bool, |
| 72 |
kind: Decimal128Kind, |
| 73 |
} |
| 74 |
|
| 75 |
#[derive(Debug, Clone, PartialEq)] |
| 76 |
enum Decimal128Kind { |
| 77 |
NaN { |
| 78 |
signalling: bool, |
| 79 |
}, |
| 80 |
Infinity, |
| 81 |
Finite { |
| 82 |
exponent: Exponent, |
| 83 |
coefficient: Coefficient, |
| 84 |
}, |
| 85 |
} |
| 86 |
|
| 87 |
#[derive(Debug, Clone, PartialEq)] |
| 88 |
struct Exponent([u8; 2]); |
| 89 |
|
| 90 |
impl Exponent { |
| 91 |
/// The exponent is stored as an unsigned value; `BIAS` is subtracted to get the actual value. |
| 92 |
const BIAS: i16 = 6176; |
| 93 |
/// The minimum representable exponent. This is distinct from the specifications "min" value, |
| 94 |
/// which marks the point at which exponents are considered subnormal. |
| 95 |
const TINY: i16 = -6176; |
| 96 |
/// The maximum representable exponent. |
| 97 |
const MAX: i16 = 6111; |
| 98 |
|
| 99 |
/// The number of unused bits in the parsed representation. |
| 100 |
const UNUSED_BITS: usize = 2; |
| 101 |
/// The total number of bits in the packed representation. |
| 102 |
const PACKED_WIDTH: usize = 14; |
| 103 |
|
| 104 |
fn from_bits(src_bits: &BitSlice<u8, Msb0>) -> Self { |
| 105 |
let mut bytes = [0u8; 2]; |
| 106 |
bytes.view_bits_mut::<Msb0>()[Self::UNUSED_BITS..].copy_from_bitslice(src_bits); |
| 107 |
Self(bytes) |
| 108 |
} |
| 109 |
|
| 110 |
fn from_native(value: i16) -> Self { |
| 111 |
let mut bytes = [0u8; 2]; |
| 112 |
bytes.view_bits_mut::<Msb0>().store_be(value + Self::BIAS); |
| 113 |
Self(bytes) |
| 114 |
} |
| 115 |
|
| 116 |
fn bits(&self) -> &BitSlice<u8, Msb0> { |
| 117 |
&self.0.view_bits::<Msb0>()[Self::UNUSED_BITS..] |
| 118 |
} |
| 119 |
|
| 120 |
fn raw(&self) -> u16 { |
| 121 |
self.0.view_bits::<Msb0>().load_be::<u16>() |
| 122 |
} |
| 123 |
|
| 124 |
fn value(&self) -> i16 { |
| 125 |
(self.raw() as i16) - Self::BIAS |
| 126 |
} |
| 127 |
} |
| 128 |
|
| 129 |
#[derive(Debug, Clone, PartialEq)] |
| 130 |
struct Coefficient([u8; 16]); |
| 131 |
|
| 132 |
impl Coefficient { |
| 133 |
/// The number of unused bits in the parsed representation. |
| 134 |
const UNUSED_BITS: usize = 14; |
| 135 |
/// The maximum number of digits allowed in a base-10 string representation of the coefficient. |
| 136 |
const MAX_DIGITS: usize = 34; |
| 137 |
/// The maximum allowable value of a coefficient. |
| 138 |
const MAX_VALUE: u128 = 9_999_999_999_999_999_999_999_999_999_999_999; |
| 139 |
|
| 140 |
fn from_bits( |
| 141 |
src_prefix: &BitSlice<u8, Msb0>, |
| 142 |
src_suffix: &BitSlice<u8, Msb0>, |
| 143 |
) -> Result<Self, ParseError> { |
| 144 |
let mut bytes = [0u8; 16]; |
| 145 |
let bits = &mut bytes.view_bits_mut::<Msb0>()[Self::UNUSED_BITS..]; |
| 146 |
let prefix_len = src_prefix.len(); |
| 147 |
bits[0..prefix_len].copy_from_bitslice(src_prefix); |
| 148 |
bits[prefix_len..].copy_from_bitslice(src_suffix); |
| 149 |
let out = Self(bytes); |
| 150 |
if out.value() > Self::MAX_VALUE { |
| 151 |
Err(ParseError::Overflow) |
| 152 |
} else { |
| 153 |
Ok(out) |
| 154 |
} |
| 155 |
} |
| 156 |
|
| 157 |
fn from_native(value: u128) -> Self { |
| 158 |
let mut bytes = [0u8; 16]; |
| 159 |
bytes.view_bits_mut::<Msb0>().store_be(value); |
| 160 |
Self(bytes) |
| 161 |
} |
| 162 |
|
| 163 |
fn bits(&self) -> &BitSlice<u8, Msb0> { |
| 164 |
&self.0.view_bits::<Msb0>()[Self::UNUSED_BITS..] |
| 165 |
} |
| 166 |
|
| 167 |
fn value(&self) -> u128 { |
| 168 |
self.0.view_bits::<Msb0>().load_be::<u128>() |
| 169 |
} |
| 170 |
} |
| 171 |
|
| 172 |
impl ParsedDecimal128 { |
| 173 |
fn new(source: &Decimal128) -> Self { |
| 174 |
// BSON byte order is the opposite of the decimal128 spec byte order, so flip 'em. The rest |
| 175 |
// of this method could be rewritten to not need this, but readability is helped by |
| 176 |
// keeping the implementation congruent with the spec. |
| 177 |
let tmp: [u8; 16] = { |
| 178 |
let mut tmp = [0u8; 16]; |
| 179 |
tmp.view_bits_mut::<Msb0>() |
| 180 |
.store_be(source.bytes.view_bits::<Msb0>().load_le::<u128>()); |
| 181 |
tmp |
| 182 |
}; |
| 183 |
let src_bits = tmp.view_bits::<Msb0>(); |
| 184 |
|
| 185 |
let sign = src_bits[0]; |
| 186 |
let kind = if src_bits[1..5].all() { |
| 187 |
// Special value |
| 188 |
if src_bits[5] { |
| 189 |
Decimal128Kind::NaN { |
| 190 |
signalling: src_bits[6], |
| 191 |
} |
| 192 |
} else { |
| 193 |
Decimal128Kind::Infinity |
| 194 |
} |
| 195 |
} else { |
| 196 |
// Finite value |
| 197 |
let exponent_offset; |
| 198 |
let coeff_prefix; |
| 199 |
if src_bits[1..3].all() { |
| 200 |
exponent_offset = 3; |
| 201 |
coeff_prefix = bits![static u8, Msb0; 1, 0, 0]; |
| 202 |
} else { |
| 203 |
exponent_offset = 1; |
| 204 |
coeff_prefix = bits![static u8, Msb0; 0]; |
| 205 |
} |
| 206 |
let coeff_offset = exponent_offset + Exponent::PACKED_WIDTH; |
| 207 |
|
| 208 |
let exponent = Exponent::from_bits(&src_bits[exponent_offset..coeff_offset]); |
| 209 |
let coefficient = match Coefficient::from_bits(coeff_prefix, &src_bits[coeff_offset..]) |
| 210 |
{ |
| 211 |
Ok(c) => c, |
| 212 |
// Invalid coefficients get silently replaced with zero. |
| 213 |
Err(_) => Coefficient([0u8; 16]), |
| 214 |
}; |
| 215 |
Decimal128Kind::Finite { |
| 216 |
exponent, |
| 217 |
coefficient, |
| 218 |
} |
| 219 |
}; |
| 220 |
ParsedDecimal128 { sign, kind } |
| 221 |
} |
| 222 |
|
| 223 |
fn pack(&self) -> Decimal128 { |
| 224 |
let mut tmp = [0u8; 16]; |
| 225 |
let dest_bits = tmp.view_bits_mut::<Msb0>(); |
| 226 |
|
| 227 |
dest_bits.set(0, self.sign); |
| 228 |
|
| 229 |
match &self.kind { |
| 230 |
Decimal128Kind::NaN { signalling } => { |
| 231 |
dest_bits[1..6].copy_from_bitslice(bits![u8, Msb0; 1, 1, 1, 1, 1]); |
| 232 |
dest_bits.set(6, *signalling); |
| 233 |
} |
| 234 |
Decimal128Kind::Infinity => { |
| 235 |
dest_bits[1..6].copy_from_bitslice(bits![u8, Msb0; 1, 1, 1, 1, 0]); |
| 236 |
} |
| 237 |
Decimal128Kind::Finite { |
| 238 |
exponent, |
| 239 |
coefficient, |
| 240 |
} => { |
| 241 |
let mut coeff_bits = coefficient.bits(); |
| 242 |
let exponent_offset; |
| 243 |
if coeff_bits[0] { |
| 244 |
dest_bits.set(1, true); |
| 245 |
dest_bits.set(2, true); |
| 246 |
coeff_bits = &coeff_bits[3..]; |
| 247 |
exponent_offset = 3; |
| 248 |
} else { |
| 249 |
coeff_bits = &coeff_bits[1..]; |
| 250 |
exponent_offset = 1; |
| 251 |
}; |
| 252 |
let coeff_offset = exponent_offset + Exponent::PACKED_WIDTH; |
| 253 |
dest_bits[exponent_offset..coeff_offset].copy_from_bitslice(exponent.bits()); |
| 254 |
dest_bits[coeff_offset..].copy_from_bitslice(coeff_bits); |
| 255 |
} |
| 256 |
} |
| 257 |
|
| 258 |
let mut bytes = [0u8; 16]; |
| 259 |
bytes |
| 260 |
.view_bits_mut::<Msb0>() |
| 261 |
.store_le(tmp.view_bits::<Msb0>().load_be::<u128>()); |
| 262 |
Decimal128 { bytes } |
| 263 |
} |
| 264 |
} |
| 265 |
|
| 266 |
impl fmt::Display for ParsedDecimal128 { |
| 267 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 268 |
// MongoDB diverges from the IEEE spec and requires no sign for NaN |
| 269 |
if self.sign && !matches!(&self.kind, Decimal128Kind::NaN { .. }) { |
| 270 |
write!(f, "-")?; |
| 271 |
} |
| 272 |
match &self.kind { |
| 273 |
Decimal128Kind::NaN { |
| 274 |
signalling: _signalling, |
| 275 |
} => { |
| 276 |
/* Likewise, MongoDB requires no 's' prefix for signalling. |
| 277 |
if *signalling { |
| 278 |
write!(f, "s")?; |
| 279 |
} |
| 280 |
*/ |
| 281 |
write!(f, "NaN")?; |
| 282 |
} |
| 283 |
Decimal128Kind::Infinity => write!(f, "Infinity")?, |
| 284 |
Decimal128Kind::Finite { |
| 285 |
exponent, |
| 286 |
coefficient, |
| 287 |
} => { |
| 288 |
let coeff_str = format!("{}", coefficient.value()); |
| 289 |
let exp_val = exponent.value(); |
| 290 |
let adj_exp = exp_val + (coeff_str.len() as i16) - 1; |
| 291 |
if exp_val <= 0 && adj_exp >= -6 { |
| 292 |
// Plain notation |
| 293 |
if exp_val == 0 { |
| 294 |
write!(f, "{}", coeff_str)?; |
| 295 |
} else { |
| 296 |
let dec_charlen = exp_val.unsigned_abs() as usize; |
| 297 |
if dec_charlen >= coeff_str.len() { |
| 298 |
write!(f, "0.")?; |
| 299 |
write!(f, "{}", "0".repeat(dec_charlen - coeff_str.len()))?; |
| 300 |
write!(f, "{}", coeff_str)?; |
| 301 |
} else { |
| 302 |
let (pre, post) = coeff_str.split_at(coeff_str.len() - dec_charlen); |
| 303 |
write!(f, "{}", pre)?; |
| 304 |
write!(f, ".")?; |
| 305 |
write!(f, "{}", post)?; |
| 306 |
} |
| 307 |
} |
| 308 |
} else { |
| 309 |
// Exponential notation |
| 310 |
let (pre, post) = coeff_str.split_at(1); |
| 311 |
write!(f, "{}", pre)?; |
| 312 |
if !post.is_empty() { |
| 313 |
write!(f, ".{}", post)?; |
| 314 |
} |
| 315 |
write!(f, "E")?; |
| 316 |
if adj_exp > 0 { |
| 317 |
write!(f, "+")?; |
| 318 |
} |
| 319 |
write!(f, "{}", adj_exp)?; |
| 320 |
} |
| 321 |
} |
| 322 |
} |
| 323 |
Ok(()) |
| 324 |
} |
| 325 |
} |
| 326 |
|
| 327 |
#[derive(Debug)] |
| 328 |
#[non_exhaustive] |
| 329 |
pub enum ParseError { |
| 330 |
EmptyExponent, |
| 331 |
InvalidExponent(std::num::ParseIntError), |
| 332 |
InvalidCoefficient(std::num::ParseIntError), |
| 333 |
Overflow, |
| 334 |
Underflow, |
| 335 |
InexactRounding, |
| 336 |
} |
| 337 |
|
| 338 |
impl fmt::Display for ParseError { |
| 339 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 340 |
match self { |
| 341 |
ParseError::EmptyExponent => write!(f, "empty exponent"), |
| 342 |
ParseError::InvalidExponent(e) => write!(f, "invalid exponent: {}", e), |
| 343 |
ParseError::InvalidCoefficient(e) => write!(f, "invalid coefficient: {}", e), |
| 344 |
ParseError::Overflow => write!(f, "overflow"), |
| 345 |
ParseError::Underflow => write!(f, "underflow"), |
| 346 |
ParseError::InexactRounding => write!(f, "inexact rounding"), |
| 347 |
} |
| 348 |
} |
| 349 |
} |
| 350 |
|
| 351 |
impl std::error::Error for ParseError { |
| 352 |
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { |
| 353 |
match self { |
| 354 |
ParseError::InvalidExponent(e) => Some(e), |
| 355 |
ParseError::InvalidCoefficient(e) => Some(e), |
| 356 |
_ => None, |
| 357 |
} |
| 358 |
} |
| 359 |
} |
| 360 |
|
| 361 |
impl std::str::FromStr for ParsedDecimal128 { |
| 362 |
type Err = ParseError; |
| 363 |
|
| 364 |
fn from_str(mut s: &str) -> Result<Self, Self::Err> { |
| 365 |
let sign; |
| 366 |
if let Some(rest) = s.strip_prefix(&['-', '+'][..]) { |
| 367 |
sign = s.starts_with('-'); |
| 368 |
s = rest; |
| 369 |
} else { |
| 370 |
sign = false; |
| 371 |
} |
| 372 |
let kind = match s.to_ascii_lowercase().as_str() { |
| 373 |
"nan" => Decimal128Kind::NaN { signalling: false }, |
| 374 |
"snan" => Decimal128Kind::NaN { signalling: true }, |
| 375 |
"infinity" | "inf" => Decimal128Kind::Infinity, |
| 376 |
finite_str => { |
| 377 |
// Split into parts |
| 378 |
let mut decimal_str; |
| 379 |
let exp_str; |
| 380 |
match finite_str.split_once('e') { |
| 381 |
None => { |
| 382 |
decimal_str = finite_str; |
| 383 |
exp_str = "0"; |
| 384 |
} |
| 385 |
Some((_, "")) => return Err(ParseError::EmptyExponent), |
| 386 |
Some((pre, post)) => { |
| 387 |
decimal_str = pre; |
| 388 |
exp_str = post; |
| 389 |
} |
| 390 |
} |
| 391 |
let mut exp = exp_str |
| 392 |
.parse::<i16>() |
| 393 |
.map_err(ParseError::InvalidExponent)?; |
| 394 |
|
| 395 |
// Remove decimal point and adjust exponent |
| 396 |
let joined_str; |
| 397 |
if let Some((pre, post)) = decimal_str.split_once('.') { |
| 398 |
let exp_adj = post.len().try_into().map_err(|_| ParseError::Underflow)?; |
| 399 |
exp = exp.checked_sub(exp_adj).ok_or(ParseError::Underflow)?; |
| 400 |
joined_str = format!("{}{}", pre, post); |
| 401 |
decimal_str = &joined_str; |
| 402 |
} |
| 403 |
|
| 404 |
// Strip leading zeros |
| 405 |
let rest = decimal_str.trim_start_matches('0'); |
| 406 |
decimal_str = if rest.is_empty() { "0" } else { rest }; |
| 407 |
|
| 408 |
// Check decimal precision |
| 409 |
{ |
| 410 |
let len = decimal_str.len(); |
| 411 |
if len > Coefficient::MAX_DIGITS { |
| 412 |
decimal_str = round_decimal_str(decimal_str, Coefficient::MAX_DIGITS)?; |
| 413 |
let exp_adj = (len - decimal_str.len()) |
| 414 |
.try_into() |
| 415 |
.map_err(|_| ParseError::Overflow)?; |
| 416 |
exp = exp.checked_add(exp_adj).ok_or(ParseError::Overflow)?; |
| 417 |
} |
| 418 |
} |
| 419 |
|
| 420 |
// Check exponent limits |
| 421 |
if exp < Exponent::TINY { |
| 422 |
if decimal_str != "0" { |
| 423 |
let delta = (Exponent::TINY - exp) |
| 424 |
.try_into() |
| 425 |
.map_err(|_| ParseError::Overflow)?; |
| 426 |
let new_precision = decimal_str |
| 427 |
.len() |
| 428 |
.checked_sub(delta) |
| 429 |
.ok_or(ParseError::Underflow)?; |
| 430 |
decimal_str = round_decimal_str(decimal_str, new_precision)?; |
| 431 |
} |
| 432 |
exp = Exponent::TINY; |
| 433 |
} |
| 434 |
let padded_str; |
| 435 |
if exp > Exponent::MAX { |
| 436 |
if decimal_str != "0" { |
| 437 |
let delta = (exp - Exponent::MAX) |
| 438 |
.try_into() |
| 439 |
.map_err(|_| ParseError::Overflow)?; |
| 440 |
if decimal_str |
| 441 |
.len() |
| 442 |
.checked_add(delta) |
| 443 |
.ok_or(ParseError::Overflow)? |
| 444 |
> Coefficient::MAX_DIGITS |
| 445 |
{ |
| 446 |
return Err(ParseError::Overflow); |
| 447 |
} |
| 448 |
padded_str = format!("{}{}", decimal_str, "0".repeat(delta)); |
| 449 |
decimal_str = &padded_str; |
| 450 |
} |
| 451 |
exp = Exponent::MAX; |
| 452 |
} |
| 453 |
|
| 454 |
// Assemble the final value |
| 455 |
let exponent = Exponent::from_native(exp); |
| 456 |
let coeff: u128 = decimal_str |
| 457 |
.parse() |
| 458 |
.map_err(ParseError::InvalidCoefficient)?; |
| 459 |
let coefficient = Coefficient::from_native(coeff); |
| 460 |
Decimal128Kind::Finite { |
| 461 |
exponent, |
| 462 |
coefficient, |
| 463 |
} |
| 464 |
} |
| 465 |
}; |
| 466 |
|
| 467 |
Ok(Self { sign, kind }) |
| 468 |
} |
| 469 |
} |
| 470 |
|
| 471 |
fn round_decimal_str(s: &str, precision: usize) -> Result<&str, ParseError> { |
| 472 |
let (pre, post) = s.split_at(precision); |
| 473 |
// Any nonzero trimmed digits mean it would be an imprecise round. |
| 474 |
if post.chars().any(|c| c != '0') { |
| 475 |
return Err(ParseError::InexactRounding); |
| 476 |
} |
| 477 |
Ok(pre) |
| 478 |
} |