Skip to content
Myr

error.rs

This file

Path

src/error.rs

317 lines · 8.6 KiB · Rust

Last changed by

Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84

History of this file

Take it

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 1–2why, one step back
1use std::any::TypeId;
2use std::backtrace::{Backtrace, BacktraceStatus};

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 3why, one step back
3use std::error::Error as StdError;

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 4–8why, one step back
4use std::fmt::{self, Debug, Display};
5use std::mem;6use std::ops::{Deref, DerefMut};7use std::ptr;8

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 9why, one step back
9/// The `Error` type, a wrapper around a dynamic error type.

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 10why, one step back
10///

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 11why, one step back
11/// `Error` functions a lot like `Box<dyn std::error::Error>`, with these differences:

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 12why, one step back
12///

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

lines 13–14why, one step back
13/// - `Error` requires that the error is `Send`, `Sync`, and `'static`
14/// - `Error` guarantees that a backtrace will exist, even if the error type

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 15why, one step back
15/// did not provide one

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 16why, one step back
16/// - `Error` is represented as a narrow pointer - exactly one word in size,

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 17why, one step back
17/// instead of two.

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 18why, one step back
18pub struct Error {

Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84

line 19why, one step back
19 inner: Box<ErrorImpl<()>>,

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 20–21why, one step back
20}
21

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 22why, one step back
22impl Error {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 23–24why, one step back
23 /// Create a new exception from any error type.
24 ///

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 25why, one step back
25 /// The error type must be threadsafe and `'static`, so that the `Error` will be as well.

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 26–28why, one step back
26 ///
27 /// If the error type does not provide a backtrace, a backtrace will be created here to ensure28 /// that a backtrace exists.

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 29why, one step back
29 pub fn new<E>(error: E) -> Error

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 30why, one step back
30 where

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 31why, one step back
31 E: StdError + Send + Sync + 'static,

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 32why, one step back
32 {

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 33why, one step back
33 Error::construct(error, TypeId::of::<E>())

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 34–36why, one step back
34 }
3536 #[doc(hidden)]

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 37why, one step back
37 pub fn new_adhoc<M>(message: M) -> Error

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 38–40why, one step back
38 where
39 M: Display + Debug + Send + Sync + 'static,40 {

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 41why, one step back
41 Error::construct(MessageError(message), TypeId::of::<M>())

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 42–43why, one step back
42 }
43

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 44why, one step back
44 fn construct<E>(error: E, type_id: TypeId) -> Error

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 45why, one step back
45 where

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 46why, one step back
46 E: StdError + Send + Sync + 'static,

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 47–52why, one step back
47 {
48 unsafe {49 let backtrace = match error.backtrace() {50 Some(_) => None,51 None => Some(Backtrace::capture()),52 };

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 53why, one step back
53 let obj: TraitObject = mem::transmute(&error as &dyn StdError);

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 54why, one step back
54 let vtable = obj.vtable;

Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84

line 55why, one step back
55 let inner = ErrorImpl {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 56–60why, one step back
56 vtable,
57 type_id,58 backtrace,59 error,60 };

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 61why, one step back
61 Error {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 62–67why, one step back
62 inner: mem::transmute(Box::new(inner)),
63 }64 }65 }6667 /// View this exception as the underlying error.

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 68why, one step back
68 pub fn as_error(&self) -> &(dyn StdError + Send + Sync + 'static) {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 69–72why, one step back
69 &**self
70 }7172 /// View this exception as the underlying error, mutably.

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 73why, one step back
73 pub fn as_error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 74–76why, one step back
74 &mut **self
75 }76

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 77why, one step back
77 /// Get the backtrace for this Error.

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 78–87why, one step back
78 pub fn backtrace(&self) -> &Backtrace {
79 // NB: this unwrap can only fail if the underlying error's backtrace method is80 // nondeterministic, which would only happen in maliciously constructed code81 self.inner82 .backtrace83 .as_ref()84 .or_else(|| self.inner.error().backtrace())85 .expect("exception backtrace capture failed")86 }87

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 88why, one step back
88 /// An iterator of errors contained by this Error.

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 89–103why, one step back
89 ///
90 /// This iterator will visit every error in the "cause chain" of this exception, beginning with91 /// the error that this exception was created from.92 pub fn errors(&self) -> Errors<'_> {93 Errors {94 next: Some(self.inner.error()),95 }96 }9798 /// Returns `true` if `E` is the type wrapped by this exception.99 pub fn is<E: Display + Debug + Send + Sync + 'static>(&self) -> bool {100 TypeId::of::<E>() == self.inner.type_id101 }102103 /// Attempt to downcast the exception to a concrete type.

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 104why, one step back
104 pub fn downcast<E: Display + Debug + Send + Sync + 'static>(self) -> Result<E, Error> {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 105–119why, one step back
105 if let Some(error) = self.downcast_ref::<E>() {
106 unsafe {107 let error = ptr::read(error);108 drop(ptr::read(&self.inner));109 mem::forget(self);110 Ok(error)111 }112 } else {113 Err(self)114 }115 }116117 /// Downcast this exception by reference.118 pub fn downcast_ref<E: Display + Debug + Send + Sync + 'static>(&self) -> Option<&E> {119 if self.is::<E>() {

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 120why, one step back
120 unsafe { Some(&*(self.inner.error() as *const dyn StdError as *const E)) }

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 121–128why, one step back
121 } else {
122 None123 }124 }125126 /// Downcast this exception by mutable reference.127 pub fn downcast_mut<E: Display + Debug + Send + Sync + 'static>(&mut self) -> Option<&mut E> {128 if self.is::<E>() {

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 129why, one step back
129 unsafe { Some(&mut *(self.inner.error_mut() as *mut dyn StdError as *mut E)) }

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 130–135why, one step back
130 } else {
131 None132 }133 }134}135

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

