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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
use anyhow::{ensure, Result};
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::iter::FromIterator;

use super::{Plaintext, PlaintextLine};
use crate::Position;

/// A builder of [`Plaintext`].
///
/// # Examples
///
/// Creates a builder via [`collect()`] with live cell positions, set a name via [`name()`], then builds [`Plaintext`] via [`build()`]:
///
/// [`collect()`]: std::iter::Iterator::collect
/// [`name()`]: #method.name
/// [`build()`]: #method.build
///
/// ```
/// use life_backend::format::PlaintextBuilder;
/// use life_backend::Position;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let pattern = [Position(1, 0), Position(2, 0), Position(0, 1), Position(1, 1), Position(1, 2)];
/// let target = pattern.iter().collect::<PlaintextBuilder>().name("R-pentomino").build()?;
/// let expected = "\
///     !Name: R-pentomino\n\
///     .OO\n\
///     OO.\n\
///     .O.\n\
/// ";
/// assert_eq!(format!("{target}"), expected);
/// # Ok(())
/// # }
/// ```
///
/// Creates an empty builder via [`new()`], set a name via [`name()`], injects live cell positions via [`extend()`], then builds [`Plaintext`] via [`build()`]:
///
/// [`new()`]: #method.new
/// [`extend()`]: #method.extend
///
/// ```
/// use life_backend::format::PlaintextBuilder;
/// use life_backend::Position;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let pattern = [Position(1, 0), Position(2, 0), Position(0, 1), Position(1, 1), Position(1, 2)];
/// let mut builder = PlaintextBuilder::new().name("R-pentomino");
/// builder.extend(pattern.iter());
/// let target = builder.build()?;
/// let expected = "\
///     !Name: R-pentomino\n\
///     .OO\n\
///     OO.\n\
///     .O.\n\
/// ";
/// assert_eq!(format!("{target}"), expected);
/// # Ok(())
/// # }
/// ```
///
#[derive(Clone, Debug)]
pub struct PlaintextBuilder<Name = PlaintextBuilderNoName, Comment = PlaintextBuilderNoComment>
where
    Name: PlaintextBuilderName,
    Comment: PlaintextBuilderComment,
{
    name: Name,
    comment: Comment,
    contents: HashSet<Position<usize>>,
}

// Traits and types for PlaintextBuilder's typestate
pub trait PlaintextBuilderName: Clone + fmt::Debug {
    fn drain(self) -> Option<String>;
}
pub trait PlaintextBuilderComment: Clone + fmt::Debug {
    fn drain(self) -> Option<String>;
}
#[derive(Clone, Debug)]
pub struct PlaintextBuilderNoName;
impl PlaintextBuilderName for PlaintextBuilderNoName {
    fn drain(self) -> Option<String> {
        None
    }
}
#[derive(Clone, Debug)]
pub struct PlaintextBuilderWithName(String);
impl PlaintextBuilderName for PlaintextBuilderWithName {
    fn drain(self) -> Option<String> {
        Some(self.0)
    }
}
#[derive(Clone, Debug)]
pub struct PlaintextBuilderNoComment;
impl PlaintextBuilderComment for PlaintextBuilderNoComment {
    fn drain(self) -> Option<String> {
        None
    }
}
#[derive(Clone, Debug)]
pub struct PlaintextBuilderWithComment(String);
impl PlaintextBuilderComment for PlaintextBuilderWithComment {
    fn drain(self) -> Option<String> {
        Some(self.0)
    }
}

// Inherent methods

impl PlaintextBuilder<PlaintextBuilderNoName, PlaintextBuilderNoComment> {
    /// Creates a builder that contains no live cells.
    ///
    /// # Examples
    ///
    /// ```
    /// use life_backend::format::PlaintextBuilder;
    /// let builder = PlaintextBuilder::new();
    /// ```
    ///
    #[inline]
    pub fn new() -> Self {
        Self {
            name: PlaintextBuilderNoName,
            comment: PlaintextBuilderNoComment,
            contents: HashSet::new(),
        }
    }
}

