diff --git a/src/ascii_str.rs b/src/ascii_str.rs index bfdf54e..3281a0a 100644 --- a/src/ascii_str.rs +++ b/src/ascii_str.rs @@ -104,6 +104,20 @@ impl AsciiStr { AsciiString::from(self.slice.to_vec()) } + /// for compatibility with `str` + #[cfg(feature = "alloc")] + #[must_use] + pub fn into_boxed_bytes(self: Box) -> Box<[u8]> { + self.into() + } + + /// Convert a `Box<[u8]>` to `Box` without allocating. + #[cfg(feature = "alloc")] + #[must_use] + pub unsafe fn from_boxed_ascii_bytes_unchecked(box_not_checked: Box<[u8]>) -> Box { + Box::from_raw(Box::into_raw(box_not_checked) as *mut AsciiStr) + } + /// Converts anything that can represent a byte slice into an `AsciiStr`. /// /// # Errors @@ -500,6 +514,13 @@ impl AsMut for [AsciiChar] { } } +#[cfg(feature = "alloc")] +impl Clone for Box { + fn clone(&self) -> Box { + self.to_ascii_string().into() + } +} + impl<'a> From<&'a AsciiStr> for &'a [AsciiChar] { #[inline] fn from(astr: &AsciiStr) -> &[AsciiChar] { @@ -1476,6 +1497,18 @@ mod tests { assert_eq!(AsRef::<[u8]>::as_ref(v), b"( ;"); } + #[test] + #[cfg(feature = "alloc")] + fn to_and_from_byte_box() { + let s = "abc".as_ascii_str().unwrap().to_ascii_string().into_boxed_ascii_str(); + unsafe { + let converted = s.clone().into_boxed_bytes(); + assert_eq!(&converted[..], &b"abc"[..]); + let converted_back = AsciiStr::from_boxed_ascii_bytes_unchecked(converted); + assert_eq!(&converted_back[..], &s[..]); + } + } + #[test] fn make_ascii_case() { let mut bytes = ([b'a', b'@', b'A'], [b'A', b'@', b'a']);