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
//! This module contains the functions and methods that enable to load and
//! save files containing grid data.
//! For now it supports two internal file formats : "Resizable Life"
//! and "Toroidal Life".

use std::collections::LinkedList;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::iter::FromIterator;

use error::FileParsingErrorKind;
use Grid;

impl Grid {
    /// Returns a new `Grid` encoded within a file located at `path`.
    ///
    /// # Errors
    ///
    /// If there is an IO error or the file isn't a valid life file,
    /// an error of the type `FileParsingErrorKind` will be returned.
    pub fn from_file(path: &str) -> Result<Grid, FileParsingErrorKind> {
        // Open and read file
        let mut f = File::open(path)?;
        let mut lines = String::new();
        f.read_to_string(&mut lines)?;

        // Remove leading and trailing whitespaces and then remove blank lines
        let lines = lines
            .lines()
            .map(|line| line.trim())
            .filter(|line| !line.is_empty());
        // Turn the iterator into a LinkedList<&str>
        let lines: LinkedList<&str> = LinkedList::from_iter(lines);

        // Check if file is valid
        valid_life_file(&lines)?;

        // The first line should indicate the format to be used
        if *lines.front().ok_or(FileParsingErrorKind::IncompleteFile)? == "#Resizable Life" {
            load_resizable_life(lines)
        } else if *lines.front().ok_or(FileParsingErrorKind::IncompleteFile)? == "#Toroidal Life" {
            load_toroidal_life(lines)
        } else {
            Err(FileParsingErrorKind::UnknownFormat)
        }
    }

    /// Writes the `Grid` into a file located at `path`.
    ///
    /// # Errors
    ///
    /// If there is an IO error, an error of the type `io::Error`
    /// will be returned.
    pub fn save_life_grid(&self, path: &str) -> Result<(), io::Error> {
        let mut lines: LinkedList<String> = LinkedList::new();

        // Recenter the `Grid`
        let mut grid = self.clone();
        if !self.is_toroidal() {
            grid.recenter_pattern(0);
        }

        // Put format
        if grid.is_toroidal() {
            lines.push_back("#Toroidal Life".to_string());
        } else {
            lines.push_back("#Resizable Life".to_string());
        }

        // Put ruleset
        let mut survival_ruleset = String::new();
        let mut birth_ruleset = String::new();
        for n in grid.survival.read().unwrap().iter() {
            survival_ruleset.push_str(&n.to_string());
        }
        for n in grid.birth.read().unwrap().iter() {
            birth_ruleset.push_str(&n.to_string());
        }
        lines.push_back(format!("#R {}/{}", survival_ruleset, birth_ruleset));

        // Put grid size if toroidal
        let width = grid.get_width();
        let height = grid.get_height();
        if grid.is_toroidal() {
            lines.push_back(format!("#S {} {}", width, height));
        }

        // Put living cells coords
        for y in 0..height {
            for x in 0..width {
                if grid.get_cell_state(x as i64, y as i64) == 255 {
                    lines.push_back(format!("{} {}", x, y));
                }
            }
        }

        // Write lines to a file
        let mut f = File::create(path)?;
        for line in lines {
            writeln!(f, "{}", line)?;
        }

        Ok(())
    }
}

fn valid_life_file(lines_ref: &LinkedList<&str>) -> Result<(), FileParsingErrorKind> {
    let mut lines = lines_ref.clone(); // Make a copy of lines_ref so it can be modified
                                       // If "lines" is empty then the file is empty
    let format_line = lines
        .pop_front()
        .ok_or(FileParsingErrorKind::IncompleteFile)?;

    if format_line == "#Resizable Life" {
        match valid_resizable_life(lines) {
            Err(err) => Err(err),
            Ok(()) => Ok(()),
        }
    } else if format_line == "#Toroidal Life" {
        match valid_toroidal_life(lines) {
            Err(err) => Err(err),
            Ok(()) => Ok(()),
        }
    } else {
        Err(FileParsingErrorKind::UnknownFormat)
    }
}

