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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
//! A hash set ordered using a linked list.
//!
//! Example:
//! ```
//! use ds_ext::OrdHashSet;
//!
//! let mut set1 = OrdHashSet::new();
//! assert!(set1.insert("d"));
//! assert!(set1.insert("a"));
//! assert!(set1.insert("c"));
//! assert!(set1.insert("b"));
//! assert!(!set1.insert("a"));
//! assert_eq!(set1.len(), 4);
//!
//! let mut set2 = set1.clone();
//! assert!(set2.remove(&"d"));
//! assert_eq!(set2.len(), 3);
//!
//! assert_eq!(
//!     set1.into_iter().collect::<Vec<&str>>(),
//!     ["a", "b", "c", "d"]
//! );
//!
//! assert_eq!(
//!     set2.into_iter().rev().collect::<Vec<&str>>(),
//!     ["c", "b", "a"]
//! );
//! ```

use std::borrow::Borrow;
use std::cmp::Ordering;
use std::collections::HashSet as Inner;
use std::fmt;
use std::hash::Hash;
use std::sync::Arc;

use get_size::GetSize;
use get_size_derive::*;

use super::list::List;

/// An iterator to drain the contents of a [`OrdHashSet`]
pub struct Drain<'a, T> {
    inner: &'a mut Inner<Arc<T>>,
    order: super::list::Drain<'a, Arc<T>>,
}

impl<'a, T> Iterator for Drain<'a, T>
where
    T: Eq + Hash + fmt::Debug,
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        let item = self.order.next()?;
        self.inner.remove(&*item);
        Some(Arc::try_unwrap(item).expect("item"))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.order.size_hint()
    }
}

impl<'a, T> DoubleEndedIterator for Drain<'a, T>
where
    T: Eq + Hash + fmt::Debug,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        let item = self.order.next_back()?;
        self.inner.remove(&*item);
        Some(Arc::try_unwrap(item).expect("item"))
    }
}

/// An iterator to drain the contents of a [`OrdHashSet`] conditionally
pub struct DrainWhile<'a, T, Cond> {
    inner: &'a mut Inner<Arc<T>>,
    order: &'a mut List<Arc<T>>,
    cond: Cond,
}

impl<'a, T, Cond> Iterator for DrainWhile<'a, T, Cond>
where
    T: Eq + Hash + fmt::Debug,
    Cond: Fn(&T) -> bool,
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if (self.cond)(self.order.front()?) {
            let item = self.order.pop_front().expect("item");
            self.inner.remove(&*item);
            Some(Arc::try_unwrap(item).expect("item"))
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, Some(self.inner.len()))
    }
}

/// An iterator over the contents of a [`OrdHashSet`]
pub struct IntoIter<T> {
    inner: super::list::IntoIter<Arc<T>>,
}

impl<T: fmt::Debug> Iterator for IntoIter<T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner
            .next()
            .map(|item| Arc::try_unwrap(item).expect("item"))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl<T: fmt::Debug> DoubleEndedIterator for IntoIter<T> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner
            .next_back()
            .map(|item| Arc::try_unwrap(item).expect("item"))
    }
}

/// An iterator over the items in a [`OrdHashSet`]
pub struct Iter<'a, T> {
    inner: super::list::Iter<'a, Arc<T>>,
}

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|item| &**item)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back().map(|item| &**item)
    }
}

/// A [`std::collections::HashSet`] ordered using a [`List`].
#[derive(GetSize)]
pub struct OrdHashSet<T> {
    inner: Inner<Arc<T>>,
    order: List<Arc<T>>,
}

impl<T: Clone + Eq + Hash + Ord + fmt::Debug> Clone for OrdHashSet<T> {
    fn clone(&self) -> Self {
        self.iter().cloned().collect()
    }
}

impl<T: PartialEq + fmt::Debug> PartialEq for OrdHashSet<T> {
    fn eq(&self, other: &Self) -> bool {
        self.order == other.order
    }
}

impl<T: Eq + fmt::Debug> Eq for OrdHashSet<T> {}

