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
// SPDX-FileCopyrightText: 2021 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.com>
// SPDX-FileContributor: Andrew Hayzen <andrew.hayzen@kdab.com>
// SPDX-FileContributor: Gerhard de Clercq <gerhard.declercq@kdab.com>
//
// SPDX-License-Identifier: MIT OR Apache-2.0
use cxx::{type_id, ExternType};
use std::cmp::Ordering;
use std::fmt;
use std::mem::MaybeUninit;

#[cxx::bridge]
mod ffi {
    #[namespace = "Qt"]
    unsafe extern "C++" {
        include!("cxx-qt-lib/qt.h");
        type CaseSensitivity = crate::CaseSensitivity;
        type SplitBehaviorFlags = crate::SplitBehaviorFlags;
    }

    unsafe extern "C++" {
        include!("cxx-qt-lib/qbytearray.h");
        type QByteArray = crate::QByteArray;
        include!("cxx-qt-lib/qstring.h");
        type QString = super::QString;
        include!("cxx-qt-lib/qstringlist.h");
        type QStringList = crate::QStringList;

        /// Appends the string str onto the end of this string.
        fn append<'a>(self: &'a mut QString, str: &QString) -> &'a mut QString;

        /// Clears the contents of the string and makes it null.
        fn clear(self: &mut QString);

        // We wrap this method to provide an enum so hide it from docs
        #[doc(hidden)]
        #[rust_name = "compare_i32"]
        fn compare(self: &QString, other: &QString, cs: CaseSensitivity) -> i32;

        /// Returns true if this string contains an occurrence of the string str; otherwise returns false.
        fn contains(self: &QString, str: &QString, cs: CaseSensitivity) -> bool;

        /// Returns true if the string ends with s; otherwise returns false.
        #[rust_name = "ends_with"]
        fn endsWith(self: &QString, s: &QString, cs: CaseSensitivity) -> bool;

        /// Returns true if the string has no characters; otherwise returns false.
        #[rust_name = "is_empty"]
        fn isEmpty(self: &QString) -> bool;

        /// Returns true if the string is lowercase, that is, it's identical to its toLower() folding.
        #[rust_name = "is_lower"]
        fn isLower(self: &QString) -> bool;

        /// Returns true if this string is null; otherwise returns false.
        #[rust_name = "is_null"]
        fn isNull(self: &QString) -> bool;

        /// Returns true if the string is read right to left.
        #[rust_name = "is_right_to_left"]
        fn isRightToLeft(self: &QString) -> bool;

        /// Returns true if the string is uppercase, that is, it's identical to its toUpper() folding.
        #[rust_name = "is_upper"]
        fn isUpper(self: &QString) -> bool;

