1use crate::internal_prelude::*;
2use crate::QString;
3use std::fmt::Display;
4use std::os::raw::c_char;
5use std::str::Utf8Error;
6
7cpp! {{
8 #include <QtCore/QString>
9 #include <QtCore/QByteArray>
10}}
11
12cpp_class!(
13 /// Wrapper around [`QByteArray`][class] class.
14 ///
15 /// [class]: https://doc.qt.io/qt-5/qbytearray.html
16 #[derive(PartialEq, PartialOrd, Eq, Ord)]
17 pub unsafe struct QByteArray as "QByteArray"
18);
19impl QByteArray {
20 pub fn to_slice(&self) -> &[u8] {
21 unsafe {
22 let mut size: usize = 0;
23 let c_ptr: *const u8 = cpp!([self as "const QByteArray*", mut size as "size_t"] -> *const u8 as "const char*" {
24 size = self->size();
25 return self->constData();
26 });
27 std::slice::from_raw_parts(data:c_ptr, len:size)
28 }
29 }
30 pub fn to_str(&self) -> Result<&str, Utf8Error> {
31 std::str::from_utf8(self.to_slice())
32 }
33}
34impl<'a> From<&'a [u8]> for QByteArray {
35 /// Constructs a `QByteArray` from a slice. (Copy the slice.)
36 fn from(s: &'a [u8]) -> QByteArray {
37 let len: usize = s.len();
38 let ptr: *const u8 = s.as_ptr();
39 cpp!(unsafe [len as "size_t", ptr as "char*"] -> QByteArray as "QByteArray" {
40 return QByteArray(ptr, len);
41 })
42 }
43}
44impl<'a> From<&'a str> for QByteArray {
45 /// Constructs a `QByteArray` from a `&str`. (Copy the string.)
46 fn from(s: &'a str) -> QByteArray {
47 s.as_bytes().into()
48 }
49}
50impl From<String> for QByteArray {
51 /// Constructs a `QByteArray` from a `String`. (Copy the string.)
52 fn from(s: String) -> QByteArray {
53 QByteArray::from(&*s)
54 }
55}
56impl From<QString> for QByteArray {
57 /// Converts a `QString` to a `QByteArray`
58 fn from(s: QString) -> QByteArray {
59 cpp!(unsafe [s as "QString"] -> QByteArray as "QByteArray" {
60 return std::move(s).toUtf8();
61 })
62 }
63}
64impl Display for QByteArray {
65 /// Prints the contents of the `QByteArray` if it contains UTF-8, do nothing otherwise.
66 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
67 unsafe {
68 let c_ptr: *const i8 = cpp!([self as "const QByteArray*"] -> *const c_char as "const char*" {
69 return self->constData();
70 });
71 f.write_str(data:std::ffi::CStr::from_ptr(c_ptr).to_str().map_err(|_| Default::default())?)
72 }
73 }
74}
75impl std::fmt::Debug for QByteArray {
76 /// Prints the contents of the `QByteArray` if it contains UTF-8, nothing otherwise
77 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
78 write!(f, "{}", self)
79 }
80}
81

Provided by KDAB

Privacy Policy