OLD | NEW |
| (Empty) |
1 // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file | |
2 // for details. All rights reserved. Use of this source code is governed by a | |
3 // BSD-style license that can be found in the LICENSE file. | |
4 | |
5 /** | |
6 * The StringBuffer class is useful for concatenating strings | |
7 * efficiently. Only on a call to [toString] are the strings | |
8 * concatenated to a single String. | |
9 */ | |
10 class StringBufferImpl implements StringBuffer { | |
11 /** | |
12 * Creates the string buffer with an initial content. | |
13 */ | |
14 StringBufferImpl([Object content = ""]) { | |
15 clear(); | |
16 add(content); | |
17 } | |
18 | |
19 /** | |
20 * Returns the length of the buffer. | |
21 */ | |
22 int get length() { | |
23 return _length; | |
24 } | |
25 | |
26 bool isEmpty() { | |
27 return _length == 0; | |
28 } | |
29 | |
30 /** | |
31 * Adds [obj] to the buffer. Returns [this]. | |
32 */ | |
33 StringBuffer add(Object obj) { | |
34 String str = obj.toString(); | |
35 if (str === null || str.isEmpty()) return this; | |
36 _buffer.add(str); | |
37 _length += str.length; | |
38 return this; | |
39 } | |
40 | |
41 /** | |
42 * Adds all items in [objects] to the buffer. Returns [this]. | |
43 */ | |
44 StringBuffer addAll(Collection<Object> objects) { | |
45 if (objects == null) { | |
46 throw const NullPointerException(); | |
47 } | |
48 for (Object obj in objects) { | |
49 add(obj); | |
50 } | |
51 return this; | |
52 } | |
53 | |
54 /** | |
55 * Adds the string representation of [charCode] to the buffer. | |
56 * Returns [this]. | |
57 */ | |
58 StringBuffer addCharCode(int charCode) { | |
59 return add(new String.fromCharCodes([charCode])); | |
60 } | |
61 | |
62 /** | |
63 * Clears the string buffer. Returns [this]. | |
64 */ | |
65 StringBuffer clear() { | |
66 _buffer = new List<String>(); | |
67 _length = 0; | |
68 return this; | |
69 } | |
70 | |
71 /** | |
72 * Returns the contents of buffer as a concatenated string. | |
73 */ | |
74 String toString() { | |
75 if (_buffer.length == 0) return ""; | |
76 if (_buffer.length == 1) return _buffer[0]; | |
77 String result = StringBase.concatAll(_buffer); | |
78 _buffer.clear(); | |
79 _buffer.add(result); | |
80 // Since we track the length at each add operation, there is no | |
81 // need to update it in this function. | |
82 return result; | |
83 } | |
84 | |
85 List<String> _buffer; | |
86 int _length; | |
87 } | |
OLD | NEW |