Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions rust/kernel/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,32 @@ pub struct Buffer<'a> {
}

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

/// Creates a new buffer from a raw pointer.
///
/// # Safety
///
/// `ptr` must be valid for read and writes, have at least `len` bytes in
/// size, and remain valid and not be used by other threads for the lifetime
/// of the returned instance.
pub unsafe fn from_raw(ptr: *mut u8, len: usize) -> Self {
// SAFETY: The safety requirements of the function satisfy those of
// `from_raw_parts_mut`.
Self::new(unsafe { core::slice::from_raw_parts_mut(ptr, len) })
}

/// Number of bytes that have already been written to the buffer.
/// This will always be less than the length of the original array.
pub fn bytes_written(&self) -> usize {
self.pos
}
}

impl<'a> fmt::Write for Buffer<'a> {
impl fmt::Write for Buffer<'_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
if s.len() > self.slice.len() - self.pos {
Err(fmt::Error)
Expand Down
6 changes: 6 additions & 0 deletions rust/kernel/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,12 @@ impl From<LayoutError> for Error {
}
}

impl From<core::fmt::Error> for Error {
fn from(_: core::fmt::Error) -> Error {
Error::EINVAL
}
}

/// A [`Result`] with an [`Error`] error type.
///
/// To be used as the return type for functions that may fail.
Expand Down