Appending to a dynamic array at specific offset
Joseph Bell
josephabell at tx.rr.com
Mon Jan 22 20:34:51 PST 2007
Hi.
I'm working with D arrays, getting my bearings, and was looking at
treating a ubtye array as a formatted message of sorts.
Consider the first byte is always a message type header.
The second and third bytes are a length indicator.
The fourth and subsequent bytes are the actual data this message conveys.
If I declare a dynamic array:
ubyte[] msg;
I can easily write
msg ~= TYPE; // TYPE is a ubyte value
msg ~= LEN_HI; // upper byte of 16-bit length
msg ~= LEN_LOW; // lower byte of 16-bit length
At this point I can
msg ~= data; // where data is a ubyte[]
But if I want to change the data, I'd like to be able to just append the
new data at the offset it needs to go at.
msg[3] ~= data; // doesn't work, msg[3] is a ubyte, can't append ubyte[]
&msg[3] ~= data; // Doesn't work, perhaps trying to write C there
This does work
msg.length = 3;
msg ~= data; // Effectively resize the array back to 3 and then append
I don't know how ineffecient the above approach is.
Also the following doesn't work:
msg[3..$] = data; // Array sizes don't match for copy
msg[3..$] ~= data; // Slice is not a modifiable lvalue
So the upshot: I have a working solution to the problem, but it looks
unnatural to me. Am I missing a magic syntactical expression for this?
Thanks much for any replies,
Joe
Budding D Zealot trying to kick C/C++ to the curb
More information about the Digitalmars-d
mailing list