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
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
// Take a look at the license at the top of the repository in the LICENSE file.

use std::{cmp, fmt, ops, slice};

use glib::{prelude::*, translate::*};
use num_rational::Rational32;

#[derive(Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct Fraction(pub Rational32);

impl Fraction {
    // rustdoc-stripper-ignore-next
    /// Creates a new `Ratio`.
    ///
    /// # Panics
    ///
    /// Panics if `denom` is zero.
    #[inline]
    pub fn new(numer: i32, denom: i32) -> Self {
        skip_assert_initialized!();
        (numer, denom).into()
    }

    // rustdoc-stripper-ignore-next
    /// Creates a `Fraction` without checking for `denom == 0` or reducing.
    ///
    /// While this does not panic, there are several methods that will panic
    /// if used on a `Fraction` with `denom == 0`.
    #[inline]
    pub const fn new_raw(numer: i32, denom: i32) -> Self {
        skip_assert_initialized!();
        Self(Rational32::new_raw(numer, denom))
    }

    // rustdoc-stripper-ignore-next
    /// Creates a `Fraction` representing the integer `t`.
    #[inline]
    pub const fn from_integer(t: i32) -> Self {
        skip_assert_initialized!();
        Self::new_raw(t, 1)
    }

    pub fn approximate_f32(x: f32) -> Option<Self> {
        skip_assert_initialized!();
        Rational32::approximate_float(x).map(|r| r.into())
    }

    pub fn approximate_f64(x: f64) -> Option<Self> {
        skip_assert_initialized!();
        Rational32::approximate_float(x).map(|r| r.into())
    }

    #[inline]
    pub fn numer(&self) -> i32 {
        *self.0.numer()
    }

    #[inline]
    pub fn denom(&self) -> i32 {
        *self.0.denom()
    }

    #[cfg(feature = "v1_24")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v1_24")))]
    #[doc(alias = "gst_util_simplify_fraction")]
    pub fn simplify(&mut self, n_terms: u32, threshold: u32) {
        skip_assert_initialized!();
        unsafe {
            let mut numer = self.numer();
            let mut denom = self.denom();
            ffi::gst_util_simplify_fraction(&mut numer, &mut denom, n_terms, threshold);
            *self = Self::new(numer, denom);
        }
    }
}

impl fmt::Display for Fraction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl ops::Deref for Fraction {
    type Target = Rational32;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl ops::DerefMut for Fraction {
    #[inline]
    fn deref_mut(&mut self) -> &mut Rational32 {
        &mut self.0
    }
}

impl AsRef<Rational32> for Fraction {
    #[inline]
    fn as_ref(&self) -> &Rational32 {
        &self.0
    }
}

macro_rules! impl_fraction_binop {
    ($name:ident, $f:ident, $name_assign:ident, $f_assign:ident) => {
        impl ops::$name<Fraction> for Fraction {
            type Output = Fraction;

            #[inline]
            fn $f(self, other: Fraction) -> Self::Output {
                Fraction((self.0).$f(other.0))
            }
        }

        impl ops::$name<Fraction> for &Fraction {
            type Output = Fraction;

            #[inline]
            fn $f(self, other: Fraction) -> Self::Output {
                Fraction((self.0).$f(other.0))
            }
        }

        impl ops::$name<&Fraction> for Fraction {
            type Output = Fraction;

            #[inline]
            fn $f(self, other: &Fraction) -> Self::Output {
                Fraction((self.0).$f(other.0))
            }
        }

        impl ops::$name<&Fraction> for &Fraction {
            type Output = Fraction;

            #[inline]
            fn $f(self, other: &Fraction) -> Self::Output {
                Fraction((self.0).$f(other.0))
            }
        }

        impl ops::$name<i32> for Fraction {
            type Output = Fraction;

            #[inline]
            fn $f(self, other: i32) -> Self::Output {
                self.$f(Fraction::from(other))
            }
        }

        impl ops::$name<i32> for &Fraction {
            type Output = Fraction;

            #[inline]
            fn $f(self, other: i32) -> Self::Output {
                self.$f(Fraction::from(other))
            }
        }

        impl ops::$name<&i32> for Fraction {
            type Output = Fraction;

            #[inline]
            fn $f(self, other: &i32) -> Self::Output {
                self.$f(Fraction::from(*other))
            }
        }

        impl ops::$name<&i32> for &Fraction {
            type Output = Fraction;

            #[inline]
            fn $f(self, other: &i32) -> Self::Output {
                self.$f(Fraction::from(*other))
            }
        }

        impl ops::$name<Fraction> for i32 {
            type Output = Fraction;

            #[inline]
            fn $f(self, other: Fraction) -> Self::Output {
                Fraction::from(self).$f(other)
            }
        }

        impl ops::$name<&Fraction> for i32 {
            type Output = Fraction;

            #[inline]
            fn $f(self, other: &Fraction) -> Self::Output {
                Fraction::from(self).$f(other)
            }
        }

        impl ops::$name<Fraction> for &i32 {
            type Output = Fraction;

            #[inline]
            fn $f(self, other: Fraction) -> Self::Output {
                Fraction::from(*self).$f(other)
            }
        }

        impl ops::$name<&Fraction> for &i32 {
            type Output = Fraction;

            #[inline]
            fn $f(self, other: &Fraction) -> Self::Output {
                Fraction::from(*self).$f(other)
            }
        }

        impl ops::$name_assign<Fraction> for Fraction {
            #[inline]
            fn $f_assign(&mut self, other: Fraction) {
                (self.0).$f_assign(other.0)
            }
        }

        impl ops::$name_assign<&Fraction> for Fraction {
            #[inline]
            fn $f_assign(&mut self, other: &Fraction) {
                (self.0).$f_assign(other.0)
            }
        }

        impl ops::$name_assign<i32> for Fraction {
            #[inline]
            fn $f_assign(&mut self, other: i32) {
                (self.0).$f_assign(other)
            }
        }

        impl ops::$name_assign<&i32> for Fraction {
            #[inline]
            fn $f_assign(&mut self, other: &i32) {
                (self.0).$f_assign(other)
            }
        }
    };
}

impl_fraction_binop!(Add, add, AddAssign, add_assign);
impl_fraction_binop!(Sub, sub, SubAssign, sub_assign);
impl_fraction_binop!(Div, div, DivAssign, div_assign);
impl_fraction_binop!(Mul, mul, MulAssign, mul_assign);
impl_fraction_binop!(Rem, rem, RemAssign, rem_assign);

impl ops::Neg for Fraction {
    type Output = Fraction;

