1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
#![allow(clippy::as_conversions)]
use std::error::Error;
use std::fmt;
use byteorder::{NetworkEndian, ReadBytesExt};
use bytes::{BufMut, BytesMut};
use dec::OrderedDecimal;
use lazy_static::lazy_static;
use postgres_types::{to_sql_checked, FromSql, IsNull, ToSql, Type};
use repr::adt::numeric::{self, cx_datum, Numeric as AdtNumeric, NumericAgg};
#[derive(Debug)]
pub struct Numeric(pub OrderedDecimal<AdtNumeric>);
impl fmt::Display for Numeric {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl From<AdtNumeric> for Numeric {
fn from(n: AdtNumeric) -> Numeric {
Numeric(OrderedDecimal(n))
}
}
const TO_FROM_SQL_BASE_POW: usize = 4;
lazy_static! {
static ref TO_SQL_BASER: AdtNumeric = AdtNumeric::from(10u32.pow(TO_FROM_SQL_BASE_POW as u32));
static ref FROM_SQL_SCALER: AdtNumeric = AdtNumeric::from(TO_FROM_SQL_BASE_POW);
}
const UNITS_LEN: usize = 11;
impl ToSql for Numeric {
fn to_sql(
&self,
_: &Type,
out: &mut BytesMut,
) -> Result<IsNull, Box<dyn Error + 'static + Send + Sync>> {
let mut d = self.0 .0.clone();
let scale = u16::from(numeric::get_scale(&d));
let is_nan = d.is_nan();
let is_neg = d.is_negative();
let is_infinite = d.is_infinite();
let mut cx = numeric::cx_datum();
cx.set_max_exponent(cx.max_exponent() + TO_FROM_SQL_BASE_POW as isize)
.unwrap();
cx.set_min_exponent(cx.min_exponent() - TO_FROM_SQL_BASE_POW as isize)
.unwrap();
cx.abs(&mut d);
let mut digits = [0u16; UNITS_LEN];
let mut d_i = UNITS_LEN;
let (fract_units, leading_zero_units) = if d.exponent() < 0 {
let pos_exp = usize::try_from(-d.exponent()).expect("positive value < 40");
let leading_zero_units = if pos_exp >= d.digits() as usize {
let digits = if d.is_zero() { 0 } else { d.digits() as usize };
(pos_exp - digits + TO_FROM_SQL_BASE_POW - 1) / TO_FROM_SQL_BASE_POW
} else {
0
};
let s = pos_exp % TO_FROM_SQL_BASE_POW;
let unit_shift_exp = if s != 0 {
pos_exp + TO_FROM_SQL_BASE_POW - s
} else {
pos_exp
};
cx.scaleb(&mut d, &AdtNumeric::from(unit_shift_exp));
(
u16::try_from(unit_shift_exp / TO_FROM_SQL_BASE_POW).expect("value < 40"),
leading_zero_units,
)
} else {
(0, 0)
};
let mut w = d.clone();
while !d.is_zero() && !d.is_special() {
d_i -= 1;
cx.rem(&mut d, &TO_SQL_BASER);
digits[d_i] =
u16::try_from(u32::try_from(d).expect("value < 10,000")).expect("value < 10,000");
cx.div_integer(&mut w, &TO_SQL_BASER);
d = w;
}
d_i -= leading_zero_units;
let units = u16::try_from(UNITS_LEN - d_i).unwrap();
let weight = i16::try_from(units - fract_units).unwrap() - 1;
out.put_u16(units);
out.put_i16(weight);
out.put_u16(if is_infinite {
if is_neg {
0xF000
} else {
0xD000
}
} else if is_nan {
0xC000
} else if is_neg {
0x4000
} else {
0
});
out.put_u16(scale);
if !is_nan {
for digit in digits[d_i..].iter() {
out.put_u16(*digit);
}
}
Ok(IsNull::No)
}
fn accepts(ty: &Type) -> bool {
matches!(*ty, Type::NUMERIC)
}
to_sql_checked!();
}
impl<'a> FromSql<'a> for Numeric {
fn from_sql(_: &Type, mut raw: &'a [u8]) -> Result<Numeric, Box<dyn Error + Sync + Send>> {
let units = usize::from(raw.read_u16::<NetworkEndian>()?);
let weight = raw.read_i16::<NetworkEndian>()?;
let sign = raw.read_u16::<NetworkEndian>()?;
let in_scale = raw.read_i16::<NetworkEndian>()?;
let mut digits = vec![];
for _ in 0..units {
digits.push(raw.read_u16::<NetworkEndian>()?)
}
let mut cx = numeric::cx_agg();
let mut d = NumericAgg::zero();
for digit in digits[..units].iter() {
cx.scaleb(&mut d, &FROM_SQL_SCALER);
let n = AdtNumeric::from(u32::from(*digit));
cx.add(&mut d, &n);
}
match sign {
0 => (),
0xD000 => return Ok(Numeric::from(AdtNumeric::infinity())),
0xF000 => {
let mut cx = numeric::cx_datum();
let mut d = AdtNumeric::infinity();
cx.neg(&mut d);
return Ok(Numeric::from(d));
}
0x4000 => cx.neg(&mut d),
0xC000 => return Ok(Numeric::from(AdtNumeric::nan())),
_ => return Err("bad sign in numeric".into()),
}
let mut scale = (units as i16 - weight - 1) * 4;
if scale < 0 {
cx.scaleb(&mut d, &AdtNumeric::from(-i32::from(scale)));
scale = 0;
} else if scale > in_scale {
cx.scaleb(&mut d, &AdtNumeric::from(-i32::from(scale - in_scale)));
scale = in_scale;
}
cx.scaleb(&mut d, &AdtNumeric::from(-i32::from(scale)));
cx.reduce(&mut d);
let mut cx = cx_datum();
let d_datum = cx.to_width(d);
if d.is_infinite() || cx.status().any() {
return Err(format!("Unable to take bytes to numeric value; rendered {}", d).into());
}
Ok(Numeric::from(d_datum))
}
fn accepts(ty: &Type) -> bool {
matches!(*ty, Type::NUMERIC)
}
}
#[test]
fn test_to_from_sql_roundtrip() {
fn inner(s: &str) {
let mut cx = numeric::cx_datum();
let d = cx.parse(s).unwrap();
let r = Numeric(OrderedDecimal(d));
let mut out = BytesMut::new();
let _ = r.to_sql(&Type::NUMERIC, &mut out).unwrap();
let d_from_sql = Numeric::from_sql(&Type::NUMERIC, &out).unwrap();
assert_eq!(r.0, d_from_sql.0);
}
inner("0");
inner("-0");
inner("0.1");
inner("0.0");
inner("0.00");
inner("0.000");
inner("0.0000");
inner("0.00000");
inner("123456789.012346789");
inner("000000000000000000000000000000000000001");
inner("000000000000000000000000000000000000000");
inner("999999999999999999999999999999999999999");
inner("123456789012345678901234567890123456789");
inner("-123456789012345678901234567890123456789");
inner(".123456789012345678901234567890123456789");
inner(".000000000000000000000000000000000000001");
inner(".000000000000000000000000000000000000000");
inner(".999999999999999999999999999999999999999");
inner("-0.123456789012345678901234567890123456789");
inner("1e25");
inner("-1e25");
inner("9.876e-25");
inner("-9.876e-25");
inner("98760000");
inner(".00009876");
inner("-.00009876");
inner("NaN");
let mut cx = numeric::cx_datum();
let v = vec![
cx.parse("-999999999999999999999999999999999999999")
.unwrap(),
cx.parse("-999999999999999999999999999999999999999")
.unwrap(),
];
let s = cx.sum(v.iter());
assert!(s.is_infinite());
let r = Numeric::from(s);
let mut out = BytesMut::new();
let _ = r.to_sql(&Type::NUMERIC, &mut out).unwrap();
let d_from_sql = Numeric::from_sql(&Type::NUMERIC, &out).unwrap();
assert_eq!(r.0, d_from_sql.0);
}