Skip to content

Commit

Permalink
Fix FixedString::from_static_trunc panic
Browse files Browse the repository at this point in the history
  • Loading branch information
GnomedDev committed Feb 9, 2024
1 parent fae92d2 commit 358088f
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ impl<LenT: ValidLength> FixedString<LenT> {
/// See [`Self::from_string_trunc`] for truncation behaviour.
pub fn from_static_trunc(val: &'static str) -> Self {
Self(FixedStringRepr::Static(StaticStr::from_static_str(
&val[..LenT::MAX.to_usize()],
&val[..val.len().min(LenT::MAX.to_usize())],
)))
}

Expand Down Expand Up @@ -127,6 +127,12 @@ impl<LenT: ValidLength> FixedString<LenT> {
pub(crate) fn is_inline(&self) -> bool {
matches!(self, Self(FixedStringRepr::Inline(_)))
}

#[cfg(test)]
#[must_use]
pub(crate) fn is_static(&self) -> bool {
matches!(self, Self(FixedStringRepr::Static(_)))
}
}

impl<LenT: ValidLength> core::ops::Deref for FixedString<LenT> {
Expand Down Expand Up @@ -350,14 +356,25 @@ mod test {

assert!(fixed.bytes().all(|c| c == b'a'));
assert_eq!(fixed.len(), i);
assert_eq!(fixed.is_inline(), fixed.len() <= 9);

if !fixed.is_static() {
assert_eq!(fixed.is_inline(), fixed.len() <= 9);
}
}
}
#[test]
fn check_u8_roundtrip() {
check_u8_roundtrip_generic(|original| FixedString::<u8>::try_from(original).unwrap());
}

#[test]
fn check_u8_roundtrip_static() {
check_u8_roundtrip_generic(|original| {
let static_str = Box::leak(original);
FixedString::from_static_trunc(static_str)
});
}

#[test]
#[cfg(feature = "serde")]
fn check_u8_roundtrip_serde() {
Expand Down

0 comments on commit 358088f

Please sign in to comment.