From 5346caaf260890f6d29eef7e6744f117dd732164 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Fri, 16 Dec 2022 14:36:56 -0500 Subject: [PATCH] More fun with macros --- aoc-shared/src/grid.rs | 28 ++++++++++++++++++++++++++++ day12/Cargo.lock | 7 +++++++ day12/Cargo.toml | 1 + day8/src/main.rs | 8 ++------ 4 files changed, 38 insertions(+), 6 deletions(-) diff --git a/aoc-shared/src/grid.rs b/aoc-shared/src/grid.rs index 7d2027e..f9d28ac 100644 --- a/aoc-shared/src/grid.rs +++ b/aoc-shared/src/grid.rs @@ -106,3 +106,31 @@ impl Grid2d for Grid { &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)) + } + } + )* + } +} diff --git a/day12/Cargo.lock b/day12/Cargo.lock index 5e9bbe3..dec816a 100644 --- a/day12/Cargo.lock +++ b/day12/Cargo.lock @@ -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", +] diff --git a/day12/Cargo.toml b/day12/Cargo.toml index ba13763..ac51653 100644 --- a/day12/Cargo.toml +++ b/day12/Cargo.toml @@ -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"} diff --git a/day8/src/main.rs b/day8/src/main.rs index c12b500..be1ba90 100644 --- a/day8/src/main.rs +++ b/day8/src/main.rs @@ -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(BaseGrid); -deref!(Grid, BaseGrid); +impl_grid_newtype!(Grid, BaseGrid, Tree); impl Grid { - pub fn new(width: usize) -> Self { - Grid(BaseGrid::new(width)) - } - pub fn from_file_str(file_str: &'static str) -> Grid { let lines: Vec<&str> = file_str.lines().collect(); let width = lines[0].len();