Debian Codegraph @

src/types/rust_decimal.rs

raw symbols SCIP
1 use rust_decimal::Decimal;
2
3 use crate::decode::Decode;
4 use crate::encode::{Encode, IsNull};
5 use crate::error::BoxDynError;
6 use crate::types::numeric::{PgNumeric, PgNumericSign};
7 use crate::types::Type;
8 use crate::{PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueFormat, PgValueRef, Postgres};
9
10 use rust_decimal::MathematicalOps;
11
12 impl Type<Postgres> for Decimal {
13 fn type_info() -> PgTypeInfo {
14 PgTypeInfo::NUMERIC
15 }
16 }
17
18 impl PgHasArrayType for Decimal {
19 fn array_type_info() -> PgTypeInfo {
20 PgTypeInfo::NUMERIC_ARRAY
21 }
22 }
23
24 impl TryFrom<PgNumeric> for Decimal {
25 type Error = BoxDynError;
26
27 fn try_from(numeric: PgNumeric) -> Result<Self, BoxDynError> {
28 Decimal::try_from(&numeric)
29 }
30 }
31
32 impl TryFrom<&'_ PgNumeric> for Decimal {
33 type Error = BoxDynError;
34
35 fn try_from(numeric: &'_ PgNumeric) -> Result<Self, BoxDynError> {
36 let (digits, sign, mut weight, scale) = match *numeric {
37 PgNumeric::Number {
38 ref digits,
39 sign,
40 weight,
41 scale,
42 } => (digits, sign, weight, scale),
43
44 PgNumeric::NotANumber => {
45 return Err("Decimal does not support NaN values".into());
46 }
47 };
48
49 if digits.is_empty() {
50 // Postgres returns an empty digit array for 0
51 return Ok(Decimal::ZERO);
52 }
53
54 let scale = u32::try_from(scale)
55 .map_err(|_| format!("invalid scale value for Pg NUMERIC: {scale}"))?;
56
57 let mut value = Decimal::ZERO;
58
59 // Sum over `digits`, multiply each by its weight and add it to `value`.
60 for &digit in digits {
61 let mul = Decimal::from(10_000i16)
62 .checked_powi(weight as i64)
63 .ok_or("value not representable as rust_decimal::Decimal")?;
64
65 let part = Decimal::from(digit) * mul;
66
67 value = value
68 .checked_add(part)
69 .ok_or("value not representable as rust_decimal::Decimal")?;
70
71 weight = weight.checked_sub(1).ok_or("weight underflowed")?;
72 }
73
74 match sign {
75 PgNumericSign::Positive => value.set_sign_positive(true),
76 PgNumericSign::Negative => value.set_sign_negative(true),
77 }
78
79 value.rescale(scale);
80
81 Ok(value)
82 }
83 }
84
85 impl From<Decimal> for PgNumeric {
86 fn from(value: Decimal) -> Self {
87 PgNumeric::from(&value)
88 }
89 }
90
91 // This impl is effectively infallible because `NUMERIC` has a greater range than `Decimal`.
92 impl From<&'_ Decimal> for PgNumeric {
93 // Impl has been manually validated.
94 #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
95 fn from(decimal: &Decimal) -> Self {
96 if Decimal::is_zero(decimal) {
97 return PgNumeric::ZERO;
98 }
99
100 assert!(
101 (0u32..=28).contains(&decimal.scale()),
102 "decimal scale out of range {:?}",
103 decimal.unpack(),
104 );
105
106 // Cannot overflow: always in the range [0, 28]
107 let scale = decimal.scale() as u16;
108
109 let mut mantissa = decimal.mantissa().unsigned_abs();
110
111 // If our scale is not a multiple of 4, we need to go to the next multiple.
112 let groups_diff = scale % 4;
113 if groups_diff > 0 {
114 let remainder = 4 - groups_diff as u32;
115 let power = 10u32.pow(remainder) as u128;
116
117 // Impossible to overflow; 0 <= mantissa <= 2^96,
118 // and we're multiplying by at most 1,000 (giving us a result < 2^106)
119 mantissa *= power;
120 }
121
122 // Array to store max mantissa of Decimal in Postgres decimal format.
123 let mut digits = Vec::with_capacity(8);
124
125 // Convert to base-10000.
126 while mantissa != 0 {
127 // Cannot overflow or wrap because of the modulus
128 digits.push((mantissa % 10_000) as i16);
129 mantissa /= 10_000;
130 }
131
132 // We started with the low digits first, but they should actually be at the end.
133 digits.reverse();
134
135 // Cannot overflow: strictly smaller than `scale`.
136 let digits_after_decimal = scale.div_ceil(4) as i16;
137
138 // `mantissa` contains at most 29 decimal digits (log10(2^96)),
139 // split into at most 8 4-digit segments.
140 assert!(
141 digits.len() <= 8,
142 "digits.len() out of range: {}; unpacked: {:?}",
143 digits.len(),
144 decimal.unpack()
145 );
146
147 // Cannot overflow; at most 8
148 let num_digits = digits.len() as i16;
149
150 // Find how many 4-digit segments should go before the decimal point.
151 // `weight = 0` puts just `digit[0]` before the decimal point, and the rest after.
152 let weight = num_digits - digits_after_decimal - 1;
153
154 // Remove non-significant zeroes.
155 while let Some(&0) = digits.last() {
156 digits.pop();
157 }
158
159 PgNumeric::Number {
160 sign: match decimal.is_sign_negative() {
161 false => PgNumericSign::Positive,
162 true => PgNumericSign::Negative,
163 },
164 // Cannot overflow; between 0 and 28
165 scale: scale as i16,
166 weight,
167 digits,
168 }
169 }
170 }
171
172 impl Encode<'_, Postgres> for Decimal {
173 fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> {
174 PgNumeric::from(self).encode(buf)?;
175
176 Ok(IsNull::No)
177 }
178 }
179
180 #[doc=include_str!("rust_decimal-range.md")]
181 impl Decode<'_, Postgres> for Decimal {
182 fn decode(value: PgValueRef<'_>) -> Result<Self, BoxDynError> {
183 match value.format() {
184 PgValueFormat::Binary => PgNumeric::decode(value.as_bytes()?)?.try_into(),
185 PgValueFormat::Text => Ok(value.as_str()?.parse::<Decimal>()?),
186 }
187 }
188 }
189
190 #[cfg(test)]
191 mod tests {
192 use super::{Decimal, PgNumeric, PgNumericSign};
193 use std::convert::TryFrom;
194
195 #[test]
196 fn zero() {
197 let zero: Decimal = "0".parse().unwrap();
198
199 assert_eq!(PgNumeric::from(&zero), PgNumeric::ZERO,);
200
201 assert_eq!(Decimal::try_from(&PgNumeric::ZERO).unwrap(), Decimal::ZERO);
202 }
203
204 #[test]
205 fn one() {
206 let one: Decimal = "1".parse().unwrap();
207 assert_eq!(
208 PgNumeric::try_from(&one).unwrap(),
209 PgNumeric::Number {
210 sign: PgNumericSign::Positive,
211 scale: 0,
212 weight: 0,
213 digits: vec![1]
214 }
215 );
216 }
217
218 #[test]
219 fn ten() {
220 let ten: Decimal = "10".parse().unwrap();
221 assert_eq!(
222 PgNumeric::try_from(&ten).unwrap(),
223 PgNumeric::Number {
224 sign: PgNumericSign::Positive,
225 scale: 0,
226 weight: 0,
227 digits: vec![10]
228 }
229 );
230 }
231
232 #[test]
233 fn one_hundred() {
234 let one_hundred: Decimal = "100".parse().unwrap();
235 assert_eq!(
236 PgNumeric::try_from(&one_hundred).unwrap(),
237 PgNumeric::Number {
238 sign: PgNumericSign::Positive,
239 scale: 0,
240 weight: 0,
241 digits: vec![100]
242 }
243 );
244 }
245
246 #[test]
247 fn ten_thousand() {
248 // Decimal doesn't normalize here
249 let ten_thousand: Decimal = "10000".parse().unwrap();
250 assert_eq!(
251 PgNumeric::try_from(&ten_thousand).unwrap(),
252 PgNumeric::Number {
253 sign: PgNumericSign::Positive,
254 scale: 0,
255 weight: 1,
256 digits: vec![1]
257 }
258 );
259 }
260
261 #[test]
262 fn two_digits() {
263 let two_digits: Decimal = "12345".parse().unwrap();
264 assert_eq!(
265 PgNumeric::try_from(&two_digits).unwrap(),
266 PgNumeric::Number {
267 sign: PgNumericSign::Positive,
268 scale: 0,
269 weight: 1,
270 digits: vec![1, 2345]
271 }
272 );
273 }
274
275 #[test]
276 fn one_tenth() {
277 let one_tenth: Decimal = "0.1".parse().unwrap();
278 assert_eq!(
279 PgNumeric::try_from(&one_tenth).unwrap(),
280 PgNumeric::Number {
281 sign: PgNumericSign::Positive,
282 scale: 1,
283 weight: -1,
284 digits: vec![1000]
285 }
286 );
287 }
288
289 #[test]
290 fn decimal_1() {
291 let decimal: Decimal = "1.2345".parse().unwrap();
292 assert_eq!(
293 PgNumeric::try_from(&decimal).unwrap(),
294 PgNumeric::Number {
295 sign: PgNumericSign::Positive,
296 scale: 4,
297 weight: 0,
298 digits: vec![1, 2345]
299 }
300 );
301 }
302
303 #[test]
304 fn decimal_2() {
305 let decimal: Decimal = "0.12345".parse().unwrap();
306 assert_eq!(
307 PgNumeric::try_from(&decimal).unwrap(),
308 PgNumeric::Number {
309 sign: PgNumericSign::Positive,
310 scale: 5,
311 weight: -1,
312 digits: vec![1234, 5000]
313 }
314 );
315 }
316
317 #[test]
318 fn decimal_3() {
319 let decimal: Decimal = "0.01234".parse().unwrap();
320 assert_eq!(
321 PgNumeric::try_from(&decimal).unwrap(),
322 PgNumeric::Number {
323 sign: PgNumericSign::Positive,
324 scale: 5,
325 weight: -1,
326 digits: vec![0123, 4000]
327 }
328 );
329 }
330
331 #[test]
332 fn decimal_4() {
333 let decimal: Decimal = "12345.67890".parse().unwrap();
334 let expected_numeric = PgNumeric::Number {
335 sign: PgNumericSign::Positive,
336 scale: 5,
337 weight: 1,
338 digits: vec![1, 2345, 6789],
339 };
340 assert_eq!(PgNumeric::try_from(&decimal).unwrap(), expected_numeric);
341
342 let actual_decimal = Decimal::try_from(expected_numeric).unwrap();
343 assert_eq!(actual_decimal, decimal);
344 assert_eq!(actual_decimal.mantissa(), 1234567890);
345 assert_eq!(actual_decimal.scale(), 5);
346 }
347
348 #[test]
349 fn one_digit_decimal() {
350 let one_digit_decimal: Decimal = "0.00001234".parse().unwrap();
351 let expected_numeric = PgNumeric::Number {
352 sign: PgNumericSign::Positive,
353 scale: 8,
354 weight: -2,
355 digits: vec![1234],
356 };
357 assert_eq!(
358 PgNumeric::try_from(&one_digit_decimal).unwrap(),
359 expected_numeric
360 );
361
362 let actual_decimal = Decimal::try_from(expected_numeric).unwrap();
363 assert_eq!(actual_decimal, one_digit_decimal);
364 assert_eq!(actual_decimal.mantissa(), 1234);
365 assert_eq!(actual_decimal.scale(), 8);
366 }
367
368 #[test]
369 fn max_value() {
370 let expected_numeric = PgNumeric::Number {
371 sign: PgNumericSign::Positive,
372 scale: 0,
373 weight: 7,
374 digits: vec![7, 9228, 1625, 1426, 4337, 5935, 4395, 0335],
375 };
376 assert_eq!(
377 PgNumeric::try_from(&Decimal::MAX).unwrap(),
378 expected_numeric
379 );
380
381 let actual_decimal = Decimal::try_from(expected_numeric).unwrap();
382 assert_eq!(actual_decimal, Decimal::MAX);
383 // Value split by 10,000's to match the expected digits[]
384 assert_eq!(
385 actual_decimal.mantissa(),
386 7_9228_1625_1426_4337_5935_4395_0335
387 );
388 assert_eq!(actual_decimal.scale(), 0);
389 }
390
391 #[test]
392 fn max_value_max_scale() {
393 let mut max_value_max_scale = Decimal::MAX;
394 max_value_max_scale.set_scale(28).unwrap();
395
396 let expected_numeric = PgNumeric::Number {
397 sign: PgNumericSign::Positive,
398 scale: 28,
399 weight: 0,
400 digits: vec![7, 9228, 1625, 1426, 4337, 5935, 4395, 0335],
401 };
402 assert_eq!(
403 PgNumeric::try_from(&max_value_max_scale).unwrap(),
404 expected_numeric
405 );
406
407 let actual_decimal = Decimal::try_from(expected_numeric).unwrap();
408 assert_eq!(actual_decimal, max_value_max_scale);
409 assert_eq!(
410 actual_decimal.mantissa(),
411 79_228_162_514_264_337_593_543_950_335
412 );
413 assert_eq!(actual_decimal.scale(), 28);
414 }
415
416 #[test]
417 fn issue_423_four_digit() {
418 // This is a regression test for https://github.com/launchbadge/sqlx/issues/423
419 let four_digit: Decimal = "1234".parse().unwrap();
420 assert_eq!(
421 PgNumeric::try_from(&four_digit).unwrap(),
422 PgNumeric::Number {
423 sign: PgNumericSign::Positive,
424 scale: 0,
425 weight: 0,
426 digits: vec![1234]
427 }
428 );
429 }
430
431 #[test]
432 fn issue_423_negative_four_digit() {
433 // This is a regression test for https://github.com/launchbadge/sqlx/issues/423
434 let negative_four_digit: Decimal = "-1234".parse().unwrap();
435 assert_eq!(
436 PgNumeric::try_from(&negative_four_digit).unwrap(),
437 PgNumeric::Number {
438 sign: PgNumericSign::Negative,
439 scale: 0,
440 weight: 0,
441 digits: vec![1234]
442 }
443 );
444 }
445
446 #[test]
447 fn issue_423_eight_digit() {
448 // This is a regression test for https://github.com/launchbadge/sqlx/issues/423
449 let eight_digit: Decimal = "12345678".parse().unwrap();
450 assert_eq!(
451 PgNumeric::try_from(&eight_digit).unwrap(),
452 PgNumeric::Number {
453 sign: PgNumericSign::Positive,
454 scale: 0,
455 weight: 1,
456 digits: vec![1234, 5678]
457 }
458 );
459 }
460
461 #[test]
462 fn issue_423_negative_eight_digit() {
463 // This is a regression test for https://github.com/launchbadge/sqlx/issues/423
464 let negative_eight_digit: Decimal = "-12345678".parse().unwrap();
465 assert_eq!(
466 PgNumeric::try_from(&negative_eight_digit).unwrap(),
467 PgNumeric::Number {
468 sign: PgNumericSign::Negative,
469 scale: 0,
470 weight: 1,
471 digits: vec![1234, 5678]
472 }
473 );
474 }
475
476 #[test]
477 fn issue_2247_trailing_zeros() {
478 // This is a regression test for https://github.com/launchbadge/sqlx/issues/2247
479 let one_hundred: Decimal = "100.00".parse().unwrap();
480 let expected_numeric = PgNumeric::Number {
481 sign: PgNumericSign::Positive,
482 scale: 2,
483 weight: 0,
484 digits: vec![100],
485 };
486 assert_eq!(PgNumeric::try_from(&one_hundred).unwrap(), expected_numeric);
487
488 let actual_decimal = Decimal::try_from(expected_numeric).unwrap();
489 assert_eq!(actual_decimal, one_hundred);
490 assert_eq!(actual_decimal.mantissa(), 10000);
491 assert_eq!(actual_decimal.scale(), 2);
492 }
493 }