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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
// 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 ).

//! Collection of traits for providers that support type erasure of data structs.

use crate::error::Error;
use crate::prelude::*;
use crate::yoke::*;
use alloc::boxed::Box;
use alloc::rc::Rc;

use core::any::Any;
use core::any::TypeId;

/// Auto-implemented trait allowing for type erasure of data provider structs.
///
/// Requires the static lifetime in order to be convertible to [`Any`].
pub trait ErasedDataStruct: 'static {
    /// Clone this trait object reference, returning a boxed trait object.
    fn clone_into_box(&self) -> Box<dyn ErasedDataStruct>;

    /// Return this boxed trait object as [`Box`]`<dyn `[`Any`]`>`.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu_provider::erased::ErasedDataStruct;
    /// use icu_provider::hello_world::HelloWorldV1;
    ///
    /// // Create type-erased box
    /// let erased: Box<dyn ErasedDataStruct> = Box::new(HelloWorldV1::default());
    ///
    /// // Convert to typed box
    /// let boxed: Box<HelloWorldV1> = erased.into_any().downcast().expect("Types should match");
    /// ```
    fn into_any(self: Box<Self>) -> Box<dyn Any>;

    fn into_any_rc(self: Rc<Self>) -> Rc<dyn Any>;

    /// Return this trait object reference as `&dyn `[`Any`].
    ///
    /// Also see associated method [`downcast_ref()`](trait.ErasedDataStruct.html#method.downcast_ref).
    ///
    /// # Examples
    ///
    /// ```
    /// use icu_provider::erased::ErasedDataStruct;
    /// use icu_provider::hello_world::HelloWorldV1;
    ///
    /// // Create type-erased reference
    /// let data = HelloWorldV1::default();
    /// let erased: &dyn ErasedDataStruct = &data;
    ///
    /// // Borrow as typed reference
    /// let borrowed: &HelloWorldV1 = erased.as_any().downcast_ref().expect("Types should match");
    /// ```
    fn as_any(&self) -> &dyn Any;
}

impl_dyn_clone!(ErasedDataStruct);

impl ZeroCopyFrom<dyn ErasedDataStruct> for &'static dyn ErasedDataStruct {
    #[allow(clippy::needless_lifetimes)]
    fn zero_copy_from<'b>(this: &'b (dyn ErasedDataStruct)) -> &'b dyn ErasedDataStruct {
        this
    }
}

/// Marker type for [`ErasedDataStruct`].
pub struct ErasedDataStructMarker {}

impl DataMarker<'static> for ErasedDataStructMarker {
    type Yokeable = &'static dyn ErasedDataStruct;
    type Cart = dyn ErasedDataStruct;
}

