lib_wpsr/boxed/
shape.rs

1use std::{fmt::Display, str::FromStr};
2
3use clap::Parser;
4
5use crate::Error;
6
7#[derive(Debug, Parser, Clone)]
8pub enum Shape {
9    Triangle,
10    Square,
11    Pentagon,
12    Hexagon,
13    Heptagon,
14    Octagon,
15}
16
17impl Display for Shape {
18    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19        match self {
20            Shape::Triangle => write!(f, "Triangle"),
21            Shape::Square => write!(f, "Square"),
22            Shape::Pentagon => write!(f, "Pentagon"),
23            Shape::Hexagon => write!(f, "Hexagon"),
24            Shape::Heptagon => write!(f, "Heptagon"),
25            Shape::Octagon => write!(f, "Octagon"),
26        }
27    }
28}
29
30impl Shape {
31    pub fn edges(&self) -> u8 {
32        match self {
33            Shape::Triangle => 3,
34            Shape::Square => 4,
35            Shape::Pentagon => 5,
36            Shape::Hexagon => 6,
37            Shape::Heptagon => 7,
38            Shape::Octagon => 8,
39        }
40    }
41
42    pub fn parse(s: &str) -> Result<Self, Error> {
43        match s.to_lowercase().as_str() {
44            "triangle" => Ok(Shape::Triangle),
45            "square" => Ok(Shape::Square),
46            "pentagon" => Ok(Shape::Pentagon),
47            "hexagon" => Ok(Shape::Hexagon),
48            "heptagon" => Ok(Shape::Heptagon),
49            "octagon" => Ok(Shape::Octagon),
50            _ => Err(Error::UnknownShape(s.to_string())),
51        }
52    }
53
54    pub fn from_edges(edges: u8) -> Result<Self, Error> {
55        match edges {
56            3 => Ok(Shape::Triangle),
57            4 => Ok(Shape::Square),
58            5 => Ok(Shape::Pentagon),
59            6 => Ok(Shape::Hexagon),
60            7 => Ok(Shape::Heptagon),
61            8 => Ok(Shape::Octagon),
62            _ => Err(Error::UnknownShapeForEdges(edges)),
63        }
64    }
65}
66
67impl FromStr for Shape {
68    type Err = Error;
69    fn from_str(s: &str) -> Result<Self, Self::Err> {
70        Shape::parse(s)
71    }
72}