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 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
// 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, ShortBoxSliceIntoIter};
use crate::subtags::{subtag, Subtag};
use alloc::vec::Vec;
use core::str::FromStr;
/// A value used in a list of [`Keywords`](super::Keywords).
///
/// 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::unicode::{value, Value};
/// use writeable::assert_writeable_eq;
///
/// assert_writeable_eq!(value!("gregory"), "gregory");
/// assert_writeable_eq!(
/// "islamic-civil".parse::<Value>().unwrap(),
/// "islamic-civil"
/// );
///
/// // The value "true" has the special, empty string representation
/// assert_eq!(value!("true").to_string(), "");
/// ```
#[derive(Debug, PartialEq, Eq, Clone, Hash, PartialOrd, Ord, Default)]
pub struct Value(ShortBoxSlice<Subtag>);
const TRUE_VALUE: Subtag = subtag!("true");
impl Value {
/// A constructor which str slice, parses it and
/// produces a well-formed [`Value`].
///
/// # Examples
///
/// ```
/// use icu::locale::extensions::unicode::Value;
///
/// Value::try_from_str("buddhist").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::new();
if !code_units.is_empty() {
for chunk in SubtagIterator::new(code_units) {
let subtag = Subtag::try_from_utf8(chunk)?;
if subtag != TRUE_VALUE {
v.push(subtag);
}
}
}
Ok(Self(v))
}
/// Returns a reference to a single [`Subtag`] if the [`Value`] contains exactly one
/// subtag, or `None` otherwise.
///
/// # Examples
///
/// ```
/// use icu::locale::extensions::unicode::Value;
/// use core::str::FromStr;
///
/// let value1 = Value::from_str("foo")
/// .expect("failed to parse a Value");
/// let value2 = Value::from_str("foo-bar")
/// .expect("failed to parse a Value");
///
/// assert!(value1.as_single_subtag().is_some());
/// assert!(value2.as_single_subtag().is_none());
/// ```
pub const fn as_single_subtag(&self) -> Option<&Subtag> {
self.0.single()
}
/// Destructs into a single [`Subtag`] if the [`Value`] contains exactly one
/// subtag, or returns `None` otherwise.
///
/// # Examples
///
/// ```
/// use icu::locale::extensions::unicode::Value;
/// use core::str::FromStr;
///
/// let value1 = Value::from_str("foo")
/// .expect("failed to parse a Value");
/// let value2 = Value::from_str("foo-bar")
/// .expect("failed to parse a Value");
///
/// assert!(value1.into_single_subtag().is_some());
/// assert!(value2.into_single_subtag().is_none());
/// ```
pub fn into_single_subtag(self) -> Option<Subtag> {
self.0.into_single()
}
#[doc(hidden)]
pub fn as_subtags_slice(&self) -> &[Subtag] {
&self.0
}
/// Appends a subtag to the back of a [`Value`].
///
/// # Examples
///
/// ```
/// use icu::locale::{
/// extensions::unicode::Value,
/// subtags::subtag,
/// };
///
/// let mut v = Value::default();
/// v.push_subtag(subtag!("foo"));
/// v.push_subtag(subtag!("bar"));
/// assert_eq!(v, "foo-bar");
/// ```
pub fn push_subtag(&mut self, subtag: Subtag) {
self.0.push(subtag);
}
/// Returns the number of subtags in the [`Value`].
///
/// # Examples
///
/// ```
/// use icu::locale::{
/// extensions::unicode::Value,
/// subtags::subtag,
/// };
///
/// let mut v = Value::default();
/// assert_eq!(v.subtag_count(), 0);
/// v.push_subtag(subtag!("foo"));
/// assert_eq!(v.subtag_count(), 1);
/// ```
pub fn subtag_count(&self) -> usize {
self.0.len()
}
/// Returns `true` if the Value has no subtags.
///
/// # Examples
///
/// ```
/// use icu::locale::{
/// extensions::unicode::Value,
/// subtags::subtag,
/// };
///
/// let mut v = Value::default();
/// assert_eq!(v.is_empty(), true);
/// ```
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Removes and returns the subtag at position `index` within the value,
/// shifting all subtags after it to the left.
///
/// # Examples
///
/// ```
/// use icu::locale::{
/// extensions::unicode::Value,
/// subtags::subtag,
/// };
/// let mut v = Value::default();
/// v.push_subtag(subtag!("foo"));
/// v.push_subtag(subtag!("bar"));
/// v.push_subtag(subtag!("baz"));
///
/// assert_eq!(v.remove_subtag(1), Some(subtag!("bar")));
/// assert_eq!(v, "foo-baz");
/// ```
pub fn remove_subtag(&mut self, idx: usize) -> Option<Subtag> {
if self.0.len() < idx {
None
} else {
let item = self.0.remove(idx);
Some(item)
}
}
/// Returns a reference to a subtag at index.
///
/// # Examples
///
/// ```
/// use icu::locale::{
/// extensions::unicode::Value,
/// subtags::subtag,
/// };
/// let mut v = Value::default();
/// v.push_subtag(subtag!("foo"));
/// v.push_subtag(subtag!("bar"));
/// v.push_subtag(subtag!("baz"));
///
/// assert_eq!(v.get_subtag(1), Some(&subtag!("bar")));
/// assert_eq!(v.get_subtag(3), None);
/// ```
pub fn get_subtag(&self, idx: usize) -> Option<&Subtag> {
self.0.get(idx)
}
#[doc(hidden)]
pub const fn from_subtag(subtag: Option<Subtag>) -> Self {
match subtag {
None | Some(TRUE_VALUE) => Self(ShortBoxSlice::new()),
Some(val) => Self(ShortBoxSlice::new_single(val)),
}
}
/// A constructor which takes a pre-sorted list of [`Value`] elements.
///
///
/// # Examples
///
/// ```
/// use icu::locale::extensions::unicode::Value;
/// use icu::locale::subtags::subtag;
///
/// let subtag1 = subtag!("foobar");
/// let subtag2 = subtag!("testing");
/// let mut v = vec![subtag1, subtag2];
/// v.sort();
/// v.dedup();
///
/// let value = Value::from_vec_unchecked(v);
/// ```
///
/// Notice: For performance- and memory-constrained environments, it is recommended
/// for the caller to use [`binary_search`](slice::binary_search) instead of [`sort`](slice::sort)
/// and [`dedup`](Vec::dedup()).
pub fn from_vec_unchecked(input: Vec<Subtag>) -> Self {
Self(input.into())
}
pub(crate) fn from_short_slice_unchecked(input: ShortBoxSlice<Subtag>) -> Self {
Self(input)
}
pub(crate) const fn parse_subtag_from_utf8(t: &[u8]) -> Result<Option<Subtag>, ParseError> {
match Subtag::try_from_utf8(t) {
Ok(TRUE_VALUE) => Ok(None),
Ok(s) => Ok(Some(s)),
Err(_) => Err(ParseError::InvalidSubtag),
}
}
pub(crate) fn for_each_subtag_str<E, F>(&self, f: &mut F) -> Result<(), E>
where
F: FnMut(&str) -> Result<(), E>,
{
self.0.iter().map(Subtag::as_str).try_for_each(f)
}
}
impl IntoIterator for Value {
type Item = Subtag;
type IntoIter = ShortBoxSliceIntoIter<Subtag>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl FromIterator<Subtag> for Value {
fn from_iter<T: IntoIterator<Item = Subtag>>(iter: T) -> Self {
Self(ShortBoxSlice::from_iter(iter))
}
}
impl Extend<Subtag> for Value {
fn extend<T: IntoIterator<Item = Subtag>>(&mut self, iter: T) {
for i in iter {
self.0.push(i);
}
}
}
impl FromStr for Value {
type Err = ParseError;
#[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::try_from_str(s)
}
}
impl PartialEq<&str> for Value {
fn eq(&self, other: &&str) -> bool {
writeable::cmp_bytes(self, other.as_bytes()).is_eq()
}
}
impl_writeable_for_subtag_list!(Value, "islamic", "civil");
/// A macro allowing for compile-time construction of valid Unicode [`Value`] subtag.
///
/// The macro only supports single-subtag values.
///
/// # Examples
///
/// ```
/// use icu::locale::extensions::unicode::{key, value};
/// use icu::locale::Locale;
///
/// let loc: Locale = "de-u-ca-buddhist".parse().unwrap();
///
/// assert_eq!(
/// loc.extensions.unicode.keywords.get(&key!("ca")),
/// Some(&value!("buddhist"))
/// );
/// ```
///
/// [`Value`]: crate::extensions::unicode::Value
#[macro_export]
#[doc(hidden)] // macro
macro_rules! extensions_unicode_value {
($value:literal) => {{
// What we want:
// const R: $crate::extensions::unicode::Value =
// match $crate::extensions::unicode::Value::try_from_single_subtag($value.as_bytes()) {
// Ok(r) => r,
// #[allow(clippy::panic)] // const context
// _ => panic!(concat!("Invalid Unicode extension value: ", $value)),
// };
// Workaround until https://github.com/rust-lang/rust/issues/73255 lands:
const R: $crate::extensions::unicode::Value =
$crate::extensions::unicode::Value::from_subtag(
match $crate::subtags::Subtag::try_from_utf8($value.as_bytes()) {
Ok(r) => Some(r),
_ => panic!(concat!("Invalid Unicode extension value: ", $value)),
},
);
R
}};
}
#[doc(inline)]
pub use extensions_unicode_value as value;