Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-plan/src/typed.rs

//! Typed values as order-preserving `u64` codes.
//!
//! Inside the engine every cell stays a `u64` ([`Value`]); a relation column has a
//! [`Type`], and each type has a code whose `u64` order and equality are the type's own, so
//! every kernel (joins, anti-joins, dedupe, sorts, aggregates, range joins) runs unchanged
//! on typed columns:
//!
//! | Type | Code | Null |
//! |---|---|---|
//! | [`Type::U64`] | the value | none |
//! | [`Type::I64`] | the bits with the sign bit flipped (a date its days since 1970-01-01, a timestamp its nanoseconds since 1970-01-01T00:00Z: [`time_value`]) | [`NULL`] (so `i64::MAX` is refused) |
//! | [`Type::F64`] | -0.0 as 0.0, every NaN as one; negative: the bits inverted, else the sign bit set (NaN after +inf) | [`NULL`] |
//! | [`Type::Bool`] | 0 or 1 | [`NULL`] |
//! | [`Type::Str`] | the string's id in the run's [`Dict`], whose ids follow the strings' byte order | [`NULL`] |

use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;

use arrow_array::builder::{BooleanBuilder, Float64Builder, Int64Builder, StringBuilder};
use arrow_array::{Array, ArrayRef, cast::AsArray, types};
use arrow_schema::DataType;

use crate::cols::Par;
use crate::facts::{Column, column_of};
use crate::rules::Value;
use crate::{PlanError, Result};

/// The code of a null in a column of any type but [`Type::U64`].
pub const NULL: Value = u64::MAX;

const SIGN: u64 = 1 << 63;

/// The type of a relation column.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub enum Type {
    /// An unsigned 64-bit integer (an id, an address, a count): the type of every column of
    /// a relation declared without types. It has no null.
    #[default]
    U64,
    /// A signed 64-bit integer (`i64::MAX` is taken by the null code and refused).
    I64,
    /// A 64-bit float, in IEEE total order with -0.0 equal to 0.0 and every NaN one value,
    /// after +inf.
    F64,
    /// A boolean, false before true.
    Bool,
    /// A UTF-8 string, in byte order (that is code point order).
    Str,
}

impl Type {
    /// The type's name as the plan prints it.
    pub fn name(self) -> &'static str {
        match self {
            Type::U64 => "u64",
            Type::I64 => "i64",
            Type::F64 => "f64",
            Type::Bool => "bool",
            Type::Str => "str",
        }
    }

    /// Whether a column of this type may hold nulls (every type but [`Type::U64`]).
    pub fn nullable(self) -> bool {
        self != Type::U64
    }

    /// The value of `code` in a column of this type; a string through `dict` (without it,
    /// a string reads as its id, `#id`).
    pub fn decode(self, code: Value, dict: Option<&Dict>) -> Datum {
        if self.nullable() && code == NULL {
            return Datum::Null;
        }
        match self {
            Type::U64 => Datum::U64(code),
            Type::I64 => Datum::I64(i64_of(code)),
            Type::F64 => Datum::F64(f64_of(code)),
            Type::Bool => Datum::Bool(code != 0),
            Type::Str => match dict.and_then(|d| d.get(code)) {
                Some(s) => Datum::Str(s.to_string()),
                None => Datum::Str(format!("#{code}")),
            },
        }
    }

    /// The code of `d` in a column of this type (a string through `dict`); `None` when it
    /// is not of this type, does not fit (`i64::MAX`), or is a string `dict` lacks.
    pub fn encode(self, d: &Datum, dict: Option<&Dict>) -> Option<Value> {
        match (self, d) {
            (t, Datum::Null) if t.nullable() => Some(NULL),
            (Type::U64, Datum::U64(x)) => Some(*x),
            (Type::I64, Datum::I64(x)) if *x != i64::MAX => Some(i64_code(*x)),
            (Type::F64, Datum::F64(x)) => Some(f64_code(*x)),
            (Type::Bool, Datum::Bool(b)) => Some(*b as Value),
            (Type::Str, Datum::Str(s)) => dict?.id(s).map(Value::from),
            _ => None,
        }
    }
}

