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
// Take a look at the license at the top of the repository in the LICENSE file.

use std::{
    borrow::{Borrow, BorrowMut, ToOwned},
    fmt,
    marker::PhantomData,
    mem,
    ops::{Deref, DerefMut},
    ptr, str,
};

use crate::ffi;
use glib::{prelude::*, translate::*};
use once_cell::sync::Lazy;

/// [`CapsFeatures`][crate::CapsFeatures] can optionally be set on a [`Caps`][crate::Caps] to add requirements
/// for additional features for a specific [`Structure`][crate::Structure]. Caps structures with
/// the same name but with a non-equal set of caps features are not compatible.
/// If a pad supports multiple sets of features it has to add multiple equal
/// structures with different feature sets to the caps.
///
/// Empty [`CapsFeatures`][crate::CapsFeatures] are equivalent with the [`CapsFeatures`][crate::CapsFeatures] that only
/// contain `GST_CAPS_FEATURE_MEMORY_SYSTEM_MEMORY`. ANY [`CapsFeatures`][crate::CapsFeatures] as
/// created by [`new_any()`][Self::new_any()] are equal to any other [`CapsFeatures`][crate::CapsFeatures]
/// and can be used to specify that any [`CapsFeatures`][crate::CapsFeatures] would be supported, e.g.
/// for elements that don't touch buffer memory. [`Caps`][crate::Caps] with ANY [`CapsFeatures`][crate::CapsFeatures]
/// are considered non-fixed and during negotiation some [`CapsFeatures`][crate::CapsFeatures] have
/// to be selected.
///
/// Examples for caps features would be the requirement of a specific [`Memory`][crate::Memory]
/// types or the requirement of having a specific `GstMeta` on the buffer. Features
/// are given as a string of the format `memory:GstMemoryTypeName` or
/// `meta:GstMetaAPIName`.
#[doc(alias = "GstCapsFeatures")]
#[repr(transparent)]
pub struct CapsFeatures(ptr::NonNull<ffi::GstCapsFeatures>);
unsafe impl Send for CapsFeatures {}
unsafe impl Sync for CapsFeatures {}

impl CapsFeatures {
    /// Creates a new [`CapsFeatures`][crate::CapsFeatures] with the given features.
    /// The last argument must be [`None`].
    /// ## `feature1`
    /// name of first feature to set
    ///
    /// # Returns
    ///
    /// a new, empty [`CapsFeatures`][crate::CapsFeatures]
    #[doc(alias = "gst_caps_features_new")]
    pub fn new(features: impl IntoIterator<Item = impl IntoGStr>) -> Self {
        skip_assert_initialized!();
        let mut f = Self::new_empty();

        for feature in features {
            f.add(feature);
        }

        f
    }

    #[doc(alias = "gst_caps_features_new_id")]
    pub fn from_quarks(features: impl IntoIterator<Item = glib::Quark>) -> Self {
        skip_assert_initialized!();
        let mut f = Self::new_empty();

        for feature in features.into_iter() {
            f.add_from_quark(feature);
        }

        f
    }

    /// Creates a new, empty [`CapsFeatures`][crate::CapsFeatures].
    ///
    /// # Returns
    ///
    /// a new, empty [`CapsFeatures`][crate::CapsFeatures]
    #[doc(alias = "gst_caps_features_new_empty")]
    pub fn new_empty() -> Self {
        assert_initialized_main_thread!();
        unsafe {
            CapsFeatures(ptr::NonNull::new_unchecked(
                ffi::gst_caps_features_new_empty(),
            ))
        }
    }

    /// Creates a new, ANY [`CapsFeatures`][crate::CapsFeatures]. This will be equal
    /// to any other [`CapsFeatures`][crate::CapsFeatures] but caps with these are
    /// unfixed.
    ///
    /// # Returns
    ///
    /// a new, ANY [`CapsFeatures`][crate::CapsFeatures]
    #[doc(alias = "gst_caps_features_new_any")]
    pub fn new_any() -> Self {
        assert_initialized_main_thread!();
        unsafe { CapsFeatures(ptr::NonNull::new_unchecked(ffi::gst_caps_features_new_any())) }
    }
}

