From 8fb426e41e8e93623c35b5867de03d43ccb671b9 Mon Sep 17 00:00:00 2001 From: Charlie Tonneslan Date: Fri, 29 May 2026 08:09:46 -0400 Subject: [PATCH] random: return empty string instead of spinning when length is 0 Random.String(0) allocates a zero-length result buffer and a zero-length read buffer, then enters the read loop. io.ReadFull on a 0-length slice returns immediately, the inner range loop does nothing, and the outer loop just spins forever without making progress. Easy to hit because the input type is uint8 so callers passing a variable can land on 0. Return "" up front when length is 0. Added a 0-length case to TestRandomString. Signed-off-by: Charlie Tonneslan --- random/random.go | 4 ++++ random/random_test.go | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/random/random.go b/random/random.go index 282241b..aac04d8 100644 --- a/random/random.go +++ b/random/random.go @@ -43,6 +43,10 @@ func New() *Random { } func (r *Random) String(length uint8, charsets ...string) string { + if length == 0 { + return "" + } + charset := strings.Join(charsets, "") if charset == "" { charset = Alphanumeric diff --git a/random/random_test.go b/random/random_test.go index 5927dcf..0b26f9b 100644 --- a/random/random_test.go +++ b/random/random_test.go @@ -28,6 +28,10 @@ func TestRandomString(t *testing.T) { name: "ok, 32", whenLength: 32, }, + { + name: "ok, 0", + whenLength: 0, + }, } for _, tc := range testCases {