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