Skip to content

Commit ef3a6a8

Browse files
committed
Add an unstable constructor for creating Rc<str> from str
1 parent a29c49f commit ef3a6a8

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

src/liballoc/rc.rs

+26-1
Original file line numberDiff line numberDiff line change
@@ -230,13 +230,14 @@ use core::hash::{Hash, Hasher};
230230
use core::intrinsics::{abort, assume};
231231
use core::marker;
232232
use core::marker::Unsize;
233-
use core::mem::{self, align_of_val, forget, size_of_val, uninitialized};
233+
use core::mem::{self, align_of_val, forget, size_of, size_of_val, uninitialized};
234234
use core::ops::Deref;
235235
use core::ops::CoerceUnsized;
236236
use core::ptr::{self, Shared};
237237
use core::convert::From;
238238

239239
use heap::deallocate;
240+
use raw_vec::RawVec;
240241

241242
struct RcBox<T: ?Sized> {
242243
strong: Cell<usize>,
@@ -365,6 +366,30 @@ impl<T> Rc<T> {
365366
}
366367
}
367368

369+
impl Rc<str> {
370+
/// Constructs a new `Rc<str>` from a string slice.
371+
#[doc(hidden)]
372+
#[unstable(feature = "rustc_private",
373+
reason = "for internal use in rustc",
374+
issue = "0")]
375+
pub fn __from_str(value: &str) -> Rc<str> {
376+
unsafe {
377+
// Allocate enough space for `RcBox<str>`.
378+
let aligned_len = (value.len() + size_of::<usize>() - 1) / size_of::<usize>();
379+
let vec = RawVec::<usize>::with_capacity(2 + aligned_len);
380+
let ptr = vec.ptr();
381+
forget(vec);
382+
// Initialize fields of `RcBox<str>`.
383+
*ptr.offset(0) = 1; // strong: Cell::new(1)
384+
*ptr.offset(1) = 1; // weak: Cell::new(1)
385+
ptr::copy_nonoverlapping(value.as_ptr(), ptr.offset(2) as *mut u8, value.len());
386+
// Combine the allocation address and the string length into a fat pointer to `RcBox`.
387+
let rcbox_ptr = mem::transmute([ptr as usize, value.len()]);
388+
Rc { ptr: Shared::new(rcbox_ptr) }
389+
}
390+
}
391+
}
392+
368393
impl<T: ?Sized> Rc<T> {
369394
/// Creates a new [`Weak`][weak] pointer to this value.
370395
///

0 commit comments

Comments
 (0)