Skip to content

fix: ChunkString returns empty slice for empty input (fixes #788)#880

Open
nghiack7 wants to merge 1 commit into
samber:masterfrom
nghiack7:fix/chunk-string-empty
Open

fix: ChunkString returns empty slice for empty input (fixes #788)#880
nghiack7 wants to merge 1 commit into
samber:masterfrom
nghiack7:fix/chunk-string-empty

Conversation

@nghiack7
Copy link
Copy Markdown

@nghiack7 nghiack7 commented May 9, 2026

Summary

ChunkString("", n) was returning [""] (a one-element slice containing an empty string) instead of [] (an empty slice). This was inconsistent with Chunk([]rune{}, n) which correctly returns an empty slice.

Root Cause

The early-return guard if size >= len(str) { return []T{str} } always fires when str is empty because any positive size satisfies size >= 0. So it returned []T{""} instead of an empty slice.

Fix

Add an explicit early-return for the empty-string case before the size check:

if len(str) == 0 {
    return []T{}
}

Test

Updated the existing test case (which already carried a // @TODO: should be [] comment referencing #788) to assert the correct behavior.

// Before
ChunkString("", 2) // => [""]

// After  
ChunkString("", 2) // => []

Full test suite passes with no regressions.

Fixes #788

ChunkString("", n) was returning [""] (a slice containing one empty
string) because the early-return guard `size >= len(str)` always
fires when str is empty (any positive size satisfies 0 >= 0).

Add an explicit early-return for the empty-string case so that
ChunkString("", n) returns [] consistently with Chunk([]rune{}, n).

Update the existing test case that carried a TODO comment noting this
inconsistency (see samber#788).
@nghiack7
Copy link
Copy Markdown
Author

Friendly ping — this is a one-line fix for ChunkString("", n) returning [""] instead of []. All tests pass ✅. Fixes #788.

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.

[v2] ChunkString behavior inconsistency with Chunk for empty input

1 participant