intrex 0.1.1

Intrusive doubly-linked lists with items addressed by indices
Documentation
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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
//! Mutable linked list accessor.
use core::{cmp::Ordering, mem::swap};

use super::*;
use crate::sort_slist;

/// Mutably borrow the [`Link`] for `$index`. Panics if
/// [`ListAccessorMut::map_link`] returns `None`.
macro_rules! link {
    ($accessor:expr, $index:expr) => {
        ($accessor.map_link)($accessor.pool.index_mut($index))
            .as_mut()
            .unwrap()
    };
}

/// A storage for elements.
///
/// This is automatically implemented for all types implementing
/// [`ops::IndexMut`].
pub trait PoolMut<Index>: accessor::Pool<Index> {
    /// Mutably borrow the element at index `index`.
    fn index_mut(&mut self, index: Index) -> &mut Self::Element;
}

impl<T, Index> PoolMut<Index> for T
where
    T: ?Sized + ops::IndexMut<Index>,
{
    #[inline]
    fn index_mut(&mut self, index: Index) -> &mut Self::Element {
        ops::IndexMut::index_mut(self, index)
    }
}

impl<Index> Head<Index> {
    /// Create a mutable accessor to the list.
    #[inline]
    pub fn accessor_mut<'head, 'pool, Pool, MapLink, Element>(
        &'head mut self,
        pool: &'pool mut Pool,
        map_link: MapLink,
    ) -> ListAccessorMut<'head, 'pool, Index, Pool, MapLink>
    where
        Pool: ?Sized + PoolMut<Index, Element = Element>,
        MapLink: Fn(&mut Element) -> &mut Option<Link<Index>>,
    {
        ListAccessorMut {
            head: self,
            pool,
            map_link,
        }
    }
}

/// Mutable accessor to a linked list.
///
/// Created by [`Head::accessor_mut`].
#[derive(Debug)]
pub struct ListAccessorMut<'head, 'pool, Index, Pool: ?Sized, MapLink> {
    head: &'head mut Head<Index>,
    pool: &'pool mut Pool,
    map_link: MapLink,
}

impl<'head, 'pool, Index, Pool, MapLink, Element>
    ListAccessorMut<'head, 'pool, Index, Pool, MapLink>
