From 247ab148248bff63bd24c352a34f63d73da1b2f3 Mon Sep 17 00:00:00 2001 From: Tobias Schmitz Date: Thu, 26 Mar 2026 10:37:23 +0100 Subject: [PATCH] Add `ToEcoString` trait --- src/string.rs | 15 +++++++++++++++ tests/tests.rs | 7 +++++++ 2 files changed, 22 insertions(+) diff --git a/src/string.rs b/src/string.rs index c393385..8c62579 100644 --- a/src/string.rs +++ b/src/string.rs @@ -594,6 +594,21 @@ impl FromStr for EcoString { } } +/// A trait for converting a value to an [`EcoString`]. +/// +/// This trait is automatically implemented for any type which implements the +/// [`Display`] trait. +pub trait ToEcoString { + /// Converts the given value to an [`EcoString`]. + fn to_eco_string(&self) -> EcoString; +} + +impl ToEcoString for T { + fn to_eco_string(&self) -> EcoString { + eco_format!("{self}") + } +} + #[cold] const fn exceeded_inline_capacity() -> ! { panic!("exceeded inline capacity"); diff --git a/tests/tests.rs b/tests/tests.rs index fdbd958..79aa890 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -9,6 +9,7 @@ use std::fmt::Write; use std::mem; use std::sync::atomic::{AtomicUsize, Ordering::*}; +use ecow::string::ToEcoString; use ecow::{eco_vec, EcoString, EcoVec}; const ALPH: &str = "abcdefghijklmnopqrstuvwxyz"; @@ -625,3 +626,9 @@ fn test_str_complex() { assert_eq!(hash_map.get("foo").unwrap(), &["bar".into(), "foo".into(), "foo".into()]); assert_eq!(hash_map.get("bar").unwrap(), &["bar".into()]); } + +#[test] +fn test_str_to_eco_string() { + let num = 123456789; + assert_eq!(num.to_eco_string(), "123456789"); +}