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
use crate::internal_prelude::*;
use crate::qtcore::{QByteArray, QUrl, UnicodeVersion};

use std::convert::TryFrom;
use std::fmt::Display;
use std::ops::{Add, AddAssign};
use std::path::{Path, PathBuf};

cpp! {{
    #include <QtCore/QString>
    #include <QtCore/QUrl>
}}

/// Bindings for [`QString::NormalizationForm`][enum] enum.
///
/// [enum]: https://doc.qt.io/qt-5/qstring.html#NormalizationForm-enum
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Debug)]
#[allow(non_camel_case_types)]
pub enum NormalizationForm {
    NormalizationForm_D = 0,
    NormalizationForm_C = 1,
    NormalizationForm_KD = 2,
    NormalizationForm_KC = 3,
}

cpp_class!(
    /// Wrapper around [`QString`][class] class.
    ///
    /// [class]: https://doc.qt.io/qt-5/qstring.html
    #[derive(PartialEq, PartialOrd, Eq, Ord)]
    pub unsafe struct QString as "QString"
);
impl QString {
    /// Return a slice containing the UTF-16 data.
    pub fn to_slice(&self) -> &[u16] {
        unsafe {
            let mut size: usize = 0;
            let c_ptr = cpp!([self as "const QString*", mut size as "size_t"] -> *const u16 as "const QChar*" {
                size = self->size();
                return self->constData();
            });
            std::slice::from_raw_parts(c_ptr, size)
        }
    }

    /// Wrapper around [`bool QString::isEmpty() const`][method] method
    ///
    /// [method]: https://doc.qt.io/qt-5/qstring.html#isEmpty
    /// ```
    /// use qttypes::QString;
    ///
    /// assert!(QString::default().is_empty());
    /// assert!(QString::from("").is_empty());
    /// assert!(!QString::from("abc").is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        cpp!(unsafe [self as "const QString*"] -> bool as "bool" {
            return self->isEmpty();
        })
    }

    /// Wrapper around [`bool QString::isNull() const`][method] method
    ///
    /// [method]: https://doc.qt.io/qt-5/qstring.html#isNull
    /// ```
    /// use qttypes::QString;
    ///
    /// assert!(QString::default().is_null());
    /// assert!(!QString::from("").is_null());
    /// assert!(!QString::from("abc").is_null());
    /// ```
    pub fn is_null(&self) -> bool {
        cpp!(unsafe [self as "const QString*"] -> bool as "bool" {
            return self->isNull();
        })
    }

    /// Returns the number of characters in this string.
    pub fn len(&self) -> usize {
        cpp!(unsafe [self as "const QString*"] -> usize as "size_t" {
            return self->length();
        })
    }

    /// Wrapper around [`bool QString::isUpper() const`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qstring.html#isUpper
    #[cfg(qt_5_12)]
    pub fn is_upper(&self) -> bool {
        cpp!(unsafe [self as "const QString*"] -> bool as "bool" {
            #if QT_VERSION >= QT_VERSION_CHECK(5,12,0)
            return self->isUpper();
            #else
            return false;
            #endif
        })
    }

    /// Wrapper around [`void QString::shrink_to_fit()`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qstring.html#shrink_to_fit
    pub fn shrink_to_fit(&mut self) {
        cpp!(unsafe [self as "QString*"] {
            self->squeeze();
        })
    }

    /// Wrapper around [`QString QString::toUpper() const`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qstring.html#toUpper
    pub fn to_upper(&self) -> QString {
        cpp!(unsafe [self as "const QString*"] -> QString as "QString" {
            return self->toUpper();
        })
    }

    /// Wrapper around [`QString QString::toLower() const`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qstring.html#toLower
    pub fn to_lower(&self) -> QString {
        cpp!(unsafe [self as "const QString*"] -> QString as "QString" {
            return self->toLower();
        })
    }

    /// Wrapper around [`QString QString::trimmed() const`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qstring.html#trimmed
    pub fn trimmed(&self) -> QString {
        cpp!(unsafe [self as "const QString*"] -> QString as "QString" {
            return self->trimmed();
        })
    }

    /// Wrapper around [`QString QString::toCascadeFold() const`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qstring.html#toCascadeFold
    pub fn to_case_folded(&self) -> QString {
        cpp!(unsafe [self as "const QString*"] -> QString as "QString" {
            return self->toCaseFolded();
        })
    }

    /// Wrapper around [`QString QString::simplified() const`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qstring.html#simplified
    pub fn simplified(&self) -> QString {
        cpp!(unsafe [self as "const QString*"] -> QString as "QString" {
            return self->simplified();
        })
    }

    /// Wrapper around [`int QString::toInt(bool *ok = nullptr, int base = 10) const`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qstring.html#toInt
    pub fn to_int(&self, base: i32) -> Result<i32, ()> {
        let flag: *mut bool = &mut false;
        unsafe {
            let t = cpp!([self as "const QString*", flag as "bool*", base as "int32_t"] -> i32 as "int32_t" {
                return self->toInt(flag, base);
            });
            flag_check(*flag, t, ())
        }
    }

    /// Wrapper around [`qlonglong QString::toLongLong(bool *ok = nullptr, int base = 10) const`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qstring.html#toLongLong
    pub fn to_long_long(&self, base: i32) -> Result<i64, ()> {
        let flag: *mut bool = &mut false;
        unsafe {
            let t = cpp!([self as "const QString*", flag as "bool*", base as "int32_t"] -> i64 as "qlonglong" {
                return self->toLongLong(flag, base);
            });
            flag_check(*flag, t, ())
        }
    }

    /// Wrapper around [`QString QString::normalized(QString::NormalizationForm mode, QChar::UnicodeVersion version = QChar::Unicode_Unassigned) const`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qstring.html#normalized
    pub fn normalized(&self, mode: NormalizationForm, version: UnicodeVersion) -> QString {
        cpp!(unsafe [self as "const QString*", mode as "QString::NormalizationForm", version as "QChar::UnicodeVersion"] -> QString as "QString" {
            return self->normalized(mode, version);
        })
    }

    /// Wrapper around [`QString QString::append(const QString &str)`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qstring.html#append
    pub fn append(&mut self, other: QString) -> QString {
        cpp!(unsafe [self as "QString*", other as "QString"] -> QString as "QString" {
            return self->append(other);
        })
    }
}

