blob: 5bf008035a370996c0cde6dbfae52a482730ff37 [file] [log] [blame]
Jeff Thompson768870c2012-12-29 21:56:41 -08001/**
2 * @author: Jeff Thompson
3 * See COPYING for copyright and distribution information.
4 * Encapsulate an Uint8Array and support dynamic reallocation.
5 */
6
7/*
8 * Create a DynamicUint8Array where this.array is a Uint8Array of size length.
9 * If length is not supplied, use a default initial length.
10 * The methods will update this.length.
11 * To access the array, use this.array or call subarray.
12 */
13var DynamicUint8Array = function DynamicUint8Array(length) {
14 if (!length)
15 length = 16;
16
17 this.array = new Uint8Array(length);
18 this.length = length;
19};
20
21/*
22 * Ensure that this.array has the length, reallocate and copy if necessary.
23 * Update this.length which may be greater than length.
24 */
25DynamicUint8Array.prototype.ensureLength = function(length) {
26 if (this.array.length >= length)
27 return;
28
29 // See if double is enough.
30 var newLength = this.array.length * 2;
31 if (length > newLength)
32 // The needed length is much greater, so use it.
33 newLength = length;
34
35 var newArray = new Uint8Array(newLength);
36 newArray.set(this.array);
37 this.array = newArray;
38 this.length = newLength;
39};
40
41/*
42 * Call this.array.set(value, offset), reallocating if necessary.
43 */
44DynamicUint8Array.prototype.set = function(value, offset) {
45 this.ensureLength(value.length + offset);
46 this.array.set(value, offset);
47};
48
49/*
50 * Return this.array.subarray(begin, end);
51 */
52DynamicUint8Array.prototype.subarray = function(begin, end) {
53 return this.array.subarray(begin, end);
54}