Skip to main content

PixelBuf

Struct PixelBuf 

Source
pub struct PixelBuf { /* private fields */ }
Expand description

Owned, unparameterized, alignment-exact pixel image buffer.

Every allocating constructor is fallible and returns Result<Self, At<BufferError>>. Mutable access automatically invalidates attached SampleClaims.

Implementations§

Source§

impl PixelBuf

Source

pub fn try_clone(&self) -> Result<PixelBuf, At<BufferError>>

Fallibly clone this buffer, preserving alignment, metadata, claims, origin, and orientation.

Source

pub fn new( width: u32, height: u32, format: impl Into<PixelFormat>, ) -> Result<PixelBuf, At<BufferError>>

Fallibly allocate a tightly packed black-filled buffer backed by native sample storage.

When spec.color.alpha() == AlphaMode::Opaque, the alpha channel is initialized to canonical full opacity (255, 65535, 1.0, or packed max code) so stored pixels honor the AlphaMode::Opaque invariant immediately.

For solid opaque signal-white initialization, use new_signal_white or new_with_fill. To skip the alpha-fill pass when you will overwrite every pixel, allocate via new_raw_zeroed with AlphaMode::Straight, fill all pixels, and retag zero-copy with into_opaque_verified or assume_opaque.

Source

pub fn new_signal_white( width: u32, height: u32, format: impl Into<PixelFormat>, ) -> Result<PixelBuf, At<BufferError>>

Fallibly allocate a tightly packed buffer filled with the format’s nominal signal-white sample pattern and canonical maximum on any alpha slot.

RGB and gray use the code for nominal signal white (1.0 after range normalization). On PQ that code represents 10,000 cd/m². On display-rendered HLG it represents the selected display peak. Linear RGB uses 1.0 even when the format can store larger values.

XYZ uses the format’s white-point chromaticity at Y = 1.0. Oklab uses [1, 0, 0] and non-inverted CMYK uses zero ink. For a luminance-calibrated fill, convert from linear samples with an explicit DiffuseWhite anchor.

Source

pub fn new_aligned( width: u32, height: u32, format: impl Into<PixelFormat>, align: RowAlign, ) -> Result<PixelBuf, At<BufferError>>

Fallibly allocate a black-filled buffer with explicit row alignment (Tight, Cache64, PixelCache64, Samples(n)).

For Cache64 and PixelCache64, storage is allocated as 64-byte aligned AlignedSamples so both the first pixel and every row start land on a 64-byte boundary. When format.color.alpha() == AlphaMode::Opaque, alpha samples are initialized to full opacity.

Source

pub fn new_with_fill( width: u32, height: u32, format: impl Into<PixelFormat>, align: RowAlign, fill: BufFill, ) -> Result<PixelBuf, At<BufferError>>

Fallibly allocate a buffer with explicit row alignment and initial BufFill (Black or SignalWhite).

Source

pub fn new_raw_zeroed( width: u32, height: u32, format: impl Into<PixelFormat>, ) -> Result<PixelBuf, At<BufferError>>

Fallibly allocate raw zero-filled OS pages with no alpha-fill pass for maximum decoder/renderer write throughput.

Refuses AlphaMode::Opaque on layouts with an alpha slot with BufferError::UnverifiedOpaqueAlpha so an opaque-tagged buffer can never silently contain zero alpha. Allocate with AlphaMode::Straight, write every pixel including full alpha, then retag zero-copy via into_opaque_verified, into_opaque_filled, or assume_opaque.

Source

pub fn new_raw_zeroed_aligned( width: u32, height: u32, format: impl Into<PixelFormat>, align: RowAlign, ) -> Result<PixelBuf, At<BufferError>>

Fallibly allocate raw zero-filled aligned OS pages with no alpha-fill pass, refusing AlphaMode::Opaque on layouts with an alpha slot.

Source

pub fn new_for_interop( width: u32, height: u32, format: impl Into<PixelFormat>, target: InteropTarget, ) -> Result<PixelBuf, At<BufferError>>

Fallibly allocate tight native storage validated upfront for a zero-copy InteropTarget.

Source

pub fn from_bytes( bytes: Vec<u8>, width: u32, height: u32, format: impl Into<PixelFormat>, ) -> Result<PixelBuf, At<BufferError>>

Adopt tightly packed bytes (Vec<u8>), handling odd-address allocators safely.

  • For 1-byte sample formats (U8, I8), adopts bytes zero-copy at any address.
  • For wider samples (U16, F16, F32, F64), adopts zero-copy when the pointer happens to be sample-aligned, and fallibly copies into properly aligned native PixelStorage when the allocator returned a misaligned address (e.g. odd address).

To recover bytes intact on error, use from_bytes_recover.

Source

pub fn from_bytes_recover( bytes: Vec<u8>, width: u32, height: u32, format: impl Into<PixelFormat>, ) -> Result<PixelBuf, (At<BufferError>, Vec<u8>)>

Adopt tightly packed bytes (Vec<u8>), returning Err((err, bytes)) with the original Vec<u8> untouched on validation or allocation failure.

Source

pub fn from_typed<P>( pixels: Vec<P>, width: u32, height: u32, format: impl Into<PixelFormat>, ) -> Result<PixelBuf, At<BufferError>>
where P: TypedElement,

Adopt a tightly packed typed Vec<P> (pixels like Vec<rgb::Rgb<u16>>, arrays [u8; 3], or raw samples like Vec<f32>).

