1use std::cmp::Ordering;
16use std::error::Error;
17use std::fmt;
18use std::sync::LazyLock;
19
20use anyhow::bail;
21use dec::{Context, Decimal, OrderedDecimal};
22use mz_ore::cast;
23use mz_persist_types::columnar::FixedSizeCodec;
24use mz_proto::{ProtoType, RustType, TryFromProtoError};
25#[cfg(any(test, feature = "proptest"))]
26use proptest::arbitrary::Arbitrary;
27#[cfg(any(test, feature = "proptest"))]
28use proptest::strategy::{BoxedStrategy, Strategy};
29use serde::{Deserialize, Serialize};
30
31include!(concat!(env!("OUT_DIR"), "/mz_repr.adt.numeric.rs"));
32
33pub const NUMERIC_DATUM_WIDTH: u8 = 13;
35
36pub const NUMERIC_DATUM_WIDTH_USIZE: usize = cast::u8_to_usize(NUMERIC_DATUM_WIDTH);
38
39pub const NUMERIC_DATUM_MAX_PRECISION: u8 = NUMERIC_DATUM_WIDTH * 3;
41
42pub type Numeric = Decimal<NUMERIC_DATUM_WIDTH_USIZE>;
44
45pub const NUMERIC_AGG_WIDTH: u8 = 27;
47
48pub const NUMERIC_AGG_WIDTH_USIZE: usize = cast::u8_to_usize(NUMERIC_AGG_WIDTH);
50
51pub const NUMERIC_AGG_MAX_PRECISION: u8 = NUMERIC_AGG_WIDTH * 3;
53
54pub type NumericAgg = Decimal<NUMERIC_AGG_WIDTH_USIZE>;
56
57#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
64pub struct OrderedNumericAgg(pub NumericAgg);
65
66impl PartialEq for OrderedNumericAgg {
67 fn eq(&self, other: &Self) -> bool {
68 OrderedDecimal(self.0) == OrderedDecimal(other.0)
69 }
70}
71
72impl Eq for OrderedNumericAgg {}
73
74impl PartialOrd for OrderedNumericAgg {
75 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
76 Some(self.cmp(other))
77 }
78}
79
80impl Ord for OrderedNumericAgg {
81 fn cmp(&self, other: &Self) -> Ordering {
82 OrderedDecimal(self.0).cmp(&OrderedDecimal(other.0))
83 }
84}
85
86static CX_DATUM: LazyLock<Context<Numeric>> = LazyLock::new(|| {
87 let mut cx = Context::<Numeric>::default();
88 cx.set_max_exponent(isize::from(NUMERIC_DATUM_MAX_PRECISION - 1))
89 .unwrap();
90 cx.set_min_exponent(-isize::from(NUMERIC_DATUM_MAX_PRECISION))
91 .unwrap();
92 cx
93});
94static CX_AGG: LazyLock<Context<NumericAgg>> = LazyLock::new(|| {
95 let mut cx = Context::<NumericAgg>::default();
96 cx.set_max_exponent(isize::from(NUMERIC_AGG_MAX_PRECISION - 1))
97 .unwrap();
98 cx.set_min_exponent(-isize::from(NUMERIC_AGG_MAX_PRECISION))
99 .unwrap();
100 cx
101});
102static U128_SPLITTER_DATUM: LazyLock<Numeric> = LazyLock::new(|| {
103 let mut cx = Numeric::context();
104 cx.parse("340282366920938463463374607431768211456").unwrap()
106});
107static U128_SPLITTER_AGG: LazyLock<NumericAgg> = LazyLock::new(|| {
108 let mut cx = NumericAgg::context();
109 cx.parse("340282366920938463463374607431768211456").unwrap()
111});
112
113pub mod str_serde {
115 use std::str::FromStr;
116
117 use serde::Deserialize;
118
119 use super::Numeric;
120
121 pub fn deserialize<'de, D>(deserializer: D) -> Result<Numeric, D::Error>
123 where
124 D: serde::Deserializer<'de>,
125 {
126 let buf = String::deserialize(deserializer)?;
127 Numeric::from_str(&buf).map_err(serde::de::Error::custom)
128 }
129}
130
131#[derive(
137 Debug,
138 Clone,
139 Copy,
140 Eq,
141 PartialEq,
142 Ord,
143 PartialOrd,
144 Hash,
145 Serialize,
146 Deserialize
147)]
148pub struct NumericMaxScale(pub(crate) u8);
149
150impl NumericMaxScale {
151 pub const ZERO: NumericMaxScale = NumericMaxScale(0);
153
154 pub fn into_u8(self) -> u8 {
156 self.0
157 }
158}
159
160#[cfg(any(test, feature = "proptest"))]
161impl Arbitrary for NumericMaxScale {
162 type Parameters = ();
163 type Strategy = BoxedStrategy<NumericMaxScale>;
164
165 fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
166 (0..=NUMERIC_DATUM_MAX_PRECISION)
167 .prop_map(NumericMaxScale)
168 .boxed()
169 }
170}
171
172impl TryFrom<i64> for NumericMaxScale {
173 type Error = InvalidNumericMaxScaleError;
174
175 fn try_from(max_scale: i64) -> Result<Self, Self::Error> {
176 match u8::try_from(max_scale) {
177 Ok(max_scale) if max_scale <= NUMERIC_DATUM_MAX_PRECISION => {
178 Ok(NumericMaxScale(max_scale))
179 }
180 _ => Err(InvalidNumericMaxScaleError),
181 }
182 }
183}
184
185impl TryFrom<usize> for NumericMaxScale {
186 type Error = InvalidNumericMaxScaleError;
187
188 fn try_from(max_scale: usize) -> Result<Self, Self::Error> {
189 Self::try_from(i64::try_from(max_scale).map_err(|_| InvalidNumericMaxScaleError)?)
190 }
191}
192
193impl RustType<ProtoNumericMaxScale> for NumericMaxScale {
194 fn into_proto(&self) -> ProtoNumericMaxScale {
195 ProtoNumericMaxScale {
196 value: self.0.into_proto(),
197 }
198 }
199
200 fn from_proto(max_scale: ProtoNumericMaxScale) -> Result<Self, TryFromProtoError> {
203 NumericMaxScale::try_from(i64::from(max_scale.value)).map_err(|e| {
204 TryFromProtoError::InvalidFieldError(format!(
205 "ProtoNumericMaxScale::value {}: {e}",
206 max_scale.value
207 ))
208 })
209 }
210}
211
212impl RustType<ProtoOptionalNumericMaxScale> for Option<NumericMaxScale> {
213 fn into_proto(&self) -> ProtoOptionalNumericMaxScale {
214 ProtoOptionalNumericMaxScale {
215 value: self.into_proto(),
216 }
217 }
218
219 fn from_proto(max_scale: ProtoOptionalNumericMaxScale) -> Result<Self, TryFromProtoError> {
220 max_scale.value.into_rust()
221 }
222}
223
224#[derive(Debug, Clone)]
227pub struct InvalidNumericMaxScaleError;
228
229impl fmt::Display for InvalidNumericMaxScaleError {
230 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
231 write!(
232 f,
233 "scale for type numeric must be between 0 and {}",
234 NUMERIC_DATUM_MAX_PRECISION
235 )
236 }
237}
238
239impl Error for InvalidNumericMaxScaleError {}
240
241pub trait Dec<const N: usize> {
244 const TWOS_COMPLEMENT_BYTE_WIDTH: usize;
247 fn context() -> Context<Decimal<N>>;
249 fn u128_splitter() -> &'static Decimal<N>;
252}
253
254impl Dec<NUMERIC_DATUM_WIDTH_USIZE> for Numeric {
255 const TWOS_COMPLEMENT_BYTE_WIDTH: usize = 17;
256 fn context() -> Context<Numeric> {
257 CX_DATUM.clone()
258 }
259 fn u128_splitter() -> &'static Numeric {
260 &U128_SPLITTER_DATUM
261 }
262}
263
264impl Dec<NUMERIC_AGG_WIDTH_USIZE> for NumericAgg {
265 const TWOS_COMPLEMENT_BYTE_WIDTH: usize = 33;
266 fn context() -> Context<NumericAgg> {
267 CX_AGG.clone()
268 }
269 fn u128_splitter() -> &'static NumericAgg {
270 &U128_SPLITTER_AGG
271 }
272}
273
274pub fn cx_datum() -> Context<Numeric> {
276 CX_DATUM.clone()
277}
278
279pub fn cx_agg() -> Context<NumericAgg> {
281 CX_AGG.clone()
282}
283
284fn twos_complement_be_to_u128(input: &[u8]) -> u128 {
285 assert!(input.len() <= 16);
286 let mut buf = [0; 16];
287 buf[16 - input.len()..16].copy_from_slice(input);
288 u128::from_be_bytes(buf)
289}
290
291fn negate_twos_complement_le<'a, I>(b: I)
295where
296 I: Iterator<Item = &'a mut u8>,
297{
298 let mut seen_first_one = false;
299 for i in b {
300 if seen_first_one {
301 *i = *i ^ 0xFF;
302 } else if *i > 0 {
303 seen_first_one = true;
304 if i == &0x80 {
305 continue;
306 }
307 let tz = i.trailing_zeros();
308 *i = *i ^ (0xFF << tz + 1);
309 }
310 }
311}
312
313pub fn numeric_to_twos_complement_be(
315 mut numeric: Numeric,
316) -> [u8; Numeric::TWOS_COMPLEMENT_BYTE_WIDTH] {
317 let mut buf = [0; Numeric::TWOS_COMPLEMENT_BYTE_WIDTH];
318 if numeric.is_special() {
322 return buf;
323 }
324
325 let mut cx = Numeric::context();
326
327 if numeric.exponent() < 0 {
329 let s = Numeric::from(-numeric.exponent());
330 cx.scaleb(&mut numeric, &s);
331 }
332
333 numeric_to_twos_complement_inner::<Numeric, NUMERIC_DATUM_WIDTH_USIZE>(
334 numeric, &mut cx, &mut buf,
335 );
336 buf
337}
338
339pub fn numeric_to_twos_complement_wide(
348 numeric: Numeric,
349) -> [u8; NumericAgg::TWOS_COMPLEMENT_BYTE_WIDTH] {
350 let mut buf = [0; NumericAgg::TWOS_COMPLEMENT_BYTE_WIDTH];
351 if numeric.is_special() {
355 return buf;
356 }
357 let mut cx = NumericAgg::context();
358 let mut d = cx.to_width(numeric);
359 let mut scaler = NumericAgg::from(NUMERIC_DATUM_MAX_PRECISION);
360 cx.neg(&mut scaler);
361 cx.rescale(&mut d, &scaler);
363 cx.abs(&mut scaler);
366 cx.scaleb(&mut d, &scaler);
367
368 numeric_to_twos_complement_inner::<NumericAgg, NUMERIC_AGG_WIDTH_USIZE>(d, &mut cx, &mut buf);
369 buf
370}
371
372fn numeric_to_twos_complement_inner<D: Dec<N>, const N: usize>(
373 mut d: Decimal<N>,
374 cx: &mut Context<Decimal<N>>,
375 buf: &mut [u8],
376) {
377 let is_neg = if d.is_negative() {
379 cx.neg(&mut d);
380 true
381 } else {
382 false
383 };
384
385 assert!(d.exponent() >= 0);
387
388 let mut buf_cursor = 0;
389 while !d.is_zero() {
390 let mut w = d.clone();
391 cx.rem(&mut w, D::u128_splitter());
393
394 let c = w.coefficient::<u128>().unwrap();
398
399 let e = std::cmp::min(buf_cursor + 16, D::TWOS_COMPLEMENT_BYTE_WIDTH);
402
403 buf[buf_cursor..e].copy_from_slice(&c.to_le_bytes()[0..e - buf_cursor]);
405 buf_cursor += 16;
407
408 cx.div_integer(&mut d, D::u128_splitter());
410 }
411
412 if is_neg {
413 negate_twos_complement_le(buf.iter_mut());
414 }
415
416 buf.reverse();
418}
419
420pub fn twos_complement_be_to_numeric(
421 input: &mut [u8],
422 scale: u8,
423) -> Result<Numeric, anyhow::Error> {
424 let mut cx = cx_datum();
425 if input.len() <= Numeric::TWOS_COMPLEMENT_BYTE_WIDTH {
426 let mut narrow = [0u8; Numeric::TWOS_COMPLEMENT_BYTE_WIDTH];
429 let narrow = &mut narrow[..input.len()];
430 narrow.copy_from_slice(input);
431 if let Ok(mut n) =
432 twos_complement_be_to_numeric_inner::<Numeric, NUMERIC_DATUM_WIDTH_USIZE>(narrow)
433 {
434 n.set_exponent(-i32::from(scale));
435 return Ok(n);
436 }
437 }
438 let mut n = twos_complement_be_to_numeric_inner::<NumericAgg, NUMERIC_AGG_WIDTH_USIZE>(input)?;
441 n.set_exponent(-i32::from(scale));
443 let d = cx.to_width(n);
444 if cx.status().inexact() {
445 bail!("Value exceeds maximum numeric value")
446 }
447 Ok(d)
448}
449
450pub fn twos_complement_be_to_numeric_inner<D: Dec<N>, const N: usize>(
453 input: &mut [u8],
454) -> Result<Decimal<N>, anyhow::Error> {
455 if input.is_empty() {
456 bail!("cannot parse a numeric value from an empty byte string");
462 }
463 let is_neg = if (input[0] & 0x80) != 0 {
464 negate_twos_complement_le(input.iter_mut().rev());
467 true
468 } else {
469 false
470 };
471
472 let head = input.len() % 16;
473 let i = twos_complement_be_to_u128(&input[0..head]);
474 let mut cx = D::context();
475 let mut d = cx.from_u128(i);
476
477 for c in input[head..].chunks(16) {
478 assert_eq!(c.len(), 16);
479 cx.mul(&mut d, D::u128_splitter());
481 let i = twos_complement_be_to_u128(c);
482 let i = cx.from_u128(i);
483 cx.add(&mut d, &i);
484 }
485
486 if cx.status().inexact() {
487 bail!("Value exceeds maximum numeric value")
488 } else if cx.status().any() {
489 bail!("unexpected status {:?}", cx.status());
490 }
491 if is_neg {
492 cx.neg(&mut d);
493 }
494 Ok(d)
495}
496
497#[mz_ore::test]
498#[cfg_attr(miri, ignore)] fn test_twos_complement_roundtrip() {
500 fn inner(s: &str) {
501 let mut cx = cx_datum();
502 let d = cx.parse(s).unwrap();
503 let scale = std::cmp::min(d.exponent(), 0).abs();
504 let mut b = numeric_to_twos_complement_be(d.clone());
505 let x = twos_complement_be_to_numeric(&mut b, u8::try_from(scale).unwrap()).unwrap();
506 assert_eq!(d, x);
507 }
508 inner("0");
509 inner("0.000000000000000000000000000000000012345");
510 inner("0.123456789012345678901234567890123456789");
511 inner("1.00000000000000000000000000000000000000");
512 inner("1");
513 inner("2");
514 inner("170141183460469231731687303715884105727");
515 inner("170141183460469231731687303715884105728");
516 inner("12345678901234567890.1234567890123456789");
517 inner("999999999999999999999999999999999999999");
518 inner("7e35");
519 inner("7e-35");
520 inner("-0.000000000000000000000000000000000012345");
521 inner("-0.12345678901234567890123456789012345678");
522 inner("-1.00000000000000000000000000000000000000");
523 inner("-1");
524 inner("-2");
525 inner("-170141183460469231731687303715884105727");
526 inner("-170141183460469231731687303715884105728");
527 inner("-12345678901234567890.1234567890123456789");
528 inner("-999999999999999999999999999999999999999");
529 inner("-7.2e35");
530 inner("-7.2e-35");
531}
532
533#[mz_ore::test]
534#[cfg_attr(miri, ignore)] fn test_twos_complement_empty_is_error() {
536 for scale in [0u8, 1, 38] {
541 assert!(twos_complement_be_to_numeric(&mut [], scale).is_err());
542 }
543 assert!(
544 twos_complement_be_to_numeric_inner::<Numeric, NUMERIC_DATUM_WIDTH_USIZE>(&mut []).is_err()
545 );
546}
547
548#[mz_ore::test]
549#[cfg_attr(miri, ignore)] fn test_twos_comp_numeric_primitive() {
551 fn inner_inner<P>(i: P, i_be_bytes: &mut [u8])
552 where
553 P: Into<Numeric> + TryFrom<Numeric> + Eq + PartialEq + std::fmt::Debug + Copy,
554 {
555 let mut e = [0; Numeric::TWOS_COMPLEMENT_BYTE_WIDTH];
556 e[Numeric::TWOS_COMPLEMENT_BYTE_WIDTH - i_be_bytes.len()..].copy_from_slice(i_be_bytes);
557 let mut w = [0; NumericAgg::TWOS_COMPLEMENT_BYTE_WIDTH];
558 w[NumericAgg::TWOS_COMPLEMENT_BYTE_WIDTH - i_be_bytes.len()..].copy_from_slice(i_be_bytes);
559
560 let d: Numeric = i.into();
561
562 if d.is_negative() {
564 for i in e[..Numeric::TWOS_COMPLEMENT_BYTE_WIDTH - i_be_bytes.len()].iter_mut() {
565 *i = 0xFF;
566 }
567 for i in w[..NumericAgg::TWOS_COMPLEMENT_BYTE_WIDTH - i_be_bytes.len()].iter_mut() {
568 *i = 0xFF;
569 }
570 }
571
572 let d_be_bytes = numeric_to_twos_complement_be(d);
575 assert_eq!(
576 e, d_be_bytes,
577 "expected repr of {:?}, got {:?}",
578 e, d_be_bytes
579 );
580
581 let e_numeric = twos_complement_be_to_numeric(&mut e, 0).unwrap();
583 let e_p: P = e_numeric
584 .try_into()
585 .unwrap_or_else(|_e| panic!("try_into failed"));
586 assert_eq!(i, e_p, "expected val of {:?}, got {:?}", i, e_p);
587
588 let w_numeric = twos_complement_be_to_numeric(&mut w, 0).unwrap();
590 let w_p: P = w_numeric
591 .try_into()
592 .unwrap_or_else(|_e| panic!("try_into failed"));
593 assert_eq!(i, w_p, "expected val of {:?}, got {:?}", i, e_p);
594
595 let p_numeric = twos_complement_be_to_numeric(i_be_bytes, 0).unwrap();
597 let p_p: P = p_numeric
598 .try_into()
599 .unwrap_or_else(|_e| panic!("try_into failed"));
600 assert_eq!(i, p_p, "expected val of {:?}, got {:?}", i, p_p);
601 }
602
603 fn inner_i32(i: i32) {
604 inner_inner(i, &mut i.to_be_bytes());
605 }
606
607 fn inner_i64(i: i64) {
608 inner_inner(i, &mut i.to_be_bytes());
609 }
610
611 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
615 struct FromableI128 {
616 i: i128,
617 }
618 impl From<i128> for FromableI128 {
619 fn from(i: i128) -> FromableI128 {
620 FromableI128 { i }
621 }
622 }
623 impl From<FromableI128> for Numeric {
624 fn from(n: FromableI128) -> Numeric {
625 Numeric::try_from(n.i).unwrap()
626 }
627 }
628 impl TryFrom<Numeric> for FromableI128 {
629 type Error = ();
630 fn try_from(n: Numeric) -> Result<FromableI128, Self::Error> {
631 match i128::try_from(n) {
632 Ok(i) => Ok(FromableI128 { i }),
633 Err(_) => Err(()),
634 }
635 }
636 }
637
638 fn inner_i128(i: i128) {
639 inner_inner(FromableI128::from(i), &mut i.to_be_bytes());
640 }
641
642 inner_i32(0);
643 inner_i32(1);
644 inner_i32(2);
645 inner_i32(-1);
646 inner_i32(-2);
647 inner_i32(i32::MAX);
648 inner_i32(i32::MIN);
649 inner_i32(i32::MAX / 7 + 7);
650 inner_i32(i32::MIN / 7 + 7);
651 inner_i64(0);
652 inner_i64(1);
653 inner_i64(2);
654 inner_i64(-1);
655 inner_i64(-2);
656 inner_i64(i64::MAX);
657 inner_i64(i64::MIN);
658 inner_i64(i64::MAX / 7 + 7);
659 inner_i64(i64::MIN / 7 + 7);
660 inner_i128(0);
661 inner_i128(1);
662 inner_i128(2);
663 inner_i128(-1);
664 inner_i128(-2);
665 inner_i128(i128::from(i64::MAX));
666 inner_i128(i128::from(i64::MIN));
667 inner_i128(i128::MAX);
668 inner_i128(i128::MIN);
669 inner_i128(i128::MAX / 7 + 7);
670 inner_i128(i128::MIN / 7 + 7);
671}
672
673#[mz_ore::test]
674#[cfg_attr(miri, ignore)] fn test_twos_complement_to_numeric_fail() {
676 fn inner(b: &mut [u8]) {
677 let r = twos_complement_be_to_numeric(b, 0);
678 mz_ore::assert_err!(r);
679 }
680 let mut e = [0xFF; Numeric::TWOS_COMPLEMENT_BYTE_WIDTH];
682 e[0] -= 0x80;
683 inner(&mut e);
684
685 let mut e = [0; Numeric::TWOS_COMPLEMENT_BYTE_WIDTH + 1];
687 e[0] = 1;
688 inner(&mut e);
689}
690
691#[mz_ore::test]
692#[cfg_attr(miri, ignore)] fn test_wide_twos_complement_roundtrip() {
694 fn inner(s: &str) {
695 let mut cx = cx_datum();
696 let d = cx.parse(s).unwrap();
697 let mut b = numeric_to_twos_complement_wide(d.clone());
698 let x = twos_complement_be_to_numeric(&mut b, NUMERIC_DATUM_MAX_PRECISION).unwrap();
699 assert_eq!(d, x);
700 }
701 inner("0");
702 inner("0.000000000000000000000000000000000012345");
703 inner("0.123456789012345678901234567890123456789");
704 inner("1.00000000000000000000000000000000000000");
705 inner("1");
706 inner("2");
707 inner("170141183460469231731687303715884105727");
708 inner("170141183460469231731687303715884105728");
709 inner("12345678901234567890.1234567890123456789");
710 inner("999999999999999999999999999999999999999");
711 inner("-0.000000000000000000000000000000000012345");
712 inner("-0.123456789012345678901234567890123456789");
713 inner("-1.00000000000000000000000000000000000000");
714 inner("-1");
715 inner("-2");
716 inner("-170141183460469231731687303715884105727");
717 inner("-170141183460469231731687303715884105728");
718 inner("-12345678901234567890.1234567890123456789");
719 inner("-999999999999999999999999999999999999999");
720}
721
722pub fn get_precision<const N: usize>(n: &Decimal<N>) -> u32 {
725 let e = n.exponent();
726 if e >= 0 {
727 n.digits() + u32::try_from(e).unwrap()
729 } else {
730 let d = n.digits();
732 let e = u32::try_from(e.abs()).unwrap();
733 std::cmp::max(d, e)
737 }
738}
739
740pub fn get_scale(n: &Numeric) -> u32 {
742 let exp = n.exponent();
743 if exp >= 0 { 0 } else { exp.unsigned_abs() }
744}
745
746pub fn munge_numeric(n: &mut Numeric) -> Result<(), anyhow::Error> {
753 rescale_within_max_precision(n)?;
754 if (n.is_zero() || n.is_nan()) && n.is_negative() {
755 cx_datum().neg(n);
756 }
757 Ok(())
758}
759
760fn rescale_within_max_precision(n: &mut Numeric) -> Result<(), anyhow::Error> {
763 let current_precision = get_precision(n);
764 if current_precision > u32::from(NUMERIC_DATUM_MAX_PRECISION) {
765 if n.exponent() < 0 {
766 let precision_diff = current_precision - u32::from(NUMERIC_DATUM_MAX_PRECISION);
767 let current_scale = u8::try_from(get_scale(n))?;
768 let scale_diff = current_scale - u8::try_from(precision_diff).unwrap();
769 rescale(n, scale_diff)?;
770 } else {
771 bail!(
772 "numeric value {} exceed maximum precision {}",
773 n,
774 NUMERIC_DATUM_MAX_PRECISION
775 )
776 }
777 }
778 Ok(())
779}
780
781pub fn rescale(n: &mut Numeric, scale: u8) -> Result<(), anyhow::Error> {
786 let mut cx = cx_datum();
787 cx.rescale(n, &Numeric::from(-i32::from(scale)));
788 if cx.status().invalid_operation() || get_precision(n) > u32::from(NUMERIC_DATUM_MAX_PRECISION)
789 {
790 bail!(
791 "numeric value {} exceed maximum precision {}",
792 n,
793 NUMERIC_DATUM_MAX_PRECISION
794 )
795 }
796 munge_numeric(n)?;
797
798 Ok(())
799}
800
801pub trait DecimalLike:
804 From<u8>
805 + From<u16>
806 + From<u32>
807 + From<i8>
808 + From<i16>
809 + From<i32>
810 + From<f32>
811 + From<f64>
812 + std::ops::Add<Output = Self>
813 + std::ops::Sub<Output = Self>
814 + std::ops::Mul<Output = Self>
815 + std::ops::Div<Output = Self>
816{
817 fn lossy_from(i: i64) -> Self;
820}
821
822impl DecimalLike for f64 {
823 #[allow(clippy::as_conversions)]
825 fn lossy_from(i: i64) -> Self {
826 i as f64
827 }
828}
829
830impl DecimalLike for Numeric {
831 fn lossy_from(i: i64) -> Self {
832 Numeric::from(i)
833 }
834}
835
836#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
841pub struct PackedNumeric(pub [u8; 40]);
842
843impl FixedSizeCodec<Numeric> for PackedNumeric {
844 const SIZE: usize = 40;
845
846 fn as_bytes(&self) -> &[u8] {
847 &self.0
848 }
849
850 fn from_bytes(slice: &[u8]) -> Result<Self, String> {
851 let buf: [u8; Self::SIZE] = slice.try_into().map_err(|_| {
852 format!(
853 "size for PackedNumeric is {} bytes, got {}",
854 Self::SIZE,
855 slice.len()
856 )
857 })?;
858 Ok(PackedNumeric(buf))
859 }
860
861 fn from_value(val: Numeric) -> PackedNumeric {
862 let (digits, exponent, bits, lsu) = val.to_raw_parts();
863
864 let mut buf = [0u8; 40];
865
866 buf[0..4].copy_from_slice(&digits.to_le_bytes());
867 buf[4..8].copy_from_slice(&exponent.to_le_bytes());
868
869 for i in 0..13 {
870 buf[(i * 2) + 8..(i * 2) + 10].copy_from_slice(&lsu[i].to_le_bytes());
871 }
872
873 buf[34..35].copy_from_slice(&bits.to_le_bytes());
874
875 PackedNumeric(buf)
876 }
877
878 fn into_value(self) -> Numeric {
879 let digits: [u8; 4] = self.0[0..4].try_into().unwrap();
880 let digits = u32::from_le_bytes(digits);
881
882 let exponent: [u8; 4] = self.0[4..8].try_into().unwrap();
883 let exponent = i32::from_le_bytes(exponent);
884
885 let mut lsu = [0u16; 13];
886 for i in 0..13 {
887 let x: [u8; 2] = self.0[(i * 2) + 8..(i * 2) + 10].try_into().unwrap();
888 let x = u16::from_le_bytes(x);
889 lsu[i] = x;
890 }
891
892 let bits: [u8; 1] = self.0[34..35].try_into().unwrap();
893 let bits = u8::from_le_bytes(bits);
894
895 Numeric::from_raw_parts(digits, exponent, bits, lsu)
896 }
897}
898
899mod columnar_impls {
900 use std::ops::Range;
901
902 use columnar::bytes::indexed::DecodedStore;
903 use columnar::{AsBytes, Borrow, Clear, Columnar, Container, FromBytes, Index, Len, Push};
904
905 use super::{NUMERIC_AGG_WIDTH_USIZE, NumericAgg, OrderedNumericAgg};
906
907 const LSU_COLUMN_WIDTH: usize = NUMERIC_AGG_WIDTH_USIZE + 1;
912 type Parts = (u32, i32, u8, [u16; LSU_COLUMN_WIDTH]);
915 type PartsContainer = (Vec<u32>, Vec<i32>, Vec<u8>, Vec<[u16; LSU_COLUMN_WIDTH]>);
919 type PartsBorrowed<'a> = <PartsContainer as Borrow>::Borrowed<'a>;
920
921 impl Columnar for OrderedNumericAgg {
922 #[inline(always)]
923 fn into_owned(other: columnar::Ref<'_, Self>) -> Self {
924 other
925 }
926 type Container = OrderedNumericAggs;
927 #[inline(always)]
928 fn reborrow<'b, 'a: 'b>(thing: columnar::Ref<'a, Self>) -> columnar::Ref<'b, Self>
929 where
930 Self: 'a,
931 {
932 thing
933 }
934 }
935
936 #[derive(Copy, Clone, Debug, Default)]
941 pub struct OrderedNumericAggs<TC = PartsContainer>(TC);
942
943 impl Borrow for OrderedNumericAggs {
944 type Ref<'a> = OrderedNumericAgg;
945 type Borrowed<'a> = OrderedNumericAggs<PartsBorrowed<'a>>;
946 #[inline(always)]
947 fn borrow<'a>(&'a self) -> Self::Borrowed<'a> {
948 OrderedNumericAggs(self.0.borrow())
949 }
950 #[inline(always)]
951 fn reborrow<'b, 'a: 'b>(item: Self::Borrowed<'a>) -> Self::Borrowed<'b>
952 where
953 Self: 'a,
954 {
955 OrderedNumericAggs(<PartsContainer as Borrow>::reborrow(item.0))
956 }
957 #[inline(always)]
958 fn reborrow_ref<'b, 'a: 'b>(item: Self::Ref<'a>) -> Self::Ref<'b>
959 where
960 Self: 'a,
961 {
962 item
963 }
964 }
965
966 impl Container for OrderedNumericAggs {
967 #[inline(always)]
968 fn extend_from_self(&mut self, other: Self::Borrowed<'_>, range: Range<usize>) {
969 self.0.extend_from_self(other.0, range);
970 }
971 #[inline(always)]
972 fn reserve_for<'a, I>(&mut self, selves: I)
973 where
974 Self: 'a,
975 I: Iterator<Item = Self::Borrowed<'a>> + Clone,
976 {
977 self.0.reserve_for(selves.map(|s| s.0));
978 }
979 }
980
981 impl<TC: Len> Len for OrderedNumericAggs<TC> {
982 #[inline(always)]
983 fn len(&self) -> usize {
984 self.0.len()
985 }
986 }
987
988 impl Clear for OrderedNumericAggs {
989 #[inline(always)]
990 fn clear(&mut self) {
991 self.0.clear();
992 }
993 }
994
995 impl<'a> Index for OrderedNumericAggs<PartsBorrowed<'a>> {
996 type Ref = OrderedNumericAgg;
997 #[inline(always)]
998 fn get(&self, index: usize) -> Self::Ref {
999 let (digits, exponent, bits, lsu) = self.0.get(index);
1000 let mut units = [0u16; NUMERIC_AGG_WIDTH_USIZE];
1001 units.copy_from_slice(&lsu[..NUMERIC_AGG_WIDTH_USIZE]);
1002 OrderedNumericAgg(NumericAgg::from_raw_parts(*digits, *exponent, *bits, units))
1003 }
1004 }
1005
1006 impl Push<OrderedNumericAgg> for OrderedNumericAggs {
1007 #[inline(always)]
1008 fn push(&mut self, item: OrderedNumericAgg) {
1009 let (digits, exponent, bits, units) = item.0.to_raw_parts();
1010 let mut lsu = [0u16; LSU_COLUMN_WIDTH];
1011 lsu[..NUMERIC_AGG_WIDTH_USIZE].copy_from_slice(&units);
1012 let parts: Parts = (digits, exponent, bits, lsu);
1013 self.0.push(parts);
1014 }
1015 }
1016
1017 impl Push<&OrderedNumericAgg> for OrderedNumericAggs {
1018 #[inline(always)]
1019 fn push(&mut self, item: &OrderedNumericAgg) {
1020 self.push(*item);
1021 }
1022 }
1023
1024 impl<'a, TC: AsBytes<'a>> AsBytes<'a> for OrderedNumericAggs<TC> {
1025 const SLICE_COUNT: usize = TC::SLICE_COUNT;
1026 #[inline(always)]
1027 fn get_byte_slice(&self, index: usize) -> (u64, &'a [u8]) {
1028 self.0.get_byte_slice(index)
1029 }
1030 }
1031
1032 impl<'a, TC: FromBytes<'a>> FromBytes<'a> for OrderedNumericAggs<TC> {
1033 const SLICE_COUNT: usize = TC::SLICE_COUNT;
1034 #[inline(always)]
1035 fn from_bytes(bytes: &mut impl Iterator<Item = &'a [u8]>) -> Self {
1036 OrderedNumericAggs(TC::from_bytes(bytes))
1037 }
1038 #[inline(always)]
1039 fn from_store(store: &DecodedStore<'a>, offset: &mut usize) -> Self {
1040 OrderedNumericAggs(TC::from_store(store, offset))
1041 }
1042 fn element_sizes(sizes: &mut Vec<usize>) -> Result<(), String> {
1043 TC::element_sizes(sizes)
1044 }
1045 }
1046}
1047
1048#[cfg(test)]
1049mod tests {
1050 use mz_ore::assert_ok;
1051 use mz_proto::protobuf_roundtrip;
1052 use proptest::prelude::*;
1053
1054 use crate::scalar::arb_numeric;
1055
1056 use super::*;
1057
1058 proptest! {
1059 #[mz_ore::test]
1060 fn numeric_max_scale_protobuf_roundtrip(expect in any::<NumericMaxScale>()) {
1061 let actual = protobuf_roundtrip::<_, ProtoNumericMaxScale>(&expect);
1062 assert_ok!(actual);
1063 assert_eq!(actual.unwrap(), expect);
1064 }
1065
1066 #[mz_ore::test]
1067 fn optional_numeric_max_scale_protobuf_roundtrip(
1068 expect in any::<Option<NumericMaxScale>>(),
1069 ) {
1070 let actual = protobuf_roundtrip::<_, ProtoOptionalNumericMaxScale>(&expect);
1071 assert_ok!(actual);
1072 assert_eq!(actual.unwrap(), expect);
1073 }
1074 }
1075
1076 #[mz_ore::test]
1077 #[cfg_attr(miri, ignore)] fn smoketest_packed_numeric_roundtrips() {
1079 let og = PackedNumeric::from_value(Numeric::from(-42));
1080 let bytes = og.as_bytes();
1081 let rnd = PackedNumeric::from_bytes(bytes).expect("valid");
1082 assert_eq!(og, rnd);
1083
1084 mz_ore::assert_err!(PackedNumeric::from_bytes(&[0, 0, 0, 0]));
1086 }
1087
1088 #[mz_ore::test]
1089 #[cfg_attr(miri, ignore)] fn proptest_packed_numeric_roundtrip() {
1091 fn test(og: Numeric) {
1092 let packed = PackedNumeric::from_value(og);
1093 let rnd = packed.into_value();
1094
1095 if og.is_nan() && rnd.is_nan() {
1096 return;
1097 }
1098 assert_eq!(og, rnd);
1099 }
1100
1101 proptest!(|(num in arb_numeric())| {
1102 test(num);
1103 });
1104 }
1105
1106 #[mz_ore::test]
1110 #[cfg_attr(miri, ignore)] fn packed_numeric_stability() {
1112 const RNG_SEED: [u8; 32] = [
1115 0xf4, 0x16, 0x16, 0x48, 0xc3, 0xac, 0x77, 0xac, 0x72, 0x20, 0x0b, 0xea, 0x99, 0x67,
1116 0x2d, 0x6d, 0xca, 0x9f, 0x76, 0xaf, 0x1b, 0x09, 0x73, 0xa0, 0x59, 0x22, 0x6d, 0xc5,
1117 0x46, 0x39, 0x1c, 0x4a,
1118 ];
1119
1120 let rng = proptest::test_runner::TestRng::from_seed(
1121 proptest::test_runner::RngAlgorithm::ChaCha,
1122 &RNG_SEED,
1123 );
1124 let config = proptest::test_runner::Config {
1126 cases: u32::MAX,
1128 rng_algorithm: proptest::test_runner::RngAlgorithm::ChaCha,
1129 ..Default::default()
1130 };
1131 let mut runner = proptest::test_runner::TestRunner::new_with_rng(config, rng);
1132
1133 let test_cases = 2_000;
1134 let strat = arb_numeric();
1135
1136 let mut all_numerics = Vec::new();
1137 for _ in 0..test_cases {
1138 let value_tree = strat.new_tree(&mut runner).unwrap();
1139 let numeric = value_tree.current();
1140 let packed = PackedNumeric::from_value(numeric);
1141 let hex_bytes = format!("{:x?}", packed.as_bytes());
1142
1143 all_numerics.push((numeric, hex_bytes));
1144 }
1145
1146 insta::assert_debug_snapshot!(all_numerics);
1147 }
1148
1149 #[mz_ore::test]
1150 fn ordered_numeric_agg_columnar_round_trip() {
1151 use columnar::{AsBytes, Borrow, BorrowedOf, Columnar, FromBytes, Index, Len};
1152
1153 let mut cx = cx_agg();
1154 let values: Vec<OrderedNumericAgg> = [
1155 "0",
1156 "-0",
1157 "1",
1158 "-12345.678",
1159 "9e39",
1160 "9e-39",
1161 "123456789012345678901234567890123456789012345678901234567890",
1162 "NaN",
1163 "Infinity",
1164 "-Infinity",
1165 ]
1166 .into_iter()
1167 .map(|s| OrderedNumericAgg(cx.parse(s).unwrap()))
1168 .collect();
1169
1170 let container = OrderedNumericAgg::as_columns(values.iter());
1171 assert_eq!(container.len(), values.len());
1172 let borrowed = container.borrow();
1173 for (index, value) in values.iter().enumerate() {
1174 assert_eq!(borrowed.get(index), *value);
1175 }
1176
1177 let bytes: Vec<&[u8]> = borrowed.as_bytes().map(|(_align, bytes)| bytes).collect();
1178 let decoded = BorrowedOf::<OrderedNumericAgg>::from_bytes(&mut bytes.into_iter());
1179 assert_eq!(decoded.len(), values.len());
1180 for (index, value) in values.iter().enumerate() {
1181 assert_eq!(decoded.get(index), *value);
1182 }
1183
1184 let mut words = Vec::new();
1187 columnar::bytes::indexed::encode(&mut words, &borrowed);
1188 columnar::bytes::indexed::validate::<BorrowedOf<OrderedNumericAgg>>(&words).unwrap();
1189 let store = columnar::bytes::indexed::DecodedStore::new(&words);
1190 let decoded = BorrowedOf::<OrderedNumericAgg>::from_store(&store, &mut 0);
1191 assert_eq!(decoded.len(), values.len());
1192 for (index, value) in values.iter().enumerate() {
1193 assert_eq!(decoded.get(index), *value);
1194 }
1195 }
1196}