www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Single-Allocation Variable-Sized Array

reply =?UTF-8?B?Tm9yZGzDtnc=?= <per.nordlow gmail.com> writes:
What's the preferred way in D to implement single-allocation 
variable-sized arrays such as

/** Single-Allocation Array. */
struct ArrayN
{
     ubyte length;  // <= maxLength
     size room;     // allocated length
     ubyte[0] data; // `room` number of bytes follows
}

where insertion/deletion typically is done via

     ArrayN* pushBack(ArrayN*, ubyte element);
     ArrayN* popBack(ArrayN*);

which, when needed, will reallocate a new larger/smaller `ArrayN`

?

Further, what's the official name for this structure?
May 18 2016
parent reply Alex Parrill <initrd.gz gmail.com> writes:
On Wednesday, 18 May 2016 at 21:28:56 UTC, Nordlöw wrote:
 What's the preferred way in D to implement single-allocation 
 variable-sized arrays such as

 /** Single-Allocation Array. */
 struct ArrayN
 {
     ubyte length;  // <= maxLength
     size room;     // allocated length
     ubyte[0] data; // `room` number of bytes follows
 }

 where insertion/deletion typically is done via

     ArrayN* pushBack(ArrayN*, ubyte element);
     ArrayN* popBack(ArrayN*);

 which, when needed, will reallocate a new larger/smaller 
 `ArrayN`

 ?

 Further, what's the official name for this structure?
In C it's called a variable-length struct or object. I don't think D implements them, but this could probably work: struct Foo { size_t len; ubyte[] data() property { auto thisptr = cast(ubyte*)(&this); return thisptr[Foo.sizeof..(Foo.sizeof+len)]; } }
May 18 2016
parent =?UTF-8?B?Tm9yZGzDtnc=?= <per.nordlow gmail.com> writes:
On Wednesday, 18 May 2016 at 23:45:07 UTC, Alex Parrill wrote:
 In C it's called a variable-length struct or object. I don't 
 think D implements them, but this could probably work:
Thanks!
May 21 2016