use super::VMGcRef;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct I31(pub(super) u32);
impl Default for I31 {
#[inline]
fn default() -> Self {
Self::wrapping_u32(0)
}
}
impl std::fmt::Debug for I31 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("I31")
.field("as_u32", &self.get_u32())
.field("as_i32", &self.get_i32())
.finish()
}
}
impl I31 {
const DISCRIMINANT: u32 = VMGcRef::I31_REF_DISCRIMINANT;
#[inline]
pub fn new_u32(value: u32) -> Option<Self> {
if ((value << 1) >> 1) == value {
let i31 = Self::wrapping_u32(value);
debug_assert_eq!(i31.get_u32(), value);
Some(i31)
} else {
None
}
}
#[inline]
pub fn new_i32(value: i32) -> Option<Self> {
if ((value << 1) >> 1) == value {
let i31 = Self::wrapping_i32(value);
debug_assert_eq!(i31.get_i32(), value);
Some(i31)
} else {
None
}
}
#[inline]
pub fn wrapping_u32(value: u32) -> Self {
Self((value << 1) | Self::DISCRIMINANT)
}
#[inline]
#[allow(clippy::cast_sign_loss)]
pub fn wrapping_i32(value: i32) -> Self {
Self::wrapping_u32(value as u32)
}
#[inline]
pub fn get_u32(&self) -> u32 {
self.0 >> 1
}
#[inline]
pub fn get_i32(&self) -> i32 {
(self.0 as i32) >> 1
}
}