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
use std::fmt;
use std::str::FromStr;

const GOBAN_LETTERS: &'static str = "ABCDEFGHJKLMNOPQRST";

/// A structure for storing the x and y coordinates of a board cell.
///
/// (0, 0) is the bottom left corner of the board.
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub struct Vertex {
    /// The x coordinate.
    pub x: usize,
    /// The y coordinate.
    pub y: usize,
}

impl fmt::Debug for Vertex {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self)
    }
}

impl fmt::Display for Vertex {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let letter = GOBAN_LETTERS.chars().nth(self.x).expect("expected char to be in GOBAN_LETTERS");
        let number = (self.y + 1).to_owned();
        write!(f, "{}{}", letter, number)
    }
}

impl FromStr for Vertex {
    type Err = String;

    fn from_str(vertex: &str) -> Result<Self, Self::Err> {
        if vertex.len() < 2 {
            return Err("string too short to be a vertex".to_owned());
        }

        let letter = vertex.chars().next().expect("expected vertex to contain a letter");
        let x = match GOBAN_LETTERS.find(letter) {
            Some(x) => x,
            None => return Err(format!("invalid coordinate letter {:?}", letter)),
        };

        let number: String = vertex.chars().skip(1).collect();
        let y = match u32::from_str_radix(&number, 10) {
            Ok(y) => y as usize,
            Err(_) => return Err("number is not a u32".to_owned()),
        };

        if y == 0 {
            return Err("number must be greater than zero".to_owned());
        }
        Ok(Vertex { x: x, y: y - 1})
    }
}