Skip to content

Commit

Permalink
Fix for 0 length new String (#404)
Browse files Browse the repository at this point in the history
* 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.
  • Loading branch information
Tyler Morten committed May 19, 2020
1 parent 63f37a2 commit d84d9cb
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
15 changes: 9 additions & 6 deletions boa/src/builtins/string/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
26 changes: 26 additions & 0 deletions boa/src/builtins/string/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down

0 comments on commit d84d9cb

Please sign in to comment.