Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 49 additions & 1 deletion src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -961,6 +961,43 @@ impl<A: Array<Item = u8>> fmt::Display for FromUtf8Error<A> {
}
}

/// 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<const N: usize>(&self) -> SmallString<[u8; N]>
where
[u8; N]: Array<Item = u8>;
}

impl<T> ToSmallString for T
where
T: Display,
{
fn to_small_string<const N: usize>(&self) -> SmallString<[u8; N]>
where
[u8; N]: Array<Item = u8>,
{
let mut s = SmallString::new();
write!(&mut s, "{self}").unwrap();
s
}
}

#[cfg(test)]
mod test {
use alloc::{
Expand All @@ -969,6 +1006,8 @@ mod test {
string::{String, ToString},
};

use crate::ToSmallString;

use super::SmallString;

#[test]
Expand Down Expand Up @@ -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() {
Expand Down