1 | use std::path::{Path, PathBuf}; |
2 | |
3 | use crate::{ |
4 | common::{ |
5 | parse_codepoint_association, CodepointIter, Codepoints, UcdFile, |
6 | UcdFileByCodepoint, |
7 | }, |
8 | error::Error, |
9 | }; |
10 | |
11 | /// A single row in the `emoji-data.txt` file. |
12 | /// |
13 | /// The `emoji-data.txt` file is the source of truth on several Emoji-related |
14 | /// Unicode properties. |
15 | /// |
16 | /// Note that `emoji-data.txt` is not formally part of the Unicode Character |
17 | /// Database. You can download the Emoji data files separately here: |
18 | /// https://unicode.org/Public/emoji/ |
19 | #[derive (Clone, Debug, Default, Eq, PartialEq)] |
20 | pub struct EmojiProperty { |
21 | /// The codepoint or codepoint range for this entry. |
22 | pub codepoints: Codepoints, |
23 | /// The property name assigned to the codepoints in this entry. |
24 | pub property: String, |
25 | } |
26 | |
27 | impl UcdFile for EmojiProperty { |
28 | fn relative_file_path() -> &'static Path { |
29 | Path::new("emoji/emoji-data.txt" ) |
30 | } |
31 | |
32 | fn file_path<P: AsRef<Path>>(ucd_dir: P) -> PathBuf { |
33 | let ucd_dir = ucd_dir.as_ref(); |
34 | // The standard location, but only on UCDs from 13.0.0 and up. |
35 | let std = ucd_dir.join(Self::relative_file_path()); |
36 | if std.exists() { |
37 | std |
38 | } else { |
39 | // If the old location does exist, use it. |
40 | let legacy = ucd_dir.join("emoji-data.txt" ); |
41 | if legacy.exists() { |
42 | legacy |
43 | } else { |
44 | // This might end up in an error message, so use the standard |
45 | // one if forced to choose. Arguably we could do something like |
46 | // peek |
47 | std |
48 | } |
49 | } |
50 | } |
51 | } |
52 | |
53 | impl UcdFileByCodepoint for EmojiProperty { |
54 | fn codepoints(&self) -> CodepointIter { |
55 | self.codepoints.into_iter() |
56 | } |
57 | } |
58 | |
59 | impl std::str::FromStr for EmojiProperty { |
60 | type Err = Error; |
61 | |
62 | fn from_str(line: &str) -> Result<EmojiProperty, Error> { |
63 | let (codepoints: Codepoints, property: &str) = parse_codepoint_association(line)?; |
64 | Ok(EmojiProperty { codepoints, property: property.to_string() }) |
65 | } |
66 | } |
67 | |
68 | #[cfg (test)] |
69 | mod tests { |
70 | use super::EmojiProperty; |
71 | |
72 | #[test ] |
73 | fn parse_single() { |
74 | let line = "24C2 ; Emoji # 1.1 [1] (Ⓜ️) circled M \n" ; |
75 | let row: EmojiProperty = line.parse().unwrap(); |
76 | assert_eq!(row.codepoints, 0x24C2); |
77 | assert_eq!(row.property, "Emoji" ); |
78 | } |
79 | |
80 | #[test ] |
81 | fn parse_range() { |
82 | let line = "1FA6E..1FFFD ; Extended_Pictographic# NA[1424] (️..️) <reserved-1FA6E>..<reserved-1FFFD> \n" ; |
83 | let row: EmojiProperty = line.parse().unwrap(); |
84 | assert_eq!(row.codepoints, (0x1FA6E, 0x1FFFD)); |
85 | assert_eq!(row.property, "Extended_Pictographic" ); |
86 | } |
87 | } |
88 | |