safe_allocator_api/
raw_alloc.rs

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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! A safe wrapper around low-level allocation primitives from `alloc::alloc`.
//!
//! This crate provides a safe interface for working with raw allocations while maintaining
//! the same error handling semantics as the underlying allocation APIs.
use core::ptr::NonNull;
use core::{alloc::Layout, fmt};

use allocator_api2::alloc::{AllocError, Allocator, Global};

/// A safe wrapper around a raw allocation with known layout.
///
/// # Safety
///
/// This type ensures that:
/// - The wrapped pointer is always non-null and properly aligned
/// - Memory is automatically deallocated when dropped
/// - Reallocation maintains proper alignment and size constraints
///
/// # Example
///
/// ```rust
/// # use core::alloc::Layout;
/// use safe_alloc::RawAlloc;
///
/// // Create a new allocation of 1024 bytes
/// let layout = Layout::array::<u8>(1024).unwrap();
/// let mut alloc = RawAlloc::new(layout).expect("allocation failed");
///
/// // Write some data
/// unsafe {
///     core::ptr::write(alloc.as_mut_ptr(), 42u8);
/// }
///
/// // Automatically deallocated when dropped
/// ```
pub struct RawAlloc<A: Allocator = Global> {
    ptr: NonNull<[u8]>,
    layout: Layout,
    allocator: A,
}

impl<A: Allocator> RawAlloc<A> {
    /// Creates a new allocation with the given layout using the provided allocator.
    ///
    /// This is equivalent to calling [`Allocator::allocate`] but provides automatic
    /// cleanup when the allocation is no longer needed.
    ///
    /// # Arguments
    ///
    /// * `layout` - The desired memory layout
    /// * `allocator` - The allocator to use
    ///
    /// # Errors
    ///
    /// Returns [`AllocError`] if the allocator reports an error or if the layout
    /// has a size of 0.
    ///
    /// # Example
    ///
    /// ```rust
    /// #![feature(allocator_api)]
    ///
    /// use core::alloc::Layout;
    /// use std::alloc::Global;
    /// use safe_alloc::RawAlloc;
    ///
    /// let layout = Layout::new::<u64>();
    /// let alloc = RawAlloc::new_in(layout, Global)?;
    /// # Ok::<_, core::alloc::AllocError>(())
    /// ```
    pub fn new_in(layout: Layout, allocator: A) -> Result<Self, AllocError> {
        if layout.size() == 0 {
            return Err(AllocError);
        }

        let ptr = allocator.allocate(layout)?;

        Ok(Self {
            ptr,
            layout,
            allocator,
        })
    }

    /// Creates a new zeroed allocation with the given layout using the provided allocator.
    ///
    /// This is equivalent to calling [`Allocator::allocate_zeroed`] but provides automatic
    /// cleanup when the allocation is no longer needed.
    ///
    /// # Errors
    ///
    /// Returns [`AllocError`] if the allocator reports an error or if the layout
    /// has a size of 0.
    pub fn new_zeroed_in(layout: Layout, allocator: A) -> Result<Self, AllocError> {
        if layout.size() == 0 {
            return Err(AllocError);
        }

        let ptr = allocator.allocate_zeroed(layout)?;

        Ok(Self {
            ptr,
            layout,
            allocator,
        })
    }

    /// Attempts to grow the allocation to the new layout.
    ///
    /// # Errors
    ///
    /// Returns [`AllocError`] if:
    /// - The allocator reports an error
    /// - The new layout has a size of 0
    /// - The new size is smaller than the current size (use [`Self::shrink`] instead)
    ///
    /// # Example
    ///
    /// ```rust
    /// #![feature(allocator_api)]
    /// use core::alloc::Layout;
    /// use safe_alloc::RawAlloc;
    ///
    /// let layout = Layout::array::<u8>(100).unwrap();
    /// let mut alloc = RawAlloc::new(layout)?;
    ///
    /// // Grow the allocation
    /// let new_layout = Layout::array::<u8>(200).unwrap();
    /// alloc.grow(new_layout)?;
    /// # Ok::<_, core::alloc::AllocError>(())
    /// ```
    pub fn grow(&mut self, new_layout: Layout) -> Result<(), AllocError> {
        if new_layout.size() == 0 {
            return Err(AllocError);
        }
        if new_layout.size() <= self.layout.size() {
            return Err(AllocError);
        }

        let new_ptr = unsafe {
            self.allocator.grow(
                NonNull::new_unchecked(self.ptr.as_ptr() as *mut u8),
                self.layout,
                new_layout,
            )?
        };

        self.ptr = new_ptr;
        self.layout = new_layout;
        Ok(())
    }

