const_panic/macros/
unwrapping.rs

1/// Gets the value in the `Some` variant.
2///
3/// # Panics
4///
5/// Panics if `$opt` is a None.
6///
7/// # Example
8///
9/// ```rust
10/// use const_panic::unwrap_some;
11///
12/// const SUM: u8 = unwrap_some!(add_up(&[3, 5, 8, 13]));
13///
14/// assert_eq!(SUM, 29);
15///
16///
17/// const fn add_up(mut slice: &[u8]) -> Option<u8> {
18///     let mut sum = 0u8;
19///     
20///     while let [x, ref rem @ ..] = *slice {
21///         match sum.checked_add(x) {
22///             Some(x) => sum = x,
23///             None => return None,
24///         }
25///         slice = rem;
26///     }
27///     
28///     Some(sum)
29/// }
30///
31/// ```
32///
33///
34/// ### Error
35///
36/// This is what the compile-time error looks like when attempting to unwrap a `None`:
37///
38/// ```text
39/// error[E0080]: evaluation of constant value failed
40///  --> src/macros/unwrapping.rs:10:17
41///   |
42/// 6 | const SUM: u8 = unwrap_some!(add_up(&[3, 5, 8, 13, 250]));
43///   |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the evaluated program panicked at '
44/// invoked `unwrap_some` macro with a `None` value', src/macros/unwrapping.rs:6:17
45///   |
46///   = note: this error originates in the macro `unwrap_some` (in Nightly builds, run with -Z macro-backtrace for more info)
47///
48/// ```
49///
50#[macro_export]
51macro_rules! unwrap_some {
52    ($opt:expr) => {
53        match $opt {
54            $crate::__::Some(x) => x,
55            $crate::__::None => $crate::concat_panic(&[&[$crate::PanicVal::write_str(
56                "\ninvoked `unwrap_some` macro with a `None` value",
57            )]]),
58        }
59    };
60}
61
62/// Gets the value in the `Ok` variant.
63///
64/// # Panics
65///
66/// This panics if `$res` is an `Err`, including the debug-formatted error in the panic message.
67///
68/// # Example
69///
70/// The struct formatting below requires the `"non_basic"` feature (enabled by default)
71///
72#[cfg_attr(feature = "non_basic", doc = "```rust")]
73#[cfg_attr(not(feature = "non_basic"), doc = "```ignore")]
74/// use const_panic::unwrap_ok;
75///
76/// const SUM: u64 = unwrap_ok!(add_up_evens(&[2, 4, 8, 16]));
77///
78/// assert_eq!(SUM, 30);
79///
80/// const fn add_up_evens(slice: &[u8]) -> Result<u64, OddError> {
81///     let mut sum = 0u64;
82///     let mut i = 0;
83///
84///     while i < slice.len() {
85///         let x = slice[i];
86///
87///         if x % 2 == 1 {
88///             return Err(OddError{at: i, number: x});
89///         }
90///
91///         sum += x as u64;
92///         i += 1;
93///     }
94///     
95///     Ok(sum)
96/// }
97///
98///
99/// struct OddError {
100///     at: usize,
101///     number: u8,
102/// }
103///
104/// // You can also use `#[derive(PanicFmt))]` with the "derive" feature
105/// const_panic::impl_panicfmt!{
106///     struct OddError {
107///         at: usize,
108///         number: u8,
109///     }
110/// }
111///
112/// ```
113///
114/// ### Error
115///
116/// This is what the compile-time error looks like when attempting to unwrap an `Err`:
117///
118/// ```text
119/// error[E0080]: evaluation of constant value failed
120///  --> src/macros/unwrapping.rs:51:18
121///   |
122/// 6 | const SUM: u64 = unwrap_ok!(add_up_evens(&[3, 5, 8, 13]));
123///   |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the evaluated program panicked at '
124/// invoked `unwrap_ok` macro with an `Err` value: OddError { at: 0, number: 3 }', src/macros/unwrapping.rs:6:18
125///   |
126/// ```
127#[macro_export]
128macro_rules! unwrap_ok {
129    ($res:expr) => {
130        match $res {
131            $crate::__::Ok(x) => x,
132            $crate::__::Err(e) => $crate::concat_panic(&[
133                &[$crate::PanicVal::write_str(
134                    "\ninvoked `unwrap_ok` macro with an `Err` value: ",
135                )],
136                &$crate::coerce_fmt!(e).to_panicvals($crate::FmtArg::DEBUG),
137            ]),
138        }
139    };
140}
141
142/// Gets the value in the `Err` variant.
143///
144/// # Panics
145///
146/// This panics if `$res` is an `Ok`, including the debug-formatted value in the panic message.
147///
148/// # Example
149///
150/// ```rust
151/// use const_panic::unwrap_err;
152///
153/// type Res = Result<u32, &'static str>;
154///
155/// const ERR: &str = unwrap_err!(Res::Err("this is an error"));
156///
157/// assert_eq!(ERR, "this is an error");
158///
159/// ```
160///
161/// ### Error
162///
163/// This is what the compile-time error looks like when attempting to unwrap an `Ok`:
164///
165/// ```text
166/// error[E0080]: evaluation of constant value failed
167///  --> src/macros/unwrapping.rs:174:19
168///   |
169/// 8 | const ERR: &str = unwrap_err!(Res::Ok(1234));
170///   |                   ^^^^^^^^^^^^^^^^^^^^^^^^^^ the evaluated program panicked at '
171/// invoked `unwrap_err` macro with an `Ok` value: 1234', src/macros/unwrapping.rs:8:19
172///   |
173/// ```
174#[macro_export]
175macro_rules! unwrap_err {
176    ($res:expr) => {
177        match $res {
178            $crate::__::Ok(x) => $crate::concat_panic(&[
179                &[$crate::PanicVal::write_str(
180                    "\ninvoked `unwrap_err` macro with an `Ok` value: ",
181                )],
182                &$crate::coerce_fmt!(x).to_panicvals($crate::FmtArg::DEBUG),
183            ]),
184            $crate::__::Err(e) => e,
185        }
186    };
187}