stockfish/
engine_eval.rs

1use std::fmt;
2use serde::{Serialize, Serializer};
3
4/// The category of evaluation returned by stockfish. Either `Centipawns` or `Mate`.
5#[derive(Debug, Clone, Copy, PartialEq)]
6pub enum EvalType {Centipawn, Mate}
7
8impl EvalType {
9
10    /// Creates an [`EvalType`] from a string descriptor. The valid descriptors are:
11    /// - `"cp"`, which translates to [`EvalType::Centipawn`]
12    /// - `"mate"`, which translates to [`EvalType::Mate`]
13    /// 
14    /// # Panics
15    /// 
16    /// This function panics when given a string descriptor that doesn't match those listed above.
17    pub fn from_descriptor(str: &str) -> EvalType {
18        match str {
19            "cp" => EvalType::Centipawn,
20            "mate" => EvalType::Mate,
21            _ => panic!("Unable to create eval type")
22        }
23    }
24}
25impl fmt::Display for EvalType {
26    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
27        write!(f, "{}", match self {
28            EvalType::Centipawn => "cp",
29            EvalType::Mate => "mate",
30        })
31    }
32}
33impl Serialize for EvalType {
34    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
35        serializer.serialize_str(&self.to_string())
36    }
37}
38
39/// Represents the evaluation returned from the engine. Includes [`EvalType`] and a numerical score value.
40#[derive(Debug, Clone, Copy, PartialEq)]
41pub struct EngineEval {
42    eval_type: EvalType,
43    value: i32,
44}
45
46impl EngineEval {
47    pub fn new(eval_type: EvalType, value: i32) -> Self {
48        Self { eval_type, value }
49    }
50
51    #[must_use]
52    pub fn eval_type(&self) -> EvalType {
53        self.eval_type
54    }
55
56    #[must_use]
57    pub fn value(&self) -> i32 {
58        self.value
59    }
60}
61impl fmt::Display for EngineEval {
62    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
63        let str = self.eval_type().to_string() + " " + &self.value().to_string();
64        write!(f, "{str}")
65    }
66}
67impl Serialize for EngineEval {
68    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
69        serializer.serialize_str(&self.to_string())
70    }
71}