|
2 | 2 |
|
3 | 3 | #![no_std] |
4 | 4 | doc_comment::doctest!("../README.md"); |
| 5 | + |
| 6 | +use core::marker::PhantomData; |
| 7 | + |
| 8 | +/// A convenience type alias to get a view from a proxy and a lifetime. |
| 9 | +pub type View<'a, P> = <P as ProxyView>::View<'a>; |
| 10 | + |
| 11 | +/// A type generator that produces a view type for a given lifetime. |
| 12 | +/// |
| 13 | +/// The owned value associated with the proxy is required to outlive any borrow lifetime, |
| 14 | +/// so it's type must be known when this trait is implemented. |
| 15 | +/// |
| 16 | +/// It also provides a static method to generate a view from a reference to an owned value, |
| 17 | +/// though views may be generated in alternative ways. The view must always be generatable |
| 18 | +/// from a reference to the owned value. An example is ndarray arrays, which can be viewed |
| 19 | +/// as sub-slices, but you can always create a view from a single owned array. For instance, |
| 20 | +/// you might store multiple Array1 using Array2 and create views using rows/columns, but |
| 21 | +/// it is important that new points being added to the space can be viewed using an ArrayView1 |
| 22 | +/// just like you can for points stored in the Array2 so that they can be compared. |
| 23 | +pub trait ProxyView { |
| 24 | + /// The concrete type that this proxy borrows from. |
| 25 | + type Owned; |
| 26 | + |
| 27 | + /// The borrowed view type for a given lifetime. |
| 28 | + /// `Self::Owned` must outlive the borrow lifetime to ensure safety. |
| 29 | + type View<'a> |
| 30 | + where |
| 31 | + Self::Owned: 'a; |
| 32 | + |
| 33 | + fn view<'a>(owned: &'a Self::Owned) -> Self::View<'a>; |
| 34 | +} |
| 35 | + |
| 36 | +/// Provides a generic way to clone owned values from arbitrary proxies. |
| 37 | +pub trait ProxyToOwned: ProxyView { |
| 38 | + fn to_owned_proxy<'a>(view: Self::View<'a>) -> Self::Owned; |
| 39 | +} |
| 40 | + |
| 41 | +/// A proxy that simply returns a reference to the owned value. |
| 42 | +pub struct ReferenceProxy<T>(pub PhantomData<T>); |
| 43 | + |
| 44 | +impl<T> ReferenceProxy<T> { |
| 45 | + pub fn new() -> Self { |
| 46 | + ReferenceProxy(PhantomData) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +impl<T> Default for ReferenceProxy<T> { |
| 51 | + fn default() -> Self { |
| 52 | + Self::new() |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +impl<T> ProxyView for ReferenceProxy<T> { |
| 57 | + type Owned = T; |
| 58 | + type View<'a> |
| 59 | + = &'a T |
| 60 | + where |
| 61 | + Self::Owned: 'a; |
| 62 | + |
| 63 | + fn view<'a>(owned: &'a Self::Owned) -> Self::View<'a> { |
| 64 | + owned |
| 65 | + } |
| 66 | +} |
0 commit comments