nstd_sys/core/
result.rs

1//! Defines a "result" type with success and error variants.
2use crate::NSTDUInt8;
3use nstdapi::nstdapi;
4
5/// Describes an erroneous `NSTDResult` value.
6pub const NSTD_RESULT_ERR: NSTDUInt8 = 0;
7/// Describes a successful `NSTDResult` value.
8pub const NSTD_RESULT_OK: NSTDUInt8 = 1;
9
10/// Defines a "result" type with success and error variants.
11#[nstdapi]
12#[repr(u8)]
13#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
14pub enum NSTDResult<T, E> {
15    /// The error variant.
16    Err(E),
17    /// The success variant.
18    Ok(T),
19}
20impl<T, E> NSTDResult<T, E> {
21    /// Attempts to return the contained `Ok` value in an `NSTDResult`.
22    ///
23    /// This operation is only useful for testing code, it's use in production should be
24    /// discouraged.
25    ///
26    /// # Panics
27    ///
28    /// Panics if `self` is an `Err` value.
29    #[inline]
30    pub fn unwrap(self) -> T {
31        match self {
32            Self::Ok(value) => value,
33            Self::Err(_) => panic!("called `NSTDResult::unwrap()` on an `Err` value"),
34        }
35    }
36
37    /// Attempts to return the contained `Ok` value in an `NSTDResult`.
38    ///
39    /// # Panics
40    ///
41    /// Panics with `msg` if `self` is an `Err` value.
42    #[inline]
43    pub fn expect(self, msg: &str) -> T {
44        match self {
45            Self::Ok(value) => value,
46            Self::Err(_) => panic!("{msg}"),
47        }
48    }
49}