blob: 802b5c2c21542ddba7e14f73d803680bf60e8381 [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
Jeff Thompson2b14c7e2013-07-29 15:09:56 -07007/**
Jeff Thompson768870c2012-12-29 21:56:41 -08008 * Create a DynamicUint8Array where this.array is a Uint8Array of size length.
Jeff Thompson768870c2012-12-29 21:56:41 -08009 * The methods will update this.length.
10 * To access the array, use this.array or call subarray.
Jeff Thompson2b14c7e2013-07-29 15:09:56 -070011 * @constructor
12 * @param {number} length the initial length of the array. If null, use a default.
Jeff Thompson768870c2012-12-29 21:56:41 -080013 */
14var DynamicUint8Array = function DynamicUint8Array(length) {
15 if (!length)
16 length = 16;
17
18 this.array = new Uint8Array(length);
19 this.length = length;
20};
21
Jeff Thompson2b14c7e2013-07-29 15:09:56 -070022/**
Jeff Thompson768870c2012-12-29 21:56:41 -080023 * Ensure that this.array has the length, reallocate and copy if necessary.
24 * Update this.length which may be greater than length.
25 */
26DynamicUint8Array.prototype.ensureLength = function(length) {
27 if (this.array.length >= length)
28 return;
29
30 // See if double is enough.
31 var newLength = this.array.length * 2;
32 if (length > newLength)
33 // The needed length is much greater, so use it.
34 newLength = length;
35
36 var newArray = new Uint8Array(newLength);
37 newArray.set(this.array);
38 this.array = newArray;
39 this.length = newLength;
40};
41
Jeff Thompson2b14c7e2013-07-29 15:09:56 -070042/**
Jeff Thompson768870c2012-12-29 21:56:41 -080043 * Call this.array.set(value, offset), reallocating if necessary.
44 */
45DynamicUint8Array.prototype.set = function(value, offset) {
46 this.ensureLength(value.length + offset);
47 this.array.set(value, offset);
48};
49
Jeff Thompson2b14c7e2013-07-29 15:09:56 -070050/**
Jeff Thompson768870c2012-12-29 21:56:41 -080051 * Return this.array.subarray(begin, end);
52 */
53DynamicUint8Array.prototype.subarray = function(begin, end) {
54 return this.array.subarray(begin, end);
Jeff Thompson2b14c7e2013-07-29 15:09:56 -070055};