Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/ascii_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Self>) -> Box<[u8]> {
self.into()
}

/// Convert a `Box<[u8]>` to `Box<AsciiStr>` without allocating.
#[cfg(feature = "alloc")]
#[must_use]
pub unsafe fn from_boxed_ascii_bytes_unchecked(box_not_checked: Box<[u8]>) -> Box<Self> {
Box::from_raw(Box::into_raw(box_not_checked) as *mut AsciiStr)
}

/// Converts anything that can represent a byte slice into an `AsciiStr`.
///
/// # Errors
Expand Down Expand Up @@ -500,6 +514,13 @@ impl AsMut<AsciiStr> for [AsciiChar] {
}
}

#[cfg(feature = "alloc")]
impl Clone for Box<AsciiStr> {
fn clone(&self) -> Box<AsciiStr> {
self.to_ascii_string().into()
}
}

impl<'a> From<&'a AsciiStr> for &'a [AsciiChar] {
#[inline]
fn from(astr: &AsciiStr) -> &[AsciiChar] {
Expand Down Expand Up @@ -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']);
Expand Down