Skip to content

Instantly share code, notes, and snippets.

@RandyMcMillan
Forked from rust-play/playground.rs
Created June 19, 2026 17:01
Show Gist options
  • Select an option

  • Save RandyMcMillan/2beb384f688047288d874a0db786347a to your computer and use it in GitHub Desktop.

Select an option

Save RandyMcMillan/2beb384f688047288d874a0db786347a to your computer and use it in GitHub Desktop.
demo_saturating_arithmetic.rs
//! Collatz sequence analyzer demonstrating both wrapping and saturating arithmetic.
//! Context: BIP-64MOD + GCC alignment verification
use std::num::Wrapping;
/// A demo function showing how saturating arithmetic behaves at the upper limit.
/// Instead of wrapping around to 0, it caps the value safely at u64::MAX.
pub fn demo_saturating_arithmetic(n: u64) -> u64 {
// If n is close to u64::MAX, regular arithmetic would panic in debug.
// saturating_mul and saturating_add will safely clamp the value at u64::MAX.
let next = n.saturating_mul(3).saturating_add(1);
if next == u64::MAX {
println!("⚠️ Arrived at saturation limit (u64::MAX)!");
}
next
}
/// Calculates the Collatz terminal token.
///
/// In release mode (`--release`), LLVM is smart enough to evaluate the constant
/// recurrence chain entirely at compile time and optimize this down to a single
/// `mov` instruction.
pub fn collatz(n: u64) -> u64 {
// Base Case: Terminal token reached
if n == 1 {
return 0xDEAD_BEEF;
}
// Even Case
if n % 2 == 0 {
let next_val = n / 2;
let result = collatz(next_val);
println!("Evaluating Even (n={}): downstream terminal is 0x{:X}", n, result);
return result;
}
// Odd Case: 3n + 1
// Using `Wrapping` prevents the runtime from throwing a "panic on overflow"
// exception during debug builds if `n` is large enough to overflow u64.
let wrapped_n = Wrapping(n);
let wrapped_three = Wrapping(3);
let wrapped_one = Wrapping(1);
// Perform operations with mathematical operators
let wrapped_next = (wrapped_n * wrapped_three) + wrapped_one;
let next = wrapped_next.0;
collatz(next)
}
fn main() {
// 1. Regular Collatz Execution
let start_val: u64 = 10;
println!("--- Starting Collatz Execution for n = {} ---", start_val);
let result = collatz(start_val);
println!("collatz({}) = 0x{:X}\n", start_val, result);
// 2. Saturating vs Wrapping Demonstration at the absolute limit
println!("--- Demonstrating Boundary Behavior (u64::MAX) ---");
let extreme_val: u64 = u64::MAX - 5;
// Wrapping behavior: rolls over like a clock
let wrapped_extreme = (Wrapping(extreme_val) * Wrapping(3) + Wrapping(1)).0;
// Saturating behavior: hits a hard ceiling
let saturated_extreme = demo_saturating_arithmetic(extreme_val);
println!("Starting value: {}", extreme_val);
println!("Wrapped result: {} (Wrapped around)", wrapped_extreme);
println!("Saturating result: {} (Capped at u64::MAX)", saturated_extreme);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment