mirror of
https://github.com/roc-lang/roc.git
synced 2025-09-30 07:14:46 +00:00
add EitherIndex type
This commit is contained in:
parent
1ae5ccaa83
commit
59c2c05588
1 changed files with 53 additions and 0 deletions
|
@ -117,3 +117,56 @@ impl<T> Slice<T> {
|
||||||
self.indices().map(|i| Index::new(i as _))
|
self.indices().map(|i| Index::new(i as _))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(PartialEq, Eq)]
|
||||||
|
pub struct EitherIndex<T, U> {
|
||||||
|
index: u32,
|
||||||
|
_marker: std::marker::PhantomData<(T, U)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, U> Clone for EitherIndex<T, U> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self {
|
||||||
|
index: self.index,
|
||||||
|
_marker: self._marker,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, U> Copy for EitherIndex<T, U> {}
|
||||||
|
|
||||||
|
impl<T, U> std::fmt::Debug for EitherIndex<T, U> {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(f, "Index({})", self.index)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, U> EitherIndex<T, U> {
|
||||||
|
const MASK: u32 = 1 << 31;
|
||||||
|
|
||||||
|
pub fn from_left(input: Index<T>) -> Self {
|
||||||
|
assert_eq!(input.index & Self::MASK, 0);
|
||||||
|
|
||||||
|
Self {
|
||||||
|
index: input.index,
|
||||||
|
_marker: std::marker::PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_right(input: Index<U>) -> Self {
|
||||||
|
assert_eq!(input.index & Self::MASK, 0);
|
||||||
|
|
||||||
|
Self {
|
||||||
|
index: input.index | Self::MASK,
|
||||||
|
_marker: std::marker::PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const fn split(self) -> Result<Index<T>, Index<U>> {
|
||||||
|
if self.index & Self::MASK == 0 {
|
||||||
|
Ok(Index::new(self.index))
|
||||||
|
} else {
|
||||||
|
Err(Index::new(self.index ^ Self::MASK))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue