[Issue 16269] add `aa.ensureAllocated` method to associative array to clear and initialize it

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Wed Jul 13 06:22:18 PDT 2016


https://issues.dlang.org/show_bug.cgi?id=16269

--- Comment #4 from Ketmar Dark <ketmar at ketmar.no-ip.org> ---
another try. this time it adds `ensureAllocated()` method, which can be used
like this:

======================================

void test (string[int] aa) { aa[42] = "42"; }

void main () {
  // inline
  {
    string[int] aa;
    test(aa.ensureAllocated);
    assert(aa[42] == "42");
    // check that AA is not cleared
    aa.ensureAllocated();
    assert(aa[42] == "42");
  }
  // function
  {
    string[int] bb;
    bb.ensureAllocated;
    test(bb);
    assert(bb[42] == "42");
    // check that AA is not cleared
    bb.ensureAllocated();
    assert(bb[42] == "42");
  }
}


======================================

diff --git a/src/object.d b/src/object.d
index 40e2391..0d82f07 100644
--- a/src/object.d
+++ b/src/object.d
@@ -1876,6 +1876,7 @@ extern (C)
     inout(void)[] _aaKeys(inout void* p, in size_t keysize, const TypeInfo
tiKeyArray) pure nothrow;
     void* _aaRehash(void** pp, in TypeInfo keyti) pure nothrow;
     void _aaClear(void* p) pure nothrow;
+    void _aaEnsureAllocated(void* p, const TypeInfo_AssociativeArray ti);

     // alias _dg_t = extern(D) int delegate(void*);
     // int _aaApply(void* aa, size_t keysize, _dg_t dg);
@@ -1919,6 +1920,18 @@ void clear(T : Value[Key], Value, Key)(T* aa)
     _aaClear(*cast(void **) aa);
 }

+T ensureAllocated(T : Value[Key], Value, Key)(ref T aa)
+{
+    _aaEnsureAllocated(cast(void*)&aa, typeid(T));
+    return aa;
+}
+
+T ensureAllocated(T : Value[Key], Value, Key)(T* aa)
+{
+    _aaEnsureAllocated(cast(void*)aa, typeid(T));
+    return *aa;
+}
+
 T rehash(T : Value[Key], Value, Key)(T aa)
 {
     _aaRehash(cast(void**)&aa, typeid(Value[Key]));
diff --git a/src/rt/aaA.d b/src/rt/aaA.d
index cf8943e..b16b6d8 100644
--- a/src/rt/aaA.d
+++ b/src/rt/aaA.d
@@ -443,6 +443,16 @@ extern (C) void _aaClear(AA aa) pure nothrow
     }
 }

+/// Remove all elements from AA, allocate new AA if it isn't allocated yet.
+extern (C) void _aaEnsureAllocated(AA* paa, const TypeInfo_AssociativeArray
ti)
+{
+    if (paa !is null && paa.impl is null)
+    {
+      // alloc implementation
+      paa.impl = new Impl(ti);
+    }
+}
+
 /// Rehash AA
 extern (C) void* _aaRehash(AA* paa, in TypeInfo keyti) pure nothrow
 {
-- 
2.9.0

--


More information about the Digitalmars-d-bugs mailing list