Bug 9313 – Provide dynamic array-dedicated "extend" function

Status
NEW
Severity
enhancement
Priority
P4
Component
druntime
Product
D
Version
D2
Platform
All
OS
All
Creation time
2013-01-13T13:43:02Z
Last change time
2024-12-07T13:32:13Z
Keywords
pull
Assigned to
No Owner
Creator
monarchdodra
Moved to GitHub: dmd#17247 →

Comments

Comment #0 by monarchdodra — 2013-01-13T13:43:02Z
GC has an extend function (http://dlang.org/phobos/core_memory.html#.GC.extend). 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); //----
Comment #1 by verylonglogin.reg — 2013-11-07T10:19:06Z
Pull with runtime support for such function: https://github.com/D-Programming-Language/druntime/pull/620
Comment #2 by robert.schadek — 2024-12-07T13:32:13Z
THIS ISSUE HAS BEEN MOVED TO GITHUB https://github.com/dlang/dmd/issues/17247 DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB