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
use board::{Tile, GoBoard};
use board::fn_str;

impl GoBoard {
	fn split_one_line(line: &str) -> Vec<Tile> {
		line.split(' ')
				.map(|x| x.trim())
				.filter(|x| x.len() > 0)
				.map(|x| {Tile::from_str(x)})
				.collect()
	}

	fn split_into_lines(to_parse: &String) -> Vec<&str> {
		to_parse.split('\n')
				.map(|x| x.trim())
				.filter(|x| x.len() > 0)
				.filter(|x| x.chars().next() != "#".chars().next())
				.collect::<Vec<&str>>()
	}

	/// Parse a string which describe the inital state of the npuzzle board.
	fn execute_parse(size: usize, lines: &Vec<&str>)
			-> GoBoard {

		// get all the tiles from the lines
		let mut tiles = Vec::with_capacity(size * size);
		for line in lines {
			let ntiles : Vec<Tile> = GoBoard::split_one_line(line);
			tiles.extend(ntiles);
		}

		//create board, no check
        let mut board : GoBoard = Default::default();
		let size = board.get_size();
        for x in 0..size {
			for y in 0..size {
				board.set_raw((x, y), tiles[y * size + x].clone());
			}
		}
		board
	}

	/// This function also parse the size of the Board.
	/// This function should only be used in test because there is no test.
	pub fn parse_with_size(to_parse: &String) -> GoBoard {
		let lines = GoBoard::split_into_lines(to_parse);
		let size = fn_str::atoi::<usize>(lines[0]).unwrap();
		let lines_reduce = (&lines[1..]).to_vec();
		GoBoard::execute_parse(size, &lines_reduce)
	}
}

#[cfg(test)]
mod test {
	use super::*;
	use board::{GoBoard, Tile};

	#[test]
	fn test_parse() {
		let mut str1 = r#"5
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
W . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . W . . . . . . . . . . . . . . .
. . . . W . . . . . . . . . . . . . .
. . . . . W . . . . . . . . . . . . .
. . . . . . W . . . . . . . . . . . .
. . . . . . . W . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
		"#;
		let board = GoBoard::parse_with_size(&str1.to_string());
		assert!(board.get((0, 2)) == Tile::WHITE);
	}
}