mls_rs_core/
error.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// Copyright by contributors to this project.
3// SPDX-License-Identifier: (Apache-2.0 OR MIT)
4
5use core::fmt::{self, Display};
6
7#[cfg(feature = "std")]
8#[derive(Debug)]
9/// Generic error used to wrap errors produced by providers.
10pub struct AnyError(Box<dyn std::error::Error + Send + Sync>);
11
12#[cfg(not(feature = "std"))]
13#[derive(Debug)]
14pub struct AnyError;
15
16#[cfg(feature = "std")]
17impl Display for AnyError {
18    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19        self.0.fmt(f)
20    }
21}
22
23#[cfg(feature = "std")]
24impl std::error::Error for AnyError {
25    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
26        self.0.source()
27    }
28}
29
30#[cfg(not(feature = "std"))]
31impl Display for AnyError {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        core::fmt::Debug::fmt(self, f)
34    }
35}
36
37/// Trait to convert a provider specific error into [`AnyError`]
38pub trait IntoAnyError: core::fmt::Debug + Sized {
39    #[cfg(feature = "std")]
40    fn into_any_error(self) -> AnyError {
41        self.into_dyn_error()
42            .map_or_else(|this| AnyError(format!("{this:?}").into()), AnyError)
43    }
44
45    #[cfg(not(feature = "std"))]
46    fn into_any_error(self) -> AnyError {
47        AnyError
48    }
49
50    #[cfg(feature = "std")]
51    fn into_dyn_error(self) -> Result<Box<dyn std::error::Error + Send + Sync>, Self> {
52        Err(self)
53    }
54}
55
56impl IntoAnyError for mls_rs_codec::Error {
57    #[cfg(feature = "std")]
58    fn into_dyn_error(self) -> Result<Box<dyn std::error::Error + Send + Sync>, Self> {
59        Ok(self.into())
60    }
61}
62
63impl IntoAnyError for core::convert::Infallible {}