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
use compact::Compact;
use std::cell::Cell;
pub struct External<T> {
maybe_owned: Cell<Option<Box<T>>>,
}
impl<T> External<T> {
pub fn new(content: T) -> Self {
External {
maybe_owned: Cell::new(Some(Box::new(content))),
}
}
pub fn from_box(content: Box<T>) -> Self {
External {
maybe_owned: Cell::new(Some(content)),
}
}
pub fn steal(&self) -> Self {
self.clone()
}
pub fn into_box(self) -> Box<T> {
self.maybe_owned
.into_inner()
.expect("Tried to get Box from already taken external")
}
}
impl<T> Clone for External<T> {
fn clone(&self) -> Self {
External {
maybe_owned: Cell::new(Some(
self.maybe_owned
.take()
.expect("Tried to clone already taken external"),
)),
}
}
}
impl<T> ::std::ops::Deref for External<T> {
type Target = T;
fn deref(&self) -> &T {
let option_ref = unsafe { &(*self.maybe_owned.as_ptr()) };
&**option_ref
.as_ref()
.expect("Tried to deref already taken external")
}
}
impl<T> ::std::ops::DerefMut for External<T> {
fn deref_mut(&mut self) -> &mut T {
&mut *self
.maybe_owned
.get_mut()
.as_mut()
.expect("Tried to mut deref already taken external")
}
}
impl<T> Compact for External<T> {
fn is_still_compact(&self) -> bool {
true
}
fn dynamic_size_bytes(&self) -> usize {
0
}
unsafe fn compact(source: *mut Self, dest: *mut Self, _new_dynamic_part: *mut u8) {
::std::ptr::copy_nonoverlapping(source, dest, 1)
}
unsafe fn decompact(source: *const Self) -> Self {
::std::ptr::read(source)
}
}