From 59c2c055885416babc2e6b6daea358f94e66eec9 Mon Sep 17 00:00:00 2001 From: Folkert Date: Sun, 13 Mar 2022 01:44:47 +0100 Subject: [PATCH] add EitherIndex type --- compiler/collections/src/soa.rs | 53 +++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/compiler/collections/src/soa.rs b/compiler/collections/src/soa.rs index 563dba4f67..c0a406da38 100644 --- a/compiler/collections/src/soa.rs +++ b/compiler/collections/src/soa.rs @@ -117,3 +117,56 @@ impl Slice { self.indices().map(|i| Index::new(i as _)) } } + +#[derive(PartialEq, Eq)] +pub struct EitherIndex { + index: u32, + _marker: std::marker::PhantomData<(T, U)>, +} + +impl Clone for EitherIndex { + fn clone(&self) -> Self { + Self { + index: self.index, + _marker: self._marker, + } + } +} + +impl Copy for EitherIndex {} + +impl std::fmt::Debug for EitherIndex { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Index({})", self.index) + } +} + +impl EitherIndex { + const MASK: u32 = 1 << 31; + + pub fn from_left(input: Index) -> Self { + assert_eq!(input.index & Self::MASK, 0); + + Self { + index: input.index, + _marker: std::marker::PhantomData, + } + } + + pub fn from_right(input: Index) -> 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> { + if self.index & Self::MASK == 0 { + Ok(Index::new(self.index)) + } else { + Err(Index::new(self.index ^ Self::MASK)) + } + } +}