floem_peniko/
image.rs

1// Copyright 2022 The peniko authors.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use super::{Blob, Extend};
5
6/// Defines the pixel format of an image.
7#[derive(Copy, Clone, PartialEq, Eq, Debug)]
8pub enum Format {
9    /// 32-bit RGBA with 8-bit channels.
10    Rgba8,
11}
12
13impl Format {
14    /// Returns the required size in bytes for an image in this format
15    /// of the given dimensions.
16    ///
17    /// A result of `None` indicates an overflow in the size calculation.
18    pub fn size_in_bytes(self, width: u32, height: u32) -> Option<usize> {
19        match self {
20            Self::Rgba8 => 4usize
21                .checked_mul(width as usize)
22                .and_then(|x| x.checked_mul(height as usize)),
23        }
24    }
25}
26
27/// Owned shareable image resource.
28#[derive(Clone, PartialEq, Debug)]
29pub struct Image {
30    /// Blob containing the image data.
31    pub data: Blob<u8>,
32    /// Pixel format of the image.
33    pub format: Format,
34    /// Width of the image.
35    pub width: u32,
36    /// Height of the image.
37    pub height: u32,
38    /// Extend mode
39    pub extend: Extend,
40}
41
42impl Image {
43    /// Creates a new image with the given data, format and dimensions.
44    pub fn new(data: Blob<u8>, format: Format, width: u32, height: u32) -> Self {
45        Self {
46            data,
47            format,
48            width,
49            height,
50            extend: Extend::Pad,
51        }
52    }
53
54    /// Builder method for setting the image extend mode.
55    pub fn with_extend(mut self, mode: Extend) -> Self {
56        self.extend = mode;
57        self
58    }
59}