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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
use num_traits::{One, Zero};
use std::fmt;
use std::iter::FromIterator;
use std::ops::RangeInclusive;

use crate::Position;

/// A range on a board.
///
/// This range consists of four pieces of information: the minimum and maximum x-coordinate values and the minimum and maximum y-coordinate values.
/// The type parameter `T` is used as the type of the x- and y-coordinate values.
///
/// # Examples
///
/// ```
/// use life_backend::{BoardRange, Position};
/// let positions = [Position(0, 0), Position(1, 0), Position(2, 0), Position(1, 1)];
/// let range: BoardRange<_> = positions.iter().collect();
/// let min_x = range.x().start();
/// let max_x = range.x().end();
/// let min_y = range.y().start();
/// let max_y = range.y().end();
/// assert_eq!(min_x, &0);
/// assert_eq!(max_x, &2);
/// assert_eq!(min_y, &0);
/// assert_eq!(max_y, &1);
/// ```
///
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct BoardRange<T>(RangeInclusive<T>, RangeInclusive<T>);

// Inherent methods

impl<T> BoardRange<T> {
    /// Creates an empty range.
    ///
    /// # Examples
    ///
    /// ```
    /// use life_backend::BoardRange;
    /// let range = BoardRange::<i32>::new();
    /// assert!(range.is_empty());
    /// ```
    ///
    pub fn new() -> Self
    where
        T: Zero + One,
    {
        Self(T::one()..=T::zero(), T::one()..=T::zero())
    }

    // Implementation of public extend().
    fn extend<U>(self, iter: U) -> Self
    where
        T: Copy + PartialOrd + Zero + One,
        U: Iterator<Item = Position<T>>,
    {
        iter.fold(self, |acc, Position(x, y)| {
            if acc.is_empty() {
                Self(x..=x, y..=y)
            } else {
                let (range_x, range_y) = acc.into_inner();
                let (x_start, x_end) = range_x.into_inner();
                let (y_start, y_end) = range_y.into_inner();
                Self(
                    (if x_start < x { x_start } else { x })..=(if x_end > x { x_end } else { x }),
                    (if y_start < y { y_start } else { y })..=(if y_end > y { y_end } else { y }),
                )
            }
        })
    }

    // Implementation of public from_iter().
    fn from_iter<U>(iter: U) -> Self
    where
        T: Copy + PartialOrd + Zero + One,
        U: Iterator<Item = Position<T>>,
    {
        Self::new().extend(iter)
    }

    /// Returns the range on the x-coordinate.
    ///
    /// # Examples
    ///
    /// ```
    /// use life_backend::{BoardRange, Position};
    /// let positions = [Position(0, 0), Position(1, 0), Position(2, 0), Position(1, 1)];
    /// let range: BoardRange<_> = positions.iter().collect();
    /// assert_eq!(range.x(), &(0..=2));
    /// ```
    ///
    #[inline]
    pub const fn x(&self) -> &RangeInclusive<T> {
        &self.0
    }

    /// Returns the range on the y-coordinate.
    ///
    /// # Examples
    ///
    /// ```
    /// use life_backend::{BoardRange, Position};
    /// let positions = [Position(0, 0), Position(1, 0), Position(2, 0), Position(1, 1)];
    /// let range: BoardRange<_> = positions.iter().collect();
    /// assert_eq!(range.y(), &(0..=1));
    /// ```
    ///
    #[inline]
    pub const fn y(&self) -> &RangeInclusive<T> {
        &self.1
    }

    /// Destructures [`BoardRange`] into (range-x, range-y).
    ///
    /// # Examples
    ///
    /// ```
    /// use life_backend::{BoardRange, Position};
    /// let positions = [Position(0, 0), Position(1, 0), Position(2, 0), Position(1, 1)];
    /// let range: BoardRange<_> = positions.iter().collect();
    /// let (range_x, range_y) = range.into_inner();
    /// assert_eq!(range_x, 0..=2);
    /// assert_eq!(range_y, 0..=1);
    /// ```
    ///
    #[inline]
    pub fn into_inner(self) -> (RangeInclusive<T>, RangeInclusive<T>) {
        (self.0, self.1)
    }

    /// Returns `true` if the range contains no area.
    ///
    /// If the range is empty, return values of methods are defined as the following:
    ///
    /// - `range.is_empty()` is `true`
    /// - `range.x().is_empty()` and `range.y().is_empty()` are `true`
    /// - `range.x().start()`, `range.x().end()`, `range.y().start()` and `range.y().end()` are unspecified
    ///
    /// # Examples
    ///
    /// ```
    /// use life_backend::{BoardRange, Position};
    /// let positions = [Position(0, 0), Position(1, 0), Position(2, 0), Position(1, 1)];
    /// let range: BoardRange<_> = positions.iter().collect();
    /// assert!(!range.is_empty());
    /// ```
    ///
    #[inline]
    pub fn is_empty(&self) -> bool
    where
        T: PartialOrd,
    {
        self.x().is_empty()
    }
}

// Trait implementations

