2
0
mirror of git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git synced 2025-09-04 20:19:47 +08:00
linux/rust/kernel/alloc/kvec/errors.rs
Alice Ryhl 294a7ecbdf rust: alloc: add Vec::remove
This is needed by Rust Binder in the range allocator, and by upcoming
GPU drivers during firmware initialization.

Panics in the kernel are best avoided when possible, so an error is
returned if the index is out of bounds. An error type is used rather
than just returning Option<T> to let callers handle errors with ?.

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Link: https://lore.kernel.org/r/20250502-vec-methods-v5-6-06d20ad9366f@google.com
[ Remove `# Panics` section; `Vec::remove() handles the error properly.`
  - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-07 18:40:02 +02:00

39 lines
915 B
Rust

// SPDX-License-Identifier: GPL-2.0
//! Errors for the [`Vec`] type.
use core::fmt::{self, Debug, Formatter};
use kernel::prelude::*;
/// Error type for [`Vec::push_within_capacity`].
pub struct PushError<T>(pub T);
impl<T> Debug for PushError<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "Not enough capacity")
}
}
impl<T> From<PushError<T>> for Error {
fn from(_: PushError<T>) -> Error {
// Returning ENOMEM isn't appropriate because the system is not out of memory. The vector
// is just full and we are refusing to resize it.
EINVAL
}
}
/// Error type for [`Vec::remove`].
pub struct RemoveError;
impl Debug for RemoveError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "Index out of bounds")
}
}
impl From<RemoveError> for Error {
fn from(_: RemoveError) -> Error {
EINVAL
}
}