From d1950def002f7b25e6447d7be9b1522d7c7722ef Mon Sep 17 00:00:00 2001 From: Eryn Wells Date: Mon, 30 Jun 2025 15:32:38 -0700 Subject: [PATCH] [core] Add conversions between Score and f32 These conversions assume the float value you want is a point value where 1 point equals 1 pawn. --- core/src/score.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/core/src/score.rs b/core/src/score.rs index 2dfd7c9..c7f4f2e 100644 --- a/core/src/score.rs +++ b/core/src/score.rs @@ -6,6 +6,7 @@ use std::{ }; pub(crate) type Value = i32; +pub(crate) type FloatValue = f32; /// A score for a position in centipawns. #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] @@ -38,6 +39,24 @@ impl Score { Self(value) } + /// Create a [`Score`] from a floating point value. This method assumes the + /// value is a point value where 1 point = 1 pawn. The floating point value + /// will be truncated as part of this conversion. + /// + /// ## Examples + /// + /// ``` + /// use chessfriend_core::score::Score; + /// assert_eq!(Score::from_float(3.1415926), Score(314)); + /// assert_ne!(Score::from_float(2.7182818).to_float(), 2.7182818); + /// ``` + /// + #[must_use] + pub const fn from_float(value: FloatValue) -> Self { + #[allow(clippy::cast_possible_truncation)] + Self((value * Self::CENTIPAWNS_PER_POINT) as Value) + } + /// Returns `true` if this [`Score`] is zero. /// /// ## Examples @@ -52,6 +71,14 @@ impl Score { pub const fn is_zero(&self) -> bool { self.0 == 0 } + + /// Return a floating point value in points where 1 point = 1 pawn. This + /// conversion loses precision. + #[must_use] + #[allow(clippy::cast_precision_loss)] + pub const fn to_float(&self) -> FloatValue { + self.0 as f32 / Self::CENTIPAWNS_PER_POINT + } } impl Add for Score {