1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use std::{fmt, str};

#[derive(Debug, Default, Copy, Clone, Eq)]
/// Four character code representing a pixelformat
pub struct FourCC {
    pub repr: [u8; 4],
}

impl FourCC {
    #[allow(clippy::trivially_copy_pass_by_ref)]
    /// Returns a pixelformat as four character code
    ///
    /// # Arguments
    ///
    /// * `repr` - Four characters as raw bytes
    ///
    /// # Example
    ///
    /// ```
    /// use v4l::format::FourCC;
    /// let fourcc = FourCC::new(b"YUYV");
    /// ```
    pub fn new(repr: &[u8; 4]) -> FourCC {
        FourCC { repr: *repr }
    }

    /// Returns the string representation of a four character code
    ///
    /// # Example
    ///
    /// ```
    /// use v4l::format::FourCC;
    /// let fourcc = FourCC::new(b"YUYV");
    /// let str = fourcc.str().unwrap();
    /// ```
    pub fn str(&self) -> Result<&str, str::Utf8Error> {
        str::from_utf8(&self.repr)
    }
}

impl fmt::Display for FourCC {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let string = str::from_utf8(&self.repr);
        if let Ok(string) = string {
            write!(f, "{}", string)?;
        }
        Ok(())
    }
}

impl PartialEq for FourCC {
    fn eq(&self, other: &FourCC) -> bool {
        self.repr.iter().zip(other.repr.iter()).all(|(a, b)| a == b)
    }
}

impl From<u32> for FourCC {
    fn from(code: u32) -> Self {
        FourCC::new(&code.to_le_bytes())
    }
}

impl From<FourCC> for u32 {
    fn from(fourcc: FourCC) -> Self {
        Self::from_le_bytes(fourcc.repr)
    }
}