From fb5ed2986e7d999d57e907f2c3351a1b3dac59c3 Mon Sep 17 00:00:00 2001 From: Amanieu d'Antras Date: Tue, 12 Dec 2023 19:55:43 +0000 Subject: [PATCH 1/2] Clarify the lifetimes of allocations returned by the `Allocator` trait The previous definition (accidentally) disallowed the implementation of stack-based allocators whose memory would become invalid once the lifetime of the allocator type ended. This also ensures the validity of the following blanket implementation: ```rust impl Allocator for &'_ A {} ``` --- library/core/src/alloc/mod.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/library/core/src/alloc/mod.rs b/library/core/src/alloc/mod.rs index 78091c0172955..681d617af9377 100644 --- a/library/core/src/alloc/mod.rs +++ b/library/core/src/alloc/mod.rs @@ -95,8 +95,10 @@ impl fmt::Display for AllocError { /// # Safety /// /// * Memory blocks returned from an allocator that are [*currently allocated*] must point to -/// valid memory and retain their validity while they are [*currently allocated*] and at -/// least one of the instance and all of its clones has not been dropped. +/// valid memory and retain their validity while they are [*currently allocated*] and the shorter +/// of: +/// - the borrow-checker lifetime of the allocator type itself. +/// - as long as at least one of the instance and all of its clones has not been dropped. /// /// * copying, cloning, or moving the allocator must not invalidate memory blocks returned from this /// allocator. A copied or cloned allocator must behave like the same allocator, and From 8e9c8dd10ad90a021381c39e8bf68a1748c2f56f Mon Sep 17 00:00:00 2001 From: Amanieu d'Antras Date: Tue, 13 Feb 2024 14:12:51 +0000 Subject: [PATCH 2/2] Add information about allocation lifetime to Allocator::allocate --- library/core/src/alloc/mod.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/library/core/src/alloc/mod.rs b/library/core/src/alloc/mod.rs index 681d617af9377..1c8e667654469 100644 --- a/library/core/src/alloc/mod.rs +++ b/library/core/src/alloc/mod.rs @@ -116,6 +116,10 @@ pub unsafe trait Allocator { /// The returned block may have a larger size than specified by `layout.size()`, and may or may /// not have its contents initialized. /// + /// The returned block of memory remains valid as long as it is [*currently allocated*] and the shorter of: + /// - the borrow-checker lifetime of the allocator type itself. + /// - as long as at the allocator and all its clones has not been dropped. + /// /// # Errors /// /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet