add code examples · rust-lang/rust@a85ee3e (original) (raw)
`@@ -557,6 +557,32 @@ impl Vec {
`
557
557
`/// assert_eq!(rebuilt, [4, 5, 6]);
`
558
558
`/// }
`
559
559
```` /// ```
``
`560`
`+
///
`
``
`561`
`+
/// Using memory that was allocated elsewhere:
`
``
`562`
`+
///
`
``
`563`
```` +
/// ```rust
``
564
`+
/// #![feature(allocator_api)]
`
``
565
`+
///
`
``
566
`+
/// use std::alloc::{AllocError, Allocator, Global, Layout};
`
``
567
`+
///
`
``
568
`+
/// fn main() {
`
``
569
`+
/// let layout = Layout::array::(16).expect("overflow cannot happen");
`
``
570
`+
///
`
``
571
`+
/// let vec = unsafe {
`
``
572
`+
/// let mem = match Global.allocate(layout) {
`
``
573
`+
/// Ok(mem) => mem.cast::().as_ptr(),
`
``
574
`+
/// Err(AllocError) => return,
`
``
575
`+
/// };
`
``
576
`+
///
`
``
577
`+
/// mem.write(1_000_000);
`
``
578
`+
///
`
``
579
`+
/// Vec::from_raw_parts_in(mem, 1, 16, Global)
`
``
580
`+
/// };
`
``
581
`+
///
`
``
582
`+
/// assert_eq!(vec, &[1_000_000]);
`
``
583
`+
/// assert_eq!(vec.capacity(), 16);
`
``
584
`+
/// }
`
``
585
/// ```
560
586
`#[inline]
`
561
587
`#[stable(feature = "rust1", since = "1.0.0")]
`
562
588
`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> {
`
669
695
`` /// See the safety documentation of [pointer::offset
].
``
670
696
`///
`
671
697
`` /// These requirements are always upheld by any ptr
that has been allocated
``
672
``
`` -
/// via Vec<T>
. Other allocation sources are allowed if the invariants are
``
``
698
`` +
/// via Vec<T, A>
. Other allocation sources are allowed if the invariants are
``
673
699
`/// upheld.
`
674
700
`///
`
675
701
`/// Violating these may cause problems like corrupting the allocator's
`
`@@ -727,6 +753,29 @@ impl<T, A: Allocator> Vec<T, A> {
`
727
753
`/// assert_eq!(rebuilt, [4, 5, 6]);
`
728
754
`/// }
`
729
755
```` /// ```
``
`756`
`+
///
`
``
`757`
`+
/// Using memory that was allocated elsewhere:
`
``
`758`
`+
///
`
``
`759`
```` +
/// ```rust
``
760
`+
/// use std::alloc::{alloc, Layout};
`
``
761
`+
///
`
``
762
`+
/// fn main() {
`
``
763
`+
/// let layout = Layout::array::(16).expect("overflow cannot happen");
`
``
764
`+
/// let vec = unsafe {
`
``
765
`+
/// let mem = alloc(layout).cast::();
`
``
766
`+
/// if mem.is_null() {
`
``
767
`+
/// return;
`
``
768
`+
/// }
`
``
769
`+
///
`
``
770
`+
/// mem.write(1_000_000);
`
``
771
`+
///
`
``
772
`+
/// Vec::from_raw_parts(mem, 1, 16)
`
``
773
`+
/// };
`
``
774
`+
///
`
``
775
`+
/// assert_eq!(vec, &[1_000_000]);
`
``
776
`+
/// assert_eq!(vec.capacity(), 16);
`
``
777
`+
/// }
`
``
778
/// ```
730
779
`#[inline]
`
731
780
`#[unstable(feature = "allocator_api", issue = "32838")]
`
732
781
`pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self {
`