where
    Pool: ?Sized + PoolMut<Index, Element = Element>,
    MapLink: Fn(&mut Element) -> &mut Option<Link<Index>>,
    Index: PartialEq + Clone,
{
    /// Borrow the list header.
    #[inline]
    pub fn head(&self) -> &Head<Index> {
        self.head
    }

    /// Mutably borrow the list header.
    #[inline]
    pub fn head_mut(&mut self) -> &mut Head<Index> {
        self.head
    }

    /// Borrow the element pool.
    #[inline]
    pub fn pool(&self) -> &Pool {
        self.pool
    }

    /// Mutably borrow the element pool.
    #[inline]
    pub fn pool_mut(&mut self) -> &mut Pool {
        self.pool
    }

    /// Check if the list is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.head.is_empty()
    }

    /// Get the first element's index.
    #[inline]
    pub fn front_index(&mut self) -> Option<Index> {
        self.head.first.clone()
    }

    /// Get the last element's index.
    #[inline]
    pub fn back_index(&mut self) -> Option<Index> {
        self.head.first.clone().map(|p| link!(self, p).prev.clone())
    }

    /// Mutably borrow the first element.
    #[doc(alias = "first_mut")]
    #[inline]
    pub fn front_mut(&mut self) -> Option<&mut Element> {
        if let Some(p) = self.front_index() {
            Some(self.pool.index_mut(p))
        } else {
            None
        }
    }

    /// Mutably borrow the last element.
    #[doc(alias = "last_mut")]
    #[inline]
    pub fn back_mut(&mut self) -> Option<&mut Element> {
        if let Some(p) = self.back_index() {
            Some(self.pool.index_mut(p))
        } else {
            None
        }
    }

    /// Reborrow `self` with [`Self::head`] replaced.
    #[inline]
    fn with_head<'head_>(
        &mut self,
        head: &'head_ mut Head<Index>,
    ) -> ListAccessorMut<'head_, '_, Index, Pool, &MapLink> {
        ListAccessorMut {
            head,
            pool: self.pool,
            map_link: &self.map_link,
        }
    }

    /// Unlink all elements.
    ///
    /// This is a linear time operation.
    /// If you do not reuse the elements (and therefore it is safe to leave
    /// their `Option<Link>` fields set), consider simply dropping `self`
    /// instead.
    pub fn clear(&mut self) {
        let Some(mut cur) = self.head.first.take() else {
            return;
        };
        loop {
            let Some(link) = (self.map_link)(self.pool.index_mut(cur)).take() else {
                return;
            };
            cur = link.next;
        }
    }

    /// Insert `item` before the position `p` (if `at` is `Some(p)`) or to the
    /// the list's back (if `at` is `None`).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use intrex::list;
    ///
    /// let mut nodes: Vec<Option<list::Link>> = vec![None; 5];
    ///
    /// // `head` = `[0, 1, 2]`
    /// let mut head = list::Head::default();
    /// let mut accessor = head.accessor_mut(&mut nodes, |n| n);
    /// accessor.extend([0, 1, 2]);
    ///
    /// // Insert `3` before `1`
    /// accessor.insert(3, Some(1));
    ///
    /// assert_eq!(
    ///     head.accessor(&nodes, |n| n).indices().collect::<Vec<_>>(),
    ///     vec![0, 3, 1, 2],
    /// )
    /// ```
    pub fn insert(&mut self, item: Index, at: Option<Index>) {
        {
            debug_assert!(
                (self.map_link)(self.pool.index_mut(item.clone())).is_none(),
                "item is already linked"
            );
        }

        if let Some(first) = self.head.first.clone() {
            let (next, update_first) = if let Some(at) = at {
                let update_first = at == first;
                (at, update_first)
            } else {
                (first, false)
            };

            let prev = link!(self, next.clone()).prev.clone();
            link!(self, prev.clone()).next = item.clone();
            link!(self, next.clone()).prev = item.clone();
            *(self.map_link)(self.pool.index_mut(item.clone())) = Some(Link { prev, next });

            if update_first {
                self.head.first = Some(item);
            }
        } else {
            debug_assert!(at.is_none());

            let link = (self.map_link)(self.pool.index_mut(item.clone()));
            self.head.first = Some(item.clone());
            *link = Some(Link {
                prev: item.clone(),
                next: item,
            });
        }
    }

    /// Insert all elements from `other` before the position `at` (if `at` is
    /// `Some(p)`) or to the list's back (if `at` is `None`).
    ///
    /// `other` will be empty after this operation.
    ///
    /// This is a constant-time operation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use intrex::list;
    ///
    /// let mut nodes: Vec<Option<list::Link>> = vec![None; 5];
    ///
    /// // `head` = `[0, 1, 2]`
    /// let mut head = list::Head::default();
    /// head.accessor_mut(&mut nodes, |n| n).extend([0, 1, 2]);
    ///
    /// // `other_head` = `[3, 4]`
    /// let mut other_head = list::Head::default();
    /// other_head.accessor_mut(&mut nodes, |n| n).extend([3, 4]);
    ///
    /// // Insert `other_head` before `1` in `head`
    /// let mut accessor = head.accessor_mut(&mut nodes, |n| n);
    /// accessor.insert_list(&mut other_head, Some(1));
    ///
    /// assert_eq!(
    ///     head.accessor(&nodes, |n| n).indices().collect::<Vec<_>>(),
    ///     vec![0, 3, 4, 1, 2],
    /// );
    /// assert!(other_head.is_empty());
    /// ```
    pub fn insert_list(&mut self, other: &mut Head<Index>, at: Option<Index>) {
        let mut other = core::mem::take(other);

        let Some(other_first) = other.first.clone() else {
            return;
        };

        let Some(first) = self.head.first.clone() else {
            debug_assert!(at.is_none());
            self.head.first = Some(other_first);
            return;
        };

        let other_last = self.with_head(&mut other).back_index().unwrap();

        let (next, update_first) = if let Some(at) = at {
            let update_first = at == first;
            (at, update_first)
        } else {
            (first, false)
        };

        let prev = link!(self, next.clone()).prev.clone();

        link!(self, prev.clone()).next = other_first.clone();
        link!(self, next.clone()).prev = other_last.clone();
        link!(self, other_first.clone()).prev = prev;
        link!(self, other_last.clone()).next = next;

        if update_first {
            self.head.first = Some(other_first);
        }
    }

    /// Append an element at index `item` to the back of the list.
    pub fn push_back(&mut self, item: Index) {
        self.insert(item, None);
    }

    /// Prepend an element at index `item` to the front of the list.
    pub fn push_front(&mut self, item: Index) {
        let at = self.front_index();
        self.insert(item, at);
    }

    /// Move all elements of `other` to the back of `self`, leaving `other` empty.
    ///
    /// This is a constant-time operation.
    #[inline]
    pub fn append(&mut self, other: &mut Head<Index>) {
        self.insert_list(other, None);
    }

    /// Move all elements of `other` to the front of `self`, leaving `other` empty.
    ///
    /// This is a constant-time operation.
    #[inline]
    pub fn prepend(&mut self, other: &mut Head<Index>) {
        let at = self.front_index();
        self.insert_list(other, at);
    }

    /// Remove `item` from the list. Returns `item`.
    pub fn remove(&mut self, item: Index) -> Index {
        {
            debug_assert!(
                (self.map_link)(self.pool.index_mut(item.clone())).is_some(),
                "item is not linked"
            );
        }

        let link: Link<Index> = {
            let link_ref = (self.map_link)(self.pool.index_mut(item.clone()));
            if self.head.first.as_ref() == Some(&item) {
                let next = link_ref.as_ref().unwrap().next.clone();
                if next == item {
                    // The list just became empty
                    self.head.first = None;
                    *link_ref = None;
                    return item;
                }

                // Move the head pointer
                self.head.first = Some(next);
            }

            link_ref.clone().unwrap()
        };

        link!(self, link.prev.clone()).next = link.next.clone();
        link!(self, link.next).prev = link.prev;
        *(self.map_link)(self.pool.index_mut(item.clone())) = None;

        item
    }

    /// Swap the elements in a given range with another list.
    ///
    /// This is a constant-time operation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use intrex::list;
    ///
    /// let mut nodes: Vec<Option<list::Link>> = vec![None; 5];
    ///
    /// // `head` = `[0, 1, 2]`
    /// let mut head = list::Head::default();
    /// head.accessor_mut(&mut nodes, |n| n).extend([0, 1, 2]);
    ///
    /// // `other_head` = `[3, 4]`
    /// let mut other_head = list::Head::default();
    /// other_head.accessor_mut(&mut nodes, |n| n).extend([3, 4]);
    ///
    /// // Swap `[1, 2]` in `head` with `other_head`
    /// head.accessor_mut(&mut nodes, |n| n)
    ///     .swap_range(Some(1).., &mut other_head);
    ///
    /// assert_eq!(
    ///     head.accessor(&nodes, |n| n).indices().collect::<Vec<_>>(),
    ///     vec![0, 3, 4],
    /// );
    /// assert_eq!(
    ///     other_head.accessor(&nodes, |n| n).indices().collect::<Vec<_>>(),
    ///     vec![1, 2],
    /// );
    /// ```
    pub fn swap_range(
        &mut self,
        range: impl ops::RangeBounds<Option<Index>>,
        other: &mut Head<Index>,
    ) {
        let (range, range_next) =
            resolve_range(range, |i| link!(self, i).clone(), self.head.first.clone());

        let Some(range) = range else {
            // If `range` is empty, delegate to `insert_list`.
            return self.insert_list(other, range_next.clone());
        };

        self.swap_range_inner(range, range_next, other)
    }

    /// An internal method of [`Self::swap_range`]. Swaps
    /// `start_inner..=end_inner` (= `start_inner..range_next`) with `*other`.
    /// Returns `end-outer`.
    fn swap_range_inner(
        &mut self,
        [start_inner, end_inner]: [Index; 2],
        end_outer: Option<Index>,
        other: &mut Head<Index>,
    ) {
        // `self` is not empty.
        let self_start = self.front_index().unwrap();

        // Both-exclusive range with wrap around
        let start_outer_wrap = link!(self, start_inner.clone()).prev.clone();
        let end_outer_wrap = link!(self, end_inner.clone()).next.clone();

        // If `range` covers entire `self`, swap the `Head`s.
        if end_outer_wrap == start_inner {
            assert!(start_inner == self_start);
            swap(self.head, other);
            return;
        }

        let mut other_acc = self.with_head(other);
        if let (Some(other_first), Some(other_last)) =
            (other_acc.front_index(), other_acc.back_index())
        {
            // If `other` is not empty...

            // Link `range`'s outer elements to `other`'s elements
            link!(self, start_outer_wrap.clone()).next = other_first.clone();
            link!(self, end_outer_wrap.clone()).prev = other_last.clone();
            link!(self, other_first.clone()).prev = start_outer_wrap.clone();
            link!(self, other_last.clone()).next = end_outer_wrap.clone();

            if start_inner == self_start {
                self.head.first = Some(other_first);
            }
        } else {
            link!(self, start_outer_wrap.clone()).next = end_outer_wrap.clone();
            link!(self, end_outer_wrap.clone()).prev = start_outer_wrap.clone();

            if start_inner == self_start {
                debug_assert!(end_outer.is_some());
                self.head.first = end_outer.clone();
            }
        }

        // Update `other` to store `range`'s inner elements
        link!(self, start_inner.clone()).prev = end_inner.clone();
        link!(self, end_inner.clone()).next = start_inner.clone();

        *other = Head {
            first: Some(start_inner),
        };
    }

    /// Replace the elements in a given range with another list, returning a
    /// new list containing the replaced elements.
    ///
    /// This is a constant-time operation.
    #[must_use = "this method returns a new list"]
    #[inline]
    pub fn replace_range(
        &mut self,
        range: impl ops::RangeBounds<Option<Index>>,
        mut other: Head<Index>,
    ) -> Head<Index> {
        self.swap_range(range, &mut other);
        other
    }

    /// Remove the elements in a given range, returning a new list containing
    /// the removed elements.
    ///
    /// This is a constant-time operation.
    #[must_use = "this method returns a new list"]
    #[doc(alias = "split_off")]
    #[inline]
    pub fn take_range(&mut self, range: impl ops::RangeBounds<Option<Index>>) -> Head<Index> {
        self.replace_range(range, Head::default())
    }

    /// Remove and return the last element's index.
    pub fn pop_back(&mut self) -> Option<Index> {
        self.back_index().map(|item| self.remove(item))
    }

    /// Remove and return the first element's index.
    pub fn pop_front(&mut self) -> Option<Index> {
        self.front_index().map(|item| self.remove(item))
    }

    /// Find the next element of the element at index `i`.
    #[inline]
    pub fn next_index(&mut self, i: Index) -> Option<Index> {
        Some(link!(self, i).next.clone()).filter(|i| *i != *self.head.first.as_ref().unwrap())
    }

    /// Find the previous element of the element at index `i`.
    #[inline]
    pub fn prev_index(&mut self, i: Index) -> Option<Index> {
        (i != *self.head.first.as_ref().unwrap()).then(|| link!(self, i).prev.clone())
    }

    /// Call the specified closure for every element, passing a mutable
    /// reference for each of them.
    #[inline]
    pub fn for_each_mut<B>(
        &mut self,
        mut f: impl FnMut(Index, &mut Element) -> ops::ControlFlow<B>,
    ) -> ops::ControlFlow<B> {
        let Some(first) = self.head.first.clone() else {
            return ops::ControlFlow::Continue(());
        };
        let mut current = first.clone();
        loop {
            let next = link!(self, current.clone()).next.clone();
            f(current.clone(), self.pool.index_mut(current))?;
            if next == first {
                break;
            } else {
                current = next;
            }
        }
        ops::ControlFlow::Continue(())
    }

    /// Call the specified closure for every element in a given range, passing
    /// a mutable reference for each of them.
    #[inline]
    pub fn for_each_in_range_mut<B>(
        &mut self,
        range: impl ops::RangeBounds<Option<Index>>,
        mut f: impl FnMut(Index, &mut Element) -> ops::ControlFlow<B>,
    ) -> ops::ControlFlow<B> {
        let (Some([first, last]), _) =
            resolve_range(range, |i| link!(self, i).clone(), self.head.first.clone())
        else {
            return ops::ControlFlow::Continue(());
        };
        let mut current = first;
        loop {
            let next = (current != last).then(|| link!(self, current.clone()).next.clone());
            f(current.clone(), self.pool.index_mut(current))?;
            let Some(next) = next else { break };
            current = next;
        }
        ops::ControlFlow::Continue(())
    }

    /// Rotate the list in-place such that the first element move to the back
    /// while the last `len - 1` elements move to the front.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use intrex::list;
    ///
    /// let mut nodes: Vec<Option<list::Link>> = vec![None; 5];
    ///
    /// // `head` = `[0, 1, 2]`
    /// let mut head = list::Head::default();
    /// let mut accessor = head.accessor_mut(&mut nodes, |n| n);
    /// accessor.extend([0, 1, 2]);
    ///
    /// accessor.rotate_left_once();
    ///
    /// assert_eq!(
    ///     head.accessor(&nodes, |n| n).indices().collect::<Vec<_>>(),
    ///     vec![1, 2, 0],
    /// );
    /// ```
    pub fn rotate_left_once(&mut self) {
        let Some(front_index) = self.front_index() else {
            return;
        };
        self.head.first = self.next_index(front_index);
    }

    /// Rotate the list in-place such that the last element move to the front
    /// while the first `len - 1` elements move to the back.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use intrex::list;
    ///
    /// let mut nodes: Vec<Option<list::Link>> = vec![None; 5];
    ///
    /// // `head` = `[0, 1, 2]`
    /// let mut head = list::Head::default();
    /// let mut accessor = head.accessor_mut(&mut nodes, |n| n);
    /// accessor.extend([0, 1, 2]);
    ///
    /// accessor.rotate_right_once();
    ///
    /// assert_eq!(
    ///     head.accessor(&nodes, |n| n).indices().collect::<Vec<_>>(),
    ///     vec![2, 0, 1],
    /// );
    /// ```
    pub fn rotate_right_once(&mut self) {
        self.head.first = self.back_index();
    }

    /// Sort the list in ascending order, preserving the initial order of
    /// equal elements.
    ///
    /// This method uses [`sort_slist::sort`] for sorting.
    pub fn sort(&mut self)
    where
        Element: Ord,
    {
        self.sort_inner(|pool, lhs, rhs| pool.index(lhs) < pool.index(rhs));
    }

    /// Sort the list in ascending order with a key extraction function,
    /// preserving the initial order of equal elements.
    ///
    /// This method uses [`sort_slist::sort`] for sorting.
    pub fn sort_by_key<F, K>(&mut self, mut f: F)
    where
        F: FnMut(&mut Pool, Index) -> K,
        K: Ord,
    {
        self.sort_inner(|pool, lhs, rhs| f(pool, lhs) < f(pool, rhs));
    }

    /// Sort the list in ascending order with a comparison function,
    /// preserving the initial order of equal elements.
    ///
    /// This method uses [`sort_slist::sort`] for sorting.
    pub fn sort_by<F, K>(&mut self, mut f: F)
    where
        F: FnMut(&mut Pool, Index, Index) -> Ordering,
    {
        self.sort_inner(|pool, lhs, rhs| f(pool, lhs, rhs) == Ordering::Less);
    }

    fn sort_inner(&mut self, less_than: impl FnMut(&mut Pool, Index, Index) -> bool) {
        struct Accessor<'a, Pool: ?Sized, MapLink, LessThan> {
            pool: &'a mut Pool,
            map_link: &'a MapLink,
            less_than: LessThan,
        }

        impl<Pool, MapLink, LessThan, Element, Index> sort_slist::SortAccessor<Index>
            for Accessor<'_, Pool, MapLink, LessThan>
        where
            Pool: ?Sized + PoolMut<Index, Element = Element>,
            MapLink: Fn(&mut Element) -> &mut Option<Link<Index>>,
            Index: PartialEq + Clone,
            LessThan: FnMut(&mut Pool, Index, Index) -> bool,
        {
            #[inline]
            fn next(&mut self, index: Index) -> Option<Index> {
                Some(
                    (self.map_link)(self.pool.index_mut(index))
                        .as_mut()?
                        .next
                        .clone(),
                )
            }

            #[inline]
            fn set_next(&mut self, index: Index, next: Option<Index>) {
                *(self.map_link)(self.pool.index_mut(index)) = next.map(|i| Link {
                    prev: i.clone(),
                    next: i,
                });
            }

            #[inline]
            fn lt(&mut self, lhs: Index, rhs: Index) -> bool {
                (self.less_than)(self.pool, lhs, rhs)
            }
        }

        // Turn it into a non-circular list
        let (Some(front_index), Some(back_index)) = (self.front_index(), self.back_index()) else {
            // Empty
            return;
        };
        *(self.map_link)(self.pool.index_mut(back_index)) = None;

        // Sort it
        let front_index = sort_slist::sort(
            &mut Accessor {
                pool: self.pool,
                map_link: &self.map_link,
                less_than,
            },
            Some(front_index),
        )
        .unwrap();

        // Restore double links
        match (self.map_link)(self.pool.index_mut(front_index.clone())) {
            Some(front_link) => {
                // Fix links for all elements but the first
                let mut cur = front_index.clone();
                let mut next = front_link.next.clone();
                loop {
                    match (self.map_link)(self.pool.index_mut(next.clone())) {
                        Some(next_link) => {
                            next_link.prev = cur;
                            cur = next;
                            next = next_link.next.clone();
                        }
                        next_link @ None => {
                            // `next` is the last element
                            *next_link = Some(Link {
                                prev: cur,
                                next: front_index.clone(),
                            });
                            break;
                        }
                    }
                }

                // Fix the link for the first element
                link!(self, front_index.clone()).prev = next;
            }
            front_link @ None => {
                // Fix the link for the only element
                *front_link = Some(Link {
                    prev: front_index.clone(),
                    next: front_index.clone(),
                })
            }
        }

        self.head.first = Some(front_index);
    }
}

