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 for (Object obj in objects) { | |
46 add(obj); | |
47 } | |
48 return this; | |
49 } | |
50 | |
51 /** | |
52 * Adds the string representation of [charCode] to the buffer. | |
53 * Returns [this]. | |
54 */ | |
55 StringBuffer addCharCode(int charCode) { | |
56 return add(new String.fromCharCodes([charCode])); | |
57 } | |
58 | |
59 /** | |
60 * Clears the string buffer. Returns [this]. | |
61 */ | |
62 StringBuffer clear() { | |
63 _buffer = new List<String>(); | |
64 _length = 0; | |
65 return this; | |
66 } | |
67 | |
68 /** | |
69 * Returns the contents of buffer as a concatenated string. | |
70 */ | |
71 String toString() { | |
72 if (_buffer.length == 0) return ""; | |
73 if (_buffer.length == 1) return _buffer[0]; | |
74 String result = StringBase.concatAll(_buffer); | |
75 _buffer.clear(); | |
76 _buffer.add(result); | |
77 // Since we track the length at each add operation, there is no | |
78 // need to update it in this function. | |
79 return result; | |
80 } | |
81 | |
82 List<String> _buffer; | |
83 int _length; | |
84 } | |
OLD | NEW |