Skip to main content

facet_reflect/peek/
result.rs

1use facet_core::{ResultDef, ResultVTable};
2
3/// Lets you read from a result (implements read-only result operations)
4#[derive(Clone, Copy)]
5pub struct PeekResult<'mem, 'facet> {
6    /// the underlying value
7    pub(crate) value: crate::Peek<'mem, 'facet>,
8
9    /// the definition of the result
10    pub(crate) def: ResultDef,
11}
12
13impl<'mem, 'facet> PeekResult<'mem, 'facet> {
14    /// Returns the result definition
15    #[inline(always)]
16    pub const fn def(self) -> ResultDef {
17        self.def
18    }
19
20    /// Returns the result vtable
21    #[inline(always)]
22    pub const fn vtable(self) -> &'static ResultVTable {
23        self.def.vtable
24    }
25
26    /// Returns whether the result is Ok
27    #[inline]
28    pub fn is_ok(self) -> bool {
29        unsafe { (self.vtable().is_ok)(self.value.data()) }
30    }
31
32    /// Returns whether the result is Err
33    #[inline]
34    pub fn is_err(self) -> bool {
35        !self.is_ok()
36    }
37
38    /// Returns the Ok value as a Peek if the result is Ok, None otherwise
39    #[inline]
40    pub fn ok(self) -> Option<crate::Peek<'mem, 'facet>> {
41        unsafe {
42            let inner_data = (self.vtable().get_ok)(self.value.data());
43            if inner_data.is_null() {
44                None
45            } else {
46                Some(crate::Peek::unchecked_new(
47                    facet_core::PtrConst::new_sized(inner_data),
48                    self.def.t(),
49                ))
50            }
51        }
52    }
53
54    /// Returns the Err value as a Peek if the result is Err, None otherwise
55    #[inline]
56    pub fn err(self) -> Option<crate::Peek<'mem, 'facet>> {
57        unsafe {
58            let inner_data = (self.vtable().get_err)(self.value.data());
59            if inner_data.is_null() {
60                None
61            } else {
62                Some(crate::Peek::unchecked_new(
63                    facet_core::PtrConst::new_sized(inner_data),
64                    self.def.e(),
65                ))
66            }
67        }
68    }
69}