[njs] Fixed String.prototype.replace() with byte strings.

Dmitry Volyntsev xeioex at nginx.com
Sat Jun 4 07:21:05 UTC 2022


details:   https://hg.nginx.org/njs/rev/9c4858617097
branches:  
changeset: 1877:9c4858617097
user:      Dmitry Volyntsev <xeioex at nginx.com>
date:      Fri Jun 03 23:24:12 2022 -0700
description:
Fixed String.prototype.replace() with byte strings.

This closes #522 issue on Github.

diffstat:

 src/njs_string.c         |  23 +++++++++++++++--------
 src/test/njs_unit_test.c |   5 +++++
 2 files changed, 20 insertions(+), 8 deletions(-)

diffs (69 lines):

diff -r dd4d6e7cd9ad -r 9c4858617097 src/njs_string.c
--- a/src/njs_string.c	Fri Jun 03 23:24:11 2022 -0700
+++ b/src/njs_string.c	Fri Jun 03 23:24:12 2022 -0700
@@ -3663,7 +3663,7 @@ njs_string_prototype_replace(njs_vm_t *v
     njs_index_t unused)
 {
     u_char             *r;
-    size_t             length, search_length, ret_length, size;
+    size_t             length, size;
     int64_t            pos;
     njs_int_t          ret;
     njs_value_t        *this, *search, *replace;
@@ -3722,8 +3722,8 @@ njs_string_prototype_replace(njs_vm_t *v
         }
     }
 
-    length = njs_string_prop(&string, this);
-    search_length = njs_string_prop(&s, search);
+    (void) njs_string_prop(&string, this);
+    (void) njs_string_prop(&s, search);
 
     pos = njs_string_index_of(&string, &s, 0);
     if (pos < 0) {
@@ -3757,7 +3757,7 @@ njs_string_prototype_replace(njs_vm_t *v
         }
     }
 
-    if (length == string.size) {
+    if (njs_is_byte_or_ascii_string(&string)) {
         p = string.start + pos;
 
     } else {
@@ -3765,10 +3765,17 @@ njs_string_prototype_replace(njs_vm_t *v
         p = njs_string_offset(string.start, string.start + string.size, pos);
     }
 
-    ret_length = njs_string_prop(&ret_string, &retval);
-
-    size = string.size + ret_string.size -  s.size;
-    length += ret_length - search_length;
+    (void) njs_string_prop(&ret_string, &retval);
+
+    size = string.size + ret_string.size - s.size;
+    length = string.length + ret_string.length - s.length;
+
+    if (njs_is_byte_string(&string)
+        || njs_is_byte_string(&s)
+        || njs_is_byte_string(&ret_string))
+    {
+        length = 0;
+    }
 
     r = njs_string_alloc(vm, &vm->retval, size, length);
     if (njs_slow_path(r == NULL)) {
diff -r dd4d6e7cd9ad -r 9c4858617097 src/test/njs_unit_test.c
--- a/src/test/njs_unit_test.c	Fri Jun 03 23:24:11 2022 -0700
+++ b/src/test/njs_unit_test.c	Fri Jun 03 23:24:12 2022 -0700
@@ -8438,6 +8438,11 @@ static njs_unit_test_t  njs_test[] =
     { njs_str("var r = 'αβγ'.replace('', 'X'); [r, r.length]"),
       njs_str("Xαβγ,4") },
 
+    { njs_str("var s = 'αz'.toUTF8();"
+              "var r = s.replace('z', 'β');"
+              "r.length"),
+      njs_str("4") },
+
     { njs_str("'abc'.replace('b', (m, o, s) => `|${s}|${o}|${m}|`)"),
       njs_str("a|abc|1|b|c") },
 


More information about the nginx-devel mailing list