More fun with macros

This commit is contained in:
Timothy Warren 2022-12-16 14:36:56 -05:00
parent 556ab5669d
commit 5346caaf26
4 changed files with 38 additions and 6 deletions

View File

@ -106,3 +106,31 @@ impl<T> Grid2d<T> for Grid<T> {
&mut self.vec[start..=end]
}
}
#[macro_export]
/// Simplifies newtype wrapping of the `Grid` struct
macro_rules! impl_grid_newtype {
($($struct: tt, $target: path, $type: ty),* ) => {
$(
impl ::core::ops::Deref for $struct<$type> {
type Target = $target;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl ::core::ops::DerefMut for $struct<$type> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl $struct<$type> {
pub fn new(width: usize) -> Self {
$struct(<$target>::new(width))
}
}
)*
}
}

7
day12/Cargo.lock generated
View File

@ -2,6 +2,13 @@
# It is not intended for manual editing.
version = 3
[[package]]
name = "aoc-shared"
version = "0.1.0"
[[package]]
name = "day12"
version = "0.1.0"
dependencies = [
"aoc-shared",
]

View File

@ -6,3 +6,4 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
aoc-shared = { path = "../aoc-shared"}

View File

@ -1,4 +1,4 @@
use aoc_shared::deref;
use aoc_shared::impl_grid_newtype;
use aoc_shared::grid::Grid as BaseGrid;
use aoc_shared::grid::Grid2d;
use std::collections::HashSet;
@ -53,13 +53,9 @@ impl Tree {
// 2. Implement the Deref trait for the wrapped struct
#[derive(Debug)]
pub struct Grid<T>(BaseGrid<T>);
deref!(Grid<Tree>, BaseGrid<Tree>);
impl_grid_newtype!(Grid, BaseGrid<Tree>, Tree);
impl Grid<Tree> {
pub fn new(width: usize) -> Self {
Grid(BaseGrid::new(width))
}
pub fn from_file_str(file_str: &'static str) -> Grid<Tree> {
let lines: Vec<&str> = file_str.lines().collect();
let width = lines[0].len();