Jeff Thompson | 768870c | 2012-12-29 21:56:41 -0800 | [diff] [blame] | 1 | /** |
| 2 | * @author: Jeff Thompson |
| 3 | * See COPYING for copyright and distribution information. |
| 4 | * Encapsulate an Uint8Array and support dynamic reallocation. |
| 5 | */ |
| 6 | |
Jeff Thompson | 2b14c7e | 2013-07-29 15:09:56 -0700 | [diff] [blame] | 7 | /** |
Jeff Thompson | 768870c | 2012-12-29 21:56:41 -0800 | [diff] [blame] | 8 | * Create a DynamicUint8Array where this.array is a Uint8Array of size length. |
Jeff Thompson | 768870c | 2012-12-29 21:56:41 -0800 | [diff] [blame] | 9 | * The methods will update this.length. |
| 10 | * To access the array, use this.array or call subarray. |
Jeff Thompson | 2b14c7e | 2013-07-29 15:09:56 -0700 | [diff] [blame] | 11 | * @constructor |
| 12 | * @param {number} length the initial length of the array. If null, use a default. |
Jeff Thompson | 768870c | 2012-12-29 21:56:41 -0800 | [diff] [blame] | 13 | */ |
| 14 | var DynamicUint8Array = function DynamicUint8Array(length) { |
| 15 | if (!length) |
| 16 | length = 16; |
| 17 | |
| 18 | this.array = new Uint8Array(length); |
| 19 | this.length = length; |
| 20 | }; |
| 21 | |
Jeff Thompson | 2b14c7e | 2013-07-29 15:09:56 -0700 | [diff] [blame] | 22 | /** |
Jeff Thompson | 768870c | 2012-12-29 21:56:41 -0800 | [diff] [blame] | 23 | * Ensure that this.array has the length, reallocate and copy if necessary. |
| 24 | * Update this.length which may be greater than length. |
| 25 | */ |
| 26 | DynamicUint8Array.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 Thompson | 2b14c7e | 2013-07-29 15:09:56 -0700 | [diff] [blame] | 42 | /** |
Jeff Thompson | 768870c | 2012-12-29 21:56:41 -0800 | [diff] [blame] | 43 | * Call this.array.set(value, offset), reallocating if necessary. |
| 44 | */ |
| 45 | DynamicUint8Array.prototype.set = function(value, offset) { |
| 46 | this.ensureLength(value.length + offset); |
| 47 | this.array.set(value, offset); |
| 48 | }; |
| 49 | |
Jeff Thompson | 2b14c7e | 2013-07-29 15:09:56 -0700 | [diff] [blame] | 50 | /** |
Jeff Thompson | 768870c | 2012-12-29 21:56:41 -0800 | [diff] [blame] | 51 | * Return this.array.subarray(begin, end); |
| 52 | */ |
| 53 | DynamicUint8Array.prototype.subarray = function(begin, end) { |
| 54 | return this.array.subarray(begin, end); |
Jeff Thompson | 2b14c7e | 2013-07-29 15:09:56 -0700 | [diff] [blame] | 55 | }; |