impl IntoGlibPtr<*mut ffi::GstCapsFeatures> for CapsFeatures {
    #[inline]
    unsafe fn into_glib_ptr(self) -> *mut ffi::GstCapsFeatures {
        let s = mem::ManuallyDrop::new(self);
        s.0.as_ptr()
    }
}

impl Deref for CapsFeatures {
    type Target = CapsFeaturesRef;

    #[inline]
    fn deref(&self) -> &CapsFeaturesRef {
        unsafe { &*(self.0.as_ref() as *const ffi::GstCapsFeatures as *const CapsFeaturesRef) }
    }
}

impl DerefMut for CapsFeatures {
    #[inline]
    fn deref_mut(&mut self) -> &mut CapsFeaturesRef {
        unsafe { &mut *(self.0.as_mut() as *mut ffi::GstCapsFeatures as *mut CapsFeaturesRef) }
    }
}

impl AsRef<CapsFeaturesRef> for CapsFeatures {
    #[inline]
    fn as_ref(&self) -> &CapsFeaturesRef {
        self.deref()
    }
}

impl AsMut<CapsFeaturesRef> for CapsFeatures {
    #[inline]
    fn as_mut(&mut self) -> &mut CapsFeaturesRef {
        self.deref_mut()
    }
}

impl Clone for CapsFeatures {
    #[inline]
    fn clone(&self) -> Self {
        unsafe {
            let ptr = ffi::gst_caps_features_copy(self.0.as_ref());
            debug_assert!(!ptr.is_null());
            CapsFeatures(ptr::NonNull::new_unchecked(ptr))
        }
    }
}

impl Drop for CapsFeatures {
    #[inline]
    fn drop(&mut self) {
        unsafe { ffi::gst_caps_features_free(self.0.as_mut()) }
    }
}

impl fmt::Debug for CapsFeatures {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("CapsFeatures")
            .field(&self.to_string())
            .finish()
    }
}

impl fmt::Display for CapsFeatures {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // Need to make sure to not call ToString::to_string() here, which
        // we have because of the Display impl. We need CapsFeaturesRef::to_string()
        f.write_str(&CapsFeaturesRef::to_string(self.as_ref()))
    }
}

impl str::FromStr for CapsFeatures {
    type Err = glib::BoolError;

    #[doc(alias = "gst_caps_features_from_string")]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        assert_initialized_main_thread!();
        unsafe {
            let ptr = s.run_with_gstr(|s| ffi::gst_caps_features_from_string(s.as_ptr()));
            if ptr.is_null() {
                return Err(glib::bool_error!(
                    "Failed to parse caps features from string"
                ));
            }

            Ok(Self(ptr::NonNull::new_unchecked(ptr)))
        }
    }
}

impl Borrow<CapsFeaturesRef> for CapsFeatures {
    #[inline]
    fn borrow(&self) -> &CapsFeaturesRef {
        self.as_ref()
    }
}

impl BorrowMut<CapsFeaturesRef> for CapsFeatures {
    #[inline]
    fn borrow_mut(&mut self) -> &mut CapsFeaturesRef {
        self.as_mut()
    }
}

impl glib::types::StaticType for CapsFeatures {
    #[inline]
    fn static_type() -> glib::types::Type {
        unsafe { from_glib(ffi::gst_caps_features_get_type()) }
    }
}

impl<'a> ToGlibPtr<'a, *const ffi::GstCapsFeatures> for CapsFeatures {
    type Storage = PhantomData<&'a Self>;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, *const ffi::GstCapsFeatures, Self> {
        unsafe { Stash(self.0.as_ref(), PhantomData) }
    }

    #[inline]
    fn to_glib_full(&self) -> *const ffi::GstCapsFeatures {
        unsafe { ffi::gst_caps_features_copy(self.0.as_ref()) }
    }
}

impl<'a> ToGlibPtr<'a, *mut ffi::GstCapsFeatures> for CapsFeatures {
    type Storage = PhantomData<&'a Self>;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, *mut ffi::GstCapsFeatures, Self> {
        unsafe {
            Stash(
                self.0.as_ref() as *const ffi::GstCapsFeatures as *mut ffi::GstCapsFeatures,
                PhantomData,
            )
        }
    }

    #[inline]
    fn to_glib_full(&self) -> *mut ffi::GstCapsFeatures {
        unsafe { ffi::gst_caps_features_copy(self.0.as_ref()) }
    }
}

