skia_safe/core/pixmap.rs
1//! Provides a utility to pair [`ImageInfo`] with pixels and row bytes. [`Pixmap`] is a low level
2//! class which provides convenience functions to access raster destinations. [`crate::Canvas`]
3//! cannot draw a [`Pixmap`], nor does [`Pixmap`] provide a direct drawing destination.
4//!
5//! Use [`crate::Bitmap`] to draw pixels referenced by [`Pixmap`]; use [`crate::Surface`] to draw
6//! into pixels referenced by [`Pixmap`].
7//!
8//! [`Pixmap`] does not try to manage the lifetime of the pixel memory. Use [`crate::PixelRef`] to
9//! manage pixel memory; [`crate::PixelRef`] is safe across threads.
10
11use crate::{
12 AlphaType, Color, Color4f, ColorSpace, ColorType, IPoint, IRect, ISize, ImageInfo,
13 SamplingOptions, prelude::*,
14};
15use skia_bindings::{self as sb, SkPixmap};
16use std::{ffi::c_void, fmt, marker::PhantomData, mem, os::raw, ptr, slice};
17
18#[repr(transparent)]
19pub struct Pixmap<'a> {
20 inner: Handle<SkPixmap>,
21 pd: PhantomData<&'a mut [u8]>,
22}
23
24impl NativeDrop for SkPixmap {
25 fn drop(&mut self) {
26 unsafe { sb::C_SkPixmap_destruct(self) }
27 }
28}
29
30impl Default for Pixmap<'_> {
31 fn default() -> Self {
32 Self::from_native_c(SkPixmap {
33 fPixels: ptr::null(),
34 fRowBytes: 0,
35 fInfo: construct(|ii| unsafe { sb::C_SkImageInfo_Construct(ii) }),
36 })
37 }
38}
39
40impl fmt::Debug for Pixmap<'_> {
41 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42 f.debug_struct("Pixmap")
43 .field("row_bytes", &self.row_bytes())
44 .field("info", self.info())
45 .finish()
46 }
47}
48
49impl<'pixels> Pixmap<'pixels> {
50 /// Creates a [`Pixmap`] from `info` width, height, alpha type, and color type. `pixels` points
51 /// to pixels. `row_bytes` should be `info.width()` times `info.bytes_per_pixel()`, or larger.
52 ///
53 /// No parameter checking is performed; it is up to the caller to ensure that `pixels` and
54 /// `row_bytes` agree with `info`.
55 ///
56 /// The memory lifetime of pixels is managed by the caller. When the [`Pixmap`] goes out of
57 /// scope, the pixel address is unaffected.
58 ///
59 /// The [`Pixmap`] may be later modified by [`Self::reset()`] to change its size, pixel type, or
60 /// storage.
61 ///
62 /// - `info` width, height, alpha type, color type of the image info
63 /// - `pixels` pointer to pixels allocated by the caller
64 /// - `row_bytes` size of one row of pixels; width times pixel size, or larger
65 ///
66 /// Example (C++): <https://fiddle.skia.org/c/@Pixmap_reset_2>
67 pub fn new(info: &ImageInfo, pixels: &'pixels mut [u8], row_bytes: usize) -> Option<Self> {
68 if row_bytes < info.min_row_bytes() {
69 return None;
70 }
71 if pixels.len() < info.compute_byte_size(row_bytes) {
72 return None;
73 }
74
75 Some(Pixmap::from_native_c(SkPixmap {
76 fPixels: pixels.as_mut_ptr() as _,
77 fRowBytes: row_bytes,
78 fInfo: info.native().clone(),
79 }))
80 }
81
82 /// Sets width, height, row bytes to zero; pixel address to null; color type to
83 /// [`ColorType::Unknown`]; and alpha type to [`AlphaType::Unknown`].
84 ///
85 /// The prior pixels are unaffected; it is up to the caller to release pixels memory if desired.
86 ///
87 /// Example (C++): <https://fiddle.skia.org/c/@Pixmap_reset>
88 pub fn reset(&mut self) -> &mut Self {
89 unsafe { self.native_mut().reset() }
90 self
91 }
92
93 // TODO: reset() function that re-borrows pixels?
94
95 /// Changes the [`ColorSpace`] in the [`ImageInfo`]; preserves width, height, alpha type, and
96 /// color type, and leaves the pixel address and row bytes unchanged. The [`ColorSpace`]
97 /// reference count is incremented.
98 ///
99 /// - `color_space` color space moved to the image info
100 ///
101 /// Example (C++): <https://fiddle.skia.org/c/@Pixmap_setColorSpace>
102 pub fn set_color_space(&mut self, color_space: impl Into<Option<ColorSpace>>) -> &mut Self {
103 unsafe {
104 sb::C_SkPixmap_setColorSpace(self.native_mut(), color_space.into().into_ptr_or_null())
105 }
106 self
107 }
108
109 /// Sets the subset width, height, pixel address to the intersection of the [`Pixmap`] with
110 /// `area`, if the intersection is not empty; and returns true. Otherwise, leaves the subset
111 /// unchanged and returns false.
112 ///
113 /// - `area` bounds to intersect with the pixmap
114 #[must_use]
115 pub fn extract_subset(&self, area: impl AsRef<IRect>) -> Option<Self> {
116 let mut pixmap = Pixmap::default();
117 unsafe {
118 self.native()
119 .extractSubset(pixmap.native_mut(), area.as_ref().native())
120 }
121 .then_some(pixmap)
122 }
123
124 /// Returns the width, height, alpha type, color type, and color space.
125 pub fn info(&self) -> &ImageInfo {
126 ImageInfo::from_native_ref(&self.native().fInfo)
127 }
128
129 /// Returns the row bytes, the interval from one pixel row to the next. Row bytes is at least as
130 /// large as `width() * info().bytes_per_pixel()`.
131 ///
132 /// Returns zero if the color type is [`ColorType::Unknown`]. It is up to the bitmap creator to
133 /// ensure that row bytes is a useful value.
134 pub fn row_bytes(&self) -> usize {
135 self.native().fRowBytes
136 }
137
138 /// Returns the pixel address, the base address corresponding to the pixel origin.
139 ///
140 /// It is up to the pixmap creator to ensure that the pixel address is a useful value.
141 pub fn addr(&self) -> *const c_void {
142 self.native().fPixels
143 }
144
145 /// Returns the pixel count in each pixel row. Should be equal to or less than
146 /// `row_bytes() / info().bytes_per_pixel()`.
147 pub fn width(&self) -> i32 {
148 self.info().width()
149 }
150
151 /// Returns the pixel row count.
152 pub fn height(&self) -> i32 {
153 self.info().height()
154 }
155
156 /// Returns true if the pixmap is empty (from its [`ImageInfo`]).
157 pub fn is_empty(&self) -> bool {
158 self.info().is_empty()
159 }
160
161 /// Returns the dimensions of the pixmap (from its [`ImageInfo`]).
162 pub fn dimensions(&self) -> ISize {
163 self.info().dimensions()
164 }
165
166 /// Returns the color type.
167 pub fn color_type(&self) -> ColorType {
168 self.info().color_type()
169 }
170
171 /// Returns the alpha type.
172 pub fn alpha_type(&self) -> AlphaType {
173 self.info().alpha_type()
174 }
175
176 /// Returns the [`ColorSpace`], the range of colors, associated with the [`ImageInfo`]. The
177 /// returned [`ColorSpace`] is immutable.
178 pub fn color_space(&self) -> Option<ColorSpace> {
179 ColorSpace::from_unshared_ptr(unsafe { self.native().colorSpace() })
180 }
181
182 /// Returns true if the alpha type is [`AlphaType::Opaque`]. Does not check if the color type
183 /// allows alpha, or if any pixel value has transparency.
184 pub fn is_opaque(&self) -> bool {
185 self.alpha_type().is_opaque()
186 }
187
188 /// Returns the integral rectangle from the origin to [`Self::width()`] and [`Self::height()`].
189 pub fn bounds(&self) -> IRect {
190 IRect::from_wh(self.width(), self.height())
191 }
192
193 /// Returns the number of pixels that fit on a row. Should be greater than or equal to
194 /// [`Self::width()`].
195 pub fn row_bytes_as_pixels(&self) -> usize {
196 self.row_bytes() >> self.shift_per_pixel()
197 }
198
199 /// Returns the bit shift converting row bytes to row pixels. Returns zero for
200 /// [`ColorType::Unknown`].
201 pub fn shift_per_pixel(&self) -> usize {
202 self.info().shift_per_pixel()
203 }
204
205 /// Returns the minimum memory required for pixel storage. Does not include unused memory on
206 /// the last row when [`Self::row_bytes_as_pixels()`] exceeds [`Self::width()`]. Returns
207 /// `usize::MAX` if the result does not fit in `usize`. Returns zero if [`Self::height()`] or
208 /// [`Self::width()`] is 0. Returns [`Self::height()`] times [`Self::row_bytes()`] if the color
209 /// type is [`ColorType::Unknown`].
210 pub fn compute_byte_size(&self) -> usize {
211 self.info().compute_byte_size(self.row_bytes())
212 }
213
214 /// Returns true if all pixels are opaque. The color type determines how pixels are encoded, and
215 /// whether a pixel describes alpha. Returns true for color types without alpha in each pixel;
216 /// for other color types, returns true if all pixels have alpha values equivalent to 1.0 or
217 /// greater.
218 ///
219 /// For [`ColorType::RGB565`] or [`ColorType::Gray8`]: always returns true. For
220 /// [`ColorType::Alpha8`], [`ColorType::BGRA8888`], [`ColorType::RGBA8888`]: returns true if all
221 /// pixel alpha values are 255. For [`ColorType::ARGB4444`]: returns true if all pixel alpha
222 /// values are 15. For [`ColorType::RGBAF16`]: returns true if all pixel alpha values are 1.0 or
223 /// greater.
224 ///
225 /// Returns false for [`ColorType::Unknown`].
226 ///
227 /// Example (C++): <https://fiddle.skia.org/c/@Pixmap_computeIsOpaque>
228 pub fn compute_is_opaque(&self) -> bool {
229 unsafe { self.native().computeIsOpaque() }
230 }
231
232 /// Returns the pixel at (`p.x`, `p.y`) as an unpremultiplied color. Returns black with alpha if
233 /// the color type is [`ColorType::Alpha8`].
234 ///
235 /// Input is not validated: out of bounds values of `p` trigger an assert if built with debug
236 /// defined; and returns undefined values or may crash if release is defined. Fails if the color
237 /// type is [`ColorType::Unknown`] or the pixel address is null.
238 ///
239 /// The [`ColorSpace`] in the [`ImageInfo`] is ignored. Some color precision may be lost in the
240 /// conversion to unpremultiplied color; original pixel data may have additional precision.
241 ///
242 /// - `p` pixel position
243 ///
244 /// Example (C++): <https://fiddle.skia.org/c/@Pixmap_getColor>
245 pub fn get_color(&self, p: impl Into<IPoint>) -> Color {
246 let p = p.into();
247 self.assert_pixel_exists(p);
248 Color::from_native_c(unsafe { self.native().getColor(p.x, p.y) })
249 }
250
251 /// Returns the pixel at (`p.x`, `p.y`) as an unpremultiplied color as a [`Color4f`]. Returns
252 /// black with alpha if the color type is [`ColorType::Alpha8`].
253 ///
254 /// Input is not validated: out of bounds values of `p` trigger an assert if built with debug
255 /// defined; and returns undefined values or may crash if release is defined. Fails if the color
256 /// type is [`ColorType::Unknown`] or the pixel address is null.
257 ///
258 /// The [`ColorSpace`] in the [`ImageInfo`] is ignored. Some color precision may be lost in the
259 /// conversion to unpremultiplied color; original pixel data may have additional precision,
260 /// though this is less likely than for [`Self::get_color()`]. Rounding errors may occur if the
261 /// underlying type has lower precision.
262 ///
263 /// - `p` pixel position
264 pub fn get_color_4f(&self, p: impl Into<IPoint>) -> Color4f {
265 let p = p.into();
266 self.assert_pixel_exists(p);
267 Color4f::from_native_c(unsafe { self.native().getColor4f(p.x, p.y) })
268 }
269
270 /// Looks up the pixel at (`p.x`, `p.y`) and returns its alpha component, normalized to [0..1].
271 /// This is roughly equivalent to `get_color().a()`, but can be more efficient (and more precise
272 /// if the pixels store more than 8 bits per component).
273 ///
274 /// - `p` pixel position
275 pub fn get_alpha_f(&self, p: impl Into<IPoint>) -> f32 {
276 let p = p.into();
277 self.assert_pixel_exists(p);
278 unsafe { self.native().getAlphaf(p.x, p.y) }
279 }
280
281 // Helper to test if the pixel does exist physically in memory.
282 fn assert_pixel_exists(&self, p: impl Into<IPoint>) {
283 let p = p.into();
284 assert!(!self.addr().is_null());
285 assert!(p.x >= 0 && p.x < self.width());
286 assert!(p.y >= 0 && p.y < self.height());
287 }
288
289 /// Returns the readable pixel address at (`p.x`, `p.y`). Returns null if the pixel ref is null.
290 ///
291 /// Input is not validated: out of bounds values of `p` trigger an assert if built with debug
292 /// defined. Returns null if the color type is [`ColorType::Unknown`].
293 ///
294 /// Performs a lookup of pixel size; for better performance, call one of the typed address
295 /// accessors.
296 ///
297 /// - `p` pixel position
298 pub fn addr_at(&self, p: impl Into<IPoint>) -> *const c_void {
299 let p = p.into();
300 self.assert_pixel_exists(p);
301 unsafe {
302 (self.addr() as *const raw::c_char).add(self.info().compute_offset(p, self.row_bytes()))
303 as _
304 }
305 }
306
307 // TODO: addr8(), addr16(), addr32(), addr64(), addrF16(),
308 // addr8_at(), addr16_at(), addr32_at(), addr64_at(), addrF16_at()
309
310 /// Returns the writable base pixel address.
311 pub fn writable_addr(&self) -> *mut c_void {
312 self.addr() as _
313 }
314
315 /// Returns the writable pixel address at (`p.x`, `p.y`).
316 ///
317 /// Input is not validated: out of bounds values of `p` trigger an assert if built with debug
318 /// defined. Returns zero if the color type is [`ColorType::Unknown`].
319 ///
320 /// - `p` pixel position
321 pub fn writable_addr_at(&self, p: impl Into<IPoint>) -> *mut c_void {
322 self.addr_at(p) as _
323 }
324
325 // TODO: writable_addr8
326 // TODO: writable_addr16
327 // TODO: writable_addr32
328 // TODO: writable_addr64
329 // TODO: writable_addrF16
330
331 /// Copies a rectangle of pixels to `pixels`. Copy starts at (`src.x`, `src.y`), and does not
332 /// exceed the pixmap (`width()`, `height()`).
333 ///
334 /// `dst_info` specifies width, height, color type, alpha type, and color space of the
335 /// destination. `dst_row_bytes` specifies the gap from one destination row to the next. Returns
336 /// true if pixels are copied. Returns false if `dst_info` address equals null, or `dst_row_bytes`
337 /// is less than `dst_info.min_row_bytes()`.
338 ///
339 /// Pixels are copied only if pixel conversion is possible. If the pixmap color type is
340 /// [`ColorType::Gray8`] or [`ColorType::Alpha8`], `dst_info.color_type()` must match. If the
341 /// pixmap color type is [`ColorType::Gray8`], `dst_info.color_space()` must match. If the pixmap
342 /// alpha type is [`AlphaType::Opaque`], `dst_info.alpha_type()` must match. If the pixmap color
343 /// space is `None`, `dst_info.color_space()` must match. Returns false if pixel conversion is
344 /// not possible.
345 ///
346 /// `src.x` and `src.y` may be negative to copy only the top or left of the source. Returns
347 /// false if the pixmap width() or height() is zero or negative. Returns false if `abs(src.x)`
348 /// is greater than or equal to the pixmap width(), or if `abs(src.y)` is greater than or equal
349 /// to the pixmap height().
350 ///
351 /// - `dst_info` destination width, height, color type, alpha type, color space
352 /// - `pixels` destination pixel storage
353 /// - `dst_row_bytes` destination row length
354 /// - `src` source position
355 pub fn read_pixels<P>(
356 &self,
357 dst_info: &ImageInfo,
358 pixels: &mut [P],
359 dst_row_bytes: usize,
360 src: impl Into<IPoint>,
361 ) -> bool {
362 if !dst_info.valid_pixels(dst_row_bytes, pixels) {
363 return false;
364 }
365
366 let src = src.into();
367
368 unsafe {
369 self.native().readPixels(
370 dst_info.native(),
371 pixels.as_mut_ptr() as _,
372 dst_row_bytes,
373 src.x,
374 src.y,
375 )
376 }
377 }
378
379 /// Access the underlying pixels as a byte array. This is a rust-skia specific function.
380 pub fn bytes(&self) -> Option<&'pixels [u8]> {
381 let addr = self.addr().into_non_null()?;
382 let len = self.compute_byte_size();
383 Some(unsafe { slice::from_raw_parts(addr.as_ptr() as *const _, len) })
384 }
385
386 pub fn bytes_mut(&mut self) -> Option<&'pixels mut [u8]> {
387 let addr = self.writable_addr().into_non_null()?;
388 let len = self.compute_byte_size();
389 Some(unsafe { slice::from_raw_parts_mut(addr.as_ptr() as *mut u8, len) })
390 }
391
392 /// Access the underlying pixels. This is a rust-skia specific function.
393 ///
394 /// The `Pixel` type must implement the _unsafe_ trait [`Pixel`] and must return `true` in
395 /// [`Pixel::matches_color_type()`] when matched against the [`ColorType`] of this Pixmap's
396 /// pixels.
397 pub fn pixels<P: Pixel>(&self) -> Option<&'pixels [P]> {
398 let addr = self.addr().into_non_null()?;
399
400 let info = self.info();
401 let ct = info.color_type();
402 let pixel_size = mem::size_of::<P>();
403
404 if info.bytes_per_pixel() == pixel_size && P::matches_color_type(ct) {
405 let len = self.compute_byte_size() / pixel_size;
406 return Some(unsafe { slice::from_raw_parts(addr.as_ptr() as *const _, len) });
407 }
408
409 None
410 }
411
412 /// Copies a rectangle of pixels to `dst`. Copy starts at `src`, and does not exceed the pixmap
413 /// (`width()`, `height()`). `dst` specifies width, height, color type, alpha type, and color
414 /// space of the destination. Returns true if pixels are copied. Returns false if the
415 /// destination address is null, or `dst.row_bytes()` is less than `dst.info().min_row_bytes()`.
416 ///
417 /// Pixels are copied only if pixel conversion is possible. If the pixmap color type is
418 /// [`ColorType::Gray8`] or [`ColorType::Alpha8`], `dst.info().color_type()` must match. If the
419 /// pixmap color type is [`ColorType::Gray8`], `dst.info().color_space()` must match. If the
420 /// pixmap alpha type is [`AlphaType::Opaque`], `dst.info().alpha_type()` must match. If the
421 /// pixmap color space is `None`, `dst.info().color_space()` must match. Returns false if pixel
422 /// conversion is not possible.
423 ///
424 /// `src.x` and `src.y` may be negative to copy only the top or left of the source. Returns
425 /// false if the pixmap width() or height() is zero or negative. Returns false if `abs(src.x)`
426 /// is greater than or equal to the pixmap width(), or if `abs(src.y)` is greater than or equal
427 /// to the pixmap height().
428 ///
429 /// - `dst` image info and pixel address to write to
430 /// - `src` source position
431 pub fn read_pixels_to_pixmap(&self, dst: &mut Pixmap, src: impl Into<IPoint>) -> bool {
432 let Some(dst_bytes) = dst.bytes_mut() else {
433 return false;
434 };
435 self.read_pixels(dst.info(), dst_bytes, dst.row_bytes(), src)
436 }
437
438 /// Copies the pixmap to `dst`, scaling pixels to fit `dst.width()` and `dst.height()`, and
439 /// converting pixels to match `dst.color_type()` and `dst.alpha_type()`. Returns true if pixels
440 /// are copied. Returns false if the destination address is null, or the destination row bytes
441 /// is less than the destination minimum row bytes.
442 ///
443 /// Pixels are copied only if pixel conversion is possible. If the pixmap color type is
444 /// [`ColorType::Gray8`] or [`ColorType::Alpha8`], the destination color type must match. If the
445 /// pixmap color type is [`ColorType::Gray8`], the destination color space must match. If the
446 /// pixmap alpha type is [`AlphaType::Opaque`], the destination alpha type must match. If the
447 /// pixmap color space is `None`, the destination color space must match. Returns false if pixel
448 /// conversion is not possible.
449 ///
450 /// Returns false if the pixmap width() or height() is zero or negative.
451 ///
452 /// - `dst` image info and pixel address to write to
453 /// - `sampling` sampling options
454 ///
455 /// Example (C++): <https://fiddle.skia.org/c/@Pixmap_scalePixels>
456 pub fn scale_pixels(&self, dst: &mut Pixmap, sampling: impl Into<SamplingOptions>) -> bool {
457 let sampling = sampling.into();
458 unsafe { self.native().scalePixels(dst.native(), sampling.native()) }
459 }
460
461 /// Writes `color` to pixels bounded by `subset`; returns true on success. Returns false if the
462 /// color type is [`ColorType::Unknown`], or if `subset` does not intersect the bounds. If
463 /// `subset` is `None`, writes color to pixels inside the bounds.
464 ///
465 /// - `color` sRGB unpremultiplied color to write
466 /// - `subset` bounding integer rectangle of pixels to write
467 ///
468 /// Example (C++): <https://fiddle.skia.org/c/@Pixmap_erase>
469 pub fn erase(&mut self, color: impl Into<Color>, subset: Option<&IRect>) -> bool {
470 let color = color.into().into_native();
471 unsafe {
472 match subset {
473 Some(subset) => self.native().erase(color, subset.native()),
474 None => self.native().erase(color, self.bounds().native()),
475 }
476 }
477 }
478
479 /// Writes `color` to pixels bounded by `subset`; returns true on success. If `subset` is `None`,
480 /// writes color to pixels inside the bounds. Returns false if the color type is
481 /// [`ColorType::Unknown`], if `subset` is not `None` and does not intersect the bounds, or if
482 /// `subset` is `None` and the bounds is empty.
483 ///
484 /// - `color` unpremultiplied color to write
485 /// - `subset` bounding integer rectangle of pixels to write; may be `None`
486 pub fn erase_4f(&mut self, color: impl AsRef<Color4f>, subset: Option<&IRect>) -> bool {
487 let color = color.as_ref();
488 unsafe {
489 self.native()
490 .erase1(color.native(), subset.native_ptr_or_null())
491 }
492 }
493
494 fn from_native_c(pixmap: SkPixmap) -> Self {
495 Self {
496 inner: Handle::from_native_c(pixmap),
497 pd: PhantomData,
498 }
499 }
500
501 #[must_use]
502 pub(crate) fn from_native_ref(n: &SkPixmap) -> &Self {
503 unsafe { transmute_ref(n) }
504 }
505
506 #[must_use]
507 pub(crate) fn from_native_ptr(np: *const SkPixmap) -> *const Self {
508 // Should be safe as long `Pixmap` is represented with repr(Transparent).
509 np as _
510 }
511
512 pub(crate) fn native_mut(&mut self) -> &mut SkPixmap {
513 self.inner.native_mut()
514 }
515
516 pub(crate) fn native(&self) -> &SkPixmap {
517 self.inner.native()
518 }
519}
520
521/// Implement this trait to use a pixel type in [`Handle<Pixmap>::pixels()`].
522///
523/// # Safety
524///
525/// This trait is unsafe because external [`Pixel`] implementations may lie about their
526/// [`ColorType`] or fail to match the alignment of the pixels stored in [`Handle<Pixmap>`].
527pub unsafe trait Pixel: Copy {
528 /// `true` if the type matches the color type's format.
529 fn matches_color_type(ct: ColorType) -> bool;
530}
531
532unsafe impl Pixel for u8 {
533 fn matches_color_type(ct: ColorType) -> bool {
534 matches!(ct, ColorType::Alpha8 | ColorType::Gray8)
535 }
536}
537
538unsafe impl Pixel for [u8; 2] {
539 fn matches_color_type(ct: ColorType) -> bool {
540 matches!(ct, ColorType::R8G8UNorm | ColorType::A16UNorm)
541 }
542}
543
544unsafe impl Pixel for (u8, u8) {
545 fn matches_color_type(ct: ColorType) -> bool {
546 matches!(ct, ColorType::R8G8UNorm | ColorType::A16UNorm)
547 }
548}
549
550unsafe impl Pixel for [u8; 4] {
551 fn matches_color_type(ct: ColorType) -> bool {
552 matches!(
553 ct,
554 ColorType::RGBA8888 | ColorType::RGB888x | ColorType::BGRA8888
555 )
556 }
557}
558
559unsafe impl Pixel for (u8, u8, u8, u8) {
560 fn matches_color_type(ct: ColorType) -> bool {
561 matches!(
562 ct,
563 ColorType::RGBA8888 | ColorType::RGB888x | ColorType::BGRA8888
564 )
565 }
566}
567
568unsafe impl Pixel for [f32; 4] {
569 fn matches_color_type(ct: ColorType) -> bool {
570 matches!(ct, ColorType::RGBAF32)
571 }
572}
573
574unsafe impl Pixel for (f32, f32, f32, f32) {
575 fn matches_color_type(ct: ColorType) -> bool {
576 matches!(ct, ColorType::RGBAF32)
577 }
578}
579
580unsafe impl Pixel for u32 {
581 fn matches_color_type(ct: ColorType) -> bool {
582 ct == ColorType::N32
583 }
584}
585
586unsafe impl Pixel for Color {
587 fn matches_color_type(ct: ColorType) -> bool {
588 ct == ColorType::N32
589 }
590}
591
592unsafe impl Pixel for Color4f {
593 fn matches_color_type(ct: ColorType) -> bool {
594 ct == ColorType::RGBAF32
595 }
596}
597
598#[cfg(test)]
599mod tests {
600 use super::*;
601
602 #[test]
603 fn pixmap_mutably_borrows_pixels() {
604 let mut pixels = [0u8; 2 * 2 * 4];
605 let info = ImageInfo::new(
606 (2, 2),
607 ColorType::RGBA8888,
608 AlphaType::Premul,
609 ColorSpace::new_srgb(),
610 );
611 let mut pixmap = Pixmap::new(&info, &mut pixels, info.min_row_bytes()).unwrap();
612 // this must fail to compile:
613 // let _pixel = pixels[0];
614 // use `.bytes()`, or `bytes_mut()` instead.
615 pixmap.reset();
616 }
617
618 #[test]
619 fn addr_may_return_null_from_a_default_pixmap() {
620 let pixmap = Pixmap::default();
621 assert!(pixmap.addr().is_null());
622 assert!(pixmap.writable_addr().is_null());
623 }
624}