Code Example Template
let profiles: Vec<Profile> = vec![];
let count: usize = profiles.len();

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: usize behaves as a u64 (8 bytes).
  • 32-bit Systems: usize behaves as a u32 (4 bytes).

Primary Purposes

  1. Container Indexing: Arrays, vectors, and slices can only be indexed or measured using usize values. This protects against address bounds violations at compile time.
  2. 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();