Skip to main content

turboquant/
error.rs

1use thiserror::Error;
2
3/// Errors that can occur during TurboQuant operations.
4#[derive(Debug, Error)]
5pub enum TurboQuantError {
6    /// The vector dimension is not a power of two, which is required for WHT.
7    #[error("dimension {0} is not a power of two")]
8    InvalidDimension(usize),
9
10    /// The bit width is not supported (must be 2, 3, or 4).
11    #[error("unsupported bit width {0}, expected 2, 3, or 4")]
12    UnsupportedBits(u8),
13
14    /// The input vector length does not match the configured dimension.
15    #[error("expected vector of length {expected}, got {actual}")]
16    DimensionMismatch { expected: usize, actual: usize },
17
18    /// A layer index is out of range.
19    #[error("layer index {index} out of range (num_layers = {num_layers})")]
20    LayerOutOfRange { index: usize, num_layers: usize },
21
22    /// A range is out of bounds for the entry count.
23    #[error("range [{start}..{end}) out of bounds for entry_count = {entry_count}")]
24    RangeOutOfBounds {
25        start: usize,
26        end: usize,
27        entry_count: usize,
28    },
29}
30
31/// Result type alias for TurboQuant operations.
32pub type Result<T> = std::result::Result<T, TurboQuantError>;
33
34/// Maps a boolean condition to a Result, returning the given error when false.
35///
36/// Pure Operation: if/else only, no project function calls.
37pub fn require(condition: bool, error: TurboQuantError) -> Result<()> {
38    if condition {
39        Ok(())
40    } else {
41        Err(error)
42    }
43}
44
45// ---------------------------------------------------------------------------
46// Shared validation primitives
47// ---------------------------------------------------------------------------
48
49/// Checks whether two values are equal.
50///
51/// Pure Operation: comparison only.
52pub(crate) fn values_match(a: usize, b: usize) -> bool {
53    a == b
54}
55
56/// Validates that `actual` matches `expected`, returning a
57/// [`TurboQuantError::DimensionMismatch`] on failure.
58///
59/// Pure Integration: only calls `require` and `values_match`.
60pub(crate) fn check_values_match(actual: usize, expected: usize) -> Result<()> {
61    require(
62        values_match(actual, expected),
63        TurboQuantError::DimensionMismatch { expected, actual },
64    )
65}