    /// Attempts to grow the allocation to the new layout, zeroing the additional memory.
    ///
    /// This is equivalent to [`Self::grow`] but ensures any additional memory is zeroed.
    ///
    /// # Errors
    ///
    /// Returns [`AllocError`] if:
    /// - The allocator reports an error
    /// - The new layout has a size of 0
    /// - The new size is smaller than the current size (use [`Self::shrink`] instead)
    pub fn grow_zeroed(&mut self, new_layout: Layout) -> Result<(), AllocError> {
        if new_layout.size() == 0 {
            return Err(AllocError);
        }
        if new_layout.size() <= self.layout.size() {
            return Err(AllocError);
        }

        let new_ptr = unsafe {
            self.allocator.grow_zeroed(
                NonNull::new_unchecked(self.ptr.as_ptr() as *mut u8),
                self.layout,
                new_layout,
            )?
        };

        self.ptr = new_ptr;
        self.layout = new_layout;
        Ok(())
    }

    /// Attempts to shrink the allocation to the new layout.
    ///
    /// # Errors
    ///
    /// Returns [`AllocError`] if:
    /// - The allocator reports an error
    /// - The new layout has a size of 0
    /// - The new size is larger than the current size (use [`Self::grow`] instead)
    ///
    /// # Example
    ///
    /// ```rust
    /// #![feature(allocator_api)]
    /// use core::alloc::Layout;
    /// use safe_alloc::RawAlloc;
    ///
    /// let layout = Layout::array::<u8>(200).unwrap();
    /// let mut alloc = RawAlloc::new(layout)?;
    ///
    /// // Shrink the allocation
    /// let new_layout = Layout::array::<u8>(100).unwrap();
    /// alloc.shrink(new_layout)?;
    /// # Ok::<_, core::alloc::AllocError>(())
    /// ```
    pub fn shrink(&mut self, new_layout: Layout) -> Result<(), AllocError> {
        if new_layout.size() == 0 {
            return Err(AllocError);
        }
        if new_layout.size() >= self.layout.size() {
            return Err(AllocError);
        }

        let new_ptr = unsafe {
            self.allocator.shrink(
                NonNull::new_unchecked(self.ptr.as_ptr() as *mut u8),
                self.layout,
                new_layout,
            )?
        };

        self.ptr = new_ptr;
        self.layout = new_layout;
        Ok(())
    }

    /// Returns a raw pointer to the allocated memory.
    ///
    /// # Safety
    ///
    /// The caller must ensure that the memory is accessed according to
    /// the original layout constraints.
    pub fn as_ptr(&self) -> *const u8 {
        self.ptr.as_ptr() as *const u8
    }

    /// Returns a raw mutable pointer to the allocated memory.
    ///
    /// # Safety
    ///
    /// The caller must ensure that the memory is accessed according to
    /// the original layout constraints.
    pub fn as_mut_ptr(&mut self) -> *mut u8 {
        self.ptr.as_ptr() as *mut u8
    }

    /// Returns the layout used for this allocation.
    pub fn layout(&self) -> Layout {
        self.layout
    }
}

impl<A: Allocator> Drop for RawAlloc<A> {
    fn drop(&mut self) {
        unsafe {
            self.allocator.deallocate(
                NonNull::new_unchecked(self.ptr.as_ptr() as *mut u8),
                self.layout,
            );
        }
    }
}

