-
-
Notifications
You must be signed in to change notification settings - Fork 14.9k
Expand file tree
/
Copy patherror.rs
More file actions
243 lines (231 loc) · 8.02 KB
/
error.rs
File metadata and controls
243 lines (231 loc) · 8.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
use core::alloc::{Allocator, Layout};
use core::io::error_internals::{Custom, ErrorBox, ErrorString};
use core::io::{Error, ErrorKind, const_error};
use core::ptr::{self, NonNull};
use core::{error, result};
use crate::alloc::Global;
use crate::boxed::Box;
use crate::string::String;
#[rustc_std_internal_symbol]
unsafe fn __rust_io_error_deallocate(ptr: NonNull<u8>, layout: Layout) {
unsafe { Global.deallocate(ptr, layout) }
}
fn into_error_box<T: ?Sized>(value: Box<T>) -> ErrorBox<T> {
unsafe { ErrorBox::from_raw(Box::into_raw(value)) }
}
fn into_box<T: ?Sized>(v: ErrorBox<T>) -> Box<T> {
unsafe { Box::from_raw(v.into_raw()) }
}
impl From<String> for ErrorString {
fn from(value: String) -> Self {
unsafe {
let (buf, length, capacity) = value.into_raw_parts();
ErrorString::from_raw_parts(
ErrorBox::from_raw(ptr::slice_from_raw_parts_mut(buf.cast(), capacity)).into(),
length,
)
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl From<crate::ffi::NulError> for Error {
/// Converts a [`crate::ffi::NulError`] into a [`Error`].
fn from(_: crate::ffi::NulError) -> Error {
const_error!(ErrorKind::InvalidInput, "data provided contains a nul byte")
}
}
#[stable(feature = "io_error_from_try_reserve", since = "1.78.0")]
impl From<crate::collections::TryReserveError> for Error {
/// Converts `TryReserveError` to an error with [`ErrorKind::OutOfMemory`].
///
/// `TryReserveError` won't be available as the error `source()`,
/// but this may change in the future.
fn from(_: crate::collections::TryReserveError) -> Error {
// ErrorData::Custom allocates, which isn't great for handling OOM errors.
ErrorKind::OutOfMemory.into()
}
}
impl Error {
/// Creates a new I/O error from a known kind of error as well as an
/// arbitrary error payload.
///
/// This function is used to generically create I/O errors which do not
/// originate from the OS itself. The `error` argument is an arbitrary
/// payload which will be contained in this [`Error`].
///
/// Note that this function allocates memory on the heap.
/// If no extra payload is required, use the `From` conversion from
/// `ErrorKind`.
///
/// # Examples
///
/// ```
/// use std::io::{Error, ErrorKind};
///
/// // errors can be created from strings
/// let custom_error = Error::new(ErrorKind::Other, "oh no!");
///
/// // errors can also be created from other errors
/// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);
///
/// // creating an error without payload (and without memory allocation)
/// let eof_error = Error::from(ErrorKind::UnexpectedEof);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(not(test), rustc_diagnostic_item = "io_error_new")]
#[rustc_allow_incoherent_impl]
#[inline(never)]
pub fn new<E>(kind: ErrorKind, error: E) -> Error
where
E: Into<Box<dyn error::Error + Send + Sync>>,
{
Self::_new(kind, error.into())
}
/// Creates a new I/O error from an arbitrary error payload.
///
/// This function is used to generically create I/O errors which do not
/// originate from the OS itself. It is a shortcut for [`Error::new`]
/// with [`ErrorKind::Other`].
///
/// # Examples
///
/// ```
/// use std::io::Error;
///
/// // errors can be created from strings
/// let custom_error = Error::other("oh no!");
///
/// // errors can also be created from other errors
/// let custom_error2 = Error::other(custom_error);
/// ```
#[stable(feature = "io_error_other", since = "1.74.0")]
#[rustc_allow_incoherent_impl]
pub fn other<E>(error: E) -> Error
where
E: Into<Box<dyn error::Error + Send + Sync>>,
{
Self::_new(ErrorKind::Other, error.into())
}
#[rustc_allow_incoherent_impl]
fn _new(kind: ErrorKind, error: Box<dyn error::Error + Send + Sync>) -> Error {
Error::_new_custom(into_error_box(Box::new(Custom { kind, error: into_error_box(error) })))
}
/// Consumes the `Error`, returning its inner error (if any).
///
/// If this [`Error`] was constructed via [`new`] then this function will
/// return [`Some`], otherwise it will return [`None`].
///
/// [`new`]: https://doc.rust-lang.org/std/io/struct.Error.html#method.new
///
/// # Examples
///
/// ```
/// use std::io::{Error, ErrorKind};
///
/// fn print_error(err: Error) {
/// if let Some(inner_err) = err.into_inner() {
/// println!("Inner error: {inner_err}");
/// } else {
/// println!("No inner error");
/// }
/// }
///
/// fn main() {
/// // Will print "No inner error".
/// print_error(Error::last_os_error());
/// // Will print "Inner error: ...".
/// print_error(Error::new(ErrorKind::Other, "oh no!"));
/// }
/// ```
#[stable(feature = "io_error_inner", since = "1.3.0")]
#[must_use = "`self` will be dropped if the result is not used"]
#[inline]
#[rustc_allow_incoherent_impl]
pub fn into_inner(self) -> Option<Box<dyn error::Error + Send + Sync>> {
self.into_inner_impl().map(into_box)
}
/// Attempts to downcast the custom boxed error to `E`.
///
/// If this [`Error`] contains a custom boxed error,
/// then it would attempt downcasting on the boxed error,
/// otherwise it will return [`Err`].
///
/// If the custom boxed error has the same type as `E`, it will return [`Ok`],
/// otherwise it will also return [`Err`].
///
/// This method is meant to be a convenience routine for calling
/// `Box<dyn Error + Sync + Send>::downcast` on the custom boxed error, returned by
/// [`Error::into_inner`].
///
///
/// # Examples
///
/// ```
/// use std::fmt;
/// use std::io;
/// use std::error::Error;
///
/// #[derive(Debug)]
/// enum E {
/// Io(io::Error),
/// SomeOtherVariant,
/// }
///
/// impl fmt::Display for E {
/// // ...
/// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// # todo!()
/// # }
/// }
/// impl Error for E {}
///
/// impl From<io::Error> for E {
/// fn from(err: io::Error) -> E {
/// err.downcast::<E>()
/// .unwrap_or_else(E::Io)
/// }
/// }
///
/// impl From<E> for io::Error {
/// fn from(err: E) -> io::Error {
/// match err {
/// E::Io(io_error) => io_error,
/// e => io::Error::new(io::ErrorKind::Other, e),
/// }
/// }
/// }
///
/// # fn main() {
/// let e = E::SomeOtherVariant;
/// // Convert it to an io::Error
/// let io_error = io::Error::from(e);
/// // Cast it back to the original variant
/// let e = E::from(io_error);
/// assert!(matches!(e, E::SomeOtherVariant));
///
/// let io_error = io::Error::from(io::ErrorKind::AlreadyExists);
/// // Convert it to E
/// let e = E::from(io_error);
/// // Cast it back to the original variant
/// let io_error = io::Error::from(e);
/// assert_eq!(io_error.kind(), io::ErrorKind::AlreadyExists);
/// assert!(io_error.get_ref().is_none());
/// assert!(io_error.raw_os_error().is_none());
/// # }
/// ```
#[stable(feature = "io_error_downcast", since = "1.79.0")]
#[rustc_allow_incoherent_impl]
pub fn downcast<E>(self) -> result::Result<E, Self>
where
E: error::Error + Send + Sync + 'static,
{
self.downcast_impl::<E>().map(|p| {
// Safety: Guaranteed by downcast_impl::<E>()
let Ok(err) = unsafe { Box::from_raw(p) }.downcast() else {
// Safety: downcast_impl::<E>() guarantees that the pointer can be downcast to E
unsafe { core::hint::unreachable_unchecked() }
};
*err
})
}
}