forked from bevyengine/bevy
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
883abbb
commit 5876fae
Showing
3 changed files
with
100 additions
and
31 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
use std::num::NonZeroUsize; | ||
|
||
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] | ||
#[repr(transparent)] | ||
pub struct NonMaxUsize(NonZeroUsize); | ||
|
||
impl std::fmt::Debug for NonMaxUsize { | ||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
f.debug_tuple("NonMaxUsize").field(&self.0.get()).finish() | ||
} | ||
} | ||
|
||
impl NonMaxUsize { | ||
#[inline] | ||
pub const fn new(n: usize) -> Option<Self> { | ||
if let Some(n) = NonZeroUsize::new(n ^ usize::MAX) { | ||
Some(Self(n)) | ||
} else { | ||
None | ||
} | ||
} | ||
|
||
/// # Safety | ||
/// `n` must not be equal to [usize]::MAX. | ||
#[inline] | ||
pub const unsafe fn new_unchecked(n: usize) -> Self { | ||
Self(NonZeroUsize::new_unchecked(n ^ usize::MAX)) | ||
} | ||
|
||
#[inline(always)] | ||
pub const fn get(self) -> usize { | ||
self.0.get() ^ usize::MAX | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod test { | ||
use super::*; | ||
|
||
#[test] | ||
fn non_max_usize() { | ||
assert!(NonMaxUsize::new(usize::MAX).is_none()); | ||
assert_eq!(NonMaxUsize::new(0).unwrap().get(), 0); | ||
|
||
// SAFE: `0` != usize::MAX | ||
unsafe { | ||
assert_eq!(NonMaxUsize::new_unchecked(0).get(), 0); | ||
} | ||
|
||
assert_eq!( | ||
std::mem::size_of::<NonMaxUsize>(), | ||
std::mem::size_of::<Option<NonMaxUsize>>() | ||
); | ||
} | ||
} |