Skip to main content

mynd_core/
plane.rs

1use core::num::{NonZeroU32, NonZeroUsize};
2
3use mynd_math::{checked_add_u64, checked_mul_u64, checked_u64_to_usize};
4
5use crate::{GeometryError, GeometryResult};
6
7/// A nonzero output-buffer length representable by the target's `usize`.
8#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
9pub struct OutputLength(NonZeroUsize);
10
11impl OutputLength {
12    /// Returns the validated number of bytes.
13    #[must_use]
14    pub const fn get(self) -> usize {
15        self.0.get()
16    }
17}
18
19/// A nonempty, aligned plane extent in a caller-owned output buffer.
20#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
21pub struct PlaneLayout {
22    offset: usize,
23    row_bytes: NonZeroUsize,
24    row_stride: NonZeroUsize,
25    rows: NonZeroU32,
26    alignment: NonZeroUsize,
27    end: OutputLength,
28}
29
30impl PlaneLayout {
31    /// Validates one plane and computes its exact last-row output extent.
32    ///
33    /// Inputs use `u64` so byte-derived fixed-width values are checked before
34    /// becoming target-width offsets. Alignment is numeric divisibility and
35    /// does not claim Rust allocator-layout validity.
36    ///
37    /// # Errors
38    ///
39    /// Rejects zero row bytes, rows, or alignment; a stride smaller than one
40    /// used row; a misaligned offset or stride; arithmetic overflow; and any
41    /// value or final extent not representable by `usize`.
42    pub fn new(
43        offset: u64,
44        row_bytes: u64,
45        row_stride: u64,
46        rows: u32,
47        alignment: u64,
48    ) -> GeometryResult<Self> {
49        validate_plane_fields(offset, row_bytes, row_stride, rows, alignment)?;
50        let (last_row_start, _) = required_extent_u64(offset, row_bytes, row_stride, rows)?;
51        let offset = checked_u64_to_usize(offset).map_err(GeometryError::Arithmetic)?;
52        let row_bytes = checked_u64_to_usize(row_bytes).map_err(GeometryError::Arithmetic)?;
53        let row_bytes = NonZeroUsize::new(row_bytes).ok_or(GeometryError::ZeroRowBytes)?;
54        let row_stride = checked_u64_to_usize(row_stride).map_err(GeometryError::Arithmetic)?;
55        let row_stride = NonZeroUsize::new(row_stride).ok_or(GeometryError::StrideTooSmall)?;
56        let alignment = checked_u64_to_usize(alignment).map_err(GeometryError::Arithmetic)?;
57        let alignment = NonZeroUsize::new(alignment).ok_or(GeometryError::ZeroAlignment)?;
58        let rows = NonZeroU32::new(rows).ok_or(GeometryError::ZeroRows)?;
59        let last_row_start =
60            checked_u64_to_usize(last_row_start).map_err(GeometryError::Arithmetic)?;
61        let end = row_bytes
62            .checked_add(last_row_start)
63            .ok_or(GeometryError::Arithmetic(
64                mynd_math::MathError::ConversionOutOfRange,
65            ))?;
66        Ok(Self {
67            offset,
68            row_bytes,
69            row_stride,
70            rows,
71            alignment,
72            end: OutputLength(end),
73        })
74    }
75
76    /// Returns the plane's byte offset.
77    #[must_use]
78    pub const fn offset(self) -> usize {
79        self.offset
80    }
81
82    /// Returns the bytes used by each row.
83    #[must_use]
84    pub const fn row_bytes(self) -> usize {
85        self.row_bytes.get()
86    }
87
88    /// Returns the distance between consecutive row starts.
89    #[must_use]
90    pub const fn row_stride(self) -> usize {
91        self.row_stride.get()
92    }
93
94    /// Returns the nonzero row count.
95    #[must_use]
96    pub const fn rows(self) -> u32 {
97        self.rows.get()
98    }
99
100    /// Returns the numeric row-start alignment.
101    #[must_use]
102    pub const fn alignment(self) -> usize {
103        self.alignment.get()
104    }
105
106    /// Returns the exclusive end required to store the final used row.
107    #[must_use]
108    pub const fn end(self) -> OutputLength {
109        self.end
110    }
111}
112
113/// Validates an ordered, nonoverlapping set of planes and returns its extent.
114///
115/// Gaps are allowed. Offsets must be in nondecreasing order, and each plane
116/// must begin at or after the preceding plane's exclusive end.
117///
118/// # Errors
119///
120/// Returns [`GeometryError::NoPlanes`],
121/// [`GeometryError::PlanesOutOfOrder`], or [`GeometryError::PlaneOverlap`]
122/// when the set violates the contract.
123pub fn checked_plane_output_len(planes: &[PlaneLayout]) -> GeometryResult<OutputLength> {
124    let mut planes = planes.iter();
125    let first = planes.next().ok_or(GeometryError::NoPlanes)?;
126    let mut previous_offset = first.offset();
127    let mut previous_end = first.end();
128    for plane in planes {
129        if plane.offset() < previous_offset {
130            return Err(GeometryError::PlanesOutOfOrder);
131        }
132        if plane.offset() < previous_end.get() {
133            return Err(GeometryError::PlaneOverlap);
134        }
135        previous_offset = plane.offset();
136        previous_end = plane.end();
137    }
138    Ok(previous_end)
139}
140
141#[cfg(kani)]
142pub(crate) const fn required_len_u64(
143    offset: u64,
144    row_bytes: u64,
145    row_stride: u64,
146    rows: u32,
147) -> GeometryResult<u64> {
148    match required_extent_u64(offset, row_bytes, row_stride, rows) {
149        Ok((_, end)) => Ok(end),
150        Err(error) => Err(error),
151    }
152}
153
154const fn required_extent_u64(
155    offset: u64,
156    row_bytes: u64,
157    row_stride: u64,
158    rows: u32,
159) -> GeometryResult<(u64, u64)> {
160    if row_bytes == 0 {
161        return Err(GeometryError::ZeroRowBytes);
162    }
163    if rows == 0 {
164        return Err(GeometryError::ZeroRows);
165    }
166    if row_stride < row_bytes {
167        return Err(GeometryError::StrideTooSmall);
168    }
169    let prior_rows = match (rows as u64).checked_sub(1) {
170        Some(prior_rows) => prior_rows,
171        None => return Err(GeometryError::ZeroRows),
172    };
173    let prior_bytes = match checked_mul_u64(row_stride, prior_rows) {
174        Ok(prior_bytes) => prior_bytes,
175        Err(error) => return Err(GeometryError::Arithmetic(error)),
176    };
177    let last_row = match checked_add_u64(offset, prior_bytes) {
178        Ok(last_row) => last_row,
179        Err(error) => return Err(GeometryError::Arithmetic(error)),
180    };
181    match checked_add_u64(last_row, row_bytes) {
182        Ok(end) => Ok((last_row, end)),
183        Err(error) => Err(GeometryError::Arithmetic(error)),
184    }
185}
186
187fn validate_plane_fields(
188    offset: u64,
189    row_bytes: u64,
190    row_stride: u64,
191    rows: u32,
192    alignment: u64,
193) -> GeometryResult<()> {
194    if row_bytes == 0 {
195        return Err(GeometryError::ZeroRowBytes);
196    }
197    if rows == 0 {
198        return Err(GeometryError::ZeroRows);
199    }
200    if alignment == 0 {
201        return Err(GeometryError::ZeroAlignment);
202    }
203    if row_stride < row_bytes {
204        return Err(GeometryError::StrideTooSmall);
205    }
206    if offset.checked_rem(alignment) != Some(0) {
207        return Err(GeometryError::OffsetMisaligned);
208    }
209    if row_stride.checked_rem(alignment) != Some(0) {
210        return Err(GeometryError::StrideMisaligned);
211    }
212    Ok(())
213}