        /// Prepends the string str to the beginning of this string and returns a reference to this string.
        fn prepend<'a>(self: &'a mut QString, str: &QString) -> &'a mut QString;

        /// Removes every occurrence of the given str string in this string, and returns a reference to this string.
        fn remove<'a>(self: &'a mut QString, str: &QString, cs: CaseSensitivity)
            -> &'a mut QString;

        /// Replaces every occurrence of the string before with the string after and returns a reference to this string.
        fn replace<'a>(
            self: &'a mut QString,
            before: &QString,
            after: &QString,
            cs: CaseSensitivity,
        ) -> &'a mut QString;

        /// Returns true if the string starts with s; otherwise returns false.
        #[rust_name = "starts_with"]
        fn startsWith(self: &QString, s: &QString, cs: CaseSensitivity) -> bool;
    }

    #[namespace = "rust::cxxqtlib1"]
    unsafe extern "C++" {
        include!("cxx-qt-lib/common.h");

        #[doc(hidden)]
        #[rust_name = "qstring_drop"]
        fn drop(string: &mut QString);

        #[doc(hidden)]
        #[rust_name = "qstring_init_default"]
        fn construct() -> QString;
        #[doc(hidden)]
        #[rust_name = "qstring_init_from_rust_string"]
        fn qstringInitFromRustString(string: &str) -> QString;
        #[doc(hidden)]
        #[rust_name = "qstring_init_from_qstring"]
        fn construct(string: &QString) -> QString;

        #[doc(hidden)]
        #[rust_name = "qstring_eq"]
        fn operatorEq(a: &QString, b: &QString) -> bool;
        #[doc(hidden)]
        #[rust_name = "qstring_cmp"]
        fn operatorCmp(a: &QString, b: &QString) -> i8;

        #[doc(hidden)]
        #[rust_name = "qstring_to_rust_string"]
        fn qstringToRustString(string: &QString) -> String;

        #[doc(hidden)]
        #[rust_name = "qstring_arg"]
        fn qstringArg(string: &QString, a: &QString) -> QString;
        #[doc(hidden)]
        #[rust_name = "qstring_index_of"]
        fn qstringIndexOf(
            string: &QString,
            str: &QString,
            from: isize,
            cs: CaseSensitivity,
        ) -> isize;
        #[doc(hidden)]
        #[rust_name = "qstring_insert"]
        fn qstringInsert<'a>(string: &'a mut QString, pos: isize, str: &QString)
            -> &'a mut QString;
        #[doc(hidden)]
        #[rust_name = "qstring_left"]
        fn qstringLeft(string: &QString, n: isize) -> QString;
        #[doc(hidden)]
        #[rust_name = "qstring_len"]
        fn qstringLen(string: &QString) -> isize;
        #[doc(hidden)]
        #[rust_name = "qstring_mid"]
        fn qstringMid(string: &QString, position: isize, n: isize) -> QString;
        #[doc(hidden)]
        #[rust_name = "qstring_right"]
        fn qstringRight(string: &QString, n: isize) -> QString;
        #[doc(hidden)]
        #[rust_name = "qstring_simplified"]
        fn qstringSimplified(string: &QString) -> QString;
        #[doc(hidden)]
        #[rust_name = "qstring_split"]
        fn qstringSplit(
            string: &QString,
            sep: &QString,
            behavior: SplitBehaviorFlags,
            cs: CaseSensitivity,
        ) -> QStringList;
        #[doc(hidden)]
        #[rust_name = "qstring_to_latin1"]
        fn qstringToLatin1(string: &QString) -> QByteArray;
        #[doc(hidden)]
        #[rust_name = "qstring_to_local8bit"]
        fn qstringToLocal8Bit(string: &QString) -> QByteArray;
        #[doc(hidden)]
        #[rust_name = "qstring_to_lower"]
        fn qstringToLower(string: &QString) -> QString;
        #[doc(hidden)]
        #[rust_name = "qstring_to_upper"]
        fn qstringToUpper(string: &QString) -> QString;
        #[doc(hidden)]
        #[rust_name = "qstring_to_utf8"]
        fn qstringToUtf8(string: &QString) -> QByteArray;
        #[doc(hidden)]
        #[rust_name = "qstring_trimmed"]
        fn qstringTrimmed(string: &QString) -> QString;
    }
}

/// The QString class provides a Unicode character string.
///
/// Note that QString is a UTF-16 whereas Rust strings are a UTF-8
#[repr(C)]
pub struct QString {
    /// The layout has changed between Qt 5 and Qt 6
    ///
    /// Qt5 QString has one pointer as a member
    /// Qt6 QString has one member, which contains two pointers and a size_t
    #[cfg(qt_version_major = "5")]
    _space: MaybeUninit<usize>,
    #[cfg(qt_version_major = "6")]
    _space: MaybeUninit<[usize; 3]>,
}

impl Clone for QString {
    /// Constructs a copy of other.
    ///
    /// This operation takes constant time, because QString is implicitly shared.
    /// This makes returning a QString from a function very fast.
    /// If a shared instance is modified, it will be copied (copy-on-write), and that takes linear time.
    fn clone(&self) -> Self {
        ffi::qstring_init_from_qstring(self)
    }
}

impl Default for QString {
    /// Constructs a null string. Null strings are also empty.
    fn default() -> Self {
        ffi::qstring_init_default()
    }
}

impl PartialEq for QString {
    fn eq(&self, other: &Self) -> bool {
        ffi::qstring_eq(self, other)
    }
}

impl Eq for QString {}

impl PartialOrd for QString {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        0.partial_cmp(&ffi::qstring_cmp(self, other))
    }
}

impl Ord for QString {
    fn cmp(&self, other: &Self) -> Ordering {
        self.partial_cmp(other).unwrap()
    }
}

impl fmt::Display for QString {
    /// Convert the QString to a Rust string
    ///
    /// Note that this converts from UTF-16 to UTF-8
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", <&QString as Into<String>>::into(self))
    }
}

impl fmt::Debug for QString {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{self}")
    }
}

impl std::ops::Add for QString {
    type Output = Self;
    fn add(self, other: Self) -> Self {
        let mut res = ffi::qstring_init_from_qstring(&self);
        res.append(&other);
        res
    }
}

