Skip to content

Commit

Permalink
Auto merge of #96078 - udoprog:refcounted-str-to-u8, r=dtolnay
Browse files Browse the repository at this point in the history
Implement str to [u8] conversion for refcounted containers

This seems motivated to complete the APIs for shared containers since we already have similar allocation-free conversions for strings like `From<Box<[u8]>> for Box<str>`.

Insta-stable since it's a new trait impl?
  • Loading branch information
bors committed May 1, 2022
2 parents 61469b6 + 100006b commit f75d884
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
19 changes: 19 additions & 0 deletions library/alloc/src/rc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1956,6 +1956,25 @@ where
}
}

#[stable(feature = "shared_from_str", since = "1.62.0")]
impl From<Rc<str>> for Rc<[u8]> {
/// Converts a reference-counted string slice into a byte slice.
///
/// # Example
///
/// ```
/// # use std::rc::Rc;
/// let string: Rc<str> = Rc::from("eggplant");
/// let bytes: Rc<[u8]> = Rc::from(string);
/// assert_eq!("eggplant".as_bytes(), bytes.as_ref());
/// ```
#[inline]
fn from(rc: Rc<str>) -> Self {
// SAFETY: `str` has the same layout as `[u8]`.
unsafe { Rc::from_raw(Rc::into_raw(rc) as *const [u8]) }
}
}

#[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
impl<T, const N: usize> TryFrom<Rc<[T]>> for Rc<[T; N]> {
type Error = Rc<[T]>;
Expand Down
19 changes: 19 additions & 0 deletions library/alloc/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2556,6 +2556,25 @@ where
}
}

#[stable(feature = "shared_from_str", since = "1.62.0")]
impl From<Arc<str>> for Arc<[u8]> {
/// Converts an atomically reference-counted string slice into a byte slice.
///
/// # Example
///
/// ```
/// # use std::sync::Arc;
/// let string: Arc<str> = Arc::from("eggplant");
/// let bytes: Arc<[u8]> = Arc::from(string);
/// assert_eq!("eggplant".as_bytes(), bytes.as_ref());
/// ```
#[inline]
fn from(rc: Arc<str>) -> Self {
// SAFETY: `str` has the same layout as `[u8]`.
unsafe { Arc::from_raw(Arc::into_raw(rc) as *const [u8]) }
}
}

#[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
impl<T, const N: usize> TryFrom<Arc<[T]>> for Arc<[T; N]> {
type Error = Arc<[T]>;
Expand Down

0 comments on commit f75d884

Please sign in to comment.