diff --git a/internal/core/string.rs b/internal/core/string.rs index de8e584b020..0b272a5fe13 100644 --- a/internal/core/string.rs +++ b/internal/core/string.rs @@ -9,6 +9,7 @@ use crate::SharedVector; #[cfg(not(feature = "std"))] use alloc::string::String; +use alloc::borrow::Cow; use core::fmt::{Debug, Display, Write}; use core::ops::Deref; @@ -212,6 +213,18 @@ impl From<&String> for SharedString { } } +impl From> for SharedString { + fn from(s: Cow<'_, str>) -> Self { + s.as_ref().into() + } +} + +impl From<&Cow<'_, str>> for SharedString { + fn from(s: &Cow<'_, str>) -> Self { + s.as_ref().into() + } +} + impl From for SharedString { fn from(c: char) -> Self { SharedString::from(c.encode_utf8(&mut [0; 6]) as &str) @@ -442,3 +455,13 @@ fn test_serialize_deserialize_sharedstring() { let deserialized: SharedString = serde_json::from_str(&serialized).unwrap(); assert_eq!(v, deserialized); } + +#[test] +fn test_from_cow() { + let borrowed = Cow::from("Foo"); + let owned = Cow::from("Bar".to_string()); + assert_eq!(SharedString::from("Foo"), SharedString::from(&borrowed)); + assert_eq!(SharedString::from("Foo"), SharedString::from(borrowed)); + assert_eq!(SharedString::from("Bar"), SharedString::from(&owned)); + assert_eq!(SharedString::from("Bar"), SharedString::from(owned)); +} \ No newline at end of file