Skip to content

Commit a238a72

Browse files
authored
Improve From<FixedString> for Cow (#11)
A statically created FixedString will now always convert to a borrowed Cow.
1 parent 4c7fecf commit a238a72

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

src/string.rs

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,10 @@ impl<'a, LenT: ValidLength> From<&'a FixedString<LenT>> for Cow<'a, str> {
333333

334334
impl<LenT: ValidLength> From<FixedString<LenT>> for Cow<'_, str> {
335335
fn from(value: FixedString<LenT>) -> Self {
336-
Cow::Owned(value.into_string())
336+
match value.0 {
337+
FixedStringRepr::Static(static_str) => Cow::Borrowed(static_str.as_str()),
338+
_ => Cow::Owned(value.into()),
339+
}
337340
}
338341
}
339342

@@ -443,6 +446,23 @@ mod test {
443446
assert_ne!(STR, str);
444447
}
445448

449+
#[test]
450+
fn test_from_static_to_cow() {
451+
const STR: &str = "static string";
452+
453+
let string = FixedString::<u8>::from_static_trunc(STR);
454+
455+
let cow: std::borrow::Cow<'static, _> = string.into();
456+
457+
assert_eq!(cow, STR);
458+
459+
let std::borrow::Cow::Borrowed(string) = cow else {
460+
panic!("Expected borrowed string");
461+
};
462+
463+
assert_eq!(string, STR);
464+
}
465+
446466
#[test]
447467
fn check_u8_roundtrip() {
448468
check_u8_roundtrip_generic(|original| {

0 commit comments

Comments
 (0)