From d84d9cbe2e1d60c85ba7c6f01b2c1eaf5b0e6e7c Mon Sep 17 00:00:00 2001 From: Tyler Morten Date: Tue, 19 May 2020 02:44:20 -0500 Subject: [PATCH] Fix for 0 length new String (#404) * Fix for 0 length field when constructing a new String. * String.length uses character count not byte count. Also, corresponding test * Made tests more succinct per suggestion. --- boa/src/builtins/string/mod.rs | 15 +++++++++------ boa/src/builtins/string/tests.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/boa/src/builtins/string/mod.rs b/boa/src/builtins/string/mod.rs index 67109cc48a1..d332f852f6f 100644 --- a/boa/src/builtins/string/mod.rs +++ b/boa/src/builtins/string/mod.rs @@ -35,13 +35,16 @@ use std::{ pub fn make_string(this: &mut Value, args: &[Value], _: &mut Interpreter) -> ResultValue { // This value is used by console.log and other routines to match Obexpecty"failed to parse argument for String method"pe // to its Javascript Identifier (global constructor method name) + let s = args + .get(0) + .expect("failed to get StringData for make_string()") + .clone(); + let length_str = s.to_string().chars().count(); + + this.set_field_slice("length", Value::from(length_str as i32)); + this.set_kind(ObjectKind::String); - this.set_internal_slot( - "StringData", - args.get(0) - .expect("failed to get StringData for make_string()") - .clone(), - ); + this.set_internal_slot("StringData", s); let arg = match args.get(0) { Some(v) => v.clone(), diff --git a/boa/src/builtins/string/tests.rs b/boa/src/builtins/string/tests.rs index e5f8d21fbe0..52bdba3efad 100644 --- a/boa/src/builtins/string/tests.rs +++ b/boa/src/builtins/string/tests.rs @@ -36,6 +36,32 @@ fn check_string_constructor_is_function() { // assert_eq!(d, String::from("4")); // } +#[test] +fn new_string_has_length() { + let realm = Realm::create(); + let mut engine = Executor::new(realm); + let init = r#" + let a = new String("1234"); + a + "#; + + forward(&mut engine, init); + assert_eq!(forward(&mut engine, "a.length"), "4"); +} + +#[test] +fn new_utf8_string_has_length() { + let realm = Realm::create(); + let mut engine = Executor::new(realm); + let init = r#" + let a = new String("中文"); + a + "#; + + forward(&mut engine, init); + assert_eq!(forward(&mut engine, "a.length"), "2"); +} + #[test] fn concat() { let realm = Realm::create();