From 556ab5669d1d87e68cbc14521e60a7673529d4ae Mon Sep 17 00:00:00 2001 From: "Timothy J. Warren" Date: Fri, 16 Dec 2022 12:20:31 -0500 Subject: [PATCH] Quick macro to do newtype deref implementation --- aoc-shared/src/lib.rs | 20 ++++++++++++++++++++ day8/src/main.rs | 15 ++------------- 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/aoc-shared/src/lib.rs b/aoc-shared/src/lib.rs index 204404f..67c5f33 100644 --- a/aoc-shared/src/lib.rs +++ b/aoc-shared/src/lib.rs @@ -1,2 +1,22 @@ pub mod grid; pub use grid::*; + +#[macro_export] +macro_rules! deref { + ($($struct: ty, $target: ty),* ) => { + $( + impl ::core::ops::Deref for $struct { + type Target = $target; + + fn deref(&self) -> &Self::Target { + &self.0 + } + } + impl ::core::ops::DerefMut for $struct { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } + } + )* + } +} diff --git a/day8/src/main.rs b/day8/src/main.rs index d5058b7..c12b500 100644 --- a/day8/src/main.rs +++ b/day8/src/main.rs @@ -1,7 +1,7 @@ +use aoc_shared::deref; use aoc_shared::grid::Grid as BaseGrid; use aoc_shared::grid::Grid2d; use std::collections::HashSet; -use std::ops::{Deref, DerefMut}; #[derive(Debug, Copy, Clone, PartialOrd, PartialEq, Eq, Hash)] enum VisibleDirection { @@ -53,18 +53,7 @@ impl Tree { // 2. Implement the Deref trait for the wrapped struct #[derive(Debug)] pub struct Grid(BaseGrid); -impl Deref for Grid { - type Target = BaseGrid; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} -impl DerefMut for Grid { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } -} +deref!(Grid, BaseGrid); impl Grid { pub fn new(width: usize) -> Self {