From 96688562d07e08d4c2668d94d100f7e0d2fbeb13 Mon Sep 17 00:00:00 2001 From: Mark Wainwright Date: Thu, 19 Dec 2024 18:23:38 +0000 Subject: [PATCH] added insert and remove to tile_set --- src/tile_set.rs | 47 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/src/tile_set.rs b/src/tile_set.rs index 98fcb29..bdccbc8 100644 --- a/src/tile_set.rs +++ b/src/tile_set.rs @@ -32,7 +32,6 @@ macro_rules! tile_set { Self(0) }; - /// The set where all tiles are present #[allow(clippy::cast_possible_truncation)] pub const ALL: Self = Self(<$inner>::MAX >> (<$inner>::BITS - SIZE as u32)); @@ -84,6 +83,23 @@ macro_rules! tile_set { } } + #[inline] + pub const fn insert(&mut self, tile: &Tile) -> bool { + let mask = 1 << tile.inner() as u32; + let r = self.0 & mask == 0; + + self.0 |= mask; + r + } + + #[inline] + pub const fn remove(&mut self, tile: &Tile) -> bool { + let mask = 1 << tile.inner() as u32; + let r = self.0 & mask != 0; + self.0 &= !mask; + r + } + /// Returns a copy of self with the bit at `tile` set to `bit` #[inline] pub const fn with_bit_set(&self, tile: &Tile, bit: bool) -> Self { @@ -255,6 +271,11 @@ macro_rules! tile_set { Self(self.0 | rhs.0) } + #[inline] + pub const fn except(&self, rhs: &Self) -> Self { + self.intersect(&rhs.negate()) + } + #[must_use] #[inline] pub const fn is_subset(&self, rhs: &Self) -> bool { @@ -689,6 +710,30 @@ mod tests { assert_eq!(grid.negate().to_string(), "_*_\n***\n_*_"); } + #[test] + fn test_remove() { + let mut grid: TileSet16<3, 3, 9> = TileSet16::from_fn(|x| x.inner() % 2 == 0); + + for tile in Tile::iter_by_row() { + let removed = grid.remove(&tile); + assert_eq!(removed, tile.inner() % 2 == 0); + //removing for the second time + assert!(!grid.remove(&tile)); + } + } + + #[test] + fn test_insert() { + let mut grid: TileSet16<3, 3, 9> = TileSet16::from_fn(|x| x.inner() % 2 == 0); + + for tile in Tile::iter_by_row() { + let inserted = grid.insert(&tile); + assert_eq!(!inserted, tile.inner() % 2 == 0); + //removing for the second time + assert!(!grid.insert(&tile)); + } + } + #[test] fn test_intersect() { let grid_left: TileSet16<3, 3, 9> = TileSet16::from_fn(|x| x.x() == 1);