Iterating through an arrayBuffer

suggest change

For a convenient way to iterate through an arrayBuffer, you can create a simple iterator that implements the DataView methods under the hood:

var ArrayBufferCursor = (function() {
  var ArrayBufferCursor = function(arrayBuffer) {
    this.dataview = new DataView(arrayBuffer, 0);
    this.size = arrayBuffer.byteLength;
    this.index = 0;
  }

  ArrayBufferCursor.prototype.next = function(type) {
    switch(type) {
      case 'Uint8':
        var result = this.dataview.getUint8(this.index);
        this.index += 1;
        return result;
      case 'Int16':
        var result = this.dataview.getInt16(this.index, true);
        this.index += 2;
        return result;
      case 'Uint16':
        var result = this.dataview.getUint16(this.index, true);
        this.index += 2;
        return result;
      case 'Int32':
        var result = this.dataview.getInt32(this.index, true);
        this.index += 4;
        return result;
      case 'Uint32':
        var result = this.dataview.getUint32(this.index, true);
        this.index += 4;
        return result;
      case 'Float':
      case 'Float32':
        var result = this.dataview.getFloat32(this.index, true);
        this.index += 4;
        return result;
      case 'Double':
      case 'Float64':
        var result = this.dataview.getFloat64(this.index, true);
        this.index += 8;
        return result;
      default:
        throw new Error("Unknown datatype");
    }
  };

  ArrayBufferCursor.prototype.hasNext = function() {
    return this.index < this.size;
  }

  return ArrayBufferCursor;
})();

You can then create an iterator like this:

const cursor = new ArrayBufferCursor(arrayBuffer);

The true argument to the DataView reads is little-endian. hasNext only checks that the index is still inside the buffer. A multi-byte next can still read past the end. Use hasNext to check whether any bytes remain:

for (;cursor.hasNext();) {
    // There's still items to process
}

You can use the next method to take the next value:

const nextValue = cursor.next('Float');

With such an iterator, writing your own parser to process binary data becomes pretty easy.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents