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
use crate::{
    free, Alpm, Backup, Conflict, Db, DbMut, Dep, DepMissing, Depend, DependMissing, FileConflict,
    Group, LoadedPackage, OwnedConflict, OwnedFileConflict, Package, Pkg,
};

use std::ffi::{c_void, CStr};
use std::fmt;
use std::iter::{ExactSizeIterator, Iterator};
use std::marker::PhantomData;
use std::mem::ManuallyDrop;
use std::os::raw::c_char;
use std::ptr;

use alpm_sys::*;

extern "C" {
    fn strndup(cs: *const c_char, n: usize) -> *mut c_char;
}

pub unsafe trait IntoAlpmListItem<'a, 'b> {
    type Borrow: fmt::Debug;
    #[doc(hidden)]
    unsafe fn ptr_into_alpm_list_item(handle: &'a Alpm, ptr: *mut c_void) -> Self;
    #[doc(hidden)]
    unsafe fn ptr_as_alpm_list_item(handle: &'a Alpm, ptr: *mut c_void) -> Self::Borrow;
}

pub unsafe trait AsAlpmListItemPtr<'a> {
    type Output;
    const FREE: Option<unsafe extern "C" fn(_ptr: *mut c_void)> = None;
    fn as_ptr(&self) -> *mut c_void;
}

pub trait Bool {
    const DROP: bool;
}

pub unsafe trait Push<'a>: AsAlpmListItemPtr<'a> {}

pub struct True;
pub struct False;

impl Bool for True {
    const DROP: bool = true;
}

impl Bool for False {
    const DROP: bool = false;
}

pub struct RawAlpmList<'a, T, D>
where
    D: Bool,
    T: AsAlpmListItemPtr<'a>,
{
    list: *mut alpm_list_t,
    _marker1: PhantomData<&'a T>,
    _marker2: PhantomData<D>,
}

impl<'a, T, D> RawAlpmList<'a, T, D>
where
    D: Bool,
    T: AsAlpmListItemPtr<'a>,
{
    pub fn list(&self) -> *mut alpm_list_t {
        self.list
    }
}

impl<'a, T, D> Drop for RawAlpmList<'a, T, D>
where
    D: Bool,
    T: AsAlpmListItemPtr<'a>,
{
    fn drop(&mut self) {
        if D::DROP {
            if let Some(free) = T::FREE {
                unsafe { alpm_list_free_inner(self.list, Some(free)) }
            }
            unsafe { alpm_list_free(self.list) };
        }
    }
}

pub trait IntoRawAlpmList<'a, T>
where
    T: AsAlpmListItemPtr<'a>,
{
    #[doc(hidden)]
    type Drop: Bool;
    #[doc(hidden)]
    unsafe fn into_raw_alpm_list(self) -> RawAlpmList<'a, T, Self::Drop>;
}

impl<'a> IntoRawAlpmList<'a, Pkg<'a>> for AlpmList<'a, LoadedPackage<'a>> {
    type Drop = False;
    unsafe fn into_raw_alpm_list(self) -> RawAlpmList<'a, Pkg<'a>, Self::Drop> {
        RawAlpmList {
            list: self.list,
            _marker1: PhantomData,
            _marker2: PhantomData,
        }
    }
}

impl<'a> IntoRawAlpmList<'a, Pkg<'a>> for AlpmList<'a, Package<'a>> {
    type Drop = False;
    unsafe fn into_raw_alpm_list(self) -> RawAlpmList<'a, Pkg<'a>, Self::Drop> {
        RawAlpmList {
            list: self.list,
            _marker1: PhantomData,
            _marker2: PhantomData,
        }
    }
}

impl<'a, T> IntoRawAlpmList<'a, T> for AlpmList<'a, T>
where
    T: AsAlpmListItemPtr<'a>,
{
    type Drop = False;
    unsafe fn into_raw_alpm_list(self) -> RawAlpmList<'a, T, Self::Drop> {
        RawAlpmList {
            list: self.list,
            _marker1: PhantomData,
            _marker2: PhantomData,
        }
    }
}

impl<'a, T> IntoRawAlpmList<'a, T> for &AlpmListMut<'a, T>
where
    for<'b> T: IntoAlpmListItem<'a, 'b> + AsAlpmListItemPtr<'a>,
{
    type Drop = False;
    unsafe fn into_raw_alpm_list(self) -> RawAlpmList<'a, T, Self::Drop> {
        RawAlpmList {
            list: self.list.list,
            _marker1: PhantomData,
            _marker2: PhantomData,
        }
    }
}

impl<'a, T, D: Bool> IntoRawAlpmList<'a, T> for RawAlpmList<'a, T, D>
where
    T: AsAlpmListItemPtr<'a>,
{
    type Drop = D;
    unsafe fn into_raw_alpm_list(self) -> RawAlpmList<'a, T, Self::Drop> {
        self
    }
}

impl<'a, T, I> IntoRawAlpmList<'a, T::Output> for I
where
    I: Iterator<Item = T>,
    T: AsAlpmListItemPtr<'a>,
    T::Output: AsAlpmListItemPtr<'a>,
{
    type Drop = True;
    unsafe fn into_raw_alpm_list(self) -> RawAlpmList<'a, T::Output, Self::Drop> {
        let mut list = ptr::null_mut();

        for item in self {
            list = alpm_list_add(list, item.as_ptr());
            if T::FREE.is_none() {
                std::mem::forget(item);
            }
        }

        RawAlpmList {
            list,
            _marker1: PhantomData,
            _marker2: PhantomData,
        }
    }
}

pub struct AlpmList<'a, T> {
    pub(crate) handle: &'a Alpm,
    pub(crate) list: *mut alpm_list_t,
    pub(crate) _marker: PhantomData<T>,
}

impl<'a, T> fmt::Debug for AlpmList<'a, T>
where
    for<'b> T: IntoAlpmListItem<'a, 'b>,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("AlpmList ")?;
        f.debug_list().entries(self).finish()
    }
}

impl<'a, T> Clone for AlpmList<'a, T> {
    fn clone(&self) -> Self {
        AlpmList {
            handle: self.handle,
            list: self.list,
            _marker: self._marker,
        }
    }
}

impl<'a, T> Copy for AlpmList<'a, T> {}

pub struct AlpmListMut<'a, T>
where
    for<'b> T: IntoAlpmListItem<'a, 'b>,
{
    list: AlpmList<'a, T>,
}

impl<'a, T> fmt::Debug for AlpmListMut<'a, T>
where
    for<'b> T: IntoAlpmListItem<'a, 'b>,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.as_list(), f)
    }
}

impl<'a, T> std::ops::Deref for AlpmListMut<'a, T>
where
    for<'b> T: IntoAlpmListItem<'a, 'b>,
{
    type Target = AlpmList<'a, T>;

    fn deref(&self) -> &Self::Target {
        &self.list
    }
}

impl<'a, T> Drop for AlpmListMut<'a, T>
where
    for<'b> T: IntoAlpmListItem<'a, 'b>,
{
    fn drop(&mut self) {
        let list = self.list.list;
        let mut curr = list;

        while !curr.is_null() {
            let item = unsafe { T::ptr_into_alpm_list_item(self.handle, (*curr).data) };
            drop(item);
            curr = unsafe { (*curr).next };
        }

        unsafe { alpm_list_free(list) }
    }
}

impl<'a, 'b, T> AlpmList<'a, T>
where
    T: IntoAlpmListItem<'a, 'b>,
{
    pub fn len(&self) -> usize {
        unsafe { alpm_list_count(self.list) }
    }

    pub fn is_empty(&self) -> bool {
        self.list.is_null()
    }

    pub fn first(&'b self) -> Option<T::Borrow> {
        if self.is_empty() {
            None
        } else {
            unsafe { Some(T::ptr_as_alpm_list_item(self.handle, (*self.list).data)) }
        }
    }

    pub fn last(&'b self) -> Option<T::Borrow> {
        let item = unsafe { alpm_list_last(self.list) };
        if item.is_null() {
            None
        } else {
            unsafe { Some(T::ptr_as_alpm_list_item(self.handle, (*item).data)) }
        }
    }

    pub fn iter(&'b self) -> Iter<'a, 'b, T> {
        self.into_iter()
    }
}