impl<A: Allocator> fmt::Debug for RawAlloc<A> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RawAlloc")
            .field("ptr", &self.ptr)
            .field("layout", &self.layout)
            .finish()
    }
}

// Convenience constructors using the Global allocator
impl RawAlloc {
    /// Creates a new allocation with the given layout using the global allocator.
    ///
    /// This is equivalent to calling [`Self::new_in`] with the global allocator.
    pub fn new(layout: Layout) -> Result<Self, AllocError> {
        Self::new_in(layout, Global)
    }

    /// Creates a new zeroed allocation with the given layout using the global allocator.
    ///
    /// This is equivalent to calling [`Self::new_zeroed_in`] with the global allocator.
    pub fn new_zeroed(layout: Layout) -> Result<Self, AllocError> {
        Self::new_zeroed_in(layout, Global)
    }
}

// Cannot implement Send + Sync automatically due to the raw pointer
// Users must opt-in by implementing these traits based on their usage
unsafe impl<A: Allocator> Send for RawAlloc<A> {}
unsafe impl<A: Allocator> Sync for RawAlloc<A> {}

#[cfg(test)]
mod tests {
    use super::*;
    use core::mem::size_of;

    #[test]
    fn zero_sized_alloc_returns_error() {
        let layout = Layout::from_size_align(0, 1).unwrap();
        assert!(RawAlloc::new(layout).is_err());
    }

    #[test]
    fn basic_alloc_and_write() {
        let layout = Layout::new::<u32>();
        let mut alloc = RawAlloc::new(layout).unwrap();

        unsafe {
            core::ptr::write(alloc.as_mut_ptr() as *mut u32, 0xDEADBEEF);
            assert_eq!(core::ptr::read(alloc.as_ptr() as *const u32), 0xDEADBEEF);
        }
    }

    #[test]
    fn zeroed_allocation() {
        let size = 1024;
        let layout = Layout::array::<u8>(size).unwrap();
        let alloc = RawAlloc::new_zeroed(layout).unwrap();

        unsafe {
            let slice = core::slice::from_raw_parts(alloc.as_ptr(), size);
            assert!(slice.iter().all(|&x| x == 0));
        }
    }

    #[test]
    fn custom_allocator() {
        let layout = Layout::new::<i32>();
        let alloc = RawAlloc::new_in(layout, Global).unwrap();
        assert_eq!(alloc.layout().size(), size_of::<i32>());
    }

    #[test]
    fn array_allocation() {
        let elements = 100;
        let layout = Layout::array::<u64>(elements).unwrap();
        let mut alloc = RawAlloc::new(layout).unwrap();

        unsafe {
            let slice = core::slice::from_raw_parts_mut(alloc.as_mut_ptr() as *mut u64, elements);

            for (i, item) in slice.iter_mut().enumerate() {
                *item = i as u64;
            }

            assert_eq!(slice[42], 42);
        }
    }

    #[test]
    fn alignment_requirements() {
        let align = 64; // Test a large alignment
        let size = 128;
        let layout = Layout::from_size_align(size, align).unwrap();
        let alloc = RawAlloc::new(layout).unwrap();

        let addr = alloc.as_ptr() as usize;
        assert_eq!(addr % align, 0, "Allocation not properly aligned");
    }

    #[test]
    fn multiple_allocations() {
        let layout = Layout::new::<u8>();
        let mut allocations = Vec::new();

        // Create many allocations to stress the allocator
        for i in 0..100 {
            let mut alloc = RawAlloc::new(layout).unwrap();
            unsafe {
                core::ptr::write(alloc.as_mut_ptr(), i as u8);
            }
            allocations.push(alloc);
        }

        // Verify each allocation is independent
        for (i, alloc) in allocations.iter().enumerate() {
            unsafe {
                assert_eq!(core::ptr::read(alloc.as_ptr()), i as u8);
            }
        }
    }

