Skip to main content

ncnn_rust/
mat.rs

1use crate::{error::status, sys, Error, Result};
2use std::{marker::PhantomData, rc::Rc};
3
4/// Scalar format of a native tensor.
5///
6/// ncnn records the element width but not whether a 16-bit element is IEEE half
7/// or bfloat16, so the caller supplies the format for those tensors.
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9#[non_exhaustive]
10pub enum ElementKind {
11    /// IEEE 754 single precision.
12    F32,
13    /// IEEE 754 half precision.
14    F16,
15    /// Brain floating point, 16 bits.
16    Bf16,
17    /// Signed 8-bit integer, the storage of a quantized tensor.
18    I8,
19    /// Unsigned 8-bit integer.
20    U8,
21    /// Signed 16-bit integer.
22    I16,
23    /// Signed 32-bit integer.
24    I32,
25}
26
27impl ElementKind {
28    fn code(self) -> i32 {
29        match self {
30            Self::F32 => 0,
31            Self::F16 => 1,
32            Self::Bf16 => 2,
33            Self::I8 => 3,
34            Self::U8 => 4,
35            Self::I16 => 5,
36            Self::I32 => 6,
37        }
38    }
39    /// Returns the byte width of one element in this format.
40    pub fn element_bytes(self) -> usize {
41        match self {
42            Self::F32 | Self::I32 => 4,
43            Self::F16 | Self::Bf16 | Self::I16 => 2,
44            Self::I8 | Self::U8 => 1,
45        }
46    }
47    /// Returns the format name used in error messages.
48    pub fn label(self) -> &'static str {
49        match self {
50            Self::F32 => "f32",
51            Self::F16 => "f16",
52            Self::Bf16 => "bf16",
53            Self::I8 => "int8",
54            Self::U8 => "uint8",
55            Self::I16 => "int16",
56            Self::I32 => "int32",
57        }
58    }
59}
60
61#[derive(Debug, Clone, Copy)]
62/// Native tensor metadata for one extracted output.
63pub struct TensorInfo {
64    /// Number of populated axes, 1 to 4.
65    pub dims: i32,
66    /// Logical width in elements.
67    pub w: i32,
68    /// Logical height in elements.
69    pub h: i32,
70    /// Logical depth in elements.
71    pub d: i32,
72    /// Channel count.
73    pub c: i32,
74    /// Batch count.
75    pub n: i32,
76    /// Size of one packed element in bytes.
77    pub elemsize: usize,
78    /// Elements stored per packed element.
79    pub elempack: i32,
80    /// Native channel stride, which can exceed the logical plane size.
81    pub cstep: usize,
82}
83#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
84/// Border sizes for the padding and crop helpers.
85///
86/// The two-dimensional helpers take the four in-plane values directly; this struct carries the
87/// depth pair that a four-axis tensor also needs.
88#[non_exhaustive]
89pub struct Borders {
90    /// Rows added or removed at the top.
91    pub top: usize,
92    /// Rows added or removed at the bottom.
93    pub bottom: usize,
94    /// Columns added or removed on the left.
95    pub left: usize,
96    /// Columns added or removed on the right.
97    pub right: usize,
98    /// Slices added or removed in front.
99    pub front: usize,
100    /// Slices added or removed behind.
101    pub behind: usize,
102}
103impl Borders {
104    /// Builds the in-plane border sizes with no depth change.
105    pub fn new(top: usize, bottom: usize, left: usize, right: usize) -> Self {
106        Self {
107            top,
108            bottom,
109            left,
110            right,
111            front: 0,
112            behind: 0,
113        }
114    }
115    /// Adds the depth pair, which only a four-axis tensor reads.
116    pub fn with_depth(mut self, front: usize, behind: usize) -> Self {
117        self.front = front;
118        self.behind = behind;
119        self
120    }
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124#[repr(i32)]
125/// Edge treatment of [`Mat::copy_make_border`].
126///
127/// The variant follows the native padding mode, so a `Reflect` border mirrors the image and a
128/// `Replicate` border repeats the edge row.
129#[non_exhaustive]
130pub enum BorderMode {
131    /// Fills the added rows and columns with the supplied value.
132    Constant = 0,
133    /// Repeats the edge row and column into the border.
134    Replicate = 1,
135    /// Mirrors the image into the border without repeating the edge row and column.
136    Reflect = 2,
137}
138
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140#[repr(i32)]
141/// Source and destination pixel layout for image conversion.
142#[non_exhaustive]
143pub enum PixelFormat {
144    /// Three interleaved channels in red, green, blue order.
145    Rgb = 1,
146    /// Three interleaved channels in blue, green, red order.
147    Bgr = 2,
148    /// One luminance channel.
149    Gray = 3,
150    /// Four interleaved channels with alpha last.
151    Rgba = 4,
152    /// Four interleaved channels in blue, green, red, alpha order.
153    Bgra = 5,
154}
155impl PixelFormat {
156    /// Returns the channel count of the layout.
157    pub fn channels(self) -> usize {
158        match self {
159            Self::Gray => 1,
160            Self::Rgb | Self::Bgr => 3,
161            _ => 4,
162        }
163    }
164}
165
166/// An immutable native tensor. Transformations return independently owned storage.
167/// Native storage provenance. Only owned storage may be transferred to a network.
168#[derive(Clone, Copy, PartialEq, Eq, Debug)]
169pub(crate) enum Provenance {
170    Owned,
171    Adopted,
172    /// Borrows caller storage; the tensor never frees it and cannot transfer it.
173    External,
174}
175
176/// An owned tensor handle released through the native allocator.
177///
178/// # Surface
179///
180/// The methods group by capability, and each group answers one question. The source order
181/// matches the table, so the rendered method list reads in the same groups:
182///
183/// | Group | Methods |
184/// |---|---|
185/// | Construction | `from_f32`, `from_f32_batch`, `from_typed`, `from_i8`, `from_pixels`, `from_external` |
186/// | Sub views | `channel`, `channel_range`, `depth`, `depth_range`, `column_range`, `row_range`, `batch`, `batch_range` |
187/// | Metadata | `info`, `is_empty` |
188/// | Typed access | `to_f32`, `to_f32_typed`, `to_i8`, `copy_to_f32`, `to_f32_into`, `as_f32_slice`, `channel_f32` |
189/// | Layout | `flatten`, `with_packing`, `deep_clone`, `reshape`, `into_reshape`, `reshape_view` |
190/// | Values in place | `fill`, `normalized`, `normalize_in_place`, `into_normalized` |
191/// | Pixels | `to_pixels`, `to_pixels_resize` |
192/// | Borders | `copy_make_border`, `copy_cut_border`, `copy_make_border_3d`, `copy_cut_border_3d` |
193/// | Raw escape | `as_raw`, `into_raw`, `from_raw_owned` |
194///
195/// The extents themselves come from [`TensorInfo`], which `info` returns: `shape` and `total`
196/// describe an existing tensor rather than build one.
197///
198/// The consuming forms (`into_reshape`, `into_normalized`) exist because they keep storage the
199/// caller already owns; the borrowing forms do the same work behind a copy.
200///
201/// # Thread affinity
202///
203/// A tensor belongs to the thread that created it: the handle is not `Send` or `Sync` because
204/// native allocation, packing and the allocator a tensor came from are thread-affine. Move the
205/// input bytes instead and build a tensor on the thread that runs inference.
206pub struct Mat {
207    pub(crate) raw: sys::ncnn_mat_t,
208    pub(crate) f32_known: bool,
209    provenance: Provenance,
210    _thread: PhantomData<Rc<()>>,
211}
212pub(crate) fn shape(shape: &[usize]) -> Result<([i32; 4], usize)> {
213    if !(1..=4).contains(&shape.len()) {
214        return Err(Error::invalid("Shape must have 1..=4 dimensions"));
215    }
216    let mut count = 1usize;
217    let mut native = [0; 4];
218    for (dimension, &v) in shape.iter().enumerate() {
219        if v == 0 || v > i32::MAX as usize {
220            return Err(Error::invalid("Invalid dimension"));
221        }
222        count = count
223            .checked_mul(v)
224            .ok_or(Error::invalid("Shape overflow"))?;
225        native[dimension] = v as i32;
226    }
227    if count > (isize::MAX as usize / 4).saturating_sub(64) {
228        return Err(Error::invalid("Tensor exceeds addressable length"));
229    }
230    Ok((native, count))
231}
232fn native_extent(value: usize, operation: &str) -> Result<i32> {
233    i32::try_from(value)
234        .map_err(|_| Error::invalid(format!("{operation} exceeds the native extent range")))
235}
236fn padded(extent: i32, before: usize, after: usize, operation: &str) -> Result<i32> {
237    (extent as usize)
238        .checked_add(before)
239        .and_then(|total| total.checked_add(after))
240        .filter(|total| *total <= i32::MAX as usize)
241        .map(|total| total as i32)
242        .ok_or_else(|| Error::invalid(format!("{operation} exceeds the native extent range")))
243}
244fn to_index(value: usize) -> Result<i32> {
245    native_extent(value, "Tensor view index")
246}
247impl TensorInfo {
248    /// Reports the storage slots one batch item occupies, excluding batch.
249    ///
250    /// This is the native `Mat::total` value, the channel stride multiplied by the channel count, so
251    /// it includes inter-channel padding.
252    pub fn total(&self) -> usize {
253        self.cstep.saturating_mul(self.c.max(0) as usize)
254    }
255    /// Reports the logical extents in native axis order: width, height, depth, channels.
256    ///
257    /// [`dims`](Self::dims) says how many of the four carry the tensor, so a two-dimensional tensor
258    /// uses the first two entries.
259    pub fn shape(&self) -> [usize; 4] {
260        [
261            self.w.max(0) as usize,
262            self.h.max(0) as usize,
263            self.d.max(0) as usize,
264            self.c.max(0) as usize,
265        ]
266    }
267}
268impl Mat {
269    // --- Construction ---
270    /// Copies FP32 values into a new tensor of the given rank and extents.
271    ///
272    /// ```
273    /// let tensor = ncnn_rust::Mat::from_f32(&[1.0, 2.0, 3.0, 4.0], &[2, 2])?;
274    /// assert_eq!(tensor.info().w, 2);
275    /// assert_eq!(tensor.to_f32()?, [1.0, 2.0, 3.0, 4.0]);
276    /// # Ok::<(), ncnn_rust::Error>(())
277    /// ```
278    pub fn from_f32(data: &[f32], dimensions: &[usize]) -> Result<Self> {
279        let (s, count) = shape(dimensions)?;
280        if data.len() != count {
281            return Err(Error::invalid(format!(
282                "Data length {} does not match a shape of {count} elements",
283                data.len()
284            )));
285        }
286        let mut raw = std::ptr::null_mut();
287        unsafe {
288            status(sys::ncnn_rs_mat_copy_f32(
289                data.as_ptr(),
290                dimensions.len() as i32,
291                s.as_ptr(),
292                &mut raw,
293            ))?;
294            Self::owned(raw, true)
295        }
296    }
297    /// Copies batched FP32 values into a new tensor.
298    ///
299    /// `data` holds `batch` tensors one after another, each in channel-plane order. Layers that do
300    /// not declare `support_batch` still run, because ncnn splits the batch and joins the result.
301    /// [`TensorInfo::n`] reports the batch count, and [`to_f32`](Self::to_f32) reads the batches
302    /// back in the same order. The arithmetic helpers, normalization and reshape, stay single
303    /// batch.
304    pub fn from_f32_batch(data: &[f32], dimensions: &[usize], batch: usize) -> Result<Self> {
305        let (s, count) = shape(dimensions)?;
306        if batch == 0 || batch > i32::MAX as usize {
307            return Err(Error::invalid("Invalid batch count"));
308        }
309        let expected = count
310            .checked_mul(batch)
311            .ok_or_else(|| Error::invalid("Batched tensor length overflows"))?;
312        if data.len() != expected {
313            return Err(Error::invalid(format!(
314                "Data length {} does not match {batch} tensors of {count} elements",
315                data.len()
316            )));
317        }
318        let mut raw = std::ptr::null_mut();
319        unsafe {
320            status(sys::ncnn_rs_mat_copy_f32_batch(
321                data.as_ptr(),
322                dimensions.len() as i32,
323                s.as_ptr(),
324                batch as i32,
325                &mut raw,
326            ))?;
327            Self::owned(raw, true)
328        }
329    }
330    /// Copies typed bytes into a new tensor of the given rank and extents.
331    ///
332    /// `data` holds elements of `kind.element_bytes()` bytes in channel-plane order, the
333    /// layout the native layers read and the typed readers expect. This is how a quantized
334    /// or half-precision tensor enters a network.
335    pub fn from_typed(kind: ElementKind, data: &[u8], dimensions: &[usize]) -> Result<Self> {
336        let (s, count) = shape(dimensions)?;
337        let width = kind.element_bytes();
338        let expected = count
339            .checked_mul(width)
340            .ok_or_else(|| Error::invalid("Tensor byte length overflows"))?;
341        if data.len() != expected {
342            return Err(Error::invalid(format!(
343                "Data length {} does not match {count} {} elements of {width} bytes",
344                data.len(),
345                kind.label()
346            )));
347        }
348        let mut raw = std::ptr::null_mut();
349        unsafe {
350            status(sys::ncnn_rs_mat_copy_typed(
351                kind.code(),
352                data.as_ptr(),
353                data.len(),
354                dimensions.len() as i32,
355                s.as_ptr(),
356                &mut raw,
357            ))?;
358            Self::owned(raw, kind == ElementKind::F32)
359        }
360    }
361    /// Copies signed 8-bit values into a new quantized tensor.
362    ///
363    /// This is the signature `Quantize` produces; `Mat::from_typed` covers the unsigned
364    /// format and every other element width.
365    pub fn from_i8(data: &[i8], dimensions: &[usize]) -> Result<Self> {
366        let bytes = unsafe { std::slice::from_raw_parts(data.as_ptr().cast::<u8>(), data.len()) };
367        Self::from_typed(ElementKind::I8, bytes, dimensions)
368    }
369    pub(crate) unsafe fn owned(raw: sys::ncnn_mat_t, f32_known: bool) -> Result<Self> {
370        if raw.is_null() {
371            return Err(Error::Native(-100));
372        }
373        let result = Self {
374            raw,
375            f32_known,
376            provenance: Provenance::Owned,
377            _thread: PhantomData,
378        };
379        if sys::ncnn_mat_get_data(raw).is_null() {
380            return Err(Error::Native(-100));
381        }
382        Ok(result)
383    }
384    pub(crate) fn is_transferable(&self) -> bool {
385        self.provenance == Provenance::Owned
386    }
387    /// Copies interleaved pixels into a new tensor.
388    pub fn from_pixels(
389        data: &[u8],
390        format: PixelFormat,
391        width: usize,
392        height: usize,
393    ) -> Result<Self> {
394        let (_, count) = shape(&[width, height, format.channels()])?;
395        let stride = width
396            .checked_mul(format.channels())
397            .and_then(|v| i32::try_from(v).ok())
398            .ok_or(Error::invalid("Pixel stride overflow"))?;
399        if count != data.len() {
400            return Err(Error::invalid("Pixel buffer size mismatch"));
401        }
402        unsafe {
403            Self::owned(
404                sys::ncnn_mat_from_pixels(
405                    data.as_ptr(),
406                    format as i32,
407                    width as i32,
408                    height as i32,
409                    stride,
410                    std::ptr::null_mut(),
411                ),
412                true,
413            )
414        }
415    }
416    /// Builds a tensor that borrows caller storage instead of copying it.
417    ///
418    /// The native tensor keeps the pointer, so this is the zero-copy input path: a caller that
419    /// already holds frame data avoids one copy per request. Reads through the returned tensor
420    /// behave like any other tensor, and the tensor never frees the buffer.
421    ///
422    /// # Safety
423    ///
424    /// `data` must stay alive, keep its length and stay free of mutable aliases until this tensor
425    /// and every native object that received it are dropped. An extractor that submitted it holds
426    /// the pointer until it is dropped, so the borrow has to cover the extraction. Use
427    /// [`Input::borrowed`](crate::Input::borrowed) when the borrow only has to cover one
428    /// request.
429    pub unsafe fn from_external(data: &[f32], dimensions: &[usize]) -> Result<Self> {
430        let (s, count) = shape(dimensions)?;
431        if data.len() != count {
432            return Err(Error::invalid(format!(
433                "Data length {} does not match a shape of {count} elements",
434                data.len()
435            )));
436        }
437        let pointer = data.as_ptr().cast_mut().cast::<std::ffi::c_void>();
438        let raw = match dimensions.len() {
439            1 => sys::ncnn_mat_create_external_1d(s[0], pointer, std::ptr::null_mut()),
440            2 => sys::ncnn_mat_create_external_2d(s[0], s[1], pointer, std::ptr::null_mut()),
441            3 => sys::ncnn_mat_create_external_3d(s[0], s[1], s[2], pointer, std::ptr::null_mut()),
442            _ => sys::ncnn_mat_create_external_4d(
443                s[0],
444                s[1],
445                s[2],
446                s[3],
447                pointer,
448                std::ptr::null_mut(),
449            ),
450        };
451        if raw.is_null() {
452            return Err(Error::Native(-100));
453        }
454        Ok(Self {
455            raw,
456            f32_known: true,
457            provenance: Provenance::External,
458            _thread: PhantomData,
459        })
460    }
461
462    // --- Sub views ---
463    /// Borrows one channel as a read-only alias.
464    ///
465    /// The alias shares this tensor's storage. It rejects a channel outside `0..c`, and the source
466    /// stays borrowed for as long as the view lives.
467    pub fn channel(&self, channel: usize) -> Result<MatView<'_>> {
468        self.native_view(3, channel, 1, "channel")
469    }
470    /// Borrows a run of channels as a read-only alias.
471    pub fn channel_range(&self, channel: usize, channels: usize) -> Result<MatView<'_>> {
472        self.native_view(3, channel, channels, "channel range")
473    }
474    /// Borrows one depth slice as a read-only alias.
475    pub fn depth(&self, depth: usize) -> Result<MatView<'_>> {
476        self.native_view(2, depth, 1, "depth slice")
477    }
478    /// Borrows a run of depth slices as a read-only alias.
479    pub fn depth_range(&self, depth: usize, depths: usize) -> Result<MatView<'_>> {
480        self.native_view(2, depth, depths, "depth range")
481    }
482    /// Borrows `width` columns starting at `x` as a one-dimensional alias of the first row.
483    pub fn column_range(&self, x: usize, width: usize) -> Result<MatView<'_>> {
484        self.native_view(0, x, width, "column range")
485    }
486    /// Borrows `rows` rows starting at `y` as a read-only alias of the first channel plane.
487    pub fn row_range(&self, y: usize, rows: usize) -> Result<MatView<'_>> {
488        self.native_view(1, y, rows, "row range")
489    }
490    /// Borrows one batch item as a read-only alias.
491    pub fn batch(&self, batch: usize) -> Result<MatView<'_>> {
492        self.native_view(4, batch, 1, "batch item")
493    }
494    /// Borrows `batches` batch items starting at `batch` as a read-only alias.
495    pub fn batch_range(&self, batch: usize, batches: usize) -> Result<MatView<'_>> {
496        self.native_view(4, batch, batches, "batch range")
497    }
498    fn native_view(
499        &self,
500        axis: i32,
501        start: usize,
502        count: usize,
503        operation: &'static str,
504    ) -> Result<MatView<'_>> {
505        let mut raw = std::ptr::null_mut();
506        let code = unsafe {
507            sys::ncnn_rs_mat_view(
508                self.raw,
509                axis,
510                to_index(start)?,
511                to_index(count)?,
512                std::ptr::addr_of_mut!(raw),
513            )
514        };
515        if code != 0 {
516            return Err(Error::NativeAt(operation, code));
517        }
518        // A view keeps no storage of its own, so it is adopted rather than owned: a consumed input
519        // copies it instead of transferring caller storage.
520        let mut mat = unsafe { Self::owned(raw, self.f32_known)? };
521        mat.provenance = Provenance::Adopted;
522        Ok(MatView { mat, _source: self })
523    }
524
525    // --- Metadata ---
526    /// Returns the native shape and stride metadata.
527    pub fn info(&self) -> TensorInfo {
528        unsafe {
529            TensorInfo {
530                dims: sys::ncnn_mat_get_dims(self.raw),
531                w: sys::ncnn_mat_get_w(self.raw),
532                h: sys::ncnn_mat_get_h(self.raw),
533                d: sys::ncnn_mat_get_d(self.raw),
534                c: sys::ncnn_mat_get_c(self.raw),
535                n: sys::ncnn_mat_get_n(self.raw),
536                elemsize: sys::ncnn_mat_get_elemsize(self.raw),
537                elempack: sys::ncnn_mat_get_elempack(self.raw),
538                cstep: sys::ncnn_mat_get_cstep(self.raw),
539            }
540        }
541    }
542    /// Reports whether the tensor holds no elements.
543    ///
544    /// A tensor is empty when native storage has not been created or a shape dimension leaves it
545    /// without storage slots, which is what a failed allocation also reports.
546    pub fn is_empty(&self) -> bool {
547        let info = self.info();
548        let detached = unsafe { sys::ncnn_mat_get_data(self.raw).is_null() };
549        detached || info.c <= 0 || info.cstep == 0
550    }
551
552    // --- Typed access ---
553    /// Copies 32-bit unpacked storage as FP32 values. The caller selects the
554    /// interpretation for tensors whose scalar format is supplied by the model.
555    pub fn to_f32(&self) -> Result<Vec<f32>> {
556        let count = self.f32_copy_count()?;
557        let mut values: Vec<f32> = Vec::with_capacity(count);
558        status(unsafe { sys::ncnn_rs_mat_read_f32(self.raw, values.as_mut_ptr(), count) })?;
559        // The native copy initializes every element before the length is set.
560        unsafe { values.set_len(count) };
561        Ok(values)
562    }
563    /// Copies any scalar format into FP32 values.
564    ///
565    /// Native tensors carry an element width but no format tag, so a 16-bit
566    /// tensor needs the caller to say whether it stores IEEE half or bfloat16.
567    /// Quantized outputs of `Quantize` and `Requantize` are signed 8-bit.
568    pub fn to_f32_typed(&self, kind: ElementKind) -> Result<Vec<f32>> {
569        let info = self.info();
570        let width = kind.element_bytes();
571        let stored = width.saturating_mul(info.elempack.max(1) as usize);
572        if info.elemsize != stored {
573            return Err(Error::invalid(format!(
574                "Tensor stores {} bytes per element, so it is not {} storage; read it with the matching kind, or extract it with FP32 conversion",
575                info.elemsize,
576                kind.label()
577            )));
578        }
579        let count = self.logical_count(&info)?;
580        let mut values = vec![0f32; count];
581        if count == 0 {
582            return Ok(values);
583        }
584        status(unsafe {
585            sys::ncnn_rs_mat_read_typed(self.raw, kind.code(), values.as_mut_ptr(), values.len())
586        })?;
587        Ok(values)
588    }
589    /// Copies signed 8-bit quantized values without going through FP32 storage.
590    ///
591    /// The tensor records one byte per element but not whether the byte is signed, so this
592    /// reads the storage as `I8`: a stored `200` returns `-56`. Read unsigned one-byte
593    /// storage with [`to_f32_typed(ElementKind::U8)`](Self::to_f32_typed) instead.
594    pub fn to_i8(&self) -> Result<Vec<i8>> {
595        Ok(self
596            .to_f32_typed(ElementKind::I8)?
597            .into_iter()
598            .map(|value| value as i8)
599            .collect())
600    }
601    fn logical_count(&self, info: &TensorInfo) -> Result<usize> {
602        if info.n <= 0 || info.w <= 0 || info.h <= 0 || info.d <= 0 || info.c <= 0 {
603            return Err(Error::invalid("Tensor has an empty extent"));
604        }
605        let pixels = (info.w as usize)
606            .checked_mul(info.h as usize)
607            .and_then(|value| value.checked_mul(info.d as usize))
608            .ok_or(Error::invalid("Tensor extent overflows"))?;
609        let pack = info.elempack.max(1) as usize;
610        pixels
611            .checked_mul(pack)
612            .and_then(|value| value.checked_mul(info.c as usize))
613            .and_then(|value| value.checked_mul(info.n as usize))
614            .ok_or(Error::invalid("Tensor extent overflows"))
615    }
616    /// Copies logical FP32 elements into an exact-sized initialized slice.
617    /// Channel padding is omitted. A size/layout error leaves the slice unchanged.
618    pub fn copy_to_f32(&self, out: &mut [f32]) -> Result<()> {
619        let count = self.f32_copy_count()?;
620        if out.len() != count {
621            return Err(Error::invalid("Output buffer size mismatch"));
622        }
623        unsafe {
624            status(sys::ncnn_rs_mat_read_f32(
625                self.raw,
626                out.as_mut_ptr(),
627                out.len(),
628            ))
629        }
630    }
631    /// Appends the logical FP32 values to a vector that keeps its capacity.
632    ///
633    /// Existing values stay in place, so several tensors concatenate in call order. A layout error
634    /// or a failed native copy leaves the vector exactly as it was, and the capacity survives, which
635    /// is what makes a steady-state loop allocation-free. A caller that wants this tensor alone
636    /// clears the vector first.
637    pub fn to_f32_into(&self, out: &mut Vec<f32>) -> Result<()> {
638        let count = self.f32_copy_count()?;
639        let start = out.len();
640        let end = start
641            .checked_add(count)
642            .ok_or(Error::invalid("Output length overflow"))?;
643        out.reserve(count);
644        let result = unsafe {
645            status(sys::ncnn_rs_mat_read_f32(
646                self.raw,
647                out.as_mut_ptr().add(start),
648                count,
649            ))
650        };
651        if result.is_ok() {
652            // The native copy initializes the appended range before publication.
653            unsafe { out.set_len(end) };
654        }
655        result
656    }
657    /// Borrows contiguous, unpacked 32-bit storage with an FP32 interpretation.
658    ///
659    /// The borrow needs single-batch storage whose channels are adjacent, which is the layout a
660    /// single-channel tensor or a network output without channel padding has. A packed, 16-bit or
661    /// batched tensor returns [`Error::Invalid`](crate::Error::Invalid), and a multi-channel tensor
662    /// with padded planes uses [`channel_f32`](Self::channel_f32) or [`to_f32`](Self::to_f32).
663    ///
664    /// ```compile_fail
665    /// let mat = ncnn_rust::Mat::from_f32(&[1.], &[1]).unwrap();
666    /// let values = mat.as_f32_slice().unwrap();
667    /// drop(mat);
668    /// println!("{}", values[0]);
669    /// ```
670    pub fn as_f32_slice(&self) -> Result<&[f32]> {
671        let (info, plane) = self.f32_layout()?;
672        if info.c > 1 && info.cstep != plane {
673            return Err(Error::invalid(
674                "Tensor channels contain padding; use channel_f32 or to_f32",
675            ));
676        }
677        let (_, count) = shape(&[
678            info.w as usize,
679            info.h as usize,
680            info.d as usize,
681            info.c as usize,
682        ])?;
683        unsafe {
684            Ok(std::slice::from_raw_parts(
685                sys::ncnn_mat_get_data(self.raw).cast::<f32>(),
686                count,
687            ))
688        }
689    }
690    /// Borrows one logical channel, excluding native alignment padding.
691    pub fn channel_f32(&self, channel: usize) -> Result<&[f32]> {
692        let (info, plane) = self.f32_layout()?;
693        if channel >= info.c as usize {
694            return Err(Error::invalid("Channel index out of bounds"));
695        }
696        let offset = channel
697            .checked_mul(info.cstep)
698            .ok_or(Error::invalid("Channel offset overflow"))?;
699        if offset
700            .checked_add(plane)
701            .filter(|count| *count <= isize::MAX as usize / 4)
702            .is_none()
703        {
704            return Err(Error::invalid("Channel exceeds addressable storage"));
705        }
706        unsafe {
707            Ok(std::slice::from_raw_parts(
708                sys::ncnn_mat_get_data(self.raw).cast::<f32>().add(offset),
709                plane,
710            ))
711        }
712    }
713    fn f32_layout(&self) -> Result<(TensorInfo, usize)> {
714        let info = self.info();
715        let (_, plane) = shape(&[info.w as usize, info.h as usize, info.d as usize])?;
716        if info.elemsize != 4
717            || info.elempack != 1
718            || info.n != 1
719            || info.c <= 0
720            || info.cstep < plane
721        {
722            return Err(Error::invalid(
723                "FP32 views require valid unpacked single-batch storage",
724            ));
725        }
726        let pointer = unsafe { sys::ncnn_mat_get_data(self.raw) };
727        if pointer.is_null() || !pointer.cast::<f32>().is_aligned() {
728            return Err(Error::invalid("FP32 storage is not aligned"));
729        }
730        Ok((info, plane))
731    }
732    fn f32_copy_count(&self) -> Result<usize> {
733        let m = self.info();
734        if m.elemsize != 4 || m.elempack != 1 || m.n <= 0 {
735            return Err(Error::invalid(format!(
736                "FP32 copies need unpacked 32-bit storage but the tensor stores {} bytes per element with pack {}; extract it with stored storage and read it with to_f32_typed or to_i8",
737                m.elemsize, m.elempack
738            )));
739        }
740        let (_, count) = shape(&[m.w as usize, m.h as usize, m.d as usize, m.c as usize])?;
741        count
742            .checked_mul(m.n as usize)
743            .filter(|n| *n <= (isize::MAX as usize / 4).saturating_sub(64))
744            .ok_or(Error::invalid("Tensor exceeds addressable length"))
745    }
746    // --- Layout ---
747    /// Collapses the tensor into one unpacked dimension.
748    ///
749    /// This is the shape a fully connected layer expects, and it runs on the native kernel. Packed
750    /// or padded storage is expanded first, so the result is unpacked FP32.
751    pub fn flatten(&self) -> Result<Self> {
752        let mut raw = std::ptr::null_mut();
753        unsafe {
754            status(sys::ncnn_rs_mat_flatten(self.raw, &mut raw))?;
755            Self::owned(raw, self.f32_known)
756        }
757    }
758    /// Returns a copy in another element packing.
759    ///
760    /// Packing groups consecutive elements of the packing axis into one lane, which is the layout
761    /// the packed SIMD kernels read. The request must divide the element count of that axis; a pack
762    /// of one returns unpacked storage. The values keep their relative order inside a lane, so a
763    /// packed tensor reads back in lane order rather than plane order; unpack it before comparing
764    /// against plane-ordered values.
765    pub fn with_packing(&self, elempack: i32) -> Result<Self> {
766        if elempack < 1 {
767            return Err(Error::invalid("Element packing must be positive"));
768        }
769        let info = self.info();
770        let axis = match info.dims {
771            1 => info.w,
772            2 => info.h,
773            3 | 4 => info.c,
774            _ => return Err(Error::invalid("Element packing needs a shaped tensor")),
775        };
776        if axis % elempack != 0 {
777            return Err(Error::invalid(
778                "Element packing must divide the packing axis",
779            ));
780        }
781        let mut raw = std::ptr::null_mut();
782        unsafe {
783            status(sys::ncnn_rs_mat_pack(self.raw, elempack, &mut raw))?;
784            Self::owned(raw, self.f32_known)
785        }
786    }
787    /// Copies the tensor into independent native storage.
788    pub fn deep_clone(&self) -> Result<Self> {
789        let mut raw = std::ptr::null_mut();
790        unsafe {
791            status(sys::ncnn_rs_mat_clone(self.raw, &mut raw))?;
792            Self::owned(raw, self.f32_known)
793        }
794    }
795    /// Returns independent storage, detaching only when native reshape aliases.
796    pub fn reshape(&self, dimensions: &[usize]) -> Result<Self> {
797        self.reshape_impl(dimensions, true)
798    }
799    /// Reshapes in place, keeping the storage this tensor already owns.
800    ///
801    /// The native reshape only rewrites the header, so consuming the tensor is what makes the
802    /// alias safe: no other reference to this storage exists afterwards. This is the form to use on
803    /// the way into a network, and it costs no copy where [`reshape`](Self::reshape) has to
804    /// duplicate aliased storage.
805    pub fn into_reshape(self, dimensions: &[usize]) -> Result<Self> {
806        let (s, count) = shape(dimensions)?;
807        let m = self.info();
808        let (_, old_count) = shape(&[m.w as usize, m.h as usize, m.d as usize, m.c as usize])?;
809        if count != old_count || m.n != 1 || m.elempack != 1 {
810            return Err(Error::invalid(
811                "Reshape requires matching unpacked dimensions",
812            ));
813        }
814        let mut raw = std::ptr::null_mut();
815        let result = unsafe {
816            let code = sys::ncnn_rs_mat_reshape(
817                self.raw,
818                dimensions.len() as i32,
819                s.as_ptr(),
820                0,
821                &mut raw,
822            );
823            if code == 0 {
824                Self::owned(raw, self.f32_known)
825            } else {
826                Err(Error::NativeAt("reshape the tensor", code))
827            }
828        };
829        // The native result holds its own reference, so the source handle can release its share.
830        result
831    }
832    /// Returns an explicitly read-only reshape that borrows this tensor.
833    /// Native padding changes may allocate. No raw handle or mutable Mat escapes;
834    /// the source borrow retains external allocator and adopted dependencies.
835    pub fn reshape_view(&self, dimensions: &[usize]) -> Result<ReshapeView<'_>> {
836        Ok(ReshapeView {
837            mat: self.reshape_impl(dimensions, false)?,
838            _source: self,
839        })
840    }
841    fn reshape_impl(&self, dimensions: &[usize], independent: bool) -> Result<Self> {
842        let (s, count) = shape(dimensions)?;
843        let m = self.info();
844        let (_, old_count) = shape(&[m.w as usize, m.h as usize, m.d as usize, m.c as usize])?;
845        if count != old_count || m.n != 1 || m.elempack != 1 {
846            return Err(Error::invalid(
847                "Reshape requires matching unpacked dimensions",
848            ));
849        }
850        let mut raw = std::ptr::null_mut();
851        unsafe {
852            status(sys::ncnn_rs_mat_reshape(
853                self.raw,
854                dimensions.len() as i32,
855                s.as_ptr(),
856                independent as i32,
857                &mut raw,
858            ))?;
859            Self::owned(raw, self.f32_known)
860        }
861    }
862
863    // --- Values in place ---
864    /// Fills owned unpacked FP32 storage with one value.
865    ///
866    /// This is the allocation-free way to clear a reusable input buffer. The storage rules match
867    /// [`normalize_in_place`](Self::normalize_in_place).
868    pub fn fill(&mut self, value: f32) -> Result<()> {
869        self.ensure_writable("In-place fill")?;
870        let m = self.info();
871        if !self.f32_known || m.elemsize != 4 || m.elempack != 1 {
872            return Err(Error::invalid("Fill requires unpacked FP32 storage"));
873        }
874        unsafe { sys::ncnn_mat_fill_float(self.raw, value) };
875        Ok(())
876    }
877    /// Returns a copy with mean subtraction and scaling applied per channel.
878    pub fn normalized(&self, mean: &[f32], norm: &[f32]) -> Result<Self> {
879        let m = self.info();
880        if !self.f32_known || m.elemsize != 4 || m.elempack != 1 || m.n != 1 {
881            return Err(Error::invalid("Normalization requires unpacked FP32"));
882        }
883        if (!mean.is_empty() && mean.len() != m.c as usize)
884            || (!norm.is_empty() && norm.len() != m.c as usize)
885        {
886            return Err(Error::invalid(
887                "Normalization requires one value per channel",
888            ));
889        }
890        self.f32_layout()?;
891        let mut raw = std::ptr::null_mut();
892        unsafe {
893            status(sys::ncnn_rs_mat_normalized(
894                self.raw,
895                if mean.is_empty() {
896                    std::ptr::null()
897                } else {
898                    mean.as_ptr()
899                },
900                if norm.is_empty() {
901                    std::ptr::null()
902                } else {
903                    norm.as_ptr()
904                },
905                &mut raw,
906            ))?;
907            Self::owned(raw, true)
908        }
909    }
910    /// Applies mean subtraction and scaling in place, without a second allocation.
911    ///
912    /// The tensor must own its storage: a tensor adopted from a raw handle, or built over an
913    /// external buffer, returns [`Error::Invalid`] because the write would reach memory the caller
914    /// still manages. Lengths follow [`normalized`](Self::normalized).
915    pub fn normalize_in_place(&mut self, mean: &[f32], norm: &[f32]) -> Result<()> {
916        self.ensure_writable("In-place normalization")?;
917        let m = self.info();
918        if !self.f32_known || m.elemsize != 4 || m.elempack != 1 || m.n != 1 {
919            return Err(Error::invalid("Normalization requires unpacked FP32"));
920        }
921        if (!mean.is_empty() && mean.len() != m.c as usize)
922            || (!norm.is_empty() && norm.len() != m.c as usize)
923        {
924            return Err(Error::invalid(
925                "Normalization requires one value per channel",
926            ));
927        }
928        self.f32_layout()?;
929        status(unsafe {
930            sys::ncnn_rs_mat_normalize_in_place(
931                self.raw,
932                if mean.is_empty() {
933                    std::ptr::null()
934                } else {
935                    mean.as_ptr()
936                },
937                if norm.is_empty() {
938                    std::ptr::null()
939                } else {
940                    norm.as_ptr()
941                },
942            )
943        })?;
944        Ok(())
945    }
946    /// Applies mean subtraction and scaling while consuming the tensor.
947    ///
948    /// Storage this crate owns is rewritten in place, so the call allocates nothing; any other
949    /// provenance copies first, which is what [`normalized`](Self::normalized) always does. Use
950    /// this form when the tensor is the caller's last reference and the request only needs the
951    /// normalized values.
952    pub fn into_normalized(mut self, mean: &[f32], norm: &[f32]) -> Result<Self> {
953        if self.provenance == Provenance::Owned {
954            self.normalize_in_place(mean, norm)?;
955            return Ok(self);
956        }
957        self.normalized(mean, norm)
958    }
959    fn ensure_writable(&self, operation: &'static str) -> Result<()> {
960        if self.provenance != Provenance::Owned {
961            return Err(Error::invalid(format!(
962                "{operation} writes through the tensor, so it needs storage this tensor owns; copy it with deep_clone first"
963            )));
964        }
965        Ok(())
966    }
967
968    // --- Pixels ---
969    /// Converts unpacked FP32 planes into interleaved pixels.
970    ///
971    /// `stride` is the destination distance between rows in bytes and must cover
972    /// `width * format.channels()`. `out` must hold `stride * height` bytes; the remaining bytes of
973    /// a wider stride stay untouched.
974    pub fn to_pixels(&self, format: PixelFormat, stride: usize, out: &mut [u8]) -> Result<()> {
975        let (width, height) = self.pixel_layout(format)?;
976        let row = (width as usize)
977            .checked_mul(format.channels())
978            .ok_or(Error::invalid("Pixel row overflows"))?;
979        if stride < row {
980            return Err(Error::invalid("Pixel stride is shorter than one row"));
981        }
982        let needed = stride
983            .checked_mul(height as usize)
984            .ok_or(Error::invalid("Pixel buffer overflows"))?;
985        if out.len() < needed {
986            return Err(Error::invalid("Pixel buffer is too small for the stride"));
987        }
988        unsafe {
989            sys::ncnn_mat_to_pixels(
990                self.raw,
991                out.as_mut_ptr(),
992                format as i32,
993                i32::try_from(stride)
994                    .map_err(|_| Error::invalid("Pixel stride exceeds native range"))?,
995            );
996        }
997        Ok(())
998    }
999    /// Converts unpacked FP32 planes into interleaved pixels of another size.
1000    ///
1001    /// The resize uses the native bilinear path. Buffer requirements match
1002    /// [`to_pixels`](Self::to_pixels) with the target width and height.
1003    pub fn to_pixels_resize(
1004        &self,
1005        format: PixelFormat,
1006        target: (usize, usize),
1007        stride: usize,
1008        out: &mut [u8],
1009    ) -> Result<()> {
1010        self.pixel_layout(format)?;
1011        if target.0 == 0
1012            || target.1 == 0
1013            || target.0 > i32::MAX as usize
1014            || target.1 > i32::MAX as usize
1015        {
1016            return Err(Error::invalid("Invalid target size"));
1017        }
1018        let row = target
1019            .0
1020            .checked_mul(format.channels())
1021            .ok_or(Error::invalid("Pixel row overflows"))?;
1022        if stride < row {
1023            return Err(Error::invalid("Pixel stride is shorter than one row"));
1024        }
1025        let needed = stride
1026            .checked_mul(target.1)
1027            .ok_or(Error::invalid("Pixel buffer overflows"))?;
1028        if out.len() < needed {
1029            return Err(Error::invalid("Pixel buffer is too small for the stride"));
1030        }
1031        unsafe {
1032            sys::ncnn_mat_to_pixels_resize(
1033                self.raw,
1034                out.as_mut_ptr(),
1035                format as i32,
1036                i32::try_from(target.0)
1037                    .map_err(|_| Error::invalid("Target width exceeds native range"))?,
1038                i32::try_from(target.1)
1039                    .map_err(|_| Error::invalid("Target height exceeds native range"))?,
1040                i32::try_from(stride)
1041                    .map_err(|_| Error::invalid("Pixel stride exceeds native range"))?,
1042            );
1043        }
1044        Ok(())
1045    }
1046    fn pixel_layout(&self, format: PixelFormat) -> Result<(i32, i32)> {
1047        let (info, _) = self.f32_layout()?;
1048        if info.c as usize != format.channels() {
1049            return Err(Error::invalid(format!(
1050                "Pixel conversion of a {} channel tensor into a {} channel format",
1051                info.c,
1052                format.channels()
1053            )));
1054        }
1055        if info.d != 1 {
1056            return Err(Error::invalid(
1057                "Pixel conversion needs a single-plane tensor",
1058            ));
1059        }
1060        Ok((info.w, info.h))
1061    }
1062
1063    // --- Borders ---
1064    /// Adds a border around every plane with the native padding kernel.
1065    ///
1066    /// This is the letterbox step: the native kernel writes the border instead of a Rust-side loop.
1067    /// The tensor must be a 2-D or 3-D unpacked single-batch tensor, and the result keeps the
1068    /// element width and the rank of `self`.
1069    pub fn copy_make_border(
1070        &self,
1071        top: usize,
1072        bottom: usize,
1073        left: usize,
1074        right: usize,
1075        mode: BorderMode,
1076        value: f32,
1077    ) -> Result<Self> {
1078        let info = self.plane_layout("Border padding")?;
1079        padded(info.w, left, right, "Border padding")?;
1080        padded(info.h, top, bottom, "Border padding")?;
1081        let raw = unsafe { sys::ncnn_mat_create() };
1082        if raw.is_null() {
1083            return Err(Error::Native(-100));
1084        }
1085        unsafe {
1086            sys::ncnn_copy_make_border(
1087                self.raw,
1088                raw,
1089                native_extent(top, "Border padding")?,
1090                native_extent(bottom, "Border padding")?,
1091                native_extent(left, "Border padding")?,
1092                native_extent(right, "Border padding")?,
1093                mode as i32,
1094                value,
1095                std::ptr::null_mut(),
1096            );
1097            Self::owned(raw, self.f32_known)
1098        }
1099    }
1100    /// Removes rows and columns from every plane.
1101    ///
1102    /// The crop runs on the native kernel and keeps the remaining storage layout, which is the
1103    /// detection-side counterpart of [`copy_make_border`](Self::copy_make_border). Requirements
1104    /// match that method, and the crop keeps at least one row and one column.
1105    pub fn copy_cut_border(
1106        &self,
1107        top: usize,
1108        bottom: usize,
1109        left: usize,
1110        right: usize,
1111    ) -> Result<Self> {
1112        let info = self.plane_layout("Border crop")?;
1113        if left.saturating_add(right) >= info.w as usize
1114            || top.saturating_add(bottom) >= info.h as usize
1115        {
1116            return Err(Error::invalid(
1117                "Border crop removes every row or column of the tensor",
1118            ));
1119        }
1120        let raw = unsafe { sys::ncnn_mat_create() };
1121        if raw.is_null() {
1122            return Err(Error::Native(-100));
1123        }
1124        unsafe {
1125            sys::ncnn_copy_cut_border(
1126                self.raw,
1127                raw,
1128                native_extent(top, "Border crop")?,
1129                native_extent(bottom, "Border crop")?,
1130                native_extent(left, "Border crop")?,
1131                native_extent(right, "Border crop")?,
1132                std::ptr::null_mut(),
1133            );
1134            Self::owned(raw, self.f32_known)
1135        }
1136    }
1137    /// Adds a border around a 4-D tensor, including the depth sides.
1138    ///
1139    /// The native 3-D padding kernel pads width, height and depth, which is what a 3-D convolution
1140    /// graph needs. Requirements match [`copy_make_border`](Self::copy_make_border), and the tensor
1141    /// must carry all four axes.
1142    pub fn copy_make_border_3d(
1143        &self,
1144        borders: Borders,
1145        mode: BorderMode,
1146        value: f32,
1147    ) -> Result<Self> {
1148        let info = self.volume_layout("3-D border padding")?;
1149        padded(info.w, borders.left, borders.right, "3-D border padding")?;
1150        padded(info.h, borders.top, borders.bottom, "3-D border padding")?;
1151        padded(info.d, borders.front, borders.behind, "3-D border padding")?;
1152        let raw = unsafe { sys::ncnn_mat_create() };
1153        if raw.is_null() {
1154            return Err(Error::Native(-100));
1155        }
1156        unsafe {
1157            sys::ncnn_copy_make_border_3d(
1158                self.raw,
1159                raw,
1160                native_extent(borders.top, "3-D border padding")?,
1161                native_extent(borders.bottom, "3-D border padding")?,
1162                native_extent(borders.left, "3-D border padding")?,
1163                native_extent(borders.right, "3-D border padding")?,
1164                native_extent(borders.front, "3-D border padding")?,
1165                native_extent(borders.behind, "3-D border padding")?,
1166                mode as i32,
1167                value,
1168                std::ptr::null_mut(),
1169            );
1170            Self::owned(raw, self.f32_known)
1171        }
1172    }
1173    /// Removes rows, columns and depth slices from a 4-D tensor.
1174    ///
1175    /// This is the depth counterpart of [`copy_cut_border`](Self::copy_cut_border) and keeps at
1176    /// least one element on every axis.
1177    pub fn copy_cut_border_3d(&self, borders: Borders) -> Result<Self> {
1178        let info = self.volume_layout("3-D border crop")?;
1179        if borders.left.saturating_add(borders.right) >= info.w as usize
1180            || borders.top.saturating_add(borders.bottom) >= info.h as usize
1181            || borders.front.saturating_add(borders.behind) >= info.d as usize
1182        {
1183            return Err(Error::invalid(
1184                "3-D border crop removes every element of an axis",
1185            ));
1186        }
1187        let raw = unsafe { sys::ncnn_mat_create() };
1188        if raw.is_null() {
1189            return Err(Error::Native(-100));
1190        }
1191        unsafe {
1192            sys::ncnn_copy_cut_border_3d(
1193                self.raw,
1194                raw,
1195                native_extent(borders.top, "3-D border crop")?,
1196                native_extent(borders.bottom, "3-D border crop")?,
1197                native_extent(borders.left, "3-D border crop")?,
1198                native_extent(borders.right, "3-D border crop")?,
1199                native_extent(borders.front, "3-D border crop")?,
1200                native_extent(borders.behind, "3-D border crop")?,
1201                std::ptr::null_mut(),
1202            );
1203            Self::owned(raw, self.f32_known)
1204        }
1205    }
1206    fn volume_layout(&self, operation: &str) -> Result<TensorInfo> {
1207        let info = self.info();
1208        if info.dims != 4 || info.elempack != 1 || info.n != 1 || info.c <= 0 {
1209            return Err(Error::invalid(format!(
1210                "{operation} needs a 4-D unpacked single-batch tensor"
1211            )));
1212        }
1213        Ok(info)
1214    }
1215    fn plane_layout(&self, operation: &str) -> Result<TensorInfo> {
1216        let info = self.info();
1217        if !(2..=3).contains(&info.dims) || info.elempack != 1 || info.n != 1 || info.c <= 0 {
1218            return Err(Error::invalid(format!(
1219                "{operation} needs a 2-D or 3-D unpacked single-batch tensor"
1220            )));
1221        }
1222        Ok(info)
1223    }
1224
1225    // --- Raw escape ---
1226    /// Borrows the native handle without transferring ownership.
1227    ///
1228    /// Unsafe native writers must preserve Rust tensor borrows, including output
1229    /// guard borrows if this storage is later transferred with `input_owned`.
1230    /// Returns the native handle. The caller keeps it alive exactly as long as this Mat.
1231    pub fn as_raw(&self) -> sys::ncnn_mat_t {
1232        self.raw
1233    }
1234    /// Releases the Rust handle and transfers release responsibility to the caller.
1235    pub fn into_raw(self) -> sys::ncnn_mat_t {
1236        let raw = self.raw;
1237        std::mem::forget(self);
1238        raw
1239    }
1240    /// Takes ownership of a native tensor with independent storage dependencies.
1241    ///
1242    /// # Safety
1243    /// The handle must be uniquely owned, valid and backed by initialized logical
1244    /// elements. Its allocator must outlive this object. Native writers respect Rust
1245    /// tensor-view borrows. `f32_known` asserts FP32 semantics. Consuming input methods
1246    /// copy adopted storage so borrowed native dependencies keep their original lifetime.
1247    pub unsafe fn from_raw_owned(raw: sys::ncnn_mat_t, f32_known: bool) -> Result<Self> {
1248        let mut mat = Self::owned(raw, f32_known)?;
1249        mat.provenance = Provenance::Adopted;
1250        Ok(mat)
1251    }
1252}
1253/// A read-only alias of part of a tensor.
1254///
1255/// A view shares the source storage: it neither copies nor extends the source's lifetime, so it
1256/// borrows the tensor it came from and cannot be transferred into an extractor. Submitting one
1257/// through [`Extractor::input`](crate::Extractor::input) copies, because an alias keeps no storage
1258/// of its own.
1259pub struct MatView<'a> {
1260    mat: Mat,
1261    _source: &'a Mat,
1262}
1263impl MatView<'_> {
1264    /// Returns the borrowed tensor metadata.
1265    pub fn info(&self) -> TensorInfo {
1266        self.mat.info()
1267    }
1268    /// Borrows the aliased tensor.
1269    ///
1270    /// The tensor keeps no storage of its own, so it cannot be transferred into an extractor, and
1271    /// submitting it through [`Extractor::input`](crate::Extractor::input) copies. The borrowed
1272    /// form accepts it without a copy: [`Input::view`](crate::Input::view) bounds
1273    /// the borrow to one request, and
1274    /// [`Extractor::input_borrowed`](crate::Extractor::input_borrowed) carries the lifetime rules
1275    /// of every other borrowed input, which requires light mode off.
1276    pub fn as_mat(&self) -> &Mat {
1277        &self.mat
1278    }
1279    /// Reports whether the region holds no elements.
1280    pub fn is_empty(&self) -> bool {
1281        self.mat.is_empty()
1282    }
1283    /// Borrows contiguous FP32 storage without padding.
1284    pub fn as_f32_slice(&self) -> Result<&[f32]> {
1285        self.mat.as_f32_slice()
1286    }
1287    /// Borrows one channel of this region, skipping inter-channel padding.
1288    pub fn channel_f32(&self, channel: usize) -> Result<&[f32]> {
1289        self.mat.channel_f32(channel)
1290    }
1291    /// Copies logical FP32 elements into a new vector.
1292    pub fn to_f32(&self) -> Result<Vec<f32>> {
1293        self.mat.to_f32()
1294    }
1295    /// Replaces the vector contents with logical FP32 elements.
1296    pub fn to_f32_into(&self, buffer: &mut Vec<f32>) -> Result<()> {
1297        self.mat.to_f32_into(buffer)
1298    }
1299    /// Copies the region into a tensor with independent storage.
1300    pub fn deep_clone(&self) -> Result<Mat> {
1301        self.mat.deep_clone()
1302    }
1303}
1304/// A read-only reshape retaining its source and allocator provenance.
1305/// It cannot be transferred into an extractor or exported as a native handle.
1306pub struct ReshapeView<'a> {
1307    mat: Mat,
1308    _source: &'a Mat,
1309}
1310impl ReshapeView<'_> {
1311    /// Returns the borrowed tensor metadata.
1312    pub fn info(&self) -> TensorInfo {
1313        self.mat.info()
1314    }
1315    /// Copies logical FP32 elements into a new vector.
1316    pub fn to_f32(&self) -> Result<Vec<f32>> {
1317        self.mat.to_f32()
1318    }
1319    /// Borrows contiguous FP32 storage without padding.
1320    pub fn as_f32_slice(&self) -> Result<&[f32]> {
1321        self.mat.as_f32_slice()
1322    }
1323    /// Borrows one channel, skipping inter-channel padding.
1324    pub fn channel_f32(&self, channel: usize) -> Result<&[f32]> {
1325        self.mat.channel_f32(channel)
1326    }
1327    /// Replaces the vector contents with logical FP32 elements.
1328    pub fn to_f32_into(&self, buffer: &mut Vec<f32>) -> Result<()> {
1329        self.mat.to_f32_into(buffer)
1330    }
1331}
1332impl Drop for Mat {
1333    fn drop(&mut self) {
1334        unsafe {
1335            sys::ncnn_mat_destroy(self.raw);
1336        }
1337    }
1338}