javascripttyped-arrays

Creating a (good) struct from a javascript typed array?


I'm thinking about typed arrays in javascript; in particular, reading binary file headers. Reading the MDN Typed Arrays documentation, they blithely say we can represent the C struct:

struct someStruct {
  unsigned long id;
  char username[16];
  float amountDue;
};

with the javascript:

var buffer = new ArrayBuffer(24);

// ... read the data into the buffer ...

var idView = new Uint32Array(buffer, 0, 1);
var usernameView = new Uint8Array(buffer, 4, 16);
var amountDueView = new Float32Array(buffer, 20, 1);

and then you can say amountDueView[0] but seem oblivious to the fact that treating a scalar as a one-element array is terrible and being able to say something like sizeof(someStruct) is useful as well.

So... is there something better? MDN makes reference to js-ctypes but it's no standard javascript.

Edit: Yes, I know about javascript objects. Modeling the data isn't the problem; reading and writing binary data elegantly is.


Solution

  • For what it's worth, there's jBinary, which lets you do stuff like:

    var binary_data = '\x0f\x00\x00\x00Bruce\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xecQXA';
    
    var myTypeset = {
        'jBinary.all': 'someStruct',
        'jBinary.littleEndian': true,
        someStruct: {
            id: 'uint32',
            username: ['string0', 16],
            amountDue: 'float'
        }
    };
    
    var binary = new jBinary(binary_data, myTypeset);
    header = binary.readAll(); // Object {id: 15, username: "Bruce", amountDue: 13.520000457763672}
    
    header.username = "Jim";
    binary.writeAll(header);
    binary.readAll(); // Object {id: 15, username: "Jim", amountDue: 13.520000457763672}
    

    It's not particularly well-documented (an example like the above would be very welcome) but it's quite good.

    The biggest caveat is that it relies on javascript objects having properties remain in the order they're defined, which is practically the case but not part of the javascript spec. I suspect this will never actually change because it would break a kajillion things, but still.