Skip to content

Commit a18813f

Browse files
authored
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
2 parents 57a71ac + 9844d9e commit a18813f

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

library/alloc/src/vec/mod.rs

+22
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,27 @@ mod spec_extend;
285285
/// you would see if you coerced it to a slice), followed by [`capacity`]` -
286286
/// `[`len`] logically uninitialized, contiguous elements.
287287
///
288+
/// A vector containing the elements `'a'` and `'b'` with capacity 4 can be
289+
/// visualized as below. The top part is the `Vec` struct, it contains a
290+
/// pointer to the head of the allocation in the heap, length and capacity.
291+
/// The bottom part is the allocation on the heap, a contiguous memory block.
292+
///
293+
/// ```text
294+
/// ptr len capacity
295+
/// +--------+--------+--------+
296+
/// | 0x0123 | 2 | 4 |
297+
/// +--------+--------+--------+
298+
/// |
299+
/// v
300+
/// Heap +--------+--------+--------+--------+
301+
/// | 'a' | 'b' | uninit | uninit |
302+
/// +--------+--------+--------+--------+
303+
/// ```
304+
///
305+
/// - **uninit** represents memory that is not initialized, see [`MaybeUninit`].
306+
/// - Note: the ABI is not stable and `Vec` makes no guarantees about its memory
307+
/// layout (including the order of fields).
308+
///
288309
/// `Vec` will never perform a "small optimization" where elements are actually
289310
/// stored on the stack for two reasons:
290311
///
@@ -345,6 +366,7 @@ mod spec_extend;
345366
/// [`push`]: Vec::push
346367
/// [`insert`]: Vec::insert
347368
/// [`reserve`]: Vec::reserve
369+
/// [`MaybeUninit`]: core::mem::MaybeUninit
348370
/// [owned slice]: Box
349371
/// [slice]: ../../std/primitive.slice.html
350372
/// [`&`]: ../../std/primitive.reference.html

0 commit comments

Comments
 (0)