impl<Name, Comment> PlaintextBuilder<Name, Comment>
where
    Name: PlaintextBuilderName,
    Comment: PlaintextBuilderComment,
{
    /// Builds the [`Plaintext`] value.
    ///
    /// # Examples
    ///
    /// ```
    /// use life_backend::format::PlaintextBuilder;
    /// use life_backend::Position;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let pattern = [Position(1, 0), Position(0, 1)];
    /// let builder: PlaintextBuilder = pattern.iter().collect();
    /// let target = builder.build()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    pub fn build(self) -> Result<Plaintext> {
        let name = self.name.drain();
        if let Some(str) = &name {
            ensure!(str.lines().count() <= 1, "the string passed by name(str) includes multiple lines");
        };
        let comments = match self.comment.drain() {
            Some(str) => {
                let buf: Vec<_> = str.lines().map(String::from).collect();
                if buf.is_empty() {
                    // buf is empty only if str == "" || str == "\n"
                    vec![String::new()]
                } else {
                    buf
                }
            }
            None => Vec::new(),
        };
        let contents_group_by_y = self.contents.into_iter().fold(HashMap::new(), |mut acc, Position(x, y)| {
            acc.entry(y).or_insert_with(Vec::new).push(x);
            acc
        });
        let contents_sorted = {
            let mut buf: Vec<_> = contents_group_by_y.into_iter().map(|(y, xs)| PlaintextLine(y, xs)).collect();
            buf.sort_by(|PlaintextLine(y0, _), PlaintextLine(y1, _)| y0.partial_cmp(y1).unwrap()); // this unwrap never panic because <usize>.partial_cmp(<usize>) always returns Some(_)
            for PlaintextLine(_, xs) in &mut buf {
                xs.sort();
            }
            buf
        };
        Ok(Plaintext {
            name,
            comments,
            contents: contents_sorted,
        })
    }
}

impl<Comment> PlaintextBuilder<PlaintextBuilderNoName, Comment>
where
    Comment: PlaintextBuilderComment,
{
    /// Set the name.
    ///
    /// # Examples
    ///
    /// ```
    /// use life_backend::format::PlaintextBuilder;
    /// use life_backend::Position;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let pattern = [Position(1, 0), Position(0, 1)];
    /// let target = pattern
    ///     .iter()
    ///     .collect::<PlaintextBuilder>()
    ///     .name("foo")
    ///     .build()?;
    /// assert_eq!(target.name(), Some("foo".to_string()));
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Code that calls [`name()`] twice or more will fail at compile time.  For example:
    ///
    /// [`name()`]: #method.name
    ///
    /// ```compile_fail
    /// use life_backend::format::PlaintextBuilder;
    /// use life_backend::Position;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let pattern = [Position(1, 0), Position(0, 1)];
    /// let target = pattern
    ///     .iter()
    ///     .collect::<PlaintextBuilder>()
    ///     .name("foo")
    ///     .name("bar") // Compile error
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`build()`] returns an error if the string passed by [`name()`] includes multiple lines.  For example:
    ///
    /// [`build()`]: #method.build
    /// [`name()`]: #method.name
    ///
    /// ```should_panic
    /// use life_backend::format::PlaintextBuilder;
    /// use life_backend::Position;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let pattern = [Position(1, 0), Position(0, 1)];
    /// let target = pattern
    ///     .iter()
    ///     .collect::<PlaintextBuilder>()
    ///     .name("foo\nbar")
    ///     .build()?; // Should fail
    /// # Ok(())
    /// # }
    /// ```
    ///
    pub fn name(self, str: &str) -> PlaintextBuilder<PlaintextBuilderWithName, Comment> {
        let name = PlaintextBuilderWithName(str.to_owned());
        PlaintextBuilder {
            name,
            comment: self.comment,
            contents: self.contents,
        }
    }
}

impl<Name> PlaintextBuilder<Name, PlaintextBuilderNoComment>
where
    Name: PlaintextBuilderName,
{
    /// Set the comment.
    /// If the argument includes newlines, the instance of [`Plaintext`] built by [`build()`] includes multiple comment lines.
    ///
    /// [`build()`]: #method.build
    ///
    /// # Examples
    ///
    /// ```
    /// use life_backend::format::PlaintextBuilder;
    /// use life_backend::Position;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let pattern = [Position(1, 0), Position(0, 1)];
    /// let target = pattern
    ///     .iter()
    ///     .collect::<PlaintextBuilder>()
    ///     .comment("comment0\ncomment1")
    ///     .build()?;
    /// assert_eq!(target.comments().len(), 2);
    /// assert_eq!(target.comments()[0], "comment0");
    /// assert_eq!(target.comments()[1], "comment1");
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Code that calls [`comment()`] twice or more will fail at compile time.  For example:
    ///
    /// [`comment()`]: #method.comment
    ///
    /// ```compile_fail
    /// use life_backend::format::PlaintextBuilder;
    /// use life_backend::Position;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let pattern = [Position(1, 0), Position(0, 1)];
    /// let target = pattern
    ///     .iter()
    ///     .collect::<PlaintextBuilder>()
    ///     .comment("comment0")
    ///     .comment("comment1") // Compile error
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    pub fn comment(self, str: &str) -> PlaintextBuilder<Name, PlaintextBuilderWithComment> {
        let comment = PlaintextBuilderWithComment(str.to_owned());
        PlaintextBuilder {
            name: self.name,
            comment,
            contents: self.contents,
        }
    }
}

