getting zero length range from end of buffer
I'm writing a custom dissector for a home-grown protocol. Strings in the protocol are encoded as a binary 4-byte byte-count followed by the bytes of the string. Zero length strings are allowable. The problem occurs when a zero length string is the very last object in the buffer.
I have a function getString():
function getString(buffer, position)
local length = buffer:range(position, 4):uint()
position = position + 4
local string = buffer:range(position, length)
position = position + length
return position, string
end
If I call that with a buffer (in hex):
00 00 00 03 41 42 43 00 00 00 00
I correctly get the string "ABC" in the TvbRange that's returned, and position is correctly returned as 7.
If I call it with a buffer:
00 00 00 00 00 00 00 00
I correctly get an empty TvbRange returned, and position is correctly returned as 4.
But, if I call it with a buffer:
00 00 00 00
I get a runtime error "Range is out of bounds".
Is there some way to get range() to correctly return an empty range in this case? Can I test for the condition (e.g. length == 0 and position == buffer:len()) and return a "fake" TvbRange.
Currently, I'm returning string as nil. But that means that I have to test for nil everywhere that getString() is called - that's inconvenient.
Thanks for any help, Graham
Why not return the range that was passed in and set
position
=nil
or-1
to indicate no more buffer to process?Something like so?
Thanks for responding Chuckc and cmaynard.
Yes, I can do that. But, as I said, it's not very convenient. I'd like to be able to do:
But, if I need to check for str being nil every time, it's not as simple.
Now that I think about it, is this really a Lua bug? Should I not be able to get a zero length TvbRange from the end of a Tvb. In other words, perhaps buffer:range(buffer:len(), 0) should not generate an error.
Thanks again, Graham.
My current workaround is:
It's not correct, but it's close enough.