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
use std::fmt;
use std::ops;

use async_trait::async_trait;
use collate::Collate;
use destream::{de, en};
use futures::TryFutureExt;
use safecast::{TryCastFrom, TryCastInto};

use tc_error::*;
use tcgeneric::{label, Id, Label, Map};

use super::{Value, ValueCollator};

/// The prefix of an inclusive [`Bound`]
pub const IN: Label = label("in");

/// The prefix of an exclusive [`Bound`]
pub const EX: Label = label("ex");

/// An optional inclusive or exclusive bound
#[derive(Clone, Eq, PartialEq)]
pub enum Bound {
    In(Value),
    Ex(Value),
    Un,
}

impl<'en> en::IntoStream<'en> for Bound {
    fn into_stream<E: en::Encoder<'en>>(self, encoder: E) -> Result<E::Ok, E::Error> {
        match self {
            Self::In(v) => single_entry(Id::from(IN), v, encoder),
            Self::Ex(v) => single_entry(Id::from(EX), v, encoder),
            Self::Un => Value::None.into_stream(encoder),
        }
    }
}

impl<'en> en::ToStream<'en> for Bound {
    fn to_stream<E: en::Encoder<'en>>(&'en self, encoder: E) -> Result<E::Ok, E::Error> {
        match self {
            Self::In(v) => single_entry(Id::from(IN), v, encoder),
            Self::Ex(v) => single_entry(Id::from(EX), v, encoder),
            Self::Un => Value::None.to_stream(encoder),
        }
    }
}

impl TryCastFrom<Map<Value>> for Bound {
    fn can_cast_from(value: &Map<Value>) -> bool {
        value.len() == 1 && (value.contains_key(&IN.into()) || value.contains_key(&EX.into()))
    }

    fn opt_cast_from(mut value: Map<Value>) -> Option<Self> {
        if value.len() == 1 {
            if let Some(value) = value.remove(&IN.into()) {
                Some(Self::In(value))
            } else if let Some(value) = value.remove(&EX.into()) {
                Some(Self::Ex(value))
            } else {
                None
            }
        } else {
            None
        }
    }
}

impl From<Bound> for ops::Bound<Value> {
    fn from(bound: Bound) -> Self {
        match bound {
            Bound::In(value) => Self::Included(value),
            Bound::Ex(value) => Self::Excluded(value),
            Bound::Un => Self::Unbounded,
        }
    }
}

impl fmt::Display for Bound {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::In(value) => write!(f, "include({})", value),
            Self::Ex(value) => write!(f, "exclude({})", value),
            Self::Un => write!(f, "unbounded"),
        }
    }
}

/// A range comprising a start and end [`Bound`]
#[derive(Clone, Eq, PartialEq)]
pub struct Range {
    pub start: Bound,
    pub end: Bound,
}

impl Range {
    /// Return true if the given `Range` is within this `Range`.
    pub fn contains_range(&self, inner: &Self, collator: &ValueCollator) -> bool {
        use std::cmp::Ordering::*;

        match &self.start {
            Bound::Un => {}
            Bound::In(outer) => match &inner.start {
                Bound::Un => return false,
                Bound::In(inner) => {
                    if collator.compare(inner, outer) == Less {
                        return false;
                    }
                }
                Bound::Ex(inner) => {
                    if collator.compare(inner, outer) != Greater {
                        return false;
                    }
                }
            },
            Bound::Ex(outer) => match &inner.start {
                Bound::Un => return false,
                Bound::In(inner) => {
                    if collator.compare(inner, outer) != Greater {
                        return false;
                    }
                }
                Bound::Ex(inner) => {
                    if collator.compare(inner, outer) == Less {
                        return false;
                    }
                }
            },
        }

        match &self.end {
            Bound::Un => {}
            Bound::In(outer) => match &inner.end {
                Bound::Un => return false,
                Bound::In(inner) => {
                    if collator.compare(inner, outer) == Greater {
                        return false;
                    }
                }
                Bound::Ex(inner) => {
                    if collator.compare(inner, outer) != Less {
                        return false;
                    }
                }
            },
            Bound::Ex(outer) => match &inner.end {
                Bound::Un => return false,
                Bound::In(inner) => {
                    if collator.compare(inner, outer) != Less {
                        return false;
                    }
                }
                Bound::Ex(inner) => {
                    if collator.compare(inner, outer) == Greater {
                        return false;
                    }
                }
            },
        }

        true
    }

