qt_core/
q_flags.rs

1use std::fmt;
2use std::marker::PhantomData;
3use std::ops::{BitAnd, BitOr, BitXor};
4use std::os::raw::c_int;
5
6/// An OR-combination of integer values of the enum type `E`.
7///
8/// This type serves as a replacement for Qt's `QFlags` C++ template class.
9#[derive(Clone, Copy)]
10pub struct QFlags<E> {
11    value: c_int,
12    _phantom_data: PhantomData<E>,
13}
14
15impl<E> From<c_int> for QFlags<E> {
16    fn from(value: c_int) -> Self {
17        Self {
18            value,
19            _phantom_data: PhantomData,
20        }
21    }
22}
23
24impl<E> From<QFlags<E>> for c_int {
25    fn from(flags: QFlags<E>) -> Self {
26        flags.value
27    }
28}
29
30impl<E> QFlags<E> {
31    pub fn to_int(self) -> c_int {
32        self.value
33    }
34}
35
36impl<E: Into<QFlags<E>>> QFlags<E> {
37    /// Returns `true` if `flag` is enabled in `self`.
38    pub fn test_flag(self, flag: E) -> bool {
39        self.value & flag.into().value != 0
40    }
41
42    /// Returns `true` if this value has no flags enabled.
43    pub fn is_empty(self) -> bool {
44        self.value == 0
45    }
46}
47
48impl<E, T: Into<QFlags<E>>> BitOr<T> for QFlags<E> {
49    type Output = QFlags<E>;
50    fn bitor(self, rhs: T) -> QFlags<E> {
51        Self {
52            value: self.value | rhs.into().value,
53            _phantom_data: PhantomData,
54        }
55    }
56}
57
58impl<E, T: Into<QFlags<E>>> BitAnd<T> for QFlags<E> {
59    type Output = QFlags<E>;
60    fn bitand(self, rhs: T) -> QFlags<E> {
61        Self {
62            value: self.value & rhs.into().value,
63            _phantom_data: PhantomData,
64        }
65    }
66}
67
68impl<E, T: Into<QFlags<E>>> BitXor<T> for QFlags<E> {
69    type Output = QFlags<E>;
70    fn bitxor(self, rhs: T) -> QFlags<E> {
71        Self {
72            value: self.value ^ rhs.into().value,
73            _phantom_data: PhantomData,
74        }
75    }
76}
77
78impl<E> Default for QFlags<E> {
79    fn default() -> Self {
80        QFlags {
81            value: 0,
82            _phantom_data: PhantomData,
83        }
84    }
85}
86
87impl<T> fmt::Debug for QFlags<T> {
88    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
89        write!(f, "QFlags({})", self.value)
90    }
91}