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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
use crate::Owns;
use core::{
    alloc::{AllocErr, AllocInit, AllocRef, Layout, MemoryBlock, ReallocPlacement},
    ptr::NonNull,
};

/// Marks newly allocated and deallocated memory with a byte pattern.
///
/// When allocating unintitialized memory, the block is set to `0xCD`. Before deallocating,
/// the memory is set `0xDD`.
/// Those values are choosed according to [Magic Debug Values] to match the Visual
/// Studio Debug Heap implementation.
///
/// Once, `const_generics` allows default implementations, the values may be alterd with a parameter.
///
/// [Magic Debug Values]: https://en.wikipedia.org/wiki/Magic_number_%28programming%29#Magic_debug_values
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
pub struct ChunkAlloc<A, const SIZE: usize>(pub A);

impl<A, const SIZE: usize> ChunkAlloc<A, SIZE> {
    const fn assert_alignment() {
        assert!(usize::is_power_of_two(SIZE), "SIZE must be a power of two");
    }

    const fn next_multiple(size: usize) -> usize {
        ((size + SIZE - 1) / SIZE) * SIZE
    }
}

unsafe impl<A: AllocRef, const SIZE: usize> AllocRef for ChunkAlloc<A, SIZE> {
    fn alloc(&mut self, layout: Layout, init: AllocInit) -> Result<MemoryBlock, AllocErr> {
        Self::assert_alignment();
        self.0.alloc(
            unsafe {
                Layout::from_size_align_unchecked(
                    Self::next_multiple(layout.size()),
                    layout.align(),
                )
            },
            init,
        )
    }
    unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
        self.0.dealloc(
            ptr,
            Layout::from_size_align_unchecked(Self::next_multiple(layout.size()), layout.align()),
        )
    }
    unsafe fn grow(
        &mut self,
        ptr: NonNull<u8>,
        layout: Layout,
        new_size: usize,
        placement: ReallocPlacement,
        init: AllocInit,
    ) -> Result<MemoryBlock, AllocErr> {
        let next_multiple = Self::next_multiple(layout.size());
        if new_size <= next_multiple {
            return Ok(MemoryBlock {
                ptr,
                size: next_multiple,
            });
        }

        self.0.grow(
            ptr,
            Layout::from_size_align_unchecked(next_multiple, layout.align()),
            Self::next_multiple(new_size),
            placement,
            init,
        )
    }
    unsafe fn shrink(
        &mut self,
        ptr: NonNull<u8>,
        layout: Layout,
        new_size: usize,
        placement: ReallocPlacement,
    ) -> Result<MemoryBlock, AllocErr> {
        let next_multiple = Self::next_multiple(layout.size());
        let previous_multiple = next_multiple - SIZE;
        if new_size > previous_multiple {
            return Ok(MemoryBlock {
                ptr,
                size: next_multiple,
            });
        }

        self.0.shrink(
            ptr,
            Layout::from_size_align_unchecked(next_multiple, layout.align()),
            Self::next_multiple(new_size),
            placement,
        )
    }
}

impl<A: Owns, const SIZE: usize> Owns for ChunkAlloc<A, SIZE> {
    fn owns(&self, memory: MemoryBlock) -> bool {
        self.0.owns(memory)
    }
}

#[cfg(test)]
mod tests {
    use super::ChunkAlloc;
    use crate::helper;
    use std::alloc::{AllocInit, AllocRef, Layout, ReallocPlacement, System};

    #[test]
    fn alloc() {
        let mut alloc = helper::tracker(ChunkAlloc::<_, 64>(System));
        let memory = alloc
            .alloc(Layout::new::<u8>(), AllocInit::Uninitialized)
            .expect("Could not allocate 64 bytes");
        assert_eq!(memory.size % 64, 0);
        assert!(memory.size >= 64);

        unsafe {
            alloc.dealloc(memory.ptr, Layout::new::<u8>());
        }
    }