    #[inline]
    fn neg(self) -> Self::Output {
        Fraction(self.0.neg())
    }
}

impl ops::Neg for &Fraction {
    type Output = Fraction;

    #[inline]
    fn neg(self) -> Self::Output {
        Fraction(self.0.neg())
    }
}

impl From<i32> for Fraction {
    #[inline]
    fn from(x: i32) -> Self {
        skip_assert_initialized!();
        Fraction(x.into())
    }
}

impl From<(i32, i32)> for Fraction {
    #[inline]
    fn from(x: (i32, i32)) -> Self {
        skip_assert_initialized!();
        Fraction(x.into())
    }
}

impl From<Fraction> for (i32, i32) {
    #[inline]
    fn from(f: Fraction) -> Self {
        skip_assert_initialized!();
        f.0.into()
    }
}

impl From<Rational32> for Fraction {
    #[inline]
    fn from(x: Rational32) -> Self {
        skip_assert_initialized!();
        Fraction(x)
    }
}

impl From<Fraction> for Rational32 {
    #[inline]
    fn from(x: Fraction) -> Self {
        skip_assert_initialized!();
        x.0
    }
}

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

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

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

    #[inline]
    unsafe fn from_value(value: &'a glib::Value) -> Self {
        skip_assert_initialized!();
        let n = ffi::gst_value_get_fraction_numerator(value.to_glib_none().0);
        let d = ffi::gst_value_get_fraction_denominator(value.to_glib_none().0);

        Fraction::new(n, d)
    }
}

impl glib::value::ToValue for Fraction {
    #[inline]
    fn to_value(&self) -> glib::Value {
        let mut value = glib::Value::for_value_type::<Self>();
        unsafe {
            ffi::gst_value_set_fraction(value.to_glib_none_mut().0, self.numer(), self.denom());
        }
        value
    }

    #[inline]
    fn value_type(&self) -> glib::Type {
        Self::static_type()
    }
}

impl From<Fraction> for glib::Value {
    #[inline]
    fn from(v: Fraction) -> glib::Value {
        skip_assert_initialized!();
        glib::value::ToValue::to_value(&v)
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct IntRange<T> {
    min: T,
    max: T,
    step: T,
}

impl<T: Copy> IntRange<T> {
    #[inline]
    pub fn min(&self) -> T {
        self.min
    }

    #[inline]
    pub fn max(&self) -> T {
        self.max
    }

    #[inline]
    pub fn step(&self) -> T {
        self.step
    }
}

#[doc(hidden)]
pub trait IntRangeType: Sized + Clone + Copy + 'static {
    fn with_min_max(min: Self, max: Self) -> IntRange<Self>;
    fn with_step(min: Self, max: Self, step: Self) -> IntRange<Self>;
}

impl IntRangeType for i32 {
    #[inline]
    fn with_min_max(min: i32, max: i32) -> IntRange<Self> {
        skip_assert_initialized!();
        IntRange { min, max, step: 1 }
    }

