ttf_name_decoder/
lib.rs

1//! This crate create decoder for ttf name record.
2//!
3//! # Usage
4//!
5//! ```rs
6//! let platform_id: u16 = 3; // Windows
7//! let encoding_id: u16 = 1; // Unicode
8//! let language_id: u16 = 1033; // English
9//! let name_data: Vec<u8> = get_data();
10//! let result = ttf_name_decoder::decode(&name_data)?;
11//! ```
12
13mod decoders;
14pub mod macintosh;
15mod macros;
16pub mod platform;
17pub mod unicode;
18pub mod windows;
19
20pub type Decoder = fn(data: &[u8]) -> Option<String>;
21#[derive(Debug, PartialEq)]
22pub enum Error {
23    UnsupportedPlatform,
24    UnsupportedEncoding,
25    UnsupportedLanguage,
26    CannotDecode,
27}
28pub type Result<T> = std::result::Result<T, Error>;
29
30pub fn decode(data: &[u8], platform_id: u16, encoding_id: u16, language_id: u16) -> Result<String> {
31    let d = get_decoder(platform_id, encoding_id, language_id)?;
32    d(data).ok_or(Error::CannotDecode)
33}
34
35fn get_decoder(platform_id: u16, encoding_id: u16, language_id: u16) -> Result<Decoder> {
36    use platform::PlatformId;
37    match PlatformId::try_from(platform_id)? {
38        PlatformId::Unicode => Ok(decoders::utf16_be_decode),
39        PlatformId::Macintosh => macintosh::get_decoder(encoding_id, language_id),
40        PlatformId::ISO => Err(Error::UnsupportedPlatform),
41        PlatformId::Windows => windows::get_decoder(encoding_id),
42        PlatformId::Custom => Err(Error::UnsupportedPlatform),
43    }
44}
45
46#[cfg(test)]
47mod tests {
48    #[test]
49    fn unicode() {
50        let data = vec![0x00, 0x74, 0x00, 0x65, 0x00, 0x73, 0x00, 0x74];
51        let result = super::decode(&data, 0, 0, 0).unwrap();
52        assert_eq!("test", result);
53    }
54    #[test]
55    fn windows_japanese() {
56        let data = vec![131, 101, 131, 88, 131, 103];
57        let result = super::decode(&data, 3, 2, 0).unwrap();
58        assert_eq!("ใƒ†ใ‚นใƒˆ", result);
59    }
60    #[test]
61    fn unsupported_platform() {
62        let data = vec![];
63        let err = super::decode(&data, 7, 0, 0).unwrap_err();
64        assert_eq!(super::Error::UnsupportedPlatform, err);
65    }
66}