Greg Chambers wrote:
> I've been using BitStruct and it works like a dream except in one area, 
> which is with strings.  My first test class I am making keeps it easy by 
> putting it at the end of the packet so I can just use a rest field.  And 
> although the output returned by description looks fine, when I convert 
> to a String for sending, the string is added on as is instead of 
> converted like all the other data.  Here was the test code I wrote:
...
> "\000\000\000\030\000\000\002\003Testing 01 10 11"
> 
> This output is fine until it gets to the string.  I just worry, like I 
> did above, because the program receiving this needs to see the string as 
> a null terminated *char string... did I say that right?  Don't know 
> enough C for this.

I see your point. You can of course add the null manually:

test_packet.text_msg = "Testing 01 10 11\0"

but that's kinda defeating the purpose of bit-struct.

Another thing you can do is define reader/writer methods that 
strip/append the null. Rename the field to _text_msg and define:

   def text_msg; _text_msg[/(.*)\0\z/, 1]; end
   def text_msg=(s); self._text_msg = "#{s}\0"; end

It would be easy to add this to bit-struct, I'm just not sure what the 
api should be. Maybe an option like

   rest :text_str, :terminator => "\0"

Thoughts?

> Anyways, that was my first question.  The second question is how would I 
> go about converting a binary string I received into a BitStruct when 
> there is a variable length, null terminated string in the center of the 
> binary string?  Figured I would ask since using a rest field won't work 
> here.

Is the field fixed length, even if the string itself is variable length? 
If so, you can use a #text field, which pads with null chars:

require 'bit-struct'

class Msg < BitStruct
   unsigned :x, 16
   text :str, 10*8
   unsigned :y, 16
end

m = Msg.new(:x => 1, :str => "foo", :y => 2)
p m
p m.to_s

__END__

#<Msg x=1, str="foo", y=2>
"\000\001foo\000\000\000\000\000\000\000\000\002"

-- 
       vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407