nsh-core 0.8.1

Platform-independent core: shadow tree, styles, layout and mount instructions.
Documentation
//! An image's own size, read from its encoded bytes' header: of every
//! target, as layout sizes an unsized `data:` or blob image by it.

use crate::geometry::{Points, Size, size};

/// An image's own size.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Natural {
    /// A bitmap's pixels.
    Pixels(u32, u32),
    /// An SVG's intrinsic size in points.
    Vector(Size<Points>),
}

impl Natural {
    /// Its size in points: a bitmap's pixels over its file name's
    /// `density`.
    pub fn points(self, density: f32) -> Size<Points> {
        match self {
            Natural::Pixels(w, h) => size(Points(w as f32 / density), Points(h as f32 / density)),
            Natural::Vector(points) => points,
        }
    }

    /// The natural size of the encoded `bytes`, from their header (an SVG:
    /// parsed), when it can be read without decoding them.
    pub fn of(bytes: &[u8]) -> Option<Natural> {
        #[cfg(feature = "svg")]
        if crate::svg::sniff(bytes) {
            return crate::svg::size(bytes).ok().map(Natural::Vector);
        }
        let size = imagesize::blob_size(bytes).ok()?;
        let side = |n: usize| u32::try_from(n).ok().filter(|n| *n > 0);
        Some(Natural::Pixels(side(size.width)?, side(size.height)?))
    }
}