impl<T> OrdHashSet<T> {
    /// Construct a new [`OrdHashSet`].
    pub fn new() -> Self {
        Self {
            inner: Inner::new(),
            order: List::new(),
        }
    }

    /// Construct a new [`OrdHashSet`] with the given `capacity`.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            inner: Inner::with_capacity(capacity),
            order: List::with_capacity(capacity),
        }
    }

    /// Construct an iterator over the items in this [`OrdHashSet`].
    pub fn iter(&self) -> Iter<T> {
        Iter {
            inner: self.order.iter(),
        }
    }

    /// Return `true` if this [`OrdHashSet`] is empty.
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Return the number of items in this [`OrdHashSet`].
    pub fn len(&self) -> usize {
        self.inner.len()
    }
}

impl<T: Eq + Hash + Ord> OrdHashSet<T> {
    fn bisect_hi<Cmp>(&self, cmp: Cmp) -> usize
    where
        Cmp: Fn(&T) -> Option<Ordering>,
    {
        if self.is_empty() {
            return 0;
        } else if cmp(self.order.back().expect("tail")).is_some() {
            return self.len();
        }

        let mut lo = 0;
        let mut hi = self.len();

        while lo < hi {
            let mid = (lo + hi) >> 1;
            let item = self.order.get(mid).expect("item");

            if cmp(&**item).is_some() {
                lo = mid + 1;
            } else {
                hi = mid;
            }
        }

        hi
    }

    fn bisect_lo<Cmp>(&self, cmp: Cmp) -> usize
    where
        Cmp: Fn(&T) -> Option<Ordering>,
    {
        if self.is_empty() {
            return 0;
        } else if cmp(self.order.front().expect("head")).is_some() {
            return 0;
        }

        let mut lo = 0;
        let mut hi = 1;

        while lo < hi {
            let mid = (lo + hi) >> 1;
            let item = self.order.get(mid).expect("item");

            if cmp(&**item).is_some() {
                hi = mid;
            } else {
                lo = mid + 1;
            }
        }

        hi
    }

    fn bisect_inner<Cmp>(&self, cmp: Cmp, mut lo: usize, mut hi: usize) -> Option<&T>
    where
        Cmp: Fn(&T) -> Option<Ordering>,
    {
        while lo < hi {
            let mid = (lo + hi) >> 1;
            let item = self.order.get(mid).expect("item");

            if let Some(order) = cmp(&**item) {
                match order {
                    Ordering::Less => hi = mid,
                    Ordering::Equal => return Some(item),
                    Ordering::Greater => lo = mid + 1,
                }
            } else {
                panic!("comparison does not match distribution")
            }
        }

        None
    }

    /// Bisect this set to match an item using the provided comparison, and return it (if present).
    ///
    /// The first item for which the comparison returns `Some(Ordering::Equal)` will be returned.
    /// This method assumes that any partially-ordered items (where `cmp(item).is_none()`)
    /// are ordered at the beginning or end of the set.
    pub fn bisect<Cmp>(&self, cmp: Cmp) -> Option<&T>
    where
        Cmp: Fn(&T) -> Option<Ordering> + Copy,
    {
        let lo = self.bisect_lo(cmp);
        let hi = self.bisect_hi(cmp);
        self.bisect_inner(cmp, lo, hi)
    }

    /// Bisect this set to match and remove an item using the provided comparison.
    ///
    /// The first item for which the comparison returns `Some(Ordering::Equal)` will be returned.
    /// This method assumes that any partially-ordered items (where `cmp(item).is_none()`)
    /// are ordered at the beginning and/or end of the set.
    pub fn bisect_and_remove<Cmp>(&mut self, cmp: Cmp) -> Option<T>
    where
        Cmp: Fn(&T) -> Option<Ordering> + Copy,
        T: fmt::Debug,
    {
        let mut lo = self.bisect_lo(cmp);
        let mut hi = self.bisect_hi(cmp);

        let item = loop {
            if lo >= hi {
                break None;
            }

            let mid = (lo + hi) >> 1;
            let item = self.order.get(mid).expect("item");

            if let Some(order) = cmp(&**item) {
                match order {
                    Ordering::Less => hi = mid,
                    Ordering::Equal => {
                        lo = mid;
                        break Some(item.clone());
                    }
                    Ordering::Greater => lo = mid + 1,
                }
            } else {
                panic!("comparison does not match distribution")
            }
        }?;

        self.order.remove(lo);
        self.inner.remove(&item);

        Some(Arc::try_unwrap(item).expect("item"))
    }