impl<'a> ToGlibPtrMut<'a, *mut ffi::GstCapsFeatures> for CapsFeatures {
    type Storage = PhantomData<&'a mut Self>;

    #[inline]
    fn to_glib_none_mut(&'a mut self) -> StashMut<*mut ffi::GstCapsFeatures, Self> {
        unsafe { StashMut(self.0.as_mut(), PhantomData) }
    }
}

impl FromGlibPtrNone<*const ffi::GstCapsFeatures> for CapsFeatures {
    #[inline]
    unsafe fn from_glib_none(ptr: *const ffi::GstCapsFeatures) -> Self {
        debug_assert!(!ptr.is_null());
        let ptr = ffi::gst_caps_features_copy(ptr);
        debug_assert!(!ptr.is_null());
        CapsFeatures(ptr::NonNull::new_unchecked(ptr))
    }
}

impl FromGlibPtrNone<*mut ffi::GstCapsFeatures> for CapsFeatures {
    #[inline]
    unsafe fn from_glib_none(ptr: *mut ffi::GstCapsFeatures) -> Self {
        debug_assert!(!ptr.is_null());
        let ptr = ffi::gst_caps_features_copy(ptr);
        debug_assert!(!ptr.is_null());
        CapsFeatures(ptr::NonNull::new_unchecked(ptr))
    }
}

impl FromGlibPtrFull<*const ffi::GstCapsFeatures> for CapsFeatures {
    #[inline]
    unsafe fn from_glib_full(ptr: *const ffi::GstCapsFeatures) -> Self {
        debug_assert!(!ptr.is_null());
        CapsFeatures(ptr::NonNull::new_unchecked(
            ptr as *mut ffi::GstCapsFeatures,
        ))
    }
}

impl FromGlibPtrFull<*mut ffi::GstCapsFeatures> for CapsFeatures {
    #[inline]
    unsafe fn from_glib_full(ptr: *mut ffi::GstCapsFeatures) -> Self {
        debug_assert!(!ptr.is_null());
        CapsFeatures(ptr::NonNull::new_unchecked(ptr))
    }
}

impl glib::value::ValueType for CapsFeatures {
    type Type = Self;
}

impl glib::value::ValueTypeOptional for CapsFeatures {}

unsafe impl<'a> glib::value::FromValue<'a> for CapsFeatures {
    type Checker = glib::value::GenericValueTypeOrNoneChecker<Self>;

    unsafe fn from_value(value: &'a glib::Value) -> Self {
        skip_assert_initialized!();
        from_glib_none(glib::gobject_ffi::g_value_get_boxed(value.to_glib_none().0)
            as *mut ffi::GstCapsFeatures)
    }
}

impl glib::value::ToValue for CapsFeatures {
    fn to_value(&self) -> glib::Value {
        let mut value = glib::Value::for_value_type::<Self>();
        unsafe {
            glib::gobject_ffi::g_value_set_boxed(
                value.to_glib_none_mut().0,
                ToGlibPtr::<*mut ffi::GstCapsFeatures>::to_glib_none(self).0 as *mut _,
            )
        }
        value
    }

    fn value_type(&self) -> glib::Type {
        Self::static_type()
    }
}

impl glib::value::ToValueOptional for CapsFeatures {
    fn to_value_optional(s: Option<&Self>) -> glib::Value {
        skip_assert_initialized!();
        let mut value = glib::Value::for_value_type::<Self>();
        unsafe {
            glib::gobject_ffi::g_value_set_boxed(
                value.to_glib_none_mut().0,
                ToGlibPtr::<*mut ffi::GstCapsFeatures>::to_glib_none(&s).0 as *mut _,
            )
        }
        value
    }
}

impl From<CapsFeatures> for glib::Value {
    fn from(v: CapsFeatures) -> glib::Value {
        skip_assert_initialized!();
        let mut value = glib::Value::for_value_type::<CapsFeatures>();
        unsafe {
            glib::gobject_ffi::g_value_take_boxed(
                value.to_glib_none_mut().0,
                IntoGlibPtr::<*mut ffi::GstCapsFeatures>::into_glib_ptr(v) as *mut _,
            )
        }
        value
    }
}