    #[inline]
    fn with_step(min: i32, max: i32, step: i32) -> IntRange<Self> {
        skip_assert_initialized!();

        assert!(min <= max);
        assert!(step > 0);

        IntRange { min, max, step }
    }
}

impl IntRangeType for i64 {
    #[inline]
    fn with_min_max(min: i64, max: i64) -> IntRange<Self> {
        skip_assert_initialized!();
        IntRange { min, max, step: 1 }
    }

    #[inline]
    fn with_step(min: i64, max: i64, step: i64) -> IntRange<Self> {
        skip_assert_initialized!();

        assert!(min <= max);
        assert!(step > 0);

        IntRange { min, max, step }
    }
}

impl<T: IntRangeType> IntRange<T> {
    #[inline]
    pub fn new(min: T, max: T) -> IntRange<T> {
        skip_assert_initialized!();
        T::with_min_max(min, max)
    }

    #[inline]
    pub fn with_step(min: T, max: T, step: T) -> IntRange<T> {
        skip_assert_initialized!();
        T::with_step(min, max, step)
    }
}

impl From<(i32, i32)> for IntRange<i32> {
    #[inline]
    fn from((min, max): (i32, i32)) -> Self {
        skip_assert_initialized!();
        Self::new(min, max)
    }
}

impl From<(i32, i32, i32)> for IntRange<i32> {
    #[inline]
    fn from((min, max, step): (i32, i32, i32)) -> Self {
        skip_assert_initialized!();
        Self::with_step(min, max, step)
    }
}

impl From<(i64, i64)> for IntRange<i64> {
    #[inline]
    fn from((min, max): (i64, i64)) -> Self {
        skip_assert_initialized!();
        Self::new(min, max)
    }
}

impl From<(i64, i64, i64)> for IntRange<i64> {
    #[inline]
    fn from((min, max, step): (i64, i64, i64)) -> Self {
        skip_assert_initialized!();
        Self::with_step(min, max, step)
    }
}

impl glib::types::StaticType for IntRange<i32> {
    #[inline]
    fn static_type() -> glib::types::Type {
        unsafe { from_glib(ffi::gst_int_range_get_type()) }
    }
}

impl glib::value::ValueType for IntRange<i32> {
    type Type = Self;
}

unsafe impl<'a> glib::value::FromValue<'a> for IntRange<i32> {
    type Checker = glib::value::GenericValueTypeChecker<Self>;

    #[inline]
    unsafe fn from_value(value: &'a glib::Value) -> Self {
        skip_assert_initialized!();
        let min = ffi::gst_value_get_int_range_min(value.to_glib_none().0);
        let max = ffi::gst_value_get_int_range_max(value.to_glib_none().0);
        let step = ffi::gst_value_get_int_range_step(value.to_glib_none().0);

        Self::with_step(min, max, step)
    }
}

impl glib::value::ToValue for IntRange<i32> {
    #[inline]
    fn to_value(&self) -> glib::Value {
        let mut value = glib::Value::for_value_type::<Self>();
        unsafe {
            ffi::gst_value_set_int_range_step(
                value.to_glib_none_mut().0,
                self.min(),
                self.max(),
                self.step(),
            );
        }
        value
    }

    #[inline]
    fn value_type(&self) -> glib::Type {
        Self::static_type()
    }
}

impl From<IntRange<i32>> for glib::Value {
    #[inline]
    fn from(v: IntRange<i32>) -> glib::Value {
        skip_assert_initialized!();
        glib::value::ToValue::to_value(&v)
    }
}

impl glib::types::StaticType for IntRange<i64> {
    #[inline]
    fn static_type() -> glib::types::Type {
        unsafe { from_glib(ffi::gst_int64_range_get_type()) }
    }
}

impl glib::value::ValueType for IntRange<i64> {
    type Type = Self;
}

unsafe impl<'a> glib::value::FromValue<'a> for IntRange<i64> {
    type Checker = glib::value::GenericValueTypeChecker<Self>;

    #[inline]
    unsafe fn from_value(value: &'a glib::Value) -> Self {
        skip_assert_initialized!();
        let min = ffi::gst_value_get_int64_range_min(value.to_glib_none().0);
        let max = ffi::gst_value_get_int64_range_max(value.to_glib_none().0);
        let step = ffi::gst_value_get_int64_range_step(value.to_glib_none().0);

        Self::with_step(min, max, step)
    }
}

impl glib::value::ToValue for IntRange<i64> {
    #[inline]
    fn to_value(&self) -> glib::Value {
        let mut value = glib::Value::for_value_type::<Self>();
        unsafe {
            ffi::gst_value_set_int64_range_step(
                value.to_glib_none_mut().0,
                self.min(),
                self.max(),
                self.step(),
            );
        }
        value
    }