Validates that P is structurally compatible with format.layout (preventing silent reinterpretation such as Vec<i32> as RGBF32). Note that untyped integer literals (vec![255, 0, 0]) default to Vec<i32> in Rust and will be rejected for U8 layouts; annotate the first element (e.g. vec![255u8, 0, 0]) or use from_bytes. For intentional raw byte reinterpretation, use from_pod_bytes.

Zero-copy whenever align_of::<P>() == format.layout.min_alignment() and bytemuck::allocation::try_cast_vec succeeds (preserving exact deallocation alignment!). Otherwise fallibly copies into native-aligned PixelStorage.

To recover pixels intact on error, use from_typed_recover.

Source

pub fn from_typed_recover<P>( pixels: Vec<P>, width: u32, height: u32, format: impl Into<PixelFormat>, ) -> Result<PixelBuf, (At<BufferError>, Vec<P>)>
where P: TypedElement,

Adopt a tightly packed typed Vec<P>, returning Err((err, pixels)) with the original Vec<P> untouched on validation or allocation failure.

Source

pub fn from_samples<S>( samples: Vec<S>, width: u32, height: u32, format: impl Into<PixelFormat>, ) -> Result<PixelBuf, At<BufferError>>
where S: StorageSample,

Adopt a tightly packed scalar sample Vec<S> (Vec<u8>, Vec<u16>, Vec<f32>, etc.).

Source

pub fn from_pixels_with_color<P>( pixels: Vec<P>, width: u32, height: u32, color: ColorSpace, ) -> Result<PixelBuf, At<BufferError>>
where P: PixelType,

Adopt a tightly packed rgb pixel Vec<P> (Vec<rgb::Rgb<u8>>, etc.) with an explicit ColorSpace (deriving SampleLayout from P::LAYOUT).

Source

pub fn from_pod_bytes<P>( pixels: Vec<P>, width: u32, height: u32, format: impl Into<PixelFormat>, ) -> Result<PixelBuf, At<BufferError>>
where P: Pod,

Explicitly reinterpret any tightly packed Vec<P: bytemuck::Pod> in native endianness as raw pixel bytes matching format without checking element-to-layout compatibility.

Source

pub fn from_storage_parts( storage: PixelStorage, byte_offset: usize, width: u32, height: u32, stride_bytes: usize, format: impl Into<PixelFormat>, ) -> Result<PixelBuf, At<BufferError>>

Checked construction from owned PixelStorage, byte offset, dimensions, byte stride, and format with fresh default metadata (claims = NONE, hdr = empty, origin = assumed, orientation = Identity).

To restore descriptive metadata from PixelBuf::into_parts, use from_parts or from_parts_recover.

Source

pub fn from_parts(parts: PixelBufParts) -> Result<PixelBuf, At<BufferError>>

Checked reconstruction from a PixelBufParts struct (preserving hdr, origin, and orientation, starting with SampleClaims::NONE).

Because detached storage can be mutated while outside PixelBuf, reconstructed buffers never inherit pre-decomposition sample claims.

On validation failure, parts is dropped; use from_parts_recover to recover the allocation intact.

Source

pub fn from_parts_recover( parts: PixelBufParts, ) -> Result<PixelBuf, (At<BufferError>, PixelBufParts)>

Checked reconstruction from PixelBufParts, returning Err((err, parts)) with the original allocation and metadata intact on validation failure.

Starts with SampleClaims::NONE because detached storage may have been edited.

Source

pub fn from_external<S>( storage: S, width: u32, height: u32, stride_bytes: usize, format: impl Into<PixelFormat>, ) -> Result<PixelBuf, (At<BufferError>, S)>
where S: ByteStorage + Send + Sync + 'static,

