use std::{cell::OnceCell, collections::HashSet, marker::PhantomData, rc::Rc};
use crate::{
data::{BindingSelector, DataSourceInfo, DataSourceRef, RawKey, RawKeyValues, SourceRows},
BooleanValues, CategoryValues, NumericValues, Result,
};
use super::{
codec::invalid,
keys::{integer, selector_pending},
};
#[doc(hidden)]
pub trait BindingInput<M = ()> {
fn binding_object(&self) -> Result<BindingObject<'_>>;
}
trait Provider {
fn object(&self) -> Result<BindingObject<'_>>;
}
struct Input<T, M>(T, PhantomData<M>);
impl<T: BindingInput<M>, M> Provider for Input<T, M> {
fn object(&self) -> Result<BindingObject<'_>> {
self.0.binding_object()
}
}
#[derive(Default)]
pub struct Bindings<'a> {
inputs: Vec<(RawKey, Box<dyn Provider + 'a>)>,
}
impl<'a> Bindings<'a> {
pub fn new() -> Self {
Self::default()
}
pub fn bind<T: BindingInput<M> + 'a, M: 'a>(
mut self,
name: impl Into<RawKey>,
input: T,
) -> Result<Self> {
let key = name.into();
if self.inputs.iter().any(|(existing, _)| existing == &key) {
return Err(invalid(format!("duplicate binding {key:?}")));
}
self.inputs.push((key, Box::new(Input(input, PhantomData))));
Ok(self)
}
pub(super) fn names(&self) -> impl Iterator<Item = &RawKey> {
self.inputs.iter().map(|(name, _)| name)
}
pub(super) fn get(&self, name: &RawKey) -> Option<BindingObject<'_>> {
let (_, provider) = self.inputs.iter().find(|(key, _)| key == name)?;
Some(BindingObject::deferred(move || provider.object()))
}
}
impl BindingInput for &Bindings<'_> {
fn binding_object(&self) -> Result<BindingObject<'_>> {
Ok(BindingObject::members(
self.inputs
.iter()
.map(|(key, provider)| {
(
key.clone(),
BindingObject::deferred(move || provider.object()),
)
})
.collect(),
))
}
}
#[doc(hidden)]
pub trait BindingArguments<M> {
fn with_bindings<T>(self, use_bindings: impl FnOnce(&Bindings<'_>) -> Result<T>) -> Result<T>;
}
#[doc(hidden)]
pub struct RegistryArguments;
#[doc(hidden)]
pub struct SequenceArguments<M>(PhantomData<M>);
impl BindingArguments<RegistryArguments> for &Bindings<'_> {
fn with_bindings<T>(self, use_bindings: impl FnOnce(&Bindings<'_>) -> Result<T>) -> Result<T> {
use_bindings(self)
}
}
impl<I, N, V, M> BindingArguments<SequenceArguments<M>> for I
where
I: IntoIterator<Item = (N, V)>,
N: Into<RawKey>,
V: BindingInput<M>,
{
fn with_bindings<T>(self, use_bindings: impl FnOnce(&Bindings<'_>) -> Result<T>) -> Result<T> {
let mut bindings = Bindings::new();
for (name, value) in self {
bindings = bindings.bind(name, value)?;
}
use_bindings(&bindings)
}
}
#[doc(hidden)]
#[derive(Clone)]
pub struct BindingField<'a> {
key: Option<RawKey>,
name: String,
numeric: bool,
value: BindingObject<'a>,
}
impl<'a> BindingField<'a> {
pub(super) fn logical_key(&self) -> Option<&RawKey> {
self.key.as_ref()
}
pub(super) fn name(&self) -> &str {
&self.name
}
pub(super) fn object(&self) -> &BindingObject<'a> {
&self.value
}
pub fn new(
key: Option<RawKey>,
name: impl Into<String>,
numeric: bool,
value: BindingObject<'a>,
) -> Self {
Self {
key,
name: name.into(),
numeric,
value,
}
}
}
#[doc(hidden)]
#[derive(Clone)]
pub struct BindingObject<'a>(Rc<Object<'a>>);
enum Object<'a> {
Column(Column),
Content(crate::composition::CompositionSource),
Table {
rows: usize,
fields: Vec<BindingField<'a>>,
},
Members(Vec<(RawKey, BindingObject<'a>)>),
Sequence {
rows: usize,
vector: BindingObject<'a>,
rectangle: BindingObject<'a>,
},
Deferred {
load: Box<dyn Fn() -> Result<BindingObject<'a>> + 'a>,
ready: OnceCell<BindingObject<'a>>,
},
}
#[doc(hidden)]
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum BindingColumnType {
Numeric,
Category,
Boolean,
Null,
Keys,
}
#[derive(Clone, Copy)]
pub(super) enum TextType {
String,
Boolean,
F32,
F64,
Signed(u32),
Unsigned(u32),
}
impl TextType {
pub(super) fn parse(value: &str) -> Result<Self> {
Ok(match value {
"string" => Self::String,
"bool" => Self::Boolean,
"f32" => Self::F32,
"f64" => Self::F64,
"i8" => Self::Signed(8),
"i16" => Self::Signed(16),
"i32" => Self::Signed(32),
"i64" => Self::Signed(64),
"i128" => Self::Signed(128),
"u8" => Self::Unsigned(8),
"u16" => Self::Unsigned(16),
"u32" => Self::Unsigned(32),
"u64" => Self::Unsigned(64),
"u128" => Self::Unsigned(128),
_ => return Err(invalid(format!("unsupported text dtype {value:?}"))),
})
}
pub(super) fn numeric(self) -> bool {
!matches!(self, Self::String | Self::Boolean)
}
pub(super) fn valid(self, token: &str) -> bool {
let token = token.trim();
if token.is_empty() || matches!(self, Self::String) {
return true;
}
match self {
Self::String => true,
Self::Boolean => {
token.eq_ignore_ascii_case("true") || token.eq_ignore_ascii_case("false")
}
Self::F32 => token.parse::<f32>().is_ok(),
Self::F64 => token.parse::<f64>().is_ok(),
Self::Signed(bits) => token.parse::<i128>().is_ok_and(|value| {
bits == 128 || (-1_i128 << (bits - 1)..1_i128 << (bits - 1)).contains(&value)
}),
Self::Unsigned(bits) => token
.parse::<u128>()
.is_ok_and(|value| bits == 128 || value < 1_u128 << bits),
}
}
fn key(self, token: &str) -> Result<Option<RawKey>> {
let raw = token;
let token = token.trim();
if matches!(self, Self::String) {
return Ok(Some(RawKey::from(raw)));
}
if token.is_empty() {
return Ok(None);
}
if !self.valid(token) {
return Err(invalid(format!("invalid typed key token {raw:?}")));
}
let key = match self {
Self::String => unreachable!("handled string tokens"),
Self::Boolean => RawKey::Boolean(token.eq_ignore_ascii_case("true")),
Self::F32 => RawKey::Float(f64::from(token.parse::<f32>().expect("validated f32"))),
Self::F64 => RawKey::Float(token.parse::<f64>().expect("validated f64")),
Self::Signed(_) | Self::Unsigned(_) => {
RawKey::Integer(super::keys::decode_integer(token)?)
}
};
Ok(Some(key))
}
}
#[derive(Clone)]
pub(super) enum Column {
Numeric(NumericValues),
Category(CategoryValues),
Boolean(BooleanValues),
Rows(SourceRows),
SignificanceTargets(std::sync::Arc<[crate::elements::SignificanceTarget]>),
SignificanceMarks(std::sync::Arc<[crate::elements::SignificanceMark]>),
FacetCells(std::sync::Arc<[crate::layout::FacetCell]>),
Keys {
values: RawKeyValues,
dtype: BindingColumnType,
integer_negative_zero: std::sync::Arc<[usize]>,
display_labels: Option<std::sync::Arc<std::collections::HashMap<RawKey, String>>>,
},
Text {
values: CategoryValues,
numeric: bool,
dtype: Option<TextType>,
},
}
macro_rules! direct_inputs {
($($native:ty => $method:ident,$variant:ident),+ $(,)?) => {$(
impl BindingObject<'_> {
#[doc(hidden)]
pub fn $method(values: $native) -> Self {
Self(Rc::new(Object::Column(Column::$variant(values))))
}
}
impl BindingInput for &$native {
fn binding_object(&self) -> Result<BindingObject<'_>> {
Ok(BindingObject::$method((*self).clone()))
}
}
impl BindingInput for $native {
fn binding_object(&self) -> Result<BindingObject<'_>> {
Ok(BindingObject::$method(self.clone()))
}
}
)+};
}
direct_inputs!(
NumericValues => numeric, Numeric,
CategoryValues => category, Category,
BooleanValues => boolean, Boolean,
SourceRows => rows, Rows,
);
macro_rules! typed_columns {
($($type:ty=>$method:ident,$variant:ident),+ $(,)?)=>{$(
impl BindingObject<'_>{
pub fn $method(values:impl Into<std::sync::Arc<[$type]>>)->Self{
Self(Rc::new(Object::Column(Column::$variant(values.into()))))
}
}
impl BindingInput for &[$type]{
fn binding_object(&self)->Result<BindingObject<'_>>{Ok(BindingObject::$method(*self))}
}
impl BindingInput for &Vec<$type>{
fn binding_object(&self)->Result<BindingObject<'_>>{Ok(BindingObject::$method(self.as_slice()))}
}
impl BindingInput for Vec<$type>{
fn binding_object(&self)->Result<BindingObject<'_>>{Ok(BindingObject::$method(self.as_slice()))}
}
impl BindingInput for &std::sync::Arc<[$type]>{
fn binding_object(&self)->Result<BindingObject<'_>>{Ok(BindingObject::$method((*self).clone()))}
}
impl<const N:usize> BindingInput for &[$type;N]{
fn binding_object(&self)->Result<BindingObject<'_>>{Ok(BindingObject::$method(self.as_slice()))}
}
)+};
}
typed_columns!(
crate::elements::SignificanceTarget=>significance_targets,SignificanceTargets,
crate::elements::SignificanceMark=>significance_marks,SignificanceMarks,
crate::layout::FacetCell=>facet_cells,FacetCells,
);
impl BindingObject<'_> {
pub fn keys(values: RawKeyValues, numeric: bool) -> Self {
Self::typed_keys(
values,
if numeric {
BindingColumnType::Numeric
} else {
BindingColumnType::Keys
},
)
}
pub fn typed_keys(values: RawKeyValues, dtype: BindingColumnType) -> Self {
Self::keys_with_integer_zero(values, dtype, Vec::new())
}
pub(super) fn keys_with_integer_zero(
values: RawKeyValues,
dtype: BindingColumnType,
negative_zero: Vec<usize>,
) -> Self {
Self(Rc::new(Object::Column(Column::Keys {
values,
dtype,
integer_negative_zero: negative_zero.into(),
display_labels: None,
})))
}
pub fn display_keys(
values: RawKeyValues,
dtype: BindingColumnType,
labels: Vec<(RawKey, String)>,
) -> Self {
Self(Rc::new(Object::Column(Column::Keys {
values,
dtype,
integer_negative_zero: Vec::new().into(),
display_labels: Some(std::sync::Arc::new(labels.into_iter().collect())),
})))
}
pub(super) fn text(values: CategoryValues, numeric: bool, dtype: Option<TextType>) -> Self {
Self(Rc::new(Object::Column(Column::Text {
values,
numeric,
dtype,
})))
}
}
impl BindingInput for &RawKeyValues {
fn binding_object(&self) -> Result<BindingObject<'_>> {
Ok(BindingObject::keys((*self).clone(), false))
}
}
impl BindingInput for RawKeyValues {
fn binding_object(&self) -> Result<BindingObject<'_>> {
Ok(BindingObject::keys(self.clone(), false))
}
}
impl BindingInput for &crate::data::IntegerValues {
fn binding_object(&self) -> Result<BindingObject<'_>> {
let values = RawKeyValues::nullable(
self.name(),
self.iter().map(|value| value.cloned().map(RawKey::Integer)),
)?;
Ok(BindingObject::typed_keys(
values,
BindingColumnType::Numeric,
))
}
}
fn status_object<'a>(values: &[crate::data::EstimateStatus]) -> Result<BindingObject<'a>> {
let values = CategoryValues::new(
"estimate_status",
values.iter().map(|status| match status {
crate::data::EstimateStatus::Estimated => "estimated",
crate::data::EstimateStatus::NotEstimable => "not_estimable",
}),
)?;
Ok(BindingObject::category(values))
}
impl BindingInput for &crate::data::EstimateStatusBinding {
fn binding_object(&self) -> Result<BindingObject<'_>> {
status_object(self.statuses())
}
}
impl BindingInput for &[crate::data::EstimateStatus] {
fn binding_object(&self) -> Result<BindingObject<'_>> {
status_object(self)
}
}
impl BindingInput for &Vec<crate::data::EstimateStatus> {
fn binding_object(&self) -> Result<BindingObject<'_>> {
status_object(self)
}
}
impl<const N: usize> BindingInput for &[crate::data::EstimateStatus; N] {
fn binding_object(&self) -> Result<BindingObject<'_>> {
status_object(self.as_slice())
}
}
macro_rules! content_inputs{
($($ty:ty),+)=>{$(
impl BindingInput for &$ty{
fn binding_object(&self)->Result<BindingObject<'_>>{
Ok(BindingObject::content((*self).into()))
}
}
impl BindingInput for $ty{
fn binding_object(&self)->Result<BindingObject<'_>>{
Ok(BindingObject::content(self.into()))
}
}
)+};
}
content_inputs!(
crate::composition::ImageAsset,
crate::Output,
crate::Canvas,
crate::layout::TextPanel
);
impl<K: crate::kind::Marker> BindingInput for &crate::Plot<K> {
fn binding_object(&self) -> Result<BindingObject<'_>> {
Ok(BindingObject::content((*self).into()))
}
}
impl<K: crate::kind::Marker> BindingInput for crate::Plot<K> {
fn binding_object(&self) -> Result<BindingObject<'_>> {
Ok(BindingObject::content(self.into()))
}
}
impl BindingInput for &crate::composition::Composite {
fn binding_object(&self) -> Result<BindingObject<'_>> {
Ok(BindingObject::content(self.output().into()))
}
}
impl BindingInput for crate::composition::Composite {
fn binding_object(&self) -> Result<BindingObject<'_>> {
Ok(BindingObject::content(self.output().into()))
}
}
fn native_variables<'a>(values: &[NumericValues]) -> Result<BindingObject<'a>> {
let rows = values
.first()
.ok_or_else(|| invalid("at least one numeric variable is required"))?
.len();
let mut fields = Vec::new();
for value in values {
if value.len() != rows {
return Err(invalid(
"native variable collection must align on its row axis",
));
}
let key = value
.field_key()
.cloned()
.unwrap_or_else(|| RawKey::from(value.name()));
fields.push(BindingField::new(
Some(key),
value.name(),
true,
BindingObject::numeric(value.clone()),
));
}
Ok(BindingObject::table(rows, fields))
}
impl BindingInput for &[NumericValues] {
fn binding_object(&self) -> Result<BindingObject<'_>> {
native_variables(self)
}
}
impl BindingInput for &Vec<NumericValues> {
fn binding_object(&self) -> Result<BindingObject<'_>> {
native_variables(self)
}
}
impl BindingInput for Vec<NumericValues> {
fn binding_object(&self) -> Result<BindingObject<'_>> {
native_variables(self)
}
}
impl<'a> BindingObject<'a> {
pub fn deferred(load: impl Fn() -> Result<Self> + 'a) -> Self {
Self(Rc::new(Object::Deferred {
load: Box::new(load),
ready: OnceCell::new(),
}))
}
pub fn table(rows: usize, fields: Vec<BindingField<'a>>) -> Self {
Self(Rc::new(Object::Table { rows, fields }))
}
pub fn members(fields: Vec<(RawKey, BindingObject<'a>)>) -> Self {
Self(Rc::new(Object::Members(fields)))
}
pub fn sequence(rows: usize, vector: Self, rectangle: Self) -> Self {
Self(Rc::new(Object::Sequence {
rows,
vector,
rectangle,
}))
}
pub(super) fn adopt(&self, rectangle: bool) -> Result<Self> {
match self.object()? {
Object::Sequence {
vector,
rectangle: table,
..
} => Ok(if rectangle {
table.clone()
} else {
vector.clone()
}),
_ => Ok(self.clone()),
}
}
fn object(&self) -> Result<&Object<'a>> {
if let Object::Deferred { load, ready } = self.0.as_ref() {
if ready.get().is_none() {
crate::operation::checkpoint()?;
let value = load()?;
let _ = ready.set(value);
}
return ready.get().expect("loaded binding").object();
}
Ok(self.0.as_ref())
}
#[doc(hidden)]
pub fn content(value: crate::composition::CompositionSource) -> Self {
Self(Rc::new(Object::Content(value)))
}
pub(super) fn content_value(&self) -> Result<crate::composition::CompositionSource> {
match self.object()? {
Object::Content(value) => Ok(value.clone()),
_ => Err(invalid("expected a native or fixed content snapshot")),
}
}
pub fn numeric_dtype(&self) -> Result<bool> {
self.column().map(Column::is_numeric)
}
pub(super) fn shape(&self) -> Result<Vec<usize>> {
match self.object()? {
Object::Column(column) => Ok(vec![column.len()]),
Object::Table { rows, fields } => Ok(vec![*rows, fields.len()]),
Object::Members(_) | Object::Content(_) => Ok(Vec::new()),
Object::Sequence { rows, .. } => Ok(vec![*rows]),
Object::Deferred { .. } => unreachable!("resolved input"),
}
}
pub(super) fn column(&self) -> Result<&Column> {
match self.object()? {
Object::Column(column) => Ok(column),
Object::Sequence { vector, .. } => vector.column(),
_ => Err(invalid(
"expected a rank-one value, not a table or named object",
)),
}
}
pub(super) fn table_fields(&self) -> Result<(usize, &[BindingField<'a>])> {
match self.object()? {
Object::Table { rows, fields } => Ok((*rows, fields)),
Object::Sequence { rectangle, .. } => rectangle.table_fields(),
_ => Err(invalid("expected an object with a logical column axis")),
}
}
pub(super) fn select(&self, selector: &BindingSelector) -> Result<Selection<'a>> {
if selector_pending(selector) {
return Err(invalid("original key is still required"));
}
if *selector == BindingSelector::Whole {
return Ok(Selection {
value: self.clone(),
source_shape: self.shape()?,
keys: None,
names: None,
positions: None,
});
}
match self.object()? {
Object::Table { rows, fields } => select_table(*rows, fields, selector),
Object::Members(members) => select_members(members, selector),
Object::Sequence { rectangle, .. } => rectangle.select(selector),
_ => Err(invalid(
"selection requires a logical column axis or named members",
)),
}
}
pub(super) fn map_keys(&self, mapping: &[(RawKey, BindingSelector)]) -> Result<Self> {
if mapping.is_empty() {
return Ok(self.clone());
}
match self.object()? {
Object::Table { rows, fields } => {
let mut mapped = fields.clone();
let mut positions = HashSet::new();
for (key, selector) in mapping {
let indices = table_indices(fields, selector)?;
let [index] = indices.as_slice() else {
return Err(invalid("key_map must select one actual field"));
};
if !positions.insert(*index) {
return Err(invalid("key_map references the same actual field twice"));
}
mapped[*index].key = Some(key.clone());
mapped[*index].name = key_name(key);
}
for (key, _) in mapping {
unique_key(mapped.iter().map(|field| field.key.as_ref()), key)?;
}
Ok(Self::table(*rows, mapped))
}
Object::Members(fields) => {
let mut mapped = fields.clone();
let mut positions = HashSet::new();
for (key, selector) in mapping {
let BindingSelector::Key(source) = selector else {
return Err(invalid("named object key_map requires one actual key"));
};
let index = unique_key(fields.iter().map(|(key, _)| Some(key)), source)?;
if !positions.insert(index) {
return Err(invalid("key_map references the same actual member twice"));
}
mapped[index].0 = key.clone();
}
for (key, _) in mapping {
unique_key(mapped.iter().map(|(key, _)| Some(key)), key)?;
}
Ok(Self::members(mapped))
}
_ => Err(invalid("key_map requires actual source fields")),
}
}
}
pub(super) struct Selection<'a> {
pub(super) value: BindingObject<'a>,
source_shape: Vec<usize>,
keys: Option<Vec<RawKey>>,
names: Option<Vec<String>>,
positions: Option<Vec<usize>>,
}
impl Selection<'_> {
pub(super) fn adopt(&mut self, rectangle: bool) -> Result<()> {
self.value = self.value.adopt(rectangle)?;
if self.positions.is_none() {
self.source_shape = self.value.shape()?;
}
Ok(())
}
pub(super) fn info(
&self,
source: &DataSourceRef,
name: &str,
selector: &BindingSelector,
) -> Result<DataSourceInfo> {
let shape = self.value.shape()?;
let mut info = DataSourceInfo::selected_optional(
source.clone(),
selector.clone(),
self.keys.clone(),
self.positions.clone(),
self.source_shape.clone(),
shape,
)
.named(name.to_owned());
if let Some(names) = &self.names {
if self.keys.is_some() {
info = info.with_selected_names(names.clone())?;
}
}
Ok(info)
}
pub(super) fn field(&self) -> Option<(RawKey, String)> {
let keys = self.keys.as_ref()?;
let names = self.names.as_ref()?;
match (keys.as_slice(), names.as_slice()) {
([key], [name]) => Some((key.clone(), name.clone())),
_ => None,
}
}
pub(super) fn name(&self) -> Option<&str> {
match self.names.as_deref() {
Some([name]) => Some(name),
_ => None,
}
}
}
fn matching_key(actual: &RawKey, query: &RawKey) -> bool {
if actual == query {
return true;
}
match (actual, query) {
(RawKey::Instant(actual), RawKey::Instant(query)) => {
actual.unix_ns() == query.unix_ns()
&& actual.zone() == query.zone()
&& query
.offset_seconds()
.is_none_or(|offset| actual.offset_seconds() == Some(offset))
&& query.fold().is_none_or(|fold| actual.fold() == Some(fold))
}
(RawKey::Tuple(actual), RawKey::Tuple(query)) => {
actual.len() == query.len()
&& actual
.iter()
.zip(query)
.all(|(actual, query)| matching_key(actual, query))
}
_ => false,
}
}
fn unique_key<'a>(fields: impl Iterator<Item = Option<&'a RawKey>>, key: &RawKey) -> Result<usize> {
let mut indices = fields.enumerate().filter_map(|(index, candidate)| {
candidate
.is_some_and(|candidate| matching_key(candidate, key))
.then_some(index)
});
let Some(index) = indices.next() else {
return Err(crate::Error::Data(crate::errors::Diagnostic::new(
crate::errors::DiagnosticKind::UnknownKey {
key: Some(key.clone()),
},
format!("no exact source key {key:?}"),
)));
};
if indices.next().is_some() {
return Err(invalid(format!("source key {key:?} is ambiguous")));
}
Ok(index)
}
fn position(value: isize, width: usize) -> Result<usize> {
let index = if value < 0 {
width.checked_sub(value.unsigned_abs())
} else {
usize::try_from(value).ok()
};
index
.filter(|&index| index < width)
.ok_or_else(|| invalid(format!("column index {value} is outside width {width}")))
}
fn slice_indices(slice: &crate::data::BindingSlice, width: usize) -> Result<Vec<usize>> {
let width =
isize::try_from(width).map_err(|_| invalid("column axis exceeds signed index range"))?;
let negative = slice.step().is_negative();
let endpoint = |value: Option<isize>, default| -> Result<isize> {
let Some(value) = value else {
return Ok(default);
};
let resolved = if value < 0 {
width.checked_add(value)
} else {
Some(value)
};
resolved
.filter(|&value| value >= 0 && value <= width && (!negative || value < width))
.ok_or_else(|| invalid("slice endpoint is outside the logical column axis"))
};
let start = endpoint(slice.start(), if negative { width - 1 } else { 0 })?;
let stop = endpoint(slice.stop(), if negative { -1 } else { width })?;
let stride = slice
.step()
.to_i128()
.and_then(|step| isize::try_from(step).ok());
let mut index = start;
let mut positions = Vec::new();
while if negative { index > stop } else { index < stop } {
crate::operation::check()?;
positions.push(usize::try_from(index).map_err(|_| invalid("invalid slice index"))?);
let Some(next) = stride.and_then(|step| index.checked_add(step)) else {
break;
};
index = next;
}
Ok(positions)
}
fn table_indices(fields: &[BindingField<'_>], selector: &BindingSelector) -> Result<Vec<usize>> {
let key = |key: &RawKey| unique_key(fields.iter().map(|field| field.key.as_ref()), key);
let indices = match selector {
BindingSelector::Key(value) => vec![key(value)?],
BindingSelector::Keys(values) => values.iter().map(key).collect::<Result<_>>()?,
BindingSelector::Index(index) => vec![position(*index, fields.len())?],
BindingSelector::Indices(indices) => indices
.iter()
.map(|&index| position(index, fields.len()))
.collect::<Result<_>>()?,
BindingSelector::Slice(slice) => slice_indices(slice, fields.len())?,
BindingSelector::Whole | BindingSelector::All => (0..fields.len()).collect(),
BindingSelector::NumericOnly => fields
.iter()
.enumerate()
.filter_map(|(index, field)| field.numeric.then_some(index))
.collect(),
};
check_indices(indices)
}
fn check_indices(indices: Vec<usize>) -> Result<Vec<usize>> {
let mut seen = HashSet::new();
if indices.is_empty() {
return Err(invalid("selection must not be empty"));
}
if indices.iter().any(|index| !seen.insert(*index)) {
return Err(invalid("duplicate selected source field"));
}
Ok(indices)
}
fn select_table<'a>(
rows: usize,
fields: &[BindingField<'a>],
selector: &BindingSelector,
) -> Result<Selection<'a>> {
let indices = table_indices(fields, selector)?;
let selected: Vec<_> = indices.iter().map(|&index| fields[index].clone()).collect();
let keys = selected.iter().map(|field| field.key.clone()).collect();
let names = Some(selected.iter().map(|field| field.name.clone()).collect());
let value = if matches!(
selector,
BindingSelector::Key(_) | BindingSelector::Index(_)
) {
let value = selected[0].value.clone();
if value.shape()? != [rows] {
return Err(invalid(
"selected field is not aligned with its table's row axis",
));
}
value
} else {
BindingObject::table(rows, selected)
};
Ok(Selection {
value,
source_shape: vec![rows, fields.len()],
keys,
names,
positions: Some(indices),
})
}
fn select_members<'a>(
members: &[(RawKey, BindingObject<'a>)],
selector: &BindingSelector,
) -> Result<Selection<'a>> {
let key = |key: &RawKey| unique_key(members.iter().map(|(key, _)| Some(key)), key);
let (indices, single) = match selector {
BindingSelector::Key(value) => (vec![key(value)?], true),
BindingSelector::Keys(values) => {
(values.iter().map(key).collect::<Result<Vec<_>>>()?, false)
}
_ => {
return Err(invalid(
"named members have no logical column positions or discovery rule",
))
}
};
let indices = check_indices(indices)?;
let selected: Vec<_> = indices
.iter()
.map(|&index| members[index].clone())
.collect();
let keys = Some(selected.iter().map(|(key, _)| key.clone()).collect());
let names = Some(selected.iter().map(|(key, _)| key_name(key)).collect());
let value = if single {
selected[0].1.clone()
} else {
let mut rows = None;
let mut fields = Vec::new();
for (key, value) in selected {
let column = value.column()?;
if rows
.replace(column.len())
.is_some_and(|length| length != column.len())
{
return Err(invalid("selected member vectors have different lengths"));
}
fields.push(BindingField::new(
Some(key.clone()),
key_name(&key),
column.is_numeric(),
value,
));
}
BindingObject::table(rows.unwrap_or(0), fields)
};
Ok(Selection {
source_shape: value.shape()?,
value,
keys,
names,
positions: None,
})
}
pub(super) fn key_name(key: &RawKey) -> String {
match key {
RawKey::String(value) => value.clone(),
RawKey::Integer(value) => integer(value).to_string(),
RawKey::Float(value) => value.to_string(),
RawKey::Boolean(value) => value.to_string(),
RawKey::Tuple(values) => format!(
"({})",
values.iter().map(key_name).collect::<Vec<_>>().join(", ")
),
RawKey::Date(value) => format!(
"{:04}-{:02}-{:02}",
value.year(),
value.month(),
value.day()
),
RawKey::Duration(value) => format!("{} ns", value.nanoseconds()),
RawKey::Instant(value) => format!("{} ns", value.unix_ns()),
RawKey::LocalTimestamp(value) => format!(
"{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:09}",
value.date().year(),
value.date().month(),
value.date().day(),
value.hour(),
value.minute(),
value.second(),
value.nanos()
),
RawKey::Interval(value) => format!(
"{}{}, {}{}",
if matches!(
value.closed(),
crate::data::IntervalClosed::Left | crate::data::IntervalClosed::Both
) {
"["
} else {
"("
},
key_name(value.left()),
key_name(value.right()),
if matches!(
value.closed(),
crate::data::IntervalClosed::Right | crate::data::IntervalClosed::Both
) {
"]"
} else {
")"
}
),
RawKey::Unavailable(value) => value.reason().to_owned(),
}
}
#[derive(Default)]
pub(super) struct KeyProjection {
tokens: std::collections::HashMap<(RawKey, String), String>,
reserved: HashSet<String>,
pub(super) labels: crate::formatting::Labels,
}
impl KeyProjection {
const PREFIX: &'static str = "__lichtung_recipe_key_";
pub(super) fn take_labels(&mut self) -> crate::formatting::Labels {
self.tokens.clear();
std::mem::take(&mut self.labels)
}
pub(super) fn reserve(&mut self, value: &str) {
if value.starts_with(Self::PREFIX) {
self.reserved.insert(value.to_owned());
}
}
pub(super) fn reserve_column(&mut self, column: &Column) {
self.reserve(column.name());
match column {
Column::Category(values) | Column::Text { values, .. } => {
for level in values.levels() {
self.reserve(level);
}
}
Column::Keys { values, .. } => {
for key in values.levels() {
if let RawKey::String(value) = key {
self.reserve(value);
}
}
}
_ => {}
}
}
fn fresh_token(&self) -> Result<String> {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT_TOKEN: AtomicU64 = AtomicU64::new(0);
loop {
let index = NEXT_TOKEN
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
value.checked_add(1)
})
.map_err(|_| invalid("renderer key identity space exhausted"))?;
let token = format!("{}{index}", Self::PREFIX);
if !self.reserved.contains(&token) {
return Ok(token);
}
}
}
pub(super) fn position_token(
&mut self,
axis: usize,
index: usize,
display: &str,
) -> Result<String> {
let token = self.fresh_token()?;
self.labels =
std::mem::take(&mut self.labels).capture_grid_label(&token, axis, index, display);
Ok(token)
}
pub(super) fn display(&self, token: &str) -> String {
self.labels
.captured_display(token)
.unwrap_or(token)
.to_owned()
}
pub(super) fn token(&mut self, key: &RawKey, display: &str) -> Result<String> {
let identity = (key.clone(), display.to_owned());
if let Some(token) = self.tokens.get(&identity) {
return Ok(token.clone());
}
let token = self.fresh_token()?;
self.tokens.insert(identity, token.clone());
self.labels = std::mem::take(&mut self.labels).capture_alias(
token.clone(),
Some(key.clone()),
display,
);
Ok(token)
}
pub(super) fn categories(
&mut self,
values: &RawKeyValues,
name: &str,
) -> Result<CategoryValues> {
self.categories_with_labels(values, name, None)
}
fn categories_with_labels(
&mut self,
values: &RawKeyValues,
name: &str,
labels: Option<&std::collections::HashMap<RawKey, String>>,
) -> Result<CategoryValues> {
let mut levels = std::collections::HashMap::new();
for key in values.levels() {
crate::operation::check()?;
let display = labels
.and_then(|labels| labels.get(key))
.cloned()
.unwrap_or_else(|| key_name(key));
let token = if matches!(key,RawKey::String(raw) if raw==&display) {
display
} else {
self.token(key, &display)?
};
levels.insert(key, token);
}
let projected = crate::data::source::collect_source(
values
.iter()
.map(|key| Ok(key.map(|key| levels[key].clone()))),
)?;
CategoryValues::nullable(name, projected)?
.with_key_values(crate::data::KeyValues::Raw(values.clone().with_name(name)))
}
}
impl Column {
pub(super) fn len(&self) -> usize {
match self {
Self::Numeric(values) => values.len(),
Self::Category(values) | Self::Text { values, .. } => values.len(),
Self::Boolean(values) => values.len(),
Self::Rows(values) => values.len(),
Self::SignificanceTargets(values) => values.len(),
Self::SignificanceMarks(values) => values.len(),
Self::FacetCells(values) => values.len(),
Self::Keys { values, .. } => values.len(),
}
}
pub(super) fn name(&self) -> &str {
match self {
Self::Numeric(values) => values.name(),
Self::Category(values) | Self::Text { values, .. } => values.original_name(),
Self::Boolean(values) => values.name(),
Self::Rows(_) => "row_id",
Self::SignificanceTargets(_) => "targets",
Self::SignificanceMarks(_) => "marks",
Self::FacetCells(_) => "facets",
Self::Keys { values, .. } => values.name(),
}
}
pub(super) fn is_numeric(&self) -> bool {
match self {
Self::Numeric(_) | Self::Rows(_) => true,
Self::Keys { dtype, .. } => *dtype == BindingColumnType::Numeric,
Self::Text { numeric, .. } => *numeric,
_ => false,
}
}
pub(super) fn numeric_values(&self, name: &str) -> Result<NumericValues> {
use crate::data::source::collect_source;
let values = match self {
Self::Numeric(values) => return Ok(values.clone().with_value_name(name)),
Self::Rows(values) => collect_source(values.iter().map(|value| {
crate::numeric::binary::signed_ratio(value.into(), 1_u8.into()).map(Some)
}))?,
Self::Keys {
values,
dtype:
BindingColumnType::Numeric | BindingColumnType::Keys | BindingColumnType::Null,
integer_negative_zero,
..
} => collect_source(values.iter().enumerate().map(|(row, key)| {
if integer_negative_zero.binary_search(&row).is_ok() {
return Ok(Some(-0.0));
}
key.map(number).transpose()
}))?,
Self::Text { values, dtype, .. } => collect_source(values.iter().map(|value| {
value
.filter(|text| !text.trim().is_empty())
.map(|text| {
let token = text.trim();
let parsed = if matches!(dtype, Some(TextType::F32)) {
token.parse::<f32>().map(f64::from)
} else {
token.parse::<f64>()
};
parsed.map_err(|_| invalid(format!("invalid numeric token {text:?}")))
})
.transpose()
}))?,
_ => return Err(invalid("numeric role requires actual numeric values")),
};
Ok(NumericValues::nullable(name, values))
}
pub(super) fn category_values(
&self,
name: &str,
projection: &mut KeyProjection,
) -> Result<CategoryValues> {
match self {
Self::Category(values) => match values.key_values() {
crate::data::KeyValues::Strings(values) => Ok(values.with_field_name(name)),
crate::data::KeyValues::Raw(values) => projection.categories(&values, name),
},
Self::Text { values, .. } => Ok(values.clone().with_field_name(name)),
Self::Keys {
values,
dtype:
BindingColumnType::Category | BindingColumnType::Keys | BindingColumnType::Null,
display_labels,
..
} => {
if values
.levels()
.iter()
.all(|key| matches!(key, RawKey::String(_)))
{
return CategoryValues::nullable(
name,
values.iter().map(|key| {
key.map(|key| match key {
RawKey::String(value) => value.as_str(),
_ => unreachable!("string key column"),
})
}),
);
}
projection.categories_with_labels(values, name, display_labels.as_deref())
}
_ => Err(invalid("categorical role requires actual category keys")),
}
}
pub(super) fn key_category(
&self,
name: &str,
projection: &mut KeyProjection,
) -> Result<CategoryValues> {
use crate::data::source::collect_source;
let keys = match self {
Self::Text {
values,
dtype: Some(dtype),
..
} if !matches!(dtype, TextType::String) => {
let keys = crate::data::source::collect_source(values.iter().map(|value| {
value
.map(|value| dtype.key(value))
.transpose()
.map(Option::flatten)
}))?;
RawKeyValues::nullable(name, keys)?
}
Self::Category(_) | Self::Text { .. } => return self.category_values(name, projection),
Self::Keys { values, .. } => values.clone(),
Self::Numeric(values) => {
RawKeyValues::nullable(name, values.iter().map(|value| value.map(RawKey::Float)))?
}
Self::Boolean(values) => {
RawKeyValues::nullable(name, values.iter().map(|value| value.map(RawKey::Boolean)))?
}
Self::Rows(values) => RawKeyValues::new(
name,
values.iter().map(|value| RawKey::Integer(value.into())),
)?,
_ => {
return Err(invalid(
"explicit typed result members require their own role",
))
}
};
if keys
.levels()
.iter()
.all(|key| matches!(key, RawKey::String(_)))
{
let values = collect_source(keys.iter().map(|key| {
Ok(key.map(|key| match key {
RawKey::String(value) => value.clone(),
_ => unreachable!("actual string key column"),
}))
}))?;
CategoryValues::nullable(name, values)
} else {
projection.categories(&keys, name)
}
}
pub(super) fn significance_targets(
&self,
projection: &mut KeyProjection,
) -> Result<std::sync::Arc<[crate::elements::SignificanceTarget]>> {
if let Self::SignificanceTargets(values) = self {
return Ok(values.clone());
}
let keys = self.key_category("targets", projection)?.key_values();
Ok(
crate::data::source::collect_source((0..keys.len()).map(|slot| {
keys.key_at(slot)
.map(crate::elements::SignificanceTarget::category)
.ok_or_else(|| invalid("missing significance target"))
}))?
.into(),
)
}
pub(super) fn facet_cells(
&self,
projection: &mut KeyProjection,
) -> Result<std::sync::Arc<[crate::layout::FacetCell]>> {
if let Self::FacetCells(values) = self {
return Ok(values.clone());
}
let keys = self.key_category("facets", projection)?.key_values();
Ok(
crate::data::source::collect_source((0..keys.len()).map(|slot| {
keys.key_at(slot)
.map(crate::layout::FacetCell::single)
.ok_or_else(|| invalid("missing result facet"))
}))?
.into(),
)
}
pub(super) fn significance_marks(
&self,
) -> Result<std::sync::Arc<[crate::elements::SignificanceMark]>> {
use crate::elements::SignificanceMark;
if let Self::SignificanceMarks(values) = self {
return Ok(values.clone());
}
let text_mark = |value: &str| match value {
"ns" => Ok(SignificanceMark::NotSignificant),
"*" => Ok(SignificanceMark::OneStar),
"**" => Ok(SignificanceMark::TwoStars),
"***" => Ok(SignificanceMark::ThreeStars),
"****" => Ok(SignificanceMark::FourStars),
_ => Err(invalid(format!("unknown significance mark {value:?}"))),
};
let marks = match self {
Self::Category(values) => {
crate::data::source::collect_source(values.iter().map(|value| {
value
.ok_or_else(|| invalid("missing significance mark"))
.and_then(text_mark)
}))?
}
Self::Text { values, dtype, .. } => {
crate::data::source::collect_source(values.iter().map(|value| {
let value = value.ok_or_else(|| invalid("missing significance mark"))?;
let parsed = match dtype {
Some(TextType::String | TextType::Boolean) => return text_mark(value),
Some(TextType::F32) => value.trim().parse::<f32>().map(f64::from),
_ => value.trim().parse::<f64>(),
};
parsed
.map(SignificanceMark::PValue)
.or_else(|_| text_mark(value))
}))?
}
Self::Keys {
values,
integer_negative_zero,
..
} => crate::data::source::collect_source(values.iter().enumerate().map(
|(index, value)| match value {
Some(_) if integer_negative_zero.binary_search(&index).is_ok() => {
Ok(SignificanceMark::PValue(-0.0))
}
Some(RawKey::String(value)) => text_mark(value),
Some(key) => number(key).map(SignificanceMark::PValue),
None => Err(invalid("missing significance mark")),
},
))?,
Self::Numeric(values) => {
crate::data::source::collect_source(values.iter().map(|value| {
value
.map(SignificanceMark::PValue)
.ok_or_else(|| invalid("missing significance mark"))
}))?
}
_ => return Err(invalid("expected explicit significance marks")),
};
Ok(marks.into())
}
pub(super) fn boolean_values(&self, name: &str) -> Result<BooleanValues> {
use crate::data::source::collect_source;
let values = match self {
Self::Boolean(values) => return Ok(values.clone().with_value_name(name)),
Self::Keys {
values,
dtype:
BindingColumnType::Boolean | BindingColumnType::Keys | BindingColumnType::Null,
..
} => collect_source(values.iter().map(|key| match key {
None => Ok(None),
Some(RawKey::Boolean(value)) => Ok(Some(*value)),
_ => Err(invalid("Boolean role requires Boolean values")),
}))?,
Self::Text { values, .. } => {
collect_source(values.iter().map(|value| match value.map(str::trim) {
None | Some("") => Ok(None),
Some("true" | "True" | "TRUE") => Ok(Some(true)),
Some("false" | "False" | "FALSE") => Ok(Some(false)),
Some(value) => Err(invalid(format!("invalid Boolean token {value:?}"))),
}))?
}
_ => return Err(invalid("Boolean role requires actual Boolean values")),
};
Ok(BooleanValues::nullable(name, values))
}
pub(super) fn source_rows(&self) -> Result<SourceRows> {
if let Self::Rows(values) = self {
return Ok(values.clone());
}
SourceRows::new(self.exact_indices("row identities")?)
}
pub(super) fn exact_indices(&self, role: &str) -> Result<Vec<usize>> {
match self {
Self::Rows(values) => Ok(values.iter().collect()),
Self::Keys { values, .. } => values
.iter()
.map(|key| match key {
Some(RawKey::Integer(value)) => value
.to_usize()
.ok_or_else(|| invalid(format!("{role} exceed the native index range"))),
_ => Err(invalid(format!("{role} require present exact integers"))),
})
.collect(),
Self::Text { values, .. } => values
.iter()
.map(|text| {
text.and_then(|text| text.trim().parse().ok())
.ok_or_else(|| invalid(format!("invalid exact integer token for {role}")))
})
.collect(),
_ => Err(invalid(format!("{role} require an exact integer source"))),
}
}
}
fn number(key: &RawKey) -> Result<f64> {
match key {
RawKey::Integer(value) => crate::numeric::binary::signed_ratio(integer(value), 1_u8.into()),
RawKey::Float(value) => Ok(*value),
_ => Err(invalid(
"numeric role requires a numeric dtype or numeric token",
)),
}
}