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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! Defines a [`Collate`] trait to standardize collation methods across data types. The provided
//! [`Collator`] struct can be used to collate a collection of slices of type `T` where `T: Ord`.
//! Also provides `bisect` (with a [`Range`]), `bisect_left`, and `bisect_right` methods.
//!
//! [`Collate`] is useful for implementing a B-Tree, or to handle cases where a collator type is
//! more efficient than calling `Ord::cmp` repeatedly, for example when collating localized strings
//! using `rust_icu_ucol`.
//!
//! Example:
//! ```
//! # use collate::*;
//! let collator = Collator::default();
//! let collection = [
//!     [1, 2, 3],
//!     [2, 3, 4],
//!     [3, 4, 5],
//! ];
//!
//! assert_eq!(collator.bisect_left(&collection, &[1]), 0);
//! assert_eq!(collator.bisect_right(&collection, &[1]), 1);
//! ```

use std::borrow::Borrow;
use std::cmp::Ordering;
use std::marker::PhantomData;
use std::ops::Bound;

#[cfg(feature = "complex")]
mod complex;
mod range;

#[cfg(feature = "complex")]
pub use complex::*;
pub use range::*;

/// Defines methods to collate a collection of slices of type `Value`, given a comparator.
pub trait Collate {
    type Value;

    /// Given a collection of slices, return the start and end indices which match the given range.
    fn bisect<V: AsRef<[Self::Value]>, B: Borrow<[Self::Value]>>(
        &self,
        slice: &[V],
        range: &Range<Self::Value, B>,
    ) -> (usize, usize) {
        debug_assert!(self.is_sorted(slice));

        let left = bisect_left(slice, |key| self.compare_range(key, range));
        let right = bisect_right(slice, |key| self.compare_range(key, range));
        (left, right)
    }

    /// Given a collection of slices, return the leftmost insert point matching the given key.
    fn bisect_left<V: AsRef<[Self::Value]>>(&self, slice: &[V], key: &[Self::Value]) -> usize {
        debug_assert!(self.is_sorted(slice));

        if slice.as_ref().is_empty() || key.as_ref().is_empty() {
            0
        } else {
            bisect_left(slice, |at| self.compare_slice(at, key))
        }
    }

    /// Given a collection of slices, return the rightmost insert point matching the given key.
    fn bisect_right<V: AsRef<[Self::Value]>>(&self, slice: &[V], key: &[Self::Value]) -> usize {
        debug_assert!(self.is_sorted(slice));
        let slice = slice.as_ref();

        if slice.is_empty() {
            0
        } else if key.is_empty() {
            slice.len()
        } else {
            bisect_right(slice, |at| self.compare_slice(at, key))
        }
    }

    /// Define the relative ordering of `Self::Value`.
    fn compare(&self, left: &Self::Value, right: &Self::Value) -> Ordering;

    /// Returns the ordering of the given key relative to the given range.
    fn compare_range<B: Borrow<[Self::Value]>>(
        &self,
        key: &[Self::Value],
        range: &Range<Self::Value, B>,
    ) -> Ordering {
        use Bound::*;
        use Ordering::*;

        if !range.prefix().is_empty() {
            let prefix_rel = self.compare_slice(key, range.prefix());
            if prefix_rel != Equal || key.len() < range.len() {
                return prefix_rel;
            }
        }

        if !range.has_bounds() {
            return Equal;
        }

        let target = &key[range.prefix().len()];

        match range.start() {
            Unbounded => {}
            Included(value) => match self.compare(target, value) {
                Less => return Less,
                _ => {}
            },
            Excluded(value) => match self.compare(target, value) {
                Less | Equal => return Less,
                _ => {}
            },
        }

        match range.end() {
            Unbounded => {}
            Included(value) => match self.compare(target, value) {
                Greater => return Greater,
                _ => {}
            },
            Excluded(value) => match self.compare(target, value) {
                Greater | Equal => return Greater,
                _ => {}
            },
        }

        Equal
    }

    /// Returns the relative ordering of the `left` slice with respect to `right`.
    fn compare_slice<L: AsRef<[Self::Value]>, R: AsRef<[Self::Value]>>(
        &self,
        left: L,
        right: R,
    ) -> Ordering {
        let left = left.as_ref();
        let right = right.as_ref();

        use Ordering::*;

        for i in 0..Ord::min(left.len(), right.len()) {
            match self.compare(&left[i], &right[i]) {
                Equal => {}
                rel => return rel,
            };
        }

        if left.is_empty() && !right.is_empty() {
            Less
        } else if !left.is_empty() && right.is_empty() {
            Greater
        } else {
            Equal
        }
    }

