Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix issue 11725: AA.dup should return mutable AA where possible #16979

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 32 additions & 3 deletions druntime/src/object.d
Original file line number Diff line number Diff line change
Expand Up @@ -3008,15 +3008,22 @@ T rehash(T : shared Value[Key], Value, Key)(T* aa)
* Params:
* aa = The associative array.
*/
V[K] dup(T : V[K], K, V)(T aa)
auto dup(T : V[K], K, V)(T aa)
{
//pragma(msg, "K = ", K, ", V = ", V);

// Bug10720 - check whether V is copyable
static assert(is(typeof({ V v = aa[K.init]; })),
"cannot call " ~ T.stringof ~ ".dup because " ~ V.stringof ~ " is not copyable");

V[K] result;
// bug 11725: return mutable AA if possible
import core.internal.traits : Unconst;
static if (is(V : Unconst!V))
alias Result = Unconst!V[K];
else // mutable dup not possible, return const object instead.
alias Result = V[K];

Result result;

//foreach (k, ref v; aa)
// result[k] = v; // Bug13701 - won't work if V is not mutable
Expand Down Expand Up @@ -3046,7 +3053,7 @@ V[K] dup(T : V[K], K, V)(T aa)
}

/** ditto */
V[K] dup(T : V[K], K, V)(T* aa)
auto dup(T : V[K], K, V)(T* aa)
{
return (*aa).dup;
}
Expand All @@ -3060,6 +3067,28 @@ V[K] dup(T : V[K], K, V)(T* aa)
assert("k2" !in a2);
}

// bug 11725
///
@safe unittest
{
const int[string] aa = ["a": 1, "b": 2];
// Copied AA values can be mutable
int[string] bb = aa.dup;
assert(bb == ["a": 1, "b": 2]);
assert(++bb["b"] == 3);
}

version (CoreUnittest)
@safe test11725()
{
// contra case of 11725: dup'ing an AA with elements that cannot convert to
// non-const should yield const AA instead.
class C { }
const C[string] aa = [ "a": new C ];
auto bb = aa.dup;
static assert(is(typeof(bb) == const(C)[string]));
}

// this should never be made public.
private AARange _aaToRange(T: V[K], K, V)(ref T aa) pure nothrow @nogc @safe
{
Expand Down
Loading