impl fmt::Display for Type {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

/// The code of a signed integer.
#[inline]
pub(crate) fn i64_code(x: i64) -> Value {
    (x as u64) ^ SIGN
}

/// The integer of a code.
#[inline]
pub(crate) fn i64_of(c: Value) -> i64 {
    (c ^ SIGN) as i64
}

/// The code of a float (-0.0 as 0.0, every NaN as one).
#[inline]
pub(crate) fn f64_code(x: f64) -> Value {
    let x = if x == 0.0 {
        0.0
    } else if x.is_nan() {
        f64::NAN
    } else {
        x
    };
    let b = x.to_bits();
    if b & SIGN != 0 { !b } else { b | SIGN }
}

/// The float of a code.
#[inline]
pub(crate) fn f64_of(c: Value) -> f64 {
    f64::from_bits(if c & SIGN != 0 { c & !SIGN } else { !c })
}

/// A typed value at the edge of the engine (input facts, results, proofs).
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum Datum {
    /// An unsigned integer.
    U64(u64),
    /// A signed integer.
    I64(i64),
    /// A float.
    F64(f64),
    /// A boolean.
    Bool(bool),
    /// A string.
    Str(String),
    /// No value.
    Null,
}

impl fmt::Display for Datum {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Datum::U64(x) => write!(f, "{x}"),
            Datum::I64(x) => write!(f, "{x}"),
            Datum::F64(x) => write!(f, "{x:?}"),
            Datum::Bool(b) => write!(f, "{b}"),
            Datum::Str(s) => write!(f, "{s:?}"),
            Datum::Null => f.write_str("null"),
        }
    }
}

/// The strings of a run, each once: first those read and the plan's constants, sorted by
/// their bytes (a string's id is its place, so these ids compare as the strings do), then
/// the strings rules made in the run that were not among them ([`Dict::sorted_len`] on),
/// in the order they were made: their ids do not follow the byte order.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Dict {
    bytes: Vec<u8>,
    /// `strings + 1` offsets into `bytes`.
    offsets: Vec<usize>,
    /// The number of strings sorted by their bytes (ids `0..sorted`).
    sorted: usize,
    /// The made strings' ids.
    made: HashMap<String, u32>,
}

impl Dict {
    /// The number of strings.
    pub fn len(&self) -> usize {
        self.offsets.len().saturating_sub(1)
    }

    /// True when there are none.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// The string of id `id`.
    pub fn get(&self, id: Value) -> Option<&str> {
        let i = usize::try_from(id).ok()?;
        if i >= self.len() {
            return None;
        }
        let s = &self.bytes[self.offsets[i]..self.offsets[i + 1]];
        Some(std::str::from_utf8(s).expect("dictionary strings are UTF-8"))
    }

    /// The id of `s`.
    pub fn id(&self, s: &str) -> Option<u32> {
        let i = self.lower_bound(s);
        if (i as usize) < self.sorted && self.get(i as Value) == Some(s) {
            return Some(i);
        }
        self.made.get(s).copied()
    }

    /// The number of strings sorted by their bytes: the ids below it follow the byte
    /// order; those from it on are strings rules made in the run.
    pub fn sorted_len(&self) -> usize {
        self.sorted
    }

    /// Whether `id` is of a string a rule made in the run.
    pub fn is_made(&self, id: Value) -> bool {
        id >= self.sorted as Value && id != NULL
    }

    /// How the strings of ids `a` and `b` compare by their bytes (by the ids alone where
    /// both are sorted ones).
    pub fn cmp_ids(&self, a: Value, b: Value) -> std::cmp::Ordering {
        if !self.is_made(a) && !self.is_made(b) {
            return a.cmp(&b);
        }
        match (self.get(a), self.get(b)) {
            (Some(x), Some(y)) => x.as_bytes().cmp(y.as_bytes()),
            _ => a.cmp(&b),
        }
    }

