segment_tree/
maybe_owned.rs1use std::cmp;
7use std::fmt::{self, Debug, Display, Formatter};
8use std::default::Default;
9use std::hash::{Hash, Hasher};
10use std::borrow::Cow;
11
12pub enum MaybeOwned<'a, T: 'a> {
17 Borrowed(&'a T),
18 Owned(T)
19}
20
21impl<'a, T: 'a> MaybeOwned<'a, T> {
22 #[inline]
24 pub fn borrow(&self) -> &T {
25 match *self {
26 MaybeOwned::Borrowed(v) => v,
27 MaybeOwned::Owned(ref v) => &v
28 }
29 }
30 #[inline]
37 pub fn into_cow(self) -> Cow<'a, T> where T: Clone {
38 match self {
39 MaybeOwned::Borrowed(v) => Cow::Borrowed(v),
40 MaybeOwned::Owned(v) => Cow::Owned(v),
41 }
42 }
43}
44
45impl<'a, T: 'a + Clone> MaybeOwned<'a, T> {
46 #[inline]
48 pub fn unwrap_or_clone(self) -> T {
49 match self {
50 MaybeOwned::Borrowed(v) => v.clone(),
51 MaybeOwned::Owned(v) => v
52 }
53 }
54}
55
56impl<'a, T: 'a + Debug> Debug for MaybeOwned<'a, T> {
57 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
58 match *self {
59 MaybeOwned::Borrowed(v) => write!(f, "Borrw({:?})", v),
60 MaybeOwned::Owned(ref v) => write!(f, "Owned({:?})", v),
61 }
62 }
63}
64
65impl<'a, T: 'a + Display> Display for MaybeOwned<'a, T> {
66 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
67 match *self {
68 MaybeOwned::Borrowed(v) => v.fmt(f),
69 MaybeOwned::Owned(ref v) => v.fmt(f),
70 }
71 }
72}
73
74impl<'a, T: 'a + PartialEq> cmp::PartialEq for MaybeOwned<'a, T> {
75 #[inline]
76 fn eq(&self, other: &MaybeOwned<T>) -> bool {
77 self.borrow().eq(other.borrow())
78 }
79 #[inline]
80 fn ne(&self, other: &MaybeOwned<T>) -> bool {
81 self.borrow().ne(other.borrow())
82 }
83}
84impl<'a, T: 'a + Eq> cmp::Eq for MaybeOwned<'a, T> { }
85
86impl<'a, T: 'a + PartialOrd> cmp::PartialOrd for MaybeOwned<'a, T> {
87 #[inline]
88 fn partial_cmp(&self, other: &MaybeOwned<T>) -> Option<cmp::Ordering> {
89 self.borrow().partial_cmp(other.borrow())
90 }
91 #[inline]
92 fn lt(&self, other: &MaybeOwned<T>) -> bool {
93 self.borrow().lt(other.borrow())
94 }
95 #[inline]
96 fn le(&self, other: &MaybeOwned<T>) -> bool {
97 self.borrow().le(other.borrow())
98 }
99 #[inline]
100 fn gt(&self, other: &MaybeOwned<T>) -> bool {
101 self.borrow().gt(other.borrow())
102 }
103 #[inline]
104 fn ge(&self, other: &MaybeOwned<T>) -> bool {
105 self.borrow().ge(other.borrow())
106 }
107}
108impl<'a, T: 'a + Ord> cmp::Ord for MaybeOwned<'a, T> {
109 #[inline]
110 fn cmp(&self, other: &MaybeOwned<T>) -> cmp::Ordering {
111 self.borrow().cmp(other.borrow())
112 }
113}
114
115impl<'a, T: 'a + Default> Default for MaybeOwned<'a, T> {
116 #[inline]
117 fn default() -> MaybeOwned<'a, T> {
118 MaybeOwned::Owned(Default::default())
119 }
120}
121
122impl<'a, T: 'a + Hash> Hash for MaybeOwned<'a, T> {
123 #[inline]
124 fn hash<H: Hasher>(&self, state: &mut H) {
125 self.borrow().hash(state)
126 }
127}