natevw/struct-fu

Add relative `_.padding` field type

Opened this issue · 1 comments

We have the absolute helper _.padTo that makes sure the struct is a certain length, but it'd be nice to also have a relative to use as a "spacer". Probably should support both bytes and bits, maybe something like: _.padding(bytes[, bits]) would do the trick.

See #4 (comment) for one case where this could come in handy.

Another similar field (or feature of this hypothetical field) might be able to automatically round to the nearest full byte, see issue #15.

The downside of this is it would mask struct incompatibility issues, e.g. one could go from

_.struct([
   _.bool("field1"), _.bool("field2"), _.bool("field3"), _.bool("field4"),
  _.bool("field5"), _.bool("field6"),
  _.padding(),
  _.uint32("number")
])

to

_.struct([
   _.bool("field1"), _.bool("field2"), _.bool("field3"), _.bool("field4"),
  _.bool("field5"), _.bool("field6"), _.bool("field7"),
  _.padding(),
  _.uint32("number")
])

relatively harmlessly, leaving the "number" field at its original offset within the binary form. But to go from

_.struct([
   _.bool("field1"), _.bool("field2"), _.bool("field3"), _.bool("field4"),
  _.bool("field5"), _.bool("field6"), _.bool("field7"),
  _.padding(),
  _.uint32("number")
])

to

_.struct([
   _.bool("field1"), _.bool("field2"), _.bool("field3"), _.bool("field4"),
  _.bool("field5"), _.bool("field6"), _.bool("field7"), _.bool("field8"),
  _.bool("field9"),
  _.padding(),
  _.uint32("number")
])

would end up pushing the following "number" field ahead a full byte. This circumstance is made a bit more apparent by my nibble-per-line code formatting but in practice could be far less obvious and potential cause someone a bad surprise.

I.e. this idea would be convenient, but would also remove much of the "what-you-see-is-what-you-get" (explicitness) that is currently designed into this library. So I suspect this enhancement would be better as part of any effort on #13 rather than in a core _.padding field, but something to consider here at least.