mc_sgx_util/lib.rs
1// Copyright (c) 2022-2024 The MobileCoin Foundation
2
3#![doc = include_str!("../README.md")]
4#![no_std]
5#![deny(missing_docs, missing_debug_implementations, unsafe_code)]
6
7mod format;
8pub use format::fmt_hex;
9
10/// A trait to add to an error type which can be constructed from an underlying
11/// "status" type which contains both success and failure codes.
12///
13/// The goal is to be able to convert a unified status type into a `Result<T,
14/// Error>` type.
15///
16/// # Examples
17///
18/// ```rust
19/// use mc_sgx_util::ResultFrom;
20///
21/// /// An example FFI type
22/// #[allow(non_camel_case_types)]
23/// #[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
24/// pub struct a_status_t(u32);
25///
26/// impl a_status_t {
27/// const SUCCESS: a_status_t = a_status_t(0);
28/// const FAIL: a_status_t = a_status_t(1);
29/// }
30///
31/// /// An example rusty enum wrapper for a_status_t
32/// #[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
33/// pub enum AnError {
34/// Stuff,
35/// Unknown
36/// }
37///
38/// impl TryFrom<a_status_t> for AnError {
39/// type Error = ();
40///
41/// fn try_from(value: a_status_t) -> Result<Self, ()> {
42/// match value {
43/// a_status_t::SUCCESS => Err(()),
44/// a_status_t::FAIL => Ok(AnError::Stuff),
45/// _ => Ok(AnError::Unknown)
46/// }
47/// }
48/// }
49///
50/// // Pick up the default implementation of [`ResultFrom`]
51/// impl ResultFrom<a_status_t> for AnError {}
52///
53/// let status = a_status_t::SUCCESS;
54/// assert_eq!(Ok(()), AnError::result_from(status));
55///
56/// let status = a_status_t::FAIL;
57/// assert_eq!(Err(AnError::Stuff), AnError::result_from(status));
58/// ```
59pub trait ResultFrom<ST>: TryFrom<ST> {
60 /// Flips the result of a `TryFrom`.
61 fn result_from(status: ST) -> Result<<Self as TryFrom<ST>>::Error, Self> {
62 match Self::try_from(status) {
63 Ok(err) => Err(err),
64 Err(success_val) => Ok(success_val),
65 }
66 }
67}
68
69/// An inverse of the [`ResultFrom`] trait, which is attached to the status
70/// type.
71///
72/// As with [`TryInto`](core::convert::TryInto), this trait is not intended to
73/// be implemented manually, but instead should be added to an FFI type via
74/// explicit impl block attached to it's derivative wrapper type.
75///
76/// ```rust,ignore
77/// // Pick up the default implementation of [`ResultInto`]
78/// impl ResultInto<AnError> for a_status_t {}
79/// ```
80///
81/// That is, users should not attach this to a bindgen-generated status type,
82/// they should attach [`ResultFrom`] to the intended error wrapper associated
83/// with it, and they will get this for free.
84pub trait ResultInto<T: TryFrom<Self>>: Sized {
85 /// Flips the result of `T::TryFrom<Self>`.
86 fn into_result(self) -> Result<<T as TryFrom<Self>>::Error, T> {
87 match T::try_from(self) {
88 Ok(err) => Err(err),
89 Err(success_val) => Ok(success_val),
90 }
91 }
92}