impl<'head, 'pool, Index, Pool, MapLink, Element> Extend<Index>
    for ListAccessorMut<'head, 'pool, Index, Pool, MapLink>
where
    Pool: ?Sized + PoolMut<Index, Element = Element>,
    MapLink: Fn(&mut Element) -> &mut Option<Link<Index>>,
    Index: PartialEq + Clone,
{
    fn extend<I: IntoIterator<Item = Index>>(&mut self, iter: I) {
        for item in iter {
            self.push_back(item);
        }
    }
}

#[cfg(test)]
mod tests {
    use proptest::prelude::*;
    use std::{println, vec, vec::Vec};

    use super::*;
    use crate::list::tests::push;

    #[test]
    fn basic_mut() {
        let mut pool = Vec::new();
        let mut head = Head::new();
        let mut accessor = head.accessor_mut(&mut pool, |&mut (_, ref mut link)| link);

        let ptr1 = push(accessor.pool_mut(), (1, None));
        accessor.push_back(ptr1);

        let ptr2 = push(accessor.pool_mut(), (2, None));
        accessor.push_back(ptr2);

        let ptr3 = push(accessor.pool_mut(), (3, None));
        accessor.push_front(ptr3);

        println!("{:?}", (accessor.pool(), accessor.head()));

        assert!(!accessor.is_empty());
        assert_eq!(accessor.front_index(), Some(ptr3));
        assert_eq!(accessor.back_index(), Some(ptr2));
        assert_eq!(accessor.front_mut().unwrap().0, 3);
        assert_eq!(accessor.back_mut().unwrap().0, 2);

        let mut items = Vec::new();
        _ = accessor.for_each_mut(|_, &mut (x, _)| {
            items.push(x);
            ops::ControlFlow::Continue::<()>(())
        });
        assert_eq!(items, vec![3, 1, 2]);

        accessor.remove(ptr1);
        accessor.remove(ptr2);
        accessor.remove(ptr3);

        assert!(accessor.is_empty());
    }

