Skip to main content

martin_core/
image_quality.rs

1//! How lossy encoded images are, shared by rendered styles and re-encoded COG tiles.
2
3use std::fmt;
4use std::num::NonZeroU8;
5
6use serde::de::{self, Visitor};
7use serde::{Deserialize, Deserializer, Serialize, Serializer};
8
9/// Quality of a lossy encode, 1 (smallest) to 100 (best).
10#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
11#[serde(transparent)]
12pub struct LossyQuality(NonZeroU8);
13
14impl LossyQuality {
15    /// The quality, if `quality` is 1 to 100.
16    #[must_use]
17    pub const fn new(quality: u8) -> Option<Self> {
18        match NonZeroU8::new(quality) {
19            Some(quality) if quality.get() <= 100 => Some(Self(quality)),
20            _ => None,
21        }
22    }
23
24    /// The quality, 1 to 100.
25    #[must_use]
26    pub const fn get(self) -> u8 {
27        self.0.get()
28    }
29}
30
31impl Default for LossyQuality {
32    fn default() -> Self {
33        Self::new(80).expect("80 is a quality")
34    }
35}
36
37/// How lossy a WebP is encoded.
38///
39/// Deserializes from a number 1 to 100 or the string `lossless`.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41pub enum ImageQuality {
42    /// Keep every pixel.
43    Lossless,
44    /// Lossy at this quality.
45    Lossy(LossyQuality),
46}
47
48impl Default for ImageQuality {
49    fn default() -> Self {
50        Self::Lossy(LossyQuality::default())
51    }
52}
53
54impl Serialize for ImageQuality {
55    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
56        match self {
57            Self::Lossless => serializer.serialize_str("lossless"),
58            Self::Lossy(quality) => quality.serialize(serializer),
59        }
60    }
61}
62
63/// The quality `quality` is, or an error naming the `allowed` values.
64fn lossy<E: de::Error>(quality: u64, allowed: &str) -> Result<LossyQuality, E> {
65    u8::try_from(quality)
66        .ok()
67        .and_then(LossyQuality::new)
68        .ok_or_else(|| E::custom(format_args!("quality must be {allowed}, not {quality}")))
69}
70
71const WEBP_QUALITIES: &str = r#"1 to 100 or "lossless""#;
72
73impl<'de> Deserialize<'de> for LossyQuality {
74    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
75        struct LossyVisitor;
76
77        impl Visitor<'_> for LossyVisitor {
78            type Value = LossyQuality;
79
80            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
81                f.write_str("a quality from 1 to 100")
82            }
83
84            fn visit_u64<E: de::Error>(self, quality: u64) -> Result<LossyQuality, E> {
85                lossy(quality, "1 to 100")
86            }
87        }
88
89        deserializer.deserialize_any(LossyVisitor)
90    }
91}
92
93impl<'de> Deserialize<'de> for ImageQuality {
94    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
95        struct QualityVisitor;
96
97        impl Visitor<'_> for QualityVisitor {
98            type Value = ImageQuality;
99
100            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
101                f.write_str(r#"a quality from 1 to 100, or "lossless""#)
102            }
103
104            fn visit_u64<E: de::Error>(self, quality: u64) -> Result<ImageQuality, E> {
105                lossy(quality, WEBP_QUALITIES).map(ImageQuality::Lossy)
106            }
107
108            fn visit_str<E: de::Error>(self, quality: &str) -> Result<ImageQuality, E> {
109                if quality == "lossless" {
110                    Ok(ImageQuality::Lossless)
111                } else {
112                    Err(E::custom(format_args!(
113                        r#"quality must be {WEBP_QUALITIES}, not "{quality}""#
114                    )))
115                }
116            }
117        }
118
119        deserializer.deserialize_any(QualityVisitor)
120    }
121}
122
123#[cfg(feature = "unstable-schemas")]
124impl schemars::JsonSchema for LossyQuality {
125    fn schema_name() -> std::borrow::Cow<'static, str> {
126        std::borrow::Cow::Borrowed("LossyQuality")
127    }
128
129    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
130        schemars::json_schema!({
131            "description": "Lossy quality from 1 to 100.",
132            "type": "integer",
133            "minimum": 1,
134            "maximum": 100
135        })
136    }
137}
138
139#[cfg(feature = "unstable-schemas")]
140impl schemars::JsonSchema for ImageQuality {
141    fn schema_name() -> std::borrow::Cow<'static, str> {
142        std::borrow::Cow::Borrowed("ImageQuality")
143    }
144
145    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
146        schemars::json_schema!({
147            "description": "Lossy quality from 1 to 100, or `lossless`.",
148            "oneOf": [
149                { "type": "integer", "minimum": 1, "maximum": 100 },
150                { "const": "lossless" }
151            ]
152        })
153    }
154}
155
156#[cfg(test)]
157mod tests {
158    use rstest::rstest;
159
160    use super::*;
161
162    #[rstest]
163    #[case::zero(0, None)]
164    #[case::lowest(1, Some(1))]
165    #[case::highest(100, Some(100))]
166    #[case::above_100(101, None)]
167    fn a_lossy_quality_is_1_to_100(#[case] quality: u8, #[case] expected: Option<u8>) {
168        assert_eq!(LossyQuality::new(quality).map(LossyQuality::get), expected);
169    }
170}