www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 21410] New: idup of an array of immutable elements should be


          Issue ID: 21410
           Summary: idup of an array of immutable elements should be a
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P5
         Component: druntime
          Assignee: nobody puremagic.com
          Reporter: dlang-bugzilla thecybershadow.net

string s = "foo";
assert(s.idup.ptr == s.ptr); // Fail

If the data is immutable, it can already be assumed that it has infinite
lifetime, so unless something is breaking the type system, it doesn't make
sense to create another copy of it.

The motivation is generic code such as the following:

int[string] dict;
void save(C : char)(C[] key, int value)
        if (auto p = key in dict)
                *p = value;
                dict[key.idup] = value;

This way, save can be called with either a char[] or string, and it will only
copy the key argument if it needs to. Such a distinction can occur when e.g.
deserializing data from memory (where it can be immutable), or chunk-wise from
a stream (where the data's lifetime is only until the next chunk is read).

Nov 20 2020