add EitherIndex type

This commit is contained in:
Folkert 2022-03-13 01:44:47 +01:00
parent 1ae5ccaa83
commit 59c2c05588
No known key found for this signature in database
GPG key ID: 1F17F6FFD112B97C

View file

@ -117,3 +117,56 @@ impl<T> Slice<T> {
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))
}
}
}