Skip to content

Fix slice when beginIndex is negative and endIndex <= 0 - #3392

Open
waw666waw666 wants to merge 1 commit into
vavr-io:mainfrom
waw666waw666:fix-stream-slice-negative-begin
Open

waw666waw666 wants to merge 1 commit into
vavr-io:mainfrom
waw666waw666:fix-stream-slice-negative-begin

Conversation

@waw666waw666

Copy link
Copy Markdown

Seq.slice clamps a negative beginIndex to 0, so slice(-1, 0) should be empty, like it is for List, Vector, Queue and CharSeq. Two implementations get this wrong:

Stream.of(1, 2, 3).slice(-1, 0)   // [1], expected []
Stream.of(1, 2, 3).slice(-3, -1)  // [1], expected []
Array.of(1, 2, 3).slice(-3, -1)   // throws NegativeArraySizeException: -1

Both check beginIndex >= endIndex before clamping beginIndex. With beginIndex = -1, endIndex = 0 the check passes, Stream then conses the head, and Array allocates an array of size min(endIndex, length) - 0, which is negative when endIndex is negative.

The fix clamps first and compares the clamped index with endIndex. In Array the "whole array" shortcut now uses the clamped index too.

Added shouldComputeSliceWhenBeginIndexIsNegativeAndEndIndexIsNotPositive to AbstractSeqTest, so it runs for every Seq. It fails on main for StreamTest (wrong result) and ArrayTest (exception) and passes with the fix. ./mvnw -pl vavr verify: 23477 tests, 0 failures; spotless:check passes.

Stream.slice and Array.slice compared the raw beginIndex with endIndex
before clamping it to 0, so a call like slice(-1, 0) was not treated as
empty. Stream returned its head ([1] for Stream.of(1, 2, 3)) and Array threw
NegativeArraySizeException for slice(-3, -1). Clamp first, then check.
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