impl GlibPtrDefault for CapsFeatures {
    type GlibType = *mut ffi::GstCapsFeatures;
}

unsafe impl TransparentPtrType for CapsFeatures {}

#[repr(transparent)]
#[doc(alias = "GstCapsFeatures")]
pub struct CapsFeaturesRef(ffi::GstCapsFeatures);

impl CapsFeaturesRef {
    #[inline]
    pub unsafe fn from_glib_borrow<'a>(ptr: *const ffi::GstCapsFeatures) -> &'a CapsFeaturesRef {
        debug_assert!(!ptr.is_null());

        &*(ptr as *mut CapsFeaturesRef)
    }

    #[inline]
    pub unsafe fn from_glib_borrow_mut<'a>(
        ptr: *mut ffi::GstCapsFeatures,
    ) -> &'a mut CapsFeaturesRef {
        debug_assert!(!ptr.is_null());

        &mut *(ptr as *mut CapsFeaturesRef)
    }

    #[inline]
    pub fn as_ptr(&self) -> *const ffi::GstCapsFeatures {
        self as *const Self as *const ffi::GstCapsFeatures
    }

    #[inline]
    pub fn as_mut_ptr(&self) -> *mut ffi::GstCapsFeatures {
        self as *const Self as *mut ffi::GstCapsFeatures
    }

    pub fn is_empty(&self) -> bool {
        self.size() == 0 && !self.is_any()
    }

    #[doc(alias = "gst_caps_features_is_any")]
    pub fn is_any(&self) -> bool {
        unsafe { from_glib(ffi::gst_caps_features_is_any(self.as_ptr())) }
    }

    #[doc(alias = "gst_caps_features_contains")]
    pub fn contains(&self, feature: impl IntoGStr) -> bool {
        unsafe {
            feature.run_with_gstr(|feature| {
                from_glib(ffi::gst_caps_features_contains(
                    self.as_ptr(),
                    feature.as_ptr(),
                ))
            })
        }
    }

    #[doc(alias = "gst_caps_features_contains_id")]
    pub fn contains_quark(&self, feature: glib::Quark) -> bool {
        unsafe {
            from_glib(ffi::gst_caps_features_contains_id(
                self.as_ptr(),
                feature.into_glib(),
            ))
        }
    }

    #[doc(alias = "get_size")]
    #[doc(alias = "gst_caps_features_get_size")]
    pub fn size(&self) -> usize {
        unsafe { ffi::gst_caps_features_get_size(self.as_ptr()) as usize }
    }

    #[doc(alias = "get_nth")]
    #[doc(alias = "gst_caps_features_get_nth")]
    pub fn nth(&self, idx: usize) -> Option<&glib::GStr> {
        if idx >= self.size() {
            return None;
        }

        unsafe {
            let feature = ffi::gst_caps_features_get_nth(self.as_ptr(), idx as u32);
            if feature.is_null() {
                return None;
            }

            Some(glib::GStr::from_ptr(feature))
        }
    }

    #[doc(alias = "gst_caps_features_get_nth_id")]
    pub fn nth_quark(&self, idx: usize) -> Option<glib::Quark> {
        if idx >= self.size() {
            return None;
        }

        unsafe {
            let feature = ffi::gst_caps_features_get_nth_id(self.as_ptr(), idx as u32);
            Some(from_glib(feature))
        }
    }

    #[doc(alias = "gst_caps_features_add")]
    pub fn add(&mut self, feature: impl IntoGStr) {
        unsafe {
            feature.run_with_gstr(|feature| {
                ffi::gst_caps_features_add(self.as_mut_ptr(), feature.as_ptr())
            })
        }
    }

    #[doc(alias = "gst_caps_features_remove")]
    pub fn remove(&mut self, feature: impl IntoGStr) {
        unsafe {
            feature.run_with_gstr(|feature| {
                ffi::gst_caps_features_remove(self.as_mut_ptr(), feature.as_ptr())
            })
        }
    }

    #[doc(alias = "gst_caps_features_add_id")]
    pub fn add_from_quark(&mut self, feature: glib::Quark) {
        unsafe { ffi::gst_caps_features_add_id(self.as_mut_ptr(), feature.into_glib()) }
    }

    #[doc(alias = "gst_caps_features_remove_id")]
    pub fn remove_by_quark(&mut self, feature: glib::Quark) {
        unsafe { ffi::gst_caps_features_remove_id(self.as_mut_ptr(), feature.into_glib()) }
    }

    pub fn iter(&self) -> Iter {
        Iter::new(self)
    }

    // This is not an equivalence relation with regards to ANY. Everything is equal to ANY
    #[doc(alias = "gst_caps_features_is_equal")]
    pub fn is_equal(&self, other: &CapsFeaturesRef) -> bool {
        unsafe {
            from_glib(ffi::gst_caps_features_is_equal(
                self.as_ptr(),
                other.as_ptr(),
            ))
        }
    }
}

