compio_buf/
buf_result.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
use std::io;
#[cfg(feature = "try_trait_v2")]
use std::{
    convert::Infallible,
    ops::{ControlFlow, FromResidual, Residual, Try},
};

use crate::IntoInner;

/// A specialized `Result` type for operations with buffers.
///
/// This type is used as a return value for asynchronous compio methods that
/// require passing ownership of a buffer to the runtime. When the operation
/// completes, the buffer is returned no matter if the operation completed
/// successfully.
#[must_use]
pub struct BufResult<T, B>(pub io::Result<T>, pub B);

impl<T, B> BufResult<T, B> {
    /// Returns [`true`] if the result is [`Ok`].
    pub const fn is_ok(&self) -> bool {
        self.0.is_ok()
    }

    /// Returns [`true`] if the result is [`Err`].
    pub const fn is_err(&self) -> bool {
        self.0.is_err()
    }

    /// Maps the result part, and allows updating the buffer.
    #[inline]
    pub fn map<U>(self, f: impl FnOnce(T, B) -> (U, B)) -> BufResult<U, B> {
        match self.0 {
            Ok(res) => {
                let (res, buf) = f(res, self.1);
                BufResult(Ok(res), buf)
            }
            Err(e) => BufResult(Err(e), self.1),
        }
    }

    /// Maps the result part, and allows changing the buffer type.
    #[inline]
    pub fn map2<U, C>(
        self,
        f_ok: impl FnOnce(T, B) -> (U, C),
        f_err: impl FnOnce(B) -> C,
    ) -> BufResult<U, C> {
        match self.0 {
            Ok(res) => {
                let (res, buf) = f_ok(res, self.1);
                BufResult(Ok(res), buf)
            }
            Err(e) => BufResult(Err(e), f_err(self.1)),
        }
    }

    /// Maps the result part, and keeps the buffer unchanged.
    #[inline]
    pub fn map_res<U>(self, f: impl FnOnce(T) -> U) -> BufResult<U, B> {
        BufResult(self.0.map(f), self.1)
    }

    /// Maps the buffer part, and keeps the result unchanged.
    #[inline]
    pub fn map_buffer<C>(self, f: impl FnOnce(B) -> C) -> BufResult<T, C> {
        BufResult(self.0, f(self.1))
    }

    /// Updating the result type and modifying the buffer.
    #[inline]
    pub fn and_then<U>(self, f: impl FnOnce(T, B) -> (io::Result<U>, B)) -> BufResult<U, B> {
        match self.0 {
            Ok(res) => BufResult::from(f(res, self.1)),
            Err(e) => BufResult(Err(e), self.1),
        }
    }

    /// Returns the contained [`Ok`] value, consuming the `self` value.
    #[inline]
    pub fn expect(self, msg: &str) -> (T, B) {
        (self.0.expect(msg), self.1)
    }

    /// Returns the contained [`Ok`] value, consuming the `self` value.
    #[inline]
    pub fn unwrap(self) -> (T, B) {
        (self.0.unwrap(), self.1)
    }
}

impl<T, B> From<(io::Result<T>, B)> for BufResult<T, B> {
    fn from((res, buf): (io::Result<T>, B)) -> Self {
        Self(res, buf)
    }
}

impl<T, B> From<BufResult<T, B>> for (io::Result<T>, B) {
    fn from(BufResult(res, buf): BufResult<T, B>) -> Self {
        (res, buf)
    }
}

impl<T: IntoInner, O> IntoInner for BufResult<O, T> {
    type Inner = BufResult<O, T::Inner>;

    fn into_inner(self) -> Self::Inner {
        BufResult(self.0, self.1.into_inner())
    }
}

/// ```
/// # use compio_buf::BufResult;
/// fn foo() -> BufResult<i32, i32> {
///     let (a, b) = BufResult(Ok(1), 2)?;
///     assert_eq!(a, 1);
///     assert_eq!(b, 2);
///     (Ok(3), 4).into()
/// }
/// assert!(foo().is_ok());
/// ```
#[cfg(feature = "try_trait_v2")]
impl<T, B> FromResidual<BufResult<Infallible, B>> for BufResult<T, B> {
    fn from_residual(residual: BufResult<Infallible, B>) -> Self {
        match residual {
            BufResult(Err(e), b) => BufResult(Err(e), b),
        }
    }
}

/// ```
/// # use compio_buf::BufResult;
/// fn foo() -> std::io::Result<i32> {
///     let (a, b) = BufResult(Ok(1), 2)?;
///     assert_eq!(a, 1);
///     assert_eq!(b, 2);
///     Ok(3)
/// }
/// assert!(foo().is_ok());
/// ```
#[cfg(feature = "try_trait_v2")]
impl<T, B> FromResidual<BufResult<Infallible, B>> for io::Result<T> {
    fn from_residual(residual: BufResult<Infallible, B>) -> Self {
        match residual {
            BufResult(Err(e), _) => Err(e),
        }
    }
}

#[cfg(feature = "try_trait_v2")]
impl<T, B> Try for BufResult<T, B> {
    type Output = (T, B);
    type Residual = BufResult<Infallible, B>;

    fn from_output((res, buf): Self::Output) -> Self {
        Self(Ok(res), buf)
    }

    fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
        match self {
            BufResult(Ok(res), buf) => ControlFlow::Continue((res, buf)),
            BufResult(Err(e), buf) => ControlFlow::Break(BufResult(Err(e), buf)),
        }
    }
}

#[cfg(feature = "try_trait_v2")]
impl<T, B> Residual<(T, B)> for BufResult<Infallible, B> {
    type TryType = BufResult<T, B>;
}

/// A helper macro to imitate the behavior of try trait `?`.
/// ```
/// # use compio_buf::{buf_try, BufResult};
/// fn foo() -> BufResult<i32, i32> {
///     let (a, b) = buf_try!(BufResult(Ok(1), 2));
///     assert_eq!(a, 1);
///     assert_eq!(b, 2);
///     (Ok(3), 4).into()
/// }
/// assert!(foo().is_ok());
/// ```
#[macro_export]
macro_rules! buf_try {
    ($e:expr) => {{
        match $e {
            $crate::BufResult(Ok(res), buf) => (res, buf),
            $crate::BufResult(Err(e), buf) => return $crate::BufResult(Err(e), buf),
        }
    }};
    ($e:expr, $b:expr) => {{
        let buf = $b;
        match $e {
            Ok(res) => (res, buf),
            Err(e) => return $crate::BufResult(Err(e), buf),
        }
    }};
    (@try $e:expr) => {{
        let $crate::BufResult(res, buf) = $e;
        (res?, buf)
    }};
}