legit-hashes 0.2.1

Versioned similarity hashes of images and text, and MinHash set signatures, with index keys for finding near matches
Documentation
//! 8-bit RGBA images: the input of the colour image hashes, `pdq-v1` and `blockhash-v1`.

use std::fmt;

use crate::luma::check_size;
use crate::{Luma, Result};

/// A borrowed 8-bit RGBA image: four bytes a pixel, red, green, blue and alpha, row by row from
/// the top left. Alpha 0 is fully transparent and 255 opaque; the colour isn't premultiplied.
///
/// Making one checks its size, so every image hash of an `Rgba` succeeds. Its sides are limited to
/// [`MAX_DIMENSION`](crate::MAX_DIMENSION), as a [`Luma`] image's are.
///
/// ```
/// use legit_hashes::Rgba;
///
/// let pixels = vec![255; 640 * 480 * 4];
/// let image = Rgba::new(640, 480, &pixels)?;
/// assert_eq!(image.width(), 640);
/// # Ok::<(), legit_hashes::Error>(())
/// ```
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Rgba<'a> {
    width: u32,
    height: u32,
    pixels: &'a [u8],
}

impl<'a> Rgba<'a> {
    /// View `pixels` as a `width` × `height` RGBA image.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ZeroDimension`](crate::Error::ZeroDimension) or
    /// [`Error::DimensionTooLarge`](crate::Error::DimensionTooLarge) when a side isn't from 1 to
    /// [`MAX_DIMENSION`](crate::MAX_DIMENSION), and [`Error::BufferLength`](crate::Error::BufferLength)
    /// when `pixels` isn't `width * height * 4` long.
    pub fn new(width: u32, height: u32, pixels: &'a [u8]) -> Result<Self> {
        check_size(width, height, 4, pixels.len())?;
        Ok(Self { width, height, pixels })
    }

    /// The width in pixels.
    #[must_use]
    pub const fn width(&self) -> u32 {
        self.width
    }

    /// The height in pixels.
    #[must_use]
    pub const fn height(&self) -> u32 {
        self.height
    }

    /// The pixels, four bytes each, row by row from the top left.
    #[must_use]
    pub const fn pixels(&self) -> &'a [u8] {
        self.pixels
    }
}

impl fmt::Debug for Rgba<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Rgba")
            .field("width", &self.width)
            .field("height", &self.height)
            .finish_non_exhaustive()
    }
}

/// An owned 8-bit RGBA image, such as one made from RGB or greyscale pixels.
/// [`view`](Self::view) borrows it for hashing.
///
/// ```
/// use legit_hashes::{RgbaBuf, blockhash_v1};
///
/// let rgb = [255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255];
/// let image = RgbaBuf::from_rgb8(2, 2, &rgb)?;
/// assert_eq!(image.pixels()[..8], [255, 0, 0, 255, 0, 255, 0, 255]);
///
/// let hash = blockhash_v1(image.view());
/// # Ok::<(), legit_hashes::Error>(())
/// ```
#[derive(Clone, PartialEq, Eq)]
pub struct RgbaBuf {
    width: u32,
    height: u32,
    pixels: Vec<u8>,
}

impl RgbaBuf {
    /// Take `pixels` as a `width` × `height` RGBA image, four bytes a pixel.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ZeroDimension`](crate::Error::ZeroDimension) or
    /// [`Error::DimensionTooLarge`](crate::Error::DimensionTooLarge) when a side isn't from 1 to
    /// [`MAX_DIMENSION`](crate::MAX_DIMENSION), and [`Error::BufferLength`](crate::Error::BufferLength)
    /// when `pixels` isn't `width * height * 4` long.
    pub fn new(width: u32, height: u32, pixels: Vec<u8>) -> Result<Self> {
        check_size(width, height, 4, pixels.len())?;
        Ok(Self { width, height, pixels })
    }

    /// Make an opaque image from a `width` × `height` RGB image, three bytes a pixel: each pixel
    /// keeps its colour and gets alpha 255.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ZeroDimension`](crate::Error::ZeroDimension) or
    /// [`Error::DimensionTooLarge`](crate::Error::DimensionTooLarge) when a side isn't from 1 to
    /// [`MAX_DIMENSION`](crate::MAX_DIMENSION), and [`Error::BufferLength`](crate::Error::BufferLength)
    /// when `rgb` isn't `width * height * 3` long.
    pub fn from_rgb8(width: u32, height: u32, rgb: &[u8]) -> Result<Self> {
        check_size(width, height, 3, rgb.len())?;
        let (pixels, _) = rgb.as_chunks::<3>();
        let pixels = pixels
            .iter()
            .flat_map(|&[red, green, blue]| [red, green, blue, u8::MAX])
            .collect();
        Ok(Self { width, height, pixels })
    }

    /// Make an opaque image from a luma image: each grey level `v` becomes the colour `(v, v, v)`
    /// with alpha 255.
    ///
    /// ```
    /// use legit_hashes::{Luma, RgbaBuf};
    ///
    /// let grey = RgbaBuf::from_luma(Luma::new(2, 1, &[7, 200])?);
    /// assert_eq!(grey.pixels(), [7, 7, 7, 255, 200, 200, 200, 255]);
    /// # Ok::<(), legit_hashes::Error>(())
    /// ```
    #[must_use]
    pub fn from_luma(image: Luma<'_>) -> Self {
        Self {
            width: image.width(),
            height: image.height(),
            pixels: image.pixels().iter().flat_map(|&v| [v, v, v, u8::MAX]).collect(),
        }
    }

    /// Borrow the image for hashing.
    #[must_use]
    pub fn view(&self) -> Rgba<'_> {
        Rgba {
            width: self.width,
            height: self.height,
            pixels: &self.pixels,
        }
    }

    /// The width in pixels.
    #[must_use]
    pub const fn width(&self) -> u32 {
        self.width
    }

    /// The height in pixels.
    #[must_use]
    pub const fn height(&self) -> u32 {
        self.height
    }

    /// The pixels, four bytes each, row by row from the top left.
    #[must_use]
    pub fn pixels(&self) -> &[u8] {
        &self.pixels
    }

    /// Take the pixels out.
    #[must_use]
    pub fn into_pixels(self) -> Vec<u8> {
        self.pixels
    }
}

impl fmt::Debug for RgbaBuf {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RgbaBuf")
            .field("width", &self.width)
            .field("height", &self.height)
            .finish_non_exhaustive()
    }
}