use std::fmt;
use std::ops::{Add, Mul};
use crate::*;
#[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, GcCompat)]
pub struct Size { raw: Int }
impl fmt::Debug for Size {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Size({} bytes)", self.bytes())
}
}
impl Size {
pub const ZERO: Size = Size { raw: Int::ZERO };
pub fn from_bits(bits: impl Into<Int>) -> Option<Size> {
let bits = bits.into();
if bits % 8 != 0 { return None; };
if bits < 0 { return None; }
let raw = bits / 8;
Some(Size { raw })
}
pub const fn from_bits_const(bits: u64) -> Option<Size> {
if bits % 8 != 0 { return None; }
let bytes = bits / 8;
let raw = Int::from_u64(bytes);
Some(Size { raw })
}
pub fn from_bytes(bytes: impl Into<Int>) -> Option<Size> {
let bytes = bytes.into();
if bytes < 0 { return None; }
Some(Size { raw: bytes })
}
pub const fn from_bytes_const(bytes: u64) -> Size {
let raw = Int::from_u64(bytes);
Size { raw }
}
pub fn bytes(self) -> Int { self.raw }
pub fn bits(self) -> Int { self.raw * 8 }
pub fn is_zero(&self) -> bool {
self.bytes() == 0
}
pub fn align_to(self, align: Align) -> Size {
Size::from_bytes(self.bytes().next_multiple_of(align.bytes())).unwrap()
}
}
impl Add for Size {
type Output = Size;
fn add(self, rhs: Size) -> Size {
let b = self.bytes() + rhs.bytes();
Size::from_bytes(b).unwrap()
}
}
impl Mul<Int> for Size {
type Output = Size;
fn mul(self, rhs: Int) -> Size {
let b = self.bytes() * rhs;
Size::from_bytes(b).unwrap()
}
}
impl Mul<Size> for Int {
type Output = Size;
fn mul(self, rhs: Size) -> Size {
let b = self * rhs.bytes();
Size::from_bytes(b).unwrap()
}
}
#[test]
fn test_align_to() {
fn size(x: impl Into<Int>) -> Size {
Size::from_bytes(x).unwrap()
}
fn align(x: impl Into<Int>) -> Align {
Align::from_bytes(x).unwrap()
}
assert_eq!(size(0).align_to(align(16)), size(0));
assert_eq!(size(1).align_to(align(4)), size(4));
assert_eq!(size(4).align_to(align(4)), size(4));
assert_eq!(size(7489).align_to(align(1)), size(7489));
}