abstract away more coordinates

This commit is contained in:
2025-02-27 21:00:04 -05:00
parent 956386fb66
commit 6ae1726010
12 changed files with 251 additions and 204 deletions

63
src/repr/coords.rs Normal file
View File

@@ -0,0 +1,63 @@
use std::fmt::Display;
use super::Board;
use static_assertions::const_assert;
// PERF! having `Coord` be of type `u8` (instead of usize) increases
// performance by about 1-2% overall
pub type CoordAxis = u8;
pub type CoordPairInner = u8;
const_assert!(CoordPairInner::MAX as usize >= Board::BOARD_AREA as usize);
#[derive(PartialEq, Eq, Copy, Clone, Hash)]
pub struct CoordPair(pub CoordPairInner);
impl Display for CoordPair {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let (i, j) = (*self).into();
write!(f, "({}, {})", i, j)
}
}
impl std::fmt::Debug for CoordPair {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self)
}
}
/// Convert a row and column to an index in the board
pub const fn get_index(row: CoordAxis, col: CoordAxis) -> CoordPair {
CoordPair(row * Board::BOARD_SIZE + col)
}
pub const fn from_index(index: CoordPair) -> (CoordAxis, CoordAxis) {
let row = index.0 % Board::BOARD_SIZE;
let col = (index.0 - row) / Board::BOARD_SIZE;
(col, row)
}
impl From<(CoordAxis, CoordAxis)> for CoordPair {
fn from(value: (CoordAxis, CoordAxis)) -> Self {
get_index(value.0, value.1)
}
}
impl From<CoordPair> for (CoordAxis, CoordAxis) {
fn from(val: CoordPair) -> Self {
from_index(val)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn into_outof() {
let a: CoordPair = (1, 3).into();
let back: (CoordAxis, CoordAxis) = a.into();
assert_eq!(back, (1, 3));
}
}