lines 136–138why, one step back
136impl<E: StdError + Send + Sync + 'static> From<E> for Error {
137 fn from(error: E) -> Error {138 Error::new(error)

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 139–141why, one step back
139 }
140}141

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 142why, one step back
142impl Deref for Error {

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 143why, one step back
143 type Target = dyn StdError + Send + Sync + 'static;

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 144–148why, one step back
144 fn deref(&self) -> &Self::Target {
145 self.inner.error()146 }147}148

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 149why, one step back
149impl DerefMut for Error {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 150–154why, one step back
150 fn deref_mut(&mut self) -> &mut Self::Target {
151 self.inner.error_mut()152 }153}154

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 155why, one step back
155impl Debug for Error {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 156–188why, one step back
156 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
157 writeln!(f, "{}", self.inner.error())?;158159 let mut errors = self.errors().skip(1).enumerate();160161 if let Some((n, error)) = errors.next() {162 writeln!(f, "\ncaused by:")?;163 writeln!(f, "\t{}: {}", n, error)?;164 for (n, error) in errors {165 writeln!(f, "\t{}: {}", n, error)?;166 }167 }168169 let backtrace = self.backtrace();170171 match backtrace.status() {172 BacktraceStatus::Captured => {173 writeln!(f, "\n{}", backtrace)?;174 }175 BacktraceStatus::Disabled => {176 writeln!(177 f,178 "\nbacktrace disabled; run with RUST_BACKTRACE=1 environment variable \179 to display a backtrace"180 )?;181 }182 _ => {}183 }184185 Ok(())186 }187}188

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 189why, one step back
189impl Display for Error {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 190–194why, one step back
190 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
191 write!(f, "{}", self.inner.error())192 }193}194

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

lines 195–196why, one step back
195unsafe impl Send for Error {}
196unsafe impl Sync for Error {}

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 197why, one step back
197

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 198why, one step back
198impl Drop for Error {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 199–205why, one step back
199 fn drop(&mut self) {
200 unsafe { ptr::drop_in_place(self.inner.error_mut()) }201 }202}203204// repr C to ensure that `E` remains in the final position205#[repr(C)]

Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84

line 206why, one step back
206struct ErrorImpl<E> {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 207–234why, one step back
207 vtable: *const (),
208 type_id: TypeId,209 backtrace: Option<Backtrace>,210 error: E,211}212213// repr C to ensure that transmuting from trait objects is safe214#[repr(C)]215struct TraitObject {216 data: *const (),217 vtable: *const (),218}219220#[repr(transparent)]221struct MessageError<M: Display + Debug>(M);222223impl<M: Display + Debug> Debug for MessageError<M> {224 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {225 Debug::fmt(&self.0, f)226 }227}228229impl<M: Display + Debug> Display for MessageError<M> {230 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {231 Display::fmt(&self.0, f)232 }233}234

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 235why, one step back
235impl<M: Display + Debug + 'static> StdError for MessageError<M> {}

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 236why, one step back
236

Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84

line 237why, one step back
237impl ErrorImpl<()> {

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 238why, one step back
238 fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 239–246why, one step back
239 unsafe {
240 mem::transmute(TraitObject {241 data: &self.error,242 vtable: self.vtable,243 })244 }245 }246

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 247why, one step back
247 fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 248–256why, one step back
248 unsafe {
249 mem::transmute(TraitObject {250 data: &mut self.error,251 vtable: self.vtable,252 })253 }254 }255}256

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 257why, one step back
257/// Iterator of errors in an `Error`.

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 258why, one step back
258pub struct Errors<'a> {

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 259why, one step back
259 next: Option<&'a (dyn StdError + 'static)>,

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 260–262why, one step back
260}
261262impl<'a> Iterator for Errors<'a> {

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 263why, one step back
263 type Item = &'a (dyn StdError + 'static);

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 264–280why, one step back
264
265 fn next(&mut self) -> Option<Self::Item> {266 let next = self.next.take()?;267 self.next = next.source();268 Some(next)269 }270}271272#[cfg(test)]273mod repr_correctness {274 use super::*;275276 use std::marker::Unpin;277 use std::mem;278279 #[test]280 fn size_of_exception() {

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 281why, one step back
281 assert_eq!(mem::size_of::<Error>(), mem::size_of::<usize>());

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 282–286why, one step back
282 }
283284 #[allow(dead_code)]285 fn assert_exception_autotraits()286 where

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 287why, one step back
287 Error: Unpin + Send + Sync + 'static,

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 288–296why, one step back
288 {
289 }290291 #[test]292 fn destructors_work() {293 use std::sync::*;294295 #[derive(Debug)]296 struct HasDrop(Box<Arc<Mutex<bool>>>);

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 297why, one step back
297 impl StdError for HasDrop {}

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 298–312why, one step back
298 impl Display for HasDrop {
299 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {300 write!(f, "does something")301 }302 }303 impl Drop for HasDrop {304 fn drop(&mut self) {305 let mut has_dropped = self.0.lock().unwrap();306 assert!(!*has_dropped);307 *has_dropped = true;308 }309 }310311 let has_dropped = Arc::new(Mutex::new(false));312

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 313why, one step back
313 drop(Error::from(HasDrop(Box::new(has_dropped.clone()))));

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 314–317why, one step back
314
315 assert!(*has_dropped.lock().unwrap());316 }317}