use std::{
fmt,
hash::{Hash, Hasher},
sync::Arc,
};
use super::{AxisValues, ExactInteger, RawKey};
use crate::{BooleanValues, CategoryValues, Error, NumericValues, Result};
#[derive(Clone)]
pub struct DataSourceRef {
logical: Arc<()>,
capture: Arc<()>,
}
impl DataSourceRef {
#[doc(hidden)]
pub fn capture() -> Self {
Self {
logical: Arc::new(()),
capture: Arc::new(()),
}
}
#[doc(hidden)]
#[must_use]
pub fn recapture(&self) -> Self {
Self {
logical: Arc::clone(&self.logical),
capture: Arc::new(()),
}
}
pub fn same_source(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.logical, &other.logical)
}
}
impl PartialEq for DataSourceRef {
fn eq(&self, other: &Self) -> bool {
self.same_source(other) && Arc::ptr_eq(&self.capture, &other.capture)
}
}
impl Eq for DataSourceRef {}
impl Hash for DataSourceRef {
fn hash<H: Hasher>(&self, state: &mut H) {
Arc::as_ptr(&self.logical).hash(state);
Arc::as_ptr(&self.capture).hash(state);
}
}
impl fmt::Debug for DataSourceRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DataSourceRef").finish_non_exhaustive()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BindingSelectorKind {
Key,
Keys,
Index,
Indices,
Slice,
All,
NumericOnly,
Whole,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BindingSlice {
start: Option<isize>,
stop: Option<isize>,
step: ExactInteger,
}
impl BindingSlice {
pub fn new(start: Option<isize>, end: Option<isize>, stride: ExactInteger) -> Result<Self> {
if stride == ExactInteger::from(0) {
return Err(Error::Data("binding slice step must not be zero".into()));
}
Ok(Self {
start,
stop: end,
step: stride,
})
}
pub const fn start(&self) -> Option<isize> {
self.start
}
pub const fn stop(&self) -> Option<isize> {
self.stop
}
pub const fn step(&self) -> &ExactInteger {
&self.step
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BindingSelector {
Key(RawKey),
Keys(Vec<RawKey>),
Index(isize),
Indices(Vec<isize>),
Slice(BindingSlice),
All,
NumericOnly,
Whole,
}
impl BindingSelector {
pub const fn kind(&self) -> BindingSelectorKind {
match self {
Self::Key(_) => BindingSelectorKind::Key,
Self::Keys(_) => BindingSelectorKind::Keys,
Self::Index(_) => BindingSelectorKind::Index,
Self::Indices(_) => BindingSelectorKind::Indices,
Self::Slice(_) => BindingSelectorKind::Slice,
Self::All => BindingSelectorKind::All,
Self::NumericOnly => BindingSelectorKind::NumericOnly,
Self::Whole => BindingSelectorKind::Whole,
}
}
pub const fn get_key(&self) -> Option<&RawKey> {
if let Self::Key(key) = self {
Some(key)
} else {
None
}
}
pub fn get_keys(&self) -> Option<&[RawKey]> {
if let Self::Keys(keys) = self {
Some(keys)
} else {
None
}
}
pub const fn get_index(&self) -> Option<isize> {
if let Self::Index(index) = self {
Some(*index)
} else {
None
}
}
pub fn get_indices(&self) -> Option<&[isize]> {
if let Self::Indices(indices) = self {
Some(indices)
} else {
None
}
}
pub const fn get_slice(&self) -> Option<&BindingSlice> {
if let Self::Slice(slice) = self {
Some(slice)
} else {
None
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BindingGeneration {
RowPosition,
ColumnNames,
GridPosition,
WideExpansion,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DataSourceInfo(Arc<SourceInfo>);
#[derive(Debug, Clone, PartialEq, Eq)]
struct SourceInfo {
reference: DataSourceRef,
binding_name: Option<String>,
generation: Option<BindingGeneration>,
relation_shape: Option<Vec<usize>>,
grid_axis: Option<usize>,
selector: Option<BindingSelector>,
selected_keys: Option<Vec<RawKey>>,
selected_names: Option<Vec<String>>,
selected_indices: Option<Vec<usize>>,
source_shape: Vec<usize>,
selected_shape: Vec<usize>,
}
impl DataSourceInfo {
#[doc(hidden)]
pub fn direct(shape: Vec<usize>) -> Self {
Self(Arc::new(SourceInfo {
reference: DataSourceRef::capture(),
binding_name: None,
generation: None,
relation_shape: None,
grid_axis: None,
selector: None,
selected_keys: None,
selected_names: None,
selected_indices: None,
source_shape: shape.clone(),
selected_shape: shape,
}))
}
#[doc(hidden)]
pub fn selected(
reference: DataSourceRef,
selector: BindingSelector,
keys: Option<Vec<RawKey>>,
indices: Vec<usize>,
source_shape: Vec<usize>,
selected_shape: Vec<usize>,
) -> Self {
Self(Arc::new(SourceInfo {
reference,
binding_name: None,
generation: None,
relation_shape: None,
grid_axis: None,
selector: Some(selector),
selected_keys: keys,
selected_names: None,
selected_indices: Some(indices),
source_shape,
selected_shape,
}))
}
#[doc(hidden)]
pub fn direct_fields(shape: Vec<usize>, keys: Option<Vec<RawKey>>) -> Self {
let mut info = Self::direct(shape);
Arc::make_mut(&mut info.0).selected_keys = keys;
info
}
#[doc(hidden)]
#[must_use]
pub fn generated(mut self, generation: BindingGeneration, shape: Vec<usize>) -> Self {
let info = Arc::make_mut(&mut self.0);
info.generation = Some(generation);
info.relation_shape = Some(shape);
self
}
#[doc(hidden)]
#[must_use]
pub fn generated_grid_axis(mut self, axis: usize, extent: usize) -> Self {
let info = Arc::make_mut(&mut self.0);
info.generation = Some(BindingGeneration::GridPosition);
info.grid_axis = Some(axis);
info.relation_shape = Some(vec![extent]);
self
}
pub(crate) fn grid_axis(&self) -> Option<usize> {
self.0.grid_axis
}
pub fn binding_name(&self) -> Option<&str> {
self.0.binding_name.as_deref()
}
pub fn logical_keys(&self) -> Option<&[RawKey]> {
self.selected_keys()
}
pub fn generation(&self) -> Option<BindingGeneration> {
self.0.generation
}
pub fn reference(&self) -> &DataSourceRef {
&self.0.reference
}
pub fn selector(&self) -> Option<&BindingSelector> {
self.0.selector.as_ref()
}
#[doc(hidden)]
pub fn with_selected_names(mut self, names: Vec<String>) -> Result<Self> {
if self.0.selected_keys.as_ref().map(Vec::len) != Some(names.len()) {
return Err(Error::Data(
"captured field names must match their actual keys".into(),
));
}
Arc::make_mut(&mut self.0).selected_names = Some(names);
Ok(self)
}
#[doc(hidden)]
pub fn selected_names(&self) -> Option<&[String]> {
self.0.selected_names.as_deref()
}
#[doc(hidden)]
pub fn field(&self, position: usize) -> Option<(RawKey, String)> {
let key = self.0.selected_keys.as_ref()?.get(position)?;
let name = if let Some(names) = &self.0.selected_names {
names.get(position)?.clone()
} else if let RawKey::String(name) = key {
name.clone()
} else {
return None;
};
Some((key.clone(), name))
}
pub fn selected_keys(&self) -> Option<&[RawKey]> {
self.0.selected_keys.as_deref()
}
pub fn selected_indices(&self) -> Option<&[usize]> {
self.0.selected_indices.as_deref()
}
pub fn source_shape(&self) -> &[usize] {
&self.0.source_shape
}
pub fn selected_shape(&self) -> &[usize] {
&self.0.selected_shape
}
pub(crate) fn member_shape(&self) -> &[usize] {
self.0
.relation_shape
.as_deref()
.unwrap_or(&self.0.selected_shape)
}
fn selected_count(&self) -> Option<usize> {
self.member_shape()
.iter()
.try_fold(1usize, |n, &size| n.checked_mul(size))
}
}
#[derive(Debug, Clone)]
pub(crate) struct VectorSource {
info: DataSourceInfo,
projection: Option<Arc<SourceProjection>>,
}
#[derive(Debug, Clone)]
enum SlotProjection {
Identity,
Repeated(usize),
Cycled(usize),
Gathered(Arc<[usize]>),
}
#[derive(Debug, Clone)]
struct SourceProjection {
slots: SlotProjection,
original_nulls: bool,
field_nulls: Option<Arc<[bool]>>,
distinct_rows: bool,
field_axis_keys: Option<Arc<super::RawKeyValues>>,
}
impl Default for SourceProjection {
fn default() -> Self {
Self {
slots: SlotProjection::Identity,
original_nulls: false,
field_nulls: None,
distinct_rows: true,
field_axis_keys: None,
}
}
}
impl VectorSource {
pub(crate) fn direct(len: usize) -> Self {
Self::new(DataSourceInfo::direct(vec![len]))
}
pub(crate) fn direct_nullable(len: usize, has_nulls: bool) -> Self {
let mut source = Self::direct(len);
if has_nulls {
source.projection_mut().original_nulls = true;
}
source
}
pub(crate) fn new(info: DataSourceInfo) -> Self {
Self {
info,
projection: None,
}
}
fn projection_mut(&mut self) -> &mut SourceProjection {
Arc::make_mut(
self.projection
.get_or_insert_with(|| Arc::new(SourceProjection::default())),
)
}
pub(crate) fn repeated(info: DataSourceInfo, copies: usize, len: usize) -> Result<Self> {
if copies == 0 || info.selected_count().and_then(|n| n.checked_mul(copies)) != Some(len) {
return Err(Error::Data(
"captured source shape and repetition must match the actual value count".into(),
));
}
let mut source = Self::new(info);
if copies != 1 {
let projection = source.projection_mut();
projection.slots = SlotProjection::Repeated(copies);
projection.distinct_rows = false;
}
Ok(source)
}
pub(crate) fn cycled(info: DataSourceInfo, len: usize) -> Result<Self> {
let count = info.selected_count().unwrap_or(0);
if count == 0 || !len.is_multiple_of(count) {
return Err(Error::Data(
"captured column identity count must divide the actual value count".into(),
));
}
let field_axis_keys = complete_field_axis(&info)?;
Ok(Self {
info,
projection: Some(super::source::source_arc(SourceProjection {
slots: SlotProjection::Cycled(count),
distinct_rows: false,
field_axis_keys,
..SourceProjection::default()
})?),
})
}
pub(crate) fn gathered(info: DataSourceInfo, slots: Vec<usize>, len: usize) -> Result<Self> {
if slots.len() != len
|| !info
.selected_count()
.is_some_and(|count| slots.iter().all(|&slot| slot < count))
{
return Err(Error::Data(
"captured source slots must match the actual value domain".into(),
));
}
let distinct_rows = info.member_shape().len() == 1 && distinct_slots(&slots)?;
let field_axis_keys = complete_field_axis(&info)?;
Ok(Self {
info,
projection: Some(super::source::source_arc(SourceProjection {
slots: SlotProjection::Gathered(slots.into()),
distinct_rows,
field_axis_keys,
..SourceProjection::default()
})?),
})
}
pub(crate) fn info(&self) -> &DataSourceInfo {
&self.info
}
pub(crate) fn slot(&self, index: usize) -> usize {
match self
.projection
.as_deref()
.map(|projection| &projection.slots)
{
None | Some(SlotProjection::Identity) => index,
Some(SlotProjection::Repeated(copies)) => index / copies,
Some(SlotProjection::Cycled(count)) => index % count,
Some(SlotProjection::Gathered(slots)) => slots[index],
}
}
pub(crate) fn is_identity(&self) -> bool {
self.projection
.as_deref()
.is_none_or(|entry| matches!(entry.slots, SlotProjection::Identity))
}
pub(crate) fn has_distinct_rows(&self) -> bool {
self.info.member_shape().len() == 1
&& self
.projection
.as_deref()
.is_none_or(|entry| entry.distinct_rows)
}
pub(crate) fn field_axis_keys(&self) -> Option<&super::RawKeyValues> {
self.projection.as_deref()?.field_axis_keys.as_deref()
}
pub(crate) fn with_original_validity(
mut self,
length: usize,
has_nulls: bool,
is_valid: impl Fn(usize) -> bool,
) -> Result<Self> {
if !has_nulls && self.projection.is_none() {
return Ok(self);
}
let mut field_nulls = None;
if has_nulls && self.info.selected_keys().is_some() {
if let [_, width] = self.info.member_shape() {
let mut fields = Vec::new();
super::source::reserve_source(&mut fields, *width)?;
fields.resize(*width, false);
crate::operation::work(length)?;
for slot in 0..length {
if !is_valid(slot) {
fields[self.slot(slot) % width] = true;
}
}
field_nulls = Some(fields.into());
}
}
let projection = self.projection_mut();
projection.original_nulls = has_nulls;
projection.field_nulls = field_nulls;
Ok(self)
}
pub(crate) fn original_has_nulls(&self, field: Option<usize>) -> bool {
let Some(projection) = self.projection.as_deref() else {
return false;
};
field
.and_then(|field| projection.field_nulls.as_ref()?.get(field).copied())
.unwrap_or(projection.original_nulls)
}
pub(crate) fn retain_original_validity(&mut self, source: &Self) {
if let Some(original) = source.projection.as_deref() {
let projection = self.projection_mut();
projection.original_nulls = original.original_nulls;
projection.field_nulls.clone_from(&original.field_nulls);
projection.distinct_rows &= original.distinct_rows;
projection
.field_axis_keys
.clone_from(&original.field_axis_keys);
}
}
pub(crate) fn select(&self, indices: &[usize]) -> Result<Self> {
let slots =
super::source::collect_source(indices.iter().map(|&index| Ok(self.slot(index))))?;
let distinct_rows = self.has_distinct_rows() && distinct_slots(&slots)?;
let mut projection = self.projection.as_deref().cloned().unwrap_or_default();
projection.slots = SlotProjection::Gathered(slots.into());
projection.distinct_rows = distinct_rows;
Ok(Self {
info: self.info.clone(),
projection: Some(super::source::source_arc(projection)?),
})
}
}
fn complete_field_axis(info: &DataSourceInfo) -> Result<Option<Arc<super::RawKeyValues>>> {
if info.generation() != Some(BindingGeneration::ColumnNames) && info.grid_axis() != Some(1) {
return Ok(None);
}
let (Some(keys), Some(&width)) = (info.selected_keys(), info.source_shape().get(1)) else {
return Ok(None);
};
if keys.len() != width {
return Ok(None);
}
let mut ordered = Vec::new();
super::source::reserve_source(&mut ordered, width)?;
ordered.resize(width, None);
for (slot, key) in keys.iter().enumerate() {
let position = info
.selected_indices()
.and_then(|indices| indices.get(slot))
.copied()
.unwrap_or(slot);
let Some(target) = ordered.get_mut(position) else {
return Ok(None);
};
if target.replace(key.clone()).is_some() {
return Ok(None);
}
}
Ok(Some(Arc::new(super::RawKeyValues::nullable(
"field", ordered,
)?)))
}
fn distinct_slots(slots: &[usize]) -> Result<bool> {
crate::operation::work(slots.len())?;
if slots.windows(2).all(|pair| pair[0] < pair[1]) {
return Ok(true);
}
let mut sorted = super::source::collect_source(slots.iter().copied().map(Ok))?;
super::source::sort_source_by(&mut sorted, usize::cmp)?;
Ok(sorted.windows(2).all(|pair| pair[0] != pair[1]))
}
#[doc(hidden)]
pub trait CapturedValue: Sized {
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn retain(
self,
source: DataSourceInfo,
copies: usize,
field: Option<(RawKey, String)>,
) -> Result<Self>;
}
macro_rules! captured_values {
($($ty:ident),+) => {$(
impl CapturedValue for $ty {
fn len(&self) -> usize { self.len() }
fn retain(
self, source: DataSourceInfo, copies: usize, field: Option<(RawKey, String)>,
) -> Result<Self> {
let value = self.with_repeated_source(source, copies)?;
Ok(if let Some((key, name)) = field {
value.with_field_key(key, name)
} else {
value
})
}
}
)+};
}
captured_values!(NumericValues, CategoryValues, BooleanValues);
impl CapturedValue for super::SourceRows {
fn len(&self) -> usize {
self.len()
}
fn retain(
self,
source: DataSourceInfo,
copies: usize,
_: Option<(RawKey, String)>,
) -> Result<Self> {
if copies != 1 {
return Err(Error::Data(
"source row identities cannot be repeated".into(),
));
}
self.with_source(source)
}
}
impl CapturedValue for AxisValues {
fn len(&self) -> usize {
self.len()
}
fn retain(
self,
source: DataSourceInfo,
copies: usize,
field: Option<(RawKey, String)>,
) -> Result<Self> {
Ok(match self {
Self::Numeric(values) => Self::Numeric(values.retain(source, copies, field)?),
Self::Category(values) => Self::Category(values.retain(source, copies, field)?),
Self::Keys(values) => {
let len = values.len();
let source = VectorSource::repeated(source, copies, len)?.with_original_validity(
len,
values.has_nulls(),
|slot| values.is_valid(slot) == Some(true),
)?;
Self::Keys(values.with_vector_source(source))
}
})
}
}