Skip to content

Commit

Permalink
feat(dirs): add Dirs struct (#371)
Browse files Browse the repository at this point in the history
  • Loading branch information
rohanku authored Jan 28, 2024
1 parent 48828a9 commit 6d6b834
Showing 1 changed file with 66 additions and 1 deletion.
67 changes: 66 additions & 1 deletion libs/geometry/src/dir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
use std::fmt::Display;

use array_map::Indexable;
use array_map::{ArrayMap, Indexable};
use serde::{Deserialize, Serialize};

/// An enumeration of axis-aligned directions.
Expand Down Expand Up @@ -71,3 +71,68 @@ impl std::ops::Not for Dir {
self.other()
}
}

/// An association of a value with type `T` to each of the two [`Dir`]s.
#[derive(Default, Debug, Clone, Copy, Eq, PartialEq)]
pub struct Dirs<T> {
inner: ArrayMap<Dir, T, 2>,
}

impl<T> Dirs<T>
where
T: Clone,
{
/// Creates a new [`Dirs`] with `value` associated with all directions.
///
/// The value will be cloned for each [`Dir`].
///
/// If your value is [`Copy`], consider using [`Dirs::uniform`] instead.
pub fn uniform_cloned(value: T) -> Self {
Self {
inner: ArrayMap::from_value(value),
}
}
}

impl<T> Dirs<T>
where
T: Copy,
{
/// Creates a new [`Dir`] with `value` associated with all directions.
pub const fn uniform(value: T) -> Self {
Self {
inner: ArrayMap::new([value; 2]),
}
}
}

impl<T> Dirs<T> {
/// Creates a new [`Dir`] with with the provided values for each direction.
pub const fn new(horiz: T, vert: T) -> Self {
// IMPORTANT: the ordering of array elements here must match
// the ordering of variants in the [`Dir`] enum.
Self {
inner: ArrayMap::new([horiz, vert]),
}
}

/// Maps a function over the provided [`Dir`], returning a new [`Dir`].
pub fn map<B>(self, f: impl FnMut(&Dir, T) -> B) -> Dirs<B> {
Dirs {
inner: self.inner.map(f),
}
}
}

impl<T> std::ops::Index<Dir> for Dirs<T> {
type Output = T;
fn index(&self, index: Dir) -> &Self::Output {
self.inner.index(index)
}
}

impl<T> std::ops::IndexMut<Dir> for Dirs<T> {
fn index_mut(&mut self, index: Dir) -> &mut Self::Output {
self.inner.index_mut(index)
}
}

0 comments on commit 6d6b834

Please sign in to comment.