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
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

use crate::parser::{ParseError, SubtagIterator};
use crate::shortvec::ShortBoxSlice;
use crate::subtags::{subtag, Subtag};
use core::ops::RangeInclusive;
use core::str::FromStr;

/// A value used in a list of [`Fields`](super::Fields).
///
/// The value has to be a sequence of one or more alphanumerical strings
/// separated by `-`.
/// Each part of the sequence has to be no shorter than three characters and no
/// longer than 8.
///
/// # Examples
///
/// ```
/// use icu::locale::extensions::transform::Value;
///
/// "hybrid".parse::<Value>().expect("Valid Value.");
///
/// "hybrid-foobar".parse::<Value>().expect("Valid Value.");
///
/// "no".parse::<Value>().expect_err("Invalid Value.");
/// ```
#[derive(Debug, PartialEq, Eq, Clone, Hash, PartialOrd, Ord, Default)]
pub struct Value(ShortBoxSlice<Subtag>);

const TYPE_LENGTH: RangeInclusive<usize> = 3..=8;
const TRUE_TVALUE: Subtag = subtag!("true");

impl Value {
    /// A constructor which takes a str slice, parses it and
    /// produces a well-formed [`Value`].
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::locale::extensions::transform::Value;
    ///
    /// let value = Value::try_from_str("hybrid").expect("Parsing failed.");
    /// ```
    #[inline]
    pub fn try_from_str(s: &str) -> Result<Self, ParseError> {
        Self::try_from_utf8(s.as_bytes())
    }

    /// See [`Self::try_from_str`]
    pub fn try_from_utf8(code_units: &[u8]) -> Result<Self, ParseError> {
        let mut v = ShortBoxSlice::default();
        let mut has_value = false;

        for subtag in SubtagIterator::new(code_units) {
            if !Self::is_type_subtag(subtag) {
                return Err(ParseError::InvalidExtension);
            }
            has_value = true;
            let val = Subtag::try_from_utf8(subtag).map_err(|_| ParseError::InvalidExtension)?;
            if val != TRUE_TVALUE {
                v.push(val);
            }
        }

        if !has_value {
            return Err(ParseError::InvalidExtension);
        }
        Ok(Self(v))
    }

    pub(crate) fn from_short_slice_unchecked(input: ShortBoxSlice<Subtag>) -> Self {
        Self(input)
    }

    pub(crate) fn is_type_subtag(t: &[u8]) -> bool {
        TYPE_LENGTH.contains(&t.len()) && t.iter().all(u8::is_ascii_alphanumeric)
    }

    pub(crate) fn parse_subtag(t: &[u8]) -> Result<Option<Subtag>, ParseError> {
        if !TYPE_LENGTH.contains(&t.len()) {
            return Err(ParseError::InvalidExtension);
        }
        let s = Subtag::try_from_utf8(t).map_err(|_| ParseError::InvalidSubtag)?;

        let s = s.to_ascii_lowercase();

        if s == TRUE_TVALUE {
            Ok(None)
        } else {
            Ok(Some(s))
        }
    }

    pub(crate) fn for_each_subtag_str<E, F>(&self, f: &mut F) -> Result<(), E>
    where
        F: FnMut(&str) -> Result<(), E>,
    {
        if self.0.is_empty() {
            f(TRUE_TVALUE.as_str())?;
        } else {
            self.0.iter().map(Subtag::as_str).try_for_each(f)?;
        }
        Ok(())
    }
}

impl FromStr for Value {
    type Err = ParseError;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from_str(s)
    }
}

impl_writeable_for_each_subtag_str_no_test!(Value, selff, selff.0.is_empty() => alloc::borrow::Cow::Borrowed("true"));

#[test]
fn test_writeable() {
    use writeable::assert_writeable_eq;

    let hybrid = "hybrid".parse().unwrap();
    let foobar = "foobar".parse().unwrap();

    assert_writeable_eq!(Value::default(), "true");
    assert_writeable_eq!(
        Value::from_short_slice_unchecked(vec![hybrid].into()),
        "hybrid"
    );
    assert_writeable_eq!(
        Value::from_short_slice_unchecked(vec![hybrid, foobar].into()),
        "hybrid-foobar"
    );
}

#[test]
fn test_short_tvalue() {
    let value = Value::try_from_str("foo-longstag");
    assert!(value.is_ok());
    let value = value.unwrap();
    assert_eq!(value.0.len(), 2);
    for (s, reference) in value.0.iter().zip(&[subtag!("foo"), subtag!("longstag")]) {
        assert_eq!(s, reference);
    }

    let value = Value::try_from_str("foo-ba");
    assert!(value.is_err());
}