From d913faaf6d68e3e5f0a160876b51639c05f7df64 Mon Sep 17 00:00:00 2001 From: "yangguo@chromium.org" Date: Fri, 17 Oct 2014 10:01:38 +0000 Subject: [PATCH] Improve String.repeat. Adapted from patch contributed by Isiah Meadows . R=jkummerow@chromium.org Review URL: https://codereview.chromium.org/657863002 git-svn-id: https://v8.googlecode.com/svn/branches/bleeding_edge@24687 ce2b1a6d-e550-0410-aec6-3dcde31c8c00 --- AUTHORS | 1 + src/harmony-string.js | 15 +++++++++------ test/mjsunit/harmony/string-repeat.js | 3 +++ 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/AUTHORS b/AUTHORS index d406a6c..89caae6 100644 --- a/AUTHORS +++ b/AUTHORS @@ -39,6 +39,7 @@ Fedor Indutny Filipe David Manana Haitao Feng Ioseb Dzmanashvili +Isiah Meadows Jacob Bramley Jan de Mooij Jay Freeman diff --git a/src/harmony-string.js b/src/harmony-string.js index ae13745..1c477e2 100644 --- a/src/harmony-string.js +++ b/src/harmony-string.js @@ -17,16 +17,19 @@ function StringRepeat(count) { var s = TO_STRING_INLINE(this); var n = ToInteger(count); - if (n < 0 || !NUMBER_IS_FINITE(n)) { + // The maximum string length is stored in a smi, so a longer repeat + // must result in a range error. + if (n < 0 || n > %_MaxSmi()) { throw MakeRangeError("invalid_count_value", []); } - var elements = new InternalArray(n); - for (var i = 0; i < n; i++) { - elements[i] = s; + var r = ""; + while (true) { + if (n & 1) r += s; + n >>= 1; + if (n === 0) return r; + s += s; } - - return %StringBuilderConcat(elements, n, ""); } diff --git a/test/mjsunit/harmony/string-repeat.js b/test/mjsunit/harmony/string-repeat.js index 761089b..0af7448 100644 --- a/test/mjsunit/harmony/string-repeat.js +++ b/test/mjsunit/harmony/string-repeat.js @@ -61,8 +61,11 @@ assertEquals("", "".repeat(5)); assertEquals("", "abc".repeat(0)); assertEquals("abcabc", "abc".repeat(2.0)); +assertEquals("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "a".repeat(37)); assertThrows('"a".repeat(-1)', RangeError); assertThrows('"a".repeat(Number.POSITIVE_INFINITY)', RangeError); +assertThrows('"a".repeat(Math.pow(2, 30))', RangeError); +assertThrows('"a".repeat(Math.pow(2, 40))', RangeError); var myobj = { toString: function() { -- 2.7.4