| 1 | use bigdecimal::BigDecimal; |
| 2 | use num_bigint::{BigInt, Sign}; |
| 3 | use std::cmp; |
| 4 | |
| 5 | use crate::decode::Decode; |
| 6 | use crate::encode::{Encode, IsNull}; |
| 7 | use crate::error::BoxDynError; |
| 8 | use crate::types::numeric::{PgNumeric, PgNumericSign}; |
| 9 | use crate::types::Type; |
| 10 | use crate::{PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueFormat, PgValueRef, Postgres}; |
| 11 | |
| 12 | impl Type<Postgres> for BigDecimal { |
| 13 | fn type_info() -> PgTypeInfo { |
| 14 | PgTypeInfo::NUMERIC |
| 15 | } |
| 16 | } |
| 17 | |
| 18 | impl PgHasArrayType for BigDecimal { |
| 19 | fn array_type_info() -> PgTypeInfo { |
| 20 | PgTypeInfo::NUMERIC_ARRAY |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | impl TryFrom<PgNumeric> for BigDecimal { |
| 25 | type Error = BoxDynError; |
| 26 | |
| 27 | fn try_from(numeric: PgNumeric) -> Result<Self, BoxDynError> { |
| 28 | Self::try_from(&numeric) |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | impl TryFrom<&'_ PgNumeric> for BigDecimal { |
| 33 | type Error = BoxDynError; |
| 34 | |
| 35 | fn try_from(numeric: &'_ PgNumeric) -> Result<Self, Self::Error> { |
| 36 | let (digits, sign, weight) = match *numeric { |
| 37 | PgNumeric::Number { |
| 38 | ref digits, |
| 39 | sign, |
| 40 | weight, |
| 41 | .. |
| 42 | } => (digits, sign, weight), |
| 43 | |
| 44 | PgNumeric::NotANumber => { |
| 45 | return Err("BigDecimal does not support NaN values".into()); |
| 46 | } |
| 47 | }; |
| 48 | |
| 49 | if digits.is_empty() { |
| 50 | // Postgres returns an empty digit array for 0 but BigInt expects at least one zero |
| 51 | return Ok(0u64.into()); |
| 52 | } |
| 53 | |
| 54 | let sign = match sign { |
| 55 | PgNumericSign::Positive => Sign::Plus, |
| 56 | PgNumericSign::Negative => Sign::Minus, |
| 57 | }; |
| 58 | |
| 59 | // weight is 0 if the decimal point falls after the first base-10000 digit |
| 60 | // |
| 61 | // `Vec` capacity cannot exceed `isize::MAX` bytes, so this cast can't wrap in practice. |
| 62 | #[allow(clippy::cast_possible_wrap)] |
| 63 | let scale = (digits.len() as i64 - weight as i64 - 1) * 4; |
| 64 | |
| 65 | // no optimized algorithm for base-10 so use base-100 for faster processing |
| 66 | let mut cents = Vec::with_capacity(digits.len() * 2); |
| 67 | |
| 68 | #[allow( |
| 69 | clippy::cast_possible_truncation, |
| 70 | clippy::cast_possible_wrap, |
| 71 | clippy::cast_sign_loss |
| 72 | )] |
| 73 | for (i, &digit) in digits.iter().enumerate() { |
| 74 | if !PgNumeric::is_valid_digit(digit) { |
| 75 | return Err(format!( |
| 76 | "PgNumeric to BigDecimal: {i}th digit is out of range {digit}" |
| 77 | ) |
| 78 | .into()); |
| 79 | } |
| 80 | |
| 81 | cents.push((digit / 100) as u8); |
| 82 | cents.push((digit % 100) as u8); |
| 83 | } |
| 84 | |
| 85 | let bigint = BigInt::from_radix_be(sign, ¢s, 100) |
| 86 | .ok_or("PgNumeric contained an out-of-range digit")?; |
| 87 | |
| 88 | Ok(BigDecimal::new(bigint, scale)) |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | impl TryFrom<&'_ BigDecimal> for PgNumeric { |
| 93 | type Error = BoxDynError; |
| 94 | |
| 95 | fn try_from(decimal: &BigDecimal) -> Result<Self, BoxDynError> { |
| 96 | let base_10_to_10000 = |chunk: &[u8]| chunk.iter().fold(0i16, |a, &d| a * 10 + d as i16); |
| 97 | |
| 98 | // NOTE: this unfortunately copies the BigInt internally |
| 99 | let (integer, exp) = decimal.as_bigint_and_exponent(); |
| 100 | |
| 101 | // this routine is specifically optimized for base-10 |
| 102 | // FIXME: is there a way to iterate over the digits to avoid the Vec allocation |
| 103 | let (sign, base_10) = integer.to_radix_be(10); |
| 104 | |
| 105 | let base_10_len = i64::try_from(base_10.len()).map_err(|_| { |
| 106 | format!( |
| 107 | "BigDecimal base-10 length out of range for PgNumeric: {}", |
| 108 | base_10.len() |
| 109 | ) |
| 110 | })?; |
| 111 | |
| 112 | // weight is positive power of 10000 |
| 113 | // exp is the negative power of 10 |
| 114 | let weight_10 = base_10_len - exp; |
| 115 | |
| 116 | // scale is only nonzero when we have fractional digits |
| 117 | // since `exp` is the _negative_ decimal exponent, it tells us |
| 118 | // exactly what our scale should be |
| 119 | let scale: i16 = cmp::max(0, exp).try_into()?; |
| 120 | |
| 121 | // there's an implicit +1 offset in the interpretation |
| 122 | let weight: i16 = if weight_10 <= 0 { |
| 123 | weight_10 / 4 - 1 |
| 124 | } else { |
| 125 | // the `-1` is a fix for an off by 1 error (4 digits should still be 0 weight) |
| 126 | (weight_10 - 1) / 4 |
| 127 | } |
| 128 | .try_into()?; |
| 129 | |
| 130 | let digits_len = if base_10.len() % 4 != 0 { |
| 131 | base_10.len() / 4 + 1 |
| 132 | } else { |
| 133 | base_10.len() / 4 |
| 134 | }; |
| 135 | |
| 136 | // For efficiency, we want to process the base-10 digits in chunks of 4, |
| 137 | // but that means we need to deal with the non-divisible remainder first. |
| 138 | let offset = weight_10.rem_euclid(4); |
| 139 | |
| 140 | // Do a checked conversion to the smallest integer, |
| 141 | // so we can widen arbitrarily without triggering lints. |
| 142 | let offset = u8::try_from(offset).unwrap_or_else(|_| { |
| 143 | panic!("BUG: `offset` should be in the range [0, 4) but is {offset}") |
| 144 | }); |
| 145 | |
| 146 | let mut digits = Vec::with_capacity(digits_len); |
| 147 | |
| 148 | if let Some(first) = base_10.get(..offset as usize) { |
| 149 | if !first.is_empty() { |
| 150 | digits.push(base_10_to_10000(first)); |
| 151 | } |
| 152 | } else if offset != 0 { |
| 153 | // If we didn't hit the `if let Some` branch, |
| 154 | // then `base_10.len()` must strictly be smaller |
| 155 | #[allow(clippy::cast_possible_truncation)] |
| 156 | let power = (offset as usize - base_10.len()) as u32; |
| 157 | |
| 158 | digits.push(base_10_to_10000(&base_10) * 10i16.pow(power)); |
| 159 | } |
| 160 | |
| 161 | if let Some(rest) = base_10.get(offset as usize..) { |
| 162 | // `chunk.len()` is always between 1 and 4 |
| 163 | #[allow(clippy::cast_possible_truncation)] |
| 164 | digits.extend( |
| 165 | rest.chunks(4) |
| 166 | .map(|chunk| base_10_to_10000(chunk) * 10i16.pow(4 - chunk.len() as u32)), |
| 167 | ); |
| 168 | } |
| 169 | |
| 170 | while let Some(&0) = digits.last() { |
| 171 | digits.pop(); |
| 172 | } |
| 173 | |
| 174 | Ok(PgNumeric::Number { |
| 175 | sign: sign_to_pg(sign), |
| 176 | scale, |
| 177 | weight, |
| 178 | digits, |
| 179 | }) |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | #[doc=include_str!("bigdecimal-range.md")] |
| 184 | impl Encode<'_, Postgres> for BigDecimal { |
| 185 | fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> { |
| 186 | PgNumeric::try_from(self)?.encode(buf)?; |
| 187 | |
| 188 | Ok(IsNull::No) |
| 189 | } |
| 190 | |
| 191 | fn size_hint(&self) -> usize { |
| 192 | PgNumeric::size_hint(self.digits()) |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | /// ### Note: `NaN` |
| 197 | /// `BigDecimal` has a greater range than `NUMERIC` (see the corresponding `Encode` impl for details) |
| 198 | /// but cannot represent `NaN`, so decoding may return an error. |
| 199 | impl Decode<'_, Postgres> for BigDecimal { |
| 200 | fn decode(value: PgValueRef<'_>) -> Result<Self, BoxDynError> { |
| 201 | match value.format() { |
| 202 | PgValueFormat::Binary => PgNumeric::decode(value.as_bytes()?)?.try_into(), |
| 203 | PgValueFormat::Text => Ok(value.as_str()?.parse::<BigDecimal>()?), |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | fn sign_to_pg(sign: Sign) -> PgNumericSign { |
| 209 | match sign { |
| 210 | Sign::Plus | Sign::NoSign => PgNumericSign::Positive, |
| 211 | Sign::Minus => PgNumericSign::Negative, |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | #[cfg(test)] |
| 216 | mod bigdecimal_to_pgnumeric { |
| 217 | use super::{BigDecimal, PgNumeric, PgNumericSign}; |
| 218 | use std::convert::TryFrom; |
| 219 | |
| 220 | #[test] |
| 221 | fn zero() { |
| 222 | let zero: BigDecimal = "0".parse().unwrap(); |
| 223 | |
| 224 | assert_eq!( |
| 225 | PgNumeric::try_from(&zero).unwrap(), |
| 226 | PgNumeric::Number { |
| 227 | sign: PgNumericSign::Positive, |
| 228 | scale: 0, |
| 229 | weight: 0, |
| 230 | digits: vec![] |
| 231 | } |
| 232 | ); |
| 233 | } |
| 234 | |
| 235 | #[test] |
| 236 | fn one() { |
| 237 | let one: BigDecimal = "1".parse().unwrap(); |
| 238 | assert_eq!( |
| 239 | PgNumeric::try_from(&one).unwrap(), |
| 240 | PgNumeric::Number { |
| 241 | sign: PgNumericSign::Positive, |
| 242 | scale: 0, |
| 243 | weight: 0, |
| 244 | digits: vec![1] |
| 245 | } |
| 246 | ); |
| 247 | } |
| 248 | |
| 249 | #[test] |
| 250 | fn ten() { |
| 251 | let ten: BigDecimal = "10".parse().unwrap(); |
| 252 | assert_eq!( |
| 253 | PgNumeric::try_from(&ten).unwrap(), |
| 254 | PgNumeric::Number { |
| 255 | sign: PgNumericSign::Positive, |
| 256 | scale: 0, |
| 257 | weight: 0, |
| 258 | digits: vec![10] |
| 259 | } |
| 260 | ); |
| 261 | } |
| 262 | |
| 263 | #[test] |
| 264 | fn one_hundred() { |
| 265 | let one_hundred: BigDecimal = "100".parse().unwrap(); |
| 266 | assert_eq!( |
| 267 | PgNumeric::try_from(&one_hundred).unwrap(), |
| 268 | PgNumeric::Number { |
| 269 | sign: PgNumericSign::Positive, |
| 270 | scale: 0, |
| 271 | weight: 0, |
| 272 | digits: vec![100] |
| 273 | } |
| 274 | ); |
| 275 | } |
| 276 | |
| 277 | #[test] |
| 278 | fn ten_thousand() { |
| 279 | // BigDecimal doesn't normalize here |
| 280 | let ten_thousand: BigDecimal = "10000".parse().unwrap(); |
| 281 | assert_eq!( |
| 282 | PgNumeric::try_from(&ten_thousand).unwrap(), |
| 283 | PgNumeric::Number { |
| 284 | sign: PgNumericSign::Positive, |
| 285 | scale: 0, |
| 286 | weight: 1, |
| 287 | digits: vec![1] |
| 288 | } |
| 289 | ); |
| 290 | } |
| 291 | |
| 292 | #[test] |
| 293 | fn two_digits() { |
| 294 | let two_digits: BigDecimal = "12345".parse().unwrap(); |
| 295 | assert_eq!( |
| 296 | PgNumeric::try_from(&two_digits).unwrap(), |
| 297 | PgNumeric::Number { |
| 298 | sign: PgNumericSign::Positive, |
| 299 | scale: 0, |
| 300 | weight: 1, |
| 301 | digits: vec![1, 2345] |
| 302 | } |
| 303 | ); |
| 304 | } |
| 305 | |
| 306 | #[test] |
| 307 | fn one_tenth() { |
| 308 | let one_tenth: BigDecimal = "0.1".parse().unwrap(); |
| 309 | assert_eq!( |
| 310 | PgNumeric::try_from(&one_tenth).unwrap(), |
| 311 | PgNumeric::Number { |
| 312 | sign: PgNumericSign::Positive, |
| 313 | scale: 1, |
| 314 | weight: -1, |
| 315 | digits: vec![1000] |
| 316 | } |
| 317 | ); |
| 318 | } |
| 319 | |
| 320 | #[test] |
| 321 | fn one_hundredth() { |
| 322 | let one_hundredth: BigDecimal = "0.01".parse().unwrap(); |
| 323 | assert_eq!( |
| 324 | PgNumeric::try_from(&one_hundredth).unwrap(), |
| 325 | PgNumeric::Number { |
| 326 | sign: PgNumericSign::Positive, |
| 327 | scale: 2, |
| 328 | weight: -1, |
| 329 | digits: vec![100] |
| 330 | } |
| 331 | ); |
| 332 | } |
| 333 | |
| 334 | #[test] |
| 335 | fn twelve_thousandths() { |
| 336 | let twelve_thousandths: BigDecimal = "0.012".parse().unwrap(); |
| 337 | assert_eq!( |
| 338 | PgNumeric::try_from(&twelve_thousandths).unwrap(), |
| 339 | PgNumeric::Number { |
| 340 | sign: PgNumericSign::Positive, |
| 341 | scale: 3, |
| 342 | weight: -1, |
| 343 | digits: vec![120] |
| 344 | } |
| 345 | ); |
| 346 | } |
| 347 | |
| 348 | #[test] |
| 349 | fn decimal_1() { |
| 350 | let decimal: BigDecimal = "1.2345".parse().unwrap(); |
| 351 | assert_eq!( |
| 352 | PgNumeric::try_from(&decimal).unwrap(), |
| 353 | PgNumeric::Number { |
| 354 | sign: PgNumericSign::Positive, |
| 355 | scale: 4, |
| 356 | weight: 0, |
| 357 | digits: vec![1, 2345] |
| 358 | } |
| 359 | ); |
| 360 | } |
| 361 | |
| 362 | #[test] |
| 363 | fn decimal_2() { |
| 364 | let decimal: BigDecimal = "0.12345".parse().unwrap(); |
| 365 | assert_eq!( |
| 366 | PgNumeric::try_from(&decimal).unwrap(), |
| 367 | PgNumeric::Number { |
| 368 | sign: PgNumericSign::Positive, |
| 369 | scale: 5, |
| 370 | weight: -1, |
| 371 | digits: vec![1234, 5000] |
| 372 | } |
| 373 | ); |
| 374 | } |
| 375 | |
| 376 | #[test] |
| 377 | fn decimal_3() { |
| 378 | let decimal: BigDecimal = "0.01234".parse().unwrap(); |
| 379 | assert_eq!( |
| 380 | PgNumeric::try_from(&decimal).unwrap(), |
| 381 | PgNumeric::Number { |
| 382 | sign: PgNumericSign::Positive, |
| 383 | scale: 5, |
| 384 | weight: -1, |
| 385 | digits: vec![0123, 4000] |
| 386 | } |
| 387 | ); |
| 388 | } |
| 389 | |
| 390 | #[test] |
| 391 | fn decimal_4() { |
| 392 | let decimal: BigDecimal = "12345.67890".parse().unwrap(); |
| 393 | assert_eq!( |
| 394 | PgNumeric::try_from(&decimal).unwrap(), |
| 395 | PgNumeric::Number { |
| 396 | sign: PgNumericSign::Positive, |
| 397 | scale: 5, |
| 398 | weight: 1, |
| 399 | digits: vec![1, 2345, 6789] |
| 400 | } |
| 401 | ); |
| 402 | } |
| 403 | |
| 404 | #[test] |
| 405 | fn one_digit_decimal() { |
| 406 | let one_digit_decimal: BigDecimal = "0.00001234".parse().unwrap(); |
| 407 | assert_eq!( |
| 408 | PgNumeric::try_from(&one_digit_decimal).unwrap(), |
| 409 | PgNumeric::Number { |
| 410 | sign: PgNumericSign::Positive, |
| 411 | scale: 8, |
| 412 | weight: -2, |
| 413 | digits: vec![1234] |
| 414 | } |
| 415 | ); |
| 416 | } |
| 417 | |
| 418 | #[test] |
| 419 | fn issue_423_four_digit() { |
| 420 | // This is a regression test for https://github.com/launchbadge/sqlx/issues/423 |
| 421 | let four_digit: BigDecimal = "1234".parse().unwrap(); |
| 422 | assert_eq!( |
| 423 | PgNumeric::try_from(&four_digit).unwrap(), |
| 424 | PgNumeric::Number { |
| 425 | sign: PgNumericSign::Positive, |
| 426 | scale: 0, |
| 427 | weight: 0, |
| 428 | digits: vec![1234] |
| 429 | } |
| 430 | ); |
| 431 | } |
| 432 | |
| 433 | #[test] |
| 434 | fn issue_423_negative_four_digit() { |
| 435 | // This is a regression test for https://github.com/launchbadge/sqlx/issues/423 |
| 436 | let negative_four_digit: BigDecimal = "-1234".parse().unwrap(); |
| 437 | assert_eq!( |
| 438 | PgNumeric::try_from(&negative_four_digit).unwrap(), |
| 439 | PgNumeric::Number { |
| 440 | sign: PgNumericSign::Negative, |
| 441 | scale: 0, |
| 442 | weight: 0, |
| 443 | digits: vec![1234] |
| 444 | } |
| 445 | ); |
| 446 | } |
| 447 | |
| 448 | #[test] |
| 449 | fn issue_423_eight_digit() { |
| 450 | // This is a regression test for https://github.com/launchbadge/sqlx/issues/423 |
| 451 | let eight_digit: BigDecimal = "12345678".parse().unwrap(); |
| 452 | assert_eq!( |
| 453 | PgNumeric::try_from(&eight_digit).unwrap(), |
| 454 | PgNumeric::Number { |
| 455 | sign: PgNumericSign::Positive, |
| 456 | scale: 0, |
| 457 | weight: 1, |
| 458 | digits: vec![1234, 5678] |
| 459 | } |
| 460 | ); |
| 461 | } |
| 462 | |
| 463 | #[test] |
| 464 | fn issue_423_negative_eight_digit() { |
| 465 | // This is a regression test for https://github.com/launchbadge/sqlx/issues/423 |
| 466 | let negative_eight_digit: BigDecimal = "-12345678".parse().unwrap(); |
| 467 | assert_eq!( |
| 468 | PgNumeric::try_from(&negative_eight_digit).unwrap(), |
| 469 | PgNumeric::Number { |
| 470 | sign: PgNumericSign::Negative, |
| 471 | scale: 0, |
| 472 | weight: 1, |
| 473 | digits: vec![1234, 5678] |
| 474 | } |
| 475 | ); |
| 476 | } |
| 477 | } |