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
#![no_std]
#![feature(const_generics)]
#![allow(incomplete_features)]
mod fallback_alloc;
mod null_alloc;
mod segregate_alloc;
use alloc::alloc::{AllocErr, AllocInit, AllocRef, Layout, MemoryBlock, ReallocPlacement};
use core::{mem, ptr};
pub use self::{
fallback_alloc::FallbackAlloc,
null_alloc::NullAlloc,
segregate_alloc::SegregateAlloc,
};
pub trait Owns {
fn owns(&self, memory: &MemoryBlock) -> bool;
}
unsafe fn grow<A1: AllocRef, A2: AllocRef>(
a1: A1,
a2: A2,
memory: &mut MemoryBlock,
new_size: usize,
placement: ReallocPlacement,
init: AllocInit,
) -> Result<(), AllocErr> {
if placement == ReallocPlacement::MayMove {
let new_layout = Layout::from_size_align_unchecked(new_size, memory.align());
let new_memory = a2.alloc(new_layout, init)?;
ptr::copy_nonoverlapping(
memory.ptr().as_ptr(),
new_memory.ptr().as_ptr(),
memory.size(),
);
a1.dealloc(mem::replace(memory, new_memory));
Ok(())
} else {
Err(AllocErr)
}
}
unsafe fn shrink<A1: AllocRef, A2: AllocRef>(
a1: A1,
a2: A2,
memory: &mut MemoryBlock,
new_size: usize,
placement: ReallocPlacement,
) -> Result<(), AllocErr> {
if placement == ReallocPlacement::MayMove {
let new_layout = Layout::from_size_align_unchecked(new_size, memory.align());
let new_memory = a2.alloc(new_layout, AllocInit::Uninitialized)?;
ptr::copy_nonoverlapping(
memory.ptr().as_ptr(),
new_memory.ptr().as_ptr(),
new_memory.size(),
);
a1.dealloc(mem::replace(memory, new_memory));
Ok(())
} else {
Err(AllocErr)
}
}