impl<'a> AlpmList<'a, String> {
    pub fn as_str<'b>(&'b self) -> AlpmList<'a, &'b str> {
        unsafe { AlpmList::from_parts(self.handle, self.list) }
    }
}

impl<'a, T> AlpmList<'a, T>
where
    for<'b> T: IntoAlpmListItem<'a, 'b>,
{
    #[allow(clippy::wrong_self_convention)]
    pub fn to_list_mut(&self) -> AlpmListMut<'a, T> {
        let list = unsafe { alpm_list_copy(self.list) };
        AlpmListMut {
            list: unsafe { AlpmList::from_parts(self.handle, list) },
        }
    }
}

impl<'a, T> AlpmListMut<'a, T>
where
    for<'b> T: IntoAlpmListItem<'a, 'b> + Push<'a> + AsAlpmListItemPtr<'a>,
{
    pub fn push(&mut self, t: T) {
        unsafe { self.list.list = alpm_list_add(self.list.list, t.as_ptr()) };
        if T::FREE.is_none() {
            std::mem::forget(t);
        }
    }
}

impl<'a, T> Extend<T> for AlpmListMut<'a, T>
where
    for<'b> T: IntoAlpmListItem<'a, 'b> + Push<'a>,
{
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        for item in iter {
            self.push(item);
        }
    }
}

impl<'a> AlpmListMut<'a, String> {
    pub fn push_str(&mut self, s: &str) {
        let s = unsafe { strndup(s.as_bytes().as_ptr() as _, s.len()) };
        unsafe { self.list.list = alpm_list_add(self.list.list, s as *mut c_void) };
    }
}

impl<'a, T> AlpmListMut<'a, T>
where
    for<'b> T: IntoAlpmListItem<'a, 'b>,
{
    pub fn retain<F>(&mut self, mut f: F)
    where
        F: FnMut(&T) -> bool,
    {
        let mut list = self.list.list;
        let mut curr = list;

        while !curr.is_null() {
            let item = unsafe { T::ptr_into_alpm_list_item(self.handle, (*curr).data) };
            let next = unsafe { (*curr).next };
            if !f(&item) {
                drop(item);
                unsafe { list = alpm_list_remove_item(list, curr) };
                unsafe { free(curr as _) };
            } else {
                std::mem::forget(item);
            }
            curr = next;
        }

        self.list.list = list;
    }

    pub fn remove(&mut self, n: usize) -> Option<T> {
        if n >= self.len() {
            return None;
        }

        let item = unsafe { alpm_list_nth(self.list.list, n) };
        unsafe { self.list.list = alpm_list_remove_item(self.list.list, item) };
        let ret = unsafe {
            Some(T::ptr_into_alpm_list_item(
                self.handle,
                (*self.list.list).data,
            ))
        };
        unsafe { free(item as _) };
        ret
    }

    pub fn remove_list(&mut self, n: usize) -> AlpmListMut<'a, T> {
        if n >= self.len() {
            return AlpmListMut::new(self.handle);
        }

        let item = unsafe { alpm_list_nth(self.list.list, n) };
        self.list.list = unsafe { alpm_list_remove_item(self.list.list, item) };
        unsafe { (*item).next = ptr::null_mut() };
        unsafe { (*item).prev = ptr::null_mut() };
        unsafe { AlpmListMut::from_parts(self.handle, item) }
    }

    pub fn as_list(&self) -> AlpmList<'a, T> {
        self.list
    }
}

impl<'a, T> IntoIterator for AlpmListMut<'a, T>
where
    for<'b> T: IntoAlpmListItem<'a, 'b>,
{
    type Item = T;
    type IntoIter = IntoIterMut<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        IntoIterMut {
            current: self.list.list,
            list: ManuallyDrop::new(self),
        }
    }
}

