usecrate::fallback::{LocaleFallbackConfig, LocaleFallbackPriority, LocaleFallbackSupplement}; use alloc::borrow::Cow; use core::fmt; use core::fmt::Write; use core::ops::Deref; use writeable::{LengthHint, Writeable}; use zerovec::ule::*;
/// A compact hash of a [`DataKey`]. Useful for keys in maps. /// /// The hash will be stable over time within major releases. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Hash, ULE)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[repr(transparent)] pubstruct DataKeyHash([u8; 4]);
/// Gets the hash value as a byte array. pubconstfn to_bytes(self) -> [u8; 4] { self.0
}
}
/// Const function to compute the FxHash of a byte array. /// /// FxHash is a speedy hash algorithm used within rustc. The algorithm is satisfactory for our /// use case since the strings being hashed originate from a trusted source (the ICU4X /// components), and the hashes are computed at compile time, so we can check for collisions. /// /// We could have considered a SHA or other cryptographic hash function. However, we are using /// FxHash because: /// /// 1. There is precedent for this algorithm in Rust /// 2. The algorithm is easy to implement as a const function /// 3. The amount of code is small enough that we can reasonably keep the algorithm in-tree /// 4. FxHash is designed to output 32-bit or 64-bit values, whereas SHA outputs more bits, /// such that truncation would be required in order to fit into a u32, partially reducing /// the benefit of a cryptographically secure algorithm // The indexing operations in this function have been reviewed in detail and won't panic. #[allow(clippy::indexing_slicing)] constfn fxhash_32(bytes: &[u8], ignore_leading: usize, ignore_trailing: usize) -> u32 { // This code is adapted from https://github.com/rust-lang/rustc-hash, // whose license text is reproduced below. // // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
if ignore_leading + ignore_trailing >= bytes.len() { return0;
}
letmut cursor = ignore_leading; let end = bytes.len() - ignore_trailing; letmut hash = 0;
while end - cursor >= 4 { let word = u32::from_le_bytes([
bytes[cursor],
bytes[cursor + 1],
bytes[cursor + 2],
bytes[cursor + 3],
]);
hash = hash_word_32(hash, word);
cursor += 4;
}
if end - cursor >= 2 { let word = u16::from_le_bytes([bytes[cursor], bytes[cursor + 1]]);
hash = hash_word_32(hash, word as u32);
cursor += 2;
}
if end - cursor >= 1 {
hash = hash_word_32(hash, bytes[cursor] as u32);
}
hash
}
impl<'a> zerovec::maps::ZeroMapKV<'a> for DataKeyHash { type Container = zerovec::ZeroVec<'a, DataKeyHash>; type Slice = zerovec::ZeroSlice<DataKeyHash>; type GetType = <DataKeyHash as AsULE>::ULE; type OwnedType = DataKeyHash;
}
// Safe since the ULE type is `self`. unsafeimpl EqULE for DataKeyHash {}
/// The string path of a data key. For example, "foo@1" #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pubstruct DataKeyPath { // This string literal is wrapped in leading_tag!() and trailing_tag!() to make it detectable // in a compiled binary.
tagged: &'static str,
}
impl DataKeyPath { /// Gets the path as a static string slice. #[inline] pubconstfn get(self) -> &'static str { unsafe { // Safe due to invariant that self.path is tagged correctly
core::str::from_utf8_unchecked(core::slice::from_raw_parts( self.tagged.as_ptr().add(leading_tag!().len()), self.tagged.len() - trailing_tag!().len() - leading_tag!().len(),
))
}
}
}
impl Deref for DataKeyPath { type Target = str; #[inline] fn deref(&self) -> &Self::Target { self.get()
}
}
/// Metadata statically associated with a particular [`DataKey`]. #[derive(Debug, PartialEq, Eq, Copy, Clone, PartialOrd, Ord)] #[non_exhaustive] pubstruct DataKeyMetadata { /// What to prioritize when fallbacking on this [`DataKey`]. pub fallback_priority: LocaleFallbackPriority, /// A Unicode extension keyword to consider when loading data for this [`DataKey`]. pub extension_key: Option<icu_locid::extensions::unicode::Key>, /// Optional choice for additional fallbacking data required for loading this marker. /// /// For more information, see `LocaleFallbackConfig::fallback_supplement`. pub fallback_supplement: Option<LocaleFallbackSupplement>, /// Whether the key has a singleton value, as opposed to per-locale values. Singleton /// keys behave differently, e.g. they never perform fallback, and can be optimized /// in data providers. pub singleton: bool,
}
/// Used for loading data from an ICU4X data provider. /// /// A resource key is tightly coupled with the code that uses it to load data at runtime. /// Executables can be searched for `DataKey` instances to produce optimized data files. /// Therefore, users should not generally create DataKey instances; they should instead use /// the ones exported by a component. /// /// `DataKey`s are created with the [`data_key!`](crate::data_key) macro: /// /// ``` /// # use icu_provider::DataKey; /// const K: DataKey = icu_provider::data_key!("foo/bar@1"); /// ``` /// /// The human-readable path string ends with `@` followed by one or more digits (the version /// number). Paths do not contain characters other than ASCII letters and digits, `_`, `/`. /// /// Invalid paths are compile-time errors (as [`data_key!`](crate::data_key) uses `const`). /// /// ```compile_fail,E0080 /// # use icu_provider::DataKey; /// const K: DataKey = icu_provider::data_key!("foo/../bar@1"); /// ``` #[derive(Copy, Clone)] pubstruct DataKey {
path: DataKeyPath,
hash: DataKeyHash,
metadata: DataKeyMetadata,
}
impl DataKey { /// Gets a human-readable representation of a [`DataKey`]. /// /// The human-readable path string ends with `@` followed by one or more digits (the version /// number). Paths do not contain characters other than ASCII letters and digits, `_`, `/`. /// /// Useful for reading and writing data to a file system. #[inline] pubconstfn path(self) -> DataKeyPath { self.path
}
/// Gets a platform-independent hash of a [`DataKey`]. /// /// The hash is 4 bytes and allows for fast key comparison. /// /// # Example /// /// ``` /// use icu_provider::DataKey; /// use icu_provider::DataKeyHash; /// /// const KEY: DataKey = icu_provider::data_key!("foo@1"); /// const KEY_HASH: DataKeyHash = KEY.hashed(); /// /// assert_eq!(KEY_HASH.to_bytes(), [0xe2, 0xb6, 0x17, 0x71]); /// ``` #[inline] pubconstfn hashed(self) -> DataKeyHash { self.hash
}
/// Gets the metadata associated with this [`DataKey`]. #[inline] pubconstfn metadata(self) -> DataKeyMetadata { self.metadata
}
/// Returns the [`LocaleFallbackConfig`] for this [`DataKey`]. #[inline] pubconstfn fallback_config(self) -> LocaleFallbackConfig { letmut config = LocaleFallbackConfig::const_default();
config.priority = self.metadata.fallback_priority;
config.extension_key = self.metadata.extension_key;
config.fallback_supplement = self.metadata.fallback_supplement;
config
}
/// Constructs a [`DataKey`] from a path and metadata. /// /// # Examples /// /// ``` /// use icu_provider::data_key; /// use icu_provider::DataKey; /// /// const CONST_KEY: DataKey = data_key!("foo@1"); /// /// let runtime_key = /// DataKey::from_path_and_metadata(CONST_KEY.path(), CONST_KEY.metadata()); /// /// assert_eq!(CONST_KEY, runtime_key); /// ``` #[inline] pubconstfn from_path_and_metadata(path: DataKeyPath, metadata: DataKeyMetadata) -> Self{ Self {
path,
hash: DataKeyHash::compute_from_path(path),
metadata,
}
}
#[doc(hidden)] // Error is a str of the expected character class and the index where it wasn't encountered // The indexing operations in this function have been reviewed in detail and won't panic. #[allow(clippy::indexing_slicing)] pubconstfn construct_internal(
path: &'static str,
metadata: DataKeyMetadata,
) -> Result<Self, (&'static str, usize)> { if path.len() < leading_tag!().len() + trailing_tag!().len() { return Err(("tag", 0));
} // Start and end of the untagged part let start = leading_tag!().len(); let end = path.len() - trailing_tag!().len();
// Check tags letmut i = 0; while i < leading_tag!().len() { if path.as_bytes()[i] != leading_tag!().as_bytes()[i] { return Err(("tag", 0));
}
i += 1;
}
i = 0; while i < trailing_tag!().len() { if path.as_bytes()[end + i] != trailing_tag!().as_bytes()[i] { return Err(("tag", end + 1));
}
i += 1;
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.