v4l/format/
fourcc.rs

1use std::{fmt, str};
2
3#[derive(Debug, Default, Copy, Clone, Eq)]
4/// Four character code representing a pixelformat
5pub struct FourCC {
6    pub repr: [u8; 4],
7}
8
9impl FourCC {
10    #[allow(clippy::trivially_copy_pass_by_ref)]
11    /// Returns a pixelformat as four character code
12    ///
13    /// # Arguments
14    ///
15    /// * `repr` - Four characters as raw bytes
16    ///
17    /// # Example
18    ///
19    /// ```
20    /// use v4l::format::FourCC;
21    /// let fourcc = FourCC::new(b"YUYV");
22    /// ```
23    pub fn new(repr: &[u8; 4]) -> FourCC {
24        FourCC { repr: *repr }
25    }
26
27    /// Returns the string representation of a four character code
28    ///
29    /// # Example
30    ///
31    /// ```
32    /// use v4l::format::FourCC;
33    /// let fourcc = FourCC::new(b"YUYV");
34    /// let str = fourcc.str().unwrap();
35    /// ```
36    pub fn str(&self) -> Result<&str, str::Utf8Error> {
37        str::from_utf8(&self.repr)
38    }
39}
40
41impl fmt::Display for FourCC {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        let string = str::from_utf8(&self.repr);
44        if let Ok(string) = string {
45            write!(f, "{}", string)?;
46        }
47        Ok(())
48    }
49}
50
51impl PartialEq for FourCC {
52    fn eq(&self, other: &FourCC) -> bool {
53        self.repr.iter().zip(other.repr.iter()).all(|(a, b)| a == b)
54    }
55}
56
57impl From<u32> for FourCC {
58    fn from(code: u32) -> Self {
59        FourCC::new(&code.to_le_bytes())
60    }
61}
62
63impl From<FourCC> for u32 {
64    fn from(fourcc: FourCC) -> Self {
65        Self::from_le_bytes(fourcc.repr)
66    }
67}