Search code examples
javascriptdataviewtyped-arrays

How to get size of a DataView type (eg. Uint32=4, Float64=8) to advance the offset?


I'm parsing a serialized object with a DataView and want to be able to increment an offset variable depending on data sizes. I'd rather not redefine variables for simple things like BYTES_PER_UINT16

...
var dv = new DataView(payload);
var offset = 0;
anObject.field1 = dv.getUint8(offset);
offset += BYTES_PER_UINT8;
anObject.field2 = dv.getUint32(offset, true);
offset += BYTES_PER_UINT32;
...

Solution

  • You need to wrap them in an object which does this for you.

    For example:

    function DataViewExt(o) {
        this.view = new DataView(o);
        this.pos = 0;
    }
    
    DataViewExt.prototype = {
        getUint8: function() {
            return this.view.getUint8(this.pos++);
        },
    
        getUint16: function() {
            var v = this.view.getUint16(this.pos);
            this.pos += 2;
            return v
        },
        // etc...
    };
    

    Now you can create an instance:

    var dv = new DataViewExt(payload);
    var uint8 = dv.getUint8();       // advances 1 byte
    var uint16 = dv.getUint16();     // advances 2 bytes
    ...
    console.log("Current position:", dv.pos);
    

    Modify to fit your scenario.