    /// Add the strings of `made` that the dictionary lacks, after the others: sorted by
    /// their bytes, each once, so their ids do not depend on the order they came in.
    pub(crate) fn add_made(&mut self, mut made: Vec<String>) -> Result<()> {
        made.sort_unstable();
        made.dedup();
        for s in made {
            if self.id(&s).is_some() {
                continue;
            }
            let id = u32::try_from(self.len())
                .ok()
                .filter(|&i| i < u32::MAX)
                .ok_or_else(|| PlanError::Input("over 4 G distinct strings in one run".into()))?;
            if self.offsets.is_empty() {
                self.offsets.push(0);
            }
            self.bytes.extend_from_slice(s.as_bytes());
            self.offsets.push(self.bytes.len());
            self.made.insert(s, id);
        }
        Ok(())
    }

    /// The first sorted id whose string is not below `s` (the number of sorted strings
    /// below it).
    pub fn lower_bound(&self, s: &str) -> u32 {
        let (mut lo, mut hi) = (0usize, self.sorted);
        while lo < hi {
            let mid = (lo + hi) / 2;
            if self.get(mid as Value).expect("in range") < s {
                lo = mid + 1;
            } else {
                hi = mid;
            }
        }
        lo as u32
    }

    /// The sorted ids of the strings that start with `prefix`: one range, `[lo, hi)`.
    pub fn prefix_range(&self, prefix: &str) -> (u32, u32) {
        let lo = self.lower_bound(prefix);
        let (mut a, mut b) = (lo as usize, self.sorted);
        while a < b {
            let mid = (a + b) / 2;
            if self
                .get(mid as Value)
                .expect("in range")
                .starts_with(prefix)
            {
                a = mid + 1;
            } else {
                b = mid;
            }
        }
        (lo, a as u32)
    }

    /// Every string, in id order.
    pub fn iter(&self) -> impl Iterator<Item = &str> + '_ {
        (0..self.len()).map(|i| self.get(i as Value).expect("in range"))
    }

    fn from_sorted<'a>(strings: impl Iterator<Item = &'a str>) -> Self {
        let mut d = Dict {
            bytes: Vec::new(),
            offsets: vec![0],
            sorted: 0,
            made: HashMap::new(),
        };
        for s in strings {
            d.bytes.extend_from_slice(s.as_bytes());
            d.offsets.push(d.bytes.len());
        }
        d.sorted = d.len();
        d
    }
}