    /// Returns `true` if the given slice is in sorted order.
    fn is_sorted<V: AsRef<[Self::Value]>>(&self, slice: &[V]) -> bool {
        if slice.len() < 2 {
            return true;
        }

        let order = self.compare_slice(slice[1].as_ref(), slice[0].as_ref());
        for i in 1..slice.len() {
            let rel = self.compare_slice(slice[i].as_ref(), slice[i - 1].as_ref());
            if rel != order && rel != Ordering::Equal {
                return false;
            }
        }

        true
    }
}

/// A generic collator for any type `T: Ord`.
#[derive(Default, Clone)]
pub struct Collator<T> {
    phantom: PhantomData<T>,
}

impl<T: Ord> Collate for Collator<T> {
    type Value = T;

    fn compare(&self, left: &Self::Value, right: &Self::Value) -> Ordering {
        left.cmp(right)
    }
}

pub fn compare_f32(left: &f32, right: &f32) -> Ordering {
    if let Some(order) = left.partial_cmp(right) {
        order
    } else {
        if left == right {
            Ordering::Equal
        } else if left == &f32::NEG_INFINITY || right == &f32::INFINITY {
            Ordering::Less
        } else if left == &f32::INFINITY || right == &f32::NEG_INFINITY {
            Ordering::Greater
        } else {
            panic!("no collation defined between {} and {}", left, right)
        }
    }
}

pub fn compare_f64(left: &f64, right: &f64) -> Ordering {
    if let Some(order) = left.partial_cmp(right) {
        order
    } else {
        if left == right {
            Ordering::Equal
        } else if left == &f64::NEG_INFINITY || right == &f64::INFINITY {
            Ordering::Less
        } else if left == &f64::INFINITY || right == &f64::NEG_INFINITY {
            Ordering::Greater
        } else {
            panic!("no collation defined between {} and {}", left, right)
        }
    }
}

#[derive(Copy, Clone)]
pub struct FloatCollator<T> {
    phantom: PhantomData<T>,
}

impl Collate for FloatCollator<f32> {
    type Value = f32;

    fn compare(&self, left: &Self::Value, right: &Self::Value) -> Ordering {
        compare_f32(left, right)
    }
}

impl Default for FloatCollator<f32> {
    fn default() -> Self {
        Self {
            phantom: PhantomData,
        }
    }
}

impl Collate for FloatCollator<f64> {
    type Value = f64;

    fn compare(&self, left: &Self::Value, right: &Self::Value) -> Ordering {
        compare_f64(left, right)
    }
}

impl Default for FloatCollator<f64> {
    fn default() -> Self {
        Self {
            phantom: PhantomData,
        }
    }
}

fn bisect_left<'a, V: 'a, W: AsRef<[V]>, F: Fn(&'a [V]) -> Ordering>(
    slice: &'a [W],
    cmp: F,
) -> usize {
    let mut start = 0;
    let mut end = slice.len();

    while start < end {
        let mid = (start + end) / 2;

        if cmp(slice[mid].as_ref()) == Ordering::Less {
            start = mid + 1;
        } else {
            end = mid;
        }
    }

    start
}