impl From<QUrl> for QString {
    /// Wrapper around [`QUrl::toString(QUrl::FormattingOptions=...)`][method] method.
    ///
    /// # Wrapper-specific
    ///
    /// Formatting options are left at defaults.
    ///
    /// [method]: https://doc.qt.io/qt-5/qurl.html#toString
    fn from(qurl: QUrl) -> QString {
        cpp!(unsafe [qurl as "QUrl"] -> QString as "QString" {
            return qurl.toString();
        })
    }
}
impl<'a> From<&'a str> for QString {
    /// Copy the data from a `&str`.
    fn from(s: &'a str) -> QString {
        let len = s.len();
        let ptr = s.as_ptr();
        cpp!(unsafe [len as "size_t", ptr as "char*"] -> QString as "QString" {
            return QString::fromUtf8(ptr, len);
        })
    }
}

impl TryFrom<&Path> for QString {
    type Error = ();

    fn try_from(s: &Path) -> Result<Self, Self::Error> {
        Ok(QString::from(s.to_str().ok_or(())?))
    }
}

impl From<QString> for PathBuf {
    fn from(s: QString) -> Self {
        PathBuf::from(s.to_string())
    }
}

impl From<String> for QString {
    fn from(s: String) -> QString {
        QString::from(&*s)
    }
}

impl Into<String> for QString {
    fn into(self) -> String {
        String::from_utf16_lossy(self.to_slice())
    }
}

impl Display for QString {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        QByteArray::from(self.clone()).fmt(f)
    }
}

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

impl TryFrom<QString> for f64 {
    type Error = ();

