Debian Codegraph @

src/postgres/common.rs

raw symbols SCIP
1 use crate::{
2 ops::array::{div_by_u32, is_all_zero, mul_by_u32},
3 Decimal,
4 };
5 use core::fmt;
6 use std::error;
7
8 #[derive(Debug, Clone)]
9 pub struct InvalidDecimal {
10 inner: Option<String>,
11 }
12
13 impl fmt::Display for InvalidDecimal {
14 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
15 if let Some(ref msg) = self.inner {
16 fmt.write_fmt(format_args!("Invalid Decimal: {}", msg))
17 } else {
18 fmt.write_str("Invalid Decimal")
19 }
20 }
21 }
22
23 impl error::Error for InvalidDecimal {}
24
25 pub(in crate::postgres) struct PostgresDecimal<D> {
26 pub neg: bool,
27 pub weight: i16,
28 pub scale: u16,
29 pub digits: D,
30 }
31
32 impl Decimal {
33 pub(in crate::postgres) fn checked_from_postgres<D: ExactSizeIterator<Item = u16>>(
34 PostgresDecimal {
35 neg,
36 scale,
37 digits,
38 weight,
39 }: PostgresDecimal<D>,
40 ) -> Option<Self> {
41 let mut digits = digits.into_iter().collect::<Vec<_>>();
42
43 let fractionals_part_count = digits.len() as i32 + (-weight as i32) - 1;
44 let integers_part_count = weight as i32 + 1;
45
46 let mut result = Self::ZERO;
47 // adding integer part
48 if integers_part_count > 0 {
49 let (start_integers, last) = if integers_part_count > digits.len() as i32 {
50 (integers_part_count - digits.len() as i32, digits.len() as i32)
51 } else {
52 (0, integers_part_count)
53 };
54 let integers: Vec<_> = digits.drain(..last as usize).collect();
55 for digit in integers {
56 result = result.checked_mul(Self::from_i128_with_scale(10i128.pow(4), 0))?;
57 result = result.checked_add(Self::new(digit as i64, 0))?;
58 }
59 result = result.checked_mul(Self::from_i128_with_scale(10i128.pow(4 * start_integers as u32), 0))?;
60 }
61 // adding fractional part
62 if fractionals_part_count > 0 {
63 let start_fractionals = if weight < 0 { (-weight as u32) - 1 } else { 0 };
64 for (i, digit) in digits.into_iter().enumerate() {
65 let fract_pow = 4_u32.checked_mul(i as u32 + 1 + start_fractionals)?;
66 if fract_pow <= Self::MAX_SCALE {
67 result = result.checked_add(
68 Self::new(digit as i64, 0) / Self::from_i128_with_scale(10i128.pow(fract_pow), 0),
69 )?;
70 } else if fract_pow == Self::MAX_SCALE + 4 {
71 // rounding last digit
72 if digit >= 5000 {
73 result = result.checked_add(
74 Self::new(1_i64, 0) / Self::from_i128_with_scale(10i128.pow(Self::MAX_SCALE), 0),
75 )?;
76 }
77 }
78 }
79 }
80
81 result.set_sign_negative(neg);
82 // Rescale to the postgres value, automatically rounding as needed.
83 result.rescale((scale as u32).min(Self::MAX_SCALE));
84 Some(result)
85 }
86
87 pub(in crate::postgres) fn to_postgres(self) -> PostgresDecimal<Vec<i16>> {
88 if self.is_zero() {
89 return PostgresDecimal {
90 neg: false,
91 weight: 0,
92 scale: 0,
93 digits: vec![],
94 };
95 }
96 let scale = self.scale() as u16;
97
98 let groups_diff = scale & 0x3; // groups_diff = scale % 4
99
100 let mut mantissa = self.mantissa_array4();
101
102 if groups_diff > 0 {
103 let remainder = 4 - groups_diff;
104 let power = 10u32.pow(u32::from(remainder));
105 mul_by_u32(&mut mantissa, power);
106 }
107
108 // array to store max mantissa of Decimal in Postgres decimal format
109 const MAX_GROUP_COUNT: usize = 8;
110 let mut digits = Vec::with_capacity(MAX_GROUP_COUNT);
111
112 while !is_all_zero(&mantissa) {
113 let digit = div_by_u32(&mut mantissa, 10000) as u16;
114 digits.push(digit.try_into().unwrap());
115 }
116 digits.reverse();
117 let digits_after_decimal = (scale + 3) / 4;
118 let weight = digits.len() as i16 - digits_after_decimal as i16 - 1;
119
120 let unnecessary_zeroes = if weight >= 0 {
121 let index_of_decimal = (weight + 1) as usize;
122 digits
123 .get(index_of_decimal..)
124 .expect("enough digits exist")
125 .iter()
126 .rev()
127 .take_while(|i| **i == 0)
128 .count()
129 } else {
130 0
131 };
132 let relevant_digits = digits.len() - unnecessary_zeroes;
133 digits.truncate(relevant_digits);
134
135 PostgresDecimal {
136 neg: self.is_sign_negative(),
137 digits,
138 scale,
139 weight,
140 }
141 }
142 }