Skip to content
Myr

Merge pull request #53 from dtolnay/nostd

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Add no_std + alloc support

authored by David Tolnay · committed by GitHub · parents e48b330, 10156dd · Browse files · 11 files+158 added−39 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

11 files+158 added−39 removed

  • other:+158 added−39 removed

11 files+158 added−39 removed

modified:src/backtrace.rs+1 added-1 removed
26 unmodified lines
27 }28 };29}3031#[cfg(not(backtrace))]31#[cfg(all(feature = "std", not(backtrace)))]32macro_rules! backtrace_if_absent {33 ($err:expr) => {34 None35 };
1 unmodified line
modified:src/chain.rs+17 added-3 removed
1use self::ChainState::{Buffered, Linked};2use crate::Chain;3use std::error::Error as StdError;1use self::ChainState::*;2use crate::StdError;34#[cfg(feature = "std")]5use std::vec;67#[cfg(feature = "std")]8pub(crate) use crate::Chain;910#[cfg(not(feature = "std"))]11pub(crate) struct Chain<'a> {12 state: ChainState<'a>,13}1415#[derive(Clone)]16pub(crate) enum ChainState<'a> {17 Linked {18 next: Option<&'a (dyn StdError + 'static)>,19 },20 #[cfg(feature = "std")]21 Buffered {22 rest: vec::IntoIter<&'a (dyn StdError + 'static)>,23 },24}
15 unmodified lines
40 let error = (*next)?;41 *next = error.source();42 Some(error)43 }44 #[cfg(feature = "std")]45 Buffered { rest } => rest.next(),46 }47 }48
2 unmodified lines
51 (len, Some(len))52 }53}5455#[cfg(feature = "std")]56impl DoubleEndedIterator for Chain<'_> {57 fn next_back(&mut self) -> Option<Self::Item> {58 match &mut self.state {59 Linked { mut next } => {
22 unmodified lines
82 len += 1;83 }84 len85 }86 #[cfg(feature = "std")]87 Buffered { rest } => rest.len(),88 }89 }90}9192#[cfg(feature = "std")]93impl Default for Chain<'_> {94 fn default() -> Self {95 Chain {96 state: ChainState::Buffered {
5 unmodified lines
modified:src/context.rs+5 added-5 removed
1use crate::error::ContextError;2use crate::{Context, Error};3use std::convert::Infallible;4use std::error::Error as StdError;5use std::fmt::{self, Debug, Display, Write};2use crate::{Context, Error, StdError};3use core::convert::Infallible;4use core::fmt::{self, Debug, Display, Write};56#[cfg(backtrace)]7use std::backtrace::Backtrace;8
5 unmodified lines
14 where15 C: Display + Send + Sync + 'static;16 }1718 #[cfg(feature = "std")]19 impl<E> StdError for E20 where21 E: std::error::Error + Send + Sync + 'static,22 {
119 unmodified lines
142 Some(self.error.backtrace())143 }144145 fn source(&self) -> Option<&(dyn StdError + 'static)> {146 Some(&*self.error)146 Some(self.error.inner.error())147 }148}149150struct Quoted<C>(C);
27 unmodified lines
modified:src/error.rs+35 added-8 removed
1use crate::alloc::Box;2use crate::backtrace::Backtrace;2use crate::wrapper::{BoxedError, DisplayError, MessageError};3use crate::{Chain, Error};4use std::any::TypeId;5use std::error::Error as StdError;6use std::fmt::{self, Debug, Display};7use std::mem::{self, ManuallyDrop};8use std::ops::{Deref, DerefMut};9use std::ptr::{self, NonNull};3use crate::chain::Chain;4use crate::{Error, StdError};5use core::any::TypeId;6use core::fmt::{self, Debug, Display};7use core::mem::{self, ManuallyDrop};8use core::ptr::{self, NonNull};910#[cfg(feature = "std")]11use core::ops::{Deref, DerefMut};1213impl Error {14 /// Create a new error object from any error type.15 ///16 /// The error type must be threadsafe and `'static`, so that the `Error`17 /// will be as well.18 ///19 /// If the error type does not provide a backtrace, a backtrace will be20 /// created here to ensure that a backtrace exists.21 #[cfg(feature = "std")]22 pub fn new<E>(error: E) -> Self23 where24 E: StdError + Send + Sync + 'static,25 {
44 unmodified lines
70 {71 Error::from_adhoc(message, backtrace!())72 }7374 #[cfg(feature = "std")]75 pub(crate) fn from_std<E>(error: E, backtrace: Option<Backtrace>) -> Self76 where77 E: StdError + Send + Sync + 'static,78 {79 let vtable = &ErrorVTable {80 object_drop: object_drop::<E>,81 object_ref: object_ref::<E>,82 #[cfg(feature = "std")]83 object_mut: object_mut::<E>,84 object_boxed: object_boxed::<E>,85 object_downcast: object_downcast::<E>,86 object_drop_rest: object_drop_front::<E>,
6 unmodified lines
93 pub(crate) fn from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> Self94 where95 M: Display + Debug + Send + Sync + 'static,96 {97 use crate::wrapper::MessageError;98 let error: MessageError<M> = MessageError(message);99 let vtable = &ErrorVTable {100 object_drop: object_drop::<MessageError<M>>,101 object_ref: object_ref::<MessageError<M>>,102 #[cfg(feature = "std")]103 object_mut: object_mut::<MessageError<M>>,104 object_boxed: object_boxed::<MessageError<M>>,105 object_downcast: object_downcast::<M>,106 object_drop_rest: object_drop_front::<M>,
7 unmodified lines
114 pub(crate) fn from_display<M>(message: M, backtrace: Option<Backtrace>) -> Self115 where116 M: Display + Send + Sync + 'static,117 {118 use crate::wrapper::DisplayError;119 let error: DisplayError<M> = DisplayError(message);120 let vtable = &ErrorVTable {121 object_drop: object_drop::<DisplayError<M>>,122 object_ref: object_ref::<DisplayError<M>>,123 #[cfg(feature = "std")]124 object_mut: object_mut::<DisplayError<M>>,125 object_boxed: object_boxed::<DisplayError<M>>,126 object_downcast: object_downcast::<M>,127 object_drop_rest: object_drop_front::<M>,
3 unmodified lines
131 // vtable to allow casting the DisplayError<M> to M.132 unsafe { Error::construct(error, vtable, backtrace) }133 }134135 #[cfg(feature = "std")]136 pub(crate) fn from_context<C, E>(context: C, error: E, backtrace: Option<Backtrace>) -> Self137 where138 C: Display + Send + Sync + 'static,139 E: StdError + Send + Sync + 'static,
2 unmodified lines
142143 let vtable = &ErrorVTable {144 object_drop: object_drop::<ContextError<C, E>>,145 object_ref: object_ref::<ContextError<C, E>>,146 #[cfg(feature = "std")]147 object_mut: object_mut::<ContextError<C, E>>,148 object_boxed: object_boxed::<ContextError<C, E>>,149 object_downcast: context_downcast::<C, E>,150 object_drop_rest: context_drop_rest::<C, E>,
2 unmodified lines
153 // Safety: passing vtable that operates on the right type.154 unsafe { Error::construct(error, vtable, backtrace) }155 }156157 #[cfg(feature = "std")]158 pub(crate) fn from_boxed(159 error: Box<dyn StdError + Send + Sync>,160 backtrace: Option<Backtrace>,161 ) -> Self {162 use crate::wrapper::BoxedError;163 let error = BoxedError(error);164 let vtable = &ErrorVTable {165 object_drop: object_drop::<BoxedError>,166 object_ref: object_ref::<BoxedError>,167 #[cfg(feature = "std")]168 object_mut: object_mut::<BoxedError>,169 object_boxed: object_boxed::<BoxedError>,170 object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,171 object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,
98 unmodified lines
270271 let vtable = &ErrorVTable {272 object_drop: object_drop::<ContextError<C, Error>>,273 object_ref: object_ref::<ContextError<C, Error>>,274 #[cfg(feature = "std")]275 object_mut: object_mut::<ContextError<C, Error>>,276 object_boxed: object_boxed::<ContextError<C, Error>>,277 object_downcast: context_chain_downcast::<C>,278 object_drop_rest: context_chain_drop_rest::<C>,
42 unmodified lines
321 /// }322 /// None323 /// }324 /// ```325 #[cfg(feature = "std")]326 pub fn chain(&self) -> Chain {327 self.inner.chain()328 }329
1 unmodified line
331 /// cause's cause etc.332 ///333 /// The root cause is the last error in the iterator produced by334 /// [`chain()`][Error::chain].335 #[cfg(feature = "std")]336 pub fn root_cause(&self) -> &(dyn StdError + 'static) {337 let mut chain = self.chain();338 let mut root_cause = chain.next().unwrap();339 for cause in chain {
113 unmodified lines
453 }454 }455}456457#[cfg(feature = "std")]458impl<E> From<E> for Error459where460 E: StdError + Send + Sync + 'static,461{
2 unmodified lines
464 Error::from_std(error, backtrace)465 }466}467468#[cfg(feature = "std")]469impl Deref for Error {470 type Target = dyn StdError + Send + Sync + 'static;471472 fn deref(&self) -> &Self::Target {473 self.inner.error()474 }475}476477#[cfg(feature = "std")]478impl DerefMut for Error {479 fn deref_mut(&mut self) -> &mut Self::Target {480 self.inner.error_mut()481 }
26 unmodified lines
508509struct ErrorVTable {510 object_drop: unsafe fn(Box<ErrorImpl<()>>),511 object_ref: unsafe fn(&ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static),512 #[cfg(feature = "std")]513 object_mut: unsafe fn(&mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static),514 object_boxed: unsafe fn(Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>,515 object_downcast: unsafe fn(&ErrorImpl<()>, TypeId) -> Option<NonNull<()>>,516 object_drop_rest: unsafe fn(Box<ErrorImpl<()>>, TypeId),
26 unmodified lines
543 &(*(e as *const ErrorImpl<()> as *const ErrorImpl<E>))._object544}545546// Safety: requires layout of *e to match ErrorImpl<E>.547#[cfg(feature = "std")]548unsafe fn object_mut<E>(e: &mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static)549where550 E: StdError + Send + Sync + 'static,551{
26 unmodified lines
578 }579}580581// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.582#[cfg(feature = "std")]583unsafe fn context_downcast<C, E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>584where585 C: 'static,586 E: 'static,
11 unmodified lines
598 }599}600601// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.602#[cfg(feature = "std")]603unsafe fn context_drop_rest<C, E>(e: Box<ErrorImpl<()>>, target: TypeId)604where605 C: 'static,606 E: 'static,
93 unmodified lines
700 // original type E.701 unsafe { &*(self.vtable.object_ref)(self) }702 }703704 #[cfg(feature = "std")]705 pub(crate) fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {706 // Use vtable to attach E's native StdError vtable for the right707 // original type E.708 unsafe { &mut *(self.vtable.object_mut)(self) }
68 unmodified lines
777 Box::<dyn StdError + Send + Sync>::from(error)778 }779}780781#[cfg(feature = "std")]782impl AsRef<dyn StdError + Send + Sync> for Error {783 fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {784 &**self785 }786}787788#[cfg(feature = "std")]789impl AsRef<dyn StdError> for Error {790 fn as_ref(&self) -> &(dyn StdError + 'static) {791 &**self792 }
1 unmodified line
modified:src/fmt.rs+2 added-2 removed
1use crate::chain::Chain;2use crate::error::ErrorImpl;2use crate::Chain;3use std::fmt::{self, Debug};3use core::fmt::{self, Debug};45impl ErrorImpl<()> {6 pub(crate) fn display(&self, f: &mut fmt::Formatter) -> fmt::Result {7 write!(f, "{}", self.error())?;
50 unmodified lines
modified:src/kind.rs+8 added-2 removed
43 unmodified lines
44// let error = $msg;45// (&error).anyhow_kind().new(error)4647use crate::Error;48use std::error::Error as StdError;49use std::fmt::{Debug, Display};48use core::fmt::{Debug, Display};4950#[cfg(feature = "std")]51use crate::StdError;5253#[cfg(backtrace)]54use std::backtrace::Backtrace;5556pub struct Adhoc;
35 unmodified lines
92 error.into()93 }94}9596#[cfg(feature = "std")]97pub struct Boxed;9899#[cfg(feature = "std")]100pub trait BoxedKind: Sized {101 #[inline]102 fn anyhow_kind(&self) -> Boxed {103 Boxed104 }105}106107#[cfg(feature = "std")]108impl BoxedKind for Box<dyn StdError + Send + Sync> {}109110#[cfg(feature = "std")]111impl Boxed {112 pub fn new(self, error: Box<dyn StdError + Send + Sync>) -> Error {113 let backtrace = backtrace_if_absent!(error);114 Error::from_boxed(error, backtrace)
2 unmodified lines
modified:src/lib.rs+55 added-9 removed
156 unmodified lines
157//! return Err(anyhow!("Missing attribute: {}", missing));158//! # Ok(())159//! # }160//! ```161//!162//! <br>163//!164//! # No-std support165//!166//! In no_std mode, the same API is almost all available and works the same way.167//! To depend on Anyhow in no_std mode, disable our default enabled "std"168//! feature in Cargo.toml. A global allocator is required.169//!170//! ```toml171//! [dependencies]172//! anyhow = { version = "1.0", default-features = false }173//! ```174//!175//! Since the `?`-based error conversions would normally rely on the176//! `std::error::Error` trait which is only available through std, no_std mode177//! will require an explicit `.map_err(Error::msg)` when working with a178//! non-Anyhow error type inside a function that returns Anyhow's error type.179180#![doc(html_root_url = "https://docs.rs/anyhow/1.0.24")]181#![cfg_attr(backtrace, feature(backtrace))]182#![cfg_attr(not(feature = "std"), no_std)]183#![allow(184 clippy::needless_doctest_main,185 clippy::new_ret_no_self,186 clippy::wrong_self_convention187)]188189mod alloc {190 #[cfg(not(feature = "std"))]191 extern crate alloc;192193 #[cfg(not(feature = "std"))]194 pub use alloc::boxed::Box;195196 #[cfg(feature = "std")]197 pub use std::boxed::Box;198}199200#[macro_use]201mod backtrace;202mod chain;203mod context;
2 unmodified lines
206mod kind;207mod macros;208mod wrapper;209210use crate::alloc::Box;211use crate::error::ErrorImpl;212use core::fmt::Display;213use core::mem::ManuallyDrop;214215#[cfg(not(feature = "std"))]181compile_error!("no_std support is not implemented yet");216use core::fmt::Debug;217183use crate::chain::ChainState;184use crate::error::ErrorImpl;185use std::fmt::Display;186use std::mem::ManuallyDrop;218#[cfg(feature = "std")]219use std::error::Error as StdError;220221#[cfg(not(feature = "std"))]222trait StdError: Debug + Display {223 fn source(&self) -> Option<&(dyn StdError + 'static)> {224 None225 }226}227228pub use anyhow as format_err;229230/// The `Error` type, a wrapper around a dynamic error type.231///
109 unmodified lines
341/// }342/// None343/// }344/// ```345#[cfg(feature = "std")]346#[derive(Clone)]347pub struct Chain<'a> {307 state: ChainState<'a>,348 state: crate::chain::ChainState<'a>,349}350351/// `Result<T, Error>`352///
43 unmodified lines
396/// println!("cluster info: {:#?}", map);397/// Ok(())398/// }399/// ```359pub type Result<T, E = Error> = std::result::Result<T, E>;400pub type Result<T, E = Error> = core::result::Result<T, E>;401402/// Provides the `context` method for `Result`.403///404/// This trait is sealed and cannot be implemented for types outside of
152 unmodified lines
557// Not public API. Referenced by macro-generated code.558#[doc(hidden)]559pub mod private {560 use crate::Error;520 use std::fmt::{Debug, Display};561 use core::fmt::{Debug, Display};562563 #[cfg(backtrace)]564 use std::backtrace::Backtrace;565566 pub use core::result::Result::Err;567568 #[doc(hidden)]569 pub mod kind {527 pub use crate::kind::{AdhocKind, BoxedKind, TraitKind};570 pub use crate::kind::{AdhocKind, TraitKind};571572 #[cfg(feature = "std")]573 pub use crate::kind::BoxedKind;574 }575576 pub fn new_adhoc<M>(message: M) -> Error577 where
5 unmodified lines
modified:src/macros.rs+6 added-6 removed
48 unmodified lines
49/// ```50#[macro_export]51macro_rules! bail {52 ($msg:literal $(,)?) => {53 return std::result::Result::Err($crate::anyhow!($msg));53 return $crate::private::Err($crate::anyhow!($msg));54 };55 ($err:expr $(,)?) => {56 return std::result::Result::Err($crate::anyhow!($err));56 return $crate::private::Err($crate::anyhow!($err));57 };58 ($fmt:expr, $($arg:tt)*) => {59 return std::result::Result::Err($crate::anyhow!($fmt, $($arg)*));59 return $crate::private::Err($crate::anyhow!($fmt, $($arg)*));60 };61}6263/// Return early with an error if a condition is not satisfied.
43 unmodified lines
107#[macro_export]108macro_rules! ensure {109 ($cond:expr, $msg:literal $(,)?) => {110 if !$cond {111 return std::result::Result::Err($crate::anyhow!($msg));111 return $crate::private::Err($crate::anyhow!($msg));112 }113 };114 ($cond:expr, $err:expr $(,)?) => {115 if !$cond {116 return std::result::Result::Err($crate::anyhow!($err));116 return $crate::private::Err($crate::anyhow!($err));117 }118 };119 ($cond:expr, $fmt:expr, $($arg:tt)*) => {120 if !$cond {121 return std::result::Result::Err($crate::anyhow!($fmt, $($arg)*));121 return $crate::private::Err($crate::anyhow!($fmt, $($arg)*));122 }123 };124}125
38 unmodified lines
modified:src/wrapper.rs+6 added-2 removed
1use std::error::Error as StdError;2use std::fmt::{self, Debug, Display};1use crate::StdError;2use core::fmt::{self, Debug, Display};34#[repr(transparent)]5pub struct MessageError<M>(pub M);6
39 unmodified lines
46}4748impl<M> StdError for DisplayError<M> where M: Display + 'static {}4950#[cfg(feature = "std")]51#[repr(transparent)]52pub struct BoxedError(pub Box<dyn StdError + Send + Sync>);5354#[cfg(feature = "std")]55impl Debug for BoxedError {56 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {57 Debug::fmt(&self.0, f)58 }59}6061#[cfg(feature = "std")]62impl Display for BoxedError {63 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {64 Display::fmt(&self.0, f)65 }66}6768#[cfg(feature = "std")]69impl StdError for BoxedError {70 #[cfg(backtrace)]71 fn backtrace(&self) -> Option<&crate::backtrace::Backtrace> {72 self.0.backtrace()
6 unmodified lines
modified:.travis.yml+5 added-1 removed
3 unmodified lines
4 - nightly5 - beta6 - stable78script: cargo test8script:9 - cargo test10 - cargo check --no-default-features1112matrix:13 include:14 - rust: 1.34.015 script: cargo check16 - rust: 1.36.017 script: cargo check --no-default-features18 - rust: nightly19 name: Clippy20 script:21 - rustup component add clippy || travis_terminate 0
1 unmodified line
modified:README.md+18 added
105 unmodified lines
106 ```107108<br>109110## No-std support111112In no_std mode, the same API is almost all available and works the same way. To113depend on Anyhow in no_std mode, disable our default enabled "std" feature in114Cargo.toml. A global allocator is required.115116```toml117[dependencies]118anyhow = { version = "1.0", default-features = false }119```120121Since the `?`-based error conversions would normally rely on the122`std::error::Error` trait which is only available through std, no_std mode will123require an explicit `.map_err(Error::msg)` when working with a non-Anyhow error124type inside a function that returns Anyhow's error type.125126<br>127128## Comparison to failure129130The `anyhow::Error` type works something like `failure::Error`, but unlike131failure ours is built around the standard library's `std::error::Error` trait
32 unmodified lines