    #[inline]
    fn value_type(&self) -> glib::Type {
        Self::static_type()
    }
}

impl From<IntRange<i64>> for glib::Value {
    #[inline]
    fn from(v: IntRange<i64>) -> glib::Value {
        skip_assert_initialized!();
        glib::value::ToValue::to_value(&v)
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FractionRange {
    min: Fraction,
    max: Fraction,
}

impl FractionRange {
    #[inline]
    pub fn new<T: Into<Fraction>, U: Into<Fraction>>(min: T, max: U) -> Self {
        skip_assert_initialized!();

        let min = min.into();
        let max = max.into();

        assert!(min <= max);

        FractionRange { min, max }
    }

    #[inline]
    pub fn min(&self) -> Fraction {
        self.min
    }

    #[inline]
    pub fn max(&self) -> Fraction {
        self.max
    }
}

impl From<(Fraction, Fraction)> for FractionRange {
    #[inline]
    fn from((min, max): (Fraction, Fraction)) -> Self {
        skip_assert_initialized!();

        Self::new(min, max)
    }
}

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

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

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

    #[inline]
    unsafe fn from_value(value: &'a glib::Value) -> Self {
        skip_assert_initialized!();
        let min = ffi::gst_value_get_fraction_range_min(value.to_glib_none().0);
        let max = ffi::gst_value_get_fraction_range_max(value.to_glib_none().0);

        let min_n = ffi::gst_value_get_fraction_numerator(min);
        let min_d = ffi::gst_value_get_fraction_denominator(min);
        let max_n = ffi::gst_value_get_fraction_numerator(max);
        let max_d = ffi::gst_value_get_fraction_denominator(max);

        Self::new((min_n, min_d), (max_n, max_d))
    }
}

impl glib::value::ToValue for FractionRange {
    #[inline]
    fn to_value(&self) -> glib::Value {
        let mut value = glib::Value::for_value_type::<Self>();
        unsafe {
            ffi::gst_value_set_fraction_range_full(
                value.to_glib_none_mut().0,
                self.min().numer(),
                self.min().denom(),
                self.max().numer(),
                self.max().denom(),
            );
        }
        value
    }

    #[inline]
    fn value_type(&self) -> glib::Type {
        Self::static_type()
    }
}

impl From<FractionRange> for glib::Value {
    #[inline]
    fn from(v: FractionRange) -> glib::Value {
        skip_assert_initialized!();
        glib::value::ToValue::to_value(&v)
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Bitmask(pub u64);

impl Bitmask {
    #[inline]
    pub fn new(v: u64) -> Self {
        skip_assert_initialized!();
        Bitmask(v)
    }
}

impl ops::Deref for Bitmask {
    type Target = u64;

    #[inline]
    fn deref(&self) -> &u64 {
        &self.0
    }
}

impl ops::DerefMut for Bitmask {
    #[inline]
    fn deref_mut(&mut self) -> &mut u64 {
        &mut self.0
    }
}

impl ops::BitAnd for Bitmask {
    type Output = Self;

    #[inline]
    fn bitand(self, rhs: Self) -> Self {
        Bitmask(self.0.bitand(rhs.0))
    }
}

impl ops::BitOr for Bitmask {
    type Output = Self;

    #[inline]
    fn bitor(self, rhs: Self) -> Self {
        Bitmask(self.0.bitor(rhs.0))
    }
}

impl ops::BitXor for Bitmask {
    type Output = Self;

    #[inline]
    fn bitxor(self, rhs: Self) -> Self {
        Bitmask(self.0.bitxor(rhs.0))
    }
}

impl ops::Not for Bitmask {
    type Output = Self;

    #[inline]
    fn not(self) -> Self {
        Bitmask(self.0.not())
    }
}

impl From<u64> for Bitmask {
    #[inline]
    fn from(v: u64) -> Self {
        skip_assert_initialized!();
        Self::new(v)
    }
}

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

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

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

    #[inline]
    unsafe fn from_value(value: &'a glib::Value) -> Self {
        skip_assert_initialized!();
        let v = ffi::gst_value_get_bitmask(value.to_glib_none().0);
        Self::new(v)
    }
}

impl glib::value::ToValue for Bitmask {
    #[inline]
    fn to_value(&self) -> glib::Value {
        let mut value = glib::Value::for_value_type::<Self>();
        unsafe {
            ffi::gst_value_set_bitmask(value.to_glib_none_mut().0, self.0);
        }
        value
    }

