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//! **What is not here yet.** Buffers are owned. Section 7.1 says a vector borrowed from a buffer
25//! managed page carries a pin, and there is no buffer manager until M2, so there is nothing to pin
26//! and pretending otherwise would be an interface built against an imaginary caller. Nested types
27//! are not stored yet either, for the same reason: a `LIST(STRUCT(...))` is offsets plus child
28//! column chunks, and child column chunks are storage.
29
30use std::borrow::Cow;
31use std::sync::Arc;
32
33use rudb_common::{Cause, Error, LogicalType, Result, Value, slow};
34
35use crate::buffer::Buffer;
36use crate::fsst::SymbolTable;
37use crate::string::{StringColumn, StringView};
38use crate::validity::Validity;
39
40/// How many values are in a full vector.
41///
42/// 1024 rather than DuckDB's 2048, per `spec/04-architecture.md` section 4.3. It is the FastLanes
43/// unit, it makes a validity mask exactly 16 `u64` words, and it keeps a vector of 16 byte string
44/// views at 16 KiB, which is the size at which several of these fit in L1 together rather than
45/// evicting each other.
46pub const VECTOR_SIZE: usize = 1024;
47
48/// Which physical form a vector is in.
49///
50/// An operator asks this once per vector and then takes the path it wants, which is the one branch
51/// per vector that the whole design is willing to spend.
52///
53/// Not exhaustive, and that is a decision rather than an oversight. `Encoded` is the fifth form
54/// and it arrives at layer three with the specialization contract. If this enum were exhaustive,
55/// the day it lands is the day every kernel in the workspace stops compiling, and the pressure at
56/// that moment would be to add an arm to each of them in a hurry rather than to think about what
57/// each one should do with an encoded vector. A required fallback arm means each kernel already
58/// has a correct answer for a form it has never seen, and specializing it is then a change that
59/// can be made one kernel at a time with a benchmark next to it.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
61#[non_exhaustive]
62pub enum Form {
63    /// One value per position.
64    Flat,
65    /// One value, repeated.
66    Constant,
67    /// A start and a step, computed rather than stored.
68    Sequence,
69    /// Codes into a smaller vector of distinct values.
70    Dictionary,
71    /// Integers stored in as many bits as the range of the column needs, offset from a base.
72    ///
73    /// The form a narrow integer column is in. A ClickBench `ResolutionWidth` is a `SMALLINT` whose
74    /// values live between 0 and 2560, which is twelve bits, so the column is three quarters of the
75    /// size it was and the pages behind it are three quarters of the reads. What it costs is a shift
76    /// and a mask per value, which is why this is worth it at storage and at rest and is not a form
77    /// anything should be building in the middle of a pipeline.
78    BitPacked,
79    /// Sixteen byte views over an arena the vector shares rather than owns.
80    ///
81    /// The form a varchar column is in once more than one vector is looking at the same page. A flat
82    /// varchar vector owns its arena, so cutting a chunk out of it copies every byte of every long
83    /// string in the range, and on ClickBench that is most of what reading `URL` costs. Sharing the
84    /// arena makes the cut the views and nothing else, the way a dictionary cut is the codes and
85    /// nothing else.
86    StringView,
87    /// Strings compressed against one symbol table, each row on its own.
88    ///
89    /// The form a text column is in at rest. FSST is about half the bytes on the ClickBench `URL`
90    /// and `Title` columns, and unlike a block compressor it keeps random access, so reading row
91    /// four million does not decompress the four million before it. What it costs is a decompression
92    /// per row read, which is why an equality filter over it is worth writing in code space: the
93    /// literal compresses once and the rows never decompress at all.
94    Fsst,
95    /// One value per run, with the row each run ends at.
96    ///
97    /// The form a clustered column is in. `hits` is written in time order, so `EventDate` is a few
98    /// hundred runs over a hundred million rows, and a sum over it is a few hundred multiplications
99    /// rather than a hundred million additions. Dictionary says which distinct values there are and
100    /// this says where they stop, and a column can want either one without wanting the other.
101    Rle,
102}
103
104/// The values of a flat vector, one Rust vector per physical type.
105///
106/// The variants are physical rather than logical, which is what lets `DATE` and `INTEGER` share
107/// storage and share a kernel. What a run of `i32` means is the vector's logical type's business.
108#[derive(Debug, Clone, PartialEq)]
109#[non_exhaustive]
110pub enum Data {
111    /// No values, for the type of an untyped `NULL`.
112    Empty,
113    /// One byte per value.
114    Bool(Buffer<bool>),
115    /// 8 bit signed.
116    Int8(Buffer<i8>),
117    /// 16 bit signed.
118    Int16(Buffer<i16>),
119    /// 32 bit signed.
120    Int32(Buffer<i32>),
121    /// 64 bit signed.
122    Int64(Buffer<i64>),
123    /// 128 bit signed.
124    Int128(Buffer<i128>),
125    /// 8 bit unsigned.
126    UInt8(Buffer<u8>),
127    /// 16 bit unsigned.
128    UInt16(Buffer<u16>),
129    /// 32 bit unsigned.
130    UInt32(Buffer<u32>),
131    /// 64 bit unsigned.
132    UInt64(Buffer<u64>),
133    /// 128 bit unsigned.
134    UInt128(Buffer<u128>),
135    /// IEEE 754 binary32.
136    Float32(Buffer<f32>),
137    /// IEEE 754 binary64.
138    Float64(Buffer<f64>),
139    /// The months, days and microseconds triple.
140    Interval(Buffer<(i32, i32, i64)>),
141    /// Strings, as 16 byte views plus the arena the long ones live in.
142    Varlen(StringColumn),
143}
144
145impl Data {
146    /// How many values are stored.
147    ///
148    /// The match below has no wildcard arm, and that is what makes this function the check that
149    /// keeps [`for_each_layout`](crate::for_each_layout) honest. A variant added to this enum
150    /// without being added to the `all` group fails to compile here, which is a line in a build log
151    /// rather than a layout quietly missing from six kernels.
152    #[must_use]
153    pub fn len(&self) -> usize {
154        macro_rules! lengths {
155            ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
156                match self {
157                    Self::Empty => 0,
158                    $(Self::$variant(values) => values.len(),)+
159                }
160            };
161        }
162        crate::for_each_layout!(all, lengths)
163    }
164
165    /// Whether there are no values.
166    #[must_use]
167    pub fn is_empty(&self) -> bool {
168        self.len() == 0
169    }
170
171    /// How many bytes of memory these values are holding.
172    ///
173    /// One arm per layout through the same macro as [`Data::len`], for the same reason: a layout
174    /// added without a size here is a layout the memory limit would charge nothing for, and a
175    /// buffer that is free is a buffer that can be grown until the process dies.
176    #[must_use]
177    pub fn footprint(&self) -> usize {
178        macro_rules! sizes {
179            ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
180                match self {
181                    Self::Empty => 0,
182                    $(Self::$variant(values) => values.footprint(),)+
183                }
184            };
185        }
186        crate::for_each_layout!(all, sizes)
187    }
188
189    /// An integer at `index`, widened, for any of the signed integer layouts.
190    ///
191    /// Used by the decimal path, which needs the unscaled value out of whichever width the width
192    /// and scale picked, and by anything else that would otherwise repeat the same five arms.
193    #[must_use]
194    pub fn signed_at(&self, index: usize) -> Option<i128> {
195        macro_rules! widened {
196            ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
197                match self {
198                    $(Self::$variant(v) => v.get(index).map(|&x| i128::from(x)),)+
199                    _ => None,
200                }
201            };
202        }
203        crate::for_each_layout!(signed, widened)
204    }
205
206    /// An unsigned integer at `index`, widened.
207    #[must_use]
208    pub fn unsigned_at(&self, index: usize) -> Option<u128> {
209        macro_rules! widened {
210            ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
211                match self {
212                    $(Self::$variant(v) => v.get(index).map(|&x| u128::from(x)),)+
213                    _ => None,
214                }
215            };
216        }
217        crate::for_each_layout!(unsigned, widened)
218    }
219
220    /// The string at `index`, for a `Varlen`.
221    #[must_use]
222    pub fn str_at(&self, index: usize) -> Option<&str> {
223        match self {
224            Self::Varlen(column) => column.get(index),
225            _ => None,
226        }
227    }
228
229    /// The bytes at `index`, for a `Varlen`, whatever they are.
230    ///
231    /// What a `BLOB` reads through, since the bytes of one are not required to be text and
232    /// [`Self::str_at`] answers `None` for the ones that are not.
233    #[must_use]
234    pub fn bytes_at(&self, index: usize) -> Option<&[u8]> {
235        match self {
236            Self::Varlen(column) => column.bytes(index),
237            _ => None,
238        }
239    }
240}
241
242/// A type, a length, a validity representation and some data.
243#[derive(Debug, Clone, PartialEq)]
244pub struct Vector {
245    ty: LogicalType,
246    len: usize,
247    validity: Validity,
248    body: Body,
249}
250
251/// What the vector holds, which is what its form is decided by.
252#[derive(Debug, Clone, PartialEq)]
253enum Body {
254    Flat(Data),
255    Constant(Box<Value>),
256    Sequence {
257        start: i64,
258        step: i64,
259    },
260    /// The values are behind an `Arc` rather than a `Box` because slicing shares them.
261    ///
262    /// A dictionary vector is cut once per chunk and the dictionary itself is the same dictionary
263    /// every time, so a `Box` meant a copy of every value in it per cut. On the ClickBench columns
264    /// that are dictionary encoded the dictionary is larger than the chunk of codes pointing into
265    /// it, and copying it was ten percent of the cycles of reading the file.
266    ///
267    /// Nothing here mutates a dictionary in place, so sharing one is only ever a read, and the one
268    /// place that wants an owned copy of the values is [`compose`], which asks for one.
269    Dictionary {
270        codes: Vec<u32>,
271        values: Arc<Vector>,
272    },
273    /// Integer codes of `width` bits each, packed end to end, each one an offset from `base`.
274    ///
275    /// Row `r` is the `width` bits starting at bit `(offset + r) * width`, read little end first, so
276    /// a code that straddles a word boundary has its low bits in the earlier word. `offset` is what
277    /// lets a cut of a packed column be free: the bits are not byte aligned, so a slice either
278    /// repacks or remembers where it starts, and remembering is one addition per read.
279    ///
280    /// The words are behind an `Arc` for the reason the dictionary's values are. A page is packed
281    /// once and cut into chunk sized pieces, and copying the words per cut would undo most of what
282    /// the packing saved.
283    Packed {
284        words: Arc<Vec<u64>>,
285        width: u32,
286        base: i128,
287        offset: usize,
288    },
289    /// The views of a string column, over an arena that other vectors are reading at the same time.
290    ///
291    /// The views are owned because a cut is a different run of views, and the arena is shared
292    /// because a cut is the same bytes. That split is the whole form: sixteen bytes a row move and
293    /// the payload does not, however many cuts a page is taken in.
294    ///
295    /// A row's bytes are found the same way [`StringColumn`] finds them, through
296    /// [`StringView::bytes_in`], so a short string never reads the arena at all and the two ways of
297    /// holding strings cannot answer a row differently.
298    Views {
299        views: Vec<StringView>,
300        arena: Arc<Buffer<u8>>,
301    },
302    /// The FSST codes of every row, end to end, with one symbol table over all of them.
303    ///
304    /// A span rather than a run of offsets, because a gather keeps this form and a gather puts the
305    /// rows in an order the codes are not in. Eight bytes a row either way, and the span is the one
306    /// that survives being permuted.
307    ///
308    /// The codes and the table are shared for the reason a dictionary's values are: one table is
309    /// trained per page and every chunk cut out of it points at the same one. A table is sixty five
310    /// thousand hash slots, so a table per chunk would cost more than the compression saves.
311    Coded {
312        codes: Arc<Vec<u8>>,
313        spans: Vec<(u32, u32)>,
314        table: Arc<SymbolTable>,
315    },
316    /// One value per run, with the row each run ends at, exclusive and increasing.
317    ///
318    /// Ends rather than lengths, because every reader of this wants to know which run holds a row
319    /// and ends answer that with a binary search while lengths answer it with a running total. The
320    /// two are the same information and only one of them is the one that gets asked for.
321    ///
322    /// The values are behind an `Arc` for the reason the dictionary's are: a page is cut into chunk
323    /// sized pieces and the values are the same values every time.
324    Runs {
325        ends: Vec<u32>,
326        values: Arc<Vector>,
327    },
328}
329
330impl Vector {
331    /// A flat vector of `data`, all valid.
332    ///
333    /// # Errors
334    ///
335    /// If the data's physical layout is not the one the type calls for. That check is here rather
336    /// than left to the caller because a vector whose type and layout disagree is a wrong answer
337    /// waiting to be read out, and it costs one comparison at construction to prevent.
338    pub fn flat(ty: LogicalType, data: Data) -> Result<Self> {
339        let len = data.len();
340        if !matches!(data, Data::Empty) && layout_of(&data) != ty.physical() {
341            return Err(Error::internal(format!(
342                "a {ty} vector cannot hold {:?} data",
343                layout_of(&data)
344            )));
345        }
346        Ok(Self { ty, len, validity: Validity::AllValid, body: Body::Flat(data) })
347    }
348
349    /// A flat vector built from single values, with the nulls among them turning into validity.
350    ///
351    /// The slow way in, and the only way in that anything outside this crate has. It is what an
352    /// `INSERT`, a `VALUES` clause and a test build a column with, all of which arrive holding
353    /// values rather than a run of `i32`. Nothing on a scan path calls it: a scan produces a run of
354    /// data directly and hands it to [`Self::flat`].
355    ///
356    /// # Errors
357    ///
358    /// If a value is not one the type can hold, or if the type is one that cannot be stored flat
359    /// yet, which today means the nested types.
360    pub fn from_values(ty: LogicalType, values: &[Value]) -> Result<Self> {
361        let mut data = empty_data_for(&ty)?;
362        for value in values {
363            push_value(&mut data, value)?;
364        }
365        let validity = Validity::from_iter(values.len(), |index| !values[index].is_null());
366        Ok(Self { ty, len: values.len(), validity, body: Body::Flat(data) })
367    }
368
369    /// A vector of `len` copies of one value.
370    ///
371    /// Costs one value regardless of the length, which is what makes a literal in a predicate free
372    /// and what makes a projection of a constant free.
373    #[must_use]
374    pub fn constant(ty: LogicalType, value: Value, len: usize) -> Self {
375        let validity = if value.is_null() { Validity::AllInvalid } else { Validity::AllValid };
376        Self { ty, len, validity, body: Body::Constant(Box::new(value)) }
377    }
378
379    /// A vector of `len` values starting at `start` and stepping by `step`.
380    ///
381    /// This is what a row identifier column is, and it costs sixteen bytes rather than eight
382    /// kilobytes. A scan that produces row ids for a later fetch produces one of these.
383    #[must_use]
384    pub fn sequence(start: i64, step: i64, len: usize) -> Self {
385        Self {
386            ty: LogicalType::BigInt,
387            len,
388            validity: Validity::AllValid,
389            body: Body::Sequence { start, step },
390        }
391    }
392
393    /// A vector of codes into a smaller vector of distinct values.
394    ///
395    /// The form the whole M3 thesis rests on. A dictionary vector handed to a group by is an
396    /// integer column, and an aggregate over one is an aggregate over integers no matter what the
397    /// logical type says.
398    ///
399    /// A dictionary over a dictionary is composed into one level here rather than left as two, so
400    /// the form has a depth of one always and a kernel that reads [`Self::dictionary_parts`] is
401    /// reading the values rather than another layer of codes. Two filters over the same chunk build
402    /// the second case and four conjuncts pushed down separately build four of it.
403    ///
404    /// The cost of leaving them stacked turned out to be a cliff rather than a slope. Every loop in
405    /// `rudb-kernels` reaches for the values behind the codes with [`Self::data`], a dictionary
406    /// pointing at a dictionary has no data to hand back, so the second level does not make the
407    /// kernels slower, it turns them off and drops the work onto the row at a time path that exists
408    /// to be correct rather than fast. Measured on server3 over a chunk of two numeric columns and a
409    /// consumer of two vectorized passes, one level reads at 3.5 nanoseconds a row and two levels at
410    /// 104, and the third and fourth levels cost almost nothing more because the first one had
411    /// already given up everything there was to give. Composing is one pass over the outer codes,
412    /// which the range check above is already making.
413    ///
414    /// The one dictionary that is not composed past is one carrying a validity of its own. A
415    /// dictionary is built all valid and only [`Self::with_validity`] can change that, so such a
416    /// vector is saying that its nulls are at this level rather than in the values it points at, and
417    /// composing past it would drop them.
418    ///
419    /// # Errors
420    ///
421    /// If any code is past the end of the value vector.
422    pub fn dictionary(codes: Vec<u32>, values: Vector) -> Result<Self> {
423        Self::dictionary_over(codes, Arc::new(values))
424    }
425
426    /// The same, over a set of values somebody else is holding too.
427    ///
428    /// The body holds its values in an `Arc` either way, so a caller that already has one has
429    /// nothing to hand over but a pointer. The caller this is for is a Parquet chunk: one dictionary
430    /// page serves every data page of the chunk, and going through [`Self::dictionary`] meant
431    /// copying the whole dictionary into each page's vector on the way to putting it in an `Arc`
432    /// that then had a single holder. On a ClickBench scan that copy was sixteen percent of the
433    /// instructions the query ran.
434    ///
435    /// Composing a dictionary over a dictionary still needs the values by value, so that case takes
436    /// them out of the handle and copies if anybody else is still reading them. Nothing that shares
437    /// a dictionary builds a stacked one, so the two paths do not meet in practice.
438    ///
439    /// The range check takes the highest code rather than stopping at the first bad one. Stopping
440    /// early sounds cheaper and is not, because a loop that can exit anywhere cannot be vectorized
441    /// and a running maximum can, and the only run that would have exited early is the one about to
442    /// fail the query anyway. Every other run reads the whole of `codes` either way. It was 5.2
443    /// percent of a ClickBench scan as a `find`.
444    ///
445    /// # Errors
446    ///
447    /// If any code is past the end of the value vector.
448    pub fn dictionary_over(codes: Vec<u32>, values: Arc<Vector>) -> Result<Self> {
449        let highest = codes.iter().copied().fold(0, u32::max);
450        if !codes.is_empty() && highest as usize >= values.len() {
451            return Err(Error::internal(format!(
452                "dictionary code {highest} is past the end of a {} value dictionary",
453                values.len()
454            )));
455        }
456        let stacked = matches!(values.validity, Validity::AllValid)
457            && matches!(values.body, Body::Dictionary { .. });
458        let (codes, values) = if stacked {
459            let (codes, values) = compose(codes, Arc::unwrap_or_clone(values));
460            (codes, Arc::new(values))
461        } else {
462            (codes, values)
463        };
464        Ok(Self {
465            ty: values.ty.clone(),
466            len: codes.len(),
467            validity: Validity::AllValid,
468            body: Body::Dictionary { codes, values },
469        })
470    }
471
472    /// A vector of runs, one value each, with the row each run ends at.
473    ///
474    /// `ends` is exclusive and strictly increasing, so run `i` covers the rows from `ends[i - 1]` to
475    /// `ends[i]` and run zero starts at nothing. The length of the vector is the last end.
476    ///
477    /// The depth is one, the same way a dictionary's is, and for a sharper reason. Every kernel that
478    /// wants runs wants the value of a run without another search, and a run length vector over a
479    /// run length vector turns one search into two and then into three. Rather than compose, this
480    /// refuses: nothing in the engine builds a stacked one, because [`Self::run_encoded`] only ever
481    /// reads a flat body, so a stacked one is a caller doing something by hand and the useful answer
482    /// is to say so rather than to quietly do a pass of work they did not ask for.
483    ///
484    /// A run over a dictionary is fine and is not that case. The two forms answer different
485    /// questions and a column that is both clustered and low cardinality genuinely wants both.
486    ///
487    /// # Errors
488    ///
489    /// If there is not exactly one value per run, if the ends do not increase, or if the values are
490    /// themselves run length encoded.
491    pub fn runs(ends: Vec<u32>, values: Vector) -> Result<Self> {
492        if matches!(values.body, Body::Runs { .. }) {
493            return Err(Error::internal("runs of runs, which is two searches to read one row"));
494        }
495        if ends.len() != values.len() {
496            return Err(Error::internal(format!(
497                "{} runs and {} values to put in them",
498                ends.len(),
499                values.len()
500            )));
501        }
502        if ends.windows(2).any(|pair| pair[0] >= pair[1]) || ends.first() == Some(&0) {
503            return Err(Error::internal("run ends that do not increase"));
504        }
505        let len = ends.last().copied().unwrap_or(0) as usize;
506        Ok(Self {
507            ty: values.ty.clone(),
508            len,
509            validity: Validity::AllValid,
510            body: Body::Runs { ends, values: Arc::new(values) },
511        })
512    }
513
514    /// The same values as runs, when there are few enough runs for that to be smaller.
515    ///
516    /// Costs one pass over the column to find out, which is why this is a call somebody makes rather
517    /// than something a constructor does. The decision is the same arithmetic every time: a row in
518    /// flat form costs one value, a run costs one value plus the four bytes of its end, so runs are
519    /// smaller once there are fewer than about half as many runs as rows, and the narrower the
520    /// column the more runs it takes. `RUNS_PAY_AT` is that ratio, written down rather than spelt
521    /// into an `if`, because it is the number a sweep will want to move.
522    ///
523    /// Only a flat body is looked at. A constant and a sequence are already one value and two
524    /// numbers, so there is nothing to win, and a dictionary that is also clustered is a real case
525    /// that wants its codes run length encoded rather than its values, which is a different function
526    /// and not this one.
527    ///
528    /// Two adjacent nulls are one run. Two adjacent equal values with a null between them are three,
529    /// because the null is a value of the column as far as anything reading it is concerned.
530    ///
531    /// # Errors
532    ///
533    /// If the type has no flat layout, which today means the nested types.
534    pub fn run_encoded(&self) -> Result<Self> {
535        let Body::Flat(data) = &self.body else {
536            return Ok(self.clone());
537        };
538        let ends = boundaries(data, &self.validity, self.len);
539        if ends.len().saturating_mul(RUNS_PAY_AT) >= self.len {
540            return Ok(self.clone());
541        }
542        let starts: Vec<u32> =
543            std::iter::once(0).chain(ends.iter().copied()).take(ends.len()).collect();
544        Self::runs(ends, self.gather(&starts)?)
545    }
546
547    /// A vector of `len` integers packed `width` bits each, every one an offset from `base`.
548    ///
549    /// The way in for a reader that already has the packed bits, which is what a column file holds
550    /// and what a network frame carries. Nothing unpacks on the way in, so a scan of a packed column
551    /// hands the bits straight to the chunk and the cost of the form is paid by whoever reads a
552    /// value rather than by the scan.
553    ///
554    /// The range check is on the two ends rather than on every code, which is the whole check. A
555    /// code is between zero and `2^width - 1` by construction, so if `base` and `base + 2^width - 1`
556    /// both fit the column's layout then every value does, and that is two comparisons instead of
557    /// one per row.
558    ///
559    /// # Errors
560    ///
561    /// If the type is not one of the integer layouts, if the width is not between one and
562    /// [`PACKED_WIDTH_MAX`], if there are not enough words for the length, or if either end of the
563    /// range would not fit the type.
564    pub fn packed(
565        ty: LogicalType,
566        words: Vec<u64>,
567        width: u32,
568        base: i128,
569        len: usize,
570    ) -> Result<Self> {
571        let Some((low, high)) = layout_range(&ty) else {
572            return Err(Error::internal(format!("a {ty} vector has no integer layout to pack")));
573        };
574        if width == 0 || width > PACKED_WIDTH_MAX {
575            return Err(Error::internal(format!(
576                "a packed width of {width}, which is outside 1 to {PACKED_WIDTH_MAX}"
577            )));
578        }
579        let needed = words_for(len, width);
580        if words.len() < needed {
581            return Err(Error::internal(format!(
582                "{} words for {len} values of {width} bits, which needs {needed}",
583                words.len()
584            )));
585        }
586        let top = base + i128::from(u64::MAX >> (64 - width));
587        if base < low || top > high {
588            return Err(Error::internal(format!(
589                "packed values from {base} to {top}, which a {ty} cannot hold"
590            )));
591        }
592        Ok(Self {
593            ty,
594            len,
595            validity: Validity::AllValid,
596            body: Body::Packed { words: Arc::new(words), width, base, offset: 0 },
597        })
598    }
599
600    /// The same values bit packed, when the range of the column makes that smaller.
601    ///
602    /// Costs one pass to find the range and one to write the bits, which is why this is a call
603    /// somebody makes rather than something a constructor does. It is the counterpart of
604    /// [`Self::run_encoded`] and the decision has the same shape: a row flat costs the width of its
605    /// layout, a row packed costs the bits the column's range needs, and the form is worth having
606    /// only when the second is a good deal smaller than the first. [`PACKING_PAYS_AT`] is that
607    /// ratio, written down rather than spelt into an `if`, because it is the number a sweep will
608    /// want to move.
609    ///
610    /// Only a flat integer body is looked at. A constant and a sequence are already smaller than any
611    /// packing of them, a dictionary's codes are the thing that would want packing rather than its
612    /// values, and a float has no range to pack into since the bits of an `f64` are not an integer
613    /// that arithmetic on the column agrees with.
614    ///
615    /// The range is taken over every slot including the null ones, which hold a zero. A column of
616    /// large values with one null in it therefore packs a range that reaches down to zero and comes
617    /// out wider than it needed to be. The alternative is a pass that consults the validity per slot
618    /// to find the range and a second rule for what to write into a null slot, and this form exists
619    /// to make reads cheap rather than to squeeze the last bit out of a sparse column.
620    ///
621    /// A column whose values are all the same packs to nothing at all, and rather than invent a zero
622    /// bit code this declines and leaves it to [`Self::run_encoded`], which turns that column into
623    /// one run and is smaller than any packing of it.
624    ///
625    /// # Errors
626    ///
627    /// If the packed bits and the length disagree, which would be a bug here rather than a caller
628    /// doing something wrong.
629    pub fn bit_packed(&self) -> Result<Self> {
630        let Body::Flat(data) = &self.body else {
631            return Ok(self.clone());
632        };
633        let Some((low, high)) = span_of(data, self.len) else {
634            return Ok(self.clone());
635        };
636        let Some(range) = high.checked_sub(low).and_then(|range| u64::try_from(range).ok()) else {
637            return Ok(self.clone());
638        };
639        let width = u64::BITS - range.leading_zeros();
640        if width == 0 || width > PACKED_WIDTH_MAX {
641            return Ok(self.clone());
642        }
643        if words_for(self.len, width) * size_of::<u64>() * PACKING_PAYS_AT > data.footprint() {
644            return Ok(self.clone());
645        }
646        let words = pack(data, self.len, low, width);
647        let packed = Self::packed(self.ty.clone(), words, width, low, self.len)?;
648        Ok(packed.with_validity(self.validity.clone()))
649    }
650
651    /// A vector of string views over an arena somebody else is holding too.
652    ///
653    /// The way in for a scan that has a page of strings and wants several chunks over it. Each chunk
654    /// gets its own run of views and they all share the one arena, so the bytes are read where the
655    /// page put them and nothing copies them.
656    ///
657    /// Every view is checked against the arena here rather than when a row is read. That is a pass
658    /// over the views at construction, which is the same pass the caller just did to build them, and
659    /// what it buys is that a row of this form cannot resolve to bytes that are not there. The check
660    /// is on the offsets and not on the bytes, so it says nothing about whether the payload is text,
661    /// which is the same promise a `BLOB` column makes.
662    ///
663    /// # Errors
664    ///
665    /// If the type is not one stored as views, or if a view points past the end of the arena.
666    pub fn string_views(
667        ty: LogicalType,
668        views: Vec<StringView>,
669        arena: Arc<Buffer<u8>>,
670    ) -> Result<Self> {
671        if ty.physical() != rudb_common::PhysicalType::Varlen {
672            return Err(Error::internal(format!("a {ty} vector cannot hold string views")));
673        }
674        if views.iter().any(|view| view.bytes_in(&arena).is_none()) {
675            return Err(Error::internal("a string view points past the end of its arena"));
676        }
677        let len = views.len();
678        Ok(Self { ty, len, validity: Validity::AllValid, body: Body::Views { views, arena } })
679    }
680
681    /// The same strings, in a form where a cut of them does not copy the bytes.
682    ///
683    /// The counterpart of [`Self::run_encoded`] and [`Self::bit_packed`] for a string column, and
684    /// the only one of the three that takes `self` by value. It has to: what it does is move the
685    /// arena into an `Arc` so nothing copies it again, and a version taking `&self` would start by
686    /// copying the arena once to have one to move.
687    ///
688    /// Anything that is not a flat string column comes back as it was, which includes a column that
689    /// is already in this form.
690    ///
691    /// # Errors
692    ///
693    /// Nothing here fails today. The result is a `Result` because the check inside
694    /// [`Self::string_views`] is worth running on the views this builds rather than trusting that
695    /// this function built them right.
696    pub fn shared_text(self) -> Result<Self> {
697        let Body::Flat(Data::Varlen(column)) = self.body else {
698            return Ok(self);
699        };
700        let (views, arena) = column.into_parts();
701        let shared = Self::string_views(self.ty, views, Arc::new(arena))?;
702        Ok(shared.with_validity(self.validity))
703    }
704
705    /// A vector of FSST codes against a table somebody else trained.
706    ///
707    /// The way in for a reader that has a page of compressed strings and the table that goes with
708    /// it. The codes are not copied and the table is not retrained, so laying several chunks over
709    /// one page costs the spans and nothing else.
710    ///
711    /// # Errors
712    ///
713    /// If the type is not one stored as text, or if a span runs past the end of the codes.
714    pub fn coded(
715        ty: LogicalType,
716        codes: Arc<Vec<u8>>,
717        spans: Vec<(u32, u32)>,
718        table: Arc<SymbolTable>,
719    ) -> Result<Self> {
720        if ty.physical() != rudb_common::PhysicalType::Varlen {
721            return Err(Error::internal(format!("a {ty} vector cannot hold FSST codes")));
722        }
723        let end = u32::try_from(codes.len()).unwrap_or(u32::MAX);
724        if spans.iter().any(|&(from, to)| from > to || to > end) {
725            return Err(Error::internal("an FSST span runs past the end of the codes"));
726        }
727        let len = spans.len();
728        Ok(Self {
729            ty,
730            len,
731            validity: Validity::AllValid,
732            body: Body::Coded { codes, spans, table },
733        })
734    }
735
736    /// The same strings, compressed against a table trained on them.
737    ///
738    /// The counterpart of [`Self::run_encoded`] and [`Self::bit_packed`] for a text column, and it
739    /// takes `self` by value for the reason [`Self::shared_text`] does.
740    ///
741    /// The table is trained on every row rather than on a sample. A vector is at most 1024 rows, so
742    /// the sample would be most of the column anyway, and the systematic sampling
743    /// `spec/06-compression.md` section 6.3 asks for is a decision about a page and belongs to
744    /// whoever is holding one.
745    ///
746    /// It declines unless the codes are at most half the bytes the strings are. FSST gets about that
747    /// on text and rather less on anything already short or already random, and below that the
748    /// decompression per row read is not bought back. A column it declines on comes back as it was.
749    ///
750    /// # Errors
751    ///
752    /// Nothing here fails today. The result is a `Result` because the checks inside [`Self::coded`]
753    /// are worth running on what this builds rather than trusting that this built it right.
754    pub fn compressed(self) -> Result<Self> {
755        let Body::Flat(Data::Varlen(column)) = &self.body else {
756            return Ok(self);
757        };
758        let rows: Vec<&[u8]> = (0..self.len).filter_map(|row| column.bytes(row)).collect();
759        if rows.len() != self.len {
760            return Ok(self);
761        }
762        let plain: usize = rows.iter().map(|row| row.len()).sum();
763        let table = SymbolTable::train(&rows);
764        let mut codes = Vec::with_capacity(plain);
765        let mut spans = Vec::with_capacity(self.len);
766        for row in &rows {
767            let from = u32::try_from(codes.len()).unwrap_or(u32::MAX);
768            table.compress(row, &mut codes);
769            spans.push((from, u32::try_from(codes.len()).unwrap_or(u32::MAX)));
770        }
771        if codes.len() * FSST_PAYS_AT > plain {
772            return Ok(self);
773        }
774        let coded = Self::coded(self.ty.clone(), Arc::new(codes), spans, Arc::new(table))?;
775        Ok(coded.with_validity(self.validity.clone()))
776    }
777
778    /// The same vector with a different validity.
779    #[must_use]
780    pub fn with_validity(mut self, validity: Validity) -> Self {
781        self.validity = validity;
782        self
783    }
784
785    /// What kind of values these are.
786    #[must_use]
787    pub fn logical_type(&self) -> &LogicalType {
788        &self.ty
789    }
790
791    /// How many values there are.
792    #[must_use]
793    pub fn len(&self) -> usize {
794        self.len
795    }
796
797    /// Whether there are no values.
798    #[must_use]
799    pub fn is_empty(&self) -> bool {
800        self.len == 0
801    }
802
803    /// How many bytes of memory this vector is holding.
804    ///
805    /// What the memory limit charges for it. A constant and a sequence hold one value and two
806    /// numbers however long they are, which is the point of both forms, so the number here is the
807    /// form's cost and not the column's width times its length.
808    ///
809    /// A dictionary counts its values in full, and two vectors sharing one dictionary each report
810    /// all of it. That over counts, deliberately: working out that two operators are looking at the
811    /// same `Arc` means threading identity through the accounting, and a limit that over counts
812    /// refuses a query that would have fit while a limit that under counts lets one through that
813    /// does not. The first is a worse answer to give and the second is a worse thing to be.
814    #[must_use]
815    pub fn footprint(&self) -> usize {
816        let body = match &self.body {
817            Body::Flat(data) => data.footprint(),
818            Body::Constant(value) => value.footprint(),
819            Body::Sequence { .. } => 0,
820            Body::Dictionary { codes, values } => {
821                codes.capacity() * size_of::<u32>() + values.footprint()
822            }
823            Body::Packed { words, .. } => words.capacity() * size_of::<u64>(),
824            // The arena counts in full in every vector sharing it, for the reason a shared
825            // dictionary does: over counting refuses a query that would have fit and under counting
826            // admits one that does not, and the first is the better way to be wrong.
827            Body::Views { views, arena } => {
828                views.capacity() * size_of::<StringView>() + arena.footprint()
829            }
830            // The table counts in full in every vector sharing it, the way a shared arena and a
831            // shared dictionary do. It is the largest of the three and the most shared of them, so
832            // this is the one place the over counting is worth saying out loud: a page of a hundred
833            // chunks reports its table a hundred times.
834            Body::Coded { codes, spans, table } => {
835                codes.capacity() + spans.capacity() * size_of::<(u32, u32)>() + table.footprint()
836            }
837            Body::Runs { ends, values } => ends.capacity() * size_of::<u32>() + values.footprint(),
838        };
839        size_of::<Self>() + self.validity.footprint() + body
840    }
841
842    /// Which of the values are not null.
843    #[must_use]
844    pub fn validity(&self) -> &Validity {
845        &self.validity
846    }
847
848    /// Which physical form this vector is in.
849    #[must_use]
850    pub fn form(&self) -> Form {
851        match self.body {
852            Body::Flat(_) => Form::Flat,
853            Body::Constant(_) => Form::Constant,
854            Body::Sequence { .. } => Form::Sequence,
855            Body::Dictionary { .. } => Form::Dictionary,
856            Body::Packed { .. } => Form::BitPacked,
857            Body::Views { .. } => Form::StringView,
858            Body::Coded { .. } => Form::Fsst,
859            Body::Runs { .. } => Form::Rle,
860        }
861    }
862
863    /// The data, for a flat vector, and `None` for any other form.
864    ///
865    /// A kernel that wants a slice asks for it and takes the flat path if it gets one. A kernel
866    /// that can do better on a constant or a dictionary checks [`Self::form`] first.
867    #[must_use]
868    pub fn data(&self) -> Option<&Data> {
869        match &self.body {
870            Body::Flat(data) => Some(data),
871            _ => None,
872        }
873    }
874
875    /// The one value, for a constant vector, and `None` for any other form.
876    ///
877    /// A kernel comparing a column against a literal wants the literal once rather than 1024
878    /// times, and [`Self::value_at`] on a constant clones it on every call because it has to be
879    /// able to hand back a `Value` for any form. This is the accessor that lets the specialized
880    /// path hoist the clone out of the loop.
881    #[must_use]
882    pub fn constant_value(&self) -> Option<&Value> {
883        match &self.body {
884            Body::Constant(value) => Some(value.as_ref()),
885            _ => None,
886        }
887    }
888
889    /// The codes and the values, for a dictionary vector, and `None` for any other form.
890    ///
891    /// The reason a kernel needs this rather than reading the dictionary through
892    /// [`Self::value_at`] is the entire argument for the form existing. A filter against a
893    /// dictionary column of 1024 rows and 40 distinct values is 40 comparisons and 1024 lookups,
894    /// not 1024 comparisons, and there is no way to write that loop without seeing the codes.
895    ///
896    /// Note what the validity of the returned vector means. A dictionary keeps its nulls in the
897    /// vector it points at, and the dictionary's own validity says nothing about them, so a caller
898    /// deciding whether row `i` is null has to ask the value vector about `codes[i]` rather than
899    /// asking this vector about `i`. [`Self::flatten`] has the same note on it for the same
900    /// reason, because getting this wrong is a null that survives being selected and comes out as
901    /// a zero.
902    #[must_use]
903    pub fn dictionary_parts(&self) -> Option<(&[u32], &Self)> {
904        match &self.body {
905            Body::Dictionary { codes, values } => Some((codes, values.as_ref())),
906            _ => None,
907        }
908    }
909
910    /// The run ends and the run values, for a run length vector, and `None` for any other form.
911    ///
912    /// The ends are exclusive and increasing, and there is exactly one value per run, so a kernel
913    /// that wants to walk this walks the pairs and never asks which run a row is in. That is the
914    /// whole argument for the form: an aggregate over a clustered column is one multiply per run
915    /// instead of one add per row, and there is no way to write that loop without seeing the ends.
916    ///
917    /// The nulls are in the values, the way a dictionary's are, so a caller deciding whether row `i`
918    /// is null asks the value vector about the run rather than asking this vector about `i`.
919    #[must_use]
920    pub fn run_parts(&self) -> Option<(&[u32], &Self)> {
921        match &self.body {
922            Body::Runs { ends, values } => Some((ends, values.as_ref())),
923            _ => None,
924        }
925    }
926
927    /// Where each row's value is, for the two forms that keep their values somewhere else.
928    ///
929    /// A dictionary and a run length vector are the same shape seen from a kernel: a run of
930    /// positions and a vector to read them out of. The difference is that a dictionary stores the
931    /// positions and a run length vector works them out, and a kernel writing `values[at[row]]` does
932    /// not care which. So every specialization written against [`Self::dictionary_parts`] covers
933    /// both forms by asking this instead, and the day a third form with an indirection arrives it
934    /// covers that one too without any of those kernels being reopened.
935    ///
936    /// The run length side costs an allocation of one position per row and a pass to fill it, which
937    /// is the same four bytes a row a dictionary was already carrying and is paid once per kernel
938    /// call rather than once per row. That is the price of this being one accessor rather than a
939    /// second arm in eighteen kernels, and it is not the last word: a kernel that wants a run at a
940    /// time reads [`Self::run_parts`] and pays nothing, which is the specialization this makes it
941    /// possible to skip writing until a sweep says it is worth it.
942    #[must_use]
943    pub fn positions(&self) -> Option<(Cow<'_, [u32]>, &Self)> {
944        match &self.body {
945            Body::Dictionary { codes, values } => Some((Cow::Borrowed(codes), values.as_ref())),
946            Body::Runs { ends, values } => {
947                let mut at = Vec::with_capacity(self.len);
948                for (run, &stop) in ends.iter().enumerate() {
949                    let run = u32::try_from(run).unwrap_or(u32::MAX);
950                    at.resize(stop as usize, run);
951                }
952                Some((Cow::Owned(at), values.as_ref()))
953            }
954            _ => None,
955        }
956    }
957
958    /// The bits and what they mean, for a bit packed vector, and `None` for any other form.
959    ///
960    /// What a kernel needs to stay in code space. A comparison against a literal is the case that
961    /// pays: `column > 900` over a column packed from a base of 40 is `code > 860`, which is the
962    /// same shift and mask the read was going to do anyway and no unpacking at all, and a literal
963    /// outside the packed range answers the whole vector without reading a bit of it. None of that
964    /// can be written without seeing the width and the base.
965    #[must_use]
966    pub fn packed_parts(&self) -> Option<Packed<'_>> {
967        match &self.body {
968            Body::Packed { words, width, base, offset } => {
969                Some(Packed { words, width: *width, base: *base, offset: *offset })
970            }
971            _ => None,
972        }
973    }
974
975    /// The views and the arena, for either form that stores strings, and `None` for the rest.
976    ///
977    /// This is to the two string forms what [`Self::positions`] is to the two forms that point
978    /// somewhere else. A flat varchar column owns its arena and a string view column shares one, and
979    /// a kernel reading a row wants the view and the bytes either way, so every specialization
980    /// written against this covers both forms and neither has to be reopened when a third way of
981    /// holding an arena arrives.
982    ///
983    /// The arena is whatever the long strings live in, which for a column over a page is the page,
984    /// including the parts of it no view points at. Only the views say which bytes are a row.
985    #[must_use]
986    pub fn text_parts(&self) -> Option<(&[StringView], &[u8])> {
987        match &self.body {
988            Body::Flat(Data::Varlen(column)) => Some((column.views(), column.arena())),
989            Body::Views { views, arena } => Some((views, arena)),
990            _ => None,
991        }
992    }
993
994    /// The codes and the table, for an FSST vector, and `None` for any other form.
995    ///
996    /// What a kernel needs to stay in code space. An equality filter is the case that pays, and it
997    /// pays completely: the literal is compressed once against the same table and after that a row
998    /// matches exactly when its code bytes match, because compressing is a function and so is
999    /// decompressing. No row is decompressed at all. An ordering comparison cannot do that, since a
1000    /// symbol code says nothing about where its symbol sorts, so those decompress and say so.
1001    #[must_use]
1002    pub fn coded_parts(&self) -> Option<Coded<'_>> {
1003        match &self.body {
1004            Body::Coded { codes, spans, table } => Some(Coded { codes, spans, table }),
1005            _ => None,
1006        }
1007    }
1008
1009    /// The start and the step, for a sequence vector, and `None` for any other form.
1010    #[must_use]
1011    pub fn sequence_parts(&self) -> Option<(i64, i64)> {
1012        match self.body {
1013            Body::Sequence { start, step } => Some((start, step)),
1014            _ => None,
1015        }
1016    }
1017
1018    /// The value at `index`, as a single value.
1019    ///
1020    /// This is the slow path on purpose. It is what a result set is read out with and what a test
1021    /// asserts on, and an operator that calls it per row is an operator that has already lost the
1022    /// argument the vector interface exists to win.
1023    #[must_use]
1024    pub fn value_at(&self, index: usize) -> Value {
1025        if index >= self.len || !self.validity.is_valid(index) {
1026            return Value::Null;
1027        }
1028        match &self.body {
1029            Body::Constant(value) => value.as_ref().clone(),
1030            Body::Sequence { start, step } => Value::BigInt(start + step * index as i64),
1031            Body::Dictionary { codes, values } => match codes.get(index) {
1032                Some(&code) => values.value_at(code as usize),
1033                None => Value::Null,
1034            },
1035            Body::Runs { ends, values } => match run_holding(ends, index) {
1036                Some(run) => values.value_at(run),
1037                None => Value::Null,
1038            },
1039            // One value unpacked into a run of one, so that what a packed value means is decided in
1040            // the same place a flat one is rather than in a second copy of the type mapping that
1041            // could drift from it. It allocates, which this path is allowed to do and the typed
1042            // unpack in `copied` is not, and it is the reason anything about to read a packed
1043            // column a row at a time should flatten it once instead.
1044            Body::Packed { words, width, base, offset } => {
1045                unpack(&self.ty, words, *offset, *width, *base, &[index])
1046                    .map_or(Value::Null, |data| value_from(&self.ty, &data, 0))
1047            }
1048            // The bytes are where the arena has them, and what they are read as is the logical
1049            // type's business, so this hands the row to the same reader a flat column goes through
1050            // rather than deciding here that a `BLOB` is a string.
1051            Body::Views { views, arena } => {
1052                match views.get(index).and_then(|v| v.bytes_in(arena)) {
1053                    Some(bytes) => bytes_as(&self.ty, bytes),
1054                    None => Value::Null,
1055                }
1056            }
1057            // One row decompressed on its own, which is the property the form is chosen for. It
1058            // allocates, which this path is allowed to do, and it is the reason anything about to
1059            // read a compressed column a row at a time should flatten it once instead.
1060            Body::Coded { codes, spans, table } => {
1061                match spans.get(index).and_then(|&(from, to)| {
1062                    let mut out = Vec::new();
1063                    table.decompress(codes.get(from as usize..to as usize)?, &mut out).ok()?;
1064                    Some(out)
1065                }) {
1066                    Some(bytes) => bytes_as(&self.ty, &bytes),
1067                    None => Value::Null,
1068                }
1069            }
1070            Body::Flat(data) => value_from(&self.ty, data, index),
1071        }
1072    }
1073
1074    /// The text at `index`, borrowed rather than copied.
1075    ///
1076    /// [`Self::value_at`] on a `VARCHAR` column allocates a `String` per call, and a group by that
1077    /// reads a string column keys on one string per input row. This hands back the bytes where they
1078    /// already are, so a caller with somewhere to put them does not go to the allocator at all.
1079    ///
1080    /// `None` for a null, for an index past the end, for a column that is not `VARCHAR`, and for the
1081    /// constant and sequence forms, whose values are not stored per position. A caller that gets
1082    /// `None` has to fall back to [`Self::value_at`], which is correct for all of those.
1083    #[must_use]
1084    pub fn text_at(&self, index: usize) -> Option<&str> {
1085        if self.ty != LogicalType::Varchar || index >= self.len || !self.validity.is_valid(index) {
1086            return None;
1087        }
1088        match &self.body {
1089            Body::Flat(data) => data.str_at(index),
1090            Body::Dictionary { codes, values } => {
1091                values.text_at(usize::try_from(*codes.get(index)?).ok()?)
1092            }
1093            Body::Runs { ends, values } => values.text_at(run_holding(ends, index)?),
1094            Body::Views { views, arena } => {
1095                std::str::from_utf8(views.get(index)?.bytes_in(arena)?).ok()
1096            }
1097            _ => None,
1098        }
1099    }
1100
1101    /// The variable length bytes at `index`, borrowed without validating or copying them.
1102    ///
1103    /// String data is validated when it enters a vector. Hashing and equality only need its bytes,
1104    /// so those kernels should not pay for UTF-8 validation again on every read.
1105    #[must_use]
1106    pub fn bytes_at(&self, index: usize) -> Option<&[u8]> {
1107        if index >= self.len || !self.validity.is_valid(index) {
1108            return None;
1109        }
1110        match &self.body {
1111            Body::Constant(value) => match value.as_ref() {
1112                Value::Varchar(text) => Some(text.as_bytes()),
1113                Value::Blob(bytes) => Some(bytes),
1114                _ => None,
1115            },
1116            Body::Dictionary { codes, values } => {
1117                values.bytes_at(usize::try_from(*codes.get(index)?).ok()?)
1118            }
1119            Body::Runs { ends, values } => values.bytes_at(run_holding(ends, index)?),
1120            Body::Views { views, arena } => views.get(index)?.bytes_in(arena),
1121            Body::Flat(data) => data.bytes_at(index),
1122            // The same `None` [`Self::text_at`] gives, for the same reason. A compressed row is not
1123            // anywhere in its plain bytes, so there is nothing here to hand back a borrow of, and a
1124            // caller that gets `None` goes to `value_at` and gets the row decompressed into a value.
1125            Body::Coded { .. } | Body::Sequence { .. } | Body::Packed { .. } => None,
1126        }
1127    }
1128
1129    /// The signed integer at `index`, widened, read without building a [`Value`].
1130    ///
1131    /// The integer sibling of [`Self::bytes_at`], and it is here for the same caller. A group by on
1132    /// an integer column compares one key per input row against the group it probed, and doing that
1133    /// through [`Self::value_at`] built and dropped a sixty four byte value a row at a time for a
1134    /// number that was already sitting in the column.
1135    ///
1136    /// Widened to `i128` because that is what [`Data::signed_at`] hands back underneath, and one
1137    /// method that covers every signed width is worth more than five that do not. A caller that
1138    /// wants a narrower type narrows it, which is a range check against a value in a register.
1139    ///
1140    /// The types this answers for are the ones whose flat data is read through `signed_at`, so the
1141    /// five signed integer widths and the decimal, date, time and timestamp types that are stored
1142    /// in them. A decimal answers with its unscaled value, which is the number the column holds.
1143    ///
1144    /// `None` for a null, for an index past the end, for a column of any other type, and for the
1145    /// packed and compressed forms, whose rows are not stored as integers anywhere a read can reach
1146    /// without unpacking. A caller that gets `None` falls back to [`Self::value_at`], which is
1147    /// correct for all of those.
1148    #[must_use]
1149    pub fn signed_at(&self, index: usize) -> Option<i128> {
1150        if index >= self.len || !self.validity.is_valid(index) {
1151            return None;
1152        }
1153        match &self.body {
1154            Body::Flat(data) => data.signed_at(index),
1155            Body::Constant(value) => match value.as_ref() {
1156                Value::TinyInt(x) => Some(i128::from(*x)),
1157                Value::SmallInt(x) => Some(i128::from(*x)),
1158                Value::Integer(x) | Value::Date(x) => Some(i128::from(*x)),
1159                Value::BigInt(x) | Value::Time(x) | Value::Timestamp(x) => Some(i128::from(*x)),
1160                Value::HugeInt(x) | Value::Decimal { unscaled: x, .. } => Some(*x),
1161                _ => None,
1162            },
1163            // The same arithmetic [`Self::value_at`] does on a sequence, so the two agree about a
1164            // sequence that runs off the end of the width it is stored in.
1165            Body::Sequence { start, step } => {
1166                Some(i128::from(start.wrapping_add(step.wrapping_mul(index as i64))))
1167            }
1168            Body::Dictionary { codes, values } => {
1169                values.signed_at(usize::try_from(*codes.get(index)?).ok()?)
1170            }
1171            Body::Runs { ends, values } => values.signed_at(run_holding(ends, index)?),
1172            // The same `None` [`Self::bytes_at`] gives, for the same reason. A packed or compressed
1173            // row is not an integer anywhere until it has been unpacked, and a caller that gets
1174            // `None` goes to `value_at` and gets the row unpacked into a value.
1175            Body::Coded { .. } | Body::Packed { .. } | Body::Views { .. } => None,
1176        }
1177    }
1178
1179    /// Every value in order, as single values.
1180    pub fn iter(&self) -> impl Iterator<Item = Value> + '_ {
1181        (0..self.len).map(|index| self.value_at(index))
1182    }
1183
1184    /// A contiguous run of the values, in the form they are already in.
1185    ///
1186    /// This is the cut [`Self::gather`] cannot do. A gather walks a dictionary to its leaf and
1187    /// copies, so gathering a piece of a dictionary encoded column hands back a flat one, and a
1188    /// caller that only wanted the first thousand rows of a page has silently paid for a copy and
1189    /// thrown the dictionary away. A group by over a dictionary encoded column is the case that
1190    /// cares, and it is most of ClickBench.
1191    ///
1192    /// So each form is cut as itself. A dictionary keeps its dictionary and slices its codes, a
1193    /// sequence stays arithmetic with its start moved along, a constant stays a shorter constant,
1194    /// and a flat body is the one that genuinely has to copy its range.
1195    ///
1196    /// The dictionary itself is shared rather than copied, so a cut is the codes and nothing else.
1197    /// It used to be copied, and on a read of a ClickBench partition that copy was ten percent of
1198    /// the cycles: a page holds one dictionary and is cut into chunk sized pieces, so the whole
1199    /// dictionary was copied once per chunk to be read the same way each time.
1200    ///
1201    /// # Errors
1202    ///
1203    /// If the range runs past the end of the vector, or if the type has no flat layout and the
1204    /// body is one that has to be copied.
1205    pub fn slice(&self, at: usize, len: usize) -> Result<Self> {
1206        let end = at.checked_add(len).ok_or_else(|| Error::internal("a slice that wraps"))?;
1207        if end > self.len {
1208            return Err(Error::internal(format!("rows {at} to {end} of a vector of {}", self.len)));
1209        }
1210        if at == 0 && len == self.len {
1211            return Ok(self.clone());
1212        }
1213        let validity = Validity::from_iter(len, |row| self.validity.is_valid(at + row));
1214        let body = match &self.body {
1215            Body::Constant(value) => Body::Constant(value.clone()),
1216            Body::Sequence { start, step } => {
1217                Body::Sequence { start: start + step * at as i64, step: *step }
1218            }
1219            Body::Dictionary { codes, values } => {
1220                Body::Dictionary { codes: codes[at..end].to_vec(), values: Arc::clone(values) }
1221            }
1222            // The bits are not byte aligned, so a cut either repacks them or moves the row the
1223            // reading starts at. Moving it is one addition and repacking is a pass, and a page is
1224            // cut into chunk sized pieces often enough that the difference is the form.
1225            Body::Packed { words, width, base, offset } => Body::Packed {
1226                words: Arc::clone(words),
1227                width: *width,
1228                base: *base,
1229                offset: offset + at,
1230            },
1231            // The cut a flat string column cannot do. Sixteen bytes a row move and the payload stays
1232            // where the page put it, so taking a chunk out of a column of long strings costs the
1233            // same as taking one out of a column of integers. A flat varchar body copies every byte
1234            // of every long string in the range instead, which is the measurement written down in
1235            // `Chunk::compact`: compaction loses on a varchar column, and this is the half of the
1236            // reason that is about cutting rather than about selecting.
1237            Body::Views { views, arena } => {
1238                Body::Views { views: views[at..end].to_vec(), arena: Arc::clone(arena) }
1239            }
1240            // The spans are absolute positions in the shared codes, so a cut is a run of them and
1241            // nothing has to be rebased. One page of compressed strings, one table, and as many
1242            // chunks over it as the reader wants.
1243            Body::Coded { codes, spans, table } => Body::Coded {
1244                codes: Arc::clone(codes),
1245                spans: spans[at..end].to_vec(),
1246                table: Arc::clone(table),
1247            },
1248            // Only the runs the range touches survive, the first and last of them cut back to where
1249            // the range starts and stops, and every end moved to be relative to the new row zero. A
1250            // cut of a hundred rows out of a column of a hundred million is a handful of runs, which
1251            // is the reason this form is worth cutting as itself rather than copying out.
1252            Body::Runs { ends, values } if len > 0 => {
1253                let first = run_holding(ends, at).unwrap_or(0);
1254                let last = run_holding(ends, end - 1).unwrap_or(first);
1255                let cut: Vec<u32> = ends[first..=last]
1256                    .iter()
1257                    .map(|&stop| stop.min(end as u32) - at as u32)
1258                    .collect();
1259                let values = values.slice(first, last - first + 1)?;
1260                Body::Runs { ends: cut, values: Arc::new(values) }
1261            }
1262            // An empty cut has no run to point at and an empty run length body would be a vector of
1263            // no runs claiming a length, so it comes back as the empty flat vector instead.
1264            Body::Runs { .. } => return self.gather(&[]),
1265            // The one form with nowhere to point, so its range is copied out. A gather is the
1266            // right tool here and does no more than this would: a flat body has no dictionary
1267            // under it for the gather to flatten.
1268            Body::Flat(_) => {
1269                let indices: Vec<u32> =
1270                    (at..end).map(|row| u32::try_from(row).unwrap_or(u32::MAX)).collect();
1271                return self.gather(&indices);
1272            }
1273        };
1274        Ok(Self { ty: self.ty.clone(), len, validity, body })
1275    }
1276
1277    /// The same values in flat form.
1278    ///
1279    /// Flattening a vector that is already flat is free. Flattening any other form costs a copy,
1280    /// which is exactly why the other forms exist and why nothing on the hot path should call
1281    /// this. It is here for the operators that genuinely cannot do better and for the tests that
1282    /// check the other forms against it.
1283    ///
1284    /// A call that copies counts itself against [`Cause::Flatten`], because a flatten on a hot path
1285    /// is the most expensive thing in this crate and the only way to find one is to have the number.
1286    /// A call on a vector that is already flat does not count, since it neither copies nor gives
1287    /// anything up.
1288    ///
1289    /// # Errors
1290    ///
1291    /// If the type is one this crate cannot store flat yet, which today means the nested types.
1292    pub fn flatten(&self) -> Result<Self> {
1293        if let Body::Flat(_) = self.body {
1294            return Ok(self.clone());
1295        }
1296        slow::took(Cause::Flatten);
1297        self.copied((0..self.len).collect(), false)
1298    }
1299
1300    /// The values at the given positions, copied, in a form that does not point back at this vector.
1301    ///
1302    /// This is the copying counterpart to [`Self::dictionary`], and the two are the two halves of
1303    /// the decision `spec/07-execution.md` section 7.1 describes. Which half is right is measured
1304    /// rather than argued, and [`Chunk::compact`](crate::Chunk::compact) is where the measurement
1305    /// is written down.
1306    ///
1307    /// A dictionary chain is walked to its leaf first and the codes composed on the way down, so the
1308    /// copy runs once over the data rather than once per level, and a position that is null at any
1309    /// level comes out null here. The copy is a typed loop per physical layout rather than a `Value`
1310    /// per row, which is the whole point of it and is what [`Self::flatten`] now goes through too.
1311    ///
1312    /// # Errors
1313    ///
1314    /// If the type has no flat layout, which today means the nested types.
1315    pub fn gather(&self, indices: &[u32]) -> Result<Self> {
1316        self.copied(indices.iter().map(|&index| index as usize).collect(), true)
1317    }
1318
1319    /// The copy both [`Self::gather`] and [`Self::flatten`] are.
1320    ///
1321    /// `forms_stay` is the one thing the two want differently. A gather of a constant is a shorter
1322    /// constant and copying it out would be a thousand writes of the same value for nothing, and a
1323    /// gather of string views is a shorter run of views over the same arena rather than a copy of
1324    /// the bytes. Flattening promises flat form to a caller that is about to read the data slice, so
1325    /// for that one both of them have to be written out.
1326    fn copied(&self, at: Vec<usize>, forms_stay: bool) -> Result<Self> {
1327        let rows = at.len();
1328        let (at, leaf) = self.resolve(at);
1329        let live: Vec<bool> = at.iter().map(|&index| index != NOWHERE).collect();
1330        let validity = Validity::from_run(&live);
1331        let body = match &leaf.body {
1332            // Every position holds the same value, so the only thing the gather can change is the
1333            // length and which positions are null. A gather with no null in it is still a constant.
1334            Body::Constant(value) => {
1335                if forms_stay && matches!(validity, Validity::AllValid) {
1336                    return Ok(Self::constant(self.ty.clone(), value.as_ref().clone(), rows));
1337                }
1338                let mut data = empty_data_for(&self.ty)?;
1339                for &index in &at {
1340                    push_value(&mut data, if index == NOWHERE { &Value::Null } else { value })?;
1341                }
1342                Body::Flat(data)
1343            }
1344            // A sequence is arithmetic rather than storage, so the gather is the arithmetic done at
1345            // the positions asked for, and a null writes the zero every other layout writes.
1346            Body::Sequence { start, step } => Body::Flat(Data::Int64(
1347                at.iter()
1348                    .map(|&index| if index == NOWHERE { 0 } else { start + step * index as i64 })
1349                    .collect(),
1350            )),
1351            // A flat body with no values is the untyped null, so every position asked for is null
1352            // whatever was asked for. Going through the copy would build a run of no values and
1353            // call it `rows` long, which is a vector whose length and data disagree.
1354            Body::Flat(Data::Empty) => {
1355                return Ok(Self::constant(self.ty.clone(), Value::Null, rows));
1356            }
1357            Body::Flat(data) => Body::Flat(copy_of(data, &at)),
1358            // The one form whose copy is arithmetic rather than a move of bytes. It goes through a
1359            // typed loop per layout the way the flat copy does, because the alternative is a `Value`
1360            // per row and this is the path a flatten of a scanned column takes.
1361            Body::Packed { words, width, base, offset } => {
1362                Body::Flat(unpack(&self.ty, words, *offset, *width, *base, &at)?)
1363            }
1364            // A gather keeps the form, which is what makes selecting rows out of a string column
1365            // cost sixteen bytes a row instead of the bytes of the strings. The arena it shares is
1366            // the whole arena and not the part the kept rows point at, so a selection that throws
1367            // most of a page away goes on holding the page. That is the trade the form is: a cut and
1368            // a filter are cheap and the memory comes back when the last vector over the page goes,
1369            // and a caller that wants the bytes narrowed asks for a flatten.
1370            Body::Views { views, arena } if forms_stay => Body::Views {
1371                views: at
1372                    .iter()
1373                    .map(|&index| views.get(index).copied().unwrap_or_else(StringView::empty))
1374                    .collect(),
1375                arena: Arc::clone(arena),
1376            },
1377            // Flattening promises a data slice, so the bytes are copied out into an arena of their
1378            // own and the shared one is let go of. The total is known before any of it is copied,
1379            // the way the flat copy works it out, so the new arena is one allocation.
1380            Body::Views { views, arena } => {
1381                let mut out = StringColumn::with_capacity(at.len());
1382                out.reserve_bytes(
1383                    at.iter()
1384                        .filter_map(|&index| views.get(index))
1385                        .filter(|view| !view.is_inline())
1386                        .map(StringView::len)
1387                        .sum(),
1388                );
1389                for &index in &at {
1390                    let bytes = views.get(index).and_then(|view| view.bytes_in(arena));
1391                    out.push_bytes(bytes.unwrap_or_default());
1392                }
1393                Body::Flat(Data::Varlen(out))
1394            }
1395            // A gather keeps the form, because the codes do not move and a span survives being put
1396            // in an order the codes are not in. A position that resolved to nowhere gets the empty
1397            // span, which decompresses to no bytes, which is the zero every other layout writes.
1398            Body::Coded { codes, spans, table } if forms_stay => Body::Coded {
1399                codes: Arc::clone(codes),
1400                spans: at
1401                    .iter()
1402                    .map(|&index| spans.get(index).copied().unwrap_or((0, 0)))
1403                    .collect(),
1404                table: Arc::clone(table),
1405            },
1406            // Flattening decompresses, which is the price of the data slice it promises. The scratch
1407            // buffer is reused across rows, so this is one allocation for the whole column rather
1408            // than one per row the way reading it a value at a time would be.
1409            Body::Coded { codes, spans, table } => {
1410                let mut out = StringColumn::with_capacity(at.len());
1411                let mut scratch = Vec::new();
1412                for &index in &at {
1413                    scratch.clear();
1414                    let span = spans
1415                        .get(index)
1416                        .and_then(|&(from, to)| codes.get(from as usize..to as usize));
1417                    if let Some(span) = span {
1418                        table.decompress(span, &mut scratch)?;
1419                    }
1420                    out.push_bytes(&scratch);
1421                }
1422                Body::Flat(Data::Varlen(out))
1423            }
1424            // Unreachable, because `resolve` walks past both of the forms that point at another
1425            // vector and stops at the first body that does not.
1426            Body::Dictionary { .. } | Body::Runs { .. } => {
1427                return Err(Error::internal(
1428                    "a form that points somewhere survived being resolved",
1429                ));
1430            }
1431        };
1432        Ok(Self { ty: self.ty.clone(), len: rows, validity, body })
1433    }
1434
1435    /// Where each wanted position lives in the first body that is not a dictionary, and that body.
1436    ///
1437    /// A position that is null anywhere on the way down, or past the end of anything on the way
1438    /// down, comes back as [`NOWHERE`]. That single sentinel is what keeps the copy loop from
1439    /// carrying a validity mask alongside the positions it is already walking.
1440    fn resolve(&self, mut at: Vec<usize>) -> (Vec<usize>, &Self) {
1441        let mut source = self;
1442        loop {
1443            for slot in &mut at {
1444                if *slot >= source.len || !source.validity.is_valid(*slot) {
1445                    *slot = NOWHERE;
1446                }
1447            }
1448            source = match &source.body {
1449                Body::Dictionary { codes, values } => {
1450                    for slot in &mut at {
1451                        *slot = match codes.get(*slot) {
1452                            Some(&code) => code as usize,
1453                            None => NOWHERE,
1454                        };
1455                    }
1456                    values.as_ref()
1457                }
1458                // A run length body is a dictionary whose code is worked out from the position
1459                // rather than stored, so the walk down is the same walk with a search where the
1460                // lookup was. `NOWHERE` searches for nothing and stays `NOWHERE`.
1461                Body::Runs { ends, values } => {
1462                    for slot in &mut at {
1463                        *slot = run_holding(ends, *slot).unwrap_or(NOWHERE);
1464                    }
1465                    values.as_ref()
1466                }
1467                _ => return (at, source),
1468            };
1469        }
1470    }
1471}
1472
1473/// So that a kernel can take its operands as either a list of vectors or a list of references.
1474///
1475/// A caller that built a `Vec<Vector>` and a caller whose operands are already somewhere else, in a
1476/// chunk or in an evaluator's scratch, want the same kernel. Without this the second kind has to
1477/// clone every operand into a `Vec` to satisfy the signature, and a clone of a vector is a copy of
1478/// the whole column, so the type would be charging real memory traffic for nothing.
1479impl AsRef<Vector> for Vector {
1480    fn as_ref(&self) -> &Vector {
1481        self
1482    }
1483}
1484
1485/// The bits of a packed vector and what they mean, for a kernel that wants to stay in code space.
1486///
1487/// Borrowed from the vector rather than owning anything, so getting one costs nothing and a kernel
1488/// that finds it cannot use them has given up nothing by asking.
1489#[derive(Debug, Clone, Copy)]
1490pub struct Packed<'a> {
1491    words: &'a [u64],
1492    width: u32,
1493    base: i128,
1494    offset: usize,
1495}
1496
1497impl Packed<'_> {
1498    /// How many bits one code takes, between one and [`PACKED_WIDTH_MAX`].
1499    #[must_use]
1500    pub fn width(&self) -> u32 {
1501        self.width
1502    }
1503
1504    /// What zero means, so that the value of a row is the base plus its code.
1505    #[must_use]
1506    pub fn base(&self) -> i128 {
1507        self.base
1508    }
1509
1510    /// The largest value this vector can be holding, whatever it is actually holding.
1511    ///
1512    /// With [`Self::base`] this is the pair a comparison kernel wants first. A literal outside the
1513    /// two answers every row of the vector the same way, which is a whole chunk decided without a
1514    /// bit being read, and that is the case a zone map would have caught if there were one here.
1515    #[must_use]
1516    pub fn ceiling(&self) -> i128 {
1517        self.base + i128::from(u64::MAX >> (u64::BITS - self.width))
1518    }
1519
1520    /// The code of row `row`, which is its value minus [`Self::base`].
1521    ///
1522    /// Out of range rows read as zero rather than panicking, the way every other accessor in this
1523    /// file answers for a row that is not there.
1524    #[must_use]
1525    pub fn code(&self, row: usize) -> u64 {
1526        code_at(self.words, (self.offset + row) * self.width as usize, self.width)
1527    }
1528
1529    /// Which code a value would have, and `None` for a value this vector cannot be holding.
1530    ///
1531    /// The translation a comparison does once per vector so that it does not have to unpack once per
1532    /// row. `None` is the useful answer rather than a failure: it says the literal is outside the
1533    /// packed range, so every row compares against it the same way.
1534    #[must_use]
1535    pub fn code_of(&self, value: i128) -> Option<u64> {
1536        u64::try_from(value.checked_sub(self.base)?).ok().filter(|&code| code <= self.mask())
1537    }
1538
1539    /// The largest code the width allows.
1540    fn mask(&self) -> u64 {
1541        u64::MAX >> (u64::BITS - self.width)
1542    }
1543}
1544
1545/// The widest a packed code is allowed to be.
1546///
1547/// Sixty three rather than sixty four so that a mask is `u64::MAX >> (64 - width)` with no shift of
1548/// a whole word in it, and reading a code is one branch on whether it straddles rather than two. A
1549/// sixty four bit code saves nothing anyway, since it is the layout it came from.
1550pub const PACKED_WIDTH_MAX: u32 = 63;
1551
1552/// How much smaller packing has to be before it is worth the shift and the mask on every read.
1553///
1554/// Two, so a column packs when the bits come to half the flat size or less. A column that would save
1555/// a tenth stays flat, because a tenth of a column is not worth turning every read of it into
1556/// arithmetic, and the whole argument for the form is that a narrow column saves most of itself.
1557pub const PACKING_PAYS_AT: usize = 2;
1558
1559/// How much smaller compressing has to be before it is worth a decompression on every read.
1560///
1561/// Two, the same rule packing follows and for the same reason. FSST gets about that on text, so a
1562/// column of English or of URLs compresses and a column of short codes or of random bytes does not,
1563/// which is the right answer for both.
1564pub const FSST_PAYS_AT: usize = 2;
1565
1566/// The codes of a compressed column and the table they are against.
1567///
1568/// Handed out by [`Vector::coded_parts`] so a kernel can work in code space. Nothing here
1569/// decompresses, which is the point: [`Self::encode`] puts the literal into the same space the rows
1570/// are already in, and after that an equality test is a byte slice comparison.
1571#[derive(Debug, Clone, Copy)]
1572pub struct Coded<'a> {
1573    codes: &'a [u8],
1574    spans: &'a [(u32, u32)],
1575    table: &'a SymbolTable,
1576}
1577
1578impl Coded<'_> {
1579    /// The table every row in this vector is compressed against.
1580    #[must_use]
1581    pub fn table(&self) -> &SymbolTable {
1582        self.table
1583    }
1584
1585    /// The code bytes of one row, still compressed.
1586    #[must_use]
1587    pub fn row(&self, row: usize) -> Option<&[u8]> {
1588        let &(from, to) = self.spans.get(row)?;
1589        self.codes.get(from as usize..to as usize)
1590    }
1591
1592    /// Some bytes in the code space this vector is in.
1593    ///
1594    /// The literal side of an equality filter. Compressing is a function of the table and the bytes,
1595    /// so two strings compress to the same codes exactly when they are the same string, and an
1596    /// equality test on the codes is an equality test on the strings with no decompression in it.
1597    #[must_use]
1598    pub fn encode(&self, bytes: &[u8]) -> Vec<u8> {
1599        let mut out = Vec::with_capacity(bytes.len());
1600        self.table.compress(bytes, &mut out);
1601        out
1602    }
1603}
1604
1605/// How many words hold `len` codes of `width` bits.
1606fn words_for(len: usize, width: u32) -> usize {
1607    (len * width as usize).div_ceil(u64::BITS as usize)
1608}
1609
1610/// The lowest and highest value a type's layout can hold, and `None` for a type with no integer one.
1611///
1612/// This is also the test of whether a type can be packed at all, and it is the only one, so the
1613/// layouts listed here and the layouts [`pack`] and [`unpack`] know how to walk are the same list
1614/// from the same macro and cannot drift apart.
1615fn layout_range(ty: &LogicalType) -> Option<(i128, i128)> {
1616    use rudb_common::PhysicalType as P;
1617    macro_rules! ranges {
1618        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
1619            match ty.physical() {
1620                $(P::$variant => Some((i128::from(<$native>::MIN), i128::from(<$native>::MAX))),)+
1621                _ => None,
1622            }
1623        };
1624    }
1625    crate::for_each_layout!(exact, ranges)
1626}
1627
1628/// The lowest and highest value in the first `len` slots of a run of integer data.
1629///
1630/// `None` for data that is not integers, which is what says a column cannot be packed. The null
1631/// slots are in the span, holding whatever zero was written into them, which
1632/// [`Vector::bit_packed`] says more about.
1633fn span_of(data: &Data, len: usize) -> Option<(i128, i128)> {
1634    macro_rules! spans {
1635        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
1636            match data {
1637                $(Data::$variant(values) => {
1638                    let mut low = i128::MAX;
1639                    let mut high = i128::MIN;
1640                    for &value in values.as_slice().iter().take(len) {
1641                        let value = i128::from(value);
1642                        low = low.min(value);
1643                        high = high.max(value);
1644                    }
1645                    (low <= high).then_some((low, high))
1646                })+
1647                _ => None,
1648            }
1649        };
1650    }
1651    crate::for_each_layout!(exact, spans)
1652}
1653
1654/// The first `len` values of a run of integer data, written out as codes of `width` bits from `base`.
1655fn pack(data: &Data, len: usize, base: i128, width: u32) -> Vec<u64> {
1656    let mut words = vec![0u64; words_for(len, width)];
1657    macro_rules! packing {
1658        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
1659            match data {
1660                $(Data::$variant(values) => {
1661                    for (row, &value) in values.as_slice().iter().take(len).enumerate() {
1662                        // In range because `base` and `width` came from the span of this same run.
1663                        let code = u64::try_from(i128::from(value) - base).unwrap_or(0);
1664                        write_code(&mut words, row * width as usize, width, code);
1665                    }
1666                })+
1667                _ => {}
1668            }
1669        };
1670    }
1671    crate::for_each_layout!(exact, packing);
1672    words
1673}
1674
1675/// The codes at the given rows, unpacked into the flat layout the type calls for.
1676///
1677/// A row of [`NOWHERE`] writes the layout's zero, which is the rule [`copy_of`] follows for the same
1678/// reason: every layout here is a parallel array to a validity mask, so a null takes a slot.
1679///
1680/// # Errors
1681///
1682/// If the type has no flat layout, which a packed vector cannot have and which is checked when one
1683/// is built, so an error here is a bug rather than a caller mistake.
1684fn unpack(
1685    ty: &LogicalType,
1686    words: &[u64],
1687    offset: usize,
1688    width: u32,
1689    base: i128,
1690    at: &[usize],
1691) -> Result<Data> {
1692    let mut out = empty_data_for(ty)?;
1693    let value_of = |row: usize| {
1694        if row == NOWHERE {
1695            return None;
1696        }
1697        Some(base + i128::from(code_at(words, (offset + row) * width as usize, width)))
1698    };
1699    macro_rules! unpacking {
1700        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
1701            match &mut out {
1702                $(Data::$variant(values) => {
1703                    values.reserve(at.len());
1704                    for &row in at {
1705                        // In range because both ends of it were checked when the vector was built.
1706                        let value = value_of(row)
1707                            .and_then(|value| <$native>::try_from(value).ok())
1708                            .unwrap_or($zero);
1709                        values.push(value);
1710                    }
1711                })+
1712                _ => {
1713                    return Err(Error::internal(format!(
1714                        "a {ty} vector was packed, which no integer layout allows"
1715                    )));
1716                }
1717            }
1718        };
1719    }
1720    crate::for_each_layout!(exact, unpacking);
1721    Ok(out)
1722}
1723
1724/// The `width` bits starting at `bit`, low end first.
1725///
1726/// Zero for bits past the end of the words, which keeps a read of a row that is not there from
1727/// panicking and matches what every other accessor here does with one.
1728fn code_at(words: &[u64], bit: usize, width: u32) -> u64 {
1729    let word = bit / u64::BITS as usize;
1730    let shift = (bit % u64::BITS as usize) as u32;
1731    let mask = u64::MAX >> (u64::BITS - width);
1732    let low = words.get(word).copied().unwrap_or(0) >> shift;
1733    let taken = u64::BITS - shift;
1734    if taken >= width {
1735        return low & mask;
1736    }
1737    // The code straddles two words, and `taken` is under the width here so it is under sixty four,
1738    // which is what makes the shift below one the hardware will do rather than one it refuses.
1739    let high = words.get(word + 1).copied().unwrap_or(0) << taken;
1740    (low | high) & mask
1741}
1742
1743/// Writes `width` bits of `code` starting at `bit`, over words that started out zero.
1744fn write_code(words: &mut [u64], bit: usize, width: u32, code: u64) {
1745    let word = bit / u64::BITS as usize;
1746    let shift = (bit % u64::BITS as usize) as u32;
1747    words[word] |= code << shift;
1748    let taken = u64::BITS - shift;
1749    if taken < width {
1750        words[word + 1] |= code >> taken;
1751    }
1752}
1753
1754/// One level of dictionary out of however many levels were handed to [`Vector::dictionary`].
1755///
1756/// Every dictionary in the system is built through that constructor and every one of them comes
1757/// through here first, so the invariant this maintains is that the vector a dictionary points at is
1758/// never itself a dictionary that could have been composed away. That makes the work a single `if`
1759/// rather than a loop: the inner vector was already composed when it was built, so composing the
1760/// outer codes through it leaves the result no deeper than the inner vector already was.
1761///
1762/// The codes are indexed rather than fetched with `get`, because the caller has already walked the
1763/// whole outer array to check that every code is in range and the inner array is exactly as long as
1764/// the vector those codes were checked against.
1765fn compose(codes: Vec<u32>, values: Vector) -> (Vec<u32>, Vector) {
1766    // A dictionary carrying a validity of its own is one whose nulls live at this level rather than
1767    // in the values, which is the one thing composition cannot carry down with it.
1768    if !matches!(values.validity, Validity::AllValid) {
1769        return (codes, values);
1770    }
1771    let Vector { ty, len, validity, body } = values;
1772    match body {
1773        Body::Dictionary { codes: inner, values: leaf } => {
1774            debug_assert!(
1775                !matches!(leaf.body, Body::Dictionary { .. })
1776                    || !matches!(leaf.validity, Validity::AllValid),
1777                "a dictionary was stacked on a dictionary without going through the constructor"
1778            );
1779            // The leaf is shared, so taking it out of the `Arc` copies it when something else is
1780            // still holding the same dictionary. That is the rare path: a dictionary over a
1781            // dictionary only arrives from a caller that built one that way, and the cut that made
1782            // sharing worth doing produces neither.
1783            (codes.iter().map(|&code| inner[code as usize]).collect(), Arc::unwrap_or_clone(leaf))
1784        }
1785        body => (codes, Vector { ty, len, validity, body }),
1786    }
1787}
1788
1789/// How many rows a run has to cover on average before run length encoding is smaller.
1790///
1791/// A run costs its value plus the four bytes of its end, so on a four byte column a run of two rows
1792/// breaks even and a run of three wins. Wider columns win sooner and narrower ones later, and this
1793/// is the one ratio for all of them because a threshold per width is a table that has to be right
1794/// nine times rather than once. It is a constant with a name so that the sweep that eventually moves
1795/// it has something to move.
1796const RUNS_PAY_AT: usize = 2;
1797
1798/// Which run holds `row`, given ends that are exclusive and increasing.
1799///
1800/// A binary search rather than a scan, because the callers that ask this are the ones that are not
1801/// walking the runs in order: a single value read out of a result set, or a gather at scattered
1802/// positions. Anything walking in order should be reading [`Vector::run_parts`] instead, which is
1803/// what the form is for.
1804fn run_holding(ends: &[u32], row: usize) -> Option<usize> {
1805    let row = u32::try_from(row).ok()?;
1806    let run = match ends.binary_search(&row) {
1807        // The ends are exclusive, so landing exactly on one means the row is the first of the next.
1808        Ok(at) => at + 1,
1809        Err(at) => at,
1810    };
1811    (run < ends.len()).then_some(run)
1812}
1813
1814/// The row each run ends at, for a flat body read alongside the validity that goes with it.
1815///
1816/// Two adjacent nulls are one run, because a reader of either gets a null and cannot tell them
1817/// apart. A null between two equal values is three runs for the same reason, since the null is a
1818/// value of the column as far as anything reading it is concerned.
1819///
1820/// The comparison is per layout rather than per `Value`, which is the whole reason this is a macro.
1821/// A `Value` a row would allocate a string per row on a `VARCHAR` column and would be the exact
1822/// defect `cargo xtask rowloop` exists to fail the build on.
1823fn boundaries(data: &Data, validity: &Validity, len: usize) -> Vec<u32> {
1824    if len == 0 {
1825        return Vec::new();
1826    }
1827    let breaks = |ends: &mut Vec<u32>, mut differs: Box<dyn FnMut(usize, usize) -> bool + '_>| {
1828        for row in 1..len {
1829            let same = match (validity.is_valid(row), validity.is_valid(row - 1)) {
1830                (false, false) => true,
1831                (true, true) => !differs(row, row - 1),
1832                _ => false,
1833            };
1834            if !same {
1835                ends.push(u32::try_from(row).unwrap_or(u32::MAX));
1836            }
1837        }
1838        ends.push(u32::try_from(len).unwrap_or(u32::MAX));
1839    };
1840    let mut ends = Vec::new();
1841    macro_rules! walked {
1842        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
1843            match data {
1844                // No values at all, so every row is the same null and the column is one run.
1845                Data::Empty => ends.push(u32::try_from(len).unwrap_or(u32::MAX)),
1846                $(Data::$variant(values) => {
1847                    breaks(&mut ends, Box::new(|a, b| values.get(a) != values.get(b)));
1848                })+
1849                Data::Varlen(values) => {
1850                    breaks(&mut ends, Box::new(|a, b| values.bytes(a) != values.bytes(b)));
1851                }
1852            }
1853        };
1854    }
1855    crate::for_each_layout!(fixed, walked);
1856    ends
1857}
1858
1859/// The position of a value that is not anywhere, because it is null or out of range.
1860///
1861/// `usize::MAX` rather than an `Option<usize>`, because the copy loop's bounds check rejects it for
1862/// free and an `Option` would put a second branch next to the one already there.
1863const NOWHERE: usize = usize::MAX;
1864
1865/// A run of data copied at the given positions, with a zero wherever the position is [`NOWHERE`].
1866///
1867/// A zero and not a skip, because every layout here is a parallel array to a validity mask and a
1868/// short one would put every value after the first null at the wrong index. It is the same rule
1869/// [`push_value`] follows for a null.
1870fn copy_of(data: &Data, at: &[usize]) -> Data {
1871    macro_rules! copied {
1872        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
1873            match data {
1874                Data::Empty => Data::Empty,
1875                $(Data::$variant(values) => {
1876                    let mut out = Buffer::with_capacity(at.len());
1877                    for &index in at {
1878                        // One bounds check rather than a null test and a bounds check, because
1879                        // `NOWHERE` is past the end of every slice there can be.
1880                        out.push(values.get(index).copied().unwrap_or($zero));
1881                    }
1882                    Data::$variant(out)
1883                })+
1884                // The one layout where a gather is a copy of bytes rather than a copy of fixed
1885                // width slots, and the reason compaction is a decision rather than a default on a
1886                // string column.
1887                Data::Varlen(values) => {
1888                    let mut out = StringColumn::with_capacity(at.len());
1889                    // The bytes are known before any of them are copied, because a view carries its
1890                    // length and the wanted positions are already in hand, so the arena is one
1891                    // allocation rather than a run of doublings that each copy what the last one
1892                    // copied.
1893                    let views = values.views();
1894                    out.reserve_bytes(
1895                        at.iter()
1896                            .filter_map(|&index| views.get(index))
1897                            .filter(|view| !view.is_inline())
1898                            .map(StringView::len)
1899                            .sum(),
1900                    );
1901                    for &index in at {
1902                        out.push_from(values, index);
1903                    }
1904                    Data::Varlen(out)
1905                }
1906            }
1907        };
1908    }
1909    crate::for_each_layout!(fixed, copied)
1910}
1911
1912/// The physical layout a run of data is in, for the check that it matches its type.
1913///
1914/// The two enums name their variants the same way on purpose, so this is one generated arm rather
1915/// than sixteen chances to pair the wrong two up.
1916fn layout_of(data: &Data) -> rudb_common::PhysicalType {
1917    use rudb_common::PhysicalType as P;
1918    macro_rules! layouts {
1919        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
1920            match data {
1921                Data::Empty => P::Empty,
1922                $(Data::$variant(_) => P::$variant,)+
1923            }
1924        };
1925    }
1926    crate::for_each_layout!(all, layouts)
1927}
1928
1929/// One value out of a run of data, given what the run means.
1930///
1931/// The match is on the logical type rather than on the data, because the data cannot tell a `DATE`
1932/// from an `INTEGER` and that is the whole reason the two are kept apart.
1933fn value_from(ty: &LogicalType, data: &Data, index: usize) -> Value {
1934    let signed = || data.signed_at(index);
1935    let unsigned = || data.unsigned_at(index);
1936    let value = match ty {
1937        LogicalType::Boolean => match data {
1938            Data::Bool(v) => v.get(index).map(|&x| Value::Boolean(x)),
1939            _ => None,
1940        },
1941        LogicalType::TinyInt => signed().and_then(|x| i8::try_from(x).ok()).map(Value::TinyInt),
1942        LogicalType::SmallInt => signed().and_then(|x| i16::try_from(x).ok()).map(Value::SmallInt),
1943        LogicalType::Integer => signed().and_then(|x| i32::try_from(x).ok()).map(Value::Integer),
1944        LogicalType::BigInt => signed().and_then(|x| i64::try_from(x).ok()).map(Value::BigInt),
1945        LogicalType::HugeInt => signed().map(Value::HugeInt),
1946        LogicalType::UTinyInt => unsigned().and_then(|x| u8::try_from(x).ok()).map(Value::UTinyInt),
1947        LogicalType::USmallInt => {
1948            unsigned().and_then(|x| u16::try_from(x).ok()).map(Value::USmallInt)
1949        }
1950        LogicalType::UInteger => {
1951            unsigned().and_then(|x| u32::try_from(x).ok()).map(Value::UInteger)
1952        }
1953        LogicalType::UBigInt => unsigned().and_then(|x| u64::try_from(x).ok()).map(Value::UBigInt),
1954        LogicalType::UHugeInt => unsigned().map(Value::UHugeInt),
1955        LogicalType::Float => match data {
1956            Data::Float32(v) => v.get(index).map(|&x| Value::Float(x)),
1957            _ => None,
1958        },
1959        LogicalType::Double => match data {
1960            Data::Float64(v) => v.get(index).map(|&x| Value::Double(x)),
1961            _ => None,
1962        },
1963        LogicalType::Decimal { width, scale } => {
1964            signed().map(|unscaled| Value::Decimal { unscaled, width: *width, scale: *scale })
1965        }
1966        LogicalType::Varchar | LogicalType::Blob | LogicalType::Bit => {
1967            data.bytes_at(index).map(|bytes| bytes_as(ty, bytes))
1968        }
1969        LogicalType::Date => signed().and_then(|x| i32::try_from(x).ok()).map(Value::Date),
1970        LogicalType::Time | LogicalType::TimeTz => {
1971            signed().and_then(|x| i64::try_from(x).ok()).map(Value::Time)
1972        }
1973        LogicalType::Timestamp
1974        | LogicalType::TimestampS
1975        | LogicalType::TimestampMs
1976        | LogicalType::TimestampNs
1977        | LogicalType::TimestampTz => {
1978            signed().and_then(|x| i64::try_from(x).ok()).map(Value::Timestamp)
1979        }
1980        LogicalType::Interval => match data {
1981            Data::Interval(v) => {
1982                v.get(index).map(|&(months, days, micros)| Value::Interval { months, days, micros })
1983            }
1984            _ => None,
1985        },
1986        _ => None,
1987    };
1988    value.unwrap_or(Value::Null)
1989}
1990
1991/// One row of a string column as a value, given what its bytes are meant to be read as.
1992///
1993/// Both forms that hold strings come through here, so a row that is a `BLOB` in a flat column is a
1994/// `BLOB` in a string view column too. Bytes that are not text in a `VARCHAR` column are a null
1995/// rather than a panic, since everything that got in went in as a string and a column that has
1996/// something else in it is a bug somewhere earlier that a read should not turn into a crash.
1997fn bytes_as(ty: &LogicalType, bytes: &[u8]) -> Value {
1998    match ty {
1999        LogicalType::Varchar => {
2000            std::str::from_utf8(bytes).map_or(Value::Null, |text| Value::Varchar(text.to_owned()))
2001        }
2002        LogicalType::Blob | LogicalType::Bit => Value::Blob(bytes.to_vec()),
2003        _ => Value::Null,
2004    }
2005}
2006
2007/// An empty run of data of the right layout for a type.
2008fn empty_data_for(ty: &LogicalType) -> Result<Data> {
2009    use rudb_common::PhysicalType as P;
2010    macro_rules! empties {
2011        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
2012            match ty.physical() {
2013                P::Empty => Data::Empty,
2014                $(P::$variant => Data::$variant(Buffer::new()),)+
2015                P::Varlen => Data::Varlen(StringColumn::new()),
2016                other => {
2017                    return Err(Error::not_implemented(format!(
2018                        "a flat vector of {other:?} data, which arrives with the storage layer"
2019                    )));
2020                }
2021            }
2022        };
2023    }
2024    Ok(crate::for_each_layout!(fixed, empties))
2025}
2026
2027/// Appends one value to a run of data, or a zero of the right shape when it is null.
2028///
2029/// The zero matters. A null still occupies a position, the validity mask is what says it is null,
2030/// and a run of data with a hole in it would put every value after the hole in the wrong place.
2031fn push_value(data: &mut Data, value: &Value) -> Result<()> {
2032    macro_rules! push {
2033        ($vec:expr, $variant:path, $zero:expr) => {
2034            match value {
2035                Value::Null => $vec.push($zero),
2036                $variant(x) => $vec.push(*x),
2037                other => {
2038                    return Err(Error::internal(format!(
2039                        "{other:?} does not belong in this vector"
2040                    )));
2041                }
2042            }
2043        };
2044    }
2045    // A decimal is stored as its unscaled integer in whatever width its precision needs, which
2046    // `LogicalType::physical` decides and which is why the same `Value::Decimal` is at home in four
2047    // different runs. The narrowing cannot fail for a value the binder produced, because the width
2048    // that chose the run is the width in the value, but it is checked rather than assumed because
2049    // an unchecked cast here would silently store a different number.
2050    macro_rules! decimal {
2051        ($vec:expr, $ty:ty, $unscaled:expr) => {
2052            match <$ty>::try_from(*$unscaled) {
2053                Ok(x) => $vec.push(x),
2054                Err(_) => {
2055                    return Err(Error::internal(format!(
2056                        "an unscaled decimal of {} does not fit the run its precision chose",
2057                        $unscaled
2058                    )));
2059                }
2060            }
2061        };
2062    }
2063    match data {
2064        Data::Empty => {}
2065        Data::Bool(v) => push!(v, Value::Boolean, false),
2066        Data::Int8(v) => push!(v, Value::TinyInt, 0),
2067        Data::Int16(v) => match value {
2068            Value::Null => v.push(0),
2069            Value::SmallInt(x) => v.push(*x),
2070            Value::Decimal { unscaled, .. } => decimal!(v, i16, unscaled),
2071            other => return Err(Error::internal(format!("{other:?} is not a 16 bit value"))),
2072        },
2073        Data::Int32(v) => match value {
2074            Value::Null => v.push(0),
2075            Value::Integer(x) | Value::Date(x) => v.push(*x),
2076            Value::Decimal { unscaled, .. } => decimal!(v, i32, unscaled),
2077            other => return Err(Error::internal(format!("{other:?} is not a 32 bit value"))),
2078        },
2079        Data::Int64(v) => match value {
2080            Value::Null => v.push(0),
2081            Value::BigInt(x) | Value::Time(x) | Value::Timestamp(x) => v.push(*x),
2082            Value::Decimal { unscaled, .. } => decimal!(v, i64, unscaled),
2083            other => return Err(Error::internal(format!("{other:?} is not a 64 bit value"))),
2084        },
2085        Data::Int128(v) => match value {
2086            Value::Null => v.push(0),
2087            Value::HugeInt(x) => v.push(*x),
2088            Value::Decimal { unscaled, .. } => v.push(*unscaled),
2089            other => return Err(Error::internal(format!("{other:?} is not a 128 bit value"))),
2090        },
2091        Data::UInt8(v) => push!(v, Value::UTinyInt, 0),
2092        Data::UInt16(v) => push!(v, Value::USmallInt, 0),
2093        Data::UInt32(v) => push!(v, Value::UInteger, 0),
2094        Data::UInt64(v) => push!(v, Value::UBigInt, 0),
2095        Data::UInt128(v) => push!(v, Value::UHugeInt, 0),
2096        Data::Float32(v) => push!(v, Value::Float, 0.0),
2097        Data::Float64(v) => push!(v, Value::Double, 0.0),
2098        Data::Interval(v) => match value {
2099            Value::Null => v.push((0, 0, 0)),
2100            Value::Interval { months, days, micros } => v.push((*months, *days, *micros)),
2101            other => return Err(Error::internal(format!("{other:?} is not an interval"))),
2102        },
2103        Data::Varlen(column) => match value {
2104            Value::Null => {
2105                column.push("");
2106            }
2107            Value::Varchar(text) => {
2108                column.push(text);
2109            }
2110            // A blob goes in as the bytes it is. The column stores a length and some bytes either
2111            // way, so text is the reading of one rather than a different column, and a blob that
2112            // is not UTF-8 is stored exactly like one that happens to be.
2113            Value::Blob(bytes) => {
2114                column.push_bytes(bytes);
2115            }
2116            other => return Err(Error::internal(format!("{other:?} is not a string"))),
2117        },
2118    }
2119    Ok(())
2120}
2121
2122#[cfg(test)]
2123mod tests {
2124    use std::sync::Arc;
2125
2126    use rudb_common::{LogicalType, Value};
2127
2128    use super::{Body, Data, FSST_PAYS_AT, Form, VECTOR_SIZE, Vector};
2129    use crate::buffer::Buffer;
2130    use crate::fsst::SymbolTable;
2131    use crate::string::{StringColumn, StringView};
2132    use crate::validity::Validity;
2133
2134    fn integers(values: &[i32]) -> Vector {
2135        Vector::flat(LogicalType::Integer, Data::Int32(values.to_vec().into())).unwrap()
2136    }
2137
2138    #[test]
2139    fn a_clustered_column_becomes_runs_and_reads_back_the_same() {
2140        let mut values = Vec::new();
2141        for (value, times) in [(7, 400), (8, 300), (7, 324)] {
2142            values.extend(std::iter::repeat_n(value, times));
2143        }
2144        let flat = integers(&values);
2145        let runs = flat.run_encoded().unwrap();
2146        assert_eq!(runs.form(), Form::Rle);
2147        assert_eq!(runs.run_parts().expect("runs").0, [400, 700, 1024]);
2148        assert_eq!(runs.len(), flat.len());
2149        assert_eq!(runs.iter().collect::<Vec<_>>(), flat.iter().collect::<Vec<_>>());
2150        assert!(
2151            runs.footprint() * 10 < flat.footprint(),
2152            "three runs against a thousand rows: {} against {}",
2153            runs.footprint(),
2154            flat.footprint()
2155        );
2156    }
2157
2158    /// The check is worth having in both directions. A form that is only ever bigger than what it
2159    /// replaced is a form that costs a pass over the column to decide not to use.
2160    #[test]
2161    fn a_column_that_does_not_repeat_is_left_flat() {
2162        let flat = integers(&(0..1024).collect::<Vec<i32>>());
2163        assert_eq!(flat.run_encoded().unwrap().form(), Form::Flat);
2164        // Two runs over four rows is exactly break even on a four byte column, and break even is
2165        // not a reason to change form.
2166        assert_eq!(integers(&[1, 1, 2, 2]).run_encoded().unwrap().form(), Form::Flat);
2167        assert_eq!(integers(&[1, 1, 1, 2, 2]).run_encoded().unwrap().form(), Form::Rle);
2168    }
2169
2170    #[test]
2171    fn two_nulls_beside_each_other_are_one_run_and_a_null_between_two_equals_is_a_break() {
2172        let mut values = vec![Value::Integer(4), Value::Integer(4)];
2173        values.extend([Value::Null, Value::Null, Value::Null]);
2174        values.extend(std::iter::repeat_n(Value::Integer(4), 5));
2175        let flat = Vector::from_values(LogicalType::Integer, &values).unwrap();
2176        let runs = flat.run_encoded().unwrap();
2177        assert_eq!(runs.run_parts().expect("runs").0, [2, 5, 10]);
2178        assert_eq!(runs.iter().collect::<Vec<_>>(), values);
2179    }
2180
2181    #[test]
2182    fn slicing_runs_keeps_them_runs_and_cuts_the_first_and_last_one_back() {
2183        let flat = integers(&[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]);
2184        let runs = flat.run_encoded().unwrap();
2185        let piece = runs.slice(3, 6).unwrap();
2186        assert_eq!(piece.form(), Form::Rle, "the form is the whole point");
2187        assert_eq!(piece.run_parts().expect("runs").0, [1, 5, 6]);
2188        assert_eq!(
2189            piece.iter().collect::<Vec<_>>(),
2190            flat.slice(3, 6).unwrap().iter().collect::<Vec<_>>()
2191        );
2192        assert_eq!(runs.slice(0, 0).unwrap().len(), 0);
2193        assert_eq!(runs.slice(0, 12).unwrap().form(), Form::Rle);
2194    }
2195
2196    #[test]
2197    fn gathering_out_of_runs_walks_to_the_values_the_way_it_walks_a_dictionary() {
2198        let mut values = vec![Value::Varchar("red".into()); 4];
2199        values.extend([Value::Null, Value::Null, Value::Null]);
2200        values.extend(vec![Value::Varchar("blue".into()); 4]);
2201        let runs =
2202            Vector::from_values(LogicalType::Varchar, &values).unwrap().run_encoded().unwrap();
2203        assert_eq!(runs.form(), Form::Rle);
2204        let picked = runs.gather(&[8, 0, 5, 2]).unwrap();
2205        assert_eq!(picked.form(), Form::Flat, "a gather copies, whatever it gathered from");
2206        assert_eq!(
2207            picked.iter().collect::<Vec<_>>(),
2208            [values[8].clone(), values[0].clone(), Value::Null, values[2].clone()]
2209        );
2210        assert_eq!(runs.text_at(1), Some("red"));
2211        assert_eq!(runs.text_at(5), None, "a null has no text");
2212        assert_eq!(runs.flatten().unwrap().iter().collect::<Vec<_>>(), values);
2213    }
2214
2215    /// A run length vector over a run length vector turns one search per row into two, and there is
2216    /// nothing in the engine that builds one, so it is refused rather than composed.
2217    #[test]
2218    fn runs_of_runs_are_refused_and_runs_of_a_dictionary_are_not() {
2219        let inner = integers(&[1, 1, 1, 1, 2]).run_encoded().unwrap();
2220        assert_eq!(inner.form(), Form::Rle);
2221        let error = Vector::runs(vec![2, 8], inner).unwrap_err();
2222        assert!(error.to_string().contains("runs of runs"), "{error}");
2223
2224        let words = Vector::from_values(
2225            LogicalType::Varchar,
2226            &[Value::Varchar("red".into()), Value::Varchar("blue".into())],
2227        )
2228        .unwrap();
2229        let dictionary = Vector::dictionary(vec![1, 0], words).unwrap();
2230        let stacked = Vector::runs(vec![4, 9], dictionary).unwrap();
2231        assert_eq!(stacked.len(), 9);
2232        assert_eq!(stacked.value_at(3), Value::Varchar("blue".into()));
2233        assert_eq!(stacked.value_at(4), Value::Varchar("red".into()));
2234    }
2235
2236    #[test]
2237    fn run_ends_have_to_increase_and_there_is_one_value_for_each_of_them() {
2238        let values = integers(&[1, 2]);
2239        assert!(Vector::runs(vec![4], values.clone()).is_err(), "two values and one run");
2240        assert!(Vector::runs(vec![4, 4], values.clone()).is_err(), "an end that repeats");
2241        assert!(Vector::runs(vec![4, 2], values.clone()).is_err(), "an end that goes backwards");
2242        assert!(Vector::runs(vec![0, 2], values.clone()).is_err(), "a first run holding no rows");
2243        assert_eq!(Vector::runs(vec![4, 9], values).unwrap().len(), 9);
2244    }
2245
2246    #[test]
2247    fn a_form_that_is_already_compact_is_left_where_it_is() {
2248        let constant = Vector::constant(LogicalType::Integer, Value::Integer(1), 1000);
2249        assert_eq!(constant.run_encoded().unwrap().form(), Form::Constant);
2250        assert_eq!(Vector::sequence(0, 1, 1000).run_encoded().unwrap().form(), Form::Sequence);
2251    }
2252
2253    /// What makes one accessor cover both forms. A dictionary hands back the codes it stores and a
2254    /// run length vector works the same numbers out, and a kernel writing `values[at[row]]` reads
2255    /// the same rows out of either.
2256    #[test]
2257    fn both_forms_that_point_somewhere_hand_back_a_position_per_row() {
2258        let words = Vector::from_values(
2259            LogicalType::Varchar,
2260            &[Value::Varchar("red".into()), Value::Varchar("blue".into())],
2261        )
2262        .unwrap();
2263        let runs = Vector::runs(vec![3, 5], words.clone()).unwrap();
2264        let (at, values) = runs.positions().expect("runs point somewhere");
2265        assert_eq!(at.as_ref(), [0, 0, 0, 1, 1]);
2266        assert_eq!(values.value_at(at[3] as usize), runs.value_at(3));
2267
2268        let dictionary = Vector::dictionary(vec![1, 0, 1], words).unwrap();
2269        let (at, values) = dictionary.positions().expect("a dictionary points somewhere");
2270        assert_eq!(at.as_ref(), [1, 0, 1]);
2271        assert_eq!(values.value_at(at[0] as usize), dictionary.value_at(0));
2272
2273        assert!(integers(&[1, 2, 3]).positions().is_none(), "a flat vector points at itself");
2274        assert!(Vector::sequence(0, 1, 4).positions().is_none(), "a sequence stores nothing");
2275    }
2276
2277    #[test]
2278    fn slicing_a_dictionary_keeps_it_a_dictionary_where_gathering_would_not() {
2279        let values = Vector::from_values(
2280            LogicalType::Varchar,
2281            &[Value::Varchar("red".into()), Value::Varchar("blue".into())],
2282        )
2283        .unwrap();
2284        let vector = Vector::dictionary(vec![0, 1, 1, 0, 1], values).unwrap();
2285
2286        let piece = vector.slice(1, 3).unwrap();
2287        assert_eq!(piece.form(), Form::Dictionary, "the form is the whole point");
2288        assert_eq!(piece.len(), 3);
2289        assert_eq!(
2290            piece.iter().collect::<Vec<_>>(),
2291            [
2292                Value::Varchar("blue".into()),
2293                Value::Varchar("blue".into()),
2294                Value::Varchar("red".into())
2295            ]
2296        );
2297        assert_eq!(vector.gather(&[1, 2, 3]).unwrap().form(), Form::Flat, "which a gather loses");
2298    }
2299
2300    #[test]
2301    fn slicing_a_dictionary_shares_the_dictionary_rather_than_copying_it() {
2302        // The assertion is about the address and not about the values, because the values were
2303        // right when the dictionary was copied too. A page holds one dictionary and is cut into a
2304        // chunk of codes at a time, so copying the dictionary here is a copy of every string in it
2305        // per chunk, and on a read of a ClickBench partition it was ten percent of the cycles.
2306        let values = Vector::from_values(
2307            LogicalType::Varchar,
2308            &[Value::Varchar("red".into()), Value::Varchar("blue".into())],
2309        )
2310        .unwrap();
2311        let vector = Vector::dictionary(vec![0, 1, 1, 0, 1], values).unwrap();
2312        let Body::Dictionary { values: whole, .. } = &vector.body else {
2313            panic!("a dictionary vector holds a dictionary");
2314        };
2315
2316        let piece = vector.slice(1, 3).unwrap();
2317        let Body::Dictionary { codes, values: cut } = &piece.body else {
2318            panic!("a slice of a dictionary is a dictionary");
2319        };
2320        assert!(Arc::ptr_eq(whole, cut), "the cut copied the dictionary");
2321        assert_eq!(codes, &[1, 1, 0], "the codes are the part that is cut");
2322
2323        // And a cut of a cut shares it too, since that is what a scan does to a page it reads twice.
2324        let again = piece.slice(1, 2).unwrap();
2325        let Body::Dictionary { values: cut, .. } = &again.body else {
2326            panic!("a slice of a slice of a dictionary is a dictionary");
2327        };
2328        assert!(Arc::ptr_eq(whole, cut), "the second cut copied the dictionary");
2329        assert_eq!(
2330            again.iter().collect::<Vec<_>>(),
2331            [Value::Varchar("blue".into()), Value::Varchar("red".into())]
2332        );
2333    }
2334
2335    #[test]
2336    fn a_slice_carries_the_nulls_that_were_in_its_range_and_not_the_others() {
2337        let vector =
2338            integers(&[1, 2, 3, 4]).with_validity(Validity::from_run(&[false, true, false, true]));
2339        let piece = vector.slice(1, 2).unwrap();
2340        assert!(piece.validity().is_valid(0));
2341        assert!(!piece.validity().is_valid(1));
2342        assert_eq!(piece.value_at(1), Value::Null);
2343    }
2344
2345    #[test]
2346    fn slicing_a_sequence_moves_its_start_rather_than_writing_the_values_out() {
2347        let vector = Vector::sequence(100, 5, 10);
2348        let piece = vector.slice(3, 4).unwrap();
2349        assert_eq!(piece.form(), Form::Sequence);
2350        assert_eq!(
2351            piece.iter().collect::<Vec<_>>(),
2352            [Value::BigInt(115), Value::BigInt(120), Value::BigInt(125), Value::BigInt(130)]
2353        );
2354    }
2355
2356    #[test]
2357    fn slicing_a_constant_is_a_shorter_constant() {
2358        let vector = Vector::constant(LogicalType::Integer, Value::Integer(9), 8);
2359        let piece = vector.slice(2, 3).unwrap();
2360        assert_eq!(piece.form(), Form::Constant);
2361        assert_eq!(piece.len(), 3);
2362        assert_eq!(piece.value_at(2), Value::Integer(9));
2363    }
2364
2365    #[test]
2366    fn slicing_the_whole_vector_hands_it_back_as_it_was() {
2367        let vector = integers(&[1, 2, 3]);
2368        assert_eq!(
2369            vector.slice(0, 3).unwrap().iter().collect::<Vec<_>>(),
2370            [Value::Integer(1), Value::Integer(2), Value::Integer(3)]
2371        );
2372    }
2373
2374    #[test]
2375    fn a_slice_past_the_end_is_an_error_rather_than_a_short_vector() {
2376        let error = integers(&[1, 2, 3]).slice(2, 2).unwrap_err();
2377        assert!(error.to_string().contains("of a vector of 3"), "{error}");
2378    }
2379
2380    #[test]
2381    fn the_vector_size_is_the_one_the_design_is_built_around() {
2382        // 1024 and not DuckDB's 2048. A validity mask is 16 u64 words and a vector of string views
2383        // is 16 KiB, both of which are consequences of this number rather than coincidences.
2384        assert_eq!(VECTOR_SIZE, 1024);
2385        assert_eq!(VECTOR_SIZE / 64, 16);
2386    }
2387
2388    #[test]
2389    fn a_flat_vector_reads_back_what_was_put_in_it() {
2390        let vector = integers(&[1, 2, 3]);
2391        assert_eq!(vector.form(), Form::Flat);
2392        assert_eq!(vector.len(), 3);
2393        assert_eq!(vector.value_at(1), Value::Integer(2));
2394        assert_eq!(
2395            vector.iter().collect::<Vec<_>>(),
2396            vec![Value::Integer(1), Value::Integer(2), Value::Integer(3)]
2397        );
2398    }
2399
2400    #[test]
2401    fn a_vector_built_from_values_reads_the_same_values_back() {
2402        let vector = Vector::from_values(
2403            LogicalType::Varchar,
2404            &[
2405                Value::Varchar("a".to_string()),
2406                Value::Null,
2407                Value::Varchar("a string too long to sit inside a view".to_string()),
2408            ],
2409        )
2410        .expect("strings and a null");
2411        assert_eq!(vector.len(), 3);
2412        assert_eq!(vector.value_at(0), Value::Varchar("a".to_string()));
2413        assert_eq!(vector.value_at(1), Value::Null);
2414        assert_eq!(
2415            vector.value_at(2),
2416            Value::Varchar("a string too long to sit inside a view".to_string())
2417        );
2418    }
2419
2420    /// A null still occupies a position. If it did not then every value after it would read back
2421    /// one place to the left, which is the kind of bug that looks like a storage bug for a week.
2422    #[test]
2423    fn a_null_in_the_middle_does_not_move_the_values_after_it() {
2424        let vector = Vector::from_values(
2425            LogicalType::Integer,
2426            &[Value::Integer(1), Value::Null, Value::Integer(3)],
2427        )
2428        .expect("integers and a null");
2429        assert_eq!(vector.value_at(2), Value::Integer(3));
2430        assert!(vector.validity().has_nulls(3), "the middle one is null");
2431    }
2432
2433    #[test]
2434    fn a_value_the_type_cannot_hold_is_refused() {
2435        let wrong = Vector::from_values(LogicalType::Integer, &[Value::Varchar("x".to_string())]);
2436        assert!(wrong.is_err(), "a string is not an integer");
2437    }
2438
2439    #[test]
2440    fn a_type_that_does_not_match_its_layout_is_refused_at_construction() {
2441        // One comparison here against a wrong answer read out three layers later.
2442        let wrong = Vector::flat(LogicalType::Varchar, Data::Int32(vec![1].into()));
2443        assert!(wrong.is_err());
2444        let right = Vector::flat(LogicalType::Date, Data::Int32(vec![1].into()));
2445        assert!(right.is_ok(), "a date is stored in an i32 and that has to be allowed");
2446    }
2447
2448    #[test]
2449    fn a_constant_vector_costs_one_value_whatever_its_length() {
2450        let vector = Vector::constant(LogicalType::Integer, Value::Integer(7), VECTOR_SIZE);
2451        assert_eq!(vector.form(), Form::Constant);
2452        assert_eq!(vector.len(), VECTOR_SIZE);
2453        assert_eq!(vector.value_at(0), Value::Integer(7));
2454        assert_eq!(vector.value_at(VECTOR_SIZE - 1), Value::Integer(7));
2455        assert_eq!(vector.value_at(VECTOR_SIZE), Value::Null, "past the end is null, not a panic");
2456    }
2457
2458    #[test]
2459    fn a_constant_null_is_all_invalid_without_being_told() {
2460        let vector = Vector::constant(LogicalType::Integer, Value::Null, 8);
2461        assert_eq!(vector.validity(), &Validity::AllInvalid);
2462        assert_eq!(vector.value_at(3), Value::Null);
2463    }
2464
2465    #[test]
2466    fn a_sequence_vector_is_sixteen_bytes_of_row_identifiers() {
2467        let vector = Vector::sequence(100, 1, VECTOR_SIZE);
2468        assert_eq!(vector.form(), Form::Sequence);
2469        assert_eq!(vector.value_at(0), Value::BigInt(100));
2470        assert_eq!(vector.value_at(923), Value::BigInt(1023));
2471        let stepped = Vector::sequence(0, 5, 4);
2472        assert_eq!(
2473            stepped.iter().collect::<Vec<_>>(),
2474            vec![Value::BigInt(0), Value::BigInt(5), Value::BigInt(10), Value::BigInt(15)]
2475        );
2476    }
2477
2478    #[test]
2479    fn a_dictionary_vector_reads_through_its_codes() {
2480        let mut column = StringColumn::new();
2481        column.push("red");
2482        column.push("green");
2483        let values = Vector::flat(LogicalType::Varchar, Data::Varlen(column)).unwrap();
2484        let vector = Vector::dictionary(vec![0, 1, 1, 0], values).unwrap();
2485        assert_eq!(vector.form(), Form::Dictionary);
2486        assert_eq!(vector.logical_type(), &LogicalType::Varchar);
2487        assert_eq!(vector.value_at(2), Value::Varchar("green".into()));
2488        assert_eq!(vector.len(), 4);
2489    }
2490
2491    /// The accessor a group by keys a string column through, which has to agree with `value_at` on
2492    /// every position or two rows holding one string end up in two groups.
2493    #[test]
2494    fn text_is_read_where_it_already_is_for_the_forms_that_store_it() {
2495        let mut column = StringColumn::new();
2496        column.push("red");
2497        column.push("green");
2498        column.push("");
2499        let flat = Vector::flat(LogicalType::Varchar, Data::Varlen(column)).unwrap();
2500        for index in 0..flat.len() {
2501            assert_eq!(flat.text_at(index).map(str::to_string), text_of(&flat.value_at(index)));
2502        }
2503        let dictionary = Vector::dictionary(vec![1, 0, 1, 2], flat).unwrap();
2504        for index in 0..dictionary.len() {
2505            assert_eq!(
2506                dictionary.text_at(index).map(str::to_string),
2507                text_of(&dictionary.value_at(index))
2508            );
2509        }
2510        assert_eq!(dictionary.text_at(4), None, "past the end");
2511    }
2512
2513    /// The forms and types that have no text to hand back, which a caller answers by falling back
2514    /// to `value_at`. A blob is the one that would be a correctness bug rather than a slow path,
2515    /// since its bytes are not required to be text and it is not a `VARCHAR` either way.
2516    #[test]
2517    fn text_is_refused_where_it_is_not_stored_as_itself() {
2518        let nulls =
2519            Vector::from_values(LogicalType::Varchar, &[Value::Varchar("red".into()), Value::Null])
2520                .unwrap();
2521        assert_eq!(nulls.text_at(0), Some("red"));
2522        assert_eq!(nulls.text_at(1), None, "a null has no text");
2523        let constant = Vector::constant(LogicalType::Varchar, Value::Varchar("red".into()), 3);
2524        assert_eq!(constant.text_at(0), None, "a constant is not stored per position");
2525        assert_eq!(integers(&[1, 2]).text_at(0), None, "an integer is not text");
2526        let mut bytes = StringColumn::new();
2527        bytes.push("red");
2528        let blob = Vector::flat(LogicalType::Blob, Data::Varlen(bytes)).unwrap();
2529        assert_eq!(blob.text_at(0), None, "a blob is not a varchar");
2530    }
2531
2532    /// The accessor a group by keys an integer column through, which has to agree with `value_at`
2533    /// on every position or two rows holding one number end up in two groups.
2534    #[test]
2535    fn a_signed_integer_is_read_where_it_already_is_for_the_forms_that_store_it() {
2536        let flat = integers(&[7, -3, 0, 2]);
2537        for index in 0..flat.len() {
2538            assert_eq!(flat.signed_at(index), signed_of(&flat.value_at(index)), "flat {index}");
2539        }
2540        let dictionary = Vector::dictionary(vec![1, 0, 3, 2], flat).unwrap();
2541        for index in 0..dictionary.len() {
2542            assert_eq!(
2543                dictionary.signed_at(index),
2544                signed_of(&dictionary.value_at(index)),
2545                "dictionary {index}"
2546            );
2547        }
2548        assert_eq!(dictionary.signed_at(4), None, "past the end");
2549
2550        let runs = Vector::runs(vec![2, 5], integers(&[4, 9])).unwrap();
2551        for index in 0..runs.len() {
2552            assert_eq!(runs.signed_at(index), signed_of(&runs.value_at(index)), "run {index}");
2553        }
2554        let constant = Vector::constant(LogicalType::BigInt, Value::BigInt(11), 3);
2555        assert_eq!(constant.signed_at(2), Some(11));
2556        let sequence = Vector::sequence(100, 5, 4);
2557        for index in 0..sequence.len() {
2558            assert_eq!(
2559                sequence.signed_at(index),
2560                signed_of(&sequence.value_at(index)),
2561                "sequence {index}"
2562            );
2563        }
2564    }
2565
2566    /// The forms and types that have no integer to hand back, which a caller answers by falling
2567    /// back to `value_at`. Reading one of these as a key that does not match rather than as a key
2568    /// that has to be built is how a packed column ends up with every row in its own group.
2569    #[test]
2570    fn a_signed_integer_is_refused_where_it_is_not_stored_as_itself() {
2571        let nulls =
2572            Vector::from_values(LogicalType::BigInt, &[Value::BigInt(4), Value::Null]).unwrap();
2573        assert_eq!(nulls.signed_at(0), Some(4));
2574        assert_eq!(nulls.signed_at(1), None, "a null is not a number");
2575        let packed = integers(&[1, 2, 3, 1]).bit_packed().unwrap();
2576        assert_eq!(
2577            packed.signed_at(0),
2578            None,
2579            "a packed row is not an integer until it is unpacked"
2580        );
2581        let mut bytes = StringColumn::new();
2582        bytes.push("red");
2583        let text = Vector::flat(LogicalType::Varchar, Data::Varlen(bytes)).unwrap();
2584        assert_eq!(text.signed_at(0), None, "a string is not a number");
2585        let double = Vector::flat(LogicalType::Double, Data::Float64(vec![1.5].into())).unwrap();
2586        assert_eq!(double.signed_at(0), None, "a double is not a signed integer");
2587    }
2588
2589    /// The integer of a value, for comparing `signed_at` against `value_at` position by position.
2590    fn signed_of(value: &Value) -> Option<i128> {
2591        match value {
2592            Value::TinyInt(x) => Some(i128::from(*x)),
2593            Value::SmallInt(x) => Some(i128::from(*x)),
2594            Value::Integer(x) | Value::Date(x) => Some(i128::from(*x)),
2595            Value::BigInt(x) | Value::Time(x) | Value::Timestamp(x) => Some(i128::from(*x)),
2596            Value::HugeInt(x) | Value::Decimal { unscaled: x, .. } => Some(*x),
2597            _ => None,
2598        }
2599    }
2600
2601    /// The text of a value, for comparing `text_at` against `value_at` position by position.
2602    fn text_of(value: &Value) -> Option<String> {
2603        match value {
2604            Value::Varchar(text) => Some(text.clone()),
2605            _ => None,
2606        }
2607    }
2608
2609    #[test]
2610    fn a_dictionary_code_past_the_end_is_refused() {
2611        // The alternative is a silent read of the wrong value, which is the failure mode the
2612        // entire M3 design has to be careful about.
2613        let values = integers(&[1, 2]);
2614        assert!(Vector::dictionary(vec![0, 2], values).is_err());
2615        // The check runs on the highest code rather than the first bad one, so it has to say that
2616        // no codes at all is fine even when there are no values for them to point at either.
2617        let empty = Vector::dictionary(Vec::new(), integers(&[])).expect("no codes, no values");
2618        assert_eq!(empty.len(), 0);
2619        // And a code of zero against an empty dictionary is still past the end.
2620        assert!(Vector::dictionary(vec![0], integers(&[])).is_err());
2621    }
2622
2623    #[test]
2624    fn every_form_flattens_to_the_same_values_it_reads_out() {
2625        // This is the shape of the equivalence testing in spec/16-testing.md section 16.2, in
2626        // miniature and long before there is an encoded kernel to point it at. A form that reads
2627        // out one way and flattens another is the exact bug that testing exists to catch.
2628        let mut column = StringColumn::new();
2629        column.push("alpha");
2630        column.push("beta");
2631        let dictionary = Vector::dictionary(
2632            vec![1, 0, 1],
2633            Vector::flat(LogicalType::Varchar, Data::Varlen(column)).unwrap(),
2634        )
2635        .unwrap();
2636        let cases = [
2637            Vector::constant(LogicalType::Integer, Value::Integer(3), 5),
2638            Vector::sequence(7, -2, 5),
2639            dictionary,
2640        ];
2641        for vector in cases {
2642            let flat = vector.flatten().unwrap();
2643            assert_eq!(flat.form(), Form::Flat);
2644            assert_eq!(flat.len(), vector.len());
2645            for index in 0..vector.len() {
2646                assert_eq!(flat.value_at(index), vector.value_at(index), "at {index}");
2647            }
2648        }
2649    }
2650
2651    #[test]
2652    fn a_null_still_occupies_a_position_after_flattening() {
2653        // The reason push_value writes a zero for a null rather than skipping it. A run of data
2654        // with a hole in it puts every value after the hole in the wrong place, and the validity
2655        // mask is what says the position is null.
2656        let vector = Vector::sequence(0, 1, 4).with_validity(Validity::from_iter(4, |i| i != 1));
2657        let flat = vector.flatten().unwrap();
2658        assert_eq!(flat.value_at(0), Value::BigInt(0));
2659        assert_eq!(flat.value_at(1), Value::Null);
2660        assert_eq!(flat.value_at(2), Value::BigInt(2));
2661        assert_eq!(flat.value_at(3), Value::BigInt(3));
2662    }
2663
2664    /// A dictionary holds its nulls in the vector it points at, so its own validity is all valid
2665    /// and reading that instead of the values turns a null into whatever zero means for the type.
2666    /// A filter over a nullable column produces exactly this vector, so the bug reaches a result
2667    /// set as `LEFT JOIN` padding that comes back as zeros.
2668    #[test]
2669    fn a_null_behind_a_dictionary_survives_flattening() {
2670        let values =
2671            Vector::from_values(LogicalType::Integer, &[Value::Integer(3), Value::Null]).unwrap();
2672        let dictionary = Vector::dictionary(vec![1, 0, 1], values).unwrap();
2673        let flat = dictionary.flatten().unwrap();
2674        assert_eq!(flat.value_at(0), Value::Null);
2675        assert_eq!(flat.value_at(1), Value::Integer(3));
2676        assert_eq!(flat.value_at(2), Value::Null);
2677    }
2678
2679    /// The property that makes `gather` usable at all: it has to be the same function as reading the
2680    /// wanted positions one at a time, over every form, or compaction changes answers.
2681    #[test]
2682    fn gathering_reads_what_reading_one_position_at_a_time_reads() {
2683        let mut column = StringColumn::new();
2684        column.push("alpha");
2685        column.push("beta");
2686        column.push("gamma");
2687        let cases = [
2688            integers(&[10, 20, 30, 40]),
2689            integers(&[10, 20, 30, 40]).with_validity(Validity::from_iter(4, |i| i != 2)),
2690            Vector::constant(LogicalType::Integer, Value::Integer(9), 4),
2691            Vector::sequence(100, -7, 4),
2692            Vector::sequence(100, -7, 4).with_validity(Validity::from_iter(4, |i| i % 2 == 0)),
2693            Vector::dictionary(
2694                vec![2, 0, 1, 2],
2695                Vector::flat(LogicalType::Varchar, Data::Varlen(column)).unwrap(),
2696            )
2697            .unwrap(),
2698            Vector::dictionary(
2699                vec![1, 0, 1, 0],
2700                Vector::from_values(LogicalType::Integer, &[Value::Integer(5), Value::Null])
2701                    .unwrap(),
2702            )
2703            .unwrap(),
2704        ];
2705        let wanted = [3_u32, 0, 2, 2, 1];
2706        for vector in cases {
2707            let gathered = vector.gather(&wanted).unwrap();
2708            assert_eq!(gathered.len(), wanted.len());
2709            assert_eq!(gathered.logical_type(), vector.logical_type());
2710            for (slot, &index) in wanted.iter().enumerate() {
2711                assert_eq!(
2712                    gathered.value_at(slot),
2713                    vector.value_at(index as usize),
2714                    "slot {slot} of {:?}",
2715                    vector.form()
2716                );
2717            }
2718        }
2719    }
2720
2721    /// A gather past the end is not an error, because the selection that produced the indices is
2722    /// checked by its caller and the one thing that must not happen here is a read of the wrong
2723    /// value. An index nothing answers is null, which is what an outer join pad needs anyway.
2724    #[test]
2725    fn gathering_a_position_that_is_not_there_is_a_null_and_not_a_wrong_value() {
2726        let vector = integers(&[1, 2, 3]);
2727        let gathered = vector.gather(&[2, 9]).unwrap();
2728        assert_eq!(gathered.value_at(0), Value::Integer(3));
2729        assert_eq!(gathered.value_at(1), Value::Null);
2730    }
2731
2732    /// The vector with nothing in it at all, which is what an untyped `NULL` is stored as. Every
2733    /// position asked for is past its end, so the answer is nulls and the length has to be the
2734    /// length that was asked for rather than the length that was there.
2735    #[test]
2736    fn gathering_from_a_vector_of_no_values_is_that_many_nulls() {
2737        let vector = Vector::flat(LogicalType::Null, Data::Empty).unwrap();
2738        let gathered = vector.gather(&[0, 1, 2]).unwrap();
2739        assert_eq!(gathered.len(), 3);
2740        assert_eq!(gathered.value_at(0), Value::Null);
2741        assert_eq!(gathered.value_at(2), Value::Null);
2742    }
2743
2744    /// Every position holds the same value, so a gather with no hole in it has nothing to copy and
2745    /// the result is the constant again rather than a run of a thousand copies of it.
2746    #[test]
2747    fn gathering_a_constant_stays_a_constant() {
2748        let vector = Vector::constant(LogicalType::Integer, Value::Integer(4), 100);
2749        let gathered = vector.gather(&[7, 7, 99]).unwrap();
2750        assert_eq!(gathered.form(), Form::Constant);
2751        assert_eq!(gathered.len(), 3);
2752        assert_eq!(gathered.value_at(2), Value::Integer(4));
2753    }
2754
2755    /// A dictionary over a dictionary is what a second filter over an already filtered chunk builds,
2756    /// and the gather has to walk to the bottom of that chain rather than one step down it. The
2757    /// constructor composes the ordinary chain away, so the one built here is the kind it cannot,
2758    /// which is a level holding nulls of its own.
2759    #[test]
2760    fn gathering_walks_a_dictionary_over_a_dictionary_to_the_values() {
2761        let inner = Vector::dictionary(vec![2, 1, 0], integers(&[7, 8, 9]))
2762            .unwrap()
2763            .with_validity(Validity::from_iter(3, |index| index != 2));
2764        let outer = Vector::dictionary(vec![1, 2], inner).unwrap();
2765        let gathered = outer.gather(&[0, 1]).unwrap();
2766        assert_eq!(gathered.form(), Form::Flat);
2767        assert_eq!(gathered.value_at(0), Value::Integer(8));
2768        assert_eq!(gathered.value_at(1), Value::Null);
2769    }
2770
2771    /// Two filters over one chunk build a dictionary over a dictionary, four conjuncts pushed down
2772    /// separately build four levels of it, and every level is a dependent load on every later read
2773    /// of every row plus a code array that cannot be freed. Composing at construction is one pass
2774    /// over the codes the range check was walking anyway.
2775    #[test]
2776    fn a_dictionary_over_a_dictionary_is_composed_into_one_level() {
2777        let inner = Vector::dictionary(vec![2, 1, 0], integers(&[7, 8, 9])).unwrap();
2778        let outer = Vector::dictionary(vec![1, 2], inner).unwrap();
2779        let (codes, values) = outer.dictionary_parts().unwrap();
2780        assert_eq!(codes, [1, 0]);
2781        assert_eq!(values.form(), Form::Flat);
2782        assert_eq!(outer.value_at(0), Value::Integer(8));
2783        assert_eq!(outer.value_at(1), Value::Integer(7));
2784    }
2785
2786    /// The invariant stated as the thing it is there for, which is that the depth does not grow with
2787    /// the number of filters. Four levels stacked one at a time are one level at the end of it.
2788    #[test]
2789    fn stacking_dictionaries_does_not_make_them_deeper() {
2790        let mut vector = integers(&[10, 20, 30, 40]);
2791        for _ in 0..4 {
2792            vector = Vector::dictionary(vec![3, 2, 1, 0], vector).unwrap();
2793        }
2794        let (codes, values) = vector.dictionary_parts().unwrap();
2795        assert_eq!(values.form(), Form::Flat);
2796        assert_eq!(codes, [0, 1, 2, 3]);
2797        assert_eq!(
2798            vector.iter().collect::<Vec<_>>(),
2799            integers(&[10, 20, 30, 40]).iter().collect::<Vec<_>>()
2800        );
2801    }
2802
2803    /// Composing has to carry the nulls down with it. The values hold them, the codes point at them,
2804    /// and a composed code that lands on a null position is still a null.
2805    #[test]
2806    fn composing_a_dictionary_keeps_the_nulls_its_values_hold() {
2807        let values =
2808            Vector::from_values(LogicalType::Integer, &[Value::Integer(3), Value::Null]).unwrap();
2809        let inner = Vector::dictionary(vec![1, 0, 1], values).unwrap();
2810        let outer = Vector::dictionary(vec![0, 1], inner).unwrap();
2811        assert_eq!(outer.dictionary_parts().unwrap().1.form(), Form::Flat);
2812        assert_eq!(outer.value_at(0), Value::Null);
2813        assert_eq!(outer.value_at(1), Value::Integer(3));
2814    }
2815
2816    /// The one level composition cannot go past. A dictionary that was given a validity of its own is
2817    /// saying its nulls are at that level rather than in the values, and pointing the outer codes
2818    /// straight at the values would read through the holes instead of stopping at them.
2819    #[test]
2820    fn a_dictionary_holding_its_own_nulls_is_not_composed_past() {
2821        let inner = Vector::dictionary(vec![0, 1, 2], integers(&[1, 2, 3]))
2822            .unwrap()
2823            .with_validity(Validity::from_iter(3, |index| index != 1));
2824        let outer = Vector::dictionary(vec![1, 2, 0], inner).unwrap();
2825        assert_eq!(outer.dictionary_parts().unwrap().1.form(), Form::Dictionary);
2826        assert_eq!(outer.value_at(0), Value::Null);
2827        assert_eq!(outer.value_at(1), Value::Integer(3));
2828        assert_eq!(outer.value_at(2), Value::Integer(1));
2829    }
2830
2831    #[test]
2832    fn flattening_a_flat_vector_is_the_same_vector() {
2833        let vector = integers(&[1, 2, 3]);
2834        assert_eq!(vector.flatten().unwrap(), vector);
2835    }
2836
2837    #[test]
2838    fn a_decimal_reads_its_width_and_scale_from_the_type_and_not_the_data() {
2839        let ty = LogicalType::decimal(9, 2).unwrap();
2840        let vector = Vector::flat(ty, Data::Int32(vec![1234].into())).unwrap();
2841        assert_eq!(vector.value_at(0), Value::Decimal { unscaled: 1234, width: 9, scale: 2 });
2842        assert_eq!(vector.value_at(0).to_string(), "12.34");
2843    }
2844
2845    #[test]
2846    fn a_decimal_writes_into_whichever_of_the_four_runs_its_precision_chose() {
2847        // The read path worked at every width and the write path only accepted the 128 bit run, so
2848        // `SELECT 2.5` produced a value nothing could store. All four widths round trip now.
2849        for (width, scale, unscaled) in
2850            [(4u8, 1u8, 25i128), (9, 2, 1234), (18, 3, 123_456), (38, 4, 1_234_567)]
2851        {
2852            let ty = LogicalType::decimal(width, scale).unwrap();
2853            let value = Value::Decimal { unscaled, width, scale };
2854            let vector = Vector::from_values(ty, &[value.clone(), Value::Null]).unwrap();
2855            assert_eq!(vector.value_at(0), value, "a decimal of width {width}");
2856            assert_eq!(vector.value_at(1), Value::Null, "a null decimal of width {width}");
2857        }
2858    }
2859
2860    /// The bytes a blob holds are not required to be text, and a vector of them used to refuse the
2861    /// ones that were not. A byte array column in a Parquet file that nothing annotated is a blob,
2862    /// which is what ClickHouse writes and what ten of the ClickBench queries compare against, so
2863    /// this is the path those take rather than a corner of the type system.
2864    #[test]
2865    fn a_blob_holds_bytes_that_are_not_text() {
2866        let bytes = |raw: &[u8]| Value::Blob(raw.to_vec());
2867        let values = [
2868            bytes(b"a\xffb"),
2869            bytes(b"\x00\x01\x02"),
2870            Value::Null,
2871            bytes(b"\xed\xa0\x80 and long enough to leave the view"),
2872            bytes(b""),
2873        ];
2874        let vector = Vector::from_values(LogicalType::Blob, &values).unwrap();
2875        for (index, value) in values.iter().enumerate() {
2876            assert_eq!(&vector.value_at(index), value, "row {index}");
2877        }
2878    }
2879
2880    #[test]
2881    fn a_decimal_too_wide_for_the_run_its_type_chose_is_an_error_and_not_a_wrong_number() {
2882        // Only reachable by hand, since a value's width is what picked the run. Truncating here
2883        // would store a different number and say nothing about it.
2884        let ty = LogicalType::decimal(4, 1).unwrap();
2885        let value = Value::Decimal { unscaled: 1_000_000, width: 4, scale: 1 };
2886        let error = Vector::from_values(ty, &[value]).unwrap_err();
2887        assert!(error.to_string().contains("does not fit"), "{error}");
2888    }
2889
2890    #[test]
2891    fn a_flat_vector_costs_its_values_and_a_constant_costs_one() {
2892        let flat = integers(&[1; 1000]);
2893        assert!(
2894            flat.footprint() >= 4000,
2895            "a thousand i32 are four thousand bytes: {}",
2896            flat.footprint()
2897        );
2898        // The forms that compute their values rather than storing them cost nothing per value,
2899        // which is the point of having them and is what the memory limit should see.
2900        let constant = Vector::constant(LogicalType::Integer, Value::Integer(1), 1_000_000);
2901        assert!(constant.footprint() < 200, "a constant is one value: {}", constant.footprint());
2902        let sequence = Vector::sequence(0, 1, 1_000_000);
2903        assert!(sequence.footprint() < 200, "a sequence is two numbers: {}", sequence.footprint());
2904    }
2905
2906    #[test]
2907    fn a_string_vector_costs_the_bytes_of_its_long_strings() {
2908        let short =
2909            Vector::from_values(LogicalType::Varchar, &[Value::Varchar("red".into())]).unwrap();
2910        let long = "a string well past the sixteen bytes a view holds inline".to_string();
2911        let spilled =
2912            Vector::from_values(LogicalType::Varchar, &[Value::Varchar(long.clone())]).unwrap();
2913        assert!(
2914            spilled.footprint() >= short.footprint() + long.len(),
2915            "the arena is counted: {} against {}",
2916            spilled.footprint(),
2917            short.footprint()
2918        );
2919    }
2920
2921    /// The cases worth checking are the widths where a code straddles a word boundary, which is
2922    /// every width that does not divide sixty four, and the two ends of the range.
2923    #[test]
2924    fn a_narrow_column_packs_and_reads_back_the_same_at_every_width() {
2925        for width in 1..=20u32 {
2926            let span = (1i64 << width) - 1;
2927            let values: Vec<i64> =
2928                (0..1000).map(|row| 1_000_000 + (row * 7919) % (span + 1)).collect();
2929            let flat =
2930                Vector::flat(LogicalType::BigInt, Data::Int64(values.clone().into())).unwrap();
2931            let packed = flat.bit_packed().unwrap();
2932            assert_eq!(packed.len(), flat.len());
2933            assert_eq!(
2934                packed.iter().collect::<Vec<_>>(),
2935                flat.iter().collect::<Vec<_>>(),
2936                "width {width} read back differently"
2937            );
2938        }
2939    }
2940
2941    #[test]
2942    fn the_width_is_the_bits_the_range_needs_and_not_the_bits_the_type_has() {
2943        let values: Vec<i32> = (0..1024).map(|row| 40 + (row * 2560) / 1023).collect();
2944        let flat = Vector::flat(LogicalType::Integer, Data::Int32(values.into())).unwrap();
2945        let packed = flat.bit_packed().unwrap();
2946        assert_eq!(packed.form(), Form::BitPacked);
2947        let parts = packed.packed_parts().expect("packed");
2948        assert_eq!(parts.width(), 12, "0 to 2560 is twelve bits");
2949        assert_eq!(parts.base(), 40);
2950        assert!(
2951            packed.footprint() * 2 < flat.footprint(),
2952            "twelve bits against thirty two: {} against {}",
2953            packed.footprint(),
2954            flat.footprint()
2955        );
2956    }
2957
2958    /// The check is worth having in both directions, the way the run length one is. A form that is
2959    /// only ever bigger than what it replaced costs a pass over the column to decide not to use.
2960    #[test]
2961    fn a_column_that_uses_its_whole_type_is_left_flat() {
2962        let values: Vec<i32> = (0..1024).map(|row| row * 2_000_000 - 1_000_000_000).collect();
2963        let flat = Vector::flat(LogicalType::Integer, Data::Int32(values.into())).unwrap();
2964        assert_eq!(flat.bit_packed().unwrap().form(), Form::Flat);
2965    }
2966
2967    /// A column of one value would pack to no bits at all, and one run is smaller than any packing
2968    /// of it, so the two forms do not fight over that column.
2969    #[test]
2970    fn a_column_of_one_value_is_left_to_the_run_length_form() {
2971        let flat = integers(&[9; 1024]);
2972        assert_eq!(flat.bit_packed().unwrap().form(), Form::Flat);
2973        assert_eq!(flat.run_encoded().unwrap().form(), Form::Rle);
2974    }
2975
2976    #[test]
2977    fn a_string_column_has_no_range_to_pack() {
2978        let text = Vector::from_values(
2979            LogicalType::Varchar,
2980            &[Value::Varchar("red".into()), Value::Varchar("blue".into())],
2981        )
2982        .unwrap();
2983        assert_eq!(text.bit_packed().unwrap().form(), Form::Flat);
2984    }
2985
2986    /// The cut is the reason the form carries a row to start reading at. It stays packed, it shares
2987    /// the same words, and it reads the rows the range asked for.
2988    #[test]
2989    fn a_cut_of_a_packed_column_stays_packed_and_shares_its_bits() {
2990        let values: Vec<i32> = (0..1024).map(|row| 100 + row % 300).collect();
2991        let flat = Vector::flat(LogicalType::Integer, Data::Int32(values.into())).unwrap();
2992        let packed = flat.bit_packed().unwrap();
2993        let cut = packed.slice(500, 24).unwrap();
2994        assert_eq!(cut.form(), Form::BitPacked);
2995        assert_eq!(cut.len(), 24);
2996        assert_eq!(
2997            cut.iter().collect::<Vec<_>>(),
2998            flat.slice(500, 24).unwrap().iter().collect::<Vec<_>>()
2999        );
3000        assert!(
3001            cut.footprint() >= packed.footprint(),
3002            "a cut shares the words rather than copying a piece of them"
3003        );
3004    }
3005
3006    #[test]
3007    fn a_gather_of_a_packed_column_comes_out_flat_and_keeps_the_nulls() {
3008        let values: Vec<i32> = (0..64).map(|row| 10 + row).collect();
3009        let flat = Vector::flat(LogicalType::Integer, Data::Int32(values.into())).unwrap();
3010        let packed =
3011            flat.bit_packed().unwrap().with_validity(Validity::from_iter(64, |row| row % 3 != 0));
3012        let taken = packed.gather(&[0, 1, 2, 3, 62]).unwrap();
3013        assert_eq!(taken.form(), Form::Flat);
3014        assert_eq!(
3015            taken.iter().collect::<Vec<_>>(),
3016            vec![
3017                Value::Null,
3018                Value::Integer(11),
3019                Value::Integer(12),
3020                Value::Null,
3021                Value::Integer(72)
3022            ]
3023        );
3024    }
3025
3026    /// The pair a comparison kernel asks for before it reads a bit. A literal inside the range has a
3027    /// code and a literal outside it does not, which answers the whole vector at once.
3028    #[test]
3029    fn a_literal_outside_the_packed_range_has_no_code() {
3030        let values: Vec<i32> = (0..256).map(|row| 1000 + row).collect();
3031        let flat = Vector::flat(LogicalType::Integer, Data::Int32(values.into())).unwrap();
3032        let packed = flat.bit_packed().unwrap();
3033        let parts = packed.packed_parts().expect("packed");
3034        assert_eq!(parts.code_of(1000), Some(0));
3035        assert_eq!(parts.code_of(1100), Some(100));
3036        assert_eq!(parts.code_of(999), None);
3037        assert!(parts.ceiling() >= 1255);
3038        assert_eq!(parts.code_of(parts.ceiling() + 1), None);
3039    }
3040
3041    /// The bits arriving from a file rather than from a flat vector, which is what the form is for.
3042    #[test]
3043    fn packed_bits_can_be_handed_in_without_a_flat_vector_to_start_from() {
3044        let packed = Vector::packed(LogicalType::SmallInt, vec![0x0000_0000_0000_4321], 4, 7, 4)
3045            .expect("four codes of four bits");
3046        assert_eq!(
3047            packed.iter().collect::<Vec<_>>(),
3048            vec![Value::SmallInt(8), Value::SmallInt(9), Value::SmallInt(10), Value::SmallInt(11)]
3049        );
3050    }
3051
3052    #[test]
3053    fn packed_bits_that_could_not_hold_what_they_claim_are_refused() {
3054        assert!(Vector::packed(LogicalType::Varchar, vec![0], 4, 0, 4).is_err(), "not an integer");
3055        assert!(Vector::packed(LogicalType::Integer, vec![0], 0, 0, 4).is_err(), "no width");
3056        assert!(Vector::packed(LogicalType::Integer, vec![0], 64, 0, 4).is_err(), "too wide");
3057        assert!(Vector::packed(LogicalType::Integer, vec![0], 8, 0, 9).is_err(), "too few words");
3058        assert!(Vector::packed(LogicalType::TinyInt, vec![0], 8, 100, 8).is_err(), "would not fit");
3059    }
3060
3061    /// A column of strings long enough that the payload is in the arena rather than in the views.
3062    fn long_strings(count: usize) -> Vector {
3063        let values: Vec<Value> = (0..count)
3064            .map(|row| {
3065                Value::Varchar(format!("a string too long to sit inside a view, number {row}"))
3066            })
3067            .collect();
3068        Vector::from_values(LogicalType::Varchar, &values).unwrap()
3069    }
3070
3071    #[test]
3072    fn a_string_column_in_view_form_reads_back_the_same_strings() {
3073        let flat = long_strings(40);
3074        let shared = flat.clone().shared_text().unwrap();
3075        assert_eq!(shared.form(), Form::StringView);
3076        assert_eq!(shared.len(), 40);
3077        for row in 0..40 {
3078            assert_eq!(shared.value_at(row), flat.value_at(row), "row {row}");
3079            assert_eq!(shared.text_at(row), flat.text_at(row), "row {row}");
3080        }
3081    }
3082
3083    #[test]
3084    fn a_short_string_is_read_out_of_its_view_and_never_out_of_the_arena() {
3085        let flat = Vector::from_values(
3086            LogicalType::Varchar,
3087            &[Value::Varchar("red".into()), Value::Varchar("green".into()), Value::Null],
3088        )
3089        .unwrap();
3090        let shared = flat.shared_text().unwrap();
3091        // Nothing went to the arena, so the whole column resolves with an empty one.
3092        let (views, arena) = shared.text_parts().unwrap();
3093        assert!(arena.is_empty(), "three short strings need no arena");
3094        assert_eq!(views[0].bytes_in(arena), Some(&b"red"[..]));
3095        assert_eq!(shared.value_at(1), Value::Varchar("green".into()));
3096        assert_eq!(shared.value_at(2), Value::Null, "the validity came across");
3097    }
3098
3099    #[test]
3100    fn a_cut_of_a_view_column_shares_the_arena_rather_than_copying_the_bytes() {
3101        let shared = long_strings(64).shared_text().unwrap();
3102        let cut = shared.slice(16, 8).unwrap();
3103        assert_eq!(cut.form(), Form::StringView, "a cut of views is views");
3104        assert_eq!(cut.len(), 8);
3105        assert_eq!(cut.value_at(0), shared.value_at(16));
3106        assert_eq!(cut.value_at(7), shared.value_at(23));
3107        // The arena is the same bytes at the same address, which is the whole point of the form.
3108        let (_, whole) = shared.text_parts().unwrap();
3109        let (_, piece) = cut.text_parts().unwrap();
3110        assert_eq!(piece.as_ptr(), whole.as_ptr(), "the cut shares the page");
3111        assert_eq!(piece.len(), whole.len());
3112    }
3113
3114    #[test]
3115    fn a_flat_string_column_has_to_copy_the_bytes_its_cut_keeps() {
3116        let flat = long_strings(64);
3117        let cut = flat.slice(16, 8).unwrap();
3118        assert_eq!(cut.form(), Form::Flat);
3119        let (_, whole) = flat.text_parts().unwrap();
3120        let (_, piece) = cut.text_parts().unwrap();
3121        assert!(piece.len() < whole.len(), "the flat cut carries only what it kept");
3122    }
3123
3124    #[test]
3125    fn a_gather_of_a_view_column_keeps_the_form_and_a_flatten_copies_out_of_it() {
3126        let shared = long_strings(32).shared_text().unwrap();
3127        let picked: Vec<u32> = (0..32).step_by(3).collect();
3128        let gathered = shared.gather(&picked).unwrap();
3129        assert_eq!(gathered.form(), Form::StringView, "selecting rows moves views, not bytes");
3130        assert_eq!(gathered.len(), picked.len());
3131        for (row, &from) in picked.iter().enumerate() {
3132            assert_eq!(gathered.value_at(row), shared.value_at(from as usize), "row {row}");
3133        }
3134        let flattened = gathered.flatten().unwrap();
3135        assert_eq!(flattened.form(), Form::Flat);
3136        assert_eq!(flattened.iter().collect::<Vec<_>>(), gathered.iter().collect::<Vec<_>>());
3137        // The flatten is what narrows the bytes, so the arena it built holds only the rows it kept.
3138        let (_, narrowed) = flattened.text_parts().unwrap();
3139        let (_, whole) = shared.text_parts().unwrap();
3140        assert!(narrowed.len() < whole.len(), "flattening lets the page go");
3141    }
3142
3143    #[test]
3144    fn a_null_in_a_view_column_survives_being_gathered_and_flattened() {
3145        let shared = long_strings(8)
3146            .with_validity(Validity::from_iter(8, |row| row % 3 != 0))
3147            .shared_text()
3148            .unwrap();
3149        let gathered = shared.gather(&[0, 1, 2, 3, 4]).unwrap();
3150        let expected =
3151            [Value::Null, shared.value_at(1), shared.value_at(2), Value::Null, shared.value_at(4)];
3152        assert_eq!(gathered.iter().collect::<Vec<_>>(), expected);
3153        assert_eq!(gathered.flatten().unwrap().iter().collect::<Vec<_>>(), expected);
3154    }
3155
3156    #[test]
3157    fn both_string_forms_hand_a_kernel_the_same_views_and_the_same_bytes() {
3158        let flat = long_strings(6);
3159        let shared = flat.clone().shared_text().unwrap();
3160        let (flat_views, flat_arena) = flat.text_parts().unwrap();
3161        let (shared_views, shared_arena) = shared.text_parts().unwrap();
3162        assert_eq!(flat_views.len(), shared_views.len());
3163        for row in 0..6 {
3164            assert_eq!(
3165                flat_views[row].bytes_in(flat_arena),
3166                shared_views[row].bytes_in(shared_arena),
3167                "row {row}"
3168            );
3169        }
3170        // Nothing else answers this, which is what keeps a kernel from taking it for a string column.
3171        assert!(Vector::sequence(0, 1, 4).text_parts().is_none());
3172        assert!(integers(&[1, 2, 3]).text_parts().is_none());
3173    }
3174
3175    #[test]
3176    fn a_column_that_is_not_strings_cannot_be_held_as_views() {
3177        let views = vec![StringView::inline("red")];
3178        let arena = Arc::new(Buffer::new());
3179        let wrong = Vector::string_views(LogicalType::Integer, views, arena);
3180        assert!(wrong.is_err(), "an integer column has no views");
3181        assert_eq!(integers(&[1, 2]).shared_text().unwrap().form(), Form::Flat, "left alone");
3182    }
3183
3184    /// A column with enough repeated structure for a symbol table to find something, which is what
3185    /// a real text column has and a column of random bytes does not.
3186    fn sentences(count: usize) -> Vector {
3187        let values: Vec<Value> = (0..count)
3188            .map(|row| {
3189                Value::Varchar(format!(
3190                    "http://example.test/catalogue/section/{}/item/{row}",
3191                    row % 7
3192                ))
3193            })
3194            .collect();
3195        Vector::from_values(LogicalType::Varchar, &values).unwrap()
3196    }
3197
3198    #[test]
3199    fn a_compressed_column_reads_back_the_strings_that_went_into_it() {
3200        let flat = sentences(64);
3201        let coded = flat.clone().compressed().unwrap();
3202        assert_eq!(coded.form(), Form::Fsst, "a text column compresses");
3203        assert_eq!(coded.len(), 64);
3204        for row in 0..64 {
3205            assert_eq!(coded.value_at(row), flat.value_at(row), "row {row}");
3206        }
3207        assert_eq!(coded.flatten().unwrap(), flat, "flattening is the column it came from");
3208    }
3209
3210    #[test]
3211    fn compressing_halves_the_bytes_or_the_column_is_left_flat() {
3212        let flat = sentences(200);
3213        let coded = flat.clone().compressed().unwrap();
3214        let parts = coded.coded_parts().expect("compressed");
3215        // Read through the flat column, because the compressed one has no bytes to hand back where
3216        // they are and answers `None` to `text_at` rather than decompressing into a borrow.
3217        assert_eq!(coded.text_at(0), None, "nothing to borrow until it is flattened");
3218        let plain: usize = (0..200).map(|row| flat.text_at(row).map_or(0, str::len)).sum();
3219        let codes: usize = (0..200).map(|row| parts.row(row).map_or(0, <[u8]>::len)).sum();
3220        assert!(codes * FSST_PAYS_AT <= plain, "{codes} codes against {plain} bytes");
3221        // Text with no repeated structure in it gives a table nothing longer than a byte to find,
3222        // so the codes are the bytes and the column stays where it is rather than paying a
3223        // decompression per read to save nothing.
3224        let mut seed = 0x2545_f491_4f6c_dd1du64;
3225        let values: Vec<Value> = (0..256)
3226            .map(|_| {
3227                let mut text = String::new();
3228                while text.len() < 12 {
3229                    seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
3230                    text.push(char::from(b'!' + ((seed >> 33) % 90) as u8));
3231                }
3232                Value::Varchar(text)
3233            })
3234            .collect();
3235        let noise = Vector::from_values(LogicalType::Varchar, &values).unwrap();
3236        assert_eq!(noise.compressed().unwrap().form(), Form::Flat);
3237    }
3238
3239    #[test]
3240    fn a_cut_of_a_compressed_column_shares_the_codes_and_the_table() {
3241        let coded = sentences(64).compressed().unwrap();
3242        let cut = coded.slice(8, 16).unwrap();
3243        assert_eq!(cut.form(), Form::Fsst);
3244        assert_eq!(cut.len(), 16);
3245        for row in 0..16 {
3246            assert_eq!(cut.value_at(row), coded.value_at(8 + row), "row {row}");
3247        }
3248        let (whole, piece) = (coded.coded_parts().unwrap(), cut.coded_parts().unwrap());
3249        assert_eq!(piece.row(0), whole.row(8), "the spans point into the same codes");
3250    }
3251
3252    #[test]
3253    fn a_gather_of_a_compressed_column_stays_compressed_and_keeps_the_nulls() {
3254        let coded = sentences(32)
3255            .with_validity(Validity::from_iter(32, |row| row % 5 != 2))
3256            .compressed()
3257            .unwrap();
3258        let picked: Vec<u32> = (0..32).step_by(2).collect();
3259        let gathered = coded.gather(&picked).unwrap();
3260        assert_eq!(gathered.form(), Form::Fsst, "selecting rows moves spans, not bytes");
3261        for (row, &from) in picked.iter().enumerate() {
3262            assert_eq!(gathered.value_at(row), coded.value_at(from as usize), "row {row}");
3263        }
3264        assert_eq!(
3265            gathered.flatten().unwrap().iter().collect::<Vec<_>>(),
3266            gathered.iter().collect::<Vec<_>>()
3267        );
3268    }
3269
3270    #[test]
3271    fn a_literal_lands_in_the_same_codes_the_row_holding_it_does() {
3272        let coded = sentences(40).compressed().unwrap();
3273        let parts = coded.coded_parts().expect("compressed");
3274        let text = coded.value_at(11);
3275        let Value::Varchar(text) = text else { panic!("a string column reads back strings") };
3276        assert_eq!(parts.encode(text.as_bytes()), parts.row(11).expect("row 11"));
3277        assert_ne!(parts.encode(b"something else entirely"), parts.row(11).unwrap());
3278    }
3279
3280    #[test]
3281    fn codes_that_run_past_what_is_there_are_refused() {
3282        let table = Arc::new(SymbolTable::empty());
3283        let codes = Arc::new(vec![1u8, 2, 3, 4]);
3284        let good = vec![(0u32, 2u32), (2, 4)];
3285        assert!(
3286            Vector::coded(LogicalType::Varchar, Arc::clone(&codes), good, Arc::clone(&table))
3287                .is_ok()
3288        );
3289        let past = vec![(0u32, 9u32)];
3290        assert!(
3291            Vector::coded(LogicalType::Varchar, Arc::clone(&codes), past, Arc::clone(&table))
3292                .is_err(),
3293            "a span past the end of the codes"
3294        );
3295        let backwards = vec![(3u32, 1u32)];
3296        assert!(
3297            Vector::coded(LogicalType::Varchar, Arc::clone(&codes), backwards, Arc::clone(&table))
3298                .is_err(),
3299            "a span that ends before it starts"
3300        );
3301        let wrong = vec![(0u32, 2u32)];
3302        assert!(
3303            Vector::coded(LogicalType::Integer, codes, wrong, table).is_err(),
3304            "an integer column has no codes"
3305        );
3306    }
3307
3308    #[test]
3309    fn a_view_pointing_past_its_arena_is_refused_at_construction() {
3310        let long = "a string too long to sit inside a view";
3311        let arena: Arc<Buffer<u8>> = Arc::new(long.as_bytes().to_vec().into());
3312        let good = vec![StringView::over(long.as_bytes(), 0)];
3313        assert!(Vector::string_views(LogicalType::Varchar, good, Arc::clone(&arena)).is_ok());
3314        let bad = vec![StringView::over(long.as_bytes(), 4)];
3315        assert!(
3316            Vector::string_views(LogicalType::Varchar, bad, arena).is_err(),
3317            "four bytes short of what the view claims"
3318        );
3319    }
3320}