    /// Return true if the given [`Value`] is within this `Range`.
    pub fn contains_value(&self, value: &Value, collator: &ValueCollator) -> bool {
        use std::cmp::Ordering::*;

        match &self.start {
            Bound::Un => {}
            Bound::In(outer) => {
                if collator.compare(value, outer) == Less {
                    return false;
                }
            }
            Bound::Ex(outer) => {
                if collator.compare(value, outer) != Greater {
                    return false;
                }
            }
        }

        match &self.end {
            Bound::Un => {}
            Bound::In(outer) => {
                if collator.compare(value, outer) == Greater {
                    return false;
                }
            }
            Bound::Ex(outer) => {
                if collator.compare(value, outer) != Less {
                    return false;
                }
            }
        }

        true
    }
}

impl Default for Range {
    fn default() -> Self {
        Self {
            start: Bound::Un,
            end: Bound::Un,
        }
    }
}

#[async_trait]
impl de::FromStream for Range {
    type Context = ();

    async fn from_stream<D: de::Decoder>(cxt: (), decoder: &mut D) -> Result<Self, D::Error> {
        let start = if let Ok(map) = Map::<Value>::from_stream(cxt, decoder).await {
            map.try_cast_into(|v| TCError::bad_request("invalid Range", v))
                .map_err(de::Error::custom)
        } else {
            Value::from_stream(cxt, decoder)
                .map_ok(|v| if v.is_none() { Bound::Un } else { Bound::In(v) })
                .await
        }?;

        let end = if let Ok(map) = Map::<Value>::from_stream(cxt, decoder).await {
            map.try_cast_into(|v| TCError::bad_request("invalid Range", v))
                .map_err(de::Error::custom)
        } else {
            Value::from_stream(cxt, decoder)
                .map_ok(|v| if v.is_none() { Bound::Un } else { Bound::Ex(v) })
                .await
        }?;

        Ok(Range { start, end })
    }
}

impl<'en> en::IntoStream<'en> for Range {
    fn into_stream<E: en::Encoder<'en>>(self, encoder: E) -> Result<E::Ok, E::Error> {
        match (self.start, self.end) {
            (Bound::In(start), Bound::Ex(end)) => (start, end).into_stream(encoder),
            (Bound::Un, Bound::Ex(end)) => ((), end).into_stream(encoder),
            (Bound::In(start), Bound::Un) => (start, ()).into_stream(encoder),
            (start, end) => (start, end).into_stream(encoder),
        }
    }
}

impl<'en> en::ToStream<'en> for Range {
    fn to_stream<E: en::Encoder<'en>>(&'en self, encoder: E) -> Result<E::Ok, E::Error> {
        use en::IntoStream;

        match (&self.start, &self.end) {
            (Bound::In(start), Bound::Ex(end)) => (start, end).into_stream(encoder),
            (Bound::Un, Bound::Ex(end)) => ((), end).into_stream(encoder),
            (Bound::In(start), Bound::Un) => (start, ()).into_stream(encoder),
            (start, end) => (start, end).into_stream(encoder),
        }
    }
}

impl From<Range> for (ops::Bound<Value>, ops::Bound<Value>) {
    fn from(range: Range) -> Self {
        (range.start.into(), range.end.into())
    }
}

impl fmt::Display for Range {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match (&self.start, &self.end) {
            (Bound::Ex(start), Bound::Ex(end)) => write!(f, "({}, {})", start, end),
            (Bound::Ex(start), Bound::In(end)) => write!(f, "({}, {}]", start, end),
            (Bound::Ex(start), Bound::Un) => write!(f, "({}...]", start),

            (Bound::In(start), Bound::Ex(end)) => write!(f, "[{}, {})", start, end),
            (Bound::In(start), Bound::In(end)) => write!(f, "[{}, {}]", start, end),
            (Bound::In(start), Bound::Un) => write!(f, "[{}...]", start),

            (Bound::Un, Bound::Ex(end)) => write!(f, "[...{})", end),
            (Bound::Un, Bound::In(end)) => write!(f, "[...{}]", end),
            (Bound::Un, Bound::Un) => f.write_str("[...]"),
        }
    }
}

fn single_entry<
    'en,
    K: en::IntoStream<'en> + 'en,
    V: en::IntoStream<'en> + 'en,
    E: en::Encoder<'en>,
>(
    key: K,
    value: V,
    encoder: E,
) -> Result<E::Ok, E::Error> {
    use en::EncodeMap;

    let mut map = encoder.encode_map(Some(1))?;
    map.encode_entry(key, value)?;
    map.end()
}