From 8e41a308cd2aa50e6e23b8a3ead7c3b76e5aa57f Mon Sep 17 00:00:00 2001 From: Chetan Date: Tue, 7 Jan 2025 23:40:25 +0530 Subject: [PATCH] fix(explore): handle zero-size cursor in binary viewer (#14592) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Description Fix cursor panic when handling size zero in binary viewer. Previously, the cursor would panic with arithmetic overflow when handling size 0. This PR fixes this by using `saturating_sub` to safely handle the edge case of size 0. Fixes #14589 # User-Facing Changes - Fixed panic when viewing very small binary inputs in the explore command (when using `0x[f] | explore`) # Tests + Formatting Added tests to verify: - Cursor handling of size 0 - Safe movement operations with size 0 - Edge case handling with size 1 ✅ Verified all checks pass: - `cargo fmt --all -- --check` - `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` - `cargo test --package nu-explore --lib cursor` --- crates/nu-explore/src/views/cursor/mod.rs | 24 ++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/nu-explore/src/views/cursor/mod.rs b/crates/nu-explore/src/views/cursor/mod.rs index 4c37b70977..638b979897 100644 --- a/crates/nu-explore/src/views/cursor/mod.rs +++ b/crates/nu-explore/src/views/cursor/mod.rs @@ -36,7 +36,7 @@ impl Cursor { /// The max position the cursor can be at pub fn end(&self) -> usize { - self.size - 1 + self.size.saturating_sub(1) } /// Set the position to a specific value within the bounds [0, end] @@ -121,4 +121,26 @@ mod tests { cursor.move_backward(3); assert_eq!(cursor.position, 0); } + + #[test] + fn test_cursor_size_zero_handling() { + let cursor = Cursor::new(0); + assert_eq!(cursor.end(), 0); + + let mut cursor = Cursor::new(0); + cursor.move_forward(1); + assert_eq!(cursor.position, 0); + + cursor.move_backward(1); + assert_eq!(cursor.position, 0); + } + + #[test] + fn test_cursor_size_one() { + let mut cursor = Cursor::new(1); + assert_eq!(cursor.end(), 0); + + cursor.move_forward(1); + assert_eq!(cursor.position, 0); + } }