use std::fmt;
use std::str::FromStr;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Unit {
Px,
Pt,
In,
Cm,
Mm,
}
impl Unit {
fn pt(self) -> Option<f64> {
match self {
Unit::Px => None,
Unit::Pt => Some(1.0),
Unit::In => Some(72.0),
Unit::Cm => Some(72.0 / 2.54),
Unit::Mm => Some(72.0 / 25.4),
}
}
fn suffix(self) -> &'static str {
match self {
Unit::Px => "px",
Unit::Pt => "pt",
Unit::In => "in",
Unit::Cm => "cm",
Unit::Mm => "mm",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Length {
pub value: f64,
pub unit: Unit,
}
impl Length {
pub fn new(value: f64, unit: Unit) -> Self {
Length { value, unit }
}
pub fn px(v: f64) -> Self {
Length::new(v, Unit::Px)
}
pub fn pt(v: f64) -> Self {
Length::new(v, Unit::Pt)
}
pub fn inches(v: f64) -> Self {
Length::new(v, Unit::In)
}
pub fn cm(v: f64) -> Self {
Length::new(v, Unit::Cm)
}
pub fn mm(v: f64) -> Self {
Length::new(v, Unit::Mm)
}
pub fn is_physical(&self) -> bool {
self.unit != Unit::Px
}
pub fn to_pt(&self) -> Option<f64> {
self.unit.pt().map(|k| self.value * k)
}
pub fn to_px(&self, dpi: f64) -> f64 {
match self.to_pt() {
Some(pt) => pt * dpi / 72.0,
None => self.value,
}
}
}
impl fmt::Display for Length {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let v = (self.value * 10_000.0).round() / 10_000.0;
match self.unit {
Unit::Px => write!(f, "{v}"),
u => write!(f, "{v}{}", u.suffix()),
}
}
}
impl FromStr for Length {
type Err = String;
fn from_str(s: &str) -> Result<Self, String> {
let t = s.trim().to_ascii_lowercase();
let split = t
.find(|c: char| !(c.is_ascii_digit() || c == '.'))
.unwrap_or(t.len());
let (num, unit) = t.split_at(split);
let unit = match unit.trim() {
"" | "px" => Unit::Px,
"pt" => Unit::Pt,
"in" | "inch" | "inches" => Unit::In,
"cm" => Unit::Cm,
"mm" => Unit::Mm,
u => return Err(format!("unknown unit '{u}' in '{s}' (px, pt, in, cm, mm)")),
};
let value: f64 = num
.parse()
.map_err(|_| format!("'{s}' is not a length (e.g. 16cm, 6.3in, 800)"))?;
if !(value.is_finite() && value > 0.0) {
return Err(format!("'{s}': a length must be above 0"));
}
Ok(Length { value, unit })
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PhysicalSize {
pub width: Length,
pub height: Length,
pub dpi: f64,
}
impl PhysicalSize {
pub fn new(width: Length, height: Length) -> Self {
PhysicalSize {
width,
height,
dpi: 300.0,
}
}
pub fn with_dpi(mut self, dpi: f64) -> Self {
self.dpi = dpi;
self
}
pub fn canvas(&self) -> Result<(u32, u32), String> {
match (self.width.to_pt(), self.height.to_pt()) {
(Some(w), Some(h)) => Ok((w.round().max(1.0) as u32, h.round().max(1.0) as u32)),
(None, None) => Ok((
self.width.value.round().max(1.0) as u32,
self.height.value.round().max(1.0) as u32,
)),
_ => {
Err("width and height must both be physical (cm, mm, in, pt) or both pixels".into())
}
}
}
pub fn raster_scale(&self) -> f64 {
if self.width.is_physical() && self.dpi.is_finite() && self.dpi > 0.0 {
self.dpi / 72.0
} else {
1.0
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lengths_parse_and_convert() {
let l: Length = "16cm".parse().unwrap();
assert_eq!(l, Length::cm(16.0));
assert!((l.to_pt().unwrap() - 453.543).abs() < 1e-3);
assert_eq!("6.3in".parse::<Length>().unwrap().to_pt(), Some(6.3 * 72.0));
assert_eq!("160 mm".parse::<Length>().unwrap(), Length::mm(160.0));
assert_eq!("800".parse::<Length>().unwrap(), Length::px(800.0));
assert_eq!("800px".parse::<Length>().unwrap().to_pt(), None);
for bad in ["", "cm", "16furlongs", "-3cm", "0in", "1.2.3cm"] {
assert!(bad.parse::<Length>().is_err(), "{bad}");
}
assert_eq!(Length::cm(16.0).to_string(), "16cm");
assert_eq!(Length::px(800.0).to_string(), "800");
assert_eq!(Length::inches(1.0).to_px(300.0), 300.0);
assert_eq!(Length::px(640.0).to_px(300.0), 640.0);
}
#[test]
fn a_size_gives_its_canvas_and_raster_scale() {
let s = PhysicalSize::new(Length::cm(16.0), Length::cm(7.5));
assert_eq!(s.canvas().unwrap(), (454, 213));
assert!((s.raster_scale() - 300.0 / 72.0).abs() < 1e-12);
let px = PhysicalSize::new(Length::px(800.0), Length::px(600.0));
assert_eq!((px.canvas().unwrap(), px.raster_scale()), ((800, 600), 1.0));
assert!(PhysicalSize::new(Length::cm(16.0), Length::px(600.0))
.canvas()
.is_err());
}
}