    /// Remove all items from this [`OrdHashSet`].
    pub fn clear(&mut self) {
        self.inner.clear();
        self.order.clear();
    }

    /// Return `true` if the given item is present in this [`OrdHashSet`].
    pub fn contains<Q: ?Sized>(&self, item: &Q) -> bool
    where
        Arc<T>: Borrow<Q>,
        Q: Hash + Eq,
    {
        self.inner.contains(item)
    }

    /// Drain all items from this [`OrdHashSet`].
    pub fn drain(&mut self) -> Drain<T> {
        Drain {
            inner: &mut self.inner,
            order: self.order.drain(),
        }
    }

    /// Drain items from this [`OrdHashSet`] while they match the given `cond`ition.
    pub fn drain_while<Cond>(&mut self, cond: Cond) -> DrainWhile<T, Cond>
    where
        Cond: Fn(&T) -> bool,
    {
        DrainWhile {
            inner: &mut self.inner,
            order: &mut self.order,
            cond,
        }
    }

    /// Consume the given `iter` and insert all its items into this [`OrdHashSet`]
    pub fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        for item in iter {
            self.insert(item);
        }
    }

    /// Borrow the first item in this [`OrdHashSet`].
    pub fn first(&self) -> Option<&T> {
        self.order.front().map(|item| &**item)
    }

    /// Insert an `item` into this [`OrdHashSet`] and return `false` if it was already present.
    pub fn insert(&mut self, item: T) -> bool {
        let new = if self.inner.contains(&item) {
            false
        } else {
            let item = Arc::new(item);

            let index = bisect(&self.order, &item);
            if index == self.len() {
                self.order.insert(index, item.clone());
            } else {
                let prior = self.order.get(index).expect("item").clone();

                if &prior < &item {
                    self.order.insert(index + 1, item.clone());
                } else {
                    self.order.insert(index, item.clone());
                }
            }

            self.inner.insert(item)
        };

        new
    }

    /// Borrow the last item in this [`OrdHashSet`].
    pub fn last(&self) -> Option<&T> {
        self.order.back().map(|item| &**item)
    }

    /// Remove and return the first item in this [`OrdHashSet`].
    pub fn pop_first(&mut self) -> Option<T>
    where
        T: fmt::Debug,
    {
        if let Some(item) = self.order.pop_front() {
            self.inner.remove(&item);
            Some(Arc::try_unwrap(item).expect("item"))
        } else {
            None
        }
    }

    /// Remove and return the last item in this [`OrdHashSet`].
    pub fn pop_last(&mut self) -> Option<T>
    where
        T: fmt::Debug,
    {
        if let Some(item) = self.order.pop_back() {
            self.inner.remove(&item);
            Some(Arc::try_unwrap(item).expect("item"))
        } else {
            None
        }
    }

    /// Remove the given `item` from this [`OrdHashSet`] and return `true` if it was present.
    ///
    /// The item may be any borrowed form of `T`,
    /// but the ordering on the borrowed form **must** match the ordering of `T`.
    pub fn remove<Q>(&mut self, item: &Q) -> bool
    where
        Arc<T>: Borrow<Q>,
        Q: Eq + Hash + Ord,
    {
        if self.inner.remove(item) {
            let index = bisect(&self.order, item);
            assert!(self.order.remove(index).expect("removed").borrow() == item);
            true
        } else {
            false
        }
    }

    /// Return `true` if the first elements in this set are equal to those in the given `iter`.
    pub fn starts_with<'a, I: IntoIterator<Item = &'a T>>(&'a self, other: I) -> bool
    where
        T: PartialEq,
    {
        let mut this = self.iter();
        let mut that = other.into_iter();

        while let Some(item) = that.next() {
            if this.next() != Some(item) {
                return false;
            }
        }

        true
    }
}

