othello/src/repr/pos_map.rs
2025-03-24 15:44:06 -04:00

70 lines
2.0 KiB
Rust

use const_for::const_for;
use std::mem::MaybeUninit;
use super::{Board, CoordPair};
/// Map of all points on the board against some type T
/// Used to index like so: example[i][j]
/// with each coordinate
pub struct PosMap<T>([T; Board::AREA.0 as usize]);
impl<T: Copy> PosMap<T> {
pub const unsafe fn uninit() -> Self {
Self([MaybeUninit::zeroed().assume_init(); Board::AREA.0 as usize])
}
pub const fn from(v: [[T; Board::SIZE as usize]; Board::SIZE as usize]) -> Self {
let mut n = unsafe { Self::uninit() };
const_for!(i in 0..Board::SIZE => {
const_for!(j in 0..Board::SIZE => {
n.set(CoordPair::from_axes(i, j), v[i as usize][j as usize]);
});
});
n
}
pub const fn into_2d(&self) -> [[T; Board::SIZE as usize]; Board::SIZE as usize] {
let mut n: [[T; Board::SIZE as usize]; Board::SIZE as usize] =
unsafe { MaybeUninit::zeroed().assume_init() };
const_for!(i in 0..Board::SIZE => {
const_for!(j in 0..Board::SIZE => {
n[i as usize][j as usize] = *self.get(CoordPair::from_axes(i, j));
});
});
n
}
pub const fn get(&self, coords: CoordPair) -> &T {
&self.0[coords.0 as usize]
}
pub const fn set(&mut self, coords: CoordPair, value: T) {
self.0[coords.0 as usize] = value;
}
}
#[cfg(test)]
mod test {
use crate::repr::coords::CoordPairInner;
use super::*;
#[test]
fn from_into_test() {
let data: [[CoordPairInner; Board::SIZE as usize]; Board::SIZE as usize] = (0..Board::AREA
.0)
.collect::<Vec<_>>()
.chunks(Board::SIZE as usize)
.map(|x| -> [CoordPairInner; Board::SIZE as usize] { x.to_vec().try_into().unwrap() })
.collect::<Vec<_>>()
.try_into()
.unwrap();
let posmap = PosMap::from(data.clone());
assert_eq!(data, posmap.into_2d());
}
}