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
const MAX_NUMBER: usize = 50000;
pub const NO_OP_CHAR: char = '"';
use std::collections::BTreeMap;
use std::str::FromStr;
use crate::error::{ConwayError, ConwayResult};
use crate::grids::{BitGrid, CharGrid};
#[derive(Debug, PartialEq, Clone)]
pub struct Pattern(pub String);
#[derive(Debug, PartialEq, Clone)]
pub struct PatternFile {
pub comment_lines: Vec<String>,
pub header_line: HeaderLine,
pub pattern: Pattern,
}
#[derive(Debug, PartialEq, Clone)]
pub struct HeaderLine {
pub x: usize,
pub y: usize,
pub rule: Option<String>,
}
impl PatternFile {
#[inline]
pub fn width(&self) -> usize {
self.header_line.x
}
#[inline]
pub fn height(&self) -> usize {
self.header_line.y
}
pub fn to_new_bit_grid(&self) -> ConwayResult<BitGrid> {
self.pattern.to_new_bit_grid(self.width(), self.height())
}
pub fn to_grid<G: CharGrid>(&self, grid: &mut G, visibility: Option<usize>) -> ConwayResult<()> {
self.pattern.to_grid(grid, visibility)
}
}
impl FromStr for PatternFile {
type Err = ConwayError;
fn from_str(file_contents: &str) -> Result<Self, Self::Err> {
use ConwayError::*;
let mut comment_lines: Vec<String> = vec![];
let mut comments_ended = false;
let mut opt_header_line: Option<HeaderLine> = None;
let mut pattern_lines: Vec<&str> = vec![];
for line in file_contents.lines() {
if line.starts_with("#") {
if comments_ended {
return Err(InvalidData{reason: "Found a comment line after a non-comment line".to_owned()});
}
comment_lines.push(line.to_owned());
continue;
} else {
comments_ended = true;
}
if opt_header_line.is_none() {
opt_header_line = Some(HeaderLine::from_str(line)?);
continue;
}
match line.find('!') {
Some(idx) => {
pattern_lines.push(&line[0..=idx]);
break;
}
None => pattern_lines.push(line),
};
}
if opt_header_line.is_none() {
return Err(InvalidData{reason: "missing header line".to_owned()});
}
if pattern_lines.is_empty() {
return Err(InvalidData{reason: "missing pattern lines".to_owned()});
}
let mut pattern = "".to_owned();
for line in pattern_lines {
pattern.push_str(line);
}
Ok(PatternFile {
comment_lines,
header_line: opt_header_line.unwrap(),
pattern: Pattern(pattern),
})
}
}
impl FromStr for HeaderLine {
type Err = ConwayError;
fn from_str(line: &str) -> Result<Self, Self::Err> {
use ConwayError::*;
let mut map = BTreeMap::new();
for term in line.split(",") {
let parts = term
.split("=")
.map(|part| part.trim())
.collect::<Vec<&str>>();
if parts.len() != 2 {
return Err(InvalidData{reason: format!("unexpected term in header line: {:?}", term)});
}
map.insert(parts[0], parts[1]);
}
if !map.contains_key("x") || !map.contains_key("y") {
return Err(InvalidData{reason: format!("header line missing `x` and/or `y`: {:?}", line)});
}
let x = usize::from_str(map.get("x").unwrap()).map_err(|e| {
InvalidData{reason: format!("Error while parsing x: {}", e)}
})?;
let y = usize::from_str(map.get("y").unwrap()).map_err(|e| {
InvalidData{reason: format!("Error while parsing y: {}", e)}
})?;
let rule = map.get("rule").map(|s: &&str| (*s).to_owned());
Ok(HeaderLine { x, y, rule })
}
}
fn digits_to_number(digits: &Vec<char>) -> ConwayResult<usize> {
use ConwayError::*;
let mut result = 0;
for ch in digits {
let d = ch.to_digit(10).unwrap();
result = result * 10 + d as usize;
if result > MAX_NUMBER {
return Err(InvalidData{reason: format!("Could not parse digits {:?} because larger than {}",
digits, MAX_NUMBER)});
}
}
Ok(result)
}
impl Pattern {
pub fn to_new_bit_grid(&self, width: usize, height: usize) -> ConwayResult<BitGrid> {
let word_width = (width - 1)/64 + 1;
let mut grid = BitGrid::new(word_width, height);
self.to_grid(&mut grid, None)?;
Ok(grid)
}
pub fn to_grid<G: CharGrid>(&self, grid: &mut G, visibility: Option<usize>) -> ConwayResult<()> {
use ConwayError::*;
let mut col: usize = 0;
let mut row: usize = 0;
let mut char_indices = self.0.char_indices();
let mut ch;
let mut i;
let mut complete = false;
let mut digits: Vec<char> = vec![];
loop {
match char_indices.next() {
Some((_i, _ch)) => {
ch = _ch;
i = _i;
}
None => break
};
if digits.len() > 0 && ch == '!' {
return Err(InvalidData{reason: format!("Cannot have {} after number at {}", ch, i)});
}
match ch {
_ if G::is_valid(ch) => {
let number = if digits.len() > 0 {
digits_to_number(&digits)?
} else { 1 };
digits.clear();
if ch != NO_OP_CHAR {
for _ in 0..number {
grid.write_at_position(col, row, ch, visibility);
col += 1;
}
} else {
col += number;
}
}
'!' => {
complete = true;
break;
}
'$' => {
let number = if digits.len() > 0 {
digits_to_number(&digits)?
} else { 1 };
digits.clear();
col = 0;
row += number;
}
'\r' | '\n' => {
}
x if x.is_digit(10) => {
digits.push(ch);
}
_ => {
return Err(InvalidData{reason: format!("Unrecognized character {} at {}", ch, i)});
}
}
}
if !complete {
return Err(InvalidData{reason: "Premature termination".to_owned()});
}
Ok(())
}
}