-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathlib.rs
2019 lines (1857 loc) · 72.1 KB
/
lib.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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![doc = include_str!("../README.md")]
#![deny(missing_debug_implementations)]
#![deny(missing_docs)]
#![no_std]
#![cfg_attr(
feature = "allocator_api",
feature(allocator_api, nonnull_slice_from_raw_parts)
)]
#[doc(hidden)]
pub extern crate alloc as core_alloc;
#[cfg(feature = "boxed")]
pub mod boxed;
#[cfg(feature = "collections")]
pub mod collections;
mod alloc;
use core::cell::Cell;
use core::fmt::Display;
use core::iter;
use core::marker::PhantomData;
use core::mem;
use core::ptr::{self, NonNull};
use core::slice;
use core::str;
use core_alloc::alloc::{alloc, dealloc, Layout};
#[cfg(feature = "allocator_api")]
use core_alloc::alloc::{AllocError, Allocator};
pub use alloc::AllocErr;
/// An error returned from [`Bump::try_alloc_try_with`].
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum AllocOrInitError<E> {
/// Indicates that the initial allocation failed.
Alloc(AllocErr),
/// Indicates that the initializer failed with the contained error after
/// allocation.
///
/// It is possible but not guaranteed that the allocated memory has been
/// released back to the allocator at this point.
Init(E),
}
impl<E> From<AllocErr> for AllocOrInitError<E> {
fn from(e: AllocErr) -> Self {
Self::Alloc(e)
}
}
impl<E: Display> Display for AllocOrInitError<E> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
AllocOrInitError::Alloc(err) => err.fmt(f),
AllocOrInitError::Init(err) => write!(f, "initialization failed: {}", err),
}
}
}
/// An arena to bump allocate into.
///
/// ## No `Drop`s
///
/// Objects that are bump-allocated will never have their [`Drop`] implementation
/// called — unless you do it manually yourself. This makes it relatively
/// easy to leak memory or other resources.
///
/// If you have a type which internally manages
///
/// * an allocation from the global heap (e.g. [`Vec<T>`]),
/// * open file descriptors (e.g. [`std::fs::File`]), or
/// * any other resource that must be cleaned up (e.g. an `mmap`)
///
/// and relies on its `Drop` implementation to clean up the internal resource,
/// then if you allocate that type with a `Bump`, you need to find a new way to
/// clean up after it yourself.
///
/// Potential solutions are:
///
/// * Using [`bumpalo::boxed::Box::new_in`] instead of [`Bump::alloc`], that
/// will drop wrapped values similarly to [`std::boxed::Box`]. Note that this
/// requires enabling the `"boxed"` Cargo feature for this crate. **This is
/// often the easiest solution.**
///
/// * Calling [`drop_in_place`][drop_in_place] or using
/// [`std::mem::ManuallyDrop`][manuallydrop] to manually drop these types.
///
/// * Using [`bumpalo::collections::Vec`] instead of [`std::vec::Vec`].
///
/// * Avoiding allocating these problematic types within a `Bump`.
///
/// Note that not calling `Drop` is memory safe! Destructors are never
/// guaranteed to run in Rust, you can't rely on them for enforcing memory
/// safety.
///
/// [`Drop`]: https://doc.rust-lang.org/std/ops/trait.Drop.html
/// [`Vec<T>`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
/// [`std::fs::File`]: https://doc.rust-lang.org/std/fs/struct.File.html
/// [drop_in_place]: https://doc.rust-lang.org/std/ptr/fn.drop_in_place.html
/// [manuallydrop]: https://doc.rust-lang.org/std/mem/struct.ManuallyDrop.html
/// [`bumpalo::collections::Vec`]: collections/vec/struct.Vec.html
/// [`std::vec::Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
/// [`bumpalo::boxed::Box::new_in`]: boxed/struct.Box.html#method.new_in
/// [`std::boxed::Box`]: https://doc.rust-lang.org/std/boxed/struct.Box.html
///
/// ## Example
///
/// ```
/// use bumpalo::Bump;
///
/// // Create a new bump arena.
/// let bump = Bump::new();
///
/// // Allocate values into the arena.
/// let forty_two = bump.alloc(42);
/// assert_eq!(*forty_two, 42);
///
/// // Mutable references are returned from allocation.
/// let mut s = bump.alloc("bumpalo");
/// *s = "the bump allocator; and also is a buffalo";
/// ```
///
/// ## Allocation Methods Come in Many Flavors
///
/// There are various allocation methods on `Bump`, the simplest being
/// [`alloc`][Bump::alloc]. The others exist to satisfy some combination of
/// fallible allocation and initialization. The allocation methods are
/// summarized in the following table:
///
/// <table>
/// <thead>
/// <tr>
/// <th></th>
/// <th>Infallible Allocation</th>
/// <th>Fallible Allocation</th>
/// </tr>
/// </thead>
/// <tr>
/// <th>By Value</th>
/// <td><a href="#method.alloc"><code>alloc</code></a></td>
/// <td><a href="#method.try_alloc"><code>try_alloc</code></a></td>
/// </tr>
/// <tr>
/// <th>Infallible Initializer Function</th>
/// <td><a href="#method.alloc_with"><code>alloc_with</code></a></td>
/// <td><a href="#method.try_alloc_with"><code>try_alloc_with</code></a></td>
/// </tr>
/// <tr>
/// <th>Fallible Initializer Function</th>
/// <td><a href="#method.alloc_try_with"><code>alloc_try_with</code></a></td>
/// <td><a href="#method.try_alloc_try_with"><code>try_alloc_try_with</code></a></td>
/// </tr>
/// <tbody>
/// </tbody>
/// </table>
///
/// ### Fallible Allocation: The `try_alloc_` Method Prefix
///
/// These allocation methods let you recover from out-of-memory (OOM)
/// scenarioes, rather than raising a panic on OOM.
///
/// ```
/// use bumpalo::Bump;
///
/// let bump = Bump::new();
///
/// match bump.try_alloc(MyStruct {
/// // ...
/// }) {
/// Ok(my_struct) => {
/// // Allocation succeeded.
/// }
/// Err(e) => {
/// // Out of memory.
/// }
/// }
///
/// struct MyStruct {
/// // ...
/// }
/// ```
///
/// ### Initializer Functions: The `_with` Method Suffix
///
/// Calling one of the generic `…alloc(x)` methods is essentially equivalent to
/// the matching [`…alloc_with(|| x)`](?search=alloc_with). However if you use
/// `…alloc_with`, then the closure will not be invoked until after allocating
/// space for storing `x` on the heap.
///
/// This can be useful in certain edge-cases related to compiler optimizations.
/// When evaluating for example `bump.alloc(x)`, semantically `x` is first put
/// on the stack and then moved onto the heap. In some cases, the compiler is
/// able to optimize this into constructing `x` directly on the heap, however
/// in many cases it does not.
///
/// The `…alloc_with` functions try to help the compiler be smarter. In most
/// cases doing for example `bump.try_alloc_with(|| x)` on release mode will be
/// enough to help the compiler realize that this optimization is valid and
/// to construct `x` directly onto the heap.
///
/// #### Warning
///
/// These functions critically depend on compiler optimizations to achieve their
/// desired effect. This means that it is not an effective tool when compiling
/// without optimizations on.
///
/// Even when optimizations are on, these functions do not **guarantee** that
/// the value is constructed on the heap. To the best of our knowledge no such
/// guarantee can be made in stable Rust as of 1.54.
///
/// ### Fallible Initialization: The `_try_with` Method Suffix
///
/// The generic [`…alloc_try_with(|| x)`](?search=_try_with) methods behave
/// like the purely `_with` suffixed methods explained above. However, they
/// allow for fallible initialization by accepting a closure that returns a
/// [`Result`] and will attempt to undo the initial allocation if this closure
/// returns [`Err`].
///
/// #### Warning
///
/// If the inner closure returns [`Ok`], space for the entire [`Result`] remains
/// allocated inside `self`. This can be a problem especially if the [`Err`]
/// variant is larger, but even otherwise there may be overhead for the
/// [`Result`]'s discriminant.
///
/// <p><details><summary>Undoing the allocation in the <code>Err</code> case
/// always fails if <code>f</code> successfully made any additional allocations
/// in <code>self</code>.</summary>
///
/// For example, the following will always leak also space for the [`Result`]
/// into this `Bump`, even though the inner reference isn't kept and the [`Err`]
/// payload is returned semantically by value:
///
/// ```rust
/// let bump = bumpalo::Bump::new();
///
/// let r: Result<&mut [u8; 1000], ()> = bump.alloc_try_with(|| {
/// let _ = bump.alloc(0_u8);
/// Err(())
/// });
///
/// assert!(r.is_err());
/// ```
///
///</details></p>
///
/// Since [`Err`] payloads are first placed on the heap and then moved to the
/// stack, `bump.…alloc_try_with(|| x)?` is likely to execute more slowly than
/// the matching `bump.…alloc(x?)` in case of initialization failure. If this
/// happens frequently, using the plain un-suffixed method may perform better.
///
/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
/// [`Ok`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Ok
/// [`Err`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err
///
/// ### `Bump` Allocation Limits
///
/// `bumpalo` supports setting a limit on the maximum bytes of memory that can
/// be allocated for use in a particular `Bump` arena. This limit can be set and removed with
/// [`set_allocation_limit`][Bump::set_allocation_limit].
/// The allocation limit is only enforced when allocating new backing chunks for
/// a `Bump`. Updating the allocation limit will not affect existing allocations
/// or any future allocations within the `Bump`'s current chunk.
///
/// #### Example
///
/// ```
/// let bump = bumpalo::Bump::new();
///
/// assert_eq!(bump.allocation_limit(), None);
/// bump.set_allocation_limit(Some(0));
///
/// assert!(bump.try_alloc(5).is_err());
///
/// bump.set_allocation_limit(Some(6));
///
/// assert_eq!(bump.allocation_limit(), Some(6));
///
/// bump.set_allocation_limit(None);
///
/// assert_eq!(bump.allocation_limit(), None);
/// ```
///
/// #### Warning
///
/// Because of backwards compatibility, allocations that fail
/// due to allocation limits will not present differently than
/// errors due to resource exhaustion.
#[derive(Debug)]
pub struct Bump {
// The current chunk we are bump allocating within.
current_chunk_footer: Cell<NonNull<ChunkFooter>>,
allocation_limit: Cell<Option<usize>>,
}
#[repr(C)]
#[derive(Debug)]
struct ChunkFooter {
// Pointer to the start of this chunk allocation. This footer is always at
// the end of the chunk.
data: NonNull<u8>,
// The layout of this chunk's allocation.
layout: Layout,
// Link to the previous chunk.
//
// Note that the last node in the `prev` linked list is the canonical empty
// chunk, whose `prev` link points to itself.
prev: Cell<NonNull<ChunkFooter>>,
// Bump allocation finger that is always in the range `self.data..=self`.
ptr: Cell<NonNull<u8>>,
// The bytes allocated in all chunks so far, the canonical empty chunk has
// a size of 0 and for all other chunks, `allocated_bytes` will be
// the allocated_bytes of the current chunk plus the allocated bytes
// of the `prev` chunk.
allocated_bytes: usize,
}
/// A wrapper type for the canonical, statically allocated empty chunk.
///
/// For the canonical empty chunk to be `static`, its type must be `Sync`, which
/// is the purpose of this wrapper type. This is safe because the empty chunk is
/// immutable and never actually modified.
#[repr(transparent)]
struct EmptyChunkFooter(ChunkFooter);
unsafe impl Sync for EmptyChunkFooter {}
static EMPTY_CHUNK: EmptyChunkFooter = EmptyChunkFooter(ChunkFooter {
// This chunk is empty (except the foot itself).
layout: Layout::new::<ChunkFooter>(),
// The start of the (empty) allocatable region for this chunk is itself.
data: unsafe { NonNull::new_unchecked(&EMPTY_CHUNK as *const EmptyChunkFooter as *mut u8) },
// The end of the (empty) allocatable region for this chunk is also itself.
ptr: Cell::new(unsafe {
NonNull::new_unchecked(&EMPTY_CHUNK as *const EmptyChunkFooter as *mut u8)
}),
// Invariant: the last chunk footer in all `ChunkFooter::prev` linked lists
// is the empty chunk footer, whose `prev` points to itself.
prev: Cell::new(unsafe {
NonNull::new_unchecked(&EMPTY_CHUNK as *const EmptyChunkFooter as *mut ChunkFooter)
}),
// Empty chunks count as 0 allocated bytes in an arena.
allocated_bytes: 0,
});
impl EmptyChunkFooter {
fn get(&'static self) -> NonNull<ChunkFooter> {
unsafe { NonNull::new_unchecked(&self.0 as *const ChunkFooter as *mut ChunkFooter) }
}
}
impl ChunkFooter {
// Returns the start and length of the currently allocated region of this
// chunk.
fn as_raw_parts(&self) -> (*const u8, usize) {
let data = self.data.as_ptr() as *const u8;
let ptr = self.ptr.get().as_ptr() as *const u8;
debug_assert!(data <= ptr);
debug_assert!(ptr <= self as *const ChunkFooter as *const u8);
let len = unsafe { (self as *const ChunkFooter as *const u8).offset_from(ptr) as usize };
(ptr, len)
}
/// Is this chunk the last empty chunk?
fn is_empty(&self) -> bool {
ptr::eq(self, EMPTY_CHUNK.get().as_ptr())
}
}
impl Default for Bump {
fn default() -> Bump {
Bump::new()
}
}
impl Drop for Bump {
fn drop(&mut self) {
unsafe {
dealloc_chunk_list(self.current_chunk_footer.get());
}
}
}
#[inline]
unsafe fn dealloc_chunk_list(mut footer: NonNull<ChunkFooter>) {
while !footer.as_ref().is_empty() {
let f = footer;
footer = f.as_ref().prev.get();
dealloc(f.as_ref().data.as_ptr(), f.as_ref().layout);
}
}
// `Bump`s are safe to send between threads because nothing aliases its owned
// chunks until you start allocating from it. But by the time you allocate from
// it, the returned references to allocations borrow the `Bump` and therefore
// prevent sending the `Bump` across threads until the borrows end.
unsafe impl Send for Bump {}
#[inline]
pub(crate) fn round_up_to(n: usize, divisor: usize) -> Option<usize> {
debug_assert!(divisor > 0);
debug_assert!(divisor.is_power_of_two());
Some(n.checked_add(divisor - 1)? & !(divisor - 1))
}
#[inline]
pub(crate) fn round_down_to(n: usize, divisor: usize) -> usize {
debug_assert!(divisor > 0);
debug_assert!(divisor.is_power_of_two());
n & !(divisor - 1)
}
// After this point, we try to hit page boundaries instead of powers of 2
const PAGE_STRATEGY_CUTOFF: usize = 0x1000;
// We only support alignments of up to 16 bytes for iter_allocated_chunks.
const SUPPORTED_ITER_ALIGNMENT: usize = 16;
const CHUNK_ALIGN: usize = SUPPORTED_ITER_ALIGNMENT;
const FOOTER_SIZE: usize = mem::size_of::<ChunkFooter>();
// Assert that ChunkFooter is at most the supported alignment. This will give a compile time error if it is not the case
const _FOOTER_ALIGN_ASSERTION: bool = mem::align_of::<ChunkFooter>() <= CHUNK_ALIGN;
const _: [(); _FOOTER_ALIGN_ASSERTION as usize] = [()];
// Maximum typical overhead per allocation imposed by allocators.
const MALLOC_OVERHEAD: usize = 16;
// This is the overhead from malloc, footer and alignment. For instance, if
// we want to request a chunk of memory that has at least X bytes usable for
// allocations (where X is aligned to CHUNK_ALIGN), then we expect that the
// after adding a footer, malloc overhead and alignment, the chunk of memory
// the allocator actually sets aside for us is X+OVERHEAD rounded up to the
// nearest suitable size boundary.
const OVERHEAD: usize = (MALLOC_OVERHEAD + FOOTER_SIZE + (CHUNK_ALIGN - 1)) & !(CHUNK_ALIGN - 1);
// Choose a relatively small default initial chunk size, since we double chunk
// sizes as we grow bump arenas to amortize costs of hitting the global
// allocator.
const FIRST_ALLOCATION_GOAL: usize = 1 << 9;
// The actual size of the first allocation is going to be a bit smaller
// than the goal. We need to make room for the footer, and we also need
// take the alignment into account.
const DEFAULT_CHUNK_SIZE_WITHOUT_FOOTER: usize = FIRST_ALLOCATION_GOAL - OVERHEAD;
/// The memory size and alignment details for a potential new chunk
/// allocation.
#[derive(Debug, Clone, Copy)]
struct NewChunkMemoryDetails {
new_size_without_footer: usize,
align: usize,
size: usize,
}
/// Wrapper around `Layout::from_size_align` that adds debug assertions.
#[inline]
unsafe fn layout_from_size_align(size: usize, align: usize) -> Layout {
if cfg!(debug_assertions) {
Layout::from_size_align(size, align).unwrap()
} else {
Layout::from_size_align_unchecked(size, align)
}
}
#[inline(never)]
fn allocation_size_overflow<T>() -> T {
panic!("requested allocation size overflowed")
}
// This can be migrated to directly use `usize::abs_diff` when the MSRV
// reaches `1.60`
fn abs_diff(a: usize, b: usize) -> usize {
usize::max(a, b) - usize::min(a, b)
}
impl Bump {
/// Construct a new arena to bump allocate into.
///
/// ## Example
///
/// ```
/// let bump = bumpalo::Bump::new();
/// # let _ = bump;
/// ```
pub fn new() -> Bump {
Self::with_capacity(0)
}
/// Attempt to construct a new arena to bump allocate into.
///
/// ## Example
///
/// ```
/// let bump = bumpalo::Bump::try_new();
/// # let _ = bump.unwrap();
/// ```
pub fn try_new() -> Result<Bump, AllocErr> {
Bump::try_with_capacity(0)
}
/// Construct a new arena with the specified byte capacity to bump allocate into.
///
/// ## Example
///
/// ```
/// let bump = bumpalo::Bump::with_capacity(100);
/// # let _ = bump;
/// ```
pub fn with_capacity(capacity: usize) -> Bump {
Bump::try_with_capacity(capacity).unwrap_or_else(|_| oom())
}
/// Attempt to construct a new arena with the specified byte capacity to bump allocate into.
///
/// ## Example
///
/// ```
/// let bump = bumpalo::Bump::try_with_capacity(100);
/// # let _ = bump.unwrap();
/// ```
pub fn try_with_capacity(capacity: usize) -> Result<Self, AllocErr> {
if capacity == 0 {
return Ok(Bump {
current_chunk_footer: Cell::new(EMPTY_CHUNK.get()),
allocation_limit: Cell::new(None),
});
}
let layout = unsafe { layout_from_size_align(capacity, 1) };
let chunk_footer = unsafe {
Self::new_chunk(
Bump::new_chunk_memory_details(None, layout).ok_or(AllocErr)?,
layout,
EMPTY_CHUNK.get(),
)
.ok_or(AllocErr)?
};
Ok(Bump {
current_chunk_footer: Cell::new(chunk_footer),
allocation_limit: Cell::new(None),
})
}
/// The allocation limit for this arena in bytes.
///
/// ## Example
///
/// ```
/// let bump = bumpalo::Bump::with_capacity(0);
///
/// assert_eq!(bump.allocation_limit(), None);
///
/// bump.set_allocation_limit(Some(6));
///
/// assert_eq!(bump.allocation_limit(), Some(6));
///
/// bump.set_allocation_limit(None);
///
/// assert_eq!(bump.allocation_limit(), None);
/// ```
pub fn allocation_limit(&self) -> Option<usize> {
self.allocation_limit.get()
}
/// Set the allocation limit in bytes for this arena.
///
/// The allocation limit is only enforced when allocating new backing chunks for
/// a `Bump`. Updating the allocation limit will not affect existing allocations
/// or any future allocations within the `Bump`'s current chunk.
///
/// ## Example
///
/// ```
/// let bump = bumpalo::Bump::with_capacity(0);
///
/// bump.set_allocation_limit(Some(0));
///
/// assert!(bump.try_alloc(5).is_err());
/// ```
pub fn set_allocation_limit(&self, limit: Option<usize>) {
self.allocation_limit.set(limit)
}
/// How much headroom an arena has before it hits its allocation
/// limit.
fn allocation_limit_remaining(&self) -> Option<usize> {
self.allocation_limit.get().and_then(|allocation_limit| {
let allocated_bytes = self.allocated_bytes();
if allocated_bytes > allocation_limit {
None
} else {
Some(abs_diff(allocation_limit, allocated_bytes))
}
})
}
/// Whether a request to allocate a new chunk with a given size for a given
/// requested layout will fit under the allocation limit set on a `Bump`.
fn chunk_fits_under_limit(
allocation_limit_remaining: Option<usize>,
new_chunk_memory_details: NewChunkMemoryDetails,
) -> bool {
allocation_limit_remaining
.map(|allocation_limit_left| {
allocation_limit_left >= new_chunk_memory_details.new_size_without_footer
})
.unwrap_or(true)
}
/// Determine the memory details including final size, alignment and
/// final size without footer for a new chunk that would be allocated
/// to fulfill an allocation request.
fn new_chunk_memory_details(
new_size_without_footer: Option<usize>,
requested_layout: Layout,
) -> Option<NewChunkMemoryDetails> {
let mut new_size_without_footer =
new_size_without_footer.unwrap_or(DEFAULT_CHUNK_SIZE_WITHOUT_FOOTER);
// We want to have CHUNK_ALIGN or better alignment
let mut align = CHUNK_ALIGN;
// If we already know we need to fulfill some request,
// make sure we allocate at least enough to satisfy it
align = align.max(requested_layout.align());
let requested_size =
round_up_to(requested_layout.size(), align).unwrap_or_else(allocation_size_overflow);
new_size_without_footer = new_size_without_footer.max(requested_size);
// We want our allocations to play nice with the memory allocator,
// and waste as little memory as possible.
// For small allocations, this means that the entire allocation
// including the chunk footer and mallocs internal overhead is
// as close to a power of two as we can go without going over.
// For larger allocations, we only need to get close to a page
// boundary without going over.
if new_size_without_footer < PAGE_STRATEGY_CUTOFF {
new_size_without_footer =
(new_size_without_footer + OVERHEAD).next_power_of_two() - OVERHEAD;
} else {
new_size_without_footer =
round_up_to(new_size_without_footer + OVERHEAD, 0x1000)? - OVERHEAD;
}
debug_assert_eq!(align % CHUNK_ALIGN, 0);
debug_assert_eq!(new_size_without_footer % CHUNK_ALIGN, 0);
let size = new_size_without_footer
.checked_add(FOOTER_SIZE)
.unwrap_or_else(allocation_size_overflow);
Some(NewChunkMemoryDetails {
new_size_without_footer,
size,
align,
})
}
/// Allocate a new chunk and return its initialized footer.
///
/// If given, `layouts` is a tuple of the current chunk size and the
/// layout of the allocation request that triggered us to fall back to
/// allocating a new chunk of memory.
unsafe fn new_chunk(
new_chunk_memory_details: NewChunkMemoryDetails,
requested_layout: Layout,
prev: NonNull<ChunkFooter>,
) -> Option<NonNull<ChunkFooter>> {
let NewChunkMemoryDetails {
new_size_without_footer,
align,
size,
} = new_chunk_memory_details;
let layout = layout_from_size_align(size, align);
debug_assert!(size >= requested_layout.size());
let data = alloc(layout);
let data = NonNull::new(data)?;
// The `ChunkFooter` is at the end of the chunk.
let footer_ptr = data.as_ptr().add(new_size_without_footer);
debug_assert_eq!((data.as_ptr() as usize) % align, 0);
debug_assert_eq!(footer_ptr as usize % CHUNK_ALIGN, 0);
let footer_ptr = footer_ptr as *mut ChunkFooter;
// The bump pointer is initialized to the end of the range we will
// bump out of.
let ptr = Cell::new(NonNull::new_unchecked(footer_ptr as *mut u8));
// The `allocated_bytes` of a new chunk counts the total size
// of the chunks, not how much of the chunks are used.
let allocated_bytes = prev.as_ref().allocated_bytes + new_size_without_footer;
ptr::write(
footer_ptr,
ChunkFooter {
data,
layout,
prev: Cell::new(prev),
ptr,
allocated_bytes,
},
);
Some(NonNull::new_unchecked(footer_ptr))
}
/// Reset this bump allocator.
///
/// Performs mass deallocation on everything allocated in this arena by
/// resetting the pointer into the underlying chunk of memory to the start
/// of the chunk. Does not run any `Drop` implementations on deallocated
/// objects; see [the top-level documentation](struct.Bump.html) for details.
///
/// If this arena has allocated multiple chunks to bump allocate into, then
/// the excess chunks are returned to the global allocator.
///
/// ## Example
///
/// ```
/// let mut bump = bumpalo::Bump::new();
///
/// // Allocate a bunch of things.
/// {
/// for i in 0..100 {
/// bump.alloc(i);
/// }
/// }
///
/// // Reset the arena.
/// bump.reset();
///
/// // Allocate some new things in the space previously occupied by the
/// // original things.
/// for j in 200..400 {
/// bump.alloc(j);
/// }
///```
pub fn reset(&mut self) {
// Takes `&mut self` so `self` must be unique and there can't be any
// borrows active that would get invalidated by resetting.
unsafe {
if self.current_chunk_footer.get().as_ref().is_empty() {
return;
}
let mut cur_chunk = self.current_chunk_footer.get();
// Deallocate all chunks except the current one
let prev_chunk = cur_chunk.as_ref().prev.replace(EMPTY_CHUNK.get());
dealloc_chunk_list(prev_chunk);
// Reset the bump finger to the end of the chunk.
cur_chunk.as_ref().ptr.set(cur_chunk.cast());
// Reset the allocated size of the chunk.
cur_chunk.as_mut().allocated_bytes = cur_chunk.as_ref().layout.size();
debug_assert!(
self.current_chunk_footer
.get()
.as_ref()
.prev
.get()
.as_ref()
.is_empty(),
"We should only have a single chunk"
);
debug_assert_eq!(
self.current_chunk_footer.get().as_ref().ptr.get(),
self.current_chunk_footer.get().cast(),
"Our chunk's bump finger should be reset to the start of its allocation"
);
}
}
/// Allocate an object in this `Bump` and return an exclusive reference to
/// it.
///
/// ## Panics
///
/// Panics if reserving space for `T` fails.
///
/// ## Example
///
/// ```
/// let bump = bumpalo::Bump::new();
/// let x = bump.alloc("hello");
/// assert_eq!(*x, "hello");
/// ```
#[inline(always)]
#[allow(clippy::mut_from_ref)]
pub fn alloc<T>(&self, val: T) -> &mut T {
self.alloc_with(|| val)
}
/// Try to allocate an object in this `Bump` and return an exclusive
/// reference to it.
///
/// ## Errors
///
/// Errors if reserving space for `T` fails.
///
/// ## Example
///
/// ```
/// let bump = bumpalo::Bump::new();
/// let x = bump.try_alloc("hello");
/// assert_eq!(x, Ok(&mut "hello"));
/// ```
#[inline(always)]
#[allow(clippy::mut_from_ref)]
pub fn try_alloc<T>(&self, val: T) -> Result<&mut T, AllocErr> {
self.try_alloc_with(|| val)
}
/// Pre-allocate space for an object in this `Bump`, initializes it using
/// the closure, then returns an exclusive reference to it.
///
/// See [The `_with` Method Suffix](#initializer-functions-the-_with-method-suffix) for a
/// discussion on the differences between the `_with` suffixed methods and
/// those methods without it, their performance characteristics, and when
/// you might or might not choose a `_with` suffixed method.
///
/// ## Panics
///
/// Panics if reserving space for `T` fails.
///
/// ## Example
///
/// ```
/// let bump = bumpalo::Bump::new();
/// let x = bump.alloc_with(|| "hello");
/// assert_eq!(*x, "hello");
/// ```
#[inline(always)]
#[allow(clippy::mut_from_ref)]
pub fn alloc_with<F, T>(&self, f: F) -> &mut T
where
F: FnOnce() -> T,
{
#[inline(always)]
unsafe fn inner_writer<T, F>(ptr: *mut T, f: F)
where
F: FnOnce() -> T,
{
// This function is translated as:
// - allocate space for a T on the stack
// - call f() with the return value being put onto this stack space
// - memcpy from the stack to the heap
//
// Ideally we want LLVM to always realize that doing a stack
// allocation is unnecessary and optimize the code so it writes
// directly into the heap instead. It seems we get it to realize
// this most consistently if we put this critical line into it's
// own function instead of inlining it into the surrounding code.
ptr::write(ptr, f())
}
let layout = Layout::new::<T>();
unsafe {
let p = self.alloc_layout(layout);
let p = p.as_ptr() as *mut T;
inner_writer(p, f);
&mut *p
}
}
/// Tries to pre-allocate space for an object in this `Bump`, initializes
/// it using the closure, then returns an exclusive reference to it.
///
/// See [The `_with` Method Suffix](#initializer-functions-the-_with-method-suffix) for a
/// discussion on the differences between the `_with` suffixed methods and
/// those methods without it, their performance characteristics, and when
/// you might or might not choose a `_with` suffixed method.
///
/// ## Errors
///
/// Errors if reserving space for `T` fails.
///
/// ## Example
///
/// ```
/// let bump = bumpalo::Bump::new();
/// let x = bump.try_alloc_with(|| "hello");
/// assert_eq!(x, Ok(&mut "hello"));
/// ```
#[inline(always)]
#[allow(clippy::mut_from_ref)]
pub fn try_alloc_with<F, T>(&self, f: F) -> Result<&mut T, AllocErr>
where
F: FnOnce() -> T,
{
#[inline(always)]
unsafe fn inner_writer<T, F>(ptr: *mut T, f: F)
where
F: FnOnce() -> T,
{
// This function is translated as:
// - allocate space for a T on the stack
// - call f() with the return value being put onto this stack space
// - memcpy from the stack to the heap
//
// Ideally we want LLVM to always realize that doing a stack
// allocation is unnecessary and optimize the code so it writes
// directly into the heap instead. It seems we get it to realize
// this most consistently if we put this critical line into it's
// own function instead of inlining it into the surrounding code.
ptr::write(ptr, f())
}
//SAFETY: Self-contained:
// `p` is allocated for `T` and then a `T` is written.
let layout = Layout::new::<T>();
let p = self.try_alloc_layout(layout)?;
let p = p.as_ptr() as *mut T;
unsafe {
inner_writer(p, f);
Ok(&mut *p)
}
}
/// Pre-allocates space for a [`Result`] in this `Bump`, initializes it using
/// the closure, then returns an exclusive reference to its `T` if [`Ok`].
///
/// Iff the allocation fails, the closure is not run.
///
/// Iff [`Err`], an allocator rewind is *attempted* and the `E` instance is
/// moved out of the allocator to be consumed or dropped as normal.
///
/// See [The `_with` Method Suffix](#initializer-functions-the-_with-method-suffix) for a
/// discussion on the differences between the `_with` suffixed methods and
/// those methods without it, their performance characteristics, and when
/// you might or might not choose a `_with` suffixed method.
///
/// For caveats specific to fallible initialization, see
/// [The `_try_with` Method Suffix](#fallible-initialization-the-_try_with-method-suffix).
///
/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
/// [`Ok`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Ok
/// [`Err`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err
///
/// ## Errors
///
/// Iff the allocation succeeds but `f` fails, that error is forwarded by value.
///
/// ## Panics
///
/// Panics if reserving space for `Result<T, E>` fails.
///
/// ## Example
///
/// ```
/// let bump = bumpalo::Bump::new();
/// let x = bump.alloc_try_with(|| Ok("hello"))?;
/// assert_eq!(*x, "hello");
/// # Result::<_, ()>::Ok(())
/// ```
#[inline(always)]
#[allow(clippy::mut_from_ref)]
pub fn alloc_try_with<F, T, E>(&self, f: F) -> Result<&mut T, E>
where
F: FnOnce() -> Result<T, E>,
{
let rewind_footer = self.current_chunk_footer.get();
let rewind_ptr = unsafe { rewind_footer.as_ref() }.ptr.get();
let mut inner_result_ptr = NonNull::from(self.alloc_with(f));
match unsafe { inner_result_ptr.as_mut() } {
Ok(t) => Ok(unsafe {
//SAFETY:
// The `&mut Result<T, E>` returned by `alloc_with` may be
// lifetime-limited by `E`, but the derived `&mut T` still has
// the same validity as in `alloc_with` since the error variant
// is already ruled out here.
// We could conditionally truncate the allocation here, but
// since it grows backwards, it seems unlikely that we'd get
// any more than the `Result`'s discriminant this way, if
// anything at all.
&mut *(t as *mut _)
}),
Err(e) => unsafe {
// If this result was the last allocation in this arena, we can
// reclaim its space. In fact, sometimes we can do even better
// than simply calling `dealloc` on the result pointer: we can
// reclaim any alignment padding we might have added (which