impl<'a, 'b, T> IntoIterator for &'b AlpmListMut<'a, T>
where
    for<'c> T: IntoAlpmListItem<'a, 'c>,
{
    type Item = <T as IntoAlpmListItem<'a, 'b>>::Borrow;
    type IntoIter = Iter<'a, 'b, T>;

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

impl<'a, 'b, T> IntoIterator for &'b AlpmList<'a, T>
where
    T: IntoAlpmListItem<'a, 'b>,
{
    type Item = T::Borrow;
    type IntoIter = Iter<'a, 'b, T>;

    fn into_iter(self) -> Self::IntoIter {
        Iter {
            current: self.list,
            list: self,
        }
    }
}

impl<'a, T> IntoIterator for AlpmList<'a, T>
where
    T: IntoAlpmListItem<'a, 'a>,
{
    type Item = T::Borrow;
    type IntoIter = IntoIter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        IntoIter {
            current: self.list,
            list: self,
        }
    }
}

#[derive(Copy, Clone)]
pub struct Iter<'a, 'b, T>
where
    T: IntoAlpmListItem<'a, 'b>,
{
    list: &'b AlpmList<'a, T>,
    current: *mut alpm_list_t,
}

impl<'a, 'b, T> fmt::Debug for Iter<'a, 'b, T>
where
    for<'c> T: IntoAlpmListItem<'a, 'c>,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Iter").field("list", self.list).finish()
    }
}

#[derive(Copy, Clone)]
pub struct IntoIter<'a, T>
where
    T: IntoAlpmListItem<'a, 'a>,
{
    list: AlpmList<'a, T>,
    current: *mut alpm_list_t,
}

impl<'a, T> fmt::Debug for IntoIter<'a, T>
where
    for<'b> T: IntoAlpmListItem<'a, 'b>,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Iter").field("list", &self.list).finish()
    }
}

impl<'a, 'b, T> Iter<'a, 'b, T>
where
    T: IntoAlpmListItem<'a, 'b>,
{
    fn next_data(&mut self) -> Option<*mut c_void> {
        if self.current.is_null() {
            None
        } else {
            let data = unsafe { (*(self.current)).data };
            self.current = unsafe { alpm_list_next(self.current) };

            Some(data)
        }
    }
}

pub struct IntoIterMut<'a, T>
where
    for<'b> T: IntoAlpmListItem<'a, 'b>,
{
    list: ManuallyDrop<AlpmListMut<'a, T>>,
    current: *mut alpm_list_t,
}

impl<'a, T> fmt::Debug for IntoIterMut<'a, T>
where
    for<'b> T: IntoAlpmListItem<'a, 'b>,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Iter").field("list", &self.list).finish()
    }
}

impl<'a, T> Drop for IntoIterMut<'a, T>
where
    for<'b> T: IntoAlpmListItem<'a, 'b>,
{
    fn drop(&mut self) {
        unsafe { AlpmListMut::<T>::from_parts(self.list.handle, self.current) };
    }
}

impl<'a, T> ExactSizeIterator for IntoIterMut<'a, T> where for<'b> T: IntoAlpmListItem<'a, 'b> {}
impl<'a, T> ExactSizeIterator for IntoIter<'a, T> where for<'b> T: IntoAlpmListItem<'a, 'b> {}
impl<'a, 'b, T> ExactSizeIterator for Iter<'a, 'b, T> where T: IntoAlpmListItem<'a, 'b> {}

