diff options
| author | Duarte Nunes <duarte.nunes@datadoghq.com> | 2022-07-14 11:47:06 -0300 |
|---|---|---|
| committer | Duarte Nunes <duarte.nunes@datadoghq.com> | 2022-07-14 11:47:06 -0300 |
| commit | a85ee3ed9130de6b263de0b05e67b04e644f269e (patch) | |
| tree | 3cac8398da0adb6a86ff5150de3dab4a06c3e741 /library/alloc/src | |
| parent | 8d35ab38067ede0b2816e0177d1d0e0869e89136 (diff) | |
| download | rust-a85ee3ed9130de6b263de0b05e67b04e644f269e.tar.gz rust-a85ee3ed9130de6b263de0b05e67b04e644f269e.zip | |
add code examples
Diffstat (limited to 'library/alloc/src')
| -rw-r--r-- | library/alloc/src/vec/mod.rs | 51 |
1 files changed, 50 insertions, 1 deletions
diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index fcfb88b18c7..ae99772450e 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -557,6 +557,32 @@ impl<T> Vec<T> { /// assert_eq!(rebuilt, [4, 5, 6]); /// } /// ``` + /// + /// Using memory that was allocated elsewhere: + /// + /// ```rust + /// #![feature(allocator_api)] + /// + /// use std::alloc::{AllocError, Allocator, Global, Layout}; + /// + /// fn main() { + /// let layout = Layout::array::<u32>(16).expect("overflow cannot happen"); + /// + /// let vec = unsafe { + /// let mem = match Global.allocate(layout) { + /// Ok(mem) => mem.cast::<u32>().as_ptr(), + /// Err(AllocError) => return, + /// }; + /// + /// mem.write(1_000_000); + /// + /// Vec::from_raw_parts_in(mem, 1, 16, Global) + /// }; + /// + /// assert_eq!(vec, &[1_000_000]); + /// assert_eq!(vec.capacity(), 16); + /// } + /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self { @@ -669,7 +695,7 @@ impl<T, A: Allocator> Vec<T, A> { /// See the safety documentation of [`pointer::offset`]. /// /// These requirements are always upheld by any `ptr` that has been allocated - /// via `Vec<T>`. Other allocation sources are allowed if the invariants are + /// via `Vec<T, A>`. Other allocation sources are allowed if the invariants are /// upheld. /// /// Violating these may cause problems like corrupting the allocator's @@ -727,6 +753,29 @@ impl<T, A: Allocator> Vec<T, A> { /// assert_eq!(rebuilt, [4, 5, 6]); /// } /// ``` + /// + /// Using memory that was allocated elsewhere: + /// + /// ```rust + /// use std::alloc::{alloc, Layout}; + /// + /// fn main() { + /// let layout = Layout::array::<u32>(16).expect("overflow cannot happen"); + /// let vec = unsafe { + /// let mem = alloc(layout).cast::<u32>(); + /// if mem.is_null() { + /// return; + /// } + /// + /// mem.write(1_000_000); + /// + /// Vec::from_raw_parts(mem, 1, 16) + /// }; + /// + /// assert_eq!(vec, &[1_000_000]); + /// assert_eq!(vec.capacity(), 16); + /// } + /// ``` #[inline] #[unstable(feature = "allocator_api", issue = "32838")] pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self { |
