lichtung-plot 0.2.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Immutable, logically indexed native arrays. No foreign array borrow survives.

use std::sync::Arc;

use super::{DataSourceInfo, Date, Duration, ExactInteger, RawKey, Timestamp};
use crate::{
    style::{LinePattern, PointShape},
    Color, Error, Result, Text,
};

/// An owning, nullable, row-major array with a statically known rank.
#[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> {
    /// Construct an array with every supplied element present.
    pub fn new(shape: [usize; D], values: Vec<T>) -> Result<Self> {
        Self::nullable(shape, values.into_iter().map(Some).collect())
    }

    /// Construct a nullable array without changing its logical shape.
    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()),
        })
    }

    /// Original captured source of this actual native array.
    #[doc(hidden)]
    pub fn get_source(&self) -> &DataSourceInfo {
        &self.source
    }

    /// Original logical shape.
    pub const fn shape(&self) -> [usize; D] {
        self.shape
    }

    /// Number of logical elements, including missing elements.
    pub fn len(&self) -> usize {
        self.values.len()
    }

    /// Whether the array has no logical elements.
    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),
        )
    }

    /// Read an original logical slot; the inner None denotes null.
    pub fn get(&self, index: [usize; D]) -> Option<Option<&T>> {
        self.values.get(self.offset(index)?).map(Option::as_ref)
    }

    /// Query the actual original validity, independently of finiteness.
    pub fn is_valid(&self, index: [usize; D]) -> Option<bool> {
        self.get(index).map(|value| value.is_some())
    }

    /// Read every logical slot in row-major order.
    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
    }
}

/// Element type of an actual native array.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ArrayElementType {
    /// Ordinary scientific binary64 values.
    F64,
    /// Exact eight-bit components.
    U8,
    /// Exact arbitrary-magnitude integers.
    Integer,
    /// Boolean values.
    Bool,
    /// Complete raw keys.
    RawKey,
    /// Complete colors.
    Color,
    /// Original text declarations.
    Text,
    /// Gregorian dates.
    Date,
    /// Exact instants.
    Instant,
    /// Exact elapsed durations.
    Duration,
    /// Logical topology indices.
    Index,
    /// Point-symbol declarations.
    PointShape,
    /// Line-pattern declarations.
    LinePattern,
    /// Complete paint declarations.
    Paint,
}

/// The actual element type and rank, independent of shape.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ArrayValueType {
    element: ArrayElementType,
    rank: usize,
}

impl ArrayValueType {
    /// Actual element type.
    pub const fn element(self) -> ArrayElementType {
        self.element
    }
    /// Actual logical rank.
    pub const fn rank(self) -> usize {
        self.rank
    }
}

mod sealed {
    pub trait Sealed {}
}

/// Element types for which the native array exposes a type descriptor.
#[doc(hidden)]
pub trait NdArrayElement: sealed::Sealed {
    /// Actual native element type.
    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> {
    /// Describe the actual native element type and rank.
    pub const fn array_type(&self) -> ArrayValueType {
        ArrayValueType {
            element: T::ELEMENT,
            rank: D,
        }
    }
}

macro_rules! arrays {
    ($($variant:ident: $ty:ty, $rank:literal => $doc:literal),+ $(,)?) => {
        /// Owning type erasure of the actual supported array values.
        #[derive(Debug, Clone, PartialEq)]
        #[non_exhaustive]
        pub enum ArrayValues {
            $(#[doc = $doc] $variant(NdArray<$ty, $rank>),)+
        }

        impl ArrayValues {
            /// Actual logical shape, borrowed from the corresponding native rank.
            pub fn shape(&self) -> Vec<usize> {
                match self {
                    $(Self::$variant(array) => array.shape().to_vec(),)+
                }
            }

            /// Actual native element type and rank.
            pub fn array_type(&self) -> ArrayValueType {
                match self {
                    $(Self::$variant(array) => array.array_type(),)+
                }
            }

            /// Number of logical slots, including nulls.
            pub fn len(&self) -> usize {
                match self {
                    $(Self::$variant(array) => array.len(),)+
                }
            }

            /// Whether the actual array has no elements.
            pub fn is_empty(&self) -> bool {
                self.len() == 0
            }

            /// Query one actual logical slot at the full rank.
            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));
    }
}