Skip to content
Myr

Format with rustfmt 2019-09-08

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 b47a6fd · Browse files · 3 files+77 added−38 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+77 added−38 removed

  • other:+77 added−38 removed

3 files+77 added−38 removed

modified:src/context.rs+21 added-8 removed
1use std::backtrace::Backtrace;2use std::fmt::{self, Debug, Display};2use std::error::Error;3use std::fmt::{self, Debug, Display};45use crate::Exception;67/// Provides the `context` method for `Result`.
1 unmodified line
9 /// Wrap the error value with additional context.10 fn context<C: Display + Send + Sync + 'static>(self, context: C) -> Result<T, Exception>;1112 /// Wrap the error value with additional context lazily.13 fn with_context<C, F>(self, f: F) -> Result<T, Exception> where13 fn with_context<C, F>(self, f: F) -> Result<T, Exception>14 where15 C: Display + Send + Sync + 'static,16 F: FnOnce(&E) -> C;17}18
1 unmodified line
20 fn context<C: Display + Send + Sync + 'static>(self, context: C) -> Result<T, Exception> {21 self.map_err(|error| Exception::from(ContextError { error, context }))22 }2323 fn with_context<C, F>(self, f: F) -> Result<T, Exception> where24 fn with_context<C, F>(self, f: F) -> Result<T, Exception>25 where26 C: Display + Send + Sync + 'static,25 F: FnOnce(&E) -> C27 F: FnOnce(&E) -> C,28 {27 self.map_err(|error| Exception::from(ContextError { context: f(&error), error }))29 self.map_err(|error| {30 Exception::from(ContextError {31 context: f(&error),32 error,33 })34 })35 }36}3738impl<T> Context<T, Exception> for Result<T, Exception> {39 fn context<C: Display + Send + Sync + 'static>(self, context: C) -> Result<T, Exception> {40 self.map_err(|error| Exception::from(ContextError { error, context }))41 }4236 fn with_context<C, F>(self, f: F) -> Result<T, Exception> where43 fn with_context<C, F>(self, f: F) -> Result<T, Exception>44 where45 C: Display + Send + Sync + 'static,38 F: FnOnce(&Exception) -> C46 F: FnOnce(&Exception) -> C,47 {40 self.map_err(|error| Exception::from(ContextError { context: f(&error), error }))48 self.map_err(|error| {49 Exception::from(ContextError {50 context: f(&error),51 error,52 })53 })54 }55}5657struct ContextError<E, C> {
43 unmodified lines
modified:src/exception.rs+51 added-27 removed
24 unmodified lines
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) -> Exception where30 E: Error + Send + Sync + 'static29 pub fn new<E>(error: E) -> Exception30 where31 E: Error + Send + Sync + 'static,32 {33 Exception::construct(error, TypeId::of::<E>())34 }3536 #[doc(hidden)]36 pub fn new_adhoc<M>(message: M) -> Exception where37 M: Display + Debug + Send + Sync + 'static37 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 }4342 fn construct<E>(error: E, type_id: TypeId) -> Exception where44 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,48 None => Some(Backtrace::capture()),51 None => Some(Backtrace::capture()),52 };53 let obj: TraitObject = mem::transmute(&error as &dyn Error);54 let vtable = obj.vtable;52 let inner = InnerException { vtable, type_id, backtrace, error };55 let inner = InnerException {56 vtable,57 type_id,58 backtrace,59 error,60 };61 Exception {54 inner: mem::transmute(Box::new(inner))62 inner: mem::transmute(Box::new(inner)),63 }64 }65 }66
10 unmodified lines
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 code73 self.inner.backtrace.as_ref().or_else(|| self.inner.error().backtrace())81 self.inner82 .backtrace83 .as_ref()84 .or_else(|| self.inner.error().backtrace())85 .expect("exception backtrace capture failed")86 }8788 /// 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<'_> {82 Errors { next: Some(self.inner.error()) }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 {
17 unmodified lines
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)) }108 } else { None }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>() {129 unsafe { Some(&mut *(self.inner.error_mut() as *mut dyn Error as *mut E)) }115 } else { None }130 } else {131 None132 }133 }134}135136impl<E: Error + Send + Sync + 'static> From<E> for Exception {
31 unmodified lines
168169 let backtrace = self.backtrace();170171 match backtrace.status() {155 BacktraceStatus::Captured => {172 BacktraceStatus::Captured => {173 writeln!(f, "\n{}", backtrace)?;174 }158 BacktraceStatus::Disabled => {159 writeln!(f, "\nbacktrace disabled; run with RUST_BACKTRACE=1 environment variable \160 to display a backtrace")?;175 BacktraceStatus::Disabled => {176 writeln!(177 f,178 "\nbacktrace disabled; run with RUST_BACKTRACE=1 environment variable \179 to display a backtrace"180 )?;181 }162 _ => { }182 _ => {}183 }184185 Ok(())186 }
4 unmodified lines
191 write!(f, "{}", self.inner.error())192 }193}194175unsafe impl Send for Exception { }176unsafe impl Sync for Exception { }195unsafe impl Send for Exception {}196unsafe impl Sync for Exception {}197198impl Drop for Exception {199 fn drop(&mut self) {200 unsafe { ptr::drop_in_place(self.inner.error_mut()) }
30 unmodified lines
231 Display::fmt(&self.0, f)232 }233}234215impl<M: Display + Debug + 'static> Error for MessageError<M> { }235impl<M: Display + Debug + 'static> Error for MessageError<M> {}236237impl InnerException<()> {238 fn error(&self) -> &(dyn Error + Send + Sync + 'static) {239 unsafe {
20 unmodified lines
260}261262impl<'a> Iterator for Errors<'a> {263 type Item = &'a (dyn Error + 'static);264265 fn next(&mut self) -> Option<Self::Item> {266 let next = self.next.take()?;267 self.next = next.source();268 Some(next)
3 unmodified lines
272#[cfg(test)]273mod repr_correctness {274 use super::*;275255 use std::mem;276 use std::marker::Unpin;277 use std::mem;278279 #[test]280 fn size_of_exception() {281 assert_eq!(mem::size_of::<Exception>(), mem::size_of::<usize>());282 }283263 #[allow(dead_code)] fn assert_exception_autotraits() where264 Exception: Unpin + Send + Sync + 'static265 { }284 #[allow(dead_code)]285 fn assert_exception_autotraits()286 where287 Exception: Unpin + Send + Sync + 'static,288 {289 }290291 #[test]292 fn destructors_work() {293 use std::sync::*;294295 #[derive(Debug)]271 #[derive(Debug)] struct HasDrop(Box<Arc<Mutex<bool>>>);272 impl Error for HasDrop { }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 }
10 unmodified lines
312313 drop(Exception::from(HasDrop(Box::new(has_dropped.clone()))));314315 assert!(*has_dropped.lock().unwrap());291316 }317}
modified:src/lib.rs+5 added-3 removed
1#![feature(backtrace)]23mod as_error;4mod exception;4mod context;5mod exception;67pub use crate::as_error::AsError;8pub use crate::exception::{Exception, Errors};8pub use crate::context::Context;9pub use crate::exception::{Errors, Exception};1011/// Throw an error.12///13/// This macro is equivalent to `Err($err)?`.14#[macro_export]15macro_rules! throw {16 ($err:expr) => (return std::result::Result::Err(std::convert::From::from($err)))16 ($err:expr) => {17 return std::result::Result::Err(std::convert::From::from($err));18 };19}2021/// Construct an ad-hoc exception from a string.22///
7 unmodified lines