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//! Types to enable polymorphic carts.
6
7use crate::CloneableCart;
8
9use core::ops::Deref;
10use stable_deref_trait::StableDeref;
11
12/// A cart that can be one type or the other. Enables ergonomic polymorphic carts.
13///
14/// `EitherCart` enables yokes originating from different data sources and therefore
15/// having different cart types to be merged into the same yoke type, but still being
16/// able to recover the original cart type if necessary.
17///
18/// All relevant Cart traits are implemented for `EitherCart`, and carts can be
19/// safely wrapped in an `EitherCart`.
20///
21/// Also see [`Yoke::erase_box_cart()`](crate::Yoke::erase_box_cart).
22///
23/// # Examples
24///
25/// ```
26/// use std::borrow::Cow;
27/// use std::rc::Rc;
28/// use yoke::either::EitherCart;
29/// use yoke::Yoke;
30///
31/// let y1: Yoke<&'static str, Rc<str>> =
32/// Yoke::attach_to_zero_copy_cart("reference counted hello world".into());
33///
34/// let y2: Yoke<&'static str, &str> = Yoke::attach_to_zero_copy_cart("borrowed hello world");
35///
36/// type CombinedYoke<'a> = Yoke<&'static str, EitherCart<Rc<str>, &'a str>>;
37///
38/// // Both yokes can be combined into a single yoke type despite different carts
39/// let y3: CombinedYoke = y1.wrap_cart_in_either_a();
40/// let y4: CombinedYoke = y2.wrap_cart_in_either_b();
41///
42/// assert_eq!(*y3.get(), "reference counted hello world");
43/// assert_eq!(*y4.get(), "borrowed hello world");
44///
45/// // The resulting yoke is cloneable if both cart types implement CloneableCart
46/// let y5 = y4.clone();
47/// assert_eq!(*y5.get(), "borrowed hello world");
48/// ```
49#[derive(Clone, PartialEq, Eq, Debug)]
50#[allow(clippy::exhaustive_enums)] // stable
51pub enum EitherCart<C0, C1> {
52 A(C0),
53 B(C1),
54}
55
56impl<C0, C1, T> Deref for EitherCart<C0, C1>
57where
58 C0: Deref<Target = T>,
59 C1: Deref<Target = T>,
60{
61 type Target = T;
62 fn deref(&self) -> &T {
63 use EitherCart::*;
64 match self {
65 A(a: &C0) => a.deref(),
66 B(b: &C1) => b.deref(),
67 }
68 }
69}
70
71// Safe because both sub-types implement the trait.
72unsafe impl<C0, C1, T> StableDeref for EitherCart<C0, C1>
73where
74 C0: StableDeref,
75 C1: StableDeref,
76 C0: Deref<Target = T>,
77 C1: Deref<Target = T>,
78{
79}
80
81// Safe because both sub-types implement the trait.
82unsafe impl<C0, C1> CloneableCart for EitherCart<C0, C1>
83where
84 C0: CloneableCart,
85 C1: CloneableCart,
86{
87}
88