www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 9313] New: Provide dynamic array-dedicated "extend" function

http://d.puremagic.com/issues/show_bug.cgi?id=9313

           Summary: Provide dynamic array-dedicated "extend" function
           Product: D
           Version: unspecified
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: enhancement
          Priority: P2
         Component: druntime
        AssignedTo: nobody puremagic.com
        ReportedBy: monarchdodra gmail.com



GC has an extend function


Problem: It does not play nice with dynamic arrays. If the user wants to have
the same functionality for a dynamic array, he must keep in mind this pitfall:

The value returned is NOT the size of the array, because some of the memory is
taken up by the array implementation. This means using extend correctly is ripe
with dangers. Here is some code illustrating the problems.

//----
    auto arr = new int[](1000); //The current slice

    //We want to extend for 2000 elements.
    //We have to overshoot... by 16 ?
    auto u = GC.extend(arr.ptr, 2000 * int.sizeof + 16, 3000 * int.sizeof +
16);

    if (u != 0)
    {
        //Sucess, we have extended but...

        //Wrong: This will access the array's implementation and fault.
        arr = arr.ptr[0 .. u / int.sizeof];

        //Wrong: some of the extended data is reserved for the array
implementation
        //Doing this will re-alocate:
        arr.length = u / int.sizeof;

        //Correct: Only the array know its own real capacity.
        //u serves no purpose other than checking for success, and
        //tricking users
        arr.length = arr.capacity;
    }
//----

Having this kind of code in the user base is dangerous, and also relies on
implementation details (16 bytes). It's really just accidents just waiting to
happen, including in phobos, such as in Append
(http://d.puremagic.com/issues/show_bug.cgi?id=9092)

"extend" for arrays would solve the problem:

//----
    auto arr = new int[](1000); //The current slice
    auto u = arr.extend(2000, 3000);
    if (u != 0)
        arr.length = u;
//----

Simple, clean, efficient and convenient, and *safe*.

So I would like to request a "extend" function for dynamic arrays:
//----
/**
 * Try to extend capacity for an array, without re-allocating.
 *
 * The return value is the new capacity of the array
 * (which may be larger than the requested capacity).
 */
pure nothrow size_t extend(T)(ref T[] arr, size_t minimum, size_t desired);
//----

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
Jan 13 2013