- /// Create an `Arc<[T]>` by reusing the underlying memory
- /// of a `Vec<T>`. This will return the vector if the existing allocation
- /// is not large enough.
- #[cfg(not(no_global_oom_handling))]
- fn try_from_vec_in_place(mut v: Vec<T>) -> Result<Arc<[T]>, Vec<T>> {
- let layout_elements = Layout::array::<T>(v.len()).unwrap();
- let layout_allocation = Layout::array::<T>(v.capacity()).unwrap();
- let layout_arcinner = arcinner_layout_for_value_layout(layout_elements);
- let mut ptr = NonNull::new(v.as_mut_ptr()).expect("`Vec<T>` stores `NonNull<T>`");
- if layout_arcinner.size() > layout_allocation.size()
- || layout_arcinner.align() > layout_allocation.align()
- {
- // Can't fit - calling `grow` would involve `realloc`
- // (which copies the elements), followed by copying again.
- return Err(v);
- }
- if layout_arcinner.size() < layout_allocation.size()
- || layout_arcinner.align() < layout_allocation.align()
- {
- // We need to shrink the allocation so that it fits
- // https://doc.rust-lang.org/nightly/std/alloc/trait.Allocator.html#memory-fitting
- // SAFETY:
- // - Vec allocates by requesting `Layout::array::<T>(capacity)`, so this capacity matches
- // - `layout_arcinner` is smaller
- // If this fails, the ownership has not been transferred
- if let Ok(p) = unsafe { Global.shrink(ptr.cast(), layout_allocation, layout_arcinner) }
- {
- ptr = p.cast();
- } else {
- return Err(v);
- }
- }
- // Make sure the vec's memory isn't deallocated now
- let v = mem::ManuallyDrop::new(v);
- let ptr: *mut ArcInner<[T]> = ptr::slice_from_raw_parts_mut(ptr.as_ptr(), v.len()) as _;
- unsafe {
- ptr::copy(ptr.cast::<T>(), &mut (*ptr).data as *mut [T] as *mut T, v.len());
- ptr::write(&mut (*ptr).strong, atomic::AtomicUsize::new(1));
- ptr::write(&mut (*ptr).weak, atomic::AtomicUsize::new(1));
- Ok(Self::from_ptr(ptr))
- }
- }
-