Skip to main content

lichtung_plot/
values.rs

1//! Immutable Rust-native values accepted by plot constructors.
2
3use std::collections::{HashMap, HashSet};
4use std::sync::Arc;
5
6use crate::Error;
7
8/// Original source-row identities attached once to a plot's aligned values.
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub struct SourceRows(Arc<[usize]>);
11
12impl SourceRows {
13    /// Construct unique source-row identities.
14    pub fn new(rows: impl IntoIterator<Item = usize>) -> Result<Self, Error> {
15        let rows = rows.into_iter().collect::<Vec<_>>();
16        let mut seen = HashSet::with_capacity(rows.len());
17        if let Some(duplicate) = rows.iter().copied().find(|row| !seen.insert(*row)) {
18            return Err(Error::Data(format!(
19                "source-row identities must be unique; found duplicate {duplicate}"
20            )));
21        }
22        Ok(Self(rows.into()))
23    }
24
25    /// Number of represented rows.
26    #[must_use]
27    pub fn len(&self) -> usize {
28        self.0.len()
29    }
30
31    /// Whether no rows are represented.
32    #[must_use]
33    pub fn is_empty(&self) -> bool {
34        self.0.is_empty()
35    }
36
37    pub(crate) fn as_slice(&self) -> &[usize] {
38        &self.0
39    }
40}
41
42#[derive(Debug, Clone)]
43enum Validity {
44    All,
45    Bitmap(Arc<[u64]>),
46}
47
48impl Validity {
49    fn from_flags(flags: &[bool]) -> Self {
50        if flags.iter().all(|valid| *valid) {
51            return Self::All;
52        }
53        let mut words = vec![0_u64; flags.len().div_ceil(64)];
54        for (index, valid) in flags.iter().copied().enumerate() {
55            if valid {
56                words[index / 64] |= 1_u64 << (index % 64);
57            }
58        }
59        Self::Bitmap(words.into())
60    }
61
62    fn is_valid(&self, index: usize) -> bool {
63        match self {
64            Self::All => true,
65            Self::Bitmap(words) => words
66                .get(index / 64)
67                .is_some_and(|word| word & (1_u64 << (index % 64)) != 0),
68        }
69    }
70}
71
72/// Named nullable numeric values stored as immutable native `f64` data.
73#[derive(Debug, Clone)]
74pub struct NumericValues {
75    name: Arc<str>,
76    values: Arc<[f64]>,
77    validity: Validity,
78}
79
80impl NumericValues {
81    /// Construct complete numeric values.
82    #[must_use]
83    pub fn new(name: impl Into<String>, values: impl IntoIterator<Item = f64>) -> Self {
84        let values = values.into_iter().collect::<Vec<_>>();
85        Self {
86            name: Arc::from(name.into()),
87            values: values.into(),
88            validity: Validity::All,
89        }
90    }
91
92    /// Construct nullable numeric values without conflating nulls with `NaN`.
93    #[must_use]
94    pub fn nullable(
95        name: impl Into<String>,
96        values: impl IntoIterator<Item = Option<f64>>,
97    ) -> Self {
98        let values = values.into_iter().collect::<Vec<_>>();
99        let validity =
100            Validity::from_flags(&values.iter().map(Option::is_some).collect::<Vec<_>>());
101        let values = values
102            .into_iter()
103            .map(|value| value.unwrap_or(0.0))
104            .collect::<Vec<_>>();
105        Self {
106            name: Arc::from(name.into()),
107            values: values.into(),
108            validity,
109        }
110    }
111
112    /// Semantic value name used for inferred labels and diagnostics.
113    #[must_use]
114    pub fn name(&self) -> &str {
115        &self.name
116    }
117
118    /// Number of values, including nulls.
119    #[must_use]
120    pub fn len(&self) -> usize {
121        self.values.len()
122    }
123
124    /// Whether no values are present.
125    #[must_use]
126    pub fn is_empty(&self) -> bool {
127        self.values.is_empty()
128    }
129
130    #[expect(
131        clippy::option_option,
132        reason = "the outer option is row bounds and the inner option is value validity"
133    )]
134    pub(crate) fn get(&self, row: usize) -> Option<Option<f64>> {
135        self.values
136            .get(row)
137            .map(|value| self.validity.is_valid(row).then_some(*value))
138    }
139}
140
141/// Named nullable categorical values stored with stable dictionary encoding.
142#[derive(Debug, Clone)]
143pub struct CategoryValues {
144    name: Arc<str>,
145    levels: Arc<[String]>,
146    codes: Arc<[u32]>,
147    validity: Validity,
148}
149
150impl CategoryValues {
151    /// Construct complete categorical values in first-observed level order.
152    pub fn new<S>(
153        name: impl Into<String>,
154        values: impl IntoIterator<Item = S>,
155    ) -> Result<Self, Error>
156    where
157        S: Into<String>,
158    {
159        Self::from_optional(
160            name.into(),
161            values.into_iter().map(|value| Some(value.into())),
162        )
163    }
164
165    /// Construct nullable categorical values in first-observed level order.
166    pub fn nullable<S>(
167        name: impl Into<String>,
168        values: impl IntoIterator<Item = Option<S>>,
169    ) -> Result<Self, Error>
170    where
171        S: Into<String>,
172    {
173        Self::from_optional(
174            name.into(),
175            values.into_iter().map(|value| value.map(Into::into)),
176        )
177    }
178
179    fn from_optional(
180        name: String,
181        values: impl IntoIterator<Item = Option<String>>,
182    ) -> Result<Self, Error> {
183        let values = values.into_iter().collect::<Vec<_>>();
184        let mut levels = Vec::new();
185        let mut indices = HashMap::new();
186        let mut codes = Vec::with_capacity(values.len());
187        let mut valid = Vec::with_capacity(values.len());
188        for value in values {
189            let Some(value) = value else {
190                valid.push(false);
191                codes.push(0);
192                continue;
193            };
194            valid.push(true);
195            let code = if let Some(code) = indices.get(&value).copied() {
196                code
197            } else {
198                let code = u32::try_from(levels.len()).map_err(|_| {
199                    Error::Data(format!(
200                        "categorical values {name:?} exceed the supported distinct-level count"
201                    ))
202                })?;
203                indices.insert(value.clone(), code);
204                levels.push(value);
205                code
206            };
207            codes.push(code);
208        }
209        Ok(Self {
210            name: Arc::from(name),
211            levels: levels.into(),
212            codes: codes.into(),
213            validity: Validity::from_flags(&valid),
214        })
215    }
216
217    /// Semantic value name used for inferred labels and diagnostics.
218    #[must_use]
219    pub fn name(&self) -> &str {
220        &self.name
221    }
222
223    /// Number of values, including nulls.
224    #[must_use]
225    pub fn len(&self) -> usize {
226        self.codes.len()
227    }
228
229    /// Whether no values are present.
230    #[must_use]
231    pub fn is_empty(&self) -> bool {
232        self.codes.is_empty()
233    }
234
235    #[expect(
236        clippy::option_option,
237        reason = "the outer option is row bounds and the inner option is value validity"
238    )]
239    pub(crate) fn get(&self, row: usize) -> Option<Option<&str>> {
240        self.codes.get(row).map(|code| {
241            if !self.validity.is_valid(row) {
242                return None;
243            }
244            usize::try_from(*code)
245                .ok()
246                .and_then(|index| self.levels.get(index))
247                .map(String::as_str)
248        })
249    }
250
251    pub(crate) fn levels(&self) -> &[String] {
252        &self.levels
253    }
254
255    pub(crate) fn raw_field(&self) -> crate::data::category::RawField {
256        crate::data::category::RawField::from_shared(Arc::clone(&self.name))
257    }
258}
259
260/// Named nullable Boolean values.
261#[derive(Debug, Clone)]
262pub struct BooleanValues {
263    name: Arc<str>,
264    values: Arc<[bool]>,
265    validity: Validity,
266}
267
268impl BooleanValues {
269    /// Construct complete Boolean values.
270    #[must_use]
271    pub fn new(name: impl Into<String>, values: impl IntoIterator<Item = bool>) -> Self {
272        let values = values.into_iter().collect::<Vec<_>>();
273        Self {
274            name: Arc::from(name.into()),
275            values: values.into(),
276            validity: Validity::All,
277        }
278    }
279
280    /// Construct nullable Boolean values.
281    #[must_use]
282    pub fn nullable(
283        name: impl Into<String>,
284        values: impl IntoIterator<Item = Option<bool>>,
285    ) -> Self {
286        let values = values.into_iter().collect::<Vec<_>>();
287        let validity =
288            Validity::from_flags(&values.iter().map(Option::is_some).collect::<Vec<_>>());
289        let values = values
290            .into_iter()
291            .map(|value| value.unwrap_or(false))
292            .collect::<Vec<_>>();
293        Self {
294            name: Arc::from(name.into()),
295            values: values.into(),
296            validity,
297        }
298    }
299
300    /// Semantic value name used for diagnostics.
301    #[must_use]
302    pub fn name(&self) -> &str {
303        &self.name
304    }
305
306    /// Number of values, including nulls.
307    #[must_use]
308    pub fn len(&self) -> usize {
309        self.values.len()
310    }
311
312    /// Whether no values are present.
313    #[must_use]
314    pub fn is_empty(&self) -> bool {
315        self.values.is_empty()
316    }
317
318    #[expect(
319        clippy::option_option,
320        reason = "the outer option is row bounds and the inner option is value validity"
321    )]
322    pub(crate) fn get(&self, row: usize) -> Option<Option<bool>> {
323        self.values
324            .get(row)
325            .map(|value| self.validity.is_valid(row).then_some(*value))
326    }
327}