Skip to main content

BorrowedTensor

Struct BorrowedTensor 

Source
pub struct BorrowedTensor<'a> { /* private fields */ }
Expand description

A TensorDyn borrowed from a raw handle the caller keeps owning, returned by TensorDyn::borrow_raw.

Dropping it releases nothing: the handle is the tensor itself.

Methods from Deref<Target = TensorDyn>§

Source

pub fn as_typed<T: Element>(&self) -> Option<&Tensor<T>>

Borrow this tensor as a statically-typed Tensor<T>, or None when the element type does not match.

Source

pub fn as_typed_mut<T: Element>(&mut self) -> Option<&mut Tensor<T>>

Mutably borrow this tensor as a statically-typed Tensor<T>, or None when the element type does not match.

Source

pub fn dtype(&self) -> DType

Return the runtime element type discriminant.

Source

pub fn pin_host(&self, access: CpuAccess) -> Result<HostPin<'static>>

Return the tensor shape. Cross-package protocol descriptor (see crate::protocol).

This is the contract between independently-linked EdgeFirst packages: they cannot share a Rust or PyO3 type, so they exchange this instead. Pin a stable host address for this tensor’s data.

See Tensor::pin_host. Dispatches to the concrete element type behind the erasure. Returns a 'static pin.

TensorDyn erases to a fixed set of concrete numeric element types, all of which are 'static, so the keepalive genuinely can outlive any borrow — which is what lets a pin cross into a PyCapsule handed to Python. Eliding to &self’s lifetime here would make the pin escape its own producer.

Source

pub fn map_bytes(&self, access: CpuAccess) -> Result<HostView<'static, u8>>

Map this tensor’s whole extent for CPU access, type-erased to raw bytes. Returns a 'static view.

TensorDyn has no byte-level counterpart to TensorTrait::map_with — every typed Tensor<T> maps to HostView<'_, T>, and a type-erased caller (a C ABI consumer, which does not know T) cannot use that. This dispatches exactly the way pin_host and the other dispatch! accessors above do — one arm per concrete element type, calling the same TensorTrait::map_with each typed Tensor<T> already implements (with its declared-vs-requested telemetry, row-stride bookkeeping, and plane-offset handling intact) — then re-views the resulting HostView<'_, T> as HostView<'_, u8> via HostView::into_bytes, which keeps the same underlying pin (so the same platform sync bracket still runs on Drop) and just restates element count as byte count.

The 'static lifetime is the same story as pin_host: map_with’s 'a is a free parameter bounding how long the backing allocation lives, not a borrow of self — the returned view shares ownership through its pin’s keepalive Arc, never a reference into this tensor — and TensorDyn erases to a fixed set of concrete element types that are all 'static, so nothing stops choosing 'a = 'static here. Eliding to &self’s lifetime instead would tie the view to this call’s borrow for no reason, forcing every caller (a C ABI entry point chief among them) into an artificial self-referential shape to hold onto it past this function returning.

§Errors

Same as map_with: Error::InvalidArgument for CpuAccess::None, plus whatever the concrete backend’s map can fail with (capacity, stride, or platform-lock errors).

Source

pub fn try_map_bytes(&self, access: CpuAccess) -> Result<HostView<'static, u8>>

Non-blocking map_bytes: returns Err(Error::IoError(WouldBlock)) while a GPU copy the map depends on is still in flight, and makes progress on a retry. Dispatches to each typed tensor’s TensorTrait::try_map_with, which aliases map_with for every backing but the Windows D3D11 texture.

Source

pub fn sync_for_cpu(&self, access: CpuAccess) -> Result<()>

Source

pub fn sync_for_device(&self, access: CpuAccess) -> Result<()>

Source

pub fn descriptor(&self) -> TensorDesc

Source

