tuwunel_core/utils/result/not_found.rs
1use super::Result;
2use crate::Error;
3
4/// Classifies and adapts results carrying the crate's not-found error family.
5///
6/// Successful results and unrelated errors are not classified as missing, and
7/// only a not-found error converts to an absent value. Classification
8/// delegates to `Error::is_not_found`.
9pub trait NotFound<T> {
10 /// Reports whether the result contains a not-found error.
11 ///
12 /// An `Ok` value always returns false. Other error variants also return
13 /// false without changing the result.
14 #[must_use]
15 fn is_not_found(&self) -> bool;
16
17 /// Converts a not-found error into an absent value.
18 ///
19 /// An `Ok` value is wrapped in `Some` and a not-found error becomes
20 /// `Ok(None)`, so a caller distinguishes an absent value from a failed
21 /// operation. Every other error is returned unchanged.
22 fn optional(self) -> Result<Option<T>>;
23}
24
25impl<T> NotFound<T> for Result<T, Error> {
26 #[inline]
27 fn is_not_found(&self) -> bool { self.as_ref().is_err_and(Error::is_not_found) }
28
29 #[inline]
30 fn optional(self) -> Result<Option<T>> {
31 self.map(Some)
32 .or_else(|error| error.is_not_found().then_some(None).ok_or(error))
33 }
34}