zachs18_stdx/
option.rs

1mod sealed {
2    pub trait Sealed {}
3}
4pub trait OptionExt: Sized + sealed::Sealed {
5    type T;
6    fn is_none_or(self, f: impl FnOnce(Self::T) -> bool) -> bool;
7    fn contains<U>(&self, u: &U) -> bool
8    where
9        Self::T: PartialEq<U>;
10    fn unwrap_none(self)
11    where
12        Self::T: core::fmt::Debug;
13    fn expect_none(self, msg: &str)
14    where
15        Self::T: core::fmt::Debug;
16}
17
18impl<T> sealed::Sealed for Option<T> {}
19
20impl<T> OptionExt for Option<T> {
21    type T = T;
22
23    #[inline]
24    fn is_none_or(self, f: impl FnOnce(Self::T) -> bool) -> bool {
25        match self {
26            Some(value) => f(value),
27            None => true,
28        }
29    }
30
31    #[inline]
32    fn contains<U>(&self, u: &U) -> bool
33    where
34        Self::T: PartialEq<U>,
35    {
36        self.as_ref().is_some_and(|this| *this == *u)
37    }
38
39    #[inline]
40    fn unwrap_none(self)
41    where
42        Self::T: core::fmt::Debug
43    {
44        if let Some(ref value) = self {
45            expect_none_failed("called `Option::unwrap_none` on a `Some` value", value);
46        }
47    }
48
49    #[inline]
50    fn expect_none(self, msg: &str)
51    where
52        Self::T: core::fmt::Debug
53    {
54        if let Some(ref value) = self {
55            expect_none_failed(msg, value);
56        }
57    }
58}
59
60// https://github.com/rust-lang/rust/pull/62596
61#[inline(never)]
62#[cold]
63fn expect_none_failed(msg: &str, value: &dyn core::fmt::Debug) -> ! {
64    panic!("{msg}: {value:?}");
65}