Skip to content

fix(table): clamp cursor to 0 when SetRows is called with empty slice#1003

Open
LeSingh1 wants to merge 1 commit into
charmbracelet:mainfrom
LeSingh1:fix/table-cursor-negative-on-empty-rows
Open

fix(table): clamp cursor to 0 when SetRows is called with empty slice#1003
LeSingh1 wants to merge 1 commit into
charmbracelet:mainfrom
LeSingh1:fix/table-cursor-negative-on-empty-rows

Conversation

@LeSingh1

Copy link
Copy Markdown

When SetRows is called with an empty rows slice, the guard added in #783
still runs the assignment on line 310:

if m.cursor > len(m.rows)-1 {
    m.cursor = len(m.rows) - 1  // len == 0, so this is -1
}

Because len(m.rows)-1 is -1 when the slice is empty, any cursor position
(including 0) satisfies the condition and gets set to -1. After that,
Cursor() returns -1 indefinitely until new rows are loaded.

The fix adds an explicit empty-slice guard that resets cursor to 0, which
matches the initial state of a freshly constructed table. The existing
shrink-to-fewer-rows path is unchanged.

Before this change, TestSetRows_CursorClampsToZeroOnEmpty failed:

cursor_shrink_test.go:23: SetRows(empty): Cursor() = -1, want >= 0

After: both new tests pass and the full table suite stays green.

When SetRows was called with an empty rows slice, len(m.rows)-1 evaluated
to -1, causing cursor to be set to -1. Subsequent calls to Cursor() would
return -1, which is out of bounds and breaks callers that expect a valid
index.

The fix guards for the empty case and resets cursor to 0, consistent with
the initial state of a new table. The existing shrink-to-fewer-rows guard
is preserved for the non-empty case.

Adds a regression test covering both the empty-rows reset and the
previously-tested shrink case.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant