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