Watch
1
0
Fork
You've already forked souveraine
0
souveraine/docs/tasks/numeric-cast-safety.md
Fimeg 19b8566e4d docs: add task files for deferred safety/enhancement work
- remote-conversation-loading.md — implement list/load for RemoteBackend
- settings-error-display.md — wire validation errors to footer
- dead-code-cleanup.md — remove allow(dead_code), Letta aliases, unused imports
- numeric-cast-safety.md — add saturating cast helpers
2026-06-15 15:42:31 -04:00

1.9 KiB

Task: Add Numeric Cast Safety Helpers

Priority: Low Effort: 2-4 hours Files: New src/ui/cast.rs or src/core/cast.rs, plus updates across src/

Context

The codebase has hundreds of numeric casts (as u16, as usize, as i32, as u64). Many are safe (values are known to fit), but some could panic in debug mode or wrap silently in release mode.

Current patterns:

  • (f32_value) as u16 — panics if negative in debug, wraps in release
  • (expr) as usize — silently wraps on 32-bit if value exceeds 2^32
  • No consistent approach across the codebase

Requirements

1. Create a cast utility module

/// Saturating cast from f32 to u16. Returns 0 for negative, u16::MAX for overflow.
pub fn f32_to_u16(v: f32) -> u16 {
    v.max(0.0).min(u16::MAX as f32) as u16
}

/// Saturating cast from f32 to usize.
pub fn f32_to_usize(v: f32) -> usize {
    v.max(0.0) as usize  // f32 can't exceed usize::MAX on 64-bit
}

/// Saturating cast from usize to u16.
pub fn usize_to_u16(v: usize) -> u16 {
    v.min(u16::MAX as usize) as u16
}

2. Apply to worst offenders

Priority files:

  • src/ui/animation.rs — bloom renderer (already partially fixed)
  • src/ui/screens/splash.rs — tuie bloom renderer
  • src/ui/cockpit_panel.rs — pressure/percentage rendering
  • src/ui/presence.rs — jitter calculations

3. Pattern for adoption

  • Use the helpers where the input range is genuinely uncertain
  • Keep raw as casts where the value is provably in range (e.g., loop indices, enum discriminants)
  • Add a comment explaining why a raw cast is safe when keeping one

Acceptance Criteria

  • cast module exists with documented helper functions
  • Worst offenders use the helpers instead of raw casts
  • No behavior change for valid inputs
  • Edge cases (negative, overflow) saturate instead of panic/wrap
  • Tests cover boundary values for each helper