diff --git a/src/liballoc/alloc.rs b/src/liballoc/alloc.rs index 755feb8496203..b12eb1415d086 100644 --- a/src/liballoc/alloc.rs +++ b/src/liballoc/alloc.rs @@ -40,10 +40,14 @@ extern "Rust" { /// accessed through the [free functions in `alloc`](index.html#functions). /// /// [`Alloc`]: trait.Alloc.html +#[cfg(not(test))] #[unstable(feature = "allocator_api", issue = "32838")] #[derive(Copy, Clone, Default, Debug)] pub struct Global; +#[cfg(test)] +pub use std::alloc::Global; + /// Allocate memory with the global allocator. /// /// This function forwards calls to the [`GlobalAlloc::alloc`] method @@ -163,6 +167,7 @@ pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 { __rust_alloc_zeroed(layout.size(), layout.align()) } +#[cfg(not(test))] #[unstable(feature = "allocator_api", issue = "32838")] unsafe impl Alloc for Global { #[inline] @@ -201,25 +206,22 @@ unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 { align as *mut u8 } else { let layout = Layout::from_size_align_unchecked(size, align); - let ptr = alloc(layout); - if !ptr.is_null() { - ptr - } else { - handle_alloc_error(layout) + match Global.alloc(layout) { + Ok(ptr) => ptr.as_ptr(), + Err(_) => handle_alloc_error(layout), } } } #[cfg_attr(not(test), lang = "box_free")] #[inline] -pub(crate) unsafe fn box_free(ptr: Unique) { - let ptr = ptr.as_ptr(); - let size = size_of_val(&*ptr); - let align = min_align_of_val(&*ptr); - // We do not allocate for Box when T is ZST, so deallocation is also not necessary. +pub(crate) unsafe fn box_free(ptr: Unique, mut a: A) { + let size = size_of_val(&*ptr.as_ptr()); + let align = min_align_of_val(&*ptr.as_ptr()); + // We do not allocate for Box when T is ZST, so deallocation is also not necessary. if size != 0 { let layout = Layout::from_size_align_unchecked(size, align); - dealloc(ptr as *mut u8, layout); + a.dealloc(NonNull::from(ptr).cast(), layout); } } diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index 76b660fba685c..6f6433bc5c936 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -88,6 +88,7 @@ use core::ops::{ use core::ptr::{self, NonNull, Unique}; use core::task::{Context, Poll}; +use crate::alloc::{Alloc, Global, Layout, handle_alloc_error}; use crate::vec::Vec; use crate::raw_vec::RawVec; use crate::str::from_boxed_utf8_unchecked; @@ -98,7 +99,7 @@ use crate::str::from_boxed_utf8_unchecked; #[lang = "owned_box"] #[fundamental] #[stable(feature = "rust1", since = "1.0.0")] -pub struct Box(Unique); +pub struct Box(Unique, pub(crate) A); impl Box { /// Allocates memory on the heap and then places `x` into it. @@ -125,6 +126,49 @@ impl Box { } } +impl Box { + /// Allocates memory in the given allocator and then places `x` into it. + /// + /// This doesn't actually allocate if `T` is zero-sized. + /// + /// # Examples + /// + /// ``` + /// # #![feature(allocator_api)] + /// use std::alloc::Global; + /// let five = Box::new_in(5, Global); + /// ``` + #[unstable(feature = "allocator_api", issue = "32838")] + #[inline(always)] + pub fn new_in(x: T, a: A) -> Box { + let mut a = a; + let layout = Layout::for_value(&x); + let size = layout.size(); + let ptr = if size == 0 { + Unique::empty() + } else { + unsafe { + let ptr = a.alloc(layout).unwrap_or_else(|_| handle_alloc_error(layout)); + ptr.cast().into() + } + }; + // Move x into the location allocated above. This needs to happen + // for any size so that x is not dropped in some cases. + unsafe { + ptr::write(ptr.as_ptr() as *mut T, x); + } + Box(ptr, a) + } + + /// Constructs a new `Pin>`. If `T` does not implement `Unpin`, then + /// `x` will be pinned in memory and unable to be moved. + #[unstable(feature = "allocator_api", issue = "32838")] + #[inline(always)] + pub fn pin_in(x: T, a: A) -> Pin> { + Box::new_in(x, a).into() + } +} + impl Box { /// Constructs a box from a raw pointer. /// @@ -165,9 +209,48 @@ impl Box { #[stable(feature = "box_raw", since = "1.4.0")] #[inline] pub unsafe fn from_raw(raw: *mut T) -> Self { - Box(Unique::new_unchecked(raw)) + Box(Unique::new_unchecked(raw), Global) + } +} + +impl Box { + /// Constructs a box from a raw pointer in the given allocator. + /// + /// This is similar to the [`Box::from_raw`] function, but assumes + /// the pointer was allocated with the given allocator. + /// + /// This function is unsafe because improper use may lead to + /// memory problems. For example, specifying the wrong allocator + /// may corrupt the allocator state. + /// + /// [`Box::from_raw`]: struct.Box.html#method.from_raw + /// + /// # Examples + /// + /// ``` + /// # #![feature(allocator_api)] + /// use std::alloc::Global; + /// let x = Box::new_in(5, Global); + /// let ptr = Box::into_raw(x); + /// let x = unsafe { Box::from_raw_in(ptr, Global) }; + /// ``` + #[unstable(feature = "allocator_api", issue = "32838")] + #[inline] + pub unsafe fn from_raw_in(raw: *mut T, a: A) -> Self { + Box(Unique::new_unchecked(raw), a) } + /// Maps a `Box` to `Box` by applying a function to the + /// raw pointer. + #[unstable(feature = "allocator_api", issue = "32838")] + #[inline] + pub unsafe fn map_raw *mut U>(b: Box, f: F) -> Box { + let a = ptr::read(&b.1); + Box::from_raw_in(f(Box::into_raw(b)), a) + } +} + +impl Box { /// Consumes the `Box`, returning a wrapped raw pointer. /// /// The pointer will be properly aligned and non-null. @@ -210,7 +293,7 @@ impl Box { /// [`Box::from_raw`]: struct.Box.html#method.from_raw #[stable(feature = "box_raw", since = "1.4.0")] #[inline] - pub fn into_raw(b: Box) -> *mut T { + pub fn into_raw(b: Box) -> *mut T { Box::into_raw_non_null(b).as_ptr() } @@ -246,14 +329,14 @@ impl Box { /// ``` #[unstable(feature = "box_into_raw_non_null", issue = "47336")] #[inline] - pub fn into_raw_non_null(b: Box) -> NonNull { + pub fn into_raw_non_null(b: Box) -> NonNull { Box::into_unique(b).into() } #[unstable(feature = "ptr_internals", issue = "0", reason = "use into_raw_non_null instead")] #[inline] #[doc(hidden)] - pub fn into_unique(b: Box) -> Unique { + pub fn into_unique(b: Box) -> Unique { let mut unique = b.0; mem::forget(b); // Box is kind-of a library type, but recognized as a "unique pointer" by @@ -308,7 +391,7 @@ impl Box { /// ``` #[stable(feature = "box_leak", since = "1.26.0")] #[inline] - pub fn leak<'a>(b: Box) -> &'a mut T + pub fn leak<'a>(b: Box) -> &'a mut T where T: 'a // Technically not needed, but kept to be explicit. { @@ -321,7 +404,7 @@ impl Box { /// /// This is also available via [`From`]. #[unstable(feature = "box_into_pin", issue = "0")] - pub fn into_pin(boxed: Box) -> Pin> { + pub fn into_pin(boxed: Box) -> Pin> { // It's not possible to move or replace the insides of a `Pin>` // when `T: !Unpin`, so it's safe to pin it directly without any // additional requirements. @@ -330,36 +413,36 @@ impl Box { } #[stable(feature = "rust1", since = "1.0.0")] -unsafe impl<#[may_dangle] T: ?Sized> Drop for Box { +unsafe impl<#[may_dangle] T: ?Sized, A> Drop for Box { fn drop(&mut self) { // FIXME: Do nothing, drop is currently performed by compiler. } } #[stable(feature = "rust1", since = "1.0.0")] -impl Default for Box { - /// Creates a `Box`, with the `Default` value for T. - fn default() -> Box { - box Default::default() +impl Default for Box { + /// Creates a `Box`, with the `Default` value for T. + fn default() -> Box { + Box::new_in(Default::default(), A::default()) } } #[stable(feature = "rust1", since = "1.0.0")] -impl Default for Box<[T]> { - fn default() -> Box<[T]> { - Box::<[T; 0]>::new([]) +impl Default for Box<[T], A> { + fn default() -> Box<[T], A> { + Box::<[T; 0], A>::new_in([], A::default()) } } #[stable(feature = "default_box_extra", since = "1.17.0")] -impl Default for Box { - fn default() -> Box { +impl Default for Box { + fn default() -> Box { unsafe { from_boxed_utf8_unchecked(Default::default()) } } } #[stable(feature = "rust1", since = "1.0.0")] -impl Clone for Box { +impl Clone for Box { /// Returns a new box with a `clone()` of this box's contents. /// /// # Examples @@ -370,8 +453,8 @@ impl Clone for Box { /// ``` #[rustfmt::skip] #[inline] - fn clone(&self) -> Box { - box { (**self).clone() } + fn clone(&self) -> Box { + Box::new_in((**self).clone(), self.1.clone()) } /// Copies `source`'s contents into `self` without creating a new allocation. /// @@ -386,17 +469,17 @@ impl Clone for Box { /// assert_eq!(*y, 5); /// ``` #[inline] - fn clone_from(&mut self, source: &Box) { + fn clone_from(&mut self, source: &Box) { (**self).clone_from(&(**source)); } } #[stable(feature = "box_slice_clone", since = "1.3.0")] -impl Clone for Box { +impl Clone for Box { fn clone(&self) -> Self { // this makes a copy of the data - let buf: Box<[u8]> = self.as_bytes().into(); + let buf = Box::<[u8], A>::from_slice_in(self.as_bytes(), self.1.clone()); unsafe { from_boxed_utf8_unchecked(buf) } @@ -404,58 +487,58 @@ impl Clone for Box { } #[stable(feature = "rust1", since = "1.0.0")] -impl PartialEq for Box { +impl PartialEq for Box { #[inline] - fn eq(&self, other: &Box) -> bool { + fn eq(&self, other: &Box) -> bool { PartialEq::eq(&**self, &**other) } #[inline] - fn ne(&self, other: &Box) -> bool { + fn ne(&self, other: &Box) -> bool { PartialEq::ne(&**self, &**other) } } #[stable(feature = "rust1", since = "1.0.0")] -impl PartialOrd for Box { +impl PartialOrd for Box { #[inline] - fn partial_cmp(&self, other: &Box) -> Option { + fn partial_cmp(&self, other: &Box) -> Option { PartialOrd::partial_cmp(&**self, &**other) } #[inline] - fn lt(&self, other: &Box) -> bool { + fn lt(&self, other: &Box) -> bool { PartialOrd::lt(&**self, &**other) } #[inline] - fn le(&self, other: &Box) -> bool { + fn le(&self, other: &Box) -> bool { PartialOrd::le(&**self, &**other) } #[inline] - fn ge(&self, other: &Box) -> bool { + fn ge(&self, other: &Box) -> bool { PartialOrd::ge(&**self, &**other) } #[inline] - fn gt(&self, other: &Box) -> bool { + fn gt(&self, other: &Box) -> bool { PartialOrd::gt(&**self, &**other) } } #[stable(feature = "rust1", since = "1.0.0")] -impl Ord for Box { +impl Ord for Box { #[inline] - fn cmp(&self, other: &Box) -> Ordering { + fn cmp(&self, other: &Box) -> Ordering { Ord::cmp(&**self, &**other) } } #[stable(feature = "rust1", since = "1.0.0")] -impl Eq for Box {} +impl Eq for Box {} #[stable(feature = "rust1", since = "1.0.0")] -impl Hash for Box { +impl Hash for Box { fn hash(&self, state: &mut H) { (**self).hash(state); } } #[stable(feature = "indirect_hasher_impl", since = "1.22.0")] -impl Hasher for Box { +impl Hasher for Box { fn finish(&self) -> u64 { (**self).finish() } @@ -501,7 +584,7 @@ impl Hasher for Box { } #[stable(feature = "from_for_ptrs", since = "1.6.0")] -impl From for Box { +impl From for Box { /// Converts a generic type `T` into a `Box` /// /// The conversion allocates on the heap and moves `t` @@ -515,22 +598,33 @@ impl From for Box { /// assert_eq!(Box::from(x), boxed); /// ``` fn from(t: T) -> Self { - Box::new(t) + Box::new_in(t, A::default()) } } #[stable(feature = "pin", since = "1.33.0")] -impl From> for Pin> { +impl From> for Pin> { /// Converts a `Box` into a `Pin>` /// /// This conversion does not allocate on the heap and happens in place. - fn from(boxed: Box) -> Self { + fn from(boxed: Box) -> Self { Box::into_pin(boxed) } } +impl Box<[T], A> { + fn from_slice_in(slice: &[T], a: A) -> Box<[T], A> { + let len = slice.len(); + let buf = RawVec::with_capacity_in(len, a); + unsafe { + ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len); + buf.into_box() + } + } +} + #[stable(feature = "box_from_slice", since = "1.17.0")] -impl From<&[T]> for Box<[T]> { +impl From<&[T]> for Box<[T], A> { /// Converts a `&[T]` into a `Box<[T]>` /// /// This conversion allocates on the heap @@ -544,18 +638,13 @@ impl From<&[T]> for Box<[T]> { /// /// println!("{:?}", boxed_slice); /// ``` - fn from(slice: &[T]) -> Box<[T]> { - let len = slice.len(); - let buf = RawVec::with_capacity(len); - unsafe { - ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len); - buf.into_box() - } + fn from(slice: &[T]) -> Box<[T], A> { + Box::<_, _>::from_slice_in(slice, A::default()) } } #[stable(feature = "box_from_slice", since = "1.17.0")] -impl From<&str> for Box { +impl From<&str> for Box { /// Converts a `&str` into a `Box` /// /// This conversion allocates on the heap @@ -567,13 +656,13 @@ impl From<&str> for Box { /// println!("{}", boxed); /// ``` #[inline] - fn from(s: &str) -> Box { + fn from(s: &str) -> Box { unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) } } } #[stable(feature = "boxed_str_conv", since = "1.19.0")] -impl From> for Box<[u8]> { +impl From> for Box<[u8], A> { /// Converts a `Box>` into a `Box<[u8]>` /// /// This conversion does not allocate on the heap and happens in place. @@ -591,12 +680,12 @@ impl From> for Box<[u8]> { /// assert_eq!(boxed_slice, boxed_str); /// ``` #[inline] - fn from(s: Box) -> Self { - unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) } + fn from(s: Box) -> Self { + unsafe { Box::map_raw(s, |p| p as *mut [u8]) } } } -impl Box { +impl Box { #[inline] #[stable(feature = "rust1", since = "1.0.0")] /// Attempt to downcast the box to a concrete type. @@ -618,19 +707,16 @@ impl Box { /// print_if_string(Box::new(0i8)); /// } /// ``` - pub fn downcast(self) -> Result, Box> { + pub fn downcast(self) -> Result, Box> { if self.is::() { - unsafe { - let raw: *mut dyn Any = Box::into_raw(self); - Ok(Box::from_raw(raw as *mut T)) - } + unsafe { Ok(Box::map_raw(self, |p| p as *mut T)) } } else { Err(self) } } } -impl Box { +impl Box { #[inline] #[stable(feature = "rust1", since = "1.0.0")] /// Attempt to downcast the box to a concrete type. @@ -652,30 +738,30 @@ impl Box { /// print_if_string(Box::new(0i8)); /// } /// ``` - pub fn downcast(self) -> Result, Box> { - >::downcast(self).map_err(|s| unsafe { + pub fn downcast(self) -> Result, Box> { + >::downcast(self).map_err(|s| unsafe { // reapply the Send marker - Box::from_raw(Box::into_raw(s) as *mut (dyn Any + Send)) + Box::map_raw(s, |p| p as *mut (dyn Any + Send)) }) } } #[stable(feature = "rust1", since = "1.0.0")] -impl fmt::Display for Box { +impl fmt::Display for Box { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&**self, f) } } #[stable(feature = "rust1", since = "1.0.0")] -impl fmt::Debug for Box { +impl fmt::Debug for Box { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&**self, f) } } #[stable(feature = "rust1", since = "1.0.0")] -impl fmt::Pointer for Box { +impl fmt::Pointer for Box { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // It's not possible to extract the inner Uniq directly from the Box, // instead we cast it to a *const which aliases the Unique @@ -685,7 +771,7 @@ impl fmt::Pointer for Box { } #[stable(feature = "rust1", since = "1.0.0")] -impl Deref for Box { +impl Deref for Box { type Target = T; fn deref(&self) -> &T { @@ -694,17 +780,17 @@ impl Deref for Box { } #[stable(feature = "rust1", since = "1.0.0")] -impl DerefMut for Box { +impl DerefMut for Box { fn deref_mut(&mut self) -> &mut T { &mut **self } } #[unstable(feature = "receiver_trait", issue = "0")] -impl Receiver for Box {} +impl Receiver for Box {} #[stable(feature = "rust1", since = "1.0.0")] -impl Iterator for Box { +impl Iterator for Box { type Item = I::Item; fn next(&mut self) -> Option { (**self).next() @@ -717,7 +803,7 @@ impl Iterator for Box { } } #[stable(feature = "rust1", since = "1.0.0")] -impl DoubleEndedIterator for Box { +impl DoubleEndedIterator for Box { fn next_back(&mut self) -> Option { (**self).next_back() } @@ -726,7 +812,7 @@ impl DoubleEndedIterator for Box { } } #[stable(feature = "rust1", since = "1.0.0")] -impl ExactSizeIterator for Box { +impl ExactSizeIterator for Box { fn len(&self) -> usize { (**self).len() } @@ -736,10 +822,10 @@ impl ExactSizeIterator for Box { } #[stable(feature = "fused", since = "1.26.0")] -impl FusedIterator for Box {} +impl FusedIterator for Box {} #[stable(feature = "boxed_closure_impls", since = "1.35.0")] -impl + ?Sized> FnOnce for Box { +impl + ?Sized, Alloc> FnOnce for Box { type Output = >::Output; extern "rust-call" fn call_once(self, args: A) -> Self::Output { @@ -748,14 +834,14 @@ impl + ?Sized> FnOnce for Box { } #[stable(feature = "boxed_closure_impls", since = "1.35.0")] -impl + ?Sized> FnMut for Box { +impl + ?Sized, Alloc> FnMut for Box { extern "rust-call" fn call_mut(&mut self, args: A) -> Self::Output { >::call_mut(self, args) } } #[stable(feature = "boxed_closure_impls", since = "1.35.0")] -impl + ?Sized> Fn for Box { +impl + ?Sized, Alloc> Fn for Box { extern "rust-call" fn call(&self, args: A) -> Self::Output { >::call(self, args) } @@ -841,8 +927,9 @@ impl FnBox for F } #[unstable(feature = "coerce_unsized", issue = "27732")] -impl, U: ?Sized> CoerceUnsized> for Box {} +impl, U: ?Sized, A> CoerceUnsized> for Box {} +//FIXME: Make generic over A when the compiler supports it. #[unstable(feature = "dispatch_from_dyn", issue = "0")] impl, U: ?Sized> DispatchFromDyn> for Box {} @@ -854,10 +941,10 @@ impl FromIterator for Box<[A]> { } #[stable(feature = "box_slice_clone", since = "1.3.0")] -impl Clone for Box<[T]> { +impl Clone for Box<[T], A> { fn clone(&self) -> Self { let mut new = BoxBuilder { - data: RawVec::with_capacity(self.len()), + data: RawVec::with_capacity_in(self.len(), self.1.clone()), len: 0, }; @@ -875,20 +962,20 @@ impl Clone for Box<[T]> { return unsafe { new.into_box() }; // Helper type for responding to panics correctly. - struct BoxBuilder { - data: RawVec, + struct BoxBuilder { + data: RawVec, len: usize, } - impl BoxBuilder { - unsafe fn into_box(self) -> Box<[T]> { + impl BoxBuilder { + unsafe fn into_box(self) -> Box<[T], A> { let raw = ptr::read(&self.data); mem::forget(self); raw.into_box() } } - impl Drop for BoxBuilder { + impl Drop for BoxBuilder { fn drop(&mut self) { let mut data = self.data.ptr(); let max = unsafe { data.add(self.len) }; @@ -905,28 +992,28 @@ impl Clone for Box<[T]> { } #[stable(feature = "box_borrow", since = "1.1.0")] -impl borrow::Borrow for Box { +impl borrow::Borrow for Box { fn borrow(&self) -> &T { &**self } } #[stable(feature = "box_borrow", since = "1.1.0")] -impl borrow::BorrowMut for Box { +impl borrow::BorrowMut for Box { fn borrow_mut(&mut self) -> &mut T { &mut **self } } #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")] -impl AsRef for Box { +impl AsRef for Box { fn as_ref(&self) -> &T { &**self } } #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")] -impl AsMut for Box { +impl AsMut for Box { fn as_mut(&mut self) -> &mut T { &mut **self } @@ -955,10 +1042,10 @@ impl AsMut for Box { * could have a method to project a Pin from it. */ #[stable(feature = "pin", since = "1.33.0")] -impl Unpin for Box { } +impl Unpin for Box { } #[unstable(feature = "generator_trait", issue = "43122")] -impl Generator for Box { +impl Generator for Box { type Yield = G::Yield; type Return = G::Return; @@ -968,7 +1055,7 @@ impl Generator for Box { } #[unstable(feature = "generator_trait", issue = "43122")] -impl Generator for Pin> { +impl Generator for Pin> { type Yield = G::Yield; type Return = G::Return; @@ -978,7 +1065,7 @@ impl Generator for Pin> { } #[stable(feature = "futures_api", since = "1.36.0")] -impl Future for Box { +impl Future for Box { type Output = F::Output; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { diff --git a/src/liballoc/raw_vec.rs b/src/liballoc/raw_vec.rs index 0454a56443579..c40624b14c7f0 100644 --- a/src/liballoc/raw_vec.rs +++ b/src/liballoc/raw_vec.rs @@ -682,8 +682,8 @@ impl RawVec { } -impl RawVec { - /// Converts the entire buffer into `Box<[T]>`. +impl RawVec { + /// Converts the entire buffer into `Box<[T], A>`. /// /// Note that this will correctly reconstitute any `cap` changes /// that may have been performed. (see description of type for details) @@ -693,10 +693,11 @@ impl RawVec { /// All elements of `RawVec` must be initialized. Notice that /// the rules around uninitialized boxed values are not finalized yet, /// but until they are, it is advisable to avoid them. - pub unsafe fn into_box(self) -> Box<[T]> { + pub unsafe fn into_box(self) -> Box<[T], A> { // NOTE: not calling `cap()` here, actually using the real `cap` field! let slice = slice::from_raw_parts_mut(self.ptr(), self.cap); - let output: Box<[T]> = Box::from_raw(slice); + let a = ptr::read(&self.a); + let output: Box<[T], A> = Box::from_raw_in(slice, a); mem::forget(self); output } diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index c827e218b2fb3..47b4d80cc5e16 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -729,7 +729,7 @@ impl Rc { value_size); // Free the allocation without dropping its contents - box_free(box_unique); + box_free::<_, Global>(box_unique, Global); Rc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData } } diff --git a/src/liballoc/str.rs b/src/liballoc/str.rs index 0c7d2b837a39a..893d1f69d8870 100644 --- a/src/liballoc/str.rs +++ b/src/liballoc/str.rs @@ -35,6 +35,7 @@ use core::ptr; use core::iter::FusedIterator; use core::unicode::conversions; +use crate::alloc::Alloc; use crate::borrow::ToOwned; use crate::boxed::Box; use crate::slice::{SliceConcatExt, SliceIndex}; @@ -585,6 +586,6 @@ impl str { /// ``` #[stable(feature = "str_box_extras", since = "1.20.0")] #[inline] -pub unsafe fn from_boxed_utf8_unchecked(v: Box<[u8]>) -> Box { - Box::from_raw(Box::into_raw(v) as *mut str) +pub unsafe fn from_boxed_utf8_unchecked(v: Box<[u8], A>) -> Box { + Box::map_raw(v, |p| p as *mut str) } diff --git a/src/liballoc/sync.rs b/src/liballoc/sync.rs index 70865656c510e..97d655e8456ab 100644 --- a/src/liballoc/sync.rs +++ b/src/liballoc/sync.rs @@ -615,7 +615,7 @@ impl Arc { value_size); // Free the allocation without dropping its contents - box_free(box_unique); + box_free::<_, Global>(box_unique, Global); Arc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData } } diff --git a/src/liballoc/tests/heap.rs b/src/liballoc/tests/heap.rs index c225ebfa96b91..a486ea8370891 100644 --- a/src/liballoc/tests/heap.rs +++ b/src/liballoc/tests/heap.rs @@ -1,4 +1,4 @@ -use std::alloc::{Global, Alloc, Layout, System}; +use std::alloc::{GlobalAlloc, Layout, System}; /// Issue #45955. #[test] @@ -6,21 +6,16 @@ fn alloc_system_overaligned_request() { check_overalign_requests(System) } -#[test] -fn std_heap_overaligned_request() { - check_overalign_requests(Global) -} - -fn check_overalign_requests(mut allocator: T) { +fn check_overalign_requests(allocator: T) { let size = 8; let align = 16; // greater than size let iterations = 100; unsafe { let pointers: Vec<_> = (0..iterations).map(|_| { - allocator.alloc(Layout::from_size_align(size, align).unwrap()).unwrap() + allocator.alloc(Layout::from_size_align(size, align).unwrap()) }).collect(); for &ptr in &pointers { - assert_eq!((ptr.as_ptr() as usize) % align, 0, + assert_eq!((ptr as usize) % align, 0, "Got a pointer less aligned than requested") } diff --git a/src/libstd/alloc.rs b/src/libstd/alloc.rs index ff52974775b05..f09176d149eee 100644 --- a/src/libstd/alloc.rs +++ b/src/libstd/alloc.rs @@ -63,7 +63,6 @@ use core::sync::atomic::{AtomicPtr, Ordering}; use core::{mem, ptr}; -use core::ptr::NonNull; use crate::sys_common::util::dumb_print; @@ -133,33 +132,6 @@ pub use alloc_crate::alloc::*; #[derive(Debug, Default, Copy, Clone)] pub struct System; -// The Alloc impl just forwards to the GlobalAlloc impl, which is in `std::sys::*::alloc`. -#[unstable(feature = "allocator_api", issue = "32838")] -unsafe impl Alloc for System { - #[inline] - unsafe fn alloc(&mut self, layout: Layout) -> Result, AllocErr> { - NonNull::new(GlobalAlloc::alloc(self, layout)).ok_or(AllocErr) - } - - #[inline] - unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result, AllocErr> { - NonNull::new(GlobalAlloc::alloc_zeroed(self, layout)).ok_or(AllocErr) - } - - #[inline] - unsafe fn dealloc(&mut self, ptr: NonNull, layout: Layout) { - GlobalAlloc::dealloc(self, ptr.as_ptr(), layout) - } - - #[inline] - unsafe fn realloc(&mut self, - ptr: NonNull, - layout: Layout, - new_size: usize) -> Result, AllocErr> { - NonNull::new(GlobalAlloc::realloc(self, ptr.as_ptr(), layout, new_size)).ok_or(AllocErr) - } -} - static HOOK: AtomicPtr<()> = AtomicPtr::new(ptr::null_mut()); /// Registers a custom allocation error hook, replacing any that was previously registered. diff --git a/src/test/run-pass/allocator/custom.rs b/src/test/run-pass/allocator/custom.rs index 71f72ae46c23f..5439e6d820955 100644 --- a/src/test/run-pass/allocator/custom.rs +++ b/src/test/run-pass/allocator/custom.rs @@ -7,14 +7,14 @@ extern crate helper; -use std::alloc::{self, Global, Alloc, System, Layout}; +use std::alloc::{Global, Alloc, GlobalAlloc, System, Layout}; use std::sync::atomic::{AtomicUsize, Ordering}; static HITS: AtomicUsize = AtomicUsize::new(0); struct A; -unsafe impl alloc::GlobalAlloc for A { +unsafe impl GlobalAlloc for A { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { HITS.fetch_add(1, Ordering::SeqCst); System.alloc(layout) @@ -49,7 +49,7 @@ fn main() { drop(s); assert_eq!(HITS.load(Ordering::SeqCst), n + 4); - let ptr = System.alloc(layout.clone()).unwrap(); + let ptr = System.alloc(layout.clone()); assert_eq!(HITS.load(Ordering::SeqCst), n + 4); helper::work_with(&ptr); System.dealloc(ptr, layout); diff --git a/src/test/run-pass/allocator/xcrate-use.rs b/src/test/run-pass/allocator/xcrate-use.rs index 039c70e77bedf..98be512f00a07 100644 --- a/src/test/run-pass/allocator/xcrate-use.rs +++ b/src/test/run-pass/allocator/xcrate-use.rs @@ -9,7 +9,7 @@ extern crate custom; extern crate helper; -use std::alloc::{Global, Alloc, System, Layout}; +use std::alloc::{Global, Alloc, GlobalAlloc, System, Layout}; use std::sync::atomic::{Ordering, AtomicUsize}; #[global_allocator] @@ -26,7 +26,7 @@ fn main() { Global.dealloc(ptr, layout.clone()); assert_eq!(GLOBAL.0.load(Ordering::SeqCst), n + 2); - let ptr = System.alloc(layout.clone()).unwrap(); + let ptr = System.alloc(layout.clone()); assert_eq!(GLOBAL.0.load(Ordering::SeqCst), n + 2); helper::work_with(&ptr); System.dealloc(ptr, layout); diff --git a/src/test/ui/error-codes/e0119/conflict-with-std.stderr b/src/test/ui/error-codes/e0119/conflict-with-std.stderr index 3e0c71e907481..7f8c4e6b32ac2 100644 --- a/src/test/ui/error-codes/e0119/conflict-with-std.stderr +++ b/src/test/ui/error-codes/e0119/conflict-with-std.stderr @@ -5,7 +5,7 @@ LL | impl AsRef for Box { | ^^^^^^^^^^^^^^^^^^^^^^^^ | = note: conflicting implementation in crate `alloc`: - - impl std::convert::AsRef for std::boxed::Box + - impl std::convert::AsRef for std::boxed::Box where T: ?Sized; error[E0119]: conflicting implementations of trait `std::convert::From` for type `S`: diff --git a/src/test/ui/issues/issue-14092.rs b/src/test/ui/issues/issue-14092.rs index 77da6badde948..3cfaa20a8b5ab 100644 --- a/src/test/ui/issues/issue-14092.rs +++ b/src/test/ui/issues/issue-14092.rs @@ -1,4 +1,4 @@ fn fn1(0: Box) {} - //~^ ERROR wrong number of type arguments: expected 1, found 0 [E0107] + //~^ ERROR wrong number of type arguments: expected at least 1, found 0 [E0107] fn main() {} diff --git a/src/test/ui/issues/issue-14092.stderr b/src/test/ui/issues/issue-14092.stderr index 626830ece8c11..b749c44780d96 100644 --- a/src/test/ui/issues/issue-14092.stderr +++ b/src/test/ui/issues/issue-14092.stderr @@ -1,8 +1,8 @@ -error[E0107]: wrong number of type arguments: expected 1, found 0 +error[E0107]: wrong number of type arguments: expected at least 1, found 0 --> $DIR/issue-14092.rs:1:11 | LL | fn fn1(0: Box) {} - | ^^^ expected 1 type argument + | ^^^ expected at least 1 type argument error: aborting due to previous error diff --git a/src/test/ui/issues/issue-41974.stderr b/src/test/ui/issues/issue-41974.stderr index 20121878a0754..3ca9ed724b56b 100644 --- a/src/test/ui/issues/issue-41974.stderr +++ b/src/test/ui/issues/issue-41974.stderr @@ -1,13 +1,13 @@ -error[E0119]: conflicting implementations of trait `std::ops::Drop` for type `std::boxed::Box<_>`: +error[E0119]: conflicting implementations of trait `std::ops::Drop` for type `std::boxed::Box<_, _>`: --> $DIR/issue-41974.rs:7:1 | LL | impl Drop for T where T: A { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: conflicting implementation in crate `alloc`: - - impl std::ops::Drop for std::boxed::Box + - impl std::ops::Drop for std::boxed::Box where T: ?Sized; - = note: downstream crates may implement trait `A` for type `std::boxed::Box<_>` + = note: downstream crates may implement trait `A` for type `std::boxed::Box<_, _>` error[E0120]: the Drop trait may only be implemented on structures --> $DIR/issue-41974.rs:7:18