Skip to main content

arena_lib/
error.rs

1//! Error type and result alias used across the crate.
2//!
3//! `arena-lib` exposes a single [`Error`] enum so callers can match on every
4//! failure mode without juggling per-module error types. New variants may be
5//! introduced in minor releases — match using `_ =>` to stay forward-compatible.
6
7use core::fmt;
8
9/// Failure modes returned by the public APIs of `arena-lib`.
10///
11/// The enum is `#[non_exhaustive]`: callers must include a wildcard arm when
12/// matching so future variants can be added in minor releases without
13/// breaking source compatibility.
14#[non_exhaustive]
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum Error {
17    /// The provided index does not point to a live element.
18    ///
19    /// Returned when an [`Index`](crate::Index) is used after its slot has
20    /// been removed and either left vacant or re-issued under a new
21    /// generation, or when the index was never live in this arena.
22    StaleIndex,
23
24    /// An allocation request exceeded the allocator's available capacity.
25    ///
26    /// Returned by [`Bump::try_alloc`](crate::bump::Bump::try_alloc) and
27    /// related fallible allocation entry points when the underlying buffer
28    /// could not be grown to satisfy the request.
29    CapacityExceeded,
30
31    /// A monotonic counter would have wrapped past its representable range.
32    ///
33    /// Returned by [`Arena::insert`](crate::arena::Arena::insert) and the
34    /// interner when generation or symbol counters reach their upper bound.
35    /// Treat this as a permanent failure: drop the affected container and
36    /// build a new one.
37    CounterOverflow,
38}
39
40impl fmt::Display for Error {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        match self {
43            Self::StaleIndex => f.write_str("stale index: handle does not refer to a live element"),
44            Self::CapacityExceeded => f.write_str("capacity exceeded: allocator could not grow"),
45            Self::CounterOverflow => {
46                f.write_str("counter overflow: generation or symbol counter exhausted")
47            }
48        }
49    }
50}
51
52#[cfg(feature = "std")]
53impl std::error::Error for Error {}
54
55/// Result alias that uses [`Error`] as the failure type.
56///
57/// # Examples
58///
59/// ```
60/// use arena_lib::{Error, Result};
61///
62/// fn checked() -> Result<u32> {
63///     Err(Error::StaleIndex)
64/// }
65///
66/// assert!(checked().is_err());
67/// ```
68pub type Result<T> = core::result::Result<T, Error>;