1use std::borrow::Borrow;
16use std::cell::{Cell, RefCell};
17use std::cmp::Ordering;
18use std::convert::{TryFrom, TryInto};
19use std::fmt::{self, Debug};
20use std::hash::{Hash, Hasher};
21use std::marker::PhantomData;
22use std::mem::{size_of, transmute};
23use std::ops::Deref;
24use std::str;
25
26use chrono::{DateTime, Datelike, NaiveDate, NaiveDateTime, NaiveTime, Timelike, Utc};
27use compact_bytes::CompactBytes;
28use mz_ore::cast::{CastFrom, ReinterpretCast};
29use mz_ore::soft_assert_no_log;
30use mz_ore::vec::Vector;
31use mz_persist_types::Codec64;
32use num_enum::{IntoPrimitive, TryFromPrimitive};
33use ordered_float::OrderedFloat;
34#[cfg(any(test, feature = "proptest"))]
35use proptest::prelude::*;
36#[cfg(any(test, feature = "proptest"))]
37use proptest::strategy::{BoxedStrategy, Strategy};
38use serde::{Deserialize, Serialize};
39use uuid::Uuid;
40
41use crate::adt::array::{
42 Array, ArrayDimension, ArrayDimensions, InvalidArrayError, MAX_ARRAY_DIMENSIONS,
43};
44use crate::adt::date::Date;
45use crate::adt::interval::Interval;
46use crate::adt::mz_acl_item::{AclItem, MzAclItem};
47use crate::adt::numeric;
48use crate::adt::numeric::Numeric;
49use crate::adt::range::{
50 self, InvalidRangeError, Range, RangeBound, RangeInner, RangeLowerBound, RangeUpperBound,
51};
52use crate::adt::timestamp::CheckedTimestamp;
53#[cfg(any(test, feature = "proptest"))]
54use crate::scalar::arb_datum;
55use crate::scalar::{DatumKind, SqlScalarType};
56use crate::{Datum, RelationDesc, Timestamp};
57
58pub(crate) mod encode;
59pub mod iter;
60
61include!(concat!(env!("OUT_DIR"), "/mz_repr.row.rs"));
62
63#[derive(Default, Eq, PartialEq, Serialize, Deserialize)]
120pub struct Row {
121 data: CompactBytes,
122}
123
124impl Row {
125 const SIZE: usize = CompactBytes::MAX_INLINE;
126
127 pub fn decode_from_proto(
130 &mut self,
131 proto: &ProtoRow,
132 desc: &RelationDesc,
133 ) -> Result<(), String> {
134 let mut packer = self.packer();
135 for (col_idx, _, _) in desc.iter_all() {
136 let d = match proto.datums.get(col_idx.to_raw()) {
137 Some(x) => x,
138 None => {
139 packer.push(Datum::Null);
140 continue;
141 }
142 };
143 packer.try_push_proto(d)?;
144 }
145
146 Ok(())
147 }
148
149 #[inline]
151 pub fn with_capacity(cap: usize) -> Self {
152 Self {
153 data: CompactBytes::with_capacity(cap),
154 }
155 }
156
157 #[inline]
159 pub const fn empty() -> Self {
160 Self {
161 data: CompactBytes::empty(),
162 }
163 }
164
165 pub unsafe fn from_bytes_unchecked(data: &[u8]) -> Self {
172 Row {
173 data: CompactBytes::new(data),
174 }
175 }
176
177 pub fn packer(&mut self) -> RowPacker<'_> {
183 self.clear();
184 RowPacker { row: self }
185 }
186
187 pub fn pack<'a, I, D>(iter: I) -> Row
195 where
196 I: IntoIterator<Item = D>,
197 D: Borrow<Datum<'a>>,
198 {
199 let mut row = Row::default();
200 row.packer().extend(iter);
201 row
202 }
203
204 pub fn pack_using<'a, I, D>(&mut self, iter: I) -> Row
209 where
210 I: IntoIterator<Item = D>,
211 D: Borrow<Datum<'a>>,
212 {
213 self.packer().extend(iter);
214 self.clone()
215 }
216
217 pub fn try_pack<'a, I, D, E>(iter: I) -> Result<Row, E>
221 where
222 I: IntoIterator<Item = Result<D, E>>,
223 D: Borrow<Datum<'a>>,
224 {
225 let mut row = Row::default();
226 row.packer().try_extend(iter)?;
227 Ok(row)
228 }
229
230 pub fn pack_slice<'a>(slice: &[Datum<'a>]) -> Row {
236 let mut row = Row::with_capacity(datums_size(slice.iter()));
238 row.packer().extend(slice.iter());
239 row
240 }
241
242 pub fn byte_len(&self) -> usize {
244 let heap_size = if self.data.spilled() {
245 self.data.len()
246 } else {
247 0
248 };
249 let inline_size = std::mem::size_of::<Self>();
250 inline_size.saturating_add(heap_size)
251 }
252
253 pub fn data_len(&self) -> usize {
255 self.data.len()
256 }
257
258 pub fn byte_capacity(&self) -> usize {
260 self.data.capacity()
261 }
262
263 #[inline]
265 pub fn as_row_ref(&self) -> &RowRef {
266 unsafe { RowRef::from_slice(self.data.as_slice()) }
268 }
269
270 #[inline]
272 fn clear(&mut self) {
273 self.data.clear();
274 }
275}
276
277impl Borrow<RowRef> for Row {
278 #[inline]
279 fn borrow(&self) -> &RowRef {
280 self.as_row_ref()
281 }
282}
283
284impl AsRef<RowRef> for Row {
285 #[inline]
286 fn as_ref(&self) -> &RowRef {
287 self.as_row_ref()
288 }
289}
290
291impl Deref for Row {
292 type Target = RowRef;
293
294 #[inline]
295 fn deref(&self) -> &Self::Target {
296 self.as_row_ref()
297 }
298}
299
300static_assertions::const_assert_eq!(std::mem::size_of::<Row>(), 24);
302
303impl Clone for Row {
304 fn clone(&self) -> Self {
305 Row {
306 data: self.data.clone(),
307 }
308 }
309
310 fn clone_from(&mut self, source: &Self) {
311 self.data.clone_from(&source.data);
312 }
313}
314
315impl std::hash::Hash for Row {
317 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
318 self.as_row_ref().hash(state)
319 }
320}
321
322#[cfg(any(test, feature = "proptest"))]
323impl Arbitrary for Row {
324 type Parameters = prop::collection::SizeRange;
325 type Strategy = BoxedStrategy<Row>;
326
327 fn arbitrary_with(size: Self::Parameters) -> Self::Strategy {
328 prop::collection::vec(arb_datum(true), size)
329 .prop_map(|items| {
330 let mut row = Row::default();
331 let mut packer = row.packer();
332 for item in items.iter() {
333 let datum: Datum<'_> = item.into();
334 packer.push(datum);
335 }
336 row
337 })
338 .boxed()
339 }
340}
341
342impl PartialOrd for Row {
343 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
344 Some(self.cmp(other))
345 }
346}
347
348impl Ord for Row {
349 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
350 self.as_ref().cmp(other.as_ref())
351 }
352}
353
354#[derive(
363 Clone,
364 Default,
365 Eq,
366 PartialEq,
367 Ord,
368 PartialOrd,
369 Hash,
370 Serialize,
371 Deserialize
372)]
373pub struct StableRow(#[serde(with = "stable_row_proto")] pub Row);
374
375impl From<Row> for StableRow {
376 fn from(row: Row) -> Self {
377 StableRow(row)
378 }
379}
380
381impl Deref for StableRow {
382 type Target = Row;
383
384 fn deref(&self) -> &Row {
385 &self.0
386 }
387}
388
389impl Debug for StableRow {
390 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
391 self.0.fmt(f)
392 }
393}
394
395mod stable_row_proto {
396 use mz_proto::RustType;
397 use prost::Message;
398 use serde::de::Error;
399 use serde::{Deserialize, Deserializer, Serializer};
400
401 use crate::row::{ProtoRow, Row};
402
403 pub fn serialize<S: Serializer>(row: &Row, serializer: S) -> Result<S::Ok, S::Error> {
404 serializer.serialize_bytes(&row.into_proto().encode_to_vec())
405 }
406
407 pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Row, D::Error> {
408 let bytes = serde_bytes::ByteBuf::deserialize(deserializer)?;
409 let proto = ProtoRow::decode(bytes.as_slice()).map_err(D::Error::custom)?;
410 Row::from_proto(proto).map_err(D::Error::custom)
411 }
412}
413
414#[allow(missing_debug_implementations)]
415mod columnation {
416 use columnation::{Columnation, Region};
417 use mz_ore::region::LgAllocRegion;
418
419 use crate::Row;
420
421 pub struct RowStack {
426 region: LgAllocRegion<u8>,
427 }
428
429 impl RowStack {
430 const LIMIT: usize = 2 << 20;
431 }
432
433 impl Default for RowStack {
435 fn default() -> Self {
436 Self {
437 region: LgAllocRegion::with_limit(Self::LIMIT),
439 }
440 }
441 }
442
443 impl Columnation for Row {
444 type InnerRegion = RowStack;
445 }
446
447 impl Region for RowStack {
448 type Item = Row;
449 #[inline]
450 fn clear(&mut self) {
451 self.region.clear();
452 }
453 #[inline(always)]
454 unsafe fn copy(&mut self, item: &Row) -> Row {
455 if item.data.spilled() {
456 let bytes = self.region.copy_slice(&item.data[..]);
457 Row {
458 data: compact_bytes::CompactBytes::from_raw_parts(
459 bytes.as_mut_ptr(),
460 item.data.len(),
461 item.data.capacity(),
462 ),
463 }
464 } else {
465 item.clone()
466 }
467 }
468
469 fn reserve_items<'a, I>(&mut self, items: I)
470 where
471 Self: 'a,
472 I: Iterator<Item = &'a Self::Item> + Clone,
473 {
474 let size = items
475 .filter(|row| row.data.spilled())
476 .map(|row| row.data.len())
477 .sum();
478 let size = std::cmp::min(size, Self::LIMIT);
479 self.region.reserve(size);
480 }
481
482 fn reserve_regions<'a, I>(&mut self, regions: I)
483 where
484 Self: 'a,
485 I: Iterator<Item = &'a Self> + Clone,
486 {
487 let size = regions.map(|r| r.region.len()).sum();
488 let size = std::cmp::min(size, Self::LIMIT);
489 self.region.reserve(size);
490 }
491
492 fn heap_size(&self, callback: impl FnMut(usize, usize)) {
493 self.region.heap_size(callback)
494 }
495 }
496}
497
498mod columnar {
499 use columnar::common::PushIndexAs;
500 use columnar::{
501 AsBytes, Borrow, Clear, Columnar, Container, FromBytes, Index, IndexAs, Len, Push,
502 };
503 use mz_ore::cast::CastFrom;
504 use std::ops::Range;
505
506 use crate::{Row, RowRef};
507
508 #[derive(
509 Copy,
510 Clone,
511 Debug,
512 Default,
513 PartialEq,
514 serde::Serialize,
515 serde::Deserialize
516 )]
517 pub struct Rows<BC = Vec<u64>, VC = Vec<u8>> {
518 bounds: BC,
520 values: VC,
522 }
523
524 impl Columnar for Row {
525 #[inline(always)]
526 fn copy_from(&mut self, other: columnar::Ref<'_, Self>) {
527 self.clear();
528 self.data.extend_from_slice(other.data());
529 }
530 #[inline(always)]
531 fn into_owned(other: columnar::Ref<'_, Self>) -> Self {
532 other.to_owned()
533 }
534 type Container = Rows;
535 #[inline(always)]
536 fn reborrow<'b, 'a: 'b>(thing: columnar::Ref<'a, Self>) -> columnar::Ref<'b, Self>
537 where
538 Self: 'a,
539 {
540 thing
541 }
542 }
543
544 impl<BC: PushIndexAs<u64>> Borrow for Rows<BC, Vec<u8>> {
545 type Ref<'a> = &'a RowRef;
546 type Borrowed<'a>
547 = Rows<BC::Borrowed<'a>, &'a [u8]>
548 where
549 Self: 'a;
550 #[inline(always)]
551 fn borrow<'a>(&'a self) -> Self::Borrowed<'a> {
552 Rows {
553 bounds: self.bounds.borrow(),
554 values: self.values.borrow(),
555 }
556 }
557 #[inline(always)]
558 fn reborrow<'c, 'a: 'c>(item: Self::Borrowed<'a>) -> Self::Borrowed<'c>
559 where
560 Self: 'a,
561 {
562 Rows {
563 bounds: BC::reborrow(item.bounds),
564 values: item.values,
565 }
566 }
567
568 fn reborrow_ref<'b, 'a: 'b>(item: Self::Ref<'a>) -> Self::Ref<'b>
569 where
570 Self: 'a,
571 {
572 item
573 }
574 }
575
576 impl<BC: PushIndexAs<u64>> Container for Rows<BC, Vec<u8>> {
577 fn extend_from_self(&mut self, other: Self::Borrowed<'_>, range: Range<usize>) {
578 if !range.is_empty() {
579 let values_len: u64 = self.values.len().try_into().expect("must fit");
581
582 let other_lower = if range.start == 0 {
584 0
585 } else {
586 other.bounds.index_as(range.start - 1)
587 };
588 let other_upper = other.bounds.index_as(range.end - 1);
589 self.values.extend_from_self(
590 other.values,
591 usize::try_from(other_lower).expect("must fit")
592 ..usize::try_from(other_upper).expect("must fit"),
593 );
594
595 if values_len == other_lower {
597 self.bounds.extend_from_self(other.bounds, range);
598 } else {
599 for index in range {
600 let shifted = other.bounds.index_as(index) - other_lower + values_len;
601 self.bounds.push(&shifted)
602 }
603 }
604 }
605 }
606 fn reserve_for<'a, I>(&mut self, selves: I)
607 where
608 Self: 'a,
609 I: Iterator<Item = Self::Borrowed<'a>> + Clone,
610 {
611 self.bounds.reserve_for(selves.clone().map(|r| r.bounds));
612 self.values.reserve_for(selves.map(|r| r.values));
613 }
614 }
615
616 impl<'a, BC: AsBytes<'a>, VC: AsBytes<'a>> AsBytes<'a> for Rows<BC, VC> {
617 const SLICE_COUNT: usize = BC::SLICE_COUNT + VC::SLICE_COUNT;
618 #[inline(always)]
619 fn get_byte_slice(&self, index: usize) -> (u64, &'a [u8]) {
620 mz_ore::soft_assert_no_log!(index < Self::SLICE_COUNT);
621 if index < BC::SLICE_COUNT {
622 self.bounds.get_byte_slice(index)
623 } else {
624 self.values.get_byte_slice(index - BC::SLICE_COUNT)
625 }
626 }
627 }
628 impl<'a, BC: FromBytes<'a>, VC: FromBytes<'a>> FromBytes<'a> for Rows<BC, VC> {
629 const SLICE_COUNT: usize = BC::SLICE_COUNT + VC::SLICE_COUNT;
630 #[inline(always)]
631 fn from_bytes(bytes: &mut impl Iterator<Item = &'a [u8]>) -> Self {
632 Self {
633 bounds: FromBytes::from_bytes(bytes),
634 values: FromBytes::from_bytes(bytes),
635 }
636 }
637 }
638
639 impl<BC: Len, VC> Len for Rows<BC, VC> {
640 #[inline(always)]
641 fn len(&self) -> usize {
642 self.bounds.len()
643 }
644 }
645
646 impl<'a, BC: Len + IndexAs<u64>> Index for Rows<BC, &'a [u8]> {
647 type Ref = &'a RowRef;
648 #[inline(always)]
649 fn get(&self, index: usize) -> Self::Ref {
650 let lower = if index == 0 {
651 0
652 } else {
653 self.bounds.index_as(index - 1)
654 };
655 let upper = self.bounds.index_as(index);
656 let lower = usize::cast_from(lower);
657 let upper = usize::cast_from(upper);
658 unsafe { RowRef::from_slice(&self.values[lower..upper]) }
661 }
662 }
663 impl<'a, BC: Len + IndexAs<u64>> Index for &'a Rows<BC, Vec<u8>> {
664 type Ref = &'a RowRef;
665 #[inline(always)]
666 fn get(&self, index: usize) -> Self::Ref {
667 let lower = if index == 0 {
668 0
669 } else {
670 self.bounds.index_as(index - 1)
671 };
672 let upper = self.bounds.index_as(index);
673 let lower = usize::cast_from(lower);
674 let upper = usize::cast_from(upper);
675 unsafe { RowRef::from_slice(&self.values[lower..upper]) }
678 }
679 }
680
681 impl<BC: Push<u64>> Push<&Row> for Rows<BC> {
682 #[inline(always)]
683 fn push(&mut self, item: &Row) {
684 self.values.extend_from_slice(item.data.as_slice());
685 self.bounds.push(u64::cast_from(self.values.len()));
686 }
687 }
688 impl<BC: Push<u64>> Push<Row> for Rows<BC> {
689 #[inline(always)]
690 fn push(&mut self, item: Row) {
691 self.push(&item);
692 }
693 }
694 impl<BC: for<'a> Push<&'a u64>> Push<&RowRef> for Rows<BC> {
695 #[inline(always)]
696 fn push(&mut self, item: &RowRef) {
697 self.values.extend_from_slice(item.data());
698 self.bounds.push(&u64::cast_from(self.values.len()));
699 }
700 }
701 impl<BC: Clear, VC: Clear> Clear for Rows<BC, VC> {
702 #[inline(always)]
703 fn clear(&mut self) {
704 self.bounds.clear();
705 self.values.clear();
706 }
707 }
708}
709
710#[derive(PartialEq, Eq, Hash)]
714#[repr(transparent)]
715pub struct RowRef([u8]);
716
717impl RowRef {
718 pub unsafe fn from_slice(row: &[u8]) -> &RowRef {
725 #[allow(clippy::as_conversions)]
726 let ptr = row as *const [u8] as *const RowRef;
727 unsafe { &*ptr }
729 }
730
731 pub fn unpack(&self) -> Vec<Datum<'_>> {
733 let len = self.iter().count();
735 let mut vec = Vec::with_capacity(len);
736 vec.extend(self.iter());
737 vec
738 }
739
740 pub fn unpack_first(&self) -> Datum<'_> {
744 self.iter().next().unwrap()
745 }
746
747 pub fn iter(&self) -> DatumListIter<'_> {
749 DatumListIter { data: &self.0 }
750 }
751
752 pub fn byte_len(&self) -> usize {
754 self.0.len()
755 }
756
757 pub fn data(&self) -> &[u8] {
759 &self.0
760 }
761
762 pub fn is_empty(&self) -> bool {
764 self.0.is_empty()
765 }
766}
767
768impl ToOwned for RowRef {
769 type Owned = Row;
770
771 fn to_owned(&self) -> Self::Owned {
772 unsafe { Row::from_bytes_unchecked(&self.0) }
774 }
775}
776
777impl<'a> IntoIterator for &'a RowRef {
778 type Item = Datum<'a>;
779 type IntoIter = DatumListIter<'a>;
780
781 fn into_iter(self) -> DatumListIter<'a> {
782 DatumListIter { data: &self.0 }
783 }
784}
785
786impl PartialOrd for RowRef {
790 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
791 Some(self.cmp(other))
792 }
793}
794
795impl Ord for RowRef {
796 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
797 match self.0.len().cmp(&other.0.len()) {
798 std::cmp::Ordering::Less => std::cmp::Ordering::Less,
799 std::cmp::Ordering::Greater => std::cmp::Ordering::Greater,
800 std::cmp::Ordering::Equal => self.0.cmp(&other.0),
801 }
802 }
803}
804
805impl fmt::Debug for RowRef {
806 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
808 f.write_str("RowRef{")?;
809 f.debug_list().entries(&*self).finish()?;
810 f.write_str("}")
811 }
812}
813
814#[derive(Debug)]
822pub struct RowPacker<'a> {
823 row: &'a mut Row,
824}
825
826pub trait FromDatum<'a>:
837 Sized + PartialEq + std::borrow::Borrow<Datum<'a>> + sealed::Sealed
838{
839 fn from_datum(datum: Datum<'a>) -> Self;
840}
841
842mod sealed {
843 use crate::Datum;
844
845 pub trait Sealed {}
846 impl<'a> Sealed for Datum<'a> {}
847}
848
849impl<'a> FromDatum<'a> for Datum<'a> {
850 #[inline]
851 fn from_datum(datum: Datum<'a>) -> Self {
852 datum
853 }
854}
855
856#[derive(Debug, Clone)]
857pub struct DatumListIter<'a> {
858 data: &'a [u8],
859}
860
861#[derive(Debug, Clone)]
862pub struct DatumListTypedIter<'a, T> {
863 inner: DatumListIter<'a>,
864 _phantom: PhantomData<fn() -> T>,
865}
866
867#[derive(Debug, Clone)]
868pub struct DatumDictIter<'a> {
869 data: &'a [u8],
870 prev_key: Option<&'a str>,
871}
872
873#[derive(Debug, Clone)]
874pub struct DatumDictTypedIter<'a, T> {
875 inner: DatumDictIter<'a>,
876 _phantom: PhantomData<fn() -> T>,
877}
878
879#[derive(Debug)]
881pub struct RowArena {
882 inner: RefCell<Vec<Vec<u8>>>,
898 scratch: RefCell<Option<Vec<u8>>>,
906 budget: Option<usize>,
917 allocated: Cell<usize>,
918}
919
920pub struct DatumList<'a, T = Datum<'a>> {
934 data: &'a [u8],
936 _phantom: PhantomData<fn() -> T>,
937}
938
939impl<'a, T> DatumList<'a, T> {
940 pub(crate) fn new(data: &'a [u8]) -> Self {
943 DatumList {
944 data,
945 _phantom: PhantomData,
946 }
947 }
948}
949
950impl<'a, T> Clone for DatumList<'a, T> {
951 fn clone(&self) -> Self {
952 *self
953 }
954}
955
956impl<'a, T> Copy for DatumList<'a, T> {}
957
958impl<'a, T> Debug for DatumList<'a, T> {
959 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
960 f.debug_list().entries(self.iter()).finish()
961 }
962}
963
964impl<'a, T> PartialEq for DatumList<'a, T> {
965 #[inline(always)]
966 fn eq(&self, other: &DatumList<'a, T>) -> bool {
967 self.iter().eq(other.iter())
968 }
969}
970
971impl<'a, T> Eq for DatumList<'a, T> {}
972
973impl<'a, T> Hash for DatumList<'a, T> {
974 #[inline(always)]
975 fn hash<H: Hasher>(&self, state: &mut H) {
976 for d in self.iter() {
977 d.hash(state);
978 }
979 }
980}
981
982impl<T> Ord for DatumList<'_, T> {
983 #[inline(always)]
984 fn cmp(&self, other: &DatumList<'_, T>) -> Ordering {
985 mz_ore::stack::maybe_grow(|| self.iter().cmp(other.iter()))
987 }
988}
989
990impl<T> PartialOrd for DatumList<'_, T> {
991 #[inline(always)]
992 fn partial_cmp(&self, other: &DatumList<'_, T>) -> Option<Ordering> {
993 Some(self.cmp(other))
994 }
995}
996
997pub struct DatumMap<'a, T = Datum<'a>> {
1008 data: &'a [u8],
1010 _phantom: PhantomData<fn() -> T>,
1011}
1012
1013impl<'a, T> DatumMap<'a, T> {
1014 pub(crate) fn new(data: &'a [u8]) -> Self {
1017 DatumMap {
1018 data,
1019 _phantom: PhantomData,
1020 }
1021 }
1022}
1023
1024impl<'a, T> Clone for DatumMap<'a, T> {
1025 fn clone(&self) -> Self {
1026 *self
1027 }
1028}
1029
1030impl<'a, T> Copy for DatumMap<'a, T> {}
1031
1032impl<'a, T> PartialEq for DatumMap<'a, T> {
1033 #[inline(always)]
1034 fn eq(&self, other: &DatumMap<'a, T>) -> bool {
1035 self.iter().eq(other.iter())
1036 }
1037}
1038
1039impl<'a, T> Eq for DatumMap<'a, T> {}
1040
1041impl<'a, T> Hash for DatumMap<'a, T> {
1042 #[inline(always)]
1043 fn hash<H: Hasher>(&self, state: &mut H) {
1044 for (k, v) in self.iter() {
1045 k.hash(state);
1046 v.hash(state);
1047 }
1048 }
1049}
1050
1051impl<'a, T> Ord for DatumMap<'a, T> {
1052 #[inline(always)]
1053 fn cmp(&self, other: &DatumMap<'a, T>) -> Ordering {
1054 mz_ore::stack::maybe_grow(|| self.iter().cmp(other.iter()))
1056 }
1057}
1058
1059impl<'a, T> PartialOrd for DatumMap<'a, T> {
1060 #[inline(always)]
1061 fn partial_cmp(&self, other: &DatumMap<'a, T>) -> Option<Ordering> {
1062 Some(self.cmp(other))
1063 }
1064}
1065
1066impl<'a> crate::scalar::SqlContainerType for DatumList<'a, Datum<'a>> {
1067 fn unwrap_element_type(container: &SqlScalarType) -> &SqlScalarType {
1068 container.unwrap_list_element_type()
1069 }
1070 fn wrap_element_type(element: SqlScalarType) -> SqlScalarType {
1071 SqlScalarType::List {
1072 element_type: Box::new(element),
1073 custom_id: None,
1074 }
1075 }
1076}
1077
1078impl<'a> crate::scalar::SqlContainerType for DatumMap<'a, Datum<'a>> {
1079 fn unwrap_element_type(container: &SqlScalarType) -> &SqlScalarType {
1080 container.unwrap_map_value_type()
1081 }
1082 fn wrap_element_type(element: SqlScalarType) -> SqlScalarType {
1083 SqlScalarType::Map {
1084 value_type: Box::new(element),
1085 custom_id: None,
1086 }
1087 }
1088}
1089
1090#[derive(Clone, Copy, Eq, PartialEq, Hash)]
1093pub struct DatumNested<'a> {
1094 val: &'a [u8],
1095}
1096
1097impl<'a> std::fmt::Display for DatumNested<'a> {
1098 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1099 std::fmt::Display::fmt(&self.datum(), f)
1100 }
1101}
1102
1103impl<'a> std::fmt::Debug for DatumNested<'a> {
1104 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1105 f.debug_struct("DatumNested")
1106 .field("val", &self.datum())
1107 .finish()
1108 }
1109}
1110
1111impl<'a> DatumNested<'a> {
1112 pub fn extract(data: &mut &'a [u8]) -> DatumNested<'a> {
1116 let prev = *data;
1117 let _ = unsafe { read_datum(data) };
1118 DatumNested {
1119 val: &prev[..(prev.len() - data.len())],
1120 }
1121 }
1122
1123 pub fn datum(&self) -> Datum<'a> {
1125 let mut temp = self.val;
1126 unsafe { read_datum(&mut temp) }
1127 }
1128}
1129
1130impl<'a> Ord for DatumNested<'a> {
1131 fn cmp(&self, other: &Self) -> Ordering {
1132 mz_ore::stack::maybe_grow(|| self.datum().cmp(&other.datum()))
1134 }
1135}
1136
1137impl<'a> PartialOrd for DatumNested<'a> {
1138 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1139 Some(self.cmp(other))
1140 }
1141}
1142
1143#[derive(Debug, Clone, Copy, PartialEq, Eq, IntoPrimitive, TryFromPrimitive)]
1147#[repr(u8)]
1148enum Tag {
1149 Null,
1150 False,
1151 True,
1152 Float32,
1153 Float64,
1154 Date,
1155 Time,
1156 Timestamp,
1157 TimestampTz,
1158 Interval,
1159 BytesTiny,
1164 BytesShort,
1165 BytesLong,
1166 BytesHuge,
1167 StringTiny,
1168 StringShort,
1169 StringLong,
1170 StringHuge,
1171 ListTiny,
1172 ListShort,
1173 ListLong,
1174 ListHuge,
1175 Uuid,
1176 Array,
1177 Dict,
1178 JsonNull,
1179 Dummy,
1180 Numeric,
1181 MzTimestamp,
1182 Range,
1183 MzAclItem,
1184 AclItem,
1185 CheapTimestamp,
1189 CheapTimestampTz,
1193 NonNegativeInt16_0, NegativeInt16_0, NonNegativeInt16_8,
1215 NegativeInt16_8,
1216 Int16,
1217
1218 NonNegativeInt32_0,
1219 NegativeInt32_0,
1220 NonNegativeInt32_8,
1221 NegativeInt32_8,
1222 NonNegativeInt32_16,
1223 NegativeInt32_16,
1224 NonNegativeInt32_24,
1225 NegativeInt32_24,
1226 Int32,
1227
1228 NonNegativeInt64_0,
1229 NegativeInt64_0,
1230 NonNegativeInt64_8,
1231 NegativeInt64_8,
1232 NonNegativeInt64_16,
1233 NegativeInt64_16,
1234 NonNegativeInt64_24,
1235 NegativeInt64_24,
1236 NonNegativeInt64_32,
1237 NegativeInt64_32,
1238 NonNegativeInt64_40,
1239 NegativeInt64_40,
1240 NonNegativeInt64_48,
1241 NegativeInt64_48,
1242 NonNegativeInt64_56,
1243 NegativeInt64_56,
1244 Int64,
1245
1246 UInt8_0, UInt8,
1251
1252 UInt16_0,
1253 UInt16_8,
1254 UInt16,
1255
1256 UInt32_0,
1257 UInt32_8,
1258 UInt32_16,
1259 UInt32_24,
1260 UInt32,
1261
1262 UInt64_0,
1263 UInt64_8,
1264 UInt64_16,
1265 UInt64_24,
1266 UInt64_32,
1267 UInt64_40,
1268 UInt64_48,
1269 UInt64_56,
1270 UInt64,
1271}
1272
1273impl Tag {
1274 #[allow(clippy::as_conversions)]
1276 const fn byte(self) -> u8 {
1277 self as u8
1278 }
1279}
1280
1281macro_rules! assert_consecutive {
1289 ($($tag:ident),+ $(,)?) => {
1290 const _: () = {
1291 let tags: &[u8] = &[$(Tag::$tag.byte()),+];
1292 let mut i = 1;
1293 while i < tags.len() {
1294 assert!(
1295 tags[i] == tags[i - 1] + 1,
1296 concat!("tags are not consecutive: ", stringify!($($tag),+))
1297 );
1298 i += 1;
1299 }
1300 };
1301 };
1302}
1303
1304assert_consecutive!(BytesTiny, BytesShort, BytesLong, BytesHuge);
1305assert_consecutive!(StringTiny, StringShort, StringLong, StringHuge);
1306assert_consecutive!(ListTiny, ListShort, ListLong, ListHuge);
1307assert_consecutive!(
1308 NonNegativeInt16_0,
1309 NegativeInt16_0,
1310 NonNegativeInt16_8,
1311 NegativeInt16_8,
1312 Int16,
1313);
1314assert_consecutive!(
1315 NonNegativeInt32_0,
1316 NegativeInt32_0,
1317 NonNegativeInt32_8,
1318 NegativeInt32_8,
1319 NonNegativeInt32_16,
1320 NegativeInt32_16,
1321 NonNegativeInt32_24,
1322 NegativeInt32_24,
1323 Int32,
1324);
1325assert_consecutive!(
1326 NonNegativeInt64_0,
1327 NegativeInt64_0,
1328 NonNegativeInt64_8,
1329 NegativeInt64_8,
1330 NonNegativeInt64_16,
1331 NegativeInt64_16,
1332 NonNegativeInt64_24,
1333 NegativeInt64_24,
1334 NonNegativeInt64_32,
1335 NegativeInt64_32,
1336 NonNegativeInt64_40,
1337 NegativeInt64_40,
1338 NonNegativeInt64_48,
1339 NegativeInt64_48,
1340 NonNegativeInt64_56,
1341 NegativeInt64_56,
1342 Int64,
1343);
1344assert_consecutive!(UInt8_0, UInt8,);
1345assert_consecutive!(UInt16_0, UInt16_8, UInt16,);
1346assert_consecutive!(UInt32_0, UInt32_8, UInt32_16, UInt32_24, UInt32,);
1347assert_consecutive!(
1348 UInt64_0, UInt64_8, UInt64_16, UInt64_24, UInt64_32, UInt64_40, UInt64_48, UInt64_56, UInt64,
1349);
1350
1351fn read_untagged_bytes<'a>(data: &mut &'a [u8]) -> &'a [u8] {
1358 let len = u64::from_le_bytes(read_byte_array(data));
1359 let len = usize::cast_from(len);
1360 let (bytes, next) = data.split_at(len);
1361 *data = next;
1362 bytes
1363}
1364
1365#[inline(always)]
1376fn read_lengthed_bytes<'a>(data: &mut &'a [u8], tag: Tag, first: Tag) -> &'a [u8] {
1377 let len = match u8::from(tag).wrapping_sub(u8::from(first)) {
1378 0 => usize::from(read_byte(data)),
1379 1 => usize::from(u16::from_le_bytes(read_byte_array(data))),
1380 2 => usize::cast_from(u32::from_le_bytes(read_byte_array(data))),
1381 _ => usize::cast_from(u64::from_le_bytes(read_byte_array(data))),
1382 };
1383 let (bytes, next) = data.split_at(len);
1384 *data = next;
1385 bytes
1386}
1387
1388#[inline(always)]
1389fn read_byte(data: &mut &[u8]) -> u8 {
1390 let byte = data[0];
1391 *data = &data[1..];
1392 byte
1393}
1394
1395#[cold]
1400#[inline(never)]
1401fn read_varint_word_tail(data: &[u8], len: usize) -> u64 {
1402 #[inline(always)]
1403 fn ext<const L: usize>(data: &[u8]) -> u64 {
1404 let mut raw = [0; 8];
1405 raw[..L].copy_from_slice(&data[..L]);
1406 u64::from_le_bytes(raw)
1407 }
1408 match len {
1411 0 => 0,
1412 1 => u64::from(data[0]),
1413 2 => ext::<2>(data),
1414 3 => ext::<3>(data),
1415 4 => ext::<4>(data),
1416 5 => ext::<5>(data),
1417 6 => ext::<6>(data),
1418 7 => ext::<7>(data),
1419 _ => panic!("payload runs past the end of the row"),
1422 }
1423}
1424
1425#[inline(always)]
1432fn read_varint_word(data: &mut &[u8], len: usize) -> u64 {
1433 let word = match data.first_chunk::<8>() {
1434 Some(chunk) => u64::from_le_bytes(*chunk),
1435 None => read_varint_word_tail(data, len),
1436 };
1437 *data = &data[len..];
1438 word
1439}
1440
1441#[inline(always)]
1446fn payload_mask(len: usize) -> u64 {
1447 if len >= 8 {
1448 u64::MAX
1449 } else {
1450 (1u64 << (len * 8)) - 1
1451 }
1452}
1453
1454#[inline(always)]
1456fn truncate<const N: usize>(word: u64) -> [u8; N] {
1457 word.to_le_bytes()[..N].try_into().expect("N <= 8")
1458}
1459
1460#[inline(always)]
1471fn read_signed_varint<const N: usize>(data: &mut &[u8], tag: Tag, first: Tag) -> [u8; N] {
1472 let delta = u8::from(tag).wrapping_sub(u8::from(first));
1473 let len = usize::from(delta >> 1);
1474 let negative = delta & 1 == 1;
1477 read_varint_payload(data, len, negative)
1478}
1479
1480#[inline(always)]
1485fn read_varint_payload<const N: usize>(data: &mut &[u8], len: usize, negative: bool) -> [u8; N] {
1486 let mask = payload_mask(len);
1487 let fill = 0u64.wrapping_sub(u64::from(negative));
1488 truncate((read_varint_word(data, len) & mask) | (fill & !mask))
1489}
1490
1491#[inline(always)]
1499fn read_unsigned_varint<const N: usize>(data: &mut &[u8], tag: Tag, first: Tag) -> [u8; N] {
1500 let len = usize::from(u8::from(tag).wrapping_sub(u8::from(first)));
1501 read_varint_payload(data, len, false)
1502}
1503
1504#[inline(always)]
1505pub(super) fn read_byte_array<const N: usize>(data: &mut &[u8]) -> [u8; N] {
1506 let (prev, next) = data.split_first_chunk().unwrap();
1507 *data = next;
1508 *prev
1509}
1510
1511pub(super) fn read_date(data: &mut &[u8]) -> Date {
1512 let days = i32::from_le_bytes(read_byte_array(data));
1513 Date::from_pg_epoch(days).expect("unexpected date")
1514}
1515
1516pub(super) fn read_naive_date(data: &mut &[u8]) -> NaiveDate {
1517 let year = i32::from_le_bytes(read_byte_array(data));
1518 let ordinal = u32::from_le_bytes(read_byte_array(data));
1519 NaiveDate::from_yo_opt(year, ordinal).unwrap()
1520}
1521
1522pub(super) fn read_time(data: &mut &[u8]) -> NaiveTime {
1523 let secs = u32::from_le_bytes(read_byte_array(data));
1524 let nanos = u32::from_le_bytes(read_byte_array(data));
1525 NaiveTime::from_num_seconds_from_midnight_opt(secs, nanos).unwrap()
1526}
1527
1528pub unsafe fn read_datum<'a>(data: &mut &'a [u8]) -> Datum<'a> {
1537 let tag = Tag::try_from_primitive(read_byte(data)).expect("unknown row tag");
1538 match tag {
1539 Tag::Null => Datum::Null,
1540 Tag::False => Datum::False,
1541 Tag::True => Datum::True,
1542 Tag::NonNegativeInt16_0
1543 | Tag::NegativeInt16_0
1544 | Tag::NonNegativeInt16_8
1545 | Tag::NegativeInt16_8
1546 | Tag::Int16 => Datum::Int16(i16::from_le_bytes(read_signed_varint(
1547 data,
1548 tag,
1549 Tag::NonNegativeInt16_0,
1550 ))),
1551 Tag::NonNegativeInt32_0
1552 | Tag::NegativeInt32_0
1553 | Tag::NonNegativeInt32_8
1554 | Tag::NegativeInt32_8
1555 | Tag::NonNegativeInt32_16
1556 | Tag::NegativeInt32_16
1557 | Tag::NonNegativeInt32_24
1558 | Tag::NegativeInt32_24
1559 | Tag::Int32 => Datum::Int32(i32::from_le_bytes(read_signed_varint(
1560 data,
1561 tag,
1562 Tag::NonNegativeInt32_0,
1563 ))),
1564 Tag::NonNegativeInt64_0
1565 | Tag::NegativeInt64_0
1566 | Tag::NonNegativeInt64_8
1567 | Tag::NegativeInt64_8
1568 | Tag::NonNegativeInt64_16
1569 | Tag::NegativeInt64_16
1570 | Tag::NonNegativeInt64_24
1571 | Tag::NegativeInt64_24
1572 | Tag::NonNegativeInt64_32
1573 | Tag::NegativeInt64_32
1574 | Tag::NonNegativeInt64_40
1575 | Tag::NegativeInt64_40
1576 | Tag::NonNegativeInt64_48
1577 | Tag::NegativeInt64_48
1578 | Tag::NonNegativeInt64_56
1579 | Tag::NegativeInt64_56
1580 | Tag::Int64 => Datum::Int64(i64::from_le_bytes(read_signed_varint(
1581 data,
1582 tag,
1583 Tag::NonNegativeInt64_0,
1584 ))),
1585 Tag::UInt8_0 | Tag::UInt8 => Datum::UInt8(u8::from_le_bytes(read_unsigned_varint(
1586 data,
1587 tag,
1588 Tag::UInt8_0,
1589 ))),
1590 Tag::UInt16_0 | Tag::UInt16_8 | Tag::UInt16 => Datum::UInt16(u16::from_le_bytes(
1591 read_unsigned_varint(data, tag, Tag::UInt16_0),
1592 )),
1593 Tag::UInt32_0 | Tag::UInt32_8 | Tag::UInt32_16 | Tag::UInt32_24 | Tag::UInt32 => {
1594 Datum::UInt32(u32::from_le_bytes(read_unsigned_varint(
1595 data,
1596 tag,
1597 Tag::UInt32_0,
1598 )))
1599 }
1600 Tag::UInt64_0
1601 | Tag::UInt64_8
1602 | Tag::UInt64_16
1603 | Tag::UInt64_24
1604 | Tag::UInt64_32
1605 | Tag::UInt64_40
1606 | Tag::UInt64_48
1607 | Tag::UInt64_56
1608 | Tag::UInt64 => Datum::UInt64(u64::from_le_bytes(read_unsigned_varint(
1609 data,
1610 tag,
1611 Tag::UInt64_0,
1612 ))),
1613
1614 Tag::Float32 => {
1615 let f = f32::from_bits(u32::from_le_bytes(read_byte_array(data)));
1616 Datum::Float32(OrderedFloat::from(f))
1617 }
1618 Tag::Float64 => {
1619 let f = f64::from_bits(u64::from_le_bytes(read_byte_array(data)));
1620 Datum::Float64(OrderedFloat::from(f))
1621 }
1622 Tag::Date => Datum::Date(read_date(data)),
1623 Tag::Time => Datum::Time(read_time(data)),
1624 Tag::CheapTimestamp => {
1625 let ts = i64::from_le_bytes(read_byte_array(data));
1626 let secs = ts.div_euclid(1_000_000_000);
1627 let nsecs: u32 = ts.rem_euclid(1_000_000_000).try_into().unwrap();
1628 let ndt = DateTime::from_timestamp(secs, nsecs)
1629 .expect("We only write round-trippable timestamps")
1630 .naive_utc();
1631 Datum::Timestamp(
1632 CheckedTimestamp::from_timestamplike(ndt).expect("unexpected timestamp"),
1633 )
1634 }
1635 Tag::CheapTimestampTz => {
1636 let ts = i64::from_le_bytes(read_byte_array(data));
1637 let secs = ts.div_euclid(1_000_000_000);
1638 let nsecs: u32 = ts.rem_euclid(1_000_000_000).try_into().unwrap();
1639 let dt = DateTime::from_timestamp(secs, nsecs)
1640 .expect("We only write round-trippable timestamps");
1641 Datum::TimestampTz(
1642 CheckedTimestamp::from_timestamplike(dt).expect("unexpected timestamp"),
1643 )
1644 }
1645 Tag::Timestamp => {
1646 let date = read_naive_date(data);
1647 let time = read_time(data);
1648 Datum::Timestamp(
1649 CheckedTimestamp::from_timestamplike(date.and_time(time))
1650 .expect("unexpected timestamp"),
1651 )
1652 }
1653 Tag::TimestampTz => {
1654 let date = read_naive_date(data);
1655 let time = read_time(data);
1656 Datum::TimestampTz(
1657 CheckedTimestamp::from_timestamplike(DateTime::from_naive_utc_and_offset(
1658 date.and_time(time),
1659 Utc,
1660 ))
1661 .expect("unexpected timestamptz"),
1662 )
1663 }
1664 Tag::Interval => {
1665 let months = i32::from_le_bytes(read_byte_array(data));
1666 let days = i32::from_le_bytes(read_byte_array(data));
1667 let micros = i64::from_le_bytes(read_byte_array(data));
1668 Datum::Interval(Interval {
1669 months,
1670 days,
1671 micros,
1672 })
1673 }
1674 Tag::BytesTiny | Tag::BytesShort | Tag::BytesLong | Tag::BytesHuge => {
1675 Datum::Bytes(read_lengthed_bytes(data, tag, Tag::BytesTiny))
1676 }
1677 Tag::StringTiny | Tag::StringShort | Tag::StringLong | Tag::StringHuge => {
1678 Datum::String(str::from_utf8_unchecked(read_lengthed_bytes(
1680 data,
1681 tag,
1682 Tag::StringTiny,
1683 )))
1684 }
1685 Tag::ListTiny | Tag::ListShort | Tag::ListLong | Tag::ListHuge => Datum::List(
1686 DatumList::new(read_lengthed_bytes(data, tag, Tag::ListTiny)),
1687 ),
1688 Tag::Uuid => Datum::Uuid(Uuid::from_bytes(read_byte_array(data))),
1689 Tag::Array => {
1690 let ndims = read_byte(data);
1693 let dims_size = usize::from(ndims) * size_of::<u64>() * 2;
1694 let (dims, next) = data.split_at(dims_size);
1695 *data = next;
1696 let bytes = read_untagged_bytes(data);
1697 Datum::Array(Array {
1698 dims: ArrayDimensions { data: dims },
1699 elements: DatumList::new(bytes),
1700 })
1701 }
1702 Tag::Dict => {
1703 let bytes = read_untagged_bytes(data);
1704 Datum::Map(DatumMap::new(bytes))
1705 }
1706 Tag::JsonNull => Datum::JsonNull,
1707 Tag::Dummy => Datum::Dummy,
1708 Tag::Numeric => {
1709 let digits = read_byte(data).into();
1710 let exponent = i8::reinterpret_cast(read_byte(data));
1711 let bits = read_byte(data);
1712
1713 let lsu_u16_len = Numeric::digits_to_lsu_elements_len(digits);
1714 let lsu_u8_len = lsu_u16_len * 2;
1715 let (lsu_u8, next) = data.split_at(lsu_u8_len);
1716 *data = next;
1717
1718 let mut lsu = [0; numeric::NUMERIC_DATUM_WIDTH_USIZE];
1722 for (i, c) in lsu_u8.chunks(2).enumerate() {
1723 lsu[i] = u16::from_le_bytes(c.try_into().unwrap());
1724 }
1725
1726 let d = Numeric::from_raw_parts(digits, exponent.into(), bits, lsu);
1727 Datum::from(d)
1728 }
1729 Tag::MzTimestamp => {
1730 let t = Timestamp::decode(read_byte_array(data));
1731 Datum::MzTimestamp(t)
1732 }
1733 Tag::Range => {
1734 let flag_byte = read_byte(data);
1736 let flags = range::InternalFlags::from_bits(flag_byte)
1737 .expect("range flags must be encoded validly");
1738
1739 if flags.contains(range::InternalFlags::EMPTY) {
1740 assert!(
1741 flags == range::InternalFlags::EMPTY,
1742 "empty ranges contain only RANGE_EMPTY flag"
1743 );
1744
1745 return Datum::Range(Range { inner: None });
1746 }
1747
1748 let lower_bound = if flags.contains(range::InternalFlags::LB_INFINITE) {
1749 None
1750 } else {
1751 Some(DatumNested::extract(data))
1752 };
1753
1754 let lower = RangeBound {
1755 inclusive: flags.contains(range::InternalFlags::LB_INCLUSIVE),
1756 bound: lower_bound,
1757 };
1758
1759 let upper_bound = if flags.contains(range::InternalFlags::UB_INFINITE) {
1760 None
1761 } else {
1762 Some(DatumNested::extract(data))
1763 };
1764
1765 let upper = RangeBound {
1766 inclusive: flags.contains(range::InternalFlags::UB_INCLUSIVE),
1767 bound: upper_bound,
1768 };
1769
1770 Datum::Range(Range {
1771 inner: Some(RangeInner { lower, upper }),
1772 })
1773 }
1774 Tag::MzAclItem => {
1775 const N: usize = MzAclItem::binary_size();
1776 let mz_acl_item =
1777 MzAclItem::decode_binary(&read_byte_array::<N>(data)).expect("invalid mz_aclitem");
1778 Datum::MzAclItem(mz_acl_item)
1779 }
1780 Tag::AclItem => {
1781 const N: usize = AclItem::binary_size();
1782 let acl_item =
1783 AclItem::decode_binary(&read_byte_array::<N>(data)).expect("invalid aclitem");
1784 Datum::AclItem(acl_item)
1785 }
1786 }
1787}
1788
1789fn push_untagged_bytes<D>(data: &mut D, bytes: &[u8])
1793where
1794 D: Vector<u8>,
1795{
1796 let len = u64::cast_from(bytes.len());
1797 data.extend_from_slice(&len.to_le_bytes());
1798 data.extend_from_slice(bytes);
1799}
1800
1801fn push_lengthed_bytes<D>(data: &mut D, bytes: &[u8], tag: Tag)
1803where
1804 D: Vector<u8>,
1805{
1806 let len = bytes.len().to_le_bytes();
1807 match tag {
1808 Tag::BytesTiny | Tag::StringTiny | Tag::ListTiny => {
1809 data.extend_from_slice(&[tag.into(), len[0]]);
1810 }
1811 Tag::BytesShort | Tag::StringShort | Tag::ListShort => {
1812 data.extend_from_slice(&[tag.into(), len[0], len[1]]);
1813 }
1814 Tag::BytesLong | Tag::StringLong | Tag::ListLong => {
1815 data.push(tag.into());
1816 data.extend_from_slice(&len[0..4]);
1817 }
1818 Tag::BytesHuge | Tag::StringHuge | Tag::ListHuge => {
1819 data.push(tag.into());
1820 data.extend_from_slice(&len);
1821 }
1822 _ => unreachable!(),
1823 }
1824 data.extend_from_slice(bytes);
1825}
1826
1827pub(super) fn date_to_array(date: Date) -> [u8; size_of::<i32>()] {
1828 i32::to_le_bytes(date.pg_epoch_days())
1829}
1830
1831fn push_date<D>(data: &mut D, date: Date)
1832where
1833 D: Vector<u8>,
1834{
1835 data.extend_from_slice(&date_to_array(date));
1836}
1837
1838pub(super) fn naive_date_to_arrays(
1839 date: NaiveDate,
1840) -> ([u8; size_of::<i32>()], [u8; size_of::<u32>()]) {
1841 (
1842 i32::to_le_bytes(date.year()),
1843 u32::to_le_bytes(date.ordinal()),
1844 )
1845}
1846
1847fn push_naive_date<D>(data: &mut D, date: NaiveDate)
1848where
1849 D: Vector<u8>,
1850{
1851 let (ds1, ds2) = naive_date_to_arrays(date);
1852 data.extend_from_slice(&ds1);
1853 data.extend_from_slice(&ds2);
1854}
1855
1856pub(super) fn time_to_arrays(time: NaiveTime) -> ([u8; size_of::<u32>()], [u8; size_of::<u32>()]) {
1857 (
1858 u32::to_le_bytes(time.num_seconds_from_midnight()),
1859 u32::to_le_bytes(time.nanosecond()),
1860 )
1861}
1862
1863fn push_time<D>(data: &mut D, time: NaiveTime)
1864where
1865 D: Vector<u8>,
1866{
1867 let (ts1, ts2) = time_to_arrays(time);
1868 data.extend_from_slice(&ts1);
1869 data.extend_from_slice(&ts2);
1870}
1871
1872fn checked_timestamp_nanos(dt: NaiveDateTime) -> Option<i64> {
1882 let subsec_nanos = dt.and_utc().timestamp_subsec_nanos();
1883 if subsec_nanos >= 1_000_000_000 {
1884 return None;
1885 }
1886 let as_ns = dt.and_utc().timestamp().checked_mul(1_000_000_000)?;
1887 as_ns.checked_add(i64::from(subsec_nanos))
1888}
1889
1890#[inline(always)]
1896#[allow(clippy::as_conversions)]
1897fn min_bytes_signed<T>(i: T) -> u8
1898where
1899 T: Into<i64>,
1900{
1901 let i: i64 = i.into();
1902
1903 let n_sign_bits = if i.is_negative() {
1907 i.leading_ones() as u8
1908 } else {
1909 i.leading_zeros() as u8
1910 };
1911
1912 (64 - n_sign_bits + 7) / 8
1913}
1914
1915#[inline(always)]
1923#[allow(clippy::as_conversions)]
1924fn min_bytes_unsigned<T>(i: T) -> u8
1925where
1926 T: Into<u64>,
1927{
1928 let i: u64 = i.into();
1929
1930 let n_sign_bits = i.leading_zeros() as u8;
1931
1932 (64 - n_sign_bits + 7) / 8
1933}
1934
1935const TINY: usize = 1 << 8;
1936const SHORT: usize = 1 << 16;
1937const LONG: usize = 1 << 32;
1938
1939#[inline(always)]
1941fn push_tagged<D, const N: usize>(data: &mut D, tag: u8, payload: &[u8; N], len: usize)
1942where
1943 D: Vector<u8>,
1944{
1945 const { assert!(N <= 16) };
1946 debug_assert!(len <= N, "payload of {N} bytes is shorter than {len}");
1947 let mut buf = [0; 17];
1950 buf[0] = tag;
1951 buf[1..][..N].copy_from_slice(payload);
1952 data.extend_from_slice(&buf[..1 + len]);
1953}
1954
1955fn push_datum<D>(data: &mut D, datum: Datum)
1956where
1957 D: Vector<u8>,
1958{
1959 match datum {
1960 Datum::Null => data.push(Tag::Null.into()),
1961 Datum::False => data.push(Tag::False.into()),
1962 Datum::True => data.push(Tag::True.into()),
1963 Datum::Int16(i) => {
1964 const WIDEST_DELTA: u8 = Tag::Int16.byte() - Tag::NonNegativeInt16_0.byte();
1968 let mbs = min_bytes_signed(i);
1969 let delta = ((mbs << 1) + u8::from(i.is_negative())).min(WIDEST_DELTA);
1970 let tag = u8::from(Tag::NonNegativeInt16_0) + delta;
1971
1972 push_tagged(data, tag, &i.to_le_bytes(), usize::from(mbs));
1973 }
1974 Datum::Int32(i) => {
1975 const WIDEST_DELTA: u8 = Tag::Int32.byte() - Tag::NonNegativeInt32_0.byte();
1979 let mbs = min_bytes_signed(i);
1980 let delta = ((mbs << 1) + u8::from(i.is_negative())).min(WIDEST_DELTA);
1981 let tag = u8::from(Tag::NonNegativeInt32_0) + delta;
1982
1983 push_tagged(data, tag, &i.to_le_bytes(), usize::from(mbs));
1984 }
1985 Datum::Int64(i) => {
1986 const WIDEST_DELTA: u8 = Tag::Int64.byte() - Tag::NonNegativeInt64_0.byte();
1990 let mbs = min_bytes_signed(i);
1991 let delta = ((mbs << 1) + u8::from(i.is_negative())).min(WIDEST_DELTA);
1992 let tag = u8::from(Tag::NonNegativeInt64_0) + delta;
1993
1994 push_tagged(data, tag, &i.to_le_bytes(), usize::from(mbs));
1995 }
1996 Datum::UInt8(i) => {
1997 let mbu = min_bytes_unsigned(i);
1998 let tag = u8::from(Tag::UInt8_0) + mbu;
1999 push_tagged(data, tag, &i.to_le_bytes(), usize::from(mbu));
2000 }
2001 Datum::UInt16(i) => {
2002 let mbu = min_bytes_unsigned(i);
2003 let tag = u8::from(Tag::UInt16_0) + mbu;
2004 push_tagged(data, tag, &i.to_le_bytes(), usize::from(mbu));
2005 }
2006 Datum::UInt32(i) => {
2007 let mbu = min_bytes_unsigned(i);
2008 let tag = u8::from(Tag::UInt32_0) + mbu;
2009 push_tagged(data, tag, &i.to_le_bytes(), usize::from(mbu));
2010 }
2011 Datum::UInt64(i) => {
2012 let mbu = min_bytes_unsigned(i);
2013 let tag = u8::from(Tag::UInt64_0) + mbu;
2014 push_tagged(data, tag, &i.to_le_bytes(), usize::from(mbu));
2015 }
2016 Datum::Float32(f) => {
2017 push_tagged(data, Tag::Float32.into(), &f.to_bits().to_le_bytes(), 4);
2018 }
2019 Datum::Float64(f) => {
2020 push_tagged(data, Tag::Float64.into(), &f.to_bits().to_le_bytes(), 8);
2021 }
2022 Datum::Date(d) => {
2023 data.push(Tag::Date.into());
2024 push_date(data, d);
2025 }
2026 Datum::Time(t) => {
2027 data.push(Tag::Time.into());
2028 push_time(data, t);
2029 }
2030 Datum::Timestamp(t) => {
2031 let datetime = t.to_naive();
2032 if let Some(nanos) = checked_timestamp_nanos(datetime) {
2033 push_tagged(data, Tag::CheapTimestamp.into(), &nanos.to_le_bytes(), 8);
2034 } else {
2035 data.push(Tag::Timestamp.into());
2036 push_naive_date(data, datetime.date());
2037 push_time(data, datetime.time());
2038 }
2039 }
2040 Datum::TimestampTz(t) => {
2041 let datetime = t.to_naive();
2042 if let Some(nanos) = checked_timestamp_nanos(datetime) {
2043 push_tagged(data, Tag::CheapTimestampTz.into(), &nanos.to_le_bytes(), 8);
2044 } else {
2045 data.push(Tag::TimestampTz.into());
2046 push_naive_date(data, datetime.date());
2047 push_time(data, datetime.time());
2048 }
2049 }
2050 Datum::Interval(i) => {
2051 push_tagged(data, Tag::Interval.into(), &i.months.to_le_bytes(), 4);
2052 data.extend_from_slice(&i.days.to_le_bytes());
2053 data.extend_from_slice(&i.micros.to_le_bytes());
2054 }
2055 Datum::Bytes(bytes) => {
2056 let tag = match bytes.len() {
2057 0..TINY => Tag::BytesTiny,
2058 TINY..SHORT => Tag::BytesShort,
2059 SHORT..LONG => Tag::BytesLong,
2060 _ => Tag::BytesHuge,
2061 };
2062 push_lengthed_bytes(data, bytes, tag);
2063 }
2064 Datum::String(string) => {
2065 let tag = match string.len() {
2066 0..TINY => Tag::StringTiny,
2067 TINY..SHORT => Tag::StringShort,
2068 SHORT..LONG => Tag::StringLong,
2069 _ => Tag::StringHuge,
2070 };
2071 push_lengthed_bytes(data, string.as_bytes(), tag);
2072 }
2073 Datum::List(list) => {
2074 let tag = match list.data.len() {
2075 0..TINY => Tag::ListTiny,
2076 TINY..SHORT => Tag::ListShort,
2077 SHORT..LONG => Tag::ListLong,
2078 _ => Tag::ListHuge,
2079 };
2080 push_lengthed_bytes(data, list.data, tag);
2081 }
2082 Datum::Uuid(u) => {
2083 push_tagged(data, Tag::Uuid.into(), u.as_bytes(), 16);
2084 }
2085 Datum::Array(array) => {
2086 data.push(Tag::Array.into());
2089 data.push(array.dims.ndims());
2090 data.extend_from_slice(array.dims.data);
2091 push_untagged_bytes(data, array.elements.data);
2092 }
2093 Datum::Map(dict) => {
2094 data.push(Tag::Dict.into());
2095 push_untagged_bytes(data, dict.data);
2096 }
2097 Datum::JsonNull => data.push(Tag::JsonNull.into()),
2098 Datum::MzTimestamp(t) => {
2099 push_tagged(data, Tag::MzTimestamp.into(), &t.encode(), 8);
2100 }
2101 Datum::Dummy => data.push(Tag::Dummy.into()),
2102 Datum::Numeric(mut n) => {
2103 numeric::cx_datum().reduce(&mut n.0);
2108 let (digits, exponent, bits, lsu) = n.0.to_raw_parts();
2109 data.push(Tag::Numeric.into());
2110 data.push(u8::try_from(digits).expect("digits to fit within u8; should not exceed 39"));
2111 data.push(
2112 i8::try_from(exponent)
2113 .expect("exponent to fit within i8; should not exceed +/- 39")
2114 .to_le_bytes()[0],
2115 );
2116 data.push(bits);
2117
2118 let lsu = &lsu[..Numeric::digits_to_lsu_elements_len(digits)];
2119
2120 if cfg!(target_endian = "little") {
2122 let (prefix, lsu_bytes, suffix) = unsafe { lsu.align_to::<u8>() };
2125 soft_assert_no_log!(
2128 lsu_bytes.len() == Numeric::digits_to_lsu_elements_len(digits) * 2,
2129 "u8 version of numeric LSU contained the wrong number of elements; expected {}, but got {}",
2130 Numeric::digits_to_lsu_elements_len(digits) * 2,
2131 lsu_bytes.len()
2132 );
2133 soft_assert_no_log!(prefix.is_empty() && suffix.is_empty());
2135 data.extend_from_slice(lsu_bytes);
2136 } else {
2137 for u in lsu {
2138 data.extend_from_slice(&u.to_le_bytes());
2139 }
2140 }
2141 }
2142 Datum::Range(range) => {
2143 data.push(Tag::Range.into());
2145 data.push(range.internal_flag_bits());
2146
2147 if let Some(RangeInner { lower, upper }) = range.inner {
2148 for bound in [lower.bound, upper.bound] {
2149 if let Some(bound) = bound {
2150 match bound.datum() {
2151 Datum::Null => panic!("cannot push Datum::Null into range"),
2152 d => push_datum::<D>(data, d),
2153 }
2154 }
2155 }
2156 }
2157 }
2158 Datum::MzAclItem(mz_acl_item) => {
2159 data.push(Tag::MzAclItem.into());
2160 data.extend_from_slice(&mz_acl_item.encode_binary());
2161 }
2162 Datum::AclItem(acl_item) => {
2163 data.push(Tag::AclItem.into());
2164 data.extend_from_slice(&acl_item.encode_binary());
2165 }
2166 }
2167}
2168
2169pub fn row_size<'a, I>(a: I) -> usize
2171where
2172 I: IntoIterator<Item = Datum<'a>>,
2173{
2174 let sz = datums_size::<_, _>(a);
2179 let size_of_row = std::mem::size_of::<Row>();
2180 if sz > Row::SIZE {
2184 sz + size_of_row
2185 } else {
2186 size_of_row
2187 }
2188}
2189
2190pub fn datum_size(datum: &Datum) -> usize {
2193 match datum {
2194 Datum::Null => 1,
2195 Datum::False => 1,
2196 Datum::True => 1,
2197 Datum::Int16(i) => 1 + usize::from(min_bytes_signed(*i)),
2198 Datum::Int32(i) => 1 + usize::from(min_bytes_signed(*i)),
2199 Datum::Int64(i) => 1 + usize::from(min_bytes_signed(*i)),
2200 Datum::UInt8(i) => 1 + usize::from(min_bytes_unsigned(*i)),
2201 Datum::UInt16(i) => 1 + usize::from(min_bytes_unsigned(*i)),
2202 Datum::UInt32(i) => 1 + usize::from(min_bytes_unsigned(*i)),
2203 Datum::UInt64(i) => 1 + usize::from(min_bytes_unsigned(*i)),
2204 Datum::Float32(_) => 1 + size_of::<f32>(),
2205 Datum::Float64(_) => 1 + size_of::<f64>(),
2206 Datum::Date(_) => 1 + size_of::<i32>(),
2207 Datum::Time(_) => 1 + 8,
2208 Datum::Timestamp(t) => {
2209 1 + if checked_timestamp_nanos(t.to_naive()).is_some() {
2210 8
2211 } else {
2212 16
2213 }
2214 }
2215 Datum::TimestampTz(t) => {
2216 1 + if checked_timestamp_nanos(t.naive_utc()).is_some() {
2217 8
2218 } else {
2219 16
2220 }
2221 }
2222 Datum::Interval(_) => 1 + size_of::<i32>() + size_of::<i32>() + size_of::<i64>(),
2223 Datum::Bytes(bytes) => {
2224 let bytes_for_length = match bytes.len() {
2226 0..TINY => 1,
2227 TINY..SHORT => 2,
2228 SHORT..LONG => 4,
2229 _ => 8,
2230 };
2231 1 + bytes_for_length + bytes.len()
2232 }
2233 Datum::String(string) => {
2234 let bytes_for_length = match string.len() {
2236 0..TINY => 1,
2237 TINY..SHORT => 2,
2238 SHORT..LONG => 4,
2239 _ => 8,
2240 };
2241 1 + bytes_for_length + string.len()
2242 }
2243 Datum::Uuid(_) => 1 + size_of::<uuid::Bytes>(),
2244 Datum::Array(array) => {
2245 1 + size_of::<u8>()
2246 + array.dims.data.len()
2247 + size_of::<u64>()
2248 + array.elements.data.len()
2249 }
2250 Datum::List(list) => 1 + size_of::<u64>() + list.data.len(),
2251 Datum::Map(dict) => 1 + size_of::<u64>() + dict.data.len(),
2252 Datum::JsonNull => 1,
2253 Datum::MzTimestamp(_) => 1 + size_of::<Timestamp>(),
2254 Datum::Dummy => 1,
2255 Datum::Numeric(d) => {
2256 let mut d = d.0.clone();
2257 numeric::cx_datum().reduce(&mut d);
2260 4 + (d.coefficient_units().len() * 2)
2262 }
2263 Datum::Range(Range { inner }) => {
2264 2 + match inner {
2266 None => 0,
2267 Some(RangeInner { lower, upper }) => [lower.bound, upper.bound]
2268 .iter()
2269 .map(|bound| match bound {
2270 None => 0,
2271 Some(bound) => bound.val.len(),
2272 })
2273 .sum(),
2274 }
2275 }
2276 Datum::MzAclItem(_) => 1 + MzAclItem::binary_size(),
2277 Datum::AclItem(_) => 1 + AclItem::binary_size(),
2278 }
2279}
2280
2281pub fn datums_size<'a, I, D>(iter: I) -> usize
2286where
2287 I: IntoIterator<Item = D>,
2288 D: Borrow<Datum<'a>>,
2289{
2290 iter.into_iter().map(|d| datum_size(d.borrow())).sum()
2291}
2292
2293pub fn datum_list_size<'a, I, D>(iter: I) -> usize
2298where
2299 I: IntoIterator<Item = D>,
2300 D: Borrow<Datum<'a>>,
2301{
2302 1 + size_of::<u64>() + datums_size(iter)
2303}
2304
2305impl RowPacker<'_> {
2306 pub fn for_existing_row(row: &mut Row) -> RowPacker<'_> {
2313 RowPacker { row }
2314 }
2315
2316 #[inline]
2318 pub fn push<'a, D>(&mut self, datum: D)
2319 where
2320 D: Borrow<Datum<'a>>,
2321 {
2322 push_datum(&mut self.row.data, *datum.borrow());
2323 }
2324
2325 #[inline]
2327 pub fn extend<'a, I, D>(&mut self, iter: I)
2328 where
2329 I: IntoIterator<Item = D>,
2330 D: Borrow<Datum<'a>>,
2331 {
2332 for datum in iter {
2333 push_datum(&mut self.row.data, *datum.borrow())
2334 }
2335 }
2336
2337 #[inline]
2343 pub fn try_extend<'a, I, E, D>(&mut self, iter: I) -> Result<(), E>
2344 where
2345 I: IntoIterator<Item = Result<D, E>>,
2346 D: Borrow<Datum<'a>>,
2347 {
2348 for datum in iter {
2349 push_datum(&mut self.row.data, *datum?.borrow());
2350 }
2351 Ok(())
2352 }
2353
2354 pub fn extend_by_row(&mut self, row: &Row) {
2356 self.row.data.extend_from_slice(row.data.as_slice());
2357 }
2358
2359 pub fn extend_by_row_ref(&mut self, row: &RowRef) {
2361 self.row.data.extend_from_slice(row.data());
2362 }
2363
2364 #[inline]
2372 pub unsafe fn extend_by_slice_unchecked(&mut self, data: &[u8]) {
2373 self.row.data.extend_from_slice(data)
2374 }
2375
2376 #[inline]
2398 pub fn push_list_with<F, R>(&mut self, f: F) -> R
2399 where
2400 F: FnOnce(&mut RowPacker) -> R,
2401 {
2402 let start = self.row.data.len();
2405 self.row.data.push(Tag::ListTiny.into());
2406 self.row.data.push(0);
2408
2409 let out = f(self);
2410
2411 let len = self.row.data.len() - start - 1 - 1;
2413 if len < TINY {
2415 self.row.data[start + 1] = len.to_le_bytes()[0];
2417 } else {
2418 long_list(&mut self.row.data, start, len);
2421 }
2422
2423 #[cold]
2430 fn long_list(data: &mut CompactBytes, start: usize, len: usize) {
2431 let long_list_inner = |data: &mut CompactBytes, len_len| {
2434 const ZEROS: [u8; 8] = [0; 8];
2437 data.extend_from_slice(&ZEROS[0..len_len - 1]);
2438 data.copy_within(start + 1 + 1..start + 1 + 1 + len, start + 1 + len_len);
2447 data[start + 1..start + 1 + len_len]
2449 .copy_from_slice(&len.to_le_bytes()[0..len_len]);
2450 };
2451 match len {
2452 0..TINY => {
2453 unreachable!()
2454 }
2455 TINY..SHORT => {
2456 data[start] = Tag::ListShort.into();
2457 long_list_inner(data, 2);
2458 }
2459 SHORT..LONG => {
2460 data[start] = Tag::ListLong.into();
2461 long_list_inner(data, 4);
2462 }
2463 _ => {
2464 data[start] = Tag::ListHuge.into();
2465 long_list_inner(data, 8);
2466 }
2467 };
2468 }
2469
2470 out
2471 }
2472
2473 pub fn push_dict_with<F, R>(&mut self, f: F) -> R
2511 where
2512 F: FnOnce(&mut RowPacker) -> R,
2513 {
2514 self.row.data.push(Tag::Dict.into());
2515 let start = self.row.data.len();
2516 self.row.data.extend_from_slice(&[0; size_of::<u64>()]);
2518
2519 let res = f(self);
2520
2521 let len = u64::cast_from(self.row.data.len() - start - size_of::<u64>());
2522 self.row.data[start..start + size_of::<u64>()].copy_from_slice(&len.to_le_bytes());
2524
2525 res
2526 }
2527
2528 pub fn try_push_dict_with<F, E>(&mut self, f: F) -> Result<(), E>
2530 where
2531 F: FnOnce(&mut RowPacker) -> Result<(), E>,
2532 {
2533 self.push_dict_with(f)
2534 }
2535
2536 pub fn try_push_array<'a, I, D>(
2543 &mut self,
2544 dims: &[ArrayDimension],
2545 iter: I,
2546 ) -> Result<(), InvalidArrayError>
2547 where
2548 I: IntoIterator<Item = D>,
2549 D: Borrow<Datum<'a>>,
2550 {
2551 unsafe {
2553 self.push_array_with_unchecked(dims, |packer| {
2554 let mut nelements = 0;
2555 for datum in iter {
2556 packer.push(datum);
2557 nelements += 1;
2558 }
2559 Ok::<_, InvalidArrayError>(nelements)
2560 })
2561 }
2562 }
2563
2564 pub fn try_push_array_fallible<'a, I, D, E>(
2567 &mut self,
2568 dims: &[ArrayDimension],
2569 iter: I,
2570 ) -> Result<Result<(), E>, InvalidArrayError>
2571 where
2572 I: IntoIterator<Item = Result<D, E>>,
2573 D: Borrow<Datum<'a>>,
2574 {
2575 enum Error<E> {
2576 Usage(InvalidArrayError),
2577 Inner(E),
2578 }
2579
2580 impl<E> From<InvalidArrayError> for Error<E> {
2581 fn from(e: InvalidArrayError) -> Self {
2582 Self::Usage(e)
2583 }
2584 }
2585
2586 let result = unsafe {
2588 self.push_array_with_unchecked(dims, |packer| {
2589 let mut nelements = 0;
2590 for datum in iter {
2591 packer.push(datum.map_err(Error::Inner)?);
2592 nelements += 1;
2593 }
2594 Ok(nelements)
2595 })
2596 };
2597 match result {
2598 Ok(()) => Ok(Ok(())),
2599 Err(Error::Usage(e)) => Err(e),
2600 Err(Error::Inner(e)) => Ok(Err(e)),
2601 }
2602 }
2603
2604 pub unsafe fn push_array_with_unchecked<F, E>(
2613 &mut self,
2614 dims: &[ArrayDimension],
2615 f: F,
2616 ) -> Result<(), E>
2617 where
2618 F: FnOnce(&mut RowPacker) -> Result<usize, E>,
2619 E: From<InvalidArrayError>,
2620 {
2621 if dims.len() > usize::from(MAX_ARRAY_DIMENSIONS) {
2633 return Err(InvalidArrayError::TooManyDimensions(dims.len()).into());
2634 }
2635
2636 let start = self.row.data.len();
2637 self.row.data.push(Tag::Array.into());
2638
2639 self.row
2641 .data
2642 .push(dims.len().try_into().expect("ndims verified to fit in u8"));
2643 for dim in dims {
2644 self.row
2645 .data
2646 .extend_from_slice(&i64::cast_from(dim.lower_bound).to_le_bytes());
2647 self.row
2648 .data
2649 .extend_from_slice(&u64::cast_from(dim.length).to_le_bytes());
2650 }
2651
2652 let off = self.row.data.len();
2654 self.row.data.extend_from_slice(&[0; size_of::<u64>()]);
2655 let nelements = match f(self) {
2656 Ok(nelements) => nelements,
2657 Err(e) => {
2658 self.row.data.truncate(start);
2659 return Err(e);
2660 }
2661 };
2662 let len = u64::cast_from(self.row.data.len() - off - size_of::<u64>());
2663 self.row.data[off..off + size_of::<u64>()].copy_from_slice(&len.to_le_bytes());
2664
2665 let cardinality = match dims {
2668 [] => 0,
2669 dims => dims
2677 .iter()
2678 .map(|d| d.length)
2679 .fold(1usize, usize::saturating_mul),
2680 };
2681 if nelements != cardinality {
2682 self.row.data.truncate(start);
2683 return Err(InvalidArrayError::WrongCardinality {
2684 actual: nelements,
2685 expected: cardinality,
2686 }
2687 .into());
2688 }
2689
2690 Ok(())
2691 }
2692
2693 pub fn push_array_with_row_major<F, I>(
2703 &mut self,
2704 dims: I,
2705 f: F,
2706 ) -> Result<(), InvalidArrayError>
2707 where
2708 I: IntoIterator<Item = ArrayDimension>,
2709 F: FnOnce(&mut RowPacker) -> usize,
2710 {
2711 let start = self.row.data.len();
2712 self.row.data.push(Tag::Array.into());
2713
2714 let dims_start = self.row.data.len();
2716 self.row.data.push(42);
2717
2718 let mut num_dims: u8 = 0;
2719 let mut cardinality: usize = 1;
2720 for dim in dims {
2721 num_dims += 1;
2722 cardinality = cardinality.saturating_mul(dim.length);
2726
2727 self.row
2728 .data
2729 .extend_from_slice(&i64::cast_from(dim.lower_bound).to_le_bytes());
2730 self.row
2731 .data
2732 .extend_from_slice(&u64::cast_from(dim.length).to_le_bytes());
2733 }
2734
2735 if num_dims > MAX_ARRAY_DIMENSIONS {
2736 self.row.data.truncate(start);
2738 return Err(InvalidArrayError::TooManyDimensions(usize::from(num_dims)));
2739 }
2740 self.row.data[dims_start..dims_start + size_of::<u8>()]
2742 .copy_from_slice(&num_dims.to_le_bytes());
2743
2744 let off = self.row.data.len();
2746 self.row.data.extend_from_slice(&[0; size_of::<u64>()]);
2747
2748 let nelements = f(self);
2749
2750 let len = u64::cast_from(self.row.data.len() - off - size_of::<u64>());
2751 self.row.data[off..off + size_of::<u64>()].copy_from_slice(&len.to_le_bytes());
2752
2753 let cardinality = match num_dims {
2756 0 => 0,
2757 _ => cardinality,
2758 };
2759 if nelements != cardinality {
2760 self.row.data.truncate(start);
2761 return Err(InvalidArrayError::WrongCardinality {
2762 actual: nelements,
2763 expected: cardinality,
2764 });
2765 }
2766
2767 Ok(())
2768 }
2769
2770 pub fn push_list<'a, I, D>(&mut self, iter: I)
2774 where
2775 I: IntoIterator<Item = D>,
2776 D: Borrow<Datum<'a>>,
2777 {
2778 self.push_list_with(|packer| {
2779 for elem in iter {
2780 packer.push(*elem.borrow())
2781 }
2782 });
2783 }
2784
2785 pub fn push_dict<'a, I, D>(&mut self, iter: I)
2787 where
2788 I: IntoIterator<Item = (&'a str, D)>,
2789 D: Borrow<Datum<'a>>,
2790 {
2791 self.push_dict_with(|packer| {
2792 for (k, v) in iter {
2793 packer.push(Datum::String(k));
2794 packer.push(*v.borrow())
2795 }
2796 })
2797 }
2798
2799 pub fn push_range<'a>(&mut self, mut range: Range<Datum<'a>>) -> Result<(), InvalidRangeError> {
2815 range.canonicalize()?;
2816 match range.inner {
2817 None => {
2818 self.row.data.push(Tag::Range.into());
2819 self.row.data.push(range::InternalFlags::EMPTY.bits());
2821 Ok(())
2822 }
2823 Some(inner) => self.push_range_with(
2824 RangeLowerBound {
2825 inclusive: inner.lower.inclusive,
2826 bound: inner
2827 .lower
2828 .bound
2829 .map(|value| move |row: &mut RowPacker| Ok(row.push(value))),
2830 },
2831 RangeUpperBound {
2832 inclusive: inner.upper.inclusive,
2833 bound: inner
2834 .upper
2835 .bound
2836 .map(|value| move |row: &mut RowPacker| Ok(row.push(value))),
2837 },
2838 ),
2839 }
2840 }
2841
2842 pub fn push_range_with<L, U, E>(
2865 &mut self,
2866 lower: RangeLowerBound<L>,
2867 upper: RangeUpperBound<U>,
2868 ) -> Result<(), E>
2869 where
2870 L: FnOnce(&mut RowPacker) -> Result<(), E>,
2871 U: FnOnce(&mut RowPacker) -> Result<(), E>,
2872 E: From<InvalidRangeError>,
2873 {
2874 let start = self.row.data.len();
2875 self.row.data.push(Tag::Range.into());
2876
2877 let mut flags = range::InternalFlags::empty();
2878
2879 flags.set(range::InternalFlags::LB_INFINITE, lower.bound.is_none());
2880 flags.set(range::InternalFlags::UB_INFINITE, upper.bound.is_none());
2881 flags.set(range::InternalFlags::LB_INCLUSIVE, lower.inclusive);
2882 flags.set(range::InternalFlags::UB_INCLUSIVE, upper.inclusive);
2883
2884 let mut expected_datums = 0;
2885
2886 self.row.data.push(flags.bits());
2887
2888 let datum_check = self.row.data.len();
2889
2890 if let Some(value) = lower.bound {
2891 let start = self.row.data.len();
2892 value(self)?;
2893 assert!(
2894 start < self.row.data.len(),
2895 "finite values must each push exactly one value; expected 1 but got 0"
2896 );
2897 expected_datums += 1;
2898 }
2899
2900 if let Some(value) = upper.bound {
2901 let start = self.row.data.len();
2902 value(self)?;
2903 assert!(
2904 start < self.row.data.len(),
2905 "finite values must each push exactly one value; expected 1 but got 0"
2906 );
2907 expected_datums += 1;
2908 }
2909
2910 let mut actual_datums = 0;
2914 let mut seen = None;
2915 let mut dataz = &self.row.data[datum_check..];
2916 while !dataz.is_empty() {
2917 let d = unsafe { read_datum(&mut dataz) };
2918 if d == Datum::Null {
2922 self.row.data.truncate(start);
2923 return Err(InvalidRangeError::InvalidRangeData.into());
2924 }
2925
2926 match seen {
2927 None => seen = Some(d),
2928 Some(seen) => {
2929 let seen_kind = DatumKind::from(seen);
2930 let d_kind = DatumKind::from(d);
2931 if seen_kind != d_kind {
2932 self.row.data.truncate(start);
2933 return Err(InvalidRangeError::InvalidRangeData.into());
2934 }
2935
2936 if seen > d {
2937 self.row.data.truncate(start);
2938 return Err(InvalidRangeError::MisorderedRangeBounds.into());
2939 }
2940 }
2941 }
2942 actual_datums += 1;
2943 }
2944
2945 if actual_datums != expected_datums {
2946 self.row.data.truncate(start);
2947 return Err(InvalidRangeError::InvalidRangeData.into());
2948 }
2949
2950 Ok(())
2951 }
2952
2953 pub fn clear(&mut self) {
2955 self.row.data.clear();
2956 }
2957
2958 pub unsafe fn truncate(&mut self, pos: usize) {
2971 self.row.data.truncate(pos)
2972 }
2973
2974 pub fn truncate_datums(&mut self, n: usize) {
2976 let prev_len = self.row.data.len();
2977 let mut iter = self.row.iter();
2978 for _ in iter.by_ref().take(n) {}
2979 let next_len = iter.data.len();
2980 unsafe { self.truncate(prev_len - next_len) }
2982 }
2983
2984 pub fn byte_len(&self) -> usize {
2986 self.row.byte_len()
2987 }
2988}
2989
2990impl<'a> IntoIterator for &'a Row {
2991 type Item = Datum<'a>;
2992 type IntoIter = DatumListIter<'a>;
2993 fn into_iter(self) -> DatumListIter<'a> {
2994 self.iter()
2995 }
2996}
2997
2998impl fmt::Debug for Row {
2999 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3001 f.write_str("Row{")?;
3002 f.debug_list().entries(self.iter()).finish()?;
3003 f.write_str("}")
3004 }
3005}
3006
3007impl fmt::Display for Row {
3008 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3010 f.write_str("(")?;
3011 for (i, datum) in self.iter().enumerate() {
3012 if i != 0 {
3013 f.write_str(", ")?;
3014 }
3015 write!(f, "{}", datum)?;
3016 }
3017 f.write_str(")")
3018 }
3019}
3020
3021impl<'a, T> DatumList<'a, T> {
3022 pub fn iter(&self) -> DatumListIter<'a> {
3023 DatumListIter { data: self.data }
3024 }
3025
3026 pub fn typed_iter(&self) -> DatumListTypedIter<'a, T>
3032 where
3033 T: FromDatum<'a>,
3034 {
3035 DatumListTypedIter {
3036 inner: self.iter(),
3037 _phantom: PhantomData,
3038 }
3039 }
3040
3041 pub fn data(&self) -> &'a [u8] {
3043 self.data
3044 }
3045}
3046
3047impl<T> DatumList<'static, T> {
3048 pub fn empty() -> Self {
3049 DatumList::new(&[])
3050 }
3051}
3052
3053impl<'a> IntoIterator for DatumList<'a> {
3054 type Item = Datum<'a>;
3055 type IntoIter = DatumListIter<'a>;
3056 fn into_iter(self) -> DatumListIter<'a> {
3057 self.iter()
3058 }
3059}
3060
3061impl<'a> Iterator for DatumListIter<'a> {
3062 type Item = Datum<'a>;
3063 fn next(&mut self) -> Option<Self::Item> {
3064 if self.data.is_empty() {
3065 None
3066 } else {
3067 Some(unsafe { read_datum(&mut self.data) })
3068 }
3069 }
3070}
3071
3072impl<'a, T: FromDatum<'a>> Iterator for DatumListTypedIter<'a, T> {
3073 type Item = T;
3074 fn next(&mut self) -> Option<Self::Item> {
3075 self.inner.next().map(T::from_datum)
3076 }
3077}
3078
3079impl<'a, T> DatumMap<'a, T> {
3080 pub fn iter(&self) -> DatumDictIter<'a> {
3081 DatumDictIter {
3082 data: self.data,
3083 prev_key: None,
3084 }
3085 }
3086
3087 pub fn typed_iter(&self) -> DatumDictTypedIter<'a, T>
3093 where
3094 T: FromDatum<'a>,
3095 {
3096 DatumDictTypedIter {
3097 inner: self.iter(),
3098 _phantom: PhantomData,
3099 }
3100 }
3101
3102 pub fn data(&self) -> &'a [u8] {
3104 self.data
3105 }
3106}
3107
3108impl<T> DatumMap<'static, T> {
3109 pub fn empty() -> Self {
3110 DatumMap::new(&[])
3111 }
3112}
3113
3114impl<'a, T> Debug for DatumMap<'a, T> {
3115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3116 f.debug_map().entries(self.iter()).finish()
3117 }
3118}
3119
3120impl<'a> IntoIterator for &'a DatumMap<'a> {
3121 type Item = (&'a str, Datum<'a>);
3122 type IntoIter = DatumDictIter<'a>;
3123 fn into_iter(self) -> DatumDictIter<'a> {
3124 self.iter()
3125 }
3126}
3127
3128impl<'a> Iterator for DatumDictIter<'a> {
3129 type Item = (&'a str, Datum<'a>);
3130 fn next(&mut self) -> Option<Self::Item> {
3131 if self.data.is_empty() {
3132 None
3133 } else {
3134 let key_tag =
3135 Tag::try_from_primitive(read_byte(&mut self.data)).expect("unknown row tag");
3136 assert!(
3137 key_tag == Tag::StringTiny
3138 || key_tag == Tag::StringShort
3139 || key_tag == Tag::StringLong
3140 || key_tag == Tag::StringHuge,
3141 "Dict keys must be strings, got {:?}",
3142 key_tag
3143 );
3144 let bytes = read_lengthed_bytes(&mut self.data, key_tag, Tag::StringTiny);
3145 let key = unsafe { str::from_utf8_unchecked(bytes) };
3147 let val = unsafe { read_datum(&mut self.data) };
3148
3149 if mz_ore::assert::soft_assertions_enabled() {
3152 if let Some(prev_key) = self.prev_key {
3153 mz_ore::soft_assert_no_log!(
3154 prev_key < key,
3155 "Dict keys must be unique and given in ascending order: {} came before {}",
3156 prev_key,
3157 key
3158 );
3159 }
3160 self.prev_key = Some(key);
3161 }
3162
3163 Some((key, val))
3164 }
3165 }
3166}
3167
3168impl<'a, T: FromDatum<'a>> Iterator for DatumDictTypedIter<'a, T> {
3169 type Item = (&'a str, T);
3170 fn next(&mut self) -> Option<Self::Item> {
3171 self.inner.next().map(|(k, v)| (k, T::from_datum(v)))
3172 }
3173}
3174
3175impl RowArena {
3176 pub fn new() -> Self {
3177 RowArena {
3178 inner: RefCell::new(vec![]),
3179 scratch: RefCell::new(None),
3180 budget: None,
3181 allocated: Cell::new(0),
3182 }
3183 }
3184
3185 pub fn with_budget(budget: usize) -> Self {
3202 RowArena {
3203 budget: Some(budget),
3204 ..RowArena::new()
3205 }
3206 }
3207
3208 pub fn allocated_bytes(&self) -> usize {
3210 self.allocated.get()
3211 }
3212
3213 pub fn over_budget(&self) -> bool {
3215 self.budget
3216 .is_some_and(|budget| self.allocated.get() > budget)
3217 }
3218
3219 pub fn budget_remaining(&self) -> usize {
3225 match self.budget {
3226 None => usize::MAX,
3227 Some(budget) => budget.saturating_sub(self.allocated.get()),
3228 }
3229 }
3230
3231 pub fn with_capacity(capacity: usize) -> Self {
3234 let mut inner = Vec::new();
3235 if capacity > 0 {
3236 inner.push(Vec::with_capacity(capacity));
3237 }
3238 RowArena {
3239 inner: RefCell::new(inner),
3240 ..RowArena::new()
3241 }
3242 }
3243
3244 pub fn reserve(&self, additional: usize) {
3247 if additional == 0 {
3248 return;
3249 }
3250 let mut inner = self.inner.borrow_mut();
3251 match inner.last_mut() {
3252 Some(active) if active.is_empty() => {
3255 if active.capacity() < additional {
3256 active.reserve_exact(additional);
3257 }
3258 }
3259 Some(active) => {
3264 let new_cap = std::cmp::max(additional, active.capacity().saturating_mul(2));
3265 inner.push(Vec::with_capacity(new_cap));
3266 }
3267 None => inner.push(Vec::with_capacity(additional)),
3268 }
3269 }
3270
3271 #[allow(clippy::transmute_ptr_to_ptr)]
3276 pub fn push_bytes<'a, B: Deref<Target = [u8]>>(&'a self, bytes: B) -> &'a [u8] {
3277 let bytes: &[u8] = &bytes;
3278 let need = bytes.len();
3279 if need == 0 {
3280 return &[];
3281 }
3282 let mut inner = self.inner.borrow_mut();
3283
3284 let has_room = inner
3287 .last()
3288 .map_or(false, |region| region.capacity() - region.len() >= need);
3289 if !has_room {
3290 let last_cap = inner.last().map_or(0, |region| region.capacity());
3291 let new_cap = std::cmp::max(need, last_cap.saturating_mul(2));
3292 inner.push(Vec::with_capacity(new_cap));
3293 }
3294
3295 let region = inner.last_mut().expect("region present");
3296 let start = region.len();
3297 region.extend_from_slice(bytes);
3298 self.allocated.set(self.allocated.get() + need);
3299 let copied = ®ion[start..];
3300 unsafe {
3301 transmute::<&[u8], &'a [u8]>(copied)
3311 }
3312 }
3313
3314 pub fn push_owned_bytes<'a>(&'a self, bytes: Vec<u8>) -> &'a [u8] {
3321 const MIN_ADOPT_BYTES: usize = 4 * 1024;
3325
3326 let need = bytes.len();
3327 if need == 0 {
3328 return &[];
3329 }
3330
3331 let mut inner = self.inner.borrow_mut();
3332 let last_cap = inner.last().map_or(0, |region| region.capacity());
3339 let adopt = need > std::cmp::max(MIN_ADOPT_BYTES, last_cap.saturating_mul(2));
3340 if !adopt {
3341 drop(inner);
3342 return self.push_bytes(&bytes[..]);
3343 }
3344
3345 self.allocated.set(self.allocated.get() + need);
3354 let idx = inner.len().saturating_sub(1);
3355 inner.insert(idx, bytes);
3356 if inner.len() == 1 {
3357 inner.push(Vec::new());
3360 }
3361 let adopted = &inner[idx][..];
3362 unsafe { transmute::<&[u8], &'a [u8]>(adopted) }
3363 }
3364
3365 pub fn push_string<'a>(&'a self, string: String) -> &'a str {
3367 let copied = self.push_owned_bytes(string.into_bytes());
3368 unsafe {
3369 std::str::from_utf8_unchecked(copied)
3371 }
3372 }
3373
3374 pub fn writer(&self) -> RowArenaBuf<'_> {
3386 let mut buf = self.scratch.borrow_mut().take().unwrap_or_default();
3390 buf.clear();
3391 RowArenaBuf { arena: self, buf }
3392 }
3393
3394 pub fn push_unary_row<'a>(&'a self, row: Row) -> Datum<'a> {
3400 let copied = self.push_bytes(row.data());
3401 unsafe {
3402 let datum = read_datum(&mut &copied[..]);
3406 transmute::<Datum<'_>, Datum<'a>>(datum)
3407 }
3408 }
3409
3410 fn push_unary_row_datum_nested<'a>(&'a self, row: Row) -> DatumNested<'a> {
3413 let copied = self.push_bytes(row.data());
3414 unsafe {
3415 let nested = DatumNested::extract(&mut &copied[..]);
3417 transmute::<DatumNested<'_>, DatumNested<'a>>(nested)
3418 }
3419 }
3420
3421 pub fn make_datum<'a, F>(&'a self, f: F) -> Datum<'a>
3433 where
3434 F: FnOnce(&mut RowPacker),
3435 {
3436 let mut row = Row::default();
3437 f(&mut row.packer());
3438 self.push_unary_row(row)
3439 }
3440
3441 pub fn make_datum_list<'a, T: std::borrow::Borrow<Datum<'a>>>(
3448 &'a self,
3449 iter: impl IntoIterator<Item = T>,
3450 ) -> DatumList<'a, T> {
3451 let datum = self.make_datum(|packer| {
3452 packer.push_list_with(|packer| {
3453 for elem in iter {
3454 packer.push(*elem.borrow());
3455 }
3456 });
3457 });
3458 DatumList::new(datum.unwrap_list().data())
3459 }
3460
3461 pub fn make_datum_nested<'a, F>(&'a self, f: F) -> DatumNested<'a>
3464 where
3465 F: FnOnce(&mut RowPacker),
3466 {
3467 let mut row = Row::default();
3468 f(&mut row.packer());
3469 self.push_unary_row_datum_nested(row)
3470 }
3471
3472 pub fn try_make_datum<'a, F, E>(&'a self, f: F) -> Result<Datum<'a>, E>
3474 where
3475 F: FnOnce(&mut RowPacker) -> Result<(), E>,
3476 {
3477 let mut row = Row::default();
3478 f(&mut row.packer())?;
3479 Ok(self.push_unary_row(row))
3480 }
3481
3482 pub fn clear(&mut self) {
3487 let inner = self.inner.get_mut();
3488 if let Some(largest) = (0..inner.len()).max_by_key(|&i| inner[i].capacity()) {
3492 inner.swap(0, largest);
3493 inner.truncate(1);
3494 inner[0].clear();
3495 }
3496 self.allocated.set(0);
3497 }
3498}
3499
3500impl Default for RowArena {
3501 fn default() -> RowArena {
3502 RowArena::new()
3503 }
3504}
3505
3506#[derive(Debug)]
3513pub struct RowArenaBuf<'a> {
3514 arena: &'a RowArena,
3515 buf: Vec<u8>,
3516}
3517
3518impl<'a> RowArenaBuf<'a> {
3519 pub fn push(&mut self, byte: u8) {
3521 self.buf.push(byte);
3522 }
3523
3524 pub fn extend_from_slice(&mut self, bytes: &[u8]) {
3526 self.buf.extend_from_slice(bytes);
3527 }
3528
3529 pub fn as_slice(&self) -> &[u8] {
3531 &self.buf
3532 }
3533
3534 pub fn len(&self) -> usize {
3536 self.buf.len()
3537 }
3538
3539 pub fn is_empty(&self) -> bool {
3541 self.buf.is_empty()
3542 }
3543
3544 pub fn finish(self) -> &'a [u8] {
3546 self.arena.push_bytes(self.buf.as_slice())
3549 }
3550
3551 pub fn finish_str(self) -> &'a str {
3556 let bytes = self.arena.push_bytes(self.buf.as_slice());
3557 std::str::from_utf8(bytes).expect("RowArenaBuf::finish_str on non-UTF-8 contents")
3558 }
3559}
3560
3561impl<'a> Drop for RowArenaBuf<'a> {
3562 fn drop(&mut self) {
3563 let mut slot = self.arena.scratch.borrow_mut();
3568 if slot.is_none() {
3569 *slot = Some(std::mem::take(&mut self.buf));
3570 }
3571 }
3572}
3573
3574impl<'a> std::ops::Deref for RowArenaBuf<'a> {
3575 type Target = [u8];
3576 fn deref(&self) -> &[u8] {
3577 &self.buf
3578 }
3579}
3580
3581impl<'a> std::io::Write for RowArenaBuf<'a> {
3582 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
3583 self.buf.extend_from_slice(bytes);
3584 Ok(bytes.len())
3585 }
3586
3587 fn flush(&mut self) -> std::io::Result<()> {
3588 Ok(())
3589 }
3590}
3591
3592impl<'a> std::fmt::Write for RowArenaBuf<'a> {
3593 fn write_str(&mut self, s: &str) -> std::fmt::Result {
3594 self.buf.extend_from_slice(s.as_bytes());
3595 Ok(())
3596 }
3597}
3598
3599#[derive(Debug)]
3617pub struct SharedRow(Row);
3618
3619impl SharedRow {
3620 thread_local! {
3621 static SHARED_ROW: Cell<Option<Row>> = const { Cell::new(Some(Row::empty())) }
3626 }
3627
3628 pub fn get() -> Self {
3636 let mut row = Self::SHARED_ROW
3637 .take()
3638 .expect("attempted to borrow already borrowed SharedRow");
3639 row.packer();
3641 Self(row)
3642 }
3643
3644 pub fn pack<'a, I, D>(iter: I) -> Row
3646 where
3647 I: IntoIterator<Item = D>,
3648 D: Borrow<Datum<'a>>,
3649 {
3650 let mut row_builder = Self::get();
3651 let mut row_packer = row_builder.packer();
3652 row_packer.extend(iter);
3653 row_builder.clone()
3654 }
3655}
3656
3657impl std::ops::Deref for SharedRow {
3658 type Target = Row;
3659
3660 fn deref(&self) -> &Self::Target {
3661 &self.0
3662 }
3663}
3664
3665impl std::ops::DerefMut for SharedRow {
3666 fn deref_mut(&mut self) -> &mut Self::Target {
3667 &mut self.0
3668 }
3669}
3670
3671impl Drop for SharedRow {
3672 fn drop(&mut self) {
3673 Self::SHARED_ROW.set(Some(std::mem::take(&mut self.0)))
3676 }
3677}
3678
3679#[cfg(test)]
3680mod tests {
3681 use std::cmp::Ordering;
3682 use std::collections::hash_map::DefaultHasher;
3683 use std::hash::{Hash, Hasher};
3684
3685 use chrono::{DateTime, NaiveDate};
3686 use itertools::Itertools;
3687 use mz_ore::{assert_err, assert_none};
3688 use ordered_float::OrderedFloat;
3689
3690 use crate::SqlScalarType;
3691
3692 use super::*;
3693
3694 proptest! {
3701 #![proptest_config(ProptestConfig::with_cases(1000))]
3702
3703 #[mz_ore::test]
3704 #[cfg_attr(miri, ignore)] fn stable_row_serde_roundtrip(
3706 stable in crate::relation::arb_relation_desc(1..8)
3707 .prop_flat_map(|desc| crate::relation::arb_row_for_relation(&desc))
3708 .prop_map(StableRow)
3709 ) {
3710 let json = serde_json::to_string(&stable).expect("serializes to JSON");
3711 let from_json: StableRow =
3712 serde_json::from_str(&json).expect("deserializes from JSON");
3713 prop_assert_eq!(&stable, &from_json);
3714
3715 let bytes = bincode::serialize(&stable).expect("serializes to bincode");
3716 let from_bincode: StableRow =
3717 bincode::deserialize(&bytes).expect("deserializes from bincode");
3718 prop_assert_eq!(&stable, &from_bincode);
3719 }
3720 }
3721
3722 fn varint_edge_cases() -> Vec<Datum<'static>> {
3725 let mut datums = vec![
3726 Datum::Int16(0),
3727 Datum::Int16(-1),
3728 Datum::Int16(i16::MIN),
3729 Datum::Int16(i16::MAX),
3730 Datum::Int32(0),
3731 Datum::Int32(-1),
3732 Datum::Int32(i32::MIN),
3733 Datum::Int32(i32::MAX),
3734 Datum::Int64(0),
3735 Datum::Int64(-1),
3736 Datum::Int64(i64::MIN),
3737 Datum::Int64(i64::MAX),
3738 Datum::UInt8(0),
3739 Datum::UInt8(u8::MAX),
3740 Datum::UInt16(0),
3741 Datum::UInt16(u16::MAX),
3742 Datum::UInt32(0),
3743 Datum::UInt32(u32::MAX),
3744 Datum::UInt64(0),
3745 Datum::UInt64(u64::MAX),
3746 ];
3747 for bits in 1..64 {
3749 let boundary = 1u64 << bits;
3750 for delta in [-1i64, 0, 1] {
3751 let Some(v) = boundary.checked_add_signed(delta) else {
3752 continue;
3753 };
3754 datums.push(Datum::UInt64(v));
3755 if let Ok(v) = u32::try_from(v) {
3756 datums.push(Datum::UInt32(v));
3757 }
3758 if let Ok(v) = u16::try_from(v) {
3759 datums.push(Datum::UInt16(v));
3760 }
3761 if let Ok(v) = u8::try_from(v) {
3762 datums.push(Datum::UInt8(v));
3763 }
3764 let Ok(v) = i64::try_from(v) else {
3765 continue;
3766 };
3767 datums.push(Datum::Int64(v));
3768 datums.push(Datum::Int64(-v));
3769 if let Ok(v) = i32::try_from(v) {
3770 datums.push(Datum::Int32(v));
3771 datums.push(Datum::Int32(-v));
3772 }
3773 if let Ok(v) = i16::try_from(v) {
3774 datums.push(Datum::Int16(v));
3775 datums.push(Datum::Int16(-v));
3776 }
3777 }
3778 }
3779 datums
3780 }
3781
3782 #[mz_ore::test]
3787 fn varint_tags_land_in_their_family() {
3788 for datum in varint_edge_cases() {
3789 let row = Row::pack_slice(&[datum]);
3790 let tag = Tag::try_from_primitive(row.data[0]).expect("valid tag");
3791 let (first, len, negative, widest) = match datum {
3792 Datum::Int16(i) => (Tag::NonNegativeInt16_0, min_bytes_signed(i), i < 0, 2),
3793 Datum::Int32(i) => (Tag::NonNegativeInt32_0, min_bytes_signed(i), i < 0, 4),
3794 Datum::Int64(i) => (Tag::NonNegativeInt64_0, min_bytes_signed(i), i < 0, 8),
3795 Datum::UInt8(u) => (Tag::UInt8_0, min_bytes_unsigned(u), false, 1),
3796 Datum::UInt16(u) => (Tag::UInt16_0, min_bytes_unsigned(u), false, 2),
3797 Datum::UInt32(u) => (Tag::UInt32_0, min_bytes_unsigned(u), false, 4),
3798 Datum::UInt64(u) => (Tag::UInt64_0, min_bytes_unsigned(u), false, 8),
3799 other => panic!("not a variable-length integer: {other:?}"),
3800 };
3801 let delta = u8::from(tag) - u8::from(first);
3802 let signed = matches!(datum, Datum::Int16(_) | Datum::Int32(_) | Datum::Int64(_));
3803 if signed {
3804 assert_eq!(delta >> 1, len, "wrong payload width in tag for {datum:?}");
3807 let sign_bit = if len == widest { 0 } else { u8::from(negative) };
3808 assert_eq!(delta & 1, sign_bit, "wrong sign in tag for {datum:?}");
3809 } else {
3810 assert_eq!(delta, len, "wrong payload width in tag for {datum:?}");
3811 }
3812 assert_eq!(row.unpack_first(), datum, "did not round-trip: {datum:?}");
3813 }
3814 }
3815
3816 #[mz_ore::test]
3819 fn varint_at_end_of_row_reads_exact_width() {
3820 for datum in varint_edge_cases() {
3821 for prefix in [None, Some(Datum::String("0123456789abcdef"))] {
3823 let row = match prefix {
3824 Some(p) => Row::pack_slice(&[p, datum]),
3825 None => Row::pack_slice(&[datum]),
3826 };
3827 assert_eq!(
3828 row.iter().last(),
3829 Some(datum),
3830 "did not round-trip at end of row: {datum:?}"
3831 );
3832 }
3833 let mut row = Row::default();
3835 let mut packer = row.packer();
3836 packer.push_list_with(|packer| packer.push(datum));
3837 packer.push(Datum::Int64(1));
3838 let list = match row.unpack_first() {
3839 Datum::List(list) => list,
3840 other => panic!("expected a list, got {other:?}"),
3841 };
3842 assert_eq!(list.iter().next(), Some(datum), "did not round-trip nested");
3843 }
3844 }
3845
3846 #[mz_ore::test]
3849 #[cfg_attr(miri, ignore)] fn cmp_deep_nested_list_does_not_overflow() {
3851 fn deep() -> Row {
3852 let mut row = Row::pack_slice(&[Datum::Int64(1)]);
3854 for _ in 0..50_000 {
3855 let mut next = Row::default();
3856 next.packer().push_list([row.unpack_first()]);
3857 row = next;
3858 }
3859 row
3860 }
3861 let a = deep();
3862 let b = deep();
3863 assert_eq!(a.unpack_first().cmp(&b.unpack_first()), Ordering::Equal);
3864 }
3865
3866 fn hash<T: Hash>(t: &T) -> u64 {
3867 let mut hasher = DefaultHasher::new();
3868 t.hash(&mut hasher);
3869 hasher.finish()
3870 }
3871
3872 #[mz_ore::test]
3873 fn test_assumptions() {
3874 assert_eq!(size_of::<Tag>(), 1);
3875 #[cfg(target_endian = "big")]
3876 {
3877 assert!(false);
3879 }
3880 }
3881
3882 #[mz_ore::test]
3883 fn miri_test_arena() {
3884 let arena = RowArena::new();
3885
3886 assert_eq!(arena.push_string("".to_owned()), "");
3887 assert_eq!(arena.push_string("العَرَبِيَّة".to_owned()), "العَرَبِيَّة");
3888
3889 let empty: &[u8] = &[];
3890 assert_eq!(arena.push_bytes(vec![]), empty);
3891 assert_eq!(arena.push_bytes(vec![0, 2, 1, 255]), &[0, 2, 1, 255]);
3892
3893 let mut row = Row::default();
3894 let mut packer = row.packer();
3895 packer.push_dict_with(|row| {
3896 row.push(Datum::String("a"));
3897 row.push_list_with(|row| {
3898 row.push(Datum::String("one"));
3899 row.push(Datum::String("two"));
3900 row.push(Datum::String("three"));
3901 });
3902 row.push(Datum::String("b"));
3903 row.push(Datum::String("c"));
3904 });
3905 assert_eq!(arena.push_unary_row(row.clone()), row.unpack_first());
3906 }
3907
3908 #[mz_ore::test]
3909 fn miri_test_arena_growth_keeps_references() {
3910 let arena = RowArena::new();
3913 let chunks: Vec<Vec<u8>> = (0..128u16)
3914 .map(|i| vec![u8::try_from(i % 256).unwrap(); usize::from(i % 13) + 1])
3915 .collect();
3916 let refs: Vec<&[u8]> = chunks
3917 .iter()
3918 .map(|c| arena.push_bytes(c.as_slice()))
3919 .collect();
3920 for (i, r) in refs.iter().enumerate() {
3921 assert_eq!(*r, chunks[i].as_slice());
3922 }
3923 }
3924
3925 #[mz_ore::test]
3926 fn miri_test_arena_unary_row_at_offset() {
3927 let arena = RowArena::new();
3930 arena.reserve(4096);
3931 let _pad = arena.push_bytes(vec![0xAB; 5]);
3932 let row = Row::pack_slice(&[Datum::String("hello"), Datum::Int64(42), Datum::True]);
3933 assert_eq!(arena.push_unary_row(row.clone()), row.unpack_first());
3934 }
3935
3936 #[mz_ore::test]
3937 fn miri_test_arena_clear_reuse() {
3938 let mut arena = RowArena::new();
3940 for i in 0..100u8 {
3941 let _ = arena.push_bytes(vec![i; 16]);
3942 }
3943 arena.clear();
3944 assert_eq!(arena.push_bytes(vec![7u8; 8]), &[7u8; 8]);
3945 assert_eq!(arena.push_string("after clear".to_owned()), "after clear");
3946 arena.clear();
3947 let empty: &[u8] = &[];
3948 assert_eq!(arena.push_bytes(Vec::<u8>::new()), empty);
3949 }
3950
3951 #[mz_ore::test]
3952 fn miri_test_arena_adopts_owned_bytes_and_keeps_references() {
3953 let arena = RowArena::new();
3957 let before = arena.push_bytes(vec![1u8; 8]);
3958 let adopted = arena.push_owned_bytes(vec![2u8; 64 * 1024]);
3959 let after = arena.push_bytes(vec![3u8; 8]);
3960 let small = arena.push_owned_bytes(vec![4u8; 4]);
3962
3963 assert_eq!(before, &[1u8; 8]);
3964 assert_eq!(adopted, &vec![2u8; 64 * 1024][..]);
3965 assert_eq!(after, &[3u8; 8]);
3966 assert_eq!(small, &[4u8; 4]);
3967
3968 let empty: &[u8] = &[];
3969 assert_eq!(arena.push_owned_bytes(vec![]), empty);
3970 }
3971
3972 #[mz_ore::test]
3973 fn test_arena_owned_pushes_keep_bump_allocating() {
3974 const VALUES: usize = 500;
3983 const VALUE: &str = "0123456789";
3984
3985 let regions = |arena: &RowArena| arena.inner.borrow().len();
3986 let push_all = |arena: &RowArena, owned: bool| {
3987 for _ in 0..VALUES {
3988 match owned {
3989 true => _ = arena.push_string(VALUE.to_string()),
3990 false => _ = arena.push_bytes(VALUE.as_bytes()),
3991 }
3992 }
3993 };
3994
3995 let copied = RowArena::new();
3997 push_all(&copied, false);
3998
3999 let owned = RowArena::new();
4000 push_all(&owned, true);
4001
4002 let seeded = RowArena::new();
4005 let _ = seeded.push_bytes(VALUE.as_bytes());
4006 push_all(&seeded, true);
4007
4008 let (copied, owned, seeded) = (regions(&copied), regions(&owned), regions(&seeded));
4012 assert!(
4013 owned <= copied * 2 && seeded <= copied * 2,
4014 "{VALUES} owned pushes left {owned} regions on an empty arena and {seeded} on a seeded \
4015 one, against {copied} for the same bytes copied",
4016 );
4017 }
4018
4019 #[mz_ore::test]
4020 fn miri_test_arena_budget() {
4021 let arena = RowArena::new();
4023 let _ = arena.push_bytes(vec![0u8; 1024]);
4024 assert!(!arena.over_budget());
4025 assert_eq!(arena.budget_remaining(), usize::MAX);
4026
4027 let arena = RowArena::with_budget(100);
4028 assert!(!arena.over_budget());
4029 assert_eq!(arena.budget_remaining(), 100);
4030
4031 let _ = arena.push_bytes(vec![0u8; 60]);
4034 assert!(!arena.over_budget());
4035 assert_eq!(arena.budget_remaining(), 40);
4036 assert_eq!(arena.allocated_bytes(), 60);
4037
4038 let pushed = arena.push_bytes(vec![7u8; 80]);
4041 assert_eq!(pushed, &[7u8; 80]);
4042 assert!(arena.over_budget());
4043 assert_eq!(arena.budget_remaining(), 0);
4044
4045 let mut arena = RowArena::with_budget(100);
4048 let _ = arena.push_owned_bytes(vec![0u8; 8 * 1024]);
4049 assert!(arena.over_budget());
4050
4051 arena.clear();
4052 assert!(!arena.over_budget());
4053 assert_eq!(arena.allocated_bytes(), 0);
4054 }
4055
4056 #[mz_ore::test]
4057 fn miri_test_arena_writer() {
4058 use std::io::Write;
4059
4060 let arena = RowArena::new();
4061
4062 let mut w = arena.writer();
4064 let mut expected = Vec::new();
4065 for i in 0..1000u16 {
4066 let byte = u8::try_from(i % 256).unwrap();
4067 w.push(byte);
4068 expected.push(byte);
4069 w.extend_from_slice(&[byte, byte]);
4070 expected.extend_from_slice(&[byte, byte]);
4071 }
4072 assert_eq!(w.as_slice(), expected.as_slice());
4073 assert_eq!(w.len(), expected.len());
4074 let first = w.finish();
4075 assert_eq!(first, expected.as_slice());
4076
4077 let mut w2 = arena.writer();
4080 write!(w2, "hello").unwrap();
4081 let second = w2.finish();
4082 assert_eq!(second, b"hello");
4083 assert_eq!(first, expected.as_slice());
4084
4085 let empty: &[u8] = &[];
4087 assert_eq!(arena.writer().finish(), empty);
4088
4089 {
4091 let mut w3 = arena.writer();
4092 w3.extend_from_slice(b"discarded");
4093 }
4094 assert_eq!(arena.writer().as_slice(), empty);
4095 }
4096
4097 #[mz_ore::test]
4098 fn miri_test_arena_writer_nested() {
4099 let arena = RowArena::new();
4103
4104 let mut outer = arena.writer();
4105 outer.extend_from_slice(b"outer-before-");
4106
4107 let inner_bytes = {
4109 let mut inner = arena.writer();
4110 inner.extend_from_slice(b"inner");
4111 assert_eq!(outer.as_slice(), b"outer-before-");
4113 inner.finish()
4114 };
4115 assert_eq!(inner_bytes, b"inner");
4116
4117 outer.extend_from_slice(b"after");
4119 let outer_bytes = outer.finish();
4120 assert_eq!(outer_bytes, b"outer-before-after");
4121 assert_eq!(inner_bytes, b"inner");
4123
4124 let mut again = arena.writer();
4126 again.extend_from_slice(b"reused");
4127 assert_eq!(again.finish(), b"reused");
4128 }
4129
4130 #[mz_ore::test]
4131 fn miri_test_arena_writer_fmt() {
4132 use std::fmt::Write;
4133
4134 let arena = RowArena::new();
4136 let mut w = arena.writer();
4137 for i in 0..5 {
4138 write!(w, "{i},").unwrap();
4139 }
4140 assert_eq!(w.finish_str(), "0,1,2,3,4,");
4141 }
4142
4143 #[mz_ore::test]
4144 fn miri_test_round_trip() {
4145 fn round_trip(datums: Vec<Datum>) {
4146 let row = Row::pack(datums.clone());
4147
4148 println!("{:?}", row.data());
4151
4152 let datums2 = row.iter().collect::<Vec<_>>();
4153 let datums3 = row.unpack();
4154 assert_eq!(datums, datums2);
4155 assert_eq!(datums, datums3);
4156 }
4157
4158 round_trip(vec![]);
4159 round_trip(
4160 SqlScalarType::enumerate()
4161 .iter()
4162 .flat_map(|r#type| r#type.interesting_datums())
4163 .collect(),
4164 );
4165 round_trip(vec![
4166 Datum::Null,
4167 Datum::Null,
4168 Datum::False,
4169 Datum::True,
4170 Datum::Int16(-21),
4171 Datum::Int32(-42),
4172 Datum::Int64(-2_147_483_648 - 42),
4173 Datum::UInt8(0),
4174 Datum::UInt8(1),
4175 Datum::UInt16(0),
4176 Datum::UInt16(1),
4177 Datum::UInt16(1 << 8),
4178 Datum::UInt32(0),
4179 Datum::UInt32(1),
4180 Datum::UInt32(1 << 8),
4181 Datum::UInt32(1 << 16),
4182 Datum::UInt32(1 << 24),
4183 Datum::UInt64(0),
4184 Datum::UInt64(1),
4185 Datum::UInt64(1 << 8),
4186 Datum::UInt64(1 << 16),
4187 Datum::UInt64(1 << 24),
4188 Datum::UInt64(1 << 32),
4189 Datum::UInt64(1 << 40),
4190 Datum::UInt64(1 << 48),
4191 Datum::UInt64(1 << 56),
4192 Datum::Float32(OrderedFloat::from(-42.12)),
4193 Datum::Float64(OrderedFloat::from(-2_147_483_648.0 - 42.12)),
4194 Datum::Date(Date::from_pg_epoch(365 * 45 + 21).unwrap()),
4195 Datum::Timestamp(
4196 CheckedTimestamp::from_timestamplike(
4197 NaiveDate::from_isoywd_opt(2019, 30, chrono::Weekday::Wed)
4198 .unwrap()
4199 .and_hms_opt(14, 32, 11)
4200 .unwrap(),
4201 )
4202 .unwrap(),
4203 ),
4204 Datum::TimestampTz(
4205 CheckedTimestamp::from_timestamplike(DateTime::from_timestamp(61, 0).unwrap())
4206 .unwrap(),
4207 ),
4208 Datum::Interval(Interval {
4209 months: 312,
4210 ..Default::default()
4211 }),
4212 Datum::Interval(Interval::new(0, 0, 1_012_312)),
4213 Datum::Bytes(&[]),
4214 Datum::Bytes(&[0, 2, 1, 255]),
4215 Datum::String(""),
4216 Datum::String("العَرَبِيَّة"),
4217 ]);
4218 }
4219
4220 #[mz_ore::test]
4221 fn test_array() {
4222 const DIM: ArrayDimension = ArrayDimension {
4225 lower_bound: 2,
4226 length: 2,
4227 };
4228 let mut row = Row::default();
4229 let mut packer = row.packer();
4230 packer
4231 .try_push_array(&[DIM], vec![Datum::Int32(1), Datum::Int32(2)])
4232 .unwrap();
4233 let arr1 = row.unpack_first().unwrap_array();
4234 assert_eq!(arr1.dims().into_iter().collect::<Vec<_>>(), vec![DIM]);
4235 assert_eq!(
4236 arr1.elements().into_iter().collect::<Vec<_>>(),
4237 vec![Datum::Int32(1), Datum::Int32(2)]
4238 );
4239
4240 let row = Row::pack_slice(&[Datum::Array(arr1)]);
4243 let arr2 = row.unpack_first().unwrap_array();
4244 assert_eq!(arr1, arr2);
4245 }
4246
4247 #[mz_ore::test]
4248 fn test_multidimensional_array() {
4249 let datums = vec![
4250 Datum::Int32(1),
4251 Datum::Int32(2),
4252 Datum::Int32(3),
4253 Datum::Int32(4),
4254 Datum::Int32(5),
4255 Datum::Int32(6),
4256 Datum::Int32(7),
4257 Datum::Int32(8),
4258 ];
4259
4260 let mut row = Row::default();
4261 let mut packer = row.packer();
4262 packer
4263 .try_push_array(
4264 &[
4265 ArrayDimension {
4266 lower_bound: 1,
4267 length: 1,
4268 },
4269 ArrayDimension {
4270 lower_bound: 1,
4271 length: 4,
4272 },
4273 ArrayDimension {
4274 lower_bound: 1,
4275 length: 2,
4276 },
4277 ],
4278 &datums,
4279 )
4280 .unwrap();
4281 let array = row.unpack_first().unwrap_array();
4282 assert_eq!(array.elements().into_iter().collect::<Vec<_>>(), datums);
4283 }
4284
4285 #[mz_ore::test]
4286 fn test_array_max_dimensions() {
4287 let mut row = Row::default();
4288 let max_dims = usize::from(MAX_ARRAY_DIMENSIONS);
4289
4290 let res = row.packer().try_push_array(
4292 &vec![
4293 ArrayDimension {
4294 lower_bound: 1,
4295 length: 1
4296 };
4297 max_dims + 1
4298 ],
4299 vec![Datum::Int32(4)],
4300 );
4301 assert_eq!(res, Err(InvalidArrayError::TooManyDimensions(max_dims + 1)));
4302 assert!(row.data.is_empty());
4303
4304 row.packer()
4307 .try_push_array(
4308 &vec![
4309 ArrayDimension {
4310 lower_bound: 1,
4311 length: 1
4312 };
4313 max_dims
4314 ],
4315 vec![Datum::Int32(4)],
4316 )
4317 .unwrap();
4318 }
4319
4320 #[mz_ore::test]
4321 fn test_array_wrong_cardinality() {
4322 let mut row = Row::default();
4323 let res = row.packer().try_push_array(
4324 &[
4325 ArrayDimension {
4326 lower_bound: 1,
4327 length: 2,
4328 },
4329 ArrayDimension {
4330 lower_bound: 1,
4331 length: 3,
4332 },
4333 ],
4334 vec![Datum::Int32(1), Datum::Int32(2)],
4335 );
4336 assert_eq!(
4337 res,
4338 Err(InvalidArrayError::WrongCardinality {
4339 actual: 2,
4340 expected: 6,
4341 })
4342 );
4343 assert!(row.data.is_empty());
4344 }
4345
4346 #[mz_ore::test]
4347 fn test_array_cardinality_overflow() {
4348 let mut row = Row::default();
4353 let res = row.packer().try_push_array(
4354 &[
4355 ArrayDimension {
4356 lower_bound: 1,
4357 length: usize::MAX,
4358 },
4359 ArrayDimension {
4360 lower_bound: 1,
4361 length: 2,
4362 },
4363 ],
4364 vec![Datum::Int32(1), Datum::Int32(2)],
4365 );
4366 assert_eq!(
4367 res,
4368 Err(InvalidArrayError::WrongCardinality {
4369 actual: 2,
4370 expected: usize::MAX,
4371 })
4372 );
4373 assert!(row.data.is_empty());
4374 }
4375
4376 #[mz_ore::test]
4377 fn test_nesting() {
4378 let mut row = Row::default();
4379 row.packer().push_dict_with(|row| {
4380 row.push(Datum::String("favourites"));
4381 row.push_list_with(|row| {
4382 row.push(Datum::String("ice cream"));
4383 row.push(Datum::String("oreos"));
4384 row.push(Datum::String("cheesecake"));
4385 });
4386 row.push(Datum::String("name"));
4387 row.push(Datum::String("bob"));
4388 });
4389
4390 let mut iter = row.unpack_first().unwrap_map().iter();
4391
4392 let (k, v) = iter.next().unwrap();
4393 assert_eq!(k, "favourites");
4394 assert_eq!(
4395 v.unwrap_list().iter().collect::<Vec<_>>(),
4396 vec![
4397 Datum::String("ice cream"),
4398 Datum::String("oreos"),
4399 Datum::String("cheesecake"),
4400 ]
4401 );
4402
4403 let (k, v) = iter.next().unwrap();
4404 assert_eq!(k, "name");
4405 assert_eq!(v, Datum::String("bob"));
4406 }
4407
4408 #[mz_ore::test]
4409 fn test_dict_errors() -> Result<(), Box<dyn std::error::Error>> {
4410 let pack = |ok| {
4411 let mut row = Row::default();
4412 row.packer().push_dict_with(|row| {
4413 if ok {
4414 row.push(Datum::String("key"));
4415 row.push(Datum::Int32(42));
4416 Ok(7)
4417 } else {
4418 Err("fail")
4419 }
4420 })?;
4421 Ok(row)
4422 };
4423
4424 assert_eq!(pack(false), Err("fail"));
4425
4426 let row = pack(true)?;
4427 let mut dict = row.unpack_first().unwrap_map().iter();
4428 assert_eq!(dict.next(), Some(("key", Datum::Int32(42))));
4429 assert_eq!(dict.next(), None);
4430
4431 Ok(())
4432 }
4433
4434 #[mz_ore::test]
4435 #[cfg_attr(miri, ignore)] fn test_datum_sizes() {
4437 let arena = RowArena::new();
4438
4439 let values_of_interest = vec![
4441 Datum::Null,
4442 Datum::False,
4443 Datum::Int16(0),
4444 Datum::Int32(0),
4445 Datum::Int64(0),
4446 Datum::UInt8(0),
4447 Datum::UInt8(1),
4448 Datum::UInt16(0),
4449 Datum::UInt16(1),
4450 Datum::UInt16(1 << 8),
4451 Datum::UInt32(0),
4452 Datum::UInt32(1),
4453 Datum::UInt32(1 << 8),
4454 Datum::UInt32(1 << 16),
4455 Datum::UInt32(1 << 24),
4456 Datum::UInt64(0),
4457 Datum::UInt64(1),
4458 Datum::UInt64(1 << 8),
4459 Datum::UInt64(1 << 16),
4460 Datum::UInt64(1 << 24),
4461 Datum::UInt64(1 << 32),
4462 Datum::UInt64(1 << 40),
4463 Datum::UInt64(1 << 48),
4464 Datum::UInt64(1 << 56),
4465 Datum::Float32(OrderedFloat(0.0)),
4466 Datum::Float64(OrderedFloat(0.0)),
4467 Datum::from(numeric::Numeric::from(0)),
4468 Datum::from(numeric::Numeric::from(1000)),
4469 Datum::from(numeric::Numeric::from(9999)),
4470 Datum::Date(
4471 NaiveDate::from_ymd_opt(1, 1, 1)
4472 .unwrap()
4473 .try_into()
4474 .unwrap(),
4475 ),
4476 Datum::Timestamp(
4477 CheckedTimestamp::from_timestamplike(
4478 DateTime::from_timestamp(0, 0).unwrap().naive_utc(),
4479 )
4480 .unwrap(),
4481 ),
4482 Datum::TimestampTz(
4483 CheckedTimestamp::from_timestamplike(DateTime::from_timestamp(0, 0).unwrap())
4484 .unwrap(),
4485 ),
4486 Datum::Interval(Interval::default()),
4487 Datum::Bytes(&[]),
4488 Datum::String(""),
4489 Datum::JsonNull,
4490 Datum::Range(Range { inner: None }),
4491 arena.make_datum(|packer| {
4492 packer
4493 .push_range(Range::new(Some((
4494 RangeLowerBound::new(Datum::Int32(-1), true),
4495 RangeUpperBound::new(Datum::Int32(1), true),
4496 ))))
4497 .unwrap();
4498 }),
4499 ];
4500 for value in values_of_interest {
4501 if datum_size(&value) != Row::pack_slice(&[value]).data.len() {
4502 panic!("Disparity in claimed size for {:?}", value);
4503 }
4504 }
4505 }
4506
4507 #[mz_ore::test]
4508 fn test_range_errors() {
4509 fn test_range_errors_inner<'a>(
4510 datums: Vec<Vec<Datum<'a>>>,
4511 ) -> Result<(), InvalidRangeError> {
4512 let mut row = Row::default();
4513 let row_len = row.byte_len();
4514 let mut packer = row.packer();
4515 let r = packer.push_range_with(
4516 RangeLowerBound {
4517 inclusive: true,
4518 bound: Some(|row: &mut RowPacker| {
4519 for d in &datums[0] {
4520 row.push(d);
4521 }
4522 Ok(())
4523 }),
4524 },
4525 RangeUpperBound {
4526 inclusive: true,
4527 bound: Some(|row: &mut RowPacker| {
4528 for d in &datums[1] {
4529 row.push(d);
4530 }
4531 Ok(())
4532 }),
4533 },
4534 );
4535
4536 assert_eq!(row_len, row.byte_len());
4537
4538 r
4539 }
4540
4541 for panicking_case in [
4546 vec![vec![Datum::Int32(1)], vec![]],
4547 vec![vec![Datum::Int32(1), Datum::Int32(2)], vec![]],
4548 ] {
4549 #[allow(clippy::disallowed_methods)] let result = std::panic::catch_unwind(|| test_range_errors_inner(panicking_case));
4551 assert_err!(result);
4552 }
4553
4554 for error_case in [
4558 vec![
4559 vec![Datum::Int32(1), Datum::Int32(2)],
4560 vec![Datum::Int32(3)],
4561 ],
4562 vec![
4563 vec![Datum::Int32(1)],
4564 vec![Datum::Int32(2), Datum::Int32(3)],
4565 ],
4566 vec![vec![Datum::Int32(1)], vec![Datum::UInt16(2)]],
4567 vec![vec![Datum::Null], vec![Datum::Int32(2)]],
4568 vec![vec![Datum::Int32(1)], vec![Datum::Null]],
4569 ] {
4570 assert_eq!(
4571 test_range_errors_inner(error_case),
4572 Err(InvalidRangeError::InvalidRangeData)
4573 );
4574 }
4575
4576 let e = test_range_errors_inner(vec![vec![Datum::Int32(2)], vec![Datum::Int32(1)]]);
4577 assert_eq!(e, Err(InvalidRangeError::MisorderedRangeBounds));
4578 }
4579
4580 #[mz_ore::test]
4582 #[cfg_attr(miri, ignore)] fn test_list_encoding() {
4584 fn test_list_encoding_inner(len: usize) {
4585 let list_elem = |i: usize| {
4586 if i % 2 == 0 {
4587 Datum::False
4588 } else {
4589 Datum::True
4590 }
4591 };
4592 let mut row = Row::default();
4593 {
4594 let mut packer = row.packer();
4596 packer.push(Datum::String("start"));
4597 packer.push_list_with(|packer| {
4598 for i in 0..len {
4599 packer.push(list_elem(i));
4600 }
4601 });
4602 packer.push(Datum::String("end"));
4603 }
4604 let mut row_it = row.iter();
4606 assert_eq!(row_it.next().unwrap(), Datum::String("start"));
4607 match row_it.next().unwrap() {
4608 Datum::List(list) => {
4609 let mut list_it = list.iter();
4610 for i in 0..len {
4611 assert_eq!(list_it.next().unwrap(), list_elem(i));
4612 }
4613 assert_none!(list_it.next());
4614 }
4615 _ => panic!("expected Datum::List"),
4616 }
4617 assert_eq!(row_it.next().unwrap(), Datum::String("end"));
4618 assert_none!(row_it.next());
4619 }
4620
4621 test_list_encoding_inner(0);
4622 test_list_encoding_inner(1);
4623 test_list_encoding_inner(10);
4624 test_list_encoding_inner(TINY - 1); test_list_encoding_inner(TINY + 1); test_list_encoding_inner(SHORT + 1); }
4631
4632 #[mz_ore::test]
4638 #[cfg_attr(miri, ignore)] fn test_datum_list_eq_ord_consistency() {
4640 let mut row_pos = Row::default();
4642 row_pos.packer().push_list_with(|p| {
4643 p.push(Datum::Float64(OrderedFloat::from(0.0)));
4644 });
4645 let list_pos = row_pos.unpack_first().unwrap_list();
4646
4647 let mut row_neg = Row::default();
4649 row_neg.packer().push_list_with(|p| {
4650 p.push(Datum::Float64(OrderedFloat::from(-0.0)));
4651 });
4652 let list_neg = row_neg.unpack_first().unwrap_list();
4653
4654 assert_eq!(
4657 list_pos, list_neg,
4658 "Eq should see different encodings as equal"
4659 );
4660
4661 assert_eq!(
4663 list_pos.cmp(&list_neg),
4664 Ordering::Equal,
4665 "Ord (datum-by-datum) should see -0.0 and +0.0 as equal"
4666 );
4667 }
4668
4669 #[mz_ore::test]
4672 fn test_datum_map_eq_bytewise_consistency() {
4673 let mut row_pos = Row::default();
4675 row_pos.packer().push_dict_with(|p| {
4676 p.push(Datum::String("k"));
4677 p.push(Datum::Float64(OrderedFloat::from(0.0)));
4678 });
4679 let map_pos = row_pos.unpack_first().unwrap_map();
4680
4681 let mut row_neg = Row::default();
4683 row_neg.packer().push_dict_with(|p| {
4684 p.push(Datum::String("k"));
4685 p.push(Datum::Float64(OrderedFloat::from(-0.0)));
4686 });
4687 let map_neg = row_neg.unpack_first().unwrap_map();
4688
4689 assert_eq!(
4691 map_pos, map_neg,
4692 "DatumMap Eq is semantic; -0.0 and +0.0 have different encodings but are equal"
4693 );
4694 let entries_pos: Vec<_> = map_pos.iter().collect();
4696 let entries_neg: Vec<_> = map_neg.iter().collect();
4697 assert_eq!(entries_pos.len(), entries_neg.len());
4698 for ((k1, v1), (k2, v2)) in entries_pos.iter().zip_eq(entries_neg.iter()) {
4699 assert_eq!(k1, k2);
4700 assert_eq!(
4701 v1, v2,
4702 "Datum-level comparison treats -0.0 and +0.0 as equal"
4703 );
4704 }
4705 }
4706
4707 #[mz_ore::test]
4709 fn test_datum_list_hash_consistency() {
4710 let mut row_pos = Row::default();
4712 row_pos.packer().push_list_with(|p| {
4713 p.push(Datum::Float64(OrderedFloat::from(0.0)));
4714 });
4715 let list_pos = row_pos.unpack_first().unwrap_list();
4716
4717 let mut row_neg = Row::default();
4718 row_neg.packer().push_list_with(|p| {
4719 p.push(Datum::Float64(OrderedFloat::from(-0.0)));
4720 });
4721 let list_neg = row_neg.unpack_first().unwrap_list();
4722
4723 assert_eq!(list_pos, list_neg);
4724 assert_eq!(
4725 hash(&list_pos),
4726 hash(&list_neg),
4727 "equal lists must have same hash"
4728 );
4729
4730 let mut row_a = Row::default();
4732 row_a.packer().push_list_with(|p| {
4733 p.push(Datum::Int32(1));
4734 p.push(Datum::Int32(2));
4735 });
4736 let list_a = row_a.unpack_first().unwrap_list();
4737
4738 let mut row_b = Row::default();
4739 row_b.packer().push_list_with(|p| {
4740 p.push(Datum::Int32(1));
4741 p.push(Datum::Int32(3));
4742 });
4743 let list_b = row_b.unpack_first().unwrap_list();
4744
4745 assert_ne!(list_a, list_b);
4746 assert_ne!(
4747 hash(&list_a),
4748 hash(&list_b),
4749 "unequal lists must have different hashes"
4750 );
4751 }
4752
4753 #[mz_ore::test]
4755 #[cfg_attr(miri, ignore)] fn test_datum_list_ordering() {
4757 let mut row_12 = Row::default();
4758 row_12.packer().push_list_with(|p| {
4759 p.push(Datum::Int32(1));
4760 p.push(Datum::Int32(2));
4761 });
4762 let list_12 = row_12.unpack_first().unwrap_list();
4763
4764 let mut row_13 = Row::default();
4765 row_13.packer().push_list_with(|p| {
4766 p.push(Datum::Int32(1));
4767 p.push(Datum::Int32(3));
4768 });
4769 let list_13 = row_13.unpack_first().unwrap_list();
4770
4771 let mut row_123 = Row::default();
4772 row_123.packer().push_list_with(|p| {
4773 p.push(Datum::Int32(1));
4774 p.push(Datum::Int32(2));
4775 p.push(Datum::Int32(3));
4776 });
4777 let list_123 = row_123.unpack_first().unwrap_list();
4778
4779 assert_eq!(list_12.cmp(&list_13), Ordering::Less);
4781 assert_eq!(list_13.cmp(&list_12), Ordering::Greater);
4782 assert_eq!(list_12.cmp(&list_12), Ordering::Equal);
4783 assert_eq!(list_12.cmp(&list_123), Ordering::Less);
4785 }
4786
4787 #[mz_ore::test]
4789 fn test_datum_map_hash_consistency() {
4790 let mut row_pos = Row::default();
4791 row_pos.packer().push_dict_with(|p| {
4792 p.push(Datum::String("x"));
4793 p.push(Datum::Float64(OrderedFloat::from(0.0)));
4794 });
4795 let map_pos = row_pos.unpack_first().unwrap_map();
4796
4797 let mut row_neg = Row::default();
4798 row_neg.packer().push_dict_with(|p| {
4799 p.push(Datum::String("x"));
4800 p.push(Datum::Float64(OrderedFloat::from(-0.0)));
4801 });
4802 let map_neg = row_neg.unpack_first().unwrap_map();
4803
4804 assert_eq!(map_pos, map_neg);
4805 assert_eq!(
4806 hash(&map_pos),
4807 hash(&map_neg),
4808 "equal maps must have same hash"
4809 );
4810
4811 let mut row_a = Row::default();
4812 row_a.packer().push_dict_with(|p| {
4813 p.push(Datum::String("a"));
4814 p.push(Datum::Int32(1));
4815 });
4816 let map_a = row_a.unpack_first().unwrap_map();
4817
4818 let mut row_b = Row::default();
4819 row_b.packer().push_dict_with(|p| {
4820 p.push(Datum::String("a"));
4821 p.push(Datum::Int32(2));
4822 });
4823 let map_b = row_b.unpack_first().unwrap_map();
4824
4825 assert_ne!(map_a, map_b);
4826 assert_ne!(
4827 hash(&map_a),
4828 hash(&map_b),
4829 "unequal maps must have different hashes"
4830 );
4831 }
4832
4833 #[mz_ore::test]
4835 #[cfg_attr(miri, ignore)] fn test_datum_map_ordering() {
4837 let mut row_a1 = Row::default();
4838 row_a1.packer().push_dict_with(|p| {
4839 p.push(Datum::String("a"));
4840 p.push(Datum::Int32(1));
4841 });
4842 let map_a1 = row_a1.unpack_first().unwrap_map();
4843
4844 let mut row_a2 = Row::default();
4845 row_a2.packer().push_dict_with(|p| {
4846 p.push(Datum::String("a"));
4847 p.push(Datum::Int32(2));
4848 });
4849 let map_a2 = row_a2.unpack_first().unwrap_map();
4850
4851 let mut row_b1 = Row::default();
4852 row_b1.packer().push_dict_with(|p| {
4853 p.push(Datum::String("b"));
4854 p.push(Datum::Int32(1));
4855 });
4856 let map_b1 = row_b1.unpack_first().unwrap_map();
4857
4858 assert_eq!(map_a1.cmp(&map_a2), Ordering::Less);
4859 assert_eq!(map_a2.cmp(&map_a1), Ordering::Greater);
4860 assert_eq!(map_a1.cmp(&map_a1), Ordering::Equal);
4861 assert_eq!(map_a1.cmp(&map_b1), Ordering::Less); }
4863
4864 #[mz_ore::test]
4867 #[cfg_attr(miri, ignore)] fn test_datum_list_and_map_null_sorts_last() {
4869 let mut row_list_1 = Row::default();
4871 row_list_1
4872 .packer()
4873 .push_list_with(|p| p.push(Datum::Int32(1)));
4874 let list_1 = row_list_1.unpack_first().unwrap_list();
4875
4876 let mut row_list_null = Row::default();
4877 row_list_null
4878 .packer()
4879 .push_list_with(|p| p.push(Datum::Null));
4880 let list_null = row_list_null.unpack_first().unwrap_list();
4881
4882 assert_eq!(list_1.cmp(&list_null), Ordering::Less);
4883 assert_eq!(list_null.cmp(&list_1), Ordering::Greater);
4884
4885 let mut row_map_1 = Row::default();
4887 row_map_1.packer().push_dict_with(|p| {
4888 p.push(Datum::String("k"));
4889 p.push(Datum::Int32(1));
4890 });
4891 let map_1 = row_map_1.unpack_first().unwrap_map();
4892
4893 let mut row_map_null = Row::default();
4894 row_map_null.packer().push_dict_with(|p| {
4895 p.push(Datum::String("k"));
4896 p.push(Datum::Null);
4897 });
4898 let map_null = row_map_null.unpack_first().unwrap_map();
4899
4900 assert_eq!(map_1.cmp(&map_null), Ordering::Less);
4901 assert_eq!(map_null.cmp(&map_1), Ordering::Greater);
4902 }
4903}