1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#![no_std]
#![deny(missing_docs, unsafe_code,
missing_debug_implementations, missing_copy_implementations,
unstable_features, unused_import_braces, unused_qualifications)]
use core::ops::{Deref, DerefMut};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Default)]
pub struct Takeable<T> {
value: Option<T>,
}
impl<T> Takeable<T> {
#[inline(always)]
pub fn new(value: T) -> Takeable<T> {
Takeable { value: Some(value) }
}
#[inline(always)]
pub fn as_ref(&self) -> &T {
self.value.as_ref().expect(
"Takeable is not usable after a panic occurred in borrow or borrow_result",
)
}
#[inline(always)]
pub fn as_mut(&mut self) -> &mut T {
self.value.as_mut().expect(
"Takeable is not usable after a panic occurred in borrow or borrow_result",
)
}
#[inline(always)]
pub fn into_inner(self) -> T {
self.value.expect(
"Takeable is not usable after a panic occurred in borrow or borrow_result",
)
}
#[inline(always)]
pub fn borrow<F>(&mut self, f: F)
where
F: FnOnce(T) -> T,
{
self.borrow_result(|v| (f(v), ()))
}
#[inline(always)]
pub fn borrow_result<F, R>(&mut self, f: F) -> R
where
F: FnOnce(T) -> (T, R),
{
let old = self.value.take().expect(
"Takeable is not usable after a panic occurred in borrow or borrow_result",
);
let (new, result) = f(old);
self.value = Some(new);
result
}
#[inline(always)]
pub fn is_usable(&self) -> bool {
self.value.is_some()
}
}
impl<T> Deref for Takeable<T> {
type Target = T;
#[inline(always)]
fn deref(&self) -> &T {
self.as_ref()
}
}
impl<T> DerefMut for Takeable<T> {
#[inline(always)]
fn deref_mut(&mut self) -> &mut T {
self.as_mut()
}
}
#[cfg(test)]
mod tests {
use super::Takeable;
#[test]
fn test_takeable() {
let mut takeable = Takeable::new(42u32);
*takeable += 1;
assert_eq!(*takeable, 43);
*takeable.as_mut() += 1;
assert_eq!(takeable.as_ref(), &44);
takeable.borrow(|n: u32| n + 1);
assert_eq!(*takeable, 45);
let out = takeable.borrow_result(|n: u32| (n + 1, n));
assert_eq!(out, 45);
assert_eq!(takeable.into_inner(), 46);
}
#[test]
#[should_panic]
fn test_usable() {
struct MyDrop {
value: Takeable<()>,
should_be_usable: bool,
};
impl Drop for MyDrop {
fn drop(&mut self) {
assert_eq!(self.value.is_usable(), self.should_be_usable);
}
}
let _drop1 = MyDrop {
value: Takeable::new(()),
should_be_usable: true,
};
let mut drop2 = MyDrop {
value: Takeable::new(()),
should_be_usable: false,
};
drop2.value.borrow(|_| panic!());
}
}