impl<'data, M> crate::dynutil::UpcastDataPayload<'static, M> for ErasedDataStructMarker
where
    M: DataMarker<'static>,
    M::Cart: Sized,
{
    /// Upcast for ErasedDataStruct creates an `Rc<dyn ErasedDataStruct>` from the current inner
    /// `Yoke` (i.e., `Rc::from(yoke)`).
    fn upcast(other: DataPayload<'static, M>) -> DataPayload<'static, ErasedDataStructMarker> {
        use crate::data_provider::DataPayloadInner::*;
        match other.inner {
            RcStruct(yoke) => {
                // Case 2: Cast the whole RcStruct Yoke to the trait object.
                let cart: Rc<dyn ErasedDataStruct> = Rc::from(yoke);
                DataPayload::from_partial_owned(cart)
            }
            Owned(yoke) => {
                // Case 3: Cast the whole Owned Yoke to the trait object.
                let cart: Rc<dyn ErasedDataStruct> = Rc::from(yoke);
                DataPayload::from_partial_owned(cart)
            }
            RcBuf(yoke) => {
                // Case 4: Cast the whole RcBuf Yoke to the trait object.
                let cart: Rc<dyn ErasedDataStruct> = Rc::from(yoke);
                DataPayload::from_partial_owned(cart)
            }
        }
    }
}

impl<'data> DataPayload<'static, ErasedDataStructMarker> {
    /// Convert this [`DataPayload`] of an [`ErasedDataStruct`] into a [`DataPayload`] of a
    /// concrete type.
    ///
    /// Returns an error if the type is not compatible.
    ///
    /// This is the main way to consume data returned from an [`ErasedDataProvider`].
    ///
    /// Internally, this method reverses the transformation performed by
    /// [`UpcastDataPayload::upcast`](crate::dynutil::UpcastDataPayload::upcast) as implemented
    /// for [`ErasedDataStructMarker`].
    ///
    /// # Examples
    ///
    /// ```
    /// use icu_provider::prelude::*;
    /// use icu_provider::erased::*;
    /// use icu_provider::hello_world::*;
    /// use icu_locid_macros::langid;
    ///
    /// let provider = HelloWorldProvider::new_with_placeholder_data();
    ///
    /// let erased_payload: DataPayload<ErasedDataStructMarker> = provider
    ///     .load_payload(&DataRequest {
    ///         resource_path: ResourcePath {
    ///             key: key::HELLO_WORLD_V1,
    ///             options: ResourceOptions {
    ///                 variant: None,
    ///                 langid: Some(langid!("de")),
    ///             }
    ///         }
    ///     })
    ///     .expect("Loading should succeed")
    ///     .take_payload()
    ///     .expect("Data should be present");
    ///
    /// let downcast_payload: DataPayload<HelloWorldV1Marker> = erased_payload
    ///     .downcast()
    ///     .expect("Types should match");
    ///
    /// assert_eq!("Hallo Welt", downcast_payload.get().message);
    /// ```
    pub fn downcast<M>(self) -> Result<DataPayload<'static, M>, Error>
    where
        M: DataMarker<'static>,
        M::Cart: Sized,
        M::Yokeable: ZeroCopyFrom<M::Cart>,
    {
        use crate::data_provider::DataPayloadInner::*;
        match self.inner {
            RcStruct(yoke) => {
                let any_rc: Rc<dyn Any> = yoke.into_backing_cart().into_any_rc();
                // `any_rc` is the Yoke that was converted into the `dyn ErasedDataStruct`. It
                // could have been either the RcStruct or the Owned variant of Yoke.
                // Check first for Case 2: an RcStruct Yoke.
                let y1 = any_rc.downcast::<Yoke<M::Yokeable, Rc<M::Cart>>>();
                let any_rc = match y1 {
                    Ok(rc_yoke) => match Rc::try_unwrap(rc_yoke) {
                        Ok(yoke) => {
                            return Ok(DataPayload {
                                inner: RcStruct(yoke),
                            })
                        }
                        // Note: We could consider cloning the Yoke instead of erroring out.
                        Err(_) => return Err(Error::MultipleReferences),
                    },
                    Err(any_rc) => any_rc,
                };
                // Check for Case 3: an Owned Yoke.
                let y2 = any_rc.downcast::<Yoke<M::Yokeable, ()>>();
                let any_rc = match y2 {
                    Ok(rc_yoke) => match Rc::try_unwrap(rc_yoke) {
                        Ok(yoke) => return Ok(DataPayload { inner: Owned(yoke) }),
                        // Note: We could consider cloning the Yoke instead of erroring out.
                        Err(_) => return Err(Error::MultipleReferences),
                    },
                    Err(any_rc) => any_rc,
                };
                // Check for Case 4: an RcBuf Yoke.
                let y2 = any_rc.downcast::<Yoke<M::Yokeable, Rc<[u8]>>>();
                let any_rc = match y2 {
                    Ok(rc_yoke) => match Rc::try_unwrap(rc_yoke) {
                        Ok(yoke) => return Ok(DataPayload { inner: RcBuf(yoke) }),
                        // Note: We could consider cloning the Yoke instead of erroring out.
                        Err(_) => return Err(Error::MultipleReferences),
                    },
                    Err(any_rc) => any_rc,
                };
                // None of the downcasts succeeded; return an error.
                Err(Error::MismatchedType {
                    actual: Some(any_rc.type_id()),
                    generic: Some(TypeId::of::<M::Cart>()),
                })
            }
            // This is unreachable because ErasedDataStruct cannot be fully owned, since it
            // contains a reference.
            Owned(_) => unreachable!(),
            // This is unreachable because ErasedDataStruct needs to reference an object.
            RcBuf(_) => unreachable!(),
        }
    }
}

impl<T> ErasedDataStruct for T
where
    T: Any,
    for<'a> &'a T: Clone,
{
    fn clone_into_box(&self) -> Box<dyn ErasedDataStruct> {
        todo!("#753")
        // Box::new(self.clone())
    }
    fn into_any(self: Box<Self>) -> Box<dyn Any> {
        self
    }
    fn into_any_rc(self: Rc<Self>) -> Rc<dyn Any> {
        self
    }
    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// A type-erased data provider that loads a payload of types implementing [`Any`].
///
/// Note: This trait is redundant with [`DataProvider`]`<dyn `[`ErasedDataStruct`]`>` and auto-implemented
/// for all types implementing that trait. This trait may eventually be removed when the following
/// Rust issues are resolved:
///
/// - [#41517](https://github.com/rust-lang/rust/issues/41517) (trait aliases are not supported)
/// - [#68636](https://github.com/rust-lang/rust/issues/68636) (identical traits can't be auto-implemented)
pub trait ErasedDataProvider<'data> {
    /// Query the provider for data, returning the result as an [`ErasedDataStruct`] trait object.
    ///
    /// Returns [`Ok`] if the request successfully loaded data. If data failed to load, returns an
    /// Error with more information.
    fn load_erased(
        &self,
        req: &DataRequest,
    ) -> Result<DataResponse<'static, ErasedDataStructMarker>, Error>;
}

// Auto-implement `ErasedDataProvider` on types implementing `DataProvider<dyn ErasedDataStruct>`
impl<'data, T> ErasedDataProvider<'data> for T
where
    T: DataProvider<'static, ErasedDataStructMarker>,
{
    fn load_erased(
        &self,
        req: &DataRequest,
    ) -> Result<DataResponse<'static, ErasedDataStructMarker>, Error> {
        DataProvider::<ErasedDataStructMarker>::load_payload(self, req)
    }
}

