Skip to main content

mz_repr/
row.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! In-memory `Tag`-based encoding of a tuple of `Datum`s.
11//!
12//! See `doc/developer/row-encoding.md` for the size limits this encoding and
13//! its datum types impose.
14
15use 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/// A packed representation for `Datum`s.
64///
65/// `Datum` is easy to work with but very space inefficient. A `Datum::Int32(42)`
66/// is laid out in memory like this:
67///
68///   tag: 3
69///   padding: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
70///   data: 0 0 0 42
71///   padding: 0 0 0 0 0 0 0 0 0 0 0 0
72///
73/// For a total of 32 bytes! The second set of padding is needed in case we were
74/// to write a 16-byte datum into this location. The first set of padding is
75/// needed to align that hypothetical decimal to a 16 bytes boundary.
76///
77/// A `Row` stores zero or more `Datum`s without any padding. We avoid the need
78/// for the first set of padding by only providing access to the `Datum`s via
79/// calls to `ptr::read_unaligned`, which on modern x86 is barely penalized. We
80/// avoid the need for the second set of padding by not providing mutable access
81/// to the `Datum`. Instead, `Row` is append-only.
82///
83/// A `Row` can be built from a collection of `Datum`s using `Row::pack`, but it
84/// is more efficient to use `Row::pack_slice` so that a right-sized allocation
85/// can be created. If that is not possible, consider using the row buffer
86/// pattern: allocate one row, pack into it, and then call [`Row::clone`] to
87/// receive a copy of that row, leaving behind the original allocation to pack
88/// future rows.
89///
90/// Creating a row via [`Row::pack_slice`]:
91///
92/// ```
93/// # use mz_repr::{Row, Datum};
94/// let row = Row::pack_slice(&[Datum::Int32(0), Datum::Int32(1), Datum::Int32(2)]);
95/// assert_eq!(row.unpack(), vec![Datum::Int32(0), Datum::Int32(1), Datum::Int32(2)])
96/// ```
97///
98/// `Row`s can be unpacked by iterating over them:
99///
100/// ```
101/// # use mz_repr::{Row, Datum};
102/// let row = Row::pack_slice(&[Datum::Int32(0), Datum::Int32(1), Datum::Int32(2)]);
103/// assert_eq!(row.iter().nth(1).unwrap(), Datum::Int32(1));
104/// ```
105///
106/// If you want random access to the `Datum`s in a `Row`, use `Row::unpack` to create a `Vec<Datum>`
107/// ```
108/// # use mz_repr::{Row, Datum};
109/// let row = Row::pack_slice(&[Datum::Int32(0), Datum::Int32(1), Datum::Int32(2)]);
110/// let datums = row.unpack();
111/// assert_eq!(datums[1], Datum::Int32(1));
112/// ```
113///
114/// # Performance
115///
116/// Rows are dynamically sized, but up to a fixed size their data is stored in-line.
117/// It is best to re-use a `Row` across multiple `Row` creation calls, as this
118/// avoids the allocations involved in `Row::new()`.
119#[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    /// A variant of `Row::from_proto` that allows for reuse of internal allocs
128    /// and validates the decoding against a provided [`RelationDesc`].
129    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    /// Allocate an empty `Row` with a pre-allocated capacity.
150    #[inline]
151    pub fn with_capacity(cap: usize) -> Self {
152        Self {
153            data: CompactBytes::with_capacity(cap),
154        }
155    }
156
157    /// Create an empty `Row`.
158    #[inline]
159    pub const fn empty() -> Self {
160        Self {
161            data: CompactBytes::empty(),
162        }
163    }
164
165    /// Creates a new row from supplied bytes.
166    ///
167    /// # Safety
168    ///
169    /// This method relies on `data` being an appropriate row encoding, and can
170    /// result in unsafety if this is not the case.
171    pub unsafe fn from_bytes_unchecked(data: &[u8]) -> Self {
172        Row {
173            data: CompactBytes::new(data),
174        }
175    }
176
177    /// Constructs a [`RowPacker`] that will pack datums into this row's
178    /// allocation.
179    ///
180    /// This method clears the existing contents of the row, but retains the
181    /// allocation.
182    pub fn packer(&mut self) -> RowPacker<'_> {
183        self.clear();
184        RowPacker { row: self }
185    }
186
187    /// Take some `Datum`s and pack them into a `Row`.
188    ///
189    /// This method builds a `Row` by repeatedly increasing the backing
190    /// allocation. If the contents of the iterator are known ahead of
191    /// time, consider [`Row::with_capacity`] to right-size the allocation
192    /// first, and then [`RowPacker::extend`] to populate it with `Datum`s.
193    /// This avoids the repeated allocation resizing and copying.
194    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    /// Use `self` to pack `iter`, and then clone the result.
205    ///
206    /// This is a convenience method meant to reduce boilerplate around row
207    /// formation.
208    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    /// Like [`Row::pack`], but the provided iterator is allowed to produce an
218    /// error, in which case the packing operation is aborted and the error
219    /// returned.
220    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    /// Pack a slice of `Datum`s into a `Row`.
231    ///
232    /// This method has the advantage over `pack` that it can determine the required
233    /// allocation before packing the elements, ensuring only one allocation and no
234    /// redundant copies required.
235    pub fn pack_slice<'a>(slice: &[Datum<'a>]) -> Row {
236        // Pre-allocate the needed number of bytes.
237        let mut row = Row::with_capacity(datums_size(slice.iter()));
238        row.packer().extend(slice.iter());
239        row
240    }
241
242    /// Returns the total amount of bytes used by this row.
243    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    /// The length of the encoded row in bytes. Does not include the size of the `Row` struct itself.
254    pub fn data_len(&self) -> usize {
255        self.data.len()
256    }
257
258    /// Returns the total capacity in bytes used by this row.
259    pub fn byte_capacity(&self) -> usize {
260        self.data.capacity()
261    }
262
263    /// Extracts a Row slice containing the entire [`Row`].
264    #[inline]
265    pub fn as_row_ref(&self) -> &RowRef {
266        // SAFETY: `Row` contains valid row data, by construction.
267        unsafe { RowRef::from_slice(self.data.as_slice()) }
268    }
269
270    /// Clear the contents of the [`Row`], leaving any allocation in place.
271    #[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
300// Nothing depends on Row being exactly 24, we just want to add visibility to the size.
301static_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
315// Row's `Hash` implementation defers to `RowRef` to ensure they hash equivalently.
316impl 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/// A [`Row`] that serializes as protobuf-encoded [`ProtoRow`] bytes.
355///
356/// `Row`'s own serde impl emits the raw bytes of the in-memory `Tag` based
357/// datum encoding, which is free to change between releases. Use this wrapper
358/// instead wherever a row is serialized into a durable, cross-version format,
359/// such as the stable LIR plan format. `ProtoRow` already carries the needed
360/// backward compatibility obligation: it is persist's storage codec for
361/// `SourceData`, and `row.proto` is covered by the buf breaking lint.
362#[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    /// Region allocation for `Row` data.
422    ///
423    /// Content bytes are stored in stable contiguous memory locations,
424    /// and then a `Row` referencing them is falsified.
425    pub struct RowStack {
426        region: LgAllocRegion<u8>,
427    }
428
429    impl RowStack {
430        const LIMIT: usize = 2 << 20;
431    }
432
433    // Implement `Default` manually to specify a region allocation limit.
434    impl Default for RowStack {
435        fn default() -> Self {
436            Self {
437                // Limit the region size to 2MiB.
438                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 container; provides indexed access to offsets.
519        bounds: BC,
520        /// Values container; provides slice access to bytes.
521        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                // Imported bounds will be relative to this starting offset.
580                let values_len: u64 = self.values.len().try_into().expect("must fit");
581
582                // Push all bytes that we can, all at once.
583                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                // Each bound needs to be shifted by `values_len - other_lower`.
596                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            // SAFETY: self.values contains only valid row data, and self.metadata delimits only ranges
659            // that correspond to the original rows.
660            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            // SAFETY: self.values contains only valid row data, and self.metadata delimits only ranges
676            // that correspond to the original rows.
677            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/// A contiguous slice of bytes that are row data.
711///
712/// A [`RowRef`] is to [`Row`] as [`prim@str`] is to [`String`].
713#[derive(PartialEq, Eq, Hash)]
714#[repr(transparent)]
715pub struct RowRef([u8]);
716
717impl RowRef {
718    /// Create a [`RowRef`] from a slice of data.
719    ///
720    /// # Safety
721    ///
722    /// We do not check that the provided slice is valid [`Row`] data; the caller is required to
723    /// ensure this.
724    pub unsafe fn from_slice(row: &[u8]) -> &RowRef {
725        #[allow(clippy::as_conversions)]
726        let ptr = row as *const [u8] as *const RowRef;
727        // SAFETY: We know `ptr` is non-null and aligned because it came from a &[u8].
728        unsafe { &*ptr }
729    }
730
731    /// Unpack `self` into a `Vec<Datum>` for efficient random access.
732    pub fn unpack(&self) -> Vec<Datum<'_>> {
733        // It's usually cheaper to unpack twice to figure out the right length than it is to grow the vec as we go
734        let len = self.iter().count();
735        let mut vec = Vec::with_capacity(len);
736        vec.extend(self.iter());
737        vec
738    }
739
740    /// Return the first [`Datum`] in `self`
741    ///
742    /// Panics if the [`RowRef`] is empty.
743    pub fn unpack_first(&self) -> Datum<'_> {
744        self.iter().next().unwrap()
745    }
746
747    /// Iterate the [`Datum`] elements of the [`RowRef`].
748    pub fn iter(&self) -> DatumListIter<'_> {
749        DatumListIter { data: &self.0 }
750    }
751
752    /// Return the byte length of this [`RowRef`].
753    pub fn byte_len(&self) -> usize {
754        self.0.len()
755    }
756
757    /// For debugging only.
758    pub fn data(&self) -> &[u8] {
759        &self.0
760    }
761
762    /// True iff there is no data in this [`RowRef`].
763    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        // SAFETY: RowRef has the invariant that the wrapped data must be a valid Row encoding.
773        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
786/// These implementations order first by length, and then by slice contents.
787/// This allows many comparisons to complete without dereferencing memory.
788/// Warning: These order by the u8 array representation, and NOT by Datum::cmp.
789impl 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    /// Debug representation using the internal datums
807    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/// Packs datums into a [`Row`].
815///
816/// Creating a `RowPacker` via [`Row::packer`] starts a packing operation on the
817/// row. A packing operation always starts from scratch: the existing contents
818/// of the underlying row are cleared.
819///
820/// To complete a packing operation, drop the `RowPacker`.
821#[derive(Debug)]
822pub struct RowPacker<'a> {
823    row: &'a mut Row,
824}
825
826/// Infallible conversion from a [`Datum`] to a typed value.
827///
828/// Used by [`DatumList::typed_iter`] to yield elements as `T` rather than
829/// raw `Datum`s. At runtime, `T` is always `Datum<'a>`, so the conversion
830/// is identity.
831///
832/// See `doc/developer/design/20260311_sqlfunc_generic.md` for the design
833/// behind the generic type parameter and type erasure.
834///
835/// This trait is sealed and cannot be implemented outside of this crate.
836pub 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/// `RowArena` is used to hold on to temporary `Row`s for functions like `eval` that need to create complex `Datum`s but don't have a `Row` to put them in yet.
880#[derive(Debug)]
881pub struct RowArena {
882    // A stack of byte regions, used as a bump allocator. Bytes handed to
883    // `push_bytes` are *copied* into the active (last) region and a reference
884    // into that region is returned.
885    //
886    // The invariant that keeps returned references valid for the arena's
887    // lifetime is that a region is never reallocated once it holds data: when
888    // the active region lacks spare capacity for a push we allocate a *new*,
889    // larger region rather than growing the current one (which would move its
890    // bytes and dangle outstanding references). The outer `Vec` may itself
891    // reallocate as regions are added, but that only moves the `Vec<u8>`
892    // headers, not the heap buffers they own, so references remain valid.
893    //
894    // `clear` retains only the largest region (emptied) to right-size the arena
895    // for reuse; reusing one region across `clear` cycles makes a steady-state
896    // workload (e.g. decoding rows one at a time) allocation-free.
897    inner: RefCell<Vec<Vec<u8>>>,
898    // A single recycled scratch buffer backing `RowArena::writer`. A writer takes ownership of this
899    // buffer (or allocates a fresh one if absent), builds into it, and on drop returns it here for
900    // the next writer to reuse — so building values incrementally does not allocate per use once the
901    // buffer reaches its high-water mark. Holding `Option` (rather than the buffer directly) means
902    // `writer` borrows this cell only transiently, to take and return the buffer, never across the
903    // writer's lifetime. That keeps nested writers sound: a writer obtained while another is live
904    // finds the slot empty and allocates its own buffer instead of double-borrowing.
905    scratch: RefCell<Option<Vec<u8>>>,
906    // Optional ceiling on the bytes this arena will hold, and a running total of what it holds.
907    // `None` is unbounded, which is what every arena in a dataflow must keep using: a budget that
908    // can change mid-run would make dataflow evaluation non-deterministic (see
909    // [`RowArena::with_budget`]). A budget is for evaluating a user-authored expression in a shared
910    // process, where that expression's memory use must be bounded (see `mz_adapter::webhook`).
911    //
912    // NOTE: exceeding the budget does not make a push fail. The pushes are infallible, and a
913    // refused push would hand back a truncated value, i.e. a corrupt datum. The budget is instead a
914    // *reported* condition: `over_budget` is polled by whoever is able to return an error, which
915    // for scalar expressions is the evaluator between calls.
916    budget: Option<usize>,
917    allocated: Cell<usize>,
918}
919
920// DatumList and DatumDict defined here rather than near Datum because we need private access to the unsafe data field
921
922/// A sequence of Datums
923///
924/// The type parameter `T` represents the element type of the list. It is a
925/// phantom parameter that carries no runtime data — the actual elements are
926/// stored as serialized bytes and `T` is not enforced at runtime. It is up
927/// to the caller to ensure `T` matches the actual element type. The default
928/// `T = Datum<'a>` means existing code that writes `DatumList<'a>` continues
929/// to work unchanged.
930///
931/// See `doc/developer/design/20260311_sqlfunc_generic.md` for the design
932/// behind the generic type parameter.
933pub struct DatumList<'a, T = Datum<'a>> {
934    /// Points at the serialized datums
935    data: &'a [u8],
936    _phantom: PhantomData<fn() -> T>,
937}
938
939impl<'a, T> DatumList<'a, T> {
940    /// Private constructor. All `DatumList` values should be created through
941    /// this function to keep the `PhantomData` bookkeeping in one place.
942    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        // Grow the stack: lists can be arbitrarily deeply nested (e.g. jsonb).
986        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
997/// A mapping from string keys to Datums
998///
999/// The type parameter `T` represents the value type of the map. It is a
1000/// phantom parameter — the actual values are stored as serialized bytes and
1001/// `T` is not enforced at runtime. It is up to the caller to ensure `T`
1002/// matches the actual value type. The default `T = Datum<'a>` means existing
1003/// code that writes `DatumMap<'a>` continues to work unchanged.
1004///
1005/// See `doc/developer/design/20260311_sqlfunc_generic.md` for the design
1006/// behind the generic type parameter.
1007pub struct DatumMap<'a, T = Datum<'a>> {
1008    /// Points at the serialized datums, which should be sorted in key order
1009    data: &'a [u8],
1010    _phantom: PhantomData<fn() -> T>,
1011}
1012
1013impl<'a, T> DatumMap<'a, T> {
1014    /// Private constructor. All `DatumMap` values should be created through
1015    /// this function to keep the `PhantomData` bookkeeping in one place.
1016    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        // Grow the stack: maps can be arbitrarily deeply nested (e.g. jsonb).
1055        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/// Represents a single `Datum`, appropriate to be nested inside other
1091/// `Datum`s.
1092#[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    // Figure out which bytes `read_datum` returns (e.g. including the tag),
1113    // and then store a reference to those bytes, so we can "replay" this same
1114    // call later on without storing the datum itself.
1115    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    /// Returns the datum `self` contains.
1124    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        // Grow the stack: this recurses once per level of nested list/map values.
1133        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// Prefer adding new tags to the end of the enum. Certain behavior, like row ordering and EXPLAIN
1144// PHYSICAL PLAN, rely on the ordering of this enum. Neither of these are breaking changes, but
1145// it's annoying when they change.
1146#[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    // The length-prefixed tags: for each of the three kinds, four tags ordered by the width of
1160    // the length prefix in front of the payload, so a tag's distance from its kind's first tag
1161    // selects the width. Each kind has its own `read_datum` arm naming the `Datum` constructor,
1162    // since the kind never varies within a column; the width does, so it stays inside the arm.
1163    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    // Everything except leap seconds and times beyond the range of
1186    // i64 nanoseconds. (Note that Materialize does not support leap
1187    // seconds, but this module does).
1188    CheapTimestamp,
1189    // Everything except leap seconds and times beyond the range of
1190    // i64 nanoseconds. (Note that Materialize does not support leap
1191    // seconds, but this module does).
1192    CheapTimestampTz,
1193    // The next several tags are for variable-length signed integer encoding.
1194    // The basic idea is that `NonNegativeIntN_K` is used to encode a datum of type
1195    // IntN whose actual value is positive or zero and fits in K bits, and similarly for
1196    // NegativeIntN_K with negative values.
1197    //
1198    // The order of these tags matters, because we want to be able to choose the
1199    // tag for a given datum quickly, with arithmetic, rather than slowly, with a
1200    // stack of `if` statements.
1201    //
1202    // Separate tags for non-negative and negative numbers are used to avoid having to
1203    // waste one bit in the actual data space to encode the sign.
1204    // A signed family alternates non-negative and negative at each payload width, so a tag
1205    // splits into both by arithmetic: the width is its distance from the family's first tag
1206    // shifted right by one, and the sign is that distance's low bit. Keeping the two signs
1207    // apart would make the width a subtraction from one of two bases, chosen by a compare.
1208    //
1209    // The family ends at the width where the payload is the whole integer. There the sign is
1210    // already the payload's top bit, so one tag serves both and the alternation stops, which is
1211    // why the fixed-width tag sits there rather than in a family of its own.
1212    NonNegativeInt16_0, // i.e., 0
1213    NegativeInt16_0,    // i.e., -1
1214    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    // These are like the ones above, but for unsigned types. The situation is slightly simpler
1247    // as we don't have negatives, so the width is the whole distance from the family's first
1248    // tag, and the fixed-width tag is again the widest member.
1249    UInt8_0, // i.e., 0
1250    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    /// The tag's discriminant, usable in const context.
1275    #[allow(clippy::as_conversions)]
1276    const fn byte(self) -> u8 {
1277        self as u8
1278    }
1279}
1280
1281/// Assert that the listed tags are consecutive, in the order given.
1282///
1283/// Every family below is addressed by arithmetic rather than by name: `push_datum` writes
1284/// `first + n` for a payload of `n` bytes, and `read_signed_varint`/`read_unsigned_varint`
1285/// invert that by subtraction. A variant inserted into the middle of a family, or two members
1286/// swapped, silently changes how many bytes a tag claims, which corrupts the datum rather than
1287/// failing to compile. These assertions turn that into a compile error at the definition.
1288macro_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
1351// --------------------------------------------------------------------------------
1352// reading data
1353
1354/// Read a byte slice starting at byte `offset`.
1355///
1356/// Updates `offset` to point to the first byte after the end of the read region.
1357fn 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/// Read a byte slice preceded by its length, the width of the length prefix given by the tag's
1366/// distance from `first`, its kind's `*Tiny` tag.
1367///
1368/// Each arm reads the prefix at a constant width, which is a plain load; deriving the width and
1369/// reading that many bytes measured twice as slow on long payloads.
1370///
1371/// # Safety
1372///
1373/// The contents are whatever `push_lengthed_bytes` wrote, so a caller may treat them as UTF-8
1374/// only for a `String` tag.
1375#[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/// The payload of a variable-length integer whose datum ends within eight bytes of the end of
1396/// `data`, so the wide load in [`read_varint_word`] would run off the end.
1397///
1398/// Out of line and cold: this is at most the tail of a row, or of a nested list or map.
1399#[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    // Each arm reads a constant width, which is a load rather than a `memcpy`. This path serves
1409    // the last datum or two of every row, which at low arity is a real share of all datums.
1410    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        // An eight-byte payload needs eight bytes past the tag, which this path's caller found
1420        // wanting, so a valid row cannot reach here.
1421        _ => panic!("payload runs past the end of the row"),
1422    }
1423}
1424
1425/// Read the `len` payload bytes of a variable-length integer, returning them in the low
1426/// `len * 8` bits of a word. Bits above that are zero or belong to whatever follows in the row,
1427/// so a caller must mask them off.
1428///
1429/// Loading a fixed eight bytes is what keeps `len` out of the load, and so off a branch. Those
1430/// bytes exist except at the very end of the buffer.
1431#[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/// Mask covering the low `len` bytes of a word.
1442///
1443/// `len` reaches eight for a 64-bit value that needs every byte, where a shift of 64 would be
1444/// undefined, so that case saturates instead.
1445#[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/// The low `N` bytes of `word`, little-endian.
1455#[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/// Read the payload of a variable-length integer of either sign, extended to `N` bytes.
1461///
1462/// A signed family alternates the two signs at each payload width, so the tag's distance from
1463/// `first` holds the width above its low bit and the sign in it. Both fall out by shifting and
1464/// masking, with no compare and nothing to dispatch on: a column's tag varies with the magnitude
1465/// and sign of every value, so any branch on it is one the predictor cannot learn.
1466///
1467/// # Correctness
1468///
1469/// `tag` must belong to the family starting at `first`, and `data` must hold its payload.
1470#[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    // All ones for a negative value, so the bytes above the payload sign-extend, and zero
1475    // otherwise. A `len` of zero leaves the whole word filled, which is the -1 the encoder means.
1476    let negative = delta & 1 == 1;
1477    read_varint_payload(data, len, negative)
1478}
1479
1480/// Read a `len` byte payload and extend it to `N` bytes, with ones above it when `negative`.
1481///
1482/// `len` must not exceed `N`, since `truncate` keeps only the low `N` bytes and a wider payload
1483/// would lose its top ones.
1484#[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/// Read the payload of an unsigned variable-length integer, zero-extended to `N` bytes.
1492///
1493/// As [`read_signed_varint`], without the sign.
1494///
1495/// # Correctness
1496///
1497/// `tag` must belong to the family starting at `first`, and `data` must hold its payload.
1498#[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
1528/// Read a datum starting at byte `offset`.
1529///
1530/// Updates `offset` to point to the first byte after the end of the read region.
1531///
1532/// # Safety
1533///
1534/// This function is safe if a `Datum` was previously written at this offset by `push_datum`.
1535/// Otherwise it could return invalid values, which is Undefined Behavior.
1536pub 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            // SAFETY: the bytes were written from a `str` under a `String` tag.
1679            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            // See the comment in `Row::push_array` for details on the encoding
1691            // of arrays.
1692            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            // TODO: if we refactor the decimal library to accept the owned
1719            // array as a parameter to `from_raw_parts` below, we could likely
1720            // avoid a copy because it is exactly the value we want
1721            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            // See notes on `push_range_with` for details about encoding.
1735            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
1789// --------------------------------------------------------------------------------
1790// writing data
1791
1792fn 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
1801/// Appends `tag`, the length of `bytes` in the width that `tag` stands for, and `bytes`.
1802fn 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
1872/// Returns an i64 representing a `NaiveDateTime`, if
1873/// said i64 can be round-tripped back to a `NaiveDateTime`.
1874///
1875/// The only exotic NDTs for which this can't happen are those that
1876/// are hundreds of years in the future or past, or those that
1877/// represent a leap second. (Note that Materialize does not support
1878/// leap seconds, but this module does).
1879// This function is inspired by `NaiveDateTime::timestamp_nanos`,
1880// with extra checking.
1881fn 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// This function is extremely hot, so
1891// we just use `as` to avoid the overhead of
1892// `try_into` followed by `unwrap`.
1893// `leading_ones` and `leading_zeros`
1894// can never return values greater than 64, so the conversion is safe.
1895#[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    // To fit in n bytes, we require that
1904    // everything but the leading sign bits fits in n*8
1905    // bits.
1906    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// In principle we could just use `min_bytes_signed`, rather than
1916// having a separate function here, as long as we made that one take
1917// `T: Into<i128>` instead of 64. But LLVM doesn't seem smart enough
1918// to realize that that function is the same as the current version,
1919// and generates worse code.
1920//
1921// Justification for `as` is the same as in `min_bytes_signed`.
1922#[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/// Appends `tag` followed by the first `len` bytes of `payload`, with a single write.
1940#[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    // NOTE: A write of the tag and one of the payload each check the capacity and move
1948    // the length of `data`, which is most of the cost of pushing a short datum.
1949    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            // The family alternates the signs at each width, so the width is two tags apart and
1965            // the sign is the low bit. The clamp folds both signs onto the widest tag, where the
1966            // payload carries its own sign. See `read_signed_varint`, which takes this apart.
1967            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            // The family alternates the signs at each width, so the width is two tags apart and
1976            // the sign is the low bit. The clamp folds both signs onto the widest tag, where the
1977            // payload carries its own sign. See `read_signed_varint`, which takes this apart.
1978            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            // The family alternates the signs at each width, so the width is two tags apart and
1987            // the sign is the low bit. The clamp folds both signs onto the widest tag, where the
1988            // payload carries its own sign. See `read_signed_varint`, which takes this apart.
1989            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            // See the comment in `Row::push_array` for details on the encoding
2087            // of arrays.
2088            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            // Pseudo-canonical representation of decimal values with
2104            // insignificant zeroes trimmed. This compresses the number further
2105            // than `Numeric::trim` by removing all zeroes, and not only those in
2106            // the fractional component.
2107            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            // Little endian machines can take the lsu directly from u16 to u8.
2121            if cfg!(target_endian = "little") {
2122                // SAFETY: `lsu` (returned by `coefficient_units()`) is a `&[u16]`, so
2123                // each element can safely be transmuted into two `u8`s.
2124                let (prefix, lsu_bytes, suffix) = unsafe { lsu.align_to::<u8>() };
2125                // The `u8` aligned version of the `lsu` should have twice as many
2126                // elements as we expect for the `u16` version.
2127                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                // There should be no unaligned elements in the prefix or suffix.
2134                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            // See notes on `push_range_with` for details about encoding.
2144            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
2169/// Return the number of bytes these Datums would use if packed as a Row.
2170pub fn row_size<'a, I>(a: I) -> usize
2171where
2172    I: IntoIterator<Item = Datum<'a>>,
2173{
2174    // Using datums_size instead of a.data().len() here is safer because it will
2175    // return the size of the datums if they were packed into a Row. Although
2176    // a.data().len() happens to give the correct answer (and is faster), data()
2177    // is documented as for debugging only.
2178    let sz = datums_size::<_, _>(a);
2179    let size_of_row = std::mem::size_of::<Row>();
2180    // The Row struct attempts to inline data until it can't fit in the
2181    // preallocated size. Otherwise it spills to heap, and uses the Row to point
2182    // to that.
2183    if sz > Row::SIZE {
2184        sz + size_of_row
2185    } else {
2186        size_of_row
2187    }
2188}
2189
2190/// Number of bytes required by the datum.
2191/// This is used to optimistically pre-allocate buffers for packing rows.
2192pub 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            // We use a variable length representation of slice length.
2225            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            // We use a variable length representation of slice length.
2235            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            // Values must be reduced to determine appropriate number of
2258            // coefficient units.
2259            numeric::cx_datum().reduce(&mut d);
2260            // 4 = 1 bit each for tag, digits, exponent, bits
2261            4 + (d.coefficient_units().len() * 2)
2262        }
2263        Datum::Range(Range { inner }) => {
2264            // Tag + flags
2265            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
2281/// Number of bytes required by a sequence of datums.
2282///
2283/// This method can be used to right-size the allocation for a `Row`
2284/// before calling [`RowPacker::extend`].
2285pub 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
2293/// Number of bytes required by a list of datums. This computes the size that would be required if
2294/// the given datums were packed into a list.
2295///
2296/// This is used to optimistically pre-allocate buffers for packing rows.
2297pub 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    /// Constructs a row packer that will pack additional datums into the
2307    /// provided row.
2308    ///
2309    /// This function is intentionally somewhat inconvenient to call. You
2310    /// usually want to call [`Row::packer`] instead to start packing from
2311    /// scratch.
2312    pub fn for_existing_row(row: &mut Row) -> RowPacker<'_> {
2313        RowPacker { row }
2314    }
2315
2316    /// Extend an existing `Row` with a `Datum`.
2317    #[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    /// Extend an existing `Row` with additional `Datum`s.
2326    #[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    /// Extend an existing `Row` with additional `Datum`s.
2338    ///
2339    /// In the case the iterator produces an error, the pushing of
2340    /// datums in terminated and the error returned. The `Row` will
2341    /// be incomplete, but it will be safe to read datums from it.
2342    #[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    /// Appends the datums of an entire `Row`.
2355    pub fn extend_by_row(&mut self, row: &Row) {
2356        self.row.data.extend_from_slice(row.data.as_slice());
2357    }
2358
2359    /// Appends the datums of an entire `Row`.
2360    pub fn extend_by_row_ref(&mut self, row: &RowRef) {
2361        self.row.data.extend_from_slice(row.data());
2362    }
2363
2364    /// Appends the slice of data representing an entire `Row`. The data is not validated.
2365    ///
2366    /// # Safety
2367    ///
2368    /// The requirements from [`Row::from_bytes_unchecked`] apply here, too:
2369    /// This method relies on `data` being an appropriate row encoding, and can
2370    /// result in unsafety if this is not the case.
2371    #[inline]
2372    pub unsafe fn extend_by_slice_unchecked(&mut self, data: &[u8]) {
2373        self.row.data.extend_from_slice(data)
2374    }
2375
2376    /// Pushes a [`DatumList`] that is built from a closure.
2377    ///
2378    /// The supplied closure will be invoked once with a `Row` that can be used
2379    /// to populate the list. It is valid to call any method on the
2380    /// [`RowPacker`] except for [`RowPacker::clear`], [`RowPacker::truncate`],
2381    /// or [`RowPacker::truncate_datums`].
2382    ///
2383    /// Returns the value returned by the closure, if any.
2384    ///
2385    /// ```
2386    /// # use mz_repr::{Row, Datum};
2387    /// let mut row = Row::default();
2388    /// row.packer().push_list_with(|row| {
2389    ///     row.push(Datum::String("age"));
2390    ///     row.push(Datum::Int64(42));
2391    /// });
2392    /// assert_eq!(
2393    ///     row.unpack_first().unwrap_list().iter().collect::<Vec<_>>(),
2394    ///     vec![Datum::String("age"), Datum::Int64(42)],
2395    /// );
2396    /// ```
2397    #[inline]
2398    pub fn push_list_with<F, R>(&mut self, f: F) -> R
2399    where
2400        F: FnOnce(&mut RowPacker) -> R,
2401    {
2402        // First, assume that the list will fit in 255 bytes, and thus the length will fit in
2403        // 1 byte. If not, we'll fix it up later.
2404        let start = self.row.data.len();
2405        self.row.data.push(Tag::ListTiny.into());
2406        // Write a dummy len, will fix it up later.
2407        self.row.data.push(0);
2408
2409        let out = f(self);
2410
2411        // The `- 1 - 1` is for the tag and the len.
2412        let len = self.row.data.len() - start - 1 - 1;
2413        // We now know the real len.
2414        if len < TINY {
2415            // If the len fits in 1 byte, we just need to fix up the len.
2416            self.row.data[start + 1] = len.to_le_bytes()[0];
2417        } else {
2418            // Note: We move this code path into its own function, so that the common case can be
2419            // inlined.
2420            long_list(&mut self.row.data, start, len);
2421        }
2422
2423        /// 1. Fix up the tag.
2424        /// 2. Move the actual data a bit (for which we also need to make room at the end).
2425        /// 3. Fix up the len.
2426        /// `data`: The row's backing data.
2427        /// `start`: where `push_list_with` started writing in `data`.
2428        /// `len`: the length of the data, excluding the tag and the length.
2429        #[cold]
2430        fn long_list(data: &mut CompactBytes, start: usize, len: usize) {
2431            // `len_len`: the length of the length. (Possible values are: 2, 4, 8. 1 is handled
2432            // elsewhere.) The other parameters are the same as for `long_list`.
2433            let long_list_inner = |data: &mut CompactBytes, len_len| {
2434                // We'll need memory for the new, bigger length, so make the `CompactBytes` bigger.
2435                // The `- 1` is because the old length was 1 byte.
2436                const ZEROS: [u8; 8] = [0; 8];
2437                data.extend_from_slice(&ZEROS[0..len_len - 1]);
2438                // Move the data to the end of the `CompactBytes`, to make space for the new length.
2439                // Originally, it started after the 1-byte tag and the 1-byte length, now it will
2440                // start after the 1-byte tag and the len_len-byte length.
2441                //
2442                // Note that this is the only operation in `long_list` whose cost is proportional
2443                // to `len`. Since `len` is at least 256 here, the other operations' cost are
2444                // negligible. `copy_within` is a memmove, which is probably a fair bit faster per
2445                // Datum than a Datum encoding in the `f` closure.
2446                data.copy_within(start + 1 + 1..start + 1 + 1 + len, start + 1 + len_len);
2447                // Write the new length.
2448                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    /// Pushes a [`DatumMap`] that is built from a closure.
2474    ///
2475    /// The supplied closure will be invoked once with a `Row` that can be used
2476    /// to populate the dict.
2477    ///
2478    /// The closure **must** alternate pushing string keys and arbitrary values,
2479    /// otherwise reading the dict will cause a panic.
2480    ///
2481    /// The closure **must** push keys in ascending order, otherwise equality
2482    /// checks on the resulting `Row` may be wrong and reading the dict IN DEBUG
2483    /// MODE will cause a panic.
2484    ///
2485    /// The closure **must not** call [`RowPacker::clear`],
2486    /// [`RowPacker::truncate`], or [`RowPacker::truncate_datums`].
2487    ///
2488    /// # Example
2489    ///
2490    /// ```
2491    /// # use mz_repr::{Row, Datum};
2492    /// let mut row = Row::default();
2493    /// row.packer().push_dict_with(|row| {
2494    ///
2495    ///     // key
2496    ///     row.push(Datum::String("age"));
2497    ///     // value
2498    ///     row.push(Datum::Int64(42));
2499    ///
2500    ///     // key
2501    ///     row.push(Datum::String("name"));
2502    ///     // value
2503    ///     row.push(Datum::String("bob"));
2504    /// });
2505    /// assert_eq!(
2506    ///     row.unpack_first().unwrap_map().iter().collect::<Vec<_>>(),
2507    ///     vec![("age", Datum::Int64(42)), ("name", Datum::String("bob"))]
2508    /// );
2509    /// ```
2510    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        // write a dummy len, will fix it up later
2517        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        // fix up the len
2523        self.row.data[start..start + size_of::<u64>()].copy_from_slice(&len.to_le_bytes());
2524
2525        res
2526    }
2527
2528    /// Like [`RowPacker::push_dict_with`], but accepts a fallible closure.
2529    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    /// Convenience function to construct an array from an iter of `Datum`s.
2537    ///
2538    /// Returns an error if the number of elements in `iter` does not match
2539    /// the cardinality of the array as described by `dims`, or if the
2540    /// number of dimensions exceeds [`MAX_ARRAY_DIMENSIONS`]. If an error
2541    /// occurs, the packer's state will be unchanged.
2542    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        // SAFETY: The function returns the exact number of elements pushed into the array.
2552        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    /// Like [`RowPacker::try_push_array`], but accepts a fallible iterator of
2565    /// elements.
2566    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        // SAFETY: The function returns the exact number of elements pushed into the array.
2587        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    /// Convenience function to construct an array from a function. The function must return the
2605    /// number of elements it pushed into the array. It is undefined behavior if the function returns
2606    /// a number different to the number of elements it pushed.
2607    ///
2608    /// Returns an error if the number of elements pushed by `f` does not match
2609    /// the cardinality of the array as described by `dims`, or if the
2610    /// number of dimensions exceeds [`MAX_ARRAY_DIMENSIONS`], or if `f` errors. If an error
2611    /// occurs, the packer's state will be unchanged.
2612    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        // Arrays are encoded as follows.
2622        //
2623        // u8    ndims
2624        // u64   dim_0 lower bound
2625        // u64   dim_0 length
2626        // ...
2627        // u64   dim_n lower bound
2628        // u64   dim_n length
2629        // u64   element data size in bytes
2630        // u8    element data, where elements are encoded in row-major order
2631
2632        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        // Write dimension information.
2640        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        // Write elements.
2653        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        // Check that the number of elements written matches the dimension
2666        // information.
2667        let cardinality = match dims {
2668            [] => 0,
2669            // Saturate the product: a cardinality that overflows `usize` is
2670            // impossibly large (no array can hold that many elements), so it can
2671            // never equal the actual `nelements` and the check below rejects it as
2672            // `WrongCardinality`. A plain `product()` would panic under overflow
2673            // checks (debug/fuzz) and silently wrap in release — and a wrapped
2674            // value could even spuriously match `nelements`, accepting a corrupt
2675            // array (e.g. dims claiming `[2^32, 2^32]` wrap to 0 elements).
2676            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    /// Pushes an [`Array`] that is built from a closure.
2694    ///
2695    /// __WARNING__: This is fairly "sharp" tool that is easy to get wrong. You
2696    /// should prefer [`RowPacker::try_push_array`] when possible.
2697    ///
2698    /// Returns an error if the number of elements pushed does not match
2699    /// the cardinality of the array as described by `dims`, or if the
2700    /// number of dimensions exceeds [`MAX_ARRAY_DIMENSIONS`]. If an error
2701    /// occurs, the packer's state will be unchanged.
2702    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        // Write dummy dimension length for now, we'll fix it up.
2715        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            // Saturate: an overflowing cardinality is impossibly large and is
2723            // rejected by the `nelements` check below. See the matching note in
2724            // `push_array_with_unchecked`.
2725            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            // Reset the packer state so we don't have invalid data.
2737            self.row.data.truncate(start);
2738            return Err(InvalidArrayError::TooManyDimensions(usize::from(num_dims)));
2739        }
2740        // Fix up our dimension length.
2741        self.row.data[dims_start..dims_start + size_of::<u8>()]
2742            .copy_from_slice(&num_dims.to_le_bytes());
2743
2744        // Write elements.
2745        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        // Check that the number of elements written matches the dimension
2754        // information.
2755        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    /// Convenience function to push a `DatumList` from an iter of `Datum`s
2771    ///
2772    /// See [`RowPacker::push_dict_with`] if you need to be able to handle errors
2773    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    /// Convenience function to push a `DatumMap` from an iter of `(&str, Datum)` pairs
2786    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    /// Pushes a `Datum::Range` derived from the `Range<Datum<'a>`.
2800    ///
2801    /// # Panics
2802    /// - If lower and upper express finite values and they are datums of
2803    ///   different types.
2804    /// - If lower or upper express finite values and are equal to
2805    ///   `Datum::Null`. To handle `Datum::Null` properly, use
2806    ///   [`RangeBound::new`].
2807    ///
2808    /// # Notes
2809    /// - This function canonicalizes the range before pushing it to the row.
2810    /// - Prefer this function over `push_range_with` because of its
2811    ///   canonicaliztion.
2812    /// - Prefer creating [`RangeBound`]s using [`RangeBound::new`], which
2813    ///   handles `Datum::Null` in a SQL-friendly way.
2814    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                // Untagged bytes only contains the `RANGE_EMPTY` flag value.
2820                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    /// Pushes a `DatumRange` built from the specified arguments.
2843    ///
2844    /// # Warning
2845    /// Unlike `push_range`, `push_range_with` _does not_ canonicalize its
2846    /// inputs. Consequentially, this means it's possible to generate ranges
2847    /// that will not reflect the proper ordering and equality.
2848    ///
2849    /// # Panics
2850    /// - If lower or upper expresses a finite value and does not push exactly
2851    ///   one value into the `RowPacker`.
2852    /// - If lower and upper express finite values and they are datums of
2853    ///   different types.
2854    /// - If lower or upper express finite values and push `Datum::Null`.
2855    ///
2856    /// # Notes
2857    /// - Prefer `push_range_with` over this function. This function should be
2858    ///   used only when you are not pushing `Datum`s to the inner row.
2859    /// - Range encoding is `[<flag bytes>,<lower>?,<upper>?]`, where `lower`
2860    ///   and `upper` are optional, contingent on the flag value expressing an
2861    ///   empty range (where neither will be present) or infinite bounds (where
2862    ///   each infinite bound will be absent).
2863    /// - To push an emtpy range, use `push_range` using `Range { inner: None }`.
2864    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        // Validate the invariants that 0, 1, or 2 elements were pushed, none are Null,
2911        // and if two are pushed then the second is not less than the first. Panic in
2912        // some cases and error in others.
2913        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            // These checks only fail when decoding untrusted/corrupted bytes;
2919            // valid callers always push consistent, non-null bounds. Return an
2920            // error rather than asserting so a crafted proto doesn't panic.
2921            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    /// Clears the contents of the packer without de-allocating its backing memory.
2954    pub fn clear(&mut self) {
2955        self.row.data.clear();
2956    }
2957
2958    /// Truncates the underlying storage to the specified byte position.
2959    ///
2960    /// # Safety
2961    ///
2962    /// `pos` MUST specify a byte offset that lies on a datum boundary.
2963    /// If `pos` specifies a byte offset that is *within* a datum, the row
2964    /// packer will produce an invalid row, the unpacking of which may
2965    /// trigger undefined behavior!
2966    ///
2967    /// To find the byte offset of a datum boundary, inspect the packer's
2968    /// byte length by calling `packer.data().len()` after pushing the desired
2969    /// number of datums onto the packer.
2970    pub unsafe fn truncate(&mut self, pos: usize) {
2971        self.row.data.truncate(pos)
2972    }
2973
2974    /// Truncates the underlying row to contain at most the first `n` datums.
2975    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        // SAFETY: iterator offsets always lie on a datum boundary.
2981        unsafe { self.truncate(prev_len - next_len) }
2982    }
2983
2984    /// Returns the total amount of bytes used by the underlying row.
2985    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    /// Debug representation using the internal datums
3000    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    /// Display representation using the internal datums
3009    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    /// Iterate elements as typed `T` values rather than raw `Datum`s.
3027    ///
3028    /// Each datum is decoded and converted via [`FromDatum`]. Since generic
3029    /// type parameters in `#[sqlfunc]` are erased to `Datum<'a>` before code
3030    /// generation, this is monomorphized to an identity conversion at runtime.
3031    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    /// For debugging only
3042    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    /// Iterate entries as `(&str, T)` pairs rather than `(&str, Datum)`.
3088    ///
3089    /// Each value datum is converted via [`FromDatum`]. Since generic type
3090    /// parameters in `#[sqlfunc]` are erased to `Datum<'a>` before code
3091    /// generation, this is monomorphized to an identity conversion at runtime.
3092    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    /// For debugging only
3103    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            // SAFETY: the bytes were written from a `str` under a `String` tag.
3146            let key = unsafe { str::from_utf8_unchecked(bytes) };
3147            let val = unsafe { read_datum(&mut self.data) };
3148
3149            // Gate the `prev_key` bookkeeping on the same flag as the assert it feeds, so builds
3150            // with soft assertions off pay nothing for it.
3151            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    /// Creates a `RowArena` that reports itself [`RowArena::over_budget`] once it holds more than
3186    /// `budget` bytes.
3187    ///
3188    /// The budget is advisory to the arena itself: pushes still succeed, because handing back a
3189    /// truncated value would corrupt the datum. It is the caller's job to poll `over_budget` at a
3190    /// point where it can fail, so the bytes an arena actually reaches is `budget` plus whatever the
3191    /// operation in flight at the time added.
3192    ///
3193    /// NOTE: a budget bounds a single ad-hoc evaluation in a shared process (see
3194    /// `mz_adapter::webhook`). It must not be given to an arena that feeds a compute dataflow. A
3195    /// dataflow re-evaluates the same expression against the same input and must return the same
3196    /// result every time. Whether an evaluation is over budget depends on what else the arena has
3197    /// accumulated, and the webhook budget is a runtime dyncfg, so a budgeted dataflow arena would
3198    /// make the result depend on when it ran. Differential then turns a changed-but-not-retracted
3199    /// result into non-accumulating diffs that corrupt the collection. A dataflow that ever needs a
3200    /// budget must fix it for the lifetime of a cluster replica.
3201    pub fn with_budget(budget: usize) -> Self {
3202        RowArena {
3203            budget: Some(budget),
3204            ..RowArena::new()
3205        }
3206    }
3207
3208    /// Bytes this arena currently holds.
3209    pub fn allocated_bytes(&self) -> usize {
3210        self.allocated.get()
3211    }
3212
3213    /// Whether this arena holds more than its budget. Always false without one.
3214    pub fn over_budget(&self) -> bool {
3215        self.budget
3216            .is_some_and(|budget| self.allocated.get() > budget)
3217    }
3218
3219    /// Bytes this arena can still take before it is [`RowArena::over_budget`], or `usize::MAX`
3220    /// without a budget.
3221    ///
3222    /// Intended for an operation that can predict its own size and would rather fail than build a
3223    /// value it is about to be told is too big.
3224    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    /// Creates a `RowArena` with an initial region sized to hold `capacity` bytes, to avoid
3232    /// reallocations as the first datums are created in the arena.
3233    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    /// Ensures the active region can hold at least `additional` more bytes without allocating a
3245    /// new region. Call this when you expect to push roughly `additional` bytes next.
3246    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            // The active region is empty, so nothing references it yet and it is safe to grow it
3253            // in place (a reallocation cannot dangle a live reference).
3254            Some(active) if active.is_empty() => {
3255                if active.capacity() < additional {
3256                    active.reserve_exact(additional);
3257                }
3258            }
3259            // The active region holds live data; we cannot grow it without moving those bytes, so
3260            // stage a fresh region. Size it like `push_bytes` does (at least double the current
3261            // region) so a sequence of small `reserve`s still yields at most log-many regions
3262            // rather than many small ones.
3263            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    /// Copies `bytes` into the arena and returns a reference valid for its lifetime.
3272    ///
3273    /// Accepts anything that derefs to `[u8]` (e.g. `Vec<u8>`, `&[u8]`); the bytes are copied, so
3274    /// the caller's allocation is not retained.
3275    #[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        // Find or create a region with spare capacity for `need` bytes, never growing a region
3285        // that already holds data (see the type-level comment for why this preserves references).
3286        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 = &region[start..];
3300        unsafe {
3301            // This is safe because:
3302            //   * `copied` references bytes inside `region`'s heap buffer, which we just sized to
3303            //     fit without reallocating; that buffer is never resized again while it holds data
3304            //     (we allocate a new region instead), so the reference stays valid.
3305            //   * The buffer lives as long as the arena: regions are only dropped by `clear`/`drop`,
3306            //     both of which take `&mut`/ownership, so no `&'a self`-tied reference can outlive
3307            //     them.
3308            //   * Pushing further regions may reallocate `self.inner`, but that moves only the
3309            //     `Vec<u8>` headers, not the heap buffers they own.
3310            transmute::<&[u8], &'a [u8]>(copied)
3311        }
3312    }
3313
3314    /// Moves `bytes` into the arena and returns a reference valid for its lifetime.
3315    ///
3316    /// Prefer this to [`RowArena::push_bytes`] whenever the bytes are already owned: a value large
3317    /// enough that it would get a region to itself has its allocation adopted as that region, rather
3318    /// than a fresh region being allocated and copied into, which for a large value halves the peak.
3319    /// Smaller values are copied, so the arena keeps bump allocating.
3320    pub fn push_owned_bytes<'a>(&'a self, bytes: Vec<u8>) -> &'a [u8] {
3321        /// Never adopt below this, however empty the arena. `last_cap` alone would let every value
3322        /// on a fresh or small arena look big enough, and then each gets an exactly-sized region
3323        /// with no headroom: one region and one `Vec<u8>` header per value.
3324        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        // Adopt only when `push_bytes` would have given these bytes a dedicated, `need`-sized region
3333        // anyway, i.e. when `need` exceeds the `last_cap * 2` it would otherwise allocate. There's
3334        // no headroom to lose, so adoption saves a copy for free. Below that we copy, because
3335        // `push_bytes` grows a region *with* headroom that later values reuse. Adopting there would
3336        // defeat the bump allocator: adoption leaves an empty region (capacity 0) on top, so nothing
3337        // would ever grow a region with headroom again.
3338        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        // `push_bytes` would allocate a fresh region here and copy into it, so adopt the caller's
3346        // allocation as that region. Sound for the same reasons as `push_bytes`: the reference
3347        // points into a heap buffer the arena now owns for `'a`, and the buffer is never resized
3348        // while it holds data.
3349        //
3350        // Inserted *below* the active region rather than appended, because `push_bytes` sizes a new
3351        // region as twice the last one's capacity: leaving a large adopted buffer on top would make
3352        // the next push allocate twice its size.
3353        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            // There was no active region to insert below, so keep an empty one on top for the same
3358            // reason. `Vec::new` does not allocate.
3359            inner.push(Vec::new());
3360        }
3361        let adopted = &inner[idx][..];
3362        unsafe { transmute::<&[u8], &'a [u8]>(adopted) }
3363    }
3364
3365    /// Moves `string` into the arena and returns a reference valid for its lifetime.
3366    pub fn push_string<'a>(&'a self, string: String) -> &'a str {
3367        let copied = self.push_owned_bytes(string.into_bytes());
3368        unsafe {
3369            // This is safe because we just moved in the bytes of a valid `String`.
3370            std::str::from_utf8_unchecked(copied)
3371        }
3372    }
3373
3374    /// Returns a growable, writeable byte buffer for assembling a value incrementally.
3375    ///
3376    /// Write into it with [`RowArenaBuf::push`], [`RowArenaBuf::extend_from_slice`], or
3377    /// [`std::io::Write`], then call [`RowArenaBuf::finish`] to copy the result into the arena and
3378    /// obtain a reference valid for the arena's lifetime. The backing buffer is a single scratch
3379    /// allocation reused across writers, so this lets a producer that builds bytes piecewise (e.g.
3380    /// decoding a row) avoid managing its own scratch.
3381    ///
3382    /// Nested writers are sound but not free: a writer obtained while another is still live can't
3383    /// reuse the (in-use) scratch, so it allocates its own buffer. Steady-state, non-nested use
3384    /// stays allocation-free.
3385    pub fn writer(&self) -> RowArenaBuf<'_> {
3386        // Take the recycled buffer if one is available, else allocate a fresh one. The cell is
3387        // borrowed only for this `take`, never for the writer's lifetime, so a nested `writer` call
3388        // doesn't double-borrow: it simply finds the slot empty and allocates its own buffer.
3389        let mut buf = self.scratch.borrow_mut().take().unwrap_or_default();
3390        buf.clear();
3391        RowArenaBuf { arena: self, buf }
3392    }
3393
3394    /// Take ownership of `row` for the lifetime of the arena, returning a
3395    /// reference to the first datum in the row.
3396    ///
3397    /// If we had an owned datum type, this method would be much clearer, and
3398    /// would be called `push_owned_datum`.
3399    pub fn push_unary_row<'a>(&'a self, row: Row) -> Datum<'a> {
3400        let copied = self.push_bytes(row.data());
3401        unsafe {
3402            // This is safe because `copied` is a valid encoding of a single datum (we just packed
3403            // it into `row`), backed by the arena for the lifetime `'a`. Copying the bytes also
3404            // sidesteps the `Row`'s inline (`SmallVec`) storage entirely.
3405            let datum = read_datum(&mut &copied[..]);
3406            transmute::<Datum<'_>, Datum<'a>>(datum)
3407        }
3408    }
3409
3410    /// Equivalent to `push_unary_row` but returns a `DatumNested` rather than a
3411    /// `Datum`.
3412    fn push_unary_row_datum_nested<'a>(&'a self, row: Row) -> DatumNested<'a> {
3413        let copied = self.push_bytes(row.data());
3414        unsafe {
3415            // Safe for the same reasons as `push_unary_row`.
3416            let nested = DatumNested::extract(&mut &copied[..]);
3417            transmute::<DatumNested<'_>, DatumNested<'a>>(nested)
3418        }
3419    }
3420
3421    /// Convenience function to make a new `Row` containing a single datum, and
3422    /// take ownership of it for the lifetime of the arena
3423    ///
3424    /// ```
3425    /// # use mz_repr::{RowArena, Datum};
3426    /// let arena = RowArena::new();
3427    /// let datum = arena.make_datum(|packer| {
3428    ///   packer.push_list(&[Datum::String("hello"), Datum::String("world")]);
3429    /// });
3430    /// assert_eq!(datum.unwrap_list().iter().collect::<Vec<_>>(), vec![Datum::String("hello"), Datum::String("world")]);
3431    /// ```
3432    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    /// Convenience function to build a list datum from an iterator of typed
3442    /// elements and return it as a `DatumList<'a, T>`.
3443    ///
3444    /// By accepting an iterator of `T: Borrow<Datum>` instead of a raw
3445    /// `RowPacker` closure, this guarantees that only elements of type `T`
3446    /// are pushed.
3447    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    /// Convenience function identical to `make_datum` but instead returns a
3462    /// `DatumNested`.
3463    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    /// Like [`RowArena::make_datum`], but the provided closure can return an error.
3473    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    /// Clear the contents of the arena.
3483    ///
3484    /// Retains the single largest region (emptied) so the arena can be reused without
3485    /// reallocating; a workload that clears between uses of similar size becomes allocation-free.
3486    pub fn clear(&mut self) {
3487        let inner = self.inner.get_mut();
3488        // Keep only the largest-capacity region, reset to empty, and drop the rest. Because region
3489        // capacities only ever grow (each new region at least doubles the previous), the largest is
3490        // normally the last; we scan for it defensively, which is cheap given log-many regions.
3491        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/// A growable, writeable byte buffer that builds a value into a [`RowArena`].
3507///
3508/// Obtained from [`RowArena::writer`]. Behaves like a writeable byte slice (push/extend bytes,
3509/// read back as `&[u8]`); [`RowArenaBuf::finish`] copies the assembled bytes into the arena and
3510/// returns a reference valid for the arena's lifetime. The buffer is owned for the writer's
3511/// lifetime and, on drop, returned to the arena to be reused by the next writer.
3512#[derive(Debug)]
3513pub struct RowArenaBuf<'a> {
3514    arena: &'a RowArena,
3515    buf: Vec<u8>,
3516}
3517
3518impl<'a> RowArenaBuf<'a> {
3519    /// Appends a single byte.
3520    pub fn push(&mut self, byte: u8) {
3521        self.buf.push(byte);
3522    }
3523
3524    /// Appends a slice of bytes.
3525    pub fn extend_from_slice(&mut self, bytes: &[u8]) {
3526        self.buf.extend_from_slice(bytes);
3527    }
3528
3529    /// The bytes written so far.
3530    pub fn as_slice(&self) -> &[u8] {
3531        &self.buf
3532    }
3533
3534    /// The number of bytes written so far.
3535    pub fn len(&self) -> usize {
3536        self.buf.len()
3537    }
3538
3539    /// Whether no bytes have been written.
3540    pub fn is_empty(&self) -> bool {
3541        self.buf.is_empty()
3542    }
3543
3544    /// Copies the written bytes into the arena, returning a reference valid for its lifetime.
3545    pub fn finish(self) -> &'a [u8] {
3546        // `self` is dropped at the end of this call, returning `buf` to the arena for reuse; the
3547        // returned reference points into a committed region, not `buf`, so it stays valid.
3548        self.arena.push_bytes(self.buf.as_slice())
3549    }
3550
3551    /// Like [`RowArenaBuf::finish`], but returns the bytes as a `&str`.
3552    ///
3553    /// Intended for buffers written via [`std::fmt::Write`] (e.g. `write!`), whose contents are
3554    /// valid UTF-8. Panics if the bytes are not valid UTF-8.
3555    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        // Return the buffer to the arena so the next writer can reuse its allocation. We keep only
3564        // one buffer: if the slot is already occupied — an outer writer is still live, or a nested
3565        // writer beat us to it — we drop ours rather than growing an unbounded pool. The borrow is
3566        // transient and never overlaps a live writer's, so this can't double-borrow.
3567        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/// A thread-local row, which can be borrowed and returned.
3600/// # Example
3601///
3602/// Use this type instead of creating a new row:
3603/// ```
3604/// use mz_repr::SharedRow;
3605///
3606/// let mut row_builder = SharedRow::get();
3607/// ```
3608///
3609/// This allows us to reuse an existing row allocation instead of creating a new one or retaining
3610/// an allocation locally. Additionally, we can observe the size of the local row in a central
3611/// place and potentially reallocate to reduce memory needs.
3612///
3613/// # Panic
3614///
3615/// [`SharedRow::get`] panics when trying to obtain multiple references to the shared row.
3616#[derive(Debug)]
3617pub struct SharedRow(Row);
3618
3619impl SharedRow {
3620    thread_local! {
3621        /// A thread-local slot containing a shared Row that can be temporarily used by a function.
3622        /// There can be at most one active user of this Row, which is tracked by the state of the
3623        /// `Option<_>` wrapper. When it is `Some(..)`, the row is available for using. When it
3624        /// is `None`, it is not, and the constructor will panic if a thread attempts to use it.
3625        static SHARED_ROW: Cell<Option<Row>> = const { Cell::new(Some(Row::empty())) }
3626    }
3627
3628    /// Get the shared row.
3629    ///
3630    /// The row's contents are cleared before returning it.
3631    ///
3632    /// # Panic
3633    ///
3634    /// Panics when the row is already borrowed elsewhere.
3635    pub fn get() -> Self {
3636        let mut row = Self::SHARED_ROW
3637            .take()
3638            .expect("attempted to borrow already borrowed SharedRow");
3639        // Clear row
3640        row.packer();
3641        Self(row)
3642    }
3643
3644    /// Gets the shared row and uses it to pack `iter`.
3645    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        // Take the Row allocation from this instance and put it back in the thread local slot for
3674        // the next user. The Row in `self` is replaced with an empty Row which does not allocate.
3675        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    // StableRow's wire format is proto bytes, not the in-memory datum
3695    // encoding, so rows of every column type must roundtrip exactly through
3696    // both a self-describing format (JSON) and a compact binary one
3697    // (bincode). Equality on Row compares the packed in-memory bytes, so
3698    // this also catches any datum normalization sneaking into the
3699    // Row -> ProtoRow -> Row conversion.
3700    proptest! {
3701        #![proptest_config(ProptestConfig::with_cases(1000))]
3702
3703        #[mz_ore::test]
3704        #[cfg_attr(miri, ignore)] // too slow, and decNumber uses FFI
3705        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    /// Every width a variable-length integer can take, at both ends of its range and either
3723    /// side of each byte boundary, plus the values whose payload is empty.
3724    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        // One below, at, and one above every point where the payload grows a byte.
3748        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    /// Both signed families of a width share one match arm, which recovers the payload width by
3783    /// subtracting the family's first tag. A value whose tag falls outside the family it is
3784    /// decoded as would read the wrong number of bytes, so check every boundary lands where the
3785    /// arithmetic expects.
3786    #[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                // Interleaved: the width sits above the low bit, the sign in it. At the widest
3805                // width the alternation stops, one tag serving both signs.
3806                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    /// The wide load in `read_varint_word` reads eight bytes whatever the payload's width, so
3817    /// the datums at the end of a row, where those bytes do not exist, take the tail path.
3818    #[mz_ore::test]
3819    fn varint_at_end_of_row_reads_exact_width() {
3820        for datum in varint_edge_cases() {
3821            // Alone in a row, and behind padding long enough to push the fast path back in.
3822            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            // And nested, where the list's slice ends before the row's data does.
3834            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    // Regression: comparing deeply nested list values must not overflow the
3847    // stack (STACK-7). `Datum` ordering recurses once per nesting level.
3848    #[mz_ore::test]
3849    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
3850    fn cmp_deep_nested_list_does_not_overflow() {
3851        fn deep() -> Row {
3852            // `push_list` byte-copies the inner value, so building does not recurse.
3853            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            // if you want to run this on a big-endian cpu, we'll need big-endian versions of the serialization code
3878            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        // References returned by `push_bytes` must stay valid as later pushes allocate new
3911        // regions; this exercises the "never resize a region that holds data" invariant.
3912        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        // A row pushed after other bytes lands at a non-zero offset within a region; reading it
3928        // back must not depend on the row starting at offset zero or on any alignment.
3929        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        // After `clear` the arena retains a region and remains usable across cycles.
3939        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        // `push_owned_bytes` adopts a buffer too large for the active region instead of copying it,
3954        // which puts a region the arena never wrote into in the middle of the stack. References
3955        // handed out before and after that must all stay valid.
3956        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        // A small buffer fits the active region, so it is copied rather than given a region.
3961        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        // Adoption never *creates* a region with headroom: it inserts the caller's buffer, whose
3975        // capacity equals its length, below whatever is on top. Only `push_bytes` grows the arena
3976        // geometrically (`new_cap = max(need, last_cap * 2)`), so once the active region cannot fit
3977        // an incoming value it never can again and every later owned push adopts: one retained
3978        // allocation and one `Vec<u8>` header per value, rather than `O(log n)` regions. That is the
3979        // default path for every `String`- and `Vec<u8>`-returning scalar function, and the arenas
3980        // in the MFP and join paths outlive a single row, so the region list grows with the number
3981        // of string values in a batch. `RowArena::clear` scans every region, so it degrades too.
3982        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        // The bump allocator working as intended, as the baseline to hold the owned path to.
3996        let copied = RowArena::new();
3997        push_all(&copied, false);
3998
3999        let owned = RowArena::new();
4000        push_all(&owned, true);
4001
4002        // Seeding with ordinary copies first must not change the answer. The arena never recovers,
4003        // so this is not just the empty-arena case where the placeholder on top has capacity 0.
4004        let seeded = RowArena::new();
4005        let _ = seeded.push_bytes(VALUE.as_bytes());
4006        push_all(&seeded, true);
4007
4008        // Compare against the copy path rather than an absolute count, so this pins the property (a
4009        // run of small owned pushes still ends with a region that has headroom) and leaves the
4010        // adoption predicate to the fix.
4011        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        // Without a budget nothing is ever over it, however much is pushed.
4022        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        // Staying within the budget leaves it satisfied, and the remaining count tracks what a
4032        // caller that predicts its own size would consult.
4033        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        // Crossing it reports, rather than refusing the push: a truncated push would corrupt the
4039        // datum, so the value is intact and it is the caller's job to fail.
4040        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        // An adopted buffer counts against the budget too, or adoption would be a way around it.
4046        // Large enough to actually be adopted rather than copied.
4047        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        // Build a value incrementally and commit it.
4063        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        // A second writer reuses the scratch; its result is independent of the first, which stays
4078        // valid because `finish` copied it into the arena.
4079        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        // An empty writer commits to an empty slice.
4086        let empty: &[u8] = &[];
4087        assert_eq!(arena.writer().finish(), empty);
4088
4089        // Abandoning a writer without finishing is fine; the next writer starts empty.
4090        {
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        // Reentrancy: a writer obtained while another is still live must not panic (no `RefCell`
4100        // double-borrow) and must not disturb the outer writer. The nested writer just gets its own
4101        // buffer; the outer one keeps building independently.
4102        let arena = RowArena::new();
4103
4104        let mut outer = arena.writer();
4105        outer.extend_from_slice(b"outer-before-");
4106
4107        // Take a second writer while `outer` is still live -- the case that double-borrowed before.
4108        let inner_bytes = {
4109            let mut inner = arena.writer();
4110            inner.extend_from_slice(b"inner");
4111            // The outer writer is unaffected by the nested one.
4112            assert_eq!(outer.as_slice(), b"outer-before-");
4113            inner.finish()
4114        };
4115        assert_eq!(inner_bytes, b"inner");
4116
4117        // `outer` is intact and still writable after the nested writer committed.
4118        outer.extend_from_slice(b"after");
4119        let outer_bytes = outer.finish();
4120        assert_eq!(outer_bytes, b"outer-before-after");
4121        // Both committed slices stay valid and independent.
4122        assert_eq!(inner_bytes, b"inner");
4123
4124        // Once all writers have dropped, the recycled buffer is reusable (and cleared on acquire).
4125        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        // Format text into the writer (e.g. building a cast-to-string result) and commit as `&str`.
4135        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            // When run under miri this catches undefined bytes written to data
4149            // eg by calling push_copy! on a type which contains undefined padding values
4150            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        // Construct an array using `Row::push_array` and verify that it unpacks
4223        // correctly.
4224        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        // Pack a previously-constructed `Datum::Array` and verify that it
4241        // unpacks correctly.
4242        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        // An array with one too many dimensions should be rejected.
4291        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        // An array with exactly the maximum allowable dimensions should be
4305        // accepted.
4306        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        // Dimension lengths whose product overflows `usize` must be rejected as
4349        // a `WrongCardinality` error, not panic (under overflow checks) or wrap
4350        // (in release, which could spuriously accept a corrupt array). The
4351        // product saturates to `usize::MAX`, which no real element count matches.
4352        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)] // unsupported operation: can't call foreign function `decNumberFromInt32` on OS `linux`
4436    fn test_datum_sizes() {
4437        let arena = RowArena::new();
4438
4439        // Test the claims about various datum sizes.
4440        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        // A finite bound whose closure pushes zero values violates the
4542        // `push_range_with` caller contract and still panics. This is
4543        // unreachable when decoding a `ProtoRow`: each decoded bound pushes
4544        // exactly one datum (or fails), so only an in-process caller can hit it.
4545        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)] // not using enhanced panic handler in tests
4550            let result = std::panic::catch_unwind(|| test_range_errors_inner(panicking_case));
4551            assert_err!(result);
4552        }
4553
4554        // Inconsistent bound counts, mismatched datum kinds, and Null bounds are
4555        // all reachable from a crafted/corrupted `ProtoRow`, so they return an
4556        // error instead of panicking.
4557        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    /// Lists have a variable-length encoding for their lengths. We test each case here.
4581    #[mz_ore::test]
4582    #[cfg_attr(miri, ignore)] // slow
4583    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                // Push some stuff.
4595                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            // Check that we read back exactly what we pushed.
4605            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); // tiny
4625        test_list_encoding_inner(TINY + 1); // short
4626        test_list_encoding_inner(SHORT + 1); // long
4627
4628        // The biggest one takes 40 s on my laptop, probably not worth it.
4629        //test_list_encoding_inner(LONG + 1); // huge
4630    }
4631
4632    /// Demonstrates that DatumList's Eq (bytewise) and Ord (datum-by-datum) are now consistent.
4633    /// A list containing -0.0 and one containing +0.0 have different byte representations
4634    /// (IEEE 754 distinguishes them), originally Eq says they are not equal. But after
4635    /// using the new Datum::cmp, Eq says they are equal, which matches what Ord
4636    /// compares via iter().cmp(other.iter()), and them as equal.
4637    #[mz_ore::test]
4638    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
4639    fn test_datum_list_eq_ord_consistency() {
4640        // Build list containing +0.0
4641        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        // Build list containing -0.0 (distinct bit pattern from +0.0)
4648        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        // Eq is bytewise: different encodings => not equal
4655        // This was a bug in the past, so we test it.
4656        assert_eq!(
4657            list_pos, list_neg,
4658            "Eq should see different encodings as equal"
4659        );
4660
4661        // Ord is datum-by-datum: -0.0 and +0.0 compare equal as Datums
4662        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    /// Demonstrates that DatumMap's derived Eq (bytewise) can make maps with equal keys and
4670    /// values compare equal when values have different encodings (e.g. -0.0 vs +0.0).
4671    #[mz_ore::test]
4672    fn test_datum_map_eq_bytewise_consistency() {
4673        // Build map {"k": +0.0}
4674        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        // Build map {"k": -0.0}
4682        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        // Same keys and semantically equal values, but Eq (bytewise) says not equal
4690        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        // Verify they have the same logical content
4695        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    /// Hash must agree with Eq: equal lists must have the same hash.
4708    #[mz_ore::test]
4709    fn test_datum_list_hash_consistency() {
4710        // Equal lists (including -0.0 vs +0.0) must hash the same
4711        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        // Unequal lists should have different hashes (with asymptotic probability 1)
4731        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    /// Ord/PartialOrd for DatumList: less, equal, greater.
4754    #[mz_ore::test]
4755    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
4756    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        // [1, 2] < [1, 3] due to the second element being different
4780        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        // shorter prefix compares less
4784        assert_eq!(list_12.cmp(&list_123), Ordering::Less);
4785    }
4786
4787    /// Hash must agree with Eq: equal maps must have the same hash.
4788    #[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    /// Ord/PartialOrd for DatumMap: less, equal, greater (by key then value).
4834    #[mz_ore::test]
4835    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
4836    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); // "a" < "b"
4862    }
4863
4864    /// Datum puts Null last in the enum so that nulls sort last (PostgreSQL default).
4865    /// This ordering is used when comparing DatumList/DatumMap (e.g. jsonb_agg tiebreaker).
4866    #[mz_ore::test]
4867    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
4868    fn test_datum_list_and_map_null_sorts_last() {
4869        // DatumList: [1] < [null] so non-null sorts before null
4870        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        // DatumMap: {"k": 1} < {"k": null} so non-null sorts before null (same as jsonb_agg)
4886        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}