allow large Size again

This commit is contained in:
Ralf Jung 2022-03-29 22:25:38 -04:00
parent 9c06e1ba47
commit 2799885ed0
1 changed files with 7 additions and 16 deletions

View File

@ -279,7 +279,6 @@ impl ToJson for Endian {
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encodable, Decodable)] #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encodable, Decodable)]
#[derive(HashStable_Generic)] #[derive(HashStable_Generic)]
pub struct Size { pub struct Size {
// The top 3 bits are ALWAYS zero.
raw: u64, raw: u64,
} }
@ -287,22 +286,9 @@ impl Size {
pub const ZERO: Size = Size { raw: 0 }; pub const ZERO: Size = Size { raw: 0 };
/// Rounds `bits` up to the next-higher byte boundary, if `bits` is /// Rounds `bits` up to the next-higher byte boundary, if `bits` is
/// is not aligned. /// not a multiple of 8.
pub fn from_bits(bits: impl TryInto<u64>) -> Size { pub fn from_bits(bits: impl TryInto<u64>) -> Size {
let bits = bits.try_into().ok().unwrap(); let bits = bits.try_into().ok().unwrap();
#[cold]
fn overflow(bits: u64) -> ! {
panic!("Size::from_bits({}) has overflowed", bits);
}
// This is the largest value of `bits` that does not cause overflow
// during rounding, and guarantees that the resulting number of bytes
// cannot cause overflow when multiplied by 8.
if bits > 0xffff_ffff_ffff_fff8 {
overflow(bits);
}
// Avoid potential overflow from `bits + 7`. // Avoid potential overflow from `bits + 7`.
Size { raw: bits / 8 + ((bits % 8) + 7) / 8 } Size { raw: bits / 8 + ((bits % 8) + 7) / 8 }
} }
@ -325,7 +311,12 @@ impl Size {
#[inline] #[inline]
pub fn bits(self) -> u64 { pub fn bits(self) -> u64 {
self.raw << 3 #[cold]
fn overflow(bytes: u64) -> ! {
panic!("Size::bits: {} bytes in bits doesn't fit in u64", bytes)
}
self.bytes().checked_mul(8).unwrap_or_else(|| overflow(self.bytes()))
} }
#[inline] #[inline]