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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
//! Newtype wrapper providing a convenient representation of _four-character-code_ values.
//!
//! Using this type in a public APIs as an alternative to simply passing the equivalent `u32`
//! makes the value's expected use explicit.
//!
//!
//! ## Creating a FourCC value
//!
//! ```rust
//! use four_cc::FourCC;
//!
//! let uuid = FourCC(*b"uuid");
//! ```
//!
//! ## From a slice
//!
//! ```rust
//! # use four_cc::FourCC;
//! let data = b"moofftyp";
//! let code = FourCC::from(&data[0..4]);  // would panic if fewer than 4 bytes
//! assert_eq!(FourCC(*b"moof"), code);
//! ```
//!
//! ## Constants
//!
//! FourCC values can be used in const expressions
//!
//! ```rust
//! # use four_cc::FourCC;
//! const UUID: FourCC = FourCC(*b"uuid");
//! ```
//!
//! ## Matching
//!
//! You can use FourCC values in match patterns as long as you define constants to match against,
//!
//! ```rust
//! # use four_cc::FourCC;
//! const UUID: FourCC = FourCC(*b"uuid");
//! const MOOV: FourCC = FourCC(*b"moov");
//! # let other_value = UUID;
//! match other_value {
//!     MOOV => println!("movie"),
//!     UUID => println!("unique identifier"),
//!     // compiler will not accept: FourCC(*b"trun") => println!("track fragment run"),
//!     _ => println!("Other value; scary stuff")
//! }
//! ```
//!
//! ## Invalid literal values
//!
//! If the literal has other than four bytes, compilation will fail
//!
//! ```compile_fail
//! # use four_cc::FourCC;
//! let bad_fourcc = FourCC(*b"uuid123");
//! // -> expected an array with a fixed size of 4 elements, found one with 7 elements
//! ```
//! **Note** the FourCC value _may_ contain non-printable byte values, including the byte-value zero.
//!
//! ## Debug display
//!
//! ```rust
//! # use four_cc::FourCC;
//! # use std::fmt::Debug;
//! let uuid = FourCC(*b"uuid");
//! # assert_eq!("FourCC(uuid)", format!("{:?}", &uuid));
//! println!("it's {:?}", uuid);  // produces: it's FourCC{uuid}
//! ```
//!
//! Note that if the FourCC bytes are not able to be converted to UTF8, then a fallback
//! representation will be used (as it would be suprising for `format!()` to panic).
//!
//! ```rust
//! # use four_cc::FourCC;
//! # use std::fmt::Debug;
//! let uuid = FourCC(*b"u\xFFi\0");
//! # assert_eq!("FourCC(u\\xffi\\x00)", format!("{:?}", &uuid));
//! println!("it's {:?}", uuid);  // produces: it's FourCC{u\xffi\x00}
//! ```

#![forbid(unsafe_code)]
#![deny(rust_2018_idioms, future_incompatible, missing_docs)]
#![cfg_attr(feature = "nightly", feature(const_trait_impl))]
#![cfg_attr(not(feature = "std"), no_std)]

use core::fmt;
use core::result::Result;