fn valid_resizable_life(lines: LinkedList<&str>) -> Result<(), FileParsingErrorKind> {
    let mut lines = lines; // Make lines mutable

    // If any, check description
    while lines
        .front()
        .ok_or(FileParsingErrorKind::IncompleteFile)?
        .starts_with("#D")
    {
        lines
            .pop_front()
            .ok_or(FileParsingErrorKind::IncompleteFile)?;
    }

    //Check ruleset
    if *lines.front().ok_or(FileParsingErrorKind::IncompleteFile)? != "#N" {
        let ruleset_line = lines
            .pop_front()
            .ok_or(FileParsingErrorKind::IncompleteFile)?;
        if !ruleset_line.starts_with("#R") || ruleset_line.split_whitespace().count() != 2 {
            return Err(FileParsingErrorKind::RuleParsingError);
        }
        let ruleset = ruleset_line
            .split_whitespace()
            .filter(|s| *s != "#R")
            .next()
            .ok_or(FileParsingErrorKind::IncompleteFile)?; // Without .next() there is a type error with split method
        if ruleset.split('/').count() != 2 {
            return Err(FileParsingErrorKind::RuleParsingError);
        }
        let ruleset: Vec<&str> = ruleset.split('/').collect();
        // ruleset[0] is the survival ruleset
        for c in ruleset[0].chars() {
            match c.to_digit(10) {
                None => return Err(FileParsingErrorKind::RuleParsingError),
                Some(n) if n == 9 => return Err(FileParsingErrorKind::RuleParsingError),
                Some(_) => {}
            }
        }
        // ruleset[1] is the birth ruleset
        for c in ruleset[1].chars() {
            match c.to_digit(10) {
                None => return Err(FileParsingErrorKind::RuleParsingError),
                Some(n) if n == 9 => return Err(FileParsingErrorKind::RuleParsingError),
                Some(_) => {}
            }
        }
    } else {
        lines
            .pop_front()
            .ok_or(FileParsingErrorKind::IncompleteFile)?;
    }

    // If no "coords" lines return an error
    if lines.is_empty() {
        return Err(FileParsingErrorKind::IncompleteFile);
    }

    // Check "coords" lines
    while !lines.is_empty() {
        if lines
            .front()
            .ok_or(FileParsingErrorKind::IncompleteFile)?
            .split_whitespace()
            .count()
            != 2
        {
            return Err(FileParsingErrorKind::CoordParsingError);
        }
        let coords: Vec<&str> = lines
            .pop_front()
            .ok_or(FileParsingErrorKind::IncompleteFile)?
            .split_whitespace()
            .collect();
        coords[0].parse::<usize>()?;
        coords[1].parse::<usize>()?;
    }

    // If all tests are passed...
    Ok(())
}

fn valid_toroidal_life(lines: LinkedList<&str>) -> Result<(), FileParsingErrorKind> {
    let mut lines = lines; // Make lines mutable

    // If any, check description
    while lines
        .front()
        .ok_or(FileParsingErrorKind::IncompleteFile)?
        .starts_with("#D")
    {
        lines
            .pop_front()
            .ok_or(FileParsingErrorKind::IncompleteFile)?;
    }

    // Check ruleset
    if *lines.front().ok_or(FileParsingErrorKind::IncompleteFile)? != "#N" {
        let ruleset_line = lines
            .pop_front()
            .ok_or(FileParsingErrorKind::IncompleteFile)?;
        if !ruleset_line.starts_with("#R") || ruleset_line.split_whitespace().count() != 2 {
            return Err(FileParsingErrorKind::RuleParsingError);
        }
        let ruleset = ruleset_line
            .split_whitespace()
            .filter(|s| *s != "#R")
            .next()
            .ok_or(FileParsingErrorKind::IncompleteFile)?; // Without .next() there is a type error with split method
        if ruleset.split('/').count() != 2 {
            return Err(FileParsingErrorKind::RuleParsingError);
        }
        let ruleset: Vec<&str> = ruleset.split('/').collect();
        // ruleset[0] is the survival ruleset
        for c in ruleset[0].chars() {
            match c.to_digit(10) {
                None => return Err(FileParsingErrorKind::RuleParsingError),
                Some(n) if n == 9 => return Err(FileParsingErrorKind::RuleParsingError),
                Some(_) => {}
            }
        }
        // ruleset[1] is the birth ruleset
        for c in ruleset[1].chars() {
            match c.to_digit(10) {
                None => return Err(FileParsingErrorKind::RuleParsingError),
                Some(n) if n == 9 => return Err(FileParsingErrorKind::RuleParsingError),
                Some(_) => {}
            }
        }
    } else {
        lines
            .pop_front()
            .ok_or(FileParsingErrorKind::IncompleteFile)?;
    }

    // Check grid size specification (#S <width> <height>)
    let grid_size_line = lines
        .pop_front()
        .ok_or(FileParsingErrorKind::IncompleteFile)?;
    if !grid_size_line.starts_with("#S") || grid_size_line.split_whitespace().count() != 3 {
        return Err(FileParsingErrorKind::CoordParsingError);
    }
    let grid_size: Vec<&str> = grid_size_line
        .split_whitespace()
        .filter(|s| *s != "#S")
        .collect();
    grid_size[0].parse::<usize>()?;
    grid_size[1].parse::<usize>()?;

    // If no "coords" lines return an error
    if lines.is_empty() {
        return Err(FileParsingErrorKind::IncompleteFile);
    }

    // Check "coords" lines
    while !lines.is_empty() {
        if lines
            .front()
            .ok_or(FileParsingErrorKind::IncompleteFile)?
            .split_whitespace()
            .count()
            != 2
        {
            return Err(FileParsingErrorKind::CoordParsingError);
        }
        let coords: Vec<&str> = lines
            .pop_front()
            .ok_or(FileParsingErrorKind::IncompleteFile)?
            .split_whitespace()
            .collect();
        coords[0].parse::<usize>()?;
        coords[1].parse::<usize>()?;
    }

    // If all tests are passed...
    Ok(())
}