    #[proptest::property_test]
    fn pt_insert_list(elems1: Vec<u8>, elems2: Vec<u8>, insert_at: prop::sample::Index) {
        let mut pool: Vec<(u8, Option<Link>)> = Vec::new();
        let mut head1 = Head::new();
        let mut head2 = Head::new();

        for &value in &elems1 {
            let ptr = push(&mut pool, (value, None));
            head1
                .accessor_mut(&mut pool, |&mut (_, ref mut link)| link)
                .push_back(ptr);
        }

        for &value in &elems2 {
            let ptr = push(&mut pool, (value, None));
            head2
                .accessor_mut(&mut pool, |&mut (_, ref mut link)| link)
                .push_back(ptr);
        }

        let at_pos = insert_at.index(elems1.len() + 1);
        let at = head1
            .accessor(&pool, |(_, link)| link)
            .indices()
            .nth(at_pos);

        head1
            .accessor_mut(&mut pool, |&mut (_, ref mut link)| link)
            .insert_list(&mut head2, at);
        assert!(head2.is_empty());

        head1
            .accessor(&pool, |(_, link)| link)
            .validate()
            .expect("validate");

        let mut expected = Vec::new();
        expected.extend(&elems1[..at_pos]);
        expected.extend(&elems2);
        expected.extend(&elems1[at_pos..]);

        let got: Vec<u8> = head1
            .accessor(&pool, |(_, link)| link)
            .values()
            .map(|&(v, _)| v)
            .collect();
        assert_eq!(got, expected);
    }

