Skip to content

Commit

Permalink
Fix ClassCastException when using StringBuilder/Buffer mozilla#496 (m…
Browse files Browse the repository at this point in the history
…ozilla#1210)

Convert non-String, non-ConsString objects to a string when creating a ConsString so that StringBuilders and other CharSequence objects can be used natively more easily.

Fixes mozilla#1206 and mozilla#496

Co-authored-by: Edward Jensen <[email protected]>
  • Loading branch information
2 people authored and jcompagner committed Aug 10, 2023
1 parent a7d4e3b commit e5009c3
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/org/mozilla/javascript/ConsString.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ public class ConsString implements CharSequence, Serializable, Wrapper {
private boolean isFlat;

public ConsString(CharSequence str1, CharSequence str2) {
if (!(str1 instanceof String) && !(str1 instanceof ConsString)) {
str1 = str1.toString();
}
if (!(str2 instanceof String) && !(str2 instanceof ConsString)) {
str2 = str2.toString();
}
left = str1;
right = str2;
length = left.length() + right.length();
Expand Down
42 changes: 42 additions & 0 deletions testsrc/org/mozilla/javascript/tests/Issue1206Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.mozilla.javascript.tests;

import junit.framework.TestCase;
import org.junit.Test;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;

/**
* Tests the ConsString class to ensure it properly supports String, StringBuffer and StringBuilder.
*/
public class Issue1206Test extends TestCase {
@Test
public void testConsStringUsingString() {
Context cx = Context.enter();
Scriptable scope = cx.initStandardObjects(null);
scope.put("var1", scope, "hello");
Object result = cx.evaluateString(scope, "var1 = var1 + ' world'", "test", 1, null);
assertEquals("hello world", result);
}

@Test
public void testConsStringUsingStringBuffer() {
Context cx = Context.enter();
Scriptable scope = cx.initStandardObjects(null);
scope.put("var1", scope, new StringBuffer("hello"));
Object result = cx.evaluateString(scope, "var1 = var1 + ' world'", "test", 1, null);
assertEquals("hello world", result);
}

@Test
public void testConsStringUsingStringBuilder() {
Context cx = Context.enter();
Scriptable scope = cx.initStandardObjects(null);
scope.put("var1", scope, new StringBuilder("hello"));
Object result = cx.evaluateString(scope, "var1 = var1 + ' world'", "test", 1, null);
assertEquals("hello world", result);
}
}

0 comments on commit e5009c3

Please sign in to comment.