kig / DataStream.js

DataStream.js is a library for reading data from ArrayBuffers
173 stars 39 forks source link

variable-size arrays #1

Closed darrenderidder closed 11 years ago

darrenderidder commented 11 years ago

This is a great utility! I'd like to parse a series of variable-size items into an array using the readStruct method. The number of elements isn't known; only the total size of the segment containing the items is known. It should read as many items as possible without exceeding the segment size. Is this possible with the current DataStream.js implementation? Also, can you add licensing information? Thanks!

kig commented 11 years ago

You could do it by first reading the segment and then using readStruct to read in as many structs as possible (by passing '*' for array length).

var mySubStruct = a struct definition;

var myFancyStruct = [
  'dataLen', 'int32', // Read in the length of the segment.
  'dataArray', function(ds, st) {
    var dataBuf = ds.mapInt8Array(st.dataLen); // Read in the segment you want to process.
    var bufDS = new DataStream(dataBuf); // Create a new DataStream from the segment.
    // Read in as many sub-structs as you can and return the array.
    return bufDS.readType(['', mySubStruct, '*'], null); 
  },
  theRest, ['', 'int8', '*'] // Read in the rest of the buffer. 
};
darrenderidder commented 11 years ago

Thanks, that's exactly what I needed.