Code Example Template
Deep-Dive System Documentation
Machine-Native Size Indexing
The usize type is an unsigned integer that matches the pointer size of the target compile architecture.
Architectural Sizes
- 64-bit Systems:
usizebehaves as au64(8 bytes). - 32-bit Systems:
usizebehaves as au32(4 bytes).
Primary Purposes
- Container Indexing: Arrays, vectors, and slices can only be indexed or measured using
usizevalues. This protects against address bounds violations at compile time. - Memory Alignment: Calculating memory strides and offsets in custom buffers.
let active_profiles: Vec<Profile> = vec![];
let count: usize = active_profiles.len(); // returns machine-word size count
Performance Metrics
- Storage Size: Equal to native register sizes (4 or 8 bytes).
- Optimization: Highly optimized by compilers to leverage direct index registers of modern CPU architectures.
Useful Methods
.saturating_sub(rhs: Self) -> Self
Saturating subtraction. Computes self - rhs, returning 0 if subtraction would overflow/underflow, preventing runtime panic crashes on size indexing.
let minimum: usize = 0;
assert_eq!(minimum.saturating_sub(1), 0); // Safely stayed at zero
.checked_add(rhs: Self) -> Option<Self>
Checked addition. Returns None if addition overflows the pointer-sized boundary. Essential for verifying safe buffer capacity sizes before allocation.
let max_ptr = usize::MAX;
assert_eq!(max_ptr.checked_add(1), None);
Quick Reference Guide
let idx: usize = 0;
let capacity: usize = array.capacity();