Skip to content

Add more Box conversions #96

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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 @@
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 @@ -145,7 +159,7 @@
loop {
if valid == b.len() {
// SAFETY: `is_ascii` having returned true for all bytes guarantees all bytes are within ascii range.
return unsafe { Ok(mem::transmute(b)) };

Check failure on line 162 in src/ascii_str.rs

View workflow job for this annotation

GitHub Actions / Lint with Clippy

transmute used without annotations
} else if b[valid].is_ascii() {
valid += 1;
} else {
Expand Down Expand Up @@ -455,7 +469,7 @@
impl<'a> From<&'a [AsciiChar]> for &'a AsciiStr {
#[inline]
fn from(slice: &[AsciiChar]) -> &AsciiStr {
let ptr = slice as *const [AsciiChar] as *const AsciiStr;

Check failure on line 472 in src/ascii_str.rs

View workflow job for this annotation

GitHub Actions / Lint with Clippy

reference as raw pointer
unsafe { &*ptr }
}
}
Expand Down Expand Up @@ -500,6 +514,13 @@
}
}

#[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 @@
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
Loading