Debian Codegraph @

src/types/numeric.rs

raw symbols SCIP
1 use sqlx_core::bytes::Buf;
2 use std::num::Saturating;
3
4 use crate::error::BoxDynError;
5 use crate::PgArgumentBuffer;
6
7 /// Represents a `NUMERIC` value in the **Postgres** wire protocol.
8 #[derive(Debug, PartialEq, Eq)]
9 pub(crate) enum PgNumeric {
10 /// Equivalent to the `'NaN'` value in Postgres. The result of, e.g. `1 / 0`.
11 NotANumber,
12
13 /// A populated `NUMERIC` value.
14 ///
15 /// A description of these fields can be found here (although the type being described is the
16 /// version for in-memory calculations, the field names are the same):
17 /// https://github.com/postgres/postgres/blob/bcd1c3630095e48bc3b1eb0fc8e8c8a7c851eba1/src/backend/utils/adt/numeric.c#L224-L269
18 Number {
19 /// The sign of the value: positive (also set for 0 and -0), or negative.
20 sign: PgNumericSign,
21
22 /// The digits of the number in base-10000 with the most significant digit first
23 /// (big-endian).
24 ///
25 /// The length of this vector must not overflow `i16` for the binary protocol.
26 ///
27 /// *Note*: the `Encode` implementation will panic if any digit is `>= 10000`.
28 digits: Vec<i16>,
29
30 /// The scaling factor of the number, such that the value will be interpreted as
31 ///
32 /// ```text
33 /// digits[0] * 10,000 ^ weight
34 /// + digits[1] * 10,000 ^ (weight - 1)
35 /// ...
36 /// + digits[N] * 10,000 ^ (weight - N) where N = digits.len() - 1
37 /// ```
38 /// May be negative.
39 weight: i16,
40
41 /// How many _decimal_ (base-10) digits following the decimal point to consider in
42 /// arithmetic regardless of how many actually follow the decimal point as determined by
43 /// `weight`--the comment in the Postgres code linked above recommends using this only for
44 /// ignoring unnecessary trailing zeroes (as trimming nonzero digits means reducing the
45 /// precision of the value).
46 ///
47 /// Must be `>= 0`.
48 scale: i16,
49 },
50 }
51
52 // https://github.com/postgres/postgres/blob/bcd1c3630095e48bc3b1eb0fc8e8c8a7c851eba1/src/backend/utils/adt/numeric.c#L167-L170
53 const SIGN_POS: u16 = 0x0000;
54 const SIGN_NEG: u16 = 0x4000;
55 const SIGN_NAN: u16 = 0xC000; // overflows i16 (C equivalent truncates from integer literal)
56
57 /// Possible sign values for [PgNumeric].
58 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
59 #[repr(u16)]
60 pub(crate) enum PgNumericSign {
61 Positive = SIGN_POS,
62 Negative = SIGN_NEG,
63 }
64
65 impl PgNumericSign {
66 fn try_from_u16(val: u16) -> Result<Self, BoxDynError> {
67 match val {
68 SIGN_POS => Ok(PgNumericSign::Positive),
69 SIGN_NEG => Ok(PgNumericSign::Negative),
70
71 SIGN_NAN => unreachable!("sign value for NaN passed to PgNumericSign"),
72
73 _ => Err(format!("invalid value for PgNumericSign: {val:#04X}").into()),
74 }
75 }
76 }
77
78 impl PgNumeric {
79 /// Equivalent value of `0::numeric`.
80 pub const ZERO: Self = PgNumeric::Number {
81 sign: PgNumericSign::Positive,
82 digits: vec![],
83 weight: 0,
84 scale: 0,
85 };
86
87 pub(crate) fn is_valid_digit(digit: i16) -> bool {
88 (0..10_000).contains(&digit)
89 }
90
91 pub(crate) fn size_hint(decimal_digits: u64) -> usize {
92 let mut size_hint = Saturating(decimal_digits);
93
94 // BigDecimal::digits() gives us base-10 digits, so we divide by 4 to get base-10000 digits
95 // and since this is just a hint we just always round up
96 size_hint /= 4;
97 size_hint += 1;
98
99 // Times two bytes for each base-10000 digit
100 size_hint *= 2;
101
102 // Plus `weight` and `scale`
103 size_hint += 8;
104
105 usize::try_from(size_hint.0).unwrap_or(usize::MAX)
106 }
107
108 pub(crate) fn decode(mut buf: &[u8]) -> Result<Self, BoxDynError> {
109 // https://github.com/postgres/postgres/blob/bcd1c3630095e48bc3b1eb0fc8e8c8a7c851eba1/src/backend/utils/adt/numeric.c#L874
110 let num_digits = buf.get_u16();
111 let weight = buf.get_i16();
112 let sign = buf.get_u16();
113 let scale = buf.get_i16();
114
115 if sign == SIGN_NAN {
116 Ok(PgNumeric::NotANumber)
117 } else {
118 let digits: Vec<_> = (0..num_digits).map(|_| buf.get_i16()).collect::<_>();
119
120 Ok(PgNumeric::Number {
121 sign: PgNumericSign::try_from_u16(sign)?,
122 scale,
123 weight,
124 digits,
125 })
126 }
127 }
128
129 /// ### Errors
130 ///
131 /// * If `digits.len()` overflows `i16`
132 /// * If any element in `digits` is greater than or equal to 10000
133 pub(crate) fn encode(&self, buf: &mut PgArgumentBuffer) -> Result<(), String> {
134 match *self {
135 PgNumeric::Number {
136 ref digits,
137 sign,
138 scale,
139 weight,
140 } => {
141 let digits_len = i16::try_from(digits.len()).map_err(|_| {
142 format!(
143 "PgNumeric digits.len() ({}) should not overflow i16",
144 digits.len()
145 )
146 })?;
147
148 buf.extend(&digits_len.to_be_bytes());
149 buf.extend(&weight.to_be_bytes());
150 buf.extend(&(sign as i16).to_be_bytes());
151 buf.extend(&scale.to_be_bytes());
152
153 for (i, &digit) in digits.iter().enumerate() {
154 if !Self::is_valid_digit(digit) {
155 return Err(format!("{i}th PgNumeric digit out of range: {digit}"));
156 }
157
158 buf.extend(&digit.to_be_bytes());
159 }
160 }
161
162 PgNumeric::NotANumber => {
163 buf.extend(&0_i16.to_be_bytes());
164 buf.extend(&0_i16.to_be_bytes());
165 buf.extend(&SIGN_NAN.to_be_bytes());
166 buf.extend(&0_i16.to_be_bytes());
167 }
168 }
169
170 Ok(())
171 }
172 }