File: leak_box.rs

package info (click to toggle)
rust-static-alloc 0.2.5-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 284 kB
  • sloc: makefile: 4
file content (69 lines) | stat: -rw-r--r-- 1,935 bytes parent folder | download
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
use core::{cell::RefCell, mem::MaybeUninit};
use static_alloc::{Bump, leaked::LeakBox};

#[test]
fn leak_box_drops() {
    let bump: Bump<[*const (); 4]> = Bump::uninit();
    let cell = RefCell::new(());
    assert!(cell.try_borrow().is_ok());

    let _ = bump.leak_box(cell.borrow()).unwrap();
    assert!(cell.try_borrow().is_ok(), "Immediately dropped it");
    assert!(cell.try_borrow_mut().is_ok(), "Immediately dropped it");

    let leak_box = bump.leak_box(cell.borrow()).unwrap();
    assert!(cell.try_borrow().is_ok(), "Borrow works, of course");
    assert!(cell.try_borrow_mut().is_err(), "Still borrowed");
    drop(leak_box);

    assert!(cell.try_borrow_mut().is_ok(), "No longer borrowed");
}

#[test]
fn leaking() {
    struct PanicOnDrop(usize);
    impl Drop for PanicOnDrop {
        fn drop(&mut self) {
            panic!("Do not drop me.");
        }
    }

    let bump: Bump<[usize; 1]> = Bump::uninit();
    let leak_box = bump.leak_box(PanicOnDrop(0)).unwrap();
    core::mem::forget(leak_box);
    // Panic averted.
}

#[test]
fn init() {
    let bump: Bump<[usize; 1]> = Bump::uninit();
    let leak_box = bump.leak_box(MaybeUninit::uninit()).unwrap();
    let init = LeakBox::write(leak_box, 0usize);
    assert_eq!(*init, 0usize);
}

#[test]
fn trait_impls() {
    let mut memory = MaybeUninit::uninit();
    let mut leak_box = LeakBox::write(LeakBox::from(&mut memory), 0usize);

    // AsMut and AsRef
    *leak_box.as_mut() = 1;
    assert_eq!(1usize, *leak_box.as_ref());
    // Deref and DerefMut
    *leak_box = 2;
    assert_eq!(2usize, *leak_box);
    // Debug, Display, Pointer
    println!("{:?}", leak_box);
    println!("{}", leak_box);
    println!("{:p}", leak_box);
}

#[test]
fn questionable_copy() {
    let mut value = 0;
    let mut quote_leak_box_unquote = LeakBox::from_mut(&mut value);
    *quote_leak_box_unquote = 1;
    drop(quote_leak_box_unquote);
    assert_eq!(value, 1)
}