Skip to main content

zenpixels/
storage.rs

1//! Alignment-exact, `#![forbid(unsafe_code)]` owned pixel storage.
2//!
3//! # Allocation / deallocation alignment rules (`bytemuck` & `GlobalAlloc`)
4//!
5//! Rust's [`core::alloc::GlobalAlloc::dealloc`] requires every allocation to be
6//! freed with the **exact same `Layout` (byte capacity and alignment)** that
7//! allocated it. Therefore:
8//!
9//! - A `Vec<u8>` (`align = 1`) can **never** become a `Vec<u16>` (`align = 2`)
10//!   or `Vec<Rgb<u16>>` (`align = 2`) without copying, even if glibc happens to
11//!   return an even pointer.
12//! - Conversely, `Vec<Rgb<u16>>` (`align = 2, size = 6`) **can** move zero-copy
13//!   to and from `Vec<u16>` (`align = 2, size = 2`) via
14//!   [`bytemuck::allocation::try_cast_vec`] whenever both length and capacity in
15//!   bytes are multiples of `size_of::<Rgb<u16>>()` (`6`).
16//! - [`AlignedSamples`] allocates `Vec<Chunk>` with `#[repr(C, align(64))]`, so
17//!   its base address is always 64-byte aligned (divisible by `1, 2, 4, 8, 16,
18//!   32, 64` for zero-copy slice borrowing via `bytemuck::cast_slice`), and it
19//!   always deallocates with `align = 64` (never UB-cast to `Vec<u8>`).
20//! - On 32-bit targets where `align_of::<u64>()` may differ from
21//!   `align_of::<f64>()`, `F64` checks exact alignment equality before casting.
22
23use alloc::boxed::Box;
24use alloc::sync::Arc;
25use alloc::vec::Vec;
26use core::any::Any;
27use core::fmt;
28
29use crate::layout::SampleType;
30use crate::pixel_types::F16Sample;
31
32/// 64-byte aligned allocation unit for [`AlignedSamples`].
33///
34/// Using `Vec<Chunk>` guarantees 64-byte base alignment and matching 64-byte
35/// deallocation layout under `#![forbid(unsafe_code)]`.
36#[derive(Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)]
37#[repr(C, align(64))]
38struct Chunk([u8; 64]);
39
40/// Owned byte storage whose first byte is guaranteed 64-byte aligned on every allocator.
41///
42/// Zero-copy slice borrowing works for every sample and pixel type (`&[u8]`,
43/// `&[u16]`, `&[f32]`, `&[f64]`, `&[Rgb<u16>]`, `&[Rgba<f32>]`, …) because 64
44/// is a multiple of every natural alignment. Cannot convert to `Vec<T>` without
45/// copying because its deallocation alignment is 64.
46#[derive(Clone)]
47pub struct AlignedSamples {
48    chunks: Vec<Chunk>,
49    byte_len: usize,
50}
51
52impl AlignedSamples {
53    /// Fallibly allocate `byte_len` zeroed bytes on a 64-byte boundary.
54    pub fn zeroed_bytes(byte_len: usize) -> Result<Self, StorageError> {
55        if byte_len > isize::MAX as usize {
56            return Err(StorageError::AllocationFailed);
57        }
58        let count = byte_len.div_ceil(core::mem::size_of::<Chunk>());
59        core::alloc::Layout::array::<Chunk>(count).map_err(|_| StorageError::AllocationFailed)?;
60        let chunks = bytemuck::allocation::try_zeroed_vec(count)
61            .map_err(|()| StorageError::AllocationFailed)?;
62        Ok(Self { chunks, byte_len })
63    }
64
65    /// Immutable byte view (guaranteed 64-byte aligned base pointer).
66    #[inline]
67    #[must_use]
68    pub fn as_bytes(&self) -> &[u8] {
69        &bytemuck::cast_slice(&self.chunks)[..self.byte_len]
70    }
71
72    /// Mutable byte view (guaranteed 64-byte aligned base pointer).
73    #[inline]
74    #[must_use]
75    pub fn as_bytes_mut(&mut self) -> &mut [u8] {
76        &mut bytemuck::cast_slice_mut(&mut self.chunks)[..self.byte_len]
77    }
78
79    /// Active byte length.
80    #[inline]
81    #[must_use]
82    pub const fn len(&self) -> usize {
83        self.byte_len
84    }
85
86    /// Whether the buffer is empty.
87    #[inline]
88    #[must_use]
89    pub const fn is_empty(&self) -> bool {
90        self.byte_len == 0
91    }
92
93    /// Fallibly clone the 64-byte aligned backing storage without aborting on OOM.
94    pub fn try_clone(&self) -> Result<Self, StorageError> {
95        let mut chunks = Vec::new();
96        chunks
97            .try_reserve_exact(self.chunks.len())
98            .map_err(|_| StorageError::AllocationFailed)?;
99        chunks.extend_from_slice(&self.chunks);
100        Ok(Self {
101            chunks,
102            byte_len: self.byte_len,
103        })
104    }
105
106    /// Truncate active byte length without reallocating.
107    #[inline]
108    pub fn truncate(&mut self, byte_len: usize) {
109        if byte_len < self.byte_len {
110            self.byte_len = byte_len;
111        }
112    }
113}
114
115impl fmt::Debug for AlignedSamples {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        write!(f, "AlignedSamples({} bytes, align=64)", self.byte_len)
118    }
119}
120
121/// Low-level storage allocation error.
122#[derive(Clone, Copy, Debug, PartialEq, Eq)]
123#[non_exhaustive]
124pub enum StorageError {
125    /// Allocator refused or byte length exceeded `isize::MAX`.
126    AllocationFailed,
127}
128
129impl fmt::Display for StorageError {
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        match self {
132            Self::AllocationFailed => f.write_str("pixel storage allocation failed"),
133        }
134    }
135}
136
137impl core::error::Error for StorageError {}
138
139/// Read access to native-endian pixel bytes without copying.
140pub trait ByteStorage {
141    /// Underlying bytes in native endianness.
142    fn as_bytes(&self) -> &[u8];
143}
144
145/// Mutable access to native-endian pixel bytes without copying.
146pub trait ByteStorageMut: ByteStorage {
147    /// Mutable underlying bytes in native endianness.
148    fn as_bytes_mut(&mut self) -> &mut [u8];
149}
150
151impl ByteStorage for AlignedSamples {
152    #[inline]
153    fn as_bytes(&self) -> &[u8] {
154        self.as_bytes()
155    }
156}
157
158impl ByteStorageMut for AlignedSamples {
159    #[inline]
160    fn as_bytes_mut(&mut self) -> &mut [u8] {
161        self.as_bytes_mut()
162    }
163}
164
165impl<T: bytemuck::Pod> ByteStorage for Vec<T> {
166    #[inline]
167    fn as_bytes(&self) -> &[u8] {
168        bytemuck::cast_slice(self)
169    }
170}
171
172impl<T: bytemuck::Pod> ByteStorageMut for Vec<T> {
173    #[inline]
174    fn as_bytes_mut(&mut self) -> &mut [u8] {
175        bytemuck::cast_slice_mut(self)
176    }
177}
178
179impl<T: bytemuck::Pod> ByteStorage for Box<[T]> {
180    #[inline]
181    fn as_bytes(&self) -> &[u8] {
182        bytemuck::cast_slice(self)
183    }
184}
185
186impl<T: bytemuck::Pod> ByteStorageMut for Box<[T]> {
187    #[inline]
188    fn as_bytes_mut(&mut self) -> &mut [u8] {
189        bytemuck::cast_slice_mut(self)
190    }
191}
192
193impl<T: bytemuck::Pod> ByteStorage for Arc<[T]> {
194    #[inline]
195    fn as_bytes(&self) -> &[u8] {
196        bytemuck::cast_slice(self)
197    }
198}
199
200impl<T: bytemuck::Pod> ByteStorage for Arc<Vec<T>> {
201    #[inline]
202    fn as_bytes(&self) -> &[u8] {
203        bytemuck::cast_slice(self)
204    }
205}
206
207impl<T: bytemuck::Pod> ByteStorage for &[T] {
208    #[inline]
209    fn as_bytes(&self) -> &[u8] {
210        bytemuck::cast_slice(self)
211    }
212}
213
214impl<T: bytemuck::Pod> ByteStorage for &mut [T] {
215    #[inline]
216    fn as_bytes(&self) -> &[u8] {
217        bytemuck::cast_slice(self)
218    }
219}
220
221impl<T: bytemuck::Pod> ByteStorageMut for &mut [T] {
222    #[inline]
223    fn as_bytes_mut(&mut self) -> &mut [u8] {
224        bytemuck::cast_slice_mut(self)
225    }
226}
227
228trait ExternalReadObj: ByteStorage + Any + Send + Sync {
229    fn as_any(&self) -> &(dyn Any + Send + Sync);
230    fn into_any(self: Box<Self>) -> Box<dyn Any + Send + Sync>;
231}
232
233impl<S: ByteStorage + Send + Sync + 'static> ExternalReadObj for S {
234    #[inline]
235    fn as_any(&self) -> &(dyn Any + Send + Sync) {
236        self
237    }
238
239    #[inline]
240    fn into_any(self: Box<Self>) -> Box<dyn Any + Send + Sync> {
241        self
242    }
243}
244
245trait ExternalMutObj: ByteStorageMut + Any + Send + Sync {
246    fn as_any(&self) -> &(dyn Any + Send + Sync);
247    fn as_any_mut(&mut self) -> &mut (dyn Any + Send + Sync);
248    fn into_any(self: Box<Self>) -> Box<dyn Any + Send + Sync>;
249}
250
251impl<S: ByteStorageMut + Send + Sync + 'static> ExternalMutObj for S {
252    #[inline]
253    fn as_any(&self) -> &(dyn Any + Send + Sync) {
254        self
255    }
256
257    #[inline]
258    fn as_any_mut(&mut self) -> &mut (dyn Any + Send + Sync) {
259        self
260    }
261
262    #[inline]
263    fn into_any(self: Box<Self>) -> Box<dyn Any + Send + Sync> {
264        self
265    }
266}
267
268/// Type-erased immutable external owned backing storage (`Arc<[T]>`, `&'static [T]`,
269/// memory-mapped files, shared buffer pools, FFI read-only buffers).
270///
271/// Read access is strictly zero-copy. Requesting mutable access through [`PixelStorage`]
272/// or [`PixelBuf`](crate::PixelBuf) performs copy-on-write promotion into 64-byte aligned
273/// owned storage; calling [`into_inner`](Self::into_inner) recovers the original
274/// owner `S` zero-copy without touching its backing allocation.
275pub struct ExternalStorage {
276    inner: Box<dyn ExternalReadObj>,
277    byte_len: usize,
278}
279
280impl ExternalStorage {
281    /// Wrap any `S: ByteStorage + Send + Sync + 'static` zero-copy.
282    #[inline]
283    #[must_use]
284    pub fn new<S: ByteStorage + Send + Sync + 'static>(owner: S) -> Self {
285        let byte_len = owner.as_bytes().len();
286        Self {
287            inner: Box::new(owner),
288            byte_len,
289        }
290    }
291
292    /// Active immutable byte view (bounded by any prior [`truncate`](Self::truncate)).
293    #[inline]
294    #[must_use]
295    pub fn as_bytes(&self) -> &[u8] {
296        let raw = self.inner.as_bytes();
297        &raw[..self.byte_len.min(raw.len())]
298    }
299
300    /// Active byte length.
301    #[inline]
302    #[must_use]
303    pub const fn len(&self) -> usize {
304        self.byte_len
305    }
306
307    /// Whether the active byte view is empty.
308    #[inline]
309    #[must_use]
310    pub const fn is_empty(&self) -> bool {
311        self.byte_len == 0
312    }
313
314    /// Narrow active byte length without touching or copying the external owner.
315    #[inline]
316    pub fn truncate(&mut self, byte_len: usize) {
317        if byte_len < self.byte_len {
318            self.byte_len = byte_len;
319        }
320    }
321
322    /// Borrow the original external owner if its concrete type is `S`.
323    #[inline]
324    #[must_use]
325    pub fn downcast_ref<S: 'static>(&self) -> Option<&S> {
326        self.inner.as_any().downcast_ref::<S>()
327    }
328
329    /// Recover the original external owner `S` zero-copy; returns `Err(self)` untouched if
330    /// the stored type is not `S`.
331    pub fn into_inner<S: 'static>(self) -> Result<S, Self> {
332        if self.inner.as_any().is::<S>() {
333            match self.inner.into_any().downcast::<S>() {
334                Ok(boxed) => Ok(*boxed),
335                Err(_) => unreachable!("checked TypeId match before downcast"),
336            }
337        } else {
338            Err(self)
339        }
340    }
341}
342
343impl ByteStorage for ExternalStorage {
344    #[inline]
345    fn as_bytes(&self) -> &[u8] {
346        self.as_bytes()
347    }
348}
349
350impl fmt::Debug for ExternalStorage {
351    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352        write!(f, "ExternalStorage({} bytes, read-only)", self.byte_len)
353    }
354}
355
356/// Type-erased mutable external owned backing storage (`Box<[T]>`, custom-allocator
357/// wrappers, mutable pool leases, FFI writable buffers).
358///
359/// Both read and in-place write access are strictly zero-copy; calling
360/// [`into_inner`](Self::into_inner) recovers the original owner `S` zero-copy.
361pub struct ExternalMutStorage {
362    inner: Box<dyn ExternalMutObj>,
363    byte_len: usize,
364}
365
366impl ExternalMutStorage {
367    /// Wrap any `S: ByteStorageMut + Send + Sync + 'static` zero-copy.
368    #[inline]
369    #[must_use]
370    pub fn new<S: ByteStorageMut + Send + Sync + 'static>(owner: S) -> Self {
371        let byte_len = owner.as_bytes().len();
372        Self {
373            inner: Box::new(owner),
374            byte_len,
375        }
376    }
377
378    /// Active immutable byte view.
379    #[inline]
380    #[must_use]
381    pub fn as_bytes(&self) -> &[u8] {
382        let raw = self.inner.as_bytes();
383        &raw[..self.byte_len.min(raw.len())]
384    }
385
386    /// Active mutable byte view (zero-copy in place).
387    #[inline]
388    #[must_use]
389    pub fn as_bytes_mut(&mut self) -> &mut [u8] {
390        let raw = self.inner.as_bytes_mut();
391        let cap = self.byte_len.min(raw.len());
392        &mut raw[..cap]
393    }
394
395    /// Active byte length.
396    #[inline]
397    #[must_use]
398    pub const fn len(&self) -> usize {
399        self.byte_len
400    }
401
402    /// Whether the active byte view is empty.
403    #[inline]
404    #[must_use]
405    pub const fn is_empty(&self) -> bool {
406        self.byte_len == 0
407    }
408
409    /// Narrow active byte length without touching or copying the external owner.
410    #[inline]
411    pub fn truncate(&mut self, byte_len: usize) {
412        if byte_len < self.byte_len {
413            self.byte_len = byte_len;
414        }
415    }
416
417    /// Borrow the original external owner if its concrete type is `S`.
418    #[inline]
419    #[must_use]
420    pub fn downcast_ref<S: 'static>(&self) -> Option<&S> {
421        self.inner.as_any().downcast_ref::<S>()
422    }
423
424    /// Mutably borrow the original external owner if its concrete type is `S`.
425    #[inline]
426    #[must_use]
427    pub fn downcast_mut<S: 'static>(&mut self) -> Option<&mut S> {
428        self.inner.as_any_mut().downcast_mut::<S>()
429    }
430
431    /// Recover the original external owner `S` zero-copy; returns `Err(self)` untouched if
432    /// the stored type is not `S`.
433    pub fn into_inner<S: 'static>(self) -> Result<S, Self> {
434        if self.inner.as_any().is::<S>() {
435            match self.inner.into_any().downcast::<S>() {
436                Ok(boxed) => Ok(*boxed),
437                Err(_) => unreachable!("checked TypeId match before downcast"),
438            }
439        } else {
440            Err(self)
441        }
442    }
443}
444
445impl ByteStorage for ExternalMutStorage {
446    #[inline]
447    fn as_bytes(&self) -> &[u8] {
448        self.as_bytes()
449    }
450}
451
452impl ByteStorageMut for ExternalMutStorage {
453    #[inline]
454    fn as_bytes_mut(&mut self) -> &mut [u8] {
455        self.as_bytes_mut()
456    }
457}
458
459impl fmt::Debug for ExternalMutStorage {
460    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
461        write!(f, "ExternalMutStorage({} bytes, mutable)", self.byte_len)
462    }
463}
464
465mod sealed {
466    use super::*;
467    pub trait Sealed: Sized {
468        fn into_storage(v: Vec<Self>) -> PixelStorage;
469        fn from_storage(s: PixelStorage) -> Result<Vec<Self>, PixelStorage>;
470    }
471}
472
473/// Sealed trait implemented by the 11 native sample types stored in [`PixelStorage`].
474pub trait StorageSample:
475    sealed::Sealed + bytemuck::Pod + Default + PartialEq + fmt::Debug + Send + Sync + 'static
476{
477    /// Corresponding [`SampleType`] variant.
478    const SAMPLE_TYPE: SampleType;
479}
480
481/// Alignment-exact owned pixel backing storage.
482///
483/// Stores the true sample-typed `Vec<T>` (or 64-byte [`AlignedSamples`]) so
484/// `Vec<u16>`, `Vec<Rgb<u16>>`, `Vec<f32>`, `Vec<Rgba<f32>>`, etc. cross
485/// type-erased [`PixelBuf`](crate::PixelBuf) boundaries **zero-copy** while
486/// strictly preserving Rust's allocation/deallocation alignment contract.
487#[non_exhaustive]
488pub enum PixelStorage {
489    /// `u8` backing (`align = 1`).
490    U8(Vec<u8>),
491    /// `i8` backing (`align = 1`).
492    I8(Vec<i8>),
493    /// `u16` backing (`align = 2`).
494    U16(Vec<u16>),
495    /// `i16` backing (`align = 2`).
496    I16(Vec<i16>),
497    /// `F16Sample` backing (`align = 2`).
498    F16(Vec<F16Sample>),
499    /// `u32` backing (`align = 4`).
500    U32(Vec<u32>),
501    /// `i32` backing (`align = 4`).
502    I32(Vec<i32>),
503    /// `f32` backing (`align = 4`).
504    F32(Vec<f32>),
505    /// `u64` backing (`align = align_of::<u64>()`).
506    U64(Vec<u64>),
507    /// `i64` backing (`align = align_of::<i64>()`).
508    I64(Vec<i64>),
509    /// `f64` backing (`align = align_of::<f64>()`).
510    F64(Vec<f64>),
511    /// 64-byte SIMD-aligned backing (`align = 64`).
512    Aligned64(AlignedSamples),
513    /// Immutable external owned backing (`Arc<[T]>`, mmap, `&'static [T]`, shared pool).
514    ///
515    /// Read access is zero-copy; mutable access promotes via copy-on-write into `Aligned64`.
516    External(ExternalStorage),
517    /// Mutable external owned backing (`Box<[T]>`, custom allocator, pool lease, FFI buffer).
518    ///
519    /// Both read and write access are zero-copy in place.
520    ExternalMut(ExternalMutStorage),
521}
522
523macro_rules! impl_storage_samples {
524    ($($ty:ty => $var:ident),* $(,)?) => {$(
525        impl sealed::Sealed for $ty {
526            #[inline]
527            fn into_storage(v: Vec<Self>) -> PixelStorage {
528                PixelStorage::$var(v)
529            }
530            #[inline]
531            fn from_storage(s: PixelStorage) -> Result<Vec<Self>, PixelStorage> {
532                match s {
533                    PixelStorage::$var(v) => Ok(v),
534                    other => Err(other),
535                }
536            }
537        }
538        impl StorageSample for $ty {
539            const SAMPLE_TYPE: SampleType = SampleType::$var;
540        }
541        impl From<Vec<$ty>> for PixelStorage {
542            #[inline]
543            fn from(v: Vec<$ty>) -> Self {
544                PixelStorage::$var(v)
545            }
546        }
547    )*};
548}
549
550impl_storage_samples! {
551    u8 => U8, i8 => I8,
552    u16 => U16, i16 => I16, F16Sample => F16,
553    u32 => U32, i32 => I32, f32 => F32,
554    u64 => U64, i64 => I64, f64 => F64,
555}
556
557#[inline]
558fn cast_same_layout<A: bytemuck::NoUninit, B: bytemuck::AnyBitPattern>(v: Vec<A>) -> Vec<B> {
559    match bytemuck::allocation::try_cast_vec(v) {
560        Ok(out) => out,
561        Err(_) => panic!("same-size same-alignment Vec cast failed"),
562    }
563}
564
565fn zeroed_vec<T: bytemuck::Zeroable + bytemuck::Pod>(bytes: usize) -> Result<Vec<T>, StorageError> {
566    let sz = core::mem::size_of::<T>();
567    let count = bytes.div_ceil(sz);
568    core::alloc::Layout::array::<T>(count).map_err(|_| StorageError::AllocationFailed)?;
569    bytemuck::allocation::try_zeroed_vec(count).map_err(|()| StorageError::AllocationFailed)
570}
571
572fn gather_typed<T: bytemuck::Zeroable + bytemuck::Pod>(
573    total_bytes: usize,
574    rows: &mut dyn Iterator<Item = &[u8]>,
575) -> Result<Vec<T>, StorageError> {
576    if total_bytes > isize::MAX as usize {
577        return Err(StorageError::AllocationFailed);
578    }
579    let mut out = zeroed_vec::<T>(total_bytes)?;
580    let dst = bytemuck::cast_slice_mut::<T, u8>(&mut out);
581    let mut pos = 0usize;
582    for row in rows {
583        let end = pos
584            .checked_add(row.len())
585            .ok_or(StorageError::AllocationFailed)?;
586        if end > total_bytes || end > dst.len() {
587            return Err(StorageError::AllocationFailed);
588        }
589        dst[pos..end].copy_from_slice(row);
590        pos = end;
591    }
592    Ok(out)
593}
594
595impl PixelStorage {
596    /// Allocate zeroed storage with exact alignment for `sample`, holding at least `byte_len` bytes.
597    pub fn zeroed_bytes(sample: SampleType, byte_len: usize) -> Result<Self, StorageError> {
598        if byte_len > isize::MAX as usize {
599            return Err(StorageError::AllocationFailed);
600        }
601        match sample {
602            SampleType::U8 => Ok(Self::U8(zeroed_vec(byte_len)?)),
603            SampleType::I8 => Ok(Self::I8(cast_same_layout(zeroed_vec::<u8>(byte_len)?))),
604            SampleType::U16 => Ok(Self::U16(zeroed_vec(byte_len)?)),
605            SampleType::I16 => Ok(Self::I16(cast_same_layout(zeroed_vec::<u16>(byte_len)?))),
606            SampleType::F16 => Ok(Self::F16(cast_same_layout(zeroed_vec::<u16>(byte_len)?))),
607            SampleType::U32 => Ok(Self::U32(zeroed_vec(byte_len)?)),
608            SampleType::I32 => Ok(Self::I32(cast_same_layout(zeroed_vec::<u32>(byte_len)?))),
609            SampleType::F32 => Ok(Self::F32(cast_same_layout(zeroed_vec::<u32>(byte_len)?))),
610            SampleType::U64 => Ok(Self::U64(zeroed_vec(byte_len)?)),
611            SampleType::I64 => Ok(Self::I64(cast_same_layout(zeroed_vec::<u64>(byte_len)?))),
612            SampleType::F64 => {
613                if core::mem::align_of::<u64>() == core::mem::align_of::<f64>() {
614                    Ok(Self::F64(cast_same_layout(zeroed_vec::<u64>(byte_len)?)))
615                } else {
616                    Ok(Self::F64(zeroed_vec(byte_len)?))
617                }
618            }
619        }
620    }
621
622    /// Allocate 64-byte SIMD-aligned zeroed storage holding at least `byte_len` bytes.
623    #[inline]
624    pub fn zeroed_aligned64_bytes(byte_len: usize) -> Result<Self, StorageError> {
625        Ok(Self::Aligned64(AlignedSamples::zeroed_bytes(byte_len)?))
626    }
627
628    /// Wrap an immutable external owned buffer (`Arc<[T]>`, mmap, `&'static [T]`, etc.) zero-copy.
629    #[inline]
630    #[must_use]
631    pub fn from_external<S: ByteStorage + Send + Sync + 'static>(owner: S) -> Self {
632        Self::External(ExternalStorage::new(owner))
633    }
634
635    /// Wrap a mutable external owned buffer (`Box<[T]>`, custom allocator, pool lease, etc.) zero-copy.
636    #[inline]
637    #[must_use]
638    pub fn from_external_mut<S: ByteStorageMut + Send + Sync + 'static>(owner: S) -> Self {
639        Self::ExternalMut(ExternalMutStorage::new(owner))
640    }
641
642    /// Whether this storage is backed by an external owner (`External` or `ExternalMut`).
643    #[inline]
644    #[must_use]
645    pub const fn is_external(&self) -> bool {
646        matches!(self, Self::External(_) | Self::ExternalMut(_))
647    }
648
649    /// Whether mutable byte access operates in place without copy-on-write promotion.
650    #[inline]
651    #[must_use]
652    pub const fn is_mutable_in_place(&self) -> bool {
653        !matches!(self, Self::External(_))
654    }
655
656    /// Borrow the external owner if this storage holds an external owner of concrete type `S`.
657    #[inline]
658    #[must_use]
659    pub fn external_ref<S: 'static>(&self) -> Option<&S> {
660        match self {
661            Self::External(ext) => ext.downcast_ref::<S>(),
662            Self::ExternalMut(ext) => ext.downcast_ref::<S>(),
663            _ => None,
664        }
665    }
666
667    /// Mutably borrow the external owner if this storage is `ExternalMut` of concrete type `S`.
668    #[inline]
669    #[must_use]
670    pub fn external_mut<S: 'static>(&mut self) -> Option<&mut S> {
671        match self {
672            Self::ExternalMut(ext) => ext.downcast_mut::<S>(),
673            _ => None,
674        }
675    }
676
677    /// Recover an immutable external owner `S` zero-copy; returns `Err(self)` untouched otherwise.
678    pub fn into_external<S: 'static>(self) -> Result<S, Self> {
679        match self {
680            Self::External(ext) => ext.into_inner::<S>().map_err(Self::External),
681            other => Err(other),
682        }
683    }
684
685    /// Recover a mutable external owner `S` zero-copy; returns `Err(self)` untouched otherwise.
686    pub fn into_external_mut<S: 'static>(self) -> Result<S, Self> {
687        match self {
688            Self::ExternalMut(ext) => ext.into_inner::<S>().map_err(Self::ExternalMut),
689            other => Err(other),
690        }
691    }
692
693    /// Fallibly obtain mutable bytes, performing **copy-on-write** promotion into 64-byte aligned
694    /// owned storage if backed by immutable [`PixelStorage::External`].
695    ///
696    /// Never fails merely because storage is immutable `External`; returns
697    /// `Err(StorageError::AllocationFailed)` only on OOM during copy-on-write promotion.
698    /// Strictly zero-copy and infallible for native `Vec`, `Aligned64`, and `ExternalMut`.
699    #[doc(alias = "try_as_bytes_mut")]
700    #[doc(alias = "try_make_bytes_mut")]
701    #[doc(alias = "cow")]
702    pub fn try_cow_bytes_mut(&mut self) -> Result<&mut [u8], StorageError> {
703        if let Self::External(ext) = self {
704            let src = ext.as_bytes();
705            let mut aligned = AlignedSamples::zeroed_bytes(src.len())?;
706            aligned.as_bytes_mut().copy_from_slice(src);
707            *self = Self::Aligned64(aligned);
708        }
709        Ok(match self {
710            Self::U8(v) => v,
711            Self::I8(v) => bytemuck::cast_slice_mut(v),
712            Self::U16(v) => bytemuck::cast_slice_mut(v),
713            Self::I16(v) => bytemuck::cast_slice_mut(v),
714            Self::F16(v) => bytemuck::cast_slice_mut(v),
715            Self::U32(v) => bytemuck::cast_slice_mut(v),
716            Self::I32(v) => bytemuck::cast_slice_mut(v),
717            Self::F32(v) => bytemuck::cast_slice_mut(v),
718            Self::U64(v) => bytemuck::cast_slice_mut(v),
719            Self::I64(v) => bytemuck::cast_slice_mut(v),
720            Self::F64(v) => bytemuck::cast_slice_mut(v),
721            Self::Aligned64(a) => a.as_bytes_mut(),
722            Self::ExternalMut(ext) => ext.as_bytes_mut(),
723            Self::External(_) => unreachable!("promoted above"),
724        })
725    }
726
727    /// Gather row slices into fresh tightly packed storage of `sample`'s native alignment.
728    pub fn from_rows<'r>(
729        sample: SampleType,
730        total_bytes: usize,
731        mut rows: impl Iterator<Item = &'r [u8]>,
732    ) -> Result<Self, StorageError> {
733        Self::from_rows_dyn(sample, total_bytes, &mut rows)
734    }
735
736    fn from_rows_dyn(
737        sample: SampleType,
738        total_bytes: usize,
739        rows: &mut dyn Iterator<Item = &[u8]>,
740    ) -> Result<Self, StorageError> {
741        match sample {
742            SampleType::U8 => Ok(Self::U8(gather_typed(total_bytes, rows)?)),
743            SampleType::I8 => Ok(Self::I8(cast_same_layout(gather_typed::<u8>(
744                total_bytes,
745                rows,
746            )?))),
747            SampleType::U16 => Ok(Self::U16(gather_typed(total_bytes, rows)?)),
748            SampleType::I16 => Ok(Self::I16(cast_same_layout(gather_typed::<u16>(
749                total_bytes,
750                rows,
751            )?))),
752            SampleType::F16 => Ok(Self::F16(cast_same_layout(gather_typed::<u16>(
753                total_bytes,
754                rows,
755            )?))),
756            SampleType::U32 => Ok(Self::U32(gather_typed(total_bytes, rows)?)),
757            SampleType::I32 => Ok(Self::I32(cast_same_layout(gather_typed::<u32>(
758                total_bytes,
759                rows,
760            )?))),
761            SampleType::F32 => Ok(Self::F32(cast_same_layout(gather_typed::<u32>(
762                total_bytes,
763                rows,
764            )?))),
765            SampleType::U64 => Ok(Self::U64(gather_typed(total_bytes, rows)?)),
766            SampleType::I64 => Ok(Self::I64(cast_same_layout(gather_typed::<u64>(
767                total_bytes,
768                rows,
769            )?))),
770            SampleType::F64 => {
771                if core::mem::align_of::<u64>() == core::mem::align_of::<f64>() {
772                    Ok(Self::F64(cast_same_layout(gather_typed::<u64>(
773                        total_bytes,
774                        rows,
775                    )?)))
776                } else {
777                    Ok(Self::F64(gather_typed(total_bytes, rows)?))
778                }
779            }
780        }
781    }
782
783    /// Move a typed `Vec<P>` into native [`PixelStorage`] **zero-copy** when
784    /// `align_of::<P>()` and capacity match `sample`'s backing layout.
785    ///
786    /// On mismatch (e.g., an over-aligned pixel type), returns `Err(pixels)`
787    /// untouched without allocating.
788    pub fn adopt_vec<P: bytemuck::Pod>(pixels: Vec<P>, sample: SampleType) -> Result<Self, Vec<P>> {
789        use bytemuck::allocation::try_cast_vec;
790        match sample {
791            SampleType::U8 => try_cast_vec::<P, u8>(pixels)
792                .map(Self::U8)
793                .map_err(|(_, v)| v),
794            SampleType::I8 => try_cast_vec::<P, i8>(pixels)
795                .map(Self::I8)
796                .map_err(|(_, v)| v),
797            SampleType::U16 => try_cast_vec::<P, u16>(pixels)
798                .map(Self::U16)
799                .map_err(|(_, v)| v),
800            SampleType::I16 => try_cast_vec::<P, i16>(pixels)
801                .map(Self::I16)
802                .map_err(|(_, v)| v),
803            SampleType::F16 => try_cast_vec::<P, F16Sample>(pixels)
804                .map(Self::F16)
805                .map_err(|(_, v)| v),
806            SampleType::U32 => try_cast_vec::<P, u32>(pixels)
807                .map(Self::U32)
808                .map_err(|(_, v)| v),
809            SampleType::I32 => try_cast_vec::<P, i32>(pixels)
810                .map(Self::I32)
811                .map_err(|(_, v)| v),
812            SampleType::F32 => try_cast_vec::<P, f32>(pixels)
813                .map(Self::F32)
814                .map_err(|(_, v)| v),
815            SampleType::U64 => try_cast_vec::<P, u64>(pixels)
816                .map(Self::U64)
817                .map_err(|(_, v)| v),
818            SampleType::I64 => try_cast_vec::<P, i64>(pixels)
819                .map(Self::I64)
820                .map_err(|(_, v)| v),
821            SampleType::F64 => try_cast_vec::<P, f64>(pixels)
822                .map(Self::F64)
823                .map_err(|(_, v)| v),
824        }
825    }
826
827    /// Move this storage into `Vec<P>` **zero-copy** when `align_of::<P>()`
828    /// matches the backing allocation's exact alignment AND both active byte
829    /// length and byte capacity are exact multiples of `size_of::<P>()`.
830    ///
831    /// Returns `Err(self)` untouched otherwise (never UB, never copies).
832    pub fn cast_into_vec<P: bytemuck::Pod>(self) -> Result<Vec<P>, Self> {
833        use bytemuck::allocation::try_cast_vec;
834        match self {
835            Self::U8(v) => try_cast_vec(v).map_err(|(_, v)| Self::U8(v)),
836            Self::I8(v) => try_cast_vec(v).map_err(|(_, v)| Self::I8(v)),
837            Self::U16(v) => try_cast_vec(v).map_err(|(_, v)| Self::U16(v)),
838            Self::I16(v) => try_cast_vec(v).map_err(|(_, v)| Self::I16(v)),
839            Self::F16(v) => try_cast_vec(v).map_err(|(_, v)| Self::F16(v)),
840            Self::U32(v) => try_cast_vec(v).map_err(|(_, v)| Self::U32(v)),
841            Self::I32(v) => try_cast_vec(v).map_err(|(_, v)| Self::I32(v)),
842            Self::F32(v) => try_cast_vec(v).map_err(|(_, v)| Self::F32(v)),
843            Self::U64(v) => try_cast_vec(v).map_err(|(_, v)| Self::U64(v)),
844            Self::I64(v) => try_cast_vec(v).map_err(|(_, v)| Self::I64(v)),
845            Self::F64(v) => try_cast_vec(v).map_err(|(_, v)| Self::F64(v)),
846            // Aligned64 has deallocation alignment 64; external storage owns an opaque type.
847            Self::Aligned64(a) => Err(Self::Aligned64(a)),
848            Self::External(e) => Err(Self::External(e)),
849            Self::ExternalMut(e) => Err(Self::ExternalMut(e)),
850        }
851    }
852
853    /// Extract the exact sample-typed `Vec<T>` zero-copy when the variant matches.
854    #[inline]
855    pub fn into_sample_vec<T: StorageSample>(self) -> Result<Vec<T>, Self> {
856        T::from_storage(self)
857    }
858
859    /// Element alignment of the underlying heap allocation.
860    #[inline]
861    #[must_use]
862    pub const fn allocation_alignment(&self) -> usize {
863        match self {
864            Self::U8(_) | Self::I8(_) => core::mem::align_of::<u8>(),
865            Self::U16(_) | Self::I16(_) | Self::F16(_) => core::mem::align_of::<u16>(),
866            Self::U32(_) | Self::I32(_) => core::mem::align_of::<u32>(),
867            Self::F32(_) => core::mem::align_of::<f32>(),
868            Self::U64(_) | Self::I64(_) => core::mem::align_of::<u64>(),
869            Self::F64(_) => core::mem::align_of::<f64>(),
870            Self::Aligned64(_) => 64,
871            Self::External(_) | Self::ExternalMut(_) => 1,
872        }
873    }
874
875    /// Byte capacity of the underlying allocation.
876    #[inline]
877    #[must_use]
878    pub fn byte_capacity(&self) -> usize {
879        match self {
880            Self::U8(v) => v.capacity(),
881            Self::I8(v) => v.capacity(),
882            Self::U16(v) => v.capacity() * 2,
883            Self::I16(v) => v.capacity() * 2,
884            Self::F16(v) => v.capacity() * 2,
885            Self::U32(v) => v.capacity() * 4,
886            Self::I32(v) => v.capacity() * 4,
887            Self::F32(v) => v.capacity() * 4,
888            Self::U64(v) => v.capacity() * 8,
889            Self::I64(v) => v.capacity() * 8,
890            Self::F64(v) => v.capacity() * 8,
891            Self::Aligned64(a) => a.byte_len,
892            Self::External(e) => e.len(),
893            Self::ExternalMut(e) => e.len(),
894        }
895    }
896
897    /// Whether truncating to `target_bytes` and calling `cast_into_vec::<P>`
898    /// will succeed zero-copy without violating deallocation alignment or capacity.
899    #[inline]
900    #[must_use]
901    pub fn can_cast_into_vec<P: bytemuck::Pod>(&self, target_bytes: usize) -> bool {
902        let p_size = core::mem::size_of::<P>();
903        let p_align = core::mem::align_of::<P>();
904        if p_size == 0
905            || matches!(
906                self,
907                Self::Aligned64(_) | Self::External(_) | Self::ExternalMut(_)
908            )
909            || self.allocation_alignment() != p_align
910            || target_bytes > self.byte_len()
911            || target_bytes % p_size != 0
912            || self.byte_capacity() % p_size != 0
913        {
914            return false;
915        }
916        // `truncate_bytes` rounds up to sample unit boundaries, so `target_bytes` must be sample-aligned.
917        let unit = match self {
918            Self::U8(_) | Self::I8(_) => 1,
919            Self::U16(_) | Self::I16(_) | Self::F16(_) => 2,
920            Self::U32(_) | Self::I32(_) | Self::F32(_) => 4,
921            Self::U64(_) | Self::I64(_) | Self::F64(_) => 8,
922            Self::Aligned64(_) | Self::External(_) | Self::ExternalMut(_) => 64,
923        };
924        target_bytes % unit == 0
925    }
926
927    /// Byte length of the stored allocation.
928    #[inline]
929    #[must_use]
930    pub fn byte_len(&self) -> usize {
931        self.as_bytes().len()
932    }
933
934    /// Fallibly clone the underlying storage without panicking on OOM.
935    ///
936    /// External storage variants clone their active bytes into 64-byte aligned owned storage.
937    pub fn try_clone(&self) -> Result<Self, StorageError> {
938        fn try_clone_vec<T: Copy>(v: &[T]) -> Result<Vec<T>, StorageError> {
939            let mut out = Vec::new();
940            out.try_reserve_exact(v.len())
941                .map_err(|_| StorageError::AllocationFailed)?;
942            out.extend_from_slice(v);
943            Ok(out)
944        }
945        match self {
946            Self::U8(v) => Ok(Self::U8(try_clone_vec(v)?)),
947            Self::I8(v) => Ok(Self::I8(try_clone_vec(v)?)),
948            Self::U16(v) => Ok(Self::U16(try_clone_vec(v)?)),
949            Self::I16(v) => Ok(Self::I16(try_clone_vec(v)?)),
950            Self::F16(v) => Ok(Self::F16(try_clone_vec(v)?)),
951            Self::U32(v) => Ok(Self::U32(try_clone_vec(v)?)),
952            Self::I32(v) => Ok(Self::I32(try_clone_vec(v)?)),
953            Self::F32(v) => Ok(Self::F32(try_clone_vec(v)?)),
954            Self::U64(v) => Ok(Self::U64(try_clone_vec(v)?)),
955            Self::I64(v) => Ok(Self::I64(try_clone_vec(v)?)),
956            Self::F64(v) => Ok(Self::F64(try_clone_vec(v)?)),
957            Self::Aligned64(a) => Ok(Self::Aligned64(a.try_clone()?)),
958            Self::External(e) => {
959                let src = e.as_bytes();
960                let mut aligned = AlignedSamples::zeroed_bytes(src.len())?;
961                aligned.as_bytes_mut().copy_from_slice(src);
962                Ok(Self::Aligned64(aligned))
963            }
964            Self::ExternalMut(e) => {
965                let src = e.as_bytes();
966                let mut aligned = AlignedSamples::zeroed_bytes(src.len())?;
967                aligned.as_bytes_mut().copy_from_slice(src);
968                Ok(Self::Aligned64(aligned))
969            }
970        }
971    }
972
973    /// Truncate active byte count in place (rounded up to whole sample units).
974    pub fn truncate_bytes(&mut self, bytes: usize) {
975        match self {
976            Self::U8(v) => v.truncate(bytes),
977            Self::I8(v) => v.truncate(bytes),
978            Self::U16(v) => v.truncate(bytes.div_ceil(2)),
979            Self::I16(v) => v.truncate(bytes.div_ceil(2)),
980            Self::F16(v) => v.truncate(bytes.div_ceil(2)),
981            Self::U32(v) => v.truncate(bytes.div_ceil(4)),
982            Self::I32(v) => v.truncate(bytes.div_ceil(4)),
983            Self::F32(v) => v.truncate(bytes.div_ceil(4)),
984            Self::U64(v) => v.truncate(bytes.div_ceil(8)),
985            Self::I64(v) => v.truncate(bytes.div_ceil(8)),
986            Self::F64(v) => v.truncate(bytes.div_ceil(8)),
987            Self::Aligned64(a) => a.truncate(bytes),
988            Self::External(e) => e.truncate(bytes),
989            Self::ExternalMut(e) => e.truncate(bytes),
990        }
991    }
992}
993
994impl Clone for PixelStorage {
995    fn clone(&self) -> Self {
996        match self {
997            Self::U8(v) => Self::U8(v.clone()),
998            Self::I8(v) => Self::I8(v.clone()),
999            Self::U16(v) => Self::U16(v.clone()),
1000            Self::I16(v) => Self::I16(v.clone()),
1001            Self::F16(v) => Self::F16(v.clone()),
1002            Self::U32(v) => Self::U32(v.clone()),
1003            Self::I32(v) => Self::I32(v.clone()),
1004            Self::F32(v) => Self::F32(v.clone()),
1005            Self::U64(v) => Self::U64(v.clone()),
1006            Self::I64(v) => Self::I64(v.clone()),
1007            Self::F64(v) => Self::F64(v.clone()),
1008            Self::Aligned64(a) => Self::Aligned64(a.clone()),
1009            Self::External(_) | Self::ExternalMut(_) => self
1010                .try_clone()
1011                .expect("cloning external PixelStorage failed"),
1012        }
1013    }
1014}
1015
1016impl ByteStorage for PixelStorage {
1017    #[inline]
1018    fn as_bytes(&self) -> &[u8] {
1019        match self {
1020            Self::U8(v) => v,
1021            Self::I8(v) => bytemuck::cast_slice(v),
1022            Self::U16(v) => bytemuck::cast_slice(v),
1023            Self::I16(v) => bytemuck::cast_slice(v),
1024            Self::F16(v) => bytemuck::cast_slice(v),
1025            Self::U32(v) => bytemuck::cast_slice(v),
1026            Self::I32(v) => bytemuck::cast_slice(v),
1027            Self::F32(v) => bytemuck::cast_slice(v),
1028            Self::U64(v) => bytemuck::cast_slice(v),
1029            Self::I64(v) => bytemuck::cast_slice(v),
1030            Self::F64(v) => bytemuck::cast_slice(v),
1031            Self::Aligned64(a) => a.as_bytes(),
1032            Self::External(e) => e.as_bytes(),
1033            Self::ExternalMut(e) => e.as_bytes(),
1034        }
1035    }
1036}
1037
1038impl ByteStorageMut for PixelStorage {
1039    #[inline]
1040    fn as_bytes_mut(&mut self) -> &mut [u8] {
1041        self.try_cow_bytes_mut()
1042            .expect("copy-on-write promotion of external PixelStorage failed")
1043    }
1044}
1045
1046impl fmt::Debug for PixelStorage {
1047    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1048        match self {
1049            Self::External(e) => e.fmt(f),
1050            Self::ExternalMut(e) => e.fmt(f),
1051            _ => write!(
1052                f,
1053                "PixelStorage({} bytes, align={})",
1054                self.byte_len(),
1055                self.allocation_alignment()
1056            ),
1057        }
1058    }
1059}