    #[inline]
    fn value_type(&self) -> glib::Type {
        Self::static_type()
    }
}

impl From<Bitmask> for glib::Value {
    #[inline]
    fn from(v: Bitmask) -> glib::Value {
        skip_assert_initialized!();
        glib::value::ToValue::to_value(&v)
    }
}

#[derive(Clone)]
pub struct Array(glib::SendValue);

unsafe impl Send for Array {}
unsafe impl Sync for Array {}

impl fmt::Debug for Array {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Array").field(&self.as_slice()).finish()
    }
}

impl Array {
    pub fn new(values: impl IntoIterator<Item = impl Into<glib::Value> + Send>) -> Self {
        assert_initialized_main_thread!();

        unsafe {
            let mut value = glib::Value::for_value_type::<Array>();
            for v in values.into_iter() {
                let mut v = v.into().into_raw();
                ffi::gst_value_array_append_and_take_value(value.to_glib_none_mut().0, &mut v);
            }

            Self(glib::SendValue::unsafe_from(value.into_raw()))
        }
    }

    pub fn from_values(values: impl IntoIterator<Item = glib::SendValue>) -> Self {
        skip_assert_initialized!();

        Self::new(values)
    }

    #[inline]
    pub fn as_slice(&self) -> &[glib::SendValue] {
        unsafe {
            let arr = (*self.0.as_ptr()).data[0].v_pointer as *const glib::ffi::GArray;
            if arr.is_null() || (*arr).len == 0 {
                &[]
            } else {
                #[allow(clippy::cast_ptr_alignment)]
                slice::from_raw_parts((*arr).data as *const glib::SendValue, (*arr).len as usize)
            }
        }
    }

    pub fn append_value(&mut self, value: glib::SendValue) {
        unsafe {
            ffi::gst_value_array_append_and_take_value(
                self.0.to_glib_none_mut().0,
                &mut value.into_raw(),
            );
        }
    }

    pub fn append(&mut self, value: impl Into<glib::Value> + Send) {
        self.append_value(glib::SendValue::from_owned(value));
    }
}

impl Default for Array {
    fn default() -> Self {
        skip_assert_initialized!();

        unsafe {
            let value = glib::Value::for_value_type::<Array>();

            Self(glib::SendValue::unsafe_from(value.into_raw()))
        }
    }
}

impl ops::Deref for Array {
    type Target = [glib::SendValue];

    #[inline]
    fn deref(&self) -> &[glib::SendValue] {
        self.as_slice()
    }
}

impl AsRef<[glib::SendValue]> for Array {
    #[inline]
    fn as_ref(&self) -> &[glib::SendValue] {
        self.as_slice()
    }
}

impl std::iter::FromIterator<glib::SendValue> for Array {
    fn from_iter<T: IntoIterator<Item = glib::SendValue>>(iter: T) -> Self {
        skip_assert_initialized!();
        Self::from_values(iter)
    }
}

impl std::iter::Extend<glib::SendValue> for Array {
    fn extend<T: IntoIterator<Item = glib::SendValue>>(&mut self, iter: T) {
        for v in iter.into_iter() {
            self.append_value(v);
        }
    }
}

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

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

    unsafe fn from_value(value: &'a glib::Value) -> Self {
        skip_assert_initialized!();
        Self(glib::SendValue::unsafe_from(value.clone().into_raw()))
    }
}

impl glib::value::ToValue for Array {
    fn to_value(&self) -> glib::Value {
        self.0.clone().into()
    }

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

impl From<Array> for glib::Value {
    fn from(v: Array) -> glib::Value {
        skip_assert_initialized!();
        v.0.into()
    }
}

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

#[derive(Debug, Clone)]
pub struct ArrayRef<'a>(&'a [glib::SendValue]);

unsafe impl<'a> Send for ArrayRef<'a> {}
unsafe impl<'a> Sync for ArrayRef<'a> {}

impl<'a> ArrayRef<'a> {
    pub fn new(values: &'a [glib::SendValue]) -> Self {
        skip_assert_initialized!();

        Self(values)
    }

    #[inline]
    pub fn as_slice(&self) -> &'a [glib::SendValue] {
        self.0
    }
}

impl<'a> ops::Deref for ArrayRef<'a> {
    type Target = [glib::SendValue];

    #[inline]
    fn deref(&self) -> &[glib::SendValue] {
        self.as_slice()
    }
}

impl<'a> AsRef<[glib::SendValue]> for ArrayRef<'a> {
    #[inline]
    fn as_ref(&self) -> &[glib::SendValue] {
        self.as_slice()
    }
}

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

    #[inline]
    unsafe fn from_value(value: &'a glib::Value) -> Self {
        skip_assert_initialized!();
        let arr = (*value.as_ptr()).data[0].v_pointer as *const glib::ffi::GArray;
        if arr.is_null() || (*arr).len == 0 {
            Self(&[])
        } else {
            #[allow(clippy::cast_ptr_alignment)]
            Self(slice::from_raw_parts(
                (*arr).data as *const glib::SendValue,
                (*arr).len as usize,
            ))
        }
    }
}

