Skip to main content

lichtung_plot/data/
arrays.rs

1//! Immutable, logically indexed native arrays. No foreign array borrow survives.
2
3use std::sync::Arc;
4
5use super::{DataSourceInfo, Date, Duration, ExactInteger, RawKey, Timestamp};
6use crate::{
7    style::{LinePattern, PointShape},
8    Color, Error, Result, Text,
9};
10
11/// An owning, nullable, row-major array with a statically known rank.
12#[derive(Debug, Clone)]
13pub struct NdArray<T, const D: usize> {
14    shape: [usize; D],
15    values: Arc<[Option<T>]>,
16    source: DataSourceInfo,
17}
18
19impl<T, const D: usize> NdArray<T, D> {
20    /// Construct an array with every supplied element present.
21    pub fn new(shape: [usize; D], values: Vec<T>) -> Result<Self> {
22        Self::nullable(shape, values.into_iter().map(Some).collect())
23    }
24
25    /// Construct a nullable array without changing its logical shape.
26    pub fn nullable(shape: [usize; D], values: Vec<Option<T>>) -> Result<Self> {
27        let count = if shape.contains(&0) {
28            Some(0)
29        } else {
30            shape
31                .iter()
32                .try_fold(1usize, |count, &extent| count.checked_mul(extent))
33        };
34        let count = count
35            .ok_or_else(|| Error::Data("array shape exceeds supported element count".into()))?;
36        if count != values.len() {
37            return Err(Error::Data(
38                format!(
39                    "array shape {shape:?} requires {count} values, got {}",
40                    values.len()
41                )
42                .into(),
43            ));
44        }
45        Ok(Self {
46            shape,
47            values: values.into(),
48            source: DataSourceInfo::direct(shape.to_vec()),
49        })
50    }
51
52    /// Original captured source of this actual native array.
53    #[doc(hidden)]
54    pub fn get_source(&self) -> &DataSourceInfo {
55        &self.source
56    }
57
58    /// Original logical shape.
59    pub const fn shape(&self) -> [usize; D] {
60        self.shape
61    }
62
63    /// Number of logical elements, including missing elements.
64    pub fn len(&self) -> usize {
65        self.values.len()
66    }
67
68    /// Whether the array has no logical elements.
69    pub fn is_empty(&self) -> bool {
70        self.values.is_empty()
71    }
72
73    fn offset(&self, index: [usize; D]) -> Option<usize> {
74        if index
75            .iter()
76            .zip(self.shape)
77            .any(|(&at, extent)| at >= extent)
78        {
79            return None;
80        }
81        Some(
82            index
83                .into_iter()
84                .zip(self.shape)
85                .fold(0usize, |offset, (at, extent)| offset * extent + at),
86        )
87    }
88
89    /// Read an original logical slot; the inner None denotes null.
90    pub fn get(&self, index: [usize; D]) -> Option<Option<&T>> {
91        self.values.get(self.offset(index)?).map(Option::as_ref)
92    }
93
94    /// Query the actual original validity, independently of finiteness.
95    pub fn is_valid(&self, index: [usize; D]) -> Option<bool> {
96        self.get(index).map(|value| value.is_some())
97    }
98
99    /// Read every logical slot in row-major order.
100    pub fn iter(&self) -> impl ExactSizeIterator<Item = Option<&T>> + '_ {
101        self.values.iter().map(Option::as_ref)
102    }
103}
104
105impl<T: PartialEq, const D: usize> PartialEq for NdArray<T, D> {
106    fn eq(&self, other: &Self) -> bool {
107        self.shape == other.shape && self.values == other.values
108    }
109}
110
111/// Element type of an actual native array.
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
113#[non_exhaustive]
114pub enum ArrayElementType {
115    /// Ordinary scientific binary64 values.
116    F64,
117    /// Exact eight-bit components.
118    U8,
119    /// Exact arbitrary-magnitude integers.
120    Integer,
121    /// Boolean values.
122    Bool,
123    /// Complete raw keys.
124    RawKey,
125    /// Complete colors.
126    Color,
127    /// Original text declarations.
128    Text,
129    /// Gregorian dates.
130    Date,
131    /// Exact instants.
132    Instant,
133    /// Exact elapsed durations.
134    Duration,
135    /// Logical topology indices.
136    Index,
137    /// Point-symbol declarations.
138    PointShape,
139    /// Line-pattern declarations.
140    LinePattern,
141    /// Complete paint declarations.
142    Paint,
143}
144
145/// The actual element type and rank, independent of shape.
146#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
147pub struct ArrayValueType {
148    element: ArrayElementType,
149    rank: usize,
150}
151
152impl ArrayValueType {
153    /// Actual element type.
154    pub const fn element(self) -> ArrayElementType {
155        self.element
156    }
157    /// Actual logical rank.
158    pub const fn rank(self) -> usize {
159        self.rank
160    }
161}
162
163mod sealed {
164    pub trait Sealed {}
165}
166
167/// Element types for which the native array exposes a type descriptor.
168#[doc(hidden)]
169pub trait NdArrayElement: sealed::Sealed {
170    /// Actual native element type.
171    const ELEMENT: ArrayElementType;
172}
173
174macro_rules! elements {
175    ($($ty:ty => $kind:ident),+ $(,)?) => {$(
176        impl sealed::Sealed for $ty {}
177        impl NdArrayElement for $ty {
178            const ELEMENT: ArrayElementType = ArrayElementType::$kind;
179        }
180    )+};
181}
182
183elements!(
184    f64 => F64, u8 => U8, ExactInteger => Integer, bool => Bool, RawKey => RawKey,
185    Color => Color, Text => Text, Date => Date, Timestamp => Instant, Duration => Duration,
186    usize => Index, PointShape => PointShape, LinePattern => LinePattern,
187);
188
189impl<T: NdArrayElement, const D: usize> NdArray<T, D> {
190    /// Describe the actual native element type and rank.
191    pub const fn array_type(&self) -> ArrayValueType {
192        ArrayValueType {
193            element: T::ELEMENT,
194            rank: D,
195        }
196    }
197}
198
199macro_rules! arrays {
200    ($($variant:ident: $ty:ty, $rank:literal => $doc:literal),+ $(,)?) => {
201        /// Owning type erasure of the actual supported array values.
202        #[derive(Debug, Clone, PartialEq)]
203        #[non_exhaustive]
204        pub enum ArrayValues {
205            $(#[doc = $doc] $variant(NdArray<$ty, $rank>),)+
206        }
207
208        impl ArrayValues {
209            /// Actual logical shape, borrowed from the corresponding native rank.
210            pub fn shape(&self) -> Vec<usize> {
211                match self {
212                    $(Self::$variant(array) => array.shape().to_vec(),)+
213                }
214            }
215
216            /// Actual native element type and rank.
217            pub fn array_type(&self) -> ArrayValueType {
218                match self {
219                    $(Self::$variant(array) => array.array_type(),)+
220                }
221            }
222
223            /// Number of logical slots, including nulls.
224            pub fn len(&self) -> usize {
225                match self {
226                    $(Self::$variant(array) => array.len(),)+
227                }
228            }
229
230            /// Whether the actual array has no elements.
231            pub fn is_empty(&self) -> bool {
232                self.len() == 0
233            }
234
235            /// Query one actual logical slot at the full rank.
236            pub fn is_valid(&self, index: &[usize]) -> Option<bool> {
237                match self {
238                    $(Self::$variant(array) => array.is_valid(index.try_into().ok()?),)+
239                }
240            }
241        }
242    };
243}
244
245arrays!(
246    F64D2: f64, 2 => "Rank-two scientific measurements.",
247    F64D3: f64, 3 => "Rank-three scientific measurements.",
248    F64D4: f64, 4 => "Rank-four scientific measurements.",
249    U8D3: u8, 3 => "Rank-three exact byte components.",
250    U8D4: u8, 4 => "Rank-four exact byte components.",
251    IntegerD2: ExactInteger, 2 => "Rank-two exact integers.",
252    IntegerD3: ExactInteger, 3 => "Rank-three exact integers.",
253    BoolD2: bool, 2 => "Rank-two Boolean values.",
254    BoolD3: bool, 3 => "Rank-three Boolean values.",
255    RawKeyD2: RawKey, 2 => "Rank-two complete raw keys.",
256    RawKeyD3: RawKey, 3 => "Rank-three complete raw keys.",
257    ColorD1: Color, 1 => "Rank-one complete colors.",
258    ColorD2: Color, 2 => "Rank-two complete colors.",
259    ColorD3: Color, 3 => "Rank-three complete colors.",
260    TextD2: Text, 2 => "Rank-two text declarations.",
261    DateD2: Date, 2 => "Rank-two dates.",
262    InstantD2: Timestamp, 2 => "Rank-two exact instants.",
263    DurationD2: Duration, 2 => "Rank-two durations.",
264);
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    #[test]
271    fn arrays_keep_rank_and_original_validity() {
272        let array = NdArray::nullable(
273            [2, 2],
274            vec![Some(-0.), None, Some(f64::INFINITY), Some(f64::NAN)],
275        )
276        .unwrap();
277        assert_eq!(array.shape(), [2, 2]);
278        assert_eq!(
279            array.get([0, 0]).flatten().unwrap().to_bits(),
280            (-0.0_f64).to_bits()
281        );
282        assert_eq!(array.is_valid([0, 1]), Some(false));
283        assert_eq!(array.is_valid([1, 1]), Some(true));
284        assert!(array.get([1, 2]).is_none());
285        assert!(NdArray::<f64, 2>::new([3, 2], vec![0.; 4]).is_err());
286        assert!(NdArray::<f64, 2>::new([usize::MAX, 2], vec![]).is_err());
287        let empty = NdArray::<f64, 3>::new([usize::MAX, usize::MAX, 0], vec![]).unwrap();
288        assert!(empty.is_empty());
289        let erased = ArrayValues::F64D2(array.clone());
290        assert_eq!(erased.array_type().element(), ArrayElementType::F64);
291        assert_eq!(erased.array_type().rank(), 2);
292        assert_eq!(erased.is_valid(&[1]), None);
293        drop(array);
294        assert_eq!(erased.is_valid(&[1, 0]), Some(true));
295    }
296}