Skip to content

Commit 60d0191

Browse files
Rollup merge of #165321 - whiplashvin:allocator-method-examples, r=tgross35
Add examples to Allocator methods Part of [#163232](#163232) Added examples to all six methods of the `Allocator` trait, namely `allocate`, `allocate_zeroed`, `deallocate`, `grow`, `grow_zeroed` and `shrink` using `System`. Follows [#165287](#165287) Checked with Miri. r? libs
2 parents 172aab0 + 118cd80 commit 60d0191

1 file changed

Lines changed: 113 additions & 1 deletion

File tree

‎library/core/src/alloc/mod.rs‎

Lines changed: 113 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,10 @@ pub const unsafe trait Allocator {
244244
/// returned excess. Implementors are free to e.g. provide an alternate method to query
245245
/// available excess if doing so is expensive and should be left to the caller.
246246
///
247+
/// The returned block may be uninitialized, so it is unsound to read it
248+
/// before it is written. Use [`allocate_zeroed`](Self::allocate_zeroed) if
249+
/// zero-initialized memory is needed.
250+
///
247251
/// Note that the returned block of memory is considered [*currently allocated*]
248252
/// with this allocator (and equivalent allocators).
249253
/// Therefore, it is the responsibility of implementors of `Allocator` to make sure that
@@ -265,6 +269,28 @@ pub const unsafe trait Allocator {
265269
/// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
266270
///
267271
/// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
272+
///
273+
/// # Examples
274+
///
275+
/// ```
276+
/// use std::alloc::{Allocator, Layout, System};
277+
///
278+
/// let s = "Hello, world!";
279+
/// let layout = Layout::array::<u8>(s.len()).unwrap();
280+
// FIXME(slice_ptr_get): use `.as_mut_ptr()` once stable
281+
/// let ptr = System.allocate(layout).expect("allocation failed").cast::<u8>();
282+
///
283+
/// // SAFETY: the block is at least `s.len()` bytes long and was just allocated,
284+
/// // so it cannot overlap `s`.
285+
/// unsafe { ptr.as_ptr().copy_from_nonoverlapping(s.as_ptr(), s.len()) };
286+
///
287+
/// // SAFETY: the first `s.len()` bytes were initialized by the copy above.
288+
/// let bytes = unsafe { std::slice::from_raw_parts(ptr.as_ptr(), s.len()) };
289+
/// assert_eq!(bytes, s.as_bytes());
290+
///
291+
/// // SAFETY: `ptr` was allocated by `System` with `layout`.
292+
/// unsafe { System.deallocate(ptr, layout) };
293+
/// ```
268294
#[stable(feature = "allocator_api", since = "1.100.0")]
269295
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>;
270296

@@ -283,6 +309,24 @@ pub const unsafe trait Allocator {
283309
/// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
284310
///
285311
/// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
312+
///
313+
/// # Examples
314+
///
315+
/// ```
316+
/// use std::alloc::{Allocator, Layout, System};
317+
///
318+
/// let layout = Layout::new::<u64>();
319+
/// let ptr = System.allocate_zeroed(layout).expect("allocation failed");
320+
///
321+
/// // N.B. the below would be unsound with `allocate` rather than `allocate_zeroed`.
322+
/// // SAFETY: `allocate_zeroed` returns a valid, initialized block.
323+
/// let bytes = unsafe { ptr.as_ref() };
324+
/// assert!(bytes.iter().all(|&b| b == 0));
325+
///
326+
/// // SAFETY: `ptr` was allocated by `System` with `layout`.
327+
// FIXME(slice_ptr_get): use `.as_mut_ptr()` once stable
328+
/// unsafe { System.deallocate(ptr.cast(), layout) };
329+
/// ```
286330
#[stable(feature = "allocator_api", since = "1.100.0")]
287331
fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
288332
let ptr = self.allocate(layout)?;
@@ -319,7 +363,9 @@ pub const unsafe trait Allocator {
319363
/// If this returns `Ok`, then the memory block referenced by `ptr` has been [*invalidated*].
320364
/// The old `ptr` must not be used to access the memory, even if the allocation was grown in-place.
321365
/// The newly returned pointer is the only valid pointer for accessing this memory now.
322-
/// All bytes past `old_layout.size()` should be assumed to be uninitialised.
366+
/// All bytes past `old_layout.size()` should be assumed to be uninitialised, so it is
367+
/// unsound to read them before they are written. Use [`grow_zeroed`](Self::grow_zeroed)
368+
/// if the new bytes should be zero-initialized.
323369
///
324370
/// If this method returns `Err`, then the memory block has not been *invalidated*,
325371
/// and the contents of the memory block are unaltered.
@@ -349,6 +395,45 @@ pub const unsafe trait Allocator {
349395
/// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
350396
///
351397
/// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
398+
///
399+
/// # Examples
400+
///
401+
/// ```
402+
/// use std::alloc::{Allocator, Layout, System};
403+
///
404+
/// let s1 = "Hello";
405+
/// let s2 = ", world!";
406+
///
407+
/// let old_layout = Layout::array::<u8>(s1.len()).unwrap();
408+
// FIXME(slice_ptr_get): use `.as_mut_ptr()` once stable
409+
/// let ptr = System.allocate(old_layout).expect("allocation failed").cast::<u8>();
410+
///
411+
/// // SAFETY: the block is at least `s1.len()` bytes long and was just allocated,
412+
/// // so it cannot overlap `s1`.
413+
/// unsafe { ptr.as_ptr().copy_from_nonoverlapping(s1.as_ptr(), s1.len()) };
414+
///
415+
/// let new_layout = Layout::array::<u8>(s1.len() + s2.len()).unwrap();
416+
///
417+
/// // N.B. the original `ptr` is invalidated by this operation
418+
/// // SAFETY: `ptr` is currently allocated by `System` with `old_layout`,
419+
/// // and `new_layout` is at least as large as `old_layout`.
420+
// FIXME(slice_ptr_get): use `.as_mut_ptr()` once stable
421+
/// let ptr = unsafe { System.grow(ptr, old_layout, new_layout) }
422+
/// .expect("grow failed").cast::<u8>();
423+
///
424+
/// // SAFETY: the block is at least `s1.len() + s2.len()` bytes long, so writing
425+
/// // `s2.len()` bytes at offset `s1.len()` stays in bounds; it cannot overlap `s2`.
426+
/// unsafe {
427+
/// ptr.as_ptr().add(s1.len()).copy_from_nonoverlapping(s2.as_ptr(), s2.len());
428+
/// }
429+
///
430+
/// // SAFETY: all bytes within `new_layout.size()` are now initialized.
431+
/// let bytes = unsafe { std::slice::from_raw_parts(ptr.as_ptr(), new_layout.size()) };
432+
/// assert_eq!(bytes, b"Hello, world!");
433+
///
434+
/// // SAFETY: `ptr` is currently allocated by `System` with `new_layout`.
435+
/// unsafe { System.deallocate(ptr, new_layout) };
436+
/// ```
352437
#[stable(feature = "allocator_api", since = "1.100.0")]
353438
unsafe fn grow(
354439
&self,
@@ -477,6 +562,33 @@ pub const unsafe trait Allocator {
477562
/// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
478563
///
479564
/// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
565+
///
566+
/// # Examples
567+
///
568+
/// ```
569+
/// use std::alloc::{Allocator, Layout, System};
570+
///
571+
/// let old_layout = Layout::array::<u32>(4).unwrap();
572+
/// let ptr = System.allocate(old_layout).expect("allocation failed");
573+
///
574+
/// // SAFETY: the block holds at least 4 `u32`s and is aligned for `u32`.
575+
/// unsafe { ptr.cast::<[u32; 4]>().write([7, 8, 9, 10]) };
576+
///
577+
/// let new_layout = Layout::array::<u32>(2).unwrap();
578+
///
579+
/// // N.B. the original `ptr` is invalidated by this operation
580+
/// // SAFETY: `ptr` is currently allocated by `System` with `old_layout`,
581+
/// // and `new_layout` is no larger than `old_layout`.
582+
/// let ptr = unsafe { System.shrink(ptr.cast(), old_layout, new_layout) }
583+
/// .expect("shrink failed");
584+
///
585+
/// // The contents that fit in the new layout are preserved.
586+
/// // SAFETY: the first two `u32`s were written above and `shrink` kept them.
587+
/// assert_eq!(unsafe { ptr.cast::<[u32; 2]>().read() }, [7, 8]);
588+
///
589+
/// // SAFETY: `ptr` is currently allocated by `System` with `new_layout`.
590+
/// unsafe { System.deallocate(ptr.cast(), new_layout) };
591+
/// ```
480592
#[stable(feature = "allocator_api", since = "1.100.0")]
481593
unsafe fn shrink(
482594
&self,

0 commit comments

Comments
 (0)