From 0a8f9ac5c00d50f9075e95d935d2b70be3a64d33 Mon Sep 17 00:00:00 2001 From: Ben Pfaff Date: Mon, 6 Oct 2025 08:30:34 -0700 Subject: [PATCH] Add `ToSmallString`, analogous to standard `ToString`. --- src/string.rs | 50 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/src/string.rs b/src/string.rs index 5b22c92..78a8bdf 100644 --- a/src/string.rs +++ b/src/string.rs @@ -2,7 +2,7 @@ use core::{ borrow::{Borrow, BorrowMut}, cmp::Ordering, convert::Infallible, - fmt, + fmt::{self, Display, Write}, hash::{Hash, Hasher}, iter::{FromIterator, FusedIterator}, ops, ptr, slice, @@ -961,6 +961,43 @@ impl> fmt::Display for FromUtf8Error { } } +/// A trait for converting a value to a [`SmallString`]. +/// +/// This trait is automatically implemented for any type which implements the +/// [`Display`] trait. +pub trait ToSmallString { + /// Converts this type to a [`SmallString`], analogous to `.to_string()` for + /// converting to a [`String`]. + /// + /// # Examples + /// + /// ``` + /// # use smallstr::{SmallString, ToSmallString}; + /// // Works with any type that implements `Display`. + /// let s = 123.to_small_string::<8>(); + /// + /// // Works for arbitrary formatting with `format_args!`. + /// let s: SmallString<[u8; 32]> = format_args!("Hello, {}!", "world").to_small_string(); + /// ``` + fn to_small_string(&self) -> SmallString<[u8; N]> + where + [u8; N]: Array; +} + +impl ToSmallString for T +where + T: Display, +{ + fn to_small_string(&self) -> SmallString<[u8; N]> + where + [u8; N]: Array, + { + let mut s = SmallString::new(); + write!(&mut s, "{self}").unwrap(); + s + } +} + #[cfg(test)] mod test { use alloc::{ @@ -969,6 +1006,8 @@ mod test { string::{String, ToString}, }; + use crate::ToSmallString; + use super::SmallString; #[test] @@ -1232,6 +1271,15 @@ mod test { assert_eq!(s, "foo"); } + #[test] + fn test_to_small_string() { + assert_eq!(123.to_small_string::<8>(), "123"); + assert_eq!( + format_args!("Hello, {}!", "world").to_small_string::<16>(), + "Hello, world!" + ); + } + #[cfg(feature = "serde")] #[test] fn test_serde() {