icu_provider_adapters/fixed.rs
1// This file is part of ICU4X. For terms of use, please see the file
2// called LICENSE at the top level of the ICU4X source tree
3// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5//! Data provider always serving the same struct.
6
7use core::fmt;
8use icu_provider::prelude::*;
9use yoke::Yokeable;
10
11/// A data provider that returns clones of a fixed type-erased payload.
12///
13/// # Examples
14///
15/// ```
16/// use icu_provider::hello_world::*;
17/// use icu_provider::prelude::*;
18/// use icu_provider_adapters::fixed::FixedProvider;
19/// use std::borrow::Cow;
20/// use writeable::assert_writeable_eq;
21///
22/// let provider = FixedProvider::<HelloWorldV1>::from_static(&HelloWorld {
23/// message: Cow::Borrowed("custom hello world"),
24/// });
25///
26/// // Check that it works:
27/// let formatter =
28/// HelloWorldFormatter::try_new_unstable(&provider, Default::default())
29/// .expect("marker matches");
30/// assert_writeable_eq!(formatter.format(), "custom hello world");
31/// ```
32#[allow(clippy::exhaustive_structs)] // this type is stable
33pub struct FixedProvider<M: DataMarker> {
34 data: DataPayload<M>,
35}
36
37impl<M: DataMarker> FixedProvider<M> {
38 /// Creates a `FixedProvider` with an owned (allocated) payload of the given data.
39 pub fn from_owned(data: M::DataStruct) -> Self {
40 Self::from_payload(DataPayload::from_owned(data))
41 }
42
43 /// Creates a `FixedProvider` with a statically borrowed payload of the given data.
44 pub fn from_static(data: &'static M::DataStruct) -> Self {
45 FixedProvider {
46 data: DataPayload::from_static_ref(data),
47 }
48 }
49
50 /// Creates a `FixedProvider` from an existing [`DataPayload`].
51 pub fn from_payload(data: DataPayload<M>) -> Self {
52 FixedProvider { data }
53 }
54
55 /// Creates a `FixedProvider` with the default (allocated) version of the data struct.
56 pub fn new_default() -> Self
57 where
58 M::DataStruct: Default,
59 {
60 Self::from_owned(M::DataStruct::default())
61 }
62}
63
64impl<M> DataProvider<M> for FixedProvider<M>
65where
66 M: DataMarker,
67 for<'a> <M::DataStruct as Yokeable<'a>>::Output: Clone,
68{
69 fn load(&self, _: DataRequest) -> Result<DataResponse<M>, DataError> {
70 Ok(DataResponse {
71 metadata: Default::default(),
72 payload: self.data.clone(),
73 })
74 }
75}
76
77impl<M> fmt::Debug for FixedProvider<M>
78where
79 M: DynamicDataMarker,
80 M: DataMarker,
81 for<'a> &'a <M::DataStruct as Yokeable<'a>>::Output: fmt::Debug,
82{
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 self.data.fmt(f)
85 }
86}