1use crate::Error;
2
3#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
9pub struct Size {
10 pub width: u32,
12 pub height: u32,
14}
15
16impl Size {
17 pub fn new(width: u32, height: u32) -> Self {
19 Self { width, height }
20 }
21
22 pub fn pixels(&self) -> u64 {
24 self.width as u64 * self.height as u64
25 }
26
27 pub(crate) fn validate(&self, what: &str) -> Result<(), Error> {
33 if self.width == 0 || self.height == 0 {
34 return Err(Error::Codec(anyhow::anyhow!(
35 "{what} {self}: dimensions must be non-zero"
36 )));
37 }
38 if !self.width.is_multiple_of(2) || !self.height.is_multiple_of(2) {
39 return Err(Error::Codec(anyhow::anyhow!("{what} {self}: dimensions must be even")));
40 }
41 Ok(())
42 }
43}
44
45impl std::fmt::Display for Size {
46 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 write!(f, "{}x{}", self.width, self.height)
48 }
49}
50
51impl From<(u32, u32)> for Size {
52 fn from((width, height): (u32, u32)) -> Self {
53 Self::new(width, height)
54 }
55}
56
57#[cfg(test)]
58mod tests {
59 use super::*;
60
61 #[test]
62 fn validate_rejects_odd_and_zero() {
63 assert!(Size::new(320, 240).validate("frame").is_ok());
64 assert!(Size::new(0, 240).validate("frame").is_err());
65 assert!(Size::new(320, 0).validate("frame").is_err());
66 assert!(Size::new(321, 240).validate("frame").is_err());
67 assert!(Size::new(320, 241).validate("frame").is_err());
68 }
69
70 #[test]
71 fn display_reads_as_a_resolution() {
72 assert_eq!(Size::new(1920, 1080).to_string(), "1920x1080");
73 }
74}