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
use std::path::Path;

use crate::{common::UcdFile, error::Error};

/// A single row in the `PropertyValueAliases.txt` file.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct PropertyValueAlias {
    /// The property name for which this value alias applies.
    pub property: String,
    /// A numeric abbreviation for this property value, if present. (This is
    /// seemingly only present for the `ccc`/`Canonical_Combining_Class`
    /// property.)
    pub numeric: Option<u8>,
    /// An abbreviation for this property value.
    pub abbreviation: String,
    /// The "long" form of this property value.
    pub long: String,
    /// Additional value aliases (if present).
    pub aliases: Vec<String>,
}

impl UcdFile for PropertyValueAlias {
    fn relative_file_path() -> &'static Path {
        Path::new("PropertyValueAliases.txt")
    }
}

impl std::str::FromStr for PropertyValueAlias {
    type Err = Error;

    fn from_str(line: &str) -> Result<PropertyValueAlias, Error> {
        let re_parts = regex!(
            r"(?x)
                ^
                \s*(?P<prop>[^\s;]+)\s*;
                \s*(?P<abbrev>[^\s;]+)\s*;
                \s*(?P<long>[^\s;]+)\s*
                (?:;(?P<aliases>.*))?
                ",
        );
        let re_parts_ccc = regex!(
            r"(?x)
                ^
                ccc;
                \s*(?P<num_class>[0-9]+)\s*;
                \s*(?P<abbrev>[^\s;]+)\s*;
                \s*(?P<long>[^\s;]+)
                ",
        );
        let re_aliases = regex!(r"\s*(?P<alias>[^\s;]+)\s*;?\s*");

        if line.starts_with("ccc;") {
            let caps = match re_parts_ccc.captures(line.trim()) {
                Some(caps) => caps,
                None => {
                    return err!("invalid PropertyValueAliases (ccc) line")
                }
            };
            let n = match caps["num_class"].parse() {
                Ok(n) => n,
                Err(err) => {
                    return err!(
                        "failed to parse ccc number '{}': {}",
                        &caps["num_class"],
                        err
                    )
                }
            };
            let abbrev = caps.name("abbrev").unwrap().as_str();
            let long = caps.name("long").unwrap().as_str();
            return Ok(PropertyValueAlias {
                property: line[0..3].to_string(),
                numeric: Some(n),
                abbreviation: abbrev.to_string(),
                long: long.to_string(),
                aliases: vec![],
            });
        }

        let caps = match re_parts.captures(line.trim()) {
            Some(caps) => caps,
            None => return err!("invalid PropertyValueAliases line"),
        };
        let mut aliases = vec![];
        if let Some(m) = caps.name("aliases") {
            for acaps in re_aliases.captures_iter(m.as_str()) {
                let alias = acaps.name("alias").unwrap().as_str();
                if alias == "#" {
                    // This starts a comment, so stop reading.
                    break;
                }
                aliases.push(alias.to_string());
            }
        }
        Ok(PropertyValueAlias {
            property: caps.name("prop").unwrap().as_str().to_string(),
            numeric: None,
            abbreviation: caps.name("abbrev").unwrap().as_str().to_string(),
            long: caps.name("long").unwrap().as_str().to_string(),
            aliases,
        })
    }
}

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

    #[test]
    fn parse1() {
        let line = "blk; Arabic_PF_A                      ; Arabic_Presentation_Forms_A      ; Arabic_Presentation_Forms-A\n";
        let row: PropertyValueAlias = line.parse().unwrap();
        assert_eq!(row.property, "blk");
        assert_eq!(row.numeric, None);
        assert_eq!(row.abbreviation, "Arabic_PF_A");
        assert_eq!(row.long, "Arabic_Presentation_Forms_A");
        assert_eq!(row.aliases, vec!["Arabic_Presentation_Forms-A"]);
    }

    #[test]
    fn parse2() {
        let line = "AHex; N                               ; No                               ; F                                ; False\n";
        let row: PropertyValueAlias = line.parse().unwrap();
        assert_eq!(row.property, "AHex");
        assert_eq!(row.numeric, None);
        assert_eq!(row.abbreviation, "N");
        assert_eq!(row.long, "No");
        assert_eq!(row.aliases, vec!["F", "False"]);
    }

    #[test]
    fn parse3() {
        let line = "age; 1.1                              ; V1_1\n";
        let row: PropertyValueAlias = line.parse().unwrap();
        assert_eq!(row.property, "age");
        assert_eq!(row.numeric, None);
        assert_eq!(row.abbreviation, "1.1");
        assert_eq!(row.long, "V1_1");
        assert!(row.aliases.is_empty());
    }

    #[test]
    fn parse4() {
        let line = "ccc;   0; NR                         ; Not_Reordered\n";
        let row: PropertyValueAlias = line.parse().unwrap();
        assert_eq!(row.property, "ccc");
        assert_eq!(row.numeric, Some(0));
        assert_eq!(row.abbreviation, "NR");
        assert_eq!(row.long, "Not_Reordered");
        assert!(row.aliases.is_empty());
    }

    #[test]
    fn parse5() {
        let line =
            "ccc; 133; CCC133                     ; CCC133 # RESERVED\n";
        let row: PropertyValueAlias = line.parse().unwrap();
        assert_eq!(row.property, "ccc");
        assert_eq!(row.numeric, Some(133));
        assert_eq!(row.abbreviation, "CCC133");
        assert_eq!(row.long, "CCC133");
        assert!(row.aliases.is_empty());
    }

    #[test]
    fn parse6() {
        let line = "gc ; P                                ; Punctuation                      ; punct                            # Pc | Pd | Pe | Pf | Pi | Po | Ps\n";
        let row: PropertyValueAlias = line.parse().unwrap();
        assert_eq!(row.property, "gc");
        assert_eq!(row.numeric, None);
        assert_eq!(row.abbreviation, "P");
        assert_eq!(row.long, "Punctuation");
        assert_eq!(row.aliases, vec!["punct"]);
    }
}