pipecircuit 0.0.2

Correct. Robust. Fast. Portable.
Documentation
use super::dense_key_index::FindOutcome;
use super::inconsistency::invariant_violation;
use super::{
    WarpTable, WarpTableInconsistency, WarpTableRow, WarpTableRowGetOutcome,
    WarpTableRowReplaceError, WarpTableRowReplaceOutcome,
};

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[must_use]
pub enum WarpTableReplaceOutcome<Key, Row> {
    Replaced { key: Key, row: usize, previous: Row },
    Absent { key: Key, rejected: Row },
}

impl<Row: WarpTableRow, Brand> WarpTable<Row, Brand> {
    pub fn replace(
        &mut self,
        key: Row::Key,
        replacement: Row,
    ) -> WarpTableReplaceOutcome<Row::Key, Row> {
        let found = {
            let keys = &self.primary_keys;
            if keys.len() != self.len {
                invariant_violation(WarpTableInconsistency::PrimaryKeyColumnLengthMismatch {
                    keys: keys.len(),
                    rows: self.len,
                });
            }
            self.primary_index.find(key, keys)
        };
        let row = match found {
            Ok(FindOutcome::Present { row, .. }) => row,
            Ok(FindOutcome::Absent) => {
                return WarpTableReplaceOutcome::Absent {
                    key,
                    rejected: replacement,
                };
            }
            Err(reason) => invariant_violation(WarpTableInconsistency::from(reason)),
        };
        let previous = self.replace_at(key, row, replacement);
        WarpTableReplaceOutcome::Replaced { key, row, previous }
    }

    pub(super) fn replace_at(&mut self, key: Row::Key, row: usize, replacement: Row) -> Row {
        let WarpTableRowGetOutcome::Present { row: current } = Row::get(&key, &self.columns, row)
            .unwrap_or_else(|reason| invariant_violation(WarpTableInconsistency::from(reason)));
        let indexes_replace =
            Row::try_prepare_indexes_replace(&mut self.indexes, current, &replacement, row)
                .unwrap_or_else(|reason| invariant_violation(reason));
        match Row::replace(&mut self.columns, row, replacement) {
            Ok(WarpTableRowReplaceOutcome::Replaced { previous }) => {
                Row::commit_indexes_replace(indexes_replace);
                previous
            }
            Err(WarpTableRowReplaceError::ColumnUnavailable { column, row, .. }) => {
                invariant_violation(WarpTableInconsistency::ColumnUnavailable { column, row })
            }
        }
    }
}