bump_scope/
bump_align_guard.rs

1use crate::{BumpScope, MinimumAlignment, SupportedMinimumAlignment, align_pos};
2
3/// Aligns the bump pointer on drop.
4///
5/// This is useful in unsafe contexts where the alignment is changed and we have to change it back.
6/// The `BumpScope` is in an invalid state when the bump pointer alignment does not match `MIN_ALIGN`.
7/// So `drop` ***must*** be called to return the bump scope to a valid state.
8pub(crate) struct BumpAlignGuard<
9    'b,
10    'a,
11    A,
12    const MIN_ALIGN: usize,
13    const UP: bool,
14    const GUARANTEED_ALLOCATED: bool,
15    const DEALLOCATES: bool,
16> where
17    MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
18{
19    pub(crate) scope: &'b mut BumpScope<'a, A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED, DEALLOCATES>,
20}
21
22impl<A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool, const DEALLOCATES: bool> Drop
23    for BumpAlignGuard<'_, '_, A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED, DEALLOCATES>
24where
25    MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
26{
27    #[inline(always)]
28    fn drop(&mut self) {
29        if let Some(chunk) = self.scope.chunk.get().guaranteed_allocated() {
30            let pos = chunk.pos().addr();
31            let addr = align_pos::<MIN_ALIGN, UP>(pos);
32            unsafe { chunk.set_pos_addr(addr) };
33        }
34    }
35}
36
37impl<'b, 'a, A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool, const DEALLOCATES: bool>
38    BumpAlignGuard<'b, 'a, A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED, DEALLOCATES>
39where
40    MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
41{
42    #[inline(always)]
43    pub(crate) fn new(scope: &'b mut BumpScope<'a, A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED, DEALLOCATES>) -> Self {
44        Self { scope }
45    }
46}