Skip to content

Commit 4b69b40

Browse files
committed
Implement conversions from and to point from arrays and tuples
1 parent f558785 commit 4b69b40

File tree

3 files changed

+41
-9
lines changed

3 files changed

+41
-9
lines changed

crates/utils/src/point.rs

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@ use std::fmt::Debug;
55
use std::ops::{Add, AddAssign, Mul, MulAssign, Sub, SubAssign};
66

77
macro_rules! point_impl {
8-
($(#[$m:meta])* $v:vis struct $s:ident{$($f:ident),+}) => {
8+
($n:literal, $tuple:tt =>
9+
$(#[$m:meta])* $v:vis struct $s:ident{$($i:tt => $f:ident),+}
10+
) => {
911
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)]
1012
$(#[$m])* $v struct $s<T: Number> {
1113
$(pub $f: T,)+
@@ -108,12 +110,44 @@ macro_rules! point_impl {
108110
$(self.$f -= rhs.$f;)+
109111
}
110112
}
113+
114+
impl<T: Number> From<[T; $n]> for $s<T> {
115+
#[inline]
116+
fn from(arr: [T; $n]) -> Self {
117+
Self{$(
118+
$f: arr[$i],
119+
)+}
120+
}
121+
}
122+
123+
impl<T: Number> From<$tuple> for $s<T> {
124+
#[inline]
125+
fn from(arr: $tuple) -> Self {
126+
Self{$(
127+
$f: arr.$i,
128+
)+}
129+
}
130+
}
131+
132+
impl<T: Number> From<$s<T>> for [T; $n] {
133+
#[inline]
134+
fn from(value: $s<T>) -> Self {
135+
[$(value.$f),+]
136+
}
137+
}
138+
139+
impl<T: Number> From<$s<T>> for $tuple {
140+
#[inline]
141+
fn from(value: $s<T>) -> Self {
142+
($(value.$f),+)
143+
}
144+
}
111145
};
112146
}
113147

114-
point_impl! {
148+
point_impl! {2, (T, T) =>
115149
/// Struct representing a 2D point or vector.
116-
pub struct Point2D{x, y}
150+
pub struct Point2D{0 => x, 1 => y}
117151
}
118152

119153
impl<T: Signed> Point2D<T> {
@@ -155,7 +189,7 @@ impl<T: Signed> Point2D<T> {
155189
}
156190
}
157191

158-
point_impl! {
192+
point_impl! {3, (T, T, T) =>
159193
/// Struct representing a 3D point or vector.
160-
pub struct Point3D{x, y, z}
194+
pub struct Point3D{0 => x, 1 => y, 2 => z}
161195
}

crates/year2017/src/day20.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,7 @@ struct Particle {
1717

1818
impl Day20 {
1919
pub fn new(input: &str, _: InputType) -> Result<Self, InputError> {
20-
let vector = parser::i64()
21-
.repeat_n(b',')
22-
.map(|[x, y, z]| Point3D::new(x, y, z));
20+
let vector = parser::i64().repeat_n(b',').map(Point3D::from);
2321

2422
Ok(Self {
2523
particles: vector

crates/year2024/src/day18.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ impl Day18 {
3434
let mut fallen = 0;
3535
for item in parser::number_range(0..=max_coord)
3636
.then(parser::number_range(0..=max_coord).with_prefix(b','))
37-
.map(|(x, y)| Point2D { x, y })
37+
.map(Point2D::from)
3838
.with_consumed()
3939
.with_suffix(parser::eol())
4040
.parse_iterator(input)

0 commit comments

Comments
 (0)