impl<'a> glib::value::ToValue for ArrayRef<'a> {
    #[inline]
    fn to_value(&self) -> glib::Value {
        let mut value = glib::Value::for_value_type::<Array>();
        unsafe {
            for v in self.0 {
                ffi::gst_value_array_append_value(value.to_glib_none_mut().0, v.to_glib_none().0);
            }
        }
        value
    }

    #[inline]
    fn value_type(&self) -> glib::Type {
        Self::static_type()
    }
}

impl<'a> From<ArrayRef<'a>> for glib::Value {
    #[inline]
    fn from(v: ArrayRef<'a>) -> glib::Value {
        skip_assert_initialized!();
        glib::value::ToValue::to_value(&v)
    }
}

impl<'a> glib::types::StaticType for ArrayRef<'a> {
    #[inline]
    fn static_type() -> glib::types::Type {
        unsafe { from_glib(ffi::gst_value_array_get_type()) }
    }
}

#[derive(Clone)]
pub struct List(glib::SendValue);

unsafe impl Send for List {}
unsafe impl Sync for List {}

impl fmt::Debug for List {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("List").field(&self.as_slice()).finish()
    }
}

impl List {
    pub fn new(values: impl IntoIterator<Item = impl Into<glib::Value> + Send>) -> Self {
        assert_initialized_main_thread!();

        unsafe {
            let mut value = glib::Value::for_value_type::<List>();
            for v in values.into_iter() {
                let mut v = v.into().into_raw();
                ffi::gst_value_list_append_and_take_value(value.to_glib_none_mut().0, &mut v);
            }

            Self(glib::SendValue::unsafe_from(value.into_raw()))
        }
    }

    pub fn from_values(values: impl IntoIterator<Item = glib::SendValue>) -> Self {
        skip_assert_initialized!();

        Self::new(values)
    }

    #[inline]
    pub fn as_slice(&self) -> &[glib::SendValue] {
        unsafe {
            let arr = (*self.0.as_ptr()).data[0].v_pointer as *const glib::ffi::GArray;
            if arr.is_null() || (*arr).len == 0 {
                &[]
            } else {
                #[allow(clippy::cast_ptr_alignment)]
                slice::from_raw_parts((*arr).data as *const glib::SendValue, (*arr).len as usize)
            }
        }
    }

    pub fn append_value(&mut self, value: glib::SendValue) {
        unsafe {
            ffi::gst_value_list_append_and_take_value(
                self.0.to_glib_none_mut().0,
                &mut value.into_raw(),
            );
        }
    }

    pub fn append(&mut self, value: impl Into<glib::Value> + Send) {
        self.append_value(glib::SendValue::from_owned(value));
    }
}

impl Default for List {
    fn default() -> Self {
        skip_assert_initialized!();

        unsafe {
            let value = glib::Value::for_value_type::<List>();

            Self(glib::SendValue::unsafe_from(value.into_raw()))
        }
    }
}

impl ops::Deref for List {
    type Target = [glib::SendValue];

    #[inline]
    fn deref(&self) -> &[glib::SendValue] {
        self.as_slice()
    }
}

impl AsRef<[glib::SendValue]> for List {
    #[inline]
    fn as_ref(&self) -> &[glib::SendValue] {
        self.as_slice()
    }
}

impl std::iter::FromIterator<glib::SendValue> for List {
    fn from_iter<T: IntoIterator<Item = glib::SendValue>>(iter: T) -> Self {
        skip_assert_initialized!();
        Self::from_values(iter)
    }
}

impl std::iter::Extend<glib::SendValue> for List {
    fn extend<T: IntoIterator<Item = glib::SendValue>>(&mut self, iter: T) {
        for v in iter.into_iter() {
            self.append_value(v);
        }
    }
}

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

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

    unsafe fn from_value(value: &'a glib::Value) -> Self {
        skip_assert_initialized!();
        Self(glib::SendValue::unsafe_from(value.clone().into_raw()))
    }
}

impl glib::value::ToValue for List {
    fn to_value(&self) -> glib::Value {
        self.0.clone().into()
    }

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

impl From<List> for glib::Value {
    fn from(v: List) -> glib::Value {
        skip_assert_initialized!();
        v.0.into()
    }
}

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

#[derive(Debug, Clone)]
pub struct ListRef<'a>(&'a [glib::SendValue]);

unsafe impl<'a> Send for ListRef<'a> {}
unsafe impl<'a> Sync for ListRef<'a> {}

impl<'a> ListRef<'a> {
    pub fn new(values: &'a [glib::SendValue]) -> Self {
        skip_assert_initialized!();

        Self(values)
    }

    #[inline]
    pub fn as_slice(&self) -> &'a [glib::SendValue] {
        self.0
    }
}

impl<'a> ops::Deref for ListRef<'a> {
    type Target = [glib::SendValue];

