orx_iterable/sources/
once.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
use crate::{Collection, CollectionMut, Iterable};

/// An iterable which yields a wrapped value only once.
pub struct Once<T>
where
    T: Clone,
{
    value: T,
}

impl<T> Iterable for Once<T>
where
    T: Clone,
{
    type Item = T;

    type Iter = core::iter::Once<T>;

    fn iter(&self) -> Self::Iter {
        core::iter::once(self.value.clone())
    }
}

impl<T> Iterable for core::iter::Once<T>
where
    T: Clone,
{
    type Item = T;

    type Iter = core::iter::Once<T>;

    fn iter(&self) -> Self::Iter {
        self.clone()
    }
}

// col

/// An iterable collection having only one item.
pub struct OnceCol<T> {
    value: T,
}

impl<'a, T> Iterable for &'a OnceCol<T> {
    type Item = &'a T;

    type Iter = core::iter::Once<Self::Item>;

    fn iter(&self) -> Self::Iter {
        core::iter::once(&self.value)
    }
}

impl<T> Collection for OnceCol<T> {
    type Item = T;

    type Iterable<'i> = &'i Self
    where
        Self: 'i;

    fn as_iterable(&self) -> Self::Iterable<'_> {
        self
    }
}

impl<T> CollectionMut for OnceCol<T> {
    type IterMut<'i> = core::iter::Once<&'i mut T>
    where
        Self: 'i;

    fn iter_mut(&mut self) -> Self::IterMut<'_> {
        core::iter::once(&mut self.value)
    }
}

/// Creates an iterable which yields only one `value`.
pub fn once<T>(value: T) -> Once<T>
where
    T: Clone,
{
    Once { value }
}

/// Creates an iterable collection having only one element with the given `value`.
pub fn once_col<T>(value: T) -> OnceCol<T> {
    OnceCol { value }
}