Skip to content

Commit 6cbadde

Browse files
committed
fix: handle empty files gracefully instead of throwing errors
- Remove empty data validation in CountBytes method - Empty files now return zero statistics instead of errors - Update tests to reflect new behavior - Add comprehensive empty data handling tests Fixes issue where empty files would cause program to crash with 'input data cannot be empty' error during directory scanning.
1 parent 7b61320 commit 6cbadde

2 files changed

Lines changed: 37 additions & 6 deletions

File tree

count.go

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -117,11 +117,8 @@ func isChinese(r rune) bool {
117117
// - Minimal function call overhead
118118
// - Local variables to reduce struct field access overhead
119119
//
120-
// Returns an error if the input data is empty.
120+
// Empty data is handled gracefully and returns zero counts for all statistics.
121121
func (c *Counter) CountBytes(data []byte) error {
122-
if len(data) == 0 {
123-
return NewInvalidInputError("input data cannot be empty")
124-
}
125122

126123
// Use local variables to minimize struct field access overhead
127124
lines := 0

count_test.go

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -190,12 +190,12 @@ func TestCounter_CountBytes_EdgeCases(t *testing.T) {
190190
{
191191
name: "Empty byte slice",
192192
input: []byte{},
193-
wantErr: true,
193+
wantErr: false,
194194
},
195195
{
196196
name: "Nil byte slice",
197197
input: nil,
198-
wantErr: true,
198+
wantErr: false,
199199
},
200200
{
201201
name: "Single newline",
@@ -226,6 +226,40 @@ func TestCounter_CountBytes_EdgeCases(t *testing.T) {
226226
}
227227
}
228228

229+
func TestCounter_CountBytes_EmptyData(t *testing.T) {
230+
tests := []struct {
231+
name string
232+
input []byte
233+
}{
234+
{
235+
name: "Empty byte slice",
236+
input: []byte{},
237+
},
238+
{
239+
name: "Nil byte slice",
240+
input: nil,
241+
},
242+
}
243+
244+
for _, tt := range tests {
245+
t.Run(tt.name, func(t *testing.T) {
246+
tc := wordcounter.NewCounter()
247+
err := tc.CountBytes(tt.input)
248+
249+
if err != nil {
250+
t.Errorf("Counter.CountBytes() error = %v, expected no error for empty data", err)
251+
return
252+
}
253+
254+
stats := tc.GetStats()
255+
if stats.Lines != 0 || stats.ChineseChars != 0 || stats.NonChineseChars != 0 || stats.TotalChars != 0 {
256+
t.Errorf("Counter.CountBytes() for empty data, expected all zero stats, got: Lines=%d, ChineseChars=%d, NonChineseChars=%d, TotalChars=%d",
257+
stats.Lines, stats.ChineseChars, stats.NonChineseChars, stats.TotalChars)
258+
}
259+
})
260+
}
261+
}
262+
229263
func TestCounter_LargeText(t *testing.T) {
230264
// Test with large text to ensure performance
231265
largeText := strings.Repeat("这是一个测试文本。", 10000) // 10,000 repetitions

0 commit comments

Comments
 (0)