Adopt an immutable external owned backing (Arc<[u8]>, Arc<[u16]>, &'static [u8], memory-mapped file wrapper, shared buffer pool handle, etc.) zero-copy.

Validates geometry and sample alignment BEFORE boxing storage; on error, returns Err((err, storage)) with zero heap allocation and storage completely untouched.

Read access (as_view, row, PixelSource) is strictly zero-copy. Requesting mutable access (as_view_mut, try_cow_view_mut, make_mut) transparently performs copy-on-write into owned aligned storage without mutating storage. Call into_external to recover S zero-copy.

Source

pub fn from_external_with_byte_offset<S>( storage: S, byte_offset: usize, width: u32, height: u32, stride_bytes: usize, format: impl Into<PixelFormat>, ) -> Result<PixelBuf, (At<BufferError>, S)>
where S: ByteStorage + Send + Sync + 'static,

Adopt an immutable external owned backing starting at byte_offset bytes zero-copy.

Returns Err((err, storage)) untouched on validation failure with zero heap allocation.

Source

pub fn from_external_mut<S>( storage: S, width: u32, height: u32, stride_bytes: usize, format: impl Into<PixelFormat>, ) -> Result<PixelBuf, (At<BufferError>, S)>
where S: ByteStorageMut + Send + Sync + 'static,

Adopt a mutable external owned backing (Box<[T]>, custom-allocator wrapper, mutable pool lease, FFI writable buffer, etc.) zero-copy for both reads and in-place writes.

Validates geometry and sample alignment BEFORE boxing storage; on error, returns Err((err, storage)) with zero heap allocation and storage completely untouched. Call into_external_mut to recover S zero-copy.

Source

pub fn from_external_mut_with_byte_offset<S>( storage: S, byte_offset: usize, width: u32, height: u32, stride_bytes: usize, format: impl Into<PixelFormat>, ) -> Result<PixelBuf, (At<BufferError>, S)>
where S: ByteStorageMut + Send + Sync + 'static,

Adopt a mutable external owned backing starting at byte_offset bytes zero-copy.

Returns Err((err, storage)) untouched on validation failure with zero heap allocation.

Source

pub const fn is_external(&self) -> bool

Whether this buffer is backed by an external owner (from_external or from_external_mut).

Source

pub const fn is_mutable_in_place(&self) -> bool

Whether mutable access modifies the current backing in place without copy-on-write.

Source

pub fn external_ref<S>(&self) -> Option<&S>
where S: 'static,

Borrow the external owner if backed by an external owner of concrete type S.

Source

pub fn into_external<S>(self) -> Result<S, PixelBuf>
where S: 'static,

Recover an immutable external owner S zero-copy; returns Err(self) untouched otherwise.

Source

pub fn into_external_mut<S>(self) -> Result<S, PixelBuf>
where S: 'static,

Recover a mutable external owner S zero-copy; returns Err(self) untouched otherwise.

Source

pub fn make_mut(&mut self) -> Result<(), At<BufferError>>

Ensure backing storage is mutable in place, fallibly promoting immutable external storage (PixelStorage::External) via copy-on-write into properly aligned owned storage.

No-op (zero copy, zero allocation) for native Vec, Aligned64, and ExternalMut buffers.

Source

pub const fn width(&self) -> u32

Width in pixels.

Source

pub const fn height(&self) -> u32

Height in rows.

Source

pub const fn stride_bytes(&self) -> usize

Stride in bytes.

Source

pub const fn row_bytes(&self) -> usize

Active bytes per row.

Source

pub const fn byte_offset(&self) -> usize

Leading byte offset inside backing storage.

Source

pub fn format(&self) -> &PixelFormat

Authoritative image specification.

Source

pub fn relabel_format( self, format: impl Into<PixelFormat>, ) -> Result<PixelBuf, At<BufferError>>

Relabel specification metadata without modifying pixel bytes, preserving numeric sample type, bit packing, and bytes_per_pixel (e.g. relabeling color space or channel order).

Rejects changes to sample type or packing (use reinterpret_bytes for deliberate raw-byte reinterpretation across sample types). Clears cached SampleClaims and resets ColorOrigin to ColorOrigin::assumed whenever format.color changes.

Source

pub fn relabel_color( self, color: ColorSpace, ) -> Result<PixelBuf, At<BufferError>>

Relabel only the color space metadata without modifying pixel bytes, keeping the exact SampleLayout.

Does not convert pixel values (use zenpixels-convert to convert colors). Resets ColorOrigin to ColorOrigin::assumed when color changes and clears cached SampleClaims when signal range, alpha mode, or color model changes.

Source

pub fn reinterpret_bytes( self, format: impl Into<PixelFormat>, ) -> Result<PixelBuf, At<BufferError>>

Deliberately reinterpret the raw pixel bytes under a new PixelFormat with identical bytes_per_pixel and satisfied sample alignment (permits changing sample type and packing, e.g. U8 ↔ I8 or U16 ↔ F16).

Does not convert pixel values. Always clears cached SampleClaims, ColorOrigin, and HdrMetadata.

Source

pub fn into_opaque_verified(self) -> Result<PixelBuf, At<BufferError>>

Scan every active pixel to verify its alpha slot equals its canonical maximum value, then retag this buffer as AlphaMode::Opaque with claims.all_opaque = true (zero copy).

Performs the full-pixel scan itself — no prior assume_claims call is required. Returns BufferError::IncompatibleLayout if the layout has no alpha slot, or BufferError::UnverifiedOpaqueAlpha if any alpha sample is not at channel maximum.

Source

pub fn into_opaque_filled(self) -> Result<PixelBuf, At<BufferError>>

Fill every active pixel’s alpha slot to its canonical maximum value and retag this buffer as AlphaMode::Opaque with claims.all_opaque = true (in place, promoting immutable external storage via copy-on-write if needed).

Source

pub fn assume_opaque(self) -> Result<PixelBuf, At<BufferError>>

Retag this buffer as AlphaMode::Opaque in O(1) without scanning pixels, asserting that the caller already filled every active alpha sample to channel maximum.

Pairs with new_raw_zeroed for maximum-speed decoder/renderer fill loops: allocate zeroed with AlphaMode::Straight, write every pixel including A = max, then call assume_opaque().

Source

pub const fn attached_claims(&self) -> SampleClaims

Read the sample claims attached to the buffer in constant time.

Source

pub fn assume_claims(&mut self, claims: SampleClaims)

Attach caller-asserted SampleClaims (caller assumes responsibility for validity; cleared on next mutable pixel access).

Source

pub fn hdr(&self) -> HdrMetadata

Descriptive HDR container metadata.

Source

pub fn hdr_ref(&self) -> Option<&HdrMetadata>

Zero-copy reference to attached non-empty HDR metadata (None if empty/unset).

Source

pub fn with_hdr(self, hdr: HdrMetadata) -> PixelBuf

Attach descriptive HDR container metadata.

Source

pub fn origin(&self) -> &ColorOrigin

Original container color provenance.

Source

pub fn with_origin(self, origin: ColorOrigin) -> PixelBuf

Attach container color provenance.

Source

pub const fn orientation(&self) -> Orientation

Pending EXIF display orientation attached to this buffer (defaults to Orientation::Identity).

Source

pub const fn display_dimensions(&self) -> (u32, u32)

Display-oriented (width, height) after applying orientation.

Source

pub const fn with_orientation(self, orientation: Orientation) -> PixelBuf

Replace the pending EXIF display orientation on this buffer.

Source

pub fn set_orientation(&mut self, orientation: Orientation)

Set the pending EXIF display orientation on this buffer in place.

Source

pub const fn compose_orientation(self, delta: Orientation) -> PixelBuf

Compose an additional display transform (including reflections) onto this buffer’s pending orientation (self.orientation.then(delta)) in O(1) without touching or copying pixels.

Source

pub fn row(&self, y: u32) -> &[u8] ⓘ

Borrow active pixel bytes for row y (len == row_bytes()).

§Panics

Panics if y >= self.height().

Source

pub fn is_contiguous(&self) -> bool

Whether rows are tightly packed (stride_bytes() == row_bytes() or height() <= 1).

Source

pub fn as_contiguous_bytes(&self) -> Option<&[u8]>

Borrow contiguous packed pixel bytes across all rows, or None if padded.

Source

pub fn row_as<P>(&self, y: u32) -> Result<&[P], At<BufferError>>
where P: TypedElement,

Zero-copy layout-checked typed slice view of row y (e.g. buf.row_as::<rgb::Rgb<u16>>(y), buf.row_as::<[f32; 3]>(y), buf.row_as::<u16>(y)).

Semantically validates P::matches_layout(self.format().layout) — rejecting mismatched sample types, mismatched channel orders (e.g. Rgba<u8> on BGRA8), and non-Full BitPacking. Use row_as_with for explicit BitPackingAccess, or row_transmute for intentional raw-POD byte reinterpretation.

Source

pub fn row_as_with<P>( &self, y: u32, packing: BitPackingAccess, ) -> Result<&[P], At<BufferError>>
where P: TypedElement,

Zero-copy layout-checked typed slice view of row y with an explicit BitPackingAccess policy (Fail or PassThrough).

Source

pub fn row_samples<S>(&self, y: u32) -> Result<&[S], At<BufferError>>
where S: StorageSample,

Zero-copy sample-checked native-endian slice view of row y (e.g. &[u16], &[f32]).

Rejects non-Full BitPacking and mismatched sample types with BufferError::IncompatibleLayout.

Source

pub fn row_samples_with<S>( &self, y: u32, packing: BitPackingAccess, ) -> Result<&[S], At<BufferError>>
where S: StorageSample,

Zero-copy sample-checked native-endian slice view of row y with an explicit BitPackingAccess policy (Fail or PassThrough).

Source

pub fn row_transmute<P>(&self, y: u32) -> Result<&[P], At<BufferError>>
where P: Pod,

Safe raw-POD byte reinterpretation of row y (bytemuck::try_cast_slice), checking only bounds, alignment, and byte divisibility without semantic layout validation.

Source

pub fn visit_rows_with_packing<S, Norm, F>( &self, mode: BitPackingRead<Norm>, f: F, ) -> Result<(), At<BufferError>>
where S: StorageSample, Norm: FnMut(BitPacking, &mut [S]), F: FnMut(u32, &[S]) -> Result<(), At<BufferError>>,

Visit every row as &[S] with an explicit BitPackingRead policy (Fail, PassThrough, or Norm(lambda)).

Source

pub fn as_contiguous_typed<P>(&self) -> Result<&[P], At<BufferError>>
where P: TypedElement,

Zero-copy layout-checked contiguous typed slice across all rows (e.g. &[rgb::Rgb<u16>], &[[f32; 3]], &[u16]).

Semantically validates P::matches_layout(self.format().layout) and tight row packing. For intentional raw-POD reinterpretation, use as_contiguous_transmute.

Source

pub fn as_contiguous_typed_with<P>( &self, packing: BitPackingAccess, ) -> Result<&[P], At<BufferError>>
where P: TypedElement,

Zero-copy layout-checked contiguous typed slice across all rows with an explicit BitPackingAccess policy (Fail or PassThrough).

Source

pub fn as_contiguous_samples<S>(&self) -> Result<&[S], At<BufferError>>
where S: StorageSample,

Zero-copy sample-checked native-endian contiguous slice across all rows (e.g. &[u16]).

Rejects padded rows, non-Full bit packing, and mismatched sample types.

Source

pub fn as_contiguous_samples_with<S>( &self, packing: BitPackingAccess, ) -> Result<&[S], At<BufferError>>
where S: StorageSample,

Zero-copy sample-checked native-endian contiguous slice across all rows with an explicit BitPackingAccess policy (Fail or PassThrough).

Source

pub fn as_contiguous_transmute<P>(&self) -> Result<&[P], At<BufferError>>
where P: Pod,

Safe raw-POD byte reinterpretation across contiguous rows (bytemuck::try_cast_slice), checking tight row packing, alignment, and byte divisibility without semantic layout checks.

Source

pub fn try_cow_row_as_mut<P>( &mut self, y: u32, ) -> Result<&mut [P], At<BufferError>>
where P: TypedElement,

Fallibly borrow a layout-checked mutable typed slice of row y (e.g. &mut [rgb::Rgb<u16>], &mut [[f32; 3]], &mut [u16]).

Rejects mismatched layouts and non-Full BitPacking before triggering CoW promotion or clearing SampleClaims.

Source

pub fn try_cow_row_as_mut_with<P>( &mut self, y: u32, packing: BitPackingAccess, ) -> Result<&mut [P], At<BufferError>>
where P: TypedElement,

Fallibly borrow a layout-checked mutable typed slice of row y with an explicit BitPackingAccess policy (Fail or PassThrough).

Source

pub fn try_cow_row_samples_mut<S>( &mut self, y: u32, ) -> Result<&mut [S], At<BufferError>>
where S: StorageSample,

Fallibly borrow a sample-checked native-endian mutable slice of row y (e.g. &mut [u16]).

Rejects non-Full BitPacking and mismatched sample types before triggering CoW promotion or clearing SampleClaims.

Source

pub fn try_cow_row_samples_mut_with<S>( &mut self, y: u32, packing: BitPackingAccess, ) -> Result<&mut [S], At<BufferError>>
where S: StorageSample,

Fallibly borrow a sample-checked native-endian mutable slice of row y with an explicit BitPackingAccess policy (Fail or PassThrough).

Source

pub fn try_cow_row_transmute_mut<P>( &mut self, y: u32, ) -> Result<&mut [P], At<BufferError>>
where P: Pod,

Fallibly borrow a safe raw-POD mutable reinterpretation of row y, copy-on-write promoting immutable external storage and clearing cached SampleClaims only once bounds, divisibility, and alignment checks pass.

Source

pub fn try_cow_contiguous_typed_mut<P>( &mut self, ) -> Result<&mut [P], At<BufferError>>
where P: TypedElement,

Fallibly borrow a layout-checked mutable contiguous typed slice across all rows (e.g. &mut [rgb::Rgba<f32>], &mut [[u16; 3]], &mut [u16]).

Rejects padded rows, mismatched layouts, and non-Full BitPacking before triggering CoW promotion or clearing SampleClaims.

Source

pub fn try_cow_contiguous_typed_mut_with<P>( &mut self, packing: BitPackingAccess, ) -> Result<&mut [P], At<BufferError>>
where P: TypedElement,

Fallibly borrow a layout-checked mutable contiguous typed slice across all rows with an explicit BitPackingAccess policy (Fail or PassThrough).

Source

pub fn try_cow_contiguous_samples_mut<S>( &mut self, ) -> Result<&mut [S], At<BufferError>>
where S: StorageSample,

Fallibly borrow a sample-checked native-endian mutable contiguous slice across all rows (e.g. &mut [u16]).

Rejects padded rows, non-Full BitPacking, and mismatched sample types before triggering CoW promotion or clearing SampleClaims.

Source

pub fn try_cow_contiguous_samples_mut_with<S>( &mut self, packing: BitPackingAccess, ) -> Result<&mut [S], At<BufferError>>
where S: StorageSample,

Fallibly borrow a sample-checked native-endian mutable contiguous slice across all rows with an explicit BitPackingAccess policy (Fail or PassThrough).

Source

pub fn try_cow_contiguous_transmute_mut<P>( &mut self, ) -> Result<&mut [P], At<BufferError>>
where P: Pod,

Fallibly borrow a safe raw-POD mutable reinterpretation across contiguous rows, copy-on-write promoting immutable external storage and clearing cached SampleClaims only once contiguity, divisibility, and alignment checks pass.

Source

pub fn mutate_rows_with_packing<S, Pre, Post, F>( &mut self, mode: BitPackingTransform<Pre, Post>, f: F, ) -> Result<(), At<BufferError>>
where S: StorageSample, Pre: FnMut(BitPacking, &mut [S]), Post: FnMut(BitPacking, &mut [S]), F: FnMut(u32, &mut [S]) -> Result<(), At<BufferError>>,

Mutate every row in place as &mut [S] with an explicit BitPackingTransform policy (Fail, PassThrough, or PrePost { norm, denorm }).

Validates S::SAMPLE_TYPE and Fail packing before copy-on-write promotion or clearing SampleClaims. For PrePost, denorm(packing, row) is guaranteed to run on every normalized row even if f returns Err or unwinds.

Source

pub fn row_mut(&mut self, y: u32) -> &mut [u8] ⓘ

Mutably borrow active pixel bytes for row y (len == row_bytes()), clearing cached SampleClaims and copy-on-write promoting immutable external storage if needed.

For fallible external-storage CoW without panicking on OOM, use buf.try_cow_view_mut()?.row_mut(y).

§Panics

Panics if y >= self.height(), or if copy-on-write promotion of immutable external storage fails to allocate.

Source

pub fn as_view(&self) -> PixelView<'_>

Borrow an immutable PixelView of the whole image (zero Arc refcount bump).

Source

pub fn try_cow_view_mut(&mut self) -> Result<PixelViewMut<'_>, At<BufferError>>

Fallibly borrow a mutable PixelViewMut, clearing cached SampleClaims and performing copy-on-write promotion of immutable external storage without panicking on OOM (zero Arc refcount bump).

Never fails merely because storage is immutable External; returns Err(BufferError::AllocationFailed) only on OOM during copy-on-write promotion.

Source

pub fn as_view_mut(&mut self) -> PixelViewMut<'_>

Borrow a mutable PixelViewMut, automatically clearing cached SampleClaims.

If backed by immutable external storage (from_external), promotes via copy-on-write; use try_cow_view_mut for fallible OOM handling.

Source

pub fn sub_rows( &self, start_y: u32, row_count: u32, ) -> Result<PixelView<'_>, At<BufferError>>

Borrow a full-width horizontal strip of row_count rows starting at start_y without copying pixels.

Source

pub fn sub_rows_mut( &mut self, start_y: u32, row_count: u32, ) -> Result<PixelViewMut<'_>, At<BufferError>>

Borrow a mutable full-width horizontal strip of row_count rows starting at start_y, automatically clearing cached SampleClaims and fallibly copy-on-write promoting immutable external storage if needed.

Source

pub fn crop_view( &self, rect: PixelRect, ) -> Result<PixelView<'_>, At<BufferError>>

Borrow a rectangular cropped subimage view without copying pixels.

Source

pub fn crop_view_mut( &mut self, rect: PixelRect, ) -> Result<PixelViewMut<'_>, At<BufferError>>

Borrow a mutable rectangular cropped subimage view without copying pixels, automatically clearing cached SampleClaims and fallibly copy-on-write promoting immutable external storage if needed.

Source

pub fn into_crop(self, rect: PixelRect) -> Result<PixelBuf, At<BufferError>>

Consume this buffer and narrow it to a rectangular crop in O(1) with zero pixel copies.

Keeps the underlying PixelStorage and row stride_bytes intact while advancing the active byte offset and narrowing (width, height). Preserves sample alignment, cached SampleClaims, HdrMetadata, ColorOrigin, and Orientation. Chain into_tight_rows afterwards to compact the cropped region into tightly packed rows if desired.

Source

pub fn mutate_with_claims<F>(&mut self, f: F) -> Result<(), At<BufferError>>

Mutate pixels in place with access to the starting SampleClaims, atomically committing the resulting SampleClaims returned by f.

Unlike try_cow_view_mut (which clears SampleClaims eagerly before returning &mut), this scoped helper hands (PixelViewMut<'_>, old_claims) to the closure so in-place algorithms can skip unnecessary work (e.g. skipping alpha normalization when old_claims.all_opaque is already true) and propagate output claims without rescanning.

Panic & error safety: self.claims is cleared to SampleClaims::NONE before invoking f. If f returns Err(_) or panics, cached claims remain cleared rather than stale. If copy-on-write promotion fails (BufferError::AllocationFailed), pixels are untouched and existing claims remain intact.

Source

pub fn transform_in_place<F>(&mut self, f: F) -> Result<(), At<BufferError>>

Atomically transform this buffer’s bytes and metadata in place with zero reallocation.

The closure receives (active_bytes, input) where active_bytes starts at pixel (0, 0) and input.claims carries the buffer’s starting SampleClaims. Return InPlaceTransformDecision::Updated to validate and atomically adopt the new stride/format/origin/claims against existing storage, or InPlaceTransformDecision::Unchanged (asserting pixel bytes were not modified) to keep existing metadata and claims intact.

Panic & error safety: self.claims is cleared to SampleClaims::NONE before invoking f so a panic or post-transform metadata validation error never leaves stale claims behind.

Source

pub fn into_tight_rows(self) -> Result<PixelBuf, At<BufferError>>

Fallibly compact strided rows into tight row packing (stride_bytes() == row_bytes()).

Compacts in place inside the existing allocation for owned mutable storage; promotes shared or immutable external storage via fallible copy-on-write (BufferError::AllocationFailed on OOM).

Note: preserves byte_offset() == 0 whenever the backing base pointer satisfies format().layout.min_alignment(), and otherwise retains the smallest aligned byte_offset() < min_alignment() (e.g. an odd-aligned Vec<u8> holding U16 samples) so sample alignment is never violated without reallocating.

Source

pub fn swizzle_in_place( &mut self, target_order: ChannelOrder, ) -> Result<(), At<BufferError>>

Permute equal-width color channels in place (Rgb ↔ Bgr, Rgba ↔ Bgra, Rgbx ↔ Bgrx) without reallocating for owned mutable storage (copy-on-write promotes immutable external storage via make_mut()).

Works for any unpacked sample type (U8, U16, F16, F32, etc.), preserving stride_bytes(), SampleClaims, and ColorSpace.

For lossless 4→3 padding or opaque-alpha lane drops (Rgbx/Bgrx/Opaque Rgba/Opaque Bgra → Rgb/Bgr), use drop_unused_lane_in_place. Refuses channel-count changes, packed-word layouts, and unsupported channel orders with BufferError::IncompatibleLayout.

Source

pub fn drop_unused_lane_in_place( &mut self, target_order: ChannelOrder, ) -> Result<(), At<BufferError>>

Losslessly drop a redundant 4th lane (undefined padding in Rgbx/Bgrx, or AlphaMode::Opaque in Rgba/Bgra) in place to 3-channel Rgb or Bgr, compacting active pixels within each row (copy-on-write promoting immutable external storage via make_mut()).

Keeps existing stride_bytes() unchanged (leaving trailing inter-row slack so multi-row buffers do not shift across rows; chain into_tight_rows afterwards if tight stride_bytes() == row_bytes() packing is required), clears cached SampleClaims, and updates AlphaMode::Opaque / AlphaMode::Undefined to AlphaMode::None. Refuses live alpha (Straight/Premultiplied), packed-word layouts, and unsupported source/target orders with BufferError::IncompatibleLayout.

Source

pub fn into_vec_zero_copy<P>(self) -> Result<Vec<P>, PixelBuf>
where P: Pod,

Move the backing allocation into a tightly packed Vec<P> strictly zero-copy.

Succeeds only when offset == 0, rows are contiguous, active byte length matches the backing storage length, align_of::<P>() equals the backing allocation’s exact alignment, and capacity in bytes is a multiple of size_of::<P>(). Returns Err(self) untouched otherwise.

Source

pub fn into_vec<P>(self) -> Result<Vec<P>, At<BufferError>>
where P: Pod,

Extract tightly packed pixels into Vec<P>, moving zero-copy when allocation alignment & capacity match, or fallibly copying active rows otherwise.

Never violates deallocation alignment, never drops row tails on cross-row elements, and never panics on OOM.

Source

pub fn into_parts(self) -> PixelBufParts

Decompose into owned backing storage and descriptive metadata (drops attached SampleClaims).

Source

pub fn storage(&self) -> &PixelStorage

Access underlying storage reference (for diagnostics and interop checks).

Source§

impl PixelBuf

Source

pub fn hash_with(&self, inclusions: HashInclusions) -> u64

Compute a portable, endian- and stride-independent XXH3 fingerprint of this buffer.

Source§

impl PixelBuf

Source

pub fn from_imgvec<P>( img: Img<Vec<P>>, color: ColorSpace, ) -> Result<PixelBuf, At<BufferError>>
where P: PixelType,

Adopt an [imgref::ImgVec<P>] zero-copy when tightly packed and alignment-compatible.

Source

pub fn into_imgvec_zero_copy<P>(self) -> Result<Img<Vec<P>>, PixelBuf>
where P: PixelType,

Move into an [imgref::ImgVec<P>] strictly zero-copy without copying or allocating.

Returns Err(self) completely untouched if layout, contiguity, alignment, or allocation capacity prevent a zero-copy Vec<P> cast.

Source

pub fn into_imgvec<P>(self) -> Result<Img<Vec<P>>, At<BufferError>>
where P: PixelType,

Move into an [imgref::ImgVec<P>], zero-copy when allocation alignment & capacity match.

Source§

impl PixelBuf

Source

pub fn into_image_buffer<P>( self, ) -> Result<ImageBuffer<P, Vec<<P as Pixel>::Subpixel>>, At<BufferError>>
where P: Pixel + PixelWithColorType + 'static, <P as Pixel>::Subpixel: StorageSample,

Move into an image::ImageBuffer<P, Vec<P::Subpixel>> zero-copy when layout and color match, propagating CICP color-space metadata onto the resulting ImageBuffer.

When self.format().color.alpha() == AlphaMode::Opaque and attached claims do not already assert all_opaque, canonicalizes the stored alpha channel to full opacity so image’s straight-alpha Rgba/LumaA buffer never receives non-opaque alpha samples.

Source§

impl PixelBuf

Source

pub fn from_image_buffer<P>( img: ImageBuffer<P, Vec<<P as Pixel>::Subpixel>>, ) -> Result<PixelBuf, At<BufferError>>
where P: Pixel + PixelWithColorType + 'static, <P as Pixel>::Subpixel: StorageSample,

Adopt any image::ImageBuffer<P, Vec<P::Subpixel>> zero-copy across all 10 standard formats (Luma, LumaA, Rgb, Rgba × u8/u16/f32), preserving its declared image::metadata::Cicp color space.

Source

pub fn from_image_buffer_with_color<P>( img: ImageBuffer<P, Vec<<P as Pixel>::Subpixel>>, color: ColorSpace, ) -> Result<PixelBuf, At<BufferError>>
where P: Pixel + PixelWithColorType + 'static, <P as Pixel>::Subpixel: StorageSample,

Adopt any image::ImageBuffer<P, Vec<P::Subpixel>> zero-copy with an explicit color, rejecting contradictory non-default CICP declarations.

Source

pub fn from_dynamic_image( img: DynamicImage, ) -> Result<PixelBuf, At<BufferError>>

Adopt an image::DynamicImage zero-copy across all 10 standard variants, reading its declared image::metadata::Cicp color space.

Note: image 0.25 defaults DynamicImage::color_space() to Cicp::SRGB even for ImageRgb32F/ImageRgba32F. Use from_dynamic_image_with_color when adopting untagged linear float DynamicImage buffers whose CICP was left default.

Source

pub fn from_dynamic_image_with_color( img: DynamicImage, color: ColorSpace, ) -> Result<PixelBuf, At<BufferError>>

Adopt an image::DynamicImage zero-copy across all 10 standard variants with an explicit color (e.g. ColorSpace::LINEAR_SRGB for ImageRgb32F), rejecting contradictory non-default CICP declarations.

Source

pub fn from_rgb8_image( img: ImageBuffer<Rgb<u8>, Vec<u8>>, ) -> Result<PixelBuf, At<BufferError>>

Adopt an image::RgbImage zero-copy, reading its declared image::metadata::Cicp color space.

Source

pub fn from_rgba8_image( img: ImageBuffer<Rgba<u8>, Vec<u8>>, ) -> Result<PixelBuf, At<BufferError>>

Adopt an image::RgbaImage zero-copy, reading its declared image::metadata::Cicp color space.

Source

pub fn from_rgb8_image_with_color( img: ImageBuffer<Rgb<u8>, Vec<u8>>, color: ColorSpace, ) -> Result<PixelBuf, At<BufferError>>

Adopt an image::ImageBuffer<image::Rgb<u8>, Vec<u8>> zero-copy with explicit color.

Rejects contradictory color spaces when img declares a non-default CICP space that disagrees with color (use from_rgb8_image to preserve img’s own declared CICP automatically).

Source

pub fn from_rgba8_image_with_color( img: ImageBuffer<Rgba<u8>, Vec<u8>>, color: ColorSpace, ) -> Result<PixelBuf, At<BufferError>>

Adopt an image::ImageBuffer<image::Rgba<u8>, Vec<u8>> zero-copy with explicit color.

Rejects contradictory color spaces when img declares a non-default CICP space that disagrees with color (use from_rgba8_image to preserve img’s own declared CICP automatically).

Source

pub fn into_dynamic_image(self) -> Result<DynamicImage, At<BufferError>>

Move into an image::DynamicImage zero-copy when InteropTarget::DynamicImage is satisfied.

Source

pub const fn try_image_srgb_default_color( order: ChannelOrder, ) -> Option<ColorSpace>

Helper: construct an sRGB ColorSpace matching image 0.25’s default Cicp::SRGB convention for standard grayscale and RGB/BGR channel orders.

Returns Some(...) for Gray, GrayAlpha, Rgb, Bgr, Rgba, Bgra, Rgbx, and Bgrx (mapping Rgb/Bgr to AlphaMode::None, Rgbx/Bgrx to AlphaMode::Undefined, and Rgba/Bgra/GrayAlpha to AlphaMode::Straight), and None for non-sRGB orders (Cmyk, Generic).

Note: from_image_buffer and from_dynamic_image read each buffer’s declared image::metadata::Cicp rather than calling this helper.

Trait Implementations§

Source§

impl Clone for PixelBuf

Source§

fn clone(&self) -> PixelBuf

Clone this buffer, preserving alignment, metadata, claims, origin, and orientation.

§Panics

Panics on allocation failure when repacking misaligned backing storage; use PixelBuf::try_clone for fallible cloning.

1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for PixelBuf

Source§

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

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

impl PixelScanExt for PixelBuf

Source§

fn measure_claims(&self) -> SampleClaims

Scan active pixels and return fresh evidence about opacity, grayscale, binary alpha, float values, and exact integer code depth. Read more
Source§

fn measure_and_attach_claims(&mut self) -> SampleClaims

Replace the attached claims with the result of measure_claims and return those fresh facts. On a view, updates the view’s own metadata.
Source§

fn check_samples(&self, bounds: SampleBounds) -> Result<(), PixelCheckError>

Check stored values against the requested SampleBounds. Read more
Source§

fn verify_claims( &self, required: SampleClaims, ) -> Result<(), ClaimVerificationError>

Check caller-supplied facts directly against stored samples. Read more
Source§

fn check_nominal_samples(&self) -> Result<(), PixelCheckError>

Check nominal sample bounds and report the bad pixel on failure. Read more
Source§

impl PixelSink for PixelBuf

Source§

fn sink_width(&self) -> u32

Frame width in pixels.
Source§

fn sink_height(&self) -> u32

Frame height in rows.
Source§

fn sink_format(&self) -> &PixelFormat

Authoritative destination specification.
Source§

fn sink_row_mut(&mut self, y: u32) -> Result<&mut [u8], At<BufferError>>

Fallibly borrow mutable active bytes of row y. Read more
Source§

fn sink_finish(&mut self, claims: SampleClaims, hdr: HdrMetadata)

Propagate output claims & HDR metadata on owned sinks (no-op on borrowed views).
Source§

fn sink_set_origin(&mut self, origin: ColorOrigin)

Propagate original container color provenance onto owned sinks (no-op on borrowed views).
Source§

fn sink_set_orientation(&mut self, orientation: Orientation)

Propagate pending EXIF display orientation onto sinks.
Source§

impl PixelSource for PixelBuf

Source§

fn source_width(&self) -> u32

Frame width in pixels.
Source§

fn source_height(&self) -> u32

Frame height in rows.
Source§

fn source_format(&self) -> &PixelFormat

Authoritative image specification.
Source§

fn source_claims(&self) -> SampleClaims

Attached sample claims.
Source§

fn source_hdr(&self) -> HdrMetadata

Descriptive HDR metadata.
Source§

fn source_origin(&self) -> Option<&ColorOrigin>

Original container color provenance, if attached.
Source§

fn source_orientation(&self) -> Orientation

Pending EXIF display orientation (defaults to Orientation::Identity).
Source§

fn source_row(&self, y: u32) -> &[u8] ⓘ

Active bytes of row y.
Source§

impl TryFrom<DynamicImage> for PixelBuf

Available on crate feature image only.
Source§

type Error = At<BufferError>

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

fn try_from(img: DynamicImage) -> Result<PixelBuf, At<BufferError>>

Performs the conversion.

Auto Trait Implementations§

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<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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<S> PixelConvertExt for S
where S: PixelSource + ?Sized,

Source§

fn convert_to( &self, destination_format: impl AsRef<PixelFormat>, policy: &ConvertPolicy, ) -> Result<PixelBuf, At<ConvertError>>

Convert self into a newly allocated tightly packed PixelBuf. Read more
Source§

fn convert_to_with_peak( &self, destination_format: impl AsRef<PixelFormat>, policy: &ConvertPolicy, peak: PeakSource, ) -> Result<PixelBuf, At<ConvertError>>

Convert self into a newly allocated PixelBuf with an explicit PeakSource.
Source§

fn convert_into<D: PixelSink + ?Sized>( &self, dst: &mut D, policy: &ConvertPolicy, ) -> Result<(), At<ConvertError>>

Convert self directly into any existing PixelSink (PixelBuf, PixelViewMut, or BandedBuf).
Source§

fn convert_into_with_peak<D: PixelSink + ?Sized>( &self, dst: &mut D, policy: &ConvertPolicy, peak: PeakSource, ) -> Result<(), At<ConvertError>>

Convert self directly into any existing PixelSink with an explicit PeakSource.
Source§

fn to_rgb8_if_opaque(&self) -> Result<PixelBuf, At<ConvertError>>

Convert self to full-range sRGB RGB8, refusing unproven alpha discard (AlphaPolicy::DiscardIfOpaque). Read more
Source§

fn to_rgba8(&self) -> Result<PixelBuf, At<ConvertError>>

Convert self to full-range sRGB straight-alpha RGBA8 under ConvertPolicy::permissive.
Source§

fn to_gray8_if_opaque(&self) -> Result<PixelBuf, At<ConvertError>>

Convert self to full-range sRGB GRAY8, refusing unproven alpha discard (AlphaPolicy::DiscardIfOpaque). Read more
Source§

fn to_bgra8(&self) -> Result<PixelBuf, At<ConvertError>>

Convert self to full-range sRGB straight-alpha BGRA8 under ConvertPolicy::permissive.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.