    #[test]
    fn oversized_allocation() {
        // Try to allocate a very large size (but not so large it would definitely fail)
        let layout = Layout::array::<u8>(1024 * 1024).unwrap();
        let result = RawAlloc::new(layout);

        // We don't assert success or failure here, as it depends on the system,
        // but we verify it doesn't panic
        let _ = result.is_ok();
    }

    #[test]
    fn grow_allocation() {
        let initial_size = 100;
        let layout = Layout::array::<u8>(initial_size).unwrap();
        let mut alloc = RawAlloc::new(layout).unwrap();

        // Write some data
        unsafe {
            let slice = core::slice::from_raw_parts_mut(alloc.as_mut_ptr(), initial_size);
            slice[0] = 42;
        }

        // Grow the allocation
        let new_size = 200;
        let new_layout = Layout::array::<u8>(new_size).unwrap();
        alloc.grow(new_layout).unwrap();

        // Verify the data is preserved
        unsafe {
            let slice = core::slice::from_raw_parts(alloc.as_ptr(), new_size);
            assert_eq!(slice[0], 42);
        }
    }

    #[test]
    fn grow_zeroed_allocation() {
        let initial_size = 100;
        let layout = Layout::array::<u8>(initial_size).unwrap();
        let mut alloc = RawAlloc::new(layout).unwrap();

        // Write some data
        unsafe {
            let slice = core::slice::from_raw_parts_mut(alloc.as_mut_ptr(), initial_size);
            slice[0] = 42;
        }

        // Grow the allocation
        let new_size = 200;
        let new_layout = Layout::array::<u8>(new_size).unwrap();
        alloc.grow_zeroed(new_layout).unwrap();

        unsafe {
            let slice = core::slice::from_raw_parts(alloc.as_ptr(), new_size);
            // Verify original data is preserved
            assert_eq!(slice[0], 42);
            // Verify new memory is zeroed
            assert!(slice[initial_size..].iter().all(|&x| x == 0));
        }
    }

    #[test]
    fn shrink_allocation() {
        let initial_size = 200;
        let layout = Layout::array::<u8>(initial_size).unwrap();
        let mut alloc = RawAlloc::new(layout).unwrap();

        // Write some data
        unsafe {
            let slice = core::slice::from_raw_parts_mut(alloc.as_mut_ptr(), initial_size);
            slice[0] = 42;
        }

        // Shrink the allocation
        let new_size = 100;
        let new_layout = Layout::array::<u8>(new_size).unwrap();
        alloc.shrink(new_layout).unwrap();

        // Verify the data is preserved
        unsafe {
            let slice = core::slice::from_raw_parts(alloc.as_ptr(), new_size);
            assert_eq!(slice[0], 42);
        }
    }

    #[test]
    fn grow_zero_size_fails() {
        let layout = Layout::array::<u8>(100).unwrap();
        let mut alloc = RawAlloc::new(layout).unwrap();

        let new_layout = Layout::from_size_align(0, 1).unwrap();
        assert!(alloc.grow(new_layout).is_err());
    }

    #[test]
    fn shrink_zero_size_fails() {
        let layout = Layout::array::<u8>(100).unwrap();
        let mut alloc = RawAlloc::new(layout).unwrap();

        let new_layout = Layout::from_size_align(0, 1).unwrap();
        assert!(alloc.shrink(new_layout).is_err());
    }

    #[test]
    fn grow_smaller_size_fails() {
        let layout = Layout::array::<u8>(200).unwrap();
        let mut alloc = RawAlloc::new(layout).unwrap();

        let new_layout = Layout::array::<u8>(100).unwrap();
        assert!(alloc.grow(new_layout).is_err());
    }

    #[test]
    fn shrink_larger_size_fails() {
        let layout = Layout::array::<u8>(100).unwrap();
        let mut alloc = RawAlloc::new(layout).unwrap();

        let new_layout = Layout::array::<u8>(200).unwrap();
        assert!(alloc.shrink(new_layout).is_err());
    }
}