use crate::LayoutError;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Layout {
size: u64,
align: u64,
}
impl Layout {
pub const EMPTY: Self = Self { size: 0, align: 1 };
pub const fn new(size: u64, align: u64) -> Result<Self, LayoutError> {
if !align.is_power_of_two() {
return Err(LayoutError::InvalidAlignment(align));
}
Ok(Self { size, align })
}
pub const fn size(self) -> u64 {
self.size
}
pub const fn align(self) -> u64 {
self.align
}
pub fn padding_needed_for(self, align: u64) -> Result<u64, LayoutError> {
Self::new(0, align)?;
Ok(self.size.wrapping_neg() & (align - 1))
}
pub fn extend(self, next: Self) -> Result<(Self, u64), LayoutError> {
let offset = self
.size
.checked_add(self.padding_needed_for(next.align)?)
.ok_or(LayoutError::Overflow)?;
let size = offset.checked_add(next.size).ok_or(LayoutError::Overflow)?;
Ok((
Self {
size,
align: self.align.max(next.align),
},
offset,
))
}
pub fn align_to(self, align: u64) -> Result<Self, LayoutError> {
Self::new(self.size, self.align.max(Self::new(0, align)?.align))
}
pub fn pad_to_align(self) -> Result<Self, LayoutError> {
let size = self
.size
.checked_add(self.padding_needed_for(self.align)?)
.ok_or(LayoutError::Overflow)?;
Ok(Self { size, ..self })
}
pub fn repeat(self, count: u64) -> Result<(Self, u64), LayoutError> {
let stride = self.pad_to_align()?.size;
let size = stride.checked_mul(count).ok_or(LayoutError::Overflow)?;
Ok((
Self {
size,
align: self.align,
},
stride,
))
}
}
impl Default for Layout {
fn default() -> Self {
Self::EMPTY
}
}