impl<'a, T> Iterator for IntoIterMut<'a, T>
where
    for<'b> T: IntoAlpmListItem<'a, 'b>,
{
    type Item = T;
    fn next(&mut self) -> Option<Self::Item> {
        let data = self.next_data();

        match data {
            Some(data) => unsafe { Some(T::ptr_into_alpm_list_item(self.list.handle, data)) },
            None => None,
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let size = unsafe { alpm_list_count(self.list.list.list) };
        (size, Some(size))
    }
}

impl<'a, 'b, T> Iterator for Iter<'a, 'b, T>
where
    T: IntoAlpmListItem<'a, 'b>,
{
    type Item = T::Borrow;
    fn next(&mut self) -> Option<Self::Item> {
        let data = self.next_data();

        match data {
            Some(data) => unsafe { Some(T::ptr_as_alpm_list_item(self.list.handle, data)) },
            None => None,
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let size = unsafe { alpm_list_count(self.list.list) };
        (size, Some(size))
    }
}

impl<'a, T> Iterator for IntoIter<'a, T>
where
    T: IntoAlpmListItem<'a, 'a>,
{
    type Item = T::Borrow;
    fn next(&mut self) -> Option<Self::Item> {
        let data = self.next_data();

        match data {
            Some(data) => unsafe { Some(T::ptr_as_alpm_list_item(self.list.handle, data)) },
            None => None,
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let size = unsafe { alpm_list_count(self.list.list) };
        (size, Some(size))
    }
}

impl<'a, T> IntoIter<'a, T>
where
    T: IntoAlpmListItem<'a, 'a>,
{
    fn next_data(&mut self) -> Option<*mut c_void> {
        if self.current.is_null() {
            None
        } else {
            let data = unsafe { (*(self.current)).data };
            self.current = unsafe { alpm_list_next(self.current) };

            Some(data)
        }
    }
}

impl<'a, T> IntoIterMut<'a, T>
where
    for<'b> T: IntoAlpmListItem<'a, 'b>,
{
    fn next_data(&mut self) -> Option<*mut c_void> {
        if self.current.is_null() {
            None
        } else {
            let data = unsafe { (*(self.current)).data };
            self.current = unsafe { alpm_list_next(self.current) };

            Some(data)
        }
    }
}

impl<'a, T> AlpmList<'a, T> {
    pub(crate) unsafe fn from_parts(handle: &'a Alpm, list: *mut alpm_list_t) -> AlpmList<'a, T> {
        AlpmList {
            handle,
            list,
            _marker: PhantomData,
        }
    }
}

impl<'a, T> AlpmListMut<'a, T>
where
    for<'b> T: IntoAlpmListItem<'a, 'b>,
{
    pub fn new(handle: &'a Alpm) -> AlpmListMut<'a, T> {
        AlpmListMut {
            list: unsafe { AlpmList::from_parts(handle, ptr::null_mut()) },
        }
    }

    pub(crate) unsafe fn from_parts(
        handle: &'a Alpm,
        list: *mut alpm_list_t,
    ) -> AlpmListMut<'a, T> {
        AlpmListMut {
            list: AlpmList::from_parts(handle, list),
        }
    }
}

unsafe impl<'a> AsAlpmListItemPtr<'a> for Pkg<'a> {
    type Output = Pkg<'a>;

    fn as_ptr(&self) -> *mut c_void {
        (*self).as_ptr() as *mut c_void
    }
}

unsafe impl<'a> AsAlpmListItemPtr<'a> for Package<'a> {
    type Output = Package<'a>;

    fn as_ptr(&self) -> *mut c_void {
        self.pkg.as_ptr() as *mut c_void
    }
}

unsafe impl<'a> AsAlpmListItemPtr<'a> for LoadedPackage<'a> {
    type Output = Pkg<'a>;

    fn as_ptr(&self) -> *mut c_void {
        self.pkg.as_ptr() as *mut c_void
    }
}

unsafe impl<'a> AsAlpmListItemPtr<'a> for Db<'a> {
    type Output = Db<'a>;

    fn as_ptr(&self) -> *mut c_void {
        (*self).as_ptr() as *mut c_void
    }
}

unsafe impl<'a> AsAlpmListItemPtr<'a> for Depend {
    type Output = Dep<'a>;

    fn as_ptr(&self) -> *mut c_void {
        Dep::as_ptr(self) as *mut c_void
    }
}

unsafe impl<'a, T: AsAlpmListItemPtr<'a>> AsAlpmListItemPtr<'a> for &T {
    type Output = T::Output;

    fn as_ptr(&self) -> *mut c_void {
        (*self).as_ptr()
    }
}

unsafe impl<'a> AsAlpmListItemPtr<'a> for Dep<'a> {
    type Output = Dep<'a>;

    fn as_ptr(&self) -> *mut c_void {
        Dep::as_ptr(self) as *mut c_void
    }
}

unsafe impl<'a> AsAlpmListItemPtr<'a> for String {
    type Output = String;
    const FREE: Option<unsafe extern "C" fn(_ptr: *mut c_void)> = Some(free);
    fn as_ptr(&self) -> *mut c_void {
        unsafe { strndup(self.as_bytes().as_ptr() as _, self.len()) as *mut c_void }
    }
}

