]> git.lizzy.rs Git - rust.git/blob - src/libarena/lib.rs
Make &Slice a thin pointer
[rust.git] / src / libarena / lib.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! The arena, a fast but limited type of allocator.
12 //!
13 //! Arenas are a type of allocator that destroy the objects within, all at
14 //! once, once the arena itself is destroyed. They do not support deallocation
15 //! of individual objects while the arena itself is still alive. The benefit
16 //! of an arena is very fast allocation; just a pointer bump.
17 //!
18 //! This crate implements `TypedArena`, a simple arena that can only hold
19 //! objects of a single type.
20
21 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
22        html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
23        html_root_url = "https://doc.rust-lang.org/nightly/",
24        test(no_crate_inject, attr(deny(warnings))))]
25
26 #![feature(alloc)]
27 #![feature(core_intrinsics)]
28 #![feature(dropck_eyepatch)]
29 #![cfg_attr(test, feature(test))]
30
31 #![allow(deprecated)]
32
33 extern crate alloc;
34 extern crate rustc_data_structures;
35
36 use rustc_data_structures::sync::MTLock;
37
38 use std::cell::{Cell, RefCell};
39 use std::cmp;
40 use std::intrinsics;
41 use std::marker::{PhantomData, Send};
42 use std::mem;
43 use std::ptr;
44 use std::slice;
45
46 use alloc::raw_vec::RawVec;
47
48 /// An arena that can hold objects of only one type.
49 pub struct TypedArena<T> {
50     /// A pointer to the next object to be allocated.
51     ptr: Cell<*mut T>,
52
53     /// A pointer to the end of the allocated area. When this pointer is
54     /// reached, a new chunk is allocated.
55     end: Cell<*mut T>,
56
57     /// A vector of arena chunks.
58     chunks: RefCell<Vec<TypedArenaChunk<T>>>,
59
60     /// Marker indicating that dropping the arena causes its owned
61     /// instances of `T` to be dropped.
62     _own: PhantomData<T>,
63 }
64
65 struct TypedArenaChunk<T> {
66     /// The raw storage for the arena chunk.
67     storage: RawVec<T>,
68 }
69
70 impl<T> TypedArenaChunk<T> {
71     #[inline]
72     unsafe fn new(capacity: usize) -> TypedArenaChunk<T> {
73         TypedArenaChunk {
74             storage: RawVec::with_capacity(capacity),
75         }
76     }
77
78     /// Destroys this arena chunk.
79     #[inline]
80     unsafe fn destroy(&mut self, len: usize) {
81         // The branch on needs_drop() is an -O1 performance optimization.
82         // Without the branch, dropping TypedArena<u8> takes linear time.
83         if mem::needs_drop::<T>() {
84             let mut start = self.start();
85             // Destroy all allocated objects.
86             for _ in 0..len {
87                 ptr::drop_in_place(start);
88                 start = start.offset(1);
89             }
90         }
91     }
92
93     // Returns a pointer to the first allocated object.
94     #[inline]
95     fn start(&self) -> *mut T {
96         self.storage.ptr()
97     }
98
99     // Returns a pointer to the end of the allocated space.
100     #[inline]
101     fn end(&self) -> *mut T {
102         unsafe {
103             if mem::size_of::<T>() == 0 {
104                 // A pointer as large as possible for zero-sized elements.
105                 !0 as *mut T
106             } else {
107                 self.start().offset(self.storage.cap() as isize)
108             }
109         }
110     }
111 }
112
113 const PAGE: usize = 4096;
114
115 impl<T> TypedArena<T> {
116     /// Creates a new `TypedArena`.
117     #[inline]
118     pub fn new() -> TypedArena<T> {
119         TypedArena {
120             // We set both `ptr` and `end` to 0 so that the first call to
121             // alloc() will trigger a grow().
122             ptr: Cell::new(0 as *mut T),
123             end: Cell::new(0 as *mut T),
124             chunks: RefCell::new(vec![]),
125             _own: PhantomData,
126         }
127     }
128
129     /// Allocates an object in the `TypedArena`, returning a reference to it.
130     #[inline]
131     pub fn alloc(&self, object: T) -> &mut T {
132         if self.ptr == self.end {
133             self.grow(1)
134         }
135
136         unsafe {
137             if mem::size_of::<T>() == 0 {
138                 self.ptr
139                     .set(intrinsics::arith_offset(self.ptr.get() as *mut u8, 1)
140                         as *mut T);
141                 let ptr = mem::align_of::<T>() as *mut T;
142                 // Don't drop the object. This `write` is equivalent to `forget`.
143                 ptr::write(ptr, object);
144                 &mut *ptr
145             } else {
146                 let ptr = self.ptr.get();
147                 // Advance the pointer.
148                 self.ptr.set(self.ptr.get().offset(1));
149                 // Write into uninitialized memory.
150                 ptr::write(ptr, object);
151                 &mut *ptr
152             }
153         }
154     }
155
156     /// Allocates a slice of objects that are copied into the `TypedArena`, returning a mutable
157     /// reference to it. Will panic if passed a zero-sized types.
158     ///
159     /// Panics:
160     ///
161     ///  - Zero-sized types
162     ///  - Zero-length slices
163     #[inline]
164     pub fn alloc_slice(&self, slice: &[T]) -> &mut [T]
165     where
166         T: Copy,
167     {
168         assert!(mem::size_of::<T>() != 0);
169         assert!(slice.len() != 0);
170
171         let available_capacity_bytes = self.end.get() as usize - self.ptr.get() as usize;
172         let at_least_bytes = slice.len() * mem::size_of::<T>();
173         if available_capacity_bytes < at_least_bytes {
174             self.grow(slice.len());
175         }
176
177         unsafe {
178             let start_ptr = self.ptr.get();
179             let arena_slice = slice::from_raw_parts_mut(start_ptr, slice.len());
180             self.ptr.set(start_ptr.offset(arena_slice.len() as isize));
181             arena_slice.copy_from_slice(slice);
182             arena_slice
183         }
184     }
185
186     /// Grows the arena.
187     #[inline(never)]
188     #[cold]
189     fn grow(&self, n: usize) {
190         unsafe {
191             let mut chunks = self.chunks.borrow_mut();
192             let (chunk, mut new_capacity);
193             if let Some(last_chunk) = chunks.last_mut() {
194                 let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize;
195                 let currently_used_cap = used_bytes / mem::size_of::<T>();
196                 if last_chunk.storage.reserve_in_place(currently_used_cap, n) {
197                     self.end.set(last_chunk.end());
198                     return;
199                 } else {
200                     new_capacity = last_chunk.storage.cap();
201                     loop {
202                         new_capacity = new_capacity.checked_mul(2).unwrap();
203                         if new_capacity >= currently_used_cap + n {
204                             break;
205                         }
206                     }
207                 }
208             } else {
209                 let elem_size = cmp::max(1, mem::size_of::<T>());
210                 new_capacity = cmp::max(n, PAGE / elem_size);
211             }
212             chunk = TypedArenaChunk::<T>::new(new_capacity);
213             self.ptr.set(chunk.start());
214             self.end.set(chunk.end());
215             chunks.push(chunk);
216         }
217     }
218
219     /// Clears the arena. Deallocates all but the longest chunk which may be reused.
220     pub fn clear(&mut self) {
221         unsafe {
222             // Clear the last chunk, which is partially filled.
223             let mut chunks_borrow = self.chunks.borrow_mut();
224             if let Some(mut last_chunk) = chunks_borrow.pop() {
225                 self.clear_last_chunk(&mut last_chunk);
226                 // If `T` is ZST, code below has no effect.
227                 for mut chunk in chunks_borrow.drain(..) {
228                     let cap = chunk.storage.cap();
229                     chunk.destroy(cap);
230                 }
231                 chunks_borrow.push(last_chunk);
232             }
233         }
234     }
235
236     // Drops the contents of the last chunk. The last chunk is partially empty, unlike all other
237     // chunks.
238     fn clear_last_chunk(&self, last_chunk: &mut TypedArenaChunk<T>) {
239         // Determine how much was filled.
240         let start = last_chunk.start() as usize;
241         // We obtain the value of the pointer to the first uninitialized element.
242         let end = self.ptr.get() as usize;
243         // We then calculate the number of elements to be dropped in the last chunk,
244         // which is the filled area's length.
245         let diff = if mem::size_of::<T>() == 0 {
246             // `T` is ZST. It can't have a drop flag, so the value here doesn't matter. We get
247             // the number of zero-sized values in the last and only chunk, just out of caution.
248             // Recall that `end` was incremented for each allocated value.
249             end - start
250         } else {
251             (end - start) / mem::size_of::<T>()
252         };
253         // Pass that to the `destroy` method.
254         unsafe {
255             last_chunk.destroy(diff);
256         }
257         // Reset the chunk.
258         self.ptr.set(last_chunk.start());
259     }
260 }
261
262 unsafe impl<#[may_dangle] T> Drop for TypedArena<T> {
263     fn drop(&mut self) {
264         unsafe {
265             // Determine how much was filled.
266             let mut chunks_borrow = self.chunks.borrow_mut();
267             if let Some(mut last_chunk) = chunks_borrow.pop() {
268                 // Drop the contents of the last chunk.
269                 self.clear_last_chunk(&mut last_chunk);
270                 // The last chunk will be dropped. Destroy all other chunks.
271                 for chunk in chunks_borrow.iter_mut() {
272                     let cap = chunk.storage.cap();
273                     chunk.destroy(cap);
274                 }
275             }
276             // RawVec handles deallocation of `last_chunk` and `self.chunks`.
277         }
278     }
279 }
280
281 unsafe impl<T: Send> Send for TypedArena<T> {}
282
283 pub struct DroplessArena {
284     /// A pointer to the next object to be allocated.
285     ptr: Cell<*mut u8>,
286
287     /// A pointer to the end of the allocated area. When this pointer is
288     /// reached, a new chunk is allocated.
289     end: Cell<*mut u8>,
290
291     /// A vector of arena chunks.
292     chunks: RefCell<Vec<TypedArenaChunk<u8>>>,
293 }
294
295 unsafe impl Send for DroplessArena {}
296
297 impl DroplessArena {
298     pub fn new() -> DroplessArena {
299         DroplessArena {
300             ptr: Cell::new(0 as *mut u8),
301             end: Cell::new(0 as *mut u8),
302             chunks: RefCell::new(vec![]),
303         }
304     }
305
306     pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool {
307         let ptr = ptr as *const u8 as *mut u8;
308         for chunk in &*self.chunks.borrow() {
309             if chunk.start() <= ptr && ptr < chunk.end() {
310                 return true;
311             }
312         }
313
314         false
315     }
316
317     fn align(&self, align: usize) {
318         let final_address = ((self.ptr.get() as usize) + align - 1) & !(align - 1);
319         self.ptr.set(final_address as *mut u8);
320         assert!(self.ptr <= self.end);
321     }
322
323     #[inline(never)]
324     #[cold]
325     fn grow(&self, needed_bytes: usize) {
326         unsafe {
327             let mut chunks = self.chunks.borrow_mut();
328             let (chunk, mut new_capacity);
329             if let Some(last_chunk) = chunks.last_mut() {
330                 let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize;
331                 if last_chunk
332                     .storage
333                     .reserve_in_place(used_bytes, needed_bytes)
334                 {
335                     self.end.set(last_chunk.end());
336                     return;
337                 } else {
338                     new_capacity = last_chunk.storage.cap();
339                     loop {
340                         new_capacity = new_capacity.checked_mul(2).unwrap();
341                         if new_capacity >= used_bytes + needed_bytes {
342                             break;
343                         }
344                     }
345                 }
346             } else {
347                 new_capacity = cmp::max(needed_bytes, PAGE);
348             }
349             chunk = TypedArenaChunk::<u8>::new(new_capacity);
350             self.ptr.set(chunk.start());
351             self.end.set(chunk.end());
352             chunks.push(chunk);
353         }
354     }
355
356     #[inline]
357     pub fn alloc_raw(&self, bytes: usize, align: usize) -> &mut [u8] {
358         unsafe {
359             assert!(bytes != 0);
360
361             self.align(align);
362
363             let future_end = intrinsics::arith_offset(self.ptr.get(), bytes as isize);
364             if (future_end as *mut u8) >= self.end.get() {
365                 self.grow(bytes);
366             }
367
368             let ptr = self.ptr.get();
369             // Set the pointer past ourselves
370             self.ptr.set(
371                 intrinsics::arith_offset(self.ptr.get(), bytes as isize) as *mut u8,
372             );
373             slice::from_raw_parts_mut(ptr, bytes)
374         }
375     }
376
377     #[inline]
378     pub fn alloc<T>(&self, object: T) -> &mut T {
379         assert!(!mem::needs_drop::<T>());
380
381         let mem = self.alloc_raw(
382             mem::size_of::<T>(),
383             mem::align_of::<T>()) as *mut _ as *mut T;
384
385         unsafe {
386             // Write into uninitialized memory.
387             ptr::write(mem, object);
388             &mut *mem
389         }
390     }
391
392     /// Allocates a slice of objects that are copied into the `DroplessArena`, returning a mutable
393     /// reference to it. Will panic if passed a zero-sized type.
394     ///
395     /// Panics:
396     ///
397     ///  - Zero-sized types
398     ///  - Zero-length slices
399     #[inline]
400     pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
401     where
402         T: Copy,
403     {
404         assert!(!mem::needs_drop::<T>());
405         assert!(mem::size_of::<T>() != 0);
406         assert!(slice.len() != 0);
407
408         let mem = self.alloc_raw(
409             slice.len() * mem::size_of::<T>(),
410             mem::align_of::<T>()) as *mut _ as *mut T;
411
412         unsafe {
413             let arena_slice = slice::from_raw_parts_mut(mem, slice.len());
414             arena_slice.copy_from_slice(slice);
415             arena_slice
416         }
417     }
418 }
419
420 pub struct SyncTypedArena<T> {
421     lock: MTLock<TypedArena<T>>,
422 }
423
424 impl<T> SyncTypedArena<T> {
425     #[inline(always)]
426     pub fn new() -> SyncTypedArena<T> {
427         SyncTypedArena {
428             lock: MTLock::new(TypedArena::new())
429         }
430     }
431
432     #[inline(always)]
433     pub fn alloc(&self, object: T) -> &mut T {
434         // Extend the lifetime of the result since it's limited to the lock guard
435         unsafe { &mut *(self.lock.lock().alloc(object) as *mut T) }
436     }
437
438     #[inline(always)]
439     pub fn alloc_slice(&self, slice: &[T]) -> &mut [T]
440     where
441         T: Copy,
442     {
443         // Extend the lifetime of the result since it's limited to the lock guard
444         unsafe { &mut *(self.lock.lock().alloc_slice(slice) as *mut [T]) }
445     }
446
447     #[inline(always)]
448     pub fn clear(&mut self) {
449         self.lock.get_mut().clear();
450     }
451 }
452
453 pub struct SyncDroplessArena {
454     lock: MTLock<DroplessArena>,
455 }
456
457 impl SyncDroplessArena {
458     #[inline(always)]
459     pub fn new() -> SyncDroplessArena {
460         SyncDroplessArena {
461             lock: MTLock::new(DroplessArena::new())
462         }
463     }
464
465     #[inline(always)]
466     pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool {
467         self.lock.lock().in_arena(ptr)
468     }
469
470     #[inline(always)]
471     pub fn alloc_raw(&self, bytes: usize, align: usize) -> &mut [u8] {
472         // Extend the lifetime of the result since it's limited to the lock guard
473         unsafe { &mut *(self.lock.lock().alloc_raw(bytes, align) as *mut [u8]) }
474     }
475
476     #[inline(always)]
477     pub fn alloc<T>(&self, object: T) -> &mut T {
478         // Extend the lifetime of the result since it's limited to the lock guard
479         unsafe { &mut *(self.lock.lock().alloc(object) as *mut T) }
480     }
481
482     #[inline(always)]
483     pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
484     where
485         T: Copy,
486     {
487         // Extend the lifetime of the result since it's limited to the lock guard
488         unsafe { &mut *(self.lock.lock().alloc_slice(slice) as *mut [T]) }
489     }
490 }
491
492 #[cfg(test)]
493 mod tests {
494     extern crate test;
495     use self::test::Bencher;
496     use super::TypedArena;
497     use std::cell::Cell;
498
499     #[allow(dead_code)]
500     #[derive(Debug, Eq, PartialEq)]
501     struct Point {
502         x: i32,
503         y: i32,
504         z: i32,
505     }
506
507     #[test]
508     pub fn test_unused() {
509         let arena: TypedArena<Point> = TypedArena::new();
510         assert!(arena.chunks.borrow().is_empty());
511     }
512
513     #[test]
514     fn test_arena_alloc_nested() {
515         struct Inner {
516             value: u8,
517         }
518         struct Outer<'a> {
519             inner: &'a Inner,
520         }
521         enum EI<'e> {
522             I(Inner),
523             O(Outer<'e>),
524         }
525
526         struct Wrap<'a>(TypedArena<EI<'a>>);
527
528         impl<'a> Wrap<'a> {
529             fn alloc_inner<F: Fn() -> Inner>(&self, f: F) -> &Inner {
530                 let r: &EI = self.0.alloc(EI::I(f()));
531                 if let &EI::I(ref i) = r {
532                     i
533                 } else {
534                     panic!("mismatch");
535                 }
536             }
537             fn alloc_outer<F: Fn() -> Outer<'a>>(&self, f: F) -> &Outer {
538                 let r: &EI = self.0.alloc(EI::O(f()));
539                 if let &EI::O(ref o) = r {
540                     o
541                 } else {
542                     panic!("mismatch");
543                 }
544             }
545         }
546
547         let arena = Wrap(TypedArena::new());
548
549         let result = arena.alloc_outer(|| Outer {
550             inner: arena.alloc_inner(|| Inner { value: 10 }),
551         });
552
553         assert_eq!(result.inner.value, 10);
554     }
555
556     #[test]
557     pub fn test_copy() {
558         let arena = TypedArena::new();
559         for _ in 0..100000 {
560             arena.alloc(Point { x: 1, y: 2, z: 3 });
561         }
562     }
563
564     #[bench]
565     pub fn bench_copy(b: &mut Bencher) {
566         let arena = TypedArena::new();
567         b.iter(|| arena.alloc(Point { x: 1, y: 2, z: 3 }))
568     }
569
570     #[bench]
571     pub fn bench_copy_nonarena(b: &mut Bencher) {
572         b.iter(|| {
573             let _: Box<_> = Box::new(Point { x: 1, y: 2, z: 3 });
574         })
575     }
576
577     #[allow(dead_code)]
578     struct Noncopy {
579         string: String,
580         array: Vec<i32>,
581     }
582
583     #[test]
584     pub fn test_noncopy() {
585         let arena = TypedArena::new();
586         for _ in 0..100000 {
587             arena.alloc(Noncopy {
588                 string: "hello world".to_string(),
589                 array: vec![1, 2, 3, 4, 5],
590             });
591         }
592     }
593
594     #[test]
595     pub fn test_typed_arena_zero_sized() {
596         let arena = TypedArena::new();
597         for _ in 0..100000 {
598             arena.alloc(());
599         }
600     }
601
602     #[test]
603     pub fn test_typed_arena_clear() {
604         let mut arena = TypedArena::new();
605         for _ in 0..10 {
606             arena.clear();
607             for _ in 0..10000 {
608                 arena.alloc(Point { x: 1, y: 2, z: 3 });
609             }
610         }
611     }
612
613     // Drop tests
614
615     struct DropCounter<'a> {
616         count: &'a Cell<u32>,
617     }
618
619     impl<'a> Drop for DropCounter<'a> {
620         fn drop(&mut self) {
621             self.count.set(self.count.get() + 1);
622         }
623     }
624
625     #[test]
626     fn test_typed_arena_drop_count() {
627         let counter = Cell::new(0);
628         {
629             let arena: TypedArena<DropCounter> = TypedArena::new();
630             for _ in 0..100 {
631                 // Allocate something with drop glue to make sure it doesn't leak.
632                 arena.alloc(DropCounter { count: &counter });
633             }
634         };
635         assert_eq!(counter.get(), 100);
636     }
637
638     #[test]
639     fn test_typed_arena_drop_on_clear() {
640         let counter = Cell::new(0);
641         let mut arena: TypedArena<DropCounter> = TypedArena::new();
642         for i in 0..10 {
643             for _ in 0..100 {
644                 // Allocate something with drop glue to make sure it doesn't leak.
645                 arena.alloc(DropCounter { count: &counter });
646             }
647             arena.clear();
648             assert_eq!(counter.get(), i * 100 + 100);
649         }
650     }
651
652     thread_local! {
653         static DROP_COUNTER: Cell<u32> = Cell::new(0)
654     }
655
656     struct SmallDroppable;
657
658     impl Drop for SmallDroppable {
659         fn drop(&mut self) {
660             DROP_COUNTER.with(|c| c.set(c.get() + 1));
661         }
662     }
663
664     #[test]
665     fn test_typed_arena_drop_small_count() {
666         DROP_COUNTER.with(|c| c.set(0));
667         {
668             let arena: TypedArena<SmallDroppable> = TypedArena::new();
669             for _ in 0..100 {
670                 // Allocate something with drop glue to make sure it doesn't leak.
671                 arena.alloc(SmallDroppable);
672             }
673             // dropping
674         };
675         assert_eq!(DROP_COUNTER.with(|c| c.get()), 100);
676     }
677
678     #[bench]
679     pub fn bench_noncopy(b: &mut Bencher) {
680         let arena = TypedArena::new();
681         b.iter(|| {
682             arena.alloc(Noncopy {
683                 string: "hello world".to_string(),
684                 array: vec![1, 2, 3, 4, 5],
685             })
686         })
687     }
688
689     #[bench]
690     pub fn bench_noncopy_nonarena(b: &mut Bencher) {
691         b.iter(|| {
692             let _: Box<_> = Box::new(Noncopy {
693                 string: "hello world".to_string(),
694                 array: vec![1, 2, 3, 4, 5],
695             });
696         })
697     }
698 }