realloc 0.1.0

A re-implementation of various ::alloc features
Documentation
use crate::{Align, Alloc, Allocator, Brand, Error, Layout};
use core::ptr::NonNull;

unsafe extern "C" {
    fn aligned_alloc(align: usize, size: usize) -> *mut core::ffi::c_void;
    fn free(ptr: *mut core::ffi::c_void);
}

/// A "handle" for the platform's allocator.
///
/// On Unix, this uses `aligned_alloc`.
///
/// Only available on feature `platform`.
pub struct PlatformAllocator(Brand);

impl PlatformAllocator {
    /// Return a handle to the platform allocator.
    ///
    /// Multiple of these can safely exist and be used concurrently, since the
    /// platform allocator is thread-safe.
    pub const fn new() -> Self {
        // SAFETY: this is the platform allocator
        Self(unsafe { crate::Brand::platform() })
    }
}

impl Default for PlatformAllocator {
    fn default() -> Self { Self::new() }
}

unsafe impl Allocator for PlatformAllocator {
    fn brand(&self) -> &Brand {
        &self.0
    }

    fn alloc_bytes(&self, layout: Layout) -> Result<Alloc<'_, u8>, Error> {
        let align = layout.align.align();

        if layout.size == 0 {
            // SAFETY:
            // - `ptr` was just "allocated" with this allocator
            // - `layout` is the layout used to "allocate" `ptr`
            // - This is not being used to double-drop an allocation
            //
            // When freed, this allocator will simply do nothing, as it did
            // during allocation.
            return Ok(unsafe {
                Alloc::new(NonNull::new(align as *mut u8).unwrap(), layout, self)
            });
        }

        // `aligned_alloc` requires that `size` is a multiple of `align`
        let size = layout.size.div_ceil(align) * align;

        // SAFETY: `size` is a multiple of `align`, and is non-zero, and `align`
        // is a power of 2
        let Some(ptr) = NonNull::new(unsafe { aligned_alloc(align, size) }) else {
            return Err(Error::PlatformError);
        };

        // SAFETY:
        // - `ptr` was just allocated with this allocator
        // - `layout` is the layout used to allocate `ptr`
        // - This is not being used to double-drop an allocation
        Ok(unsafe { Alloc::new(ptr.cast(), layout, self) })
    }

    fn dealloc_bytes<'this>(&'this self, alloc: Alloc<'this, u8>) {
        if alloc.allocator().brand() != &self.0 || alloc.layout().size == 0 {
            return;
        }

        // SAFETY: the pointer was gotten from this allocator, thus it must also
        // be from `aligned_alloc`
        unsafe { free(alloc.as_ptr().cast()) };
    }

    fn dangling(&self, align: Align) -> Alloc<'_, u8> {
        let layout = Layout { size: 0, align };
        unsafe { Alloc::new(NonNull::new(align.align() as *mut u8).unwrap(), layout, self) }
    }
}