| name | check-bounds-safety |
| description | Apply type-safe bounds checking patterns using Index/Length types instead of usize. Use when working with arrays, buffers, cursors, viewports, or any code that handles indices and lengths. |
Type-Safe Bounds Checking
When to Use
- Working with array access or buffer operations
- Implementing cursor positioning logic (text editors, terminal emulators)
- Handling viewport rendering and scrolling
- Dealing with 0-based indices vs 1-based lengths
- Validating range boundaries
- Converting VT-100 ranges to Rust ranges
- Before creating commits with bounds-sensitive code
- When user asks about "bounds checking", "type safety", "off-by-one errors", etc.
The Problem
Raw usize values are ambiguous and error-prone:
let x = 10_usize;
if x < length {
buffer[x]
}
The Solution
Use type-safe wrappers from tui/src/core/units/bounds_check/:
use r3bl_tui::{idx, len, ArrayBoundsCheck};
let index = idx(10);
let length = len(100);
if index.overflows(length) {
}
Core Principles
Follow these principles when working with indices and lengths:
-
Use Index types (0-based) instead of usize
RowIndex, ColIndex, Index
- Construct with
row(), col(), idx()
-
Use Length types (1-based) instead of usize
RowHeight, ColWidth, Length
- Construct with
height(), width(), len()
-
Type-safe comparisons
- Cannot compare
RowIndex with ColWidth (compile error!)
- Prevents category errors like "is row 5 < width 10?"
-
Use .is_zero() for zero checks
- Instead of
== 0
- More idiomatic with newtype wrappers
-
Distinguish navigation from measurement
- Navigation (
index - offset → index): Moving backward in position space
- Measurement (
index.distance_from(other) → length): Calculating distance between positions
- Use
- for cursor movement, use distance_from() for calculating spans
Common Imports
use std::ops::Range;
use r3bl_tui::{
ArrayBoundsCheck, CursorBoundsCheck, ViewportBoundsCheck,
RangeBoundsExt, RangeConvertExt, RangeExt, IndexOps, LengthOps,
ArrayOverflowResult, CursorPositionBoundsStatus,
RangeValidityStatus, RangeBoundsResult,
col, row, width, height, idx, len,
TermRowDelta, TermColDelta, term_row_delta, term_col_delta,
};
Quick Pattern Reference
| Use Case | Trait | Key Method | When to Use |
|---|
| Array access | ArrayBoundsCheck | index.overflows(length) | Validating buffer[index] access (index < length) |
| Cursor positioning | CursorBoundsCheck | length.check_cursor_position_bounds(pos) | Text editing where cursor can be at end (index <= length) |
| Viewport visibility | ViewportBoundsCheck | index.check_viewport_bounds(start, size) | Rendering optimization (is content on-screen?) |
| Range validation | RangeBoundsExt | range.check_range_is_valid_for_length(len) | Iterator bounds, algorithm parameters |
| Range membership | RangeBoundsExt | range.check_index_is_within(index) | VT-100 scroll regions, text selections |
| Range conversion | RangeConvertExt | inclusive_range.to_exclusive() | Converting VT-100 ranges for Rust iteration |
| Slice indexing | RangeExt | range.as_usize_range() | Converting strongly-typed index ranges into raw [usize] ranges for slice indexing |
| Relative movement | TermRowDelta/TermColDelta | TermRowDelta::new(n) returns Option | ANSI cursor movement preventing CSI zero bug |
Detailed Examples
Example 1: Array Bounds Checking
Use ArrayBoundsCheck when validating buffer access.
use r3bl_tui::{idx, len, ArrayBoundsCheck, ArrayOverflowResult};
let buffer_length = len(100);
let index = idx(50);
match index.overflows(buffer_length) {
ArrayOverflowResult::Within => {
let value = buffer[index.value()];
}
ArrayOverflowResult::Overflows => {
eprintln!("Index {} overflows buffer length {}", index, buffer_length);
}
}
Mathematical law:
- For valid access:
0 <= index < length
- Or equivalently:
index < length (since Index is always >= 0)
Example 2: Cursor Position Bounds
Use CursorBoundsCheck for text cursor positioning.
use r3bl_tui::{idx, len, CursorBoundsCheck, CursorPositionBoundsStatus};
let text_length = len(10);
let cursor = idx(10);
match text_length.check_cursor_position_bounds(cursor) {
CursorPositionBoundsStatus::Within => {
}
CursorPositionBoundsStatus::Overflows => {
}
}
Mathematical law:
- For valid cursor:
0 <= position <= length
- Note: Cursor CAN be at
length (after the last character)
Key difference from array access:
- Array access:
index < length (strict inequality)
- Cursor position:
index <= length (includes equality)
Example 3: Viewport Visibility Check
Use ViewportBoundsCheck to optimize rendering.
use r3bl_tui::{idx, len, ViewportBoundsCheck};
let line_index = idx(150);
let viewport_start = idx(100);
let viewport_size = len(50);
if line_index.check_viewport_bounds(viewport_start, viewport_size) {
} else {
}
Mathematical law:
- Visible if:
viewport_start <= index < viewport_start + viewport_size
Example 4: Range Validation
Use RangeBoundsExt to validate range boundaries.
use r3bl_tui::{len, RangeBoundsExt, RangeValidityStatus};
let buffer_length = len(100);
let range = 10..50;
match range.check_range_is_valid_for_length(buffer_length) {
RangeValidityStatus::Valid => {
for i in range {
process(buffer[i]);
}
}
RangeValidityStatus::Invalid(reason) => {
eprintln!("Invalid range: {}", reason);
}
}
Example 5: Range Membership
Use RangeBoundsExt to check if index is within a range.
use r3bl_tui::{idx, RangeBoundsExt};
let scroll_region = 5..=15;
let cursor_row = idx(10);
if scroll_region.check_index_is_within(cursor_row) {
} else {
}
Example 6: Range Conversion
Use RangeConvertExt to convert inclusive to exclusive ranges.
use r3bl_tui::RangeConvertExt;
let vt100_range = 1..=10;
let rust_range = vt100_range.to_exclusive();
for line in rust_range {
process_line(line);
}
Example 7: Navigation vs Measurement
Use - for navigation (moving cursor), distance_from() for measurement (calculating spans).
use r3bl_tui::{row, height, RowIndex, RowHeight};
let cursor_pos = row(10);
let new_pos = cursor_pos - row(3);
let start = row(5);
let end = row(15);
let distance: RowHeight = end.distance_from(start);
When to use which:
- Moving cursor up/down/left/right →
- operator
- Calculating scroll amount, viewport span, selection size →
distance_from()
Example 8: Terminal Cursor Movement (Make Illegal States Unrepresentable)
Use TermRowDelta/TermColDelta for relative cursor movement in ANSI sequences.
The CSI zero problem: ANSI cursor movement commands interpret parameter 0 as 1:
CSI 0 A (CursorUp with n=0) moves cursor 1 row up, not 0
CSI 0 C (CursorForward with n=0) moves cursor 1 column right, not 0
Solution: TermRowDelta and TermColDelta wrap NonZeroU16 internally, making zero-valued
deltas impossible to represent. Construction is fallible:
use r3bl_tui::{TermRowDelta, TermColDelta, CsiSequence};
use std::io::Write;
let position: u16 = 240;
let term_width: u16 = 80;
if let Some(delta) = TermRowDelta::new(position / term_width) {
term.write_all(CsiSequence::CursorDown(delta).to_string().as_bytes())?;
}
if let Some(delta) = TermColDelta::new(position % term_width) {
term.write_all(CsiSequence::CursorForward(delta).to_string().as_bytes())?;
}
Using the ONE constant for common case:
use r3bl_tui::{TermRowDelta, TermColDelta, CsiSequence};
let up_one = CsiSequence::CursorUp(TermRowDelta::ONE);
let right_one = CsiSequence::CursorForward(TermColDelta::ONE);
Mathematical law:
- Zero deltas cannot exist - prevented at compile time by
NonZeroU16 wrapper
new() returns None for zero, Some(delta) for non-zero
Key difference from absolute positioning:
TermRow/TermCol: 1-based absolute coordinates (for CursorPosition)
TermRowDelta/TermColDelta: Relative movement amounts (for CursorUp/Down/Forward/Backward)
Example 9: Slice Indexing with Coordinate Ranges
Use RangeExt to convert strongly-typed index ranges into primitive usize ranges for slice indexing.
use r3bl_tui::{idx, RangeExt};
let index_range = idx(2)..idx(5);
for item in &mut buffer[index_range.as_usize_range()] {
process(item);
}
Supported range types:
Range<I> (e.g. start..end)
RangeInclusive<I> (e.g. start..=end)
RangeFrom<I> (e.g. start..)
RangeTo<I> (e.g. ..end)
Decision Trees
See the accompanying decision-trees.md file for flowcharts showing which trait to use for
each scenario.
Detailed Reference
For comprehensive documentation, decision trees, and more examples, see:
tui/src/core/units/bounds_check/mod.rs
This module contains:
- Complete API documentation
- Mathematical laws for each trait
- Visual decision trees
- Edge case handling
- Performance notes
Common Mistakes
❌ Mistake 1: Using raw usize
let index: usize = 10;
let length: usize = 100;
if index < length {
}
Fix:
let index = idx(10);
let length = len(100);
if !index.overflows(length) {
}
❌ Mistake 2: Array bounds used for cursor
let cursor = idx(10);
let text_length = len(10);
if cursor.overflows(text_length) {
return Err("Invalid cursor");
}
Fix:
if text_length.check_cursor_position_bounds(cursor) == CursorPositionBoundsStatus::Overflows {
return Err("Invalid cursor");
}
❌ Mistake 3: Comparing incompatible types
let row = row(5);
let width = width(10);
if row < width {
}
This is actually GOOD - the type system prevents nonsensical comparisons!
❌ Mistake 4: Using - when you need distance
let current_row = row(5);
let target_row = row(15);
let rows_to_scroll = target_row - current_row;
Fix:
let rows_to_scroll: RowHeight = target_row.distance_from(current_row);
❌ Mistake 5: Emitting CSI zero for cursor movement
let cols = position % term_width;
let seq = CsiSequence::CursorForward(cols);
Fix:
if let Some(delta) = TermColDelta::new(position % term_width) {
term.write_all(CsiSequence::CursorForward(delta).to_string().as_bytes())?;
}
Reporting Results
When applying bounds checking:
- ✅ All bounds checked with types → "Bounds safety verified with type-safe checks!"
- 🔧 Converted raw usize to Index/Length types → Report conversions made
- 📝 Added bounds checks → List where checks were added
Supporting Files in This Skill
This skill includes additional reference material:
decision-trees.md - Visual decision trees and flowcharts for choosing the right bounds checking approach: main decision tree (which trait?), array vs cursor bounds comparison, index vs length visual diagrams, viewport visibility flowchart, range validation flowchart, comparison table, edge case reference, and quick reference card. Read this when:
- Not sure which trait to use → Main decision tree
- Array access vs cursor positioning confusion → Visual comparison diagrams
- Viewport visibility logic → Viewport flowchart
- Range validation → Range validation flowchart
- Edge cases (empty arrays, cursor at end, zero-sized viewport) → Edge cases section
- Quick lookup of which method for which scenario → Comparison table
Related Skills
check-code-quality - Includes testing bounds-checking code
write-documentation - For documenting bounds-checking logic
Related Commands
No dedicated command, but used throughout the codebase for safe index/length handling.
Additional Resources
- Main implementation:
tui/src/core/units/bounds_check/mod.rs
- Type definitions:
tui/src/core/units/
- Examples in tests:
tui/src/core/units/bounds_check/tests/
- Terminal delta types:
tui/src/core/coordinates/vt_100_ansi_coords/term_row_delta.rs and term_col_delta.rs