summary refs log tree commit diff
path: root/tests/ui/drop/box-conditional-drop-allocator.rs
blob: 8f78da16473e72008770db42040a8244d21f3cfb (plain)
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
//@ run-pass
#![feature(allocator_api)]

// Regression test for #131082.
// Testing that the allocator of a Box is dropped in conditional drops

use std::alloc::{AllocError, Allocator, Global, Layout};
use std::cell::Cell;
use std::ptr::NonNull;

struct DropCheckingAllocator<'a>(&'a Cell<bool>);

unsafe impl Allocator for DropCheckingAllocator<'_> {
    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
        Global.allocate(layout)
    }
    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
        Global.deallocate(ptr, layout);
    }
}
impl Drop for DropCheckingAllocator<'_> {
    fn drop(&mut self) {
        self.0.set(true);
    }
}

struct HasDrop;
impl Drop for HasDrop {
    fn drop(&mut self) {}
}

fn main() {
    let dropped = Cell::new(false);
    {
        let b = Box::new_in(HasDrop, DropCheckingAllocator(&dropped));
        if true {
            drop(*b);
        } else {
            drop(b);
        }
    }
    assert!(dropped.get());
}