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//! Traits for data providers that produce opaque buffers.
6
7use crate::prelude::*;
8
9/// [`DataMarker`] for raw buffers. Returned by [`BufferProvider`].
10///
11/// The data is expected to be deserialized before it can be used; see
12/// [`DataPayload::into_deserialized`].
13#[allow(clippy::exhaustive_structs)] // marker type
14#[derive(Debug)]
15pub struct BufferMarker;
16
17impl DataMarker for BufferMarker {
18 type Yokeable = &'static [u8];
19}
20
21/// A data provider that returns opaque bytes.
22///
23/// Generally, these bytes are expected to be deserializable with Serde. To get an object
24/// implementing [`DataProvider`] via Serde, use [`as_deserializing()`].
25///
26/// Passing a `BufferProvider` to a `*_with_buffer_provider` constructor requires enabling
27/// the deserialization Cargo feature for the expected format(s):
28/// - `deserialize_json`
29/// - `deserialize_postcard_1`
30/// - `deserialize_bincode_1`
31///
32/// Along with [`DataProvider`], this is one of the two foundational traits in this crate.
33///
34/// [`BufferProvider`] can be made into a trait object. It is used over FFI.
35///
36/// # Examples
37///
38/// ```
39/// # #[cfg(feature = "deserialize_json")] {
40/// use icu_locid::locale;
41/// use icu_provider::hello_world::*;
42/// use icu_provider::prelude::*;
43/// use std::borrow::Cow;
44///
45/// let buffer_provider = HelloWorldProvider.into_json_provider();
46///
47/// let req = DataRequest {
48/// locale: &locale!("de").into(),
49/// metadata: Default::default(),
50/// };
51///
52/// // Deserializing manually
53/// assert_eq!(
54/// serde_json::from_slice::<HelloWorldV1>(
55/// buffer_provider
56/// .load_buffer(HelloWorldV1Marker::KEY, req)
57/// .expect("load should succeed")
58/// .take_payload()
59/// .unwrap()
60/// .get()
61/// )
62/// .expect("should deserialize"),
63/// HelloWorldV1 {
64/// message: Cow::Borrowed("Hallo Welt"),
65/// },
66/// );
67///
68/// // Deserialize automatically
69/// let deserializing_provider: &dyn DataProvider<HelloWorldV1Marker> =
70/// &buffer_provider.as_deserializing();
71///
72/// assert_eq!(
73/// deserializing_provider
74/// .load(req)
75/// .expect("load should succeed")
76/// .take_payload()
77/// .unwrap()
78/// .get(),
79/// &HelloWorldV1 {
80/// message: Cow::Borrowed("Hallo Welt"),
81/// },
82/// );
83/// # }
84/// ```
85///
86/// [`as_deserializing()`]: AsDeserializingBufferProvider::as_deserializing
87pub trait BufferProvider {
88 /// Loads a [`DataPayload`]`<`[`BufferMarker`]`>` according to the key and request.
89 fn load_buffer(
90 &self,
91 key: DataKey,
92 req: DataRequest,
93 ) -> Result<DataResponse<BufferMarker>, DataError>;
94}
95
96impl<T: BufferProvider + ?Sized> BufferProvider for alloc::boxed::Box<T> {
97 fn load_buffer(
98 &self,
99 key: DataKey,
100 req: DataRequest,
101 ) -> Result<DataResponse<BufferMarker>, DataError> {
102 (**self).load_buffer(key, req)
103 }
104}
105
106/// An enum expressing all Serde formats known to ICU4X.
107#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
108#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
109#[non_exhaustive]
110pub enum BufferFormat {
111 /// Serialize using JavaScript Object Notation (JSON).
112 Json,
113 /// Serialize using Bincode version 1.
114 Bincode1,
115 /// Serialize using Postcard version 1.
116 Postcard1,
117}
118
119impl BufferFormat {
120 /// Returns an error if the buffer format is not enabled.
121 pub fn check_available(&self) -> Result<(), DataError> {
122 match self {
123 #[cfg(feature = "deserialize_json")]
124 BufferFormat::Json => Ok(()),
125
126 #[cfg(feature = "deserialize_bincode_1")]
127 BufferFormat::Bincode1 => Ok(()),
128
129 #[cfg(feature = "deserialize_postcard_1")]
130 BufferFormat::Postcard1 => Ok(()),
131
132 // Allowed for cases in which all features are enabled
133 #[allow(unreachable_patterns)]
134 _ => Err(DataErrorKind::UnavailableBufferFormat(*self).into_error()),
135 }
136 }
137}
138