i_slint_core/
string.rs

1// Copyright © SixtyFPS GmbH <info@slint.dev>
2// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
3
4//! module for the SharedString and related things
5
6#![allow(unsafe_code)]
7#![warn(missing_docs)]
8
9use crate::SharedVector;
10use alloc::string::String;
11use core::fmt::{Debug, Display, Write};
12use core::ops::Deref;
13#[cfg(not(feature = "std"))]
14#[allow(unused)]
15use num_traits::Float;
16
17/// This macro is the same as [`std::format!`], but it returns a [`SharedString`] instead.
18///
19/// ### Example
20/// ```rust
21/// let s : slint::SharedString = slint::format!("Hello {}", "world");
22/// assert_eq!(s, slint::SharedString::from("Hello world"));
23/// ```
24#[macro_export]
25macro_rules! format {
26    ($($arg:tt)*) => {{
27        $crate::string::format(core::format_args!($($arg)*))
28    }}
29}
30
31/// A string type used by the Slint run-time.
32///
33/// SharedString uses implicit data sharing to make it efficient to pass around copies. When
34/// cloning, a reference to the data is cloned, not the data itself. The data itself is only copied
35/// when modifying it, for example using [push_str](SharedString::push_str). This is also called copy-on-write.
36///
37/// Under the hood the string data is UTF-8 encoded and it is always terminated with a null character.
38///
39/// `SharedString` implements [`Deref<Target=str>`] so it can be easily passed to any function taking a `&str`.
40/// It also implement `From` such that it an easily be converted to and from the typical rust String type with `.into()`
41#[derive(Clone, Default)]
42#[repr(C)]
43pub struct SharedString {
44    // Invariant: valid utf-8, `\0` terminated
45    inner: SharedVector<u8>,
46}
47
48impl SharedString {
49    /// Creates a new empty string
50    ///
51    /// Same as `SharedString::default()`
52    pub fn new() -> Self {
53        Self::default()
54    }
55
56    fn as_ptr(&self) -> *const u8 {
57        self.inner.as_ptr()
58    }
59
60    /// Size of the string, in bytes. This excludes the terminating null character.
61    pub fn len(&self) -> usize {
62        self.inner.len().saturating_sub(1)
63    }
64
65    /// Return true if the String is empty
66    pub fn is_empty(&self) -> bool {
67        self.len() == 0
68    }
69
70    /// Return a slice to the string
71    pub fn as_str(&self) -> &str {
72        // Safety: self.as_ptr is a pointer from the inner which has utf-8
73        unsafe {
74            core::str::from_utf8_unchecked(core::slice::from_raw_parts(self.as_ptr(), self.len()))
75        }
76    }
77
78    /// Append a string to this string
79    ///
80    /// ```
81    /// # use i_slint_core::SharedString;
82    /// let mut hello = SharedString::from("Hello");
83    /// hello.push_str(", ");
84    /// hello.push_str("World");
85    /// hello.push_str("!");
86    /// assert_eq!(hello, "Hello, World!");
87    /// ```
88    pub fn push_str(&mut self, x: &str) {
89        let mut iter = x.as_bytes().iter().copied();
90        if self.inner.is_empty() {
91            self.inner.extend(iter.chain(core::iter::once(0)));
92        } else if let Some(first) = iter.next() {
93            // We skip the `first` from `iter` because we will write it at the
94            // location of the previous `\0`, after extend did the re-alloc of the
95            // right size
96            let prev_len = self.len();
97            self.inner.extend(iter.chain(core::iter::once(0)));
98            self.inner.make_mut_slice()[prev_len] = first;
99        }
100    }
101}
102
103impl Deref for SharedString {
104    type Target = str;
105    fn deref(&self) -> &Self::Target {
106        self.as_str()
107    }
108}
109
110impl From<&str> for SharedString {
111    fn from(value: &str) -> Self {
112        SharedString {
113            inner: SharedVector::from_iter(
114                value.as_bytes().iter().cloned().chain(core::iter::once(0)),
115            ),
116        }
117    }
118}
119
120impl Debug for SharedString {
121    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
122        Debug::fmt(self.as_str(), f)
123    }
124}
125
126impl Display for SharedString {
127    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
128        Display::fmt(self.as_str(), f)
129    }
130}
131
132impl AsRef<str> for SharedString {
133    #[inline]
134    fn as_ref(&self) -> &str {
135        self.as_str()
136    }
137}
138
139#[cfg(feature = "serde")]
140impl serde::Serialize for SharedString {
141    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
142    where
143        S: serde::Serializer,
144    {
145        let string = self.as_str();
146        serializer.serialize_str(string)
147    }
148}
149
150#[cfg(feature = "serde")]
151impl<'de> serde::Deserialize<'de> for SharedString {
152    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
153    where
154        D: serde::Deserializer<'de>,
155    {
156        let string = String::deserialize(deserializer)?;
157        Ok(SharedString::from(string))
158    }
159}
160
161#[cfg(feature = "std")]
162impl AsRef<std::ffi::CStr> for SharedString {
163    #[inline]
164    fn as_ref(&self) -> &std::ffi::CStr {
165        if self.inner.is_empty() {
166            return Default::default();
167        }
168        // Safety: we ensure that there is always a terminated \0
169        debug_assert_eq!(self.inner.as_slice()[self.inner.len() - 1], 0);
170        unsafe { std::ffi::CStr::from_bytes_with_nul_unchecked(self.inner.as_slice()) }
171    }
172}
173
174#[cfg(feature = "std")]
175impl AsRef<std::path::Path> for SharedString {
176    #[inline]
177    fn as_ref(&self) -> &std::path::Path {
178        self.as_str().as_ref()
179    }
180}
181
182#[cfg(feature = "std")]
183impl AsRef<std::ffi::OsStr> for SharedString {
184    #[inline]
185    fn as_ref(&self) -> &std::ffi::OsStr {
186        self.as_str().as_ref()
187    }
188}
189
190impl AsRef<[u8]> for SharedString {
191    #[inline]
192    fn as_ref(&self) -> &[u8] {
193        self.as_str().as_bytes()
194    }
195}
196
197impl<T> PartialEq<T> for SharedString
198where
199    T: ?Sized + AsRef<str>,
200{
201    fn eq(&self, other: &T) -> bool {
202        self.as_str() == other.as_ref()
203    }
204}
205impl Eq for SharedString {}
206
207impl<T> PartialOrd<T> for SharedString
208where
209    T: ?Sized + AsRef<str>,
210{
211    fn partial_cmp(&self, other: &T) -> Option<core::cmp::Ordering> {
212        PartialOrd::partial_cmp(self.as_str(), other.as_ref())
213    }
214}
215impl Ord for SharedString {
216    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
217        Ord::cmp(self.as_str(), other.as_str())
218    }
219}
220
221impl From<String> for SharedString {
222    fn from(s: String) -> Self {
223        s.as_str().into()
224    }
225}
226
227impl From<&String> for SharedString {
228    fn from(s: &String) -> Self {
229        s.as_str().into()
230    }
231}
232
233impl From<char> for SharedString {
234    fn from(c: char) -> Self {
235        SharedString::from(c.encode_utf8(&mut [0; 6]) as &str)
236    }
237}
238
239impl From<SharedString> for String {
240    fn from(s: SharedString) -> String {
241        s.as_str().into()
242    }
243}
244
245impl From<&SharedString> for String {
246    fn from(s: &SharedString) -> String {
247        s.as_str().into()
248    }
249}
250
251impl core::ops::AddAssign<&str> for SharedString {
252    fn add_assign(&mut self, other: &str) {
253        self.push_str(other);
254    }
255}
256
257impl core::ops::Add<&str> for SharedString {
258    type Output = SharedString;
259    fn add(mut self, other: &str) -> SharedString {
260        self.push_str(other);
261        self
262    }
263}
264
265impl core::hash::Hash for SharedString {
266    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
267        self.as_str().hash(state)
268    }
269}
270
271impl Write for SharedString {
272    fn write_str(&mut self, s: &str) -> core::fmt::Result {
273        self.push_str(s);
274        Ok(())
275    }
276}
277
278impl core::borrow::Borrow<str> for SharedString {
279    fn borrow(&self) -> &str {
280        self.as_str()
281    }
282}
283
284/// Same as [`std::fmt::format()`], but return a [`SharedString`] instead
285pub fn format(args: core::fmt::Arguments<'_>) -> SharedString {
286    // unfortunately, the estimated_capacity is unstable
287    //let capacity = args.estimated_capacity();
288    let mut output = SharedString::default();
289    output.write_fmt(args).unwrap();
290    output
291}
292
293/// A trait for converting a value to a [`SharedString`].
294///
295/// This trait is automatically implemented for any type which implements the [`Display`] trait as long as the trait is in scope.
296/// As such, `ToSharedString` shouldn’t be implemented directly: [`Display`] should be implemented instead, and you get the `ToSharedString` implementation for free.
297pub trait ToSharedString {
298    /// Converts the given value to a [`SharedString`].
299    fn to_shared_string(&self) -> SharedString;
300}
301
302impl<T> ToSharedString for T
303where
304    T: Display + ?Sized,
305{
306    fn to_shared_string(&self) -> SharedString {
307        format!("{}", self)
308    }
309}
310
311/// Convert a f62 to a SharedString
312pub fn shared_string_from_number(n: f64) -> SharedString {
313    // Number from which the increment of f32 is 1, so that we print enough precision to be able to represent all integers
314    if n < 16777216. {
315        crate::format!("{}", n as f32)
316    } else {
317        crate::format!("{}", n)
318    }
319}
320
321/// Convert a f64 to a SharedString with a fixed number of digits after the decimal point
322pub fn shared_string_from_number_fixed(n: f64, digits: usize) -> SharedString {
323    crate::format!("{number:.digits$}", number = n, digits = digits)
324}
325
326/// Convert a f64 to a SharedString following a similar logic as JavaScript's Number.toPrecision()
327pub fn shared_string_from_number_precision(n: f64, precision: usize) -> SharedString {
328    let exponent = f64::log10(n.abs()).floor() as isize;
329    if precision == 0 {
330        shared_string_from_number(n)
331    } else if exponent < -6 || (exponent >= 0 && exponent as usize >= precision) {
332        crate::format!(
333            "{number:.digits$e}",
334            number = n,
335            digits = precision.saturating_add_signed(-1)
336        )
337    } else {
338        shared_string_from_number_fixed(n, precision.saturating_add_signed(-(exponent + 1)))
339    }
340}
341
342#[test]
343fn simple_test() {
344    use std::string::ToString;
345    let x = SharedString::from("hello world!");
346    assert_eq!(x, "hello world!");
347    assert_ne!(x, "hello world?");
348    assert_eq!(x, x.clone());
349    assert_eq!("hello world!", x.as_str());
350    let string = String::from("hello world!");
351    assert_eq!(x, string);
352    assert_eq!(x.to_string(), string);
353    let def = SharedString::default();
354    assert_eq!(def, SharedString::default());
355    assert_eq!(def, SharedString::new());
356    assert_ne!(def, x);
357    assert_eq!(
358        (&x as &dyn AsRef<std::ffi::CStr>).as_ref(),
359        &*std::ffi::CString::new("hello world!").unwrap()
360    );
361    assert_eq!(SharedString::from('h'), "h");
362    assert_eq!(SharedString::from('😎'), "😎");
363}
364
365#[test]
366fn threading() {
367    let shared_cst = SharedString::from("Hello there!");
368    let shared_mtx = std::sync::Arc::new(std::sync::Mutex::new(SharedString::from("Shared:")));
369    let mut handles = std::vec![];
370    for _ in 0..20 {
371        let cst = shared_cst.clone();
372        let mtx = shared_mtx.clone();
373        handles.push(std::thread::spawn(move || {
374            assert_eq!(cst, "Hello there!");
375            let mut cst2 = cst.clone();
376            cst2.push_str(" ... or not?");
377            assert_eq!(cst2, "Hello there! ... or not?");
378            assert_eq!(cst.clone(), "Hello there!");
379
380            let shared = {
381                let mut lock = mtx.lock().unwrap();
382                assert!(lock.starts_with("Shared:"));
383                lock.push_str("!");
384                lock.clone()
385            };
386            assert!(shared.clone().starts_with("Shared:"));
387        }));
388    }
389    for j in handles {
390        j.join().unwrap();
391    }
392    assert_eq!(shared_cst.clone(), "Hello there!");
393    assert_eq!(shared_mtx.lock().unwrap().as_str(), "Shared:!!!!!!!!!!!!!!!!!!!!");
394    // 20x"!"
395}
396
397#[test]
398fn to_shared_string() {
399    let i = 5.1;
400    let five = SharedString::from("5.1");
401
402    assert_eq!(five, i.to_shared_string());
403}
404
405#[cfg(feature = "ffi")]
406pub(crate) mod ffi {
407    use super::*;
408
409    /// for cbindgen.
410    #[allow(non_camel_case_types)]
411    type c_char = u8;
412
413    #[unsafe(no_mangle)]
414    /// Returns a nul-terminated pointer for this string.
415    /// The returned value is owned by the string, and should not be used after any
416    /// mutable function have been called on the string, and must not be freed.
417    pub extern "C" fn slint_shared_string_bytes(ss: &SharedString) -> *const c_char {
418        if ss.is_empty() {
419            "\0".as_ptr()
420        } else {
421            ss.as_ptr()
422        }
423    }
424
425    #[unsafe(no_mangle)]
426    /// Destroy the shared string
427    pub unsafe extern "C" fn slint_shared_string_drop(ss: *const SharedString) {
428        core::ptr::read(ss);
429    }
430
431    #[unsafe(no_mangle)]
432    /// Increment the reference count of the string.
433    /// The resulting structure must be passed to slint_shared_string_drop
434    pub unsafe extern "C" fn slint_shared_string_clone(out: *mut SharedString, ss: &SharedString) {
435        core::ptr::write(out, ss.clone())
436    }
437
438    #[unsafe(no_mangle)]
439    /// Safety: bytes must be a valid utf-8 string of size len without null inside.
440    /// The resulting structure must be passed to slint_shared_string_drop
441    pub unsafe extern "C" fn slint_shared_string_from_bytes(
442        out: *mut SharedString,
443        bytes: *const c_char,
444        len: usize,
445    ) {
446        let str = core::str::from_utf8(core::slice::from_raw_parts(bytes, len)).unwrap();
447        core::ptr::write(out, SharedString::from(str));
448    }
449
450    /// Create a string from a number.
451    /// The resulting structure must be passed to slint_shared_string_drop
452    #[unsafe(no_mangle)]
453    pub unsafe extern "C" fn slint_shared_string_from_number(out: *mut SharedString, n: f64) {
454        let str = shared_string_from_number(n);
455        core::ptr::write(out, str);
456    }
457
458    #[test]
459    fn test_slint_shared_string_from_number() {
460        unsafe {
461            let mut s = core::mem::MaybeUninit::uninit();
462            slint_shared_string_from_number(s.as_mut_ptr(), 45.);
463            assert_eq!(s.assume_init(), "45");
464
465            let mut s = core::mem::MaybeUninit::uninit();
466            slint_shared_string_from_number(s.as_mut_ptr(), 45.12);
467            assert_eq!(s.assume_init(), "45.12");
468
469            let mut s = core::mem::MaybeUninit::uninit();
470            slint_shared_string_from_number(s.as_mut_ptr(), -1325466.);
471            assert_eq!(s.assume_init(), "-1325466");
472
473            let mut s = core::mem::MaybeUninit::uninit();
474            slint_shared_string_from_number(s.as_mut_ptr(), 0.);
475            assert_eq!(s.assume_init(), "0");
476
477            let mut s = core::mem::MaybeUninit::uninit();
478            slint_shared_string_from_number(
479                s.as_mut_ptr(),
480                ((1235.82756f32 * 1000f32).round() / 1000f32) as _,
481            );
482            assert_eq!(s.assume_init(), "1235.828");
483        }
484    }
485
486    #[unsafe(no_mangle)]
487    pub extern "C" fn slint_shared_string_from_number_fixed(
488        out: &mut SharedString,
489        n: f64,
490        digits: usize,
491    ) {
492        *out = shared_string_from_number_fixed(n, digits);
493    }
494
495    #[test]
496    fn test_slint_shared_string_from_number_fixed() {
497        let mut s = SharedString::default();
498
499        let num = 12345.6789;
500
501        slint_shared_string_from_number_fixed(&mut s, num, 0);
502        assert_eq!(s.as_str(), "12346");
503
504        slint_shared_string_from_number_fixed(&mut s, num, 1);
505        assert_eq!(s.as_str(), "12345.7");
506
507        slint_shared_string_from_number_fixed(&mut s, num, 6);
508        assert_eq!(s.as_str(), "12345.678900");
509
510        let num = -12345.6789;
511
512        slint_shared_string_from_number_fixed(&mut s, num, 0);
513        assert_eq!(s.as_str(), "-12346");
514
515        slint_shared_string_from_number_fixed(&mut s, num, 1);
516        assert_eq!(s.as_str(), "-12345.7");
517
518        slint_shared_string_from_number_fixed(&mut s, num, 6);
519        assert_eq!(s.as_str(), "-12345.678900");
520
521        slint_shared_string_from_number_fixed(&mut s, 1.23E+20_f64, 2);
522        assert_eq!(s.as_str(), "123000000000000000000.00");
523
524        slint_shared_string_from_number_fixed(&mut s, 1.23E-10_f64, 2);
525        assert_eq!(s.as_str(), "0.00");
526
527        slint_shared_string_from_number_fixed(&mut s, 2.34, 1);
528        assert_eq!(s.as_str(), "2.3");
529
530        slint_shared_string_from_number_fixed(&mut s, 2.35, 1);
531        assert_eq!(s.as_str(), "2.4");
532
533        slint_shared_string_from_number_fixed(&mut s, 2.55, 1);
534        assert_eq!(s.as_str(), "2.5");
535    }
536
537    #[unsafe(no_mangle)]
538    pub extern "C" fn slint_shared_string_from_number_precision(
539        out: &mut SharedString,
540        n: f64,
541        precision: usize,
542    ) {
543        *out = shared_string_from_number_precision(n, precision);
544    }
545
546    #[test]
547    fn test_slint_shared_string_from_number_precision() {
548        let mut s = SharedString::default();
549
550        let num = 5.123456;
551
552        slint_shared_string_from_number_precision(&mut s, num, 0);
553        assert_eq!(s.as_str(), "5.123456");
554
555        slint_shared_string_from_number_precision(&mut s, num, 5);
556        assert_eq!(s.as_str(), "5.1235");
557
558        slint_shared_string_from_number_precision(&mut s, num, 2);
559        assert_eq!(s.as_str(), "5.1");
560
561        slint_shared_string_from_number_precision(&mut s, num, 1);
562        assert_eq!(s.as_str(), "5");
563
564        let num = 0.000123;
565
566        slint_shared_string_from_number_precision(&mut s, num, 0);
567        assert_eq!(s.as_str(), "0.000123");
568
569        slint_shared_string_from_number_precision(&mut s, num, 5);
570        assert_eq!(s.as_str(), "0.00012300");
571
572        slint_shared_string_from_number_precision(&mut s, num, 2);
573        assert_eq!(s.as_str(), "0.00012");
574
575        slint_shared_string_from_number_precision(&mut s, num, 1);
576        assert_eq!(s.as_str(), "0.0001");
577
578        let num = 1234.5;
579
580        slint_shared_string_from_number_precision(&mut s, num, 1);
581        assert_eq!(s.as_str(), "1e3");
582
583        slint_shared_string_from_number_precision(&mut s, num, 2);
584        assert_eq!(s.as_str(), "1.2e3");
585
586        slint_shared_string_from_number_precision(&mut s, num, 6);
587        assert_eq!(s.as_str(), "1234.50");
588
589        let num = -1234.5;
590
591        slint_shared_string_from_number_precision(&mut s, num, 1);
592        assert_eq!(s.as_str(), "-1e3");
593
594        slint_shared_string_from_number_precision(&mut s, num, 2);
595        assert_eq!(s.as_str(), "-1.2e3");
596
597        slint_shared_string_from_number_precision(&mut s, num, 6);
598        assert_eq!(s.as_str(), "-1234.50");
599
600        let num = 0.00000012345;
601
602        slint_shared_string_from_number_precision(&mut s, num, 1);
603        assert_eq!(s.as_str(), "1e-7");
604
605        slint_shared_string_from_number_precision(&mut s, num, 10);
606        assert_eq!(s.as_str(), "1.234500000e-7");
607    }
608
609    /// Append some bytes to an existing shared string
610    ///
611    /// bytes must be a valid utf8 array of size `len`, without null bytes inside
612    #[unsafe(no_mangle)]
613    pub unsafe extern "C" fn slint_shared_string_append(
614        self_: &mut SharedString,
615        bytes: *const c_char,
616        len: usize,
617    ) {
618        let str = core::str::from_utf8(core::slice::from_raw_parts(bytes, len)).unwrap();
619        self_.push_str(str);
620    }
621    #[test]
622    fn test_slint_shared_string_append() {
623        let mut s = SharedString::default();
624        let mut append = |x: &str| unsafe {
625            slint_shared_string_append(&mut s, x.as_bytes().as_ptr(), x.len());
626        };
627        append("Hello");
628        append(", ");
629        append("world");
630        append("");
631        append("!");
632        assert_eq!(s.as_str(), "Hello, world!");
633    }
634
635    #[unsafe(no_mangle)]
636    pub unsafe extern "C" fn slint_shared_string_to_lowercase(
637        out: &mut SharedString,
638        ss: &SharedString,
639    ) {
640        *out = SharedString::from(ss.to_lowercase());
641    }
642    #[test]
643    fn test_slint_shared_string_to_lowercase() {
644        let s = SharedString::from("Hello");
645        let mut out = SharedString::default();
646
647        unsafe {
648            slint_shared_string_to_lowercase(&mut out, &s);
649        }
650        assert_eq!(out.as_str(), "hello");
651    }
652
653    #[unsafe(no_mangle)]
654    pub unsafe extern "C" fn slint_shared_string_to_uppercase(
655        out: &mut SharedString,
656        ss: &SharedString,
657    ) {
658        *out = SharedString::from(ss.to_uppercase());
659    }
660    #[test]
661    fn test_slint_shared_string_to_uppercase() {
662        let s = SharedString::from("Hello");
663        let mut out = SharedString::default();
664
665        unsafe {
666            slint_shared_string_to_uppercase(&mut out, &s);
667        }
668        assert_eq!(out.as_str(), "HELLO");
669    }
670}
671
672#[cfg(feature = "serde")]
673#[test]
674fn test_serialize_deserialize_sharedstring() {
675    let v = SharedString::from("data");
676    let serialized = serde_json::to_string(&v).unwrap();
677    let deserialized: SharedString = serde_json::from_str(&serialized).unwrap();
678    assert_eq!(v, deserialized);
679}