Compare commits

...
Sign in to create a new pull request.

1 commit

Author SHA1 Message Date
d1950def00 [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.
2025-06-30 15:32:38 -07:00

View file

@ -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 {