Debian Codegraph @

libphobos/libdruntime/rt/aaA.d

raw
1 /**
2 * Implementation of associative arrays.
3 *
4 * Copyright: Copyright Digital Mars 2000 - 2015.
5 * License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
6 * Authors: Martin Nowak
7 * Source: $(DRUNTIMESRC rt/_aaA.d)
8 */
9 module rt.aaA;
10
11 /// AA version for debuggers, bump whenever changing the layout
12 extern (C) immutable int _aaVersion = 1;
13
14 import core.memory : GC;
15 import core.internal.util.math : min, max;
16
17 // grow threshold
18 private enum GROW_NUM = 4;
19 private enum GROW_DEN = 5;
20 // shrink threshold
21 private enum SHRINK_NUM = 1;
22 private enum SHRINK_DEN = 8;
23 // grow factor
24 private enum GROW_FAC = 4;
25 // growing the AA doubles it's size, so the shrink threshold must be
26 // smaller than half the grow threshold to have a hysteresis
27 static assert(GROW_FAC * SHRINK_NUM * GROW_DEN < GROW_NUM * SHRINK_DEN);
28 // initial load factor (for literals), mean of both thresholds
29 private enum INIT_NUM = (GROW_DEN * SHRINK_NUM + GROW_NUM * SHRINK_DEN) / 2;
30 private enum INIT_DEN = SHRINK_DEN * GROW_DEN;
31
32 private enum INIT_NUM_BUCKETS = 8;
33 // magic hash constants to distinguish empty, deleted, and filled buckets
34 private enum HASH_EMPTY = 0;
35 private enum HASH_DELETED = 0x1;
36 private enum HASH_FILLED_MARK = size_t(1) << 8 * size_t.sizeof - 1;
37
38 /// Opaque AA wrapper
39 struct AA
40 {
41 Impl* impl;
42 alias impl this;
43
44 private @property bool empty() const pure nothrow @nogc @safe
45 {
46 return impl is null || !impl.length;
47 }
48 }
49
50 private struct Impl
51 {
52 private:
53 this(scope const TypeInfo_AssociativeArray ti, size_t sz = INIT_NUM_BUCKETS) nothrow
54 {
55 keysz = cast(uint) ti.key.tsize;
56 valsz = cast(uint) ti.value.tsize;
57 buckets = allocBuckets(sz);
58 firstUsed = cast(uint) buckets.length;
59 valoff = cast(uint) talign(keysz, ti.value.talign);
60 hashFn = &ti.key.getHash;
61
62 import rt.lifetime : hasPostblit, unqualify;
63
64 if (hasPostblit(unqualify(ti.key)))
65 flags |= Flags.keyHasPostblit;
66 if ((ti.key.flags | ti.value.flags) & 1)
67 flags |= Flags.hasPointers;
68
69 entryTI = ti.entry;
70 }
71
72 Bucket[] buckets;
73 uint used;
74 uint deleted;
75 const(TypeInfo) entryTI;
76 uint firstUsed;
77 immutable uint keysz;
78 immutable uint valsz;
79 immutable uint valoff;
80 Flags flags;
81
82 // function that calculates hash of a key. Set on creation
83 // the parameter is a pointer to the key.
84 size_t delegate(scope const void*) nothrow hashFn;
85
86 enum Flags : ubyte
87 {
88 none = 0x0,
89 keyHasPostblit = 0x1,
90 hasPointers = 0x2,
91 }
92
93 @property size_t length() const pure nothrow @nogc @safe
94 {
95 assert(used >= deleted);
96 return used - deleted;
97 }
98
99 @property size_t dim() const pure nothrow @nogc @safe
100 {
101 return buckets.length;
102 }
103
104 @property size_t mask() const pure nothrow @nogc
105 {
106 return dim - 1;
107 }
108
109 // find the first slot to insert a value with hash
110 inout(Bucket)* findSlotInsert(size_t hash) inout pure nothrow @nogc
111 {
112 for (size_t i = hash & mask, j = 1;; ++j)
113 {
114 if (!buckets[i].filled)
115 return &buckets[i];
116 i = (i + j) & mask;
117 }
118 }
119
120 // lookup a key
121 inout(Bucket)* findSlotLookup(size_t hash, scope const void* pkey, scope const TypeInfo keyti) inout
122 {
123 for (size_t i = hash & mask, j = 1;; ++j)
124 {
125 if (buckets[i].hash == hash && keyti.equals(pkey, buckets[i].entry))
126 return &buckets[i];
127 else if (buckets[i].empty)
128 return null;
129 i = (i + j) & mask;
130 }
131 }
132
133 void grow(scope const TypeInfo keyti) pure nothrow
134 {
135 // If there are so many deleted entries, that growing would push us
136 // below the shrink threshold, we just purge deleted entries instead.
137 if (length * SHRINK_DEN < GROW_FAC * dim * SHRINK_NUM)
138 resize(dim);
139 else
140 resize(GROW_FAC * dim);
141 }
142
143 void shrink(scope const TypeInfo keyti) pure nothrow
144 {
145 if (dim > INIT_NUM_BUCKETS)
146 resize(dim / GROW_FAC);
147 }
148
149 void resize(size_t ndim) pure nothrow
150 {
151 auto obuckets = buckets;
152 buckets = allocBuckets(ndim);
153
154 foreach (ref b; obuckets[firstUsed .. $])
155 if (b.filled)
156 *findSlotInsert(b.hash) = b;
157
158 firstUsed = 0;
159 used -= deleted;
160 deleted = 0;
161 GC.free(obuckets.ptr); // safe to free b/c impossible to reference
162 }
163
164 void clear() pure nothrow @trusted
165 {
166 import core.stdc.string : memset;
167 // clear all data, but don't change bucket array length
168 memset(&buckets[firstUsed], 0, (buckets.length - firstUsed) * Bucket.sizeof);
169 deleted = used = 0;
170 firstUsed = cast(uint) dim;
171 }
172 }
173
174 //==============================================================================
175 // Bucket
176 //------------------------------------------------------------------------------
177
178 private struct Bucket
179 {
180 private pure nothrow @nogc:
181 size_t hash;
182 void* entry;
183
184 @property bool empty() const
185 {
186 return hash == HASH_EMPTY;
187 }
188
189 @property bool deleted() const
190 {
191 return hash == HASH_DELETED;
192 }
193
194 @property bool filled() const @safe
195 {
196 return cast(ptrdiff_t) hash < 0;
197 }
198 }
199
200 Bucket[] allocBuckets(size_t dim) @trusted pure nothrow
201 {
202 enum attr = GC.BlkAttr.NO_INTERIOR;
203 immutable sz = dim * Bucket.sizeof;
204 return (cast(Bucket*) GC.calloc(sz, attr))[0 .. dim];
205 }
206
207 //==============================================================================
208 // Entry
209 //------------------------------------------------------------------------------
210
211 private void* allocEntry(scope const Impl* aa, scope const void* pkey)
212 {
213 import rt.lifetime : _d_newitemU;
214 import core.stdc.string : memcpy, memset;
215
216 immutable akeysz = aa.valoff;
217 void* res = void;
218 if (aa.entryTI)
219 res = _d_newitemU(aa.entryTI);
220 else
221 {
222 auto flags = (aa.flags & Impl.Flags.hasPointers) ? 0 : GC.BlkAttr.NO_SCAN;
223 res = GC.malloc(akeysz + aa.valsz, flags);
224 }
225
226 memcpy(res, pkey, aa.keysz); // copy key
227 memset(res + akeysz, 0, aa.valsz); // zero value
228
229 return res;
230 }
231
232 private bool hasDtor(const TypeInfo ti) pure nothrow
233 {
234 import rt.lifetime : unqualify;
235
236 if (typeid(ti) is typeid(TypeInfo_Struct))
237 if ((cast(TypeInfo_Struct) cast(void*) ti).xdtor)
238 return true;
239 if (typeid(ti) is typeid(TypeInfo_StaticArray))
240 return hasDtor(unqualify(ti.next));
241
242 return false;
243 }
244
245 private immutable(void)* getRTInfo(const TypeInfo ti) pure nothrow
246 {
247 // classes are references
248 const isNoClass = ti && typeid(ti) !is typeid(TypeInfo_Class);
249 return isNoClass ? ti.rtInfo() : rtinfoHasPointers;
250 }
251
252 unittest
253 {
254 void test(K, V)()
255 {
256 static struct Entry
257 {
258 K key;
259 V val;
260 }
261 auto keyti = typeid(K);
262 auto valti = typeid(V);
263 auto valrti = getRTInfo(valti);
264 auto keyrti = getRTInfo(keyti);
265
266 auto impl = new Impl(typeid(V[K]));
267 if (valrti is rtinfoNoPointers && keyrti is rtinfoNoPointers)
268 {
269 assert(!(impl.flags & Impl.Flags.hasPointers));
270 }
271 else if (valrti is rtinfoHasPointers && keyrti is rtinfoHasPointers)
272 {
273 assert(impl.flags & Impl.Flags.hasPointers);
274 }
275 else
276 {
277 auto rtInfo = cast(size_t*) impl.entryTI.rtInfo();
278 auto refInfo = cast(size_t*) typeid(Entry).rtInfo();
279 assert(rtInfo[0] == refInfo[0]); // size
280 enum bytesPerWord = 8 * size_t.sizeof * (void*).sizeof;
281 size_t words = (rtInfo[0] + bytesPerWord - 1) / bytesPerWord;
282 foreach (i; 0 .. words)
283 assert(rtInfo[1 + i] == refInfo[i + 1]);
284 }
285 }
286 test!(long, int)();
287 test!(string, string);
288 test!(ubyte[16], Object);
289
290 static struct Small
291 {
292 ubyte[16] guid;
293 string name;
294 }
295 test!(string, Small);
296
297 static struct Large
298 {
299 ubyte[1024] data;
300 string[412] names;
301 ubyte[1024] moredata;
302 }
303 version (OnlyLowMemUnittests) {} else
304 test!(Large, Large);
305 }
306
307 //==============================================================================
308 // Helper functions
309 //------------------------------------------------------------------------------
310
311 private size_t talign(size_t tsize, size_t algn) @safe pure nothrow @nogc
312 {
313 immutable mask = algn - 1;
314 assert(!(mask & algn));
315 return (tsize + mask) & ~mask;
316 }
317
318 // mix hash to "fix" bad hash functions
319 private size_t mix(size_t h) @safe pure nothrow @nogc
320 {
321 // final mix function of MurmurHash2
322 enum m = 0x5bd1e995;
323 h ^= h >> 13;
324 h *= m;
325 h ^= h >> 15;
326 return h;
327 }
328
329 private size_t calcHash(scope const void *pkey, scope const Impl* impl) nothrow
330 {
331 immutable hash = impl.hashFn(pkey);
332 // highest bit is set to distinguish empty/deleted from filled buckets
333 return mix(hash) | HASH_FILLED_MARK;
334 }
335
336 private size_t nextpow2(const size_t n) pure nothrow @nogc
337 {
338 import core.bitop : bsr;
339
340 if (!n)
341 return 1;
342
343 const isPowerOf2 = !((n - 1) & n);
344 return 1 << (bsr(n) + !isPowerOf2);
345 }
346
347 pure nothrow @nogc unittest
348 {
349 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
350 foreach (const n, const pow2; [1, 1, 2, 4, 4, 8, 8, 8, 8, 16])
351 assert(nextpow2(n) == pow2);
352 }
353
354 //==============================================================================
355 // API Implementation
356 //------------------------------------------------------------------------------
357
358 /** Allocate associative array data.
359 * Called for `new SomeAA` expression.
360 * Params:
361 * ti = TypeInfo for the associative array
362 * Returns:
363 * A new associative array.
364 */
365 extern (C) Impl* _aaNew(const TypeInfo_AssociativeArray ti)
366 {
367 return new Impl(ti);
368 }
369
370 /// Determine number of entries in associative array.
371 extern (C) size_t _aaLen(scope const AA aa) pure nothrow @nogc
372 {
373 return aa ? aa.length : 0;
374 }
375
376 /******************************
377 * Lookup *pkey in aa.
378 * Called only from implementation of (aa[key]) expressions when value is mutable.
379 * Params:
380 * paa = associative array opaque pointer
381 * ti = TypeInfo for the associative array
382 * valsz = ignored
383 * pkey = pointer to the key value
384 * Returns:
385 * if key was in the aa, a mutable pointer to the existing value.
386 * If key was not in the aa, a mutable pointer to newly inserted value which
387 * is set to all zeros
388 */
389 extern (C) void* _aaGetY(scope AA* paa, const TypeInfo_AssociativeArray ti,
390 const size_t valsz, scope const void* pkey)
391 {
392 bool found;
393 return _aaGetX(paa, ti, valsz, pkey, found);
394 }
395
396 /******************************
397 * Lookup *pkey in aa.
398 * Called only from implementation of require
399 * Params:
400 * paa = associative array opaque pointer
401 * ti = TypeInfo for the associative array
402 * valsz = ignored
403 * pkey = pointer to the key value
404 * found = true if the value was found
405 * Returns:
406 * if key was in the aa, a mutable pointer to the existing value.
407 * If key was not in the aa, a mutable pointer to newly inserted value which
408 * is set to all zeros
409 */
410 extern (C) void* _aaGetX(scope AA* paa, const TypeInfo_AssociativeArray ti,
411 const size_t valsz, scope const void* pkey, out bool found)
412 {
413 // lazily alloc implementation
414 AA aa = *paa;
415 if (aa is null)
416 {
417 aa = new Impl(ti);
418 *paa = aa;
419 }
420
421 // get hash and bucket for key
422 immutable hash = calcHash(pkey, aa);
423
424 // found a value => return it
425 if (auto p = aa.findSlotLookup(hash, pkey, ti.key))
426 {
427 found = true;
428 return p.entry + aa.valoff;
429 }
430
431 auto p = aa.findSlotInsert(hash);
432 if (p.deleted)
433 --aa.deleted;
434 // check load factor and possibly grow
435 else if (++aa.used * GROW_DEN > aa.dim * GROW_NUM)
436 {
437 aa.grow(ti.key);
438 p = aa.findSlotInsert(hash);
439 assert(p.empty);
440 }
441
442 // update search cache and allocate entry
443 aa.firstUsed = min(aa.firstUsed, cast(uint)(p - aa.buckets.ptr));
444 p.hash = hash;
445 p.entry = allocEntry(aa, pkey);
446 // postblit for key
447 if (aa.flags & Impl.Flags.keyHasPostblit)
448 {
449 import rt.lifetime : __doPostblit, unqualify;
450
451 __doPostblit(p.entry, aa.keysz, unqualify(ti.key));
452 }
453 // return pointer to value
454 return p.entry + aa.valoff;
455 }
456
457 /******************************
458 * Lookup *pkey in aa.
459 * Called only from implementation of (aa[key]) expressions when value is not mutable.
460 * Params:
461 * aa = associative array opaque pointer
462 * keyti = TypeInfo for the key
463 * valsz = ignored
464 * pkey = pointer to the key value
465 * Returns:
466 * pointer to value if present, null otherwise
467 */
468 extern (C) inout(void)* _aaGetRvalueX(inout AA aa, scope const TypeInfo keyti, const size_t valsz,
469 scope const void* pkey)
470 {
471 return _aaInX(aa, keyti, pkey);
472 }
473
474 /******************************
475 * Lookup *pkey in aa.
476 * Called only from implementation of (key in aa) expressions.
477 * Params:
478 * aa = associative array opaque pointer
479 * keyti = TypeInfo for the key
480 * pkey = pointer to the key value
481 * Returns:
482 * pointer to value if present, null otherwise
483 */
484 extern (C) inout(void)* _aaInX(inout AA aa, scope const TypeInfo keyti, scope const void* pkey)
485 {
486 if (aa.empty)
487 return null;
488
489 immutable hash = calcHash(pkey, aa);
490 if (auto p = aa.findSlotLookup(hash, pkey, keyti))
491 return p.entry + aa.valoff;
492 return null;
493 }
494
495 /// Delete entry scope const AA, return true if it was present
496 extern (C) bool _aaDelX(AA aa, scope const TypeInfo keyti, scope const void* pkey)
497 {
498 if (aa.empty)
499 return false;
500
501 immutable hash = calcHash(pkey, aa);
502 if (auto p = aa.findSlotLookup(hash, pkey, keyti))
503 {
504 // clear entry
505 p.hash = HASH_DELETED;
506 p.entry = null;
507
508 ++aa.deleted;
509 // `shrink` reallocates, and allocating from a finalizer leads to
510 // InvalidMemoryError: https://issues.dlang.org/show_bug.cgi?id=21442
511 if (aa.length * SHRINK_DEN < aa.dim * SHRINK_NUM && !GC.inFinalizer())
512 aa.shrink(keyti);
513
514 return true;
515 }
516 return false;
517 }
518
519 /// Remove all elements from AA.
520 extern (C) void _aaClear(AA aa) pure nothrow @safe
521 {
522 if (!aa.empty)
523 {
524 aa.clear();
525 }
526 }
527
528 /// Rehash AA
529 extern (C) void* _aaRehash(AA* paa, scope const TypeInfo keyti) pure nothrow
530 {
531 AA aa = *paa;
532 if (!aa.empty)
533 aa.resize(nextpow2(INIT_DEN * aa.length / INIT_NUM));
534 return aa;
535 }
536
537 /// Return a GC allocated array of all values
538 extern (C) inout(void[]) _aaValues(inout AA aa, const size_t keysz, const size_t valsz,
539 const TypeInfo tiValueArray) pure nothrow
540 {
541 if (aa.empty)
542 return null;
543
544 import rt.lifetime : _d_newarrayU;
545
546 auto res = _d_newarrayU(tiValueArray, aa.length).ptr;
547 auto pval = res;
548
549 immutable off = aa.valoff;
550 foreach (b; aa.buckets[aa.firstUsed .. $])
551 {
552 if (!b.filled)
553 continue;
554 pval[0 .. valsz] = cast(void[]) b.entry[off .. valsz + off];
555 pval += valsz;
556 }
557 // postblit is done in object.values
558 return (cast(inout(void)*) res)[0 .. aa.length]; // fake length, return number of elements
559 }
560
561 /// Return a GC allocated array of all keys
562 extern (C) inout(void[]) _aaKeys(inout AA aa, const size_t keysz, const TypeInfo tiKeyArray) pure nothrow
563 {
564 if (aa.empty)
565 return null;
566
567 import rt.lifetime : _d_newarrayU;
568
569 auto res = _d_newarrayU(tiKeyArray, aa.length).ptr;
570 auto pkey = res;
571
572 foreach (b; aa.buckets[aa.firstUsed .. $])
573 {
574 if (!b.filled)
575 continue;
576 pkey[0 .. keysz] = cast(void[]) b.entry[0 .. keysz];
577 pkey += keysz;
578 }
579 // postblit is done in object.keys
580 return (cast(inout(void)*) res)[0 .. aa.length]; // fake length, return number of elements
581 }
582
583 // opApply callbacks are extern(D)
584 extern (D) alias dg_t = int delegate(void*);
585 extern (D) alias dg2_t = int delegate(void*, void*);
586
587 /// foreach opApply over all values
588 extern (C) int _aaApply(AA aa, const size_t keysz, dg_t dg)
589 {
590 if (aa.empty)
591 return 0;
592
593 immutable off = aa.valoff;
594 foreach (b; aa.buckets)
595 {
596 if (!b.filled)
597 continue;
598 if (auto res = dg(b.entry + off))
599 return res;
600 }
601 return 0;
602 }
603
604 /// foreach opApply over all key/value pairs
605 extern (C) int _aaApply2(AA aa, const size_t keysz, dg2_t dg)
606 {
607 if (aa.empty)
608 return 0;
609
610 immutable off = aa.valoff;
611 foreach (b; aa.buckets)
612 {
613 if (!b.filled)
614 continue;
615 if (auto res = dg(b.entry, b.entry + off))
616 return res;
617 }
618 return 0;
619 }
620
621 /** Construct an associative array of type ti from corresponding keys and values.
622 * Called for an AA literal `[k1:v1, k2:v2]`.
623 * Params:
624 * ti = TypeInfo for the associative array
625 * keys = array of keys
626 * vals = array of values
627 * Returns:
628 * A new associative array opaque pointer, or null if `keys` is empty.
629 */
630 extern (C) Impl* _d_assocarrayliteralTX(const TypeInfo_AssociativeArray ti, void[] keys,
631 void[] vals)
632 {
633 assert(keys.length == vals.length);
634
635 immutable keysz = ti.key.tsize;
636 immutable valsz = ti.value.tsize;
637 immutable length = keys.length;
638
639 if (!length)
640 return null;
641
642 auto aa = new Impl(ti, nextpow2(INIT_DEN * length / INIT_NUM));
643
644 void* pkey = keys.ptr;
645 void* pval = vals.ptr;
646 immutable off = aa.valoff;
647 uint actualLength = 0;
648 foreach (_; 0 .. length)
649 {
650 immutable hash = calcHash(pkey, aa);
651
652 auto p = aa.findSlotLookup(hash, pkey, ti.key);
653 if (p is null)
654 {
655 p = aa.findSlotInsert(hash);
656 p.hash = hash;
657 p.entry = allocEntry(aa, pkey); // move key, no postblit
658 aa.firstUsed = min(aa.firstUsed, cast(uint)(p - aa.buckets.ptr));
659 actualLength++;
660 }
661 else if (aa.entryTI && hasDtor(ti.value))
662 {
663 // destroy existing value before overwriting it
664 ti.value.destroy(p.entry + off);
665 }
666 // set hash and blit value
667 auto pdst = p.entry + off;
668 pdst[0 .. valsz] = pval[0 .. valsz]; // move value, no postblit
669
670 pkey += keysz;
671 pval += valsz;
672 }
673 aa.used = actualLength;
674 return aa;
675 }
676
677 /// compares 2 AAs for equality
678 extern (C) int _aaEqual(scope const TypeInfo tiRaw, scope const AA aa1, scope const AA aa2)
679 {
680 if (aa1 is aa2)
681 return true;
682
683 immutable len = _aaLen(aa1);
684 if (len != _aaLen(aa2))
685 return false;
686
687 if (!len) // both empty
688 return true;
689
690 import rt.lifetime : unqualify;
691
692 auto uti = unqualify(tiRaw);
693 auto ti = *cast(TypeInfo_AssociativeArray*)&uti;
694 // compare the entries
695 immutable off = aa1.valoff;
696 foreach (b1; aa1.buckets)
697 {
698 if (!b1.filled)
699 continue;
700 auto pb2 = aa2.findSlotLookup(b1.hash, b1.entry, ti.key);
701 if (pb2 is null || !ti.value.equals(b1.entry + off, pb2.entry + off))
702 return false;
703 }
704 return true;
705 }
706
707 /// compute a hash
708 extern (C) hash_t _aaGetHash(scope const AA* paa, scope const TypeInfo tiRaw) nothrow
709 {
710 const AA aa = *paa;
711
712 if (aa.empty)
713 return 0;
714
715 import rt.lifetime : unqualify;
716
717 auto uti = unqualify(tiRaw);
718 auto ti = *cast(TypeInfo_AssociativeArray*)&uti;
719 immutable off = aa.valoff;
720 auto keyHash = &ti.key.getHash;
721 auto valHash = &ti.value.getHash;
722
723 size_t h;
724 foreach (b; aa.buckets)
725 {
726 // use addition here, so that hash is independent of element order
727 if (b.filled)
728 h += hashOf(valHash(b.entry + off), keyHash(b.entry));
729 }
730
731 return h;
732 }
733
734 /**
735 * _aaRange implements a ForwardRange
736 */
737 struct Range
738 {
739 Impl* impl;
740 size_t idx;
741 alias impl this;
742 }
743
744 extern (C) pure nothrow @nogc @safe
745 {
746 Range _aaRange(return scope AA aa)
747 {
748 if (!aa)
749 return Range();
750
751 foreach (i; aa.firstUsed .. aa.dim)
752 {
753 if (aa.buckets[i].filled)
754 return Range(aa, i);
755 }
756 return Range(aa, aa.dim);
757 }
758
759 bool _aaRangeEmpty(Range r)
760 {
761 return r.impl is null || r.idx >= r.dim;
762 }
763
764 void* _aaRangeFrontKey(Range r)
765 {
766 assert(!_aaRangeEmpty(r));
767 if (r.idx >= r.dim)
768 return null;
769 return r.buckets[r.idx].entry;
770 }
771
772 void* _aaRangeFrontValue(Range r)
773 {
774 assert(!_aaRangeEmpty(r));
775 if (r.idx >= r.dim)
776 return null;
777
778 auto entry = r.buckets[r.idx].entry;
779 return entry is null ?
780 null :
781 (() @trusted { return entry + r.valoff; } ());
782 }
783
784 void _aaRangePopFront(ref Range r)
785 {
786 if (r.idx >= r.dim) return;
787 for (++r.idx; r.idx < r.dim; ++r.idx)
788 {
789 if (r.buckets[r.idx].filled)
790 break;
791 }
792 }
793 }
794
795 // Most tests are now in test_aa.d
796
797 // test postblit for AA literals
798 unittest
799 {
800 static struct T
801 {
802 ubyte field;
803 static size_t postblit, dtor;
804 this(this)
805 {
806 ++postblit;
807 }
808
809 ~this()
810 {
811 ++dtor;
812 }
813 }
814
815 T t;
816 auto aa1 = [0 : t, 1 : t];
817 assert(T.dtor == 0 && T.postblit == 2);
818 aa1[0] = t;
819 assert(T.dtor == 1 && T.postblit == 3);
820
821 T.dtor = 0;
822 T.postblit = 0;
823
824 auto aa2 = [0 : t, 1 : t, 0 : t]; // literal with duplicate key => value overwritten
825 assert(T.dtor == 1 && T.postblit == 3);
826
827 T.dtor = 0;
828 T.postblit = 0;
829
830 auto aa3 = [t : 0];
831 assert(T.dtor == 0 && T.postblit == 1);
832 aa3[t] = 1;
833 assert(T.dtor == 0 && T.postblit == 1);
834 aa3.remove(t);
835 assert(T.dtor == 0 && T.postblit == 1);
836 aa3[t] = 2;
837 assert(T.dtor == 0 && T.postblit == 2);
838
839 // dtor will be called by GC finalizers
840 aa1 = null;
841 aa2 = null;
842 aa3 = null;
843 auto dtor1 = typeid(TypeInfo_AssociativeArray.Entry!(int, T)).xdtor;
844 GC.runFinalizers((cast(char*)dtor1)[0 .. 1]);
845 auto dtor2 = typeid(TypeInfo_AssociativeArray.Entry!(T, int)).xdtor;
846 GC.runFinalizers((cast(char*)dtor2)[0 .. 1]);
847 assert(T.dtor == 6 && T.postblit == 2);
848 }
849
850 // Ensure the newaa struct layout (used for static initialization) is in sync
851 unittest
852 {
853 import newaa = core.internal.newaa;
854 static assert(newaa.Impl.sizeof == Impl.sizeof);
855 // ensure compatible types and offsets
856 static foreach (i; 0 .. Impl.tupleof.length)
857 {
858 // for bucket array and Flags, we "compatible" types, not exactly the same types.
859 static if (__traits(identifier, Impl.tupleof[i]) == "buckets"
860 || __traits(identifier, Impl.tupleof[i]) == "flags")
861 static assert(Impl.tupleof[i].sizeof == newaa.Impl.tupleof[i].sizeof);
862 else
863 static assert(is(typeof(Impl.tupleof[i]) == typeof(newaa.Impl.tupleof[i])));
864
865 static assert(Impl.tupleof[i].offsetof == newaa.Impl.tupleof[i].offsetof);
866 }
867 }