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
// 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 ).

//! Provides the [`DeserializingBufferProvider`] wrapper, which deserializes data using Serde.
//!
//! Providers that produce opaque buffers that need to be deserialized into concrete data structs,
//! such as `FsDataProvider`, should implement [`BufferProvider`]. These can be converted into
//! [`DeserializingBufferProvider`] using the [`as_deserializing`](AsDeserializingBufferProvider::as_deserializing)
//! convenience method.
//!
//! [`BufferProvider`]: crate::buf::BufferProvider

use crate::buf::BufferFormat;
use crate::buf::BufferProvider;
use crate::data_provider::DynamicDryDataProvider;
use crate::prelude::*;
use crate::DryDataProvider;
use serde::de::Deserialize;
use yoke::trait_hack::YokeTraitHack;
use yoke::Yokeable;

/// A [`BufferProvider`] that deserializes its data using Serde.
#[derive(Debug)]
pub struct DeserializingBufferProvider<'a, P: ?Sized>(&'a P);

/// Blanket-implemented trait adding the [`Self::as_deserializing()`] function.
pub trait AsDeserializingBufferProvider {
    /// Wrap this [`BufferProvider`] in a [`DeserializingBufferProvider`].
    ///
    /// This requires enabling the deserialization Cargo feature
    /// for the expected format(s):
    ///
    /// - `deserialize_json`
    /// - `deserialize_postcard_1`
    /// - `deserialize_bincode_1`
    fn as_deserializing(&self) -> DeserializingBufferProvider<Self>;
}

impl<P> AsDeserializingBufferProvider for P
where
    P: BufferProvider + ?Sized,
{
    /// Wrap this [`BufferProvider`] in a [`DeserializingBufferProvider`].
    ///
    /// This requires enabling the deserialization Cargo feature
    /// for the expected format(s):
    ///
    /// - `deserialize_json`
    /// - `deserialize_postcard_1`
    /// - `deserialize_bincode_1`
    fn as_deserializing(&self) -> DeserializingBufferProvider<Self> {
        DeserializingBufferProvider(self)
    }
}

fn deserialize_impl<'data, M>(
    // Allow `bytes` to be unused in case all buffer formats are disabled
    #[allow(unused_variables)] bytes: &'data [u8],
    buffer_format: BufferFormat,
) -> Result<<M::DataStruct as Yokeable<'data>>::Output, DataError>
where
    M: DynamicDataMarker,
    // Actual bound:
    //     for<'de> <M::DataStruct as Yokeable<'de>>::Output: Deserialize<'de>,
    // Necessary workaround bound (see `yoke::trait_hack` docs):
    for<'de> YokeTraitHack<<M::DataStruct as Yokeable<'de>>::Output>: Deserialize<'de>,
{
    match buffer_format {
        #[cfg(feature = "deserialize_json")]
        BufferFormat::Json => {
            let mut d = serde_json::Deserializer::from_slice(bytes);
            let data = YokeTraitHack::<<M::DataStruct as Yokeable>::Output>::deserialize(&mut d)?;
            Ok(data.0)
        }

        #[cfg(feature = "deserialize_bincode_1")]
        BufferFormat::Bincode1 => {
            use bincode::Options;
            let options = bincode::DefaultOptions::new()
                .with_fixint_encoding()
                .allow_trailing_bytes();
            let mut d = bincode::de::Deserializer::from_slice(bytes, options);
            let data = YokeTraitHack::<<M::DataStruct as Yokeable>::Output>::deserialize(&mut d)?;
            Ok(data.0)
        }

        #[cfg(feature = "deserialize_postcard_1")]
        BufferFormat::Postcard1 => {
            let mut d = postcard::Deserializer::from_bytes(bytes);
            let data = YokeTraitHack::<<M::DataStruct as Yokeable>::Output>::deserialize(&mut d)?;
            Ok(data.0)
        }

        // Allowed for cases in which all features are enabled
        #[allow(unreachable_patterns)]
        _ => {
            buffer_format.check_available()?;
            unreachable!()
        }
    }
}

impl DataPayload<BufferMarker> {
    /// Deserialize a [`DataPayload`]`<`[`BufferMarker`]`>` into a [`DataPayload`] of a
    /// specific concrete type.
    ///
    /// This requires enabling the deserialization Cargo feature
    /// for the expected format(s):
    ///
    /// - `deserialize_json`
    /// - `deserialize_postcard_1`
    /// - `deserialize_bincode_1`
    ///
    /// This function takes the buffer format as an argument. When a buffer payload is returned
    /// from a data provider, the buffer format is stored in the [`DataResponseMetadata`].
    ///
    /// # Examples
    ///
    /// Requires the `deserialize_json` Cargo feature:
    ///
    /// ```
    /// use icu_provider::buf::BufferFormat;
    /// use icu_provider::hello_world::*;
    /// use icu_provider::prelude::*;
    ///
    /// let buffer: &[u8] = br#"{"message":"Hallo Welt"}"#;
    ///
    /// let buffer_payload = DataPayload::from_owned(buffer);
    /// let payload: DataPayload<HelloWorldV1Marker> = buffer_payload
    ///     .into_deserialized(BufferFormat::Json)
    ///     .expect("Deserialization successful");
    ///
    /// assert_eq!(payload.get().message, "Hallo Welt");
    /// ```
    pub fn into_deserialized<M>(
        self,
        buffer_format: BufferFormat,
    ) -> Result<DataPayload<M>, DataError>
    where
        M: DynamicDataMarker,
        // Actual bound:
        //     for<'de> <M::DataStruct as Yokeable<'de>>::Output: Deserialize<'de>,
        // Necessary workaround bound (see `yoke::trait_hack` docs):
        for<'de> YokeTraitHack<<M::DataStruct as Yokeable<'de>>::Output>: Deserialize<'de>,
    {
        self.try_map_project(|bytes, _| deserialize_impl::<M>(bytes, buffer_format))
    }
}

