-
Notifications
You must be signed in to change notification settings - Fork 241
/
Copy paththin_box.rs
288 lines (257 loc) · 8.37 KB
/
thin_box.rs
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under both the MIT license found in the
* LICENSE-MIT file in the root directory of this source tree and the Apache
* License, Version 2.0 found in the LICENSE-APACHE file in the root directory
* of this source tree.
*/
use std::alloc;
use std::alloc::Layout;
use std::fmt::Debug;
use std::hash::Hash;
use std::hash::Hasher;
use std::mem;
use std::mem::MaybeUninit;
use std::ops::Deref;
use std::ops::DerefMut;
use std::ptr;
use std::ptr::NonNull;
use std::slice;
use allocative::Allocative;
#[repr(C)]
struct ThinBoxSliceLayout<T> {
len: usize,
data: [T; 0],
}
impl<T> ThinBoxSliceLayout<T> {
fn offset_of_data() -> usize {
mem::offset_of!(ThinBoxSliceLayout::<T>, data)
}
}
/// `Box<[T]>` but thin pointer.
///
/// Statically allocated for empty slice.
// We don't really need `'static` here, but we hit type checker limitations.
pub struct ThinBoxSlice<T: 'static> {
/// Pointer to the first element, `ThinBoxSliceLayout.data`.
ptr: NonNull<T>,
}
unsafe impl<T: Sync> Sync for ThinBoxSlice<T> {}
unsafe impl<T: Send> Send for ThinBoxSlice<T> {}
impl<T: 'static> ThinBoxSlice<T> {
#[inline]
pub const fn empty() -> ThinBoxSlice<T> {
const fn instance<T>() -> &'static ThinBoxSliceLayout<T> {
&ThinBoxSliceLayout::<T> { len: 0, data: [] }
}
unsafe {
ThinBoxSlice {
ptr: NonNull::new_unchecked(instance::<T>().data.as_ptr() as *mut T),
}
}
}
/// Allocation layout for a slice of length `len`.
#[inline]
fn layout_for_len(len: usize) -> Layout {
let (layout, _offset_of_data) = Layout::new::<ThinBoxSliceLayout<T>>()
.extend(Layout::array::<T>(len).unwrap())
.unwrap();
layout
}
/// Length of the slice.
// Not called `len` to avoid overload with `Deref::len`.
#[inline]
fn read_len(&self) -> usize {
unsafe {
(*self
.ptr
.as_ptr()
.cast::<u8>()
.sub(ThinBoxSliceLayout::<T>::offset_of_data())
.cast::<ThinBoxSliceLayout<T>>())
.len
}
}
/// Allocate uninitialized memory for a slice of length `len`.
#[inline]
pub fn new_uninit(len: usize) -> ThinBoxSlice<MaybeUninit<T>> {
if len == 0 {
ThinBoxSlice::empty()
} else {
let layout = Self::layout_for_len(len);
unsafe {
let alloc = alloc::alloc(layout);
if alloc.is_null() {
alloc::handle_alloc_error(layout);
}
ptr::write(alloc as *mut usize, len);
let ptr = alloc.add(mem::size_of::<usize>()) as *mut MaybeUninit<T>;
let ptr = NonNull::new_unchecked(ptr);
ThinBoxSlice { ptr }
}
}
}
#[inline]
pub fn new<const N: usize>(data: [T; N]) -> ThinBoxSlice<T> {
ThinBoxSlice::from_iter(data)
}
}
impl<T: 'static> Deref for ThinBoxSlice<T> {
type Target = [T];
#[inline]
fn deref(&self) -> &Self::Target {
unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.read_len()) }
}
}
impl<T: 'static> DerefMut for ThinBoxSlice<T> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { slice::from_raw_parts_mut(self.ptr.as_ptr(), self.read_len()) }
}
}
impl<T> ThinBoxSlice<MaybeUninit<T>> {
#[inline]
pub unsafe fn assume_init(self) -> ThinBoxSlice<T> {
let result = ThinBoxSlice {
ptr: self.ptr.cast::<T>(),
};
mem::forget(self);
result
}
}
impl<T: 'static> Drop for ThinBoxSlice<T> {
#[inline]
fn drop(&mut self) {
unsafe {
let len = self.read_len();
if len != 0 {
let slice = ptr::slice_from_raw_parts_mut(self.ptr.as_ptr(), len);
ptr::drop_in_place(slice);
let alloc = self.ptr.cast::<usize>().as_ptr().sub(1);
alloc::dealloc(alloc as *mut u8, Self::layout_for_len(len));
}
}
}
}
impl<T: 'static> Default for ThinBoxSlice<T> {
#[inline]
fn default() -> Self {
ThinBoxSlice::empty()
}
}
impl<T: Debug> Debug for ThinBoxSlice<T> {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
<[T] as Debug>::fmt(&**self, f)
}
}
impl<T: PartialEq> PartialEq for ThinBoxSlice<T> {
#[inline]
fn eq(&self, other: &Self) -> bool {
<[T] as PartialEq>::eq(&**self, &**other)
}
}
impl<T: Eq> Eq for ThinBoxSlice<T> {}
impl<T: PartialOrd> PartialOrd for ThinBoxSlice<T> {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
<[T] as PartialOrd>::partial_cmp(&**self, &**other)
}
}
impl<T: Ord> Ord for ThinBoxSlice<T> {
#[inline]
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
<[T] as Ord>::cmp(&**self, &**other)
}
}
impl<T: Hash> Hash for ThinBoxSlice<T> {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
<[T] as Hash>::hash(&**self, state)
}
}
impl<T> FromIterator<T> for ThinBoxSlice<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let iter = iter.into_iter();
let (lower, upper) = iter.size_hint();
if Some(lower) == upper {
let mut thin = ThinBoxSlice::<T>::new_uninit(lower);
let mut i = 0;
for item in iter {
assert!(i < lower, "iterator produced more than promised");
MaybeUninit::write(&mut thin[i], item);
i += 1;
}
assert_eq!(i, lower, "iterator produced less than promised");
unsafe { thin.assume_init() }
} else {
// TODO(nga): we can collect into partially initialized `ThinBoxSlice`
// to get a chance of avoiding last reallocation.
let vec = Vec::from_iter(iter);
Self::from_iter(vec)
}
}
}
impl<T: Allocative> Allocative for ThinBoxSlice<T> {
fn visit<'a, 'b: 'a>(&self, visitor: &'a mut allocative::Visitor<'b>) {
let mut visitor = visitor.enter_self_sized::<Self>();
{
let ptr_key = allocative::Key::new("ptr");
if self.len() == 0 {
// Statically allocated data, so just report the pointer itself
visitor.visit_simple(ptr_key, mem::size_of_val(&self.ptr));
} else {
let mut visitor =
visitor.enter_unique(allocative::Key::new("ptr"), mem::size_of_val(&self.ptr));
{
let mut visitor = visitor.enter(
allocative::Key::new("alloc"),
Self::layout_for_len(self.len()).size(),
);
visitor.visit_simple(allocative::Key::new("len"), mem::size_of::<usize>());
{
let mut visitor = visitor
.enter(allocative::Key::new("data"), mem::size_of_val::<[_]>(self));
visitor.visit_slice::<T>(self);
visitor.exit();
}
visitor.exit();
}
visitor.exit();
}
}
visitor.exit();
}
}
#[cfg(test)]
mod tests {
use crate::thin_box::ThinBoxSlice;
#[test]
fn test_empty() {
assert_eq!(0, ThinBoxSlice::<String>::empty().len());
}
#[test]
fn test_from_iter_sized() {
let thin = ThinBoxSlice::from_iter(["a".to_owned(), "b".to_owned(), "c".to_owned()]);
assert_eq!(["a".to_owned(), "b".to_owned(), "c".to_owned()], *thin);
}
#[test]
fn test_from_iter_unknown_size() {
let thin = ThinBoxSlice::from_iter(
["a".to_owned(), "b".to_owned(), "c".to_owned()]
.into_iter()
.filter(|_| true),
);
assert_eq!(["a".to_owned(), "b".to_owned(), "c".to_owned()], *thin);
}
/// If there are obvious memory violations, this test will catch them.
#[test]
fn test_stress() {
for i in 0..1000 {
let slice = ThinBoxSlice::from_iter((0..i).map(|j| j.to_string()));
assert_eq!(i, slice.len());
assert_eq!((0..i).map(|j| j.to_string()).collect::<Vec<_>>(), *slice);
}
}
}