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
#![cfg_attr(not(doctest), no_std)]
extern crate alloc;
use alloc::alloc::{alloc as alloc_raw, handle_alloc_error, Layout};
use alloc::boxed::Box;
use core::ptr;
pub use default_boxed_derive::DefaultBoxed;
pub trait DefaultBoxed {
fn default_boxed() -> Box<Self>
where
Self: Sized,
{
let layout = Layout::new::<Self>();
unsafe {
if layout.size() == 0 {
return Box::from_raw(ptr::NonNull::<Self>::dangling().as_ptr());
}
let raw = alloc_raw(layout) as *mut Self;
if raw.is_null() {
handle_alloc_error(layout)
} else {
Self::default_in_place(raw);
Box::from_raw(raw)
}
}
}
unsafe fn default_in_place(ptr: *mut Self);
}
impl<T: Default> DefaultBoxed for T {
unsafe fn default_in_place(ptr: *mut Self) {
ptr::write(ptr, Default::default());
}
}