impl<'data, M> DataProvider<'static, M> for dyn ErasedDataProvider<'data> + 'data
where
    M: DataMarker<'static>,
    <M::Yokeable as Yokeable<'static>>::Output: Clone + Any,
    M::Yokeable: ZeroCopyFrom<M::Cart>,
    M::Cart: Sized,
{
    /// Serve [`Sized`] objects from an [`ErasedDataProvider`] via downcasting.
    fn load_payload(&self, req: &DataRequest) -> Result<DataResponse<'static, M>, Error> {
        let result = ErasedDataProvider::load_erased(self, req)?;
        Ok(DataResponse {
            metadata: result.metadata,
            payload: result.payload.map(|p| p.downcast()).transpose()?,
        })
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::dynutil::UpcastDataPayload;
    use crate::marker::CowStringMarker;
    use alloc::borrow::Cow;

    #[test]
    fn test_erased_case_2() {
        let data = Rc::new("foo".to_string());
        let original = DataPayload::<CowStringMarker>::from_partial_owned(data);
        let upcasted = ErasedDataStructMarker::upcast(original);
        let downcasted = upcasted
            .downcast::<CowStringMarker>()
            .expect("Type conversion");
        assert_eq!(downcasted.get(), "foo");
    }

    #[test]
    fn test_erased_case_3() {
        let data = "foo".to_string();
        let original = DataPayload::<CowStringMarker>::from_owned(Cow::Owned(data));
        let upcasted = ErasedDataStructMarker::upcast(original);
        let downcasted = upcasted
            .downcast::<CowStringMarker>()
            .expect("Type conversion");
        assert_eq!(downcasted.get(), "foo");
    }

    #[test]
    fn test_erased_case_4() {
        let data: Rc<[u8]> = "foo".as_bytes().into();
        let original = DataPayload::<CowStringMarker>::try_from_rc_buffer_badly(data, |bytes| {
            core::str::from_utf8(bytes).map(|s| Cow::Borrowed(s))
        })
        .expect("String is valid UTF-8");
        let upcasted = ErasedDataStructMarker::upcast(original);
        let downcasted = upcasted
            .downcast::<CowStringMarker>()
            .expect("Type conversion");
        assert_eq!(downcasted.get(), "foo");
    }
}