unsafe impl<'a> AsAlpmListItemPtr<'a> for &str {
    type Output = String;
    const FREE: Option<unsafe extern "C" fn(_ptr: *mut c_void)> = Some(free);

    fn as_ptr(&self) -> *mut c_void {
        unsafe { strndup(self.as_bytes().as_ptr() as _, self.len()) as *mut c_void }
    }
}

unsafe impl<'a> Push<'a> for String {}
unsafe impl<'a> Push<'a> for Pkg<'a> {}
unsafe impl<'a> Push<'a> for Package<'a> {}
unsafe impl<'a> Push<'a> for Db<'a> {}
unsafe impl<'a> Push<'a> for Depend {}
unsafe impl<'a> Push<'a> for Dep<'a> {}

unsafe impl<'a, 'b> IntoAlpmListItem<'a, 'b> for Package<'a> {
    type Borrow = Self;
    unsafe fn ptr_into_alpm_list_item(handle: &'a Alpm, ptr: *mut c_void) -> Self {
        Package::new(handle, ptr as *mut alpm_pkg_t)
    }
    unsafe fn ptr_as_alpm_list_item(handle: &'a Alpm, ptr: *mut c_void) -> Self::Borrow {
        Package::new(handle, ptr as *mut alpm_pkg_t)
    }
}

unsafe impl<'a, 'b> IntoAlpmListItem<'a, 'b> for Group<'a> {
    type Borrow = Self;
    unsafe fn ptr_into_alpm_list_item(handle: &'a Alpm, ptr: *mut c_void) -> Self {
        Group::new(handle, ptr as *mut alpm_group_t)
    }
    unsafe fn ptr_as_alpm_list_item(handle: &'a Alpm, ptr: *mut c_void) -> Self::Borrow {
        Group::new(handle, ptr as *mut alpm_group_t)
    }
}

unsafe impl<'a, 'b> IntoAlpmListItem<'a, 'b> for Depend {
    type Borrow = Dep<'b>;
    unsafe fn ptr_into_alpm_list_item(_handle: &'a Alpm, ptr: *mut c_void) -> Self {
        Depend::from_ptr(ptr as *mut alpm_depend_t)
    }
    unsafe fn ptr_as_alpm_list_item(_handle: &'a Alpm, ptr: *mut c_void) -> Self::Borrow {
        Dep::from_ptr(ptr as *mut alpm_depend_t)
    }
}

unsafe impl<'a, 'b> IntoAlpmListItem<'a, 'b> for Dep<'a> {
    type Borrow = Self;
    unsafe fn ptr_into_alpm_list_item(_handle: &'a Alpm, ptr: *mut c_void) -> Self {
        Dep::from_ptr(ptr as *mut alpm_depend_t)
    }

    unsafe fn ptr_as_alpm_list_item(_handle: &'a Alpm, ptr: *mut c_void) -> Self::Borrow {
        Dep::from_ptr(ptr as *mut alpm_depend_t)
    }
}

unsafe impl<'a, 'b> IntoAlpmListItem<'a, 'b> for Backup {
    type Borrow = Self;
    unsafe fn ptr_into_alpm_list_item(_handle: &'a Alpm, ptr: *mut c_void) -> Self {
        Backup::from_ptr(ptr as *mut alpm_backup_t)
    }
    unsafe fn ptr_as_alpm_list_item(_handle: &'a Alpm, ptr: *mut c_void) -> Self::Borrow {
        Backup::from_ptr(ptr as *mut alpm_backup_t)
    }
}

unsafe impl<'a, 'b> IntoAlpmListItem<'a, 'b> for OwnedFileConflict {
    type Borrow = FileConflict<'b>;
    unsafe fn ptr_into_alpm_list_item(_handle: &'a Alpm, ptr: *mut c_void) -> Self {
        OwnedFileConflict {
            inner: FileConflict::from_ptr(ptr as *mut alpm_fileconflict_t),
        }
    }

    unsafe fn ptr_as_alpm_list_item(_handle: &'a Alpm, ptr: *mut c_void) -> Self::Borrow {
        FileConflict::from_ptr(ptr as *mut alpm_fileconflict_t)
    }
}

