natevw/struct-fu

Char and null termination

Closed this issue · 1 comments

var login = _.struct([
    _.char('msg', 99),
    _.char('from', 30)
])

var buf = new Buffer('45454500454545', 'hex')

var obj1 = login.valueFromBytes(buf)

console.log(obj1)

Why does it return msg: 'EEE', from: ''? Shouldn't it return msg: 'EE', from: 'EE'?

There are no dynamic-width fields in struct-fu, and invalid input detection is pretty minimal (at least for now). You have declared a structure that will always be the same length, login.size === 99+30, whether reading or writing.

What happens is that when reading a char field, it reads only to the first \0 and then assumes the rest is padding. So that explains why msg only reads the three characters "EEE", as they are nul-terminated.

Why from is an empty string instead of throwing an exception is because struct-fu basically just relies on node.js buffer routines to assert as they please, rather than explicitly checking the remaining field size. A little more aggressive assertions would probably help flag usage errors a little more quickly, so I'll add an issue for that.

Since this is behaving ± as expected (except for better error detection) I'll mark this as closed, but happy to help if you have any followup questions just let me know.