]> git.lizzy.rs Git - rust.git/blob - src/libarena/lib.rs
Auto merge of #67540 - Mark-Simulacrum:fmt-the-world, r=Centril
[rust.git] / src / libarena / lib.rs
1 //! The arena, a fast but limited type of allocator.
2 //!
3 //! Arenas are a type of allocator that destroy the objects within, all at
4 //! once, once the arena itself is destroyed. They do not support deallocation
5 //! of individual objects while the arena itself is still alive. The benefit
6 //! of an arena is very fast allocation; just a pointer bump.
7 //!
8 //! This crate implements `TypedArena`, a simple arena that can only hold
9 //! objects of a single type.
10
11 #![doc(
12     html_root_url = "https://doc.rust-lang.org/nightly/",
13     test(no_crate_inject, attr(deny(warnings)))
14 )]
15 #![feature(core_intrinsics)]
16 #![feature(dropck_eyepatch)]
17 #![feature(raw_vec_internals)]
18 #![cfg_attr(test, feature(test))]
19 #![allow(deprecated)]
20
21 extern crate alloc;
22
23 use rustc_data_structures::cold_path;
24 use rustc_data_structures::sync::MTLock;
25 use smallvec::SmallVec;
26
27 use std::cell::{Cell, RefCell};
28 use std::cmp;
29 use std::intrinsics;
30 use std::marker::{PhantomData, Send};
31 use std::mem;
32 use std::ptr;
33 use std::slice;
34
35 use alloc::raw_vec::RawVec;
36
37 /// An arena that can hold objects of only one type.
38 pub struct TypedArena<T> {
39     /// A pointer to the next object to be allocated.
40     ptr: Cell<*mut T>,
41
42     /// A pointer to the end of the allocated area. When this pointer is
43     /// reached, a new chunk is allocated.
44     end: Cell<*mut T>,
45
46     /// A vector of arena chunks.
47     chunks: RefCell<Vec<TypedArenaChunk<T>>>,
48
49     /// Marker indicating that dropping the arena causes its owned
50     /// instances of `T` to be dropped.
51     _own: PhantomData<T>,
52 }
53
54 struct TypedArenaChunk<T> {
55     /// The raw storage for the arena chunk.
56     storage: RawVec<T>,
57     /// The number of valid entries in the chunk.
58     entries: usize,
59 }
60
61 impl<T> TypedArenaChunk<T> {
62     #[inline]
63     unsafe fn new(capacity: usize) -> TypedArenaChunk<T> {
64         TypedArenaChunk { storage: RawVec::with_capacity(capacity), entries: 0 }
65     }
66
67     /// Destroys this arena chunk.
68     #[inline]
69     unsafe fn destroy(&mut self, len: usize) {
70         // The branch on needs_drop() is an -O1 performance optimization.
71         // Without the branch, dropping TypedArena<u8> takes linear time.
72         if mem::needs_drop::<T>() {
73             let mut start = self.start();
74             // Destroy all allocated objects.
75             for _ in 0..len {
76                 ptr::drop_in_place(start);
77                 start = start.offset(1);
78             }
79         }
80     }
81
82     // Returns a pointer to the first allocated object.
83     #[inline]
84     fn start(&self) -> *mut T {
85         self.storage.ptr()
86     }
87
88     // Returns a pointer to the end of the allocated space.
89     #[inline]
90     fn end(&self) -> *mut T {
91         unsafe {
92             if mem::size_of::<T>() == 0 {
93                 // A pointer as large as possible for zero-sized elements.
94                 !0 as *mut T
95             } else {
96                 self.start().add(self.storage.capacity())
97             }
98         }
99     }
100 }
101
102 const PAGE: usize = 4096;
103
104 impl<T> Default for TypedArena<T> {
105     /// Creates a new `TypedArena`.
106     fn default() -> TypedArena<T> {
107         TypedArena {
108             // We set both `ptr` and `end` to 0 so that the first call to
109             // alloc() will trigger a grow().
110             ptr: Cell::new(ptr::null_mut()),
111             end: Cell::new(ptr::null_mut()),
112             chunks: RefCell::new(vec![]),
113             _own: PhantomData,
114         }
115     }
116 }
117
118 impl<T> TypedArena<T> {
119     pub fn in_arena(&self, ptr: *const T) -> bool {
120         let ptr = ptr as *const T as *mut T;
121
122         self.chunks.borrow().iter().any(|chunk| chunk.start() <= ptr && ptr < chunk.end())
123     }
124     /// Allocates an object in the `TypedArena`, returning a reference to it.
125     #[inline]
126     pub fn alloc(&self, object: T) -> &mut T {
127         if self.ptr == self.end {
128             self.grow(1)
129         }
130
131         unsafe {
132             if mem::size_of::<T>() == 0 {
133                 self.ptr.set(intrinsics::arith_offset(self.ptr.get() as *mut u8, 1) as *mut T);
134                 let ptr = mem::align_of::<T>() as *mut T;
135                 // Don't drop the object. This `write` is equivalent to `forget`.
136                 ptr::write(ptr, object);
137                 &mut *ptr
138             } else {
139                 let ptr = self.ptr.get();
140                 // Advance the pointer.
141                 self.ptr.set(self.ptr.get().offset(1));
142                 // Write into uninitialized memory.
143                 ptr::write(ptr, object);
144                 &mut *ptr
145             }
146         }
147     }
148
149     #[inline]
150     fn can_allocate(&self, len: usize) -> bool {
151         let available_capacity_bytes = self.end.get() as usize - self.ptr.get() as usize;
152         let at_least_bytes = len.checked_mul(mem::size_of::<T>()).unwrap();
153         available_capacity_bytes >= at_least_bytes
154     }
155
156     /// Ensures there's enough space in the current chunk to fit `len` objects.
157     #[inline]
158     fn ensure_capacity(&self, len: usize) {
159         if !self.can_allocate(len) {
160             self.grow(len);
161             debug_assert!(self.can_allocate(len));
162         }
163     }
164
165     #[inline]
166     unsafe fn alloc_raw_slice(&self, len: usize) -> *mut T {
167         assert!(mem::size_of::<T>() != 0);
168         assert!(len != 0);
169
170         self.ensure_capacity(len);
171
172         let start_ptr = self.ptr.get();
173         self.ptr.set(start_ptr.add(len));
174         start_ptr
175     }
176
177     /// Allocates a slice of objects that are copied into the `TypedArena`, returning a mutable
178     /// reference to it. Will panic if passed a zero-sized types.
179     ///
180     /// Panics:
181     ///
182     ///  - Zero-sized types
183     ///  - Zero-length slices
184     #[inline]
185     pub fn alloc_slice(&self, slice: &[T]) -> &mut [T]
186     where
187         T: Copy,
188     {
189         unsafe {
190             let len = slice.len();
191             let start_ptr = self.alloc_raw_slice(len);
192             slice.as_ptr().copy_to_nonoverlapping(start_ptr, len);
193             slice::from_raw_parts_mut(start_ptr, len)
194         }
195     }
196
197     #[inline]
198     pub fn alloc_from_iter<I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
199         assert!(mem::size_of::<T>() != 0);
200         let mut vec: SmallVec<[_; 8]> = iter.into_iter().collect();
201         if vec.is_empty() {
202             return &mut [];
203         }
204         // Move the content to the arena by copying it and then forgetting
205         // the content of the SmallVec
206         unsafe {
207             let len = vec.len();
208             let start_ptr = self.alloc_raw_slice(len);
209             vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
210             vec.set_len(0);
211             slice::from_raw_parts_mut(start_ptr, len)
212         }
213     }
214
215     /// Grows the arena.
216     #[inline(never)]
217     #[cold]
218     fn grow(&self, n: usize) {
219         unsafe {
220             let mut chunks = self.chunks.borrow_mut();
221             let (chunk, mut new_capacity);
222             if let Some(last_chunk) = chunks.last_mut() {
223                 let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize;
224                 let currently_used_cap = used_bytes / mem::size_of::<T>();
225                 last_chunk.entries = currently_used_cap;
226                 if last_chunk.storage.reserve_in_place(currently_used_cap, n) {
227                     self.end.set(last_chunk.end());
228                     return;
229                 } else {
230                     new_capacity = last_chunk.storage.capacity();
231                     loop {
232                         new_capacity = new_capacity.checked_mul(2).unwrap();
233                         if new_capacity >= currently_used_cap + n {
234                             break;
235                         }
236                     }
237                 }
238             } else {
239                 let elem_size = cmp::max(1, mem::size_of::<T>());
240                 new_capacity = cmp::max(n, PAGE / elem_size);
241             }
242             chunk = TypedArenaChunk::<T>::new(new_capacity);
243             self.ptr.set(chunk.start());
244             self.end.set(chunk.end());
245             chunks.push(chunk);
246         }
247     }
248
249     /// Clears the arena. Deallocates all but the longest chunk which may be reused.
250     pub fn clear(&mut self) {
251         unsafe {
252             // Clear the last chunk, which is partially filled.
253             let mut chunks_borrow = self.chunks.borrow_mut();
254             if let Some(mut last_chunk) = chunks_borrow.last_mut() {
255                 self.clear_last_chunk(&mut last_chunk);
256                 let len = chunks_borrow.len();
257                 // If `T` is ZST, code below has no effect.
258                 for mut chunk in chunks_borrow.drain(..len - 1) {
259                     chunk.destroy(chunk.entries);
260                 }
261             }
262         }
263     }
264
265     // Drops the contents of the last chunk. The last chunk is partially empty, unlike all other
266     // chunks.
267     fn clear_last_chunk(&self, last_chunk: &mut TypedArenaChunk<T>) {
268         // Determine how much was filled.
269         let start = last_chunk.start() as usize;
270         // We obtain the value of the pointer to the first uninitialized element.
271         let end = self.ptr.get() as usize;
272         // We then calculate the number of elements to be dropped in the last chunk,
273         // which is the filled area's length.
274         let diff = if mem::size_of::<T>() == 0 {
275             // `T` is ZST. It can't have a drop flag, so the value here doesn't matter. We get
276             // the number of zero-sized values in the last and only chunk, just out of caution.
277             // Recall that `end` was incremented for each allocated value.
278             end - start
279         } else {
280             (end - start) / mem::size_of::<T>()
281         };
282         // Pass that to the `destroy` method.
283         unsafe {
284             last_chunk.destroy(diff);
285         }
286         // Reset the chunk.
287         self.ptr.set(last_chunk.start());
288     }
289 }
290
291 unsafe impl<#[may_dangle] T> Drop for TypedArena<T> {
292     fn drop(&mut self) {
293         unsafe {
294             // Determine how much was filled.
295             let mut chunks_borrow = self.chunks.borrow_mut();
296             if let Some(mut last_chunk) = chunks_borrow.pop() {
297                 // Drop the contents of the last chunk.
298                 self.clear_last_chunk(&mut last_chunk);
299                 // The last chunk will be dropped. Destroy all other chunks.
300                 for chunk in chunks_borrow.iter_mut() {
301                     chunk.destroy(chunk.entries);
302                 }
303             }
304             // RawVec handles deallocation of `last_chunk` and `self.chunks`.
305         }
306     }
307 }
308
309 unsafe impl<T: Send> Send for TypedArena<T> {}
310
311 pub struct DroplessArena {
312     /// A pointer to the next object to be allocated.
313     ptr: Cell<*mut u8>,
314
315     /// A pointer to the end of the allocated area. When this pointer is
316     /// reached, a new chunk is allocated.
317     end: Cell<*mut u8>,
318
319     /// A vector of arena chunks.
320     chunks: RefCell<Vec<TypedArenaChunk<u8>>>,
321 }
322
323 unsafe impl Send for DroplessArena {}
324
325 impl Default for DroplessArena {
326     #[inline]
327     fn default() -> DroplessArena {
328         DroplessArena {
329             ptr: Cell::new(ptr::null_mut()),
330             end: Cell::new(ptr::null_mut()),
331             chunks: Default::default(),
332         }
333     }
334 }
335
336 impl DroplessArena {
337     pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool {
338         let ptr = ptr as *const u8 as *mut u8;
339
340         self.chunks.borrow().iter().any(|chunk| chunk.start() <= ptr && ptr < chunk.end())
341     }
342
343     #[inline]
344     fn align(&self, align: usize) {
345         let final_address = ((self.ptr.get() as usize) + align - 1) & !(align - 1);
346         self.ptr.set(final_address as *mut u8);
347         assert!(self.ptr <= self.end);
348     }
349
350     #[inline(never)]
351     #[cold]
352     fn grow(&self, needed_bytes: usize) {
353         unsafe {
354             let mut chunks = self.chunks.borrow_mut();
355             let (chunk, mut new_capacity);
356             if let Some(last_chunk) = chunks.last_mut() {
357                 let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize;
358                 if last_chunk.storage.reserve_in_place(used_bytes, needed_bytes) {
359                     self.end.set(last_chunk.end());
360                     return;
361                 } else {
362                     new_capacity = last_chunk.storage.capacity();
363                     loop {
364                         new_capacity = new_capacity.checked_mul(2).unwrap();
365                         if new_capacity >= used_bytes + needed_bytes {
366                             break;
367                         }
368                     }
369                 }
370             } else {
371                 new_capacity = cmp::max(needed_bytes, PAGE);
372             }
373             chunk = TypedArenaChunk::<u8>::new(new_capacity);
374             self.ptr.set(chunk.start());
375             self.end.set(chunk.end());
376             chunks.push(chunk);
377         }
378     }
379
380     #[inline]
381     pub fn alloc_raw(&self, bytes: usize, align: usize) -> &mut [u8] {
382         unsafe {
383             assert!(bytes != 0);
384
385             self.align(align);
386
387             let future_end = intrinsics::arith_offset(self.ptr.get(), bytes as isize);
388             if (future_end as *mut u8) >= self.end.get() {
389                 self.grow(bytes);
390             }
391
392             let ptr = self.ptr.get();
393             // Set the pointer past ourselves
394             self.ptr.set(intrinsics::arith_offset(self.ptr.get(), bytes as isize) as *mut u8);
395             slice::from_raw_parts_mut(ptr, bytes)
396         }
397     }
398
399     #[inline]
400     pub fn alloc<T>(&self, object: T) -> &mut T {
401         assert!(!mem::needs_drop::<T>());
402
403         let mem = self.alloc_raw(mem::size_of::<T>(), mem::align_of::<T>()) as *mut _ as *mut T;
404
405         unsafe {
406             // Write into uninitialized memory.
407             ptr::write(mem, object);
408             &mut *mem
409         }
410     }
411
412     /// Allocates a slice of objects that are copied into the `DroplessArena`, returning a mutable
413     /// reference to it. Will panic if passed a zero-sized type.
414     ///
415     /// Panics:
416     ///
417     ///  - Zero-sized types
418     ///  - Zero-length slices
419     #[inline]
420     pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
421     where
422         T: Copy,
423     {
424         assert!(!mem::needs_drop::<T>());
425         assert!(mem::size_of::<T>() != 0);
426         assert!(!slice.is_empty());
427
428         let mem = self.alloc_raw(slice.len() * mem::size_of::<T>(), mem::align_of::<T>()) as *mut _
429             as *mut T;
430
431         unsafe {
432             let arena_slice = slice::from_raw_parts_mut(mem, slice.len());
433             arena_slice.copy_from_slice(slice);
434             arena_slice
435         }
436     }
437
438     #[inline]
439     unsafe fn write_from_iter<T, I: Iterator<Item = T>>(
440         &self,
441         mut iter: I,
442         len: usize,
443         mem: *mut T,
444     ) -> &mut [T] {
445         let mut i = 0;
446         // Use a manual loop since LLVM manages to optimize it better for
447         // slice iterators
448         loop {
449             let value = iter.next();
450             if i >= len || value.is_none() {
451                 // We only return as many items as the iterator gave us, even
452                 // though it was supposed to give us `len`
453                 return slice::from_raw_parts_mut(mem, i);
454             }
455             ptr::write(mem.add(i), value.unwrap());
456             i += 1;
457         }
458     }
459
460     #[inline]
461     pub fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
462         let iter = iter.into_iter();
463         assert!(mem::size_of::<T>() != 0);
464         assert!(!mem::needs_drop::<T>());
465
466         let size_hint = iter.size_hint();
467
468         match size_hint {
469             (min, Some(max)) if min == max => {
470                 // We know the exact number of elements the iterator will produce here
471                 let len = min;
472
473                 if len == 0 {
474                     return &mut [];
475                 }
476                 let size = len.checked_mul(mem::size_of::<T>()).unwrap();
477                 let mem = self.alloc_raw(size, mem::align_of::<T>()) as *mut _ as *mut T;
478                 unsafe { self.write_from_iter(iter, len, mem) }
479             }
480             (_, _) => {
481                 cold_path(move || -> &mut [T] {
482                     let mut vec: SmallVec<[_; 8]> = iter.collect();
483                     if vec.is_empty() {
484                         return &mut [];
485                     }
486                     // Move the content to the arena by copying it and then forgetting
487                     // the content of the SmallVec
488                     unsafe {
489                         let len = vec.len();
490                         let start_ptr = self
491                             .alloc_raw(len * mem::size_of::<T>(), mem::align_of::<T>())
492                             as *mut _ as *mut T;
493                         vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
494                         vec.set_len(0);
495                         slice::from_raw_parts_mut(start_ptr, len)
496                     }
497                 })
498             }
499         }
500     }
501 }
502
503 #[derive(Default)]
504 // FIXME(@Zoxc): this type is entirely unused in rustc
505 pub struct SyncTypedArena<T> {
506     lock: MTLock<TypedArena<T>>,
507 }
508
509 impl<T> SyncTypedArena<T> {
510     #[inline(always)]
511     pub fn alloc(&self, object: T) -> &mut T {
512         // Extend the lifetime of the result since it's limited to the lock guard
513         unsafe { &mut *(self.lock.lock().alloc(object) as *mut T) }
514     }
515
516     #[inline(always)]
517     pub fn alloc_slice(&self, slice: &[T]) -> &mut [T]
518     where
519         T: Copy,
520     {
521         // Extend the lifetime of the result since it's limited to the lock guard
522         unsafe { &mut *(self.lock.lock().alloc_slice(slice) as *mut [T]) }
523     }
524
525     #[inline(always)]
526     pub fn clear(&mut self) {
527         self.lock.get_mut().clear();
528     }
529 }
530
531 #[derive(Default)]
532 pub struct SyncDroplessArena {
533     lock: MTLock<DroplessArena>,
534 }
535
536 impl SyncDroplessArena {
537     #[inline(always)]
538     pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool {
539         self.lock.lock().in_arena(ptr)
540     }
541
542     #[inline(always)]
543     pub fn alloc_raw(&self, bytes: usize, align: usize) -> &mut [u8] {
544         // Extend the lifetime of the result since it's limited to the lock guard
545         unsafe { &mut *(self.lock.lock().alloc_raw(bytes, align) as *mut [u8]) }
546     }
547
548     #[inline(always)]
549     pub fn alloc<T>(&self, object: T) -> &mut T {
550         // Extend the lifetime of the result since it's limited to the lock guard
551         unsafe { &mut *(self.lock.lock().alloc(object) as *mut T) }
552     }
553
554     #[inline(always)]
555     pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
556     where
557         T: Copy,
558     {
559         // Extend the lifetime of the result since it's limited to the lock guard
560         unsafe { &mut *(self.lock.lock().alloc_slice(slice) as *mut [T]) }
561     }
562 }
563
564 #[cfg(test)]
565 mod tests;