vortex_error/
ext.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use crate::VortexResult;
5
6/// Extension trait for VortexResult
7pub trait ResultExt<T>: private::Sealed {
8    /// Unnest a nested [`VortexResult`]. Helper function until <https://github.com/rust-lang/rust/issues/70142> is stabilized.
9    fn unnest(self) -> VortexResult<T>;
10}
11
12mod private {
13    use crate::VortexResult;
14
15    pub trait Sealed {}
16
17    impl<T> Sealed for VortexResult<VortexResult<T>> {}
18}
19
20impl<T> ResultExt<T> for VortexResult<VortexResult<T>> {
21    fn unnest(self) -> VortexResult<T> {
22        match self {
23            Ok(Ok(v)) => Ok(v),
24            Ok(Err(e)) | Err(e) => Err(e),
25        }
26    }
27}
28
29#[cfg(test)]
30mod tests {
31    use super::*;
32
33    #[test]
34    fn basic_example() {
35        let r: VortexResult<VortexResult<usize>> = Ok(Ok(5_usize));
36
37        // Only need to unwrap once!
38        assert_eq!(5, r.unnest().unwrap());
39    }
40}