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

use std::{cmp, ffi::CStr, fmt, ops::Deref, ptr};

use crate::{prelude::*, translate::*, ParamSpecEnum, ParamSpecFlags, Type, TypeInfo, Value};

#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum UserDirectory {
    #[doc(alias = "G_USER_DIRECTORY_DESKTOP")]
    Desktop,
    #[doc(alias = "G_USER_DIRECTORY_DOCUMENTS")]
    Documents,
    #[doc(alias = "G_USER_DIRECTORY_DOWNLOAD")]
    Downloads,
    #[doc(alias = "G_USER_DIRECTORY_MUSIC")]
    Music,
    #[doc(alias = "G_USER_DIRECTORY_PICTURES")]
    Pictures,
    #[doc(alias = "G_USER_DIRECTORY_PUBLIC_SHARE")]
    PublicShare,
    #[doc(alias = "G_USER_DIRECTORY_TEMPLATES")]
    Templates,
    #[doc(alias = "G_USER_DIRECTORY_VIDEOS")]
    Videos,
}

#[doc(hidden)]
impl IntoGlib for UserDirectory {
    type GlibType = ffi::GUserDirectory;

    #[inline]
    fn into_glib(self) -> ffi::GUserDirectory {
        match self {
            Self::Desktop => ffi::G_USER_DIRECTORY_DESKTOP,
            Self::Documents => ffi::G_USER_DIRECTORY_DOCUMENTS,
            Self::Downloads => ffi::G_USER_DIRECTORY_DOWNLOAD,
            Self::Music => ffi::G_USER_DIRECTORY_MUSIC,
            Self::Pictures => ffi::G_USER_DIRECTORY_PICTURES,
            Self::PublicShare => ffi::G_USER_DIRECTORY_PUBLIC_SHARE,
            Self::Templates => ffi::G_USER_DIRECTORY_TEMPLATES,
            Self::Videos => ffi::G_USER_DIRECTORY_VIDEOS,
        }
    }
}

// rustdoc-stripper-ignore-next
/// Representation of an `enum` for dynamically, at runtime, querying the values of the enum and
/// using them.
#[doc(alias = "GEnumClass")]
#[repr(transparent)]
pub struct EnumClass(ptr::NonNull<gobject_ffi::GEnumClass>);

unsafe impl Send for EnumClass {}
unsafe impl Sync for EnumClass {}

impl fmt::Debug for EnumClass {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EnumClass")
            .field("type", &self.type_())
            .field("values", &self.values())
            .finish()
    }
}

impl EnumClass {
    // rustdoc-stripper-ignore-next
    /// Create a new `EnumClass` from a static type `T`.
    ///
    /// Panics if `T` is not representing an enum.
    pub fn new<T: StaticType + HasParamSpec<ParamSpec = ParamSpecEnum>>() -> Self {
        Self::with_type(T::static_type()).expect("invalid enum class")
    }
    // rustdoc-stripper-ignore-next
    /// Create a new `EnumClass` from a `Type`.
    ///
    /// Returns `None` if `type_` is not representing an enum.
    pub fn with_type(type_: Type) -> Option<Self> {
        unsafe {
            let is_enum: bool = from_glib(gobject_ffi::g_type_is_a(
                type_.into_glib(),
                gobject_ffi::G_TYPE_ENUM,
            ));
            if !is_enum {
                return None;
            }

            Some(EnumClass(
                ptr::NonNull::new(gobject_ffi::g_type_class_ref(type_.into_glib()) as *mut _)
                    .unwrap(),
            ))
        }
    }

    // rustdoc-stripper-ignore-next
    /// `Type` of the enum.
    pub fn type_(&self) -> Type {
        unsafe { from_glib(self.0.as_ref().g_type_class.g_type) }
    }

