Skip to content

Commit f0527d1

Browse files
committed
helpers: Add AlignedBuffer
AlignedBuffer is a helper class that manages the livetime of a memory region, allocated using a certain alignment. Like Box, it handles deallocation when the object isn't used anymore.
1 parent 5e94f4d commit f0527d1

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

uefi/src/helpers/aligned_buffer.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// SPDX-License-Identifier: MIT OR Apache-2.0
2+
3+
use alloc::alloc::{alloc, dealloc, Layout, LayoutError};
4+
5+
/// Helper class to maintain the lifetime of a memory region allocated with a non-standard alignment.
6+
/// Facilitates RAII to properly deallocate when lifetime of the object ends.
7+
#[derive(Debug)]
8+
pub struct AlignedBuffer {
9+
ptr: *mut u8,
10+
layout: Layout,
11+
}
12+
impl AlignedBuffer {
13+
/// Allocate a new memory region with the requested len and alignment.
14+
pub fn alloc(len: usize, alignment: usize) -> Result<Self, LayoutError> {
15+
let layout = Layout::from_size_align(len, alignment)?;
16+
let ptr = unsafe { alloc(layout) };
17+
Ok(Self { ptr, layout })
18+
}
19+
/// Get a pointer to the aligned memory region managed by this instance.
20+
pub fn ptr(&self) -> *const u8 {
21+
self.ptr as *const u8
22+
}
23+
/// Get a mutable pointer to the aligned memory region managed by this instance.
24+
pub fn ptr_mut(&mut self) -> *mut u8 {
25+
self.ptr as *mut u8
26+
}
27+
/// Get the size of the aligned memory region managed by this instance.
28+
pub fn len(&self) -> usize {
29+
self.layout.size()
30+
}
31+
/// Fill the aligned memory region with data from the given buffer.
32+
pub fn copy_from(&mut self, data: &[u8]) {
33+
let len = data.len().min(self.len());
34+
unsafe {
35+
self.ptr.copy_from(data.as_ptr(), len);
36+
}
37+
}
38+
}
39+
impl Drop for AlignedBuffer {
40+
fn drop(&mut self) {
41+
unsafe {
42+
dealloc(self.ptr, self.layout);
43+
}
44+
}
45+
}

uefi/src/helpers/mod.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,12 @@ use crate::Result;
2424
#[doc(hidden)]
2525
pub use println::_print;
2626

27+
#[cfg(feature = "alloc")]
28+
mod aligned_buffer;
29+
#[doc(hidden)]
30+
#[cfg(feature = "alloc")]
31+
pub use aligned_buffer::AlignedBuffer;
32+
2733
#[cfg(feature = "global_allocator")]
2834
mod global_allocator;
2935
#[cfg(feature = "logger")]

0 commit comments

Comments
 (0)