From f13e8b602e20a80bc7e2e32a971307c0d34e07ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1ty=C3=A1s=20Mustoha?= Date: Fri, 15 May 2020 22:18:42 +0200 Subject: [PATCH] Fix position calculations of String.startsWith (#3734) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes two bugs in the index calculations that affect the result of the `String.startsWith` function: - Fixes the implementation of ECMA-262 v6, 21.1.3.18, step 14: "If searchLength+start is greater than len, return false". - Fixes the return value of the helper function `ecma_builtin_helper_string_find_index`. If it is called with a starting search position, the returned index should be not less than that. These changes fix the following test cases in the test262 suite: - built-ins/String/prototype/startsWith/return-true-if-searchstring-is-empty.js - built-ins/String/prototype/startsWith/searchstring-found-with-position.js JerryScript-DCO-1.0-Signed-off-by: Mátyás Mustoha mmatyas@inf.u-szeged.hu --- jerry-core/ecma/builtin-objects/ecma-builtin-helpers.c | 6 ++++-- tests/jerry/es2015/string-prototype-startswith.js | 3 +++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/jerry-core/ecma/builtin-objects/ecma-builtin-helpers.c b/jerry-core/ecma/builtin-objects/ecma-builtin-helpers.c index 26d2a15b8..eea19bf1e 100644 --- a/jerry-core/ecma/builtin-objects/ecma-builtin-helpers.c +++ b/jerry-core/ecma/builtin-objects/ecma-builtin-helpers.c @@ -585,7 +585,9 @@ ecma_builtin_helper_string_prototype_object_index_of (ecma_string_t *original_st #if ENABLED (JERRY_ES2015) case ECMA_STRING_STARTS_WITH: { - if (pos_num + start > original_len) + const ecma_length_t search_len = ecma_string_get_length (search_str_p); + + if (search_len + start > original_len) { break; } @@ -687,7 +689,7 @@ ecma_builtin_helper_string_find_index (ecma_string_t *original_str_p, /**< index if (!search_len) { match_found = true; - *ret_index_p = first_index ? 0 : original_len; + *ret_index_p = first_index ? start_pos : original_len; } else { diff --git a/tests/jerry/es2015/string-prototype-startswith.js b/tests/jerry/es2015/string-prototype-startswith.js index 0effd36b4..3f23487f3 100644 --- a/tests/jerry/es2015/string-prototype-startswith.js +++ b/tests/jerry/es2015/string-prototype-startswith.js @@ -15,7 +15,10 @@ var x = "My cat is awesome"; assert (x.startsWith ("My")); assert (x.startsWith ("cat", 3)); +assert (x.startsWith ("awesome", 10)); assert (x.startsWith ("")); +assert (x.startsWith ("", 1)); +assert (x.startsWith ("", 17)); assert (x.startsWith ([])); assert (x.startsWith ("doggo") === false);