impl<T> Default for BoardRange<T>
where
    T: Zero + One,
{
    /// Returns the default value of the type, same as the return value of [`new()`].
    ///
    /// [`new()`]: #method.new
    ///
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<T> fmt::Display for BoardRange<T>
where
    T: PartialOrd + fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.is_empty() {
            write!(f, "(empty)")?;
        } else {
            write!(
                f,
                "(x:[{}, {}], y:[{}, {}])",
                self.x().start(),
                self.x().end(),
                self.y().start(),
                self.y().end()
            )?;
        }
        Ok(())
    }
}

impl<'a, T> FromIterator<&'a Position<T>> for BoardRange<T>
where
    T: Copy + PartialOrd + Zero + One + 'a,
{
    /// Creates a value from a non-owning iterator over a series of [`&Position<T>`].
    /// Each item in the series represents an immutable reference of a position to be contained to the range.
    ///
    /// [`&Position<T>`]: Position
    ///
    /// # Examples
    ///
    /// ```
    /// use life_backend::{BoardRange, Position};
    /// let positions = [Position(0, 0), Position(1, 0), Position(2, 0), Position(1, 1)];
    /// let range: BoardRange<_> = positions.iter().collect();
    /// assert!(!range.is_empty());
    /// assert_eq!(range.x(), &(0..=2));
    /// assert_eq!(range.y(), &(0..=1));
    /// ```
    ///
    #[inline]
    fn from_iter<U>(iter: U) -> Self
    where
        U: IntoIterator<Item = &'a Position<T>>,
    {
        Self::from_iter(iter.into_iter().copied())
    }
}

impl<T> FromIterator<Position<T>> for BoardRange<T>
where
    T: Copy + PartialOrd + Zero + One,
{
    /// Creates a value from an owning iterator over a series of [`Position<T>`].
    /// Each item in the series represents a moved position to be contained to the range.
    ///
    /// [`Position<T>`]: Position
    ///
    /// # Examples
    ///
    /// ```
    /// use life_backend::{BoardRange, Position};
    /// let positions = [Position(0, 0), Position(1, 0), Position(2, 0), Position(1, 1)];
    /// let range: BoardRange<_> = positions.into_iter().collect();
    /// assert!(!range.is_empty());
    /// assert_eq!(range.x(), &(0..=2));
    /// assert_eq!(range.y(), &(0..=1));
    /// ```
    ///
    #[inline]
    fn from_iter<U>(iter: U) -> Self
    where
        U: IntoIterator<Item = Position<T>>,
    {
        Self::from_iter(iter.into_iter())
    }
}

impl<'a, T> Extend<&'a Position<T>> for BoardRange<T>
where
    T: Copy + PartialOrd + Zero + One + 'a,
{
    /// Extends the range with the contents of the specified non-owning iterator over the series of [`&Position<T>`].
    /// Each item in the series represents an immutable reference of a position.
    ///
    /// [`&Position<T>`]: Position
    ///
    /// # Examples
    ///
    /// ```
    /// use life_backend::{BoardRange, Position};
    /// let positions = [Position(0, 0), Position(1, 0), Position(2, 0), Position(1, 1)];
    /// let mut range = BoardRange::new();
    /// range.extend(positions.iter());
    /// assert!(!range.is_empty());
    /// assert_eq!(range.x(), &(0..=2));
    /// assert_eq!(range.y(), &(0..=1));
    /// ```
    ///
    fn extend<U>(&mut self, iter: U)
    where
        U: IntoIterator<Item = &'a Position<T>>,
    {
        *self = self.clone().extend(iter.into_iter().copied())
    }
}

impl<T> Extend<Position<T>> for BoardRange<T>
where
    T: Copy + PartialOrd + Zero + One,
{
    /// Extends the range with the contents of the specified owning iterator over the series of [`Position<T>`].
    /// Each item in the series represents a moved position.
    ///
    /// [`Position<T>`]: Position
    ///
    /// # Examples
    ///
    /// ```
    /// use life_backend::{BoardRange, Position};
    /// let positions = [Position(0, 0), Position(1, 0), Position(2, 0), Position(1, 1)];
    /// let mut range = BoardRange::new();
    /// range.extend(positions.into_iter());
    /// assert!(!range.is_empty());
    /// assert_eq!(range.x(), &(0..=2));
    /// assert_eq!(range.y(), &(0..=1));
    /// ```
    ///
    fn extend<U>(&mut self, iter: U)
    where
        U: IntoIterator<Item = Position<T>>,
    {
        *self = self.clone().extend(iter.into_iter())
    }
}

// Unit tests

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn default() {
        let target = BoardRange::<i32>::default();
        let expected = BoardRange::<i32>::new();
        assert_eq!(target, expected);
    }
    #[test]
    fn display_empty() {
        let target = BoardRange::<i32>::new();
        assert_eq!(format!("{target}"), "(empty)".to_string());
    }
    #[test]
    fn display_notempty() {
        let positions = [Position(0, 0), Position(1, 0), Position(2, 0), Position(1, 1)];
        let target: BoardRange<_> = positions.iter().collect();
        assert_eq!(format!("{target}"), "(x:[0, 2], y:[0, 1])".to_string());
    }
}