Skip to main content

subms_hyperloglog/
error.rs

1//! Typed error surface.
2//!
3//! Merge and the wire codec both fail for reasons a caller can act on - a
4//! precision mismatch is a config bug, a truncated buffer is a transport bug -
5//! so the failure names itself instead of returning a string.
6
7use core::fmt;
8
9/// Every failure `subms-hyperloglog` can return.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11#[non_exhaustive]
12pub enum HllError {
13    /// Two sketches at different precisions cannot be reconciled: the register
14    /// index is cut from a different slice of the hash.
15    PrecisionMismatch { left: u32, right: u32 },
16    /// Precision outside the calibrated `[4, 18]` range.
17    InvalidPrecision(u32),
18    /// Buffer does not start with the `SHLL` magic.
19    BadMagic,
20    /// Format version this build does not understand.
21    UnsupportedVersion(u8),
22    /// Encoding byte this build does not understand, or one the target type
23    /// refuses (a sparse buffer handed to `HyperLogLog::from_bytes`).
24    UnsupportedEncoding(u8),
25    /// Buffer ended before the declared payload did.
26    Truncated { expected: usize, actual: usize },
27}
28
29impl fmt::Display for HllError {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        match self {
32            HllError::PrecisionMismatch { left, right } => {
33                write!(f, "precision mismatch: {left} vs {right}")
34            }
35            HllError::InvalidPrecision(p) => write!(f, "precision {p} outside [4, 18]"),
36            HllError::BadMagic => write!(f, "bad magic: not a subms-hyperloglog buffer"),
37            HllError::UnsupportedVersion(v) => write!(f, "unsupported format version {v}"),
38            HllError::UnsupportedEncoding(e) => write!(f, "unsupported encoding {e}"),
39            HllError::Truncated { expected, actual } => {
40                write!(
41                    f,
42                    "truncated buffer: expected {expected} bytes, got {actual}"
43                )
44            }
45        }
46    }
47}
48
49impl std::error::Error for HllError {}
50
51#[cfg(test)]
52#[path = "error_tests.rs"]
53mod tests;