From 7668ee6861eb2c041fc8d0b7a46ed0ee770682c6 Mon Sep 17 00:00:00 2001 From: Dmitry Chestnykh Date: Wed, 21 Jan 2015 18:36:13 +0100 Subject: [PATCH] Fix hanging when requested zero-length string. Add test for NewLen from 0 to 100. --- uniuri.go | 3 +++ uniuri_test.go | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/uniuri.go b/uniuri.go index ef1cd24..3981c00 100644 --- a/uniuri.go +++ b/uniuri.go @@ -53,6 +53,9 @@ func NewLen(length int) string { // NewLenChars returns a new random string of the provided length, consisting // of the provided byte slice of allowed characters (maximum 256). func NewLenChars(length int, chars []byte) string { + if length == 0 { + return "" + } b := make([]byte, length) r := make([]byte, length+(length/4)) // storage for random bytes. clen := len(chars) diff --git a/uniuri_test.go b/uniuri_test.go index c564c60..a2478af 100644 --- a/uniuri_test.go +++ b/uniuri_test.go @@ -46,6 +46,15 @@ func TestNew(t *testing.T) { } } +func TestNewLen(t *testing.T) { + for i := 0; i < 100; i++ { + u := NewLen(i) + if len(u) != i { + t.Fatalf("request length %d, got %d", i, len(u)) + } + } +} + func TestNewLenChars(t *testing.T) { length := 10 chars := []byte("01234567")