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