1use std::ops::{Deref, DerefMut};
2
3#[derive(Debug)]
4pub struct Unwrap<T> {
5 value: Option<T>,
6}
7
8impl<T> Unwrap<T> {
9 pub const fn const_default() -> Self {
10 Self { value: None }
11 }
12
13 pub fn new(val: T) -> Self {
14 Self { value: Some(val) }
15 }
16
17 pub fn is_none(&self) -> bool {
18 self.value.is_none()
19 }
20
21 pub fn set(&mut self, val: T) -> Option<T> {
22 let result = self.take();
23 self.value = Some(val);
24 result
25 }
26
27 pub fn take(&mut self) -> Option<T> {
28 self.value.take()
29 }
30}
31
32impl<T> Deref for Unwrap<T> {
33 type Target = T;
34 fn deref(&self) -> &T {
35 match self.value.as_ref() {
36 Some(rf) => rf,
37 None => {
38 panic!("Invalid Unwrap<{}>", std::any::type_name::<T>());
39 }
40 }
41 }
42}
43
44impl<T> DerefMut for Unwrap<T> {
45 fn deref_mut(&mut self) -> &mut T {
46 match self.value.as_mut() {
47 Some(rf) => rf,
48 None => {
49 panic!("Invalid Unwrap<{}>", std::any::type_name::<T>());
50 }
51 }
52 }
53}
54
55impl<T> From<T> for Unwrap<T> {
56 fn from(val: T) -> Self {
57 Self { value: val.into() }
58 }
59}
60
61impl<T> Default for Unwrap<T> {
62 fn default() -> Self {
63 Self { value: None }
64 }
65}
66
67#[cfg(test)]
68mod test {
69 use crate::Unwrap;
70
71 #[test]
72 fn unwrap() {
73 let val = Unwrap::from(5);
74 assert_eq!(5, *val);
75 dbg!(val);
76 let no = Unwrap::<u32>::default();
77 assert!(no.is_none());
78 }
79}