Skip to main content

kernel/alloc/kvec/
errors.rs

1// SPDX-License-Identifier: GPL-2.0
2
3//! Errors for the [`Vec`] type.
4
5use crate::{
6    fmt,
7    prelude::*, //
8};
9
10/// Error type for a push that fails because there is no spare capacity.
11pub struct PushError<T>(pub T);
12
13impl<T> fmt::Debug for PushError<T> {
14    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
15        write!(f, "Not enough capacity")
16    }
17}
18
19impl<T> From<PushError<T>> for Error {
20    #[inline]
21    fn from(_: PushError<T>) -> Error {
22        // Returning ENOMEM isn't appropriate because the system is not out of memory. The vector
23        // is just full and we are refusing to resize it.
24        EINVAL
25    }
26}
27
28/// Error type for [`Vec::try_push_init`].
29pub enum TryPushInitError<I, E> {
30    /// The allocation failed. Hand the initializer back.
31    AllocError(I),
32    /// The initializer failed.
33    InitError(E),
34}
35
36impl<I, E> fmt::Debug for TryPushInitError<I, E> {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        match self {
39            TryPushInitError::AllocError(_) => write!(f, "Failed to allocate"),
40            TryPushInitError::InitError(_) => write!(f, "Initializer failed"),
41        }
42    }
43}
44
45impl<I, E> From<TryPushInitError<I, E>> for Error
46where
47    Error: From<E>,
48{
49    #[inline]
50    fn from(e: TryPushInitError<I, E>) -> Error {
51        match e {
52            TryPushInitError::AllocError(_) => ENOMEM,
53            TryPushInitError::InitError(e) => Error::from(e),
54        }
55    }
56}
57
58/// Error type for [`Vec::remove`].
59pub struct RemoveError;
60
61impl fmt::Debug for RemoveError {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        write!(f, "Index out of bounds")
64    }
65}
66
67impl From<RemoveError> for Error {
68    #[inline]
69    fn from(_: RemoveError) -> Error {
70        EINVAL
71    }
72}
73
74/// Error type for [`Vec::insert_within_capacity`].
75pub enum InsertError<T> {
76    /// The value could not be inserted because the index is out of bounds.
77    IndexOutOfBounds(T),
78    /// The value could not be inserted because the vector is out of capacity.
79    OutOfCapacity(T),
80}
81
82impl<T> fmt::Debug for InsertError<T> {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        match self {
85            InsertError::IndexOutOfBounds(_) => write!(f, "Index out of bounds"),
86            InsertError::OutOfCapacity(_) => write!(f, "Not enough capacity"),
87        }
88    }
89}
90
91impl<T> From<InsertError<T>> for Error {
92    #[inline]
93    fn from(_: InsertError<T>) -> Error {
94        EINVAL
95    }
96}