lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Exact, owned integers and nullable integer columns.

use std::{cmp::Ordering, sync::Arc};

use crate::{Error, Result};

/// An arbitrary-precision integer with canonical sign and big-endian magnitude.
/// Scientific counts and externally supplied integer keys never pass through f64.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ExactInteger {
    negative: bool,
    magnitude: Arc<[u8]>,
}

impl ExactInteger {
    /// Construct from a sign and unsigned big-endian magnitude. Leading zeros
    /// are removed and zero always has a nonnegative sign.
    pub fn from_parts(negative: bool, magnitude_be: &[u8]) -> Result<Self> {
        let first = magnitude_be
            .iter()
            .position(|&byte| byte != 0)
            .unwrap_or(magnitude_be.len());
        let bytes = &magnitude_be[first..];
        let mut magnitude = Vec::new();
        magnitude
            .try_reserve_exact(bytes.len())
            .map_err(|error| Error::Data(format!("integer magnitude storage: {error}").into()))?;
        magnitude.extend_from_slice(bytes);
        Ok(Self {
            negative: negative && !magnitude.is_empty(),
            magnitude: magnitude.into(),
        })
    }

    /// Whether the represented integer is negative.
    pub const fn is_negative(&self) -> bool {
        self.negative
    }

    /// The canonical unsigned magnitude. Zero is the empty magnitude.
    pub fn magnitude_be(&self) -> &[u8] {
        &self.magnitude
    }

    fn magnitude_u128(&self) -> Option<u128> {
        let mut bytes = [0; 16];
        let offset = bytes.len().checked_sub(self.magnitude.len())?;
        bytes[offset..].copy_from_slice(&self.magnitude);
        Some(u128::from_be_bytes(bytes))
    }

    /// Read the exact unsigned value when it fits.
    pub fn to_u128(&self) -> Option<u128> {
        if self.negative {
            None
        } else {
            self.magnitude_u128()
        }
    }

    /// Read the exact signed value when it fits.
    pub fn to_i128(&self) -> Option<i128> {
        let magnitude = self.magnitude_u128()?;
        if self.negative {
            if magnitude == i128::MIN.unsigned_abs() {
                Some(i128::MIN)
            } else {
                i128::try_from(magnitude).ok().map(|value| -value)
            }
        } else {
            i128::try_from(magnitude).ok()
        }
    }

    /// Read the exact nonnegative index when it fits the host index type.
    pub fn to_usize(&self) -> Option<usize> {
        usize::try_from(self.to_u128()?).ok()
    }

    fn bounded(negative: bool, bytes: [u8; 16]) -> Self {
        let first = bytes
            .iter()
            .position(|&byte| byte != 0)
            .unwrap_or(bytes.len());
        Self {
            negative: negative && first != bytes.len(),
            magnitude: Arc::from(&bytes[first..]),
        }
    }
}

impl From<u128> for ExactInteger {
    fn from(value: u128) -> Self {
        Self::bounded(false, value.to_be_bytes())
    }
}

impl From<i128> for ExactInteger {
    fn from(value: i128) -> Self {
        Self::bounded(value < 0, value.unsigned_abs().to_be_bytes())
    }
}

macro_rules! integer_from {
    ($large:ty; $($ty:ty),+) => {$(
        impl From<$ty> for ExactInteger {
            fn from(value: $ty) -> Self { Self::from(<$large>::from(value)) }
        }
    )+};
}
integer_from!(i128; i8, i16, i32, i64);
integer_from!(u128; u8, u16, u32, u64);
impl From<usize> for ExactInteger {
    fn from(value: usize) -> Self {
        Self::from(value as u128)
    }
}
impl From<isize> for ExactInteger {
    fn from(value: isize) -> Self {
        Self::from(value as i128)
    }
}

impl Ord for ExactInteger {
    fn cmp(&self, other: &Self) -> Ordering {
        let magnitude = || {
            self.magnitude
                .len()
                .cmp(&other.magnitude.len())
                .then_with(|| self.magnitude.cmp(&other.magnitude))
        };
        match (self.negative, other.negative) {
            (true, false) => Ordering::Less,
            (false, true) => Ordering::Greater,
            (true, true) => magnitude().reverse(),
            (false, false) => magnitude(),
        }
    }
}
impl PartialOrd for ExactInteger {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// An owned named nullable column of exact integers.
#[derive(Debug, Clone)]
pub struct IntegerValues {
    name: Arc<str>,
    values: Arc<[Option<ExactInteger>]>,
    source: super::binding::VectorSource,
}

impl IntegerValues {
    /// Capture a complete integer column.
    pub fn new(
        name: impl Into<String>,
        values: impl IntoIterator<Item = ExactInteger>,
    ) -> Result<Self> {
        Self::nullable(name, values.into_iter().map(Some))
    }

    /// Capture an integer column with missing entries independent of value.
    pub fn nullable(
        name: impl Into<String>,
        values: impl IntoIterator<Item = Option<ExactInteger>>,
    ) -> Result<Self> {
        let values = super::source::collect_source(values.into_iter().map(Ok))?;
        Ok(Self {
            name: Arc::from(name.into()),
            source: super::binding::VectorSource::direct_nullable(
                values.len(),
                values.iter().any(Option::is_none),
            ),
            values: values.into(),
        })
    }

    /// Original captured source.
    #[doc(hidden)]
    pub fn get_source(&self) -> &super::DataSourceInfo {
        self.source.info()
    }

    pub(crate) fn vector_source(&self) -> &super::binding::VectorSource {
        &self.source
    }

    /// The semantic column name.
    pub fn name(&self) -> &str {
        &self.name
    }
    /// The number of original slots.
    pub fn len(&self) -> usize {
        self.values.len()
    }
    /// Whether the column has no slots.
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }
    /// Read one slot, retaining the distinction between missing and out of bounds.
    pub fn get(&self, index: usize) -> Option<Option<&ExactInteger>> {
        self.values.get(index).map(Option::as_ref)
    }
    /// Iterate the original integer slots.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = Option<&ExactInteger>> + '_ {
        self.values.iter().map(Option::as_ref)
    }
    /// Query the actual validity of one slot.
    pub fn is_valid(&self, index: usize) -> Option<bool> {
        self.values.get(index).map(Option::is_some)
    }
}

impl PartialEq for IntegerValues {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name && self.values == other.values
    }
}
impl Eq for IntegerValues {}