    #[inline]
    fn deref(&self) -> &[glib::SendValue] {
        self.as_slice()
    }
}

impl<'a> AsRef<[glib::SendValue]> for ListRef<'a> {
    #[inline]
    fn as_ref(&self) -> &[glib::SendValue] {
        self.as_slice()
    }
}

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

    #[inline]
    unsafe fn from_value(value: &'a glib::Value) -> Self {
        skip_assert_initialized!();
        let arr = (*value.as_ptr()).data[0].v_pointer as *const glib::ffi::GArray;
        if arr.is_null() || (*arr).len == 0 {
            Self(&[])
        } else {
            #[allow(clippy::cast_ptr_alignment)]
            Self(slice::from_raw_parts(
                (*arr).data as *const glib::SendValue,
                (*arr).len as usize,
            ))
        }
    }
}

impl<'a> glib::value::ToValue for ListRef<'a> {
    #[inline]
    fn to_value(&self) -> glib::Value {
        let mut value = glib::Value::for_value_type::<List>();
        unsafe {
            for v in self.0 {
                ffi::gst_value_list_append_value(value.to_glib_none_mut().0, v.to_glib_none().0);
            }
        }
        value
    }

    #[inline]
    fn value_type(&self) -> glib::Type {
        Self::static_type()
    }
}

impl<'a> From<ListRef<'a>> for glib::Value {
    #[inline]
    fn from(v: ListRef<'a>) -> glib::Value {
        skip_assert_initialized!();
        glib::value::ToValue::to_value(&v)
    }
}

impl<'a> glib::types::StaticType for ListRef<'a> {
    #[inline]
    fn static_type() -> glib::types::Type {
        unsafe { from_glib(ffi::gst_value_list_get_type()) }
    }
}

pub trait GstValueExt: Sized {
    #[doc(alias = "gst_value_can_compare")]
    fn can_compare(&self, other: &Self) -> bool;
    #[doc(alias = "gst_value_compare")]
    fn compare(&self, other: &Self) -> Option<cmp::Ordering>;
    fn eq(&self, other: &Self) -> bool;
    #[doc(alias = "gst_value_can_intersect")]
    fn can_intersect(&self, other: &Self) -> bool;
    #[doc(alias = "gst_value_intersect")]
    fn intersect(&self, other: &Self) -> Option<Self>;
    #[doc(alias = "gst_value_can_subtract")]
    fn can_subtract(&self, other: &Self) -> bool;
    #[doc(alias = "gst_value_subtract")]
    fn subtract(&self, other: &Self) -> Option<Self>;
    #[doc(alias = "gst_value_can_union")]
    fn can_union(&self, other: &Self) -> bool;
    #[doc(alias = "gst_value_union")]
    fn union(&self, other: &Self) -> Option<Self>;
    #[doc(alias = "gst_value_fixate")]
    fn fixate(&self) -> Option<Self>;
    #[doc(alias = "gst_value_is_fixed")]
    fn is_fixed(&self) -> bool;
    #[doc(alias = "gst_value_is_subset")]
    fn is_subset(&self, superset: &Self) -> bool;
    #[doc(alias = "gst_value_serialize")]
    fn serialize(&self) -> Result<glib::GString, glib::BoolError>;
    #[doc(alias = "gst_value_deserialize")]
    fn deserialize(s: &str, type_: glib::Type) -> Result<glib::Value, glib::BoolError>;
    #[cfg(feature = "v1_20")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v1_20")))]
    #[doc(alias = "gst_value_deserialize_with_pspec")]
    fn deserialize_with_pspec(
        s: &str,
        pspec: &glib::ParamSpec,
    ) -> Result<glib::Value, glib::BoolError>;
}

impl GstValueExt for glib::Value {
    fn can_compare(&self, other: &Self) -> bool {
        unsafe {
            from_glib(ffi::gst_value_can_compare(
                self.to_glib_none().0,
                other.to_glib_none().0,
            ))
        }
    }

    fn compare(&self, other: &Self) -> Option<cmp::Ordering> {
        unsafe {
            let val = ffi::gst_value_compare(self.to_glib_none().0, other.to_glib_none().0);

            match val {
                ffi::GST_VALUE_LESS_THAN => Some(cmp::Ordering::Less),
                ffi::GST_VALUE_EQUAL => Some(cmp::Ordering::Equal),
                ffi::GST_VALUE_GREATER_THAN => Some(cmp::Ordering::Greater),
                _ => None,
            }
        }
    }

    fn eq(&self, other: &Self) -> bool {
        self.compare(other) == Some(cmp::Ordering::Equal)
    }

    fn can_intersect(&self, other: &Self) -> bool {
        unsafe {
            from_glib(ffi::gst_value_can_intersect(
                self.to_glib_none().0,
                other.to_glib_none().0,
            ))
        }
    }

