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    /// Every value in order, as single values.
1130    pub fn iter(&self) -> impl Iterator<Item = Value> + '_ {
1131        (0..self.len).map(|index| self.value_at(index))
1132    }
1133
1134    /// A contiguous run of the values, in the form they are already in.
1135    ///
1136    /// This is the cut [`Self::gather`] cannot do. A gather walks a dictionary to its leaf and
1137    /// copies, so gathering a piece of a dictionary encoded column hands back a flat one, and a
1138    /// caller that only wanted the first thousand rows of a page has silently paid for a copy and
1139    /// thrown the dictionary away. A group by over a dictionary encoded column is the case that
1140    /// cares, and it is most of ClickBench.
1141    ///
1142    /// So each form is cut as itself. A dictionary keeps its dictionary and slices its codes, a
1143    /// sequence stays arithmetic with its start moved along, a constant stays a shorter constant,
1144    /// and a flat body is the one that genuinely has to copy its range.
1145    ///
1146    /// The dictionary itself is shared rather than copied, so a cut is the codes and nothing else.
1147    /// It used to be copied, and on a read of a ClickBench partition that copy was ten percent of
1148    /// the cycles: a page holds one dictionary and is cut into chunk sized pieces, so the whole
1149    /// dictionary was copied once per chunk to be read the same way each time.
1150    ///
1151    /// # Errors
1152    ///
1153    /// If the range runs past the end of the vector, or if the type has no flat layout and the
1154    /// body is one that has to be copied.
1155    pub fn slice(&self, at: usize, len: usize) -> Result<Self> {
1156        let end = at.checked_add(len).ok_or_else(|| Error::internal("a slice that wraps"))?;
1157        if end > self.len {
1158            return Err(Error::internal(format!("rows {at} to {end} of a vector of {}", self.len)));
1159        }
1160        if at == 0 && len == self.len {
1161            return Ok(self.clone());
1162        }
1163        let validity = Validity::from_iter(len, |row| self.validity.is_valid(at + row));
1164        let body = match &self.body {
1165            Body::Constant(value) => Body::Constant(value.clone()),
1166            Body::Sequence { start, step } => {
1167                Body::Sequence { start: start + step * at as i64, step: *step }
1168            }
1169            Body::Dictionary { codes, values } => {
1170                Body::Dictionary { codes: codes[at..end].to_vec(), values: Arc::clone(values) }
1171            }
1172            // The bits are not byte aligned, so a cut either repacks them or moves the row the
1173            // reading starts at. Moving it is one addition and repacking is a pass, and a page is
1174            // cut into chunk sized pieces often enough that the difference is the form.
1175            Body::Packed { words, width, base, offset } => Body::Packed {
1176                words: Arc::clone(words),
1177                width: *width,
1178                base: *base,
1179                offset: offset + at,
1180            },
1181            // The cut a flat string column cannot do. Sixteen bytes a row move and the payload stays
1182            // where the page put it, so taking a chunk out of a column of long strings costs the
1183            // same as taking one out of a column of integers. A flat varchar body copies every byte
1184            // of every long string in the range instead, which is the measurement written down in
1185            // `Chunk::compact`: compaction loses on a varchar column, and this is the half of the
1186            // reason that is about cutting rather than about selecting.
1187            Body::Views { views, arena } => {
1188                Body::Views { views: views[at..end].to_vec(), arena: Arc::clone(arena) }
1189            }
1190            // The spans are absolute positions in the shared codes, so a cut is a run of them and
1191            // nothing has to be rebased. One page of compressed strings, one table, and as many
1192            // chunks over it as the reader wants.
1193            Body::Coded { codes, spans, table } => Body::Coded {
1194                codes: Arc::clone(codes),
1195                spans: spans[at..end].to_vec(),
1196                table: Arc::clone(table),
1197            },
1198            // Only the runs the range touches survive, the first and last of them cut back to where
1199            // the range starts and stops, and every end moved to be relative to the new row zero. A
1200            // cut of a hundred rows out of a column of a hundred million is a handful of runs, which
1201            // is the reason this form is worth cutting as itself rather than copying out.
1202            Body::Runs { ends, values } if len > 0 => {
1203                let first = run_holding(ends, at).unwrap_or(0);
1204                let last = run_holding(ends, end - 1).unwrap_or(first);
1205                let cut: Vec<u32> = ends[first..=last]
1206                    .iter()
1207                    .map(|&stop| stop.min(end as u32) - at as u32)
1208                    .collect();
1209                let values = values.slice(first, last - first + 1)?;
1210                Body::Runs { ends: cut, values: Arc::new(values) }
1211            }
1212            // An empty cut has no run to point at and an empty run length body would be a vector of
1213            // no runs claiming a length, so it comes back as the empty flat vector instead.
1214            Body::Runs { .. } => return self.gather(&[]),
1215            // The one form with nowhere to point, so its range is copied out. A gather is the
1216            // right tool here and does no more than this would: a flat body has no dictionary
1217            // under it for the gather to flatten.
1218            Body::Flat(_) => {
1219                let indices: Vec<u32> =
1220                    (at..end).map(|row| u32::try_from(row).unwrap_or(u32::MAX)).collect();
1221                return self.gather(&indices);
1222            }
1223        };
1224        Ok(Self { ty: self.ty.clone(), len, validity, body })
1225    }
1226
1227    /// The same values in flat form.
1228    ///
1229    /// Flattening a vector that is already flat is free. Flattening any other form costs a copy,
1230    /// which is exactly why the other forms exist and why nothing on the hot path should call
1231    /// this. It is here for the operators that genuinely cannot do better and for the tests that
1232    /// check the other forms against it.
1233    ///
1234    /// A call that copies counts itself against [`Cause::Flatten`], because a flatten on a hot path
1235    /// is the most expensive thing in this crate and the only way to find one is to have the number.
1236    /// A call on a vector that is already flat does not count, since it neither copies nor gives
1237    /// anything up.
1238    ///
1239    /// # Errors
1240    ///
1241    /// If the type is one this crate cannot store flat yet, which today means the nested types.
1242    pub fn flatten(&self) -> Result<Self> {
1243        if let Body::Flat(_) = self.body {
1244            return Ok(self.clone());
1245        }
1246        slow::took(Cause::Flatten);
1247        self.copied((0..self.len).collect(), false)
1248    }
1249
1250    /// The values at the given positions, copied, in a form that does not point back at this vector.
1251    ///
1252    /// This is the copying counterpart to [`Self::dictionary`], and the two are the two halves of
1253    /// the decision `spec/07-execution.md` section 7.1 describes. Which half is right is measured
1254    /// rather than argued, and [`Chunk::compact`](crate::Chunk::compact) is where the measurement
1255    /// is written down.
1256    ///
1257    /// A dictionary chain is walked to its leaf first and the codes composed on the way down, so the
1258    /// copy runs once over the data rather than once per level, and a position that is null at any
1259    /// level comes out null here. The copy is a typed loop per physical layout rather than a `Value`
1260    /// per row, which is the whole point of it and is what [`Self::flatten`] now goes through too.
1261    ///
1262    /// # Errors
1263    ///
1264    /// If the type has no flat layout, which today means the nested types.
1265    pub fn gather(&self, indices: &[u32]) -> Result<Self> {
1266        self.copied(indices.iter().map(|&index| index as usize).collect(), true)
1267    }
1268
1269    /// The copy both [`Self::gather`] and [`Self::flatten`] are.
1270    ///
1271    /// `forms_stay` is the one thing the two want differently. A gather of a constant is a shorter
1272    /// constant and copying it out would be a thousand writes of the same value for nothing, and a
1273    /// gather of string views is a shorter run of views over the same arena rather than a copy of
1274    /// the bytes. Flattening promises flat form to a caller that is about to read the data slice, so
1275    /// for that one both of them have to be written out.
1276    fn copied(&self, at: Vec<usize>, forms_stay: bool) -> Result<Self> {
1277        let rows = at.len();
1278        let (at, leaf) = self.resolve(at);
1279        let live: Vec<bool> = at.iter().map(|&index| index != NOWHERE).collect();
1280        let validity = Validity::from_run(&live);
1281        let body = match &leaf.body {
1282            // Every position holds the same value, so the only thing the gather can change is the
1283            // length and which positions are null. A gather with no null in it is still a constant.
1284            Body::Constant(value) => {
1285                if forms_stay && matches!(validity, Validity::AllValid) {
1286                    return Ok(Self::constant(self.ty.clone(), value.as_ref().clone(), rows));
1287                }
1288                let mut data = empty_data_for(&self.ty)?;
1289                for &index in &at {
1290                    push_value(&mut data, if index == NOWHERE { &Value::Null } else { value })?;
1291                }
1292                Body::Flat(data)
1293            }
1294            // A sequence is arithmetic rather than storage, so the gather is the arithmetic done at
1295            // the positions asked for, and a null writes the zero every other layout writes.
1296            Body::Sequence { start, step } => Body::Flat(Data::Int64(
1297                at.iter()
1298                    .map(|&index| if index == NOWHERE { 0 } else { start + step * index as i64 })
1299                    .collect(),
1300            )),
1301            // A flat body with no values is the untyped null, so every position asked for is null
1302            // whatever was asked for. Going through the copy would build a run of no values and
1303            // call it `rows` long, which is a vector whose length and data disagree.
1304            Body::Flat(Data::Empty) => {
1305                return Ok(Self::constant(self.ty.clone(), Value::Null, rows));
1306            }
1307            Body::Flat(data) => Body::Flat(copy_of(data, &at)),
1308            // The one form whose copy is arithmetic rather than a move of bytes. It goes through a
1309            // typed loop per layout the way the flat copy does, because the alternative is a `Value`
1310            // per row and this is the path a flatten of a scanned column takes.
1311            Body::Packed { words, width, base, offset } => {
1312                Body::Flat(unpack(&self.ty, words, *offset, *width, *base, &at)?)
1313            }
1314            // A gather keeps the form, which is what makes selecting rows out of a string column
1315            // cost sixteen bytes a row instead of the bytes of the strings. The arena it shares is
1316            // the whole arena and not the part the kept rows point at, so a selection that throws
1317            // most of a page away goes on holding the page. That is the trade the form is: a cut and
1318            // a filter are cheap and the memory comes back when the last vector over the page goes,
1319            // and a caller that wants the bytes narrowed asks for a flatten.
1320            Body::Views { views, arena } if forms_stay => Body::Views {
1321                views: at
1322                    .iter()
1323                    .map(|&index| views.get(index).copied().unwrap_or_else(StringView::empty))
1324                    .collect(),
1325                arena: Arc::clone(arena),
1326            },
1327            // Flattening promises a data slice, so the bytes are copied out into an arena of their
1328            // own and the shared one is let go of. The total is known before any of it is copied,
1329            // the way the flat copy works it out, so the new arena is one allocation.
1330            Body::Views { views, arena } => {
1331                let mut out = StringColumn::with_capacity(at.len());
1332                out.reserve_bytes(
1333                    at.iter()
1334                        .filter_map(|&index| views.get(index))
1335                        .filter(|view| !view.is_inline())
1336                        .map(StringView::len)
1337                        .sum(),
1338                );
1339                for &index in &at {
1340                    let bytes = views.get(index).and_then(|view| view.bytes_in(arena));
1341                    out.push_bytes(bytes.unwrap_or_default());
1342                }
1343                Body::Flat(Data::Varlen(out))
1344            }
1345            // A gather keeps the form, because the codes do not move and a span survives being put
1346            // in an order the codes are not in. A position that resolved to nowhere gets the empty
1347            // span, which decompresses to no bytes, which is the zero every other layout writes.
1348            Body::Coded { codes, spans, table } if forms_stay => Body::Coded {
1349                codes: Arc::clone(codes),
1350                spans: at
1351                    .iter()
1352                    .map(|&index| spans.get(index).copied().unwrap_or((0, 0)))
1353                    .collect(),
1354                table: Arc::clone(table),
1355            },
1356            // Flattening decompresses, which is the price of the data slice it promises. The scratch
1357            // buffer is reused across rows, so this is one allocation for the whole column rather
1358            // than one per row the way reading it a value at a time would be.
1359            Body::Coded { codes, spans, table } => {
1360                let mut out = StringColumn::with_capacity(at.len());
1361                let mut scratch = Vec::new();
1362                for &index in &at {
1363                    scratch.clear();
1364                    let span = spans
1365                        .get(index)
1366                        .and_then(|&(from, to)| codes.get(from as usize..to as usize));
1367                    if let Some(span) = span {
1368                        table.decompress(span, &mut scratch)?;
1369                    }
1370                    out.push_bytes(&scratch);
1371                }
1372                Body::Flat(Data::Varlen(out))
1373            }
1374            // Unreachable, because `resolve` walks past both of the forms that point at another
1375            // vector and stops at the first body that does not.
1376            Body::Dictionary { .. } | Body::Runs { .. } => {
1377                return Err(Error::internal(
1378                    "a form that points somewhere survived being resolved",
1379                ));
1380            }
1381        };
1382        Ok(Self { ty: self.ty.clone(), len: rows, validity, body })
1383    }
1384
1385    /// Where each wanted position lives in the first body that is not a dictionary, and that body.
1386    ///
1387    /// A position that is null anywhere on the way down, or past the end of anything on the way
1388    /// down, comes back as [`NOWHERE`]. That single sentinel is what keeps the copy loop from
1389    /// carrying a validity mask alongside the positions it is already walking.
1390    fn resolve(&self, mut at: Vec<usize>) -> (Vec<usize>, &Self) {
1391        let mut source = self;
1392        loop {
1393            for slot in &mut at {
1394                if *slot >= source.len || !source.validity.is_valid(*slot) {
1395                    *slot = NOWHERE;
1396                }
1397            }
1398            source = match &source.body {
1399                Body::Dictionary { codes, values } => {
1400                    for slot in &mut at {
1401                        *slot = match codes.get(*slot) {
1402                            Some(&code) => code as usize,
1403                            None => NOWHERE,
1404                        };
1405                    }
1406                    values.as_ref()
1407                }
1408                // A run length body is a dictionary whose code is worked out from the position
1409                // rather than stored, so the walk down is the same walk with a search where the
1410                // lookup was. `NOWHERE` searches for nothing and stays `NOWHERE`.
1411                Body::Runs { ends, values } => {
1412                    for slot in &mut at {
1413                        *slot = run_holding(ends, *slot).unwrap_or(NOWHERE);
1414                    }
1415                    values.as_ref()
1416                }
1417                _ => return (at, source),
1418            };
1419        }
1420    }
1421}
1422
1423/// So that a kernel can take its operands as either a list of vectors or a list of references.
1424///
1425/// A caller that built a `Vec<Vector>` and a caller whose operands are already somewhere else, in a
1426/// chunk or in an evaluator's scratch, want the same kernel. Without this the second kind has to
1427/// clone every operand into a `Vec` to satisfy the signature, and a clone of a vector is a copy of
1428/// the whole column, so the type would be charging real memory traffic for nothing.
1429impl AsRef<Vector> for Vector {
1430    fn as_ref(&self) -> &Vector {
1431        self
1432    }
1433}
1434
1435/// The bits of a packed vector and what they mean, for a kernel that wants to stay in code space.
1436///
1437/// Borrowed from the vector rather than owning anything, so getting one costs nothing and a kernel
1438/// that finds it cannot use them has given up nothing by asking.
1439#[derive(Debug, Clone, Copy)]
1440pub struct Packed<'a> {
1441    words: &'a [u64],
1442    width: u32,
1443    base: i128,
1444    offset: usize,
1445}
1446
1447impl Packed<'_> {
1448    /// How many bits one code takes, between one and [`PACKED_WIDTH_MAX`].
1449    #[must_use]
1450    pub fn width(&self) -> u32 {
1451        self.width
1452    }
1453
1454    /// What zero means, so that the value of a row is the base plus its code.
1455    #[must_use]
1456    pub fn base(&self) -> i128 {
1457        self.base
1458    }
1459
1460    /// The largest value this vector can be holding, whatever it is actually holding.
1461    ///
1462    /// With [`Self::base`] this is the pair a comparison kernel wants first. A literal outside the
1463    /// two answers every row of the vector the same way, which is a whole chunk decided without a
1464    /// bit being read, and that is the case a zone map would have caught if there were one here.
1465    #[must_use]
1466    pub fn ceiling(&self) -> i128 {
1467        self.base + i128::from(u64::MAX >> (u64::BITS - self.width))
1468    }
1469
1470    /// The code of row `row`, which is its value minus [`Self::base`].
1471    ///
1472    /// Out of range rows read as zero rather than panicking, the way every other accessor in this
1473    /// file answers for a row that is not there.
1474    #[must_use]
1475    pub fn code(&self, row: usize) -> u64 {
1476        code_at(self.words, (self.offset + row) * self.width as usize, self.width)
1477    }
1478
1479    /// Which code a value would have, and `None` for a value this vector cannot be holding.
1480    ///
1481    /// The translation a comparison does once per vector so that it does not have to unpack once per
1482    /// row. `None` is the useful answer rather than a failure: it says the literal is outside the
1483    /// packed range, so every row compares against it the same way.
1484    #[must_use]
1485    pub fn code_of(&self, value: i128) -> Option<u64> {
1486        u64::try_from(value.checked_sub(self.base)?).ok().filter(|&code| code <= self.mask())
1487    }
1488
1489    /// The largest code the width allows.
1490    fn mask(&self) -> u64 {
1491        u64::MAX >> (u64::BITS - self.width)
1492    }
1493}
1494
1495/// The widest a packed code is allowed to be.
1496///
1497/// Sixty three rather than sixty four so that a mask is `u64::MAX >> (64 - width)` with no shift of
1498/// a whole word in it, and reading a code is one branch on whether it straddles rather than two. A
1499/// sixty four bit code saves nothing anyway, since it is the layout it came from.
1500pub const PACKED_WIDTH_MAX: u32 = 63;
1501
1502/// How much smaller packing has to be before it is worth the shift and the mask on every read.
1503///
1504/// Two, so a column packs when the bits come to half the flat size or less. A column that would save
1505/// a tenth stays flat, because a tenth of a column is not worth turning every read of it into
1506/// arithmetic, and the whole argument for the form is that a narrow column saves most of itself.
1507pub const PACKING_PAYS_AT: usize = 2;
1508
1509/// How much smaller compressing has to be before it is worth a decompression on every read.
1510///
1511/// Two, the same rule packing follows and for the same reason. FSST gets about that on text, so a
1512/// column of English or of URLs compresses and a column of short codes or of random bytes does not,
1513/// which is the right answer for both.
1514pub const FSST_PAYS_AT: usize = 2;
1515
1516/// The codes of a compressed column and the table they are against.
1517///
1518/// Handed out by [`Vector::coded_parts`] so a kernel can work in code space. Nothing here
1519/// decompresses, which is the point: [`Self::encode`] puts the literal into the same space the rows
1520/// are already in, and after that an equality test is a byte slice comparison.
1521#[derive(Debug, Clone, Copy)]
1522pub struct Coded<'a> {
1523    codes: &'a [u8],
1524    spans: &'a [(u32, u32)],
1525    table: &'a SymbolTable,
1526}
1527
1528impl Coded<'_> {
1529    /// The table every row in this vector is compressed against.
1530    #[must_use]
1531    pub fn table(&self) -> &SymbolTable {
1532        self.table
1533    }
1534
1535    /// The code bytes of one row, still compressed.
1536    #[must_use]
1537    pub fn row(&self, row: usize) -> Option<&[u8]> {
1538        let &(from, to) = self.spans.get(row)?;
1539        self.codes.get(from as usize..to as usize)
1540    }
1541
1542    /// Some bytes in the code space this vector is in.
1543    ///
1544    /// The literal side of an equality filter. Compressing is a function of the table and the bytes,
1545    /// so two strings compress to the same codes exactly when they are the same string, and an
1546    /// equality test on the codes is an equality test on the strings with no decompression in it.
1547    #[must_use]
1548    pub fn encode(&self, bytes: &[u8]) -> Vec<u8> {
1549        let mut out = Vec::with_capacity(bytes.len());
1550        self.table.compress(bytes, &mut out);
1551        out
1552    }
1553}
1554
1555/// How many words hold `len` codes of `width` bits.
1556fn words_for(len: usize, width: u32) -> usize {
1557    (len * width as usize).div_ceil(u64::BITS as usize)
1558}
1559
1560/// The lowest and highest value a type's layout can hold, and `None` for a type with no integer one.
1561///
1562/// This is also the test of whether a type can be packed at all, and it is the only one, so the
1563/// layouts listed here and the layouts [`pack`] and [`unpack`] know how to walk are the same list
1564/// from the same macro and cannot drift apart.
1565fn layout_range(ty: &LogicalType) -> Option<(i128, i128)> {
1566    use rudb_common::PhysicalType as P;
1567    macro_rules! ranges {
1568        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
1569            match ty.physical() {
1570                $(P::$variant => Some((i128::from(<$native>::MIN), i128::from(<$native>::MAX))),)+
1571                _ => None,
1572            }
1573        };
1574    }
1575    crate::for_each_layout!(exact, ranges)
1576}
1577
1578/// The lowest and highest value in the first `len` slots of a run of integer data.
1579///
1580/// `None` for data that is not integers, which is what says a column cannot be packed. The null
1581/// slots are in the span, holding whatever zero was written into them, which
1582/// [`Vector::bit_packed`] says more about.
1583fn span_of(data: &Data, len: usize) -> Option<(i128, i128)> {
1584    macro_rules! spans {
1585        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
1586            match data {
1587                $(Data::$variant(values) => {
1588                    let mut low = i128::MAX;
1589                    let mut high = i128::MIN;
1590                    for &value in values.as_slice().iter().take(len) {
1591                        let value = i128::from(value);
1592                        low = low.min(value);
1593                        high = high.max(value);
1594                    }
1595                    (low <= high).then_some((low, high))
1596                })+
1597                _ => None,
1598            }
1599        };
1600    }
1601    crate::for_each_layout!(exact, spans)
1602}
1603
1604/// The first `len` values of a run of integer data, written out as codes of `width` bits from `base`.
1605fn pack(data: &Data, len: usize, base: i128, width: u32) -> Vec<u64> {
1606    let mut words = vec![0u64; words_for(len, width)];
1607    macro_rules! packing {
1608        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
1609            match data {
1610                $(Data::$variant(values) => {
1611                    for (row, &value) in values.as_slice().iter().take(len).enumerate() {
1612                        // In range because `base` and `width` came from the span of this same run.
1613                        let code = u64::try_from(i128::from(value) - base).unwrap_or(0);
1614                        write_code(&mut words, row * width as usize, width, code);
1615                    }
1616                })+
1617                _ => {}
1618            }
1619        };
1620    }
1621    crate::for_each_layout!(exact, packing);
1622    words
1623}
1624
1625/// The codes at the given rows, unpacked into the flat layout the type calls for.
1626///
1627/// A row of [`NOWHERE`] writes the layout's zero, which is the rule [`copy_of`] follows for the same
1628/// reason: every layout here is a parallel array to a validity mask, so a null takes a slot.
1629///
1630/// # Errors
1631///
1632/// If the type has no flat layout, which a packed vector cannot have and which is checked when one
1633/// is built, so an error here is a bug rather than a caller mistake.
1634fn unpack(
1635    ty: &LogicalType,
1636    words: &[u64],
1637    offset: usize,
1638    width: u32,
1639    base: i128,
1640    at: &[usize],
1641) -> Result<Data> {
1642    let mut out = empty_data_for(ty)?;
1643    let value_of = |row: usize| {
1644        if row == NOWHERE {
1645            return None;
1646        }
1647        Some(base + i128::from(code_at(words, (offset + row) * width as usize, width)))
1648    };
1649    macro_rules! unpacking {
1650        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
1651            match &mut out {
1652                $(Data::$variant(values) => {
1653                    values.reserve(at.len());
1654                    for &row in at {
1655                        // In range because both ends of it were checked when the vector was built.
1656                        let value = value_of(row)
1657                            .and_then(|value| <$native>::try_from(value).ok())
1658                            .unwrap_or($zero);
1659                        values.push(value);
1660                    }
1661                })+
1662                _ => {
1663                    return Err(Error::internal(format!(
1664                        "a {ty} vector was packed, which no integer layout allows"
1665                    )));
1666                }
1667            }
1668        };
1669    }
1670    crate::for_each_layout!(exact, unpacking);
1671    Ok(out)
1672}
1673
1674/// The `width` bits starting at `bit`, low end first.
1675///
1676/// Zero for bits past the end of the words, which keeps a read of a row that is not there from
1677/// panicking and matches what every other accessor here does with one.
1678fn code_at(words: &[u64], bit: usize, width: u32) -> u64 {
1679    let word = bit / u64::BITS as usize;
1680    let shift = (bit % u64::BITS as usize) as u32;
1681    let mask = u64::MAX >> (u64::BITS - width);
1682    let low = words.get(word).copied().unwrap_or(0) >> shift;
1683    let taken = u64::BITS - shift;
1684    if taken >= width {
1685        return low & mask;
1686    }
1687    // The code straddles two words, and `taken` is under the width here so it is under sixty four,
1688    // which is what makes the shift below one the hardware will do rather than one it refuses.
1689    let high = words.get(word + 1).copied().unwrap_or(0) << taken;
1690    (low | high) & mask
1691}
1692
1693/// Writes `width` bits of `code` starting at `bit`, over words that started out zero.
1694fn write_code(words: &mut [u64], bit: usize, width: u32, code: u64) {
1695    let word = bit / u64::BITS as usize;
1696    let shift = (bit % u64::BITS as usize) as u32;
1697    words[word] |= code << shift;
1698    let taken = u64::BITS - shift;
1699    if taken < width {
1700        words[word + 1] |= code >> taken;
1701    }
1702}
1703
1704/// One level of dictionary out of however many levels were handed to [`Vector::dictionary`].
1705///
1706/// Every dictionary in the system is built through that constructor and every one of them comes
1707/// through here first, so the invariant this maintains is that the vector a dictionary points at is
1708/// never itself a dictionary that could have been composed away. That makes the work a single `if`
1709/// rather than a loop: the inner vector was already composed when it was built, so composing the
1710/// outer codes through it leaves the result no deeper than the inner vector already was.
1711///
1712/// The codes are indexed rather than fetched with `get`, because the caller has already walked the
1713/// whole outer array to check that every code is in range and the inner array is exactly as long as
1714/// the vector those codes were checked against.
1715fn compose(codes: Vec<u32>, values: Vector) -> (Vec<u32>, Vector) {
1716    // A dictionary carrying a validity of its own is one whose nulls live at this level rather than
1717    // in the values, which is the one thing composition cannot carry down with it.
1718    if !matches!(values.validity, Validity::AllValid) {
1719        return (codes, values);
1720    }
1721    let Vector { ty, len, validity, body } = values;
1722    match body {
1723        Body::Dictionary { codes: inner, values: leaf } => {
1724            debug_assert!(
1725                !matches!(leaf.body, Body::Dictionary { .. })
1726                    || !matches!(leaf.validity, Validity::AllValid),
1727                "a dictionary was stacked on a dictionary without going through the constructor"
1728            );
1729            // The leaf is shared, so taking it out of the `Arc` copies it when something else is
1730            // still holding the same dictionary. That is the rare path: a dictionary over a
1731            // dictionary only arrives from a caller that built one that way, and the cut that made
1732            // sharing worth doing produces neither.
1733            (codes.iter().map(|&code| inner[code as usize]).collect(), Arc::unwrap_or_clone(leaf))
1734        }
1735        body => (codes, Vector { ty, len, validity, body }),
1736    }
1737}
1738
1739/// How many rows a run has to cover on average before run length encoding is smaller.
1740///
1741/// A run costs its value plus the four bytes of its end, so on a four byte column a run of two rows
1742/// breaks even and a run of three wins. Wider columns win sooner and narrower ones later, and this
1743/// is the one ratio for all of them because a threshold per width is a table that has to be right
1744/// nine times rather than once. It is a constant with a name so that the sweep that eventually moves
1745/// it has something to move.
1746const RUNS_PAY_AT: usize = 2;
1747
1748/// Which run holds `row`, given ends that are exclusive and increasing.
1749///
1750/// A binary search rather than a scan, because the callers that ask this are the ones that are not
1751/// walking the runs in order: a single value read out of a result set, or a gather at scattered
1752/// positions. Anything walking in order should be reading [`Vector::run_parts`] instead, which is
1753/// what the form is for.
1754fn run_holding(ends: &[u32], row: usize) -> Option<usize> {
1755    let row = u32::try_from(row).ok()?;
1756    let run = match ends.binary_search(&row) {
1757        // The ends are exclusive, so landing exactly on one means the row is the first of the next.
1758        Ok(at) => at + 1,
1759        Err(at) => at,
1760    };
1761    (run < ends.len()).then_some(run)
1762}
1763
1764/// The row each run ends at, for a flat body read alongside the validity that goes with it.
1765///
1766/// Two adjacent nulls are one run, because a reader of either gets a null and cannot tell them
1767/// apart. A null between two equal values is three runs for the same reason, since the null is a
1768/// value of the column as far as anything reading it is concerned.
1769///
1770/// The comparison is per layout rather than per `Value`, which is the whole reason this is a macro.
1771/// A `Value` a row would allocate a string per row on a `VARCHAR` column and would be the exact
1772/// defect `cargo xtask rowloop` exists to fail the build on.
1773fn boundaries(data: &Data, validity: &Validity, len: usize) -> Vec<u32> {
1774    if len == 0 {
1775        return Vec::new();
1776    }
1777    let breaks = |ends: &mut Vec<u32>, mut differs: Box<dyn FnMut(usize, usize) -> bool + '_>| {
1778        for row in 1..len {
1779            let same = match (validity.is_valid(row), validity.is_valid(row - 1)) {
1780                (false, false) => true,
1781                (true, true) => !differs(row, row - 1),
1782                _ => false,
1783            };
1784            if !same {
1785                ends.push(u32::try_from(row).unwrap_or(u32::MAX));
1786            }
1787        }
1788        ends.push(u32::try_from(len).unwrap_or(u32::MAX));
1789    };
1790    let mut ends = Vec::new();
1791    macro_rules! walked {
1792        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
1793            match data {
1794                // No values at all, so every row is the same null and the column is one run.
1795                Data::Empty => ends.push(u32::try_from(len).unwrap_or(u32::MAX)),
1796                $(Data::$variant(values) => {
1797                    breaks(&mut ends, Box::new(|a, b| values.get(a) != values.get(b)));
1798                })+
1799                Data::Varlen(values) => {
1800                    breaks(&mut ends, Box::new(|a, b| values.bytes(a) != values.bytes(b)));
1801                }
1802            }
1803        };
1804    }
1805    crate::for_each_layout!(fixed, walked);
1806    ends
1807}
1808
1809/// The position of a value that is not anywhere, because it is null or out of range.
1810///
1811/// `usize::MAX` rather than an `Option<usize>`, because the copy loop's bounds check rejects it for
1812/// free and an `Option` would put a second branch next to the one already there.
1813const NOWHERE: usize = usize::MAX;
1814
1815/// A run of data copied at the given positions, with a zero wherever the position is [`NOWHERE`].
1816///
1817/// A zero and not a skip, because every layout here is a parallel array to a validity mask and a
1818/// short one would put every value after the first null at the wrong index. It is the same rule
1819/// [`push_value`] follows for a null.
1820fn copy_of(data: &Data, at: &[usize]) -> Data {
1821    macro_rules! copied {
1822        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
1823            match data {
1824                Data::Empty => Data::Empty,
1825                $(Data::$variant(values) => {
1826                    let mut out = Buffer::with_capacity(at.len());
1827                    for &index in at {
1828                        // One bounds check rather than a null test and a bounds check, because
1829                        // `NOWHERE` is past the end of every slice there can be.
1830                        out.push(values.get(index).copied().unwrap_or($zero));
1831                    }
1832                    Data::$variant(out)
1833                })+
1834                // The one layout where a gather is a copy of bytes rather than a copy of fixed
1835                // width slots, and the reason compaction is a decision rather than a default on a
1836                // string column.
1837                Data::Varlen(values) => {
1838                    let mut out = StringColumn::with_capacity(at.len());
1839                    // The bytes are known before any of them are copied, because a view carries its
1840                    // length and the wanted positions are already in hand, so the arena is one
1841                    // allocation rather than a run of doublings that each copy what the last one
1842                    // copied.
1843                    let views = values.views();
1844                    out.reserve_bytes(
1845                        at.iter()
1846                            .filter_map(|&index| views.get(index))
1847                            .filter(|view| !view.is_inline())
1848                            .map(StringView::len)
1849                            .sum(),
1850                    );
1851                    for &index in at {
1852                        out.push_from(values, index);
1853                    }
1854                    Data::Varlen(out)
1855                }
1856            }
1857        };
1858    }
1859    crate::for_each_layout!(fixed, copied)
1860}
1861
1862/// The physical layout a run of data is in, for the check that it matches its type.
1863///
1864/// The two enums name their variants the same way on purpose, so this is one generated arm rather
1865/// than sixteen chances to pair the wrong two up.
1866fn layout_of(data: &Data) -> rudb_common::PhysicalType {
1867    use rudb_common::PhysicalType as P;
1868    macro_rules! layouts {
1869        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
1870            match data {
1871                Data::Empty => P::Empty,
1872                $(Data::$variant(_) => P::$variant,)+
1873            }
1874        };
1875    }
1876    crate::for_each_layout!(all, layouts)
1877}
1878
1879/// One value out of a run of data, given what the run means.
1880///
1881/// The match is on the logical type rather than on the data, because the data cannot tell a `DATE`
1882/// from an `INTEGER` and that is the whole reason the two are kept apart.
1883fn value_from(ty: &LogicalType, data: &Data, index: usize) -> Value {
1884    let signed = || data.signed_at(index);
1885    let unsigned = || data.unsigned_at(index);
1886    let value = match ty {
1887        LogicalType::Boolean => match data {
1888            Data::Bool(v) => v.get(index).map(|&x| Value::Boolean(x)),
1889            _ => None,
1890        },
1891        LogicalType::TinyInt => signed().and_then(|x| i8::try_from(x).ok()).map(Value::TinyInt),
1892        LogicalType::SmallInt => signed().and_then(|x| i16::try_from(x).ok()).map(Value::SmallInt),
1893        LogicalType::Integer => signed().and_then(|x| i32::try_from(x).ok()).map(Value::Integer),
1894        LogicalType::BigInt => signed().and_then(|x| i64::try_from(x).ok()).map(Value::BigInt),
1895        LogicalType::HugeInt => signed().map(Value::HugeInt),
1896        LogicalType::UTinyInt => unsigned().and_then(|x| u8::try_from(x).ok()).map(Value::UTinyInt),
1897        LogicalType::USmallInt => {
1898            unsigned().and_then(|x| u16::try_from(x).ok()).map(Value::USmallInt)
1899        }
1900        LogicalType::UInteger => {
1901            unsigned().and_then(|x| u32::try_from(x).ok()).map(Value::UInteger)
1902        }
1903        LogicalType::UBigInt => unsigned().and_then(|x| u64::try_from(x).ok()).map(Value::UBigInt),
1904        LogicalType::UHugeInt => unsigned().map(Value::UHugeInt),
1905        LogicalType::Float => match data {
1906            Data::Float32(v) => v.get(index).map(|&x| Value::Float(x)),
1907            _ => None,
1908        },
1909        LogicalType::Double => match data {
1910            Data::Float64(v) => v.get(index).map(|&x| Value::Double(x)),
1911            _ => None,
1912        },
1913        LogicalType::Decimal { width, scale } => {
1914            signed().map(|unscaled| Value::Decimal { unscaled, width: *width, scale: *scale })
1915        }
1916        LogicalType::Varchar | LogicalType::Blob | LogicalType::Bit => {
1917            data.bytes_at(index).map(|bytes| bytes_as(ty, bytes))
1918        }
1919        LogicalType::Date => signed().and_then(|x| i32::try_from(x).ok()).map(Value::Date),
1920        LogicalType::Time | LogicalType::TimeTz => {
1921            signed().and_then(|x| i64::try_from(x).ok()).map(Value::Time)
1922        }
1923        LogicalType::Timestamp
1924        | LogicalType::TimestampS
1925        | LogicalType::TimestampMs
1926        | LogicalType::TimestampNs
1927        | LogicalType::TimestampTz => {
1928            signed().and_then(|x| i64::try_from(x).ok()).map(Value::Timestamp)
1929        }
1930        LogicalType::Interval => match data {
1931            Data::Interval(v) => {
1932                v.get(index).map(|&(months, days, micros)| Value::Interval { months, days, micros })
1933            }
1934            _ => None,
1935        },
1936        _ => None,
1937    };
1938    value.unwrap_or(Value::Null)
1939}
1940
1941/// One row of a string column as a value, given what its bytes are meant to be read as.
1942///
1943/// Both forms that hold strings come through here, so a row that is a `BLOB` in a flat column is a
1944/// `BLOB` in a string view column too. Bytes that are not text in a `VARCHAR` column are a null
1945/// rather than a panic, since everything that got in went in as a string and a column that has
1946/// something else in it is a bug somewhere earlier that a read should not turn into a crash.
1947fn bytes_as(ty: &LogicalType, bytes: &[u8]) -> Value {
1948    match ty {
1949        LogicalType::Varchar => {
1950            std::str::from_utf8(bytes).map_or(Value::Null, |text| Value::Varchar(text.to_owned()))
1951        }
1952        LogicalType::Blob | LogicalType::Bit => Value::Blob(bytes.to_vec()),
1953        _ => Value::Null,
1954    }
1955}
1956
1957/// An empty run of data of the right layout for a type.
1958fn empty_data_for(ty: &LogicalType) -> Result<Data> {
1959    use rudb_common::PhysicalType as P;
1960    macro_rules! empties {
1961        ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
1962            match ty.physical() {
1963                P::Empty => Data::Empty,
1964                $(P::$variant => Data::$variant(Buffer::new()),)+
1965                P::Varlen => Data::Varlen(StringColumn::new()),
1966                other => {
1967                    return Err(Error::not_implemented(format!(
1968                        "a flat vector of {other:?} data, which arrives with the storage layer"
1969                    )));
1970                }
1971            }
1972        };
1973    }
1974    Ok(crate::for_each_layout!(fixed, empties))
1975}
1976
1977/// Appends one value to a run of data, or a zero of the right shape when it is null.
1978///
1979/// The zero matters. A null still occupies a position, the validity mask is what says it is null,
1980/// and a run of data with a hole in it would put every value after the hole in the wrong place.
1981fn push_value(data: &mut Data, value: &Value) -> Result<()> {
1982    macro_rules! push {
1983        ($vec:expr, $variant:path, $zero:expr) => {
1984            match value {
1985                Value::Null => $vec.push($zero),
1986                $variant(x) => $vec.push(*x),
1987                other => {
1988                    return Err(Error::internal(format!(
1989                        "{other:?} does not belong in this vector"
1990                    )));
1991                }
1992            }
1993        };
1994    }
1995    // A decimal is stored as its unscaled integer in whatever width its precision needs, which
1996    // `LogicalType::physical` decides and which is why the same `Value::Decimal` is at home in four
1997    // different runs. The narrowing cannot fail for a value the binder produced, because the width
1998    // that chose the run is the width in the value, but it is checked rather than assumed because
1999    // an unchecked cast here would silently store a different number.
2000    macro_rules! decimal {
2001        ($vec:expr, $ty:ty, $unscaled:expr) => {
2002            match <$ty>::try_from(*$unscaled) {
2003                Ok(x) => $vec.push(x),
2004                Err(_) => {
2005                    return Err(Error::internal(format!(
2006                        "an unscaled decimal of {} does not fit the run its precision chose",
2007                        $unscaled
2008                    )));
2009                }
2010            }
2011        };
2012    }
2013    match data {
2014        Data::Empty => {}
2015        Data::Bool(v) => push!(v, Value::Boolean, false),
2016        Data::Int8(v) => push!(v, Value::TinyInt, 0),
2017        Data::Int16(v) => match value {
2018            Value::Null => v.push(0),
2019            Value::SmallInt(x) => v.push(*x),
2020            Value::Decimal { unscaled, .. } => decimal!(v, i16, unscaled),
2021            other => return Err(Error::internal(format!("{other:?} is not a 16 bit value"))),
2022        },
2023        Data::Int32(v) => match value {
2024            Value::Null => v.push(0),
2025            Value::Integer(x) | Value::Date(x) => v.push(*x),
2026            Value::Decimal { unscaled, .. } => decimal!(v, i32, unscaled),
2027            other => return Err(Error::internal(format!("{other:?} is not a 32 bit value"))),
2028        },
2029        Data::Int64(v) => match value {
2030            Value::Null => v.push(0),
2031            Value::BigInt(x) | Value::Time(x) | Value::Timestamp(x) => v.push(*x),
2032            Value::Decimal { unscaled, .. } => decimal!(v, i64, unscaled),
2033            other => return Err(Error::internal(format!("{other:?} is not a 64 bit value"))),
2034        },
2035        Data::Int128(v) => match value {
2036            Value::Null => v.push(0),
2037            Value::HugeInt(x) => v.push(*x),
2038            Value::Decimal { unscaled, .. } => v.push(*unscaled),
2039            other => return Err(Error::internal(format!("{other:?} is not a 128 bit value"))),
2040        },
2041        Data::UInt8(v) => push!(v, Value::UTinyInt, 0),
2042        Data::UInt16(v) => push!(v, Value::USmallInt, 0),
2043        Data::UInt32(v) => push!(v, Value::UInteger, 0),
2044        Data::UInt64(v) => push!(v, Value::UBigInt, 0),
2045        Data::UInt128(v) => push!(v, Value::UHugeInt, 0),
2046        Data::Float32(v) => push!(v, Value::Float, 0.0),
2047        Data::Float64(v) => push!(v, Value::Double, 0.0),
2048        Data::Interval(v) => match value {
2049            Value::Null => v.push((0, 0, 0)),
2050            Value::Interval { months, days, micros } => v.push((*months, *days, *micros)),
2051            other => return Err(Error::internal(format!("{other:?} is not an interval"))),
2052        },
2053        Data::Varlen(column) => match value {
2054            Value::Null => {
2055                column.push("");
2056            }
2057            Value::Varchar(text) => {
2058                column.push(text);
2059            }
2060            // A blob goes in as the bytes it is. The column stores a length and some bytes either
2061            // way, so text is the reading of one rather than a different column, and a blob that
2062            // is not UTF-8 is stored exactly like one that happens to be.
2063            Value::Blob(bytes) => {
2064                column.push_bytes(bytes);
2065            }
2066            other => return Err(Error::internal(format!("{other:?} is not a string"))),
2067        },
2068    }
2069    Ok(())
2070}
2071
2072#[cfg(test)]
2073mod tests {
2074    use std::sync::Arc;
2075
2076    use rudb_common::{LogicalType, Value};
2077
2078    use super::{Body, Data, FSST_PAYS_AT, Form, VECTOR_SIZE, Vector};
2079    use crate::buffer::Buffer;
2080    use crate::fsst::SymbolTable;
2081    use crate::string::{StringColumn, StringView};
2082    use crate::validity::Validity;
2083
2084    fn integers(values: &[i32]) -> Vector {
2085        Vector::flat(LogicalType::Integer, Data::Int32(values.to_vec().into())).unwrap()
2086    }
2087
2088    #[test]
2089    fn a_clustered_column_becomes_runs_and_reads_back_the_same() {
2090        let mut values = Vec::new();
2091        for (value, times) in [(7, 400), (8, 300), (7, 324)] {
2092            values.extend(std::iter::repeat_n(value, times));
2093        }
2094        let flat = integers(&values);
2095        let runs = flat.run_encoded().unwrap();
2096        assert_eq!(runs.form(), Form::Rle);
2097        assert_eq!(runs.run_parts().expect("runs").0, [400, 700, 1024]);
2098        assert_eq!(runs.len(), flat.len());
2099        assert_eq!(runs.iter().collect::<Vec<_>>(), flat.iter().collect::<Vec<_>>());
2100        assert!(
2101            runs.footprint() * 10 < flat.footprint(),
2102            "three runs against a thousand rows: {} against {}",
2103            runs.footprint(),
2104            flat.footprint()
2105        );
2106    }
2107
2108    /// The check is worth having in both directions. A form that is only ever bigger than what it
2109    /// replaced is a form that costs a pass over the column to decide not to use.
2110    #[test]
2111    fn a_column_that_does_not_repeat_is_left_flat() {
2112        let flat = integers(&(0..1024).collect::<Vec<i32>>());
2113        assert_eq!(flat.run_encoded().unwrap().form(), Form::Flat);
2114        // Two runs over four rows is exactly break even on a four byte column, and break even is
2115        // not a reason to change form.
2116        assert_eq!(integers(&[1, 1, 2, 2]).run_encoded().unwrap().form(), Form::Flat);
2117        assert_eq!(integers(&[1, 1, 1, 2, 2]).run_encoded().unwrap().form(), Form::Rle);
2118    }
2119
2120    #[test]
2121    fn two_nulls_beside_each_other_are_one_run_and_a_null_between_two_equals_is_a_break() {
2122        let mut values = vec![Value::Integer(4), Value::Integer(4)];
2123        values.extend([Value::Null, Value::Null, Value::Null]);
2124        values.extend(std::iter::repeat_n(Value::Integer(4), 5));
2125        let flat = Vector::from_values(LogicalType::Integer, &values).unwrap();
2126        let runs = flat.run_encoded().unwrap();
2127        assert_eq!(runs.run_parts().expect("runs").0, [2, 5, 10]);
2128        assert_eq!(runs.iter().collect::<Vec<_>>(), values);
2129    }
2130
2131    #[test]
2132    fn slicing_runs_keeps_them_runs_and_cuts_the_first_and_last_one_back() {
2133        let flat = integers(&[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]);
2134        let runs = flat.run_encoded().unwrap();
2135        let piece = runs.slice(3, 6).unwrap();
2136        assert_eq!(piece.form(), Form::Rle, "the form is the whole point");
2137        assert_eq!(piece.run_parts().expect("runs").0, [1, 5, 6]);
2138        assert_eq!(
2139            piece.iter().collect::<Vec<_>>(),
2140            flat.slice(3, 6).unwrap().iter().collect::<Vec<_>>()
2141        );
2142        assert_eq!(runs.slice(0, 0).unwrap().len(), 0);
2143        assert_eq!(runs.slice(0, 12).unwrap().form(), Form::Rle);
2144    }
2145
2146    #[test]
2147    fn gathering_out_of_runs_walks_to_the_values_the_way_it_walks_a_dictionary() {
2148        let mut values = vec![Value::Varchar("red".into()); 4];
2149        values.extend([Value::Null, Value::Null, Value::Null]);
2150        values.extend(vec![Value::Varchar("blue".into()); 4]);
2151        let runs =
2152            Vector::from_values(LogicalType::Varchar, &values).unwrap().run_encoded().unwrap();
2153        assert_eq!(runs.form(), Form::Rle);
2154        let picked = runs.gather(&[8, 0, 5, 2]).unwrap();
2155        assert_eq!(picked.form(), Form::Flat, "a gather copies, whatever it gathered from");
2156        assert_eq!(
2157            picked.iter().collect::<Vec<_>>(),
2158            [values[8].clone(), values[0].clone(), Value::Null, values[2].clone()]
2159        );
2160        assert_eq!(runs.text_at(1), Some("red"));
2161        assert_eq!(runs.text_at(5), None, "a null has no text");
2162        assert_eq!(runs.flatten().unwrap().iter().collect::<Vec<_>>(), values);
2163    }
2164
2165    /// A run length vector over a run length vector turns one search per row into two, and there is
2166    /// nothing in the engine that builds one, so it is refused rather than composed.
2167    #[test]
2168    fn runs_of_runs_are_refused_and_runs_of_a_dictionary_are_not() {
2169        let inner = integers(&[1, 1, 1, 1, 2]).run_encoded().unwrap();
2170        assert_eq!(inner.form(), Form::Rle);
2171        let error = Vector::runs(vec![2, 8], inner).unwrap_err();
2172        assert!(error.to_string().contains("runs of runs"), "{error}");
2173
2174        let words = Vector::from_values(
2175            LogicalType::Varchar,
2176            &[Value::Varchar("red".into()), Value::Varchar("blue".into())],
2177        )
2178        .unwrap();
2179        let dictionary = Vector::dictionary(vec![1, 0], words).unwrap();
2180        let stacked = Vector::runs(vec![4, 9], dictionary).unwrap();
2181        assert_eq!(stacked.len(), 9);
2182        assert_eq!(stacked.value_at(3), Value::Varchar("blue".into()));
2183        assert_eq!(stacked.value_at(4), Value::Varchar("red".into()));
2184    }
2185
2186    #[test]
2187    fn run_ends_have_to_increase_and_there_is_one_value_for_each_of_them() {
2188        let values = integers(&[1, 2]);
2189        assert!(Vector::runs(vec![4], values.clone()).is_err(), "two values and one run");
2190        assert!(Vector::runs(vec![4, 4], values.clone()).is_err(), "an end that repeats");
2191        assert!(Vector::runs(vec![4, 2], values.clone()).is_err(), "an end that goes backwards");
2192        assert!(Vector::runs(vec![0, 2], values.clone()).is_err(), "a first run holding no rows");
2193        assert_eq!(Vector::runs(vec![4, 9], values).unwrap().len(), 9);
2194    }
2195
2196    #[test]
2197    fn a_form_that_is_already_compact_is_left_where_it_is() {
2198        let constant = Vector::constant(LogicalType::Integer, Value::Integer(1), 1000);
2199        assert_eq!(constant.run_encoded().unwrap().form(), Form::Constant);
2200        assert_eq!(Vector::sequence(0, 1, 1000).run_encoded().unwrap().form(), Form::Sequence);
2201    }
2202
2203    /// What makes one accessor cover both forms. A dictionary hands back the codes it stores and a
2204    /// run length vector works the same numbers out, and a kernel writing `values[at[row]]` reads
2205    /// the same rows out of either.
2206    #[test]
2207    fn both_forms_that_point_somewhere_hand_back_a_position_per_row() {
2208        let words = Vector::from_values(
2209            LogicalType::Varchar,
2210            &[Value::Varchar("red".into()), Value::Varchar("blue".into())],
2211        )
2212        .unwrap();
2213        let runs = Vector::runs(vec![3, 5], words.clone()).unwrap();
2214        let (at, values) = runs.positions().expect("runs point somewhere");
2215        assert_eq!(at.as_ref(), [0, 0, 0, 1, 1]);
2216        assert_eq!(values.value_at(at[3] as usize), runs.value_at(3));
2217
2218        let dictionary = Vector::dictionary(vec![1, 0, 1], words).unwrap();
2219        let (at, values) = dictionary.positions().expect("a dictionary points somewhere");
2220        assert_eq!(at.as_ref(), [1, 0, 1]);
2221        assert_eq!(values.value_at(at[0] as usize), dictionary.value_at(0));
2222
2223        assert!(integers(&[1, 2, 3]).positions().is_none(), "a flat vector points at itself");
2224        assert!(Vector::sequence(0, 1, 4).positions().is_none(), "a sequence stores nothing");
2225    }
2226
2227    #[test]
2228    fn slicing_a_dictionary_keeps_it_a_dictionary_where_gathering_would_not() {
2229        let values = Vector::from_values(
2230            LogicalType::Varchar,
2231            &[Value::Varchar("red".into()), Value::Varchar("blue".into())],
2232        )
2233        .unwrap();
2234        let vector = Vector::dictionary(vec![0, 1, 1, 0, 1], values).unwrap();
2235
2236        let piece = vector.slice(1, 3).unwrap();
2237        assert_eq!(piece.form(), Form::Dictionary, "the form is the whole point");
2238        assert_eq!(piece.len(), 3);
2239        assert_eq!(
2240            piece.iter().collect::<Vec<_>>(),
2241            [
2242                Value::Varchar("blue".into()),
2243                Value::Varchar("blue".into()),
2244                Value::Varchar("red".into())
2245            ]
2246        );
2247        assert_eq!(vector.gather(&[1, 2, 3]).unwrap().form(), Form::Flat, "which a gather loses");
2248    }
2249
2250    #[test]
2251    fn slicing_a_dictionary_shares_the_dictionary_rather_than_copying_it() {
2252        // The assertion is about the address and not about the values, because the values were
2253        // right when the dictionary was copied too. A page holds one dictionary and is cut into a
2254        // chunk of codes at a time, so copying the dictionary here is a copy of every string in it
2255        // per chunk, and on a read of a ClickBench partition it was ten percent of the cycles.
2256        let values = Vector::from_values(
2257            LogicalType::Varchar,
2258            &[Value::Varchar("red".into()), Value::Varchar("blue".into())],
2259        )
2260        .unwrap();
2261        let vector = Vector::dictionary(vec![0, 1, 1, 0, 1], values).unwrap();
2262        let Body::Dictionary { values: whole, .. } = &vector.body else {
2263            panic!("a dictionary vector holds a dictionary");
2264        };
2265
2266        let piece = vector.slice(1, 3).unwrap();
2267        let Body::Dictionary { codes, values: cut } = &piece.body else {
2268            panic!("a slice of a dictionary is a dictionary");
2269        };
2270        assert!(Arc::ptr_eq(whole, cut), "the cut copied the dictionary");
2271        assert_eq!(codes, &[1, 1, 0], "the codes are the part that is cut");
2272
2273        // And a cut of a cut shares it too, since that is what a scan does to a page it reads twice.
2274        let again = piece.slice(1, 2).unwrap();
2275        let Body::Dictionary { values: cut, .. } = &again.body else {
2276            panic!("a slice of a slice of a dictionary is a dictionary");
2277        };
2278        assert!(Arc::ptr_eq(whole, cut), "the second cut copied the dictionary");
2279        assert_eq!(
2280            again.iter().collect::<Vec<_>>(),
2281            [Value::Varchar("blue".into()), Value::Varchar("red".into())]
2282        );
2283    }
2284
2285    #[test]
2286    fn a_slice_carries_the_nulls_that_were_in_its_range_and_not_the_others() {
2287        let vector =
2288            integers(&[1, 2, 3, 4]).with_validity(Validity::from_run(&[false, true, false, true]));
2289        let piece = vector.slice(1, 2).unwrap();
2290        assert!(piece.validity().is_valid(0));
2291        assert!(!piece.validity().is_valid(1));
2292        assert_eq!(piece.value_at(1), Value::Null);
2293    }
2294
2295    #[test]
2296    fn slicing_a_sequence_moves_its_start_rather_than_writing_the_values_out() {
2297        let vector = Vector::sequence(100, 5, 10);
2298        let piece = vector.slice(3, 4).unwrap();
2299        assert_eq!(piece.form(), Form::Sequence);
2300        assert_eq!(
2301            piece.iter().collect::<Vec<_>>(),
2302            [Value::BigInt(115), Value::BigInt(120), Value::BigInt(125), Value::BigInt(130)]
2303        );
2304    }
2305
2306    #[test]
2307    fn slicing_a_constant_is_a_shorter_constant() {
2308        let vector = Vector::constant(LogicalType::Integer, Value::Integer(9), 8);
2309        let piece = vector.slice(2, 3).unwrap();
2310        assert_eq!(piece.form(), Form::Constant);
2311        assert_eq!(piece.len(), 3);
2312        assert_eq!(piece.value_at(2), Value::Integer(9));
2313    }
2314
2315    #[test]
2316    fn slicing_the_whole_vector_hands_it_back_as_it_was() {
2317        let vector = integers(&[1, 2, 3]);
2318        assert_eq!(
2319            vector.slice(0, 3).unwrap().iter().collect::<Vec<_>>(),
2320            [Value::Integer(1), Value::Integer(2), Value::Integer(3)]
2321        );
2322    }
2323
2324    #[test]
2325    fn a_slice_past_the_end_is_an_error_rather_than_a_short_vector() {
2326        let error = integers(&[1, 2, 3]).slice(2, 2).unwrap_err();
2327        assert!(error.to_string().contains("of a vector of 3"), "{error}");
2328    }
2329
2330    #[test]
2331    fn the_vector_size_is_the_one_the_design_is_built_around() {
2332        // 1024 and not DuckDB's 2048. A validity mask is 16 u64 words and a vector of string views
2333        // is 16 KiB, both of which are consequences of this number rather than coincidences.
2334        assert_eq!(VECTOR_SIZE, 1024);
2335        assert_eq!(VECTOR_SIZE / 64, 16);
2336    }
2337
2338    #[test]
2339    fn a_flat_vector_reads_back_what_was_put_in_it() {
2340        let vector = integers(&[1, 2, 3]);
2341        assert_eq!(vector.form(), Form::Flat);
2342        assert_eq!(vector.len(), 3);
2343        assert_eq!(vector.value_at(1), Value::Integer(2));
2344        assert_eq!(
2345            vector.iter().collect::<Vec<_>>(),
2346            vec![Value::Integer(1), Value::Integer(2), Value::Integer(3)]
2347        );
2348    }
2349
2350    #[test]
2351    fn a_vector_built_from_values_reads_the_same_values_back() {
2352        let vector = Vector::from_values(
2353            LogicalType::Varchar,
2354            &[
2355                Value::Varchar("a".to_string()),
2356                Value::Null,
2357                Value::Varchar("a string too long to sit inside a view".to_string()),
2358            ],
2359        )
2360        .expect("strings and a null");
2361        assert_eq!(vector.len(), 3);
2362        assert_eq!(vector.value_at(0), Value::Varchar("a".to_string()));
2363        assert_eq!(vector.value_at(1), Value::Null);
2364        assert_eq!(
2365            vector.value_at(2),
2366            Value::Varchar("a string too long to sit inside a view".to_string())
2367        );
2368    }
2369
2370    /// A null still occupies a position. If it did not then every value after it would read back
2371    /// one place to the left, which is the kind of bug that looks like a storage bug for a week.
2372    #[test]
2373    fn a_null_in_the_middle_does_not_move_the_values_after_it() {
2374        let vector = Vector::from_values(
2375            LogicalType::Integer,
2376            &[Value::Integer(1), Value::Null, Value::Integer(3)],
2377        )
2378        .expect("integers and a null");
2379        assert_eq!(vector.value_at(2), Value::Integer(3));
2380        assert!(vector.validity().has_nulls(3), "the middle one is null");
2381    }
2382
2383    #[test]
2384    fn a_value_the_type_cannot_hold_is_refused() {
2385        let wrong = Vector::from_values(LogicalType::Integer, &[Value::Varchar("x".to_string())]);
2386        assert!(wrong.is_err(), "a string is not an integer");
2387    }
2388
2389    #[test]
2390    fn a_type_that_does_not_match_its_layout_is_refused_at_construction() {
2391        // One comparison here against a wrong answer read out three layers later.
2392        let wrong = Vector::flat(LogicalType::Varchar, Data::Int32(vec![1].into()));
2393        assert!(wrong.is_err());
2394        let right = Vector::flat(LogicalType::Date, Data::Int32(vec![1].into()));
2395        assert!(right.is_ok(), "a date is stored in an i32 and that has to be allowed");
2396    }
2397
2398    #[test]
2399    fn a_constant_vector_costs_one_value_whatever_its_length() {
2400        let vector = Vector::constant(LogicalType::Integer, Value::Integer(7), VECTOR_SIZE);
2401        assert_eq!(vector.form(), Form::Constant);
2402        assert_eq!(vector.len(), VECTOR_SIZE);
2403        assert_eq!(vector.value_at(0), Value::Integer(7));
2404        assert_eq!(vector.value_at(VECTOR_SIZE - 1), Value::Integer(7));
2405        assert_eq!(vector.value_at(VECTOR_SIZE), Value::Null, "past the end is null, not a panic");
2406    }
2407
2408    #[test]
2409    fn a_constant_null_is_all_invalid_without_being_told() {
2410        let vector = Vector::constant(LogicalType::Integer, Value::Null, 8);
2411        assert_eq!(vector.validity(), &Validity::AllInvalid);
2412        assert_eq!(vector.value_at(3), Value::Null);
2413    }
2414
2415    #[test]
2416    fn a_sequence_vector_is_sixteen_bytes_of_row_identifiers() {
2417        let vector = Vector::sequence(100, 1, VECTOR_SIZE);
2418        assert_eq!(vector.form(), Form::Sequence);
2419        assert_eq!(vector.value_at(0), Value::BigInt(100));
2420        assert_eq!(vector.value_at(923), Value::BigInt(1023));
2421        let stepped = Vector::sequence(0, 5, 4);
2422        assert_eq!(
2423            stepped.iter().collect::<Vec<_>>(),
2424            vec![Value::BigInt(0), Value::BigInt(5), Value::BigInt(10), Value::BigInt(15)]
2425        );
2426    }
2427
2428    #[test]
2429    fn a_dictionary_vector_reads_through_its_codes() {
2430        let mut column = StringColumn::new();
2431        column.push("red");
2432        column.push("green");
2433        let values = Vector::flat(LogicalType::Varchar, Data::Varlen(column)).unwrap();
2434        let vector = Vector::dictionary(vec![0, 1, 1, 0], values).unwrap();
2435        assert_eq!(vector.form(), Form::Dictionary);
2436        assert_eq!(vector.logical_type(), &LogicalType::Varchar);
2437        assert_eq!(vector.value_at(2), Value::Varchar("green".into()));
2438        assert_eq!(vector.len(), 4);
2439    }
2440
2441    /// The accessor a group by keys a string column through, which has to agree with `value_at` on
2442    /// every position or two rows holding one string end up in two groups.
2443    #[test]
2444    fn text_is_read_where_it_already_is_for_the_forms_that_store_it() {
2445        let mut column = StringColumn::new();
2446        column.push("red");
2447        column.push("green");
2448        column.push("");
2449        let flat = Vector::flat(LogicalType::Varchar, Data::Varlen(column)).unwrap();
2450        for index in 0..flat.len() {
2451            assert_eq!(flat.text_at(index).map(str::to_string), text_of(&flat.value_at(index)));
2452        }
2453        let dictionary = Vector::dictionary(vec![1, 0, 1, 2], flat).unwrap();
2454        for index in 0..dictionary.len() {
2455            assert_eq!(
2456                dictionary.text_at(index).map(str::to_string),
2457                text_of(&dictionary.value_at(index))
2458            );
2459        }
2460        assert_eq!(dictionary.text_at(4), None, "past the end");
2461    }
2462
2463    /// The forms and types that have no text to hand back, which a caller answers by falling back
2464    /// to `value_at`. A blob is the one that would be a correctness bug rather than a slow path,
2465    /// since its bytes are not required to be text and it is not a `VARCHAR` either way.
2466    #[test]
2467    fn text_is_refused_where_it_is_not_stored_as_itself() {
2468        let nulls =
2469            Vector::from_values(LogicalType::Varchar, &[Value::Varchar("red".into()), Value::Null])
2470                .unwrap();
2471        assert_eq!(nulls.text_at(0), Some("red"));
2472        assert_eq!(nulls.text_at(1), None, "a null has no text");
2473        let constant = Vector::constant(LogicalType::Varchar, Value::Varchar("red".into()), 3);
2474        assert_eq!(constant.text_at(0), None, "a constant is not stored per position");
2475        assert_eq!(integers(&[1, 2]).text_at(0), None, "an integer is not text");
2476        let mut bytes = StringColumn::new();
2477        bytes.push("red");
2478        let blob = Vector::flat(LogicalType::Blob, Data::Varlen(bytes)).unwrap();
2479        assert_eq!(blob.text_at(0), None, "a blob is not a varchar");
2480    }
2481
2482    /// The text of a value, for comparing `text_at` against `value_at` position by position.
2483    fn text_of(value: &Value) -> Option<String> {
2484        match value {
2485            Value::Varchar(text) => Some(text.clone()),
2486            _ => None,
2487        }
2488    }
2489
2490    #[test]
2491    fn a_dictionary_code_past_the_end_is_refused() {
2492        // The alternative is a silent read of the wrong value, which is the failure mode the
2493        // entire M3 design has to be careful about.
2494        let values = integers(&[1, 2]);
2495        assert!(Vector::dictionary(vec![0, 2], values).is_err());
2496        // The check runs on the highest code rather than the first bad one, so it has to say that
2497        // no codes at all is fine even when there are no values for them to point at either.
2498        let empty = Vector::dictionary(Vec::new(), integers(&[])).expect("no codes, no values");
2499        assert_eq!(empty.len(), 0);
2500        // And a code of zero against an empty dictionary is still past the end.
2501        assert!(Vector::dictionary(vec![0], integers(&[])).is_err());
2502    }
2503
2504    #[test]
2505    fn every_form_flattens_to_the_same_values_it_reads_out() {
2506        // This is the shape of the equivalence testing in spec/16-testing.md section 16.2, in
2507        // miniature and long before there is an encoded kernel to point it at. A form that reads
2508        // out one way and flattens another is the exact bug that testing exists to catch.
2509        let mut column = StringColumn::new();
2510        column.push("alpha");
2511        column.push("beta");
2512        let dictionary = Vector::dictionary(
2513            vec![1, 0, 1],
2514            Vector::flat(LogicalType::Varchar, Data::Varlen(column)).unwrap(),
2515        )
2516        .unwrap();
2517        let cases = [
2518            Vector::constant(LogicalType::Integer, Value::Integer(3), 5),
2519            Vector::sequence(7, -2, 5),
2520            dictionary,
2521        ];
2522        for vector in cases {
2523            let flat = vector.flatten().unwrap();
2524            assert_eq!(flat.form(), Form::Flat);
2525            assert_eq!(flat.len(), vector.len());
2526            for index in 0..vector.len() {
2527                assert_eq!(flat.value_at(index), vector.value_at(index), "at {index}");
2528            }
2529        }
2530    }
2531
2532    #[test]
2533    fn a_null_still_occupies_a_position_after_flattening() {
2534        // The reason push_value writes a zero for a null rather than skipping it. A run of data
2535        // with a hole in it puts every value after the hole in the wrong place, and the validity
2536        // mask is what says the position is null.
2537        let vector = Vector::sequence(0, 1, 4).with_validity(Validity::from_iter(4, |i| i != 1));
2538        let flat = vector.flatten().unwrap();
2539        assert_eq!(flat.value_at(0), Value::BigInt(0));
2540        assert_eq!(flat.value_at(1), Value::Null);
2541        assert_eq!(flat.value_at(2), Value::BigInt(2));
2542        assert_eq!(flat.value_at(3), Value::BigInt(3));
2543    }
2544
2545    /// A dictionary holds its nulls in the vector it points at, so its own validity is all valid
2546    /// and reading that instead of the values turns a null into whatever zero means for the type.
2547    /// A filter over a nullable column produces exactly this vector, so the bug reaches a result
2548    /// set as `LEFT JOIN` padding that comes back as zeros.
2549    #[test]
2550    fn a_null_behind_a_dictionary_survives_flattening() {
2551        let values =
2552            Vector::from_values(LogicalType::Integer, &[Value::Integer(3), Value::Null]).unwrap();
2553        let dictionary = Vector::dictionary(vec![1, 0, 1], values).unwrap();
2554        let flat = dictionary.flatten().unwrap();
2555        assert_eq!(flat.value_at(0), Value::Null);
2556        assert_eq!(flat.value_at(1), Value::Integer(3));
2557        assert_eq!(flat.value_at(2), Value::Null);
2558    }
2559
2560    /// The property that makes `gather` usable at all: it has to be the same function as reading the
2561    /// wanted positions one at a time, over every form, or compaction changes answers.
2562    #[test]
2563    fn gathering_reads_what_reading_one_position_at_a_time_reads() {
2564        let mut column = StringColumn::new();
2565        column.push("alpha");
2566        column.push("beta");
2567        column.push("gamma");
2568        let cases = [
2569            integers(&[10, 20, 30, 40]),
2570            integers(&[10, 20, 30, 40]).with_validity(Validity::from_iter(4, |i| i != 2)),
2571            Vector::constant(LogicalType::Integer, Value::Integer(9), 4),
2572            Vector::sequence(100, -7, 4),
2573            Vector::sequence(100, -7, 4).with_validity(Validity::from_iter(4, |i| i % 2 == 0)),
2574            Vector::dictionary(
2575                vec![2, 0, 1, 2],
2576                Vector::flat(LogicalType::Varchar, Data::Varlen(column)).unwrap(),
2577            )
2578            .unwrap(),
2579            Vector::dictionary(
2580                vec![1, 0, 1, 0],
2581                Vector::from_values(LogicalType::Integer, &[Value::Integer(5), Value::Null])
2582                    .unwrap(),
2583            )
2584            .unwrap(),
2585        ];
2586        let wanted = [3_u32, 0, 2, 2, 1];
2587        for vector in cases {
2588            let gathered = vector.gather(&wanted).unwrap();
2589            assert_eq!(gathered.len(), wanted.len());
2590            assert_eq!(gathered.logical_type(), vector.logical_type());
2591            for (slot, &index) in wanted.iter().enumerate() {
2592                assert_eq!(
2593                    gathered.value_at(slot),
2594                    vector.value_at(index as usize),
2595                    "slot {slot} of {:?}",
2596                    vector.form()
2597                );
2598            }
2599        }
2600    }
2601
2602    /// A gather past the end is not an error, because the selection that produced the indices is
2603    /// checked by its caller and the one thing that must not happen here is a read of the wrong
2604    /// value. An index nothing answers is null, which is what an outer join pad needs anyway.
2605    #[test]
2606    fn gathering_a_position_that_is_not_there_is_a_null_and_not_a_wrong_value() {
2607        let vector = integers(&[1, 2, 3]);
2608        let gathered = vector.gather(&[2, 9]).unwrap();
2609        assert_eq!(gathered.value_at(0), Value::Integer(3));
2610        assert_eq!(gathered.value_at(1), Value::Null);
2611    }
2612
2613    /// The vector with nothing in it at all, which is what an untyped `NULL` is stored as. Every
2614    /// position asked for is past its end, so the answer is nulls and the length has to be the
2615    /// length that was asked for rather than the length that was there.
2616    #[test]
2617    fn gathering_from_a_vector_of_no_values_is_that_many_nulls() {
2618        let vector = Vector::flat(LogicalType::Null, Data::Empty).unwrap();
2619        let gathered = vector.gather(&[0, 1, 2]).unwrap();
2620        assert_eq!(gathered.len(), 3);
2621        assert_eq!(gathered.value_at(0), Value::Null);
2622        assert_eq!(gathered.value_at(2), Value::Null);
2623    }
2624
2625    /// Every position holds the same value, so a gather with no hole in it has nothing to copy and
2626    /// the result is the constant again rather than a run of a thousand copies of it.
2627    #[test]
2628    fn gathering_a_constant_stays_a_constant() {
2629        let vector = Vector::constant(LogicalType::Integer, Value::Integer(4), 100);
2630        let gathered = vector.gather(&[7, 7, 99]).unwrap();
2631        assert_eq!(gathered.form(), Form::Constant);
2632        assert_eq!(gathered.len(), 3);
2633        assert_eq!(gathered.value_at(2), Value::Integer(4));
2634    }
2635
2636    /// A dictionary over a dictionary is what a second filter over an already filtered chunk builds,
2637    /// and the gather has to walk to the bottom of that chain rather than one step down it. The
2638    /// constructor composes the ordinary chain away, so the one built here is the kind it cannot,
2639    /// which is a level holding nulls of its own.
2640    #[test]
2641    fn gathering_walks_a_dictionary_over_a_dictionary_to_the_values() {
2642        let inner = Vector::dictionary(vec![2, 1, 0], integers(&[7, 8, 9]))
2643            .unwrap()
2644            .with_validity(Validity::from_iter(3, |index| index != 2));
2645        let outer = Vector::dictionary(vec![1, 2], inner).unwrap();
2646        let gathered = outer.gather(&[0, 1]).unwrap();
2647        assert_eq!(gathered.form(), Form::Flat);
2648        assert_eq!(gathered.value_at(0), Value::Integer(8));
2649        assert_eq!(gathered.value_at(1), Value::Null);
2650    }
2651
2652    /// Two filters over one chunk build a dictionary over a dictionary, four conjuncts pushed down
2653    /// separately build four levels of it, and every level is a dependent load on every later read
2654    /// of every row plus a code array that cannot be freed. Composing at construction is one pass
2655    /// over the codes the range check was walking anyway.
2656    #[test]
2657    fn a_dictionary_over_a_dictionary_is_composed_into_one_level() {
2658        let inner = Vector::dictionary(vec![2, 1, 0], integers(&[7, 8, 9])).unwrap();
2659        let outer = Vector::dictionary(vec![1, 2], inner).unwrap();
2660        let (codes, values) = outer.dictionary_parts().unwrap();
2661        assert_eq!(codes, [1, 0]);
2662        assert_eq!(values.form(), Form::Flat);
2663        assert_eq!(outer.value_at(0), Value::Integer(8));
2664        assert_eq!(outer.value_at(1), Value::Integer(7));
2665    }
2666
2667    /// The invariant stated as the thing it is there for, which is that the depth does not grow with
2668    /// the number of filters. Four levels stacked one at a time are one level at the end of it.
2669    #[test]
2670    fn stacking_dictionaries_does_not_make_them_deeper() {
2671        let mut vector = integers(&[10, 20, 30, 40]);
2672        for _ in 0..4 {
2673            vector = Vector::dictionary(vec![3, 2, 1, 0], vector).unwrap();
2674        }
2675        let (codes, values) = vector.dictionary_parts().unwrap();
2676        assert_eq!(values.form(), Form::Flat);
2677        assert_eq!(codes, [0, 1, 2, 3]);
2678        assert_eq!(
2679            vector.iter().collect::<Vec<_>>(),
2680            integers(&[10, 20, 30, 40]).iter().collect::<Vec<_>>()
2681        );
2682    }
2683
2684    /// Composing has to carry the nulls down with it. The values hold them, the codes point at them,
2685    /// and a composed code that lands on a null position is still a null.
2686    #[test]
2687    fn composing_a_dictionary_keeps_the_nulls_its_values_hold() {
2688        let values =
2689            Vector::from_values(LogicalType::Integer, &[Value::Integer(3), Value::Null]).unwrap();
2690        let inner = Vector::dictionary(vec![1, 0, 1], values).unwrap();
2691        let outer = Vector::dictionary(vec![0, 1], inner).unwrap();
2692        assert_eq!(outer.dictionary_parts().unwrap().1.form(), Form::Flat);
2693        assert_eq!(outer.value_at(0), Value::Null);
2694        assert_eq!(outer.value_at(1), Value::Integer(3));
2695    }
2696
2697    /// The one level composition cannot go past. A dictionary that was given a validity of its own is
2698    /// saying its nulls are at that level rather than in the values, and pointing the outer codes
2699    /// straight at the values would read through the holes instead of stopping at them.
2700    #[test]
2701    fn a_dictionary_holding_its_own_nulls_is_not_composed_past() {
2702        let inner = Vector::dictionary(vec![0, 1, 2], integers(&[1, 2, 3]))
2703            .unwrap()
2704            .with_validity(Validity::from_iter(3, |index| index != 1));
2705        let outer = Vector::dictionary(vec![1, 2, 0], inner).unwrap();
2706        assert_eq!(outer.dictionary_parts().unwrap().1.form(), Form::Dictionary);
2707        assert_eq!(outer.value_at(0), Value::Null);
2708        assert_eq!(outer.value_at(1), Value::Integer(3));
2709        assert_eq!(outer.value_at(2), Value::Integer(1));
2710    }
2711
2712    #[test]
2713    fn flattening_a_flat_vector_is_the_same_vector() {
2714        let vector = integers(&[1, 2, 3]);
2715        assert_eq!(vector.flatten().unwrap(), vector);
2716    }
2717
2718    #[test]
2719    fn a_decimal_reads_its_width_and_scale_from_the_type_and_not_the_data() {
2720        let ty = LogicalType::decimal(9, 2).unwrap();
2721        let vector = Vector::flat(ty, Data::Int32(vec![1234].into())).unwrap();
2722        assert_eq!(vector.value_at(0), Value::Decimal { unscaled: 1234, width: 9, scale: 2 });
2723        assert_eq!(vector.value_at(0).to_string(), "12.34");
2724    }
2725
2726    #[test]
2727    fn a_decimal_writes_into_whichever_of_the_four_runs_its_precision_chose() {
2728        // The read path worked at every width and the write path only accepted the 128 bit run, so
2729        // `SELECT 2.5` produced a value nothing could store. All four widths round trip now.
2730        for (width, scale, unscaled) in
2731            [(4u8, 1u8, 25i128), (9, 2, 1234), (18, 3, 123_456), (38, 4, 1_234_567)]
2732        {
2733            let ty = LogicalType::decimal(width, scale).unwrap();
2734            let value = Value::Decimal { unscaled, width, scale };
2735            let vector = Vector::from_values(ty, &[value.clone(), Value::Null]).unwrap();
2736            assert_eq!(vector.value_at(0), value, "a decimal of width {width}");
2737            assert_eq!(vector.value_at(1), Value::Null, "a null decimal of width {width}");
2738        }
2739    }
2740
2741    /// The bytes a blob holds are not required to be text, and a vector of them used to refuse the
2742    /// ones that were not. A byte array column in a Parquet file that nothing annotated is a blob,
2743    /// which is what ClickHouse writes and what ten of the ClickBench queries compare against, so
2744    /// this is the path those take rather than a corner of the type system.
2745    #[test]
2746    fn a_blob_holds_bytes_that_are_not_text() {
2747        let bytes = |raw: &[u8]| Value::Blob(raw.to_vec());
2748        let values = [
2749            bytes(b"a\xffb"),
2750            bytes(b"\x00\x01\x02"),
2751            Value::Null,
2752            bytes(b"\xed\xa0\x80 and long enough to leave the view"),
2753            bytes(b""),
2754        ];
2755        let vector = Vector::from_values(LogicalType::Blob, &values).unwrap();
2756        for (index, value) in values.iter().enumerate() {
2757            assert_eq!(&vector.value_at(index), value, "row {index}");
2758        }
2759    }
2760
2761    #[test]
2762    fn a_decimal_too_wide_for_the_run_its_type_chose_is_an_error_and_not_a_wrong_number() {
2763        // Only reachable by hand, since a value's width is what picked the run. Truncating here
2764        // would store a different number and say nothing about it.
2765        let ty = LogicalType::decimal(4, 1).unwrap();
2766        let value = Value::Decimal { unscaled: 1_000_000, width: 4, scale: 1 };
2767        let error = Vector::from_values(ty, &[value]).unwrap_err();
2768        assert!(error.to_string().contains("does not fit"), "{error}");
2769    }
2770
2771    #[test]
2772    fn a_flat_vector_costs_its_values_and_a_constant_costs_one() {
2773        let flat = integers(&[1; 1000]);
2774        assert!(
2775            flat.footprint() >= 4000,
2776            "a thousand i32 are four thousand bytes: {}",
2777            flat.footprint()
2778        );
2779        // The forms that compute their values rather than storing them cost nothing per value,
2780        // which is the point of having them and is what the memory limit should see.
2781        let constant = Vector::constant(LogicalType::Integer, Value::Integer(1), 1_000_000);
2782        assert!(constant.footprint() < 200, "a constant is one value: {}", constant.footprint());
2783        let sequence = Vector::sequence(0, 1, 1_000_000);
2784        assert!(sequence.footprint() < 200, "a sequence is two numbers: {}", sequence.footprint());
2785    }
2786
2787    #[test]
2788    fn a_string_vector_costs_the_bytes_of_its_long_strings() {
2789        let short =
2790            Vector::from_values(LogicalType::Varchar, &[Value::Varchar("red".into())]).unwrap();
2791        let long = "a string well past the sixteen bytes a view holds inline".to_string();
2792        let spilled =
2793            Vector::from_values(LogicalType::Varchar, &[Value::Varchar(long.clone())]).unwrap();
2794        assert!(
2795            spilled.footprint() >= short.footprint() + long.len(),
2796            "the arena is counted: {} against {}",
2797            spilled.footprint(),
2798            short.footprint()
2799        );
2800    }
2801
2802    /// The cases worth checking are the widths where a code straddles a word boundary, which is
2803    /// every width that does not divide sixty four, and the two ends of the range.
2804    #[test]
2805    fn a_narrow_column_packs_and_reads_back_the_same_at_every_width() {
2806        for width in 1..=20u32 {
2807            let span = (1i64 << width) - 1;
2808            let values: Vec<i64> =
2809                (0..1000).map(|row| 1_000_000 + (row * 7919) % (span + 1)).collect();
2810            let flat =
2811                Vector::flat(LogicalType::BigInt, Data::Int64(values.clone().into())).unwrap();
2812            let packed = flat.bit_packed().unwrap();
2813            assert_eq!(packed.len(), flat.len());
2814            assert_eq!(
2815                packed.iter().collect::<Vec<_>>(),
2816                flat.iter().collect::<Vec<_>>(),
2817                "width {width} read back differently"
2818            );
2819        }
2820    }
2821
2822    #[test]
2823    fn the_width_is_the_bits_the_range_needs_and_not_the_bits_the_type_has() {
2824        let values: Vec<i32> = (0..1024).map(|row| 40 + (row * 2560) / 1023).collect();
2825        let flat = Vector::flat(LogicalType::Integer, Data::Int32(values.into())).unwrap();
2826        let packed = flat.bit_packed().unwrap();
2827        assert_eq!(packed.form(), Form::BitPacked);
2828        let parts = packed.packed_parts().expect("packed");
2829        assert_eq!(parts.width(), 12, "0 to 2560 is twelve bits");
2830        assert_eq!(parts.base(), 40);
2831        assert!(
2832            packed.footprint() * 2 < flat.footprint(),
2833            "twelve bits against thirty two: {} against {}",
2834            packed.footprint(),
2835            flat.footprint()
2836        );
2837    }
2838
2839    /// The check is worth having in both directions, the way the run length one is. A form that is
2840    /// only ever bigger than what it replaced costs a pass over the column to decide not to use.
2841    #[test]
2842    fn a_column_that_uses_its_whole_type_is_left_flat() {
2843        let values: Vec<i32> = (0..1024).map(|row| row * 2_000_000 - 1_000_000_000).collect();
2844        let flat = Vector::flat(LogicalType::Integer, Data::Int32(values.into())).unwrap();
2845        assert_eq!(flat.bit_packed().unwrap().form(), Form::Flat);
2846    }
2847
2848    /// A column of one value would pack to no bits at all, and one run is smaller than any packing
2849    /// of it, so the two forms do not fight over that column.
2850    #[test]
2851    fn a_column_of_one_value_is_left_to_the_run_length_form() {
2852        let flat = integers(&[9; 1024]);
2853        assert_eq!(flat.bit_packed().unwrap().form(), Form::Flat);
2854        assert_eq!(flat.run_encoded().unwrap().form(), Form::Rle);
2855    }
2856
2857    #[test]
2858    fn a_string_column_has_no_range_to_pack() {
2859        let text = Vector::from_values(
2860            LogicalType::Varchar,
2861            &[Value::Varchar("red".into()), Value::Varchar("blue".into())],
2862        )
2863        .unwrap();
2864        assert_eq!(text.bit_packed().unwrap().form(), Form::Flat);
2865    }
2866
2867    /// The cut is the reason the form carries a row to start reading at. It stays packed, it shares
2868    /// the same words, and it reads the rows the range asked for.
2869    #[test]
2870    fn a_cut_of_a_packed_column_stays_packed_and_shares_its_bits() {
2871        let values: Vec<i32> = (0..1024).map(|row| 100 + row % 300).collect();
2872        let flat = Vector::flat(LogicalType::Integer, Data::Int32(values.into())).unwrap();
2873        let packed = flat.bit_packed().unwrap();
2874        let cut = packed.slice(500, 24).unwrap();
2875        assert_eq!(cut.form(), Form::BitPacked);
2876        assert_eq!(cut.len(), 24);
2877        assert_eq!(
2878            cut.iter().collect::<Vec<_>>(),
2879            flat.slice(500, 24).unwrap().iter().collect::<Vec<_>>()
2880        );
2881        assert!(
2882            cut.footprint() >= packed.footprint(),
2883            "a cut shares the words rather than copying a piece of them"
2884        );
2885    }
2886
2887    #[test]
2888    fn a_gather_of_a_packed_column_comes_out_flat_and_keeps_the_nulls() {
2889        let values: Vec<i32> = (0..64).map(|row| 10 + row).collect();
2890        let flat = Vector::flat(LogicalType::Integer, Data::Int32(values.into())).unwrap();
2891        let packed =
2892            flat.bit_packed().unwrap().with_validity(Validity::from_iter(64, |row| row % 3 != 0));
2893        let taken = packed.gather(&[0, 1, 2, 3, 62]).unwrap();
2894        assert_eq!(taken.form(), Form::Flat);
2895        assert_eq!(
2896            taken.iter().collect::<Vec<_>>(),
2897            vec![
2898                Value::Null,
2899                Value::Integer(11),
2900                Value::Integer(12),
2901                Value::Null,
2902                Value::Integer(72)
2903            ]
2904        );
2905    }
2906
2907    /// The pair a comparison kernel asks for before it reads a bit. A literal inside the range has a
2908    /// code and a literal outside it does not, which answers the whole vector at once.
2909    #[test]
2910    fn a_literal_outside_the_packed_range_has_no_code() {
2911        let values: Vec<i32> = (0..256).map(|row| 1000 + row).collect();
2912        let flat = Vector::flat(LogicalType::Integer, Data::Int32(values.into())).unwrap();
2913        let packed = flat.bit_packed().unwrap();
2914        let parts = packed.packed_parts().expect("packed");
2915        assert_eq!(parts.code_of(1000), Some(0));
2916        assert_eq!(parts.code_of(1100), Some(100));
2917        assert_eq!(parts.code_of(999), None);
2918        assert!(parts.ceiling() >= 1255);
2919        assert_eq!(parts.code_of(parts.ceiling() + 1), None);
2920    }
2921
2922    /// The bits arriving from a file rather than from a flat vector, which is what the form is for.
2923    #[test]
2924    fn packed_bits_can_be_handed_in_without_a_flat_vector_to_start_from() {
2925        let packed = Vector::packed(LogicalType::SmallInt, vec![0x0000_0000_0000_4321], 4, 7, 4)
2926            .expect("four codes of four bits");
2927        assert_eq!(
2928            packed.iter().collect::<Vec<_>>(),
2929            vec![Value::SmallInt(8), Value::SmallInt(9), Value::SmallInt(10), Value::SmallInt(11)]
2930        );
2931    }
2932
2933    #[test]
2934    fn packed_bits_that_could_not_hold_what_they_claim_are_refused() {
2935        assert!(Vector::packed(LogicalType::Varchar, vec![0], 4, 0, 4).is_err(), "not an integer");
2936        assert!(Vector::packed(LogicalType::Integer, vec![0], 0, 0, 4).is_err(), "no width");
2937        assert!(Vector::packed(LogicalType::Integer, vec![0], 64, 0, 4).is_err(), "too wide");
2938        assert!(Vector::packed(LogicalType::Integer, vec![0], 8, 0, 9).is_err(), "too few words");
2939        assert!(Vector::packed(LogicalType::TinyInt, vec![0], 8, 100, 8).is_err(), "would not fit");
2940    }
2941
2942    /// A column of strings long enough that the payload is in the arena rather than in the views.
2943    fn long_strings(count: usize) -> Vector {
2944        let values: Vec<Value> = (0..count)
2945            .map(|row| {
2946                Value::Varchar(format!("a string too long to sit inside a view, number {row}"))
2947            })
2948            .collect();
2949        Vector::from_values(LogicalType::Varchar, &values).unwrap()
2950    }
2951
2952    #[test]
2953    fn a_string_column_in_view_form_reads_back_the_same_strings() {
2954        let flat = long_strings(40);
2955        let shared = flat.clone().shared_text().unwrap();
2956        assert_eq!(shared.form(), Form::StringView);
2957        assert_eq!(shared.len(), 40);
2958        for row in 0..40 {
2959            assert_eq!(shared.value_at(row), flat.value_at(row), "row {row}");
2960            assert_eq!(shared.text_at(row), flat.text_at(row), "row {row}");
2961        }
2962    }
2963
2964    #[test]
2965    fn a_short_string_is_read_out_of_its_view_and_never_out_of_the_arena() {
2966        let flat = Vector::from_values(
2967            LogicalType::Varchar,
2968            &[Value::Varchar("red".into()), Value::Varchar("green".into()), Value::Null],
2969        )
2970        .unwrap();
2971        let shared = flat.shared_text().unwrap();
2972        // Nothing went to the arena, so the whole column resolves with an empty one.
2973        let (views, arena) = shared.text_parts().unwrap();
2974        assert!(arena.is_empty(), "three short strings need no arena");
2975        assert_eq!(views[0].bytes_in(arena), Some(&b"red"[..]));
2976        assert_eq!(shared.value_at(1), Value::Varchar("green".into()));
2977        assert_eq!(shared.value_at(2), Value::Null, "the validity came across");
2978    }
2979
2980    #[test]
2981    fn a_cut_of_a_view_column_shares_the_arena_rather_than_copying_the_bytes() {
2982        let shared = long_strings(64).shared_text().unwrap();
2983        let cut = shared.slice(16, 8).unwrap();
2984        assert_eq!(cut.form(), Form::StringView, "a cut of views is views");
2985        assert_eq!(cut.len(), 8);
2986        assert_eq!(cut.value_at(0), shared.value_at(16));
2987        assert_eq!(cut.value_at(7), shared.value_at(23));
2988        // The arena is the same bytes at the same address, which is the whole point of the form.
2989        let (_, whole) = shared.text_parts().unwrap();
2990        let (_, piece) = cut.text_parts().unwrap();
2991        assert_eq!(piece.as_ptr(), whole.as_ptr(), "the cut shares the page");
2992        assert_eq!(piece.len(), whole.len());
2993    }
2994
2995    #[test]
2996    fn a_flat_string_column_has_to_copy_the_bytes_its_cut_keeps() {
2997        let flat = long_strings(64);
2998        let cut = flat.slice(16, 8).unwrap();
2999        assert_eq!(cut.form(), Form::Flat);
3000        let (_, whole) = flat.text_parts().unwrap();
3001        let (_, piece) = cut.text_parts().unwrap();
3002        assert!(piece.len() < whole.len(), "the flat cut carries only what it kept");
3003    }
3004
3005    #[test]
3006    fn a_gather_of_a_view_column_keeps_the_form_and_a_flatten_copies_out_of_it() {
3007        let shared = long_strings(32).shared_text().unwrap();
3008        let picked: Vec<u32> = (0..32).step_by(3).collect();
3009        let gathered = shared.gather(&picked).unwrap();
3010        assert_eq!(gathered.form(), Form::StringView, "selecting rows moves views, not bytes");
3011        assert_eq!(gathered.len(), picked.len());
3012        for (row, &from) in picked.iter().enumerate() {
3013            assert_eq!(gathered.value_at(row), shared.value_at(from as usize), "row {row}");
3014        }
3015        let flattened = gathered.flatten().unwrap();
3016        assert_eq!(flattened.form(), Form::Flat);
3017        assert_eq!(flattened.iter().collect::<Vec<_>>(), gathered.iter().collect::<Vec<_>>());
3018        // The flatten is what narrows the bytes, so the arena it built holds only the rows it kept.
3019        let (_, narrowed) = flattened.text_parts().unwrap();
3020        let (_, whole) = shared.text_parts().unwrap();
3021        assert!(narrowed.len() < whole.len(), "flattening lets the page go");
3022    }
3023
3024    #[test]
3025    fn a_null_in_a_view_column_survives_being_gathered_and_flattened() {
3026        let shared = long_strings(8)
3027            .with_validity(Validity::from_iter(8, |row| row % 3 != 0))
3028            .shared_text()
3029            .unwrap();
3030        let gathered = shared.gather(&[0, 1, 2, 3, 4]).unwrap();
3031        let expected =
3032            [Value::Null, shared.value_at(1), shared.value_at(2), Value::Null, shared.value_at(4)];
3033        assert_eq!(gathered.iter().collect::<Vec<_>>(), expected);
3034        assert_eq!(gathered.flatten().unwrap().iter().collect::<Vec<_>>(), expected);
3035    }
3036
3037    #[test]
3038    fn both_string_forms_hand_a_kernel_the_same_views_and_the_same_bytes() {
3039        let flat = long_strings(6);
3040        let shared = flat.clone().shared_text().unwrap();
3041        let (flat_views, flat_arena) = flat.text_parts().unwrap();
3042        let (shared_views, shared_arena) = shared.text_parts().unwrap();
3043        assert_eq!(flat_views.len(), shared_views.len());
3044        for row in 0..6 {
3045            assert_eq!(
3046                flat_views[row].bytes_in(flat_arena),
3047                shared_views[row].bytes_in(shared_arena),
3048                "row {row}"
3049            );
3050        }
3051        // Nothing else answers this, which is what keeps a kernel from taking it for a string column.
3052        assert!(Vector::sequence(0, 1, 4).text_parts().is_none());
3053        assert!(integers(&[1, 2, 3]).text_parts().is_none());
3054    }
3055
3056    #[test]
3057    fn a_column_that_is_not_strings_cannot_be_held_as_views() {
3058        let views = vec![StringView::inline("red")];
3059        let arena = Arc::new(Buffer::new());
3060        let wrong = Vector::string_views(LogicalType::Integer, views, arena);
3061        assert!(wrong.is_err(), "an integer column has no views");
3062        assert_eq!(integers(&[1, 2]).shared_text().unwrap().form(), Form::Flat, "left alone");
3063    }
3064
3065    /// A column with enough repeated structure for a symbol table to find something, which is what
3066    /// a real text column has and a column of random bytes does not.
3067    fn sentences(count: usize) -> Vector {
3068        let values: Vec<Value> = (0..count)
3069            .map(|row| {
3070                Value::Varchar(format!(
3071                    "http://example.test/catalogue/section/{}/item/{row}",
3072                    row % 7
3073                ))
3074            })
3075            .collect();
3076        Vector::from_values(LogicalType::Varchar, &values).unwrap()
3077    }
3078
3079    #[test]
3080    fn a_compressed_column_reads_back_the_strings_that_went_into_it() {
3081        let flat = sentences(64);
3082        let coded = flat.clone().compressed().unwrap();
3083        assert_eq!(coded.form(), Form::Fsst, "a text column compresses");
3084        assert_eq!(coded.len(), 64);
3085        for row in 0..64 {
3086            assert_eq!(coded.value_at(row), flat.value_at(row), "row {row}");
3087        }
3088        assert_eq!(coded.flatten().unwrap(), flat, "flattening is the column it came from");
3089    }
3090
3091    #[test]
3092    fn compressing_halves_the_bytes_or_the_column_is_left_flat() {
3093        let flat = sentences(200);
3094        let coded = flat.clone().compressed().unwrap();
3095        let parts = coded.coded_parts().expect("compressed");
3096        // Read through the flat column, because the compressed one has no bytes to hand back where
3097        // they are and answers `None` to `text_at` rather than decompressing into a borrow.
3098        assert_eq!(coded.text_at(0), None, "nothing to borrow until it is flattened");
3099        let plain: usize = (0..200).map(|row| flat.text_at(row).map_or(0, str::len)).sum();
3100        let codes: usize = (0..200).map(|row| parts.row(row).map_or(0, <[u8]>::len)).sum();
3101        assert!(codes * FSST_PAYS_AT <= plain, "{codes} codes against {plain} bytes");
3102        // Text with no repeated structure in it gives a table nothing longer than a byte to find,
3103        // so the codes are the bytes and the column stays where it is rather than paying a
3104        // decompression per read to save nothing.
3105        let mut seed = 0x2545_f491_4f6c_dd1du64;
3106        let values: Vec<Value> = (0..256)
3107            .map(|_| {
3108                let mut text = String::new();
3109                while text.len() < 12 {
3110                    seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
3111                    text.push(char::from(b'!' + ((seed >> 33) % 90) as u8));
3112                }
3113                Value::Varchar(text)
3114            })
3115            .collect();
3116        let noise = Vector::from_values(LogicalType::Varchar, &values).unwrap();
3117        assert_eq!(noise.compressed().unwrap().form(), Form::Flat);
3118    }
3119
3120    #[test]
3121    fn a_cut_of_a_compressed_column_shares_the_codes_and_the_table() {
3122        let coded = sentences(64).compressed().unwrap();
3123        let cut = coded.slice(8, 16).unwrap();
3124        assert_eq!(cut.form(), Form::Fsst);
3125        assert_eq!(cut.len(), 16);
3126        for row in 0..16 {
3127            assert_eq!(cut.value_at(row), coded.value_at(8 + row), "row {row}");
3128        }
3129        let (whole, piece) = (coded.coded_parts().unwrap(), cut.coded_parts().unwrap());
3130        assert_eq!(piece.row(0), whole.row(8), "the spans point into the same codes");
3131    }
3132
3133    #[test]
3134    fn a_gather_of_a_compressed_column_stays_compressed_and_keeps_the_nulls() {
3135        let coded = sentences(32)
3136            .with_validity(Validity::from_iter(32, |row| row % 5 != 2))
3137            .compressed()
3138            .unwrap();
3139        let picked: Vec<u32> = (0..32).step_by(2).collect();
3140        let gathered = coded.gather(&picked).unwrap();
3141        assert_eq!(gathered.form(), Form::Fsst, "selecting rows moves spans, not bytes");
3142        for (row, &from) in picked.iter().enumerate() {
3143            assert_eq!(gathered.value_at(row), coded.value_at(from as usize), "row {row}");
3144        }
3145        assert_eq!(
3146            gathered.flatten().unwrap().iter().collect::<Vec<_>>(),
3147            gathered.iter().collect::<Vec<_>>()
3148        );
3149    }
3150
3151    #[test]
3152    fn a_literal_lands_in_the_same_codes_the_row_holding_it_does() {
3153        let coded = sentences(40).compressed().unwrap();
3154        let parts = coded.coded_parts().expect("compressed");
3155        let text = coded.value_at(11);
3156        let Value::Varchar(text) = text else { panic!("a string column reads back strings") };
3157        assert_eq!(parts.encode(text.as_bytes()), parts.row(11).expect("row 11"));
3158        assert_ne!(parts.encode(b"something else entirely"), parts.row(11).unwrap());
3159    }
3160
3161    #[test]
3162    fn codes_that_run_past_what_is_there_are_refused() {
3163        let table = Arc::new(SymbolTable::empty());
3164        let codes = Arc::new(vec![1u8, 2, 3, 4]);
3165        let good = vec![(0u32, 2u32), (2, 4)];
3166        assert!(
3167            Vector::coded(LogicalType::Varchar, Arc::clone(&codes), good, Arc::clone(&table))
3168                .is_ok()
3169        );
3170        let past = vec![(0u32, 9u32)];
3171        assert!(
3172            Vector::coded(LogicalType::Varchar, Arc::clone(&codes), past, Arc::clone(&table))
3173                .is_err(),
3174            "a span past the end of the codes"
3175        );
3176        let backwards = vec![(3u32, 1u32)];
3177        assert!(
3178            Vector::coded(LogicalType::Varchar, Arc::clone(&codes), backwards, Arc::clone(&table))
3179                .is_err(),
3180            "a span that ends before it starts"
3181        );
3182        let wrong = vec![(0u32, 2u32)];
3183        assert!(
3184            Vector::coded(LogicalType::Integer, codes, wrong, table).is_err(),
3185            "an integer column has no codes"
3186        );
3187    }
3188
3189    #[test]
3190    fn a_view_pointing_past_its_arena_is_refused_at_construction() {
3191        let long = "a string too long to sit inside a view";
3192        let arena: Arc<Buffer<u8>> = Arc::new(long.as_bytes().to_vec().into());
3193        let good = vec![StringView::over(long.as_bytes(), 0)];
3194        assert!(Vector::string_views(LogicalType::Varchar, good, Arc::clone(&arena)).is_ok());
3195        let bad = vec![StringView::over(long.as_bytes(), 4)];
3196        assert!(
3197            Vector::string_views(LogicalType::Varchar, bad, arena).is_err(),
3198            "four bytes short of what the view claims"
3199        );
3200    }
3201}