Skip to main content

lichtung_plot/data/
integer.rs

1//! Exact, owned integers and nullable integer columns.
2
3use std::{cmp::Ordering, sync::Arc};
4
5use crate::{Error, Result};
6
7/// An arbitrary-precision integer with canonical sign and big-endian magnitude.
8/// Scientific counts and externally supplied integer keys never pass through f64.
9#[derive(Debug, Clone, PartialEq, Eq, Hash)]
10pub struct ExactInteger {
11    negative: bool,
12    magnitude: Arc<[u8]>,
13}
14
15impl ExactInteger {
16    /// Construct from a sign and unsigned big-endian magnitude. Leading zeros
17    /// are removed and zero always has a nonnegative sign.
18    pub fn from_parts(negative: bool, magnitude_be: &[u8]) -> Result<Self> {
19        let first = magnitude_be
20            .iter()
21            .position(|&byte| byte != 0)
22            .unwrap_or(magnitude_be.len());
23        let bytes = &magnitude_be[first..];
24        let mut magnitude = Vec::new();
25        magnitude
26            .try_reserve_exact(bytes.len())
27            .map_err(|error| Error::Data(format!("integer magnitude storage: {error}").into()))?;
28        magnitude.extend_from_slice(bytes);
29        Ok(Self {
30            negative: negative && !magnitude.is_empty(),
31            magnitude: magnitude.into(),
32        })
33    }
34
35    /// Whether the represented integer is negative.
36    pub const fn is_negative(&self) -> bool {
37        self.negative
38    }
39
40    /// The canonical unsigned magnitude. Zero is the empty magnitude.
41    pub fn magnitude_be(&self) -> &[u8] {
42        &self.magnitude
43    }
44
45    fn magnitude_u128(&self) -> Option<u128> {
46        let mut bytes = [0; 16];
47        let offset = bytes.len().checked_sub(self.magnitude.len())?;
48        bytes[offset..].copy_from_slice(&self.magnitude);
49        Some(u128::from_be_bytes(bytes))
50    }
51
52    /// Read the exact unsigned value when it fits.
53    pub fn to_u128(&self) -> Option<u128> {
54        if self.negative {
55            None
56        } else {
57            self.magnitude_u128()
58        }
59    }
60
61    /// Read the exact signed value when it fits.
62    pub fn to_i128(&self) -> Option<i128> {
63        let magnitude = self.magnitude_u128()?;
64        if self.negative {
65            if magnitude == i128::MIN.unsigned_abs() {
66                Some(i128::MIN)
67            } else {
68                i128::try_from(magnitude).ok().map(|value| -value)
69            }
70        } else {
71            i128::try_from(magnitude).ok()
72        }
73    }
74
75    /// Read the exact nonnegative index when it fits the host index type.
76    pub fn to_usize(&self) -> Option<usize> {
77        usize::try_from(self.to_u128()?).ok()
78    }
79
80    fn bounded(negative: bool, bytes: [u8; 16]) -> Self {
81        let first = bytes
82            .iter()
83            .position(|&byte| byte != 0)
84            .unwrap_or(bytes.len());
85        Self {
86            negative: negative && first != bytes.len(),
87            magnitude: Arc::from(&bytes[first..]),
88        }
89    }
90}
91
92impl From<u128> for ExactInteger {
93    fn from(value: u128) -> Self {
94        Self::bounded(false, value.to_be_bytes())
95    }
96}
97
98impl From<i128> for ExactInteger {
99    fn from(value: i128) -> Self {
100        Self::bounded(value < 0, value.unsigned_abs().to_be_bytes())
101    }
102}
103
104macro_rules! integer_from {
105    ($large:ty; $($ty:ty),+) => {$(
106        impl From<$ty> for ExactInteger {
107            fn from(value: $ty) -> Self { Self::from(<$large>::from(value)) }
108        }
109    )+};
110}
111integer_from!(i128; i8, i16, i32, i64);
112integer_from!(u128; u8, u16, u32, u64);
113impl From<usize> for ExactInteger {
114    fn from(value: usize) -> Self {
115        Self::from(value as u128)
116    }
117}
118impl From<isize> for ExactInteger {
119    fn from(value: isize) -> Self {
120        Self::from(value as i128)
121    }
122}
123
124impl Ord for ExactInteger {
125    fn cmp(&self, other: &Self) -> Ordering {
126        let magnitude = || {
127            self.magnitude
128                .len()
129                .cmp(&other.magnitude.len())
130                .then_with(|| self.magnitude.cmp(&other.magnitude))
131        };
132        match (self.negative, other.negative) {
133            (true, false) => Ordering::Less,
134            (false, true) => Ordering::Greater,
135            (true, true) => magnitude().reverse(),
136            (false, false) => magnitude(),
137        }
138    }
139}
140impl PartialOrd for ExactInteger {
141    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
142        Some(self.cmp(other))
143    }
144}
145
146/// An owned named nullable column of exact integers.
147#[derive(Debug, Clone)]
148pub struct IntegerValues {
149    name: Arc<str>,
150    values: Arc<[Option<ExactInteger>]>,
151    source: super::binding::VectorSource,
152}
153
154impl IntegerValues {
155    /// Capture a complete integer column.
156    pub fn new(
157        name: impl Into<String>,
158        values: impl IntoIterator<Item = ExactInteger>,
159    ) -> Result<Self> {
160        Self::nullable(name, values.into_iter().map(Some))
161    }
162
163    /// Capture an integer column with missing entries independent of value.
164    pub fn nullable(
165        name: impl Into<String>,
166        values: impl IntoIterator<Item = Option<ExactInteger>>,
167    ) -> Result<Self> {
168        let values = super::source::collect_source(values.into_iter().map(Ok))?;
169        Ok(Self {
170            name: Arc::from(name.into()),
171            source: super::binding::VectorSource::direct_nullable(
172                values.len(),
173                values.iter().any(Option::is_none),
174            ),
175            values: values.into(),
176        })
177    }
178
179    /// Original captured source.
180    #[doc(hidden)]
181    pub fn get_source(&self) -> &super::DataSourceInfo {
182        self.source.info()
183    }
184
185    pub(crate) fn vector_source(&self) -> &super::binding::VectorSource {
186        &self.source
187    }
188
189    /// The semantic column name.
190    pub fn name(&self) -> &str {
191        &self.name
192    }
193    /// The number of original slots.
194    pub fn len(&self) -> usize {
195        self.values.len()
196    }
197    /// Whether the column has no slots.
198    pub fn is_empty(&self) -> bool {
199        self.values.is_empty()
200    }
201    /// Read one slot, retaining the distinction between missing and out of bounds.
202    pub fn get(&self, index: usize) -> Option<Option<&ExactInteger>> {
203        self.values.get(index).map(Option::as_ref)
204    }
205    /// Iterate the original integer slots.
206    pub fn iter(&self) -> impl ExactSizeIterator<Item = Option<&ExactInteger>> + '_ {
207        self.values.iter().map(Option::as_ref)
208    }
209    /// Query the actual validity of one slot.
210    pub fn is_valid(&self, index: usize) -> Option<bool> {
211        self.values.get(index).map(Option::is_some)
212    }
213}
214
215impl PartialEq for IntegerValues {
216    fn eq(&self, other: &Self) -> bool {
217        self.name == other.name && self.values == other.values
218    }
219}
220impl Eq for IntegerValues {}