kutsurak / python-bitstring

Automatically exported from code.google.com/p/python-bitstring
0 stars 0 forks source link

More powerful append method #139

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
Right now, the only way to append something to a BitArray seems to be to pass 
another bitstring, or something following the "auto" conventions to the append 
method. However, I find myself wanting to add a integer into a specified number 
of bits as well, so I end up doing:

    data.append(Bits(uint=foo, length=4))

or

    data.append(pack('uint:4', foo))

In both cases, I'm first creating an intermediate Bits object, and then append 
it to the original BitArray.

Wouldn't it make sense to have a shortcut method here? For example, have the 
append method take the same keyword arguments as the Bits constructor, so you 
can just write:

    data.append(uint=foo, length=4)

This would be especially useful combined with my other request, #138.

Alternatively (or in addition) perhaps something like "append_pack" might be 
useful?

    data.append_pack('uint:4', foo)

Original issue reported on code.google.com by matthijskooijman@gmail.com on 7 Nov 2013 at 3:51

GoogleCodeExporter commented 9 years ago
The append method is the same as the += operator for BitArrays, which is quite 
standard and would be broken by your change. It's not really much extra work to 
type Bits(), and if you find that you're doing it a lot then it would probably 
be worth taking a look at improving the way you construct the BitArray.

Just something along the lines of

Bits().join([Bits(uint=x, length=y) for x, y in [int_array, length_array]])

might be helpful?

Original comment by dr.scott...@gmail.com on 7 Nov 2013 at 4:09

GoogleCodeExporter commented 9 years ago
I think my proposed change would be a superset of the current interface: if 
called with a single positional parameter, it would still behave as before 
(just like you can call Bits('0x12') as well as Bits(uint=0x12, length=8)). 
However, I might be missing some subtlety about how += works...

As for your other suggestion, I don't have a uniform datastructure but 
something with uneven header fields (e.g., similar to the IPv4 packet header).

I realize that I could use something like

   pack('uint:8, uint:4, uint:3, uint:5', foo, bar, 0, baz)

However, that makes it harder to see the relation between the value and the 
corresponding size, which seems less elegant and more error-prone to me.

Furthermore, it's not just that I'm too lazy to type Bits (I am, but I have 
yank-paste for that), it's also that it seems wrong to create a new Bits 
object, just to have it appended and then destroyed again. Also, it clutters my 
code a bit, making it less clear to see what is happening.

Original comment by matthijskooijman@gmail.com on 7 Nov 2013 at 4:17