impl<T: Eq + Hash + Ord + fmt::Debug> OrdHashSet<T> {
    #[allow(unused)]
    fn is_valid(&self) -> bool {
        assert_eq!(self.inner.len(), self.order.len());

        if self.is_empty() {
            return true;
        }

        let mut item = self.order.get(0).expect("item");
        for i in 1..self.len() {
            let next = self.order.get(i).expect("next");
            assert!(*item <= *next, "set out of order: {:?}", self);
            assert!(*next >= *item);
            item = next;
        }

        true
    }
}

impl<T: Eq + Hash + Ord + fmt::Debug> fmt::Debug for OrdHashSet<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("[ ")?;

        for item in self {
            write!(f, "{:?} ", item)?;
        }

        f.write_str("]")
    }
}

impl<T: Eq + Hash + Ord + fmt::Debug> FromIterator<T> for OrdHashSet<T> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let iter = iter.into_iter();
        let mut set = match iter.size_hint() {
            (_, Some(max)) => Self::with_capacity(max),
            (min, None) if min > 0 => Self::with_capacity(min),
            _ => Self::new(),
        };

        set.extend(iter);
        set
    }
}

impl<T: fmt::Debug> IntoIterator for OrdHashSet<T> {
    type Item = T;
    type IntoIter = IntoIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        IntoIter {
            inner: self.order.into_iter(),
        }
    }
}

impl<'a, T> IntoIterator for &'a OrdHashSet<T> {
    type Item = &'a T;
    type IntoIter = Iter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        OrdHashSet::iter(self)
    }
}

#[inline]
fn bisect<T, Q>(list: &List<T>, target: &Q) -> usize
where
    T: Borrow<Q> + Ord,
    Q: Ord,
{
    if let Some(front) = list.front() {
        if target < (*front).borrow() {
            return 0;
        }
    }

    if let Some(last) = list.back() {
        if target > (*last).borrow() {
            return list.len();
        }
    }

    let mut lo = 0;
    let mut hi = list.len();

    while lo < hi {
        let mid = (lo + hi) >> 1;
        let item = &*list.get(mid).expect("item");

        match item.borrow().cmp(target) {
            Ordering::Less => lo = mid + 1,
            Ordering::Greater => hi = mid,
            Ordering::Equal => return mid,
        }
    }

    lo
}

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

    #[test]
    fn test_bisect_and_remove() {
        let mut set = OrdHashSet::<u8>::new();

        assert!(set.bisect_and_remove(|item| item.partial_cmp(&8)).is_none());

        set.insert(8);
        assert!(set.bisect_and_remove(|item| item.partial_cmp(&8)).is_some());
        assert!(set.bisect_and_remove(|item| item.partial_cmp(&8)).is_none());

        set.insert(9);
        assert!(set.bisect_and_remove(|item| item.partial_cmp(&8)).is_none());

        set.insert(7);
        assert!(set.bisect_and_remove(|item| item.partial_cmp(&8)).is_none());
    }

    #[test]
    fn test_into_iter() {
        let mut set = OrdHashSet::new();
        assert!(set.insert("d"));
        assert!(set.insert("a"));
        assert!(set.insert("c"));
        assert!(set.insert("b"));
        assert!(!set.insert("a"));
        assert_eq!(set.len(), 4);

        assert_eq!(set.into_iter().collect::<Vec<&str>>(), ["a", "b", "c", "d"]);
    }

    #[test]
    fn test_drain() {
        let mut set = OrdHashSet::from_iter(0..10);
        let expected = (0..10).into_iter().collect::<Vec<_>>();
        let actual = set.drain().collect::<Vec<_>>();
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_drain_while() {
        let mut set = OrdHashSet::from_iter(0..10);
        let drained = set.drain_while(|x| *x < 5).collect::<Vec<_>>();
        assert_eq!(drained, vec![0, 1, 2, 3, 4]);
        assert_eq!(set, OrdHashSet::from_iter(5..10));
    }
}