Debian Codegraph @

rhino/src/org/mozilla/javascript/ConsString.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 package org.mozilla.javascript;
8
9 import java.io.Serializable;
10 import java.util.ArrayList;
11
12 /**
13 * <p>This class represents a string composed of two components, each of which
14 * may be a <code>java.lang.String</code> or another ConsString.</p>
15 *
16 * <p>This string representation is optimized for concatenation using the "+"
17 * operator. Instead of immediately copying both components to a new character
18 * array, ConsString keeps references to the original components and only
19 * converts them to a String if either toString() is called or a certain depth
20 * level is reached.</p>
21 *
22 * <p>Note that instances of this class are only immutable if both parts are
23 * immutable, i.e. either Strings or ConsStrings that are ultimately composed
24 * of Strings.</p>
25 *
26 * <p>Both the name and the concept are borrowed from V8.</p>
27 */
28 public class ConsString implements CharSequence, Serializable {
29
30 private static final long serialVersionUID = -8432806714471372570L;
31
32 private CharSequence s1, s2;
33 private final int length;
34 private int depth;
35
36 public ConsString(CharSequence str1, CharSequence str2) {
37 s1 = str1;
38 s2 = str2;
39 length = str1.length() + str2.length();
40 depth = 1;
41 if (str1 instanceof ConsString) {
42 depth += ((ConsString)str1).depth;
43 }
44 if (str2 instanceof ConsString) {
45 depth += ((ConsString)str2).depth;
46 }
47 }
48
49 // Replace with string representation when serializing
50 private Object writeReplace() {
51 return this.toString();
52 }
53
54 @Override
55 public String toString() {
56 return depth == 0 ? (String)s1 : flatten();
57 }
58
59 private synchronized String flatten() {
60 if (depth > 0) {
61 StringBuilder b = new StringBuilder(length);
62 ArrayList<CharSequence> buffer = new ArrayList<CharSequence>();
63 buffer.add(s2);
64 buffer.add(s1);
65 while(!buffer.isEmpty()) {
66 CharSequence next = buffer.remove(buffer.size() - 1);
67 if (next instanceof ConsString) {
68 ConsString casted = (ConsString) next;
69 buffer.add(casted.s2);
70 buffer.add(casted.s1);
71 } else {
72 b.append(next);
73 }
74 }
75 s1 = b.toString();
76 s2 = "";
77 depth = 0;
78 }
79 return (String)s1;
80 }
81
82 public int length() {
83 return length;
84 }
85
86 public char charAt(int index) {
87 String str = depth == 0 ? (String)s1 : flatten();
88 return str.charAt(index);
89 }
90
91 public CharSequence subSequence(int start, int end) {
92 String str = depth == 0 ? (String)s1 : flatten();
93 return str.substring(start, end);
94 }
95
96 }