unsafe impl<'a, 'b> IntoAlpmListItem<'a, 'b> for DependMissing {
    type Borrow = DepMissing<'b>;
    unsafe fn ptr_into_alpm_list_item(_handle: &'a Alpm, ptr: *mut c_void) -> Self {
        DependMissing {
            inner: DepMissing::from_ptr(ptr as *mut alpm_depmissing_t),
        }
    }

    unsafe fn ptr_as_alpm_list_item(_handle: &'a Alpm, ptr: *mut c_void) -> Self::Borrow {
        DepMissing::from_ptr(ptr as *mut alpm_depmissing_t)
    }
}

unsafe impl<'a, 'b> IntoAlpmListItem<'a, 'b> for OwnedConflict {
    type Borrow = Conflict<'b>;
    unsafe fn ptr_into_alpm_list_item(_handle: &'a Alpm, ptr: *mut c_void) -> Self {
        OwnedConflict::from_ptr(ptr as *mut alpm_conflict_t)
    }
    unsafe fn ptr_as_alpm_list_item(_handle: &'a Alpm, ptr: *mut c_void) -> Self::Borrow {
        Conflict::from_ptr(ptr as *mut alpm_conflict_t)
    }
}

unsafe impl<'a, 'b> IntoAlpmListItem<'a, 'b> for Conflict<'a> {
    type Borrow = Self;
    unsafe fn ptr_into_alpm_list_item(_handle: &'a Alpm, ptr: *mut c_void) -> Self {
        Conflict::from_ptr(ptr as *mut alpm_conflict_t)
    }
    unsafe fn ptr_as_alpm_list_item(_handle: &'a Alpm, ptr: *mut c_void) -> Self::Borrow {
        Conflict::from_ptr(ptr as *mut alpm_conflict_t)
    }
}

unsafe impl<'a, 'b> IntoAlpmListItem<'a, 'b> for Db<'a> {
    type Borrow = Self;
    unsafe fn ptr_into_alpm_list_item(handle: &'a Alpm, ptr: *mut c_void) -> Self {
        Db::new(handle, ptr as *mut alpm_db_t)
    }
    unsafe fn ptr_as_alpm_list_item(handle: &'a Alpm, ptr: *mut c_void) -> Self::Borrow {
        Db::new(handle, ptr as *mut alpm_db_t)
    }
}

unsafe impl<'a, 'b> IntoAlpmListItem<'a, 'b> for DbMut<'a> {
    type Borrow = Self;
    unsafe fn ptr_into_alpm_list_item(handle: &'a Alpm, ptr: *mut c_void) -> Self {
        DbMut {
            inner: Db::new(handle, ptr as *mut alpm_db_t),
        }
    }
    unsafe fn ptr_as_alpm_list_item(handle: &'a Alpm, ptr: *mut c_void) -> Self::Borrow {
        DbMut {
            inner: Db::new(handle, ptr as *mut alpm_db_t),
        }
    }
}

unsafe impl<'a, 'b> IntoAlpmListItem<'a, 'b> for &'a str {
    type Borrow = Self;
    unsafe fn ptr_into_alpm_list_item(_handle: &'a Alpm, ptr: *mut c_void) -> Self {
        let s = CStr::from_ptr(ptr as *mut c_char);
        s.to_str().unwrap()
    }
    unsafe fn ptr_as_alpm_list_item(_handle: &'a Alpm, ptr: *mut c_void) -> Self::Borrow {
        let s = CStr::from_ptr(ptr as *mut c_char);
        s.to_str().unwrap()
    }
}

