about summary refs log tree commit diff
diff options
context:
space:
mode:
authorYuki Okushi <huyuumi.dev@gmail.com>2021-01-21 20:04:38 +0900
committerGitHub <noreply@github.com>2021-01-21 20:04:38 +0900
commita18813f6cc06917bf1babca87ec313aa680eceee (patch)
tree1e015bed24019338fb4158f5b3bec417756317b6
parent57a71ac0e17e4f7070b090ab7bdc5474d8e37ecc (diff)
parent9844d9ee97f27f3d603f633e64bd03e1cc14e55b (diff)
downloadrust-a18813f6cc06917bf1babca87ec313aa680eceee.tar.gz
rust-a18813f6cc06917bf1babca87ec313aa680eceee.zip
Rollup merge of #79655 - pickfire:visual-vec, r=m-ou-se
Add Vec visualization to understand capacity

Visualize vector while differentiating between stack and heap.

Inspired by cheats.rs, as this is probably the first place beginner go,
they could understand stack and heap, length and capacity with this. Not
sure if adding this means we should add to other places too.

Superseeds #76066

r? `@m-ou-se`

cc `@the8472` I put back the order of the fields as it feels weird, the note already explains that the order of fields is not guaranteed
-rw-r--r--library/alloc/src/vec/mod.rs22
1 files changed, 22 insertions, 0 deletions
diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs
index ccc4f03a1e5..0f5feb4ab8d 100644
--- a/library/alloc/src/vec/mod.rs
+++ b/library/alloc/src/vec/mod.rs
@@ -285,6 +285,27 @@ mod spec_extend;
 /// you would see if you coerced it to a slice), followed by [`capacity`]` -
 /// `[`len`] logically uninitialized, contiguous elements.
 ///
+/// A vector containing the elements `'a'` and `'b'` with capacity 4 can be
+/// visualized as below. The top part is the `Vec` struct, it contains a
+/// pointer to the head of the allocation in the heap, length and capacity.
+/// The bottom part is the allocation on the heap, a contiguous memory block.
+///
+/// ```text
+///             ptr      len  capacity
+///        +--------+--------+--------+
+///        | 0x0123 |      2 |      4 |
+///        +--------+--------+--------+
+///             |
+///             v
+/// Heap   +--------+--------+--------+--------+
+///        |    'a' |    'b' | uninit | uninit |
+///        +--------+--------+--------+--------+
+/// ```
+///
+/// - **uninit** represents memory that is not initialized, see [`MaybeUninit`].
+/// - Note: the ABI is not stable and `Vec` makes no guarantees about its memory
+///   layout (including the order of fields).
+///
 /// `Vec` will never perform a "small optimization" where elements are actually
 /// stored on the stack for two reasons:
 ///
@@ -345,6 +366,7 @@ mod spec_extend;
 /// [`push`]: Vec::push
 /// [`insert`]: Vec::insert
 /// [`reserve`]: Vec::reserve
+/// [`MaybeUninit`]: core::mem::MaybeUninit
 /// [owned slice]: Box
 /// [slice]: ../../std/primitive.slice.html
 /// [`&`]: ../../std/primitive.reference.html