Skip to main content

rudb_vector/
vector.rs

1//! The vector itself.
2//!
3//! `spec/07-execution.md` section 7.1 calls this the widest interface in the system, says every
4//! operator depends on it, and says changing it after twenty operators exist is expensive. So it
5//! is written before the first operator rather than after the fifth.
6//!
7//! A vector is a type, a length of at most [`VECTOR_SIZE`], a physical form, a validity
8//! representation and some data. Four of the forms are the ones in `spec/04-architecture.md`
9//! section 4.3: flat, constant, sequence and dictionary. Run length, bit packed and string view come
10//! after them, one at a time with the kernels that read them rather than all at once ahead of
11//! anything that can use them.
12//!
13//! Dictionary and run length are the pair worth understanding together, because they answer
14//! different questions about the same column. A dictionary says which distinct values there are, so
15//! it wins on low cardinality however the rows are ordered. Run length says where the values stop,
16//! so it wins on a clustered column however many distinct values it has. A column can want either
17//! one without wanting the other, and `hits` has columns of both kinds.
18//!
19//! String view is the odd one out, because it is not about making a column smaller. It is about who
20//! owns the bytes: the views are the vector's and the arena is shared, so cutting a chunk out of a
21//! page of strings moves sixteen bytes a row and copies none of the payload. Every other form here
22//! trades a little work per row for less memory, and that one trades nothing at all.
23//!
24//! The nested forms are the odd ones out in a different direction. The forms above are all ways of
25//! writing a column of scalars down more cheaply, and a nested value is not a scalar at all, so
26//! [`Form::List`] and [`Form::Struct`] are each the only form their column has rather than one of
27//! several it could be in. A list is a child vector of every element plus a start and a length per
28//! row. A struct is one child per field with no entries at all, because a struct row holds one value
29//! per field rather than a run of them. Either way the children are ordinary vectors and can be in any
30//! of the forms above, which is where a nested column gets made smaller.
31//!
32//! **What is not here yet.** Buffers are owned. Section 7.1 says a vector borrowed from a buffer
33//! managed page carries a pin, and there is no buffer manager until M2, so there is nothing to pin
34//! and pretending otherwise would be an interface built against an imaginary caller. `ARRAY` is not
35//! stored yet either, and it is a composition of what is here rather than a new shape: it is a list
36//! whose length is the type's rather than the row's, the way a `MAP` is a list whose child is a two
37//! field struct of keys and values. `UNION` is the one that is genuinely different, since it is one
38//! child per member plus a tag saying which member each row is in.
39
40use std::borrow::Cow;
41use std::cmp::Ordering;
42use std::sync::Arc;
43
44use rudb_common::{Cause, Error, Field, LogicalType, Result, Value, slow};
45
46use crate::buffer::Buffer;
47use crate::fsst::SymbolTable;
48use crate::string::{StringColumn, StringView};
49use crate::validity::Validity;
50
51/// How many values are in a full vector.
52///
53/// 1024 rather than DuckDB's 2048, per `spec/04-architecture.md` section 4.3. It is the FastLanes
54/// unit, it makes a validity mask exactly 16 `u64` words, and it keeps a vector of 16 byte string
55/// views at 16 KiB, which is the size at which several of these fit in L1 together rather than
56/// evicting each other.
57pub const VECTOR_SIZE: usize = 1024;
58
59/// What the key field of a map's child struct is called.
60///
61/// A map is stored as a list of two field structs, and these are the two names. They are DuckDB's, and
62/// they are also the names the Parquet specification gives a map's repeated group, so a reader that
63/// builds one of these from a file finds the names already agreed rather than translated.
64pub const MAP_KEY: &str = "key";
65
66/// What the value field of a map's child struct is called. See [`MAP_KEY`].
67pub const MAP_VALUE: &str = "value";
68
69/// What [`Vector::map_parts`] hands back: one entry per row, then the keys and then the values.
70///
71/// A name rather than the triple written out, because the triple written out is over the complexity
72/// clippy allows and because a kernel that takes these as an argument should be able to say so in one
73/// word.
74pub type MapParts<'a> = (&'a [(u32, u32)], &'a Vector, &'a Vector);
75
76/// Which physical form a vector is in.
77///
78/// An operator asks this once per vector and then takes the path it wants, which is the one branch
79/// per vector that the whole design is willing to spend.
80///
81/// Not exhaustive, and that is a decision rather than an oversight. `Encoded` is the fifth form
82/// and it arrives at layer three with the specialization contract. If this enum were exhaustive,
83/// the day it lands is the day every kernel in the workspace stops compiling, and the pressure at
84/// that moment would be to add an arm to each of them in a hurry rather than to think about what
85/// each one should do with an encoded vector. A required fallback arm means each kernel already
86/// has a correct answer for a form it has never seen, and specializing it is then a change that
87/// can be made one kernel at a time with a benchmark next to it.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
89#[non_exhaustive]
90pub enum Form {
91    /// One value per position.
92    Flat,
93    /// One value, repeated.
94    Constant,
95    /// A start and a step, computed rather than stored.
96    Sequence,
97    /// Codes into a smaller vector of distinct values.
98    Dictionary,
99    /// Integers stored in as many bits as the range of the column needs, offset from a base.
100    ///
101    /// The form a narrow integer column is in. A ClickBench `ResolutionWidth` is a `SMALLINT` whose
102    /// values live between 0 and 2560, which is twelve bits, so the column is three quarters of the
103    /// size it was and the pages behind it are three quarters of the reads. What it costs is a shift
104    /// and a mask per value, which is why this is worth it at storage and at rest and is not a form
105    /// anything should be building in the middle of a pipeline.
106    BitPacked,
107    /// Sixteen byte views over an arena the vector shares rather than owns.
108    ///
109    /// The form a varchar column is in once more than one vector is looking at the same page. A flat
110    /// varchar vector owns its arena, so cutting a chunk out of it copies every byte of every long
111    /// string in the range, and on ClickBench that is most of what reading `URL` costs. Sharing the
112    /// arena makes the cut the views and nothing else, the way a dictionary cut is the codes and
113    /// nothing else.
114    StringView,
115    /// Strings compressed against one symbol table, each row on its own.
116    ///
117    /// The form a text column is in at rest. FSST is about half the bytes on the ClickBench `URL`
118    /// and `Title` columns, and unlike a block compressor it keeps random access, so reading row
119    /// four million does not decompress the four million before it. What it costs is a decompression
120    /// per row read, which is why an equality filter over it is worth writing in code space: the
121    /// literal compresses once and the rows never decompress at all.
122    Fsst,
123    /// One value per run, with the row each run ends at.
124    ///
125    /// The form a clustered column is in. `hits` is written in time order, so `EventDate` is a few
126    /// hundred runs over a hundred million rows, and a sum over it is a few hundred multiplications
127    /// rather than a hundred million additions. Dictionary says which distinct values there are and
128    /// this says where they stop, and a column can want either one without wanting the other.
129    Rle,
130    /// A child vector of every element, and a start and a length per row.
131    ///
132    /// The form a `LIST` column is in, and the only form it has. The others are all ways of writing
133    /// down a column of scalars more cheaply and this is the shape a nested value has at all, so a
134    /// list vector reports this whether or not anything has tried to make it smaller. Making it
135    /// smaller happens in the child, which is an ordinary vector and can be any of the forms above.
136    ///
137    /// A `MAP` column reports this too, because a map is a list whose child is a two field struct and
138    /// the bytes really are a list's. This enum is about the physical layout, and the logical type is
139    /// what remembers the difference, which is the same division `LogicalType::physical` already makes.
140    List,
141    /// One child vector per field, each as long as the vector itself.
142    ///
143    /// The form a `STRUCT` column is in, and the only form it has, for the reason [`Form::List`] is
144    /// the only form a list has. A struct holds exactly one value per field per row rather than a run
145    /// of them, so there are no entries here and the children line up with the rows one to one, which
146    /// makes a cut a cut of every child and a gather a gather of every child. Each child is an
147    /// ordinary vector and can be in any of the forms above, so that is where a struct column gets
148    /// made smaller.
149    Struct,
150}
151
152/// The values of a flat vector, one Rust vector per physical type.
153///
154/// The variants are physical rather than logical, which is what lets `DATE` and `INTEGER` share
155/// storage and share a kernel. What a run of `i32` means is the vector's logical type's business.
156#[derive(Debug, Clone, PartialEq)]
157#[non_exhaustive]
158pub enum Data {
159    /// No values, for the type of an untyped `NULL`.
160    Empty,
161    /// One byte per value.
162    Bool(Buffer<bool>),
163    /// 8 bit signed.
164    Int8(Buffer<i8>),
165    /// 16 bit signed.
166    Int16(Buffer<i16>),
167    /// 32 bit signed.
168    Int32(Buffer<i32>),
169    /// 64 bit signed.
170    Int64(Buffer<i64>),
171    /// 128 bit signed.
172    Int128(Buffer<i128>),
173    /// 8 bit unsigned.
174    UInt8(Buffer<u8>),
175    /// 16 bit unsigned.
176    UInt16(Buffer<u16>),
177    /// 32 bit unsigned.
178    UInt32(Buffer<u32>),
179    /// 64 bit unsigned.
180    UInt64(Buffer<u64>),
181    /// 128 bit unsigned.
182    UInt128(Buffer<u128>),
183    /// IEEE 754 binary32.
184    Float32(Buffer<f32>),
185    /// IEEE 754 binary64.
186    Float64(Buffer<f64>),
187    /// The months, days and microseconds triple.
188    Interval(Buffer<(i32, i32, i64)>),
189    /// Strings, as 16 byte views plus the arena the long ones live in.
190    Varlen(StringColumn),
191}
192
193impl Data {
194    /// How many values are stored.
195    ///
196    /// The match below has no wildcard arm, and that is what makes this function the check that
197    /// keeps [`for_each_layout`](crate::for_each_layout) honest. A variant added to this enum
198    /// without being added to the `all` group fails to compile here, which is a line in a build log
199    /// rather than a layout quietly missing from six kernels.
200    #[must_use]
201    pub fn len(&self) -> usize {
202        macro_rules! lengths {
203            ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
204                match self {
205                    Self::Empty => 0,
206                    $(Self::$variant(values) => values.len(),)+
207                }
208            };
209        }
210        crate::for_each_layout!(all, lengths)
211    }
212
213    /// Whether there are no values.
214    #[must_use]
215    pub fn is_empty(&self) -> bool {
216        self.len() == 0
217    }
218
219    /// How many bytes of memory these values are holding.
220    ///
221    /// One arm per layout through the same macro as [`Data::len`], for the same reason: a layout
222    /// added without a size here is a layout the memory limit would charge nothing for, and a
223    /// buffer that is free is a buffer that can be grown until the process dies.
224    #[must_use]
225    pub fn footprint(&self) -> usize {
226        macro_rules! sizes {
227            ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
228                match self {
229                    Self::Empty => 0,
230                    $(Self::$variant(values) => values.footprint(),)+
231                }
232            };
233        }
234        crate::for_each_layout!(all, sizes)
235    }
236
237    /// An integer at `index`, widened, for any of the signed integer layouts.
238    ///
239    /// Used by the decimal path, which needs the unscaled value out of whichever width the width
240    /// and scale picked, and by anything else that would otherwise repeat the same five arms.
241    #[must_use]
242    pub fn signed_at(&self, index: usize) -> Option<i128> {
243        macro_rules! widened {
244            ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
245                match self {
246                    $(Self::$variant(v) => v.get(index).map(|&x| i128::from(x)),)+
247                    _ => None,
248                }
249            };
250        }
251        crate::for_each_layout!(signed, widened)
252    }
253
254    /// An unsigned integer at `index`, widened.
255    #[must_use]
256    pub fn unsigned_at(&self, index: usize) -> Option<u128> {
257        macro_rules! widened {
258            ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
259                match self {
260                    $(Self::$variant(v) => v.get(index).map(|&x| u128::from(x)),)+
261                    _ => None,
262                }
263            };
264        }
265        crate::for_each_layout!(unsigned, widened)
266    }
267
268    /// The string at `index`, for a `Varlen`.
269    #[must_use]
270    pub fn str_at(&self, index: usize) -> Option<&str> {
271        match self {
272            Self::Varlen(column) => column.get(index),
273            _ => None,
274        }
275    }
276
277    /// The bytes at `index`, for a `Varlen`, whatever they are.
278    ///
279    /// What a `BLOB` reads through, since the bytes of one are not required to be text and
280    /// [`Self::str_at`] answers `None` for the ones that are not.
281    #[must_use]
282    pub fn bytes_at(&self, index: usize) -> Option<&[u8]> {
283        match self {
284            Self::Varlen(column) => column.bytes(index),
285            _ => None,
286        }
287    }
288}
289
290/// A type, a length, a validity representation and some data.
291#[derive(Debug, Clone, PartialEq)]
292pub struct Vector {
293    ty: LogicalType,
294    len: usize,
295    validity: Validity,
296    body: Body,
297}
298
299/// What the vector holds, which is what its form is decided by.
300#[derive(Debug, Clone, PartialEq)]
301enum Body {
302    Flat(Data),
303    Constant(Box<Value>),
304    Sequence {
305        start: i64,
306        step: i64,
307    },
308    /// The values are behind an `Arc` rather than a `Box` because slicing shares them.
309    ///
310    /// A dictionary vector is cut once per chunk and the dictionary itself is the same dictionary
311    /// every time, so a `Box` meant a copy of every value in it per cut. On the ClickBench columns
312    /// that are dictionary encoded the dictionary is larger than the chunk of codes pointing into
313    /// it, and copying it was ten percent of the cycles of reading the file.
314    ///
315    /// Nothing here mutates a dictionary in place, so sharing one is only ever a read, and the one
316    /// place that wants an owned copy of the values is [`compose`], which asks for one.
317    Dictionary {
318        codes: Vec<u32>,
319        values: Arc<Vector>,
320        stable: bool,
321    },
322    /// Integer codes of `width` bits each, packed end to end, each one an offset from `base`.
323    ///
324    /// Row `r` is the `width` bits starting at bit `(offset + r) * width`, read little end first, so
325    /// a code that straddles a word boundary has its low bits in the earlier word. `offset` is what
326    /// lets a cut of a packed column be free: the bits are not byte aligned, so a slice either
327    /// repacks or remembers where it starts, and remembering is one addition per read.
328    ///
329    /// The words are behind an `Arc` for the reason the dictionary's values are. A page is packed
330    /// once and cut into chunk sized pieces, and copying the words per cut would undo most of what
331    /// the packing saved.
332    Packed {
333        words: Arc<Vec<u64>>,
334        width: u32,
335        base: i128,
336        offset: usize,
337    },
338    /// The views of a string column, over an arena that other vectors are reading at the same time.
339    ///
340    /// The views are owned because a cut is a different run of views, and the arena is shared
341    /// because a cut is the same bytes. That split is the whole form: sixteen bytes a row move and
342    /// the payload does not, however many cuts a page is taken in.
343    ///
344    /// A row's bytes are found the same way [`StringColumn`] finds them, through
345    /// [`StringView::bytes_in`], so a short string never reads the arena at all and the two ways of
346    /// holding strings cannot answer a row differently.
347    Views {
348        views: Vec<StringView>,
349        arena: Arc<Buffer<u8>>,
350    },
351    /// Text owned by a storage source and fetched by position.
352    ExternalText {
353        source: Arc<dyn TextSource>,
354    },
355    /// The FSST codes of every row, end to end, with one symbol table over all of them.
356    ///
357    /// A span rather than a run of offsets, because a gather keeps this form and a gather puts the
358    /// rows in an order the codes are not in. Eight bytes a row either way, and the span is the one
359    /// that survives being permuted.
360    ///
361    /// The codes and the table are shared for the reason a dictionary's values are: one table is
362    /// trained per page and every chunk cut out of it points at the same one. A table is sixty five
363    /// thousand hash slots, so a table per chunk would cost more than the compression saves.
364    Coded {
365        codes: Arc<Vec<u8>>,
366        spans: Vec<(u32, u32)>,
367        table: Arc<SymbolTable>,
368    },
369    /// One value per run, with the row each run ends at, exclusive and increasing.
370    ///
371    /// Ends rather than lengths, because every reader of this wants to know which run holds a row
372    /// and ends answer that with a binary search while lengths answer it with a running total. The
373    /// two are the same information and only one of them is the one that gets asked for.
374    ///
375    /// The values are behind an `Arc` for the reason the dictionary's are: a page is cut into chunk
376    /// sized pieces and the values are the same values every time.
377    Runs {
378        ends: Vec<u32>,
379        values: Arc<Vector>,
380    },
381    /// One child vector holding every element of every row, and a start and a length per row.
382    ///
383    /// Start and length rather than the run of offsets Arrow carries, because offsets say where a
384    /// row ends by saying where the next one begins, and that is only true while the rows are in
385    /// order and none is skipped. A gather permutes the rows and a filter drops them, both of which
386    /// this form has to survive without copying the child, so each row says where its own elements
387    /// are and nothing is implied about its neighbour.
388    ///
389    /// The child is behind an `Arc` for the reason a dictionary's values are. A cut of a list column
390    /// is the entries and nothing else, so a page of lists taken in chunk sized pieces holds one
391    /// child however many pieces it is read in, and the elements outside the cut stay reachable but
392    /// unreferenced rather than being copied out.
393    ///
394    /// A null list and an empty list are different rows and this is where the difference lives. A
395    /// null is the validity mask at this level being false, the same as for any other type, and its
396    /// entry is `(start, 0)` and never read. An empty list is a valid row whose entry is `(start, 0)`
397    /// as well. So the entry alone does not say which one a row is, the mask does, which is the same
398    /// division of labour every other form here uses.
399    ///
400    /// A `MAP` is stored here too, with a [`Body::Fields`] child of `key` and `value`. Everything above
401    /// is true of it unchanged, which is the point of storing it this way: the cut, the gather and the
402    /// null rule are written once and a map inherits all three.
403    Nested {
404        entries: Vec<(u32, u32)>,
405        child: Arc<Vector>,
406    },
407    /// One child vector per field, in the order the type names them, each as long as this vector.
408    ///
409    /// No entries, which is the whole difference from [`Body::Nested`]. A list row is a run of
410    /// elements so it needs to say where its run is, and a struct row is one value per field so row
411    /// `r` of field `f` is position `r` of child `f` and there is nothing to record. That makes a cut
412    /// a cut of every child and a gather a gather of every child, both at the same positions, rather
413    /// than a rewrite of an index.
414    ///
415    /// The children are behind an `Arc` for the reason a dictionary's values are, and it pays off less
416    /// often here. A cut of a list column shares its child untouched because the entries carry the
417    /// range, and a cut of a struct column has to cut each child, so the sharing only survives the
418    /// cases where nothing moves. It is still worth having, because a struct of a hundred fields
419    /// handed between operators is a hundred pointers rather than a hundred columns.
420    ///
421    /// A null struct is the validity mask at this level being false and says nothing about the
422    /// children, which still hold whatever was put in them at that row. That is DuckDB's behaviour and
423    /// it is the reason this form cannot decide a row is null by looking down: the mask is the answer,
424    /// the same as it is for a list.
425    Fields {
426        children: Vec<Arc<Vector>>,
427    },
428}
429
430/// Random access to immutable text kept by a storage reader.
431pub trait TextSource: std::fmt::Debug + Send + Sync {
432    /// Number of values available.
433    fn len(&self) -> usize;
434    /// Whether this source has no values.
435    fn is_empty(&self) -> bool {
436        self.len() == 0
437    }
438    /// Bytes at one position, or no value when the position is outside the source.
439    fn bytes_at(&self, index: usize) -> Result<Option<&[u8]>>;
440    /// Byte length at one position without requiring the payload when the source has an index.
441    fn bytes_len_at(&self, index: usize) -> Result<Option<usize>> {
442        Ok(self.bytes_at(index)?.map(<[u8]>::len))
443    }
444    /// Resident bytes retained by this source.
445    fn footprint(&self) -> usize;
446    /// How many ranks this source's sorted value order has, when it has one.
447    ///
448    /// A rank is a position in the values sorted by their bytes, so rank zero is the smallest value
449    /// and rank `ranks() - 1` is the largest. A storage format that keeps a dictionary for a whole
450    /// column can afford to sort the distinct values once when it writes the file, and what that
451    /// buys is a binary search where a reader that only knows the values are distinct has to ask
452    /// every one of them whether it matches.
453    ///
454    /// `None` means the source does not know its order, which is the honest answer for anything
455    /// built in memory and for a file written before its format stored one. Nothing is allowed to
456    /// depend on this for correctness, only for speed.
457    ///
458    /// A source that answers with `Some` promises the ranks cover every value it has, and that
459    /// [`compare_rank`](Self::compare_rank) is consistent with an ordering in which the values are
460    /// strictly increasing. Strictly, which is to say the values are distinct, because what reads
461    /// this searches it, and a search of a run of equal values finds one of them rather than all of
462    /// them. A source that holds the same value twice must answer `None` here even though it could
463    /// sort itself perfectly well.
464    fn ranks(&self) -> Option<usize> {
465        None
466    }
467    /// How the value at `rank` compares against `wanted`.
468    ///
469    /// This is a method rather than a slice of positions the caller indexes because the answer is
470    /// the only thing a search wants, and a source that knows that can answer most probes without
471    /// reading a value at all. A file that stores the first few bytes of each value in rank order
472    /// settles every probe from those bytes except the ones where two values start the same way,
473    /// and the payload stays untouched. A caller handed positions instead would have to read a
474    /// value per probe, which for a dictionary of half a million entries spread over thirty
475    /// megabytes is a fresh block of the file every time.
476    ///
477    /// Only called for a rank below [`ranks`](Self::ranks), so the default is the error a source
478    /// that has no order should never be asked to produce.
479    fn compare_rank(&self, rank: usize, wanted: &[u8]) -> Result<Ordering> {
480        let _ = (rank, wanted);
481        Err(Error::internal("a text source without a sorted order was asked to compare a rank"))
482    }
483    /// The position of the value at `rank`, which is what a search returns once it has found one.
484    ///
485    /// Called about once per search rather than once per probe, so unlike
486    /// [`compare_rank`](Self::compare_rank) it is free to be the expensive one.
487    fn code_at_rank(&self, rank: usize) -> Result<u32> {
488        let _ = rank;
489        Err(Error::internal("a text source without a sorted order was asked for a rank"))
490    }
491    /// Whether another source presents the same values.
492    fn equal(&self, other: &dyn TextSource) -> bool {
493        self.len() == other.len()
494            && (0..self.len()).all(|index| {
495                matches!(
496                    (self.bytes_at(index), other.bytes_at(index)),
497                    (Ok(left), Ok(right)) if left == right
498                )
499            })
500    }
501}
502
503impl PartialEq for dyn TextSource {
504    fn eq(&self, other: &Self) -> bool {
505        self.equal(other)
506    }
507}
508
509impl Vector {
510    /// A flat vector of `data`, all valid.
511    ///
512    /// # Errors
513    ///
514    /// If the data's physical layout is not the one the type calls for. That check is here rather
515    /// than left to the caller because a vector whose type and layout disagree is a wrong answer
516    /// waiting to be read out, and it costs one comparison at construction to prevent.
517    pub fn flat(ty: LogicalType, data: Data) -> Result<Self> {
518        let len = data.len();
519        if !matches!(data, Data::Empty) && layout_of(&data) != ty.physical() {
520            return Err(Error::internal(format!(
521                "a {ty} vector cannot hold {:?} data",
522                layout_of(&data)
523            )));
524        }
525        Ok(Self { ty, len, validity: Validity::AllValid, body: Body::Flat(data) })
526    }
527
528    /// A flat vector built from single values, with the nulls among them turning into validity.
529    ///
530    /// The slow way in, and the only way in that anything outside this crate has. It is what an
531    /// `INSERT`, a `VALUES` clause and a test build a column with, all of which arrive holding
532    /// values rather than a run of `i32`. Nothing on a scan path calls it: a scan produces a run of
533    /// data directly and hands it to [`Self::flat`].
534    ///
535    /// # Errors
536    ///
537    /// If a value is not one the type can hold, or if the type is one there is no vector for yet,
538    /// which today means `ARRAY` and `UNION`. A `LIST`, a `STRUCT` and a `MAP` are routed to their own
539    /// builders and come back built.
540    pub fn from_values(ty: LogicalType, values: &[Value]) -> Result<Self> {
541        match &ty {
542            LogicalType::List(element) => {
543                return Self::list_from_values(element.as_ref().clone(), values);
544            }
545            LogicalType::Struct(fields) => return Self::struct_from_values(fields, values),
546            LogicalType::Map(key, value) => {
547                return Self::map_from_values(key.as_ref().clone(), value.as_ref().clone(), values);
548            }
549            _ => {}
550        }
551        let mut data = empty_data_for(&ty)?;
552        for value in values {
553            push_value(&mut data, value)?;
554        }
555        let validity = Validity::from_iter(values.len(), |index| !values[index].is_null());
556        Ok(Self { ty, len: values.len(), validity, body: Body::Flat(data) })
557    }
558
559    /// A list vector of `element`, built from one [`Value::List`] per row.
560    ///
561    /// The elements of every row go into one child vector end to end, so a row's elements are a
562    /// contiguous range of it and a row is a start and a length into it. That is what makes a cut of
563    /// this form the entries and nothing else.
564    ///
565    /// A null row contributes no elements and gets an entry of length zero, which is the same entry
566    /// an empty list gets. The two are told apart by the validity mask rather than by the entry, for
567    /// the reason written on [`Body::Nested`].
568    fn list_from_values(element: LogicalType, values: &[Value]) -> Result<Self> {
569        let mut flat = Vec::new();
570        let mut entries = Vec::with_capacity(values.len());
571        for value in values {
572            let start = u32::try_from(flat.len())
573                .map_err(|_| Error::internal("a list column with more than u32 elements in it"))?;
574            match value {
575                Value::Null => entries.push((start, 0)),
576                Value::List { values: held, .. } => {
577                    let len = u32::try_from(held.len())
578                        .map_err(|_| Error::internal("a list longer than u32"))?;
579                    flat.extend_from_slice(held);
580                    entries.push((start, len));
581                }
582                other => {
583                    return Err(Error::internal(format!(
584                        "{other:?} does not belong in a list vector"
585                    )));
586                }
587            }
588        }
589        // The element type is the column's rather than any one value's. A `Value::List` carries what
590        // it thinks it is empty of, and a column built from a row of `INTEGER[]` and a row of
591        // `[]::NULL[]` would otherwise take its type from whichever row came first.
592        let child = Self::from_values(element, &flat)?;
593        let validity = Validity::from_iter(values.len(), |index| !values[index].is_null());
594        Ok(Self {
595            ty: LogicalType::list(child.ty.clone()),
596            len: values.len(),
597            validity,
598            body: Body::Nested { entries, child: Arc::new(child) },
599        })
600    }
601
602    /// A list vector over a child that already exists, one entry per row.
603    ///
604    /// What a scan and a list returning kernel build, both of which produce the elements in bulk and
605    /// then say which row each range belongs to. Every row is valid, since a caller with nulls to
606    /// record adds them with [`Self::with_validity`].
607    ///
608    /// # Errors
609    ///
610    /// If an entry runs past the end of the child, which would be a row that reads elements belonging
611    /// to nobody and is the one mistake this form makes easy.
612    pub fn list(entries: Vec<(u32, u32)>, child: Vector) -> Result<Self> {
613        let reach = child.len();
614        for &(start, len) in &entries {
615            if start as usize + len as usize > reach {
616                return Err(Error::internal(format!(
617                    "a list entry of {len} at {start} in a child of {reach}"
618                )));
619            }
620        }
621        Ok(Self {
622            ty: LogicalType::list(child.ty.clone()),
623            len: entries.len(),
624            validity: Validity::AllValid,
625            body: Body::Nested { entries, child: Arc::new(child) },
626        })
627    }
628
629    /// A struct vector of `fields`, built from one [`Value::Struct`] per row.
630    ///
631    /// One pass per field rather than one pass per row, because each field becomes its own child
632    /// vector and a child is built from a run of values of one type. So a struct of three fields over
633    /// a thousand rows is three calls to [`Self::from_values`] and not a thousand.
634    ///
635    /// The fields are matched by name and not by position. A `Value::Struct` carries its names, and a
636    /// caller that built one in a different order from the type's would otherwise get the values
637    /// silently transposed into the wrong columns, which is the kind of wrong answer that reads as
638    /// right. A row missing a field the type names is an error rather than a null for the same reason.
639    ///
640    /// A null row is a null in every child as well as a false bit in the mask here. [`Body::Fields`]
641    /// says a null struct is allowed to have readable children and that is about a struct built out of
642    /// children that already exist, where whatever is underneath is the caller's. Built from values
643    /// there is nothing underneath to keep, so the children get the null.
644    fn struct_from_values(fields: &[Field], values: &[Value]) -> Result<Self> {
645        let mut children = Vec::with_capacity(fields.len());
646        for field in fields {
647            let mut column = Vec::with_capacity(values.len());
648            for value in values {
649                column.push(match value {
650                    Value::Null => Value::Null,
651                    Value::Struct(held) => held
652                        .iter()
653                        .find(|(name, _)| *name == field.name)
654                        .map(|(_, held)| held.clone())
655                        .ok_or_else(|| {
656                            Error::internal(format!(
657                                "a struct row with no {} field in it",
658                                field.name
659                            ))
660                        })?,
661                    other => {
662                        return Err(Error::internal(format!(
663                            "{other:?} does not belong in a struct vector"
664                        )));
665                    }
666                });
667            }
668            children.push(Arc::new(Self::from_values(field.ty.clone(), &column)?));
669        }
670        let validity = Validity::from_iter(values.len(), |index| !values[index].is_null());
671        Ok(Self {
672            ty: LogicalType::Struct(fields.to_vec()),
673            len: values.len(),
674            validity,
675            body: Body::Fields { children },
676        })
677    }
678
679    /// A struct vector over children that already exist, one per field.
680    ///
681    /// What a scan and a struct returning kernel build, both of which produce each field as a column
682    /// and then put them side by side. Every row is valid, since a caller with nulls to record adds
683    /// them with [`Self::with_validity`].
684    ///
685    /// # Errors
686    ///
687    /// If there are no fields, or if the children are not all the same length. The first is not a
688    /// fussy restriction: a struct vector with no children has no child to take its length from, so a
689    /// zero field struct column would be a length with nothing to check it against, and a caller that
690    /// wants a column of empty structs wants a constant vector of one.
691    pub fn structure(children: Vec<(String, Vector)>) -> Result<Self> {
692        let Some((_, first)) = children.first() else {
693            return Err(Error::internal("a struct vector of no fields, which has no length"));
694        };
695        let len = first.len();
696        for (name, child) in &children {
697            if child.len() != len {
698                return Err(Error::internal(format!(
699                    "a {} field of {} rows beside a struct of {len}",
700                    name,
701                    child.len()
702                )));
703            }
704        }
705        let fields = children
706            .iter()
707            .map(|(name, child)| Field::new(name.clone(), child.ty.clone()))
708            .collect();
709        let children = children.into_iter().map(|(_, child)| Arc::new(child)).collect();
710        Ok(Self {
711            ty: LogicalType::Struct(fields),
712            len,
713            validity: Validity::AllValid,
714            body: Body::Fields { children },
715        })
716    }
717
718    /// The children, for a struct vector, and `None` for any other form.
719    ///
720    /// The accessor a kernel over a struct column reads, and the reason field extraction is free:
721    /// picking one field out of a struct is picking one of these, so a projection of `s.a` hands back
722    /// a vector that already exists rather than reading a row at a time and rebuilding a column.
723    #[must_use]
724    pub fn struct_parts(&self) -> Option<&[Arc<Self>]> {
725        match &self.body {
726            Body::Fields { children } => Some(children),
727            _ => None,
728        }
729    }
730
731    /// A map vector, built from one [`Value::Map`] per row.
732    ///
733    /// A map is a list whose child is a two field struct of keys and values, which is what DuckDB
734    /// stores and what Arrow and Parquet store, so this is the list builder and the struct builder
735    /// composed rather than a third layout. The keys of every row go into one column end to end, the
736    /// values into another beside it, and a row is a start and a length into the pair.
737    ///
738    /// The field names are [`MAP_KEY`] and [`MAP_VALUE`] because those are the names DuckDB gives them
739    /// and the names anything reading a Parquet map field will expect to find.
740    ///
741    /// A null row and an empty map are both an entry of length zero, told apart by the validity mask,
742    /// for the reason written on [`Body::Nested`].
743    fn map_from_values(key: LogicalType, value: LogicalType, values: &[Value]) -> Result<Self> {
744        let mut keys = Vec::new();
745        let mut held = Vec::new();
746        let mut entries = Vec::with_capacity(values.len());
747        for row in values {
748            let start = u32::try_from(keys.len())
749                .map_err(|_| Error::internal("a map column with more than u32 entries in it"))?;
750            match row {
751                Value::Null => entries.push((start, 0)),
752                Value::Map { entries: pairs, .. } => {
753                    let len = u32::try_from(pairs.len())
754                        .map_err(|_| Error::internal("a map with more than u32 entries"))?;
755                    for (one, other) in pairs {
756                        keys.push(one.clone());
757                        held.push(other.clone());
758                    }
759                    entries.push((start, len));
760                }
761                other => {
762                    return Err(Error::internal(format!(
763                        "{other:?} does not belong in a map vector"
764                    )));
765                }
766            }
767        }
768        // The two types are the column's rather than any one row's, for the reason the list builder
769        // takes the element type from the column: a row that is the empty map carries whatever it was
770        // built as being empty of, and the column is not entitled to take its type from that.
771        let child = Self::structure(vec![
772            (MAP_KEY.to_string(), Self::from_values(key, &keys)?),
773            (MAP_VALUE.to_string(), Self::from_values(value, &held)?),
774        ])?;
775        let ty = LogicalType::map(
776            fields_of(&child.ty)[0].ty.clone(),
777            fields_of(&child.ty)[1].ty.clone(),
778        );
779        let validity = Validity::from_iter(values.len(), |index| !values[index].is_null());
780        Ok(Self {
781            ty,
782            len: values.len(),
783            validity,
784            body: Body::Nested { entries, child: Arc::new(child) },
785        })
786    }
787
788    /// A map vector over a pair of columns that already exist, one entry per row.
789    ///
790    /// What a scan and a map returning kernel build. The keys and the values are two columns of the
791    /// same length, and each row of the map is the same range of both. Every row is valid, since a
792    /// caller with nulls to record adds them with [`Self::with_validity`].
793    ///
794    /// # Errors
795    ///
796    /// If the two columns are different lengths, or if an entry runs past the end of them.
797    pub fn map(entries: Vec<(u32, u32)>, keys: Vector, values: Vector) -> Result<Self> {
798        let key = keys.ty.clone();
799        let value = values.ty.clone();
800        let child =
801            Self::structure(vec![(MAP_KEY.to_string(), keys), (MAP_VALUE.to_string(), values)])?;
802        let mut vector = Self::list(entries, child)?;
803        vector.ty = LogicalType::map(key, value);
804        Ok(vector)
805    }
806
807    /// The entries and the two columns, for a map vector, and `None` for anything else.
808    ///
809    /// Reaches through the struct child that a map is stored as, so that a kernel over a map column
810    /// reads the keys and the values as the two columns they are rather than having to know that the
811    /// pair is spelled as a struct underneath.
812    #[must_use]
813    pub fn map_parts(&self) -> Option<MapParts<'_>> {
814        if !matches!(self.ty, LogicalType::Map(_, _)) {
815            return None;
816        }
817        let (entries, child) = self.list_parts()?;
818        let [keys, values] = child.struct_parts()? else { return None };
819        Some((entries, keys, values))
820    }
821
822    /// The entries and the child, for a list vector, and `None` for any other form.
823    ///
824    /// The accessor a kernel over a list column reads, for the reason
825    /// [`Self::dictionary_parts`] exists: `unnest` over 1024 rows wants the child once and the
826    /// entries once, and reading it through [`Self::value_at`] would build a `Value::List` per row
827    /// and then throw every one of them away.
828    ///
829    /// A map answers here as well, with the struct child it is stored as, because this is a question
830    /// about the layout and a map's layout is a list's. A caller that wants the keys and the values as
831    /// two columns wants [`Self::map_parts`], which reaches through that child.
832    #[must_use]
833    pub fn list_parts(&self) -> Option<(&[(u32, u32)], &Self)> {
834        match &self.body {
835            Body::Nested { entries, child } => Some((entries, child)),
836            _ => None,
837        }
838    }
839
840    /// A vector of `len` copies of one value.
841    ///
842    /// Costs one value regardless of the length, which is what makes a literal in a predicate free
843    /// and what makes a projection of a constant free.
844    #[must_use]
845    pub fn constant(ty: LogicalType, value: Value, len: usize) -> Self {
846        let validity = if value.is_null() { Validity::AllInvalid } else { Validity::AllValid };
847        Self { ty, len, validity, body: Body::Constant(Box::new(value)) }
848    }
849
850    /// A vector of `len` values starting at `start` and stepping by `step`.
851    ///
852    /// This is what a row identifier column is, and it costs sixteen bytes rather than eight
853    /// kilobytes. A scan that produces row ids for a later fetch produces one of these.
854    #[must_use]
855    pub fn sequence(start: i64, step: i64, len: usize) -> Self {
856        Self {
857            ty: LogicalType::BigInt,
858            len,
859            validity: Validity::AllValid,
860            body: Body::Sequence { start, step },
861        }
862    }
863
864    /// A vector of codes into a smaller vector of distinct values.
865    ///
866    /// The form the whole M3 thesis rests on. A dictionary vector handed to a group by is an
867    /// integer column, and an aggregate over one is an aggregate over integers no matter what the
868    /// logical type says.
869    ///
870    /// A dictionary over a dictionary is composed into one level here rather than left as two, so
871    /// the form has a depth of one always and a kernel that reads [`Self::dictionary_parts`] is
872    /// reading the values rather than another layer of codes. Two filters over the same chunk build
873    /// the second case and four conjuncts pushed down separately build four of it.
874    ///
875    /// The cost of leaving them stacked turned out to be a cliff rather than a slope. Every loop in
876    /// `rudb-kernels` reaches for the values behind the codes with [`Self::data`], a dictionary
877    /// pointing at a dictionary has no data to hand back, so the second level does not make the
878    /// kernels slower, it turns them off and drops the work onto the row at a time path that exists
879    /// to be correct rather than fast. Measured on server3 over a chunk of two numeric columns and a
880    /// consumer of two vectorized passes, one level reads at 3.5 nanoseconds a row and two levels at
881    /// 104, and the third and fourth levels cost almost nothing more because the first one had
882    /// already given up everything there was to give. Composing is one pass over the outer codes,
883    /// which the range check above is already making.
884    ///
885    /// The one dictionary that is not composed past is one carrying a validity of its own. A
886    /// dictionary is built all valid and only [`Self::with_validity`] can change that, so such a
887    /// vector is saying that its nulls are at this level rather than in the values it points at, and
888    /// composing past it would drop them.
889    ///
890    /// # Errors
891    ///
892    /// If any code is past the end of the value vector.
893    pub fn dictionary(codes: Vec<u32>, values: Vector) -> Result<Self> {
894        Self::dictionary_over(codes, Arc::new(values))
895    }
896
897    /// The same, over a set of values somebody else is holding too.
898    ///
899    /// The body holds its values in an `Arc` either way, so a caller that already has one has
900    /// nothing to hand over but a pointer. The caller this is for is a Parquet chunk: one dictionary
901    /// page serves every data page of the chunk, and going through [`Self::dictionary`] meant
902    /// copying the whole dictionary into each page's vector on the way to putting it in an `Arc`
903    /// that then had a single holder. On a ClickBench scan that copy was sixteen percent of the
904    /// instructions the query ran.
905    ///
906    /// Composing a dictionary over a dictionary still needs the values by value, so that case takes
907    /// them out of the handle and copies if anybody else is still reading them. Nothing that shares
908    /// a dictionary builds a stacked one, so the two paths do not meet in practice.
909    ///
910    /// The range check takes the highest code rather than stopping at the first bad one. Stopping
911    /// early sounds cheaper and is not, because a loop that can exit anywhere cannot be vectorized
912    /// and a running maximum can, and the only run that would have exited early is the one about to
913    /// fail the query anyway. Every other run reads the whole of `codes` either way. It was 5.2
914    /// percent of a ClickBench scan as a `find`.
915    ///
916    /// # Errors
917    ///
918    /// If any code is past the end of the value vector.
919    pub fn dictionary_over(codes: Vec<u32>, values: Arc<Vector>) -> Result<Self> {
920        let highest = codes.iter().copied().fold(0, u32::max);
921        if !codes.is_empty() && highest as usize >= values.len() {
922            return Err(Error::internal(format!(
923                "dictionary code {highest} is past the end of a {} value dictionary",
924                values.len()
925            )));
926        }
927        let stacked = matches!(values.validity, Validity::AllValid)
928            && matches!(values.body, Body::Dictionary { .. });
929        let (codes, values) = if stacked {
930            let (codes, values) = compose(codes, Arc::unwrap_or_clone(values));
931            (codes, Arc::new(values))
932        } else {
933            (codes, values)
934        };
935        Ok(Self {
936            ty: values.ty.clone(),
937            len: codes.len(),
938            validity: Validity::AllValid,
939            body: Body::Dictionary { codes, values, stable: false },
940        })
941    }
942
943    /// A dictionary whose codes keep the same meaning across every page of its source.
944    pub fn stable_dictionary(codes: Vec<u32>, values: Arc<Vector>) -> Result<Self> {
945        let mut vector = Self::dictionary_over(codes, values)?;
946        if let Body::Dictionary { stable, .. } = &mut vector.body {
947            *stable = true;
948        }
949        Ok(vector)
950    }
951
952    /// A stable dictionary whose caller already found the largest code while decoding it.
953    pub fn stable_dictionary_validated(
954        codes: Vec<u32>,
955        values: Arc<Vector>,
956        highest: Option<u32>,
957    ) -> Result<Self> {
958        if highest.is_some_and(|code| code as usize >= values.len()) {
959            return Err(Error::internal("a stable dictionary code is past its value dictionary"));
960        }
961        Ok(Self {
962            ty: values.ty.clone(),
963            len: codes.len(),
964            validity: Validity::AllValid,
965            body: Body::Dictionary { codes, values, stable: true },
966        })
967    }
968
969    /// A vector of runs, one value each, with the row each run ends at.
970    ///
971    /// `ends` is exclusive and strictly increasing, so run `i` covers the rows from `ends[i - 1]` to
972    /// `ends[i]` and run zero starts at nothing. The length of the vector is the last end.
973    ///
974    /// The depth is one, the same way a dictionary's is, and for a sharper reason. Every kernel that
975    /// wants runs wants the value of a run without another search, and a run length vector over a
976    /// run length vector turns one search into two and then into three. Rather than compose, this
977    /// refuses: nothing in the engine builds a stacked one, because [`Self::run_encoded`] only ever
978    /// reads a flat body, so a stacked one is a caller doing something by hand and the useful answer
979    /// is to say so rather than to quietly do a pass of work they did not ask for.
980    ///
981    /// A run over a dictionary is fine and is not that case. The two forms answer different
982    /// questions and a column that is both clustered and low cardinality genuinely wants both.
983    ///
984    /// # Errors
985    ///
986    /// If there is not exactly one value per run, if the ends do not increase, or if the values are
987    /// themselves run length encoded.
988    pub fn runs(ends: Vec<u32>, values: Vector) -> Result<Self> {
989        if matches!(values.body, Body::Runs { .. }) {
990            return Err(Error::internal("runs of runs, which is two searches to read one row"));
991        }
992        if ends.len() != values.len() {
993            return Err(Error::internal(format!(
994                "{} runs and {} values to put in them",
995                ends.len(),
996                values.len()
997            )));
998        }
999        if ends.windows(2).any(|pair| pair[0] >= pair[1]) || ends.first() == Some(&0) {
1000            return Err(Error::internal("run ends that do not increase"));
1001        }
1002        let len = ends.last().copied().unwrap_or(0) as usize;
1003        Ok(Self {
1004            ty: values.ty.clone(),
1005            len,
1006            validity: Validity::AllValid,
1007            body: Body::Runs { ends, values: Arc::new(values) },
1008        })
1009    }
1010
1011    /// The same values as runs, when there are few enough runs for that to be smaller.
1012    ///
1013    /// Costs one pass over the column to find out, which is why this is a call somebody makes rather
1014    /// than something a constructor does. The decision is the same arithmetic every time: a row in
1015    /// flat form costs one value, a run costs one value plus the four bytes of its end, so runs are
1016    /// smaller once there are fewer than about half as many runs as rows, and the narrower the
1017    /// column the more runs it takes. `RUNS_PAY_AT` is that ratio, written down rather than spelt
1018    /// into an `if`, because it is the number a sweep will want to move.
1019    ///
1020    /// Only a flat body is looked at. A constant and a sequence are already one value and two
1021    /// numbers, so there is nothing to win, and a dictionary that is also clustered is a real case
1022    /// that wants its codes run length encoded rather than its values, which is a different function
1023    /// and not this one.
1024    ///
1025    /// Two adjacent nulls are one run. Two adjacent equal values with a null between them are three,
1026    /// because the null is a value of the column as far as anything reading it is concerned.
1027    ///
1028    /// # Errors
1029    ///
1030    /// From the gather this does at the end, and nowhere else. A body that is not flat comes back
1031    /// unchanged rather than as an error, so a nested vector never reaches the part that can fail.
1032    pub fn run_encoded(&self) -> Result<Self> {
1033        let Body::Flat(data) = &self.body else {
1034            return Ok(self.clone());
1035        };
1036        let ends = boundaries(data, &self.validity, self.len);
1037        if ends.len().saturating_mul(RUNS_PAY_AT) >= self.len {
1038            return Ok(self.clone());
1039        }
1040        let starts: Vec<u32> =
1041            std::iter::once(0).chain(ends.iter().copied()).take(ends.len()).collect();
1042        Self::runs(ends, self.gather(&starts)?)
1043    }
1044
1045    /// A vector of `len` integers packed `width` bits each, every one an offset from `base`.
1046    ///
1047    /// The way in for a reader that already has the packed bits, which is what a column file holds
1048    /// and what a network frame carries. Nothing unpacks on the way in, so a scan of a packed column
1049    /// hands the bits straight to the chunk and the cost of the form is paid by whoever reads a
1050    /// value rather than by the scan.
1051    ///
1052    /// The range check is on the two ends rather than on every code, which is the whole check. A
1053    /// code is between zero and `2^width - 1` by construction, so if `base` and `base + 2^width - 1`
1054    /// both fit the column's layout then every value does, and that is two comparisons instead of
1055    /// one per row.
1056    ///
1057    /// # Errors
1058    ///
1059    /// If the type is not one of the integer layouts, if the width is not between one and
1060    /// [`PACKED_WIDTH_MAX`], if there are not enough words for the length, or if either end of the
1061    /// range would not fit the type.
1062    pub fn packed(
1063        ty: LogicalType,
1064        words: Vec<u64>,
1065        width: u32,
1066        base: i128,
1067        len: usize,
1068    ) -> Result<Self> {
1069        let Some((low, high)) = layout_range(&ty) else {
1070            return Err(Error::internal(format!("a {ty} vector has no integer layout to pack")));
1071        };
1072        if width == 0 || width > PACKED_WIDTH_MAX {
1073            return Err(Error::internal(format!(
1074                "a packed width of {width}, which is outside 1 to {PACKED_WIDTH_MAX}"
1075            )));
1076        }
1077        let needed = words_for(len, width);
1078        if words.len() < needed {
1079            return Err(Error::internal(format!(
1080                "{} words for {len} values of {width} bits, which needs {needed}",
1081                words.len()
1082            )));
1083        }
1084        let top = base + i128::from(u64::MAX >> (64 - width));
1085        if base < low || top > high {
1086            return Err(Error::internal(format!(
1087                "packed values from {base} to {top}, which a {ty} cannot hold"
1088            )));
1089        }
1090        Ok(Self {
1091            ty,
1092            len,
1093            validity: Validity::AllValid,
1094            body: Body::Packed { words: Arc::new(words), width, base, offset: 0 },
1095        })
1096    }
1097
1098    /// The same values bit packed, when the range of the column makes that smaller.
1099    ///
1100    /// Costs one pass to find the range and one to write the bits, which is why this is a call
1101    /// somebody makes rather than something a constructor does. It is the counterpart of
1102    /// [`Self::run_encoded`] and the decision has the same shape: a row flat costs the width of its
1103    /// layout, a row packed costs the bits the column's range needs, and the form is worth having
1104    /// only when the second is a good deal smaller than the first. [`PACKING_PAYS_AT`] is that
1105    /// ratio, written down rather than spelt into an `if`, because it is the number a sweep will
1106    /// want to move.
1107    ///
1108    /// Only a flat integer body is looked at. A constant and a sequence are already smaller than any
1109    /// packing of them, a dictionary's codes are the thing that would want packing rather than its
1110    /// values, and a float has no range to pack into since the bits of an `f64` are not an integer
1111    /// that arithmetic on the column agrees with.
1112    ///
1113    /// The range is taken over every slot including the null ones, which hold a zero. A column of
1114    /// large values with one null in it therefore packs a range that reaches down to zero and comes
1115    /// out wider than it needed to be. The alternative is a pass that consults the validity per slot
1116    /// to find the range and a second rule for what to write into a null slot, and this form exists
1117    /// to make reads cheap rather than to squeeze the last bit out of a sparse column.
1118    ///
1119    /// A column whose values are all the same packs to nothing at all, and rather than invent a zero
1120    /// bit code this declines and leaves it to [`Self::run_encoded`], which turns that column into
1121    /// one run and is smaller than any packing of it.
1122    ///
1123    /// # Errors
1124    ///
1125    /// If the packed bits and the length disagree, which would be a bug here rather than a caller
1126    /// doing something wrong.
1127    pub fn bit_packed(&self) -> Result<Self> {
1128        let Body::Flat(data) = &self.body else {
1129            return Ok(self.clone());
1130        };
1131        let Some((low, high)) = span_of(data, self.len) else {
1132            return Ok(self.clone());
1133        };
1134        let Some(range) = high.checked_sub(low).and_then(|range| u64::try_from(range).ok()) else {
1135            return Ok(self.clone());
1136        };
1137        let width = u64::BITS - range.leading_zeros();
1138        if width == 0 || width > PACKED_WIDTH_MAX {
1139            return Ok(self.clone());
1140        }
1141        if words_for(self.len, width) * size_of::<u64>() * PACKING_PAYS_AT > data.footprint() {
1142            return Ok(self.clone());
1143        }
1144        let words = pack(data, self.len, low, width);
1145        let packed = Self::packed(self.ty.clone(), words, width, low, self.len)?;
1146        Ok(packed.with_validity(self.validity.clone()))
1147    }
1148
1149    /// A vector of string views over an arena somebody else is holding too.
1150    ///
1151    /// The way in for a scan that has a page of strings and wants several chunks over it. Each chunk
1152    /// gets its own run of views and they all share the one arena, so the bytes are read where the
1153    /// page put them and nothing copies them.
1154    ///
1155    /// Every view is checked against the arena here rather than when a row is read. That is a pass
1156    /// over the views at construction, which is the same pass the caller just did to build them, and
1157    /// what it buys is that a row of this form cannot resolve to bytes that are not there. The check
1158    /// is on the offsets and not on the bytes, so it says nothing about whether the payload is text,
1159    /// which is the same promise a `BLOB` column makes.
1160    ///
1161    /// # Errors
1162    ///
1163    /// If the type is not one stored as views, or if a view points past the end of the arena.
1164    pub fn string_views(
1165        ty: LogicalType,
1166        views: Vec<StringView>,
1167        arena: Arc<Buffer<u8>>,
1168    ) -> Result<Self> {
1169        if ty.physical() != rudb_common::PhysicalType::Varlen {
1170            return Err(Error::internal(format!("a {ty} vector cannot hold string views")));
1171        }
1172        if views.iter().any(|view| view.bytes_in(&arena).is_none()) {
1173            return Err(Error::internal("a string view points past the end of its arena"));
1174        }
1175        let len = views.len();
1176        Ok(Self { ty, len, validity: Validity::AllValid, body: Body::Views { views, arena } })
1177    }
1178
1179    /// A text vector whose values remain in a storage source until they are read.
1180    pub fn external_text(ty: LogicalType, source: Arc<dyn TextSource>) -> Result<Self> {
1181        if ty.physical() != rudb_common::PhysicalType::Varlen {
1182            return Err(Error::internal(format!(
1183                "a {ty} vector cannot use an external text source"
1184            )));
1185        }
1186        let len = source.len();
1187        Ok(Self { ty, len, validity: Validity::AllValid, body: Body::ExternalText { source } })
1188    }
1189
1190    /// The same strings, in a form where a cut of them does not copy the bytes.
1191    ///
1192    /// The counterpart of [`Self::run_encoded`] and [`Self::bit_packed`] for a string column, and
1193    /// the only one of the three that takes `self` by value. It has to: what it does is move the
1194    /// arena into an `Arc` so nothing copies it again, and a version taking `&self` would start by
1195    /// copying the arena once to have one to move.
1196    ///
1197    /// Anything that is not a flat string column comes back as it was, which includes a column that
1198    /// is already in this form.
1199    ///
1200    /// # Errors
1201    ///
1202    /// Nothing here fails today. The result is a `Result` because the check inside
1203    /// [`Self::string_views`] is worth running on the views this builds rather than trusting that
1204    /// this function built them right.
1205    pub fn shared_text(self) -> Result<Self> {
1206        let Body::Flat(Data::Varlen(column)) = self.body else {
1207            return Ok(self);
1208        };
1209        let (views, arena) = column.into_parts();
1210        let shared = Self::string_views(self.ty, views, Arc::new(arena))?;
1211        Ok(shared.with_validity(self.validity))
1212    }
1213
1214    /// A vector of FSST codes against a table somebody else trained.
1215    ///
1216    /// The way in for a reader that has a page of compressed strings and the table that goes with
1217    /// it. The codes are not copied and the table is not retrained, so laying several chunks over
1218    /// one page costs the spans and nothing else.
1219    ///
1220    /// # Errors
1221    ///
1222    /// If the type is not one stored as text, or if a span runs past the end of the codes.
1223    pub fn coded(
1224        ty: LogicalType,
1225        codes: Arc<Vec<u8>>,
1226        spans: Vec<(u32, u32)>,
1227        table: Arc<SymbolTable>,
1228    ) -> Result<Self> {
1229        if ty.physical() != rudb_common::PhysicalType::Varlen {
1230            return Err(Error::internal(format!("a {ty} vector cannot hold FSST codes")));
1231        }
1232        let end = u32::try_from(codes.len()).unwrap_or(u32::MAX);
1233        if spans.iter().any(|&(from, to)| from > to || to > end) {
1234            return Err(Error::internal("an FSST span runs past the end of the codes"));
1235        }
1236        let len = spans.len();
1237        Ok(Self {
1238            ty,
1239            len,
1240            validity: Validity::AllValid,
1241            body: Body::Coded { codes, spans, table },
1242        })
1243    }
1244
1245    /// The same strings, compressed against a table trained on them.
1246    ///
1247    /// The counterpart of [`Self::run_encoded`] and [`Self::bit_packed`] for a text column, and it
1248    /// takes `self` by value for the reason [`Self::shared_text`] does.
1249    ///
1250    /// The table is trained on every row rather than on a sample. A vector is at most 1024 rows, so
1251    /// the sample would be most of the column anyway, and the systematic sampling
1252    /// `spec/06-compression.md` section 6.3 asks for is a decision about a page and belongs to
1253    /// whoever is holding one.
1254    ///
1255    /// It declines unless the codes are at most half the bytes the strings are. FSST gets about that
1256    /// on text and rather less on anything already short or already random, and below that the
1257    /// decompression per row read is not bought back. A column it declines on comes back as it was.
1258    ///
1259    /// # Errors
1260    ///
1261    /// Nothing here fails today. The result is a `Result` because the checks inside [`Self::coded`]
1262    /// are worth running on what this builds rather than trusting that this built it right.
1263    pub fn compressed(self) -> Result<Self> {
1264        let Body::Flat(Data::Varlen(column)) = &self.body else {
1265            return Ok(self);
1266        };
1267        let rows: Vec<&[u8]> = (0..self.len).filter_map(|row| column.bytes(row)).collect();
1268        if rows.len() != self.len {
1269            return Ok(self);
1270        }
1271        let plain: usize = rows.iter().map(|row| row.len()).sum();
1272        let table = SymbolTable::train(&rows);
1273        let mut codes = Vec::with_capacity(plain);
1274        let mut spans = Vec::with_capacity(self.len);
1275        for row in &rows {
1276            let from = u32::try_from(codes.len()).unwrap_or(u32::MAX);
1277            table.compress(row, &mut codes);
1278            spans.push((from, u32::try_from(codes.len()).unwrap_or(u32::MAX)));
1279        }
1280        if codes.len() * FSST_PAYS_AT > plain {
1281            return Ok(self);
1282        }
1283        let coded = Self::coded(self.ty.clone(), Arc::new(codes), spans, Arc::new(table))?;
1284        Ok(coded.with_validity(self.validity.clone()))
1285    }
1286
1287    /// The same vector with a different validity.
1288    #[must_use]
1289    pub fn with_validity(mut self, validity: Validity) -> Self {
1290        self.validity = validity;
1291        self
1292    }
1293
1294    /// What kind of values these are.
1295    #[must_use]
1296    pub fn logical_type(&self) -> &LogicalType {
1297        &self.ty
1298    }
1299
1300    /// How many values there are.
1301    #[must_use]
1302    pub fn len(&self) -> usize {
1303        self.len
1304    }
1305
1306    /// Whether there are no values.
1307    #[must_use]
1308    pub fn is_empty(&self) -> bool {
1309        self.len == 0
1310    }
1311
1312    /// How many bytes of memory this vector is holding.
1313    ///
1314    /// What the memory limit charges for it. A constant and a sequence hold one value and two
1315    /// numbers however long they are, which is the point of both forms, so the number here is the
1316    /// form's cost and not the column's width times its length.
1317    ///
1318    /// A dictionary counts its values in full, and two vectors sharing one dictionary each report
1319    /// all of it. That over counts, deliberately: working out that two operators are looking at the
1320    /// same `Arc` means threading identity through the accounting, and a limit that over counts
1321    /// refuses a query that would have fit while a limit that under counts lets one through that
1322    /// does not. The first is a worse answer to give and the second is a worse thing to be.
1323    #[must_use]
1324    pub fn footprint(&self) -> usize {
1325        let body = match &self.body {
1326            Body::Flat(data) => data.footprint(),
1327            Body::Constant(value) => value.footprint(),
1328            Body::Sequence { .. } => 0,
1329            Body::Dictionary { codes, values, .. } => {
1330                codes.capacity() * size_of::<u32>() + values.footprint()
1331            }
1332            Body::Packed { words, .. } => words.capacity() * size_of::<u64>(),
1333            // The arena counts in full in every vector sharing it, for the reason a shared
1334            // dictionary does: over counting refuses a query that would have fit and under counting
1335            // admits one that does not, and the first is the better way to be wrong.
1336            Body::Views { views, arena } => {
1337                views.capacity() * size_of::<StringView>() + arena.footprint()
1338            }
1339            Body::ExternalText { source } => source.footprint(),
1340            // The table counts in full in every vector sharing it, the way a shared arena and a
1341            // shared dictionary do. It is the largest of the three and the most shared of them, so
1342            // this is the one place the over counting is worth saying out loud: a page of a hundred
1343            // chunks reports its table a hundred times.
1344            Body::Coded { codes, spans, table } => {
1345                codes.capacity() + spans.capacity() * size_of::<(u32, u32)>() + table.footprint()
1346            }
1347            Body::Runs { ends, values } => ends.capacity() * size_of::<u32>() + values.footprint(),
1348            // The child counts in full in every vector sharing it, the way a shared dictionary and a
1349            // shared arena do, and for the same reason.
1350            Body::Nested { entries, child } => {
1351                entries.capacity() * size_of::<(u32, u32)>() + child.footprint()
1352            }
1353            // Every child in full, the way the list child counts. A struct is as wide as its fields
1354            // are, so this is the one body whose cost is a sum over children rather than one number,
1355            // and a struct of a hundred narrow fields costs what the hundred columns cost.
1356            Body::Fields { children } => {
1357                children.capacity() * size_of::<Arc<Self>>()
1358                    + children.iter().map(|child| child.footprint()).sum::<usize>()
1359            }
1360        };
1361        size_of::<Self>() + self.validity.footprint() + body
1362    }
1363
1364    /// Which of the values are not null, at this level and no deeper.
1365    ///
1366    /// This is not the same question as [`Self::is_null_at`] and the difference has already cost
1367    /// one wrong answer. A dictionary and a run length vector keep their nulls in the values they
1368    /// point at rather than in a mask of their own, so both are built with every row marked present
1369    /// here and a row whose value is null reads as valid. A caller that wants to know whether a row
1370    /// is null wants the other one. A caller that wants the mask of a flat column, to copy it or to
1371    /// count it, wants this one.
1372    #[must_use]
1373    pub fn validity(&self) -> &Validity {
1374        &self.validity
1375    }
1376
1377    /// Whether the row at `index` is null, in whichever form the vector is in.
1378    ///
1379    /// Reads through a dictionary or a run to the value it stands for, which is where those two
1380    /// forms keep their nulls, and answers from the mask for every other form. A row past the end
1381    /// is null, the same answer [`Self::value_at`] gives it.
1382    #[must_use]
1383    pub fn is_null_at(&self, index: usize) -> bool {
1384        if index >= self.len || !self.validity.is_valid(index) {
1385            return true;
1386        }
1387        match &self.body {
1388            Body::Dictionary { codes, values, .. } => match codes.get(index) {
1389                Some(&code) => values.is_null_at(code as usize),
1390                None => true,
1391            },
1392            Body::Runs { ends, values } => match run_holding(ends, index) {
1393                Some(run) => values.is_null_at(run),
1394                None => true,
1395            },
1396            _ => false,
1397        }
1398    }
1399
1400    /// Which physical form this vector is in.
1401    #[must_use]
1402    pub fn form(&self) -> Form {
1403        match self.body {
1404            Body::Flat(_) => Form::Flat,
1405            Body::Constant(_) => Form::Constant,
1406            Body::Sequence { .. } => Form::Sequence,
1407            Body::Dictionary { .. } => Form::Dictionary,
1408            Body::Packed { .. } => Form::BitPacked,
1409            Body::Views { .. } => Form::StringView,
1410            Body::ExternalText { .. } => Form::StringView,
1411            Body::Coded { .. } => Form::Fsst,
1412            Body::Runs { .. } => Form::Rle,
1413            Body::Nested { .. } => Form::List,
1414            Body::Fields { .. } => Form::Struct,
1415        }
1416    }
1417
1418    /// The data, for a flat vector, and `None` for any other form.
1419    ///
1420    /// A kernel that wants a slice asks for it and takes the flat path if it gets one. A kernel
1421    /// that can do better on a constant or a dictionary checks [`Self::form`] first.
1422    #[must_use]
1423    pub fn data(&self) -> Option<&Data> {
1424        match &self.body {
1425            Body::Flat(data) => Some(data),
1426            _ => None,
1427        }
1428    }
1429
1430    /// The one value, for a constant vector, and `None` for any other form.
1431    ///
1432    /// A kernel comparing a column against a literal wants the literal once rather than 1024
1433    /// times, and [`Self::value_at`] on a constant clones it on every call because it has to be
1434    /// able to hand back a `Value` for any form. This is the accessor that lets the specialized
1435    /// path hoist the clone out of the loop.
1436    #[must_use]
1437    pub fn constant_value(&self) -> Option<&Value> {
1438        match &self.body {
1439            Body::Constant(value) => Some(value.as_ref()),
1440            _ => None,
1441        }
1442    }
1443
1444    /// The codes and the values, for a dictionary vector, and `None` for any other form.
1445    ///
1446    /// The reason a kernel needs this rather than reading the dictionary through
1447    /// [`Self::value_at`] is the entire argument for the form existing. A filter against a
1448    /// dictionary column of 1024 rows and 40 distinct values is 40 comparisons and 1024 lookups,
1449    /// not 1024 comparisons, and there is no way to write that loop without seeing the codes.
1450    ///
1451    /// Note what the validity of the returned vector means. A dictionary keeps its nulls in the
1452    /// vector it points at, and the dictionary's own validity says nothing about them, so a caller
1453    /// deciding whether row `i` is null has to ask the value vector about `codes[i]` rather than
1454    /// asking this vector about `i`. [`Self::flatten`] has the same note on it for the same
1455    /// reason, because getting this wrong is a null that survives being selected and comes out as
1456    /// a zero.
1457    #[must_use]
1458    pub fn dictionary_parts(&self) -> Option<(&[u32], &Self)> {
1459        match &self.body {
1460            Body::Dictionary { codes, values, .. } => Some((codes, values.as_ref())),
1461            _ => None,
1462        }
1463    }
1464
1465    /// The codes and the shared dictionary handle for a dictionary vector.
1466    ///
1467    /// Storage readers use the identity of this handle to prove that codes from separate pages
1468    /// belong to one table-wide dictionary. Kernels that only read values should continue to use
1469    /// [`Self::dictionary_parts`].
1470    #[must_use]
1471    pub fn shared_dictionary_parts(&self) -> Option<(&[u32], &Arc<Self>)> {
1472        match &self.body {
1473            Body::Dictionary { codes, values, .. } => Some((codes, values)),
1474            _ => None,
1475        }
1476    }
1477
1478    /// Stable codes and their shared values, when storage guarantees one code space across pages.
1479    #[must_use]
1480    pub fn stable_dictionary_parts(&self) -> Option<(&[u32], &Arc<Self>)> {
1481        match &self.body {
1482            Body::Dictionary { codes, values, stable: true } => Some((codes, values)),
1483            _ => None,
1484        }
1485    }
1486
1487    /// The run ends and the run values, for a run length vector, and `None` for any other form.
1488    ///
1489    /// The ends are exclusive and increasing, and there is exactly one value per run, so a kernel
1490    /// that wants to walk this walks the pairs and never asks which run a row is in. That is the
1491    /// whole argument for the form: an aggregate over a clustered column is one multiply per run
1492    /// instead of one add per row, and there is no way to write that loop without seeing the ends.
1493    ///
1494    /// The nulls are in the values, the way a dictionary's are, so a caller deciding whether row `i`
1495    /// is null asks the value vector about the run rather than asking this vector about `i`.
1496    #[must_use]
1497    pub fn run_parts(&self) -> Option<(&[u32], &Self)> {
1498        match &self.body {
1499            Body::Runs { ends, values } => Some((ends, values.as_ref())),
1500            _ => None,
1501        }
1502    }
1503
1504    /// Where each row's value is, for the two forms that keep their values somewhere else.
1505    ///
1506    /// A dictionary and a run length vector are the same shape seen from a kernel: a run of
1507    /// positions and a vector to read them out of. The difference is that a dictionary stores the
1508    /// positions and a run length vector works them out, and a kernel writing `values[at[row]]` does
1509    /// not care which. So every specialization written against [`Self::dictionary_parts`] covers
1510    /// both forms by asking this instead, and the day a third form with an indirection arrives it
1511    /// covers that one too without any of those kernels being reopened.
1512    ///
1513    /// The run length side costs an allocation of one position per row and a pass to fill it, which
1514    /// is the same four bytes a row a dictionary was already carrying and is paid once per kernel
1515    /// call rather than once per row. That is the price of this being one accessor rather than a
1516    /// second arm in eighteen kernels, and it is not the last word: a kernel that wants a run at a
1517    /// time reads [`Self::run_parts`] and pays nothing, which is the specialization this makes it
1518    /// possible to skip writing until a sweep says it is worth it.
1519    #[must_use]
1520    pub fn positions(&self) -> Option<(Cow<'_, [u32]>, &Self)> {
1521        match &self.body {
1522            Body::Dictionary { codes, values, .. } => Some((Cow::Borrowed(codes), values.as_ref())),
1523            Body::Runs { ends, values } => {
1524                let mut at = Vec::with_capacity(self.len);
1525                for (run, &stop) in ends.iter().enumerate() {
1526                    let run = u32::try_from(run).unwrap_or(u32::MAX);
1527                    at.resize(stop as usize, run);
1528                }
1529                Some((Cow::Owned(at), values.as_ref()))
1530            }
1531            _ => None,
1532        }
1533    }
1534
1535    /// The bits and what they mean, for a bit packed vector, and `None` for any other form.
1536    ///
1537    /// What a kernel needs to stay in code space. A comparison against a literal is the case that
1538    /// pays: `column > 900` over a column packed from a base of 40 is `code > 860`, which is the
1539    /// same shift and mask the read was going to do anyway and no unpacking at all, and a literal
1540    /// outside the packed range answers the whole vector without reading a bit of it. None of that
1541    /// can be written without seeing the width and the base.
1542    #[must_use]
1543    pub fn packed_parts(&self) -> Option<Packed<'_>> {
1544        match &self.body {
1545            Body::Packed { words, width, base, offset } => {
1546                Some(Packed { words, width: *width, base: *base, offset: *offset })
1547            }
1548            _ => None,
1549        }
1550    }
1551
1552    /// The views and the arena, for either form that stores strings, and `None` for the rest.
1553    ///
1554    /// This is to the two string forms what [`Self::positions`] is to the two forms that point
1555    /// somewhere else. A flat varchar column owns its arena and a string view column shares one, and
1556    /// a kernel reading a row wants the view and the bytes either way, so every specialization
1557    /// written against this covers both forms and neither has to be reopened when a third way of
1558    /// holding an arena arrives.
1559    ///
1560    /// The arena is whatever the long strings live in, which for a column over a page is the page,
1561    /// including the parts of it no view points at. Only the views say which bytes are a row.
1562    #[must_use]
1563    pub fn text_parts(&self) -> Option<(&[StringView], &[u8])> {
1564        match &self.body {
1565            Body::Flat(Data::Varlen(column)) => Some((column.views(), column.arena())),
1566            Body::Views { views, arena } => Some((views, arena)),
1567            _ => None,
1568        }
1569    }
1570
1571    /// The codes and the table, for an FSST vector, and `None` for any other form.
1572    ///
1573    /// What a kernel needs to stay in code space. An equality filter is the case that pays, and it
1574    /// pays completely: the literal is compressed once against the same table and after that a row
1575    /// matches exactly when its code bytes match, because compressing is a function and so is
1576    /// decompressing. No row is decompressed at all. An ordering comparison cannot do that, since a
1577    /// symbol code says nothing about where its symbol sorts, so those decompress and say so.
1578    #[must_use]
1579    pub fn coded_parts(&self) -> Option<Coded<'_>> {
1580        match &self.body {
1581            Body::Coded { codes, spans, table } => Some(Coded { codes, spans, table }),
1582            _ => None,
1583        }
1584    }
1585
1586    /// The start and the step, for a sequence vector, and `None` for any other form.
1587    #[must_use]
1588    pub fn sequence_parts(&self) -> Option<(i64, i64)> {
1589        match self.body {
1590            Body::Sequence { start, step } => Some((start, step)),
1591            _ => None,
1592        }
1593    }
1594
1595    /// The value at `index`, as a single value.
1596    ///
1597    /// This is the slow path on purpose. It is what a result set is read out with and what a test
1598    /// asserts on, and an operator that calls it per row is an operator that has already lost the
1599    /// argument the vector interface exists to win.
1600    #[must_use]
1601    pub fn value_at(&self, index: usize) -> Value {
1602        if index >= self.len || !self.validity.is_valid(index) {
1603            return Value::Null;
1604        }
1605        match &self.body {
1606            Body::Constant(value) => value.as_ref().clone(),
1607            Body::Sequence { start, step } => Value::BigInt(start + step * index as i64),
1608            Body::Dictionary { codes, values, .. } => match codes.get(index) {
1609                Some(&code) => values.value_at(code as usize),
1610                None => Value::Null,
1611            },
1612            Body::Runs { ends, values } => match run_holding(ends, index) {
1613                Some(run) => values.value_at(run),
1614                None => Value::Null,
1615            },
1616            // One value unpacked into a run of one, so that what a packed value means is decided in
1617            // the same place a flat one is rather than in a second copy of the type mapping that
1618            // could drift from it. It allocates, which this path is allowed to do and the typed
1619            // unpack in `copied` is not, and it is the reason anything about to read a packed
1620            // column a row at a time should flatten it once instead.
1621            Body::Packed { words, width, base, offset } => {
1622                unpack(&self.ty, words, *offset, *width, *base, &[index])
1623                    .map_or(Value::Null, |data| value_from(&self.ty, &data, 0))
1624            }
1625            // The bytes are where the arena has them, and what they are read as is the logical
1626            // type's business, so this hands the row to the same reader a flat column goes through
1627            // rather than deciding here that a `BLOB` is a string.
1628            Body::Views { views, arena } => {
1629                match views.get(index).and_then(|v| v.bytes_in(arena)) {
1630                    Some(bytes) => bytes_as(&self.ty, bytes),
1631                    None => Value::Null,
1632                }
1633            }
1634            Body::ExternalText { source } => source
1635                .bytes_at(index)
1636                .ok()
1637                .flatten()
1638                .map_or(Value::Null, |bytes| bytes_as(&self.ty, bytes)),
1639            // One row decompressed on its own, which is the property the form is chosen for. It
1640            // allocates, which this path is allowed to do, and it is the reason anything about to
1641            // read a compressed column a row at a time should flatten it once instead.
1642            Body::Coded { codes, spans, table } => {
1643                match spans.get(index).and_then(|&(from, to)| {
1644                    let mut out = Vec::new();
1645                    table.decompress(codes.get(from as usize..to as usize)?, &mut out).ok()?;
1646                    Some(out)
1647                }) {
1648                    Some(bytes) => bytes_as(&self.ty, &bytes),
1649                    None => Value::Null,
1650                }
1651            }
1652            // A row's elements are read out of the child one at a time, which is the slow path this
1653            // whole function is and is why a kernel over a list column reads `list_parts` instead.
1654            // The element type comes from the child rather than from this vector's type, so a list
1655            // whose child was built narrower than the column claims still hands back what is in it.
1656            //
1657            // A map is stored in this body too, so which value comes out is decided by the logical
1658            // type rather than by the body. That is the one place the composition shows: the bytes of
1659            // a map really are the bytes of a list of two field structs, and the only thing that
1660            // remembers it is a map is the type.
1661            Body::Nested { entries, child } => match (entries.get(index), &self.ty) {
1662                (Some(&(start, len)), LogicalType::Map(key, value)) => {
1663                    let pairs = child.struct_parts().unwrap_or_default();
1664                    Value::map(
1665                        key.as_ref().clone(),
1666                        value.as_ref().clone(),
1667                        (start..start + len)
1668                            .filter_map(|at| {
1669                                let [keys, values] = pairs else { return None };
1670                                Some((keys.value_at(at as usize), values.value_at(at as usize)))
1671                            })
1672                            .collect(),
1673                    )
1674                }
1675                (Some(&(start, len)), _) => Value::List {
1676                    element: child.ty.clone(),
1677                    values: (start..start + len).map(|at| child.value_at(at as usize)).collect(),
1678                },
1679                (None, _) => Value::Null,
1680            },
1681            // One value read out of each child at the same position, which is the slow path this whole
1682            // function is and is why a kernel over a struct column reads `struct_parts` instead. The
1683            // names come from this vector's type rather than from the children, because a child is a
1684            // vector and a vector has no name, and the type is where the field order is written down.
1685            Body::Fields { children } => Value::Struct(
1686                fields_of(&self.ty)
1687                    .iter()
1688                    .zip(children)
1689                    .map(|(field, child)| (field.name.clone(), child.value_at(index)))
1690                    .collect(),
1691            ),
1692            Body::Flat(data) => value_from(&self.ty, data, index),
1693        }
1694    }
1695
1696    /// The value at `index`, preserving storage read and validation failures.
1697    pub fn try_value_at(&self, index: usize) -> Result<Value> {
1698        if index >= self.len || !self.validity.is_valid(index) {
1699            return Ok(Value::Null);
1700        }
1701        match &self.body {
1702            Body::ExternalText { source } => {
1703                Ok(source.bytes_at(index)?.map_or(Value::Null, |bytes| bytes_as(&self.ty, bytes)))
1704            }
1705            Body::Dictionary { codes, values, .. } => match codes.get(index) {
1706                Some(&code) => values.try_value_at(code as usize),
1707                None => Ok(Value::Null),
1708            },
1709            Body::Runs { ends, values } => match run_holding(ends, index) {
1710                Some(run) => values.try_value_at(run),
1711                None => Ok(Value::Null),
1712            },
1713            Body::Nested { entries, child } => match (entries.get(index), &self.ty) {
1714                (Some(&(start, len)), LogicalType::Map(key, value)) => {
1715                    let pairs = child.struct_parts().unwrap_or_default();
1716                    let [keys, values] = pairs else { return Ok(Value::Null) };
1717                    let mut entries = Vec::with_capacity(len as usize);
1718                    for at in start..start + len {
1719                        entries.push((
1720                            keys.try_value_at(at as usize)?,
1721                            values.try_value_at(at as usize)?,
1722                        ));
1723                    }
1724                    Ok(Value::map(key.as_ref().clone(), value.as_ref().clone(), entries))
1725                }
1726                (Some(&(start, len)), _) => {
1727                    let mut values = Vec::with_capacity(len as usize);
1728                    for at in start..start + len {
1729                        values.push(child.try_value_at(at as usize)?);
1730                    }
1731                    Ok(Value::List { element: child.ty.clone(), values })
1732                }
1733                (None, _) => Ok(Value::Null),
1734            },
1735            Body::Fields { children } => {
1736                let mut values = Vec::with_capacity(children.len());
1737                for (field, child) in fields_of(&self.ty).iter().zip(children) {
1738                    values.push((field.name.clone(), child.try_value_at(index)?));
1739                }
1740                Ok(Value::Struct(values))
1741            }
1742            _ => Ok(self.value_at(index)),
1743        }
1744    }
1745
1746    /// The text at `index`, borrowed rather than copied.
1747    ///
1748    /// [`Self::value_at`] on a `VARCHAR` column allocates a `String` per call, and a group by that
1749    /// reads a string column keys on one string per input row. This hands back the bytes where they
1750    /// already are, so a caller with somewhere to put them does not go to the allocator at all.
1751    ///
1752    /// `None` for a null, for an index past the end, for a column that is not `VARCHAR`, and for the
1753    /// constant and sequence forms, whose values are not stored per position. A caller that gets
1754    /// `None` has to fall back to [`Self::value_at`], which is correct for all of those.
1755    #[must_use]
1756    pub fn text_at(&self, index: usize) -> Option<&str> {
1757        if self.ty != LogicalType::Varchar || index >= self.len || !self.validity.is_valid(index) {
1758            return None;
1759        }
1760        match &self.body {
1761            Body::Flat(data) => data.str_at(index),
1762            Body::Dictionary { codes, values, .. } => {
1763                values.text_at(usize::try_from(*codes.get(index)?).ok()?)
1764            }
1765            Body::Runs { ends, values } => values.text_at(run_holding(ends, index)?),
1766            Body::Views { views, arena } => {
1767                std::str::from_utf8(views.get(index)?.bytes_in(arena)?).ok()
1768            }
1769            Body::ExternalText { source } => {
1770                std::str::from_utf8(source.bytes_at(index).ok().flatten()?).ok()
1771            }
1772            _ => None,
1773        }
1774    }
1775
1776    /// The variable length bytes at `index`, borrowed without validating or copying them.
1777    ///
1778    /// String data is validated when it enters a vector. Hashing and equality only need its bytes,
1779    /// so those kernels should not pay for UTF-8 validation again on every read.
1780    #[must_use]
1781    pub fn bytes_at(&self, index: usize) -> Option<&[u8]> {
1782        if index >= self.len || !self.validity.is_valid(index) {
1783            return None;
1784        }
1785        match &self.body {
1786            Body::Constant(value) => match value.as_ref() {
1787                Value::Varchar(text) => Some(text.as_bytes()),
1788                Value::Blob(bytes) => Some(bytes),
1789                _ => None,
1790            },
1791            Body::Dictionary { codes, values, .. } => {
1792                values.bytes_at(usize::try_from(*codes.get(index)?).ok()?)
1793            }
1794            Body::Runs { ends, values } => values.bytes_at(run_holding(ends, index)?),
1795            Body::Views { views, arena } => views.get(index)?.bytes_in(arena),
1796            Body::ExternalText { source } => source.bytes_at(index).ok().flatten(),
1797            Body::Flat(data) => data.bytes_at(index),
1798            // The same `None` [`Self::text_at`] gives, for the same reason. A compressed row is not
1799            // anywhere in its plain bytes, so there is nothing here to hand back a borrow of, and a
1800            // caller that gets `None` goes to `value_at` and gets the row decompressed into a value.
1801            // A list row is `None` for a nearer reason: it is not bytes at all, and a caller wanting
1802            // its elements wants [`Self::list_parts`] rather than a borrow of one row.
1803            Body::Coded { .. }
1804            | Body::Sequence { .. }
1805            | Body::Packed { .. }
1806            | Body::Nested { .. }
1807            | Body::Fields { .. } => None,
1808        }
1809    }
1810
1811    /// Variable length bytes at `index`, preserving storage read and validation failures.
1812    pub fn try_bytes_at(&self, index: usize) -> Result<Option<&[u8]>> {
1813        if index >= self.len || !self.validity.is_valid(index) {
1814            return Ok(None);
1815        }
1816        match &self.body {
1817            Body::Constant(value) => Ok(match value.as_ref() {
1818                Value::Varchar(text) => Some(text.as_bytes()),
1819                Value::Blob(bytes) => Some(bytes.as_slice()),
1820                _ => None,
1821            }),
1822            Body::Dictionary { codes, values, .. } => match codes.get(index) {
1823                Some(&code) => values.try_bytes_at(code as usize),
1824                None => Ok(None),
1825            },
1826            Body::Runs { ends, values } => match run_holding(ends, index) {
1827                Some(run) => values.try_bytes_at(run),
1828                None => Ok(None),
1829            },
1830            Body::Views { views, arena } => {
1831                Ok(views.get(index).and_then(|view| view.bytes_in(arena)))
1832            }
1833            Body::ExternalText { source } => source.bytes_at(index),
1834            Body::Flat(data) => Ok(data.bytes_at(index)),
1835            Body::Coded { .. }
1836            | Body::Sequence { .. }
1837            | Body::Packed { .. }
1838            | Body::Nested { .. }
1839            | Body::Fields { .. } => Ok(None),
1840        }
1841    }
1842
1843    /// Variable length byte count at `index`, preserving storage failures.
1844    pub fn try_bytes_len_at(&self, index: usize) -> Result<Option<usize>> {
1845        if index >= self.len || !self.validity.is_valid(index) {
1846            return Ok(None);
1847        }
1848        match &self.body {
1849            Body::Dictionary { codes, values, .. } => match codes.get(index) {
1850                Some(&code) => values.try_bytes_len_at(code as usize),
1851                None => Ok(None),
1852            },
1853            Body::Runs { ends, values } => match run_holding(ends, index) {
1854                Some(run) => values.try_bytes_len_at(run),
1855                None => Ok(None),
1856            },
1857            Body::ExternalText { source } => source.bytes_len_at(index),
1858            _ => Ok(self.bytes_at(index).map(<[u8]>::len)),
1859        }
1860    }
1861
1862    /// How many ranks this vector's values have in sorted order, when whatever holds them knows.
1863    ///
1864    /// See [`TextSource::ranks`] for what a rank is and what a source promises by answering with
1865    /// one. Only a vector whose values come from storage can answer, because only storage is in a
1866    /// position to have sorted them once and written the answer down.
1867    #[must_use]
1868    pub fn ranks(&self) -> Option<usize> {
1869        match &self.body {
1870            Body::ExternalText { source } => source.ranks(),
1871            _ => None,
1872        }
1873    }
1874
1875    /// How the value at `rank` compares against `wanted`. See [`TextSource::compare_rank`].
1876    pub fn compare_rank(&self, rank: usize, wanted: &[u8]) -> Result<Ordering> {
1877        match &self.body {
1878            Body::ExternalText { source } => source.compare_rank(rank, wanted),
1879            _ => {
1880                Err(Error::internal("a vector without a sorted order was asked to compare a rank"))
1881            }
1882        }
1883    }
1884
1885    /// The position of the value at `rank`. See [`TextSource::code_at_rank`].
1886    pub fn code_at_rank(&self, rank: usize) -> Result<u32> {
1887        match &self.body {
1888            Body::ExternalText { source } => source.code_at_rank(rank),
1889            _ => Err(Error::internal("a vector without a sorted order was asked for a rank")),
1890        }
1891    }
1892
1893    /// Text at `index`, preserving storage read, validation and UTF-8 failures.
1894    pub fn try_text_at(&self, index: usize) -> Result<Option<&str>> {
1895        if self.ty != LogicalType::Varchar {
1896            return Ok(None);
1897        }
1898        self.try_bytes_at(index)?
1899            .map(|bytes| {
1900                std::str::from_utf8(bytes).map_err(|error| {
1901                    Error::conversion(format!("invalid UTF-8 in VARCHAR: {error}"))
1902                })
1903            })
1904            .transpose()
1905    }
1906
1907    /// Read every storage-backed value reachable through this vector.
1908    pub fn validate_external(&self) -> Result<()> {
1909        match &self.body {
1910            Body::ExternalText { source } => {
1911                for index in 0..source.len() {
1912                    source.bytes_at(index)?;
1913                }
1914            }
1915            Body::Dictionary { codes, values, .. } => {
1916                for &code in codes {
1917                    values.try_bytes_at(code as usize)?;
1918                }
1919            }
1920            Body::Runs { values, .. } => values.validate_external()?,
1921            Body::Nested { child, .. } => child.validate_external()?,
1922            Body::Fields { children } => {
1923                for child in children {
1924                    child.validate_external()?;
1925                }
1926            }
1927            _ => {}
1928        }
1929        Ok(())
1930    }
1931
1932    /// The signed integer at `index`, widened, read without building a [`Value`].
1933    ///
1934    /// The integer sibling of [`Self::bytes_at`], and it is here for the same caller. A group by on
1935    /// an integer column compares one key per input row against the group it probed, and doing that
1936    /// through [`Self::value_at`] built and dropped a sixty four byte value a row at a time for a
1937    /// number that was already sitting in the column.
1938    ///
1939    /// Widened to `i128` because that is what [`Data::signed_at`] hands back underneath, and one
1940    /// method that covers every signed width is worth more than five that do not. A caller that
1941    /// wants a narrower type narrows it, which is a range check against a value in a register.
1942    ///
1943    /// The types this answers for are the ones whose flat data is read through `signed_at`, so the
1944    /// five signed integer widths and the decimal, date, time and timestamp types that are stored
1945    /// in them. A decimal answers with its unscaled value, which is the number the column holds.
1946    ///
1947    /// `None` for a null, for an index past the end, for a column of any other type, and for the
1948    /// compressed form. Packed integers stay in code space and answer `base + code` directly. A
1949    /// caller that gets `None` falls back to [`Self::value_at`], which is correct for the remaining
1950    /// forms.
1951    #[must_use]
1952    pub fn signed_at(&self, index: usize) -> Option<i128> {
1953        if index >= self.len || !self.validity.is_valid(index) {
1954            return None;
1955        }
1956        match &self.body {
1957            Body::Flat(data) => data.signed_at(index),
1958            Body::Constant(value) => match value.as_ref() {
1959                Value::TinyInt(x) => Some(i128::from(*x)),
1960                Value::SmallInt(x) => Some(i128::from(*x)),
1961                Value::Integer(x) | Value::Date(x) => Some(i128::from(*x)),
1962                Value::BigInt(x) | Value::Time(x) | Value::Timestamp(x) => Some(i128::from(*x)),
1963                Value::HugeInt(x) | Value::Decimal { unscaled: x, .. } => Some(*x),
1964                _ => None,
1965            },
1966            // The same arithmetic [`Self::value_at`] does on a sequence, so the two agree about a
1967            // sequence that runs off the end of the width it is stored in.
1968            Body::Sequence { start, step } => {
1969                Some(i128::from(start.wrapping_add(step.wrapping_mul(index as i64))))
1970            }
1971            Body::Dictionary { codes, values, .. } => {
1972                values.signed_at(usize::try_from(*codes.get(index)?).ok()?)
1973            }
1974            Body::Runs { ends, values } => values.signed_at(run_holding(ends, index)?),
1975            Body::Packed { words, width, base, offset } => Some(
1976                *base + i128::from(code_at(words, (*offset + index) * *width as usize, *width)),
1977            ),
1978            // The same `None` [`Self::bytes_at`] gives, for the same reason. A compressed row is not
1979            // an integer anywhere until it has been unpacked, and a caller that gets
1980            // `None` goes to `value_at` and gets the row unpacked into a value. A list row is not an
1981            // integer in any form, however many integers are in it, and a struct row is not one even
1982            // when it has exactly one integer field, since the row is the struct and not the field.
1983            Body::Coded { .. }
1984            | Body::Views { .. }
1985            | Body::ExternalText { .. }
1986            | Body::Nested { .. }
1987            | Body::Fields { .. } => None,
1988        }
1989    }
1990
1991    /// Every value in order, as single values.
1992    pub fn iter(&self) -> impl Iterator<Item = Value> + '_ {
1993        (0..self.len).map(|index| self.value_at(index))
1994    }
1995
1996    /// A contiguous run of the values, in the form they are already in.
1997    ///
1998    /// This is the cut [`Self::gather`] cannot do. A gather walks a dictionary to its leaf and
1999    /// copies, so gathering a piece of a dictionary encoded column hands back a flat one, and a
2000    /// caller that only wanted the first thousand rows of a page has silently paid for a copy and
2001    /// thrown the dictionary away. A group by over a dictionary encoded column is the case that
2002    /// cares, and it is most of ClickBench.
2003    ///
2004    /// So each form is cut as itself. A dictionary keeps its dictionary and slices its codes, a
2005    /// sequence stays arithmetic with its start moved along, a constant stays a shorter constant,
2006    /// and a flat body is the one that genuinely has to copy its range.
2007    ///
2008    /// The dictionary itself is shared rather than copied, so a cut is the codes and nothing else.
2009    /// It used to be copied, and on a read of a ClickBench partition that copy was ten percent of
2010    /// the cycles: a page holds one dictionary and is cut into chunk sized pieces, so the whole
2011    /// dictionary was copied once per chunk to be read the same way each time.
2012    ///
2013    /// # Errors
2014    ///
2015    /// If the range runs past the end of the vector, or if the type has no flat layout and the
2016    /// body is one that has to be copied.
2017    pub fn slice(&self, at: usize, len: usize) -> Result<Self> {
2018        let end = at.checked_add(len).ok_or_else(|| Error::internal("a slice that wraps"))?;
2019        if end > self.len {
2020            return Err(Error::internal(format!("rows {at} to {end} of a vector of {}", self.len)));
2021        }
2022        if at == 0 && len == self.len {
2023            return Ok(self.clone());
2024        }
2025        let validity = self.validity.slice(at, len);
2026        let body = match &self.body {
2027            Body::Constant(value) => Body::Constant(value.clone()),
2028            Body::Sequence { start, step } => {
2029                Body::Sequence { start: start + step * at as i64, step: *step }
2030            }
2031            Body::Dictionary { codes, values, stable } => Body::Dictionary {
2032                codes: codes[at..end].to_vec(),
2033                values: Arc::clone(values),
2034                stable: *stable,
2035            },
2036            // The bits are not byte aligned, so a cut either repacks them or moves the row the
2037            // reading starts at. Moving it is one addition and repacking is a pass, and a page is
2038            // cut into chunk sized pieces often enough that the difference is the form.
2039            Body::Packed { words, width, base, offset } => Body::Packed {
2040                words: Arc::clone(words),
2041                width: *width,
2042                base: *base,
2043                offset: offset + at,
2044            },
2045            // The cut a flat string column cannot do. Sixteen bytes a row move and the payload stays
2046            // where the page put it, so taking a chunk out of a column of long strings costs the
2047            // same as taking one out of a column of integers. A flat varchar body copies every byte
2048            // of every long string in the range instead, which is the measurement written down in
2049            // `Chunk::compact`: compaction loses on a varchar column, and this is the half of the
2050            // reason that is about cutting rather than about selecting.
2051            Body::Views { views, arena } => {
2052                Body::Views { views: views[at..end].to_vec(), arena: Arc::clone(arena) }
2053            }
2054            // The spans are absolute positions in the shared codes, so a cut is a run of them and
2055            // nothing has to be rebased. One page of compressed strings, one table, and as many
2056            // chunks over it as the reader wants.
2057            Body::Coded { codes, spans, table } => Body::Coded {
2058                codes: Arc::clone(codes),
2059                spans: spans[at..end].to_vec(),
2060                table: Arc::clone(table),
2061            },
2062            // Only the runs the range touches survive, the first and last of them cut back to where
2063            // the range starts and stops, and every end moved to be relative to the new row zero. A
2064            // cut of a hundred rows out of a column of a hundred million is a handful of runs, which
2065            // is the reason this form is worth cutting as itself rather than copying out.
2066            Body::Runs { ends, values } if len > 0 => {
2067                let first = run_holding(ends, at).unwrap_or(0);
2068                let last = run_holding(ends, end - 1).unwrap_or(first);
2069                let cut: Vec<u32> = ends[first..=last]
2070                    .iter()
2071                    .map(|&stop| stop.min(end as u32) - at as u32)
2072                    .collect();
2073                let values = values.slice(first, last - first + 1)?;
2074                Body::Runs { ends: cut, values: Arc::new(values) }
2075            }
2076            // An empty cut has no run to point at and an empty run length body would be a vector of
2077            // no runs claiming a length, so it comes back as the empty flat vector instead.
2078            Body::Runs { .. } => return self.gather(&[]),
2079            // The entries are absolute positions in the shared child, so a cut is a run of them and
2080            // nothing has to be rebased, the same as a cut of FSST spans. The elements outside the
2081            // range stay in the child unreferenced, which is the trade this form makes: a chunk cut
2082            // out of a page of lists moves eight bytes a row and copies no elements at all.
2083            Body::Nested { entries, child } => {
2084                Body::Nested { entries: entries[at..end].to_vec(), child: Arc::clone(child) }
2085            }
2086            // Every child cut at the same place, because a struct row is one value per field at the
2087            // same position in each and there is no entry standing between the row and the child to
2088            // rewrite instead. So this is the one nested form whose cut is not free, and what it costs
2089            // is whatever cutting each field costs, which for a field of string views is sixteen bytes
2090            // a row and for a field of packed integers is one addition.
2091            Body::Fields { children } => Body::Fields {
2092                children: children
2093                    .iter()
2094                    .map(|child| child.slice(at, len).map(Arc::new))
2095                    .collect::<Result<Vec<_>>>()?,
2096            },
2097            Body::ExternalText { source } => {
2098                let mut out = StringColumn::with_capacity(len);
2099                for index in at..end {
2100                    out.push_bytes(source.bytes_at(index)?.unwrap_or_default());
2101                }
2102                Body::Flat(Data::Varlen(out))
2103            }
2104            // The one form with nowhere to point, so its range is copied out. A run and not a
2105            // gather: this used to build a vector of the positions `at..end` and hand it to
2106            // `gather`, which then built a vector of `usize` from it, a vector of `bool` beside
2107            // that, and read the values back one bounds checked index at a time. That is five
2108            // passes and three allocations to say `memcpy`, and on a scan it was the largest thing
2109            // in the program after the aggregation itself, because every chunk of every column of
2110            // every page comes through here.
2111            Body::Flat(data) => Body::Flat(run_of(data, at, end)),
2112        };
2113        Ok(Self { ty: self.ty.clone(), len, validity, body })
2114    }
2115
2116    /// The same values in flat form.
2117    ///
2118    /// Flattening a vector that is already flat is free. Flattening any other form costs a copy,
2119    /// which is exactly why the other forms exist and why nothing on the hot path should call
2120    /// this. It is here for the operators that genuinely cannot do better and for the tests that
2121    /// check the other forms against it.
2122    ///
2123    /// A call that copies counts itself against [`Cause::Flatten`], because a flatten on a hot path
2124    /// is the most expensive thing in this crate and the only way to find one is to have the number.
2125    /// A call on a vector that is already flat does not count, since it neither copies nor gives
2126    /// anything up.
2127    ///
2128    /// # Errors
2129    ///
2130    /// If the type is one there is no vector for yet, which today means `ARRAY` and `UNION`. A `LIST`
2131    /// and a `MAP` flatten to themselves and a `STRUCT` to a struct of flattened fields, since none of
2132    /// the three has a data slice in any form and there is nothing flatter to become.
2133    pub fn flatten(&self) -> Result<Self> {
2134        if let Body::Flat(_) = self.body {
2135            return Ok(self.clone());
2136        }
2137        slow::took(Cause::Flatten);
2138        self.copied((0..self.len).collect(), false)
2139    }
2140
2141    /// The values at the given positions, copied, in a form that does not point back at this vector.
2142    ///
2143    /// This is the copying counterpart to [`Self::dictionary`], and the two are the two halves of
2144    /// the decision `spec/07-execution.md` section 7.1 describes. Which half is right is measured
2145    /// rather than argued, and [`Chunk::compact`](crate::Chunk::compact) is where the measurement
2146    /// is written down.
2147    ///
2148    /// A dictionary chain is walked to its leaf first and the codes composed on the way down, so the
2149    /// copy runs once over the data rather than once per level, and a position that is null at any
2150    /// level comes out null here. The copy is a typed loop per physical layout rather than a `Value`
2151    /// per row, which is the whole point of it and is what [`Self::flatten`] now goes through too.
2152    ///
2153    /// # Errors
2154    ///
2155    /// If the type is one there is no vector for yet, which today means `ARRAY` and `UNION`. A `LIST`
2156    /// and a `MAP` gather by permuting their entries and a `STRUCT` by gathering every field.
2157    pub fn gather(&self, indices: &[u32]) -> Result<Self> {
2158        self.copied(indices.iter().map(|&index| index as usize).collect(), true)
2159    }
2160
2161    /// The copy both [`Self::gather`] and [`Self::flatten`] are.
2162    ///
2163    /// `forms_stay` is the one thing the two want differently. A gather of a constant is a shorter
2164    /// constant and copying it out would be a thousand writes of the same value for nothing, and a
2165    /// gather of string views is a shorter run of views over the same arena rather than a copy of
2166    /// the bytes. Flattening promises flat form to a caller that is about to read the data slice, so
2167    /// for that one both of them have to be written out.
2168    fn copied(&self, at: Vec<usize>, forms_stay: bool) -> Result<Self> {
2169        let rows = at.len();
2170        if forms_stay {
2171            if let Body::Dictionary { codes, values, stable: true } = &self.body {
2172                let validity = Validity::from_iter(rows, |row| {
2173                    at.get(row).is_some_and(|&index| index < self.len && !self.is_null_at(index))
2174                });
2175                let gathered =
2176                    at.iter().map(|&index| codes.get(index).copied().unwrap_or(0)).collect();
2177                return Ok(
2178                    Self::stable_dictionary(gathered, Arc::clone(values))?.with_validity(validity)
2179                );
2180            }
2181        }
2182        let (at, leaf) = self.resolve(at);
2183        let live: Vec<bool> = at.iter().map(|&index| index != NOWHERE).collect();
2184        let validity = Validity::from_run(&live);
2185        let body = match &leaf.body {
2186            // The same gather the arm below is, for a type that has no flat layout to be written out
2187            // into. It goes through the nested builders rather than through a run of data, because they
2188            // are the one place that knows a row of a list column is a range of a child and a row of a
2189            // struct column is one position in each of several, and a second copy of that here would
2190            // be a second thing to keep in step with them.
2191            Body::Constant(value)
2192                if matches!(
2193                    self.ty,
2194                    LogicalType::List(_) | LogicalType::Struct(_) | LogicalType::Map(_, _)
2195                ) =>
2196            {
2197                if forms_stay && matches!(validity, Validity::AllValid) {
2198                    return Ok(Self::constant(self.ty.clone(), value.as_ref().clone(), rows));
2199                }
2200                let rows: Vec<Value> = at
2201                    .iter()
2202                    .map(
2203                        |&index| {
2204                            if index == NOWHERE { Value::Null } else { value.as_ref().clone() }
2205                        },
2206                    )
2207                    .collect();
2208                return Self::from_values(self.ty.clone(), &rows);
2209            }
2210            // Every position holds the same value, so the only thing the gather can change is the
2211            // length and which positions are null. A gather with no null in it is still a constant.
2212            Body::Constant(value) => {
2213                if forms_stay && matches!(validity, Validity::AllValid) {
2214                    return Ok(Self::constant(self.ty.clone(), value.as_ref().clone(), rows));
2215                }
2216                let mut data = empty_data_for(&self.ty)?;
2217                for &index in &at {
2218                    push_value(&mut data, if index == NOWHERE { &Value::Null } else { value })?;
2219                }
2220                Body::Flat(data)
2221            }
2222            // A sequence is arithmetic rather than storage, so the gather is the arithmetic done at
2223            // the positions asked for, and a null writes the zero every other layout writes.
2224            Body::Sequence { start, step } => Body::Flat(Data::Int64(
2225                at.iter()
2226                    .map(|&index| if index == NOWHERE { 0 } else { start + step * index as i64 })
2227                    .collect(),
2228            )),
2229            // A flat body with no values is the untyped null, so every position asked for is null
2230            // whatever was asked for. Going through the copy would build a run of no values and
2231            // call it `rows` long, which is a vector whose length and data disagree.
2232            Body::Flat(Data::Empty) => {
2233                return Ok(Self::constant(self.ty.clone(), Value::Null, rows));
2234            }
2235            Body::Flat(data) => Body::Flat(copy_of(data, &at)),
2236            // The one form whose copy is arithmetic rather than a move of bytes. It goes through a
2237            // typed loop per layout the way the flat copy does, because the alternative is a `Value`
2238            // per row and this is the path a flatten of a scanned column takes.
2239            Body::Packed { words, width, base, offset } => {
2240                Body::Flat(unpack(&self.ty, words, *offset, *width, *base, &at)?)
2241            }
2242            // A gather keeps the form, which is what makes selecting rows out of a string column
2243            // cost sixteen bytes a row instead of the bytes of the strings. The arena it shares is
2244            // the whole arena and not the part the kept rows point at, so a selection that throws
2245            // most of a page away goes on holding the page. That is the trade the form is: a cut and
2246            // a filter are cheap and the memory comes back when the last vector over the page goes,
2247            // and a caller that wants the bytes narrowed asks for a flatten.
2248            Body::Views { views, arena } if forms_stay => Body::Views {
2249                views: at
2250                    .iter()
2251                    .map(|&index| views.get(index).copied().unwrap_or_else(StringView::empty))
2252                    .collect(),
2253                arena: Arc::clone(arena),
2254            },
2255            // Flattening promises a data slice, so the bytes are copied out into an arena of their
2256            // own and the shared one is let go of. The total is known before any of it is copied,
2257            // the way the flat copy works it out, so the new arena is one allocation.
2258            Body::Views { views, arena } => {
2259                let mut out = StringColumn::with_capacity(at.len());
2260                out.reserve_bytes(
2261                    at.iter()
2262                        .filter_map(|&index| views.get(index))
2263                        .filter(|view| !view.is_inline())
2264                        .map(StringView::len)
2265                        .sum(),
2266                );
2267                for &index in &at {
2268                    let bytes = views.get(index).and_then(|view| view.bytes_in(arena));
2269                    out.push_bytes(bytes.unwrap_or_default());
2270                }
2271                Body::Flat(Data::Varlen(out))
2272            }
2273            Body::ExternalText { source } => {
2274                let mut out = StringColumn::with_capacity(at.len());
2275                for &index in &at {
2276                    out.push_bytes(source.bytes_at(index)?.unwrap_or_default());
2277                }
2278                Body::Flat(Data::Varlen(out))
2279            }
2280            // A gather keeps the form, because the codes do not move and a span survives being put
2281            // in an order the codes are not in. A position that resolved to nowhere gets the empty
2282            // span, which decompresses to no bytes, which is the zero every other layout writes.
2283            Body::Coded { codes, spans, table } if forms_stay => Body::Coded {
2284                codes: Arc::clone(codes),
2285                spans: at
2286                    .iter()
2287                    .map(|&index| spans.get(index).copied().unwrap_or((0, 0)))
2288                    .collect(),
2289                table: Arc::clone(table),
2290            },
2291            // Flattening decompresses, which is the price of the data slice it promises. The scratch
2292            // buffer is reused across rows, so this is one allocation for the whole column rather
2293            // than one per row the way reading it a value at a time would be.
2294            Body::Coded { codes, spans, table } => {
2295                let mut out = StringColumn::with_capacity(at.len());
2296                let mut scratch = Vec::new();
2297                for &index in &at {
2298                    scratch.clear();
2299                    let span = spans
2300                        .get(index)
2301                        .and_then(|&(from, to)| codes.get(from as usize..to as usize));
2302                    if let Some(span) = span {
2303                        table.decompress(span, &mut scratch)?;
2304                    }
2305                    out.push_bytes(&scratch);
2306                }
2307                Body::Flat(Data::Varlen(out))
2308            }
2309            // The entries move and the child does not, which is the same trade the string forms
2310            // make and is why a gather of a list column costs eight bytes a row however long the
2311            // lists are. A position that resolved to nowhere gets a zero length entry, and the mask
2312            // already says it is null, so the entry is never read.
2313            //
2314            // This arm ignores `forms_stay`, unlike every arm above it, because there is nothing
2315            // flatter for a list to become. The other forms are all cheaper ways of writing down a
2316            // column of scalars and flattening gives up the saving to hand back a data slice, and a
2317            // list has no data slice in any form, so a flatten of one is this and a caller reading it
2318            // goes through `list_parts` either way.
2319            Body::Nested { entries, child } => Body::Nested {
2320                entries: at
2321                    .iter()
2322                    .map(|&index| entries.get(index).copied().unwrap_or((0, 0)))
2323                    .collect(),
2324                child: Arc::clone(child),
2325            },
2326            // Every child gathered at the same positions, for the reason the cut cuts every child:
2327            // there are no entries to permute instead, so the permutation happens once per field. The
2328            // positions handed down are the resolved ones, sentinel and all, so a row that resolved to
2329            // nowhere comes back null in each field as well as null here.
2330            //
2331            // `forms_stay` is passed straight through rather than ignored, which is the opposite of
2332            // what the list arm does, and the difference is real. There is nothing flatter for a list
2333            // to become, and a struct is only as flat as its fields are, so a flatten of a struct
2334            // column is a flatten of each field and a caller that asked for data slices gets them.
2335            Body::Fields { children } => Body::Fields {
2336                children: children
2337                    .iter()
2338                    .map(|child| child.copied(at.clone(), forms_stay).map(Arc::new))
2339                    .collect::<Result<Vec<_>>>()?,
2340            },
2341            // Unreachable, because `resolve` walks past both of the forms that point at another
2342            // vector and stops at the first body that does not.
2343            Body::Dictionary { .. } | Body::Runs { .. } => {
2344                return Err(Error::internal(
2345                    "a form that points somewhere survived being resolved",
2346                ));
2347            }
2348        };
2349        Ok(Self { ty: self.ty.clone(), len: rows, validity, body })
2350    }
2351
2352    /// Where each wanted position lives in the first body that is not a dictionary, and that body.
2353    ///
2354    /// A position that is null anywhere on the way down, or past the end of anything on the way
2355    /// down, comes back as [`NOWHERE`]. That single sentinel is what keeps the copy loop from
2356    /// carrying a validity mask alongside the positions it is already walking.
2357    fn resolve(&self, mut at: Vec<usize>) -> (Vec<usize>, &Self) {
2358        let mut source = self;
2359        loop {
2360            for slot in &mut at {
2361                if *slot >= source.len || !source.validity.is_valid(*slot) {
2362                    *slot = NOWHERE;
2363                }
2364            }
2365            source = match &source.body {
2366                Body::Dictionary { codes, values, .. } => {
2367                    for slot in &mut at {
2368                        *slot = match codes.get(*slot) {
2369                            Some(&code) => code as usize,
2370                            None => NOWHERE,
2371                        };
2372                    }
2373                    values.as_ref()
2374                }
2375                // A run length body is a dictionary whose code is worked out from the position
2376                // rather than stored, so the walk down is the same walk with a search where the
2377                // lookup was. `NOWHERE` searches for nothing and stays `NOWHERE`.
2378                Body::Runs { ends, values } => {
2379                    for slot in &mut at {
2380                        *slot = run_holding(ends, *slot).unwrap_or(NOWHERE);
2381                    }
2382                    values.as_ref()
2383                }
2384                _ => return (at, source),
2385            };
2386        }
2387    }
2388}
2389
2390/// So that a kernel can take its operands as either a list of vectors or a list of references.
2391///
2392/// A caller that built a `Vec<Vector>` and a caller whose operands are already somewhere else, in a
2393/// chunk or in an evaluator's scratch, want the same kernel. Without this the second kind has to
2394/// clone every operand into a `Vec` to satisfy the signature, and a clone of a vector is a copy of
2395/// the whole column, so the type would be charging real memory traffic for nothing.
2396impl AsRef<Vector> for Vector {
2397    fn as_ref(&self) -> &Vector {
2398        self
2399    }
2400}
2401
2402/// The bits of a packed vector and what they mean, for a kernel that wants to stay in code space.
2403///
2404/// Borrowed from the vector rather than owning anything, so getting one costs nothing and a kernel
2405/// that finds it cannot use them has given up nothing by asking.
2406#[derive(Debug, Clone, Copy)]
2407pub struct Packed<'a> {
2408    words: &'a [u64],
2409    width: u32,
2410    base: i128,
2411    offset: usize,
2412}
2413
2414impl Packed<'_> {
2415    /// Packed words. A persisted vector also records [`Self::offset`].
2416    #[must_use]
2417    pub fn words(&self) -> &[u64] {
2418        self.words
2419    }
2420
2421    /// Bit offset, in rows, of the first value.
2422    #[must_use]
2423    pub fn offset(&self) -> usize {
2424        self.offset
2425    }
2426
2427    /// How many bits one code takes, between one and [`PACKED_WIDTH_MAX`].
2428    #[must_use]
2429    pub fn width(&self) -> u32 {
2430        self.width
2431    }
2432
2433    /// What zero means, so that the value of a row is the base plus its code.
2434    #[must_use]
2435    pub fn base(&self) -> i128 {
2436        self.base
2437    }
2438
2439    /// The largest value this vector can be holding, whatever it is actually holding.
2440    ///
2441    /// With [`Self::base`] this is the pair a comparison kernel wants first. A literal outside the
2442    /// two answers every row of the vector the same way, which is a whole chunk decided without a
2443    /// bit being read, and that is the case a zone map would have caught if there were one here.
2444    #[must_use]
2445    pub fn ceiling(&self) -> i128 {
2446        self.base + i128::from(u64::MAX >> (u64::BITS - self.width))
2447    }
2448
2449    /// The code of row `row`, which is its value minus [`Self::base`].
2450    ///
2451    /// Out of range rows read as zero rather than panicking, the way every other accessor in this
2452    /// file answers for a row that is not there.
2453    #[must_use]
2454    pub fn code(&self, row: usize) -> u64 {
2455        code_at(self.words, (self.offset + row) * self.width as usize, self.width)
2456    }
2457
2458    /// Which code a value would have, and `None` for a value this vector cannot be holding.
2459    ///
2460    /// The translation a comparison does once per vector so that it does not have to unpack once per
2461    /// row. `None` is the useful answer rather than a failure: it says the literal is outside the
2462    /// packed range, so every row compares against it the same way.
2463    #[must_use]
2464    pub fn code_of(&self, value: i128) -> Option<u64> {
2465        u64::try_from(value.checked_sub(self.base)?).ok().filter(|&code| code <= self.mask())
2466    }
2467
2468    /// The largest code the width allows.
2469    fn mask(&self) -> u64 {
2470        u64::MAX >> (u64::BITS - self.width)
2471    }
2472}
2473
2474/// The widest a packed code is allowed to be.
2475///
2476/// Sixty three rather than sixty four so that a mask is `u64::MAX >> (64 - width)` with no shift of
2477/// a whole word in it, and reading a code is one branch on whether it straddles rather than two. A
2478/// sixty four bit code saves nothing anyway, since it is the layout it came from.
2479pub const PACKED_WIDTH_MAX: u32 = 63;
2480
2481/// How much smaller packing has to be before it is worth the shift and the mask on every read.
2482///
2483/// Two, so a column packs when the bits come to half the flat size or less. A column that would save
2484/// a tenth stays flat, because a tenth of a column is not worth turning every read of it into
2485/// arithmetic, and the whole argument for the form is that a narrow column saves most of itself.
2486pub const PACKING_PAYS_AT: usize = 2;
2487
2488/// How much smaller compressing has to be before it is worth a decompression on every read.
2489///
2490/// Two, the same rule packing follows and for the same reason. FSST gets about that on text, so a
2491/// column of English or of URLs compresses and a column of short codes or of random bytes does not,
2492/// which is the right answer for both.
2493pub const FSST_PAYS_AT: usize = 2;
2494
2495/// The codes of a compressed column and the table they are against.
2496///
2497/// Handed out by [`Vector::coded_parts`] so a kernel can work in code space. Nothing here
2498/// decompresses, which is the point: [`Self::encode`] puts the literal into the same space the rows
2499/// are already in, and after that an equality test is a byte slice comparison.
2500#[derive(Debug, Clone, Copy)]
2501pub struct Coded<'a> {
2502    codes: &'a [u8],
2503    spans: &'a [(u32, u32)],
2504    table: &'a SymbolTable,
2505}
2506
2507impl Coded<'_> {
2508    /// The table every row in this vector is compressed against.
2509    #[must_use]
2510    pub fn table(&self) -> &SymbolTable {
2511        self.table
2512    }
2513
2514    /// The code bytes of one row, still compressed.
2515    #[must_use]
2516    pub fn row(&self, row: usize) -> Option<&[u8]> {
2517        let &(from, to) = self.spans.get(row)?;
2518        self.codes.get(from as usize..to as usize)
2519    }
2520
2521    /// Some bytes in the code space this vector is in.
2522    ///
2523    /// The literal side of an equality filter. Compressing is a function of the table and the bytes,
2524    /// so two strings compress to the same codes exactly when they are the same string, and an
2525    /// equality test on the codes is an equality test on the strings with no decompression in it.
2526    #[must_use]
2527    pub fn encode(&self, bytes: &[u8]) -> Vec<u8> {
2528        let mut out = Vec::with_capacity(bytes.len());
2529        self.table.compress(bytes, &mut out);
2530        out
2531    }
2532}
2533
2534/// How many words hold `len` codes of `width` bits.
2535fn words_for(len: usize, width: u32) -> usize {
2536    (len * width as usize).div_ceil(u64::BITS as usize)
2537}
2538
2539/// The lowest and highest value a type's layout can hold, and `None` for a type with no integer one.
2540///
2541/// This is also the test of whether a type can be packed at all, and it is the only one, so the
2542/// layouts listed here and the layouts [`pack`] and [`unpack`] know how to walk are the same list
2543/// from the same macro and cannot drift apart.
2544fn layout_range(ty: &LogicalType) -> Option<(i128, i128)> {
2545    use rudb_common::PhysicalType as P;
2546    macro_rules! ranges {
2547        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
2548            match ty.physical() {
2549                $(P::$variant => Some((i128::from(<$native>::MIN), i128::from(<$native>::MAX))),)+
2550                _ => None,
2551            }
2552        };
2553    }
2554    crate::for_each_layout!(exact, ranges)
2555}
2556
2557/// The lowest and highest value in the first `len` slots of a run of integer data.
2558///
2559/// `None` for data that is not integers, which is what says a column cannot be packed. The null
2560/// slots are in the span, holding whatever zero was written into them, which
2561/// [`Vector::bit_packed`] says more about.
2562fn span_of(data: &Data, len: usize) -> Option<(i128, i128)> {
2563    macro_rules! spans {
2564        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
2565            match data {
2566                $(Data::$variant(values) => {
2567                    let mut low = i128::MAX;
2568                    let mut high = i128::MIN;
2569                    for &value in values.as_slice().iter().take(len) {
2570                        let value = i128::from(value);
2571                        low = low.min(value);
2572                        high = high.max(value);
2573                    }
2574                    (low <= high).then_some((low, high))
2575                })+
2576                _ => None,
2577            }
2578        };
2579    }
2580    crate::for_each_layout!(exact, spans)
2581}
2582
2583/// The first `len` values of a run of integer data, written out as codes of `width` bits from `base`.
2584fn pack(data: &Data, len: usize, base: i128, width: u32) -> Vec<u64> {
2585    let mut words = vec![0u64; words_for(len, width)];
2586    macro_rules! packing {
2587        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
2588            match data {
2589                $(Data::$variant(values) => {
2590                    for (row, &value) in values.as_slice().iter().take(len).enumerate() {
2591                        // In range because `base` and `width` came from the span of this same run.
2592                        let code = u64::try_from(i128::from(value) - base).unwrap_or(0);
2593                        write_code(&mut words, row * width as usize, width, code);
2594                    }
2595                })+
2596                _ => {}
2597            }
2598        };
2599    }
2600    crate::for_each_layout!(exact, packing);
2601    words
2602}
2603
2604/// The codes at the given rows, unpacked into the flat layout the type calls for.
2605///
2606/// A row of [`NOWHERE`] writes the layout's zero, which is the rule [`copy_of`] follows for the same
2607/// reason: every layout here is a parallel array to a validity mask, so a null takes a slot.
2608///
2609/// # Errors
2610///
2611/// If the type has no flat layout, which a packed vector cannot have and which is checked when one
2612/// is built, so an error here is a bug rather than a caller mistake.
2613fn unpack(
2614    ty: &LogicalType,
2615    words: &[u64],
2616    offset: usize,
2617    width: u32,
2618    base: i128,
2619    at: &[usize],
2620) -> Result<Data> {
2621    let mut out = empty_data_for(ty)?;
2622    let value_of = |row: usize| {
2623        if row == NOWHERE {
2624            return None;
2625        }
2626        Some(base + i128::from(code_at(words, (offset + row) * width as usize, width)))
2627    };
2628    macro_rules! unpacking {
2629        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
2630            match &mut out {
2631                $(Data::$variant(values) => {
2632                    values.reserve(at.len());
2633                    for &row in at {
2634                        // In range because both ends of it were checked when the vector was built.
2635                        let value = value_of(row)
2636                            .and_then(|value| <$native>::try_from(value).ok())
2637                            .unwrap_or($zero);
2638                        values.push(value);
2639                    }
2640                })+
2641                _ => {
2642                    return Err(Error::internal(format!(
2643                        "a {ty} vector was packed, which no integer layout allows"
2644                    )));
2645                }
2646            }
2647        };
2648    }
2649    crate::for_each_layout!(exact, unpacking);
2650    Ok(out)
2651}
2652
2653/// The `width` bits starting at `bit`, low end first.
2654///
2655/// Zero for bits past the end of the words, which keeps a read of a row that is not there from
2656/// panicking and matches what every other accessor here does with one.
2657fn code_at(words: &[u64], bit: usize, width: u32) -> u64 {
2658    let word = bit / u64::BITS as usize;
2659    let shift = (bit % u64::BITS as usize) as u32;
2660    let mask = u64::MAX >> (u64::BITS - width);
2661    let low = words.get(word).copied().unwrap_or(0) >> shift;
2662    let taken = u64::BITS - shift;
2663    if taken >= width {
2664        return low & mask;
2665    }
2666    // The code straddles two words, and `taken` is under the width here so it is under sixty four,
2667    // which is what makes the shift below one the hardware will do rather than one it refuses.
2668    let high = words.get(word + 1).copied().unwrap_or(0) << taken;
2669    (low | high) & mask
2670}
2671
2672/// Writes `width` bits of `code` starting at `bit`, over words that started out zero.
2673fn write_code(words: &mut [u64], bit: usize, width: u32, code: u64) {
2674    let word = bit / u64::BITS as usize;
2675    let shift = (bit % u64::BITS as usize) as u32;
2676    words[word] |= code << shift;
2677    let taken = u64::BITS - shift;
2678    if taken < width {
2679        words[word + 1] |= code >> taken;
2680    }
2681}
2682
2683/// One level of dictionary out of however many levels were handed to [`Vector::dictionary`].
2684///
2685/// Every dictionary in the system is built through that constructor and every one of them comes
2686/// through here first, so the invariant this maintains is that the vector a dictionary points at is
2687/// never itself a dictionary that could have been composed away. That makes the work a single `if`
2688/// rather than a loop: the inner vector was already composed when it was built, so composing the
2689/// outer codes through it leaves the result no deeper than the inner vector already was.
2690///
2691/// The codes are indexed rather than fetched with `get`, because the caller has already walked the
2692/// whole outer array to check that every code is in range and the inner array is exactly as long as
2693/// the vector those codes were checked against.
2694fn compose(codes: Vec<u32>, values: Vector) -> (Vec<u32>, Vector) {
2695    // A dictionary carrying a validity of its own is one whose nulls live at this level rather than
2696    // in the values, which is the one thing composition cannot carry down with it.
2697    if !matches!(values.validity, Validity::AllValid) {
2698        return (codes, values);
2699    }
2700    let Vector { ty, len, validity, body } = values;
2701    match body {
2702        Body::Dictionary { codes: inner, values: leaf, .. } => {
2703            debug_assert!(
2704                !matches!(leaf.body, Body::Dictionary { .. })
2705                    || !matches!(leaf.validity, Validity::AllValid),
2706                "a dictionary was stacked on a dictionary without going through the constructor"
2707            );
2708            // The leaf is shared, so taking it out of the `Arc` copies it when something else is
2709            // still holding the same dictionary. That is the rare path: a dictionary over a
2710            // dictionary only arrives from a caller that built one that way, and the cut that made
2711            // sharing worth doing produces neither.
2712            (codes.iter().map(|&code| inner[code as usize]).collect(), Arc::unwrap_or_clone(leaf))
2713        }
2714        body => (codes, Vector { ty, len, validity, body }),
2715    }
2716}
2717
2718/// How many rows a run has to cover on average before run length encoding is smaller.
2719///
2720/// A run costs its value plus the four bytes of its end, so on a four byte column a run of two rows
2721/// breaks even and a run of three wins. Wider columns win sooner and narrower ones later, and this
2722/// is the one ratio for all of them because a threshold per width is a table that has to be right
2723/// nine times rather than once. It is a constant with a name so that the sweep that eventually moves
2724/// it has something to move.
2725const RUNS_PAY_AT: usize = 2;
2726
2727/// Which run holds `row`, given ends that are exclusive and increasing.
2728///
2729/// A binary search rather than a scan, because the callers that ask this are the ones that are not
2730/// walking the runs in order: a single value read out of a result set, or a gather at scattered
2731/// positions. Anything walking in order should be reading [`Vector::run_parts`] instead, which is
2732/// what the form is for.
2733fn run_holding(ends: &[u32], row: usize) -> Option<usize> {
2734    let row = u32::try_from(row).ok()?;
2735    let run = match ends.binary_search(&row) {
2736        // The ends are exclusive, so landing exactly on one means the row is the first of the next.
2737        Ok(at) => at + 1,
2738        Err(at) => at,
2739    };
2740    (run < ends.len()).then_some(run)
2741}
2742
2743/// The row each run ends at, for a flat body read alongside the validity that goes with it.
2744///
2745/// Two adjacent nulls are one run, because a reader of either gets a null and cannot tell them
2746/// apart. A null between two equal values is three runs for the same reason, since the null is a
2747/// value of the column as far as anything reading it is concerned.
2748///
2749/// The comparison is per layout rather than per `Value`, which is the whole reason this is a macro.
2750/// A `Value` a row would allocate a string per row on a `VARCHAR` column and would be the exact
2751/// defect `cargo xtask rowloop` exists to fail the build on.
2752fn boundaries(data: &Data, validity: &Validity, len: usize) -> Vec<u32> {
2753    if len == 0 {
2754        return Vec::new();
2755    }
2756    let breaks = |ends: &mut Vec<u32>, mut differs: Box<dyn FnMut(usize, usize) -> bool + '_>| {
2757        for row in 1..len {
2758            let same = match (validity.is_valid(row), validity.is_valid(row - 1)) {
2759                (false, false) => true,
2760                (true, true) => !differs(row, row - 1),
2761                _ => false,
2762            };
2763            if !same {
2764                ends.push(u32::try_from(row).unwrap_or(u32::MAX));
2765            }
2766        }
2767        ends.push(u32::try_from(len).unwrap_or(u32::MAX));
2768    };
2769    let mut ends = Vec::new();
2770    macro_rules! walked {
2771        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
2772            match data {
2773                // No values at all, so every row is the same null and the column is one run.
2774                Data::Empty => ends.push(u32::try_from(len).unwrap_or(u32::MAX)),
2775                $(Data::$variant(values) => {
2776                    breaks(&mut ends, Box::new(|a, b| values.get(a) != values.get(b)));
2777                })+
2778                Data::Varlen(values) => {
2779                    breaks(&mut ends, Box::new(|a, b| values.bytes(a) != values.bytes(b)));
2780                }
2781            }
2782        };
2783    }
2784    crate::for_each_layout!(fixed, walked);
2785    ends
2786}
2787
2788/// The position of a value that is not anywhere, because it is null or out of range.
2789///
2790/// `usize::MAX` rather than an `Option<usize>`, because the copy loop's bounds check rejects it for
2791/// free and an `Option` would put a second branch next to the one already there.
2792const NOWHERE: usize = usize::MAX;
2793
2794/// A run of data copied at the given positions, with a zero wherever the position is [`NOWHERE`].
2795///
2796/// A zero and not a skip, because every layout here is a parallel array to a validity mask and a
2797/// short one would put every value after the first null at the wrong index. It is the same rule
2798/// [`push_value`] follows for a null.
2799/// A contiguous run of a flat body, copied out.
2800///
2801/// The counterpart to [`copy_of`] for the one case that is a range rather than a set of positions,
2802/// which is what [`Vector::slice`] asks for. Every fixed width layout is one `memcpy` and the
2803/// string layout is a run of views and their bytes, where `copy_of` is a bounds checked index and a
2804/// null test per row.
2805///
2806/// The caller has already checked that `end` is inside the vector, and a body whose data is shorter
2807/// than its vector claims is a bug elsewhere, so a short run is clamped rather than reported.
2808fn run_of(data: &Data, at: usize, end: usize) -> Data {
2809    macro_rules! run {
2810        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
2811            match data {
2812                Data::Empty => Data::Empty,
2813                $(Data::$variant(values) => {
2814                    let values = values.as_slice();
2815                    let from = at.min(values.len());
2816                    let to = end.max(from).min(values.len());
2817                    let mut out = Buffer::with_capacity(end - at);
2818                    out.extend_from_slice(&values[from..to]);
2819                    // A body shorter than the rows asked for pads with the zero every layout uses
2820                    // for a null, which is the answer `copy_of` gives for a position past the end.
2821                    // row at a time: never runs on a vector whose data matches its length.
2822                    for _ in to..end {
2823                        out.push($zero);
2824                    }
2825                    Data::$variant(out)
2826                })+
2827                // A view says where its bytes are, so a run of rows is not a run of bytes and this
2828                // is the one layout whose cut is still a loop. The total is known before any of it
2829                // is copied, so the arena is one allocation.
2830                Data::Varlen(values) => {
2831                    let views = values.views();
2832                    let mut out = StringColumn::with_capacity(end - at);
2833                    out.reserve_bytes(
2834                        views
2835                            .get(at.min(views.len())..end.min(views.len()))
2836                            .unwrap_or(&[])
2837                            .iter()
2838                            .filter(|view| !view.is_inline())
2839                            .map(StringView::len)
2840                            .sum(),
2841                    );
2842                    // row at a time: see above, the bytes of consecutive rows need not be next to
2843                    // each other.
2844                    for index in at..end {
2845                        out.push_from(values, index);
2846                    }
2847                    Data::Varlen(out)
2848                }
2849            }
2850        };
2851    }
2852    crate::for_each_layout!(fixed, run)
2853}
2854
2855fn copy_of(data: &Data, at: &[usize]) -> Data {
2856    macro_rules! copied {
2857        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
2858            match data {
2859                Data::Empty => Data::Empty,
2860                $(Data::$variant(values) => {
2861                    let mut out = Buffer::with_capacity(at.len());
2862                    for &index in at {
2863                        // One bounds check rather than a null test and a bounds check, because
2864                        // `NOWHERE` is past the end of every slice there can be.
2865                        out.push(values.get(index).copied().unwrap_or($zero));
2866                    }
2867                    Data::$variant(out)
2868                })+
2869                // The one layout where a gather is a copy of bytes rather than a copy of fixed
2870                // width slots, and the reason compaction is a decision rather than a default on a
2871                // string column.
2872                Data::Varlen(values) => {
2873                    let mut out = StringColumn::with_capacity(at.len());
2874                    // The bytes are known before any of them are copied, because a view carries its
2875                    // length and the wanted positions are already in hand, so the arena is one
2876                    // allocation rather than a run of doublings that each copy what the last one
2877                    // copied.
2878                    let views = values.views();
2879                    out.reserve_bytes(
2880                        at.iter()
2881                            .filter_map(|&index| views.get(index))
2882                            .filter(|view| !view.is_inline())
2883                            .map(StringView::len)
2884                            .sum(),
2885                    );
2886                    for &index in at {
2887                        out.push_from(values, index);
2888                    }
2889                    Data::Varlen(out)
2890                }
2891            }
2892        };
2893    }
2894    crate::for_each_layout!(fixed, copied)
2895}
2896
2897/// The physical layout a run of data is in, for the check that it matches its type.
2898///
2899/// The two enums name their variants the same way on purpose, so this is one generated arm rather
2900/// than sixteen chances to pair the wrong two up.
2901fn layout_of(data: &Data) -> rudb_common::PhysicalType {
2902    use rudb_common::PhysicalType as P;
2903    macro_rules! layouts {
2904        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
2905            match data {
2906                Data::Empty => P::Empty,
2907                $(Data::$variant(_) => P::$variant,)+
2908            }
2909        };
2910    }
2911    crate::for_each_layout!(all, layouts)
2912}
2913
2914/// One value out of a run of data, given what the run means.
2915///
2916/// The match is on the logical type rather than on the data, because the data cannot tell a `DATE`
2917/// from an `INTEGER` and that is the whole reason the two are kept apart.
2918fn value_from(ty: &LogicalType, data: &Data, index: usize) -> Value {
2919    let signed = || data.signed_at(index);
2920    let unsigned = || data.unsigned_at(index);
2921    let value = match ty {
2922        LogicalType::Boolean => match data {
2923            Data::Bool(v) => v.get(index).map(|&x| Value::Boolean(x)),
2924            _ => None,
2925        },
2926        LogicalType::TinyInt => signed().and_then(|x| i8::try_from(x).ok()).map(Value::TinyInt),
2927        LogicalType::SmallInt => signed().and_then(|x| i16::try_from(x).ok()).map(Value::SmallInt),
2928        LogicalType::Integer => signed().and_then(|x| i32::try_from(x).ok()).map(Value::Integer),
2929        LogicalType::BigInt => signed().and_then(|x| i64::try_from(x).ok()).map(Value::BigInt),
2930        LogicalType::HugeInt => signed().map(Value::HugeInt),
2931        LogicalType::UTinyInt => unsigned().and_then(|x| u8::try_from(x).ok()).map(Value::UTinyInt),
2932        LogicalType::USmallInt => {
2933            unsigned().and_then(|x| u16::try_from(x).ok()).map(Value::USmallInt)
2934        }
2935        LogicalType::UInteger => {
2936            unsigned().and_then(|x| u32::try_from(x).ok()).map(Value::UInteger)
2937        }
2938        LogicalType::UBigInt => unsigned().and_then(|x| u64::try_from(x).ok()).map(Value::UBigInt),
2939        LogicalType::UHugeInt => unsigned().map(Value::UHugeInt),
2940        LogicalType::Float => match data {
2941            Data::Float32(v) => v.get(index).map(|&x| Value::Float(x)),
2942            _ => None,
2943        },
2944        LogicalType::Double => match data {
2945            Data::Float64(v) => v.get(index).map(|&x| Value::Double(x)),
2946            _ => None,
2947        },
2948        LogicalType::Decimal { width, scale } => {
2949            signed().map(|unscaled| Value::Decimal { unscaled, width: *width, scale: *scale })
2950        }
2951        LogicalType::Varchar | LogicalType::Blob | LogicalType::Bit => {
2952            data.bytes_at(index).map(|bytes| bytes_as(ty, bytes))
2953        }
2954        LogicalType::Date => signed().and_then(|x| i32::try_from(x).ok()).map(Value::Date),
2955        LogicalType::Time => signed().and_then(|x| i64::try_from(x).ok()).map(Value::Time),
2956        LogicalType::TimeTz => signed().and_then(|x| i64::try_from(x).ok()).map(Value::TimeTz),
2957        LogicalType::Timestamp
2958        | LogicalType::TimestampS
2959        | LogicalType::TimestampMs
2960        | LogicalType::TimestampNs => {
2961            signed().and_then(|x| i64::try_from(x).ok()).map(Value::Timestamp)
2962        }
2963        LogicalType::TimestampTz => {
2964            signed().and_then(|x| i64::try_from(x).ok()).map(Value::TimestampTz)
2965        }
2966        LogicalType::Interval => match data {
2967            Data::Interval(v) => {
2968                v.get(index).map(|&(months, days, micros)| Value::Interval { months, days, micros })
2969            }
2970            _ => None,
2971        },
2972        _ => None,
2973    };
2974    value.unwrap_or(Value::Null)
2975}
2976
2977/// The fields a struct type names, and nothing for any other type.
2978///
2979/// Only a `STRUCT` vector has a [`Body::Fields`] body, and the two are built together, so in practice
2980/// the empty slice is unreachable and is here so that reading a field name is not a panic if that ever
2981/// stops being true. A struct vector whose type has fewer fields than it has children answers about
2982/// the fields it can name, because the zip stops at the shorter of the two.
2983fn fields_of(ty: &LogicalType) -> &[Field] {
2984    match ty {
2985        LogicalType::Struct(fields) => fields,
2986        _ => &[],
2987    }
2988}
2989
2990/// One row of a string column as a value, given what its bytes are meant to be read as.
2991///
2992/// Both forms that hold strings come through here, so a row that is a `BLOB` in a flat column is a
2993/// `BLOB` in a string view column too. Bytes that are not text in a `VARCHAR` column are a null
2994/// rather than a panic, since everything that got in went in as a string and a column that has
2995/// something else in it is a bug somewhere earlier that a read should not turn into a crash.
2996fn bytes_as(ty: &LogicalType, bytes: &[u8]) -> Value {
2997    match ty {
2998        LogicalType::Varchar => {
2999            std::str::from_utf8(bytes).map_or(Value::Null, |text| Value::Varchar(text.to_owned()))
3000        }
3001        LogicalType::Blob | LogicalType::Bit => Value::Blob(bytes.to_vec()),
3002        _ => Value::Null,
3003    }
3004}
3005
3006/// An empty run of data of the right layout for a type.
3007fn empty_data_for(ty: &LogicalType) -> Result<Data> {
3008    use rudb_common::PhysicalType as P;
3009    macro_rules! empties {
3010        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
3011            match ty.physical() {
3012                P::Empty => Data::Empty,
3013                $(P::$variant => Data::$variant(Buffer::new()),)+
3014                P::Varlen => Data::Varlen(StringColumn::new()),
3015                other => {
3016                    return Err(Error::not_implemented(format!(
3017                        "a flat vector of {other:?} data, which arrives with the storage layer"
3018                    )));
3019                }
3020            }
3021        };
3022    }
3023    Ok(crate::for_each_layout!(fixed, empties))
3024}
3025
3026/// Appends one value to a run of data, or a zero of the right shape when it is null.
3027///
3028/// The zero matters. A null still occupies a position, the validity mask is what says it is null,
3029/// and a run of data with a hole in it would put every value after the hole in the wrong place.
3030fn push_value(data: &mut Data, value: &Value) -> Result<()> {
3031    macro_rules! push {
3032        ($vec:expr, $variant:path, $zero:expr) => {
3033            match value {
3034                Value::Null => $vec.push($zero),
3035                $variant(x) => $vec.push(*x),
3036                other => {
3037                    return Err(Error::internal(format!(
3038                        "{other:?} does not belong in this vector"
3039                    )));
3040                }
3041            }
3042        };
3043    }
3044    // A decimal is stored as its unscaled integer in whatever width its precision needs, which
3045    // `LogicalType::physical` decides and which is why the same `Value::Decimal` is at home in four
3046    // different runs. The narrowing cannot fail for a value the binder produced, because the width
3047    // that chose the run is the width in the value, but it is checked rather than assumed because
3048    // an unchecked cast here would silently store a different number.
3049    macro_rules! decimal {
3050        ($vec:expr, $ty:ty, $unscaled:expr) => {
3051            match <$ty>::try_from(*$unscaled) {
3052                Ok(x) => $vec.push(x),
3053                Err(_) => {
3054                    return Err(Error::internal(format!(
3055                        "an unscaled decimal of {} does not fit the run its precision chose",
3056                        $unscaled
3057                    )));
3058                }
3059            }
3060        };
3061    }
3062    match data {
3063        Data::Empty => {}
3064        Data::Bool(v) => push!(v, Value::Boolean, false),
3065        Data::Int8(v) => push!(v, Value::TinyInt, 0),
3066        Data::Int16(v) => match value {
3067            Value::Null => v.push(0),
3068            Value::SmallInt(x) => v.push(*x),
3069            Value::Decimal { unscaled, .. } => decimal!(v, i16, unscaled),
3070            other => return Err(Error::internal(format!("{other:?} is not a 16 bit value"))),
3071        },
3072        Data::Int32(v) => match value {
3073            Value::Null => v.push(0),
3074            Value::Integer(x) | Value::Date(x) => v.push(*x),
3075            Value::Decimal { unscaled, .. } => decimal!(v, i32, unscaled),
3076            other => return Err(Error::internal(format!("{other:?} is not a 32 bit value"))),
3077        },
3078        Data::Int64(v) => match value {
3079            Value::Null => v.push(0),
3080            Value::BigInt(x)
3081            | Value::Time(x)
3082            | Value::TimeTz(x)
3083            | Value::Timestamp(x)
3084            | Value::TimestampTz(x) => v.push(*x),
3085            Value::Decimal { unscaled, .. } => decimal!(v, i64, unscaled),
3086            other => return Err(Error::internal(format!("{other:?} is not a 64 bit value"))),
3087        },
3088        Data::Int128(v) => match value {
3089            Value::Null => v.push(0),
3090            Value::HugeInt(x) => v.push(*x),
3091            Value::Decimal { unscaled, .. } => v.push(*unscaled),
3092            other => return Err(Error::internal(format!("{other:?} is not a 128 bit value"))),
3093        },
3094        Data::UInt8(v) => push!(v, Value::UTinyInt, 0),
3095        Data::UInt16(v) => push!(v, Value::USmallInt, 0),
3096        Data::UInt32(v) => push!(v, Value::UInteger, 0),
3097        Data::UInt64(v) => push!(v, Value::UBigInt, 0),
3098        Data::UInt128(v) => push!(v, Value::UHugeInt, 0),
3099        Data::Float32(v) => push!(v, Value::Float, 0.0),
3100        Data::Float64(v) => push!(v, Value::Double, 0.0),
3101        Data::Interval(v) => match value {
3102            Value::Null => v.push((0, 0, 0)),
3103            Value::Interval { months, days, micros } => v.push((*months, *days, *micros)),
3104            other => return Err(Error::internal(format!("{other:?} is not an interval"))),
3105        },
3106        Data::Varlen(column) => match value {
3107            Value::Null => {
3108                column.push("");
3109            }
3110            Value::Varchar(text) => {
3111                column.push(text);
3112            }
3113            // A blob goes in as the bytes it is. The column stores a length and some bytes either
3114            // way, so text is the reading of one rather than a different column, and a blob that
3115            // is not UTF-8 is stored exactly like one that happens to be.
3116            Value::Blob(bytes) => {
3117                column.push_bytes(bytes);
3118            }
3119            other => return Err(Error::internal(format!("{other:?} is not a string"))),
3120        },
3121    }
3122    Ok(())
3123}
3124
3125#[cfg(test)]
3126mod tests {
3127    use std::sync::Arc;
3128
3129    use rudb_common::{Field, LogicalType, Value};
3130
3131    use super::{Body, Data, FSST_PAYS_AT, Form, MAP_KEY, MAP_VALUE, VECTOR_SIZE, Vector};
3132    use crate::buffer::Buffer;
3133    use crate::fsst::SymbolTable;
3134    use crate::string::{StringColumn, StringView};
3135    use crate::validity::Validity;
3136
3137    fn integers(values: &[i32]) -> Vector {
3138        Vector::flat(LogicalType::Integer, Data::Int32(values.to_vec().into())).unwrap()
3139    }
3140
3141    /// A `Value::List` of integers, which is what a row of a list column arrives as.
3142    fn list(values: &[i32]) -> Value {
3143        Value::List {
3144            element: LogicalType::Integer,
3145            values: values.iter().map(|&v| Value::Integer(v)).collect(),
3146        }
3147    }
3148
3149    fn list_column(rows: &[Value]) -> Vector {
3150        Vector::from_values(LogicalType::list(LogicalType::Integer), rows).unwrap()
3151    }
3152
3153    #[test]
3154    fn a_list_column_is_one_child_and_a_range_per_row() {
3155        let rows = vec![list(&[1, 2, 3]), list(&[]), Value::Null, list(&[4])];
3156        let column = list_column(&rows);
3157        assert_eq!(column.form(), Form::List);
3158        assert_eq!(column.len(), 4);
3159        assert_eq!(column.logical_type(), &LogicalType::list(LogicalType::Integer));
3160        // Four rows and four elements, because a null and an empty list both contribute none.
3161        let (entries, child) = column.list_parts().expect("a list");
3162        assert_eq!(entries, [(0, 3), (3, 0), (3, 0), (3, 1)]);
3163        assert_eq!(child.len(), 4);
3164        assert_eq!(column.iter().collect::<Vec<_>>(), rows);
3165    }
3166
3167    /// The one thing the entries cannot say on their own, so it has to be checked that the mask says
3168    /// it. An empty list is a row that is there and holds nothing, a null is a row that is not there,
3169    /// and both of them have an entry of length zero.
3170    #[test]
3171    fn an_empty_list_and_a_null_list_have_the_same_entry_and_are_different_rows() {
3172        let column = list_column(&[list(&[]), Value::Null]);
3173        let (entries, _) = column.list_parts().expect("a list");
3174        assert_eq!(entries[0].1, entries[1].1, "both entries are empty");
3175        assert!(!column.is_null_at(0), "an empty list is not null");
3176        assert!(column.is_null_at(1), "a null list is null");
3177        assert_eq!(column.value_at(0), list(&[]));
3178        assert_eq!(column.value_at(1), Value::Null);
3179    }
3180
3181    #[test]
3182    fn slicing_a_list_column_shares_the_child_rather_than_copying_it() {
3183        let rows: Vec<Value> = (0..64).map(|row| list(&[row, row + 1, row + 2])).collect();
3184        let column = list_column(&rows);
3185        let cut = column.slice(8, 4).unwrap();
3186        assert_eq!(cut.form(), Form::List);
3187        assert_eq!(cut.iter().collect::<Vec<_>>(), rows[8..12]);
3188        // The entries are absolute positions in a child that was not cut, which is what makes the
3189        // cut eight bytes a row however long the lists are. The elements outside the range are still
3190        // there and nothing points at them.
3191        let (entries, child) = cut.list_parts().expect("a list");
3192        assert_eq!(entries[0], (24, 3));
3193        assert_eq!(child.len(), 192);
3194    }
3195
3196    #[test]
3197    fn gathering_a_list_column_permutes_the_entries_and_leaves_the_child_alone() {
3198        let rows = vec![list(&[1]), list(&[2, 2]), list(&[3, 3, 3])];
3199        let column = list_column(&rows);
3200        let picked = column.gather(&[2, 0, 2]).unwrap();
3201        assert_eq!(
3202            picked.iter().collect::<Vec<_>>(),
3203            [list(&[3, 3, 3]), list(&[1]), list(&[3, 3, 3])]
3204        );
3205        // Two of the three rows are the same row, which is the case a run of offsets cannot write
3206        // down and a start and a length can. That is the whole reason this form carries both.
3207        assert_eq!(picked.list_parts().expect("a list").1.len(), 6);
3208    }
3209
3210    #[test]
3211    fn a_gather_past_the_end_of_a_list_column_is_null_rather_than_somebody_elses_elements() {
3212        let column = list_column(&[list(&[1, 2]), list(&[3])]);
3213        let picked = column.gather(&[1, 9]).unwrap();
3214        assert_eq!(picked.value_at(0), list(&[3]));
3215        assert_eq!(picked.value_at(1), Value::Null);
3216    }
3217
3218    #[test]
3219    fn a_list_of_lists_nests_as_far_as_it_is_written() {
3220        let outer = Value::List {
3221            element: LogicalType::list(LogicalType::Integer),
3222            values: vec![list(&[1, 2]), list(&[3])],
3223        };
3224        let column = Vector::from_values(
3225            LogicalType::list(LogicalType::list(LogicalType::Integer)),
3226            std::slice::from_ref(&outer),
3227        )
3228        .unwrap();
3229        assert_eq!(column.value_at(0), outer);
3230        assert_eq!(column.list_parts().expect("a list").1.form(), Form::List);
3231    }
3232
3233    /// A list row is not bytes and not an integer, and a caller that asks for either gets nothing
3234    /// rather than the first element or a length. Both of those would be a wrong answer that a
3235    /// group by or a hash would read without complaining.
3236    #[test]
3237    fn the_scalar_readers_decline_a_list_instead_of_answering_about_its_elements() {
3238        let column = list_column(&[list(&[7])]);
3239        assert_eq!(column.signed_at(0), None);
3240        assert_eq!(column.bytes_at(0), None);
3241        assert_eq!(column.data(), None);
3242    }
3243
3244    fn pair(a: i32, b: &str) -> Value {
3245        Value::Struct(vec![
3246            ("a".to_string(), Value::Integer(a)),
3247            ("b".to_string(), Value::Varchar(b.to_string())),
3248        ])
3249    }
3250
3251    fn pair_type() -> LogicalType {
3252        LogicalType::Struct(vec![
3253            Field::new("a", LogicalType::Integer),
3254            Field::new("b", LogicalType::Varchar),
3255        ])
3256    }
3257
3258    fn pair_column(rows: &[Value]) -> Vector {
3259        Vector::from_values(pair_type(), rows).unwrap()
3260    }
3261
3262    #[test]
3263    fn a_struct_column_is_one_child_per_field_as_long_as_the_column() {
3264        let rows = vec![pair(1, "x"), pair(2, "y"), pair(3, "z")];
3265        let column = pair_column(&rows);
3266        assert_eq!(column.form(), Form::Struct);
3267        assert_eq!(column.len(), 3);
3268        assert_eq!(column.logical_type(), &pair_type());
3269        // Two children rather than two entries and a child, and both of them as long as the column,
3270        // which is the whole difference between this form and the list one.
3271        let children = column.struct_parts().expect("a struct");
3272        assert_eq!(children.len(), 2);
3273        assert_eq!(children[0].len(), 3);
3274        assert_eq!(children[1].len(), 3);
3275        assert_eq!(children[0].logical_type(), &LogicalType::Integer);
3276        assert_eq!(children[1].logical_type(), &LogicalType::Varchar);
3277        assert_eq!(column.iter().collect::<Vec<_>>(), rows);
3278    }
3279
3280    /// Picking one field out of a struct is picking one child, which is the reason this accessor is
3281    /// public. A projection of `s.a` hands back a vector that already exists, so it costs a pointer
3282    /// rather than a pass over the rows, and that is only true while the children are full length.
3283    #[test]
3284    fn one_field_of_a_struct_column_is_a_column_that_is_already_there() {
3285        let column = pair_column(&[pair(10, "x"), pair(20, "y")]);
3286        let field = &column.struct_parts().expect("a struct")[0];
3287        assert_eq!(field.iter().collect::<Vec<_>>(), [Value::Integer(10), Value::Integer(20)]);
3288        assert_eq!(field.signed_at(1), Some(20), "the field is a scalar column and reads like one");
3289    }
3290
3291    /// A null struct is a bit in the mask at the top and nothing deeper, which is how every other type
3292    /// records a null and is what DuckDB does. The row reads as a single null rather than as a struct of
3293    /// nulls, and the fields underneath are still their own columns.
3294    #[test]
3295    fn a_null_struct_is_the_mask_at_the_top_and_not_a_struct_full_of_nulls() {
3296        let column = pair_column(&[pair(1, "x"), Value::Null]);
3297        assert!(!column.is_null_at(0));
3298        assert!(column.is_null_at(1));
3299        assert_eq!(column.value_at(1), Value::Null);
3300        // A struct row whose every field happens to be null is a different row, and it is not null.
3301        let all_null = pair_column(&[Value::Struct(vec![
3302            ("a".to_string(), Value::Null),
3303            ("b".to_string(), Value::Null),
3304        ])]);
3305        assert!(!all_null.is_null_at(0), "a struct of nulls is a row that is there");
3306        assert_ne!(all_null.value_at(0), Value::Null);
3307    }
3308
3309    #[test]
3310    fn slicing_a_struct_column_cuts_every_field_at_the_same_place() {
3311        let rows: Vec<Value> = (0..64).map(|row| pair(row, "s")).collect();
3312        let column = pair_column(&rows);
3313        let cut = column.slice(8, 4).unwrap();
3314        assert_eq!(cut.form(), Form::Struct);
3315        assert_eq!(cut.iter().collect::<Vec<_>>(), rows[8..12]);
3316        // The cut a list column does not have to do. A list shares its child untouched because the
3317        // entries carry the range, and a struct has no entry standing between the row and the child,
3318        // so every child is four rows long here rather than sixty four.
3319        for child in cut.struct_parts().expect("a struct") {
3320            assert_eq!(child.len(), 4);
3321        }
3322    }
3323
3324    #[test]
3325    fn gathering_a_struct_column_gathers_every_field_at_the_same_positions() {
3326        let column = pair_column(&[pair(1, "x"), pair(2, "y"), pair(3, "z")]);
3327        let picked = column.gather(&[2, 0, 2]).unwrap();
3328        assert_eq!(picked.iter().collect::<Vec<_>>(), [pair(3, "z"), pair(1, "x"), pair(3, "z")]);
3329        for child in picked.struct_parts().expect("a struct") {
3330            assert_eq!(child.len(), 3, "a field is as long as the gather, not as the source");
3331        }
3332    }
3333
3334    #[test]
3335    fn a_gather_past_the_end_of_a_struct_column_is_null_in_every_field_and_at_the_top() {
3336        let column = pair_column(&[pair(1, "x"), pair(2, "y")]);
3337        let picked = column.gather(&[1, 9]).unwrap();
3338        assert_eq!(picked.value_at(0), pair(2, "y"));
3339        assert_eq!(picked.value_at(1), Value::Null);
3340        for child in picked.struct_parts().expect("a struct") {
3341            assert!(child.is_null_at(1), "a row that came from nowhere has no field value either");
3342        }
3343    }
3344
3345    /// The names are matched and not counted, because a caller holding a struct value built in a
3346    /// different order from the type's would otherwise get its columns transposed, and that is a wrong
3347    /// answer that reads as a right one.
3348    #[test]
3349    fn the_fields_of_a_struct_value_go_in_by_name_rather_than_by_position() {
3350        let swapped = Value::Struct(vec![
3351            ("b".to_string(), Value::Varchar("x".to_string())),
3352            ("a".to_string(), Value::Integer(1)),
3353        ]);
3354        let column = pair_column(&[swapped]);
3355        assert_eq!(column.value_at(0), pair(1, "x"));
3356        let wrong = Value::Struct(vec![
3357            ("a".to_string(), Value::Integer(1)),
3358            ("c".to_string(), Value::Varchar("x".to_string())),
3359        ]);
3360        let failed = Vector::from_values(pair_type(), &[wrong]);
3361        assert!(failed.is_err(), "a row with no b field is an error rather than a null b");
3362    }
3363
3364    #[test]
3365    fn a_struct_built_from_children_takes_its_field_names_from_the_caller() {
3366        let column = Vector::structure(vec![
3367            ("a".to_string(), integers(&[1, 2, 3])),
3368            ("b".to_string(), integers(&[4, 5, 6])),
3369        ])
3370        .expect("two columns of three");
3371        assert_eq!(column.len(), 3);
3372        assert_eq!(
3373            column.logical_type(),
3374            &LogicalType::Struct(vec![
3375                Field::new("a", LogicalType::Integer),
3376                Field::new("b", LogicalType::Integer),
3377            ])
3378        );
3379        assert_eq!(
3380            column.value_at(1),
3381            Value::Struct(vec![
3382                ("a".to_string(), Value::Integer(2)),
3383                ("b".to_string(), Value::Integer(5)),
3384            ])
3385        );
3386    }
3387
3388    /// The two mistakes this constructor makes easy, both refused rather than stored. A short field is
3389    /// the one that matters: it would be a struct that reads past the end of one of its own children,
3390    /// which is the same mistake `Vector::list` checks for at the other end.
3391    #[test]
3392    fn a_struct_of_uneven_children_or_of_no_children_is_refused() {
3393        let uneven = Vector::structure(vec![
3394            ("a".to_string(), integers(&[1, 2, 3])),
3395            ("b".to_string(), integers(&[4, 5])),
3396        ]);
3397        assert!(uneven.is_err(), "a field shorter than the struct");
3398        assert!(Vector::structure(vec![]).is_err(), "no field to take a length from");
3399    }
3400
3401    #[test]
3402    fn a_struct_of_lists_and_a_list_of_structs_both_nest() {
3403        let ty =
3404            LogicalType::Struct(vec![Field::new("a", LogicalType::list(LogicalType::Integer))]);
3405        let row = Value::Struct(vec![("a".to_string(), list(&[1, 2]))]);
3406        let column = Vector::from_values(ty, std::slice::from_ref(&row)).unwrap();
3407        assert_eq!(column.value_at(0), row);
3408        assert_eq!(column.struct_parts().expect("a struct")[0].form(), Form::List);
3409
3410        let outer = Value::List { element: pair_type(), values: vec![pair(1, "x"), pair(2, "y")] };
3411        let lists =
3412            Vector::from_values(LogicalType::list(pair_type()), std::slice::from_ref(&outer))
3413                .unwrap();
3414        assert_eq!(lists.value_at(0), outer);
3415        assert_eq!(lists.list_parts().expect("a list").1.form(), Form::Struct);
3416    }
3417
3418    fn tags(pairs: &[(&str, &str)]) -> Value {
3419        Value::map(
3420            LogicalType::Varchar,
3421            LogicalType::Varchar,
3422            pairs
3423                .iter()
3424                .map(|&(key, value)| {
3425                    (Value::Varchar(key.to_string()), Value::Varchar(value.to_string()))
3426                })
3427                .collect(),
3428        )
3429    }
3430
3431    fn tag_column(rows: &[Value]) -> Vector {
3432        Vector::from_values(LogicalType::map(LogicalType::Varchar, LogicalType::Varchar), rows)
3433            .unwrap()
3434    }
3435
3436    /// A map is a list of two field structs, which is the whole design, so the test that says so is
3437    /// the one that reaches through both layers and finds the pieces where each of them puts them.
3438    #[test]
3439    fn a_map_column_is_a_list_whose_child_is_a_struct_of_keys_and_values() {
3440        let rows =
3441            vec![tags(&[("a", "b"), ("c", "d")]), tags(&[]), Value::Null, tags(&[("e", "f")])];
3442        let column = tag_column(&rows);
3443        assert_eq!(column.len(), 4);
3444        assert_eq!(
3445            column.logical_type(),
3446            &LogicalType::map(LogicalType::Varchar, LogicalType::Varchar)
3447        );
3448        // The physical form is a list's, because the bytes are a list's. The logical type is what
3449        // remembers it is a map, which is the same split `LogicalType::physical` already makes.
3450        assert_eq!(column.form(), Form::List);
3451        let (entries, child) = column.list_parts().expect("the layout of a list");
3452        assert_eq!(entries, [(0, 2), (2, 0), (2, 0), (2, 1)]);
3453        assert_eq!(child.form(), Form::Struct);
3454        assert_eq!(
3455            child.logical_type(),
3456            &LogicalType::Struct(vec![
3457                Field::new(MAP_KEY, LogicalType::Varchar),
3458                Field::new(MAP_VALUE, LogicalType::Varchar),
3459            ])
3460        );
3461        // And the accessor that reaches through it hands back the two columns rather than the struct.
3462        let (entries, keys, values) = column.map_parts().expect("a map");
3463        assert_eq!(entries.len(), 4);
3464        assert_eq!(keys.text_at(0), Some("a"));
3465        assert_eq!(values.text_at(0), Some("b"));
3466        assert_eq!(column.iter().collect::<Vec<_>>(), rows);
3467    }
3468
3469    /// The same distinction a list has, checked again here rather than assumed from the composition,
3470    /// because the empty map is the one every catalog table in D2 is full of and a null map is what a
3471    /// column with no tags at all would be.
3472    #[test]
3473    fn an_empty_map_and_a_null_map_are_different_rows() {
3474        let column = tag_column(&[tags(&[]), Value::Null]);
3475        assert!(!column.is_null_at(0), "an empty map is a row that is there");
3476        assert!(column.is_null_at(1));
3477        assert_eq!(column.value_at(0), tags(&[]));
3478        assert_eq!(column.value_at(1), Value::Null);
3479        assert_eq!(column.value_at(0).to_string(), "{}");
3480        assert_eq!(column.value_at(1).to_string(), "NULL");
3481    }
3482
3483    /// A map prints `{a=b}` and a struct prints `{'a': b}`, both measured off the pin. They share a
3484    /// layout and they cannot share a printer, which is the one thing about this composition that does
3485    /// not fall out of it.
3486    #[test]
3487    fn a_map_prints_with_equals_signs_and_a_struct_prints_with_quoted_names() {
3488        assert_eq!(tags(&[("a", "b"), ("c", "d")]).to_string(), "{a=b, c=d}");
3489        assert_eq!(pair(1, "x").to_string(), "{'a': 1, 'b': x}");
3490        let numbers = Value::map(
3491            LogicalType::Integer,
3492            LogicalType::Integer,
3493            vec![(Value::Integer(1), Value::Integer(3)), (Value::Integer(2), Value::Integer(4))],
3494        );
3495        assert_eq!(numbers.to_string(), "{1=3, 2=4}");
3496        let null_value = Value::map(
3497            LogicalType::Varchar,
3498            LogicalType::Varchar,
3499            vec![(Value::Varchar("x".to_string()), Value::Null)],
3500        );
3501        assert_eq!(null_value.to_string(), "{x=NULL}");
3502    }
3503
3504    /// A map inherits the list's cut and the list's gather, which is the payoff for storing it as one.
3505    /// Neither of these is code written for maps and both of them are worth a test that says the
3506    /// inheritance works, since the type is rewritten on the way through and a form that came back as a
3507    /// list would still read.
3508    #[test]
3509    fn cutting_and_gathering_a_map_keeps_it_a_map() {
3510        let rows: Vec<Value> =
3511            (0..16).map(|row| tags(&[("k", if row % 2 == 0 { "e" } else { "o" })])).collect();
3512        let column = tag_column(&rows);
3513
3514        let cut = column.slice(4, 3).unwrap();
3515        assert!(matches!(cut.logical_type(), LogicalType::Map(_, _)), "still a map after a cut");
3516        assert_eq!(cut.iter().collect::<Vec<_>>(), rows[4..7]);
3517        // The child was not cut, the same as for a list, which is what makes the cut eight bytes a row.
3518        assert_eq!(cut.map_parts().expect("a map").1.len(), 16);
3519
3520        let picked = column.gather(&[3, 0, 3]).unwrap();
3521        assert!(matches!(picked.logical_type(), LogicalType::Map(_, _)));
3522        assert_eq!(
3523            picked.iter().collect::<Vec<_>>(),
3524            [rows[3].clone(), rows[0].clone(), rows[3].clone()]
3525        );
3526        let past = column.gather(&[0, 99]).unwrap();
3527        assert_eq!(past.value_at(1), Value::Null);
3528    }
3529
3530    #[test]
3531    fn a_map_built_from_two_columns_pairs_them_by_position() {
3532        let keys = Vector::from_values(
3533            LogicalType::Varchar,
3534            &[Value::Varchar("a".to_string()), Value::Varchar("c".to_string())],
3535        )
3536        .unwrap();
3537        let values = Vector::from_values(
3538            LogicalType::Varchar,
3539            &[Value::Varchar("b".to_string()), Value::Varchar("d".to_string())],
3540        )
3541        .unwrap();
3542        let column = Vector::map(vec![(0, 2), (2, 0)], keys, values).expect("two rows");
3543        assert_eq!(column.len(), 2);
3544        assert_eq!(
3545            column.logical_type(),
3546            &LogicalType::map(LogicalType::Varchar, LogicalType::Varchar)
3547        );
3548        assert_eq!(column.value_at(0), tags(&[("a", "b"), ("c", "d")]));
3549        assert_eq!(column.value_at(1), tags(&[]));
3550        // The entry check the list constructor does is the one a map gets, so an entry past the end of
3551        // the pair of columns is refused here too rather than read as somebody else's keys.
3552        let short =
3553            Vector::from_values(LogicalType::Varchar, &[Value::Varchar("a".to_string())]).unwrap();
3554        let other =
3555            Vector::from_values(LogicalType::Varchar, &[Value::Varchar("b".to_string())]).unwrap();
3556        assert!(Vector::map(vec![(0, 9)], short, other).is_err(), "an entry past the end");
3557    }
3558
3559    /// `map_parts` is about the logical type and `list_parts` is about the layout, so a list has to
3560    /// decline the first and a map has to answer the second. Getting that backwards would let a kernel
3561    /// written for maps read a list of two field structs as if it were one.
3562    #[test]
3563    fn a_list_is_not_a_map_however_much_its_child_looks_like_one() {
3564        let pairs = Value::List { element: pair_type(), values: vec![pair(1, "x")] };
3565        let column =
3566            Vector::from_values(LogicalType::list(pair_type()), std::slice::from_ref(&pairs))
3567                .unwrap();
3568        assert!(column.map_parts().is_none(), "a list of structs is a list");
3569        assert!(column.list_parts().is_some());
3570        let map = tag_column(&[tags(&[("a", "b")])]);
3571        assert!(map.map_parts().is_some());
3572        assert!(map.list_parts().is_some(), "a map has a list's layout and says so");
3573    }
3574
3575    /// A struct row is not bytes and not an integer, and it stays that way when it has exactly one
3576    /// integer field, which is the case where answering about the field would look reasonable and would
3577    /// be a hash keyed on the wrong thing.
3578    #[test]
3579    fn the_scalar_readers_decline_a_struct_of_one_integer_field() {
3580        let ty = LogicalType::Struct(vec![Field::new("a", LogicalType::Integer)]);
3581        let row = Value::Struct(vec![("a".to_string(), Value::Integer(7))]);
3582        let column = Vector::from_values(ty, &[row]).unwrap();
3583        assert_eq!(column.signed_at(0), None);
3584        assert_eq!(column.bytes_at(0), None);
3585        assert_eq!(column.data(), None);
3586    }
3587
3588    #[test]
3589    fn a_clustered_column_becomes_runs_and_reads_back_the_same() {
3590        let mut values = Vec::new();
3591        for (value, times) in [(7, 400), (8, 300), (7, 324)] {
3592            values.extend(std::iter::repeat_n(value, times));
3593        }
3594        let flat = integers(&values);
3595        let runs = flat.run_encoded().unwrap();
3596        assert_eq!(runs.form(), Form::Rle);
3597        assert_eq!(runs.run_parts().expect("runs").0, [400, 700, 1024]);
3598        assert_eq!(runs.len(), flat.len());
3599        assert_eq!(runs.iter().collect::<Vec<_>>(), flat.iter().collect::<Vec<_>>());
3600        assert!(
3601            runs.footprint() * 10 < flat.footprint(),
3602            "three runs against a thousand rows: {} against {}",
3603            runs.footprint(),
3604            flat.footprint()
3605        );
3606    }
3607
3608    /// The check is worth having in both directions. A form that is only ever bigger than what it
3609    /// replaced is a form that costs a pass over the column to decide not to use.
3610    #[test]
3611    fn a_column_that_does_not_repeat_is_left_flat() {
3612        let flat = integers(&(0..1024).collect::<Vec<i32>>());
3613        assert_eq!(flat.run_encoded().unwrap().form(), Form::Flat);
3614        // Two runs over four rows is exactly break even on a four byte column, and break even is
3615        // not a reason to change form.
3616        assert_eq!(integers(&[1, 1, 2, 2]).run_encoded().unwrap().form(), Form::Flat);
3617        assert_eq!(integers(&[1, 1, 1, 2, 2]).run_encoded().unwrap().form(), Form::Rle);
3618    }
3619
3620    #[test]
3621    fn two_nulls_beside_each_other_are_one_run_and_a_null_between_two_equals_is_a_break() {
3622        let mut values = vec![Value::Integer(4), Value::Integer(4)];
3623        values.extend([Value::Null, Value::Null, Value::Null]);
3624        values.extend(std::iter::repeat_n(Value::Integer(4), 5));
3625        let flat = Vector::from_values(LogicalType::Integer, &values).unwrap();
3626        let runs = flat.run_encoded().unwrap();
3627        assert_eq!(runs.run_parts().expect("runs").0, [2, 5, 10]);
3628        assert_eq!(runs.iter().collect::<Vec<_>>(), values);
3629    }
3630
3631    #[test]
3632    fn slicing_runs_keeps_them_runs_and_cuts_the_first_and_last_one_back() {
3633        let flat = integers(&[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]);
3634        let runs = flat.run_encoded().unwrap();
3635        let piece = runs.slice(3, 6).unwrap();
3636        assert_eq!(piece.form(), Form::Rle, "the form is the whole point");
3637        assert_eq!(piece.run_parts().expect("runs").0, [1, 5, 6]);
3638        assert_eq!(
3639            piece.iter().collect::<Vec<_>>(),
3640            flat.slice(3, 6).unwrap().iter().collect::<Vec<_>>()
3641        );
3642        assert_eq!(runs.slice(0, 0).unwrap().len(), 0);
3643        assert_eq!(runs.slice(0, 12).unwrap().form(), Form::Rle);
3644    }
3645
3646    #[test]
3647    fn gathering_out_of_runs_walks_to_the_values_the_way_it_walks_a_dictionary() {
3648        let mut values = vec![Value::Varchar("red".into()); 4];
3649        values.extend([Value::Null, Value::Null, Value::Null]);
3650        values.extend(vec![Value::Varchar("blue".into()); 4]);
3651        let runs =
3652            Vector::from_values(LogicalType::Varchar, &values).unwrap().run_encoded().unwrap();
3653        assert_eq!(runs.form(), Form::Rle);
3654        let picked = runs.gather(&[8, 0, 5, 2]).unwrap();
3655        assert_eq!(picked.form(), Form::Flat, "a gather copies, whatever it gathered from");
3656        assert_eq!(
3657            picked.iter().collect::<Vec<_>>(),
3658            [values[8].clone(), values[0].clone(), Value::Null, values[2].clone()]
3659        );
3660        assert_eq!(runs.text_at(1), Some("red"));
3661        assert_eq!(runs.text_at(5), None, "a null has no text");
3662        assert_eq!(runs.flatten().unwrap().iter().collect::<Vec<_>>(), values);
3663    }
3664
3665    /// A run length vector over a run length vector turns one search per row into two, and there is
3666    /// nothing in the engine that builds one, so it is refused rather than composed.
3667    #[test]
3668    fn runs_of_runs_are_refused_and_runs_of_a_dictionary_are_not() {
3669        let inner = integers(&[1, 1, 1, 1, 2]).run_encoded().unwrap();
3670        assert_eq!(inner.form(), Form::Rle);
3671        let error = Vector::runs(vec![2, 8], inner).unwrap_err();
3672        assert!(error.to_string().contains("runs of runs"), "{error}");
3673
3674        let words = Vector::from_values(
3675            LogicalType::Varchar,
3676            &[Value::Varchar("red".into()), Value::Varchar("blue".into())],
3677        )
3678        .unwrap();
3679        let dictionary = Vector::dictionary(vec![1, 0], words).unwrap();
3680        let stacked = Vector::runs(vec![4, 9], dictionary).unwrap();
3681        assert_eq!(stacked.len(), 9);
3682        assert_eq!(stacked.value_at(3), Value::Varchar("blue".into()));
3683        assert_eq!(stacked.value_at(4), Value::Varchar("red".into()));
3684    }
3685
3686    #[test]
3687    fn run_ends_have_to_increase_and_there_is_one_value_for_each_of_them() {
3688        let values = integers(&[1, 2]);
3689        assert!(Vector::runs(vec![4], values.clone()).is_err(), "two values and one run");
3690        assert!(Vector::runs(vec![4, 4], values.clone()).is_err(), "an end that repeats");
3691        assert!(Vector::runs(vec![4, 2], values.clone()).is_err(), "an end that goes backwards");
3692        assert!(Vector::runs(vec![0, 2], values.clone()).is_err(), "a first run holding no rows");
3693        assert_eq!(Vector::runs(vec![4, 9], values).unwrap().len(), 9);
3694    }
3695
3696    #[test]
3697    fn a_form_that_is_already_compact_is_left_where_it_is() {
3698        let constant = Vector::constant(LogicalType::Integer, Value::Integer(1), 1000);
3699        assert_eq!(constant.run_encoded().unwrap().form(), Form::Constant);
3700        assert_eq!(Vector::sequence(0, 1, 1000).run_encoded().unwrap().form(), Form::Sequence);
3701    }
3702
3703    /// What makes one accessor cover both forms. A dictionary hands back the codes it stores and a
3704    /// run length vector works the same numbers out, and a kernel writing `values[at[row]]` reads
3705    /// the same rows out of either.
3706    #[test]
3707    fn both_forms_that_point_somewhere_hand_back_a_position_per_row() {
3708        let words = Vector::from_values(
3709            LogicalType::Varchar,
3710            &[Value::Varchar("red".into()), Value::Varchar("blue".into())],
3711        )
3712        .unwrap();
3713        let runs = Vector::runs(vec![3, 5], words.clone()).unwrap();
3714        let (at, values) = runs.positions().expect("runs point somewhere");
3715        assert_eq!(at.as_ref(), [0, 0, 0, 1, 1]);
3716        assert_eq!(values.value_at(at[3] as usize), runs.value_at(3));
3717
3718        let dictionary = Vector::dictionary(vec![1, 0, 1], words).unwrap();
3719        let (at, values) = dictionary.positions().expect("a dictionary points somewhere");
3720        assert_eq!(at.as_ref(), [1, 0, 1]);
3721        assert_eq!(values.value_at(at[0] as usize), dictionary.value_at(0));
3722
3723        assert!(integers(&[1, 2, 3]).positions().is_none(), "a flat vector points at itself");
3724        assert!(Vector::sequence(0, 1, 4).positions().is_none(), "a sequence stores nothing");
3725    }
3726
3727    #[test]
3728    fn slicing_a_dictionary_keeps_it_a_dictionary_where_gathering_would_not() {
3729        let values = Vector::from_values(
3730            LogicalType::Varchar,
3731            &[Value::Varchar("red".into()), Value::Varchar("blue".into())],
3732        )
3733        .unwrap();
3734        let vector = Vector::dictionary(vec![0, 1, 1, 0, 1], values).unwrap();
3735
3736        let piece = vector.slice(1, 3).unwrap();
3737        assert_eq!(piece.form(), Form::Dictionary, "the form is the whole point");
3738        assert_eq!(piece.len(), 3);
3739        assert_eq!(
3740            piece.iter().collect::<Vec<_>>(),
3741            [
3742                Value::Varchar("blue".into()),
3743                Value::Varchar("blue".into()),
3744                Value::Varchar("red".into())
3745            ]
3746        );
3747        assert_eq!(vector.gather(&[1, 2, 3]).unwrap().form(), Form::Flat, "which a gather loses");
3748    }
3749
3750    #[test]
3751    fn slicing_a_dictionary_shares_the_dictionary_rather_than_copying_it() {
3752        // The assertion is about the address and not about the values, because the values were
3753        // right when the dictionary was copied too. A page holds one dictionary and is cut into a
3754        // chunk of codes at a time, so copying the dictionary here is a copy of every string in it
3755        // per chunk, and on a read of a ClickBench partition it was ten percent of the cycles.
3756        let values = Vector::from_values(
3757            LogicalType::Varchar,
3758            &[Value::Varchar("red".into()), Value::Varchar("blue".into())],
3759        )
3760        .unwrap();
3761        let vector = Vector::dictionary(vec![0, 1, 1, 0, 1], values).unwrap();
3762        let Body::Dictionary { values: whole, .. } = &vector.body else {
3763            panic!("a dictionary vector holds a dictionary");
3764        };
3765
3766        let piece = vector.slice(1, 3).unwrap();
3767        let Body::Dictionary { codes, values: cut, .. } = &piece.body else {
3768            panic!("a slice of a dictionary is a dictionary");
3769        };
3770        assert!(Arc::ptr_eq(whole, cut), "the cut copied the dictionary");
3771        assert_eq!(codes, &[1, 1, 0], "the codes are the part that is cut");
3772
3773        // And a cut of a cut shares it too, since that is what a scan does to a page it reads twice.
3774        let again = piece.slice(1, 2).unwrap();
3775        let Body::Dictionary { values: cut, .. } = &again.body else {
3776            panic!("a slice of a slice of a dictionary is a dictionary");
3777        };
3778        assert!(Arc::ptr_eq(whole, cut), "the second cut copied the dictionary");
3779        assert_eq!(
3780            again.iter().collect::<Vec<_>>(),
3781            [Value::Varchar("blue".into()), Value::Varchar("red".into())]
3782        );
3783    }
3784
3785    #[test]
3786    fn a_slice_carries_the_nulls_that_were_in_its_range_and_not_the_others() {
3787        let vector =
3788            integers(&[1, 2, 3, 4]).with_validity(Validity::from_run(&[false, true, false, true]));
3789        let piece = vector.slice(1, 2).unwrap();
3790        assert!(piece.validity().is_valid(0));
3791        assert!(!piece.validity().is_valid(1));
3792        assert_eq!(piece.value_at(1), Value::Null);
3793    }
3794
3795    #[test]
3796    fn slicing_a_sequence_moves_its_start_rather_than_writing_the_values_out() {
3797        let vector = Vector::sequence(100, 5, 10);
3798        let piece = vector.slice(3, 4).unwrap();
3799        assert_eq!(piece.form(), Form::Sequence);
3800        assert_eq!(
3801            piece.iter().collect::<Vec<_>>(),
3802            [Value::BigInt(115), Value::BigInt(120), Value::BigInt(125), Value::BigInt(130)]
3803        );
3804    }
3805
3806    #[test]
3807    fn slicing_a_constant_is_a_shorter_constant() {
3808        let vector = Vector::constant(LogicalType::Integer, Value::Integer(9), 8);
3809        let piece = vector.slice(2, 3).unwrap();
3810        assert_eq!(piece.form(), Form::Constant);
3811        assert_eq!(piece.len(), 3);
3812        assert_eq!(piece.value_at(2), Value::Integer(9));
3813    }
3814
3815    #[test]
3816    fn slicing_the_whole_vector_hands_it_back_as_it_was() {
3817        let vector = integers(&[1, 2, 3]);
3818        assert_eq!(
3819            vector.slice(0, 3).unwrap().iter().collect::<Vec<_>>(),
3820            [Value::Integer(1), Value::Integer(2), Value::Integer(3)]
3821        );
3822    }
3823
3824    #[test]
3825    fn cutting_a_flat_body_answers_what_gathering_the_same_rows_answers() {
3826        // The cut of a flat body used to be written as a gather over the positions in the range,
3827        // and it is now a run copied out, so the two have to keep saying the same thing. Every
3828        // start and every length, with nulls in the range and out of it, since the validity is the
3829        // half of this that changed shape.
3830        let rows: Vec<i32> = (0..70).collect();
3831        let valid: Vec<bool> = (0..70).map(|row| row % 7 != 0 && row % 11 != 3).collect();
3832        let vector = integers(&rows).with_validity(Validity::from_run(&valid));
3833        for at in 0..70usize {
3834            for len in 0..=(70 - at) {
3835                let cut = vector.slice(at, len).unwrap();
3836                let positions: Vec<u32> = (at..at + len).map(|row| row as u32).collect();
3837                let gathered = vector.gather(&positions).unwrap();
3838                assert_eq!(cut.len(), len, "rows {at} to {}", at + len);
3839                assert_eq!(
3840                    cut.iter().collect::<Vec<_>>(),
3841                    gathered.iter().collect::<Vec<_>>(),
3842                    "rows {at} to {}",
3843                    at + len
3844                );
3845            }
3846        }
3847    }
3848
3849    #[test]
3850    fn cutting_a_flat_string_column_answers_what_gathering_it_answers() {
3851        // The string layout is the one whose cut is still a loop, and it is also the one where a
3852        // row is a view into an arena rather than a slot, so it gets the same treatment separately.
3853        // Both inline and out of line strings, since they are copied by different paths.
3854        let rows: Vec<String> =
3855            (0..40).map(|row| "x".repeat(row % 30) + &row.to_string()).collect();
3856        let values: Vec<Value> = rows.iter().map(|row| Value::Varchar(row.clone())).collect();
3857        let vector = Vector::from_values(LogicalType::Varchar, &values).unwrap().flatten().unwrap();
3858        assert_eq!(vector.form(), Form::Flat, "the cut under test is the flat one");
3859        for at in 0..40usize {
3860            for len in 0..=(40 - at) {
3861                let cut = vector.slice(at, len).unwrap();
3862                let positions: Vec<u32> = (at..at + len).map(|row| row as u32).collect();
3863                let gathered = vector.gather(&positions).unwrap();
3864                assert_eq!(
3865                    cut.iter().collect::<Vec<_>>(),
3866                    gathered.iter().collect::<Vec<_>>(),
3867                    "rows {at} to {}",
3868                    at + len
3869                );
3870            }
3871        }
3872    }
3873
3874    #[test]
3875    fn a_slice_past_the_end_is_an_error_rather_than_a_short_vector() {
3876        let error = integers(&[1, 2, 3]).slice(2, 2).unwrap_err();
3877        assert!(error.to_string().contains("of a vector of 3"), "{error}");
3878    }
3879
3880    #[test]
3881    fn the_vector_size_is_the_one_the_design_is_built_around() {
3882        // 1024 and not DuckDB's 2048. A validity mask is 16 u64 words and a vector of string views
3883        // is 16 KiB, both of which are consequences of this number rather than coincidences.
3884        assert_eq!(VECTOR_SIZE, 1024);
3885        assert_eq!(VECTOR_SIZE / 64, 16);
3886    }
3887
3888    #[test]
3889    fn a_flat_vector_reads_back_what_was_put_in_it() {
3890        let vector = integers(&[1, 2, 3]);
3891        assert_eq!(vector.form(), Form::Flat);
3892        assert_eq!(vector.len(), 3);
3893        assert_eq!(vector.value_at(1), Value::Integer(2));
3894        assert_eq!(
3895            vector.iter().collect::<Vec<_>>(),
3896            vec![Value::Integer(1), Value::Integer(2), Value::Integer(3)]
3897        );
3898    }
3899
3900    #[test]
3901    fn a_vector_built_from_values_reads_the_same_values_back() {
3902        let vector = Vector::from_values(
3903            LogicalType::Varchar,
3904            &[
3905                Value::Varchar("a".to_string()),
3906                Value::Null,
3907                Value::Varchar("a string too long to sit inside a view".to_string()),
3908            ],
3909        )
3910        .expect("strings and a null");
3911        assert_eq!(vector.len(), 3);
3912        assert_eq!(vector.value_at(0), Value::Varchar("a".to_string()));
3913        assert_eq!(vector.value_at(1), Value::Null);
3914        assert_eq!(
3915            vector.value_at(2),
3916            Value::Varchar("a string too long to sit inside a view".to_string())
3917        );
3918    }
3919
3920    /// A null still occupies a position. If it did not then every value after it would read back
3921    /// one place to the left, which is the kind of bug that looks like a storage bug for a week.
3922    #[test]
3923    fn a_null_in_the_middle_does_not_move_the_values_after_it() {
3924        let vector = Vector::from_values(
3925            LogicalType::Integer,
3926            &[Value::Integer(1), Value::Null, Value::Integer(3)],
3927        )
3928        .expect("integers and a null");
3929        assert_eq!(vector.value_at(2), Value::Integer(3));
3930        assert!(vector.validity().has_nulls(3), "the middle one is null");
3931    }
3932
3933    #[test]
3934    fn a_value_the_type_cannot_hold_is_refused() {
3935        let wrong = Vector::from_values(LogicalType::Integer, &[Value::Varchar("x".to_string())]);
3936        assert!(wrong.is_err(), "a string is not an integer");
3937    }
3938
3939    #[test]
3940    fn a_type_that_does_not_match_its_layout_is_refused_at_construction() {
3941        // One comparison here against a wrong answer read out three layers later.
3942        let wrong = Vector::flat(LogicalType::Varchar, Data::Int32(vec![1].into()));
3943        assert!(wrong.is_err());
3944        let right = Vector::flat(LogicalType::Date, Data::Int32(vec![1].into()));
3945        assert!(right.is_ok(), "a date is stored in an i32 and that has to be allowed");
3946    }
3947
3948    #[test]
3949    fn a_constant_vector_costs_one_value_whatever_its_length() {
3950        let vector = Vector::constant(LogicalType::Integer, Value::Integer(7), VECTOR_SIZE);
3951        assert_eq!(vector.form(), Form::Constant);
3952        assert_eq!(vector.len(), VECTOR_SIZE);
3953        assert_eq!(vector.value_at(0), Value::Integer(7));
3954        assert_eq!(vector.value_at(VECTOR_SIZE - 1), Value::Integer(7));
3955        assert_eq!(vector.value_at(VECTOR_SIZE), Value::Null, "past the end is null, not a panic");
3956    }
3957
3958    #[test]
3959    fn a_constant_null_is_all_invalid_without_being_told() {
3960        let vector = Vector::constant(LogicalType::Integer, Value::Null, 8);
3961        assert_eq!(vector.validity(), &Validity::AllInvalid);
3962        assert_eq!(vector.value_at(3), Value::Null);
3963    }
3964
3965    #[test]
3966    fn a_sequence_vector_is_sixteen_bytes_of_row_identifiers() {
3967        let vector = Vector::sequence(100, 1, VECTOR_SIZE);
3968        assert_eq!(vector.form(), Form::Sequence);
3969        assert_eq!(vector.value_at(0), Value::BigInt(100));
3970        assert_eq!(vector.value_at(923), Value::BigInt(1023));
3971        let stepped = Vector::sequence(0, 5, 4);
3972        assert_eq!(
3973            stepped.iter().collect::<Vec<_>>(),
3974            vec![Value::BigInt(0), Value::BigInt(5), Value::BigInt(10), Value::BigInt(15)]
3975        );
3976    }
3977
3978    #[test]
3979    fn a_dictionary_vector_reads_through_its_codes() {
3980        let mut column = StringColumn::new();
3981        column.push("red");
3982        column.push("green");
3983        let values = Vector::flat(LogicalType::Varchar, Data::Varlen(column)).unwrap();
3984        let vector = Vector::dictionary(vec![0, 1, 1, 0], values).unwrap();
3985        assert_eq!(vector.form(), Form::Dictionary);
3986        assert_eq!(vector.logical_type(), &LogicalType::Varchar);
3987        assert_eq!(vector.value_at(2), Value::Varchar("green".into()));
3988        assert_eq!(vector.len(), 4);
3989    }
3990
3991    /// The accessor a group by keys a string column through, which has to agree with `value_at` on
3992    /// every position or two rows holding one string end up in two groups.
3993    #[test]
3994    fn text_is_read_where_it_already_is_for_the_forms_that_store_it() {
3995        let mut column = StringColumn::new();
3996        column.push("red");
3997        column.push("green");
3998        column.push("");
3999        let flat = Vector::flat(LogicalType::Varchar, Data::Varlen(column)).unwrap();
4000        for index in 0..flat.len() {
4001            assert_eq!(flat.text_at(index).map(str::to_string), text_of(&flat.value_at(index)));
4002        }
4003        let dictionary = Vector::dictionary(vec![1, 0, 1, 2], flat).unwrap();
4004        for index in 0..dictionary.len() {
4005            assert_eq!(
4006                dictionary.text_at(index).map(str::to_string),
4007                text_of(&dictionary.value_at(index))
4008            );
4009        }
4010        assert_eq!(dictionary.text_at(4), None, "past the end");
4011    }
4012
4013    /// The forms and types that have no text to hand back, which a caller answers by falling back
4014    /// to `value_at`. A blob is the one that would be a correctness bug rather than a slow path,
4015    /// since its bytes are not required to be text and it is not a `VARCHAR` either way.
4016    #[test]
4017    fn text_is_refused_where_it_is_not_stored_as_itself() {
4018        let nulls =
4019            Vector::from_values(LogicalType::Varchar, &[Value::Varchar("red".into()), Value::Null])
4020                .unwrap();
4021        assert_eq!(nulls.text_at(0), Some("red"));
4022        assert_eq!(nulls.text_at(1), None, "a null has no text");
4023        let constant = Vector::constant(LogicalType::Varchar, Value::Varchar("red".into()), 3);
4024        assert_eq!(constant.text_at(0), None, "a constant is not stored per position");
4025        assert_eq!(integers(&[1, 2]).text_at(0), None, "an integer is not text");
4026        let mut bytes = StringColumn::new();
4027        bytes.push("red");
4028        let blob = Vector::flat(LogicalType::Blob, Data::Varlen(bytes)).unwrap();
4029        assert_eq!(blob.text_at(0), None, "a blob is not a varchar");
4030    }
4031
4032    /// The accessor a group by keys an integer column through, which has to agree with `value_at`
4033    /// on every position or two rows holding one number end up in two groups.
4034    #[test]
4035    fn a_signed_integer_is_read_where_it_already_is_for_the_forms_that_store_it() {
4036        let flat = integers(&[7, -3, 0, 2]);
4037        for index in 0..flat.len() {
4038            assert_eq!(flat.signed_at(index), signed_of(&flat.value_at(index)), "flat {index}");
4039        }
4040        let dictionary = Vector::dictionary(vec![1, 0, 3, 2], flat).unwrap();
4041        for index in 0..dictionary.len() {
4042            assert_eq!(
4043                dictionary.signed_at(index),
4044                signed_of(&dictionary.value_at(index)),
4045                "dictionary {index}"
4046            );
4047        }
4048        assert_eq!(dictionary.signed_at(4), None, "past the end");
4049
4050        let runs = Vector::runs(vec![2, 5], integers(&[4, 9])).unwrap();
4051        for index in 0..runs.len() {
4052            assert_eq!(runs.signed_at(index), signed_of(&runs.value_at(index)), "run {index}");
4053        }
4054        let constant = Vector::constant(LogicalType::BigInt, Value::BigInt(11), 3);
4055        assert_eq!(constant.signed_at(2), Some(11));
4056        let sequence = Vector::sequence(100, 5, 4);
4057        for index in 0..sequence.len() {
4058            assert_eq!(
4059                sequence.signed_at(index),
4060                signed_of(&sequence.value_at(index)),
4061                "sequence {index}"
4062            );
4063        }
4064    }
4065
4066    /// The forms and types that have no integer to hand back, which a caller answers by falling
4067    /// back to `value_at`.
4068    #[test]
4069    fn a_signed_integer_is_refused_where_it_is_not_stored_as_itself() {
4070        let nulls =
4071            Vector::from_values(LogicalType::BigInt, &[Value::BigInt(4), Value::Null]).unwrap();
4072        assert_eq!(nulls.signed_at(0), Some(4));
4073        assert_eq!(nulls.signed_at(1), None, "a null is not a number");
4074        let packed = integers(&[1, 2, 3, 1]).bit_packed().unwrap();
4075        assert_eq!(packed.signed_at(0), Some(1), "a packed integer is read in code space");
4076        let mut bytes = StringColumn::new();
4077        bytes.push("red");
4078        let text = Vector::flat(LogicalType::Varchar, Data::Varlen(bytes)).unwrap();
4079        assert_eq!(text.signed_at(0), None, "a string is not a number");
4080        let double = Vector::flat(LogicalType::Double, Data::Float64(vec![1.5].into())).unwrap();
4081        assert_eq!(double.signed_at(0), None, "a double is not a signed integer");
4082    }
4083
4084    /// The integer of a value, for comparing `signed_at` against `value_at` position by position.
4085    fn signed_of(value: &Value) -> Option<i128> {
4086        match value {
4087            Value::TinyInt(x) => Some(i128::from(*x)),
4088            Value::SmallInt(x) => Some(i128::from(*x)),
4089            Value::Integer(x) | Value::Date(x) => Some(i128::from(*x)),
4090            Value::BigInt(x) | Value::Time(x) | Value::Timestamp(x) => Some(i128::from(*x)),
4091            Value::HugeInt(x) | Value::Decimal { unscaled: x, .. } => Some(*x),
4092            _ => None,
4093        }
4094    }
4095
4096    /// The text of a value, for comparing `text_at` against `value_at` position by position.
4097    fn text_of(value: &Value) -> Option<String> {
4098        match value {
4099            Value::Varchar(text) => Some(text.clone()),
4100            _ => None,
4101        }
4102    }
4103
4104    #[test]
4105    fn a_dictionary_code_past_the_end_is_refused() {
4106        // The alternative is a silent read of the wrong value, which is the failure mode the
4107        // entire M3 design has to be careful about.
4108        let values = integers(&[1, 2]);
4109        assert!(Vector::dictionary(vec![0, 2], values).is_err());
4110        // The check runs on the highest code rather than the first bad one, so it has to say that
4111        // no codes at all is fine even when there are no values for them to point at either.
4112        let empty = Vector::dictionary(Vec::new(), integers(&[])).expect("no codes, no values");
4113        assert_eq!(empty.len(), 0);
4114        // And a code of zero against an empty dictionary is still past the end.
4115        assert!(Vector::dictionary(vec![0], integers(&[])).is_err());
4116    }
4117
4118    #[test]
4119    fn every_form_flattens_to_the_same_values_it_reads_out() {
4120        // This is the shape of the equivalence testing in spec/16-testing.md section 16.2, in
4121        // miniature and long before there is an encoded kernel to point it at. A form that reads
4122        // out one way and flattens another is the exact bug that testing exists to catch.
4123        let mut column = StringColumn::new();
4124        column.push("alpha");
4125        column.push("beta");
4126        let dictionary = Vector::dictionary(
4127            vec![1, 0, 1],
4128            Vector::flat(LogicalType::Varchar, Data::Varlen(column)).unwrap(),
4129        )
4130        .unwrap();
4131        let cases = [
4132            Vector::constant(LogicalType::Integer, Value::Integer(3), 5),
4133            Vector::sequence(7, -2, 5),
4134            dictionary,
4135        ];
4136        for vector in cases {
4137            let flat = vector.flatten().unwrap();
4138            assert_eq!(flat.form(), Form::Flat);
4139            assert_eq!(flat.len(), vector.len());
4140            for index in 0..vector.len() {
4141                assert_eq!(flat.value_at(index), vector.value_at(index), "at {index}");
4142            }
4143        }
4144    }
4145
4146    #[test]
4147    fn a_null_still_occupies_a_position_after_flattening() {
4148        // The reason push_value writes a zero for a null rather than skipping it. A run of data
4149        // with a hole in it puts every value after the hole in the wrong place, and the validity
4150        // mask is what says the position is null.
4151        let vector = Vector::sequence(0, 1, 4).with_validity(Validity::from_iter(4, |i| i != 1));
4152        let flat = vector.flatten().unwrap();
4153        assert_eq!(flat.value_at(0), Value::BigInt(0));
4154        assert_eq!(flat.value_at(1), Value::Null);
4155        assert_eq!(flat.value_at(2), Value::BigInt(2));
4156        assert_eq!(flat.value_at(3), Value::BigInt(3));
4157    }
4158
4159    /// A dictionary holds its nulls in the vector it points at, so its own validity is all valid
4160    /// and reading that instead of the values turns a null into whatever zero means for the type.
4161    /// A filter over a nullable column produces exactly this vector, so the bug reaches a result
4162    /// set as `LEFT JOIN` padding that comes back as zeros.
4163    #[test]
4164    fn a_null_behind_a_dictionary_survives_flattening() {
4165        let values =
4166            Vector::from_values(LogicalType::Integer, &[Value::Integer(3), Value::Null]).unwrap();
4167        let dictionary = Vector::dictionary(vec![1, 0, 1], values).unwrap();
4168        let flat = dictionary.flatten().unwrap();
4169        assert_eq!(flat.value_at(0), Value::Null);
4170        assert_eq!(flat.value_at(1), Value::Integer(3));
4171        assert_eq!(flat.value_at(2), Value::Null);
4172    }
4173
4174    /// The property that makes `gather` usable at all: it has to be the same function as reading the
4175    /// wanted positions one at a time, over every form, or compaction changes answers.
4176    #[test]
4177    fn gathering_reads_what_reading_one_position_at_a_time_reads() {
4178        let mut column = StringColumn::new();
4179        column.push("alpha");
4180        column.push("beta");
4181        column.push("gamma");
4182        let cases = [
4183            integers(&[10, 20, 30, 40]),
4184            integers(&[10, 20, 30, 40]).with_validity(Validity::from_iter(4, |i| i != 2)),
4185            Vector::constant(LogicalType::Integer, Value::Integer(9), 4),
4186            Vector::sequence(100, -7, 4),
4187            Vector::sequence(100, -7, 4).with_validity(Validity::from_iter(4, |i| i % 2 == 0)),
4188            Vector::dictionary(
4189                vec![2, 0, 1, 2],
4190                Vector::flat(LogicalType::Varchar, Data::Varlen(column)).unwrap(),
4191            )
4192            .unwrap(),
4193            Vector::dictionary(
4194                vec![1, 0, 1, 0],
4195                Vector::from_values(LogicalType::Integer, &[Value::Integer(5), Value::Null])
4196                    .unwrap(),
4197            )
4198            .unwrap(),
4199        ];
4200        let wanted = [3_u32, 0, 2, 2, 1];
4201        for vector in cases {
4202            let gathered = vector.gather(&wanted).unwrap();
4203            assert_eq!(gathered.len(), wanted.len());
4204            assert_eq!(gathered.logical_type(), vector.logical_type());
4205            for (slot, &index) in wanted.iter().enumerate() {
4206                assert_eq!(
4207                    gathered.value_at(slot),
4208                    vector.value_at(index as usize),
4209                    "slot {slot} of {:?}",
4210                    vector.form()
4211                );
4212            }
4213        }
4214    }
4215
4216    /// A gather past the end is not an error, because the selection that produced the indices is
4217    /// checked by its caller and the one thing that must not happen here is a read of the wrong
4218    /// value. An index nothing answers is null, which is what an outer join pad needs anyway.
4219    #[test]
4220    fn gathering_a_position_that_is_not_there_is_a_null_and_not_a_wrong_value() {
4221        let vector = integers(&[1, 2, 3]);
4222        let gathered = vector.gather(&[2, 9]).unwrap();
4223        assert_eq!(gathered.value_at(0), Value::Integer(3));
4224        assert_eq!(gathered.value_at(1), Value::Null);
4225    }
4226
4227    /// The vector with nothing in it at all, which is what an untyped `NULL` is stored as. Every
4228    /// position asked for is past its end, so the answer is nulls and the length has to be the
4229    /// length that was asked for rather than the length that was there.
4230    #[test]
4231    fn gathering_from_a_vector_of_no_values_is_that_many_nulls() {
4232        let vector = Vector::flat(LogicalType::Null, Data::Empty).unwrap();
4233        let gathered = vector.gather(&[0, 1, 2]).unwrap();
4234        assert_eq!(gathered.len(), 3);
4235        assert_eq!(gathered.value_at(0), Value::Null);
4236        assert_eq!(gathered.value_at(2), Value::Null);
4237    }
4238
4239    /// Every position holds the same value, so a gather with no hole in it has nothing to copy and
4240    /// the result is the constant again rather than a run of a thousand copies of it.
4241    #[test]
4242    fn gathering_a_constant_stays_a_constant() {
4243        let vector = Vector::constant(LogicalType::Integer, Value::Integer(4), 100);
4244        let gathered = vector.gather(&[7, 7, 99]).unwrap();
4245        assert_eq!(gathered.form(), Form::Constant);
4246        assert_eq!(gathered.len(), 3);
4247        assert_eq!(gathered.value_at(2), Value::Integer(4));
4248    }
4249
4250    /// A dictionary over a dictionary is what a second filter over an already filtered chunk builds,
4251    /// and the gather has to walk to the bottom of that chain rather than one step down it. The
4252    /// constructor composes the ordinary chain away, so the one built here is the kind it cannot,
4253    /// which is a level holding nulls of its own.
4254    #[test]
4255    fn gathering_walks_a_dictionary_over_a_dictionary_to_the_values() {
4256        let inner = Vector::dictionary(vec![2, 1, 0], integers(&[7, 8, 9]))
4257            .unwrap()
4258            .with_validity(Validity::from_iter(3, |index| index != 2));
4259        let outer = Vector::dictionary(vec![1, 2], inner).unwrap();
4260        let gathered = outer.gather(&[0, 1]).unwrap();
4261        assert_eq!(gathered.form(), Form::Flat);
4262        assert_eq!(gathered.value_at(0), Value::Integer(8));
4263        assert_eq!(gathered.value_at(1), Value::Null);
4264    }
4265
4266    /// Two filters over one chunk build a dictionary over a dictionary, four conjuncts pushed down
4267    /// separately build four levels of it, and every level is a dependent load on every later read
4268    /// of every row plus a code array that cannot be freed. Composing at construction is one pass
4269    /// over the codes the range check was walking anyway.
4270    #[test]
4271    fn a_dictionary_over_a_dictionary_is_composed_into_one_level() {
4272        let inner = Vector::dictionary(vec![2, 1, 0], integers(&[7, 8, 9])).unwrap();
4273        let outer = Vector::dictionary(vec![1, 2], inner).unwrap();
4274        let (codes, values) = outer.dictionary_parts().unwrap();
4275        assert_eq!(codes, [1, 0]);
4276        assert_eq!(values.form(), Form::Flat);
4277        assert_eq!(outer.value_at(0), Value::Integer(8));
4278        assert_eq!(outer.value_at(1), Value::Integer(7));
4279    }
4280
4281    /// The invariant stated as the thing it is there for, which is that the depth does not grow with
4282    /// the number of filters. Four levels stacked one at a time are one level at the end of it.
4283    #[test]
4284    fn stacking_dictionaries_does_not_make_them_deeper() {
4285        let mut vector = integers(&[10, 20, 30, 40]);
4286        for _ in 0..4 {
4287            vector = Vector::dictionary(vec![3, 2, 1, 0], vector).unwrap();
4288        }
4289        let (codes, values) = vector.dictionary_parts().unwrap();
4290        assert_eq!(values.form(), Form::Flat);
4291        assert_eq!(codes, [0, 1, 2, 3]);
4292        assert_eq!(
4293            vector.iter().collect::<Vec<_>>(),
4294            integers(&[10, 20, 30, 40]).iter().collect::<Vec<_>>()
4295        );
4296    }
4297
4298    /// Composing has to carry the nulls down with it. The values hold them, the codes point at them,
4299    /// and a composed code that lands on a null position is still a null.
4300    #[test]
4301    fn composing_a_dictionary_keeps_the_nulls_its_values_hold() {
4302        let values =
4303            Vector::from_values(LogicalType::Integer, &[Value::Integer(3), Value::Null]).unwrap();
4304        let inner = Vector::dictionary(vec![1, 0, 1], values).unwrap();
4305        let outer = Vector::dictionary(vec![0, 1], inner).unwrap();
4306        assert_eq!(outer.dictionary_parts().unwrap().1.form(), Form::Flat);
4307        assert_eq!(outer.value_at(0), Value::Null);
4308        assert_eq!(outer.value_at(1), Value::Integer(3));
4309    }
4310
4311    /// The one level composition cannot go past. A dictionary that was given a validity of its own is
4312    /// saying its nulls are at that level rather than in the values, and pointing the outer codes
4313    /// straight at the values would read through the holes instead of stopping at them.
4314    #[test]
4315    fn a_dictionary_holding_its_own_nulls_is_not_composed_past() {
4316        let inner = Vector::dictionary(vec![0, 1, 2], integers(&[1, 2, 3]))
4317            .unwrap()
4318            .with_validity(Validity::from_iter(3, |index| index != 1));
4319        let outer = Vector::dictionary(vec![1, 2, 0], inner).unwrap();
4320        assert_eq!(outer.dictionary_parts().unwrap().1.form(), Form::Dictionary);
4321        assert_eq!(outer.value_at(0), Value::Null);
4322        assert_eq!(outer.value_at(1), Value::Integer(3));
4323        assert_eq!(outer.value_at(2), Value::Integer(1));
4324    }
4325
4326    /// The difference between the two questions about nulls, which a group by got wrong. A filtered
4327    /// chunk is dictionary vectors, those are built with every row marked present at their own
4328    /// level, and the nulls are down in the values. So the mask says the row has a value and the
4329    /// row does not.
4330    #[test]
4331    fn a_null_behind_a_dictionary_reads_as_null_even_though_the_mask_says_otherwise() {
4332        let values = Vector::flat(LogicalType::Integer, Data::Int32(vec![0, 7].into()))
4333            .unwrap()
4334            .with_validity(Validity::from_iter(2, |index| index != 0));
4335        let vector = Vector::dictionary(vec![0, 1, 0], values).unwrap();
4336        assert!(vector.validity().is_valid(0), "the mask at this level says present");
4337        assert!(vector.is_null_at(0));
4338        assert!(!vector.is_null_at(1));
4339        assert!(vector.is_null_at(2));
4340        assert!(vector.is_null_at(3), "a row past the end is null");
4341    }
4342
4343    /// The same for runs, which are built the same way and keep their nulls in the same place.
4344    #[test]
4345    fn a_null_inside_a_run_reads_as_null_even_though_the_mask_says_otherwise() {
4346        let values = Vector::flat(LogicalType::Integer, Data::Int32(vec![0, 7].into()))
4347            .unwrap()
4348            .with_validity(Validity::from_iter(2, |index| index != 0));
4349        let vector = Vector::runs(vec![2, 3], values).unwrap();
4350        assert!(vector.validity().is_valid(0));
4351        assert!(vector.is_null_at(0));
4352        assert!(vector.is_null_at(1));
4353        assert!(!vector.is_null_at(2));
4354    }
4355
4356    /// Every other form keeps its nulls in its own mask, so the two answers agree there.
4357    #[test]
4358    fn the_forms_that_hold_their_own_nulls_answer_the_same_either_way() {
4359        let flat = Vector::flat(LogicalType::Integer, Data::Int32(vec![0, 7].into()))
4360            .unwrap()
4361            .with_validity(Validity::from_iter(2, |index| index != 0));
4362        let constant = Vector::constant(LogicalType::Integer, Value::Null, 2);
4363        let sequence = Vector::sequence(10, 2, 2);
4364        for vector in [flat, constant, sequence] {
4365            for row in 0..vector.len() {
4366                assert_eq!(vector.is_null_at(row), !vector.validity().is_valid(row));
4367            }
4368        }
4369    }
4370
4371    #[test]
4372    fn flattening_a_flat_vector_is_the_same_vector() {
4373        let vector = integers(&[1, 2, 3]);
4374        assert_eq!(vector.flatten().unwrap(), vector);
4375    }
4376
4377    #[test]
4378    fn a_decimal_reads_its_width_and_scale_from_the_type_and_not_the_data() {
4379        let ty = LogicalType::decimal(9, 2).unwrap();
4380        let vector = Vector::flat(ty, Data::Int32(vec![1234].into())).unwrap();
4381        assert_eq!(vector.value_at(0), Value::Decimal { unscaled: 1234, width: 9, scale: 2 });
4382        assert_eq!(vector.value_at(0).to_string(), "12.34");
4383    }
4384
4385    #[test]
4386    fn a_decimal_writes_into_whichever_of_the_four_runs_its_precision_chose() {
4387        // The read path worked at every width and the write path only accepted the 128 bit run, so
4388        // `SELECT 2.5` produced a value nothing could store. All four widths round trip now.
4389        for (width, scale, unscaled) in
4390            [(4u8, 1u8, 25i128), (9, 2, 1234), (18, 3, 123_456), (38, 4, 1_234_567)]
4391        {
4392            let ty = LogicalType::decimal(width, scale).unwrap();
4393            let value = Value::Decimal { unscaled, width, scale };
4394            let vector = Vector::from_values(ty, &[value.clone(), Value::Null]).unwrap();
4395            assert_eq!(vector.value_at(0), value, "a decimal of width {width}");
4396            assert_eq!(vector.value_at(1), Value::Null, "a null decimal of width {width}");
4397        }
4398    }
4399
4400    /// The bytes a blob holds are not required to be text, and a vector of them used to refuse the
4401    /// ones that were not. A byte array column in a Parquet file that nothing annotated is a blob,
4402    /// which is what ClickHouse writes and what ten of the ClickBench queries compare against, so
4403    /// this is the path those take rather than a corner of the type system.
4404    #[test]
4405    fn a_blob_holds_bytes_that_are_not_text() {
4406        let bytes = |raw: &[u8]| Value::Blob(raw.to_vec());
4407        let values = [
4408            bytes(b"a\xffb"),
4409            bytes(b"\x00\x01\x02"),
4410            Value::Null,
4411            bytes(b"\xed\xa0\x80 and long enough to leave the view"),
4412            bytes(b""),
4413        ];
4414        let vector = Vector::from_values(LogicalType::Blob, &values).unwrap();
4415        for (index, value) in values.iter().enumerate() {
4416            assert_eq!(&vector.value_at(index), value, "row {index}");
4417        }
4418    }
4419
4420    #[test]
4421    fn a_decimal_too_wide_for_the_run_its_type_chose_is_an_error_and_not_a_wrong_number() {
4422        // Only reachable by hand, since a value's width is what picked the run. Truncating here
4423        // would store a different number and say nothing about it.
4424        let ty = LogicalType::decimal(4, 1).unwrap();
4425        let value = Value::Decimal { unscaled: 1_000_000, width: 4, scale: 1 };
4426        let error = Vector::from_values(ty, &[value]).unwrap_err();
4427        assert!(error.to_string().contains("does not fit"), "{error}");
4428    }
4429
4430    #[test]
4431    fn a_flat_vector_costs_its_values_and_a_constant_costs_one() {
4432        let flat = integers(&[1; 1000]);
4433        assert!(
4434            flat.footprint() >= 4000,
4435            "a thousand i32 are four thousand bytes: {}",
4436            flat.footprint()
4437        );
4438        // The forms that compute their values rather than storing them cost nothing per value,
4439        // which is the point of having them and is what the memory limit should see.
4440        let constant = Vector::constant(LogicalType::Integer, Value::Integer(1), 1_000_000);
4441        assert!(constant.footprint() < 200, "a constant is one value: {}", constant.footprint());
4442        let sequence = Vector::sequence(0, 1, 1_000_000);
4443        assert!(sequence.footprint() < 200, "a sequence is two numbers: {}", sequence.footprint());
4444    }
4445
4446    #[test]
4447    fn a_string_vector_costs_the_bytes_of_its_long_strings() {
4448        let short =
4449            Vector::from_values(LogicalType::Varchar, &[Value::Varchar("red".into())]).unwrap();
4450        let long = "a string well past the sixteen bytes a view holds inline".to_string();
4451        let spilled =
4452            Vector::from_values(LogicalType::Varchar, &[Value::Varchar(long.clone())]).unwrap();
4453        assert!(
4454            spilled.footprint() >= short.footprint() + long.len(),
4455            "the arena is counted: {} against {}",
4456            spilled.footprint(),
4457            short.footprint()
4458        );
4459    }
4460
4461    /// The cases worth checking are the widths where a code straddles a word boundary, which is
4462    /// every width that does not divide sixty four, and the two ends of the range.
4463    #[test]
4464    fn a_narrow_column_packs_and_reads_back_the_same_at_every_width() {
4465        for width in 1..=20u32 {
4466            let span = (1i64 << width) - 1;
4467            let values: Vec<i64> =
4468                (0..1000).map(|row| 1_000_000 + (row * 7919) % (span + 1)).collect();
4469            let flat =
4470                Vector::flat(LogicalType::BigInt, Data::Int64(values.clone().into())).unwrap();
4471            let packed = flat.bit_packed().unwrap();
4472            assert_eq!(packed.len(), flat.len());
4473            assert_eq!(
4474                packed.iter().collect::<Vec<_>>(),
4475                flat.iter().collect::<Vec<_>>(),
4476                "width {width} read back differently"
4477            );
4478        }
4479    }
4480
4481    #[test]
4482    fn the_width_is_the_bits_the_range_needs_and_not_the_bits_the_type_has() {
4483        let values: Vec<i32> = (0..1024).map(|row| 40 + (row * 2560) / 1023).collect();
4484        let flat = Vector::flat(LogicalType::Integer, Data::Int32(values.into())).unwrap();
4485        let packed = flat.bit_packed().unwrap();
4486        assert_eq!(packed.form(), Form::BitPacked);
4487        let parts = packed.packed_parts().expect("packed");
4488        assert_eq!(parts.width(), 12, "0 to 2560 is twelve bits");
4489        assert_eq!(parts.base(), 40);
4490        assert!(
4491            packed.footprint() * 2 < flat.footprint(),
4492            "twelve bits against thirty two: {} against {}",
4493            packed.footprint(),
4494            flat.footprint()
4495        );
4496    }
4497
4498    /// The check is worth having in both directions, the way the run length one is. A form that is
4499    /// only ever bigger than what it replaced costs a pass over the column to decide not to use.
4500    #[test]
4501    fn a_column_that_uses_its_whole_type_is_left_flat() {
4502        let values: Vec<i32> = (0..1024).map(|row| row * 2_000_000 - 1_000_000_000).collect();
4503        let flat = Vector::flat(LogicalType::Integer, Data::Int32(values.into())).unwrap();
4504        assert_eq!(flat.bit_packed().unwrap().form(), Form::Flat);
4505    }
4506
4507    /// A column of one value would pack to no bits at all, and one run is smaller than any packing
4508    /// of it, so the two forms do not fight over that column.
4509    #[test]
4510    fn a_column_of_one_value_is_left_to_the_run_length_form() {
4511        let flat = integers(&[9; 1024]);
4512        assert_eq!(flat.bit_packed().unwrap().form(), Form::Flat);
4513        assert_eq!(flat.run_encoded().unwrap().form(), Form::Rle);
4514    }
4515
4516    #[test]
4517    fn a_string_column_has_no_range_to_pack() {
4518        let text = Vector::from_values(
4519            LogicalType::Varchar,
4520            &[Value::Varchar("red".into()), Value::Varchar("blue".into())],
4521        )
4522        .unwrap();
4523        assert_eq!(text.bit_packed().unwrap().form(), Form::Flat);
4524    }
4525
4526    /// The cut is the reason the form carries a row to start reading at. It stays packed, it shares
4527    /// the same words, and it reads the rows the range asked for.
4528    #[test]
4529    fn a_cut_of_a_packed_column_stays_packed_and_shares_its_bits() {
4530        let values: Vec<i32> = (0..1024).map(|row| 100 + row % 300).collect();
4531        let flat = Vector::flat(LogicalType::Integer, Data::Int32(values.into())).unwrap();
4532        let packed = flat.bit_packed().unwrap();
4533        let cut = packed.slice(500, 24).unwrap();
4534        assert_eq!(cut.form(), Form::BitPacked);
4535        assert_eq!(cut.len(), 24);
4536        assert_eq!(
4537            cut.iter().collect::<Vec<_>>(),
4538            flat.slice(500, 24).unwrap().iter().collect::<Vec<_>>()
4539        );
4540        assert!(
4541            cut.footprint() >= packed.footprint(),
4542            "a cut shares the words rather than copying a piece of them"
4543        );
4544    }
4545
4546    #[test]
4547    fn a_gather_of_a_packed_column_comes_out_flat_and_keeps_the_nulls() {
4548        let values: Vec<i32> = (0..64).map(|row| 10 + row).collect();
4549        let flat = Vector::flat(LogicalType::Integer, Data::Int32(values.into())).unwrap();
4550        let packed =
4551            flat.bit_packed().unwrap().with_validity(Validity::from_iter(64, |row| row % 3 != 0));
4552        let taken = packed.gather(&[0, 1, 2, 3, 62]).unwrap();
4553        assert_eq!(taken.form(), Form::Flat);
4554        assert_eq!(
4555            taken.iter().collect::<Vec<_>>(),
4556            vec![
4557                Value::Null,
4558                Value::Integer(11),
4559                Value::Integer(12),
4560                Value::Null,
4561                Value::Integer(72)
4562            ]
4563        );
4564    }
4565
4566    /// The pair a comparison kernel asks for before it reads a bit. A literal inside the range has a
4567    /// code and a literal outside it does not, which answers the whole vector at once.
4568    #[test]
4569    fn a_literal_outside_the_packed_range_has_no_code() {
4570        let values: Vec<i32> = (0..256).map(|row| 1000 + row).collect();
4571        let flat = Vector::flat(LogicalType::Integer, Data::Int32(values.into())).unwrap();
4572        let packed = flat.bit_packed().unwrap();
4573        let parts = packed.packed_parts().expect("packed");
4574        assert_eq!(parts.code_of(1000), Some(0));
4575        assert_eq!(parts.code_of(1100), Some(100));
4576        assert_eq!(parts.code_of(999), None);
4577        assert!(parts.ceiling() >= 1255);
4578        assert_eq!(parts.code_of(parts.ceiling() + 1), None);
4579    }
4580
4581    /// The bits arriving from a file rather than from a flat vector, which is what the form is for.
4582    #[test]
4583    fn packed_bits_can_be_handed_in_without_a_flat_vector_to_start_from() {
4584        let packed = Vector::packed(LogicalType::SmallInt, vec![0x0000_0000_0000_4321], 4, 7, 4)
4585            .expect("four codes of four bits");
4586        assert_eq!(
4587            packed.iter().collect::<Vec<_>>(),
4588            vec![Value::SmallInt(8), Value::SmallInt(9), Value::SmallInt(10), Value::SmallInt(11)]
4589        );
4590    }
4591
4592    #[test]
4593    fn packed_bits_that_could_not_hold_what_they_claim_are_refused() {
4594        assert!(Vector::packed(LogicalType::Varchar, vec![0], 4, 0, 4).is_err(), "not an integer");
4595        assert!(Vector::packed(LogicalType::Integer, vec![0], 0, 0, 4).is_err(), "no width");
4596        assert!(Vector::packed(LogicalType::Integer, vec![0], 64, 0, 4).is_err(), "too wide");
4597        assert!(Vector::packed(LogicalType::Integer, vec![0], 8, 0, 9).is_err(), "too few words");
4598        assert!(Vector::packed(LogicalType::TinyInt, vec![0], 8, 100, 8).is_err(), "would not fit");
4599    }
4600
4601    /// A column of strings long enough that the payload is in the arena rather than in the views.
4602    fn long_strings(count: usize) -> Vector {
4603        let values: Vec<Value> = (0..count)
4604            .map(|row| {
4605                Value::Varchar(format!("a string too long to sit inside a view, number {row}"))
4606            })
4607            .collect();
4608        Vector::from_values(LogicalType::Varchar, &values).unwrap()
4609    }
4610
4611    #[test]
4612    fn a_string_column_in_view_form_reads_back_the_same_strings() {
4613        let flat = long_strings(40);
4614        let shared = flat.clone().shared_text().unwrap();
4615        assert_eq!(shared.form(), Form::StringView);
4616        assert_eq!(shared.len(), 40);
4617        for row in 0..40 {
4618            assert_eq!(shared.value_at(row), flat.value_at(row), "row {row}");
4619            assert_eq!(shared.text_at(row), flat.text_at(row), "row {row}");
4620        }
4621    }
4622
4623    #[test]
4624    fn a_short_string_is_read_out_of_its_view_and_never_out_of_the_arena() {
4625        let flat = Vector::from_values(
4626            LogicalType::Varchar,
4627            &[Value::Varchar("red".into()), Value::Varchar("green".into()), Value::Null],
4628        )
4629        .unwrap();
4630        let shared = flat.shared_text().unwrap();
4631        // Nothing went to the arena, so the whole column resolves with an empty one.
4632        let (views, arena) = shared.text_parts().unwrap();
4633        assert!(arena.is_empty(), "three short strings need no arena");
4634        assert_eq!(views[0].bytes_in(arena), Some(&b"red"[..]));
4635        assert_eq!(shared.value_at(1), Value::Varchar("green".into()));
4636        assert_eq!(shared.value_at(2), Value::Null, "the validity came across");
4637    }
4638
4639    #[test]
4640    fn a_cut_of_a_view_column_shares_the_arena_rather_than_copying_the_bytes() {
4641        let shared = long_strings(64).shared_text().unwrap();
4642        let cut = shared.slice(16, 8).unwrap();
4643        assert_eq!(cut.form(), Form::StringView, "a cut of views is views");
4644        assert_eq!(cut.len(), 8);
4645        assert_eq!(cut.value_at(0), shared.value_at(16));
4646        assert_eq!(cut.value_at(7), shared.value_at(23));
4647        // The arena is the same bytes at the same address, which is the whole point of the form.
4648        let (_, whole) = shared.text_parts().unwrap();
4649        let (_, piece) = cut.text_parts().unwrap();
4650        assert_eq!(piece.as_ptr(), whole.as_ptr(), "the cut shares the page");
4651        assert_eq!(piece.len(), whole.len());
4652    }
4653
4654    #[test]
4655    fn a_flat_string_column_has_to_copy_the_bytes_its_cut_keeps() {
4656        let flat = long_strings(64);
4657        let cut = flat.slice(16, 8).unwrap();
4658        assert_eq!(cut.form(), Form::Flat);
4659        let (_, whole) = flat.text_parts().unwrap();
4660        let (_, piece) = cut.text_parts().unwrap();
4661        assert!(piece.len() < whole.len(), "the flat cut carries only what it kept");
4662    }
4663
4664    #[test]
4665    fn a_gather_of_a_view_column_keeps_the_form_and_a_flatten_copies_out_of_it() {
4666        let shared = long_strings(32).shared_text().unwrap();
4667        let picked: Vec<u32> = (0..32).step_by(3).collect();
4668        let gathered = shared.gather(&picked).unwrap();
4669        assert_eq!(gathered.form(), Form::StringView, "selecting rows moves views, not bytes");
4670        assert_eq!(gathered.len(), picked.len());
4671        for (row, &from) in picked.iter().enumerate() {
4672            assert_eq!(gathered.value_at(row), shared.value_at(from as usize), "row {row}");
4673        }
4674        let flattened = gathered.flatten().unwrap();
4675        assert_eq!(flattened.form(), Form::Flat);
4676        assert_eq!(flattened.iter().collect::<Vec<_>>(), gathered.iter().collect::<Vec<_>>());
4677        // The flatten is what narrows the bytes, so the arena it built holds only the rows it kept.
4678        let (_, narrowed) = flattened.text_parts().unwrap();
4679        let (_, whole) = shared.text_parts().unwrap();
4680        assert!(narrowed.len() < whole.len(), "flattening lets the page go");
4681    }
4682
4683    #[test]
4684    fn a_null_in_a_view_column_survives_being_gathered_and_flattened() {
4685        let shared = long_strings(8)
4686            .with_validity(Validity::from_iter(8, |row| row % 3 != 0))
4687            .shared_text()
4688            .unwrap();
4689        let gathered = shared.gather(&[0, 1, 2, 3, 4]).unwrap();
4690        let expected =
4691            [Value::Null, shared.value_at(1), shared.value_at(2), Value::Null, shared.value_at(4)];
4692        assert_eq!(gathered.iter().collect::<Vec<_>>(), expected);
4693        assert_eq!(gathered.flatten().unwrap().iter().collect::<Vec<_>>(), expected);
4694    }
4695
4696    #[test]
4697    fn both_string_forms_hand_a_kernel_the_same_views_and_the_same_bytes() {
4698        let flat = long_strings(6);
4699        let shared = flat.clone().shared_text().unwrap();
4700        let (flat_views, flat_arena) = flat.text_parts().unwrap();
4701        let (shared_views, shared_arena) = shared.text_parts().unwrap();
4702        assert_eq!(flat_views.len(), shared_views.len());
4703        for row in 0..6 {
4704            assert_eq!(
4705                flat_views[row].bytes_in(flat_arena),
4706                shared_views[row].bytes_in(shared_arena),
4707                "row {row}"
4708            );
4709        }
4710        // Nothing else answers this, which is what keeps a kernel from taking it for a string column.
4711        assert!(Vector::sequence(0, 1, 4).text_parts().is_none());
4712        assert!(integers(&[1, 2, 3]).text_parts().is_none());
4713    }
4714
4715    #[test]
4716    fn a_column_that_is_not_strings_cannot_be_held_as_views() {
4717        let views = vec![StringView::inline("red")];
4718        let arena = Arc::new(Buffer::new());
4719        let wrong = Vector::string_views(LogicalType::Integer, views, arena);
4720        assert!(wrong.is_err(), "an integer column has no views");
4721        assert_eq!(integers(&[1, 2]).shared_text().unwrap().form(), Form::Flat, "left alone");
4722    }
4723
4724    /// A column with enough repeated structure for a symbol table to find something, which is what
4725    /// a real text column has and a column of random bytes does not.
4726    fn sentences(count: usize) -> Vector {
4727        let values: Vec<Value> = (0..count)
4728            .map(|row| {
4729                Value::Varchar(format!(
4730                    "http://example.test/catalogue/section/{}/item/{row}",
4731                    row % 7
4732                ))
4733            })
4734            .collect();
4735        Vector::from_values(LogicalType::Varchar, &values).unwrap()
4736    }
4737
4738    #[test]
4739    fn a_compressed_column_reads_back_the_strings_that_went_into_it() {
4740        let flat = sentences(64);
4741        let coded = flat.clone().compressed().unwrap();
4742        assert_eq!(coded.form(), Form::Fsst, "a text column compresses");
4743        assert_eq!(coded.len(), 64);
4744        for row in 0..64 {
4745            assert_eq!(coded.value_at(row), flat.value_at(row), "row {row}");
4746        }
4747        assert_eq!(coded.flatten().unwrap(), flat, "flattening is the column it came from");
4748    }
4749
4750    #[test]
4751    fn compressing_halves_the_bytes_or_the_column_is_left_flat() {
4752        let flat = sentences(200);
4753        let coded = flat.clone().compressed().unwrap();
4754        let parts = coded.coded_parts().expect("compressed");
4755        // Read through the flat column, because the compressed one has no bytes to hand back where
4756        // they are and answers `None` to `text_at` rather than decompressing into a borrow.
4757        assert_eq!(coded.text_at(0), None, "nothing to borrow until it is flattened");
4758        let plain: usize = (0..200).map(|row| flat.text_at(row).map_or(0, str::len)).sum();
4759        let codes: usize = (0..200).map(|row| parts.row(row).map_or(0, <[u8]>::len)).sum();
4760        assert!(codes * FSST_PAYS_AT <= plain, "{codes} codes against {plain} bytes");
4761        // Text with no repeated structure in it gives a table nothing longer than a byte to find,
4762        // so the codes are the bytes and the column stays where it is rather than paying a
4763        // decompression per read to save nothing.
4764        let mut seed = 0x2545_f491_4f6c_dd1du64;
4765        let values: Vec<Value> = (0..256)
4766            .map(|_| {
4767                let mut text = String::new();
4768                while text.len() < 12 {
4769                    seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
4770                    text.push(char::from(b'!' + ((seed >> 33) % 90) as u8));
4771                }
4772                Value::Varchar(text)
4773            })
4774            .collect();
4775        let noise = Vector::from_values(LogicalType::Varchar, &values).unwrap();
4776        assert_eq!(noise.compressed().unwrap().form(), Form::Flat);
4777    }
4778
4779    #[test]
4780    fn a_cut_of_a_compressed_column_shares_the_codes_and_the_table() {
4781        let coded = sentences(64).compressed().unwrap();
4782        let cut = coded.slice(8, 16).unwrap();
4783        assert_eq!(cut.form(), Form::Fsst);
4784        assert_eq!(cut.len(), 16);
4785        for row in 0..16 {
4786            assert_eq!(cut.value_at(row), coded.value_at(8 + row), "row {row}");
4787        }
4788        let (whole, piece) = (coded.coded_parts().unwrap(), cut.coded_parts().unwrap());
4789        assert_eq!(piece.row(0), whole.row(8), "the spans point into the same codes");
4790    }
4791
4792    #[test]
4793    fn a_gather_of_a_compressed_column_stays_compressed_and_keeps_the_nulls() {
4794        let coded = sentences(32)
4795            .with_validity(Validity::from_iter(32, |row| row % 5 != 2))
4796            .compressed()
4797            .unwrap();
4798        let picked: Vec<u32> = (0..32).step_by(2).collect();
4799        let gathered = coded.gather(&picked).unwrap();
4800        assert_eq!(gathered.form(), Form::Fsst, "selecting rows moves spans, not bytes");
4801        for (row, &from) in picked.iter().enumerate() {
4802            assert_eq!(gathered.value_at(row), coded.value_at(from as usize), "row {row}");
4803        }
4804        assert_eq!(
4805            gathered.flatten().unwrap().iter().collect::<Vec<_>>(),
4806            gathered.iter().collect::<Vec<_>>()
4807        );
4808    }
4809
4810    #[test]
4811    fn a_literal_lands_in_the_same_codes_the_row_holding_it_does() {
4812        let coded = sentences(40).compressed().unwrap();
4813        let parts = coded.coded_parts().expect("compressed");
4814        let text = coded.value_at(11);
4815        let Value::Varchar(text) = text else { panic!("a string column reads back strings") };
4816        assert_eq!(parts.encode(text.as_bytes()), parts.row(11).expect("row 11"));
4817        assert_ne!(parts.encode(b"something else entirely"), parts.row(11).unwrap());
4818    }
4819
4820    #[test]
4821    fn codes_that_run_past_what_is_there_are_refused() {
4822        let table = Arc::new(SymbolTable::empty());
4823        let codes = Arc::new(vec![1u8, 2, 3, 4]);
4824        let good = vec![(0u32, 2u32), (2, 4)];
4825        assert!(
4826            Vector::coded(LogicalType::Varchar, Arc::clone(&codes), good, Arc::clone(&table))
4827                .is_ok()
4828        );
4829        let past = vec![(0u32, 9u32)];
4830        assert!(
4831            Vector::coded(LogicalType::Varchar, Arc::clone(&codes), past, Arc::clone(&table))
4832                .is_err(),
4833            "a span past the end of the codes"
4834        );
4835        let backwards = vec![(3u32, 1u32)];
4836        assert!(
4837            Vector::coded(LogicalType::Varchar, Arc::clone(&codes), backwards, Arc::clone(&table))
4838                .is_err(),
4839            "a span that ends before it starts"
4840        );
4841        let wrong = vec![(0u32, 2u32)];
4842        assert!(
4843            Vector::coded(LogicalType::Integer, codes, wrong, table).is_err(),
4844            "an integer column has no codes"
4845        );
4846    }
4847
4848    #[test]
4849    fn a_view_pointing_past_its_arena_is_refused_at_construction() {
4850        let long = "a string too long to sit inside a view";
4851        let arena: Arc<Buffer<u8>> = Arc::new(long.as_bytes().to_vec().into());
4852        let good = vec![StringView::over(long.as_bytes(), 0)];
4853        assert!(Vector::string_views(LogicalType::Varchar, good, Arc::clone(&arena)).is_ok());
4854        let bad = vec![StringView::over(long.as_bytes(), 4)];
4855        assert!(
4856            Vector::string_views(LogicalType::Varchar, bad, arena).is_err(),
4857            "four bytes short of what the view claims"
4858        );
4859    }
4860}