unsafe impl<'a, 'b> IntoAlpmListItem<'a, 'b> for String {
    type Borrow = &'b str;
    unsafe fn ptr_into_alpm_list_item(_handle: &'a Alpm, ptr: *mut c_void) -> Self {
        let s = CStr::from_ptr(ptr as *mut c_char);
        let s = s.to_str().unwrap().to_string();
        free(ptr);
        s
    }
    unsafe fn ptr_as_alpm_list_item(_handle: &'a Alpm, ptr: *mut c_void) -> Self::Borrow {
        let s = CStr::from_ptr(ptr as *mut c_char);
        s.to_str().unwrap()
    }
}

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

    #[test]
    fn test_depends_list_debug() {
        let handle = Alpm::new("/", "tests/db").unwrap();
        let db = handle.register_syncdb("core", SigLevel::NONE).unwrap();
        let pkg = db.pkg("linux").unwrap();

        println!("{:#?}", db.pkgs());
        println!("{:#?}", pkg.depends());
    }

    #[test]
    fn test_depends_list_free() {
        let handle = Alpm::new("/", "tests/db").unwrap();
        let db = handle.register_syncdb("core", SigLevel::NONE).unwrap();
        let pkg = db.pkg("linux").unwrap();
        let depends = pkg.depends();
        assert_eq!(depends.first().unwrap().to_string(), "coreutils");
    }

    #[test]
    fn test_is_empty() {
        let handle = Alpm::new("/", "tests/db").unwrap();
        let db = handle.register_syncdb("core", SigLevel::NONE).unwrap();
        let pkg = db.pkg("linux").unwrap();
        let depends = pkg.depends();
        assert!(!depends.is_empty());

        let pkg = db.pkg("tzdata").unwrap();
        let depends = pkg.depends();
        assert!(depends.is_empty());
    }

    #[test]
    fn test_string_list_free() {
        let handle = Alpm::new("/", "tests/db").unwrap();
        handle.register_syncdb("community", SigLevel::NONE).unwrap();
        handle.register_syncdb("extra", SigLevel::NONE).unwrap();
        let db = handle.register_syncdb("core", SigLevel::NONE).unwrap();
        let pkg = db.pkg("linux").unwrap();
        let required_by = pkg.required_by();
        assert_eq!("acpi_call", required_by.first().unwrap());
    }

    #[test]
    fn test_str_list_free() {
        let handle = Alpm::new("/", "tests/db").unwrap();
        let db = handle.register_syncdb("core", SigLevel::NONE).unwrap();
        let pkg = db.pkg("pacman").unwrap();
        let groups = pkg.groups();
        assert_eq!("base", groups.first().unwrap());
    }

    #[test]
    fn test_push() {
        let handle = Alpm::new("/", "tests/db").unwrap();
        let db = handle.register_syncdb("core", SigLevel::NONE).unwrap();
        let pkg = db.pkg("pacman").unwrap();

        let mut list = AlpmListMut::new(&handle);
        list.push(pkg);
        assert_eq!(list.first().unwrap().name(), "pacman");

        let mut list = AlpmListMut::new(&handle);
        list.push(Depend::new("a"));
        list.push(Depend::new("b"));
        list.push(Depend::new("c"));

        let mut list = AlpmListMut::new(&handle);
        list.push("a".to_string());
        list.push("b".to_string());
        list.push("c".to_string());

        let mut list = AlpmListMut::new(&handle);
        list.push("a".to_string());
        list.push_str("b");
        list.push_str("c");
    }

    #[test]
    fn test_retain() {
        let handle = Alpm::new("/", "tests/db").unwrap();
        let db = handle.register_syncdb("core", SigLevel::NONE).unwrap();
        let mut pkgs = db.pkgs().to_list_mut();
        pkgs.retain(|p| p.name().starts_with('a'));

        assert!(!pkgs.is_empty());
        pkgs.iter().for_each(|p| assert!(p.name().starts_with('a')));
    }

    #[test]
    fn test_into_raw_alpm_list() {
        let handle = Alpm::new("/", "tests/db").unwrap();
        let db = handle.register_syncdb("core", SigLevel::NONE).unwrap();
        let pkg = db.pkg("linux").unwrap();
        assert_eq!(handle.syncdbs().to_list_mut().remove_list(0).len(), 1);
        pkg.sync_new_version(handle.syncdbs());
        pkg.sync_new_version(&handle.syncdbs().to_list_mut().remove_list(0));
        pkg.sync_new_version(vec![db].into_iter());
        pkg.sync_new_version(vec![db].iter());
    }

    #[test]
    fn test_into_raw_alpm_list2() {
        let mut handle = Alpm::new("/", "tests/db").unwrap();

        let list = vec![Depend::new("foo")];
        handle.set_assume_installed(list.iter()).unwrap();
    }
}