fn bisect_right<'a, V: 'a, W: AsRef<[V]>, F: Fn(&'a [V]) -> Ordering>(
    slice: &'a [W],
    cmp: F,
) -> usize {
    let mut start = 0;
    let mut end = slice.len();

    while start < end {
        let mid = (start + end) / 2;

        if cmp(slice[mid].as_ref()) == Ordering::Greater {
            end = mid;
        } else {
            start = mid + 1;
        }
    }

    end
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ops::Deref;

    struct Key {
        inner: Vec<i32>,
    }

    impl Deref for Key {
        type Target = [i32];

        fn deref(&self) -> &[i32] {
            &self.inner
        }
    }

    impl AsRef<[i32]> for Key {
        fn as_ref(&self) -> &[i32] {
            self.deref()
        }
    }

    struct Block {
        keys: Vec<Key>,
    }

    impl Deref for Block {
        type Target = [Key];

        fn deref(&self) -> &[Key] {
            &self.keys
        }
    }

    impl AsRef<[Key]> for Block {
        fn as_ref(&self) -> &[Key] {
            self.deref()
        }
    }

    #[test]
    fn test_bisect() {
        let block = Block {
            keys: vec![
                Key {
                    inner: vec![0, -1, 1],
                },
                Key {
                    inner: vec![1, 0, 2, 2],
                },
                Key {
                    inner: vec![1, 1, 0],
                },
                Key {
                    inner: vec![1, 1, 0],
                },
                Key {
                    inner: vec![2, 0, -1],
                },
                Key { inner: vec![2, 1] },
            ],
        };

        let collator = Collator::<i32>::default();
        assert!(collator.is_sorted(&block));

        assert_eq!(collator.bisect_left(&block, &[0, 0, 0]), 1);
        assert_eq!(collator.bisect_right(&block, &[0, 0, 0]), 1);

        assert_eq!(collator.bisect_left(&block, &[0]), 0);
        assert_eq!(collator.bisect_right(&block, &[0]), 1);

        assert_eq!(collator.bisect_left(&block, &[1]), 1);
        assert_eq!(collator.bisect_right(&block, &[1]), 4);

        assert_eq!(collator.bisect_left(&block, &[1, 1, 0]), 2);
        assert_eq!(collator.bisect_right(&block, &[1, 1, 0]), 4);

        assert_eq!(collator.bisect_left(&block, &[1, 1, 0, -1]), 2);
        assert_eq!(collator.bisect_right(&block, &[1, 1, 0, -1]), 4);
        assert_eq!(collator.bisect_right(&block, &[1, 1, 0, 1]), 4);

        assert_eq!(collator.bisect_left(&block, &[3]), 6);
        assert_eq!(collator.bisect_right(&block, &[3]), 6);
    }

    #[test]
    fn test_range() {
        let block = Block {
            keys: vec![
                Key {
                    inner: vec![0, -1, 1],
                },
                Key {
                    inner: vec![1, -1, 2],
                },
                Key {
                    inner: vec![1, 0, -1],
                },
                Key {
                    inner: vec![1, 0, 2, 2],
                },
                Key {
                    inner: vec![1, 1, 0],
                },
                Key {
                    inner: vec![1, 1, 0],
                },
                Key {
                    inner: vec![1, 2, 1],
                },
                Key { inner: vec![2, 1] },
                Key { inner: vec![3, 1] },
            ],
        };

        let collator = Collator::<i32>::default();
        assert!(collator.is_sorted(&block));

        let range = Range::from(([], 0..1));
        assert_eq!(collator.bisect(&block, &range), (0, 1));

        let range = Range::from(([1], 0..1));
        assert_eq!(collator.bisect(&block, &range), (2, 4));

        let range = Range::from(([1], -1..));
        assert_eq!(collator.bisect(&block, &range), (1, 7));

        let range = Range::from(([1], 0..));
        assert_eq!(collator.bisect(&block, &range), (2, 7));

        let range = Range::from(([1, 0], ..1));
        assert_eq!(collator.bisect(&block, &range), (2, 3));

        assert_eq!(collator.bisect(&block, &Range::default()), (0, block.len()));
    }

    #[test]
    fn test_range_contains() {
        let outer = Range::with_prefix(vec![1]);
        let inner = Range::with_prefix(vec![1, 2]);
        assert!(outer.contains(&inner, &Collator::default()));
        assert!(!inner.contains(&outer, &Collator::default()));

        let outer = Range::with_prefix(vec![1, 2]);
        let inner = Range::new(vec![1, 2], 1..3);
        assert!(outer.contains(&inner, &Collator::default()));
        assert!(!inner.contains(&outer, &Collator::default()));

        let outer = Range::with_prefix(vec![1, 2, 2]);
        let inner = Range::new(vec![1, 2], 1..2);
        assert!(!outer.contains(&inner, &Collator::default()));
        assert!(!inner.contains(&outer, &Collator::default()));

        let outer = Range::new(vec![1, 2], 3..4);
        let inner = Range::with_prefix(vec![1, 2, 3]);
        assert!(outer.contains(&inner, &Collator::default()));
        assert!(!inner.contains(&outer, &Collator::default()));
    }
}