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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356

use interpolate::Scalar;
use interpolation::Spatial;
use point::Point;
use std;


/// Types that are representable as an Envelope.
pub trait Envelope<'a>: Sized {
    type X: PartialEq + PartialOrd + Clone;
    type Y: PartialEq + Spatial;
    /// The `Point` type which may be referenced and interpolated by the `Envelope`.
    type Point: Point<X=Self::X, Y=Self::Y> + 'a;
    /// An iterator yielding references to `Self::Point`s.
    type Points: Iterator<Item=&'a Self::Point>
        + ExactSizeIterator
        + DoubleEndedIterator
        + Clone
        + 'a;

    /// An iterator yielding the `Point`s of the Envelope.
    fn points(&'a self) -> Self::Points;

    /// The index of the `Point` that comes directly before the given `x`.
    #[inline]
    fn point_idx_before(&'a self, x: Self::X) -> Option<usize> {
        point_idx_before(self, x)
    }

    /// The index of the `Point` that either lands on or comes directly before the given `x`.
    #[inline]
    fn point_idx_on_or_before(&'a self, x: Self::X) -> Option<usize> {
        point_idx_on_or_before(self, x)
    }

    /// The index of the `Point` that comes directly after the given `x`.
    #[inline]
    fn point_idx_after(&'a self, x: Self::X) -> Option<usize> {
        point_idx_after(self, x)
    }

    /// The index of the `Point` that comes directly after the given `x`.
    #[inline]
    fn point_idx_on_or_after(&'a self, x: Self::X) -> Option<usize> {
        point_idx_on_or_after(self, x)
    }

    /// A reference to the first point that comes before the given `x`.
    #[inline]
    fn point_before(&'a self, x: Self::X) -> Option<&'a Self::Point> {
        self.point_idx_before(x).and_then(|i| self.points().nth(i))
    }

    /// A reference to the first point that is equal to or comes before the given `x`.
    #[inline]
    fn point_on_or_before(&'a self, x: Self::X) -> Option<&'a Self::Point> {
        self.point_idx_on_or_before(x).and_then(|i| self.points().nth(i))
    }

    /// A reference to the first point that comes before the given `x` along with its index.
    #[inline]
    fn point_before_with_idx(&'a self, x: Self::X) -> Option<(usize, &'a Self::Point)> {
        self.point_idx_before(x).and_then(|i| self.points().nth(i).map(|p| (i, p)))
    }

    /// A reference to the first point that is equal to or comes before the given `x` along with
    /// its index.
    #[inline]
    fn point_on_or_before_with_idx(&'a self, x: Self::X) -> Option<(usize, &'a Self::Point)> {
        self.point_idx_on_or_before(x).and_then(|i| self.points().nth(i).map(|p| (i, p)))
    }

    /// A reference to the first point that comes after the given `x`.
    #[inline]
    fn point_after(&'a self, x: Self::X) -> Option<&'a Self::Point> {
        self.point_idx_after(x).and_then(|i| self.points().nth(i))
    }

    /// A reference to the first point that is equal to or comes after the given `x`.
    #[inline]
    fn point_on_or_after(&'a self, x: Self::X) -> Option<&'a Self::Point> {
        self.point_idx_on_or_after(x).and_then(|i| self.points().nth(i))
    }

    /// A reference to the first point that comes after the given `x` along with its index.
    #[inline]
    fn point_after_with_idx(&'a self, x: Self::X) -> Option<(usize, &'a Self::Point)> {
        self.point_idx_after(x).and_then(|i| self.points().nth(i).map(|p| (i, p)))
    }

    /// A reference to the first point that is equal to or comes after the given `x` along with
    /// its index.
    #[inline]
    fn point_on_or_after_with_idx(&'a self, x: Self::X) -> Option<(usize, &'a Self::Point)> {
        self.point_idx_on_or_after(x).and_then(|i| self.points().nth(i).map(|p| (i, p)))
    }

    /// A reference to the first point lying directly on the given `x` if there is one.
    #[inline]
    fn point_at(&'a self, x: Self::X) -> Option<&'a Self::Point> {
        self.points().find(|p| p.x() == x)
    }

    /// A reference to the first point (along with it's index) lying directly on the given `x` if
    /// there is one.
    #[inline]
    fn point_at_with_idx(&'a self, x: Self::X) -> Option<(usize, &'a Self::Point)> {
        self.points().enumerate().find(|&(_, p)| p.x() == x)
    }

    /// The points that lie on either side of the given `x`.
    ///
    /// FIXME: This could be much faster.
    #[inline]
    fn surrounding_points(&'a self, x: Self::X)
        -> (Option<&'a Self::Point>, Option<&'a Self::Point>)
    {
        (self.point_on_or_before(x.clone()), self.point_after(x))
    }

    /// A reference point that is closest to the given `x` if there is one.
    ///
    /// FIXME: This could be much faster.
    #[inline]
    fn closest_point(&'a self, x: Self::X) -> Option<&'a Self::Point>
        where <Self as Envelope<'a>>::X: std::ops::Sub<Output=<Self as Envelope<'a>>::X>,
    {
        match self.surrounding_points(x.clone()) {
            (Some(before), Some(after)) =>
                if x.clone() - before.x() < after.x() - x { Some(before) } else { Some(after) },
            (Some(point), None) | (None, Some(point)) => Some(point),
            (None, None) => None,
        }
    }

    /// Return `y` for the given `x`.
    ///
    /// If there is less than two points interpolation is not meaningful,
    /// thus we should just return None.
    ///
    /// Note: It is assumed that the points owned by the Envelope are sorted by `x`.
    #[inline]
    fn y(&'a self, x: Self::X) -> Option<Self::Y>
        where <Self::Y as Spatial>::Scalar: Scalar,
    {
        y(self, x)
    }

    /// Sample the `Envelope`'s `y` value for every given positive `x` step starting from the first
    /// point's `X` value.
    ///
    /// The envelope will yield `Some(Y)` until the first step is out of range of all points on the
    /// y axis.
    ///
    /// Returns `None` if `start` is outside the bounds of all points.
    ///
    /// Note: This method assumes that the envelope points are ordered.
    #[inline]
    fn steps(&'a self, start: Self::X, step: Self::X) -> Option<Steps<'a, Self>> {
        let mut points = self.points();
        points.next().and_then(|mut left| {
            let mut maybe_right = None;

            // Iterate through `points` until `start` is between `left` and `right`
            while let Some(point) = points.next() {
                maybe_right = Some(point);
                if point.x() < start {
                    left = maybe_right.take().unwrap();
                } else {
                    break;
                }
            }

            // Check that the remaining points bound the `start`.
            match maybe_right {
                Some(right) => if right.x() < start { return None; },
                None => if left.x() < start { return None; },
            }

            Some(Steps {
                points: points,
                step: step,
                next_x: start,
                left: left,
                maybe_right: maybe_right,
                env: std::marker::PhantomData,
            })
        })
    }

    // /// An iterator yielding the X for each point at which the envelope intersects the given `y`.
    // ///
    // /// If there are any periods at which X is continuous, only the start X of the continuous
    // /// period will be returned.
    // fn xs_at_y(&self, y: Y) -> XsAtY {
    //     unimplemented!();
    // }

}


/// An iterator that interpolates the envelope `E` one `step` and yields the result.
///
/// Returns `None` the first time `next` falls out of range of all points in `env`.
#[derive(Clone)]
pub struct Steps<'a, E>
    where E: Envelope<'a> + 'a,
{
    points: E::Points,
    step: E::X,
    next_x: E::X,
    left: &'a E::Point,
    maybe_right: Option<&'a E::Point>,
    env: std::marker::PhantomData<E>,
}

impl<'a, E> Steps<'a, E>
    where E: Envelope<'a>,
{
    /// This is useful when the step size must change between steps.
    #[inline]
    pub fn set_step(&mut self, step: E::X) {
        self.step = step;
    }

    /// Yields the next step along with its position along the step.
    #[inline]
    pub fn next_xy(&mut self) -> Option<(E::X, E::Y)>
        where Self: Iterator<Item=E::Y>,
    {
        let x = self.next_x.clone();
        self.next().map(|y| (x, y))
    }
}

impl<'a, E> Iterator for Steps<'a, E>
    where E: Envelope<'a>,
          <E as Envelope<'a>>::X: std::ops::Add<Output=<E as Envelope<'a>>::X>,
          <<E as Envelope<'a>>::Y as Spatial>::Scalar: Scalar,
{
    type Item = E::Y;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        let Steps {
            ref step,
            ref mut points,
            ref mut next_x,
            ref mut left,
            ref mut maybe_right,
            ..
        } = *self;

        let x = next_x.clone();
        *next_x = x.clone() + step.clone();
        maybe_right.as_mut()
            .and_then(|right| {
                let x = x.clone();
                while x > right.x() {
                    *left = right;
                    *right = match points.next() {
                        Some(point) => point,
                        None => return None,
                    };
                }
                Some(Point::interpolate(x, *left, *right))
            })
            .or_else(|| if x == left.x() { Some(left.y()) } else { None })
    }
}


#[inline]
fn point_idx_before<'a, E>(env: &'a E, x: E::X) -> Option<usize>
    where E: Envelope<'a>,
{
    env.points().enumerate()
        .take_while(|&(_, point)| point.x() < x )
        .last()
        .map(|(i, _)| i)
}


#[inline]
fn point_idx_on_or_before<'a, E>(env: &'a E, x: E::X) -> Option<usize>
    where E: Envelope<'a>,
{
    env.points().enumerate()
        .take_while(|&(_, point)| point.x() <= x )
        .last()
        .map(|(i, _)| i)
}


#[inline]
fn point_idx_after<'a, E>(env: &'a E, x: E::X) -> Option<usize>
    where E: Envelope<'a>,
{
    env.points().enumerate().rev()
        .take_while(|&(_, point)| point.x() > x )
        .last()
        .map(|(i, _)| i)
}


#[inline]
fn point_idx_on_or_after<'a, E>(env: &'a E, x: E::X) -> Option<usize>
    where E: Envelope<'a>,
{
    env.points().enumerate().rev()
        .take_while(|&(_, point)| point.x() >= x )
        .last()
        .map(|(i, _)| i)
}


#[inline]
fn y<'a, E>(env: &'a E, x: E::X) -> Option<E::Y>
    where E: Envelope<'a>,
          E::Y: Spatial + PartialEq + 'a,
          <<E as Envelope<'a>>::Y as Spatial>::Scalar: Scalar,
{
    let mut points = env.points();
    points.next().and_then(|mut left| {
        let mut maybe_right = None;

        // Iterate through `points` until `x` is between `left` and `right`
        while let Some(point) = points.next() {
            maybe_right = Some(point);
            if point.x() < x {
                left = maybe_right.take().unwrap();
            } else {
                break;
            }
        }

        // Check that the remaining points bound the `x`.
        match maybe_right {
            Some(right) => if right.x() < x { return None; },
            None => if left.x() < x { return None; },
        }

        maybe_right
            .and_then(|mut right| {
                let x = x.clone();
                while x > right.x() {
                    left = right;
                    right = match points.next() {
                        Some(point) => point,
                        None => return None,
                    };
                }
                Some(Point::interpolate(x, left, right))
            })
            .or_else(|| if x == left.x() { Some(left.y()) } else { None })
    })
}