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
//! # unflatten
//!
//! `unflatten` is a <sup>[joke of a]</sup> library which provides one thing:
//!
//! ```rs
//! use unflatten::Unflatten;
//!
//! let option = Some("body once told me");
//! let unflattened = option.unflatten();
//!
//! assert_eq!(unflattened, Some(Some("body once told me")));
//! ```
//!
#![no_std]

mod sealed {
    pub trait Sealed {}
}

use sealed::Sealed;

pub trait Unflatten: Sealed + Sized {
    fn unflatten(self) -> Option<Self> {
        Some(self)
    }
}

impl<T>    Sealed for Option<T> {}
impl<T> Unflatten for Option<T> {}

#[cfg(test)]
mod tests {
    use super::Unflatten;

    #[test]
    fn unflattening_some_works() {
        let x: Option<i32> = Some(1);

        assert_eq!(x.unflatten(), Some(Some(1)));
    }

    #[test]
    fn unflattening_none_works() {
        let x: Option<i32> = None;

        assert_eq!(x.unflatten(), Some(None));
    }

    #[test]
    fn flattening_unflattened_some_returns_same() {
        let x: Option<i32> = Some(1);

        assert_eq!(x.unflatten().flatten(), x);
    }

    #[test]
    fn flattening_unflattened_none_returns_same() {
        let x: Option<i32> = None;

        assert_eq!(x.unflatten().flatten(), x);
    }

    #[test]
    fn unflattening_flattened_some_returns_same() {
        let x: Option<Option<i32>> = Some(Some(1));

        assert_eq!(x.flatten().unflatten(), x);
    }
}