@@ -2,16 +2,20 @@ import 'dart:typed_data';
22
33/// A utility class that manages a growing byte buffer.
44/// It dynamically increases its capacity in factors of 2 when needed.
5- class GrowingByteBuffer {
5+ class DynamicBuffer {
66 Uint8List _buffer;
77 int _capacity;
88 int _length = 0 ;
99
10- /// Creates a [GrowingByteBuffer ] with an optional initial capacity.
10+ /// Creates a [DynamicBuffer ] with an optional initial capacity.
1111 /// The default initial capacity is 1024 bytes.
12- GrowingByteBuffer ([int initialCapacity = 1024 ])
12+ DynamicBuffer ([int initialCapacity = 1024 ])
1313 : _capacity = initialCapacity,
14- _buffer = Uint8List (initialCapacity);
14+ _buffer = Uint8List (initialCapacity) {
15+ if (initialCapacity < 1 ) {
16+ throw ArgumentError ("initialCapacity must be positive" );
17+ }
18+ }
1519
1620 /// Adds [data] to the buffer, expanding its capacity if necessary.
1721 void add (Uint8List data) {
@@ -26,7 +30,7 @@ class GrowingByteBuffer {
2630 if (offset < 0 ) {
2731 throw ArgumentError ("Offset must be non-negative" );
2832 }
29- int endPosition = offset + data.length;
33+ final endPosition = offset + data.length;
3034 _ensureCapacity (endPosition);
3135 _buffer.setRange (offset, endPosition, data);
3236 if (endPosition > _length) {
@@ -35,6 +39,9 @@ class GrowingByteBuffer {
3539 }
3640
3741 /// Truncates the buffer to a specific [newSize] .
42+ ///
43+ /// No memory is freed when using [truncate] .
44+ ///
3845 /// If [newSize] is less than the current length, the buffer is truncated.
3946 /// If [newSize] is greater than the current length, the buffer length is extended with zeros.
4047 void truncate (int newSize) {
@@ -49,7 +56,7 @@ class GrowingByteBuffer {
4956 _length = newSize;
5057 }
5158
52- /// Returns a [Uint8List] containing the data up to the current length.
59+ /// Returns a [Uint8List] view containing the data up to the current length.
5360 Uint8List toUint8List () {
5461 return Uint8List .view (_buffer.buffer, 0 , _length);
5562 }
@@ -63,7 +70,6 @@ class GrowingByteBuffer {
6370 newCapacity *= 2 ;
6471 }
6572 // Allocate a new buffer and copy existing data.
66- print ('resizing to $newCapacity ' );
6773 Uint8List newBuffer = Uint8List (newCapacity);
6874 newBuffer.setRange (0 , _length, _buffer);
6975 _buffer = newBuffer;
0 commit comments