    #[proptest::property_test]
    fn pt_swap_range(elems1: Vec<u8>, elems2: Vec<u8>, [start, end]: [prop::sample::Index; 2]) {
        let mut pool: Vec<(u8, Option<Link>)> = Vec::new();
        let mut head1 = Head::new();
        let mut head2 = Head::new();

        for &value in &elems1 {
            let ptr = push(&mut pool, (value, None));
            head1
                .accessor_mut(&mut pool, |&mut (_, ref mut link)| link)
                .push_back(ptr);
        }

        for &value in &elems2 {
            let ptr = push(&mut pool, (value, None));
            head2
                .accessor_mut(&mut pool, |&mut (_, ref mut link)| link)
                .push_back(ptr);
        }

        let start = start.index(elems1.len() + 1);
        let end = end.index(elems1.len() + 1 - start) + start;

        let [start_ind, end_ind] = [start, end].map(|i| (i < elems1.len()).then_some(i));

        head1
            .accessor_mut(&mut pool, |&mut (_, ref mut link)| link)
            .swap_range(start_ind..end_ind, &mut head2);

        head1
            .accessor(&pool, |(_, link)| link)
            .validate()
            .expect("validate head1");
        head2
            .accessor(&pool, |(_, link)| link)
            .validate()
            .expect("validate head2");

        let mut expected1: Vec<u8> = elems1.clone();
        let expected2: Vec<u8> = expected1
            .splice(start..end, elems2.iter().copied())
            .collect();

        let got1: Vec<u8> = head1
            .accessor(&pool, |(_, link)| link)
            .values()
            .map(|&(v, _)| v)
            .collect();
        let got2: Vec<u8> = head2
            .accessor(&pool, |(_, link)| link)
            .values()
            .map(|&(v, _)| v)
            .collect();

        assert_eq!(got1, expected1);
        assert_eq!(got2, expected2);
    }

    #[proptest::property_test]
    fn pt_sort(elems: Vec<u8>) {
        let mut pool: Vec<(u8, Option<Link>)> = elems.iter().map(|&value| (value, None)).collect();
        let mut head = Head::new();

        for i in 0..elems.len() {
            head.accessor_mut(&mut pool, |&mut (_, ref mut link)| link)
                .push_back(i);
        }

        head.accessor(&pool, |(_, link)| link)
            .validate()
            .expect("validate");

        // Sort it
        head.accessor_mut(&mut pool, |&mut (_, ref mut link)| link)
            .sort_by_key(|pool, index| pool[index].0);

        // Validate the result
        head.accessor(&pool, |(_, link)| link)
            .validate()
            .expect("post-sort validate");

        let mut elems_expected = elems;
        elems_expected.sort_unstable();

        let elems_got: Vec<u8> = head
            .accessor(&pool, |(_, link)| link)
            .values()
            .map(|&(value, _)| value)
            .collect();

        assert_eq!(elems_got, elems_expected);
    }
}