impl glib::types::StaticType for CapsFeaturesRef {
    #[inline]
    fn static_type() -> glib::types::Type {
        unsafe { from_glib(ffi::gst_structure_get_type()) }
    }
}

impl<'a> std::iter::Extend<&'a str> for CapsFeaturesRef {
    fn extend<T: IntoIterator<Item = &'a str>>(&mut self, iter: T) {
        iter.into_iter().for_each(|f| self.add(f));
    }
}

impl<'a> std::iter::Extend<&'a glib::GStr> for CapsFeaturesRef {
    fn extend<T: IntoIterator<Item = &'a glib::GStr>>(&mut self, iter: T) {
        iter.into_iter().for_each(|f| self.add(f));
    }
}

impl std::iter::Extend<String> for CapsFeaturesRef {
    fn extend<T: IntoIterator<Item = String>>(&mut self, iter: T) {
        iter.into_iter().for_each(|f| self.add(&f));
    }
}

impl std::iter::Extend<glib::GString> for CapsFeaturesRef {
    fn extend<T: IntoIterator<Item = glib::GString>>(&mut self, iter: T) {
        iter.into_iter().for_each(|f| self.add(&f));
    }
}

impl std::iter::Extend<glib::Quark> for CapsFeaturesRef {
    fn extend<T: IntoIterator<Item = glib::Quark>>(&mut self, iter: T) {
        iter.into_iter().for_each(|f| self.add_from_quark(f));
    }
}

unsafe impl<'a> glib::value::FromValue<'a> for &'a CapsFeaturesRef {
    type Checker = glib::value::GenericValueTypeOrNoneChecker<Self>;

    unsafe fn from_value(value: &'a glib::Value) -> Self {
        skip_assert_initialized!();
        &*(glib::gobject_ffi::g_value_get_boxed(value.to_glib_none().0) as *const CapsFeaturesRef)
    }
}

impl glib::value::ToValue for CapsFeaturesRef {
    fn to_value(&self) -> glib::Value {
        let mut value = glib::Value::for_value_type::<CapsFeatures>();
        unsafe {
            glib::gobject_ffi::g_value_set_boxed(
                value.to_glib_none_mut().0,
                self.as_mut_ptr() as *mut _,
            )
        }
        value
    }

    fn value_type(&self) -> glib::Type {
        Self::static_type()
    }
}

impl glib::value::ToValueOptional for CapsFeaturesRef {
    fn to_value_optional(s: Option<&Self>) -> glib::Value {
        skip_assert_initialized!();
        let mut value = glib::Value::for_value_type::<CapsFeatures>();
        unsafe {
            glib::gobject_ffi::g_value_set_boxed(
                value.to_glib_none_mut().0,
                s.map(|s| s.as_mut_ptr()).unwrap_or(ptr::null_mut()) as *mut _,
            )
        }
        value
    }
}

#[derive(Debug)]
pub struct Iter<'a> {
    caps_features: &'a CapsFeaturesRef,
    idx: usize,
    n_features: usize,
}