pub fn descriptor_pinned(&self, pin: Option<&HostPin<'_>>) -> TensorDesc

Descriptor carrying a pinned host address.

A bare descriptor is descriptive only: a consumer learns the shape, format and backing kind but cannot reach the bytes. Supplying a HostPin fills in ptr, and the caller is responsible for keeping that pin alive at least as long as the descriptor is used — which is what the capsule keepalive does.

Source

pub fn shape(&self) -> &[usize]

Source

pub fn set_logical_shape(&mut self, shape: &[usize]) -> Result<()>

Set the logical shape to any shape whose bytes fit the allocation, without reshape’s equal-count constraint. See crate::TensorTrait::set_logical_shape.

Source

pub fn capacity_bytes(&self) -> usize

Source

pub fn name(&self) -> String

Return the tensor name.

Source

pub fn format(&self) -> Option<PixelFormat>

Return the pixel format (None if not an image tensor).

Source

pub fn width(&self) -> Option<usize>

Return the image width (None if not an image tensor).

Source

pub fn height(&self) -> Option<usize>

Return the image height (None if not an image tensor).

Source

pub fn size(&self) -> usize

Return the total size of this tensor in bytes.

Source

pub fn set_dtype(&mut self, dtype: DType) -> Result<()>

Retag this tensor’s element type, keeping its bytes untouched.

The recorded dtype is metadata over the same allocation: U8 and I8 address identical bytes and differ only in how a consumer reads them. edgefirst-image relies on exactly that – a PBO or DMA buffer is allocated as u8 and handed back as i8, with the int8 shader applying an XOR 0x80 bias over the same buffer.

Refuses a dtype of a different width. That is not a retag but a reinterpretation: len() and size() are derived from the shape and the element width, so widening or narrowing here would silently change how many elements the tensor claims to hold over an allocation whose size did not change.

§Errors

crate::Error::InvalidArgument when dtype.size() differs from the current dtype’s. The tensor is left untouched.

Source

pub fn memory(&self) -> TensorMemory

Return the memory allocation type.

Source

pub fn cpu_access(&self) -> CpuAccess

The CPU access declared for this tensor at allocation.

See Tensor::cpu_access; dispatches to the concrete element type behind the erasure, the same way memory and dtype do. .writes() on the result is the declaration query a type-erased caller (a C ABI consumer deciding whether a writable map is allowed) needs before mapping – unlike TensorMapTrait::is_writable, which answers a different question about an already-open map guard (“was this particular mapping opened writable”), this answers it about the tensor itself, before any map exists.

Source

pub fn restrict_cpu_access(&mut self, access: CpuAccess)

Source

pub fn reshape(&mut self, shape: &[usize]) -> Result<()>

Reshape this tensor. Total element count must remain the same.

Source

pub fn set_format(&mut self, format: PixelFormat) -> Result<()>

Attach pixel format metadata to this tensor.

Validates that the tensor’s shape is compatible with the format’s layout (packed, planar, or semi-planar).

§Arguments
  • format - The pixel format to attach
§Returns

Ok(()) on success, with the format stored as metadata on the tensor.

§Errors

Returns Error::InvalidShape if the tensor shape doesn’t match the expected layout for the given format.

Source

pub fn colorimetry(&self) -> Option<Colorimetry>

Colorimetry metadata (None = undefined; never auto-filled).

Source

pub fn set_colorimetry(&mut self, c: Option<Colorimetry>)

Attach/clear colorimetry metadata.

Source

pub fn row_stride(&self) -> Option<usize>

Row stride in bytes (None = tightly packed).

Source

pub fn effective_row_stride(&self) -> Option<usize>

Effective row stride: stored stride or computed from format and width.

Source

pub fn configure_image( &mut self, width: usize, height: usize, format: PixelFormat, ) -> Result<()>

Set logical dimensions + format to a decoded image, reusing the allocation. See Tensor::configure_image.

Source

pub fn set_row_stride(&mut self, stride: usize) -> Result<()>

Set the row stride in bytes for externally allocated buffers with row padding.

Must be called before the tensor is first used for rendering. The format must be set before calling this method.

Source

pub fn set_row_stride_unchecked(&mut self, stride: usize)

Set the row stride in bytes without format validation. See Tensor::set_row_stride_unchecked. Added for tensor-capi’s ef_tensor_set_row_stride_unchecked (task 17): the dynamic backend needs a type-erased entry point the same way Self::set_row_stride already gives it one for the checked setter.

Source

pub fn plane_offset(&self) -> Option<usize>

Byte offset within the DMA-BUF where image data starts (None = 0).

Source

pub fn view_origin(&self) -> Option<ViewOrigin>

The parent-image snapshot if this tensor is a view/ batch sub-region; None for a whole tensor. See Tensor::view_origin.

Source

pub fn is_view(&self) -> bool

Source

pub fn mark_view(&mut self)

Source

pub fn set_plane_offset(&mut self, offset: usize)

Set the byte offset within the DMA-BUF where image data starts.

Source

pub fn batch(&self, n: usize) -> Result<TensorDyn>

Borrow batch element n of a batched tensor (leading N dimension) as a zero-copy view sharing this tensor’s allocation. See Tensor::batch.

Source

pub fn view(&self, region: Region) -> Result<TensorDyn>

Borrow a rectangular spatial sub-region (the destination/source crop) as a zero-copy view sharing this tensor’s allocation. See Tensor::view.

Source

pub fn cuda(&self) -> Option<&CudaHandle>

The CUDA registration for this tensor, if any.

Returns None when no CUDA handle has been attached (the common non-CUDA case). This check is a pure local field read — no thread routing occurs.

Source

pub fn cuda_map(&self) -> Option<CudaMap<'_>>

Fast-fail CUDA map: None when no handle is attached; else maps the PBO through the GL worker and returns a scoped device-pointer guard.

The same try-cuda_map-then-map fallback pattern that applies to Tensor::cuda_map applies here: call cuda_map() first for a zero-copy device pointer; when it returns None (no CUDA handle attached), fall back to the typed host mapping via the inner tensor.

§Example
use edgefirst_tensor::TensorDyn;
if let Some(cuda) = t.cuda_map() {
    feed_tensorrt(cuda.device_ptr(), cuda.len());
} else {
    // No CUDA handle — use the typed inner tensor for host access.
    // See Tensor::cuda_map for the full fallback example.
}
Source

pub fn cuda_map_mut(&self) -> Option<CudaMap<'_>>

Writable counterpart of cuda_map. See CudaHandle::map_mut for which backings distinguish the two.

Source

pub fn set_cuda_handle(&mut self, h: CudaHandle)

Attach a CUDA handle (PBO cudaGraphicsGLRegisterBuffer).

Source

pub fn is_cuda_attached(&self) -> bool

Whether a CUDA registration is attached.

Source

pub fn quantization(&self) -> Option<&Quantization>

Quantization metadata. Returns None for float variants (F16, F32, F64) — quantization does not apply to floating-point tensors. Otherwise delegates to the typed Tensor<T>::quantization() accessor.

Source

pub fn set_quantization(&mut self, q: Quantization) -> Result<()>

Attach quantization metadata. Fails on float variants with crate::Error::QuantizationInvalid; delegates to the typed setter for integer variants.

Source

pub fn clear_quantization(&mut self)

Clear any quantization metadata. No-op on float variants.

Source

pub fn clone_fd(&self) -> Result<OwnedFd>

Clone the file descriptor associated with this tensor.

Source

pub fn dmabuf_clone(&self) -> Result<OwnedFd>

Clone the DMA-BUF file descriptor backing this tensor (Linux only).

§Returns

An owned duplicate of the DMA-BUF file descriptor.

§Errors
  • Error::NotImplemented if the tensor is not DMA-backed (Mem/Shm/Pbo)
  • Error::IoError if the fd clone syscall fails (e.g., fd limit reached)
Source

pub fn dmabuf(&self) -> Result<BorrowedFd<'_>>

Borrow the DMA-BUF file descriptor backing this tensor (Linux only).

§Returns

A borrowed reference to the DMA-BUF file descriptor, tied to self’s lifetime.

§Errors
  • Error::NotImplemented if the tensor is not DMA-backed
Source

pub fn is_multiplane(&self) -> bool

Return true if this tensor uses separate plane allocations.

Source

pub fn chroma_dyn(&self) -> Option<TensorDyn>

Owned chroma plane as its own TensorDyn, or None if this is not a two-allocation semi-planar tensor.

Source

pub fn buffer_identity(&self) -> &BufferIdentity

Return the BufferIdentity of the underlying allocation.

Two TensorDyn values share a crate::BufferIdentity::id iff they were produced by cloning the same allocation (e.g. through DmaTensor::try_clone). Separate imports of the same physical buffer (e.g. two from_fd calls on the same dmabuf fd) have distinct identities — use aliases if you need to detect that case.

Source

pub fn aliases(&self, other: &Self) -> bool

Return true if self and other reference the same underlying buffer.

This is the correct check for APIs that require distinct input and output tensors (e.g. ImageProcessor::draw_decoded_masks, where aliasing dst and background would cause the GL backend to read and write the same texture — undefined behaviour on most drivers).

Matching is conservative:

  1. Matching crate::BufferIdentity::id → same buffer (always).
  2. Matching backing type + matching dmabuf fd number (Linux, DMA tensors only) → same buffer, even across separate from_fd imports in the same process.

Two distinct dup’d fds pointing at the same kernel dma-buf are not detected — there is no cheap way to resolve that without a round-trip through the kernel.

Source

pub fn as_u8(&self) -> Option<&Tensor<u8>>

Returns a shared reference to the inner tensor if the type matches.

Source

pub fn as_u8_mut(&mut self) -> Option<&mut Tensor<u8>>

Returns a mutable reference to the inner tensor if the type matches.

Source

pub fn as_i8(&self) -> Option<&Tensor<i8>>

Returns a shared reference to the inner tensor if the type matches.

Source

pub fn as_i8_mut(&mut self) -> Option<&mut Tensor<i8>>

Returns a mutable reference to the inner tensor if the type matches.

Source

pub fn as_u16(&self) -> Option<&Tensor<u16>>

Returns a shared reference to the inner tensor if the type matches.

Source

pub fn as_u16_mut(&mut self) -> Option<&mut Tensor<u16>>

Returns a mutable reference to the inner tensor if the type matches.

Source

pub fn as_i16(&self) -> Option<&Tensor<i16>>

Returns a shared reference to the inner tensor if the type matches.

Source

pub fn as_i16_mut(&mut self) -> Option<&mut Tensor<i16>>

Returns a mutable reference to the inner tensor if the type matches.

Source

pub fn as_u32(&self) -> Option<&Tensor<u32>>

Returns a shared reference to the inner tensor if the type matches.

Source

pub fn as_u32_mut(&mut self) -> Option<&mut Tensor<u32>>

Returns a mutable reference to the inner tensor if the type matches.

Source

pub fn as_i32(&self) -> Option<&Tensor<i32>>

Returns a shared reference to the inner tensor if the type matches.

Source

pub fn as_i32_mut(&mut self) -> Option<&mut Tensor<i32>>

Returns a mutable reference to the inner tensor if the type matches.

Source

pub fn as_u64(&self) -> Option<&Tensor<u64>>

Returns a shared reference to the inner tensor if the type matches.

Source

pub fn as_u64_mut(&mut self) -> Option<&mut Tensor<u64>>

Returns a mutable reference to the inner tensor if the type matches.

Source

pub fn as_i64(&self) -> Option<&Tensor<i64>>

Returns a shared reference to the inner tensor if the type matches.

Source

pub fn as_i64_mut(&mut self) -> Option<&mut Tensor<i64>>

Returns a mutable reference to the inner tensor if the type matches.

Source

pub fn as_f16(&self) -> Option<&Tensor<f16>>

Returns a shared reference to the inner tensor if the type matches.

Source

pub fn as_f16_mut(&mut self) -> Option<&mut Tensor<f16>>

Returns a mutable reference to the inner tensor if the type matches.

Source

pub fn as_f32(&self) -> Option<&Tensor<f32>>

Returns a shared reference to the inner tensor if the type matches.

Source

pub fn as_f32_mut(&mut self) -> Option<&mut Tensor<f32>>

Returns a mutable reference to the inner tensor if the type matches.

Source

pub fn as_f64(&self) -> Option<&Tensor<f64>>

Returns a shared reference to the inner tensor if the type matches.

Source

pub fn as_f64_mut(&mut self) -> Option<&mut Tensor<f64>>

Returns a mutable reference to the inner tensor if the type matches.

Source

pub fn pbo_id(&self) -> Option<u32>

GL buffer ID for this PBO. Returns None when the tensor is not PBO-backed.

Source

pub fn pbo_is_mapped(&self) -> Option<bool>

Whether this PBO currently holds (or is establishing) a CPU mapping. None when the tensor is not PBO-backed. See crate::Tensor::pbo_is_mapped.

Source

pub fn pbo_vtable_ptr(&self) -> Option<*const c_void>

The C-ABI PboOpsVtable address for this PBO, for cross-cdylib export via crate::TensorDesc::ptr (see that field’s doc comment). Returns None when the tensor is not PBO-backed.

Source

pub fn pbo_keepalive(&self) -> Option<Arc<dyn Send + Sync>>

A type-erased keepalive that must stay alive for at least as long as Self::pbo_vtable_ptr’s address is used. None when the tensor is not PBO-backed. See crate::pbo::PboTensor::pbo_keepalive’s own doc comment.

Source

pub fn gpu_write_value(&self) -> u64

The fence value of the newest GPU write recorded on this tensor, or 0 when there is none; every platform, 0 off Windows. See Tensor::gpu_write_value.

Source

pub fn copy_to_flat(&self, dst: &mut [u8]) -> Result<()>

Copy the tensor’s logical bytes into dst, compacting away any recorded row-stride padding — see Tensor::copy_to_flat for the full contract. dst.len() must equal the tight byte footprint (shape product × element size).

Source

pub fn compression(&self) -> Option<CompressionScheme>

The recorded vendor tile-compression scheme (see Tensor::compression).

Source

pub fn contiguity(&self) -> Contiguity

Whether the memory is known to be physically contiguous (see Tensor::contiguity).

Trait Implementations§

Source§

impl Debug for BorrowedTensor<'_>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for BorrowedTensor<'_>

Source§

type Target = TensorDyn

The resulting type after dereferencing.
Source§

fn deref(&self) -> &TensorDyn

Dereferences the value.
Source§

impl DerefMut for BorrowedTensor<'_>

Source§

fn deref_mut(&mut self) -> &mut TensorDyn

Mutably dereferences the value.
Source§

impl Send for BorrowedTensor<'_>

Source§

impl Sync for BorrowedTensor<'_>

Auto Trait Implementations§

§

impl<'a> !RefUnwindSafe for BorrowedTensor<'a>

§

impl<'a> !UnwindSafe for BorrowedTensor<'a>

§

impl<'a> Freeze for BorrowedTensor<'a>

§

impl<'a> Unpin for BorrowedTensor<'a>

§

impl<'a> UnsafeUnpin for BorrowedTensor<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more