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
203
204
205
206
207
208
209
210
211
212
213
////////////////////////////////////////////////////////////////////////////////
// Few -- A generalization of `std::Option` allowing for up to two optional
// values.
////////////////////////////////////////////////////////////////////////////////
// Copyright 2020 Skylor R. Schermer
// This code is dual licenced using the MIT or Apache 2 license.
// See licence-mit.md and licence-apache.md for details.
////////////////////////////////////////////////////////////////////////////////
//! Few library.
////////////////////////////////////////////////////////////////////////////////
#![warn(anonymous_parameters)]
#![warn(bad_style)]
#![warn(bare_trait_objects)]
#![warn(const_err)]
#![warn(dead_code)]
#![warn(elided_lifetimes_in_paths)]
#![warn(improper_ctypes)]
#![warn(missing_copy_implementations)]
#![warn(missing_debug_implementations)]
#![warn(missing_doc_code_examples)]
#![warn(missing_docs)]
#![warn(no_mangle_generic_items)]
#![warn(non_shorthand_field_patterns)]
#![warn(nonstandard_style)]
#![warn(overflowing_literals)]
#![warn(path_statements)]
#![warn(patterns_in_fns_without_body)]
#![warn(private_in_public)]
#![warn(rust_2018_idioms)]
#![warn(trivial_casts)]
#![warn(trivial_numeric_casts)]
#![warn(unconditional_recursion)]
#![warn(unreachable_pub)]
#![warn(unused)]
#![warn(unused_allocation)]
#![warn(unused_comparisons)]
#![warn(unused_parens)]
#![warn(unused_qualifications)]
#![warn(unused_results)]
#![warn(variant_size_differences)]
#![warn(while_true)]


////////////////////////////////////////////////////////////////////////////////
// Few
////////////////////////////////////////////////////////////////////////////////
/// A type which may contain zero, one, or two of a value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Few<T> {
    /// No value present.
    Zero,
    /// One value present.
    One(T),
    /// Two values present.
    Two(T, T),
}

impl<T> Few<T> {
    /// Returns true if the `Few` is a `Zero` value.
    pub fn is_zero(&self) -> bool {
        match self {
            Few::Zero => true,
            _         => false,
        }
    }

    /// Returns true if the `Few` is a `One` value.
    pub fn is_one(&self) -> bool {
        match self {
            Few::One(_) => true,
            _           => false,
        }
    }

    /// Returns true if the `Few` is a `Two` value.
    pub fn is_two(&self) -> bool {
        match self {
            Few::Two(_, _) => true,
            _              => false,
        }
    }

    /// Returns true if the `Few` is a `One` or `Two` value containing the given
    /// value.
    pub fn contains<U>(&self, x: &U) -> bool
        where U: PartialEq<T>
    {
        match self {
            Few::Zero      => false,
            Few::One(v)    => x == v,
            Few::Two(a, b) => x == a || x == b,
        }
    }
}

impl<T> Iterator for Few<T> {
    type Item = T;

    fn next(&mut self) -> Option<T> {
        let mut res = None;
        replace_with(self, |curr|
            match curr {
                Few::Zero      => { res = None;    Few::Zero },
                Few::One(v)    => { res = Some(v); Few::Zero },
                Few::Two(a, b) => { res = Some(a); Few::One(b) },
            }
        );
        res
    }
}

impl<T> DoubleEndedIterator for Few<T> {
    fn next_back(&mut self) -> Option<T> {
        let mut res = None;
        replace_with(self, |curr|
            match curr {
                Few::Zero      => { res = None;    Few::Zero },
                Few::One(v)    => { res = Some(v); Few::Zero },
                Few::Two(a, b) => { res = Some(b); Few::One(a) },
            }
        );
        res
    }
}

impl<T> ExactSizeIterator for Few<T> {
    fn len(&self) -> usize {
        match self {
            Few::Zero      => 0,
            Few::One(_)    => 1,
            Few::Two(_, _) => 2,
        }
    }
}

impl<T> std::iter::FusedIterator for Few<T> {}


impl<T> Default for Few<T> {
    fn default() -> Self {
        Few::Zero
    }
}

impl<T> From<T> for Few<T> {
    fn from(value: T) -> Self {
        Few::One(value)
    }
}

impl<T> From<(T, T)> for Few<T> {
    fn from(value: (T, T)) -> Self {
        Few::Two(value.0, value.1)
    }
}

impl<T> From<Option<T>> for Few<T> {
    fn from(value: Option<T>) -> Self {
        match value {
            None        => Few::Zero,
            Some(value) => Few::One(value),
        }
    }
}

impl<T> From<Option<(T, T)>> for Few<T> {
    fn from(value: Option<(T, T)>) -> Self {
        match value {
            None         => Few::Zero,
            Some((a, b)) => Few::Two(a, b),
        }
    }
}

impl<T> From<(Option<T>, Option<T>)> for Few<T> {
    fn from(value: (Option<T>, Option<T>)) -> Self {
        match (value.0, value.1) {
            (None,    None)    => Few::Zero,
            (Some(a), None)    => Few::One(a),
            (None,    Some(b)) => Few::One(b),
            (Some(a), Some(b)) => Few::Two(a, b),
        }
    }
}



////////////////////////////////////////////////////////////////////////////////
// replace_with
////////////////////////////////////////////////////////////////////////////////
/// Replaces the value behind a mut reference with the result of a closure
/// called on the value. Will abort if a panic occurs in the given closure.
#[inline]
fn replace_with<T, F>(val: &mut T, replace: F)
    where F: FnOnce(T) -> T {
    let guard = ExitGuard;

    unsafe {
        let old = std::ptr::read(val);
        let new = replace(old);
        std::ptr::write(val, new);
    }

    std::mem::forget(guard);
}

struct ExitGuard;

impl Drop for ExitGuard {
    fn drop(&mut self) {
        panic!("`replace_with` closure unwind");
    }
}