title: Creating a (good) struct from a javascript typed array?
body: <p>I'm thinking about typed arrays in javascript; in particular, reading binary file headers. Reading the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays" rel="nofollow">MDN Typed Arrays documentation</a>, they blithely say we can represent the C struct:</p>
  
  <pre><code>struct someStruct {
    unsigned long id;
    char username[16];
    float amountDue;
  };
  </code></pre>
  
  <p>with the javascript:</p>
  
  <pre><code>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);
  </code></pre>
  
  <p>and then you can say <code>amountDueView[0]</code> but seem oblivious to the fact that treating a scalar as a one-element array is terrible and being able to say something like <code>sizeof(someStruct)</code> is useful as well.</p>
  
  <p>So... is there something better? MDN makes reference to <a href="https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes" rel="nofollow">js-ctypes</a> but it's no standard javascript.</p>
  
  <p>Edit: Yes, I know about javascript objects. Modeling the data isn't the problem; reading and writing binary data elegantly is.</p>