impl<'a> Iter<'a> {
    fn new(caps_features: &'a CapsFeaturesRef) -> Iter<'a> {
        skip_assert_initialized!();
        let n_features = caps_features.size();

        Iter {
            caps_features,
            idx: 0,
            n_features,
        }
    }
}

impl<'a> Iterator for Iter<'a> {
    type Item = &'a glib::GStr;

    fn next(&mut self) -> Option<Self::Item> {
        if self.idx >= self.n_features {
            return None;
        }

        unsafe {
            let feature =
                ffi::gst_caps_features_get_nth(self.caps_features.as_ptr(), self.idx as u32);
            debug_assert!(!feature.is_null());

            self.idx += 1;

            Some(glib::GStr::from_ptr(feature))
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.n_features - self.idx;

        (remaining, Some(remaining))
    }

    fn count(self) -> usize {
        self.n_features - self.idx
    }

    // checker-ignore-item
    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        let (end, overflow) = self.idx.overflowing_add(n);
        if end >= self.n_features || overflow {
            self.idx = self.n_features;
            None
        } else {
            unsafe {
                self.idx = end + 1;
                let feature =
                    ffi::gst_caps_features_get_nth(self.caps_features.as_ptr(), end as u32);
                debug_assert!(!feature.is_null());
                Some(glib::GStr::from_ptr(feature))
            }
        }
    }

    fn last(self) -> Option<Self::Item> {
        if self.idx == self.n_features {
            None
        } else {
            unsafe {
                let feature = ffi::gst_caps_features_get_nth(
                    self.caps_features.as_ptr(),
                    self.n_features as u32 - 1,
                );
                debug_assert!(!feature.is_null());
                Some(glib::GStr::from_ptr(feature))
            }
        }
    }
}

impl<'a> DoubleEndedIterator for Iter<'a> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.idx == self.n_features {
            return None;
        }

        self.n_features -= 1;

        unsafe {
            let feature =
                ffi::gst_caps_features_get_nth(self.caps_features.as_ptr(), self.n_features as u32);
            debug_assert!(!feature.is_null());

            Some(glib::GStr::from_ptr(feature))
        }
    }

    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
        let (end, overflow) = self.n_features.overflowing_sub(n);
        if end <= self.idx || overflow {
            self.idx = self.n_features;
            None
        } else {
            unsafe {
                self.n_features = end - 1;
                let feature = ffi::gst_caps_features_get_nth(
                    self.caps_features.as_ptr(),
                    self.n_features as u32,
                );
                debug_assert!(!feature.is_null());

                Some(glib::GStr::from_ptr(feature))
            }
        }
    }
}

impl<'a> ExactSizeIterator for Iter<'a> {}

impl<'a> std::iter::FusedIterator for Iter<'a> {}

impl<'a> IntoIterator for &'a CapsFeaturesRef {
    type IntoIter = Iter<'a>;
    type Item = &'a glib::GStr;

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

impl<'a> From<&'a str> for CapsFeatures {
    fn from(value: &'a str) -> Self {
        skip_assert_initialized!();
        let mut features = CapsFeatures::new_empty();

        features.add(value);

        features
    }
}

impl<'a> From<&'a glib::GStr> for CapsFeatures {
    fn from(value: &'a glib::GStr) -> Self {
        skip_assert_initialized!();
        let mut features = CapsFeatures::new_empty();

        features.add(value);

        features
    }
}

impl From<glib::Quark> for CapsFeatures {
    fn from(value: glib::Quark) -> Self {
        skip_assert_initialized!();
        let mut features = CapsFeatures::new_empty();

        features.add_from_quark(value);

        features
    }
}

impl<'a, const N: usize> From<[&'a str; N]> for CapsFeatures {
    fn from(value: [&'a str; N]) -> Self {
        skip_assert_initialized!();
        let mut features = CapsFeatures::new_empty();

        value.into_iter().for_each(|f| features.add(f));

        features
    }
}

impl<'a, const N: usize> From<[&'a glib::GStr; N]> for CapsFeatures {
    fn from(value: [&'a glib::GStr; N]) -> Self {
        skip_assert_initialized!();
        let mut features = CapsFeatures::new_empty();

        value.into_iter().for_each(|f| features.add(f));

        features
    }
}

impl<const N: usize> From<[String; N]> for CapsFeatures {
    fn from(value: [String; N]) -> Self {
        skip_assert_initialized!();
        let mut features = CapsFeatures::new_empty();

        value.into_iter().for_each(|f| features.add(&f));

        features
    }
}

impl<const N: usize> From<[glib::GString; N]> for CapsFeatures {
    fn from(value: [glib::GString; N]) -> Self {
        skip_assert_initialized!();
        let mut features = CapsFeatures::new_empty();

        value.into_iter().for_each(|f| features.add(&f));

        features
    }
}

impl<const N: usize> From<[glib::Quark; N]> for CapsFeatures {
    fn from(value: [glib::Quark; N]) -> Self {
        skip_assert_initialized!();
        let mut features = CapsFeatures::new_empty();

        value.into_iter().for_each(|f| features.add_from_quark(f));

        features
    }
}

impl<'a> std::iter::FromIterator<&'a str> for CapsFeatures {
    fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
        skip_assert_initialized!();
        let mut features = CapsFeatures::new_empty();

