Appending to a dynamic array at specific offset
Derek Parnell
derek at psych.ward
Tue Jan 23 03:49:14 PST 2007
On Mon, 22 Jan 2007 22:34:51 -0600, Joseph Bell wrote:
> 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
Of course, 'append' does mean 'add to the end of something'. But what you
seem to be saying is that you wish to replace any existing data from offset
3 onwards with new data.
> 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.
Quite efficient and is probably the better way to do it due to its
simplicity.
> 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
You could do this I suppose ...
msg.length = data.length + 3;
msg[3..$] = data;
which might be faster if replacing a larger message with a smaller one as
the msg array will not get reallocated.
--
Derek Parnell
More information about the Digitalmars-d
mailing list