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
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
// Copyright of the original code is the following.
// --------
// Summary: lists interfaces
// Description: this module implement the list support used in
// various place in the library.
//
// Copy: See Copyright for the status of this software.
//
// Author: Gary Pennington <Gary.Pennington@uk.sun.com>
// --------
// list.c: lists handling implementation
//
// Copyright (C) 2000 Gary Pennington and Daniel Veillard.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE AUTHORS AND
// CONTRIBUTORS ACCEPT NO RESPONSIBILITY IN ANY CONCEIVABLE MANNER.
//
// Author: Gary.Pennington@uk.sun.com
use std::{
cmp::Ordering,
ops::{Deref, DerefMut},
ptr::NonNull,
rc::Rc,
};
// pub use libxml_api::*;
pub struct XmlLink<T> {
prev: Option<XmlLinkRef<T>>,
next: Option<XmlLinkRef<T>>,
data: T,
}
impl<T> XmlLink<T> {
pub fn get(&self) -> &T {
&self.data
}
}
#[derive(Debug)]
pub(crate) struct XmlLinkRef<T>(NonNull<XmlLink<T>>);
impl<T> XmlLinkRef<T> {
fn new(data: T) -> Option<Self> {
let boxed = Box::new(XmlLink {
prev: None,
next: None,
data,
});
let leaked = Box::leak(boxed);
NonNull::new(leaked).map(Self)
}
// fn from_raw(ptr: *mut XmlLink<T>) -> Option<Self> {
// NonNull::new(ptr).map(Self)
// }
fn into_inner(self) -> XmlLink<T> {
unsafe { *Box::from_raw(self.0.as_ptr()) }
}
}
impl<T> Clone for XmlLinkRef<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for XmlLinkRef<T> {}
impl<T> Deref for XmlLinkRef<T> {
type Target = XmlLink<T>;
fn deref(&self) -> &Self::Target {
unsafe { self.0.as_ref() }
}
}
impl<T> DerefMut for XmlLinkRef<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { self.0.as_mut() }
}
}
type Deallocator<T> = Rc<dyn Fn(T)>;
type Comparator<T> = Rc<dyn Fn(&T, &T) -> Ordering>;
pub struct XmlList<T> {
head: Option<XmlLinkRef<T>>,
tail: Option<XmlLinkRef<T>>,
deallocator: Deallocator<T>,
comparator: Comparator<T>,
}
impl<T> XmlList<T> {
/// Clear all elements.
///
/// # Examples
/// ```rust
/// use exml::list::XmlList;
///
/// let mut list = XmlList::without_comparator(None);
/// list.insert_lower_bound(1u32);
/// list.insert_lower_bound(2u32);
///
/// assert!(!list.is_empty());
///
/// list.clear();
///
/// assert!(list.is_empty());
/// ```
pub fn clear(&mut self) {
let mut link = self.head.take();
while let Some(now) = link {
link = now.next;
let now = now.into_inner();
(self.deallocator)(now.data);
}
self.tail = None;
}
}
impl<T: Ord + 'static> XmlList<T> {
/// Create new `XmlList`.
///
/// If `deallocator` is `None`, `drop` is used by default.
/// If `comparator` is `None`, `T::cmp` is used by default.
pub fn without_comparator(deallocator: Option<Deallocator<T>>) -> Self {
let mut default = Self::default();
if let Some(deallocator) = deallocator {
default.deallocator = deallocator;
}
default
}
}
impl<T: 'static> XmlList<T> {
/// Create new `XmlList`.
///
/// If `deallocator` is `None`, `drop` is used by default.
pub fn new(deallocator: Option<Deallocator<T>>, comparator: Comparator<T>) -> Self {
Self {
head: None,
tail: None,
deallocator: deallocator.unwrap_or(Rc::new(drop)),
comparator,
}
}
/// Return a `link` satisfies `!self.comparator(&link.data, &data).is_lt()`.
///
/// If all elements satisfies `self.comparator(&link.data, &data).is_lt()`, return `None`.
///
/// # Constraint
/// - `self` must be sorted.
fn lower_search(&self, data: &T) -> Option<XmlLinkRef<T>> {
let mut link = self.head;
while let Some(now) = link.filter(|link| (self.comparator)(&link.data, data).is_lt()) {
link = now.next;
}
link
}
/// Return the first `link` satisfies `self.comparator(&link.data, &data).is_eq()`.
///
/// If such element is not found, return `None`.
///
/// # Constraint
/// - `self` must be sorted.
fn link_search(&self, data: &T) -> Option<XmlLinkRef<T>> {
let link = self.lower_search(data)?;
(self.comparator)(&link.data, data).is_eq().then_some(link)
}
fn link_search_by(&self, mut pred: impl FnMut(&T) -> bool) -> Option<XmlLinkRef<T>> {
let mut link = self.head;
while let Some(now) = link {
if pred(&now.data) {
return Some(now);
}
link = now.next;
}
None
}
/// Return the first data that `self.comparator` determines to be equal to `data`.
///
/// If such element is not found, return `None`.
///
/// # Constraint
/// - `self` must be sorted.
///
/// # Examples
/// ```rust
/// use std::rc::Rc;
///
/// use exml::list::XmlList;
///
/// // ignore second element when comparing
/// let comparator = |l: &(u32, u32), r: &(u32, u32)| l.0.cmp(&r.0);
/// let mut list = XmlList::new(None, Rc::new(comparator));
/// list.push_last((0u32, 0u32));
/// list.push_last((1, 0));
/// list.push_last((1, 2));
/// list.push_last((3, 0));
///
/// assert_eq!(list.search(&(0, 0)), Some(&(0, 0)));
/// // `(1, 0)` is equal to `(1, 0)` and `(1, 2)` bacause second element is ignored.
/// // Of these, the more forward `(1, 0)` is chosen.
/// assert_eq!(list.search(&(1, 0)), Some(&(1, 0)));
/// assert_eq!(list.search(&(2, 0)), None);
/// assert_eq!(list.search(&(3, 0)), Some(&(3, 0)));
/// assert_eq!(list.search(&(4, 0)), None);
/// ```
pub fn search(&self, data: &T) -> Option<&T> {
self.link_search(data).map(|link| unsafe {
// we cannot use `&link.data` because of lifetime constraint.
&link.0.as_ref().data
})
}
/// Return a `link` satisfies `!self.comparator(&link.data, &data).is_gt()`.
///
/// If all elements satisfies `self.comparator(&link.data, &data).is_gt()`, return `None`.
///
/// # Constraint
/// - `self` must be sorted.
fn higher_search(&self, data: &T) -> Option<XmlLinkRef<T>> {
let mut link = self.tail;
while let Some(now) = link.filter(|link| (self.comparator)(&link.data, data).is_gt()) {
link = now.prev;
}
link
}
/// Return the last `link` satisfies `self.comparator(&link.data, &data).is_eq()`.
///
/// If such element is not found, return `None`.
///
/// # Constraint
/// - `self` must be sorted.
fn link_reverse_search(&self, data: &T) -> Option<XmlLinkRef<T>> {
let link = self.higher_search(data)?;
(self.comparator)(&link.data, data).is_eq().then_some(link)
}
/// Return the last data that `self.comparator` determines to be equal to `data`.
///
/// If such element is not found, return `None`.
///
/// # Constraint
/// - `self` must be sorted.
///
/// # Examples
/// ```rust
/// use std::rc::Rc;
///
/// use exml::list::XmlList;
///
/// // ignore second element when comparing
/// let comparator = |l: &(u32, u32), r: &(u32, u32)| l.0.cmp(&r.0);
/// let mut list = XmlList::new(None, Rc::new(comparator));
/// list.push_last((0u32, 0u32));
/// list.push_last((1, 0));
/// list.push_last((1, 2));
/// list.push_last((3, 0));
///
/// assert_eq!(list.reverse_search(&(0, 0)), Some(&(0, 0)));
/// // `(1, 0)` is equal to `(1, 0)` and `(1, 2)` bacause second element is ignored.
/// // Of these, the more backward `(1, 2)` is chosen.
/// assert_eq!(list.reverse_search(&(1, 0)), Some(&(1, 2)));
/// assert_eq!(list.reverse_search(&(2, 0)), None);
/// assert_eq!(list.reverse_search(&(3, 0)), Some(&(3, 0)));
/// assert_eq!(list.reverse_search(&(4, 0)), None);
/// ```
pub fn reverse_search(&self, data: &T) -> Option<&T> {
self.link_reverse_search(data).map(|link| unsafe {
// we cannot use `&link.data` because of lifetime constraint.
&link.0.as_ref().data
})
}
/// Insert `data` in a position where the list can remain sorted.
///
/// If there are multiple such positions, insert at the beginning of them.
///
/// # Constraint
/// - `self` must be sorted.
///
/// # Examples
/// ```rust
/// use std::rc::Rc;
///
/// use exml::list::XmlList;
///
/// // ignore second element when comparing
/// let comparator = |l: &(u32, u32), r: &(u32, u32)| l.0.cmp(&r.0);
/// let mut list = XmlList::new(None, Rc::new(comparator));
/// list.insert_lower_bound((0u32, 0u32));
/// list.insert_lower_bound((1, 0));
/// list.insert_lower_bound((1, 2));
/// list.insert_lower_bound((3, 0));
///
/// // `(1, 0)` is equal to `(1, 2)` because second element is ignored.
/// // `insert_lower_bound` inserted `(1, 2)` before `(1, 0)`.
/// assert_eq!(list.search(&(1, 0)), Some(&(1, 2)));
/// ```
pub fn insert_lower_bound(&mut self, data: T) {
let bound = self.lower_search(&data);
let mut new = XmlLinkRef::new(data).expect("Failed to generate new XmlLinkRef");
if let Some(mut bound) = bound {
// (bound.prev ->) new -> bound
new.prev = bound.prev;
new.next = Some(bound);
if let Some(mut prev) = bound.prev {
prev.next = Some(new);
} else {
// If `bound.prev` is `None`, `bound` is the head of the list
self.head = Some(new);
}
bound.prev = Some(new);
} else {
// If `bound` is `None`, `new` is the tail of the list
if let Some(mut tail) = self.tail {
// old-tail -> new
tail.next = Some(new);
new.prev = Some(tail);
} else {
// If `self.tail` is `None`, the list is empty.
self.head = Some(new);
}
self.tail = Some(new);
}
}
/// Insert `data` in a position where the list can remain sorted.
///
/// If there are multiple such positions, insert at the end of them.
///
/// # Constraint
/// - `self` must be sorted.
///
/// # Examples
/// ```rust
/// use std::rc::Rc;
///
/// use exml::list::XmlList;
///
/// // ignore second element when comparing
/// let comparator = |l: &(u32, u32), r: &(u32, u32)| l.0.cmp(&r.0);
/// let mut list = XmlList::new(None, Rc::new(comparator));
/// list.insert_upper_bound((0u32, 0u32));
/// list.insert_upper_bound((1, 0));
/// list.insert_upper_bound((1, 2));
/// list.insert_upper_bound((3, 0));
///
/// // `(1, 0)` is equal to `(1, 2)` because second element is ignored.
/// // `insert_lower_bound` inserted `(1, 2)` after `(1, 0)`.
/// assert_eq!(list.search(&(1, 0)), Some(&(1, 0)));
/// ```
pub fn insert_upper_bound(&mut self, data: T) {
let bound = self.higher_search(&data);
let mut new = XmlLinkRef::new(data).expect("Failed to generate new XmlLinkRef");
if let Some(mut bound) = bound {
// bound -> new (-> bound.next)
new.prev = Some(bound);
new.next = bound.next;
if let Some(mut next) = bound.next {
next.prev = Some(new);
} else {
// If `bound.next` is `None`, `bound` is the tail of the list
self.tail = Some(new);
}
bound.next = Some(new);
} else {
// If `bound` is `None`, `new` is the head of the list
if let Some(mut head) = self.head {
// new -> old-head
head.prev = Some(new);
new.next = Some(head);
} else {
// If `self.head` is `None`, the list is empty
self.tail = Some(new);
}
self.head = Some(new);
}
}
fn remove_link(&mut self, link: XmlLinkRef<T>) -> T {
if let Some(mut prev) = link.prev {
prev.next = link.next;
} else {
self.head = link.next;
}
if let Some(mut next) = link.next {
next.prev = link.prev;
} else {
self.tail = link.prev;
}
let XmlLink { data, .. } = link.into_inner();
data
}
/// Remove the first element determined to be equal with `data` by `self.comparator` of the list
/// and return its data.
///
/// # Constraint
/// - `self` must be sorted.
///
/// # Examples
/// ```rust
/// use std::rc::Rc;
///
/// use exml::list::XmlList;
///
/// // ignore second element when comparing
/// let comparator = |l: &(u32, u32), r: &(u32, u32)| l.0.cmp(&r.0);
/// let mut list = XmlList::new(None, Rc::new(comparator));
/// list.push_last((0u32, 0u32));
/// list.push_last((1, 0));
/// list.push_last((1, 2));
/// list.push_last((3, 0));
///
/// assert_eq!(list.search(&(1, 0)), Some(&(1, 0)));
///
/// assert_eq!(list.remove_first(&(1, 0)), Some((1, 0)));
///
/// assert_eq!(list.search(&(1, 0)), Some(&(1, 2)));
/// ```
pub fn remove_first(&mut self, data: &T) -> Option<T> {
let link = self.link_search(data)?;
Some(self.remove_link(link))
}
/// Remove the first element determined that `pred` is `true` of the list
/// and return its data.
pub fn remove_first_by(&mut self, pred: impl FnMut(&T) -> bool) -> Option<T> {
let link = self.link_search_by(pred)?;
Some(self.remove_link(link))
}
/// Remove the last element determined to be equal with `data` by `self.comparator` of the list
/// and return its data.
///
/// # Constraint
/// - `self` must be sorted.
///
/// # Examples
/// ```rust
/// use std::rc::Rc;
///
/// use exml::list::XmlList;
///
/// // ignore second element when comparing
/// let comparator = |l: &(u32, u32), r: &(u32, u32)| l.0.cmp(&r.0);
/// let mut list = XmlList::new(None, Rc::new(comparator));
/// list.push_last((0u32, 0u32));
/// list.push_last((1, 0));
/// list.push_last((1, 2));
/// list.push_last((3, 0));
///
/// assert_eq!(list.reverse_search(&(1, 0)), Some(&(1, 2)));
///
/// assert_eq!(list.remove_last(&(1, 0)), Some((1, 2)));
///
/// assert_eq!(list.reverse_search(&(1, 0)), Some(&(1, 0)));
/// ```
pub fn remove_last(&mut self, data: &T) -> Option<T> {
let link = self.link_reverse_search(data)?;
Some(self.remove_link(link))
}
/// Remove all elements determined to be equal with `data` by `self.comparator` of the list
/// and return its data.
///
/// # Constraint
/// - `self` must be sorted.
///
/// # Examples
/// ```rust
/// use std::rc::Rc;
///
/// use exml::list::XmlList;
///
/// // ignore second element when comparing
/// let comparator = |l: &(u32, u32), r: &(u32, u32)| l.0.cmp(&r.0);
/// let mut list = XmlList::new(None, Rc::new(comparator));
/// list.push_last((0u32, 0u32));
/// list.push_last((1, 0));
/// list.push_last((1, 2));
/// list.push_last((3, 0));
///
/// assert_eq!(list.search(&(1, 0)), Some(&(1, 0)));
///
/// assert_eq!(list.remove_all(&(1, 0)).collect::<Vec<_>>(), vec![(1, 0), (1, 2)]);
///
/// assert_eq!(list.search(&(1, 0)), None);
/// ```
pub fn remove_all<'a>(&'a mut self, data: &'a T) -> impl Iterator<Item = T> + 'a {
let mut link = self.link_search(data);
std::iter::from_fn(move || {
let now = link?;
(self.comparator)(&now.data, data).is_eq().then(|| {
link = now.next;
self.remove_link(now)
})
})
}
/// Check if the list is empty.
pub fn is_empty(&self) -> bool {
self.head.is_none()
}
/// Count how many elements the list has.
///
/// # Note
/// Since `XmlList` does not has a counter, this method enumerates elements on each call.
/// Therefore, the complexity of this method is `O(N)`, `N` is the number of elements of the list.
pub fn len(&self) -> usize {
let mut link = self.head;
let mut count = 0;
while let Some(now) = link {
count += 1;
link = now.next;
}
count
}
// /// In original libxml2, this is the public API.
// /// However, XmlLinkRef should only be published in the crate
// /// because publishing XmlLinkRef may break the constraints of XmlList.
// pub(crate) fn first(&self) -> Option<&XmlLinkRef<T>> {
// self.head.as_ref()
// }
// /// In original libxml2, this is the public API.
// /// However, XmlLinkRef should only be published in the crate
// /// because publishing XmlLinkRef may break the constraints of XmlList.
// pub(crate) fn last(&self) -> Option<&XmlLinkRef<T>> {
// self.tail.as_ref()
// }
/// Remove the head of the list and return its data.
///
/// # Examples
/// ```rust
/// use std::rc::Rc;
///
/// use exml::list::XmlList;
///
/// let mut list = XmlList::without_comparator(None);
/// list.push_last(0u32);
/// list.push_last(1);
/// list.push_last(1);
///
/// assert_eq!(list.pop_first(), Some(0));
/// assert_eq!(list.pop_first(), Some(1));
/// assert_eq!(list.pop_first(), Some(1));
/// assert_eq!(list.pop_first(), None);
/// ```
pub fn pop_first(&mut self) -> Option<T> {
let head = self.head?;
Some(self.remove_link(head))
}
/// Remove the tail of the list and return its data.
///
/// # Examples
/// ```rust
/// use std::rc::Rc;
///
/// use exml::list::XmlList;
///
/// let mut list = XmlList::without_comparator(None);
/// list.push_last(0u32);
/// list.push_last(1);
/// list.push_last(1);
///
/// assert_eq!(list.pop_last(), Some(1));
/// assert_eq!(list.pop_last(), Some(1));
/// assert_eq!(list.pop_last(), Some(0));
/// assert_eq!(list.pop_last(), None);
/// ```
pub fn pop_last(&mut self) -> Option<T> {
let tail = self.tail?;
Some(self.remove_link(tail))
}
/// Insert `data` at the head of the list.
///
/// This method may makes the order of `self` inconsistent.
/// Therefore, the user should guarantee the order of `self` yourself after using this method.
///
/// # Examples
/// ```rust
/// use std::rc::Rc;
///
/// use exml::list::XmlList;
///
/// let mut list = XmlList::without_comparator(None);
/// list.push_first(0u32);
/// list.push_first(2);
/// list.push_first(1);
///
/// // Unless explicitly sorted, the order in which they are pushed is preserved.
/// assert_eq!(list.pop_first(), Some(1));
/// assert_eq!(list.pop_first(), Some(2));
/// assert_eq!(list.pop_first(), Some(0));
/// assert_eq!(list.pop_first(), None);
/// ```
pub fn push_first(&mut self, data: T) {
let mut new = XmlLinkRef::new(data).expect("Failed to generate new XmlLinkRef");
if let Some(mut head) = self.head {
new.next = Some(head);
head.prev = Some(new);
} else {
self.tail = Some(new);
}
self.head = Some(new);
}
/// Insert `data` at the tail of the list.
///
/// This method may makes the order of `self` inconsistent.
/// Therefore, the user should guarantee the order of `self` yourself after using this method.
///
/// # Examples
/// ```rust
/// use std::rc::Rc;
///
/// use exml::list::XmlList;
///
/// let mut list = XmlList::without_comparator(None);
/// list.push_last(0u32);
/// list.push_last(2);
/// list.push_last(1);
///
/// // Unless explicitly sorted, the order in which they are pushed is preserved.
/// assert_eq!(list.pop_first(), Some(0));
/// assert_eq!(list.pop_first(), Some(2));
/// assert_eq!(list.pop_first(), Some(1));
/// assert_eq!(list.pop_first(), None);
/// ```
pub fn push_last(&mut self, data: T) {
let mut new = XmlLinkRef::new(data).expect("Failed to generate new XmlLinkRef");
if let Some(mut tail) = self.tail {
new.prev = Some(tail);
tail.next = Some(new);
} else {
self.head = Some(new);
}
self.tail = Some(new);
}
/// Reverse the order of `self`.
///
/// # Examples
/// ```rust
/// use std::rc::Rc;
///
/// use exml::list::XmlList;
///
/// let mut list = XmlList::without_comparator(None);
/// list.push_last(0u32);
/// list.push_last(2);
/// list.push_last(1);
///
/// list.reverse();
///
/// assert_eq!(list.pop_first(), Some(1));
/// assert_eq!(list.pop_first(), Some(2));
/// assert_eq!(list.pop_first(), Some(0));
/// assert_eq!(list.pop_first(), None);
/// ```
pub fn reverse(&mut self) {
let Some(mut link) = self.head else {
return;
};
self.tail = Some(link);
let mut prev = None;
while let Some(next) = link.next {
// before: prev -> link -> next
// after : next -> link -> prev
link.next = prev;
link.prev = Some(next);
prev = Some(link);
link = next;
}
link.next = prev;
link.prev = None;
self.head = Some(link);
}
/// Split the list at `at`-th element and return the tail-side of split lists.
fn split_off(&mut self, at: usize) -> XmlList<T> {
let mut count = 0;
let mut link = self.head;
let mut prev = None::<XmlLinkRef<T>>;
while let Some(mut now) = link {
if count == at {
let new = XmlList {
head: Some(now),
tail: self.tail,
deallocator: Rc::clone(&self.deallocator),
comparator: Rc::clone(&self.comparator),
};
now.prev = None;
if let Some(mut prev) = prev {
prev.next = None;
}
self.tail = prev;
return new;
}
prev = Some(now);
link = now.next;
count += 1;
}
assert!(count == at);
XmlList {
head: None,
tail: None,
deallocator: Rc::clone(&self.deallocator),
comparator: Rc::clone(&self.comparator),
}
}
/// Sort the elements of the list.
///
/// In original libxml2, it seems that insertion sort is used.
/// This method uses merge sort.
///
/// # Examples
/// ```rust
/// use std::rc::Rc;
///
/// use exml::list::XmlList;
///
/// let mut list = XmlList::without_comparator(None);
/// list.push_last(0u32);
/// list.push_last(2);
/// list.push_last(1);
///
/// list.sort();
///
/// assert_eq!(list.pop_first(), Some(0));
/// assert_eq!(list.pop_first(), Some(1));
/// assert_eq!(list.pop_first(), Some(2));
/// assert_eq!(list.pop_first(), None);
/// ```
pub fn sort(&mut self) {
let len = self.len();
if len <= 1 {
return;
}
let mut back = self.split_off(len / 2);
self.sort();
back.sort();
self.merge_sorted_lists(back);
}
/// # Constraint
/// - Both `self` and `other` must be sorted.
/// - Both `self` and `other` must have same `deallocator` and `comparator`.
/// - `self` and `other` can be empty.
fn merge_sorted_lists(&mut self, mut other: Self) {
if self.is_empty() {
self.head = other.head;
self.tail = other.tail;
return;
}
if other.is_empty() {
return;
}
let (mut shead, mut ohead) = (self.head, other.head);
let mut prev = None::<XmlLinkRef<T>>;
while let (Some(slink), Some(olink)) = (shead, ohead) {
let mut link = if (self.comparator)(&slink.data, &olink.data).is_le() {
shead = slink.next;
slink
} else {
ohead = olink.next;
olink
};
if let Some(mut p) = prev {
p.next = Some(link);
link.prev = Some(p);
} else {
self.head = Some(link);
}
prev = Some(link);
}
// Both `self` and `other` are checked that they are not empty.
// Therefore, at least either `shead` or `ohead` is not `None` and `prev` cannot be `None`.
// By the above, it is not a problem to do `unwrap` at this point.
let mut prev = prev.unwrap();
if let Some(mut shead) = shead {
prev.next = Some(shead);
shead.prev = Some(prev);
} else if let Some(mut ohead) = ohead {
prev.next = Some(ohead);
ohead.prev = Some(prev);
self.tail = other.tail;
}
// At this point, both `self` and `other` own the head and tail pointers of `other`.
// To prevent double-free is done for them,
// overwrite the head and tail pointers of `other` with `None`.
other.head = None;
other.tail = None;
}
/// Walk from the head and process each data with `walk` until `walk` returns `false`.
///
/// # Examples
/// ```rust
/// use std::rc::Rc;
///
/// use exml::list::XmlList;
///
/// let mut list = XmlList::without_comparator(None);
/// list.push_last(0u32);
/// list.push_last(1);
/// list.push_last(2);
/// list.push_last(3);
/// list.push_last(4);
///
/// let mut buf = vec![];
/// list.walk(|&value| {
/// buf.push(value * 2);
/// value < 2
/// });
///
/// assert_eq!(buf, vec![0, 2, 4]);
/// ```
pub fn walk(&self, mut walk: impl FnMut(&T) -> bool) {
let mut link = self.head;
while let Some(now) = link {
if !walk(&now.data) {
break;
}
link = now.next;
}
}
/// Walk from the tail and process each data with `walk` until `walk` returns `false`.
///
/// # Examples
/// ```rust
/// use std::rc::Rc;
///
/// use exml::list::XmlList;
///
/// let mut list = XmlList::without_comparator(None);
/// list.push_last(0u32);
/// list.push_last(1);
/// list.push_last(2);
/// list.push_last(3);
/// list.push_last(4);
///
/// let mut buf = vec![];
/// list.reverse_walk(|&value| {
/// buf.push(value * 2);
/// value > 2
/// });
///
/// assert_eq!(buf, vec![8, 6, 4]);
/// ```
pub fn reverse_walk(&self, mut walk: impl FnMut(&T) -> bool) {
let mut link = self.tail;
while let Some(now) = link {
if !walk(&now.data) {
break;
}
link = now.prev;
}
}
/// Append list `other` to `self`.
/// `self` will sorted after processing this method.
///
/// If the comparator of `other` is different from the one of `self`,
/// the one of `self` is used in preference.
///
/// # Examples
/// ```rust
/// use std::rc::Rc;
///
/// use exml::list::XmlList;
///
/// let mut list = XmlList::without_comparator(None);
/// list.push_last(0u32);
/// list.push_last(2);
/// list.push_last(4);
///
/// let mut list2 = XmlList::without_comparator(None);
/// list.push_last(1u32);
/// list.push_last(3);
/// list.push_last(4);
/// list.push_last(5);
///
/// list.extend(list2);
///
/// assert_eq!(list.into_iter().collect::<Vec<_>>(), vec![0, 1, 2, 3, 4, 4, 5]);
/// ```
pub fn extend(&mut self, mut other: Self) {
self.sort();
other.comparator = Rc::clone(&self.comparator);
other.sort();
self.merge_sorted_lists(other);
}
}
impl<T: Ord + Clone + 'static> Clone for XmlList<T> {
fn clone(&self) -> Self {
let mut new = XmlList {
deallocator: Rc::clone(&self.deallocator),
comparator: Rc::clone(&self.comparator),
..Default::default()
};
if self.is_empty() {
return new;
}
let mut head = XmlLinkRef::new(self.head.unwrap().data.clone())
.expect("Failed to generate new XmlLinkRef");
new.head = Some(head);
let mut shead = self.head.unwrap();
while let Some(snext) = shead.next {
let next =
XmlLinkRef::new(snext.data.clone()).expect("Failed to generate new XmlLinkRef");
head = next;
shead = snext;
}
new.tail = Some(head);
new
}
}
impl<T: Ord + 'static> Default for XmlList<T> {
fn default() -> Self {
Self {
head: None,
tail: None,
deallocator: Rc::new(drop),
comparator: Rc::new(T::cmp),
}
}
}
impl<T: Ord + 'static> IntoIterator for XmlList<T> {
type Item = T;
type IntoIter = IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
IntoIter { list: self }
}
}
impl<T> Drop for XmlList<T> {
fn drop(&mut self) {
self.clear();
}
}
pub struct IntoIter<T> {
list: XmlList<T>,
}
impl<T: Ord + 'static> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.list.pop_first()
}
}
impl<T: Ord + 'static> DoubleEndedIterator for IntoIter<T> {
fn next_back(&mut self) -> Option<Self::Item> {
self.list.pop_last()
}
}
pub struct XmlListRef<T>(NonNull<XmlList<T>>);
impl<T> XmlListRef<T> {
pub fn from_list(list: XmlList<T>) -> Option<Self> {
let boxed = Box::new(list);
let leaked = Box::leak(boxed);
NonNull::new(leaked).map(Self)
}
// fn from_raw(ptr: *mut XmlList<T>) -> Option<Self> {
// NonNull::new(ptr).map(Self)
// }
pub fn free(self) {
unsafe {
let _ = Box::from_raw(self.0.as_ptr());
}
}
}
impl<T> Clone for XmlListRef<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for XmlListRef<T> {}
impl<T> Deref for XmlListRef<T> {
type Target = XmlList<T>;
fn deref(&self) -> &Self::Target {
unsafe { self.0.as_ref() }
}
}
impl<T> DerefMut for XmlListRef<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { self.0.as_mut() }
}
}