        iter.into_iter().for_each(|f| features.add(f));

        features
    }
}

impl<'a> std::iter::FromIterator<&'a glib::GStr> for CapsFeatures {
    fn from_iter<T: IntoIterator<Item = &'a glib::GStr>>(iter: T) -> Self {
        assert_initialized_main_thread!();

        let mut features = CapsFeatures::new_empty();

        iter.into_iter().for_each(|f| features.add(f));

        features
    }
}

impl std::iter::FromIterator<String> for CapsFeatures {
    fn from_iter<T: IntoIterator<Item = String>>(iter: T) -> Self {
        skip_assert_initialized!();
        let mut features = CapsFeatures::new_empty();

        iter.into_iter().for_each(|f| features.add(&f));

        features
    }
}

impl std::iter::FromIterator<glib::GString> for CapsFeatures {
    fn from_iter<T: IntoIterator<Item = glib::GString>>(iter: T) -> Self {
        assert_initialized_main_thread!();

        let mut features = CapsFeatures::new_empty();

        iter.into_iter().for_each(|f| features.add(&f));

        features
    }
}

impl std::iter::FromIterator<glib::Quark> for CapsFeatures {
    fn from_iter<T: IntoIterator<Item = glib::Quark>>(iter: T) -> Self {
        skip_assert_initialized!();
        let mut features = CapsFeatures::new_empty();

        iter.into_iter().for_each(|f| features.add_from_quark(f));

        features
    }
}

impl fmt::Debug for CapsFeaturesRef {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("CapsFeatures")
            .field(&self.to_string())
            .finish()
    }
}

impl fmt::Display for CapsFeaturesRef {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let s = unsafe {
            glib::GString::from_glib_full(ffi::gst_caps_features_to_string(self.as_ptr()))
        };
        f.write_str(&s)
    }
}

impl ToOwned for CapsFeaturesRef {
    type Owned = CapsFeatures;

    #[inline]
    fn to_owned(&self) -> CapsFeatures {
        unsafe { from_glib_full(ffi::gst_caps_features_copy(self.as_ptr() as *const _) as *mut _) }
    }
}

unsafe impl Sync for CapsFeaturesRef {}
unsafe impl Send for CapsFeaturesRef {}

pub static CAPS_FEATURE_MEMORY_SYSTEM_MEMORY: &glib::GStr =
    unsafe { glib::GStr::from_utf8_with_nul_unchecked(ffi::GST_CAPS_FEATURE_MEMORY_SYSTEM_MEMORY) };
pub static CAPS_FEATURES_MEMORY_SYSTEM_MEMORY: Lazy<CapsFeatures> =
    Lazy::new(|| CapsFeatures::new([CAPS_FEATURE_MEMORY_SYSTEM_MEMORY]));

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

    #[test]
    fn test_from_value_optional() {
        use glib::value::ToValue;

        crate::init().unwrap();

        let a = None::<CapsFeatures>.to_value();
        assert!(a.get::<Option<CapsFeatures>>().unwrap().is_none());
        let b = glib::value::Value::from(&CapsFeatures::new_empty());
        assert!(b.get::<Option<CapsFeatures>>().unwrap().is_some());
    }
}