// Trait implementations

impl Default for PlaintextBuilder<PlaintextBuilderNoName, PlaintextBuilderNoComment> {
    /// Returns the default value of the type, same as the return value of [`new()`].
    ///
    /// [`new()`]: #method.new
    ///
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<Name, Comment> PlaintextBuilder<Name, Comment>
where
    Name: PlaintextBuilderName,
    Comment: PlaintextBuilderComment,
{
    // Implementation of public extend()
    #[inline]
    fn extend<T>(&mut self, iter: T)
    where
        T: IntoIterator<Item = Position<usize>>,
    {
        self.contents.extend(iter);
    }
}

impl PlaintextBuilder<PlaintextBuilderNoName, PlaintextBuilderNoComment> {
    // Implementation of public from_iter()
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = Position<usize>>,
    {
        let mut v = Self::new();
        v.extend(iter);
        v
    }
}

impl<'a> FromIterator<&'a Position<usize>> for PlaintextBuilder<PlaintextBuilderNoName, PlaintextBuilderNoComment> {
    /// Creates a value from a non-owning iterator over a series of [`&Position<usize>`].
    /// Each item in the series represents an immutable reference of a live cell position.
    ///
    /// [`&Position<usize>`]: Position
    ///
    /// # Examples
    ///
    /// ```
    /// use life_backend::format::PlaintextBuilder;
    /// use life_backend::Position;
    /// let pattern = [Position(1, 0), Position(0, 1)];
    /// let iter = pattern.iter();
    /// let builder: PlaintextBuilder = iter.collect();
    /// ```
    ///
    #[inline]
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = &'a Position<usize>>,
    {
        Self::from_iter(iter.into_iter().copied())
    }
}

impl FromIterator<Position<usize>> for PlaintextBuilder<PlaintextBuilderNoName, PlaintextBuilderNoComment> {
    /// Creates a value from an owning iterator over a series of [`Position<usize>`].
    /// Each item in the series represents a moved live cell position.
    ///
    /// [`Position<usize>`]: Position
    ///
    /// # Examples
    ///
    /// ```
    /// use life_backend::format::PlaintextBuilder;
    /// use life_backend::Position;
    /// let pattern = [Position(1, 0), Position(0, 1)];
    /// let iter = pattern.into_iter();
    /// let builder: PlaintextBuilder = iter.collect();
    /// ```
    ///
    #[inline]
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = Position<usize>>,
    {
        Self::from_iter(iter)
    }
}

impl<'a, Name, Comment> Extend<&'a Position<usize>> for PlaintextBuilder<Name, Comment>
where
    Name: PlaintextBuilderName,
    Comment: PlaintextBuilderComment,
{
    /// Extends the builder with the contents of the specified non-owning iterator over the series of [`&Position<usize>`].
    /// Each item in the series represents an immutable reference of a live cell position.
    ///
    /// [`&Position<usize>`]: Position
    ///
    /// # Examples
    ///
    /// ```
    /// use life_backend::format::PlaintextBuilder;
    /// use life_backend::Position;
    /// let pattern = [Position(1, 0), Position(0, 1)];
    /// let iter = pattern.iter();
    /// let mut builder = PlaintextBuilder::new();
    /// builder.extend(iter);
    /// ```
    ///
    #[inline]
    fn extend<T>(&mut self, iter: T)
    where
        T: IntoIterator<Item = &'a Position<usize>>,
    {
        self.extend(iter.into_iter().copied());
    }
}

impl<Name, Comment> Extend<Position<usize>> for PlaintextBuilder<Name, Comment>
where
    Name: PlaintextBuilderName,
    Comment: PlaintextBuilderComment,
{
    /// Extends the builder with the contents of the specified owning iterator over the series of [`Position<usize>`].
    /// Each item in the series represents a moved live cell position.
    ///
    /// [`Position<usize>`]: Position
    ///
    /// # Examples
    ///
    /// ```
    /// use life_backend::format::PlaintextBuilder;
    /// use life_backend::Position;
    /// let pattern = [Position(1, 0), Position(0, 1)];
    /// let iter = pattern.into_iter();
    /// let mut builder = PlaintextBuilder::new();
    /// builder.extend(iter);
    /// ```
    ///
    #[inline]
    fn extend<T>(&mut self, iter: T)
    where
        T: IntoIterator<Item = Position<usize>>,
    {
        self.extend(iter);
    }
}

// Unit tests

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn default() {
        let target = PlaintextBuilder::default();
        assert!(target.contents.is_empty());
    }
}