    // rustdoc-stripper-ignore-next
    /// Gets `EnumValue` by integer `value`, if existing.
    ///
    /// Returns `None` if the enum does not contain any value
    /// with `value`.
    #[doc(alias = "g_enum_get_value")]
    #[doc(alias = "get_value")]
    pub fn value(&self, value: i32) -> Option<&EnumValue> {
        unsafe {
            let v = gobject_ffi::g_enum_get_value(self.0.as_ptr(), value);
            if v.is_null() {
                None
            } else {
                Some(&*(v as *const EnumValue))
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Gets `EnumValue` by string name `name`, if existing.
    ///
    /// Returns `None` if the enum does not contain any value
    /// with name `name`.
    #[doc(alias = "g_enum_get_value_by_name")]
    #[doc(alias = "get_value_by_name")]
    pub fn value_by_name(&self, name: &str) -> Option<&EnumValue> {
        unsafe {
            let v = gobject_ffi::g_enum_get_value_by_name(self.0.as_ptr(), name.to_glib_none().0);
            if v.is_null() {
                None
            } else {
                Some(&*(v as *const EnumValue))
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Gets `EnumValue` by string nick `nick`, if existing.
    ///
    /// Returns `None` if the enum does not contain any value
    /// with nick `nick`.
    #[doc(alias = "g_enum_get_value_by_nick")]
    #[doc(alias = "get_value_by_nick")]
    pub fn value_by_nick(&self, nick: &str) -> Option<&EnumValue> {
        unsafe {
            let v = gobject_ffi::g_enum_get_value_by_nick(self.0.as_ptr(), nick.to_glib_none().0);
            if v.is_null() {
                None
            } else {
                Some(&*(v as *const EnumValue))
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Gets all `EnumValue` of this `EnumClass`.
    #[doc(alias = "get_values")]
    pub fn values(&self) -> &[EnumValue] {
        unsafe {
            if self.0.as_ref().n_values == 0 {
                return &[];
            }
            std::slice::from_raw_parts(
                self.0.as_ref().values as *const EnumValue,
                self.0.as_ref().n_values as usize,
            )
        }
    }

    // rustdoc-stripper-ignore-next
    /// Converts integer `value` to a `Value`, if part of the enum.
    pub fn to_value(&self, value: i32) -> Option<Value> {
        self.value(value).map(|v| v.to_value(self))
    }

    // rustdoc-stripper-ignore-next
    /// Converts string name `name` to a `Value`, if part of the enum.
    pub fn to_value_by_name(&self, name: &str) -> Option<Value> {
        self.value_by_name(name).map(|v| v.to_value(self))
    }

    // rustdoc-stripper-ignore-next
    /// Converts string nick `nick` to a `Value`, if part of the enum.
    pub fn to_value_by_nick(&self, nick: &str) -> Option<Value> {
        self.value_by_nick(nick).map(|v| v.to_value(self))
    }

    // rustdoc-stripper-ignore-next
    /// Complete `TypeInfo` for an enum with values.
    /// This is an associated function. A method would result in a stack overflow due to a recurvice call:
    /// callers should first create an `EnumClass` instance by calling `EnumClass::with_type()` which indirectly
    /// calls `TypePluginRegisterImpl::register_dynamic_enum()` and `TypePluginImpl::complete_type_info()`
    /// and one of them should call `EnumClass::with_type()` before calling this method.
    /// `const_static_values` is a reference on a wrapper of a slice of `EnumValue`.
    /// It must be static to ensure enumeration values are never dropped, and ensures that slice is terminated
    ///  by an `EnumValue` with all members being 0, as expected by GLib.
    #[doc(alias = "g_enum_complete_type_info")]
    pub fn complete_type_info(
        type_: Type,
        const_static_values: &'static EnumValues,
    ) -> Option<TypeInfo> {
        unsafe {
            let is_enum: bool = from_glib(gobject_ffi::g_type_is_a(
                type_.into_glib(),
                gobject_ffi::G_TYPE_ENUM,
            ));
            if !is_enum {
                return None;
            }

            let info = TypeInfo::default();
            gobject_ffi::g_enum_complete_type_info(
                type_.into_glib(),
                info.as_ptr(),
                const_static_values.to_glib_none().0,
            );
            Some(info)
        }
    }
}

impl Drop for EnumClass {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            gobject_ffi::g_type_class_unref(self.0.as_ptr() as *mut _);
        }
    }
}

impl Clone for EnumClass {
    #[inline]
    fn clone(&self) -> Self {
        unsafe {
            Self(ptr::NonNull::new(gobject_ffi::g_type_class_ref(self.type_().into_glib()) as *mut _).unwrap())
        }
    }
}

// rustdoc-stripper-ignore-next
/// Representation of a single enum value of an `EnumClass`.
#[doc(alias = "GEnumValue")]
#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct EnumValue(gobject_ffi::GEnumValue);

unsafe impl Send for EnumValue {}
unsafe impl Sync for EnumValue {}

impl fmt::Debug for EnumValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EnumValue")
            .field("value", &self.value())
            .field("name", &self.name())
            .field("nick", &self.nick())
            .finish()
    }
}

impl EnumValue {
    // rustdoc-stripper-ignore-next
    /// # Safety
    ///
    /// It is the responsibility of the caller to ensure `GEnumValue` is
    /// valid.
    pub const unsafe fn unsafe_from(g_value: gobject_ffi::GEnumValue) -> Self {
        Self(g_value)
    }

    // rustdoc-stripper-ignore-next
    /// Get integer value corresponding to the value.
    #[doc(alias = "get_value")]
    pub fn value(&self) -> i32 {
        self.0.value
    }

    // rustdoc-stripper-ignore-next
    /// Get name corresponding to the value.
    #[doc(alias = "get_name")]
    pub fn name(&self) -> &str {
        unsafe { CStr::from_ptr(self.0.value_name).to_str().unwrap() }
    }

    // rustdoc-stripper-ignore-next
    /// Get nick corresponding to the value.
    #[doc(alias = "get_nick")]
    pub fn nick(&self) -> &str {
        unsafe { CStr::from_ptr(self.0.value_nick).to_str().unwrap() }
    }

    // rustdoc-stripper-ignore-next
    /// Convert enum value to a `Value`.
    pub fn to_value(&self, enum_: &EnumClass) -> Value {
        unsafe {
            let mut v = Value::from_type_unchecked(enum_.type_());
            gobject_ffi::g_value_set_enum(v.to_glib_none_mut().0, self.0.value);
            v
        }
    }

    // rustdoc-stripper-ignore-next
    /// Convert enum value from a `Value`.
    pub fn from_value(value: &Value) -> Option<(EnumClass, &EnumValue)> {
        unsafe {
            let enum_class = EnumClass::with_type(value.type_())?;
            let v = enum_class.value(gobject_ffi::g_value_get_enum(value.to_glib_none().0))?;
            let v = &*(v as *const EnumValue);
            Some((enum_class, v))
        }
    }
}

impl PartialEq for EnumValue {
    fn eq(&self, other: &Self) -> bool {
        self.value().eq(&other.value())
    }
}

impl Eq for EnumValue {}

impl PartialOrd for EnumValue {
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for EnumValue {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        self.value().cmp(&other.value())
    }
}

impl UnsafeFrom<gobject_ffi::GEnumValue> for EnumValue {
    unsafe fn unsafe_from(g_value: gobject_ffi::GEnumValue) -> Self {
        Self::unsafe_from(g_value)
    }
}

unsafe impl<'a, 'b> crate::value::FromValue<'a> for &'b EnumValue {
    type Checker = EnumTypeChecker;

    unsafe fn from_value(value: &'a Value) -> Self {
        let (_, v) = EnumValue::from_value(value).unwrap();
        // SAFETY: The enum class and its values live forever
        std::mem::transmute(v)
    }
}

// rustdoc-stripper-ignore-next
/// Define the zero value and the associated GLib type.
impl EnumerationValue<EnumValue> for EnumValue {
    type GlibType = gobject_ffi::GEnumValue;
    const ZERO: EnumValue = unsafe {
        EnumValue::unsafe_from(gobject_ffi::GEnumValue {
            value: 0,
            value_name: ptr::null(),
            value_nick: ptr::null(),
        })
    };
}

// rustdoc-stripper-ignore-next
/// Storage of enum values.
pub type EnumValuesStorage<const N: usize> = EnumerationValuesStorage<EnumValue, N>;

// rustdoc-stripper-ignore-next
/// Representation of enum values wrapped by `EnumValuesStorage`
pub type EnumValues = EnumerationValues<EnumValue>;

pub struct EnumTypeChecker();
unsafe impl crate::value::ValueTypeChecker for EnumTypeChecker {
    type Error = InvalidEnumError;

    fn check(value: &Value) -> Result<(), Self::Error> {
        let t = value.type_();
        if t.is_a(Type::ENUM) {
            Ok(())
        } else {
            Err(InvalidEnumError)
        }
    }
}

// rustdoc-stripper-ignore-next
/// An error returned from the [`get`](struct.Value.html#method.get) function
/// on a [`Value`](struct.Value.html) for enum types.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct InvalidEnumError;

impl fmt::Display for InvalidEnumError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Value is not an enum")
    }
}

impl std::error::Error for InvalidEnumError {}

// rustdoc-stripper-ignore-next
/// Representation of a `flags` for dynamically, at runtime, querying the values of the enum and
/// using them
#[doc(alias = "GFlagsClass")]
#[repr(transparent)]
pub struct FlagsClass(ptr::NonNull<gobject_ffi::GFlagsClass>);

unsafe impl Send for FlagsClass {}
unsafe impl Sync for FlagsClass {}

impl fmt::Debug for FlagsClass {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FlagsClass")
            .field("type", &self.type_())
            .field("values", &self.values())
            .finish()
    }
}

impl FlagsClass {
    // rustdoc-stripper-ignore-next
    /// Create a new `FlagsClass` from a static type `T`.
    ///
    /// Panics if `T` is not representing an flags type.
    pub fn new<T: StaticType + HasParamSpec<ParamSpec = ParamSpecFlags>>() -> Self {
        Self::with_type(T::static_type()).expect("invalid flags class")
    }
    // rustdoc-stripper-ignore-next
    /// Create a new `FlagsClass` from a `Type`
    ///
    /// Returns `None` if `type_` is not representing a flags type.
    pub fn with_type(type_: Type) -> Option<Self> {
        unsafe {
            let is_flags: bool = from_glib(gobject_ffi::g_type_is_a(
                type_.into_glib(),
                gobject_ffi::G_TYPE_FLAGS,
            ));
            if !is_flags {
                return None;
            }

            Some(FlagsClass(
                ptr::NonNull::new(gobject_ffi::g_type_class_ref(type_.into_glib()) as *mut _)
                    .unwrap(),
            ))
        }
    }

    // rustdoc-stripper-ignore-next
    /// `Type` of the flags.
    pub fn type_(&self) -> Type {
        unsafe { from_glib(self.0.as_ref().g_type_class.g_type) }
    }

    // rustdoc-stripper-ignore-next
    /// Gets `FlagsValue` by integer `value`, if existing.
    ///
    /// Returns `None` if the flags do not contain any value
    /// with `value`.
    #[doc(alias = "g_flags_get_first_value")]
    #[doc(alias = "get_value")]
    pub fn value(&self, value: u32) -> Option<&FlagsValue> {
        unsafe {
            let v = gobject_ffi::g_flags_get_first_value(self.0.as_ptr(), value);
            if v.is_null() {
                None
            } else {
                Some(&*(v as *const FlagsValue))
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Gets `FlagsValue` by string name `name`, if existing.
    ///
    /// Returns `None` if the flags do not contain any value
    /// with name `name`.
    #[doc(alias = "g_flags_get_value_by_name")]
    #[doc(alias = "get_value_by_name")]
    pub fn value_by_name(&self, name: &str) -> Option<&FlagsValue> {
        unsafe {
            let v = gobject_ffi::g_flags_get_value_by_name(self.0.as_ptr(), name.to_glib_none().0);
            if v.is_null() {
                None
            } else {
                Some(&*(v as *const FlagsValue))
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Gets `FlagsValue` by string nick `nick`, if existing.
    ///
    /// Returns `None` if the flags do not contain any value
    /// with nick `nick`.
    #[doc(alias = "g_flags_get_value_by_nick")]
    #[doc(alias = "get_value_by_nick")]
    pub fn value_by_nick(&self, nick: &str) -> Option<&FlagsValue> {
        unsafe {
            let v = gobject_ffi::g_flags_get_value_by_nick(self.0.as_ptr(), nick.to_glib_none().0);
            if v.is_null() {
                None
            } else {
                Some(&*(v as *const FlagsValue))
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Gets all `FlagsValue` of this `FlagsClass`.
    #[doc(alias = "get_values")]
    pub fn values(&self) -> &[FlagsValue] {
        unsafe {
            if self.0.as_ref().n_values == 0 {
                return &[];
            }
            std::slice::from_raw_parts(
                self.0.as_ref().values as *const FlagsValue,
                self.0.as_ref().n_values as usize,
            )
        }
    }

    // rustdoc-stripper-ignore-next
    /// Converts integer `value` to a `Value`, if part of the flags.
    pub fn to_value(&self, value: u32) -> Option<Value> {
        self.value(value).map(|v| v.to_value(self))
    }

    // rustdoc-stripper-ignore-next
    /// Converts string name `name` to a `Value`, if part of the flags.
    pub fn to_value_by_name(&self, name: &str) -> Option<Value> {
        self.value_by_name(name).map(|v| v.to_value(self))
    }

    // rustdoc-stripper-ignore-next
    /// Converts string nick `nick` to a `Value`, if part of the flags.
    pub fn to_value_by_nick(&self, nick: &str) -> Option<Value> {
        self.value_by_nick(nick).map(|v| v.to_value(self))
    }

    // rustdoc-stripper-ignore-next
    /// Checks if the flags corresponding to integer `f` is set in `value`.
    pub fn is_set(&self, value: &Value, f: u32) -> bool {
        unsafe {
            if self.type_() != value.type_() {
                return false;
            }

            let flags = gobject_ffi::g_value_get_flags(value.to_glib_none().0);
            flags & f != 0
        }
    }

    // rustdoc-stripper-ignore-next
    /// Checks if the flags corresponding to string name `name` is set in `value`.
    pub fn is_set_by_name(&self, value: &Value, name: &str) -> bool {
        unsafe {
            if self.type_() != value.type_() {
                return false;
            }

            if let Some(f) = self.value_by_name(name) {
                let flags = gobject_ffi::g_value_get_flags(value.to_glib_none().0);
                flags & f.value() != 0
            } else {
                false
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Checks if the flags corresponding to string nick `nick` is set in `value`.
    pub fn is_set_by_nick(&self, value: &Value, nick: &str) -> bool {
        unsafe {
            if self.type_() != value.type_() {
                return false;
            }

            if let Some(f) = self.value_by_nick(nick) {
                let flags = gobject_ffi::g_value_get_flags(value.to_glib_none().0);
                flags & f.value() != 0
            } else {
                false
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Set flags value corresponding to integer `f` in `value`, if part of that flags. If the
    /// flag is already set, it will succeed without doing any changes.
    ///
    /// Returns `Ok(value)` with the flag set if successful, or `Err(value)` with the original
    /// value otherwise.
    #[doc(alias = "g_value_set_flags")]
    pub fn set(&self, mut value: Value, f: u32) -> Result<Value, Value> {
        unsafe {
            if self.type_() != value.type_() {
                return Err(value);
            }

            if let Some(f) = self.value(f) {
                let flags = gobject_ffi::g_value_get_flags(value.to_glib_none().0);
                gobject_ffi::g_value_set_flags(value.to_glib_none_mut().0, flags | f.value());
                Ok(value)
            } else {
                Err(value)
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Set flags value corresponding to string name `name` in `value`, if part of that flags.
    /// If the flag is already set, it will succeed without doing any changes.
    ///
    /// Returns `Ok(value)` with the flag set if successful, or `Err(value)` with the original
    /// value otherwise.
    pub fn set_by_name(&self, mut value: Value, name: &str) -> Result<Value, Value> {
        unsafe {
            if self.type_() != value.type_() {
                return Err(value);
            }

            if let Some(f) = self.value_by_name(name) {
                let flags = gobject_ffi::g_value_get_flags(value.to_glib_none().0);
                gobject_ffi::g_value_set_flags(value.to_glib_none_mut().0, flags | f.value());
                Ok(value)
            } else {
                Err(value)
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Set flags value corresponding to string nick `nick` in `value`, if part of that flags.
    /// If the flag is already set, it will succeed without doing any changes.
    ///
    /// Returns `Ok(value)` with the flag set if successful, or `Err(value)` with the original
    /// value otherwise.
    pub fn set_by_nick(&self, mut value: Value, nick: &str) -> Result<Value, Value> {
        unsafe {
            if self.type_() != value.type_() {
                return Err(value);
            }

            if let Some(f) = self.value_by_nick(nick) {
                let flags = gobject_ffi::g_value_get_flags(value.to_glib_none().0);
                gobject_ffi::g_value_set_flags(value.to_glib_none_mut().0, flags | f.value());
                Ok(value)
            } else {
                Err(value)
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Unset flags value corresponding to integer `f` in `value`, if part of that flags.
    /// If the flag is already unset, it will succeed without doing any changes.
    ///
    /// Returns `Ok(value)` with the flag unset if successful, or `Err(value)` with the original
    /// value otherwise.
    pub fn unset(&self, mut value: Value, f: u32) -> Result<Value, Value> {
        unsafe {
            if self.type_() != value.type_() {
                return Err(value);
            }

            if let Some(f) = self.value(f) {
                let flags = gobject_ffi::g_value_get_flags(value.to_glib_none().0);
                gobject_ffi::g_value_set_flags(value.to_glib_none_mut().0, flags & !f.value());
                Ok(value)
            } else {
                Err(value)
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Unset flags value corresponding to string name `name` in `value`, if part of that flags.
    /// If the flag is already unset, it will succeed without doing any changes.
    ///
    /// Returns `Ok(value)` with the flag unset if successful, or `Err(value)` with the original
    /// value otherwise.
    pub fn unset_by_name(&self, mut value: Value, name: &str) -> Result<Value, Value> {
        unsafe {
            if self.type_() != value.type_() {
                return Err(value);
            }

            if let Some(f) = self.value_by_name(name) {
                let flags = gobject_ffi::g_value_get_flags(value.to_glib_none().0);
                gobject_ffi::g_value_set_flags(value.to_glib_none_mut().0, flags & !f.value());
                Ok(value)
            } else {
                Err(value)
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Unset flags value corresponding to string nick `nick` in `value`, if part of that flags.
    /// If the flag is already unset, it will succeed without doing any changes.
    ///
    /// Returns `Ok(value)` with the flag unset if successful, or `Err(value)` with the original
    /// value otherwise.
    pub fn unset_by_nick(&self, mut value: Value, nick: &str) -> Result<Value, Value> {
        unsafe {
            if self.type_() != value.type_() {
                return Err(value);
            }

            if let Some(f) = self.value_by_nick(nick) {
                let flags = gobject_ffi::g_value_get_flags(value.to_glib_none().0);
                gobject_ffi::g_value_set_flags(value.to_glib_none_mut().0, flags & !f.value());
                Ok(value)
            } else {
                Err(value)
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Converts an integer `value` to a string of nicks separated by `|`.
    pub fn to_nick_string(&self, mut value: u32) -> String {
        let mut s = String::new();
        for val in self.values() {
            let v = val.value();
            if v != 0 && (value & v) == v {
                value &= !v;
                if !s.is_empty() {
                    s.push('|');
                }
                s.push_str(val.nick());
            }
        }
        s
    }

    // rustdoc-stripper-ignore-next
    /// Converts a string of nicks `s` separated by `|` to an integer value.
    pub fn from_nick_string(&self, s: &str) -> Result<u32, ParseFlagsError> {
        s.split('|').try_fold(0u32, |acc, flag| {
            self.value_by_nick(flag.trim())
                .map(|v| acc + v.value())
                .ok_or_else(|| ParseFlagsError(flag.to_owned()))
        })
    }

    // rustdoc-stripper-ignore-next
    /// Returns a new `FlagsBuilder` for conveniently setting/unsetting flags
    /// and building a `Value`.
    pub fn builder(&self) -> FlagsBuilder {
        FlagsBuilder::new(self)
    }

    // rustdoc-stripper-ignore-next
    /// Returns a new `FlagsBuilder` for conveniently setting/unsetting flags
    /// and building a `Value`. The `Value` is initialized with `value`.
    pub fn builder_with_value(&self, value: Value) -> Option<FlagsBuilder> {
        if self.type_() != value.type_() {
            return None;
        }

        Some(FlagsBuilder::with_value(self, value))
    }

    // rustdoc-stripper-ignore-next
    /// Complete `TypeInfo` for the flags with values.
    /// This is an associated function. A method would result in a stack overflow due to a recurvice call:
    /// callers should first create an `FlagsClass` instance by calling `FlagsClass::with_type()` which indirectly
    /// calls `TypePluginRegisterImpl::register_dynamic_flags()` and `TypePluginImpl::complete_type_info()`
    /// and one of them should call `FlagsClass::with_type()` before calling this method.
    /// `const_static_values` is a reference on a wrapper of a slice of `FlagsValue`.
    /// It must be static to ensure flags values are never dropped, and ensures that slice is terminated
    ///  by an `FlagsValue` with all members being 0, as expected by GLib.
    #[doc(alias = "g_flags_complete_type_info")]
    pub fn complete_type_info(
        type_: Type,
        const_static_values: &'static FlagsValues,
    ) -> Option<TypeInfo> {
        unsafe {
            let is_flags: bool = from_glib(gobject_ffi::g_type_is_a(
                type_.into_glib(),
                gobject_ffi::G_TYPE_FLAGS,
            ));
            if !is_flags {
                return None;
            }

            let info = TypeInfo::default();
            gobject_ffi::g_flags_complete_type_info(
                type_.into_glib(),
                info.as_ptr(),
                const_static_values.to_glib_none().0,
            );
            Some(info)
        }
    }
}

impl Drop for FlagsClass {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            gobject_ffi::g_type_class_unref(self.0.as_ptr() as *mut _);
        }
    }
}

impl Clone for FlagsClass {
    #[inline]
    fn clone(&self) -> Self {
        unsafe {
            Self(ptr::NonNull::new(gobject_ffi::g_type_class_ref(self.type_().into_glib()) as *mut _).unwrap())
        }
    }
}

#[derive(Debug)]
pub struct ParseFlagsError(String);

impl std::error::Error for ParseFlagsError {}

impl fmt::Display for ParseFlagsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Unknown flag: '{}'", self.0)
    }
}

impl ParseFlagsError {
    pub fn flag(&self) -> &str {
        &self.0
    }
}

// rustdoc-stripper-ignore-next
/// Representation of a single flags value of a `FlagsClass`.
#[doc(alias = "GFlagsValue")]
#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct FlagsValue(gobject_ffi::GFlagsValue);

unsafe impl Send for FlagsValue {}
unsafe impl Sync for FlagsValue {}

impl fmt::Debug for FlagsValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FlagsValue")
            .field("value", &self.value())
            .field("name", &self.name())
            .field("nick", &self.nick())
            .finish()
    }
}

impl FlagsValue {
    // rustdoc-stripper-ignore-next
    /// # Safety
    ///
    /// It is the responsibility of the caller to ensure `GFlagsValue` is
    /// valid.
    pub const unsafe fn unsafe_from(g_value: gobject_ffi::GFlagsValue) -> Self {
        Self(g_value)
    }

    // rustdoc-stripper-ignore-next
    /// Get integer value corresponding to the value.
    #[doc(alias = "get_value")]
    pub fn value(&self) -> u32 {
        self.0.value
    }

    // rustdoc-stripper-ignore-next
    /// Get name corresponding to the value.
    #[doc(alias = "get_name")]
    pub fn name(&self) -> &str {
        unsafe { CStr::from_ptr(self.0.value_name).to_str().unwrap() }
    }

    // rustdoc-stripper-ignore-next
    /// Get nick corresponding to the value.
    #[doc(alias = "get_nick")]
    pub fn nick(&self) -> &str {
        unsafe { CStr::from_ptr(self.0.value_nick).to_str().unwrap() }
    }

    // rustdoc-stripper-ignore-next
    /// Convert flags value to a `Value`.
    pub fn to_value(&self, flags: &FlagsClass) -> Value {
        unsafe {
            let mut v = Value::from_type_unchecked(flags.type_());
            gobject_ffi::g_value_set_flags(v.to_glib_none_mut().0, self.0.value);
            v
        }
    }

    // rustdoc-stripper-ignore-next
    /// Convert flags values from a `Value`. This returns all flags that are set.
    pub fn from_value(value: &Value) -> Option<(FlagsClass, Vec<&FlagsValue>)> {
        unsafe {
            let flags_class = FlagsClass::with_type(value.type_())?;
            let mut res = Vec::new();
            let f = gobject_ffi::g_value_get_flags(value.to_glib_none().0);
            for v in flags_class.values() {
                if v.value() & f != 0 {
                    res.push(&*(v as *const FlagsValue));
                }
            }
            Some((flags_class, res))
        }
    }
}

impl PartialEq for FlagsValue {
    fn eq(&self, other: &Self) -> bool {
        self.value().eq(&other.value())
    }
}

impl Eq for FlagsValue {}

impl UnsafeFrom<gobject_ffi::GFlagsValue> for FlagsValue {
    unsafe fn unsafe_from(g_value: gobject_ffi::GFlagsValue) -> Self {
        Self::unsafe_from(g_value)
    }
}

// rustdoc-stripper-ignore-next
/// Define the zero value and the associated GLib type.
impl EnumerationValue<FlagsValue> for FlagsValue {
    type GlibType = gobject_ffi::GFlagsValue;
    const ZERO: FlagsValue = unsafe {
        FlagsValue::unsafe_from(gobject_ffi::GFlagsValue {
            value: 0,
            value_name: ptr::null(),
            value_nick: ptr::null(),
        })
    };
}

// rustdoc-stripper-ignore-next
/// Storage of flags values.
pub type FlagsValuesStorage<const N: usize> = EnumerationValuesStorage<FlagsValue, N>;

// rustdoc-stripper-ignore-next
/// Representation of flags values wrapped by `FlagsValuesStorage`
pub type FlagsValues = EnumerationValues<FlagsValue>;

// rustdoc-stripper-ignore-next
/// Builder for conveniently setting/unsetting flags and returning a `Value`.
///
/// Example for getting a flags property, unsetting some flags and setting the updated flags on the
/// object again:
///
/// ```ignore
/// let flags = obj.property("flags").unwrap();
/// let flags_class = FlagsClass::new(flags.type_()).unwrap();
/// let flags = flags_class.builder_with_value(flags).unwrap()
///     .unset_by_nick("some-flag")
///     .unset_by_nick("some-other-flag")
///     .build()
///     .unwrap();
/// obj.set_property("flags", &flags).unwrap();
/// ```
///
/// If setting/unsetting any value fails, `build()` returns `None`.
#[must_use = "The builder must be built to be used"]
pub struct FlagsBuilder<'a>(&'a FlagsClass, Option<Value>);
impl<'a> FlagsBuilder<'a> {
    fn new(flags_class: &FlagsClass) -> FlagsBuilder {
        let value = unsafe { Value::from_type_unchecked(flags_class.type_()) };
        FlagsBuilder(flags_class, Some(value))
    }

    fn with_value(flags_class: &FlagsClass, value: Value) -> FlagsBuilder {
        FlagsBuilder(flags_class, Some(value))
    }

    // rustdoc-stripper-ignore-next
    /// Set flags corresponding to integer value `f`.
    pub fn set(mut self, f: u32) -> Self {
        if let Some(value) = self.1.take() {
            self.1 = self.0.set(value, f).ok();
        }

        self
    }

    // rustdoc-stripper-ignore-next
    /// Set flags corresponding to string name `name`.
    pub fn set_by_name(mut self, name: &str) -> Self {
        if let Some(value) = self.1.take() {
            self.1 = self.0.set_by_name(value, name).ok();
        }

        self
    }

    // rustdoc-stripper-ignore-next
    /// Set flags corresponding to string nick `nick`.
    pub fn set_by_nick(mut self, nick: &str) -> Self {
        if let Some(value) = self.1.take() {
            self.1 = self.0.set_by_nick(value, nick).ok();
        }

        self
    }

    // rustdoc-stripper-ignore-next
    /// Unsets flags corresponding to integer value `f`.
    pub fn unset(mut self, f: u32) -> Self {
        if let Some(value) = self.1.take() {
            self.1 = self.0.unset(value, f).ok();
        }

        self
    }

    // rustdoc-stripper-ignore-next
    /// Unset flags corresponding to string name `name`.
    pub fn unset_by_name(mut self, name: &str) -> Self {
        if let Some(value) = self.1.take() {
            self.1 = self.0.unset_by_name(value, name).ok();
        }

        self
    }

    // rustdoc-stripper-ignore-next
    /// Unset flags corresponding to string nick `nick`.
    pub fn unset_by_nick(mut self, nick: &str) -> Self {
        if let Some(value) = self.1.take() {
            self.1 = self.0.unset_by_nick(value, nick).ok();
        }

        self
    }

    // rustdoc-stripper-ignore-next
    /// Converts to the final `Value`, unless any previous setting/unsetting of flags failed.
    #[must_use = "Value returned from the builder should probably be used"]
    pub fn build(self) -> Option<Value> {
        self.1
    }
}

unsafe impl<'a, 'b> crate::value::FromValue<'a> for Vec<&'b FlagsValue> {
    type Checker = FlagsTypeChecker;

    unsafe fn from_value(value: &'a Value) -> Self {
        let (_, v) = FlagsValue::from_value(value).unwrap();
        // SAFETY: The enum class and its values live forever
        std::mem::transmute(v)
    }
}

pub struct FlagsTypeChecker();
unsafe impl crate::value::ValueTypeChecker for FlagsTypeChecker {
    type Error = InvalidFlagsError;

    fn check(value: &Value) -> Result<(), Self::Error> {
        let t = value.type_();
        if t.is_a(Type::FLAGS) {
            Ok(())
        } else {
            Err(InvalidFlagsError)
        }
    }
}

// rustdoc-stripper-ignore-next
/// An error returned from the [`get`](struct.Value.html#method.get) function
/// on a [`Value`](struct.Value.html) for flags types.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct InvalidFlagsError;

impl fmt::Display for InvalidFlagsError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Value is not a flags")
    }
}

impl std::error::Error for InvalidFlagsError {}

// rustdoc-stripper-ignore-next
/// helper trait to define the zero value and the associated GLib type.
pub trait EnumerationValue<E>: Copy {
    type GlibType;
    const ZERO: E;
}

// rustdoc-stripper-ignore-next
/// Storage of enumeration values terminated by a zero value. Should be used
/// only as a storage location for `EnumValue` or `FlagsValue` when registering
/// an enum or flags as a dynamic type.
/// see `TypePluginRegisterImpl::register_dynamic_enum()`, `TypePluginRegisterImpl::register_dynamic_flags()`
/// and `TypePluginImpl::complete_type_info()`.
/// Inner is intentionally private to ensure other modules will not access the
/// enum (or flags) values by this way.
/// Use `EnumClass::values()` or `EnumClass::value()` to get the enum values.
/// Use `FlagsClass::values()` or `FlagsClass::value()` to get the flags values.
#[repr(C)]
pub struct EnumerationValuesStorage<E: EnumerationValue<E>, const S: usize>([E; S]);

impl<E: EnumerationValue<E>, const S: usize> EnumerationValuesStorage<E, S> {
    // rustdoc-stripper-ignore-next
    /// creates a new `EnumerationValuesStorage` with the given values and a final zero value.
    pub const fn new<const N: usize>(values: [E; N]) -> Self {
        #[repr(C)]
        #[derive(Copy, Clone)]
        struct Both<E: Copy, const N: usize>([E; N], [E; 1]);

        #[repr(C)]
        union Transmute<E: Copy, const N: usize, const S: usize> {
            from: Both<E, N>,
            to: [E; S],
        }

        // SAFETY: Transmute is repr(C) and union fields are compatible in terms of size and alignment, so the access to union fields is safe.
        unsafe {
            // create an array with the values and terminated by a zero value.
            let all = Transmute {
                from: Both(values, [E::ZERO; 1]),
            }
            .to;
            Self(all)
        }
    }
}

impl<E: EnumerationValue<E>, const S: usize> AsRef<EnumerationValues<E>>
    for EnumerationValuesStorage<E, S>
{
    fn as_ref(&self) -> &EnumerationValues<E> {
        // SAFETY: EnumerationStorage and EnumerationValues are repr(C) and their unique field are compatible (array and slice of the same type), so the cast is safe.
        unsafe { &*(&self.0 as *const [E] as *const EnumerationValues<E>) }
    }
}

// rustdoc-stripper-ignore-next
/// Representation of enumeration values wrapped by `EnumerationValuesStorage`.
/// Easier to use because don't have a size parameter to be specify. Should be
/// used only to register an enum or flags as a dynamic type.
/// see `TypePluginRegisterImpl::register_dynamic_enum()`, `TypePluginRegisterImpl::register_dynamic_flags()`
/// and `TypePluginImpl::complete_type_info()`.
/// Field is intentionally private to ensure other modules will not access the
/// enum (or flags) values by this way.
/// Use `EnumClass::values()` or `EnumClass::value()` to get the enum values.
/// Use `FlagsClass::values()` or `FlagsClass::value()` to get the flags values.
#[repr(C)]
pub struct EnumerationValues<E: EnumerationValue<E>>([E]);

impl<E: EnumerationValue<E>> Deref for EnumerationValues<E> {
    type Target = [E];

    // rustdoc-stripper-ignore-next
    /// Dereferences the enumeration values as a slice, but excluding the last value which is zero.
    fn deref(&self) -> &Self::Target {
        // SAFETY: EnumerationValues contains at least the zero value which terminates the array.
        unsafe { std::slice::from_raw_parts(self.0.as_ptr(), self.0.len() - 1) }
    }
}

#[doc(hidden)]
impl<'a, E: 'a + EnumerationValue<E>> ToGlibPtr<'a, *const E::GlibType> for EnumerationValues<E> {
    type Storage = &'a Self;

    fn to_glib_none(&'a self) -> Stash<'a, *const E::GlibType, Self> {
        Stash(self.0.as_ptr() as *const E::GlibType, self)
    }
}

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

    #[test]
    fn test_flags() {
        let flags = FlagsClass::new::<crate::BindingFlags>();
        let values = flags.values();
        let def1 = values
            .iter()
            .find(|v| v.name() == "G_BINDING_DEFAULT")
            .unwrap();
        let def2 = flags.value_by_name("G_BINDING_DEFAULT").unwrap();
        assert!(ptr::eq(def1, def2));

        let value = flags.to_value(0).unwrap();
        let values = value.get::<Vec<&FlagsValue>>().unwrap();
        assert_eq!(values.len(), 0);

        assert_eq!(def1.value(), crate::BindingFlags::DEFAULT.bits());
    }
}