impl Drop for QString {
    /// Destroys the string.
    fn drop(&mut self) {
        ffi::qstring_drop(self)
    }
}

impl From<&str> for QString {
    /// Constructs a QString from a Rust string
    ///
    /// Note that this converts from UTF-8 to UTF-16
    fn from(str: &str) -> Self {
        ffi::qstring_init_from_rust_string(str)
    }
}

impl From<&String> for QString {
    /// Constructs a QString from a Rust string
    ///
    /// Note that this converts from UTF-8 to UTF-16
    fn from(str: &String) -> Self {
        ffi::qstring_init_from_rust_string(str)
    }
}

impl From<&QString> for String {
    /// Convert the QString to a Rust string
    ///
    /// Note that this converts from UTF-16 to UTF-8
    fn from(qstring: &QString) -> Self {
        ffi::qstring_to_rust_string(qstring)
    }
}

impl QString {
    /// Returns a copy of this string with the lowest numbered place marker replaced by string a, i.e., %1, %2, ..., %99.
    pub fn arg(&self, a: &QString) -> Self {
        ffi::qstring_arg(self, a)
    }

    /// Lexically compares this string with the other string and
    /// returns if this string is less than, equal to, or greater than the other string.
    pub fn compare(&self, other: &QString, cs: ffi::CaseSensitivity) -> Ordering {
        0.cmp(&self.compare_i32(other, cs))
    }

    /// Returns the index position of the first occurrence of the string str in this string,
    /// searching forward from index position from. Returns -1 if str is not found.
    pub fn index_of(&self, str: &QString, from: isize, cs: ffi::CaseSensitivity) -> isize {
        ffi::qstring_index_of(self, str, from, cs)
    }

    /// Inserts the string str at the given index position and returns a mutable reference to this string.
    pub fn insert<'a>(&'a mut self, pos: isize, str: &Self) -> &'a mut Self {
        ffi::qstring_insert(self, pos, str)
    }

    /// Returns a substring that contains the n leftmost characters of the string.
    pub fn left(&self, n: isize) -> Self {
        ffi::qstring_left(self, n)
    }

    /// Returns the number of characters in this string.
    pub fn len(self: &QString) -> isize {
        ffi::qstring_len(self)
    }

    /// Returns a string that contains n characters of this string, starting at the specified position index.
    pub fn mid(&self, position: isize, n: isize) -> Self {
        ffi::qstring_mid(self, position, n)
    }

    /// Returns a substring that contains the n rightmost characters of the string.
    pub fn right(&self, n: isize) -> Self {
        ffi::qstring_right(self, n)
    }

    /// Returns a string that has whitespace removed from the start and the end,
    /// and that has each sequence of internal whitespace replaced with a single space.
    pub fn simplified(&self) -> Self {
        ffi::qstring_simplified(self)
    }

    /// Splits the string into substrings wherever sep occurs, and returns the list of those strings.
    /// If sep does not match anywhere in the string, split() returns a single-element list containing this string.
    pub fn split(
        &self,
        sep: &QString,
        behavior: ffi::SplitBehaviorFlags,
        cs: ffi::CaseSensitivity,
    ) -> ffi::QStringList {
        ffi::qstring_split(self, sep, behavior, cs)
    }

    /// Returns a Latin-1 representation of the string as a QByteArray.
    pub fn to_latin1(&self) -> ffi::QByteArray {
        ffi::qstring_to_latin1(self)
    }

    /// Returns the local 8-bit representation of the string as a QByteArray.
    /// The returned byte array is undefined if the string contains characters not supported by the local 8-bit encoding.
    pub fn to_local8bit(&self) -> ffi::QByteArray {
        ffi::qstring_to_local8bit(self)
    }

    /// Returns a lowercase copy of the string.
    pub fn to_lower(&self) -> Self {
        ffi::qstring_to_lower(self)
    }

    /// Returns an uppercase copy of the string.
    pub fn to_upper(&self) -> Self {
        ffi::qstring_to_upper(self)
    }

    /// Returns a UTF-8 representation of the string as a QByteArray.
    pub fn to_utf8(&self) -> ffi::QByteArray {
        ffi::qstring_to_utf8(self)
    }

    /// Returns a string that has whitespace removed from the start and the end.
    pub fn trimmed(&self) -> Self {
        ffi::qstring_trimmed(self)
    }
}

// Safety:
//
// Static checks on the C++ side to ensure the size is the same.
unsafe impl ExternType for QString {
    type Id = type_id!("QString");
    type Kind = cxx::kind::Trivial;
}