natevw/struct-fu

Add standalone/explicit `_.array` field type?

Opened this issue · 1 comments

The current API here is intended to mimic the ease of C-style structures: uint32_t field[5] maps ± directly to _.uint32('field', 5) which is nice.

However, this breaks some symmetry with the _.struct type and also makes it harder to create a custom type since the arrayizeField helper remains internal. Perhaps exposing an _.array([name,] field, count) field would be useful?

Because of _hoistFields you can sometimes accomplish this:

var coordStruct = _.struct([
  _.uint16le("x"),
  _.uint16le("y")
]);
var coordPair = _.struct([coordStruct], 2);

This might only work because the coordStruct is a struct itself (and anonymous). If it were just a standardField it's unclear to me what behavior would result.

UPDATE: I tried it. With _.struct("top", [subfield], 2) you always get an array of objects which makes sense because its the "top" struct that is repeated and a struct always results in an object. What the object contains varies:

  • subfield = _.struct([_.uint16le("x"),_.uint16le("y")]) — array of [{x:…,y:…}, {x:…,y:…}] due to hoisting
  • subfield = _.uint32le("xy") — array of [{xy:…}, {xy:…}] which is just normal behavior
  • subfield = _.uint32le() — array of [{}, {}] which is sort of an edge case, but also expected

An _.array field would potentially be useful, although…how would it differ from uint32le("xy", 2)? I'm having trouble remembering the exact use case here.