Skip to content

Commit f75d884

Browse files
committed
Auto merge of #96078 - udoprog:refcounted-str-to-u8, r=dtolnay
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?
2 parents 61469b6 + 100006b commit f75d884

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

library/alloc/src/rc.rs

+19
Original file line numberDiff line numberDiff line change
@@ -1956,6 +1956,25 @@ where
19561956
}
19571957
}
19581958

1959+
#[stable(feature = "shared_from_str", since = "1.62.0")]
1960+
impl From<Rc<str>> for Rc<[u8]> {
1961+
/// Converts a reference-counted string slice into a byte slice.
1962+
///
1963+
/// # Example
1964+
///
1965+
/// ```
1966+
/// # use std::rc::Rc;
1967+
/// let string: Rc<str> = Rc::from("eggplant");
1968+
/// let bytes: Rc<[u8]> = Rc::from(string);
1969+
/// assert_eq!("eggplant".as_bytes(), bytes.as_ref());
1970+
/// ```
1971+
#[inline]
1972+
fn from(rc: Rc<str>) -> Self {
1973+
// SAFETY: `str` has the same layout as `[u8]`.
1974+
unsafe { Rc::from_raw(Rc::into_raw(rc) as *const [u8]) }
1975+
}
1976+
}
1977+
19591978
#[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
19601979
impl<T, const N: usize> TryFrom<Rc<[T]>> for Rc<[T; N]> {
19611980
type Error = Rc<[T]>;

library/alloc/src/sync.rs

+19
Original file line numberDiff line numberDiff line change
@@ -2556,6 +2556,25 @@ where
25562556
}
25572557
}
25582558

2559+
#[stable(feature = "shared_from_str", since = "1.62.0")]
2560+
impl From<Arc<str>> for Arc<[u8]> {
2561+
/// Converts an atomically reference-counted string slice into a byte slice.
2562+
///
2563+
/// # Example
2564+
///
2565+
/// ```
2566+
/// # use std::sync::Arc;
2567+
/// let string: Arc<str> = Arc::from("eggplant");
2568+
/// let bytes: Arc<[u8]> = Arc::from(string);
2569+
/// assert_eq!("eggplant".as_bytes(), bytes.as_ref());
2570+
/// ```
2571+
#[inline]
2572+
fn from(rc: Arc<str>) -> Self {
2573+
// SAFETY: `str` has the same layout as `[u8]`.
2574+
unsafe { Arc::from_raw(Arc::into_raw(rc) as *const [u8]) }
2575+
}
2576+
}
2577+
25592578
#[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
25602579
impl<T, const N: usize> TryFrom<Arc<[T]>> for Arc<[T; N]> {
25612580
type Error = Arc<[T]>;

0 commit comments

Comments
 (0)