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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#![cfg_attr(feature = "cargo-clippy", allow(clippy::cargo))]
#![cfg_attr(feature = "cargo-clippy", allow(clippy::complexity))]
#![cfg_attr(feature = "cargo-clippy", allow(clippy::correctness))]
#![cfg_attr(feature = "cargo-clippy", allow(clippy::pedantic))]
#![cfg_attr(feature = "cargo-clippy", allow(clippy::perf))]
#![cfg_attr(feature = "cargo-clippy", allow(clippy::style))]
#![cfg_attr(feature = "cargo-clippy", feature(tool_lints))]
#[cfg(test)]
extern crate quickcheck;
#[deny(bad_style)]
#[deny(future_incompatible)]
#[deny(missing_docs)]
#[deny(nonstandard_style)]
#[deny(rust_2018_compatibility)]
#[deny(rust_2018_idioms)]
#[deny(unused)]
#[deny(warnings)]
pub mod fuzz;
use std::alloc::{GlobalAlloc, Layout};
use std::ptr;
use std::sync::atomic::{AtomicUsize, Ordering};
pub const TOTAL_BYTES: usize = 500_000_000; static mut HEAP: [u8; TOTAL_BYTES] = [0; TOTAL_BYTES];
pub struct BumpAlloc {
offset: AtomicUsize,
}
unsafe impl Sync for BumpAlloc {}
trait ConstInit {
const INIT: Self;
}
impl ConstInit for BumpAlloc {
const INIT: BumpAlloc = BumpAlloc {
offset: AtomicUsize::new(0),
};
}
impl BumpAlloc {
pub const INIT: Self = <Self as ConstInit>::INIT;
}
fn round_to_multiple_of(val: usize, align: usize) -> usize {
if align == 0 {
return val;
}
let rem = val % align;
if rem == 0 {
val
} else {
(val + align) - rem
}
}
unsafe impl GlobalAlloc for BumpAlloc {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let alignment = layout.align();
let byte_size: usize = round_to_multiple_of(layout.size() as usize, alignment);
let mut offset = self.offset.load(Ordering::Relaxed);
loop {
let end = offset + byte_size;
if end >= TOTAL_BYTES {
return ptr::null_mut();
} else {
match self.offset.compare_exchange_weak(
offset,
end,
Ordering::Acquire,
Ordering::Relaxed,
) {
Ok(_) => {
return HEAP[offset..end].as_mut_ptr() as *mut u8;
}
Err(cur) => {
offset = cur;
}
}
}
}
}
unsafe fn dealloc(&self, _: *mut u8, _: Layout) {
}
}
#[cfg(test)]
mod test {
use super::*;
use quickcheck::{QuickCheck, TestResult};
#[test]
fn round_up_test_always_greater_equal() {
fn inner(val: usize, align: usize) -> TestResult {
let ret = round_to_multiple_of(val, align);
TestResult::from_bool(ret >= val)
}
QuickCheck::new().quickcheck(inner as fn(usize, usize) -> TestResult);
}
}