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