impl<P, M> DynamicDataProvider<M> for DeserializingBufferProvider<'_, P>
where
    M: DynamicDataMarker,
    P: DynamicDataProvider<BufferMarker> + ?Sized,
    // Actual bound:
    //     for<'de> <M::DataStruct as Yokeable<'de>>::Output: serde::de::Deserialize<'de>,
    // Necessary workaround bound (see `yoke::trait_hack` docs):
    for<'de> YokeTraitHack<<M::DataStruct as Yokeable<'de>>::Output>: Deserialize<'de>,
{
    /// Converts a buffer into a concrete type by deserializing from a supported buffer format.
    ///
    /// This requires enabling the deserialization Cargo feature
    /// for the expected format(s):
    ///
    /// - `deserialize_json`
    /// - `deserialize_postcard_1`
    /// - `deserialize_bincode_1`
    fn load_data(
        &self,
        marker: DataMarkerInfo,
        req: DataRequest,
    ) -> Result<DataResponse<M>, DataError> {
        let buffer_response = self.0.load_data(marker, req)?;
        let buffer_format = buffer_response.metadata.buffer_format.ok_or_else(|| {
            DataErrorKind::Deserialize
                .with_str_context("BufferProvider didn't set BufferFormat")
                .with_req(marker, req)
        })?;
        Ok(DataResponse {
            metadata: buffer_response.metadata,
            payload: buffer_response
                .payload
                .into_deserialized(buffer_format)
                .map_err(|e| e.with_req(marker, req))?,
        })
    }
}

impl<P, M> DynamicDryDataProvider<M> for DeserializingBufferProvider<'_, P>
where
    M: DynamicDataMarker,
    P: DynamicDryDataProvider<BufferMarker> + ?Sized,
    // Actual bound:
    //     for<'de> <M::DataStruct as Yokeable<'de>>::Output: serde::de::Deserialize<'de>,
    // Necessary workaround bound (see `yoke::trait_hack` docs):
    for<'de> YokeTraitHack<<M::DataStruct as Yokeable<'de>>::Output>: Deserialize<'de>,
{
    fn dry_load_data(
        &self,
        marker: DataMarkerInfo,
        req: DataRequest,
    ) -> Result<DataResponseMetadata, DataError> {
        self.0.dry_load_data(marker, req)
    }
}

impl<P, M> DataProvider<M> for DeserializingBufferProvider<'_, P>
where
    M: DataMarker,
    P: DynamicDataProvider<BufferMarker> + ?Sized,
    // Actual bound:
    //     for<'de> <M::DataStruct as Yokeable<'de>>::Output: Deserialize<'de>,
    // Necessary workaround bound (see `yoke::trait_hack` docs):
    for<'de> YokeTraitHack<<M::DataStruct as Yokeable<'de>>::Output>: Deserialize<'de>,
{
    /// Converts a buffer into a concrete type by deserializing from a supported buffer format.
    ///
    /// This requires enabling the deserialization Cargo feature
    /// for the expected format(s):
    ///
    /// - `deserialize_json`
    /// - `deserialize_postcard_1`
    /// - `deserialize_bincode_1`
    fn load(&self, req: DataRequest) -> Result<DataResponse<M>, DataError> {
        self.load_data(M::INFO, req)
    }
}

impl<P, M> DryDataProvider<M> for DeserializingBufferProvider<'_, P>
where
    M: DataMarker,
    P: DynamicDryDataProvider<BufferMarker> + ?Sized,
    // Actual bound:
    //     for<'de> <M::DataStruct as Yokeable<'de>>::Output: Deserialize<'de>,
    // Necessary workaround bound (see `yoke::trait_hack` docs):
    for<'de> YokeTraitHack<<M::DataStruct as Yokeable<'de>>::Output>: Deserialize<'de>,
{
    fn dry_load(&self, req: DataRequest) -> Result<DataResponseMetadata, DataError> {
        self.0.dry_load_data(M::INFO, req)
    }
}

#[cfg(feature = "deserialize_json")]
impl From<serde_json::error::Error> for crate::DataError {
    fn from(e: serde_json::error::Error) -> Self {
        DataErrorKind::Deserialize
            .with_str_context("serde_json")
            .with_display_context(&e)
    }
}

#[cfg(feature = "deserialize_bincode_1")]
impl From<bincode::Error> for crate::DataError {
    fn from(e: bincode::Error) -> Self {
        DataErrorKind::Deserialize
            .with_str_context("bincode")
            .with_display_context(&e)
    }
}

#[cfg(feature = "deserialize_postcard_1")]
impl From<postcard::Error> for crate::DataError {
    fn from(e: postcard::Error) -> Self {
        DataErrorKind::Deserialize
            .with_str_context("postcard")
            .with_display_context(&e)
    }
}