Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 //! Cell allowing the inner value to be consumed without a mutable reference.
2 //!
3 //! In order to maintain safety, it is not possible to get a reference to the
4 //! inner value.
5
6 use std::fmt;
7 use std::cell::UnsafeCell;
8
9 /// Cell allowing the inner value to be consumed without a mutable reference.
10 pub struct Take<T> {
11 val: UnsafeCell<Option<T>>,
12 }
13
14 impl<T> Take<T> {
15 /// Create and return a new `Take` value containing the given inner value.
16 pub fn new(val: T) -> Take<T> {
17 Take { val: UnsafeCell::new(Some(val)) }
18 }
19
20 /// Consume and return the inner value.
21 ///
22 /// # Panics
23 ///
24 /// If the inner value has already been consumed, the call will panic.
25 pub fn take(&self) -> T {
26 unsafe { (*self.val.get()).take() }.expect("value already consumed")
27 }
28
29 // This function cannot be public as no public API functions should be able
30 // to return a reference to the inner value. It is only safe to grab this
31 // reference if `take` is not called while the reference is held.
32 fn inner(&self) -> &Option<T> {
33 unsafe { &*self.val.get() }
34 }
35 }
36
37 impl<T: fmt::Debug> fmt::Debug for Take<T> {
38 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
39 fmt.debug_struct("Take")
40 .field("val", self.inner())
41 .finish()
42 }
43 }