Optional fields + C strings
timkurvers opened this issue · 11 comments
Is there a way to optionally exclude fields depending on other values?
Record = new r.Struct({
name: new r.String(),
flags: r.uint32,
age: r.uint8, // optional if flags & 0x50
friends: new r.Array(..)
})
Does restructure have support for NULL-terminated C strings?
No, but both of those things would be interesting PRs that I would merge.
For the optional fields part, you could implement it like this:
Record = new r.Struct({
name: new r.String(),
flags: r.uint32,
age: new Optional(r.uint8, function() { !(this.flags & 0x50) }),
friends: new r.Array(..)
})
You would make an Optional class that took a type and a function. In the decode
method, you would run the function which would return a boolean. If true, decode the type, otherwise return null. In the encode
method, if the value is null, don't encode, otherwise encoding using the type. You can find more docs about implementing custom types here, and check out the source for some of the builtin types as well.
Ah, fantastic, will give that a shot!
The String
class as it is supports fixed/computed lengths and Pascal-style encoded strings.
I'm leaning towards adding a new type CString
for NULL-terminated strings, would that be preferred?
Hmm, I'd rather there just be one string class. There will just need to be a special case for decoding instead of using utils.resolveLength. For encoding, just add a null byte after the string.
Question though: should this only work for ascii or utf-8 or is it also needed for double byte encodings? If it is, the null terminator will need to be 2 bytes as well.
Sounds great! How would you prefer to signify that the string is a C-string? Explicitly set the length parameter to null? Or perhaps omitting the length altogether?
As for double byte encoding, very good question. I'm thinking the actual encoded characters are separate from the length indicator/terminator, so there would only be one NULL-byte signifying the end of the string.
As outlined here, attempting to encode/decode the NULL-byte itself or use certain encodings (such as utf-16) will not work appropriately, but that would be up to developers themselves to decide.
Sure, I'd say null or undefined, or not provided (which is the same). I'd use CoffeeScript's existential operator, e.g. if not length?
. A single null byte sounds fine to me.
Yay, thanks very much for the assistance :)
Published to npm in v0.1.8.
Is it possible the compiled JavaScript files are missing from this release?
Crap, yes. I forgot I had to use make publish
instead of npm publish
directly (I need to change that). Try v0.1.9.
Fantastic, works now! Thanks.