compio_buf/
buf_result.rs

1use std::io;
2#[cfg(feature = "try_trait_v2")]
3use std::{
4    convert::Infallible,
5    ops::{ControlFlow, FromResidual, Residual, Try},
6};
7
8use crate::IntoInner;
9
10/// A specialized `Result` type for operations with buffers.
11///
12/// This type is used as a return value for asynchronous compio methods that
13/// require passing ownership of a buffer to the runtime. When the operation
14/// completes, the buffer is returned no matter if the operation completed
15/// successfully.
16#[must_use]
17pub struct BufResult<T, B>(pub io::Result<T>, pub B);
18
19impl<T, B> BufResult<T, B> {
20    /// Returns [`true`] if the result is [`Ok`].
21    pub const fn is_ok(&self) -> bool {
22        self.0.is_ok()
23    }
24
25    /// Returns [`true`] if the result is [`Err`].
26    pub const fn is_err(&self) -> bool {
27        self.0.is_err()
28    }
29
30    /// Maps the result part, and allows updating the buffer.
31    #[inline]
32    pub fn map<U>(self, f: impl FnOnce(T, B) -> (U, B)) -> BufResult<U, B> {
33        match self.0 {
34            Ok(res) => {
35                let (res, buf) = f(res, self.1);
36                BufResult(Ok(res), buf)
37            }
38            Err(e) => BufResult(Err(e), self.1),
39        }
40    }
41
42    /// Maps the result part, and allows changing the buffer type.
43    #[inline]
44    pub fn map2<U, C>(
45        self,
46        f_ok: impl FnOnce(T, B) -> (U, C),
47        f_err: impl FnOnce(B) -> C,
48    ) -> BufResult<U, C> {
49        match self.0 {
50            Ok(res) => {
51                let (res, buf) = f_ok(res, self.1);
52                BufResult(Ok(res), buf)
53            }
54            Err(e) => BufResult(Err(e), f_err(self.1)),
55        }
56    }
57
58    /// Maps the result part, and keeps the buffer unchanged.
59    #[inline]
60    pub fn map_res<U>(self, f: impl FnOnce(T) -> U) -> BufResult<U, B> {
61        BufResult(self.0.map(f), self.1)
62    }
63
64    /// Maps the buffer part, and keeps the result unchanged.
65    #[inline]
66    pub fn map_buffer<C>(self, f: impl FnOnce(B) -> C) -> BufResult<T, C> {
67        BufResult(self.0, f(self.1))
68    }
69
70    /// Updating the result type and modifying the buffer.
71    #[inline]
72    pub fn and_then<U>(self, f: impl FnOnce(T, B) -> (io::Result<U>, B)) -> BufResult<U, B> {
73        match self.0 {
74            Ok(res) => BufResult::from(f(res, self.1)),
75            Err(e) => BufResult(Err(e), self.1),
76        }
77    }
78
79    /// Returns the contained [`Ok`] value, consuming the `self` value.
80    #[inline]
81    pub fn expect(self, msg: &str) -> (T, B) {
82        (self.0.expect(msg), self.1)
83    }
84
85    /// Returns the contained [`Ok`] value, consuming the `self` value.
86    #[inline]
87    pub fn unwrap(self) -> (T, B) {
88        (self.0.unwrap(), self.1)
89    }
90}
91
92impl<T, B> From<(io::Result<T>, B)> for BufResult<T, B> {
93    fn from((res, buf): (io::Result<T>, B)) -> Self {
94        Self(res, buf)
95    }
96}
97
98impl<T, B> From<BufResult<T, B>> for (io::Result<T>, B) {
99    fn from(BufResult(res, buf): BufResult<T, B>) -> Self {
100        (res, buf)
101    }
102}
103
104impl<T: IntoInner, O> IntoInner for BufResult<O, T> {
105    type Inner = BufResult<O, T::Inner>;
106
107    fn into_inner(self) -> Self::Inner {
108        BufResult(self.0, self.1.into_inner())
109    }
110}
111
112/// ```
113/// # use compio_buf::BufResult;
114/// fn foo() -> BufResult<i32, i32> {
115///     let (a, b) = BufResult(Ok(1), 2)?;
116///     assert_eq!(a, 1);
117///     assert_eq!(b, 2);
118///     (Ok(3), 4).into()
119/// }
120/// assert!(foo().is_ok());
121/// ```
122#[cfg(feature = "try_trait_v2")]
123impl<T, B> FromResidual<BufResult<Infallible, B>> for BufResult<T, B> {
124    fn from_residual(residual: BufResult<Infallible, B>) -> Self {
125        match residual {
126            BufResult(Err(e), b) => BufResult(Err(e), b),
127        }
128    }
129}
130
131/// ```
132/// # use compio_buf::BufResult;
133/// fn foo() -> std::io::Result<i32> {
134///     let (a, b) = BufResult(Ok(1), 2)?;
135///     assert_eq!(a, 1);
136///     assert_eq!(b, 2);
137///     Ok(3)
138/// }
139/// assert!(foo().is_ok());
140/// ```
141#[cfg(feature = "try_trait_v2")]
142impl<T, B> FromResidual<BufResult<Infallible, B>> for io::Result<T> {
143    fn from_residual(residual: BufResult<Infallible, B>) -> Self {
144        match residual {
145            BufResult(Err(e), _) => Err(e),
146        }
147    }
148}
149
150#[cfg(feature = "try_trait_v2")]
151impl<T, B> Try for BufResult<T, B> {
152    type Output = (T, B);
153    type Residual = BufResult<Infallible, B>;
154
155    fn from_output((res, buf): Self::Output) -> Self {
156        Self(Ok(res), buf)
157    }
158
159    fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
160        match self {
161            BufResult(Ok(res), buf) => ControlFlow::Continue((res, buf)),
162            BufResult(Err(e), buf) => ControlFlow::Break(BufResult(Err(e), buf)),
163        }
164    }
165}
166
167#[cfg(feature = "try_trait_v2")]
168impl<T, B> Residual<(T, B)> for BufResult<Infallible, B> {
169    type TryType = BufResult<T, B>;
170}
171
172/// A helper macro to imitate the behavior of try trait `?`.
173/// ```
174/// # use compio_buf::{buf_try, BufResult};
175/// fn foo() -> BufResult<i32, i32> {
176///     let (a, b) = buf_try!(BufResult(Ok(1), 2));
177///     assert_eq!(a, 1);
178///     assert_eq!(b, 2);
179///     (Ok(3), 4).into()
180/// }
181/// assert!(foo().is_ok());
182/// ```
183#[macro_export]
184macro_rules! buf_try {
185    ($e:expr) => {{
186        match $e {
187            $crate::BufResult(Ok(res), buf) => (res, buf),
188            $crate::BufResult(Err(e), buf) => return $crate::BufResult(Err(e), buf),
189        }
190    }};
191    ($e:expr, $b:expr) => {{
192        let buf = $b;
193        match $e {
194            Ok(res) => (res, buf),
195            Err(e) => return $crate::BufResult(Err(e), buf),
196        }
197    }};
198    (@try $e:expr) => {{
199        let $crate::BufResult(res, buf) = $e;
200        (res?, buf)
201    }};
202}