Skip to content

Commit c9c55dc

Browse files
committed
Add more Box conversions
1 parent 7203d9a commit c9c55dc

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/ascii_str.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,20 @@ impl AsciiStr {
104104
AsciiString::from(self.slice.to_vec())
105105
}
106106

107+
/// for compatibility with `str`
108+
#[cfg(feature = "alloc")]
109+
#[must_use]
110+
pub fn into_boxed_bytes(self: Box<Self>) -> Box<[u8]> {
111+
self.into()
112+
}
113+
114+
/// Convert a `Box<[u8]>` to `Box<AsciiStr>` without allocating.
115+
#[cfg(feature = "alloc")]
116+
#[must_use]
117+
pub unsafe fn from_boxed_ascii_bytes_unchecked(box_not_checked: Box<[u8]>) -> Box<Self> {
118+
Box::from_raw(Box::into_raw(box_not_checked) as *mut AsciiStr)
119+
}
120+
107121
/// Converts anything that can represent a byte slice into an `AsciiStr`.
108122
///
109123
/// # Errors
@@ -1476,6 +1490,19 @@ mod tests {
14761490
assert_eq!(AsRef::<[u8]>::as_ref(v), b"( ;");
14771491
}
14781492

1493+
#[test]
1494+
#[cfg(feature = "alloc")]
1495+
fn to_and_from_byte_box() {
1496+
let s = "abc".as_ascii_str().unwrap().to_ascii_string();
1497+
let boxed = s.clone().into_boxed_ascii_str();
1498+
unsafe {
1499+
let converted = boxed.into_boxed_bytes();
1500+
assert_eq!(&converted[..], &b"abc"[..]);
1501+
let converted_back = AsciiStr::from_boxed_ascii_bytes_unchecked(converted);
1502+
assert_eq!(&converted_back[..], &s[..]);
1503+
}
1504+
}
1505+
14791506
#[test]
14801507
fn make_ascii_case() {
14811508
let mut bytes = ([b'a', b'@', b'A'], [b'A', b'@', b'a']);

0 commit comments

Comments
 (0)