www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - home made copy-on-write arrays

Discussing constant-ness / read-only-ness.....

As we know, in D, there is no difference between
array (master buffer) and slices from it (slave buffer).
So far this unisex solution is working (at least in Harmonia) and
allows to build effective code.
So I can e.g. return subvector of Widgets from a container and
caller can use it effectively for immutable enumerations (90% of cases).
The main problem for me is that I want to prevent cases when caller
will decide to modify such subvector - it can modify master buffer
too. The bad thing that it may happen in code far from original place
and in worst case asynchronously. Implementation nightmare to be short.

So to add some robustness to the library and keep effectiveness almost
at the same level I've came up with the idea of using array
wrappers with 'mutable' flags. (Kris, thanks, this is sort of your 
read-only)

struct array(T)
{
    T[] elements;
    bit  mutable;

    void mutate();
   ....
}

Full implementation of the array(T) attached.
It is an imperfect solution - there are some holes - but it seems is the
best one of what we can reach without compiler/runtime support.
(Actually it is feasible to implement mutable flag as higher bit in the
 length field of builtin arrays - max possible length will be twice less 
though. )

Any comments will be appreciated at this point
as I am going to use this approach for strings also - so it will be a 
massive update.

Andrew.
May 26 2005