Debian Codegraph @

third_party/rust/icu_provider/src/serde/mod.rs

raw
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 //! Provides the [`DeserializingBufferProvider`] wrapper, which deserializes data using Serde.
6 //!
7 //! Providers that produce opaque buffers that need to be deserialized into concrete data structs,
8 //! such as `FsDataProvider`, should implement [`BufferProvider`]. These can be converted into
9 //! [`DeserializingBufferProvider`] using the [`as_deserializing`](AsDeserializingBufferProvider::as_deserializing)
10 //! convenience method.
11 //!
12 //! [`BufferProvider`]: crate::buf::BufferProvider
13
14 // Hidden for now, but could be made public-stable in the future.
15 #[doc(hidden)]
16 pub mod borrow_de_utils;
17
18 use crate::buf::BufferFormat;
19 use crate::buf::BufferProvider;
20 use crate::prelude::*;
21 use serde::de::Deserialize;
22 use yoke::trait_hack::YokeTraitHack;
23 use yoke::Yokeable;
24
25 /// A [`BufferProvider`] that deserializes its data using Serde.
26 #[derive(Debug)]
27 pub struct DeserializingBufferProvider<'a, P: ?Sized>(&'a P);
28
29 /// Blanket-implemented trait adding the [`Self::as_deserializing()`] function.
30 pub trait AsDeserializingBufferProvider {
31 /// Wrap this [`BufferProvider`] in a [`DeserializingBufferProvider`].
32 ///
33 /// This requires enabling the deserialization Cargo feature
34 /// for the expected format(s):
35 ///
36 /// - `deserialize_json`
37 /// - `deserialize_postcard_1`
38 /// - `deserialize_bincode_1`
39 fn as_deserializing(&self) -> DeserializingBufferProvider<Self>;
40 }
41
42 impl<P> AsDeserializingBufferProvider for P
43 where
44 P: BufferProvider + ?Sized,
45 {
46 /// Wrap this [`BufferProvider`] in a [`DeserializingBufferProvider`].
47 ///
48 /// This requires enabling the deserialization Cargo feature
49 /// for the expected format(s):
50 ///
51 /// - `deserialize_json`
52 /// - `deserialize_postcard_1`
53 /// - `deserialize_bincode_1`
54 fn as_deserializing(&self) -> DeserializingBufferProvider<Self> {
55 DeserializingBufferProvider(self)
56 }
57 }
58
59 fn deserialize_impl<'data, M>(
60 // Allow `bytes` to be unused in case all buffer formats are disabled
61 #[allow(unused_variables)] bytes: &'data [u8],
62 buffer_format: BufferFormat,
63 ) -> Result<<M::Yokeable as Yokeable<'data>>::Output, DataError>
64 where
65 M: DataMarker,
66 // Actual bound:
67 // for<'de> <M::Yokeable as Yokeable<'de>>::Output: Deserialize<'de>,
68 // Necessary workaround bound (see `yoke::trait_hack` docs):
69 for<'de> YokeTraitHack<<M::Yokeable as Yokeable<'de>>::Output>: Deserialize<'de>,
70 {
71 match buffer_format {
72 #[cfg(feature = "deserialize_json")]
73 BufferFormat::Json => {
74 let mut d = serde_json::Deserializer::from_slice(bytes);
75 let data = YokeTraitHack::<<M::Yokeable as Yokeable>::Output>::deserialize(&mut d)?;
76 Ok(data.0)
77 }
78
79 #[cfg(feature = "deserialize_bincode_1")]
80 BufferFormat::Bincode1 => {
81 use bincode::Options;
82 let options = bincode::DefaultOptions::new()
83 .with_fixint_encoding()
84 .allow_trailing_bytes();
85 let mut d = bincode::de::Deserializer::from_slice(bytes, options);
86 let data = YokeTraitHack::<<M::Yokeable as Yokeable>::Output>::deserialize(&mut d)?;
87 Ok(data.0)
88 }
89
90 #[cfg(feature = "deserialize_postcard_1")]
91 BufferFormat::Postcard1 => {
92 let mut d = postcard::Deserializer::from_bytes(bytes);
93 let data = YokeTraitHack::<<M::Yokeable as Yokeable>::Output>::deserialize(&mut d)?;
94 Ok(data.0)
95 }
96
97 // Allowed for cases in which all features are enabled
98 #[allow(unreachable_patterns)]
99 _ => Err(DataErrorKind::UnavailableBufferFormat(buffer_format).into_error()),
100 }
101 }
102
103 impl DataPayload<BufferMarker> {
104 /// Deserialize a [`DataPayload`]`<`[`BufferMarker`]`>` into a [`DataPayload`] of a
105 /// specific concrete type.
106 ///
107 /// This requires enabling the deserialization Cargo feature
108 /// for the expected format(s):
109 ///
110 /// - `deserialize_json`
111 /// - `deserialize_postcard_1`
112 /// - `deserialize_bincode_1`
113 ///
114 /// This function takes the buffer format as an argument. When a buffer payload is returned
115 /// from a data provider, the buffer format is stored in the [`DataResponseMetadata`].
116 ///
117 /// # Examples
118 ///
119 /// Requires the `deserialize_json` Cargo feature:
120 ///
121 /// ```
122 /// use icu_provider::buf::BufferFormat;
123 /// use icu_provider::hello_world::*;
124 /// use icu_provider::prelude::*;
125 ///
126 /// let buffer: &[u8] = br#"{"message":"Hallo Welt"}"#;
127 ///
128 /// let buffer_payload = DataPayload::from_owned(buffer);
129 /// let payload: DataPayload<HelloWorldV1Marker> = buffer_payload
130 /// .into_deserialized(BufferFormat::Json)
131 /// .expect("Deserialization successful");
132 ///
133 /// assert_eq!(payload.get().message, "Hallo Welt");
134 /// ```
135 pub fn into_deserialized<M>(
136 self,
137 buffer_format: BufferFormat,
138 ) -> Result<DataPayload<M>, DataError>
139 where
140 M: DataMarker,
141 // Actual bound:
142 // for<'de> <M::Yokeable as Yokeable<'de>>::Output: Deserialize<'de>,
143 // Necessary workaround bound (see `yoke::trait_hack` docs):
144 for<'de> YokeTraitHack<<M::Yokeable as Yokeable<'de>>::Output>: Deserialize<'de>,
145 {
146 self.try_map_project(|bytes, _| deserialize_impl::<M>(bytes, buffer_format))
147 }
148 }
149
150 impl<P, M> DynamicDataProvider<M> for DeserializingBufferProvider<'_, P>
151 where
152 M: DataMarker,
153 P: BufferProvider + ?Sized,
154 // Actual bound:
155 // for<'de> <M::Yokeable as Yokeable<'de>>::Output: serde::de::Deserialize<'de>,
156 // Necessary workaround bound (see `yoke::trait_hack` docs):
157 for<'de> YokeTraitHack<<M::Yokeable as Yokeable<'de>>::Output>: Deserialize<'de>,
158 {
159 /// Converts a buffer into a concrete type by deserializing from a supported buffer format.
160 ///
161 /// This requires enabling the deserialization Cargo feature
162 /// for the expected format(s):
163 ///
164 /// - `deserialize_json`
165 /// - `deserialize_postcard_1`
166 /// - `deserialize_bincode_1`
167 fn load_data(&self, key: DataKey, req: DataRequest) -> Result<DataResponse<M>, DataError> {
168 let buffer_response = BufferProvider::load_buffer(self.0, key, req)?;
169 let buffer_format = buffer_response.metadata.buffer_format.ok_or_else(|| {
170 DataError::custom("BufferProvider didn't set BufferFormat").with_req(key, req)
171 })?;
172 Ok(DataResponse {
173 metadata: buffer_response.metadata,
174 payload: buffer_response
175 .payload
176 .map(|p| p.into_deserialized(buffer_format))
177 .transpose()
178 .map_err(|e| e.with_req(key, req))?,
179 })
180 }
181 }
182
183 impl<P, M> DataProvider<M> for DeserializingBufferProvider<'_, P>
184 where
185 M: KeyedDataMarker,
186 P: BufferProvider + ?Sized,
187 // Actual bound:
188 // for<'de> <M::Yokeable as Yokeable<'de>>::Output: Deserialize<'de>,
189 // Necessary workaround bound (see `yoke::trait_hack` docs):
190 for<'de> YokeTraitHack<<M::Yokeable as Yokeable<'de>>::Output>: Deserialize<'de>,
191 {
192 /// Converts a buffer into a concrete type by deserializing from a supported buffer format.
193 ///
194 /// This requires enabling the deserialization Cargo feature
195 /// for the expected format(s):
196 ///
197 /// - `deserialize_json`
198 /// - `deserialize_postcard_1`
199 /// - `deserialize_bincode_1`
200 fn load(&self, req: DataRequest) -> Result<DataResponse<M>, DataError> {
201 self.load_data(M::KEY, req)
202 }
203 }
204
205 #[cfg(feature = "deserialize_json")]
206 impl From<serde_json::error::Error> for crate::DataError {
207 fn from(e: serde_json::error::Error) -> Self {
208 crate::DataError::custom("JSON deserialize").with_display_context(&e)
209 }
210 }
211
212 #[cfg(feature = "deserialize_bincode_1")]
213 impl From<bincode::Error> for crate::DataError {
214 fn from(e: bincode::Error) -> Self {
215 crate::DataError::custom("Bincode deserialize").with_display_context(&e)
216 }
217 }
218
219 #[cfg(feature = "deserialize_postcard_1")]
220 impl From<postcard::Error> for crate::DataError {
221 fn from(e: postcard::Error) -> Self {
222 crate::DataError::custom("Postcard deserialize").with_display_context(&e)
223 }
224 }