pipecircuit 0.0.5

Correct. Robust. Fast. Portable.
Documentation
use alloc::collections::TryReserveError;
use core::num::{NonZeroU32, TryFromIntError};

use super::dense_key_index::{DenseKeyIndex, DenseKeyIndexCreationError};
use super::{WarpTable, WarpTableRow};

crate::value_wrapper! {
    #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
    pub struct Capacity(NonZeroU32);
}

#[derive(Debug)]
pub enum WarpTableCreationError<ColumnsError, IndexesError> {
    CapacityUnrepresentable {
        capacity: Capacity,
        source: TryFromIntError,
    },
    ColumnsUnavailable {
        source: ColumnsError,
    },
    IndexesUnavailable {
        source: IndexesError,
    },
    IdStorageUnavailable {
        source: TryReserveError,
    },
    PrimaryIndexCapacityOverflow {
        maximum_rows: usize,
    },
    PrimaryIndexStorageUnavailable {
        source: TryReserveError,
    },
}

impl<Row: WarpTableRow, Brand> WarpTable<Row, Brand> {
    pub fn try_new(
        capacity: Capacity,
    ) -> Result<Self, WarpTableCreationError<Row::ColumnsCreationError, Row::IndexesCreationError>>
    {
        let maximum_rows = usize::try_from(capacity.value().get()).map_err(|source| {
            WarpTableCreationError::CapacityUnrepresentable { capacity, source }
        })?;
        let columns = Row::try_new_columns(maximum_rows)
            .map_err(|source| WarpTableCreationError::ColumnsUnavailable { source })?;
        let indexes = Row::try_new_indexes(maximum_rows)
            .map_err(|source| WarpTableCreationError::IndexesUnavailable { source })?;
        let mut ids = alloc::vec::Vec::new();
        ids.try_reserve_exact(maximum_rows)
            .map_err(|source| WarpTableCreationError::IdStorageUnavailable { source })?;
        let primary_index =
            DenseKeyIndex::try_new(maximum_rows).map_err(|reason| match reason {
                DenseKeyIndexCreationError::CapacityOverflow { maximum_rows } => {
                    WarpTableCreationError::PrimaryIndexCapacityOverflow { maximum_rows }
                }
                DenseKeyIndexCreationError::StorageUnavailable { source } => {
                    WarpTableCreationError::PrimaryIndexStorageUnavailable { source }
                }
            })?;
        Ok(Self {
            capacity,
            maximum_rows,
            len: 0,
            next_id: Some(core::num::NonZeroU64::MIN),
            ids,
            columns,
            indexes,
            primary_index,
            brand: core::marker::PhantomData,
        })
    }
}