    #[test]
    fn dealloc() {
        let mut alloc = helper::tracker(ChunkAlloc::<_, 64>(System));

        unsafe {
            let memory = alloc
                .alloc(Layout::new::<[u8; 4]>(), AllocInit::Uninitialized)
                .expect("Could not allocate 4 bytes");
            assert_eq!(memory.size % 64, 0);
            alloc.dealloc(memory.ptr, Layout::new::<[u8; 4]>());

            let memory = alloc
                .alloc(Layout::new::<[u8; 4]>(), AllocInit::Uninitialized)
                .expect("Could not allocate 4 bytes");
            assert_eq!(memory.size % 64, 0);
            alloc.dealloc(memory.ptr, Layout::new::<[u8; 32]>());

            let memory = alloc
                .alloc(Layout::new::<[u8; 4]>(), AllocInit::Uninitialized)
                .expect("Could not allocate 4 bytes");
            assert_eq!(memory.size % 64, 0);
            alloc.dealloc(memory.ptr, Layout::new::<[u8; 64]>());

            let memory = alloc
                .alloc(Layout::new::<[u8; 4]>(), AllocInit::Uninitialized)
                .expect("Could not allocate 4 bytes");
            assert_eq!(memory.size % 64, 0);
            alloc.dealloc(memory.ptr, Layout::new::<[u8; 64]>());
        }
    }

    #[test]
    fn grow() {
        let mut alloc = helper::tracker(ChunkAlloc::<_, 64>(System));

        unsafe {
            let memory = alloc
                .alloc(Layout::new::<[u8; 4]>(), AllocInit::Uninitialized)
                .expect("Could not allocate 4 bytes");
            assert_eq!(memory.size % 64, 0);

            let memory = alloc
                .grow(
                    memory.ptr,
                    Layout::new::<[u8; 4]>(),
                    8,
                    ReallocPlacement::InPlace,
                    AllocInit::Uninitialized,
                )
                .expect("Could not grow to 8 bytes");
            assert_eq!(memory.size % 64, 0);
            assert!(memory.size >= 64);

            let memory = alloc
                .grow(
                    memory.ptr,
                    Layout::new::<[u8; 8]>(),
                    64,
                    ReallocPlacement::InPlace,
                    AllocInit::Uninitialized,
                )
                .expect("Could not grow to 64 bytes");
            assert_eq!(memory.size % 64, 0);
            assert!(memory.size >= 64);

            alloc
                .grow(
                    memory.ptr,
                    Layout::new::<[u8; 64]>(),
                    65,
                    ReallocPlacement::InPlace,
                    AllocInit::Uninitialized,
                )
                .expect_err("Could grow to 65 bytes in place");

            alloc.dealloc(memory.ptr, Layout::new::<[u8; 64]>());
        }
    }

    #[test]
    fn shrink() {
        let mut alloc = helper::tracker(ChunkAlloc::<_, 64>(System));

        unsafe {
            let memory = alloc
                .alloc(Layout::new::<[u8; 128]>(), AllocInit::Uninitialized)
                .expect("Could not allocate 128 bytes");
            assert_eq!(memory.size % 64, 0);

            let memory = alloc
                .shrink(
                    memory.ptr,
                    Layout::new::<[u8; 128]>(),
                    100,
                    ReallocPlacement::InPlace,
                )
                .expect("Could not shrink to 100 bytes");
            assert_eq!(memory.size % 64, 0);
            assert!(memory.size >= 128);

            let memory = alloc
                .shrink(
                    memory.ptr,
                    Layout::new::<[u8; 100]>(),
                    65,
                    ReallocPlacement::InPlace,
                )
                .expect("Could not shrink to 65 bytes");
            assert_eq!(memory.size % 64, 0);
            assert!(memory.size >= 128);

            alloc
                .shrink(
                    memory.ptr,
                    Layout::new::<[u8; 65]>(),
                    64,
                    ReallocPlacement::InPlace,
                )
                .expect_err("Could shrink to 64 bytes in place");

            alloc.dealloc(memory.ptr, Layout::new::<[u8; 65]>());
        }
    }
}