fn load_resizable_life(lines: LinkedList<&str>) -> Result<Grid, FileParsingErrorKind> {
    let mut lines = lines; // Make lines mutable

    // Get file format
    let frmt = lines.pop_front().unwrap();

    // Skip description
    while lines.front().unwrap().starts_with("#D") {
        lines.pop_front().unwrap();
    }

    // Get ruleset
    let mut srvl: Vec<u32> = Vec::new();
    let mut brth: Vec<u32> = Vec::new();
    if *lines.front().unwrap() == "#N" {
        lines.pop_front().unwrap();
        srvl = vec![2, 3];
        brth = vec![3];
    } else {
        let ruleset_line = lines.pop_front().unwrap();
        let ruleset = ruleset_line
            .split_whitespace()
            .filter(|s| *s != "#R")
            .next()
            .unwrap(); // Without .next().unwrap() there is a type error with split method
        let ruleset: Vec<&str> = ruleset.split("/").collect();
        let survival_ruleset = ruleset[0].chars();
        let birth_ruleset = ruleset[1].chars();
        for c in survival_ruleset {
            srvl.push(c.to_digit(10).unwrap() as u32);
        }
        for c in birth_ruleset {
            brth.push(c.to_digit(10).unwrap() as u32);
        }
    }
    // Sort and remove duplicated rules
    srvl.sort();
    srvl.dedup();
    brth.sort();
    brth.dedup();

    // Guess the "cells" size
    let mut file_coords: Vec<(usize, usize)> = Vec::new();
    while !lines.is_empty() {
        let coords_str: Vec<&str> = lines.pop_front().unwrap().split_whitespace().collect();
        let coords: (usize, usize) = (
            coords_str[0].parse().unwrap(),
            coords_str[1].parse().unwrap(),
        );
        file_coords.push(coords);
    }
    let (width, height) = guess_pattern_size(&file_coords);

    // Make CA grid
    let mut grid = Grid::new(&frmt.to_string(), false, &srvl, &brth, width, height);

    // Set to true the cells that are alive
    for (x, y) in file_coords {
        grid.set_cell_state(x, y, 255)?;
    }

    // Return CA grid
    Ok(grid)
}

// Works like Life 1.06 except there is a #S <width> <height> before the cells "coords"
fn load_toroidal_life(lines: LinkedList<&str>) -> Result<Grid, FileParsingErrorKind> {
    let mut lines = lines; // Make lines mutable

    // Get file format
    let frmt = lines.pop_front().unwrap();

    // Skip description
    while lines.front().unwrap().starts_with("#D") {
        lines.pop_front().unwrap();
    }

    // Get ruleset
    let mut srvl: Vec<u32> = Vec::new();
    let mut brth: Vec<u32> = Vec::new();
    if *lines.front().unwrap() == "#N" {
        lines.pop_front().unwrap();
        srvl = vec![2, 3];
        brth = vec![3];
    } else {
        let ruleset_line = lines.pop_front().unwrap();
        let ruleset = ruleset_line
            .split_whitespace()
            .filter(|s| *s != "#R")
            .next()
            .unwrap(); // Without .next().unwrap() there is a type error with split method
        let ruleset: Vec<&str> = ruleset.split("/").collect();
        let survival_ruleset = ruleset[0].chars();
        let birth_ruleset = ruleset[1].chars();
        for c in survival_ruleset {
            srvl.push(c.to_digit(10).unwrap() as u32);
        }
        for c in birth_ruleset {
            brth.push(c.to_digit(10).unwrap() as u32);
        }
    }
    // Sort and remove duplicated rules
    srvl.sort();
    srvl.dedup();
    brth.sort();
    brth.dedup();

    // Get the grid size
    let grid_size_line_terms: Vec<&str> = lines
        .pop_front()
        .unwrap()
        .split_whitespace()
        .filter(|s| *s != "#S")
        .collect();
    let (width, height): (usize, usize) = (
        grid_size_line_terms[0].parse().unwrap(),
        grid_size_line_terms[1].parse().unwrap(),
    );

    // Make CA grid
    let mut grid = Grid::new(&frmt.to_string(), true, &srvl, &brth, width, height);

    // Get the coordinates from the file
    let mut file_coords: Vec<(usize, usize)> = Vec::new();
    while !lines.is_empty() {
        let coords_str: Vec<&str> = lines.pop_front().unwrap().split_whitespace().collect();
        let coords: (usize, usize) = (
            coords_str[0].parse().unwrap(),
            coords_str[1].parse().unwrap(),
        );
        file_coords.push(coords);
    }

    // Set to true the cells that are alive
    for (x, y) in file_coords {
        grid.set_cell_state(x, y, 255)?;
    }

    // Return CA grid
    Ok(grid)
}

fn guess_pattern_size(coords: &[(usize, usize)]) -> (usize, usize) {
    let (mut lim_x, mut lim_y): (usize, usize) = (0, 0);

    for &(x, y) in coords {
        if x > lim_x {
            lim_x = x;
        }
        if y > lim_y {
            lim_y = y;
        }
    }
    // The "+ 1"s are here because because the "coords" start at 0
    (lim_x + 1, lim_y + 1)
}