From c9c55dc53a7836939cb453fc21bab35495899e73 Mon Sep 17 00:00:00 2001 From: tormol Date: Thu, 22 Aug 2019 07:04:32 +0200 Subject: [PATCH 1/2] Add more Box conversions --- src/ascii_str.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/ascii_str.rs b/src/ascii_str.rs index bfdf54e..f586b8f 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 @@ -1476,6 +1490,19 @@ 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(); + let boxed = s.clone().into_boxed_ascii_str(); + unsafe { + let converted = boxed.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']); From 9dca9340e490d6692ddc461e94afb8a96d6d4f64 Mon Sep 17 00:00:00 2001 From: tormol Date: Tue, 13 Sep 2022 00:45:57 +0200 Subject: [PATCH 2/2] Implement Clone for BoxAsciiStr> --- src/ascii_str.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/ascii_str.rs b/src/ascii_str.rs index f586b8f..3281a0a 100644 --- a/src/ascii_str.rs +++ b/src/ascii_str.rs @@ -514,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] { @@ -1493,10 +1500,9 @@ mod tests { #[test] #[cfg(feature = "alloc")] fn to_and_from_byte_box() { - let s = "abc".as_ascii_str().unwrap().to_ascii_string(); - let boxed = s.clone().into_boxed_ascii_str(); + let s = "abc".as_ascii_str().unwrap().to_ascii_string().into_boxed_ascii_str(); unsafe { - let converted = boxed.into_boxed_bytes(); + 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[..]);