chess_lab/common/errors/movements.rs
1use thiserror::Error;
2
3use crate::core::Move;
4
5/// Errors that can occur when trying to move a [Piece](crate::core::Piece)
6///
7#[non_exhaustive]
8#[derive(Debug, Error, PartialEq)]
9pub enum MoveError {
10 /// The move is invalid
11 #[error("Invalid move: {0}")]
12 Invalid(String),
13 /// The move is illegal
14 #[error("Illegal move: {0}")]
15 Illegal(String),
16 /// The move is ambiguous
17 #[error("Ambiguous move: {0}")]
18 Ambiguous(String),
19}
20
21/// Errors that can occur when trying to move a [Piece](crate::core::Piece)
22///
23#[derive(Debug, Error)]
24#[error("Error moving piece: {error}")]
25pub struct MoveInfoError {
26 /// The error message
27 pub error: String,
28 /// The move that caused the error
29 pub mov: Move,
30}
31
32impl MoveInfoError {
33 /// Creates a new [MoveInfoError] with the given error message and [Move]
34 ///
35 /// # Arguments
36 /// * `error` - The error message
37 /// * `mov` - The [Move] that caused the error
38 ///
39 /// # Example
40 /// ```
41 /// # use chess_lab::errors::MoveInfoError;
42 /// use chess_lab::core::{Color, PieceType, Position, Move, MoveType, Piece};
43 ///
44 /// let piece = Piece::new(Color::White, PieceType::Pawn);
45 /// let from = Position::new(4, 1).unwrap();
46 /// let to = Position::new(4, 3).unwrap();
47 /// let move_type = MoveType::Normal {
48 /// capture: false,
49 /// promotion: None,
50 /// };
51 /// let captured_piece = None;
52 /// let rook_from = None;
53 /// let ambiguity = (false, false);
54 ///
55 /// let mov = Move::new(
56 /// piece,
57 /// from,
58 /// to,
59 /// move_type,
60 /// captured_piece,
61 /// rook_from,
62 /// ambiguity,
63 /// false,
64 /// false
65 /// ).unwrap();
66 /// let error = MoveInfoError::new("Invalid move".to_string(), mov);
67 /// ```
68 ///
69 pub fn new(error: String, mov: Move) -> Self {
70 MoveInfoError { error, mov }
71 }
72}
73
74#[cfg(test)]
75mod tests {
76 use super::*;
77
78 #[test]
79 fn test_move_info_error_creation() {
80 let piece =
81 crate::core::Piece::new(crate::core::Color::White, crate::core::PieceType::Pawn);
82 let from = crate::core::Position::new(4, 1).unwrap();
83 let to = crate::core::Position::new(4, 3).unwrap();
84 let move_type = crate::core::MoveType::Normal {
85 capture: false,
86 promotion: None,
87 };
88 let captured_piece = None;
89 let rook_from = None;
90 let ambiguity = (false, false);
91
92 let mov = Move::new(
93 piece,
94 from,
95 to,
96 move_type,
97 captured_piece,
98 rook_from,
99 ambiguity,
100 false,
101 false,
102 )
103 .unwrap();
104 let error = MoveInfoError::new("Invalid move".to_string(), mov.clone());
105
106 assert_eq!(error.error, "Invalid move");
107 assert_eq!(error.mov, mov);
108 }
109}