Skip to main content

edgefirst_tensor/
tensor_dyn.rs

1// SPDX-FileCopyrightText: Copyright 2025 Au-Zone Technologies
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::{DType, PixelFormat, Tensor, TensorMemory, TensorTrait};
5use half::f16;
6use std::fmt;
7
8/// Type-erased tensor. Wraps a `Tensor<T>` with runtime element type.
9#[non_exhaustive]
10pub enum TensorDyn {
11    /// Unsigned 8-bit integer tensor.
12    U8(Tensor<u8>),
13    /// Signed 8-bit integer tensor.
14    I8(Tensor<i8>),
15    /// Unsigned 16-bit integer tensor.
16    U16(Tensor<u16>),
17    /// Signed 16-bit integer tensor.
18    I16(Tensor<i16>),
19    /// Unsigned 32-bit integer tensor.
20    U32(Tensor<u32>),
21    /// Signed 32-bit integer tensor.
22    I32(Tensor<i32>),
23    /// Unsigned 64-bit integer tensor.
24    U64(Tensor<u64>),
25    /// Signed 64-bit integer tensor.
26    I64(Tensor<i64>),
27    /// 16-bit floating-point tensor.
28    F16(Tensor<f16>),
29    /// 32-bit floating-point tensor.
30    F32(Tensor<f32>),
31    /// 64-bit floating-point tensor.
32    F64(Tensor<f64>),
33}
34
35/// Dispatch a method call across all TensorDyn variants.
36macro_rules! dispatch {
37    ($self:expr, $method:ident $(, $arg:expr)*) => {
38        match $self {
39            TensorDyn::U8(t) => t.$method($($arg),*),
40            TensorDyn::I8(t) => t.$method($($arg),*),
41            TensorDyn::U16(t) => t.$method($($arg),*),
42            TensorDyn::I16(t) => t.$method($($arg),*),
43            TensorDyn::U32(t) => t.$method($($arg),*),
44            TensorDyn::I32(t) => t.$method($($arg),*),
45            TensorDyn::U64(t) => t.$method($($arg),*),
46            TensorDyn::I64(t) => t.$method($($arg),*),
47            TensorDyn::F16(t) => t.$method($($arg),*),
48            TensorDyn::F32(t) => t.$method($($arg),*),
49            TensorDyn::F64(t) => t.$method($($arg),*),
50        }
51    };
52}
53
54/// Generate the three downcast methods (ref, mut ref, owned) for one variant.
55macro_rules! downcast_methods {
56    ($variant:ident, $ty:ty, $as_name:ident, $as_mut_name:ident, $into_name:ident) => {
57        /// Returns a shared reference to the inner tensor if the type matches.
58        pub fn $as_name(&self) -> Option<&Tensor<$ty>> {
59            match self {
60                Self::$variant(t) => Some(t),
61                _ => None,
62            }
63        }
64
65        /// Returns a mutable reference to the inner tensor if the type matches.
66        pub fn $as_mut_name(&mut self) -> Option<&mut Tensor<$ty>> {
67            match self {
68                Self::$variant(t) => Some(t),
69                _ => None,
70            }
71        }
72
73        /// Unwraps the inner tensor if the type matches, otherwise returns `self` as `Err`.
74        /// The Err variant is necessarily large (returns the unconsumed TensorDyn).
75        #[allow(clippy::result_large_err)]
76        pub fn $into_name(self) -> Result<Tensor<$ty>, Self> {
77            match self {
78                Self::$variant(t) => Ok(t),
79                other => Err(other),
80            }
81        }
82    };
83}
84
85impl TensorDyn {
86    /// Return the runtime element type discriminant.
87    pub fn dtype(&self) -> DType {
88        match self {
89            Self::U8(_) => DType::U8,
90            Self::I8(_) => DType::I8,
91            Self::U16(_) => DType::U16,
92            Self::I16(_) => DType::I16,
93            Self::U32(_) => DType::U32,
94            Self::I32(_) => DType::I32,
95            Self::U64(_) => DType::U64,
96            Self::I64(_) => DType::I64,
97            Self::F16(_) => DType::F16,
98            Self::F32(_) => DType::F32,
99            Self::F64(_) => DType::F64,
100        }
101    }
102
103    /// Return the tensor shape.
104    pub fn shape(&self) -> &[usize] {
105        dispatch!(self, shape)
106    }
107
108    /// Return the tensor name.
109    pub fn name(&self) -> String {
110        dispatch!(self, name)
111    }
112
113    /// Return the pixel format (None if not an image tensor).
114    pub fn format(&self) -> Option<PixelFormat> {
115        dispatch!(self, format)
116    }
117
118    /// Return the image width (None if not an image tensor).
119    pub fn width(&self) -> Option<usize> {
120        dispatch!(self, width)
121    }
122
123    /// Return the image height (None if not an image tensor).
124    pub fn height(&self) -> Option<usize> {
125        dispatch!(self, height)
126    }
127
128    /// Return the total size of this tensor in bytes.
129    pub fn size(&self) -> usize {
130        dispatch!(self, size)
131    }
132
133    /// Return the memory allocation type.
134    pub fn memory(&self) -> TensorMemory {
135        dispatch!(self, memory)
136    }
137
138    /// Reshape this tensor. Total element count must remain the same.
139    pub fn reshape(&mut self, shape: &[usize]) -> crate::Result<()> {
140        dispatch!(self, reshape, shape)
141    }
142
143    /// Attach pixel format metadata to this tensor.
144    ///
145    /// Validates that the tensor's shape is compatible with the format's
146    /// layout (packed, planar, or semi-planar).
147    ///
148    /// # Arguments
149    ///
150    /// * `format` - The pixel format to attach
151    ///
152    /// # Returns
153    ///
154    /// `Ok(())` on success, with the format stored as metadata on the tensor.
155    ///
156    /// # Errors
157    ///
158    /// Returns `Error::InvalidShape` if the tensor shape doesn't match
159    /// the expected layout for the given format.
160    pub fn set_format(&mut self, format: PixelFormat) -> crate::Result<()> {
161        dispatch!(self, set_format, format)
162    }
163
164    /// Attach pixel format metadata, consuming and returning self.
165    ///
166    /// Enables builder-style chaining.
167    ///
168    /// # Arguments
169    ///
170    /// * `format` - The pixel format to attach
171    ///
172    /// # Returns
173    ///
174    /// The tensor with format metadata attached.
175    ///
176    /// # Errors
177    ///
178    /// Returns `Error::InvalidShape` if the tensor shape doesn't match
179    /// the expected layout for the given format.
180    pub fn with_format(mut self, format: PixelFormat) -> crate::Result<Self> {
181        self.set_format(format)?;
182        Ok(self)
183    }
184
185    /// Row stride in bytes (`None` = tightly packed).
186    pub fn row_stride(&self) -> Option<usize> {
187        dispatch!(self, row_stride)
188    }
189
190    /// Effective row stride: stored stride or computed from format and width.
191    pub fn effective_row_stride(&self) -> Option<usize> {
192        dispatch!(self, effective_row_stride)
193    }
194
195    /// Set the row stride in bytes for externally allocated buffers with
196    /// row padding.
197    ///
198    /// Must be called before the tensor is first used for rendering. The
199    /// format must be set before calling this method.
200    pub fn set_row_stride(&mut self, stride: usize) -> crate::Result<()> {
201        dispatch!(self, set_row_stride, stride)
202    }
203
204    /// Builder-style: set row stride, consuming and returning self.
205    pub fn with_row_stride(mut self, stride: usize) -> crate::Result<Self> {
206        self.set_row_stride(stride)?;
207        Ok(self)
208    }
209
210    /// Byte offset within the DMA-BUF where image data starts (`None` = 0).
211    pub fn plane_offset(&self) -> Option<usize> {
212        dispatch!(self, plane_offset)
213    }
214
215    /// Set the byte offset within the DMA-BUF where image data starts.
216    pub fn set_plane_offset(&mut self, offset: usize) {
217        dispatch!(self, set_plane_offset, offset)
218    }
219
220    /// Builder-style: set plane offset, consuming and returning self.
221    pub fn with_plane_offset(mut self, offset: usize) -> Self {
222        self.set_plane_offset(offset);
223        self
224    }
225
226    /// Clone the file descriptor associated with this tensor.
227    #[cfg(unix)]
228    pub fn clone_fd(&self) -> crate::Result<std::os::fd::OwnedFd> {
229        dispatch!(self, clone_fd)
230    }
231
232    /// Clone the DMA-BUF file descriptor backing this tensor (Linux only).
233    ///
234    /// # Returns
235    ///
236    /// An owned duplicate of the DMA-BUF file descriptor.
237    ///
238    /// # Errors
239    ///
240    /// * `Error::NotImplemented` if the tensor is not DMA-backed (Mem/Shm/Pbo)
241    /// * `Error::IoError` if the fd clone syscall fails (e.g., fd limit reached)
242    #[cfg(target_os = "linux")]
243    pub fn dmabuf_clone(&self) -> crate::Result<std::os::fd::OwnedFd> {
244        if self.memory() != TensorMemory::Dma {
245            return Err(crate::Error::NotImplemented(format!(
246                "dmabuf_clone requires DMA-backed tensor, got {:?}",
247                self.memory()
248            )));
249        }
250        self.clone_fd()
251    }
252
253    /// Borrow the DMA-BUF file descriptor backing this tensor (Linux only).
254    ///
255    /// # Returns
256    ///
257    /// A borrowed reference to the DMA-BUF file descriptor, tied to `self`'s
258    /// lifetime.
259    ///
260    /// # Errors
261    ///
262    /// * `Error::NotImplemented` if the tensor is not DMA-backed
263    #[cfg(target_os = "linux")]
264    pub fn dmabuf(&self) -> crate::Result<std::os::fd::BorrowedFd<'_>> {
265        dispatch!(self, dmabuf)
266    }
267
268    /// Return `true` if this tensor uses separate plane allocations.
269    pub fn is_multiplane(&self) -> bool {
270        dispatch!(self, is_multiplane)
271    }
272
273    // --- Downcasting ---
274
275    downcast_methods!(U8, u8, as_u8, as_u8_mut, into_u8);
276    downcast_methods!(I8, i8, as_i8, as_i8_mut, into_i8);
277    downcast_methods!(U16, u16, as_u16, as_u16_mut, into_u16);
278    downcast_methods!(I16, i16, as_i16, as_i16_mut, into_i16);
279    downcast_methods!(U32, u32, as_u32, as_u32_mut, into_u32);
280    downcast_methods!(I32, i32, as_i32, as_i32_mut, into_i32);
281    downcast_methods!(U64, u64, as_u64, as_u64_mut, into_u64);
282    downcast_methods!(I64, i64, as_i64, as_i64_mut, into_i64);
283    downcast_methods!(F16, f16, as_f16, as_f16_mut, into_f16);
284    downcast_methods!(F32, f32, as_f32, as_f32_mut, into_f32);
285    downcast_methods!(F64, f64, as_f64, as_f64_mut, into_f64);
286
287    /// Create a type-erased tensor with the given shape and element type.
288    pub fn new(
289        shape: &[usize],
290        dtype: DType,
291        memory: Option<TensorMemory>,
292        name: Option<&str>,
293    ) -> crate::Result<Self> {
294        match dtype {
295            DType::U8 => Tensor::<u8>::new(shape, memory, name).map(Self::U8),
296            DType::I8 => Tensor::<i8>::new(shape, memory, name).map(Self::I8),
297            DType::U16 => Tensor::<u16>::new(shape, memory, name).map(Self::U16),
298            DType::I16 => Tensor::<i16>::new(shape, memory, name).map(Self::I16),
299            DType::U32 => Tensor::<u32>::new(shape, memory, name).map(Self::U32),
300            DType::I32 => Tensor::<i32>::new(shape, memory, name).map(Self::I32),
301            DType::U64 => Tensor::<u64>::new(shape, memory, name).map(Self::U64),
302            DType::I64 => Tensor::<i64>::new(shape, memory, name).map(Self::I64),
303            DType::F16 => Tensor::<f16>::new(shape, memory, name).map(Self::F16),
304            DType::F32 => Tensor::<f32>::new(shape, memory, name).map(Self::F32),
305            DType::F64 => Tensor::<f64>::new(shape, memory, name).map(Self::F64),
306        }
307    }
308
309    /// Create a type-erased tensor from a file descriptor.
310    #[cfg(unix)]
311    pub fn from_fd(
312        fd: std::os::fd::OwnedFd,
313        shape: &[usize],
314        dtype: DType,
315        name: Option<&str>,
316    ) -> crate::Result<Self> {
317        match dtype {
318            DType::U8 => Tensor::<u8>::from_fd(fd, shape, name).map(Self::U8),
319            DType::I8 => Tensor::<i8>::from_fd(fd, shape, name).map(Self::I8),
320            DType::U16 => Tensor::<u16>::from_fd(fd, shape, name).map(Self::U16),
321            DType::I16 => Tensor::<i16>::from_fd(fd, shape, name).map(Self::I16),
322            DType::U32 => Tensor::<u32>::from_fd(fd, shape, name).map(Self::U32),
323            DType::I32 => Tensor::<i32>::from_fd(fd, shape, name).map(Self::I32),
324            DType::U64 => Tensor::<u64>::from_fd(fd, shape, name).map(Self::U64),
325            DType::I64 => Tensor::<i64>::from_fd(fd, shape, name).map(Self::I64),
326            DType::F16 => Tensor::<f16>::from_fd(fd, shape, name).map(Self::F16),
327            DType::F32 => Tensor::<f32>::from_fd(fd, shape, name).map(Self::F32),
328            DType::F64 => Tensor::<f64>::from_fd(fd, shape, name).map(Self::F64),
329        }
330    }
331
332    /// Create a type-erased image tensor.
333    ///
334    /// # Arguments
335    ///
336    /// * `width` - Image width in pixels
337    /// * `height` - Image height in pixels
338    /// * `format` - Pixel format
339    /// * `dtype` - Element type discriminant
340    /// * `memory` - Optional memory backend (None selects the best available)
341    ///
342    /// # Returns
343    ///
344    /// A new `TensorDyn` wrapping an image tensor of the requested element type.
345    ///
346    /// # Errors
347    ///
348    /// Returns an error if the underlying `Tensor::image` call fails.
349    pub fn image(
350        width: usize,
351        height: usize,
352        format: PixelFormat,
353        dtype: DType,
354        memory: Option<TensorMemory>,
355    ) -> crate::Result<Self> {
356        match dtype {
357            DType::U8 => Tensor::<u8>::image(width, height, format, memory).map(Self::U8),
358            DType::I8 => Tensor::<i8>::image(width, height, format, memory).map(Self::I8),
359            DType::U16 => Tensor::<u16>::image(width, height, format, memory).map(Self::U16),
360            DType::I16 => Tensor::<i16>::image(width, height, format, memory).map(Self::I16),
361            DType::U32 => Tensor::<u32>::image(width, height, format, memory).map(Self::U32),
362            DType::I32 => Tensor::<i32>::image(width, height, format, memory).map(Self::I32),
363            DType::U64 => Tensor::<u64>::image(width, height, format, memory).map(Self::U64),
364            DType::I64 => Tensor::<i64>::image(width, height, format, memory).map(Self::I64),
365            DType::F16 => Tensor::<f16>::image(width, height, format, memory).map(Self::F16),
366            DType::F32 => Tensor::<f32>::image(width, height, format, memory).map(Self::F32),
367            DType::F64 => Tensor::<f64>::image(width, height, format, memory).map(Self::F64),
368        }
369    }
370}
371
372// --- From impls ---
373
374impl From<Tensor<u8>> for TensorDyn {
375    fn from(t: Tensor<u8>) -> Self {
376        Self::U8(t)
377    }
378}
379
380impl From<Tensor<i8>> for TensorDyn {
381    fn from(t: Tensor<i8>) -> Self {
382        Self::I8(t)
383    }
384}
385
386impl From<Tensor<u16>> for TensorDyn {
387    fn from(t: Tensor<u16>) -> Self {
388        Self::U16(t)
389    }
390}
391
392impl From<Tensor<i16>> for TensorDyn {
393    fn from(t: Tensor<i16>) -> Self {
394        Self::I16(t)
395    }
396}
397
398impl From<Tensor<u32>> for TensorDyn {
399    fn from(t: Tensor<u32>) -> Self {
400        Self::U32(t)
401    }
402}
403
404impl From<Tensor<i32>> for TensorDyn {
405    fn from(t: Tensor<i32>) -> Self {
406        Self::I32(t)
407    }
408}
409
410impl From<Tensor<u64>> for TensorDyn {
411    fn from(t: Tensor<u64>) -> Self {
412        Self::U64(t)
413    }
414}
415
416impl From<Tensor<i64>> for TensorDyn {
417    fn from(t: Tensor<i64>) -> Self {
418        Self::I64(t)
419    }
420}
421
422impl From<Tensor<f16>> for TensorDyn {
423    fn from(t: Tensor<f16>) -> Self {
424        Self::F16(t)
425    }
426}
427
428impl From<Tensor<f32>> for TensorDyn {
429    fn from(t: Tensor<f32>) -> Self {
430        Self::F32(t)
431    }
432}
433
434impl From<Tensor<f64>> for TensorDyn {
435    fn from(t: Tensor<f64>) -> Self {
436        Self::F64(t)
437    }
438}
439
440impl fmt::Debug for TensorDyn {
441    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
442        dispatch!(self, fmt, f)
443    }
444}
445
446#[cfg(test)]
447mod tests {
448    use super::*;
449
450    #[test]
451    fn from_typed_tensor() {
452        let t = Tensor::<u8>::new(&[10], None, None).unwrap();
453        let dyn_t: TensorDyn = t.into();
454        assert_eq!(dyn_t.dtype(), DType::U8);
455        assert_eq!(dyn_t.shape(), &[10]);
456    }
457
458    #[test]
459    fn downcast_ref() {
460        let t = Tensor::<u8>::new(&[10], None, None).unwrap();
461        let dyn_t: TensorDyn = t.into();
462        assert!(dyn_t.as_u8().is_some());
463        assert!(dyn_t.as_i8().is_none());
464    }
465
466    #[test]
467    fn downcast_into() {
468        let t = Tensor::<u8>::new(&[10], None, None).unwrap();
469        let dyn_t: TensorDyn = t.into();
470        let back = dyn_t.into_u8().unwrap();
471        assert_eq!(back.shape(), &[10]);
472    }
473
474    #[test]
475    fn image_accessors() {
476        let t = Tensor::<u8>::image(640, 480, PixelFormat::Rgba, None).unwrap();
477        let dyn_t: TensorDyn = t.into();
478        assert_eq!(dyn_t.format(), Some(PixelFormat::Rgba));
479        assert_eq!(dyn_t.width(), Some(640));
480        assert_eq!(dyn_t.height(), Some(480));
481        assert!(!dyn_t.is_multiplane());
482    }
483
484    #[test]
485    fn image_constructor() {
486        let dyn_t = TensorDyn::image(640, 480, PixelFormat::Rgb, DType::U8, None).unwrap();
487        assert_eq!(dyn_t.dtype(), DType::U8);
488        assert_eq!(dyn_t.format(), Some(PixelFormat::Rgb));
489        assert_eq!(dyn_t.width(), Some(640));
490    }
491
492    #[test]
493    fn image_constructor_i8() {
494        let dyn_t = TensorDyn::image(640, 480, PixelFormat::Rgb, DType::I8, None).unwrap();
495        assert_eq!(dyn_t.dtype(), DType::I8);
496        assert_eq!(dyn_t.format(), Some(PixelFormat::Rgb));
497    }
498
499    #[test]
500    fn set_format_packed() {
501        let mut t = TensorDyn::new(&[480, 640, 3], DType::U8, None, None).unwrap();
502        assert_eq!(t.format(), None);
503        t.set_format(PixelFormat::Rgb).unwrap();
504        assert_eq!(t.format(), Some(PixelFormat::Rgb));
505        assert_eq!(t.width(), Some(640));
506        assert_eq!(t.height(), Some(480));
507    }
508
509    #[test]
510    fn set_format_planar() {
511        let mut t = TensorDyn::new(&[3, 480, 640], DType::U8, None, None).unwrap();
512        t.set_format(PixelFormat::PlanarRgb).unwrap();
513        assert_eq!(t.format(), Some(PixelFormat::PlanarRgb));
514        assert_eq!(t.width(), Some(640));
515        assert_eq!(t.height(), Some(480));
516    }
517
518    #[test]
519    fn set_format_rejects_wrong_shape() {
520        let mut t = TensorDyn::new(&[480, 640, 4], DType::U8, None, None).unwrap();
521        assert!(t.set_format(PixelFormat::Rgb).is_err());
522    }
523
524    #[test]
525    fn with_format_builder() {
526        let t = TensorDyn::new(&[480, 640, 4], DType::U8, None, None)
527            .unwrap()
528            .with_format(PixelFormat::Rgba)
529            .unwrap();
530        assert_eq!(t.format(), Some(PixelFormat::Rgba));
531        assert_eq!(t.width(), Some(640));
532        assert_eq!(t.height(), Some(480));
533    }
534
535    #[cfg(target_os = "linux")]
536    #[test]
537    fn dmabuf_clone_mem_tensor_fails() {
538        let t = TensorDyn::new(&[480, 640, 3], DType::U8, Some(TensorMemory::Mem), None).unwrap();
539        assert_eq!(t.memory(), TensorMemory::Mem);
540        assert!(t.dmabuf_clone().is_err());
541    }
542
543    #[cfg(target_os = "linux")]
544    #[test]
545    fn dmabuf_mem_tensor_fails() {
546        let t = TensorDyn::new(&[480, 640, 3], DType::U8, Some(TensorMemory::Mem), None).unwrap();
547        assert!(t.dmabuf().is_err());
548    }
549
550    #[test]
551    fn set_format_semi_planar_nv12() {
552        // 720 rows = 480 * 3/2 (NV12: height + height/2 for chroma)
553        let mut t = TensorDyn::new(&[720, 640], DType::U8, Some(TensorMemory::Mem), None).unwrap();
554        t.set_format(PixelFormat::Nv12).unwrap();
555        assert_eq!(t.format(), Some(PixelFormat::Nv12));
556        assert_eq!(t.width(), Some(640));
557        assert_eq!(t.height(), Some(480));
558    }
559
560    #[test]
561    fn set_format_semi_planar_nv16() {
562        // 960 rows = 480 * 2 (NV16: height + height for chroma)
563        let mut t = TensorDyn::new(&[960, 640], DType::U8, Some(TensorMemory::Mem), None).unwrap();
564        t.set_format(PixelFormat::Nv16).unwrap();
565        assert_eq!(t.format(), Some(PixelFormat::Nv16));
566        assert_eq!(t.width(), Some(640));
567        assert_eq!(t.height(), Some(480));
568    }
569
570    #[test]
571    fn with_format_rejects_wrong_shape() {
572        let result = TensorDyn::new(&[480, 640, 4], DType::U8, None, None)
573            .unwrap()
574            .with_format(PixelFormat::Rgb);
575        assert!(result.is_err());
576    }
577
578    #[test]
579    fn set_format_preserved_after_rejection() {
580        let mut t = TensorDyn::new(&[480, 640, 3], DType::U8, None, None).unwrap();
581        t.set_format(PixelFormat::Rgb).unwrap();
582        assert_eq!(t.format(), Some(PixelFormat::Rgb));
583
584        // Rgba requires 4 channels, should fail on a 3-channel tensor
585        assert!(t.set_format(PixelFormat::Rgba).is_err());
586
587        // Original format should be preserved
588        assert_eq!(t.format(), Some(PixelFormat::Rgb));
589    }
590
591    #[test]
592    fn set_format_idempotent() {
593        let mut t = TensorDyn::new(&[480, 640, 3], DType::U8, None, None).unwrap();
594        t.set_format(PixelFormat::Rgb).unwrap();
595        t.set_format(PixelFormat::Rgb).unwrap();
596        assert_eq!(t.format(), Some(PixelFormat::Rgb));
597        assert_eq!(t.width(), Some(640));
598        assert_eq!(t.height(), Some(480));
599    }
600
601    // --- Row stride tests ---
602
603    #[test]
604    fn set_row_stride_valid() {
605        // RGBA 100px wide: min stride = 400, set 512
606        let mut t = TensorDyn::image(100, 100, PixelFormat::Rgba, DType::U8, None).unwrap();
607        t.set_row_stride(512).unwrap();
608        assert_eq!(t.row_stride(), Some(512));
609        assert_eq!(t.effective_row_stride(), Some(512));
610    }
611
612    #[test]
613    fn set_row_stride_equals_min() {
614        // RGB 100px: min stride = 300, set exactly 300
615        let mut t = TensorDyn::image(100, 100, PixelFormat::Rgb, DType::U8, None).unwrap();
616        t.set_row_stride(300).unwrap();
617        assert_eq!(t.row_stride(), Some(300));
618    }
619
620    #[test]
621    fn set_row_stride_too_small() {
622        // RGBA 100px: min stride = 400, set 300
623        let mut t = TensorDyn::image(100, 100, PixelFormat::Rgba, DType::U8, None).unwrap();
624        assert!(t.set_row_stride(300).is_err());
625        assert_eq!(t.row_stride(), None);
626    }
627
628    #[test]
629    fn set_row_stride_zero() {
630        let mut t = TensorDyn::image(100, 100, PixelFormat::Rgb, DType::U8, None).unwrap();
631        assert!(t.set_row_stride(0).is_err());
632    }
633
634    #[test]
635    fn set_row_stride_requires_format() {
636        let mut t = TensorDyn::new(&[480, 640, 3], DType::U8, None, None).unwrap();
637        assert!(t.set_row_stride(2048).is_err());
638    }
639
640    #[test]
641    fn effective_row_stride_without_stride() {
642        let t = TensorDyn::image(100, 100, PixelFormat::Rgb, DType::U8, None).unwrap();
643        assert_eq!(t.row_stride(), None);
644        assert_eq!(t.effective_row_stride(), Some(300)); // 100 * 3
645    }
646
647    #[test]
648    fn effective_row_stride_no_format() {
649        let t = TensorDyn::new(&[480, 640, 3], DType::U8, None, None).unwrap();
650        assert_eq!(t.effective_row_stride(), None);
651    }
652
653    #[test]
654    fn with_row_stride_builder() {
655        let t = TensorDyn::image(100, 100, PixelFormat::Rgba, DType::U8, None)
656            .unwrap()
657            .with_row_stride(512)
658            .unwrap();
659        assert_eq!(t.row_stride(), Some(512));
660        assert_eq!(t.effective_row_stride(), Some(512));
661    }
662
663    #[test]
664    fn with_row_stride_rejects_small() {
665        let result = TensorDyn::image(100, 100, PixelFormat::Rgba, DType::U8, None)
666            .unwrap()
667            .with_row_stride(200);
668        assert!(result.is_err());
669    }
670
671    #[test]
672    fn set_format_clears_row_stride() {
673        let mut t = TensorDyn::new(&[480, 640, 3], DType::U8, None, None).unwrap();
674        t.set_format(PixelFormat::Rgb).unwrap();
675        t.set_row_stride(2048).unwrap();
676        assert_eq!(t.row_stride(), Some(2048));
677
678        // Incompatible format change (4-chan on 3-chan shape) fails — stride preserved
679        let _ = t.set_format(PixelFormat::Bgra);
680        assert_eq!(t.row_stride(), Some(2048));
681
682        // Re-set to same format — stride preserved
683        t.set_format(PixelFormat::Rgb).unwrap();
684        assert_eq!(t.row_stride(), Some(2048));
685
686        // Reshape clears format and stride
687        t.reshape(&[480 * 640 * 3]).unwrap();
688        assert_eq!(t.row_stride(), None);
689        assert_eq!(t.format(), None);
690    }
691
692    #[test]
693    fn set_format_different_compatible_clears_stride() {
694        // RGBA and BGRA are both 4-channel packed — switching between them
695        // succeeds and must clear the stored stride.
696        let mut t = TensorDyn::new(&[480, 640, 4], DType::U8, None, None).unwrap();
697        t.set_format(PixelFormat::Rgba).unwrap();
698        t.set_row_stride(4096).unwrap();
699        assert_eq!(t.row_stride(), Some(4096));
700
701        // Successful format change to a different compatible format clears stride
702        t.set_format(PixelFormat::Bgra).unwrap();
703        assert_eq!(t.format(), Some(PixelFormat::Bgra));
704        assert_eq!(t.row_stride(), None);
705    }
706
707    #[test]
708    fn set_format_same_preserves_stride() {
709        let mut t = TensorDyn::image(100, 100, PixelFormat::Rgb, DType::U8, None).unwrap();
710        t.set_row_stride(512).unwrap();
711        // Re-setting the same format should not clear stride
712        t.set_format(PixelFormat::Rgb).unwrap();
713        assert_eq!(t.row_stride(), Some(512));
714    }
715
716    #[test]
717    fn effective_row_stride_planar() {
718        let t = TensorDyn::image(640, 480, PixelFormat::PlanarRgb, DType::U8, None).unwrap();
719        assert_eq!(t.effective_row_stride(), Some(640)); // planar: width only
720    }
721
722    #[test]
723    fn effective_row_stride_nv12() {
724        let t = TensorDyn::image(640, 480, PixelFormat::Nv12, DType::U8, None).unwrap();
725        assert_eq!(t.effective_row_stride(), Some(640)); // semi-planar: width only
726    }
727
728    #[test]
729    fn map_rejects_strided_tensor() {
730        let mut t =
731            Tensor::<u8>::image(100, 100, PixelFormat::Rgba, Some(TensorMemory::Mem)).unwrap();
732        // Map works before stride is set
733        assert!(t.map().is_ok());
734        // After setting stride, map should be rejected
735        t.set_row_stride(512).unwrap();
736        let err = t.map();
737        assert!(err.is_err());
738    }
739
740    // ── plane_offset tests ──────────────────────────────────────────
741
742    #[test]
743    fn plane_offset_default_none() {
744        let t = TensorDyn::image(100, 100, PixelFormat::Rgba, DType::U8, None).unwrap();
745        assert_eq!(t.plane_offset(), None);
746    }
747
748    #[test]
749    fn set_plane_offset_basic() {
750        let mut t = TensorDyn::image(100, 100, PixelFormat::Rgba, DType::U8, None).unwrap();
751        t.set_plane_offset(4096);
752        assert_eq!(t.plane_offset(), Some(4096));
753    }
754
755    #[test]
756    fn set_plane_offset_zero() {
757        let mut t = TensorDyn::image(100, 100, PixelFormat::Rgb, DType::U8, None).unwrap();
758        t.set_plane_offset(0);
759        assert_eq!(t.plane_offset(), Some(0));
760    }
761
762    #[test]
763    fn set_plane_offset_no_format() {
764        // plane_offset does not require format (it is format-independent)
765        let mut t = TensorDyn::new(&[480, 640, 3], DType::U8, None, None).unwrap();
766        t.set_plane_offset(4096);
767        assert_eq!(t.plane_offset(), Some(4096));
768    }
769
770    #[test]
771    fn with_plane_offset_builder() {
772        let t = TensorDyn::image(100, 100, PixelFormat::Rgba, DType::U8, None)
773            .unwrap()
774            .with_plane_offset(8192);
775        assert_eq!(t.plane_offset(), Some(8192));
776    }
777
778    #[test]
779    fn set_format_clears_plane_offset() {
780        let mut t = TensorDyn::new(&[480, 640, 3], DType::U8, None, None).unwrap();
781        t.set_format(PixelFormat::Rgb).unwrap();
782        t.set_plane_offset(4096);
783        assert_eq!(t.plane_offset(), Some(4096));
784
785        // Re-set same format — offset preserved
786        t.set_format(PixelFormat::Rgb).unwrap();
787        assert_eq!(t.plane_offset(), Some(4096));
788
789        // Reshape clears everything
790        t.reshape(&[480 * 640 * 3]).unwrap();
791        assert_eq!(t.plane_offset(), None);
792        assert_eq!(t.format(), None);
793    }
794
795    #[test]
796    fn map_rejects_offset_tensor() {
797        let mut t =
798            Tensor::<u8>::image(100, 100, PixelFormat::Rgba, Some(TensorMemory::Mem)).unwrap();
799        // Map works before offset is set
800        assert!(t.map().is_ok());
801        // After setting non-zero offset, map should be rejected
802        t.set_plane_offset(4096);
803        assert!(t.map().is_err());
804    }
805
806    #[test]
807    fn map_accepts_zero_offset_tensor() {
808        let mut t =
809            Tensor::<u8>::image(100, 100, PixelFormat::Rgba, Some(TensorMemory::Mem)).unwrap();
810        t.set_plane_offset(0);
811        // Zero offset is fine for CPU mapping
812        assert!(t.map().is_ok());
813    }
814
815    #[test]
816    fn from_planes_propagates_plane_offset() {
817        let mut luma =
818            Tensor::<u8>::new(&[480, 640], Some(TensorMemory::Mem), Some("luma")).unwrap();
819        luma.set_plane_offset(4096);
820        let chroma =
821            Tensor::<u8>::new(&[240, 640], Some(TensorMemory::Mem), Some("chroma")).unwrap();
822        let combined = Tensor::<u8>::from_planes(luma, chroma, PixelFormat::Nv12).unwrap();
823        assert_eq!(combined.plane_offset(), Some(4096));
824    }
825}