qt_core/
impl_q_string.rs

1use crate::QString;
2use cpp_core::CppBox;
3use std::os::raw::{c_char, c_int};
4
5/// Allows to convert Qt strings to `std` strings
6impl<'a> From<&'a QString> for String {
7    fn from(s: &'a QString) -> String {
8        s.to_std_string()
9    }
10}
11
12impl QString {
13    /// Creates Qt string from an `std` string.
14    ///
15    /// `QString` makes a deep copy of the data.
16    pub fn from_std_str<S: AsRef<str>>(s: S) -> CppBox<QString> {
17        let slice = s.as_ref().as_bytes();
18        unsafe { QString::from_utf8_char_int(slice.as_ptr() as *mut c_char, slice.len() as c_int) }
19    }
20
21    /// Creates an `std` string from a Qt string.
22    pub fn to_std_string(&self) -> String {
23        unsafe {
24            let buf = self.to_utf8();
25            let bytes =
26                std::slice::from_raw_parts(buf.const_data() as *const u8, buf.size() as usize);
27            std::str::from_utf8_unchecked(bytes).to_string()
28        }
29    }
30}
31
32/// Creates a `QString` from a Rust string.
33///
34/// This is the same as `QString::from_std_str(str)`.
35pub fn qs<S: AsRef<str>>(str: S) -> CppBox<QString> {
36    QString::from_std_str(str)
37}