const_str/__ctfe/
unwrap.rs1pub struct Unwrap<T>(pub T);
2
3impl<T: Copy> Unwrap<Option<T>> {
4 pub const fn const_eval(self) -> T {
5 match self.0 {
6 Some(x) => x,
7 None => panic!("called `Option::unwrap()` on a `None` value"),
8 }
9 }
10}
11
12#[macro_export]
21macro_rules! unwrap {
22 ($expr: expr) => {{
23 $crate::__ctfe::Unwrap($expr).const_eval()
24 }};
25}
26
27#[cfg(test)]
28mod tests {
29 use super::*;
30
31 #[test]
32 fn test_unwrap_some() {
33 const X: Option<i32> = Some(42);
34 const Y: i32 = unwrap!(X);
35 assert_eq!(Y, 42);
36
37 const S: Option<&str> = Some("hello");
38 const T: &str = unwrap!(S);
39 assert_eq!(T, "hello");
40
41 let b: Option<bool> = Some(true);
42 let c: bool = unwrap!(b);
43 assert!(c);
44 }
45
46 #[test]
47 fn test_unwrap_runtime() {
48 let unwrap_some = Unwrap(Some(42));
50 assert_eq!(unwrap_some.const_eval(), 42);
51
52 let unwrap_str = Unwrap(Some("test"));
53 assert_eq!(unwrap_str.const_eval(), "test");
54
55 let unwrap_bool = Unwrap(Some(false));
56 assert!(!unwrap_bool.const_eval());
57 }
58}