rust: added ToSharedString trait (#6845)

This commit is contained in:
FloVanGH 2024-11-20 13:17:26 +00:00 committed by GitHub
parent 2200a64471
commit bad71b7a13
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 30 additions and 1 deletions

View file

@ -226,7 +226,10 @@ pub use i_slint_core::model::{
pub use i_slint_core::sharedvector::SharedVector;
pub use i_slint_core::timers::{Timer, TimerMode};
pub use i_slint_core::translations::{select_bundled_translation, SelectBundledTranslationError};
pub use i_slint_core::{format, string::SharedString};
pub use i_slint_core::{
format,
string::{SharedString, ToSharedString},
};
pub mod private_unstable_api;

View file

@ -288,6 +288,24 @@ pub fn format(args: core::fmt::Arguments<'_>) -> SharedString {
output
}
/// A trait for converting a value to a [`SharedString`].
///
/// This trait is automatically implemented for any type which implements the [`Display`] trait as long as the trait is in scope.
/// As such, `ToSharedString` shouldnt be implemented directly: [`Display`] should be implemented instead, and you get the `ToSharedString` implementation for free.
pub trait ToSharedString {
/// Converts the given value to a [`SharedString`].
fn to_shared_string(&self) -> SharedString;
}
impl<T> ToSharedString for T
where
T: Display + ?Sized,
{
fn to_shared_string(&self) -> SharedString {
format!("{}", self)
}
}
#[test]
fn simple_test() {
let x = SharedString::from("hello world!");
@ -342,6 +360,14 @@ fn threading() {
// 20x"!"
}
#[test]
fn to_shared_string() {
let i = 5.1;
let five = SharedString::from("5.1");
assert_eq!(five, i.to_shared_string());
}
#[cfg(feature = "ffi")]
pub(crate) mod ffi {
use super::*;