From 4d196760ee3aef866ea949253fd9547c80cba9cd Mon Sep 17 00:00:00 2001 From: Andrea Ciliberti Date: Wed, 23 Nov 2022 16:24:34 +0100 Subject: [PATCH] Fix alignment and follow suggestions --- ctru-rs/src/lib.rs | 1 + ctru-rs/src/linear.rs | 18 ++++++++++-------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/ctru-rs/src/lib.rs b/ctru-rs/src/lib.rs index 8439531..490b268 100644 --- a/ctru-rs/src/lib.rs +++ b/ctru-rs/src/lib.rs @@ -4,6 +4,7 @@ #![feature(custom_test_frameworks)] #![feature(try_trait_v2)] #![feature(allocator_api)] +#![feature(nonnull_slice_from_raw_parts)] #![test_runner(test_runner::run)] extern "C" fn services_deinit() { diff --git a/ctru-rs/src/linear.rs b/ctru-rs/src/linear.rs index 8a68de6..b9ee0e4 100644 --- a/ctru-rs/src/linear.rs +++ b/ctru-rs/src/linear.rs @@ -7,7 +7,8 @@ //!
//! -use std::alloc::Allocator; +use std::alloc::{Allocator, AllocError, Layout}; +use std::ptr::NonNull; // Implementing an `std::alloc::Allocator` type is the best way to handle this case, since it gives // us full control over the normal `std` implementations (like `Box`). The only issue is that this is another unstable feature to add. @@ -15,6 +16,7 @@ use std::alloc::Allocator; // but the default fallback of the `std` will take care of that for us. /// [`std::alloc::Allocator`] struct for LINEAR memory +/// To use this struct the main crate must activate the `allocator_api` unstable feature. pub struct LinearAllocator; impl LinearAllocator { @@ -27,16 +29,16 @@ impl LinearAllocator { unsafe impl Allocator for LinearAllocator { fn allocate( &self, - layout: std::alloc::Layout, - ) -> Result, std::alloc::AllocError> { - let pointer = unsafe { ctru_sys::linearAlloc(layout.size() as u32) }; - let slice: &mut [u8] = - unsafe { std::slice::from_raw_parts_mut(pointer as *mut u8, layout.size()) }; + layout: Layout, + ) -> Result, AllocError> { + let pointer = unsafe { ctru_sys::linearMemAlign(layout.size() as u32, layout.align() as u32) }; - std::ptr::NonNull::new(slice).ok_or(std::alloc::AllocError) + NonNull::new(pointer.cast()) + .map(|ptr| NonNull::slice_from_raw_parts(ptr, layout.size())) + .ok_or(AllocError) } - unsafe fn deallocate(&self, ptr: std::ptr::NonNull, _layout: std::alloc::Layout) { + unsafe fn deallocate(&self, ptr: NonNull, _layout: Layout) { ctru_sys::linearFree(ptr.as_ptr() as *mut _); } }