Skip to main content

rschess/
lib.rs

1//! A Rust chess library with the aim to be as feature-rich as possible
2//!
3//! Examples are available on the [GitHub repository page](https://github.com/Python3-8/rschess).
4
5mod board;
6pub mod errors;
7mod fen;
8mod game_result;
9mod helpers;
10#[cfg(feature = "img")]
11pub mod img;
12mod move_;
13#[cfg(feature = "pgn")]
14pub mod pgn;
15mod piece;
16mod position;
17
18pub use board::*;
19pub(crate) use errors::*;
20pub use fen::Fen;
21pub use game_result::*;
22pub use move_::*;
23pub use piece::*;
24pub use position::*;
25use std::{fmt, ops::Not};
26
27/// Converts a square index (`0..64`) to a square name, returning an error if the square index is invalid.
28pub fn idx_to_sq(idx: usize) -> Result<(char, char), InvalidSquareIndexError> {
29    if !(0..64).contains(&idx) {
30        return Err(InvalidSquareIndexError(idx));
31    }
32    Ok(helpers::idx_to_sq(idx))
33}
34
35/// Converts a square name to a square index, returning an error if the square name is invalid.
36pub fn sq_to_idx(file: char, rank: char) -> Result<usize, InvalidSquareNameError> {
37    if !(('a'..='h').contains(&file) && ('1'..='8').contains(&rank)) {
38        return Err(InvalidSquareNameError(file, rank));
39    }
40    Ok(helpers::sq_to_idx(file, rank))
41}
42
43/// Represents a side/color.
44#[derive(Eq, PartialEq, Hash, Copy, Clone, Debug)]
45pub enum Color {
46    White,
47    Black,
48}
49
50impl Color {
51    /// Checks if the color is white.
52    pub fn is_white(&self) -> bool {
53        matches!(self, Self::White)
54    }
55
56    /// Checks if the color is black.
57    pub fn is_black(&self) -> bool {
58        matches!(self, Self::Black)
59    }
60}
61
62impl TryFrom<&str> for Color {
63    type Error = InvalidColorCharacterError;
64
65    /// Attempts to convert a color character in a string slice to a `Color` ("w" is white, and "b" is black).
66    fn try_from(string: &str) -> Result<Self, Self::Error> {
67        match string {
68            "w" => Ok(Self::White),
69            "b" => Ok(Self::Black),
70            _ => Err(InvalidColorCharacterError(string.to_string())),
71        }
72    }
73}
74
75impl From<Color> for char {
76    /// Converts a `Color` to a color character (white is 'w', and black is 'b').
77    fn from(c: Color) -> char {
78        match c {
79            Color::White => 'w',
80            Color::Black => 'b',
81        }
82    }
83}
84
85impl fmt::Display for Color {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        write!(f, "{}", char::from(*self))
88    }
89}
90
91impl Not for Color {
92    type Output = Self;
93
94    fn not(self) -> Self {
95        match self {
96            Self::White => Self::Black,
97            Self::Black => Self::White,
98        }
99    }
100}
101
102#[cfg(test)]
103mod test;