mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-18 00:15:44 +00:00
refactor(geom): clean up Clippy pedantic diagnostics (M14)
This commit is contained in:
1 parent
f8c66d0692
commit
e2f94ecef9
4 files changed
+127
-39
No files matched your search
+59
-20
@@ -1,4 +1,4 @@
|
||||
//! WordCraft geometry and units.
|
||||
//! `WordCraft` geometry and units.
|
||||
//!
|
||||
//! Layout works in **points** (1/72 inch, `f32`). File formats use other units: OOXML uses
|
||||
//! twentieths of a point (twips) for most lengths, half-points for font sizes, eighths of a point
|
||||
@@ -25,31 +25,44 @@ pub const EMU_PER_PT: f32 = 12_700.0;
|
||||
pub const PT_PER_CM: f32 = 72.0 / 2.54;
|
||||
|
||||
/// Twips → points.
|
||||
#[must_use]
|
||||
#[expect(clippy::cast_precision_loss, reason = "The f32 return type intentionally rounds i64 inputs to f32 precision.")]
|
||||
pub fn twips(v: i64) -> f32 {
|
||||
v as f32 / TWIPS_PER_PT
|
||||
}
|
||||
/// Points → twips (rounded).
|
||||
#[must_use]
|
||||
#[expect(clippy::cast_possible_truncation, reason = "The value is rounded first; Rust's float-to-integer cast saturates outside the i64 range.")]
|
||||
pub fn to_twips(pt: f32) -> i64 {
|
||||
finite(pt * TWIPS_PER_PT).round() as i64
|
||||
}
|
||||
/// EMU → points.
|
||||
#[must_use]
|
||||
#[expect(clippy::cast_precision_loss, reason = "The f32 return type intentionally rounds i64 inputs to f32 precision.")]
|
||||
pub fn emu(v: i64) -> f32 {
|
||||
v as f32 / EMU_PER_PT
|
||||
}
|
||||
/// Points → EMU (rounded).
|
||||
#[must_use]
|
||||
#[expect(clippy::cast_possible_truncation, reason = "The value is rounded first; Rust's float-to-integer cast saturates outside the i64 range.")]
|
||||
pub fn to_emu(pt: f32) -> i64 {
|
||||
(finite(pt) as f64 * EMU_PER_PT as f64).round() as i64
|
||||
(f64::from(finite(pt)) * f64::from(EMU_PER_PT)).round() as i64
|
||||
}
|
||||
/// Half-points (OOXML font sizes) → points.
|
||||
#[must_use]
|
||||
#[expect(clippy::cast_precision_loss, reason = "The f32 return type intentionally rounds i64 inputs to f32 precision.")]
|
||||
pub fn half_points(v: i64) -> f32 {
|
||||
v as f32 / 2.0
|
||||
}
|
||||
/// Points → half-points (rounded).
|
||||
#[must_use]
|
||||
#[expect(clippy::cast_possible_truncation, reason = "The value is rounded first; Rust's float-to-integer cast saturates outside the i64 range.")]
|
||||
pub fn to_half_points(pt: f32) -> i64 {
|
||||
(finite(pt) * 2.0).round() as i64
|
||||
}
|
||||
|
||||
/// Replace NaN/inf with 0 so casts and arithmetic stay defined.
|
||||
#[must_use]
|
||||
pub fn finite(v: f32) -> f32 {
|
||||
if v.is_finite() { v } else { 0.0 }
|
||||
}
|
||||
@@ -67,6 +80,7 @@ pub enum Unit {
|
||||
}
|
||||
|
||||
impl Unit {
|
||||
#[must_use]
|
||||
pub fn suffix(self) -> &'static str {
|
||||
match self {
|
||||
Unit::Inches => "\"",
|
||||
@@ -76,6 +90,7 @@ impl Unit {
|
||||
Unit::Picas => " pi",
|
||||
}
|
||||
}
|
||||
#[must_use]
|
||||
pub fn pt_per_unit(self) -> f32 {
|
||||
match self {
|
||||
Unit::Inches => PT_PER_IN,
|
||||
@@ -86,14 +101,17 @@ impl Unit {
|
||||
}
|
||||
}
|
||||
/// Format `pt` in this unit the way Word's fields show it (`1"`, `2.54 cm`, `12 pt`).
|
||||
#[must_use]
|
||||
pub fn format(self, pt: f32) -> String {
|
||||
self.format_with(pt, '.')
|
||||
}
|
||||
/// [`Unit::format`] with the region's decimal separator (`2,54 cm` with `,`).
|
||||
#[must_use]
|
||||
pub fn format_with(self, pt: f32, decimal: char) -> String {
|
||||
format!("{}{}", self.number(pt, decimal), self.suffix())
|
||||
}
|
||||
/// `pt` as a number in this unit, at most two decimals, without the unit (`2,54` with `,`).
|
||||
#[must_use]
|
||||
pub fn number(self, pt: f32, decimal: char) -> String {
|
||||
let v = finite(pt) / self.pt_per_unit();
|
||||
let s = format!("{v:.2}");
|
||||
@@ -106,6 +124,7 @@ impl Unit {
|
||||
/// Parse a measurement typed by a user: `1"`, `1 in`, `2.5cm`, `12pt`, `3 pi`, `10 mm`, `1.5 li`
|
||||
/// (lines are 12 pt). A bare number is in `default`. Returns points. Either decimal separator
|
||||
/// works (`2,5 cm` and `2.5 cm`), whatever the region.
|
||||
#[must_use]
|
||||
pub fn parse_measure(s: &str, default: Unit) -> Option<f32> {
|
||||
let t = s.trim().to_ascii_lowercase().replace('\u{2212}', "-");
|
||||
if t.is_empty() {
|
||||
@@ -123,8 +142,7 @@ pub fn parse_measure(s: &str, default: Unit) -> Option<f32> {
|
||||
"cm" => PT_PER_CM,
|
||||
"mm" => PT_PER_CM / 10.0,
|
||||
"pt" | "pts" | "point" | "points" => 1.0,
|
||||
"pi" | "pc" | "pica" | "picas" => 12.0,
|
||||
"li" | "line" | "lines" => 12.0,
|
||||
"pi" | "pc" | "pica" | "picas" | "li" | "line" | "lines" => 12.0,
|
||||
"px" => 0.75,
|
||||
_ => return None,
|
||||
};
|
||||
@@ -143,6 +161,7 @@ pub struct Point {
|
||||
}
|
||||
|
||||
impl Point {
|
||||
#[must_use]
|
||||
pub const fn new(x: f32, y: f32) -> Self {
|
||||
Point { x, y }
|
||||
}
|
||||
@@ -158,36 +177,45 @@ pub struct Rect {
|
||||
}
|
||||
|
||||
impl Rect {
|
||||
#[must_use]
|
||||
pub fn new(x: f32, y: f32, w: f32, h: f32) -> Self {
|
||||
Rect { x: finite(x), y: finite(y), w: finite(w).max(0.0), h: finite(h).max(0.0) }
|
||||
}
|
||||
#[must_use]
|
||||
pub fn right(&self) -> f32 {
|
||||
self.x + self.w
|
||||
}
|
||||
#[must_use]
|
||||
pub fn bottom(&self) -> f32 {
|
||||
self.y + self.h
|
||||
}
|
||||
#[must_use]
|
||||
pub fn contains(&self, p: Point) -> bool {
|
||||
p.x >= self.x && p.x <= self.right() && p.y >= self.y && p.y <= self.bottom()
|
||||
}
|
||||
#[must_use]
|
||||
pub fn intersects(&self, o: &Rect) -> bool {
|
||||
self.x < o.right() && o.x < self.right() && self.y < o.bottom() && o.y < self.bottom()
|
||||
}
|
||||
#[must_use]
|
||||
pub fn union(&self, o: &Rect) -> Rect {
|
||||
let x = self.x.min(o.x);
|
||||
let y = self.y.min(o.y);
|
||||
Rect::new(x, y, self.right().max(o.right()) - x, self.bottom().max(o.bottom()) - y)
|
||||
}
|
||||
#[must_use]
|
||||
pub fn inset(&self, l: f32, t: f32, r: f32, b: f32) -> Rect {
|
||||
Rect::new(self.x + l, self.y + t, self.w - l - r, self.h - t - b)
|
||||
}
|
||||
/// Grown by `d` on every side (shrunk for negative `d`, down to zero size).
|
||||
#[must_use]
|
||||
pub fn expand(&self, d: f32) -> Rect {
|
||||
self.inset(-d, -d, -d, -d)
|
||||
}
|
||||
}
|
||||
|
||||
/// An angle in degrees brought into `0..360` (NaN and infinities become 0).
|
||||
#[must_use]
|
||||
pub fn normalize_degrees(deg: f32) -> f32 {
|
||||
if !deg.is_finite() {
|
||||
return 0.0;
|
||||
@@ -198,7 +226,7 @@ pub fn normalize_degrees(deg: f32) -> f32 {
|
||||
}
|
||||
|
||||
/// How a drawing is turned about its centre: mirrored first (`flip_h` left to right, `flip_v` top
|
||||
/// to bottom), then rotated `deg` degrees clockwise (page space, y down), as DrawingML's `a:xfrm`
|
||||
/// to bottom), then rotated `deg` degrees clockwise (page space, y down), as `DrawingML`'s `a:xfrm`
|
||||
/// `flipH`, `flipV` and `rot` say (ECMA-376 §20.1.7.6).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Default)]
|
||||
pub struct Spin {
|
||||
@@ -209,17 +237,19 @@ pub struct Spin {
|
||||
|
||||
impl Spin {
|
||||
/// A spin with its angle normalised to `0..360`.
|
||||
#[must_use]
|
||||
pub fn new(deg: f32, flip_h: bool, flip_v: bool) -> Spin {
|
||||
Spin { deg: normalize_degrees(deg), flip_h, flip_v }
|
||||
}
|
||||
|
||||
/// No rotation and no mirroring.
|
||||
#[must_use]
|
||||
pub fn is_identity(&self) -> bool {
|
||||
normalize_degrees(self.deg) == 0.0 && !self.flip_h && !self.flip_v
|
||||
}
|
||||
|
||||
/// The linear part (a, b, c, d: x' = a·x + c·y, y' = b·x + d·y).
|
||||
fn linear(&self) -> [f32; 4] {
|
||||
fn linear(self) -> [f32; 4] {
|
||||
let r = normalize_degrees(self.deg).to_radians();
|
||||
let (s, c) = r.sin_cos();
|
||||
let fx = if self.flip_h { -1.0 } else { 1.0 };
|
||||
@@ -229,6 +259,7 @@ impl Spin {
|
||||
|
||||
/// The affine map (a, b, c, d, e, f: x' = a·x + c·y + e, y' = b·x + d·y + f) turning the page
|
||||
/// about point (`cx`, `cy`).
|
||||
#[must_use]
|
||||
pub fn matrix(&self, cx: f32, cy: f32) -> [f32; 6] {
|
||||
let [a, b, c, d] = self.linear();
|
||||
let (cx, cy) = (finite(cx), finite(cy));
|
||||
@@ -236,36 +267,41 @@ impl Spin {
|
||||
}
|
||||
|
||||
/// Where point (`x`, `y`) goes when turned about (`cx`, `cy`).
|
||||
#[must_use]
|
||||
pub fn apply(&self, cx: f32, cy: f32, x: f32, y: f32) -> (f32, f32) {
|
||||
let [a, b, c, d] = self.linear();
|
||||
let (u, v) = (x - cx, y - cy);
|
||||
(cx + a * u + c * v, cy + b * u + d * v)
|
||||
let [x_from_x, y_from_x, x_from_y, y_from_y] = self.linear();
|
||||
let (relative_x, relative_y) = (x - cx, y - cy);
|
||||
(cx + x_from_x * relative_x + x_from_y * relative_y, cy + y_from_x * relative_x + y_from_y * relative_y)
|
||||
}
|
||||
|
||||
/// The point that [`Spin::apply`] takes to (`x`, `y`).
|
||||
#[must_use]
|
||||
pub fn unapply(&self, cx: f32, cy: f32, x: f32, y: f32) -> (f32, f32) {
|
||||
// The linear part is orthogonal: its inverse is its transpose.
|
||||
let [a, b, c, d] = self.linear();
|
||||
let (u, v) = (x - cx, y - cy);
|
||||
(cx + a * u + b * v, cy + c * u + d * v)
|
||||
let [x_from_x, y_from_x, x_from_y, y_from_y] = self.linear();
|
||||
let (relative_x, relative_y) = (x - cx, y - cy);
|
||||
(cx + x_from_x * relative_x + y_from_x * relative_y, cy + x_from_y * relative_x + y_from_y * relative_y)
|
||||
}
|
||||
|
||||
/// The axis-aligned box `r` covers once turned about its centre.
|
||||
#[must_use]
|
||||
pub fn bounds(&self, r: Rect) -> Rect {
|
||||
let (bw, bh) = self.extent(r.w, r.h);
|
||||
Rect::new(r.x + (r.w - bw) / 2.0, r.y + (r.h - bh) / 2.0, bw, bh)
|
||||
}
|
||||
|
||||
/// The width and height of the box a `w` × `h` rectangle covers once turned.
|
||||
#[must_use]
|
||||
pub fn extent(&self, w: f32, h: f32) -> (f32, f32) {
|
||||
let (w, h) = (finite(w).abs(), finite(h).abs());
|
||||
let r = normalize_degrees(self.deg).to_radians();
|
||||
let (s, c) = (r.sin().abs(), r.cos().abs());
|
||||
(w * c + h * s, w * s + h * c)
|
||||
let (width, height) = (finite(w).abs(), finite(h).abs());
|
||||
let radians = normalize_degrees(self.deg).to_radians();
|
||||
let (sine, cosine) = (radians.sin().abs(), radians.cos().abs());
|
||||
(width * cosine + height * sine, width * sine + height * cosine)
|
||||
}
|
||||
|
||||
/// This spin applied inside `outer` (a group member's own spin within its group's): the one
|
||||
/// spin doing both.
|
||||
#[must_use]
|
||||
pub fn within(self, outer: Spin) -> Spin {
|
||||
// outer = R(θo)·Fo, self = R(θs)·Fs; Fo·R(θ) = R(±θ)·Fo (one mirror reverses the turn).
|
||||
let one_mirror = outer.flip_h != outer.flip_v;
|
||||
@@ -291,6 +327,7 @@ pub const PAPER_SIZES: &[(&str, f32, f32)] = &[
|
||||
];
|
||||
|
||||
/// The paper size whose dimensions match (either orientation, within half a point).
|
||||
#[must_use]
|
||||
pub fn paper_name(w: f32, h: f32) -> Option<&'static str> {
|
||||
PAPER_SIZES
|
||||
.iter()
|
||||
@@ -299,6 +336,7 @@ pub fn paper_name(w: f32, h: f32) -> Option<&'static str> {
|
||||
}
|
||||
|
||||
/// The standard paper size named `name` (case-insensitive), as (name, width, height) in points.
|
||||
#[must_use]
|
||||
pub fn paper_by_name(name: &str) -> Option<(&'static str, f32, f32)> {
|
||||
let name = name.trim();
|
||||
PAPER_SIZES.iter().find(|(n, _, _)| n.eq_ignore_ascii_case(name)).copied()
|
||||
@@ -321,6 +359,7 @@ pub struct PaperFit {
|
||||
/// page's orientation, the page is scaled up or down by one factor to fill it and centred, as
|
||||
/// Word's Pages per sheet › Scale to paper size does. Degenerate or non-finite sizes give the
|
||||
/// page as it is (scale 1 on paper of its own size).
|
||||
#[must_use]
|
||||
pub fn fit_to_paper(page_w: f32, page_h: f32, paper_w: f32, paper_h: f32) -> PaperFit {
|
||||
let ok = |v: f32| v.is_finite() && v >= 1.0;
|
||||
let as_is = PaperFit { paper_w: page_w, paper_h: page_h, k: 1.0, dx: 0.0, dy: 0.0 };
|
||||
@@ -343,11 +382,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn unit_round_trips() {
|
||||
assert_eq!(twips(1440), 72.0);
|
||||
assert_eq!(twips(1440).to_bits(), 72.0f32.to_bits());
|
||||
assert_eq!(to_twips(72.0), 1440);
|
||||
assert_eq!(emu(914_400), 72.0);
|
||||
assert_eq!(emu(914_400).to_bits(), 72.0f32.to_bits());
|
||||
assert_eq!(to_emu(72.0), 914_400);
|
||||
assert_eq!(half_points(24), 12.0);
|
||||
assert_eq!(half_points(24).to_bits(), 12.0f32.to_bits());
|
||||
assert_eq!(to_half_points(10.5), 21);
|
||||
assert_eq!(to_twips(f32::NAN), 0);
|
||||
}
|
||||
@@ -429,7 +468,7 @@ mod tests {
|
||||
assert!(a.intersects(&b));
|
||||
assert_eq!(a.union(&b), Rect::new(0.0, 0.0, 15.0, 15.0));
|
||||
assert!(a.contains(Point::new(5.0, 5.0)));
|
||||
assert_eq!(Rect::new(0.0, 0.0, -5.0, f32::NAN).w, 0.0);
|
||||
assert_eq!(Rect::new(0.0, 0.0, -5.0, f32::NAN).w.to_bits(), 0.0f32.to_bits());
|
||||
assert_eq!(a.inset(1.0, 2.0, 3.0, 4.0), Rect::new(1.0, 2.0, 6.0, 4.0));
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ use image::{DynamicImage, ImageDecoder, ImageFormat};
|
||||
/// Why a picture isn't decoded.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Refusal {
|
||||
/// Not a raster picture WordCraft decodes (a metafile, SVG or other bytes).
|
||||
/// Not a raster picture `WordCraft` decodes (a metafile, SVG or other bytes).
|
||||
NotAPicture,
|
||||
/// A kind of picture that is never decoded, because its decoder can't be held to a budget.
|
||||
Unsupported(&'static str),
|
||||
@@ -36,7 +36,7 @@ impl std::fmt::Display for Refusal {
|
||||
|
||||
impl std::error::Error for Refusal {}
|
||||
|
||||
fn broken(e: image::ImageError) -> Refusal {
|
||||
fn broken(e: &image::ImageError) -> Refusal {
|
||||
Refusal::Broken(e.to_string())
|
||||
}
|
||||
|
||||
@@ -56,11 +56,17 @@ pub struct Probe<'a> {
|
||||
}
|
||||
|
||||
/// TIFF compressions decoded within the caller's limits: none, CCITT Group 4, LZW, Deflate (both
|
||||
/// codes) and PackBits. The `tiff` crate decodes a JPEG strip (7) with a decoder of its own and
|
||||
/// codes) and `PackBits`. The `tiff` crate decodes a JPEG strip (7) with a decoder of its own and
|
||||
/// default limits, whatever size the TIFF declares, so such a TIFF is not decoded (#3645).
|
||||
const TIFF_COMPRESSIONS: [u16; 6] = [1, 4, 5, 8, 32946, 32773];
|
||||
|
||||
/// Read a picture's header: PNG, JPEG, GIF, WebP, BMP or TIFF.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `Refusal::NotAPicture` for an unsupported format, `Refusal::Unsupported` for a TIFF
|
||||
/// whose compression cannot be budgeted, `Refusal::TooLarge` on size arithmetic overflow, and
|
||||
/// `Refusal::Broken` for an invalid header.
|
||||
pub fn probe(bytes: &[u8]) -> Result<Probe<'_>, Refusal> {
|
||||
let format = image::guess_format(bytes).map_err(|_| Refusal::NotAPicture)?;
|
||||
let held = match format {
|
||||
@@ -79,7 +85,7 @@ pub fn probe(bytes: &[u8]) -> Result<Probe<'_>, Refusal> {
|
||||
let (width, height, peak) = sized(width, height, native, 0)?;
|
||||
return Ok(Probe { bytes: Cow::Borrowed(bytes), dib: false, format, width, height, peak, png_alpha: Some(alpha) });
|
||||
}
|
||||
let decoder = image::ImageReader::with_format(Cursor::new(bytes), format).into_decoder().map_err(broken)?;
|
||||
let decoder = image::ImageReader::with_format(Cursor::new(bytes), format).into_decoder().map_err(|error| broken(&error))?;
|
||||
let (width, height, peak) = measure(&decoder, held)?;
|
||||
Ok(Probe { bytes: Cow::Borrowed(bytes), dib: false, format, width, height, peak, png_alpha: None })
|
||||
}
|
||||
@@ -121,10 +127,15 @@ fn png_chunks(bytes: &[u8]) -> Option<(u32, u32, u64, bool)> {
|
||||
/// Read a DIB's header: a BMP without its 14-byte file header, as the Windows clipboard holds
|
||||
/// one (`CF_DIB`, `CF_DIBV5`). Its layout is first made the one the decoder reads (see
|
||||
/// [`dib_layout`]).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `Refusal::Broken` for an invalid DIB header and `Refusal::TooLarge` on size arithmetic
|
||||
/// overflow.
|
||||
pub fn probe_dib(dib: Vec<u8>) -> Result<Probe<'static>, Refusal> {
|
||||
let dib = dib_layout(dib);
|
||||
let (width, height, peak) = {
|
||||
let decoder = image::codecs::bmp::BmpDecoder::new_without_file_header(Cursor::new(dib.as_slice())).map_err(broken)?;
|
||||
let decoder = image::codecs::bmp::BmpDecoder::new_without_file_header(Cursor::new(dib.as_slice())).map_err(|error| broken(&error))?;
|
||||
measure(&decoder, 0)?
|
||||
};
|
||||
Ok(Probe { bytes: Cow::Owned(dib), dib: true, format: ImageFormat::Bmp, width, height, peak, png_alpha: None })
|
||||
@@ -147,6 +158,7 @@ fn sized(width: u32, height: u32, native: u64, held: u64) -> Result<(u32, u32, u
|
||||
|
||||
impl Probe<'_> {
|
||||
/// Bytes decoding takes at its peak.
|
||||
#[must_use]
|
||||
pub fn peak_bytes(&self) -> u64 {
|
||||
self.peak
|
||||
}
|
||||
@@ -164,12 +176,18 @@ impl Probe<'_> {
|
||||
}
|
||||
|
||||
/// Whether decoding fits `budget` bytes.
|
||||
#[must_use]
|
||||
pub fn fits(&self, budget: u64) -> bool {
|
||||
self.peak <= budget
|
||||
}
|
||||
|
||||
/// Decode, refused before anything is allocated when the peak would pass `budget` bytes. The
|
||||
/// decoder is held to the header's size and to `budget` as well.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `Refusal::TooLarge` when the picture does not fit `budget` and `Refusal::Broken`
|
||||
/// when the decoder rejects its input or limits.
|
||||
pub fn decode(&self, budget: u64) -> Result<DynamicImage, Refusal> {
|
||||
if !self.fits(budget) {
|
||||
return Err(Refusal::TooLarge { width: self.width, height: self.height });
|
||||
@@ -179,17 +197,21 @@ impl Probe<'_> {
|
||||
limits.max_image_height = Some(self.height);
|
||||
limits.max_alloc = Some(budget);
|
||||
if self.dib {
|
||||
let mut decoder = image::codecs::bmp::BmpDecoder::new_without_file_header(Cursor::new(&*self.bytes)).map_err(broken)?;
|
||||
decoder.set_limits(limits).map_err(broken)?;
|
||||
return DynamicImage::from_decoder(decoder).map_err(broken);
|
||||
let mut decoder = image::codecs::bmp::BmpDecoder::new_without_file_header(Cursor::new(&*self.bytes)).map_err(|error| broken(&error))?;
|
||||
decoder.set_limits(limits).map_err(|error| broken(&error))?;
|
||||
return DynamicImage::from_decoder(decoder).map_err(|error| broken(&error));
|
||||
}
|
||||
let mut reader = image::ImageReader::with_format(Cursor::new(&*self.bytes), self.format);
|
||||
reader.limits(limits);
|
||||
reader.decode().map_err(broken)
|
||||
reader.decode().map_err(|error| broken(&error))
|
||||
}
|
||||
}
|
||||
|
||||
/// [`probe`], then [`Probe::decode`] within `budget` bytes.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns the probing or decoding `Refusal`; see [`probe`] and [`Probe::decode`].
|
||||
pub fn decode(bytes: &[u8], budget: u64) -> Result<DynamicImage, Refusal> {
|
||||
probe(bytes)?.decode(budget)
|
||||
}
|
||||
@@ -553,6 +575,7 @@ mod tests {
|
||||
let mut s = vec![8];
|
||||
s.extend(h.to_be_bytes());
|
||||
s.extend(w.to_be_bytes());
|
||||
#[expect(clippy::cast_possible_truncation, reason = "These fixtures contain at most four three-byte component records.")]
|
||||
s.push((comps.len() / 3) as u8);
|
||||
s.extend(comps);
|
||||
s
|
||||
@@ -567,6 +590,7 @@ mod tests {
|
||||
// A marker walk over SOI, an APP0 segment, SOF2, then the scan.
|
||||
let mut jpeg = vec![0xFF, 0xD8, 0xFF, 0xE0, 0, 4, 0, 0, 0xFF, 0xC2];
|
||||
let f = sof(64, 64, &[1, 0x11, 0]);
|
||||
#[expect(clippy::cast_possible_truncation, reason = "This fixture's nine-byte frame header and length field fit u16.")]
|
||||
jpeg.extend(((f.len() + 2) as u16).to_be_bytes());
|
||||
jpeg.extend(&f);
|
||||
jpeg.extend([0xFF, 0xDA]);
|
||||
|
||||
+27
-10
@@ -8,11 +8,13 @@ pub const MAX_DECODED_BYTES: u64 = 512 * 1024 * 1024;
|
||||
pub const MAX_RASTER_PIXELS: u64 = 100_000_000;
|
||||
|
||||
/// Bytes of a `w`×`h` RGBA8 raster, None on overflow.
|
||||
#[must_use]
|
||||
pub fn rgba_bytes(w: u32, h: u32) -> Option<u64> {
|
||||
(w as u64).checked_mul(h as u64)?.checked_mul(4)
|
||||
u64::from(w).checked_mul(u64::from(h))?.checked_mul(4)
|
||||
}
|
||||
|
||||
/// Whether a `w`×`h` RGBA8 raster fits `budget` bytes.
|
||||
#[must_use]
|
||||
pub fn rgba_fits(w: u32, h: u32, budget: u64) -> bool {
|
||||
w > 0 && h > 0 && rgba_bytes(w, h).is_some_and(|b| b <= budget)
|
||||
}
|
||||
@@ -20,6 +22,7 @@ pub fn rgba_fits(w: u32, h: u32, budget: u64) -> bool {
|
||||
/// Whether decoding a `w`×`h` picture fits `budget` bytes at its peak: the decoder's buffer and
|
||||
/// the RGBA conversion (or its premultiplied copy) are alive together, so two RGBA buffers. For a
|
||||
/// decoder whose buffer isn't four bytes a pixel, see [`decode_peak_fits`].
|
||||
#[must_use]
|
||||
pub fn decode_fits(w: u32, h: u32, budget: u64) -> bool {
|
||||
decode_peak_fits(w, h, 4, budget)
|
||||
}
|
||||
@@ -27,24 +30,38 @@ pub fn decode_fits(w: u32, h: u32, budget: u64) -> bool {
|
||||
/// [`decode_fits`] for a decoder that hands back `native` bytes a pixel (8 for 16-bit RGBA, 16 for
|
||||
/// float RGBA): its buffer lives alongside the RGBA8 conversion, then the conversion alongside its
|
||||
/// premultiplied copy, so the peak is the larger of `native + 4` and `8` bytes a pixel.
|
||||
#[must_use]
|
||||
pub fn decode_peak_fits(w: u32, h: u32, native: u64, budget: u64) -> bool {
|
||||
let per_pixel = native.saturating_add(4).max(8);
|
||||
w > 0 && h > 0 && (w as u64).checked_mul(h as u64).and_then(|p| p.checked_mul(per_pixel)).is_some_and(|b| b <= budget)
|
||||
w > 0 && h > 0 && u64::from(w).checked_mul(u64::from(h)).and_then(|p| p.checked_mul(per_pixel)).is_some_and(|b| b <= budget)
|
||||
}
|
||||
|
||||
/// `w`×`h` shrunk (aspect kept, each side at least 1) until it holds at most `max_pixels`.
|
||||
#[must_use]
|
||||
pub fn fit_pixels(w: u32, h: u32, max_pixels: u64) -> (u32, u32) {
|
||||
let (w, h) = (w.max(1), h.max(1));
|
||||
let max_pixels = max_pixels.max(1);
|
||||
let area = w as u64 * h as u64;
|
||||
let area = u64::from(w) * u64::from(h);
|
||||
if area <= max_pixels {
|
||||
return (w, h);
|
||||
}
|
||||
let f = (max_pixels as f64 / area as f64).sqrt();
|
||||
let nh = ((h as f64 * f) as u64).clamp(1, h as u64);
|
||||
let nw = ((w as f64 * f) as u64).clamp(1, w as u64).min(max_pixels / nh).max(1);
|
||||
let nh = nh.min(max_pixels / nw).max(1);
|
||||
(nw as u32, nh as u32)
|
||||
#[expect(clippy::cast_precision_loss, reason = "Floating point only approximates the scale; the integer clamps below enforce every bound.")]
|
||||
let scale = (max_pixels as f64 / area as f64).sqrt();
|
||||
#[expect(
|
||||
clippy::cast_possible_truncation,
|
||||
clippy::cast_sign_loss,
|
||||
reason = "The scale is finite and within 0..=1; truncation floors a positive dimension before clamping."
|
||||
)]
|
||||
let new_height = ((f64::from(h) * scale) as u64).clamp(1, u64::from(h));
|
||||
#[expect(
|
||||
clippy::cast_possible_truncation,
|
||||
clippy::cast_sign_loss,
|
||||
reason = "The scale is finite and within 0..=1; truncation floors a positive dimension before clamping."
|
||||
)]
|
||||
let new_width = ((f64::from(w) * scale) as u64).clamp(1, u64::from(w)).min(max_pixels / new_height).max(1);
|
||||
let new_height = new_height.min(max_pixels / new_width).max(1);
|
||||
#[expect(clippy::cast_possible_truncation, reason = "Both dimensions are clamped to their original u32 values above.")]
|
||||
(new_width as u32, new_height as u32)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -78,9 +95,9 @@ mod tests {
|
||||
fn fit_pixels_keeps_normal_sizes_and_shrinks_huge_ones() {
|
||||
assert_eq!(fit_pixels(612, 792, MAX_RASTER_PIXELS), (612, 792));
|
||||
let (w, h) = fit_pixels(16_000, 16_000, 1_000_000);
|
||||
assert!(w as u64 * h as u64 <= 1_000_000 && w >= 900, "{w}x{h}");
|
||||
assert!(u64::from(w) * u64::from(h) <= 1_000_000 && w >= 900, "{w}x{h}");
|
||||
let (w, h) = fit_pixels(16_000, 1, 100);
|
||||
assert!(w as u64 * h as u64 <= 100 && h == 1, "{w}x{h}");
|
||||
assert!(u64::from(w) * u64::from(h) <= 100 && h == 1, "{w}x{h}");
|
||||
assert_eq!(fit_pixels(0, 5, 10).0, 1);
|
||||
}
|
||||
}
|
||||
@@ -63,6 +63,7 @@ impl Region {
|
||||
/// The region a BCP 47 or POSIX locale tag names (`pl-PL`, `pl_PL.UTF-8@euro`,
|
||||
/// `zh-Hans-CN`, `en-US-u-ms-metric`). An empty or unreadable tag, `C` and `POSIX` are
|
||||
/// `en-US`; a bare `en` is the United States, any other bare language has no territory.
|
||||
#[must_use]
|
||||
pub fn from_tag(tag: &str) -> Region {
|
||||
// Locale tags are short; anything long is junk and only its start is read.
|
||||
let tag: String = tag.chars().take(64).collect();
|
||||
@@ -97,6 +98,7 @@ impl Region {
|
||||
|
||||
/// This region with another territory (from a platform setting that names only the
|
||||
/// territory, like Windows' home location). A value that isn't a territory code is ignored.
|
||||
#[must_use]
|
||||
pub fn with_territory(mut self, territory: &str) -> Region {
|
||||
let t = territory.trim();
|
||||
let ok = (t.len() == 2 && t.chars().all(|c| c.is_ascii_alphabetic())) || (t.len() == 3 && t.chars().all(|c| c.is_ascii_digit()));
|
||||
@@ -109,6 +111,7 @@ impl Region {
|
||||
/// This region with the paper and the measurement system taken from their own locale tags,
|
||||
/// when the platform sets them apart (Unix `LC_PAPER`, `LC_MEASUREMENT`): `LANG=pl_PL.UTF-8`
|
||||
/// with `LC_PAPER=en_US.UTF-8` writes `2,54 cm` on Letter.
|
||||
#[must_use]
|
||||
pub fn with_paper_and_measurement(mut self, paper: Option<&str>, measurement: Option<&str>) -> Region {
|
||||
if let Some(t) = paper {
|
||||
self.letter = Some(Region::from_tag(t).uses_letter());
|
||||
@@ -134,21 +137,25 @@ impl Region {
|
||||
}
|
||||
|
||||
/// Does a new document start on US Letter here (otherwise A4)?
|
||||
#[must_use]
|
||||
pub fn uses_letter(&self) -> bool {
|
||||
self.letter.unwrap_or_else(|| LETTER.contains(&self.territory.as_str()))
|
||||
}
|
||||
|
||||
/// The default paper's name and portrait size in points: Letter (612 × 792) or A4.
|
||||
#[must_use]
|
||||
pub fn paper(&self) -> (&'static str, f32, f32) {
|
||||
if self.uses_letter() { ("Letter", 612.0, 792.0) } else { ("A4", 595.28, 841.89) }
|
||||
}
|
||||
|
||||
/// The unit lengths are shown in by default: inches in the US, centimetres elsewhere.
|
||||
#[must_use]
|
||||
pub fn units(&self) -> Unit {
|
||||
if self.inches.unwrap_or_else(|| INCHES.contains(&self.territory.as_str())) { Unit::Inches } else { Unit::Centimeters }
|
||||
}
|
||||
|
||||
/// The decimal separator numbers are written with here (`,` or `.`).
|
||||
#[must_use]
|
||||
pub fn decimal(&self) -> char {
|
||||
let lang = self.language.as_str();
|
||||
let t = self.territory.as_str();
|
||||
@@ -160,6 +167,7 @@ impl Region {
|
||||
}
|
||||
|
||||
/// `pt` in `unit` written the way this region writes numbers (`2,54 cm` in Poland).
|
||||
#[must_use]
|
||||
pub fn format(&self, unit: Unit, pt: f32) -> String {
|
||||
unit.format_with(pt, self.decimal())
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user