Skip to content

Commit 84b6443

Browse files
committed
Add more Box conversions
1 parent eb0ea87 commit 84b6443

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/ascii_str.rs

+27
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,20 @@ impl AsciiStr {
8787
AsciiString::from(self.slice.to_vec())
8888
}
8989

90+
/// for compatibility with `str`
91+
#[cfg(feature = "alloc")]
92+
#[must_use]
93+
pub fn into_boxed_bytes(self: Box<Self>) -> Box<[u8]> {
94+
self.into()
95+
}
96+
97+
/// Convert a `Box<[u8]>` to `Box<AsciiStr>` without allocating.
98+
#[cfg(feature = "alloc")]
99+
#[must_use]
100+
pub unsafe fn from_boxed_ascii_bytes_unchecked(box_not_checked: Box<[u8]>) -> Box<Self> {
101+
Box::from_raw(Box::into_raw(box_not_checked) as *mut AsciiStr)
102+
}
103+
90104
/// Converts anything that can represent a byte slice into an `AsciiStr`.
91105
///
92106
/// # Errors
@@ -1414,6 +1428,19 @@ mod tests {
14141428
assert_eq!(AsRef::<[u8]>::as_ref(v), b"( ;");
14151429
}
14161430

1431+
#[test]
1432+
#[cfg(feature = "alloc")]
1433+
fn to_and_from_byte_box() {
1434+
let s = "abc".as_ascii_str().unwrap().to_ascii_string();
1435+
let boxed = s.clone().into_boxed_ascii_str();
1436+
unsafe {
1437+
let converted = boxed.into_boxed_bytes();
1438+
assert_eq!(&converted[..], &b"abc"[..]);
1439+
let converted_back = AsciiStr::from_boxed_ascii_bytes_unchecked(converted);
1440+
assert_eq!(&converted_back[..], &s[..]);
1441+
}
1442+
}
1443+
14171444
#[test]
14181445
fn make_ascii_case() {
14191446
let mut bytes = ([b'a', b'@', b'A'], [b'A', b'@', b'a']);

0 commit comments

Comments
 (0)