/// A _four-character-code_ value.
///
/// See the [module level documentation](index.html).
#[derive(Clone,Copy,PartialEq,Eq,Hash)]
#[cfg_attr(feature = "zerocopy", derive(zerocopy::FromBytes, zerocopy::AsBytes))]
#[repr(C, packed)]
pub struct FourCC (
    pub [u8; 4]
);
impl FourCC {
    const fn from_u32(self: Self) -> u32 {
        ((self.0[0] as u32) << 24 & 0xff000000) |
        ((self.0[1] as u32) << 16 & 0x00ff0000) |
        ((self.0[2] as u32) << 8  & 0x0000ff00) |
        ((self.0[3] as u32)       & 0x000000ff)
    }
}
impl<'a> From<&'a[u8; 4]> for FourCC {
    fn from(buf: &[u8; 4]) -> FourCC {
        FourCC([buf[0], buf[1], buf[2], buf[3]])
    }
}
impl<'a> From<&'a[u8]> for FourCC {
    fn from(buf: &[u8]) -> FourCC {
        FourCC([buf[0], buf[1], buf[2], buf[3]])
    }
}
impl From<u32> for FourCC {
    fn from(val: u32) -> FourCC {
        FourCC([
            (val >> 24 & 0xff) as u8,
            (val >> 16 & 0xff) as u8,
            (val >> 8  & 0xff) as u8,
            (val       & 0xff) as u8
        ])
    }
}
// The macro is needed, because the `impl const` syntax doesn't exists on `stable`.
#[cfg(not(feature = "nightly"))]
macro_rules! from_fourcc_for_u32 {
    () => {
        impl From<FourCC> for u32 {
            fn from(val: FourCC) -> Self {
                val.from_u32()
            }
        }
    };
}
#[cfg(feature = "nightly")]
macro_rules! from_fourcc_for_u32 {
    ($($t:tt)*) => {
        impl const From<FourCC> for u32 {
            fn from(val: FourCC) -> Self {
                val.from_u32()
            }
        }
    };
}
from_fourcc_for_u32!();

impl fmt::Display for FourCC {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        match core::str::from_utf8(&self.0) {
            Ok(s) => f.write_str(s),
            Err(_) => {
                // If we return fmt::Error, then for example format!() will panic, so we choose
                // an alternative representation instead
                let b = &self.0;
                f.write_fmt(format_args!("{}{}{}{}",
                                         core::ascii::escape_default(b[0]),
                                         core::ascii::escape_default(b[1]),
                                         core::ascii::escape_default(b[2]),
                                         core::ascii::escape_default(b[3])))
            },
        }
    }
}

impl fmt::Debug for FourCC {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        let b = self.0;
        f.debug_tuple("FourCC")
          .field(&format_args!("{}{}{}{}",
                               core::ascii::escape_default(b[0]),
                               core::ascii::escape_default(b[1]),
                               core::ascii::escape_default(b[2]),
                               core::ascii::escape_default(b[3])))
          .finish()
    }
}

#[cfg(feature = "schemars")]
impl schemars::JsonSchema for FourCC {
    fn schema_name() -> String {
        "FourCC".to_string()
    }
    fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
        gen.subschema_for::<&str>()
    }
    fn is_referenceable() -> bool {
        false
    }
}

#[cfg(feature = "serde")]
impl serde::ser::Serialize for FourCC {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

#[cfg(feature = "serde")]
struct FromStrVisitor<T> {
    expecting: &'static str,
    ty: core::marker::PhantomData<T>,
}

#[cfg(feature = "serde")]
impl<T> FromStrVisitor<T> {
    fn new(expecting: &'static str) -> Self {
        FromStrVisitor {
            expecting: expecting,
            ty: core::marker::PhantomData,
        }
    }
}

#[cfg(feature = "serde")]
impl core::str::FromStr for FourCC {
    type Err = u32;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(s.as_bytes().into())
    }
}

#[cfg(feature = "serde")]
impl<'de, T> serde::de::Visitor<'de> for FromStrVisitor<T>
where
    T: core::str::FromStr,
    T::Err: fmt::Display,
{
    type Value = T;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.expecting)
    }

    fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        s.parse().map_err(serde::de::Error::custom)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::de::Deserialize<'de> for FourCC {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_str(FromStrVisitor::new("FourCC"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn eq() {
        assert_eq!(FourCC(*b"uuid"), b"uuid".into());
        assert_ne!(FourCC(*b"uuid"), b"diuu".into());
    }

    #[test]
    fn int_conversions() {
        assert_eq!(0x41424344u32, FourCC(*b"ABCD").into());
        assert_eq!(FourCC(*b"ABCD"), 0x41424344u32.into());
    }
}