pipecircuit 0.0.11

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

use super::super::dense_key_index::{DenseKeyIndex, DenseKeyIndexCreationError};
use super::{IndexKey, UniqueIndex};

#[derive(Debug)]
pub enum UniqueIndexCreationError {
    CapacityOverflow { maximum_keys: usize },
    KeyStorageUnavailable { source: TryReserveError },
    IndexStorageUnavailable { source: TryReserveError },
}

impl<Key: IndexKey> UniqueIndex<Key> {
    pub fn try_new(maximum_keys: usize) -> Result<Self, UniqueIndexCreationError> {
        let key_index = DenseKeyIndex::try_new(maximum_keys).map_err(|reason| match reason {
            DenseKeyIndexCreationError::CapacityOverflow { maximum_rows } => {
                UniqueIndexCreationError::CapacityOverflow {
                    maximum_keys: maximum_rows,
                }
            }
            DenseKeyIndexCreationError::StorageUnavailable { source } => {
                UniqueIndexCreationError::IndexStorageUnavailable { source }
            }
        })?;
        let mut keys = Vec::new();
        keys.try_reserve_exact(maximum_keys)
            .map_err(|source| UniqueIndexCreationError::KeyStorageUnavailable { source })?;
        Ok(Self {
            maximum_keys,
            keys,
            key_index,
        })
    }
}