use std::sync::Arc;
use super::{DataSourceInfo, Date, Duration, ExactInteger, RawKey, Timestamp};
use crate::{
style::{LinePattern, PointShape},
Color, Error, Result, Text,
};
#[derive(Debug, Clone)]
pub struct NdArray<T, const D: usize> {
shape: [usize; D],
values: Arc<[Option<T>]>,
source: DataSourceInfo,
}
impl<T, const D: usize> NdArray<T, D> {
pub fn new(shape: [usize; D], values: Vec<T>) -> Result<Self> {
Self::nullable(shape, values.into_iter().map(Some).collect())
}
pub fn nullable(shape: [usize; D], values: Vec<Option<T>>) -> Result<Self> {
let count = if shape.contains(&0) {
Some(0)
} else {
shape
.iter()
.try_fold(1usize, |count, &extent| count.checked_mul(extent))
};
let count = count
.ok_or_else(|| Error::Data("array shape exceeds supported element count".into()))?;
if count != values.len() {
return Err(Error::Data(
format!(
"array shape {shape:?} requires {count} values, got {}",
values.len()
)
.into(),
));
}
Ok(Self {
shape,
values: values.into(),
source: DataSourceInfo::direct(shape.to_vec()),
})
}
#[doc(hidden)]
pub fn get_source(&self) -> &DataSourceInfo {
&self.source
}
pub const fn shape(&self) -> [usize; D] {
self.shape
}
pub fn len(&self) -> usize {
self.values.len()
}
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
fn offset(&self, index: [usize; D]) -> Option<usize> {
if index
.iter()
.zip(self.shape)
.any(|(&at, extent)| at >= extent)
{
return None;
}
Some(
index
.into_iter()
.zip(self.shape)
.fold(0usize, |offset, (at, extent)| offset * extent + at),
)
}
pub fn get(&self, index: [usize; D]) -> Option<Option<&T>> {
self.values.get(self.offset(index)?).map(Option::as_ref)
}
pub fn is_valid(&self, index: [usize; D]) -> Option<bool> {
self.get(index).map(|value| value.is_some())
}
pub fn iter(&self) -> impl ExactSizeIterator<Item = Option<&T>> + '_ {
self.values.iter().map(Option::as_ref)
}
}
impl<T: PartialEq, const D: usize> PartialEq for NdArray<T, D> {
fn eq(&self, other: &Self) -> bool {
self.shape == other.shape && self.values == other.values
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ArrayElementType {
F64,
U8,
Integer,
Bool,
RawKey,
Color,
Text,
Date,
Instant,
Duration,
Index,
PointShape,
LinePattern,
Paint,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ArrayValueType {
element: ArrayElementType,
rank: usize,
}
impl ArrayValueType {
pub const fn element(self) -> ArrayElementType {
self.element
}
pub const fn rank(self) -> usize {
self.rank
}
}
mod sealed {
pub trait Sealed {}
}
#[doc(hidden)]
pub trait NdArrayElement: sealed::Sealed {
const ELEMENT: ArrayElementType;
}
macro_rules! elements {
($($ty:ty => $kind:ident),+ $(,)?) => {$(
impl sealed::Sealed for $ty {}
impl NdArrayElement for $ty {
const ELEMENT: ArrayElementType = ArrayElementType::$kind;
}
)+};
}
elements!(
f64 => F64, u8 => U8, ExactInteger => Integer, bool => Bool, RawKey => RawKey,
Color => Color, Text => Text, Date => Date, Timestamp => Instant, Duration => Duration,
usize => Index, PointShape => PointShape, LinePattern => LinePattern,
);
impl<T: NdArrayElement, const D: usize> NdArray<T, D> {
pub const fn array_type(&self) -> ArrayValueType {
ArrayValueType {
element: T::ELEMENT,
rank: D,
}
}
}
macro_rules! arrays {
($($variant:ident: $ty:ty, $rank:literal => $doc:literal),+ $(,)?) => {
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum ArrayValues {
$(#[doc = $doc] $variant(NdArray<$ty, $rank>),)+
}
impl ArrayValues {
pub fn shape(&self) -> Vec<usize> {
match self {
$(Self::$variant(array) => array.shape().to_vec(),)+
}
}
pub fn array_type(&self) -> ArrayValueType {
match self {
$(Self::$variant(array) => array.array_type(),)+
}
}
pub fn len(&self) -> usize {
match self {
$(Self::$variant(array) => array.len(),)+
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn is_valid(&self, index: &[usize]) -> Option<bool> {
match self {
$(Self::$variant(array) => array.is_valid(index.try_into().ok()?),)+
}
}
}
};
}
arrays!(
F64D2: f64, 2 => "Rank-two scientific measurements.",
F64D3: f64, 3 => "Rank-three scientific measurements.",
F64D4: f64, 4 => "Rank-four scientific measurements.",
U8D3: u8, 3 => "Rank-three exact byte components.",
U8D4: u8, 4 => "Rank-four exact byte components.",
IntegerD2: ExactInteger, 2 => "Rank-two exact integers.",
IntegerD3: ExactInteger, 3 => "Rank-three exact integers.",
BoolD2: bool, 2 => "Rank-two Boolean values.",
BoolD3: bool, 3 => "Rank-three Boolean values.",
RawKeyD2: RawKey, 2 => "Rank-two complete raw keys.",
RawKeyD3: RawKey, 3 => "Rank-three complete raw keys.",
ColorD1: Color, 1 => "Rank-one complete colors.",
ColorD2: Color, 2 => "Rank-two complete colors.",
ColorD3: Color, 3 => "Rank-three complete colors.",
TextD2: Text, 2 => "Rank-two text declarations.",
DateD2: Date, 2 => "Rank-two dates.",
InstantD2: Timestamp, 2 => "Rank-two exact instants.",
DurationD2: Duration, 2 => "Rank-two durations.",
);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn arrays_keep_rank_and_original_validity() {
let array = NdArray::nullable(
[2, 2],
vec![Some(-0.), None, Some(f64::INFINITY), Some(f64::NAN)],
)
.unwrap();
assert_eq!(array.shape(), [2, 2]);
assert_eq!(
array.get([0, 0]).flatten().unwrap().to_bits(),
(-0.0_f64).to_bits()
);
assert_eq!(array.is_valid([0, 1]), Some(false));
assert_eq!(array.is_valid([1, 1]), Some(true));
assert!(array.get([1, 2]).is_none());
assert!(NdArray::<f64, 2>::new([3, 2], vec![0.; 4]).is_err());
assert!(NdArray::<f64, 2>::new([usize::MAX, 2], vec![]).is_err());
let empty = NdArray::<f64, 3>::new([usize::MAX, usize::MAX, 0], vec![]).unwrap();
assert!(empty.is_empty());
let erased = ArrayValues::F64D2(array.clone());
assert_eq!(erased.array_type().element(), ArrayElementType::F64);
assert_eq!(erased.array_type().rank(), 2);
assert_eq!(erased.is_valid(&[1]), None);
drop(array);
assert_eq!(erased.is_valid(&[1, 0]), Some(true));
}
}