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

use super::Error;
use crate::buf::BufferFormat;
use crate::buf::BufferProvider;
use crate::prelude::*;
use core::marker::PhantomData;
use serde::de::Deserialize;
use yoke::trait_hack::YokeTraitHack;
use yoke::Yokeable;

/// Returns an error if the buffer format is not enabled.
pub fn check_format_supported(buffer_format: BufferFormat) -> Result<(), Error> {
    match buffer_format {
        #[cfg(feature = "deserialize_json")]
        BufferFormat::Json => Ok(()),

        #[cfg(feature = "deserialize_bincode_1")]
        BufferFormat::Bincode1 => Ok(()),

        #[cfg(feature = "deserialize_postcard_07")]
        BufferFormat::Postcard07 => Ok(()),

        // Allowed for cases in which all features are enabled
        #[allow(unreachable_patterns)]
        _ => Err(Error::UnavailableFormat(buffer_format)),
    }
}

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

/// Auto-implemented for all [`BufferProvider`] for easy wrapping in [`DeserializingBufferProvider`].
pub trait AsDeserializingBufferProvider {
    fn as_deserializing(&self) -> DeserializingBufferProvider<Self>;
}

impl<P> AsDeserializingBufferProvider for P
where
    P: BufferProvider + ?Sized,
{
    /// Wrap this [`BufferProvider`] in a [`DeserializingBufferProvider`].
    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,
    _: PhantomData<&'data ()>,
) -> Result<<M::Yokeable as Yokeable<'data>>::Output, Error>
where
    M: DataMarker,
    // Actual bound:
    //     for<'de> <M::Yokeable as Yokeable<'de>>::Output: Deserialize<'de>,
    // Necessary workaround bound (see `yoke::trait_hack` docs):
    for<'de> YokeTraitHack<<M::Yokeable 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::Yokeable 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::Yokeable as Yokeable>::Output>::deserialize(&mut d)?;
            Ok(data.0)
        }

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

        // Allowed for cases in which all features are enabled
        #[allow(unreachable_patterns)]
        _ => Err(Error::UnavailableFormat(buffer_format)),
    }
}

impl DataPayload<BufferMarker> {
    pub fn into_deserialized<M>(self, buffer_format: BufferFormat) -> Result<DataPayload<M>, Error>
    where
        M: DataMarker,
        // Actual bound:
        //     for<'de> <M::Yokeable as Yokeable<'de>>::Output: Deserialize<'de>,
        // Necessary workaround bound (see `yoke::trait_hack` docs):
        for<'de> YokeTraitHack<<M::Yokeable as Yokeable<'de>>::Output>: Deserialize<'de>,
    {
        self.try_map_project_with_capture(buffer_format, deserialize_impl::<M>)
    }
}

impl<P, M> ResourceProvider<M> for DeserializingBufferProvider<'_, P>
where
    M: ResourceMarker,
    P: BufferProvider + ?Sized,
    // Actual bound:
    //     for<'de> <M::Yokeable as Yokeable<'de>>::Output: Deserialize<'de>,
    // Necessary workaround bound (see `yoke::trait_hack` docs):
    for<'de> YokeTraitHack<<M::Yokeable as Yokeable<'de>>::Output>: Deserialize<'de>,
{
    /// Converts a buffer into a concrete type by deserializing from a supported buffer format.
    fn load_resource(&self, req: &DataRequest) -> Result<DataResponse<M>, DataError> {
        self.load_payload(M::KEY, req)
    }
}

impl<P, M> DynProvider<M> for DeserializingBufferProvider<'_, P>
where
    M: DataMarker,
    P: BufferProvider + ?Sized,
    // Actual bound:
    //     for<'de> <M::Yokeable as Yokeable<'de>>::Output: serde::de::Deserialize<'de>,
    // Necessary workaround bound (see `yoke::trait_hack` docs):
    for<'de> YokeTraitHack<<M::Yokeable as Yokeable<'de>>::Output>: Deserialize<'de>,
{
    fn load_payload(
        &self,
        key: ResourceKey,
        req: &DataRequest,
    ) -> Result<DataResponse<M>, DataError> {
        let old_response = BufferProvider::load_buffer(self.0, key, req)?;
        if let Some(old_payload) = old_response.payload {
            let buffer_format = old_response
                .metadata
                .buffer_format
                .ok_or(Error::FormatNotSpecified)?;
            let new_payload = old_payload.into_deserialized(buffer_format)?;
            Ok(DataResponse {
                metadata: old_response.metadata,
                payload: Some(new_payload),
            })
        } else {
            Ok(DataResponse {
                metadata: old_response.metadata,
                payload: None,
            })
        }
    }
}

/// Implements [ResourceProvider] and [DynProvider] if [BufferProvider] is implemented.
/// This allows dropping the call to `.as_deserializing()`.
#[macro_export]
macro_rules! impl_auto_deserializing {
    ($buffer_provider: ty) => {
        impl<M> ResourceProvider<M> for $buffer_provider
        where
            M: ResourceMarker,
            // Actual bound:
            //     for<'de> <M::Yokeable as Yokeable<'de>>::Output: serde::de::Deserialize<'de>,
            // Necessary workaround bound (see `yoke::trait_hack` docs):
            for<'de> yoke::trait_hack::YokeTraitHack<<M::Yokeable as yoke::Yokeable<'de>>::Output>:
                serde::de::Deserialize<'de>,
        {
            fn load_resource(&self, req: &DataRequest) -> Result<DataResponse<M>, DataError> {
                self.as_deserializing().load_resource(req)
            }
        }

        impl<M> DynProvider<M> for $buffer_provider
        where
            M: DataMarker,
            // Actual bound:
            //     for<'de> <M::Yokeable as Yokeable<'de>>::Output: serde::de::Deserialize<'de>,
            // Necessary workaround bound (see `yoke::trait_hack` docs):
            for<'de> yoke::trait_hack::YokeTraitHack<<M::Yokeable as yoke::Yokeable<'de>>::Output>:
                serde::de::Deserialize<'de>,
        {
            fn load_payload(
                &self,
                key: ResourceKey,
                req: &DataRequest,
            ) -> Result<DataResponse<M>, DataError> {
                self.as_deserializing().load_payload(key, req)
            }
        }
    };
}