From 66cfd331924ef201e6ca35fe33e6c8e0b5a502d7 Mon Sep 17 00:00:00 2001 From: Oxey Date: Sat, 15 Oct 2022 16:53:20 +0200 Subject: [PATCH 1/2] add `From` impl for SmallString --- src/inline.rs | 11 +++++++++++ src/lib.rs | 6 ++++++ 2 files changed, 17 insertions(+) diff --git a/src/inline.rs b/src/inline.rs index 2815137..ba6c444 100644 --- a/src/inline.rs +++ b/src/inline.rs @@ -80,6 +80,17 @@ impl InlineString { } } +impl From for InlineString { + fn from(c: char) -> Self { + let len = c.len_utf8(); + let mut out = Self::new(); + + out.marker = Marker::new_inline(len as u8); + c.encode_utf8(&mut out.data); + out + } +} + impl From<&str> for InlineString { fn from(string: &str) -> Self { let len = string.len(); diff --git a/src/lib.rs b/src/lib.rs index 33e0023..73d0f4a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -643,6 +643,12 @@ impl IndexMut> for SmartString From for SmartString { + fn from(c: char) -> Self { + Self::from_inline(c.into()) + } +} + impl From<&'_ str> for SmartString { fn from(string: &'_ str) -> Self { if string.len() > MAX_INLINE { From bb0c2fa6f6ba34d33672bf18f3098fa006e20df1 Mon Sep 17 00:00:00 2001 From: Oxey Date: Sat, 15 Oct 2022 17:03:39 +0200 Subject: [PATCH 2/2] add test for `From` --- src/test.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/test.rs b/src/test.rs index 8abba06..2311a98 100644 --- a/src/test.rs +++ b/src/test.rs @@ -563,4 +563,15 @@ mod tests { assert_eq!(std_s, unsmart_s); // This test exists just to provoke a Miri problem when dropping a string created by SmartString::into::() (#28) } + + #[test] + fn from_char() { + let c = 'a'; + let std_s = String::from(c); + let smart_s = SmartString::::from(c); + let unsmart_s = smart_s.clone().to_string(); + assert_eq!(smart_s, std_s); + assert_eq!(smart_s, unsmart_s); + assert_eq!(std_s, unsmart_s); + } }