/// The strings of one column chunk, read where they lie: string columns, and byte columns
/// read as text (a value that is not UTF-8 has no text: null).
enum Strs<'a> {
    Utf8(&'a arrow_array::StringArray),
    Large(&'a arrow_array::LargeStringArray),
    View(&'a arrow_array::StringViewArray),
    Bin(&'a arrow_array::BinaryArray),
    LargeBin(&'a arrow_array::LargeBinaryArray),
    BinView(&'a arrow_array::BinaryViewArray),
}

impl<'a> Strs<'a> {
    #[inline]
    fn get(&self, i: usize) -> Option<&'a str> {
        let text = |b: &'a [u8]| std::str::from_utf8(b).ok();
        match self {
            Strs::Utf8(a) => a.is_valid(i).then(|| a.value(i)),
            Strs::Large(a) => a.is_valid(i).then(|| a.value(i)),
            Strs::View(a) => a.is_valid(i).then(|| a.value(i)),
            Strs::Bin(a) => a.is_valid(i).then(|| a.value(i)).and_then(text),
            Strs::LargeBin(a) => a.is_valid(i).then(|| a.value(i)).and_then(text),
            Strs::BinView(a) => a.is_valid(i).then(|| a.value(i)).and_then(text),
        }
    }
}

fn strs_of<'a>(a: &'a dyn Array) -> Option<Strs<'a>> {
    match a.data_type() {
        DataType::Utf8 => Some(Strs::Utf8(a.as_string::<i32>())),
        DataType::LargeUtf8 => Some(Strs::Large(a.as_string::<i64>())),
        DataType::Utf8View => Some(Strs::View(a.as_string_view())),
        DataType::Binary => Some(Strs::Bin(a.as_binary::<i32>())),
        DataType::LargeBinary => Some(Strs::LargeBin(a.as_binary::<i64>())),
        DataType::BinaryView => Some(Strs::BinView(a.as_binary_view())),
        _ => None,
    }
}

/// The bytes of value `i` of a string or bytes column (`None` for a null or a column of
/// another type).
fn bytes_at(a: &dyn Array, i: usize) -> Option<&[u8]> {
    if a.is_null(i) {
        return None;
    }
    Some(match a.data_type() {
        DataType::Utf8 => a.as_string::<i32>().value(i).as_bytes(),
        DataType::LargeUtf8 => a.as_string::<i64>().value(i).as_bytes(),
        DataType::Utf8View => a.as_string_view().value(i).as_bytes(),
        DataType::Binary => a.as_binary::<i32>().value(i),
        DataType::LargeBinary => a.as_binary::<i64>().value(i),
        DataType::BinaryView => a.as_binary_view().value(i),
        DataType::FixedSizeBinary(_) => a.as_fixed_size_binary().value(i),
        _ => return None,
    })
}

/// A dictionary column's keys (normalized; `None` for a null key) and its values.
fn dictionary_parts(a: &ArrayRef) -> (Vec<Option<usize>>, ArrayRef) {
    let d = a.as_any_dictionary();
    let norm = d.normalized_keys();
    let keys = (0..a.len())
        .map(|i| d.keys().is_valid(i).then(|| norm[i]))
        .collect();
    (keys, d.values().clone())
}

/// A string or bytes column (or a dictionary of one) as the lowercase hex of each value's
/// bytes, a null null: the text of [`crate::Catalog::relation`]'s `@hex`, and of a
/// `FixedSizeBinary` column read as strings. Hex text compares as the bytes do.
pub(crate) fn hex_column(a: &ArrayRef) -> Result<ArrayRef> {
    const DIGITS: &[u8; 16] = b"0123456789abcdef";
    let (keys, values) = match a.data_type() {
        DataType::Dictionary(_, _) => {
            let (k, v) = dictionary_parts(a);
            (Some(k), v)
        }
        _ => (None, a.clone()),
    };
    let readable = matches!(
        values.data_type(),
        DataType::Utf8
            | DataType::LargeUtf8
            | DataType::Utf8View
            | DataType::Binary
            | DataType::LargeBinary
            | DataType::BinaryView
            | DataType::FixedSizeBinary(_)
    );
    if !readable {
        return Err(PlanError::Input(format!(
            "a column of {}; hex reads strings or bytes",
            a.data_type()
        )));
    }
    let mut b = StringBuilder::with_capacity(a.len(), 0);
    let mut text = String::new();
    for i in 0..a.len() {
        let at = match &keys {
            Some(k) => k[i],
            None => Some(i),
        };
        match at.and_then(|j| bytes_at(values.as_ref(), j)) {
            None => b.append_null(),
            Some(bytes) => {
                text.clear();
                for &x in bytes {
                    text.push(DIGITS[(x >> 4) as usize] as char);
                    text.push(DIGITS[(x & 15) as usize] as char);
                }
                b.append_value(&text);
            }
        }
    }
    Ok(Arc::new(b.finish()))
}

/// A string column chunk: plain strings (bytes read as text), or a dictionary array's keys
/// and values; a `FixedSizeBinary` column, never text, as its hex ([`hex_column`]).
fn string_parts(a: &ArrayRef) -> Result<(Option<Vec<Option<usize>>>, ArrayRef)> {
    if let DataType::FixedSizeBinary(_) = a.data_type() {
        return Ok((None, hex_column(a)?));
    }
    if let DataType::Dictionary(_, _) = a.data_type() {
        let (keys, mut values) = dictionary_parts(a);
        if let DataType::FixedSizeBinary(_) = values.data_type() {
            values = hex_column(&values)?;
        }
        if strs_of(values.as_ref()).is_none() {
            return Err(PlanError::Input(format!(
                "a dictionary column of {}; a string column needs strings",
                values.data_type()
            )));
        }
        return Ok((Some(keys), values));
    }
    if strs_of(a.as_ref()).is_none() {
        return Err(PlanError::Input(format!(
            "a column of {}; a string column needs Utf8, LargeUtf8, Utf8View, bytes (Binary, \
             LargeBinary, BinaryView: read as text, a value that is not UTF-8 null), \
             FixedSizeBinary (read as hex) or a dictionary of them",
            a.data_type()
        )));
    }
    Ok((None, a.clone()))
}

/// The run's dictionary over the string columns `chunks` and the plan's string constants
/// `extra`, and every chunk coded by it (in order): one hash pass gives each distinct string
/// an arrival number, a sort of the distinct strings its rank, a gather the codes.
pub(crate) fn build_dict(
    par: &Par,
    chunks: &[&ArrayRef],
    extra: &[String],
) -> Result<(Dict, Vec<Column>)> {
    let parts: Vec<(Option<Vec<Option<usize>>>, ArrayRef)> = chunks
        .iter()
        .map(|a| string_parts(a))
        .collect::<Result<_>>()?;
    let mut seen: HashMap<&str, u32> = HashMap::new();
    let mut order: Vec<&str> = Vec::new();
    // codes by arrival, per chunk (NULL kept)
    let mut first: Vec<Vec<u64>> = Vec::with_capacity(parts.len());
    for (keys, values) in &parts {
        let s = strs_of(values.as_ref()).expect("checked");
        let vals: Vec<u64> = (0..values.len())
            .map(|i| match s.get(i) {
                None => NULL,
                Some(x) => {
                    let n = order.len() as u32;
                    *seen.entry(x).or_insert_with(|| {
                        order.push(x);
                        n
                    }) as u64
                }
            })
            .collect();
        first.push(match keys {
            None => vals,
            Some(k) => k.iter().map(|k| k.map_or(NULL, |i| vals[i])).collect(),
        });
    }
    for x in extra {
        let n = order.len() as u32;
        seen.entry(x.as_str()).or_insert_with(|| {
            order.push(x.as_str());
            n
        });
    }
    if order.len() > u32::MAX as usize {
        return Err(PlanError::Input(
            "over 4 G distinct strings in one run".into(),
        ));
    }
    let mut by_str: Vec<u32> = (0..order.len() as u32).collect();
    par.sort_by(&mut by_str, |&a, &b| {
        order[a as usize].cmp(order[b as usize])
    });
    let mut rank = vec![0u32; order.len()];
    for (r, &a) in by_str.iter().enumerate() {
        rank[a as usize] = r as u32;
    }
    let dict = Dict::from_sorted(by_str.iter().map(|&a| order[a as usize]));
    let cols = first
        .into_iter()
        .map(|c| {
            let rank = &rank;
            let coded: Vec<u32> = par.fill(c.len(), |i| {
                let x = c[i];
                if x == NULL {
                    u32::MAX
                } else {
                    rank[x as usize]
                }
            });
            // a null is u32::MAX here; widened to NULL only when a column has one
            if coded.contains(&u32::MAX) {
                Column::from(
                    coded
                        .iter()
                        .map(|&x| if x == u32::MAX { NULL } else { x as u64 })
                        .collect::<Vec<u64>>(),
                )
            } else {
                Column::from(coded)
            }
        })
        .collect();
    Ok((dict, cols))
}

/// Milliseconds in a day.
const DAY_MS: i64 = 86_400_000;

/// The [`Type::I64`] value a date or timestamp column holds as `raw` (its Arrow value): a
/// date (`Date32`, `Date64`) the days since 1970-01-01, a timestamp (`Timestamp` of any unit
/// and time zone, an instant) the nanoseconds since 1970-01-01T00:00Z; any other column's
/// value as it is. Refused: a `Date64` that is not a whole day, a timestamp outside the
/// nanoseconds of an `i64` (before 1677 or after 2262).
pub fn time_value(ty: &DataType, raw: i64) -> Result<i64> {
    use arrow_schema::TimeUnit;
    match ty {
        DataType::Date64 if raw % DAY_MS != 0 => Err(PlanError::Input(format!(
            "a Date64 of {raw} ms is not a whole day"
        ))),
        DataType::Date64 => Ok(raw / DAY_MS),
        DataType::Timestamp(unit, _) => {
            let per = match unit {
                TimeUnit::Second => 1_000_000_000,
                TimeUnit::Millisecond => 1_000_000,
                TimeUnit::Microsecond => 1_000,
                TimeUnit::Nanosecond => 1,
            };
            raw.checked_mul(per).ok_or_else(|| {
                PlanError::Input(format!(
                    "a timestamp of {raw} {unit:?} is outside the nanoseconds of an i64"
                ))
            })
        }
        _ => Ok(raw),
    }
}

/// One column chunk of a type other than [`Type::Str`] as codes: [`Type::U64`] as read
/// today (in place, no nulls), the others coded in pieces on the device's workers.
pub(crate) fn coded(par: &Par, ty: Type, a: &ArrayRef) -> Result<Column> {
    let null = |i: usize| a.is_null(i);
    let nulls = a.null_count() > 0;
    let code_all = |f: &(dyn Fn(usize) -> Result<Value> + Sync)| -> Result<Column> {
        let pieces = par.split(a.len(), |lo, hi| {
            (lo..hi)
                .map(|i| if nulls && null(i) { Ok(NULL) } else { f(i) })
                .collect::<Result<Vec<Value>>>()
        });
        let mut out = Vec::with_capacity(a.len());
        for p in pieces {
            out.extend(p?);
        }
        Ok(Column::from(out))
    };
    let refuse = |what: &str| {
        Err(PlanError::Input(format!(
            "a column of {}; a {} column takes {what}",
            a.data_type(),
            ty.name()
        )))
    };
    let int = |x: i64| -> Result<Value> {
        if x == i64::MAX {
            return Err(PlanError::Input(
                "the value i64::MAX: its code is the null's in an i64 column".into(),
            ));
        }
        Ok(i64_code(x))
    };
    match ty {
        Type::U64 => column_of(a),
        Type::I64 => match a.data_type() {
            DataType::Int64 => {
                let v = a.as_primitive::<types::Int64Type>().values();
                code_all(&|i| int(v[i]))
            }
            DataType::Int32 => {
                let v = a.as_primitive::<types::Int32Type>().values();
                code_all(&|i| int(v[i] as i64))
            }
            DataType::Int16 => {
                let v = a.as_primitive::<types::Int16Type>().values();
                code_all(&|i| int(v[i] as i64))
            }
            DataType::Int8 => {
                let v = a.as_primitive::<types::Int8Type>().values();
                code_all(&|i| int(v[i] as i64))
            }
            DataType::UInt32 => {
                let v = a.as_primitive::<types::UInt32Type>().values();
                code_all(&|i| int(v[i] as i64))
            }
            DataType::UInt16 => {
                let v = a.as_primitive::<types::UInt16Type>().values();
                code_all(&|i| int(v[i] as i64))
            }
            DataType::UInt8 => {
                let v = a.as_primitive::<types::UInt8Type>().values();
                code_all(&|i| int(v[i] as i64))
            }
            DataType::UInt64 => {
                let v = a.as_primitive::<types::UInt64Type>().values();
                code_all(&|i| {
                    i64::try_from(v[i])
                        .map_err(|_| {
                            PlanError::Input(format!("value {} does not fit an i64 column", v[i]))
                        })
                        .and_then(int)
                })
            }
            DataType::Date32 => {
                let v = a.as_primitive::<types::Date32Type>().values();
                let t = a.data_type();
                code_all(&|i| int(time_value(t, v[i] as i64)?))
            }
            DataType::Date64 => {
                let v = a.as_primitive::<types::Date64Type>().values();
                let t = a.data_type();
                code_all(&|i| int(time_value(t, v[i])?))
            }
            DataType::Timestamp(unit, _) => {
                use arrow_schema::TimeUnit;
                let v = match unit {
                    TimeUnit::Second => a.as_primitive::<types::TimestampSecondType>().values(),
                    TimeUnit::Millisecond => {
                        a.as_primitive::<types::TimestampMillisecondType>().values()
                    }
                    TimeUnit::Microsecond => {
                        a.as_primitive::<types::TimestampMicrosecondType>().values()
                    }
                    TimeUnit::Nanosecond => {
                        a.as_primitive::<types::TimestampNanosecondType>().values()
                    }
                };
                let t = a.data_type();
                code_all(&|i| int(time_value(t, v[i])?))
            }
            _ => refuse("integers, dates or timestamps"),
        },
        Type::F64 => match a.data_type() {
            DataType::Float64 => {
                let v = a.as_primitive::<types::Float64Type>().values();
                code_all(&|i| Ok(f64_code(v[i])))
            }
            DataType::Float32 => {
                let v = a.as_primitive::<types::Float32Type>().values();
                code_all(&|i| Ok(f64_code(v[i] as f64)))
            }
            _ => refuse("Float64 or Float32"),
        },
        Type::Bool => match a.data_type() {
            DataType::Boolean => {
                let v = a.as_boolean();
                code_all(&|i| Ok(v.value(i) as Value))
            }
            _ => refuse("Boolean"),
        },
        Type::Str => unreachable!("strings are coded through the run's dictionary"),
    }
}

/// A column of codes of type `ty` as an Arrow array of that type: `UInt32` or `UInt64` as
/// stored for [`Type::U64`] (shared), `Int64`, `Float64`, `Boolean` and `Utf8` (from
/// `dict`) with nulls.
pub(crate) fn to_arrow(ty: Type, c: &Column, dict: Option<&Dict>) -> Result<ArrayRef> {
    let n = c.len();
    Ok(match ty {
        Type::U64 => c.to_arrow(),
        Type::I64 => {
            let mut b = Int64Builder::with_capacity(n);
            for x in c.iter() {
                b.append_option((x != NULL).then(|| i64_of(x)));
            }
            Arc::new(b.finish())
        }
        Type::F64 => {
            let mut b = Float64Builder::with_capacity(n);
            for x in c.iter() {
                b.append_option((x != NULL).then(|| f64_of(x)));
            }
            Arc::new(b.finish())
        }
        Type::Bool => {
            let mut b = BooleanBuilder::with_capacity(n);
            for x in c.iter() {
                b.append_option((x != NULL).then_some(x != 0));
            }
            Arc::new(b.finish())
        }
        Type::Str => {
            let empty = Dict::default();
            let d = dict.unwrap_or(&empty);
            let mut b = StringBuilder::with_capacity(n, 0);
            for x in c.iter() {
                if x == NULL {
                    b.append_null();
                } else {
                    let s = d.get(x).ok_or_else(|| {
                        PlanError::Input(format!("string id {x} is not in the run's dictionary"))
                    })?;
                    b.append_value(s);
                }
            }
            Arc::new(b.finish())
        }
    })
}