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 not found, and
7/// only a not-found error converts to an absent value. Classification
8/// delegates to `Error::is_not_found`, or to the narrower `Error::is_missing`
9/// for the forms that must not read a storage fault as absence.
10pub trait NotFound<T> {
11 /// Reports whether the result contains a not-found error.
12 ///
13 /// An `Ok` value always returns false. Other error variants also return
14 /// false without changing the result.
15 #[must_use]
16 fn is_not_found(&self) -> bool;
17
18 /// Converts a not-found error into an absent value.
19 ///
20 /// An `Ok` value is wrapped in `Some` and a not-found error becomes
21 /// `Ok(None)`, so a caller distinguishes an absent value from a failed
22 /// operation. Every other error is returned unchanged.
23 fn optional(self) -> Result<Option<T>>;
24
25 /// Reports whether the result contains a missing-record error.
26 ///
27 /// Unlike `is_not_found`, an I/O not-found or any other error mapping to
28 /// 404 returns false.
29 #[must_use]
30 fn is_missing(&self) -> bool;
31
32 /// Converts only a missing-record error into an absent value.
33 ///
34 /// Like `optional`, but an I/O not-found and any other error mapping to
35 /// 404 are returned unchanged, so a storage fault never reads as absence.
36 fn present(self) -> Result<Option<T>>;
37}
38
39impl<T> NotFound<T> for Result<T, Error> {
40 #[inline]
41 fn is_not_found(&self) -> bool { self.as_ref().is_err_and(Error::is_not_found) }
42
43 #[inline]
44 fn optional(self) -> Result<Option<T>> { none_if(self, Error::is_not_found) }
45
46 #[inline]
47 fn is_missing(&self) -> bool { self.as_ref().is_err_and(Error::is_missing) }
48
49 #[inline]
50 fn present(self) -> Result<Option<T>> { none_if(self, Error::is_missing) }
51}
52
53#[inline]
54fn none_if<T>(result: Result<T>, absent: fn(&Error) -> bool) -> Result<Option<T>> {
55 result
56 .map(Some)
57 .or_else(|error| absent(&error).then_some(None).ok_or(error))
58}