From 632a538eb3aadd03e91792aa079fccc7ae5f96f4 Mon Sep 17 00:00:00 2001 From: Alexey Date: Sat, 29 Feb 2020 17:25:31 +0300 Subject: [PATCH] string: update `string.repeat` behavior Panic if a repeat count is negative. Return an empty string if a repeat count is zero. --- vlib/builtin/string.v | 6 +++++- vlib/builtin/string_test.v | 14 +++++++++----- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/vlib/builtin/string.v b/vlib/builtin/string.v index b1e8232476..4f26446c7f 100644 --- a/vlib/builtin/string.v +++ b/vlib/builtin/string.v @@ -1251,7 +1251,11 @@ pub fn (s string) bytes() []byte { // repeat returns a new string with a specified number of copies of the string it was called on. pub fn (s string) repeat(count int) string { - if count <= 1 { + if count < 0 { + panic('string.repeat: count is negative: $count') + } else if count == 0 { + return '' + } else if count == 1 { return s } mut ret := malloc(s.len * count + 1) diff --git a/vlib/builtin/string_test.v b/vlib/builtin/string_test.v index 44b6209a77..3b1c1f225c 100644 --- a/vlib/builtin/string_test.v +++ b/vlib/builtin/string_test.v @@ -603,11 +603,15 @@ fn test_limit() { } fn test_repeat() { - s := 'V! ' - assert s.repeat(5) == 'V! V! V! V! V! ' - assert s.repeat(1) == s - assert s.repeat(0) == s - assert s.repeat(-1) == s + s1 := 'V! ' + assert s1.repeat(5) == 'V! V! V! V! V! ' + assert s1.repeat(1) == s1 + assert s1.repeat(0) == '' + s2 := '' + assert s2.repeat(5) == s2 + assert s2.repeat(1) == s2 + assert s2.repeat(0) == s2 + // TODO Add test for negative values } fn test_raw() {