|
| 1 | +use crate::convert::TryFrom; |
| 2 | +use crate::{fmt, num}; |
| 3 | + |
| 4 | +/// A type storing a possible object size (in bytes) in the rust abstract machine. |
| 5 | +/// |
| 6 | +/// This can be thought of as a positive `isize`, or `usize` without the high bit |
| 7 | +/// set. This is important because [`pointer::offset`] is UB for *byte* sizes |
| 8 | +/// too large for an `isize`, and there's a corresponding language limit on the |
| 9 | +/// size of any allocated object. |
| 10 | +/// |
| 11 | +/// Note that particularly large sizes, while representable in this type, are |
| 12 | +/// likely not to be supported by actual allocators and machines. |
| 13 | +#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] |
| 14 | +#[repr(transparent)] |
| 15 | +#[cfg_attr(target_pointer_width = "16", rustc_layout_scalar_valid_range_end(0x7FFF))] |
| 16 | +#[cfg_attr(target_pointer_width = "32", rustc_layout_scalar_valid_range_end(0x7FFF_FFFF))] |
| 17 | +#[cfg_attr(target_pointer_width = "64", rustc_layout_scalar_valid_range_end(0x7FFF_FFFF_FFFF_FFFF))] |
| 18 | +pub(crate) struct ValidSize(usize); |
| 19 | + |
| 20 | +const MAX_SIZE: usize = isize::MAX as usize; |
| 21 | + |
| 22 | +const _: () = unsafe { ValidSize::new_unchecked(MAX_SIZE); }; |
| 23 | + |
| 24 | +impl ValidSize { |
| 25 | + /// Creates a `ValidSize` from a `usize` that fits in an `isize`. |
| 26 | + /// |
| 27 | + /// # Safety |
| 28 | + /// |
| 29 | + /// `size` must be less than or equal to `isize::MAX`. |
| 30 | + /// |
| 31 | + /// Equivalently, it must not have its high bit set. |
| 32 | + #[inline] |
| 33 | + pub(crate) const unsafe fn new_unchecked(size: usize) -> Self { |
| 34 | + debug_assert!(size <= MAX_SIZE); |
| 35 | + |
| 36 | + // SAFETY: By precondition, this must be within our validity invariant. |
| 37 | + unsafe { ValidSize(size) } |
| 38 | + } |
| 39 | + |
| 40 | + #[inline] |
| 41 | + pub(crate) const fn as_usize(self) -> usize { |
| 42 | + self.0 |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +impl TryFrom<usize> for ValidSize { |
| 47 | + type Error = num::TryFromIntError; |
| 48 | + |
| 49 | + #[inline] |
| 50 | + fn try_from(size: usize) -> Result<ValidSize, Self::Error> { |
| 51 | + if size <= MAX_SIZE { |
| 52 | + // SAFETY: Just checked it's within our validity invariant. |
| 53 | + unsafe { Ok(ValidSize(size)) } |
| 54 | + } else { |
| 55 | + Err(num::TryFromIntError(())) |
| 56 | + } |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +impl fmt::Debug for ValidSize { |
| 61 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 62 | + self.as_usize().fmt(f) |
| 63 | + } |
| 64 | +} |
0 commit comments