OLD | NEW |
| (Empty) |
1 // Copyright (c) 2012, 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 part of dart.io; | |
6 | |
7 /** | |
8 * Utility class that can fast concatenate [List<int>]s of bytes. Use | |
9 * [readBytes] to get the final buffer. | |
10 */ | |
11 class _BufferList { | |
12 static const int _INIT_SIZE = 1 * 1024; | |
13 | |
14 _BufferList() { | |
15 clear(); | |
16 } | |
17 | |
18 int pow2roundup(int x) { | |
19 --x; | |
20 x |= x >> 1; | |
21 x |= x >> 2; | |
22 x |= x >> 4; | |
23 x |= x >> 8; | |
24 x |= x >> 16; | |
25 return x + 1; | |
26 } | |
27 | |
28 /** | |
29 * Adds a new buffer to the list. | |
30 */ | |
31 void add(List<int> buffer) { | |
32 int bufferLength = buffer.length; | |
33 int required = _length + bufferLength; | |
34 if (_buffer == null) { | |
35 int size = pow2roundup(required); | |
36 if (size < _INIT_SIZE) size = _INIT_SIZE; | |
37 _buffer = new Uint8List(size); | |
38 } else if (_buffer.length < required) { | |
39 // This will give is a list in the range of 2-4 times larger than | |
40 // required. | |
41 int size = pow2roundup(required) * 2; | |
42 Uint8List newBuffer = new Uint8List(size); | |
43 newBuffer.setRange(0, _buffer.length, _buffer); | |
44 _buffer = newBuffer; | |
45 } | |
46 assert(_buffer.length >= required); | |
47 if (buffer is Uint8List) { | |
48 _buffer.setRange(_length, required, buffer); | |
49 } else { | |
50 for (int i = 0; i < bufferLength; i++) { | |
51 _buffer[_length + i] = buffer[i]; | |
52 } | |
53 } | |
54 _length = required; | |
55 } | |
56 | |
57 /** | |
58 * Same as [add]. | |
59 */ | |
60 void write(List<int> buffer) { | |
61 add(buffer); | |
62 } | |
63 | |
64 /** | |
65 * Read all the bytes from the buffer list. If it's empty, an empty list | |
66 * is returned. A call to [readBytes] will clear the buffer. | |
67 */ | |
68 List<int> readBytes() { | |
69 if (_buffer == null) return new Uint8List(0); | |
70 var buffer = new Uint8List.view(_buffer.buffer, 0, _length); | |
71 clear(); | |
72 return buffer; | |
73 } | |
74 | |
75 /** | |
76 * Returns the total number of bytes in the buffer. | |
77 */ | |
78 int get length => _length; | |
79 | |
80 /** | |
81 * Returns whether the buffer list is empty. | |
82 */ | |
83 bool get isEmpty => _length == 0; | |
84 | |
85 /** | |
86 * Returns whether the buffer list is not empty. | |
87 */ | |
88 bool get isNotEmpty => !isEmpty; | |
89 | |
90 /** | |
91 * Clears the content of the buffer list. | |
92 */ | |
93 void clear() { | |
94 _length = 0; | |
95 _buffer = null; | |
96 } | |
97 | |
98 int _length; // Total number of bytes in the buffer. | |
99 Uint8List _buffer; // Internal buffer. | |
100 } | |
OLD | NEW |