pipecircuit 0.0.14

Correct. Robust. Fast. Portable.
Documentation
use alloc::{collections::TryReserveError, vec::Vec};

use super::SecondaryIndex;
use crate::storage::warp_table::IndexKey;
use crate::storage::warp_table::dense_key_index::{DenseKeyIndex, DenseKeyIndexCreationError};

#[derive(Debug)]
pub enum SecondaryIndexCreationError {
    SecondaryKeyStorageUnavailable { source: TryReserveError },
    SlotSetStorageUnavailable { source: TryReserveError },
    SecondaryKeyIndexCapacityOverflow { maximum_distinct_keys: usize },
    SecondaryKeyIndexStorageUnavailable { source: TryReserveError },
}

impl<SecondaryKey: IndexKey> SecondaryIndex<SecondaryKey> {
    pub fn try_new(maximum_distinct_keys: usize) -> Result<Self, SecondaryIndexCreationError> {
        let mut secondary_keys = Vec::new();
        secondary_keys
            .try_reserve_exact(maximum_distinct_keys)
            .map_err(
                |source| SecondaryIndexCreationError::SecondaryKeyStorageUnavailable { source },
            )?;
        let mut slot_sets = Vec::new();
        slot_sets
            .try_reserve_exact(maximum_distinct_keys)
            .map_err(|source| SecondaryIndexCreationError::SlotSetStorageUnavailable { source })?;
        let secondary_key_index =
            DenseKeyIndex::try_new(maximum_distinct_keys).map_err(|reason| match reason {
                DenseKeyIndexCreationError::CapacityOverflow { maximum_rows } => {
                    SecondaryIndexCreationError::SecondaryKeyIndexCapacityOverflow {
                        maximum_distinct_keys: maximum_rows,
                    }
                }
                DenseKeyIndexCreationError::StorageUnavailable { source } => {
                    SecondaryIndexCreationError::SecondaryKeyIndexStorageUnavailable { source }
                }
            })?;
        Ok(Self {
            maximum_distinct_keys,
            secondary_keys,
            slot_sets,
            secondary_key_index,
        })
    }
}