Rename exception module to error
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Tolnay · committed by David Tolnay · parent 27b8f24 · Browse files · 3 files·+319 added−319 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+319 added−319 removed
- other:+319 added−319 removed
Provenance
- Commit
2000930- Tree
6244409- Author
David Tolnay <dtolnay@gmail.com>- Committer
David Tolnay <dtolnay@gmail.com>- Parent
27b8f24
3 files changed+319 added−319 removed
added:src/error.rs+317 added
1+use std::any::TypeId;2+use std::backtrace::{Backtrace, BacktraceStatus};3+use std::error::Error;4+use std::fmt::{self, Debug, Display};5+use std::mem;6+use std::ops::{Deref, DerefMut};7+use std::ptr;8+9+/// The `Exception type, a wrapper around a dynamic error type.10+///11+/// `Exception` functions a lot like `Box<dyn Error>`, with these differences:12+///13+/// - `Exception` requires that the error is `Send`, `Sync`, and `'static`14+/// - `Exception` guarantees that a backtrace will exist, even if the error type15+/// did not provide one16+/// - `Exception` is represented as a narrow pointer - exactly one word in size,17+/// instead of two.18+pub struct Exception {19+ inner: Box<InnerException<()>>,20+}21+22+impl Exception {23+ /// Create a new exception from any error type.24+ ///25+ /// The error type must be threadsafe and `'static`, so that the `Exception` will be as well.26+ ///27+ /// If the error type does not provide a backtrace, a backtrace will be created here to ensure28+ /// that a backtrace exists.29+ pub fn new<E>(error: E) -> Exception30+ where31+ E: Error + Send + Sync + 'static,32+ {33+ Exception::construct(error, TypeId::of::<E>())34+ }35+36+ #[doc(hidden)]37+ pub fn new_adhoc<M>(message: M) -> Exception38+ where39+ M: Display + Debug + Send + Sync + 'static,40+ {41+ Exception::construct(MessageError(message), TypeId::of::<M>())42+ }43+44+ fn construct<E>(error: E, type_id: TypeId) -> Exception45+ where46+ E: Error + Send + Sync + 'static,47+ {48+ unsafe {49+ let backtrace = match error.backtrace() {50+ Some(_) => None,51+ None => Some(Backtrace::capture()),52+ };53+ let obj: TraitObject = mem::transmute(&error as &dyn Error);54+ let vtable = obj.vtable;55+ let inner = InnerException {56+ vtable,57+ type_id,58+ backtrace,59+ error,60+ };61+ Exception {62+ inner: mem::transmute(Box::new(inner)),63+ }64+ }65+ }66+67+ /// View this exception as the underlying error.68+ pub fn as_error(&self) -> &(dyn Error + Send + Sync + 'static) {69+ &**self70+ }71+72+ /// View this exception as the underlying error, mutably.73+ pub fn as_error_mut(&mut self) -> &mut (dyn Error + Send + Sync + 'static) {74+ &mut **self75+ }76+77+ /// Get the backtrace for this Exception.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+88+ /// An iterator of errors contained by this Exception.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+ }97+98+ /// 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+ }102+103+ /// Attempt to downcast the exception to a concrete type.104+ pub fn downcast<E: Display + Debug + Send + Sync + 'static>(self) -> Result<E, Exception> {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+ }116+117+ /// Downcast this exception by reference.118+ pub fn downcast_ref<E: Display + Debug + Send + Sync + 'static>(&self) -> Option<&E> {119+ if self.is::<E>() {120+ unsafe { Some(&*(self.inner.error() as *const dyn Error as *const E)) }121+ } else {122+ None123+ }124+ }125+126+ /// 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>() {129+ unsafe { Some(&mut *(self.inner.error_mut() as *mut dyn Error as *mut E)) }130+ } else {131+ None132+ }133+ }134+}135+136+impl<E: Error + Send + Sync + 'static> From<E> for Exception {137+ fn from(error: E) -> Exception {138+ Exception::new(error)139+ }140+}141+142+impl Deref for Exception {143+ type Target = dyn Error + Send + Sync + 'static;144+ fn deref(&self) -> &Self::Target {145+ self.inner.error()146+ }147+}148+149+impl DerefMut for Exception {150+ fn deref_mut(&mut self) -> &mut Self::Target {151+ self.inner.error_mut()152+ }153+}154+155+impl Debug for Exception {156+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {157+ writeln!(f, "{}", self.inner.error())?;158+159+ let mut errors = self.errors().skip(1).enumerate();160+161+ 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+ }168+169+ let backtrace = self.backtrace();170+171+ 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+ }184+185+ Ok(())186+ }187+}188+189+impl Display for Exception {190+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {191+ write!(f, "{}", self.inner.error())192+ }193+}194+195+unsafe impl Send for Exception {}196+unsafe impl Sync for Exception {}197+198+impl Drop for Exception {199+ fn drop(&mut self) {200+ unsafe { ptr::drop_in_place(self.inner.error_mut()) }201+ }202+}203+204+// repr C to ensure that `E` remains in the final position205+#[repr(C)]206+struct InnerException<E> {207+ vtable: *const (),208+ type_id: TypeId,209+ backtrace: Option<Backtrace>,210+ error: E,211+}212+213+// repr C to ensure that transmuting from trait objects is safe214+#[repr(C)]215+struct TraitObject {216+ data: *const (),217+ vtable: *const (),218+}219+220+#[repr(transparent)]221+struct MessageError<M: Display + Debug>(M);222+223+impl<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+}228+229+impl<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+235+impl<M: Display + Debug + 'static> Error for MessageError<M> {}236+237+impl InnerException<()> {238+ fn error(&self) -> &(dyn Error + Send + Sync + 'static) {239+ unsafe {240+ mem::transmute(TraitObject {241+ data: &self.error,242+ vtable: self.vtable,243+ })244+ }245+ }246+247+ fn error_mut(&mut self) -> &mut (dyn Error + Send + Sync + 'static) {248+ unsafe {249+ mem::transmute(TraitObject {250+ data: &mut self.error,251+ vtable: self.vtable,252+ })253+ }254+ }255+}256+257+/// Iterator of errors in an `Exception`.258+pub struct Errors<'a> {259+ next: Option<&'a (dyn Error + 'static)>,260+}261+262+impl<'a> Iterator for Errors<'a> {263+ type Item = &'a (dyn Error + 'static);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+}271+272+#[cfg(test)]273+mod repr_correctness {274+ use super::*;275+276+ use std::marker::Unpin;277+ use std::mem;278+279+ #[test]280+ fn size_of_exception() {281+ assert_eq!(mem::size_of::<Exception>(), mem::size_of::<usize>());282+ }283+284+ #[allow(dead_code)]285+ fn assert_exception_autotraits()286+ where287+ Exception: Unpin + Send + Sync + 'static,288+ {289+ }290+291+ #[test]292+ fn destructors_work() {293+ use std::sync::*;294+295+ #[derive(Debug)]296+ struct HasDrop(Box<Arc<Mutex<bool>>>);297+ impl Error for HasDrop {}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+ }310+311+ let has_dropped = Arc::new(Mutex::new(false));312+313+ drop(Exception::from(HasDrop(Box::new(has_dropped.clone()))));314+315+ assert!(*has_dropped.lock().unwrap());316+ }317+}deleted:src/exception.rs-317 removed
1-use std::any::TypeId;2-use std::backtrace::{Backtrace, BacktraceStatus};3-use std::error::Error;4-use std::fmt::{self, Debug, Display};5-use std::mem;6-use std::ops::{Deref, DerefMut};7-use std::ptr;8-9-/// The `Exception type, a wrapper around a dynamic error type.10-///11-/// `Exception` functions a lot like `Box<dyn Error>`, with these differences:12-///13-/// - `Exception` requires that the error is `Send`, `Sync`, and `'static`14-/// - `Exception` guarantees that a backtrace will exist, even if the error type15-/// did not provide one16-/// - `Exception` is represented as a narrow pointer - exactly one word in size,17-/// instead of two.18-pub struct Exception {19- inner: Box<InnerException<()>>,20-}21-22-impl Exception {23- /// Create a new exception from any error type.24- ///25- /// The error type must be threadsafe and `'static`, so that the `Exception` will be as well.26- ///27- /// If the error type does not provide a backtrace, a backtrace will be created here to ensure28- /// that a backtrace exists.29- pub fn new<E>(error: E) -> Exception30- where31- E: Error + Send + Sync + 'static,32- {33- Exception::construct(error, TypeId::of::<E>())34- }35-36- #[doc(hidden)]37- pub fn new_adhoc<M>(message: M) -> Exception38- where39- M: Display + Debug + Send + Sync + 'static,40- {41- Exception::construct(MessageError(message), TypeId::of::<M>())42- }43-44- fn construct<E>(error: E, type_id: TypeId) -> Exception45- where46- E: Error + Send + Sync + 'static,47- {48- unsafe {49- let backtrace = match error.backtrace() {50- Some(_) => None,51- None => Some(Backtrace::capture()),52- };53- let obj: TraitObject = mem::transmute(&error as &dyn Error);54- let vtable = obj.vtable;55- let inner = InnerException {56- vtable,57- type_id,58- backtrace,59- error,60- };61- Exception {62- inner: mem::transmute(Box::new(inner)),63- }64- }65- }66-67- /// View this exception as the underlying error.68- pub fn as_error(&self) -> &(dyn Error + Send + Sync + 'static) {69- &**self70- }71-72- /// View this exception as the underlying error, mutably.73- pub fn as_error_mut(&mut self) -> &mut (dyn Error + Send + Sync + 'static) {74- &mut **self75- }76-77- /// Get the backtrace for this Exception.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-88- /// An iterator of errors contained by this Exception.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- }97-98- /// 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- }102-103- /// Attempt to downcast the exception to a concrete type.104- pub fn downcast<E: Display + Debug + Send + Sync + 'static>(self) -> Result<E, Exception> {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- }116-117- /// Downcast this exception by reference.118- pub fn downcast_ref<E: Display + Debug + Send + Sync + 'static>(&self) -> Option<&E> {119- if self.is::<E>() {120- unsafe { Some(&*(self.inner.error() as *const dyn Error as *const E)) }121- } else {122- None123- }124- }125-126- /// 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>() {129- unsafe { Some(&mut *(self.inner.error_mut() as *mut dyn Error as *mut E)) }130- } else {131- None132- }133- }134-}135-136-impl<E: Error + Send + Sync + 'static> From<E> for Exception {137- fn from(error: E) -> Exception {138- Exception::new(error)139- }140-}141-142-impl Deref for Exception {143- type Target = dyn Error + Send + Sync + 'static;144- fn deref(&self) -> &Self::Target {145- self.inner.error()146- }147-}148-149-impl DerefMut for Exception {150- fn deref_mut(&mut self) -> &mut Self::Target {151- self.inner.error_mut()152- }153-}154-155-impl Debug for Exception {156- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {157- writeln!(f, "{}", self.inner.error())?;158-159- let mut errors = self.errors().skip(1).enumerate();160-161- 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- }168-169- let backtrace = self.backtrace();170-171- 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- }184-185- Ok(())186- }187-}188-189-impl Display for Exception {190- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {191- write!(f, "{}", self.inner.error())192- }193-}194-195-unsafe impl Send for Exception {}196-unsafe impl Sync for Exception {}197-198-impl Drop for Exception {199- fn drop(&mut self) {200- unsafe { ptr::drop_in_place(self.inner.error_mut()) }201- }202-}203-204-// repr C to ensure that `E` remains in the final position205-#[repr(C)]206-struct InnerException<E> {207- vtable: *const (),208- type_id: TypeId,209- backtrace: Option<Backtrace>,210- error: E,211-}212-213-// repr C to ensure that transmuting from trait objects is safe214-#[repr(C)]215-struct TraitObject {216- data: *const (),217- vtable: *const (),218-}219-220-#[repr(transparent)]221-struct MessageError<M: Display + Debug>(M);222-223-impl<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-}228-229-impl<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-235-impl<M: Display + Debug + 'static> Error for MessageError<M> {}236-237-impl InnerException<()> {238- fn error(&self) -> &(dyn Error + Send + Sync + 'static) {239- unsafe {240- mem::transmute(TraitObject {241- data: &self.error,242- vtable: self.vtable,243- })244- }245- }246-247- fn error_mut(&mut self) -> &mut (dyn Error + Send + Sync + 'static) {248- unsafe {249- mem::transmute(TraitObject {250- data: &mut self.error,251- vtable: self.vtable,252- })253- }254- }255-}256-257-/// Iterator of errors in an `Exception`.258-pub struct Errors<'a> {259- next: Option<&'a (dyn Error + 'static)>,260-}261-262-impl<'a> Iterator for Errors<'a> {263- type Item = &'a (dyn Error + 'static);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-}271-272-#[cfg(test)]273-mod repr_correctness {274- use super::*;275-276- use std::marker::Unpin;277- use std::mem;278-279- #[test]280- fn size_of_exception() {281- assert_eq!(mem::size_of::<Exception>(), mem::size_of::<usize>());282- }283-284- #[allow(dead_code)]285- fn assert_exception_autotraits()286- where287- Exception: Unpin + Send + Sync + 'static,288- {289- }290-291- #[test]292- fn destructors_work() {293- use std::sync::*;294-295- #[derive(Debug)]296- struct HasDrop(Box<Arc<Mutex<bool>>>);297- impl Error for HasDrop {}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- }310-311- let has_dropped = Arc::new(Mutex::new(false));312-313- drop(Exception::from(HasDrop(Box::new(has_dropped.clone()))));314-315- assert!(*has_dropped.lock().unwrap());316- }317-}modified:src/lib.rs+2 added-2 removed
1 #![feature(backtrace)]2 3 mod as_error;4 mod context;5-mod exception;5+mod error;6 7 pub use crate::as_error::AsError;8 pub use crate::context::Context;9-pub use crate::exception::{Errors, Exception};9+pub use crate::error::{Errors, Exception};10 11 /// Return early with an error.12 ///13 /// This macro is equivalent to `return Err(From::from($err))`.16 unmodified lines