flatk/
view.rs

1/// A marker trait to indicate a viewed collection type. Note that collections
2/// can be partially viewed, but only completely viewed collections are marked
3/// by `Viewed`.
4pub trait Viewed {}
5
6/// A trait defining a collection that can be accessed via an
7/// immutable (shared) view. This type of view can be cloned and copied.
8pub trait View<'a> {
9    type Type: Viewed;
10
11    fn view(&'a self) -> Self::Type;
12}
13
14/// A trait defining a collection that can be accessed via a mutable (unique)
15/// view.
16pub trait ViewMut<'a> {
17    type Type: Viewed;
18
19    fn view_mut(&'a mut self) -> Self::Type;
20}
21
22/// Blanket implementation of `View` for all immutable borrows.
23impl<'a, S: ?Sized + 'a + View<'a>> View<'a> for &S {
24    type Type = S::Type;
25
26    #[inline]
27    fn view(&'a self) -> Self::Type {
28        <S as View<'a>>::view(*self)
29    }
30}
31
32/// Blanket implementation of `View` for all mutable borrows.
33impl<'a, S: ?Sized + 'a + View<'a>> View<'a> for &mut S {
34    type Type = S::Type;
35
36    #[inline]
37    fn view(&'a self) -> Self::Type {
38        <S as View<'a>>::view(*self)
39    }
40}
41
42/// Blanket implementation of `ViewMut` for all mutable borrows.
43impl<'a, S: ?Sized + 'a + ViewMut<'a>> ViewMut<'a> for &mut S {
44    type Type = S::Type;
45
46    #[inline]
47    fn view_mut(&'a mut self) -> Self::Type {
48        <S as ViewMut<'a>>::view_mut(*self)
49    }
50}
51
52pub trait IntoView {
53    type View;
54    fn into_view(self) -> Self::View;
55}
56
57impl<'a, V: View<'a>> IntoView for &'a V {
58    type View = V::Type;
59    #[inline]
60    fn into_view(self) -> Self::View {
61        self.view()
62    }
63}
64
65impl<'a, V: ViewMut<'a>> IntoView for &'a mut V {
66    type View = V::Type;
67    #[inline]
68    fn into_view(self) -> Self::View {
69        self.view_mut()
70    }
71}
72
73/// A convenience trait to allow generic implementations to call an iterator over the view. This
74/// is necessary because the `View` trait has an explicit lifetime parameter, which makes it
75/// difficult or impossible to use in generic functions.
76/// For instance it becomes difficult/impossible to impose constraints like `Set` on `View::Type`.
77pub trait ViewIterator<'a> {
78    type Item;
79    type Iter: Iterator<Item = Self::Item>;
80
81    fn view_iter(&'a self) -> Self::Iter;
82}
83
84pub trait ViewMutIterator<'a> {
85    type Item;
86    type Iter: Iterator<Item = Self::Item>;
87
88    fn view_mut_iter(&'a mut self) -> Self::Iter;
89}