    fn intersect(&self, other: &Self) -> Option<Self> {
        unsafe {
            let mut value = glib::Value::uninitialized();
            let ret: bool = from_glib(ffi::gst_value_intersect(
                value.to_glib_none_mut().0,
                self.to_glib_none().0,
                other.to_glib_none().0,
            ));
            if ret {
                Some(value)
            } else {
                None
            }
        }
    }

    fn can_subtract(&self, other: &Self) -> bool {
        unsafe {
            from_glib(ffi::gst_value_can_subtract(
                self.to_glib_none().0,
                other.to_glib_none().0,
            ))
        }
    }

    fn subtract(&self, other: &Self) -> Option<Self> {
        unsafe {
            let mut value = glib::Value::uninitialized();
            let ret: bool = from_glib(ffi::gst_value_subtract(
                value.to_glib_none_mut().0,
                self.to_glib_none().0,
                other.to_glib_none().0,
            ));
            if ret {
                Some(value)
            } else {
                None
            }
        }
    }

    fn can_union(&self, other: &Self) -> bool {
        unsafe {
            from_glib(ffi::gst_value_can_union(
                self.to_glib_none().0,
                other.to_glib_none().0,
            ))
        }
    }

    fn union(&self, other: &Self) -> Option<Self> {
        unsafe {
            let mut value = glib::Value::uninitialized();
            let ret: bool = from_glib(ffi::gst_value_union(
                value.to_glib_none_mut().0,
                self.to_glib_none().0,
                other.to_glib_none().0,
            ));
            if ret {
                Some(value)
            } else {
                None
            }
        }
    }

    fn fixate(&self) -> Option<Self> {
        unsafe {
            let mut value = glib::Value::uninitialized();
            let ret: bool = from_glib(ffi::gst_value_fixate(
                value.to_glib_none_mut().0,
                self.to_glib_none().0,
            ));
            if ret {
                Some(value)
            } else {
                None
            }
        }
    }

    fn is_fixed(&self) -> bool {
        unsafe { from_glib(ffi::gst_value_is_fixed(self.to_glib_none().0)) }
    }

    fn is_subset(&self, superset: &Self) -> bool {
        unsafe {
            from_glib(ffi::gst_value_is_subset(
                self.to_glib_none().0,
                superset.to_glib_none().0,
            ))
        }
    }

    fn serialize(&self) -> Result<glib::GString, glib::BoolError> {
        unsafe {
            Option::<_>::from_glib_full(ffi::gst_value_serialize(self.to_glib_none().0))
                .ok_or_else(|| glib::bool_error!("Failed to serialize value"))
        }
    }

    fn deserialize(s: &str, type_: glib::Type) -> Result<glib::Value, glib::BoolError> {
        skip_assert_initialized!();

        unsafe {
            let mut value = glib::Value::from_type(type_);
            let ret: bool = from_glib(ffi::gst_value_deserialize(
                value.to_glib_none_mut().0,
                s.to_glib_none().0,
            ));
            if ret {
                Ok(value)
            } else {
                Err(glib::bool_error!("Failed to deserialize value"))
            }
        }
    }

    #[cfg(feature = "v1_20")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v1_20")))]
    fn deserialize_with_pspec(
        s: &str,
        pspec: &glib::ParamSpec,
    ) -> Result<glib::Value, glib::BoolError> {
        skip_assert_initialized!();

        unsafe {
            let mut value = glib::Value::from_type_unchecked(pspec.value_type());
            let ret: bool = from_glib(ffi::gst_value_deserialize_with_pspec(
                value.to_glib_none_mut().0,
                s.to_glib_none().0,
                pspec.to_glib_none().0,
            ));
            if ret {
                Ok(value)
            } else {
                Err(glib::bool_error!("Failed to deserialize value"))
            }
        }
    }
}

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

    #[test]
    fn test_fraction() {
        crate::init().unwrap();

        let f1 = crate::Fraction::new(1, 2);
        let f2 = crate::Fraction::new(2, 3);
        let mut f3 = f1 * f2;
        let f4 = f1 * f2;
        f3 *= f2;
        f3 *= f4;

        assert_eq!(f3, crate::Fraction::new(2, 27));
    }

    #[test]
    fn test_int_range_constructor() {
        crate::init().unwrap();

        // Type inference should figure out the type
        let _r1 = crate::IntRange::new(1i32, 2i32);
        let _r2 = crate::IntRange::with_step(2i64, 3i64, 4i64);
    }

    #[test]
    fn test_deserialize() {
        crate::init().unwrap();

        let v = glib::Value::deserialize("123", i32::static_type()).unwrap();
        assert_eq!(v.get::<i32>(), Ok(123));
    }
}