Skip to content

Commit 4349c44

Browse files
authored
Merge pull request #581 from wedsonaf/raw-buffer
rust: add support for creating a `Buffer` from a raw pointer.
2 parents 33eca68 + b1e5694 commit 4349c44

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

rust/kernel/buffer.rs

+15-2
Original file line numberDiff line numberDiff line change
@@ -14,19 +14,32 @@ pub struct Buffer<'a> {
1414
}
1515

1616
impl<'a> Buffer<'a> {
17-
/// Create a new buffer from an existing array.
17+
/// Creates a new buffer from an existing array.
1818
pub fn new(slice: &'a mut [u8]) -> Self {
1919
Buffer { slice, pos: 0 }
2020
}
2121

22+
/// Creates a new buffer from a raw pointer.
23+
///
24+
/// # Safety
25+
///
26+
/// `ptr` must be valid for read and writes, have at least `len` bytes in
27+
/// size, and remain valid and not be used by other threads for the lifetime
28+
/// of the returned instance.
29+
pub unsafe fn from_raw(ptr: *mut u8, len: usize) -> Self {
30+
// SAFETY: The safety requirements of the function satisfy those of
31+
// `from_raw_parts_mut`.
32+
Self::new(unsafe { core::slice::from_raw_parts_mut(ptr, len) })
33+
}
34+
2235
/// Number of bytes that have already been written to the buffer.
2336
/// This will always be less than the length of the original array.
2437
pub fn bytes_written(&self) -> usize {
2538
self.pos
2639
}
2740
}
2841

29-
impl<'a> fmt::Write for Buffer<'a> {
42+
impl fmt::Write for Buffer<'_> {
3043
fn write_str(&mut self, s: &str) -> fmt::Result {
3144
if s.len() > self.slice.len() - self.pos {
3245
Err(fmt::Error)

rust/kernel/error.rs

+6
Original file line numberDiff line numberDiff line change
@@ -396,6 +396,12 @@ impl From<LayoutError> for Error {
396396
}
397397
}
398398

399+
impl From<core::fmt::Error> for Error {
400+
fn from(_: core::fmt::Error) -> Error {
401+
Error::EINVAL
402+
}
403+
}
404+
399405
/// A [`Result`] with an [`Error`] error type.
400406
///
401407
/// To be used as the return type for functions that may fail.

0 commit comments

Comments
 (0)