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
Provenance
- Commit
55343b9- Tree
7981e88- Author
David Tolnay <dtolnay@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
e48b330- Parent 2
10156dd
11 files changed+158 added−39 removed
modified:src/backtrace.rs+1 added-1 removed
26 unmodified lines27 }28 };29 }30 31-#[cfg(not(backtrace))]31+#[cfg(all(feature = "std", not(backtrace)))]32 macro_rules! backtrace_if_absent {33 ($err:expr) => {34 None35 };1 unmodified linemodified:src/chain.rs+17 added-3 removed
1-use self::ChainState::{Buffered, Linked};2-use crate::Chain;3-use std::error::Error as StdError;1+use self::ChainState::*;2+use crate::StdError;3+4+#[cfg(feature = "std")]5 use std::vec;6 7+#[cfg(feature = "std")]8+pub(crate) use crate::Chain;9+10+#[cfg(not(feature = "std"))]11+pub(crate) struct Chain<'a> {12+ state: ChainState<'a>,13+}14+15 #[derive(Clone)]16 pub(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 lines40 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 lines51 (len, Some(len))52 }53 }54 55+#[cfg(feature = "std")]56 impl DoubleEndedIterator for Chain<'_> {57 fn next_back(&mut self) -> Option<Self::Item> {58 match &mut self.state {59 Linked { mut next } => {22 unmodified lines82 len += 1;83 }84 len85 }86+ #[cfg(feature = "std")]87 Buffered { rest } => rest.len(),88 }89 }90 }91 92+#[cfg(feature = "std")]93 impl Default for Chain<'_> {94 fn default() -> Self {95 Chain {96 state: ChainState::Buffered {5 unmodified linesmodified:src/context.rs+5 added-5 removed
1 use crate::error::ContextError;2-use crate::{Context, Error};3-use std::convert::Infallible;4-use std::error::Error as StdError;5-use std::fmt::{self, Debug, Display, Write};2+use crate::{Context, Error, StdError};3+use core::convert::Infallible;4+use core::fmt::{self, Debug, Display, Write};5 6 #[cfg(backtrace)]7 use std::backtrace::Backtrace;8 5 unmodified lines14 where15 C: Display + Send + Sync + 'static;16 }17 18+ #[cfg(feature = "std")]19 impl<E> StdError for E20 where21 E: std::error::Error + Send + Sync + 'static,22 {119 unmodified lines142 Some(self.error.backtrace())143 }144 145 fn source(&self) -> Option<&(dyn StdError + 'static)> {146- Some(&*self.error)146+ Some(self.error.inner.error())147 }148 }149 150 struct Quoted<C>(C);27 unmodified linesmodified:src/error.rs+35 added-8 removed
1+use crate::alloc::Box;2 use crate::backtrace::Backtrace;2-use crate::wrapper::{BoxedError, DisplayError, MessageError};3-use crate::{Chain, Error};4-use std::any::TypeId;5-use std::error::Error as StdError;6-use std::fmt::{self, Debug, Display};7-use std::mem::{self, ManuallyDrop};8-use std::ops::{Deref, DerefMut};9-use std::ptr::{self, NonNull};3+use crate::chain::Chain;4+use crate::{Error, StdError};5+use core::any::TypeId;6+use core::fmt::{self, Debug, Display};7+use core::mem::{self, ManuallyDrop};8+use core::ptr::{self, NonNull};9 10+#[cfg(feature = "std")]11+use core::ops::{Deref, DerefMut};12+13 impl 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 lines70 {71 Error::from_adhoc(message, backtrace!())72 }73 74+ #[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 lines93 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 lines114 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 lines131 // vtable to allow casting the DisplayError<M> to M.132 unsafe { Error::construct(error, vtable, backtrace) }133 }134 135+ #[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 lines142 143 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 lines153 // Safety: passing vtable that operates on the right type.154 unsafe { Error::construct(error, vtable, backtrace) }155 }156 157+ #[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 lines270 271 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 lines321 /// }322 /// None323 /// }324 /// ```325+ #[cfg(feature = "std")]326 pub fn chain(&self) -> Chain {327 self.inner.chain()328 }329 1 unmodified line331 /// 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 lines453 }454 }455 }456 457+#[cfg(feature = "std")]458 impl<E> From<E> for Error459 where460 E: StdError + Send + Sync + 'static,461 {2 unmodified lines464 Error::from_std(error, backtrace)465 }466 }467 468+#[cfg(feature = "std")]469 impl Deref for Error {470 type Target = dyn StdError + Send + Sync + 'static;471 472 fn deref(&self) -> &Self::Target {473 self.inner.error()474 }475 }476 477+#[cfg(feature = "std")]478 impl DerefMut for Error {479 fn deref_mut(&mut self) -> &mut Self::Target {480 self.inner.error_mut()481 }26 unmodified lines508 509 struct 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 lines543 &(*(e as *const ErrorImpl<()> as *const ErrorImpl<E>))._object544 }545 546 // Safety: requires layout of *e to match ErrorImpl<E>.547+#[cfg(feature = "std")]548 unsafe fn object_mut<E>(e: &mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static)549 where550 E: StdError + Send + Sync + 'static,551 {26 unmodified lines578 }579 }580 581 // Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.582+#[cfg(feature = "std")]583 unsafe fn context_downcast<C, E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>584 where585 C: 'static,586 E: 'static,11 unmodified lines598 }599 }600 601 // Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.602+#[cfg(feature = "std")]603 unsafe fn context_drop_rest<C, E>(e: Box<ErrorImpl<()>>, target: TypeId)604 where605 C: 'static,606 E: 'static,93 unmodified lines700 // original type E.701 unsafe { &*(self.vtable.object_ref)(self) }702 }703 704+ #[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 lines777 Box::<dyn StdError + Send + Sync>::from(error)778 }779 }780 781+#[cfg(feature = "std")]782 impl AsRef<dyn StdError + Send + Sync> for Error {783 fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {784 &**self785 }786 }787 788+#[cfg(feature = "std")]789 impl AsRef<dyn StdError> for Error {790 fn as_ref(&self) -> &(dyn StdError + 'static) {791 &**self792 }1 unmodified linemodified:src/fmt.rs+2 added-2 removed
1+use crate::chain::Chain;2 use crate::error::ErrorImpl;2-use crate::Chain;3-use std::fmt::{self, Debug};3+use core::fmt::{self, Debug};4 5 impl ErrorImpl<()> {6 pub(crate) fn display(&self, f: &mut fmt::Formatter) -> fmt::Result {7 write!(f, "{}", self.error())?;50 unmodified linesmodified:src/kind.rs+8 added-2 removed
43 unmodified lines44 // let error = $msg;45 // (&error).anyhow_kind().new(error)46 47 use crate::Error;48-use std::error::Error as StdError;49-use std::fmt::{Debug, Display};48+use core::fmt::{Debug, Display};49 50+#[cfg(feature = "std")]51+use crate::StdError;52+53 #[cfg(backtrace)]54 use std::backtrace::Backtrace;55 56 pub struct Adhoc;35 unmodified lines92 error.into()93 }94 }95 96+#[cfg(feature = "std")]97 pub struct Boxed;98 99+#[cfg(feature = "std")]100 pub trait BoxedKind: Sized {101 #[inline]102 fn anyhow_kind(&self) -> Boxed {103 Boxed104 }105 }106 107+#[cfg(feature = "std")]108 impl BoxedKind for Box<dyn StdError + Send + Sync> {}109 110+#[cfg(feature = "std")]111 impl 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 linesmodified:src/lib.rs+55 added-9 removed
156 unmodified lines157 //! 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.179 180 #![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 )]188 189+mod alloc {190+ #[cfg(not(feature = "std"))]191+ extern crate alloc;192+193+ #[cfg(not(feature = "std"))]194+ pub use alloc::boxed::Box;195+196+ #[cfg(feature = "std")]197+ pub use std::boxed::Box;198+}199+200 #[macro_use]201 mod backtrace;202 mod chain;203 mod context;2 unmodified lines206 mod kind;207 mod macros;208 mod wrapper;209 210+use crate::alloc::Box;211+use crate::error::ErrorImpl;212+use core::fmt::Display;213+use core::mem::ManuallyDrop;214+215 #[cfg(not(feature = "std"))]181-compile_error!("no_std support is not implemented yet");216+use core::fmt::Debug;217 183-use crate::chain::ChainState;184-use crate::error::ErrorImpl;185-use std::fmt::Display;186-use std::mem::ManuallyDrop;218+#[cfg(feature = "std")]219+use std::error::Error as StdError;220 221+#[cfg(not(feature = "std"))]222+trait StdError: Debug + Display {223+ fn source(&self) -> Option<&(dyn StdError + 'static)> {224+ None225+ }226+}227+228 pub use anyhow as format_err;229 230 /// The `Error` type, a wrapper around a dynamic error type.231 ///109 unmodified lines341 /// }342 /// None343 /// }344 /// ```345+#[cfg(feature = "std")]346 #[derive(Clone)]347 pub struct Chain<'a> {307- state: ChainState<'a>,348+ state: crate::chain::ChainState<'a>,349 }350 351 /// `Result<T, Error>`352 ///43 unmodified lines396 /// println!("cluster info: {:#?}", map);397 /// Ok(())398 /// }399 /// ```359-pub type Result<T, E = Error> = std::result::Result<T, E>;400+pub type Result<T, E = Error> = core::result::Result<T, E>;401 402 /// Provides the `context` method for `Result`.403 ///404 /// This trait is sealed and cannot be implemented for types outside of152 unmodified lines557 // Not public API. Referenced by macro-generated code.558 #[doc(hidden)]559 pub mod private {560 use crate::Error;520- use std::fmt::{Debug, Display};561+ use core::fmt::{Debug, Display};562 563 #[cfg(backtrace)]564 use std::backtrace::Backtrace;565 566+ pub use core::result::Result::Err;567+568 #[doc(hidden)]569 pub mod kind {527- pub use crate::kind::{AdhocKind, BoxedKind, TraitKind};570+ pub use crate::kind::{AdhocKind, TraitKind};571+572+ #[cfg(feature = "std")]573+ pub use crate::kind::BoxedKind;574 }575 576 pub fn new_adhoc<M>(message: M) -> Error577 where5 unmodified linesmodified:src/macros.rs+6 added-6 removed
48 unmodified lines49 /// ```50 #[macro_export]51 macro_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 }62 63 /// Return early with an error if a condition is not satisfied.43 unmodified lines107 #[macro_export]108 macro_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 linesmodified:src/wrapper.rs+6 added-2 removed
1-use std::error::Error as StdError;2-use std::fmt::{self, Debug, Display};1+use crate::StdError;2+use core::fmt::{self, Debug, Display};3 4 #[repr(transparent)]5 pub struct MessageError<M>(pub M);6 39 unmodified lines46 }47 48 impl<M> StdError for DisplayError<M> where M: Display + 'static {}49 50+#[cfg(feature = "std")]51 #[repr(transparent)]52 pub struct BoxedError(pub Box<dyn StdError + Send + Sync>);53 54+#[cfg(feature = "std")]55 impl Debug for BoxedError {56 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {57 Debug::fmt(&self.0, f)58 }59 }60 61+#[cfg(feature = "std")]62 impl Display for BoxedError {63 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {64 Display::fmt(&self.0, f)65 }66 }67 68+#[cfg(feature = "std")]69 impl StdError for BoxedError {70 #[cfg(backtrace)]71 fn backtrace(&self) -> Option<&crate::backtrace::Backtrace> {72 self.0.backtrace()6 unmodified linesmodified:.travis.yml+5 added-1 removed
3 unmodified lines4 - nightly5 - beta6 - stable7 8-script: cargo test8+script:9+ - cargo test10+ - cargo check --no-default-features11 12 matrix: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 01 unmodified linemodified:README.md+18 added
105 unmodified lines106 ```107 108 <br>109 110+## No-std support111+112+In no_std mode, the same API is almost all available and works the same way. To113+depend on Anyhow in no_std mode, disable our default enabled "std" feature in114+Cargo.toml. A global allocator is required.115+116+```toml117+[dependencies]118+anyhow = { version = "1.0", default-features = false }119+```120+121+Since the `?`-based error conversions would normally rely on the122+`std::error::Error` trait which is only available through std, no_std mode will123+require an explicit `.map_err(Error::msg)` when working with a non-Anyhow error124+type inside a function that returns Anyhow's error type.125+126+<br>127+128 ## Comparison to failure129 130 The `anyhow::Error` type works something like `failure::Error`, but unlike131 failure ours is built around the standard library's `std::error::Error` trait32 unmodified lines