    fn try_from(value: QString) -> Result<Self, Self::Error> {
        let flag: *mut bool = &mut false;
        unsafe {
            let t = cpp!([value as "QString", flag as "bool*"] -> f64 as "double" {
                return value.toDouble(flag);
            });
            flag_check(*flag, t, ())
        }
    }
}

impl TryFrom<QString> for f32 {
    type Error = ();

    fn try_from(value: QString) -> Result<Self, Self::Error> {
        let flag: *mut bool = &mut false;
        unsafe {
            let t = cpp!([value as "QString", flag as "bool*"] -> f32 as "float" {
                return value.toFloat(flag);
            });
            flag_check(*flag, t, ())
        }
    }
}

impl TryFrom<QString> for i32 {
    type Error = ();

    fn try_from(value: QString) -> Result<Self, Self::Error> {
        value.to_int(10)
    }
}

impl TryFrom<QString> for i64 {
    type Error = ();

    fn try_from(value: QString) -> Result<Self, Self::Error> {
        value.to_long_long(10)
    }
}

impl TryFrom<QString> for i16 {
    type Error = ();

    fn try_from(value: QString) -> Result<Self, Self::Error> {
        let flag: *mut bool = &mut false;
        unsafe {
            let t = cpp!([value as "QString", flag as "bool*"] -> i16 as "int16_t" {
                return value.toShort(flag);
            });
            flag_check(*flag, t, ())
        }
    }
}

impl Add for QString {
    type Output = QString;

    fn add(mut self, rhs: Self) -> Self::Output {
        self.append(rhs)
    }
}

impl AddAssign for QString {
    fn add_assign(&mut self, rhs: Self) {
        self.append(rhs);
    }
}

#[inline]
fn flag_check<T, E>(flag: bool, ans: T, err: E) -> Result<T, E> {
    if flag {
        Ok(ans)
    } else {
        Err(err)
    }
}

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

    #[test]
    fn basic() {
        let upper = QString::from("ABC");
        let lower = QString::from("abc");

        assert_eq!(lower.len(), 3);

        #[cfg(qt_5_12)]
        assert!(upper.is_upper());
        #[cfg(qt_5_12)]
        assert!(!lower.is_upper());

        assert_eq!(lower.to_upper(), upper);
        assert_eq!(upper.to_lower(), lower);
        assert_eq!(
            QString::from("  lots\t of\nwhitespace\r\n ").simplified(),
            QString::from("lots of whitespace")
        );
        assert_eq!(upper.to_lower(), upper.to_case_folded());

        assert_eq!(QString::from(" ABC Hello\n").trimmed(), QString::from("ABC Hello"));
    }

    #[test]
    fn conversions() {
        assert_eq!(f64::try_from(QString::from("1.54")), Ok(1.54));
        assert!(f64::try_from(QString::from("abc")).is_err());

        assert_eq!(f32::try_from(QString::from("1.54")), Ok(1.54));
        assert!(f32::try_from(QString::from("abc")).is_err());

        assert_eq!(i32::try_from(QString::from("29")), Ok(29));
        assert!(i32::try_from(QString::from("abc")).is_err());

        assert_eq!(i64::try_from(QString::from("99487489")), Ok(99487489));
        assert!(i64::try_from(QString::from("abc")).is_err());

        assert_eq!(i16::try_from(QString::from("-32")), Ok(-32));
        assert!(i16::try_from(QString::from("abc")).is_err());

        let p = PathBuf::from("/home/ayush/");
        let qstr = QString::try_from(p.as_path()).unwrap();
        assert_eq!(p, PathBuf::from(qstr));
    }

    #[test]
    fn append() {
        let mut str1 = QString::from("abc");
        let str2 = QString::from("efg");

        let mut s = str1.append(str2.clone());
        assert_eq!(str1, "abcefg".into());
        assert_eq!(s, str1);

        // Check that s and str1 do not point to same underlying QString.
        s.append("123".into());

        str1 += str2;
        assert_eq!(str1, "abcefgefg".into());

        let str3 = QString::from("abcef") + QString::from("gefg");
        assert_eq!(str1, str3);
    }
}