This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Increase $mro::VERSION to 1.15
[perl5.git] / hv.c
1 /*    hv.c
2  *
3  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4  *    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
5  *
6  *    You may distribute under the terms of either the GNU General Public
7  *    License or the Artistic License, as specified in the README file.
8  *
9  */
10
11 /*
12  *      I sit beside the fire and think
13  *          of all that I have seen.
14  *                         --Bilbo
15  *
16  *     [p.278 of _The Lord of the Rings_, II/iii: "The Ring Goes South"]
17  */
18
19 /* 
20 =head1 Hash Manipulation Functions
21
22 A HV structure represents a Perl hash.  It consists mainly of an array
23 of pointers, each of which points to a linked list of HE structures.  The
24 array is indexed by the hash function of the key, so each linked list
25 represents all the hash entries with the same hash value.  Each HE contains
26 a pointer to the actual value, plus a pointer to a HEK structure which
27 holds the key and hash value.
28
29 =cut
30
31 */
32
33 #include "EXTERN.h"
34 #define PERL_IN_HV_C
35 #define PERL_HASH_INTERNAL_ACCESS
36 #include "perl.h"
37
38 #define DO_HSPLIT(xhv) ((xhv)->xhv_keys > (xhv)->xhv_max) /* HvTOTALKEYS(hv) > HvMAX(hv) */
39 #define HV_FILL_THRESHOLD 31
40
41 static const char S_strtab_error[]
42     = "Cannot modify shared string table in hv_%s";
43
44 #ifdef PURIFY
45
46 #define new_HE() (HE*)safemalloc(sizeof(HE))
47 #define del_HE(p) safefree((char*)p)
48
49 #else
50
51 STATIC HE*
52 S_new_he(pTHX)
53 {
54     dVAR;
55     HE* he;
56     void ** const root = &PL_body_roots[HE_SVSLOT];
57
58     if (!*root)
59         Perl_more_bodies(aTHX_ HE_SVSLOT, sizeof(HE), PERL_ARENA_SIZE);
60     he = (HE*) *root;
61     assert(he);
62     *root = HeNEXT(he);
63     return he;
64 }
65
66 #define new_HE() new_he()
67 #define del_HE(p) \
68     STMT_START { \
69         HeNEXT(p) = (HE*)(PL_body_roots[HE_SVSLOT]);    \
70         PL_body_roots[HE_SVSLOT] = p; \
71     } STMT_END
72
73
74
75 #endif
76
77 STATIC HEK *
78 S_save_hek_flags(const char *str, I32 len, U32 hash, int flags)
79 {
80     const int flags_masked = flags & HVhek_MASK;
81     char *k;
82     HEK *hek;
83
84     PERL_ARGS_ASSERT_SAVE_HEK_FLAGS;
85
86     Newx(k, HEK_BASESIZE + len + 2, char);
87     hek = (HEK*)k;
88     Copy(str, HEK_KEY(hek), len, char);
89     HEK_KEY(hek)[len] = 0;
90     HEK_LEN(hek) = len;
91     HEK_HASH(hek) = hash;
92     HEK_FLAGS(hek) = (unsigned char)flags_masked | HVhek_UNSHARED;
93
94     if (flags & HVhek_FREEKEY)
95         Safefree(str);
96     return hek;
97 }
98
99 /* free the pool of temporary HE/HEK pairs returned by hv_fetch_ent
100  * for tied hashes */
101
102 void
103 Perl_free_tied_hv_pool(pTHX)
104 {
105     dVAR;
106     HE *he = PL_hv_fetch_ent_mh;
107     while (he) {
108         HE * const ohe = he;
109         Safefree(HeKEY_hek(he));
110         he = HeNEXT(he);
111         del_HE(ohe);
112     }
113     PL_hv_fetch_ent_mh = NULL;
114 }
115
116 #if defined(USE_ITHREADS)
117 HEK *
118 Perl_hek_dup(pTHX_ HEK *source, CLONE_PARAMS* param)
119 {
120     HEK *shared;
121
122     PERL_ARGS_ASSERT_HEK_DUP;
123     PERL_UNUSED_ARG(param);
124
125     if (!source)
126         return NULL;
127
128     shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
129     if (shared) {
130         /* We already shared this hash key.  */
131         (void)share_hek_hek(shared);
132     }
133     else {
134         shared
135             = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
136                               HEK_HASH(source), HEK_FLAGS(source));
137         ptr_table_store(PL_ptr_table, source, shared);
138     }
139     return shared;
140 }
141
142 HE *
143 Perl_he_dup(pTHX_ const HE *e, bool shared, CLONE_PARAMS* param)
144 {
145     HE *ret;
146
147     PERL_ARGS_ASSERT_HE_DUP;
148
149     if (!e)
150         return NULL;
151     /* look for it in the table first */
152     ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
153     if (ret)
154         return ret;
155
156     /* create anew and remember what it is */
157     ret = new_HE();
158     ptr_table_store(PL_ptr_table, e, ret);
159
160     HeNEXT(ret) = he_dup(HeNEXT(e),shared, param);
161     if (HeKLEN(e) == HEf_SVKEY) {
162         char *k;
163         Newx(k, HEK_BASESIZE + sizeof(const SV *), char);
164         HeKEY_hek(ret) = (HEK*)k;
165         HeKEY_sv(ret) = sv_dup_inc(HeKEY_sv(e), param);
166     }
167     else if (shared) {
168         /* This is hek_dup inlined, which seems to be important for speed
169            reasons.  */
170         HEK * const source = HeKEY_hek(e);
171         HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
172
173         if (shared) {
174             /* We already shared this hash key.  */
175             (void)share_hek_hek(shared);
176         }
177         else {
178             shared
179                 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
180                                   HEK_HASH(source), HEK_FLAGS(source));
181             ptr_table_store(PL_ptr_table, source, shared);
182         }
183         HeKEY_hek(ret) = shared;
184     }
185     else
186         HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
187                                         HeKFLAGS(e));
188     HeVAL(ret) = sv_dup_inc(HeVAL(e), param);
189     return ret;
190 }
191 #endif  /* USE_ITHREADS */
192
193 static void
194 S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
195                 const char *msg)
196 {
197     SV * const sv = sv_newmortal();
198
199     PERL_ARGS_ASSERT_HV_NOTALLOWED;
200
201     if (!(flags & HVhek_FREEKEY)) {
202         sv_setpvn(sv, key, klen);
203     }
204     else {
205         /* Need to free saved eventually assign to mortal SV */
206         /* XXX is this line an error ???:  SV *sv = sv_newmortal(); */
207         sv_usepvn(sv, (char *) key, klen);
208     }
209     if (flags & HVhek_UTF8) {
210         SvUTF8_on(sv);
211     }
212     Perl_croak(aTHX_ msg, SVfARG(sv));
213 }
214
215 /* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
216  * contains an SV* */
217
218 /*
219 =for apidoc hv_store
220
221 Stores an SV in a hash.  The hash key is specified as C<key> and the
222 absolute value of C<klen> is the length of the key.  If C<klen> is
223 negative the key is assumed to be in UTF-8-encoded Unicode.  The
224 C<hash> parameter is the precomputed hash value; if it is zero then
225 Perl will compute it.
226
227 The return value will be
228 NULL if the operation failed or if the value did not need to be actually
229 stored within the hash (as in the case of tied hashes).  Otherwise it can
230 be dereferenced to get the original C<SV*>.  Note that the caller is
231 responsible for suitably incrementing the reference count of C<val> before
232 the call, and decrementing it if the function returned NULL.  Effectively
233 a successful hv_store takes ownership of one reference to C<val>.  This is
234 usually what you want; a newly created SV has a reference count of one, so
235 if all your code does is create SVs then store them in a hash, hv_store
236 will own the only reference to the new SV, and your code doesn't need to do
237 anything further to tidy up.  hv_store is not implemented as a call to
238 hv_store_ent, and does not create a temporary SV for the key, so if your
239 key data is not already in SV form then use hv_store in preference to
240 hv_store_ent.
241
242 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
243 information on how to use this function on tied hashes.
244
245 =for apidoc hv_store_ent
246
247 Stores C<val> in a hash.  The hash key is specified as C<key>.  The C<hash>
248 parameter is the precomputed hash value; if it is zero then Perl will
249 compute it.  The return value is the new hash entry so created.  It will be
250 NULL if the operation failed or if the value did not need to be actually
251 stored within the hash (as in the case of tied hashes).  Otherwise the
252 contents of the return value can be accessed using the C<He?> macros
253 described here.  Note that the caller is responsible for suitably
254 incrementing the reference count of C<val> before the call, and
255 decrementing it if the function returned NULL.  Effectively a successful
256 hv_store_ent takes ownership of one reference to C<val>.  This is
257 usually what you want; a newly created SV has a reference count of one, so
258 if all your code does is create SVs then store them in a hash, hv_store
259 will own the only reference to the new SV, and your code doesn't need to do
260 anything further to tidy up.  Note that hv_store_ent only reads the C<key>;
261 unlike C<val> it does not take ownership of it, so maintaining the correct
262 reference count on C<key> is entirely the caller's responsibility.  hv_store
263 is not implemented as a call to hv_store_ent, and does not create a temporary
264 SV for the key, so if your key data is not already in SV form then use
265 hv_store in preference to hv_store_ent.
266
267 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
268 information on how to use this function on tied hashes.
269
270 =for apidoc hv_exists
271
272 Returns a boolean indicating whether the specified hash key exists.  The
273 absolute value of C<klen> is the length of the key.  If C<klen> is
274 negative the key is assumed to be in UTF-8-encoded Unicode.
275
276 =for apidoc hv_fetch
277
278 Returns the SV which corresponds to the specified key in the hash.
279 The absolute value of C<klen> is the length of the key.  If C<klen> is
280 negative the key is assumed to be in UTF-8-encoded Unicode.  If
281 C<lval> is set then the fetch will be part of a store.  This means that if
282 there is no value in the hash associated with the given key, then one is
283 created and a pointer to it is returned.  The C<SV*> it points to can be
284 assigned to.  But always check that the
285 return value is non-null before dereferencing it to an C<SV*>.
286
287 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
288 information on how to use this function on tied hashes.
289
290 =for apidoc hv_exists_ent
291
292 Returns a boolean indicating whether
293 the specified hash key exists.  C<hash>
294 can be a valid precomputed hash value, or 0 to ask for it to be
295 computed.
296
297 =cut
298 */
299
300 /* returns an HE * structure with the all fields set */
301 /* note that hent_val will be a mortal sv for MAGICAL hashes */
302 /*
303 =for apidoc hv_fetch_ent
304
305 Returns the hash entry which corresponds to the specified key in the hash.
306 C<hash> must be a valid precomputed hash number for the given C<key>, or 0
307 if you want the function to compute it.  IF C<lval> is set then the fetch
308 will be part of a store.  Make sure the return value is non-null before
309 accessing it.  The return value when C<hv> is a tied hash is a pointer to a
310 static location, so be sure to make a copy of the structure if you need to
311 store it somewhere.
312
313 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
314 information on how to use this function on tied hashes.
315
316 =cut
317 */
318
319 /* Common code for hv_delete()/hv_exists()/hv_fetch()/hv_store()  */
320 void *
321 Perl_hv_common_key_len(pTHX_ HV *hv, const char *key, I32 klen_i32,
322                        const int action, SV *val, const U32 hash)
323 {
324     STRLEN klen;
325     int flags;
326
327     PERL_ARGS_ASSERT_HV_COMMON_KEY_LEN;
328
329     if (klen_i32 < 0) {
330         klen = -klen_i32;
331         flags = HVhek_UTF8;
332     } else {
333         klen = klen_i32;
334         flags = 0;
335     }
336     return hv_common(hv, NULL, key, klen, flags, action, val, hash);
337 }
338
339 void *
340 Perl_hv_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
341                int flags, int action, SV *val, U32 hash)
342 {
343     dVAR;
344     XPVHV* xhv;
345     HE *entry;
346     HE **oentry;
347     SV *sv;
348     bool is_utf8;
349     int masked_flags;
350     const int return_svp = action & HV_FETCH_JUST_SV;
351
352     if (!hv)
353         return NULL;
354     if (SvTYPE(hv) == (svtype)SVTYPEMASK)
355         return NULL;
356
357     assert(SvTYPE(hv) == SVt_PVHV);
358
359     if (SvSMAGICAL(hv) && SvGMAGICAL(hv) && !(action & HV_DISABLE_UVAR_XKEY)) {
360         MAGIC* mg;
361         if ((mg = mg_find((const SV *)hv, PERL_MAGIC_uvar))) {
362             struct ufuncs * const uf = (struct ufuncs *)mg->mg_ptr;
363             if (uf->uf_set == NULL) {
364                 SV* obj = mg->mg_obj;
365
366                 if (!keysv) {
367                     keysv = newSVpvn_flags(key, klen, SVs_TEMP |
368                                            ((flags & HVhek_UTF8)
369                                             ? SVf_UTF8 : 0));
370                 }
371                 
372                 mg->mg_obj = keysv;         /* pass key */
373                 uf->uf_index = action;      /* pass action */
374                 magic_getuvar(MUTABLE_SV(hv), mg);
375                 keysv = mg->mg_obj;         /* may have changed */
376                 mg->mg_obj = obj;
377
378                 /* If the key may have changed, then we need to invalidate
379                    any passed-in computed hash value.  */
380                 hash = 0;
381             }
382         }
383     }
384     if (keysv) {
385         if (flags & HVhek_FREEKEY)
386             Safefree(key);
387         key = SvPV_const(keysv, klen);
388         is_utf8 = (SvUTF8(keysv) != 0);
389         if (SvIsCOW_shared_hash(keysv)) {
390             flags = HVhek_KEYCANONICAL | (is_utf8 ? HVhek_UTF8 : 0);
391         } else {
392             flags = is_utf8 ? HVhek_UTF8 : 0;
393         }
394     } else {
395         is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
396     }
397
398     if (action & HV_DELETE) {
399         return (void *) hv_delete_common(hv, keysv, key, klen,
400                                          flags, action, hash);
401     }
402
403     xhv = (XPVHV*)SvANY(hv);
404     if (SvMAGICAL(hv)) {
405         if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS))) {
406             if (mg_find((const SV *)hv, PERL_MAGIC_tied)
407                 || SvGMAGICAL((const SV *)hv))
408             {
409                 /* FIXME should be able to skimp on the HE/HEK here when
410                    HV_FETCH_JUST_SV is true.  */
411                 if (!keysv) {
412                     keysv = newSVpvn_utf8(key, klen, is_utf8);
413                 } else {
414                     keysv = newSVsv(keysv);
415                 }
416                 sv = sv_newmortal();
417                 mg_copy(MUTABLE_SV(hv), sv, (char *)keysv, HEf_SVKEY);
418
419                 /* grab a fake HE/HEK pair from the pool or make a new one */
420                 entry = PL_hv_fetch_ent_mh;
421                 if (entry)
422                     PL_hv_fetch_ent_mh = HeNEXT(entry);
423                 else {
424                     char *k;
425                     entry = new_HE();
426                     Newx(k, HEK_BASESIZE + sizeof(const SV *), char);
427                     HeKEY_hek(entry) = (HEK*)k;
428                 }
429                 HeNEXT(entry) = NULL;
430                 HeSVKEY_set(entry, keysv);
431                 HeVAL(entry) = sv;
432                 sv_upgrade(sv, SVt_PVLV);
433                 LvTYPE(sv) = 'T';
434                  /* so we can free entry when freeing sv */
435                 LvTARG(sv) = MUTABLE_SV(entry);
436
437                 /* XXX remove at some point? */
438                 if (flags & HVhek_FREEKEY)
439                     Safefree(key);
440
441                 if (return_svp) {
442                     return entry ? (void *) &HeVAL(entry) : NULL;
443                 }
444                 return (void *) entry;
445             }
446 #ifdef ENV_IS_CASELESS
447             else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
448                 U32 i;
449                 for (i = 0; i < klen; ++i)
450                     if (isLOWER(key[i])) {
451                         /* Would be nice if we had a routine to do the
452                            copy and upercase in a single pass through.  */
453                         const char * const nkey = strupr(savepvn(key,klen));
454                         /* Note that this fetch is for nkey (the uppercased
455                            key) whereas the store is for key (the original)  */
456                         void *result = hv_common(hv, NULL, nkey, klen,
457                                                  HVhek_FREEKEY, /* free nkey */
458                                                  0 /* non-LVAL fetch */
459                                                  | HV_DISABLE_UVAR_XKEY
460                                                  | return_svp,
461                                                  NULL /* no value */,
462                                                  0 /* compute hash */);
463                         if (!result && (action & HV_FETCH_LVALUE)) {
464                             /* This call will free key if necessary.
465                                Do it this way to encourage compiler to tail
466                                call optimise.  */
467                             result = hv_common(hv, keysv, key, klen, flags,
468                                                HV_FETCH_ISSTORE
469                                                | HV_DISABLE_UVAR_XKEY
470                                                | return_svp,
471                                                newSV(0), hash);
472                         } else {
473                             if (flags & HVhek_FREEKEY)
474                                 Safefree(key);
475                         }
476                         return result;
477                     }
478             }
479 #endif
480         } /* ISFETCH */
481         else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
482             if (mg_find((const SV *)hv, PERL_MAGIC_tied)
483                 || SvGMAGICAL((const SV *)hv)) {
484                 /* I don't understand why hv_exists_ent has svret and sv,
485                    whereas hv_exists only had one.  */
486                 SV * const svret = sv_newmortal();
487                 sv = sv_newmortal();
488
489                 if (keysv || is_utf8) {
490                     if (!keysv) {
491                         keysv = newSVpvn_utf8(key, klen, TRUE);
492                     } else {
493                         keysv = newSVsv(keysv);
494                     }
495                     mg_copy(MUTABLE_SV(hv), sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
496                 } else {
497                     mg_copy(MUTABLE_SV(hv), sv, key, klen);
498                 }
499                 if (flags & HVhek_FREEKEY)
500                     Safefree(key);
501                 magic_existspack(svret, mg_find(sv, PERL_MAGIC_tiedelem));
502                 /* This cast somewhat evil, but I'm merely using NULL/
503                    not NULL to return the boolean exists.
504                    And I know hv is not NULL.  */
505                 return SvTRUE(svret) ? (void *)hv : NULL;
506                 }
507 #ifdef ENV_IS_CASELESS
508             else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
509                 /* XXX This code isn't UTF8 clean.  */
510                 char * const keysave = (char * const)key;
511                 /* Will need to free this, so set FREEKEY flag.  */
512                 key = savepvn(key,klen);
513                 key = (const char*)strupr((char*)key);
514                 is_utf8 = FALSE;
515                 hash = 0;
516                 keysv = 0;
517
518                 if (flags & HVhek_FREEKEY) {
519                     Safefree(keysave);
520                 }
521                 flags |= HVhek_FREEKEY;
522             }
523 #endif
524         } /* ISEXISTS */
525         else if (action & HV_FETCH_ISSTORE) {
526             bool needs_copy;
527             bool needs_store;
528             hv_magic_check (hv, &needs_copy, &needs_store);
529             if (needs_copy) {
530                 const bool save_taint = TAINT_get;
531                 if (keysv || is_utf8) {
532                     if (!keysv) {
533                         keysv = newSVpvn_utf8(key, klen, TRUE);
534                     }
535                     if (TAINTING_get)
536                         TAINT_set(SvTAINTED(keysv));
537                     keysv = sv_2mortal(newSVsv(keysv));
538                     mg_copy(MUTABLE_SV(hv), val, (char*)keysv, HEf_SVKEY);
539                 } else {
540                     mg_copy(MUTABLE_SV(hv), val, key, klen);
541                 }
542
543                 TAINT_IF(save_taint);
544 #ifdef NO_TAINT_SUPPORT
545                 PERL_UNUSED_VAR(save_taint);
546 #endif
547                 if (!needs_store) {
548                     if (flags & HVhek_FREEKEY)
549                         Safefree(key);
550                     return NULL;
551                 }
552 #ifdef ENV_IS_CASELESS
553                 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
554                     /* XXX This code isn't UTF8 clean.  */
555                     const char *keysave = key;
556                     /* Will need to free this, so set FREEKEY flag.  */
557                     key = savepvn(key,klen);
558                     key = (const char*)strupr((char*)key);
559                     is_utf8 = FALSE;
560                     hash = 0;
561                     keysv = 0;
562
563                     if (flags & HVhek_FREEKEY) {
564                         Safefree(keysave);
565                     }
566                     flags |= HVhek_FREEKEY;
567                 }
568 #endif
569             }
570         } /* ISSTORE */
571     } /* SvMAGICAL */
572
573     if (!HvARRAY(hv)) {
574         if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
575 #ifdef DYNAMIC_ENV_FETCH  /* if it's an %ENV lookup, we may get it on the fly */
576                  || (SvRMAGICAL((const SV *)hv)
577                      && mg_find((const SV *)hv, PERL_MAGIC_env))
578 #endif
579                                                                   ) {
580             char *array;
581             Newxz(array,
582                  PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
583                  char);
584             HvARRAY(hv) = (HE**)array;
585         }
586 #ifdef DYNAMIC_ENV_FETCH
587         else if (action & HV_FETCH_ISEXISTS) {
588             /* for an %ENV exists, if we do an insert it's by a recursive
589                store call, so avoid creating HvARRAY(hv) right now.  */
590         }
591 #endif
592         else {
593             /* XXX remove at some point? */
594             if (flags & HVhek_FREEKEY)
595                 Safefree(key);
596
597             return NULL;
598         }
599     }
600
601     if (is_utf8 && !(flags & HVhek_KEYCANONICAL)) {
602         char * const keysave = (char *)key;
603         key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
604         if (is_utf8)
605             flags |= HVhek_UTF8;
606         else
607             flags &= ~HVhek_UTF8;
608         if (key != keysave) {
609             if (flags & HVhek_FREEKEY)
610                 Safefree(keysave);
611             flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
612             /* If the caller calculated a hash, it was on the sequence of
613                octets that are the UTF-8 form. We've now changed the sequence
614                of octets stored to that of the equivalent byte representation,
615                so the hash we need is different.  */
616             hash = 0;
617         }
618     }
619
620     if (!hash) {
621         if (keysv && (SvIsCOW_shared_hash(keysv)))
622             hash = SvSHARED_HASH(keysv);
623         else
624             PERL_HASH(hash, key, klen);
625     }
626
627     masked_flags = (flags & HVhek_MASK);
628
629 #ifdef DYNAMIC_ENV_FETCH
630     if (!HvARRAY(hv)) entry = NULL;
631     else
632 #endif
633     {
634         entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
635     }
636     for (; entry; entry = HeNEXT(entry)) {
637         if (HeHASH(entry) != hash)              /* strings can't be equal */
638             continue;
639         if (HeKLEN(entry) != (I32)klen)
640             continue;
641         if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen))        /* is this it? */
642             continue;
643         if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
644             continue;
645
646         if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
647             if (HeKFLAGS(entry) != masked_flags) {
648                 /* We match if HVhek_UTF8 bit in our flags and hash key's
649                    match.  But if entry was set previously with HVhek_WASUTF8
650                    and key now doesn't (or vice versa) then we should change
651                    the key's flag, as this is assignment.  */
652                 if (HvSHAREKEYS(hv)) {
653                     /* Need to swap the key we have for a key with the flags we
654                        need. As keys are shared we can't just write to the
655                        flag, so we share the new one, unshare the old one.  */
656                     HEK * const new_hek = share_hek_flags(key, klen, hash,
657                                                    masked_flags);
658                     unshare_hek (HeKEY_hek(entry));
659                     HeKEY_hek(entry) = new_hek;
660                 }
661                 else if (hv == PL_strtab) {
662                     /* PL_strtab is usually the only hash without HvSHAREKEYS,
663                        so putting this test here is cheap  */
664                     if (flags & HVhek_FREEKEY)
665                         Safefree(key);
666                     Perl_croak(aTHX_ S_strtab_error,
667                                action & HV_FETCH_LVALUE ? "fetch" : "store");
668                 }
669                 else
670                     HeKFLAGS(entry) = masked_flags;
671                 if (masked_flags & HVhek_ENABLEHVKFLAGS)
672                     HvHASKFLAGS_on(hv);
673             }
674             if (HeVAL(entry) == &PL_sv_placeholder) {
675                 /* yes, can store into placeholder slot */
676                 if (action & HV_FETCH_LVALUE) {
677                     if (SvMAGICAL(hv)) {
678                         /* This preserves behaviour with the old hv_fetch
679                            implementation which at this point would bail out
680                            with a break; (at "if we find a placeholder, we
681                            pretend we haven't found anything")
682
683                            That break mean that if a placeholder were found, it
684                            caused a call into hv_store, which in turn would
685                            check magic, and if there is no magic end up pretty
686                            much back at this point (in hv_store's code).  */
687                         break;
688                     }
689                     /* LVAL fetch which actually needs a store.  */
690                     val = newSV(0);
691                     HvPLACEHOLDERS(hv)--;
692                 } else {
693                     /* store */
694                     if (val != &PL_sv_placeholder)
695                         HvPLACEHOLDERS(hv)--;
696                 }
697                 HeVAL(entry) = val;
698             } else if (action & HV_FETCH_ISSTORE) {
699                 SvREFCNT_dec(HeVAL(entry));
700                 HeVAL(entry) = val;
701             }
702         } else if (HeVAL(entry) == &PL_sv_placeholder) {
703             /* if we find a placeholder, we pretend we haven't found
704                anything */
705             break;
706         }
707         if (flags & HVhek_FREEKEY)
708             Safefree(key);
709         if (return_svp) {
710             return entry ? (void *) &HeVAL(entry) : NULL;
711         }
712         return entry;
713     }
714 #ifdef DYNAMIC_ENV_FETCH  /* %ENV lookup?  If so, try to fetch the value now */
715     if (!(action & HV_FETCH_ISSTORE) 
716         && SvRMAGICAL((const SV *)hv)
717         && mg_find((const SV *)hv, PERL_MAGIC_env)) {
718         unsigned long len;
719         const char * const env = PerlEnv_ENVgetenv_len(key,&len);
720         if (env) {
721             sv = newSVpvn(env,len);
722             SvTAINTED_on(sv);
723             return hv_common(hv, keysv, key, klen, flags,
724                              HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
725                              sv, hash);
726         }
727     }
728 #endif
729
730     if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
731         hv_notallowed(flags, key, klen,
732                         "Attempt to access disallowed key '%"SVf"' in"
733                         " a restricted hash");
734     }
735     if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
736         /* Not doing some form of store, so return failure.  */
737         if (flags & HVhek_FREEKEY)
738             Safefree(key);
739         return NULL;
740     }
741     if (action & HV_FETCH_LVALUE) {
742         val = action & HV_FETCH_EMPTY_HE ? NULL : newSV(0);
743         if (SvMAGICAL(hv)) {
744             /* At this point the old hv_fetch code would call to hv_store,
745                which in turn might do some tied magic. So we need to make that
746                magic check happen.  */
747             /* gonna assign to this, so it better be there */
748             /* If a fetch-as-store fails on the fetch, then the action is to
749                recurse once into "hv_store". If we didn't do this, then that
750                recursive call would call the key conversion routine again.
751                However, as we replace the original key with the converted
752                key, this would result in a double conversion, which would show
753                up as a bug if the conversion routine is not idempotent.
754                Hence the use of HV_DISABLE_UVAR_XKEY.  */
755             return hv_common(hv, keysv, key, klen, flags,
756                              HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
757                              val, hash);
758             /* XXX Surely that could leak if the fetch-was-store fails?
759                Just like the hv_fetch.  */
760         }
761     }
762
763     /* Welcome to hv_store...  */
764
765     if (!HvARRAY(hv)) {
766         /* Not sure if we can get here.  I think the only case of oentry being
767            NULL is for %ENV with dynamic env fetch.  But that should disappear
768            with magic in the previous code.  */
769         char *array;
770         Newxz(array,
771              PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
772              char);
773         HvARRAY(hv) = (HE**)array;
774     }
775
776     oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
777
778     entry = new_HE();
779     /* share_hek_flags will do the free for us.  This might be considered
780        bad API design.  */
781     if (HvSHAREKEYS(hv))
782         HeKEY_hek(entry) = share_hek_flags(key, klen, hash, flags);
783     else if (hv == PL_strtab) {
784         /* PL_strtab is usually the only hash without HvSHAREKEYS, so putting
785            this test here is cheap  */
786         if (flags & HVhek_FREEKEY)
787             Safefree(key);
788         Perl_croak(aTHX_ S_strtab_error,
789                    action & HV_FETCH_LVALUE ? "fetch" : "store");
790     }
791     else                                       /* gotta do the real thing */
792         HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
793     HeVAL(entry) = val;
794
795     if (!*oentry && SvOOK(hv)) {
796         /* initial entry, and aux struct present.  */
797         struct xpvhv_aux *const aux = HvAUX(hv);
798         if (aux->xhv_fill_lazy)
799             ++aux->xhv_fill_lazy;
800     }
801
802 #ifdef PERL_HASH_RANDOMIZE_KEYS
803     /* This logic semi-randomizes the insert order in a bucket.
804      * Either we insert into the top, or the slot below the top,
805      * making it harder to see if there is a collision. We also
806      * reset the iterator randomizer if there is one.
807      */
808     if ( *oentry && PL_HASH_RAND_BITS_ENABLED) {
809         PL_hash_rand_bits++;
810         PL_hash_rand_bits= ROTL_UV(PL_hash_rand_bits,1);
811         if ( PL_hash_rand_bits & 1 ) {
812             HeNEXT(entry) = HeNEXT(*oentry);
813             HeNEXT(*oentry) = entry;
814         } else {
815             HeNEXT(entry) = *oentry;
816             *oentry = entry;
817         }
818     } else
819 #endif
820     {
821         HeNEXT(entry) = *oentry;
822         *oentry = entry;
823     }
824 #ifdef PERL_HASH_RANDOMIZE_KEYS
825     if (SvOOK(hv)) {
826         /* Currently this makes various tests warn in annoying ways.
827          * So Silenced for now. - Yves | bogus end of comment =>* /
828         if (HvAUX(hv)->xhv_riter != -1) {
829             Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
830                              "[TESTING] Inserting into a hash during each() traversal results in undefined behavior"
831                              pTHX__FORMAT
832                              pTHX__VALUE);
833         }
834         */
835         if (PL_HASH_RAND_BITS_ENABLED) {
836             if (PL_HASH_RAND_BITS_ENABLED == 1)
837                 PL_hash_rand_bits += (PTRV)entry + 1;  /* we don't bother to use ptr_hash here */
838             PL_hash_rand_bits= ROTL_UV(PL_hash_rand_bits,1);
839         }
840         HvAUX(hv)->xhv_rand= (U32)PL_hash_rand_bits;
841     }
842 #endif
843
844     if (val == &PL_sv_placeholder)
845         HvPLACEHOLDERS(hv)++;
846     if (masked_flags & HVhek_ENABLEHVKFLAGS)
847         HvHASKFLAGS_on(hv);
848
849     xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
850     if ( DO_HSPLIT(xhv) ) {
851         const STRLEN oldsize = xhv->xhv_max + 1;
852         const U32 items = (U32)HvPLACEHOLDERS_get(hv);
853
854         if (items /* hash has placeholders  */
855             && !SvREADONLY(hv) /* but is not a restricted hash */) {
856             /* If this hash previously was a "restricted hash" and had
857                placeholders, but the "restricted" flag has been turned off,
858                then the placeholders no longer serve any useful purpose.
859                However, they have the downsides of taking up RAM, and adding
860                extra steps when finding used values. It's safe to clear them
861                at this point, even though Storable rebuilds restricted hashes by
862                putting in all the placeholders (first) before turning on the
863                readonly flag, because Storable always pre-splits the hash.
864                If we're lucky, then we may clear sufficient placeholders to
865                avoid needing to split the hash at all.  */
866             clear_placeholders(hv, items);
867             if (DO_HSPLIT(xhv))
868                 hsplit(hv, oldsize, oldsize * 2);
869         } else
870             hsplit(hv, oldsize, oldsize * 2);
871     }
872
873     if (return_svp) {
874         return entry ? (void *) &HeVAL(entry) : NULL;
875     }
876     return (void *) entry;
877 }
878
879 STATIC void
880 S_hv_magic_check(HV *hv, bool *needs_copy, bool *needs_store)
881 {
882     const MAGIC *mg = SvMAGIC(hv);
883
884     PERL_ARGS_ASSERT_HV_MAGIC_CHECK;
885
886     *needs_copy = FALSE;
887     *needs_store = TRUE;
888     while (mg) {
889         if (isUPPER(mg->mg_type)) {
890             *needs_copy = TRUE;
891             if (mg->mg_type == PERL_MAGIC_tied) {
892                 *needs_store = FALSE;
893                 return; /* We've set all there is to set. */
894             }
895         }
896         mg = mg->mg_moremagic;
897     }
898 }
899
900 /*
901 =for apidoc hv_scalar
902
903 Evaluates the hash in scalar context and returns the result.  Handles magic
904 when the hash is tied.
905
906 =cut
907 */
908
909 SV *
910 Perl_hv_scalar(pTHX_ HV *hv)
911 {
912     SV *sv;
913
914     PERL_ARGS_ASSERT_HV_SCALAR;
915
916     if (SvRMAGICAL(hv)) {
917         MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_tied);
918         if (mg)
919             return magic_scalarpack(hv, mg);
920     }
921
922     sv = sv_newmortal();
923     if (HvTOTALKEYS((const HV *)hv)) 
924         Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
925                 (long)HvFILL(hv), (long)HvMAX(hv) + 1);
926     else
927         sv_setiv(sv, 0);
928     
929     return sv;
930 }
931
932 /*
933 =for apidoc hv_delete
934
935 Deletes a key/value pair in the hash.  The value's SV is removed from
936 the hash, made mortal, and returned to the caller.  The absolute
937 value of C<klen> is the length of the key.  If C<klen> is negative the
938 key is assumed to be in UTF-8-encoded Unicode.  The C<flags> value
939 will normally be zero; if set to G_DISCARD then NULL will be returned.
940 NULL will also be returned if the key is not found.
941
942 =for apidoc hv_delete_ent
943
944 Deletes a key/value pair in the hash.  The value SV is removed from the hash,
945 made mortal, and returned to the caller.  The C<flags> value will normally be
946 zero; if set to G_DISCARD then NULL will be returned.  NULL will also be
947 returned if the key is not found.  C<hash> can be a valid precomputed hash
948 value, or 0 to ask for it to be computed.
949
950 =cut
951 */
952
953 STATIC SV *
954 S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
955                    int k_flags, I32 d_flags, U32 hash)
956 {
957     dVAR;
958     XPVHV* xhv;
959     HE *entry;
960     HE **oentry;
961     HE *const *first_entry;
962     bool is_utf8 = (k_flags & HVhek_UTF8) ? TRUE : FALSE;
963     int masked_flags;
964
965     if (SvRMAGICAL(hv)) {
966         bool needs_copy;
967         bool needs_store;
968         hv_magic_check (hv, &needs_copy, &needs_store);
969
970         if (needs_copy) {
971             SV *sv;
972             entry = (HE *) hv_common(hv, keysv, key, klen,
973                                      k_flags & ~HVhek_FREEKEY,
974                                      HV_FETCH_LVALUE|HV_DISABLE_UVAR_XKEY,
975                                      NULL, hash);
976             sv = entry ? HeVAL(entry) : NULL;
977             if (sv) {
978                 if (SvMAGICAL(sv)) {
979                     mg_clear(sv);
980                 }
981                 if (!needs_store) {
982                     if (mg_find(sv, PERL_MAGIC_tiedelem)) {
983                         /* No longer an element */
984                         sv_unmagic(sv, PERL_MAGIC_tiedelem);
985                         return sv;
986                     }           
987                     return NULL;                /* element cannot be deleted */
988                 }
989 #ifdef ENV_IS_CASELESS
990                 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
991                     /* XXX This code isn't UTF8 clean.  */
992                     keysv = newSVpvn_flags(key, klen, SVs_TEMP);
993                     if (k_flags & HVhek_FREEKEY) {
994                         Safefree(key);
995                     }
996                     key = strupr(SvPVX(keysv));
997                     is_utf8 = 0;
998                     k_flags = 0;
999                     hash = 0;
1000                 }
1001 #endif
1002             }
1003         }
1004     }
1005     xhv = (XPVHV*)SvANY(hv);
1006     if (!HvARRAY(hv))
1007         return NULL;
1008
1009     if (is_utf8 && !(k_flags & HVhek_KEYCANONICAL)) {
1010         const char * const keysave = key;
1011         key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
1012
1013         if (is_utf8)
1014             k_flags |= HVhek_UTF8;
1015         else
1016             k_flags &= ~HVhek_UTF8;
1017         if (key != keysave) {
1018             if (k_flags & HVhek_FREEKEY) {
1019                 /* This shouldn't happen if our caller does what we expect,
1020                    but strictly the API allows it.  */
1021                 Safefree(keysave);
1022             }
1023             k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
1024         }
1025         HvHASKFLAGS_on(MUTABLE_SV(hv));
1026     }
1027
1028     if (!hash) {
1029         if (keysv && (SvIsCOW_shared_hash(keysv)))
1030             hash = SvSHARED_HASH(keysv);
1031         else
1032             PERL_HASH(hash, key, klen);
1033     }
1034
1035     masked_flags = (k_flags & HVhek_MASK);
1036
1037     first_entry = oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
1038     entry = *oentry;
1039     for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
1040         SV *sv;
1041         U8 mro_changes = 0; /* 1 = isa; 2 = package moved */
1042         GV *gv = NULL;
1043         HV *stash = NULL;
1044
1045         if (HeHASH(entry) != hash)              /* strings can't be equal */
1046             continue;
1047         if (HeKLEN(entry) != (I32)klen)
1048             continue;
1049         if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen))        /* is this it? */
1050             continue;
1051         if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
1052             continue;
1053
1054         if (hv == PL_strtab) {
1055             if (k_flags & HVhek_FREEKEY)
1056                 Safefree(key);
1057             Perl_croak(aTHX_ S_strtab_error, "delete");
1058         }
1059
1060         /* if placeholder is here, it's already been deleted.... */
1061         if (HeVAL(entry) == &PL_sv_placeholder) {
1062             if (k_flags & HVhek_FREEKEY)
1063                 Safefree(key);
1064             return NULL;
1065         }
1066         if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1067             hv_notallowed(k_flags, key, klen,
1068                             "Attempt to delete readonly key '%"SVf"' from"
1069                             " a restricted hash");
1070         }
1071         if (k_flags & HVhek_FREEKEY)
1072             Safefree(key);
1073
1074         /* If this is a stash and the key ends with ::, then someone is 
1075          * deleting a package.
1076          */
1077         if (HeVAL(entry) && HvENAME_get(hv)) {
1078                 gv = (GV *)HeVAL(entry);
1079                 if (keysv) key = SvPV(keysv, klen);
1080                 if ((
1081                      (klen > 1 && key[klen-2] == ':' && key[klen-1] == ':')
1082                       ||
1083                      (klen == 1 && key[0] == ':')
1084                     )
1085                  && (klen != 6 || hv!=PL_defstash || memNE(key,"main::",6))
1086                  && SvTYPE(gv) == SVt_PVGV && (stash = GvHV((GV *)gv))
1087                  && HvENAME_get(stash)) {
1088                         /* A previous version of this code checked that the
1089                          * GV was still in the symbol table by fetching the
1090                          * GV with its name. That is not necessary (and
1091                          * sometimes incorrect), as HvENAME cannot be set
1092                          * on hv if it is not in the symtab. */
1093                         mro_changes = 2;
1094                         /* Hang on to it for a bit. */
1095                         SvREFCNT_inc_simple_void_NN(
1096                          sv_2mortal((SV *)gv)
1097                         );
1098                 }
1099                 else if (klen == 3 && strnEQ(key, "ISA", 3))
1100                     mro_changes = 1;
1101         }
1102
1103         sv = d_flags & G_DISCARD ? HeVAL(entry) : sv_2mortal(HeVAL(entry));
1104         HeVAL(entry) = &PL_sv_placeholder;
1105         if (sv) {
1106             /* deletion of method from stash */
1107             if (isGV(sv) && isGV_with_GP(sv) && GvCVu(sv)
1108              && HvENAME_get(hv))
1109                 mro_method_changed_in(hv);
1110         }
1111
1112         /*
1113          * If a restricted hash, rather than really deleting the entry, put
1114          * a placeholder there. This marks the key as being "approved", so
1115          * we can still access via not-really-existing key without raising
1116          * an error.
1117          */
1118         if (SvREADONLY(hv))
1119             /* We'll be saving this slot, so the number of allocated keys
1120              * doesn't go down, but the number placeholders goes up */
1121             HvPLACEHOLDERS(hv)++;
1122         else {
1123             *oentry = HeNEXT(entry);
1124             if(!*first_entry && SvOOK(hv)) {
1125                 /* removed last entry, and aux struct present.  */
1126                 struct xpvhv_aux *const aux = HvAUX(hv);
1127                 if (aux->xhv_fill_lazy)
1128                     --aux->xhv_fill_lazy;
1129             }
1130             if (SvOOK(hv) && entry == HvAUX(hv)->xhv_eiter /* HvEITER(hv) */)
1131                 HvLAZYDEL_on(hv);
1132             else {
1133                 if (SvOOK(hv) && HvLAZYDEL(hv) &&
1134                     entry == HeNEXT(HvAUX(hv)->xhv_eiter))
1135                     HeNEXT(HvAUX(hv)->xhv_eiter) = HeNEXT(entry);
1136                 hv_free_ent(hv, entry);
1137             }
1138             xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
1139             if (xhv->xhv_keys == 0)
1140                 HvHASKFLAGS_off(hv);
1141         }
1142
1143         if (d_flags & G_DISCARD) {
1144             SvREFCNT_dec(sv);
1145             sv = NULL;
1146         }
1147
1148         if (mro_changes == 1) mro_isa_changed_in(hv);
1149         else if (mro_changes == 2)
1150             mro_package_moved(NULL, stash, gv, 1);
1151
1152         return sv;
1153     }
1154     if (SvREADONLY(hv)) {
1155         hv_notallowed(k_flags, key, klen,
1156                         "Attempt to delete disallowed key '%"SVf"' from"
1157                         " a restricted hash");
1158     }
1159
1160     if (k_flags & HVhek_FREEKEY)
1161         Safefree(key);
1162     return NULL;
1163 }
1164
1165 STATIC void
1166 S_hsplit(pTHX_ HV *hv, STRLEN const oldsize, STRLEN newsize)
1167 {
1168     dVAR;
1169     STRLEN i = 0;
1170     char *a = (char*) HvARRAY(hv);
1171     HE **aep;
1172
1173     PERL_ARGS_ASSERT_HSPLIT;
1174
1175     /*PerlIO_printf(PerlIO_stderr(), "hsplit called for %p which had %d\n",
1176       (void*)hv, (int) oldsize);*/
1177
1178     PL_nomemok = TRUE;
1179     Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1180           + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1181     if (!a) {
1182       PL_nomemok = FALSE;
1183       return;
1184     }
1185 #ifdef PERL_HASH_RANDOMIZE_KEYS
1186     /* the idea of this is that we create a "random" value by hashing the address of
1187      * the array, we then use the low bit to decide if we insert at the top, or insert
1188      * second from top. After each such insert we rotate the hashed value. So we can
1189      * use the same hashed value over and over, and in normal build environments use
1190      * very few ops to do so. ROTL32() should produce a single machine operation. */
1191     if (PL_HASH_RAND_BITS_ENABLED) {
1192         if (PL_HASH_RAND_BITS_ENABLED == 1)
1193             PL_hash_rand_bits += ptr_hash((PTRV)a);
1194         PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,1);
1195     }
1196 #endif
1197
1198     if (SvOOK(hv)) {
1199         struct xpvhv_aux *const dest
1200             = (struct xpvhv_aux*) &a[newsize * sizeof(HE*)];
1201         Move(&a[oldsize * sizeof(HE*)], dest, 1, struct xpvhv_aux);
1202         /* we reset the iterator's xhv_rand as well, so they get a totally new ordering */
1203 #ifdef PERL_HASH_RANDOMIZE_KEYS
1204         dest->xhv_rand = (U32)PL_hash_rand_bits;
1205 #endif
1206         /* For now, just reset the lazy fill counter.
1207            It would be possible to update the counter in the code below
1208            instead.  */
1209         dest->xhv_fill_lazy = 0;
1210     }
1211
1212     PL_nomemok = FALSE;
1213     Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char);     /* zero 2nd half*/
1214     HvMAX(hv) = --newsize;
1215     HvARRAY(hv) = (HE**) a;
1216
1217     if (!HvTOTALKEYS(hv))       /* skip rest if no entries */
1218         return;
1219
1220     aep = (HE**)a;
1221     do {
1222         HE **oentry = aep + i;
1223         HE *entry = aep[i];
1224
1225         if (!entry)                             /* non-existent */
1226             continue;
1227         do {
1228             U32 j = (HeHASH(entry) & newsize);
1229             if (j != (U32)i) {
1230                 *oentry = HeNEXT(entry);
1231 #ifdef PERL_HASH_RANDOMIZE_KEYS
1232                 /* if the target cell is empty or PL_HASH_RAND_BITS_ENABLED is false
1233                  * insert to top, otherwise rotate the bucket rand 1 bit,
1234                  * and use the new low bit to decide if we insert at top,
1235                  * or next from top. IOW, we only rotate on a collision.*/
1236                 if (aep[j] && PL_HASH_RAND_BITS_ENABLED) {
1237                     PL_hash_rand_bits+= ROTL_UV(HeHASH(entry), 17);
1238                     PL_hash_rand_bits= ROTL_UV(PL_hash_rand_bits,1);
1239                     if (PL_hash_rand_bits & 1) {
1240                         HeNEXT(entry)= HeNEXT(aep[j]);
1241                         HeNEXT(aep[j])= entry;
1242                     } else {
1243                         /* Note, this is structured in such a way as the optimizer
1244                         * should eliminate the duplicated code here and below without
1245                         * us needing to explicitly use a goto. */
1246                         HeNEXT(entry) = aep[j];
1247                         aep[j] = entry;
1248                     }
1249                 } else
1250 #endif
1251                 {
1252                     /* see comment above about duplicated code */
1253                     HeNEXT(entry) = aep[j];
1254                     aep[j] = entry;
1255                 }
1256             }
1257             else {
1258                 oentry = &HeNEXT(entry);
1259             }
1260             entry = *oentry;
1261         } while (entry);
1262     } while (i++ < oldsize);
1263 }
1264
1265 void
1266 Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
1267 {
1268     dVAR;
1269     XPVHV* xhv = (XPVHV*)SvANY(hv);
1270     const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1271     I32 newsize;
1272     char *a;
1273
1274     PERL_ARGS_ASSERT_HV_KSPLIT;
1275
1276     newsize = (I32) newmax;                     /* possible truncation here */
1277     if (newsize != newmax || newmax <= oldsize)
1278         return;
1279     while ((newsize & (1 + ~newsize)) != newsize) {
1280         newsize &= ~(newsize & (1 + ~newsize)); /* get proper power of 2 */
1281     }
1282     if (newsize < newmax)
1283         newsize *= 2;
1284     if (newsize < newmax)
1285         return;                                 /* overflow detection */
1286
1287     a = (char *) HvARRAY(hv);
1288     if (a) {
1289         hsplit(hv, oldsize, newsize);
1290     } else {
1291         Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1292         xhv->xhv_max = --newsize;
1293         HvARRAY(hv) = (HE **) a;
1294     }
1295 }
1296
1297 /* IMO this should also handle cases where hv_max is smaller than hv_keys
1298  * as tied hashes could play silly buggers and mess us around. We will
1299  * do the right thing during hv_store() afterwards, but still - Yves */
1300 #define HV_SET_MAX_ADJUSTED_FOR_KEYS(hv,hv_max,hv_keys) STMT_START {\
1301     /* Can we use fewer buckets? (hv_max is always 2^n-1) */        \
1302     if (hv_max < PERL_HASH_DEFAULT_HvMAX) {                         \
1303         hv_max = PERL_HASH_DEFAULT_HvMAX;                           \
1304     } else {                                                        \
1305         while (hv_max > PERL_HASH_DEFAULT_HvMAX && hv_max + 1 >= hv_keys * 2) \
1306             hv_max = hv_max / 2;                                    \
1307     }                                                               \
1308     HvMAX(hv) = hv_max;                                             \
1309 } STMT_END
1310
1311
1312 HV *
1313 Perl_newHVhv(pTHX_ HV *ohv)
1314 {
1315     dVAR;
1316     HV * const hv = newHV();
1317     STRLEN hv_max;
1318
1319     if (!ohv || (!HvTOTALKEYS(ohv) && !SvMAGICAL((const SV *)ohv)))
1320         return hv;
1321     hv_max = HvMAX(ohv);
1322
1323     if (!SvMAGICAL((const SV *)ohv)) {
1324         /* It's an ordinary hash, so copy it fast. AMS 20010804 */
1325         STRLEN i;
1326         const bool shared = !!HvSHAREKEYS(ohv);
1327         HE **ents, ** const oents = (HE **)HvARRAY(ohv);
1328         char *a;
1329         Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
1330         ents = (HE**)a;
1331
1332         /* In each bucket... */
1333         for (i = 0; i <= hv_max; i++) {
1334             HE *prev = NULL;
1335             HE *oent = oents[i];
1336
1337             if (!oent) {
1338                 ents[i] = NULL;
1339                 continue;
1340             }
1341
1342             /* Copy the linked list of entries. */
1343             for (; oent; oent = HeNEXT(oent)) {
1344                 const U32 hash   = HeHASH(oent);
1345                 const char * const key = HeKEY(oent);
1346                 const STRLEN len = HeKLEN(oent);
1347                 const int flags  = HeKFLAGS(oent);
1348                 HE * const ent   = new_HE();
1349                 SV *const val    = HeVAL(oent);
1350
1351                 HeVAL(ent) = SvIMMORTAL(val) ? val : newSVsv(val);
1352                 HeKEY_hek(ent)
1353                     = shared ? share_hek_flags(key, len, hash, flags)
1354                              :  save_hek_flags(key, len, hash, flags);
1355                 if (prev)
1356                     HeNEXT(prev) = ent;
1357                 else
1358                     ents[i] = ent;
1359                 prev = ent;
1360                 HeNEXT(ent) = NULL;
1361             }
1362         }
1363
1364         HvMAX(hv)   = hv_max;
1365         HvTOTALKEYS(hv)  = HvTOTALKEYS(ohv);
1366         HvARRAY(hv) = ents;
1367     } /* not magical */
1368     else {
1369         /* Iterate over ohv, copying keys and values one at a time. */
1370         HE *entry;
1371         const I32 riter = HvRITER_get(ohv);
1372         HE * const eiter = HvEITER_get(ohv);
1373         STRLEN hv_keys = HvTOTALKEYS(ohv);
1374
1375         HV_SET_MAX_ADJUSTED_FOR_KEYS(hv,hv_max,hv_keys);
1376
1377         hv_iterinit(ohv);
1378         while ((entry = hv_iternext_flags(ohv, 0))) {
1379             SV *val = hv_iterval(ohv,entry);
1380             SV * const keysv = HeSVKEY(entry);
1381             val = SvIMMORTAL(val) ? val : newSVsv(val);
1382             if (keysv)
1383                 (void)hv_store_ent(hv, keysv, val, 0);
1384             else
1385                 (void)hv_store_flags(hv, HeKEY(entry), HeKLEN(entry), val,
1386                                  HeHASH(entry), HeKFLAGS(entry));
1387         }
1388         HvRITER_set(ohv, riter);
1389         HvEITER_set(ohv, eiter);
1390     }
1391
1392     return hv;
1393 }
1394
1395 /*
1396 =for apidoc Am|HV *|hv_copy_hints_hv|HV *ohv
1397
1398 A specialised version of L</newHVhv> for copying C<%^H>.  I<ohv> must be
1399 a pointer to a hash (which may have C<%^H> magic, but should be generally
1400 non-magical), or C<NULL> (interpreted as an empty hash).  The content
1401 of I<ohv> is copied to a new hash, which has the C<%^H>-specific magic
1402 added to it.  A pointer to the new hash is returned.
1403
1404 =cut
1405 */
1406
1407 HV *
1408 Perl_hv_copy_hints_hv(pTHX_ HV *const ohv)
1409 {
1410     HV * const hv = newHV();
1411
1412     if (ohv) {
1413         STRLEN hv_max = HvMAX(ohv);
1414         STRLEN hv_keys = HvTOTALKEYS(ohv);
1415         HE *entry;
1416         const I32 riter = HvRITER_get(ohv);
1417         HE * const eiter = HvEITER_get(ohv);
1418
1419         ENTER;
1420         SAVEFREESV(hv);
1421
1422         HV_SET_MAX_ADJUSTED_FOR_KEYS(hv,hv_max,hv_keys);
1423
1424         hv_iterinit(ohv);
1425         while ((entry = hv_iternext_flags(ohv, 0))) {
1426             SV *const sv = newSVsv(hv_iterval(ohv,entry));
1427             SV *heksv = HeSVKEY(entry);
1428             if (!heksv && sv) heksv = newSVhek(HeKEY_hek(entry));
1429             if (sv) sv_magic(sv, NULL, PERL_MAGIC_hintselem,
1430                      (char *)heksv, HEf_SVKEY);
1431             if (heksv == HeSVKEY(entry))
1432                 (void)hv_store_ent(hv, heksv, sv, 0);
1433             else {
1434                 (void)hv_common(hv, heksv, HeKEY(entry), HeKLEN(entry),
1435                                  HeKFLAGS(entry), HV_FETCH_ISSTORE|HV_FETCH_JUST_SV, sv, HeHASH(entry));
1436                 SvREFCNT_dec_NN(heksv);
1437             }
1438         }
1439         HvRITER_set(ohv, riter);
1440         HvEITER_set(ohv, eiter);
1441
1442         SvREFCNT_inc_simple_void_NN(hv);
1443         LEAVE;
1444     }
1445     hv_magic(hv, NULL, PERL_MAGIC_hints);
1446     return hv;
1447 }
1448 #undef HV_SET_MAX_ADJUSTED_FOR_KEYS
1449
1450 /* like hv_free_ent, but returns the SV rather than freeing it */
1451 STATIC SV*
1452 S_hv_free_ent_ret(pTHX_ HV *hv, HE *entry)
1453 {
1454     dVAR;
1455     SV *val;
1456
1457     PERL_ARGS_ASSERT_HV_FREE_ENT_RET;
1458
1459     val = HeVAL(entry);
1460     if (HeKLEN(entry) == HEf_SVKEY) {
1461         SvREFCNT_dec(HeKEY_sv(entry));
1462         Safefree(HeKEY_hek(entry));
1463     }
1464     else if (HvSHAREKEYS(hv))
1465         unshare_hek(HeKEY_hek(entry));
1466     else
1467         Safefree(HeKEY_hek(entry));
1468     del_HE(entry);
1469     return val;
1470 }
1471
1472
1473 void
1474 Perl_hv_free_ent(pTHX_ HV *hv, HE *entry)
1475 {
1476     dVAR;
1477     SV *val;
1478
1479     PERL_ARGS_ASSERT_HV_FREE_ENT;
1480
1481     if (!entry)
1482         return;
1483     val = hv_free_ent_ret(hv, entry);
1484     SvREFCNT_dec(val);
1485 }
1486
1487
1488 void
1489 Perl_hv_delayfree_ent(pTHX_ HV *hv, HE *entry)
1490 {
1491     dVAR;
1492
1493     PERL_ARGS_ASSERT_HV_DELAYFREE_ENT;
1494
1495     if (!entry)
1496         return;
1497     /* SvREFCNT_inc to counter the SvREFCNT_dec in hv_free_ent  */
1498     sv_2mortal(SvREFCNT_inc(HeVAL(entry)));     /* free between statements */
1499     if (HeKLEN(entry) == HEf_SVKEY) {
1500         sv_2mortal(SvREFCNT_inc(HeKEY_sv(entry)));
1501     }
1502     hv_free_ent(hv, entry);
1503 }
1504
1505 /*
1506 =for apidoc hv_clear
1507
1508 Frees the all the elements of a hash, leaving it empty.
1509 The XS equivalent of C<%hash = ()>.  See also L</hv_undef>.
1510
1511 If any destructors are triggered as a result, the hv itself may
1512 be freed.
1513
1514 =cut
1515 */
1516
1517 void
1518 Perl_hv_clear(pTHX_ HV *hv)
1519 {
1520     dVAR;
1521     XPVHV* xhv;
1522     if (!hv)
1523         return;
1524
1525     DEBUG_A(Perl_hv_assert(aTHX_ hv));
1526
1527     xhv = (XPVHV*)SvANY(hv);
1528
1529     ENTER;
1530     SAVEFREESV(SvREFCNT_inc_simple_NN(hv));
1531     if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
1532         /* restricted hash: convert all keys to placeholders */
1533         STRLEN i;
1534         for (i = 0; i <= xhv->xhv_max; i++) {
1535             HE *entry = (HvARRAY(hv))[i];
1536             for (; entry; entry = HeNEXT(entry)) {
1537                 /* not already placeholder */
1538                 if (HeVAL(entry) != &PL_sv_placeholder) {
1539                     if (HeVAL(entry)) {
1540                         if (SvREADONLY(HeVAL(entry))) {
1541                             SV* const keysv = hv_iterkeysv(entry);
1542                             Perl_croak_nocontext(
1543                                 "Attempt to delete readonly key '%"SVf"' from a restricted hash",
1544                                 (void*)keysv);
1545                         }
1546                         SvREFCNT_dec_NN(HeVAL(entry));
1547                     }
1548                     HeVAL(entry) = &PL_sv_placeholder;
1549                     HvPLACEHOLDERS(hv)++;
1550                 }
1551             }
1552         }
1553     }
1554     else {
1555         hfreeentries(hv);
1556         HvPLACEHOLDERS_set(hv, 0);
1557
1558         if (SvRMAGICAL(hv))
1559             mg_clear(MUTABLE_SV(hv));
1560
1561         HvHASKFLAGS_off(hv);
1562     }
1563     if (SvOOK(hv)) {
1564         if(HvENAME_get(hv))
1565             mro_isa_changed_in(hv);
1566         HvEITER_set(hv, NULL);
1567     }
1568     LEAVE;
1569 }
1570
1571 /*
1572 =for apidoc hv_clear_placeholders
1573
1574 Clears any placeholders from a hash.  If a restricted hash has any of its keys
1575 marked as readonly and the key is subsequently deleted, the key is not actually
1576 deleted but is marked by assigning it a value of &PL_sv_placeholder.  This tags
1577 it so it will be ignored by future operations such as iterating over the hash,
1578 but will still allow the hash to have a value reassigned to the key at some
1579 future point.  This function clears any such placeholder keys from the hash.
1580 See Hash::Util::lock_keys() for an example of its use.
1581
1582 =cut
1583 */
1584
1585 void
1586 Perl_hv_clear_placeholders(pTHX_ HV *hv)
1587 {
1588     dVAR;
1589     const U32 items = (U32)HvPLACEHOLDERS_get(hv);
1590
1591     PERL_ARGS_ASSERT_HV_CLEAR_PLACEHOLDERS;
1592
1593     if (items)
1594         clear_placeholders(hv, items);
1595 }
1596
1597 static void
1598 S_clear_placeholders(pTHX_ HV *hv, U32 items)
1599 {
1600     dVAR;
1601     I32 i;
1602
1603     PERL_ARGS_ASSERT_CLEAR_PLACEHOLDERS;
1604
1605     if (items == 0)
1606         return;
1607
1608     i = HvMAX(hv);
1609     do {
1610         /* Loop down the linked list heads  */
1611         HE **oentry = &(HvARRAY(hv))[i];
1612         HE *entry;
1613
1614         while ((entry = *oentry)) {
1615             if (HeVAL(entry) == &PL_sv_placeholder) {
1616                 *oentry = HeNEXT(entry);
1617                 if (entry == HvEITER_get(hv))
1618                     HvLAZYDEL_on(hv);
1619                 else {
1620                     if (SvOOK(hv) && HvLAZYDEL(hv) &&
1621                         entry == HeNEXT(HvAUX(hv)->xhv_eiter))
1622                         HeNEXT(HvAUX(hv)->xhv_eiter) = HeNEXT(entry);
1623                     hv_free_ent(hv, entry);
1624                 }
1625
1626                 if (--items == 0) {
1627                     /* Finished.  */
1628                     HvTOTALKEYS(hv) -= (IV)HvPLACEHOLDERS_get(hv);
1629                     if (HvUSEDKEYS(hv) == 0)
1630                         HvHASKFLAGS_off(hv);
1631                     HvPLACEHOLDERS_set(hv, 0);
1632                     return;
1633                 }
1634             } else {
1635                 oentry = &HeNEXT(entry);
1636             }
1637         }
1638     } while (--i >= 0);
1639     /* You can't get here, hence assertion should always fail.  */
1640     assert (items == 0);
1641     NOT_REACHED;
1642 }
1643
1644 STATIC void
1645 S_hfreeentries(pTHX_ HV *hv)
1646 {
1647     STRLEN index = 0;
1648     XPVHV * const xhv = (XPVHV*)SvANY(hv);
1649     SV *sv;
1650
1651     PERL_ARGS_ASSERT_HFREEENTRIES;
1652
1653     while ((sv = Perl_hfree_next_entry(aTHX_ hv, &index))||xhv->xhv_keys) {
1654         SvREFCNT_dec(sv);
1655     }
1656 }
1657
1658
1659 /* hfree_next_entry()
1660  * For use only by S_hfreeentries() and sv_clear().
1661  * Delete the next available HE from hv and return the associated SV.
1662  * Returns null on empty hash. Nevertheless null is not a reliable
1663  * indicator that the hash is empty, as the deleted entry may have a
1664  * null value.
1665  * indexp is a pointer to the current index into HvARRAY. The index should
1666  * initially be set to 0. hfree_next_entry() may update it.  */
1667
1668 SV*
1669 Perl_hfree_next_entry(pTHX_ HV *hv, STRLEN *indexp)
1670 {
1671     struct xpvhv_aux *iter;
1672     HE *entry;
1673     HE ** array;
1674 #ifdef DEBUGGING
1675     STRLEN orig_index = *indexp;
1676 #endif
1677
1678     PERL_ARGS_ASSERT_HFREE_NEXT_ENTRY;
1679
1680     if (SvOOK(hv) && ((iter = HvAUX(hv)))) {
1681         if ((entry = iter->xhv_eiter)) {
1682             /* the iterator may get resurrected after each
1683              * destructor call, so check each time */
1684             if (entry && HvLAZYDEL(hv)) {       /* was deleted earlier? */
1685                 HvLAZYDEL_off(hv);
1686                 hv_free_ent(hv, entry);
1687                 /* warning: at this point HvARRAY may have been
1688                  * re-allocated, HvMAX changed etc */
1689             }
1690             iter->xhv_riter = -1;       /* HvRITER(hv) = -1 */
1691             iter->xhv_eiter = NULL;     /* HvEITER(hv) = NULL */
1692 #ifdef PERL_HASH_RANDOMIZE_KEYS
1693             iter->xhv_last_rand = iter->xhv_rand;
1694 #endif
1695         }
1696         /* Reset any cached HvFILL() to "unknown".  It's unlikely that anyone
1697            will actually call HvFILL() on a hash under destruction, so it
1698            seems pointless attempting to track the number of keys remaining.
1699            But if they do, we want to reset it again.  */
1700         if (iter->xhv_fill_lazy)
1701             iter->xhv_fill_lazy = 0;
1702     }
1703
1704     if (!((XPVHV*)SvANY(hv))->xhv_keys)
1705         return NULL;
1706
1707     array = HvARRAY(hv);
1708     assert(array);
1709     while ( ! ((entry = array[*indexp])) ) {
1710         if ((*indexp)++ >= HvMAX(hv))
1711             *indexp = 0;
1712         assert(*indexp != orig_index);
1713     }
1714     array[*indexp] = HeNEXT(entry);
1715     ((XPVHV*) SvANY(hv))->xhv_keys--;
1716
1717     if (   PL_phase != PERL_PHASE_DESTRUCT && HvENAME(hv)
1718         && HeVAL(entry) && isGV(HeVAL(entry))
1719         && GvHV(HeVAL(entry)) && HvENAME(GvHV(HeVAL(entry)))
1720     ) {
1721         STRLEN klen;
1722         const char * const key = HePV(entry,klen);
1723         if ((klen > 1 && key[klen-1]==':' && key[klen-2]==':')
1724          || (klen == 1 && key[0] == ':')) {
1725             mro_package_moved(
1726              NULL, GvHV(HeVAL(entry)),
1727              (GV *)HeVAL(entry), 0
1728             );
1729         }
1730     }
1731     return hv_free_ent_ret(hv, entry);
1732 }
1733
1734
1735 /*
1736 =for apidoc hv_undef
1737
1738 Undefines the hash.  The XS equivalent of C<undef(%hash)>.
1739
1740 As well as freeing all the elements of the hash (like hv_clear()), this
1741 also frees any auxiliary data and storage associated with the hash.
1742
1743 If any destructors are triggered as a result, the hv itself may
1744 be freed.
1745
1746 See also L</hv_clear>.
1747
1748 =cut
1749 */
1750
1751 void
1752 Perl_hv_undef_flags(pTHX_ HV *hv, U32 flags)
1753 {
1754     dVAR;
1755     XPVHV* xhv;
1756     const bool save = !!SvREFCNT(hv);
1757
1758     if (!hv)
1759         return;
1760     DEBUG_A(Perl_hv_assert(aTHX_ hv));
1761     xhv = (XPVHV*)SvANY(hv);
1762
1763     /* The name must be deleted before the call to hfreeeeentries so that
1764        CVs are anonymised properly. But the effective name must be pre-
1765        served until after that call (and only deleted afterwards if the
1766        call originated from sv_clear). For stashes with one name that is
1767        both the canonical name and the effective name, hv_name_set has to
1768        allocate an array for storing the effective name. We can skip that
1769        during global destruction, as it does not matter where the CVs point
1770        if they will be freed anyway. */
1771     /* note that the code following prior to hfreeentries is duplicated
1772      * in sv_clear(), and changes here should be done there too */
1773     if (PL_phase != PERL_PHASE_DESTRUCT && HvNAME(hv)) {
1774         if (PL_stashcache) {
1775             DEBUG_o(Perl_deb(aTHX_ "hv_undef_flags clearing PL_stashcache for '%"
1776                              HEKf"'\n", HvNAME_HEK(hv)));
1777             (void)hv_deletehek(PL_stashcache, HvNAME_HEK(hv), G_DISCARD);
1778         }
1779         hv_name_set(hv, NULL, 0, 0);
1780     }
1781     if (save) {
1782         ENTER;
1783         SAVEFREESV(SvREFCNT_inc_simple_NN(hv));
1784     }
1785     hfreeentries(hv);
1786     if (SvOOK(hv)) {
1787       struct xpvhv_aux * const aux = HvAUX(hv);
1788       struct mro_meta *meta;
1789       const char *name;
1790
1791       if (HvENAME_get(hv)) {
1792         if (PL_phase != PERL_PHASE_DESTRUCT)
1793             mro_isa_changed_in(hv);
1794         if (PL_stashcache) {
1795             DEBUG_o(Perl_deb(aTHX_ "hv_undef_flags clearing PL_stashcache for effective name '%"
1796                              HEKf"'\n", HvENAME_HEK(hv)));
1797             (void)hv_deletehek(PL_stashcache, HvENAME_HEK(hv), G_DISCARD);
1798         }
1799       }
1800
1801       /* If this call originated from sv_clear, then we must check for
1802        * effective names that need freeing, as well as the usual name. */
1803       name = HvNAME(hv);
1804       if (flags & HV_NAME_SETALL ? !!aux->xhv_name_u.xhvnameu_name : !!name) {
1805         if (name && PL_stashcache) {
1806             DEBUG_o(Perl_deb(aTHX_ "hv_undef_flags clearing PL_stashcache for name '%"
1807                              HEKf"'\n", HvNAME_HEK(hv)));
1808             (void)hv_deletehek(PL_stashcache, HvNAME_HEK(hv), G_DISCARD);
1809         }
1810         hv_name_set(hv, NULL, 0, flags);
1811       }
1812       if((meta = aux->xhv_mro_meta)) {
1813         if (meta->mro_linear_all) {
1814             SvREFCNT_dec_NN(meta->mro_linear_all);
1815             /* mro_linear_current is just acting as a shortcut pointer,
1816                hence the else.  */
1817         }
1818         else
1819             /* Only the current MRO is stored, so this owns the data.
1820              */
1821             SvREFCNT_dec(meta->mro_linear_current);
1822         SvREFCNT_dec(meta->mro_nextmethod);
1823         SvREFCNT_dec(meta->isa);
1824         SvREFCNT_dec(meta->super);
1825         Safefree(meta);
1826         aux->xhv_mro_meta = NULL;
1827       }
1828       if (!aux->xhv_name_u.xhvnameu_name && ! aux->xhv_backreferences)
1829         SvFLAGS(hv) &= ~SVf_OOK;
1830     }
1831     if (!SvOOK(hv)) {
1832         Safefree(HvARRAY(hv));
1833         xhv->xhv_max = PERL_HASH_DEFAULT_HvMAX;        /* HvMAX(hv) = 7 (it's a normal hash) */
1834         HvARRAY(hv) = 0;
1835     }
1836     /* if we're freeing the HV, the SvMAGIC field has been reused for
1837      * other purposes, and so there can't be any placeholder magic */
1838     if (SvREFCNT(hv))
1839         HvPLACEHOLDERS_set(hv, 0);
1840
1841     if (SvRMAGICAL(hv))
1842         mg_clear(MUTABLE_SV(hv));
1843     if (save) LEAVE;
1844 }
1845
1846 /*
1847 =for apidoc hv_fill
1848
1849 Returns the number of hash buckets that
1850 happen to be in use.  This function is
1851 wrapped by the macro C<HvFILL>.
1852
1853 Previously this value was always stored in the HV structure, which created an
1854 overhead on every hash (and pretty much every object) for something that was
1855 rarely used.  Now we calculate it on demand the first
1856 time that it is needed, and cache it if that calculation
1857 is going to be costly to repeat.  The cached
1858 value is updated by insertions and deletions, but (currently) discarded if
1859 the hash is split.
1860
1861 =cut
1862 */
1863
1864 STRLEN
1865 Perl_hv_fill(pTHX_ HV *const hv)
1866 {
1867     STRLEN count = 0;
1868     HE **ents = HvARRAY(hv);
1869     struct xpvhv_aux *aux = SvOOK(hv) ? HvAUX(hv) : NULL;
1870
1871     PERL_ARGS_ASSERT_HV_FILL;
1872
1873     /* No keys implies no buckets used.
1874        One key can only possibly mean one bucket used.  */
1875     if (HvTOTALKEYS(hv) < 2)
1876         return HvTOTALKEYS(hv);
1877
1878 #ifndef DEBUGGING
1879     if (aux && aux->xhv_fill_lazy)
1880         return aux->xhv_fill_lazy;
1881 #endif
1882
1883     if (ents) {
1884         HE *const *const last = ents + HvMAX(hv);
1885         count = last + 1 - ents;
1886
1887         do {
1888             if (!*ents)
1889                 --count;
1890         } while (++ents <= last);
1891     }
1892     if (aux) {
1893 #ifdef DEBUGGING
1894         if (aux->xhv_fill_lazy)
1895             assert(aux->xhv_fill_lazy == count);
1896 #endif
1897         aux->xhv_fill_lazy = count;
1898     } else if (HvMAX(hv) >= HV_FILL_THRESHOLD) {
1899         aux = hv_auxinit(hv);
1900         aux->xhv_fill_lazy = count;
1901     }        
1902     return count;
1903 }
1904
1905 /* hash a pointer to a U32 - Used in the hash traversal randomization
1906  * and bucket order randomization code
1907  *
1908  * this code was derived from Sereal, which was derived from autobox.
1909  */
1910
1911 PERL_STATIC_INLINE U32 S_ptr_hash(PTRV u) {
1912 #if PTRSIZE == 8
1913     /*
1914      * This is one of Thomas Wang's hash functions for 64-bit integers from:
1915      * http://www.concentric.net/~Ttwang/tech/inthash.htm
1916      */
1917     u = (~u) + (u << 18);
1918     u = u ^ (u >> 31);
1919     u = u * 21;
1920     u = u ^ (u >> 11);
1921     u = u + (u << 6);
1922     u = u ^ (u >> 22);
1923 #else
1924     /*
1925      * This is one of Bob Jenkins' hash functions for 32-bit integers
1926      * from: http://burtleburtle.net/bob/hash/integer.html
1927      */
1928     u = (u + 0x7ed55d16) + (u << 12);
1929     u = (u ^ 0xc761c23c) ^ (u >> 19);
1930     u = (u + 0x165667b1) + (u << 5);
1931     u = (u + 0xd3a2646c) ^ (u << 9);
1932     u = (u + 0xfd7046c5) + (u << 3);
1933     u = (u ^ 0xb55a4f09) ^ (u >> 16);
1934 #endif
1935     return (U32)u;
1936 }
1937
1938
1939 static struct xpvhv_aux*
1940 S_hv_auxinit(pTHX_ HV *hv) {
1941     struct xpvhv_aux *iter;
1942     char *array;
1943
1944     PERL_ARGS_ASSERT_HV_AUXINIT;
1945
1946     if (!SvOOK(hv)) {
1947         if (!HvARRAY(hv)) {
1948             Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1949                 + sizeof(struct xpvhv_aux), char);
1950         } else {
1951             array = (char *) HvARRAY(hv);
1952             Renew(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1953                   + sizeof(struct xpvhv_aux), char);
1954         }
1955         HvARRAY(hv) = (HE**)array;
1956         SvOOK_on(hv);
1957         iter = HvAUX(hv);
1958 #ifdef PERL_HASH_RANDOMIZE_KEYS
1959         if (PL_HASH_RAND_BITS_ENABLED) {
1960             /* mix in some new state to PL_hash_rand_bits to "randomize" the traversal order*/
1961             if (PL_HASH_RAND_BITS_ENABLED == 1)
1962                 PL_hash_rand_bits += ptr_hash((PTRV)array);
1963             PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,1);
1964         }
1965         iter->xhv_rand = (U32)PL_hash_rand_bits;
1966 #endif
1967     } else {
1968         iter = HvAUX(hv);
1969     }
1970
1971     iter->xhv_riter = -1;       /* HvRITER(hv) = -1 */
1972     iter->xhv_eiter = NULL;     /* HvEITER(hv) = NULL */
1973 #ifdef PERL_HASH_RANDOMIZE_KEYS
1974     iter->xhv_last_rand = iter->xhv_rand;
1975 #endif
1976     iter->xhv_fill_lazy = 0;
1977     iter->xhv_name_u.xhvnameu_name = 0;
1978     iter->xhv_name_count = 0;
1979     iter->xhv_backreferences = 0;
1980     iter->xhv_mro_meta = NULL;
1981     return iter;
1982 }
1983
1984 /*
1985 =for apidoc hv_iterinit
1986
1987 Prepares a starting point to traverse a hash table.  Returns the number of
1988 keys in the hash (i.e. the same as C<HvUSEDKEYS(hv)>).  The return value is
1989 currently only meaningful for hashes without tie magic.
1990
1991 NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
1992 hash buckets that happen to be in use.  If you still need that esoteric
1993 value, you can get it through the macro C<HvFILL(hv)>.
1994
1995
1996 =cut
1997 */
1998
1999 I32
2000 Perl_hv_iterinit(pTHX_ HV *hv)
2001 {
2002     PERL_ARGS_ASSERT_HV_ITERINIT;
2003
2004     /* FIXME: Are we not NULL, or do we croak? Place bets now! */
2005
2006     if (!hv)
2007         Perl_croak(aTHX_ "Bad hash");
2008
2009     if (SvOOK(hv)) {
2010         struct xpvhv_aux * const iter = HvAUX(hv);
2011         HE * const entry = iter->xhv_eiter; /* HvEITER(hv) */
2012         if (entry && HvLAZYDEL(hv)) {   /* was deleted earlier? */
2013             HvLAZYDEL_off(hv);
2014             hv_free_ent(hv, entry);
2015         }
2016         iter->xhv_riter = -1;   /* HvRITER(hv) = -1 */
2017         iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
2018 #ifdef PERL_HASH_RANDOMIZE_KEYS
2019         iter->xhv_last_rand = iter->xhv_rand;
2020 #endif
2021     } else {
2022         hv_auxinit(hv);
2023     }
2024
2025     /* used to be xhv->xhv_fill before 5.004_65 */
2026     return HvTOTALKEYS(hv);
2027 }
2028
2029 I32 *
2030 Perl_hv_riter_p(pTHX_ HV *hv) {
2031     struct xpvhv_aux *iter;
2032
2033     PERL_ARGS_ASSERT_HV_RITER_P;
2034
2035     if (!hv)
2036         Perl_croak(aTHX_ "Bad hash");
2037
2038     iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2039     return &(iter->xhv_riter);
2040 }
2041
2042 HE **
2043 Perl_hv_eiter_p(pTHX_ HV *hv) {
2044     struct xpvhv_aux *iter;
2045
2046     PERL_ARGS_ASSERT_HV_EITER_P;
2047
2048     if (!hv)
2049         Perl_croak(aTHX_ "Bad hash");
2050
2051     iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2052     return &(iter->xhv_eiter);
2053 }
2054
2055 void
2056 Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
2057     struct xpvhv_aux *iter;
2058
2059     PERL_ARGS_ASSERT_HV_RITER_SET;
2060
2061     if (!hv)
2062         Perl_croak(aTHX_ "Bad hash");
2063
2064     if (SvOOK(hv)) {
2065         iter = HvAUX(hv);
2066     } else {
2067         if (riter == -1)
2068             return;
2069
2070         iter = hv_auxinit(hv);
2071     }
2072     iter->xhv_riter = riter;
2073 }
2074
2075 void
2076 Perl_hv_rand_set(pTHX_ HV *hv, U32 new_xhv_rand) {
2077     struct xpvhv_aux *iter;
2078
2079     PERL_ARGS_ASSERT_HV_RAND_SET;
2080
2081 #ifdef PERL_HASH_RANDOMIZE_KEYS
2082     if (!hv)
2083         Perl_croak(aTHX_ "Bad hash");
2084
2085     if (SvOOK(hv)) {
2086         iter = HvAUX(hv);
2087     } else {
2088         iter = hv_auxinit(hv);
2089     }
2090     iter->xhv_rand = new_xhv_rand;
2091 #else
2092     Perl_croak(aTHX_ "This Perl has not been built with support for randomized hash key traversal but something called Perl_hv_rand_set().");
2093 #endif
2094 }
2095
2096 void
2097 Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
2098     struct xpvhv_aux *iter;
2099
2100     PERL_ARGS_ASSERT_HV_EITER_SET;
2101
2102     if (!hv)
2103         Perl_croak(aTHX_ "Bad hash");
2104
2105     if (SvOOK(hv)) {
2106         iter = HvAUX(hv);
2107     } else {
2108         /* 0 is the default so don't go malloc()ing a new structure just to
2109            hold 0.  */
2110         if (!eiter)
2111             return;
2112
2113         iter = hv_auxinit(hv);
2114     }
2115     iter->xhv_eiter = eiter;
2116 }
2117
2118 void
2119 Perl_hv_name_set(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2120 {
2121     dVAR;
2122     struct xpvhv_aux *iter;
2123     U32 hash;
2124     HEK **spot;
2125
2126     PERL_ARGS_ASSERT_HV_NAME_SET;
2127
2128     if (len > I32_MAX)
2129         Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
2130
2131     if (SvOOK(hv)) {
2132         iter = HvAUX(hv);
2133         if (iter->xhv_name_u.xhvnameu_name) {
2134             if(iter->xhv_name_count) {
2135               if(flags & HV_NAME_SETALL) {
2136                 HEK ** const name = HvAUX(hv)->xhv_name_u.xhvnameu_names;
2137                 HEK **hekp = name + (
2138                     iter->xhv_name_count < 0
2139                      ? -iter->xhv_name_count
2140                      :  iter->xhv_name_count
2141                    );
2142                 while(hekp-- > name+1) 
2143                     unshare_hek_or_pvn(*hekp, 0, 0, 0);
2144                 /* The first elem may be null. */
2145                 if(*name) unshare_hek_or_pvn(*name, 0, 0, 0);
2146                 Safefree(name);
2147                 spot = &iter->xhv_name_u.xhvnameu_name;
2148                 iter->xhv_name_count = 0;
2149               }
2150               else {
2151                 if(iter->xhv_name_count > 0) {
2152                     /* shift some things over */
2153                     Renew(
2154                      iter->xhv_name_u.xhvnameu_names, iter->xhv_name_count + 1, HEK *
2155                     );
2156                     spot = iter->xhv_name_u.xhvnameu_names;
2157                     spot[iter->xhv_name_count] = spot[1];
2158                     spot[1] = spot[0];
2159                     iter->xhv_name_count = -(iter->xhv_name_count + 1);
2160                 }
2161                 else if(*(spot = iter->xhv_name_u.xhvnameu_names)) {
2162                     unshare_hek_or_pvn(*spot, 0, 0, 0);
2163                 }
2164               }
2165             }
2166             else if (flags & HV_NAME_SETALL) {
2167                 unshare_hek_or_pvn(iter->xhv_name_u.xhvnameu_name, 0, 0, 0);
2168                 spot = &iter->xhv_name_u.xhvnameu_name;
2169             }
2170             else {
2171                 HEK * const existing_name = iter->xhv_name_u.xhvnameu_name;
2172                 Newx(iter->xhv_name_u.xhvnameu_names, 2, HEK *);
2173                 iter->xhv_name_count = -2;
2174                 spot = iter->xhv_name_u.xhvnameu_names;
2175                 spot[1] = existing_name;
2176             }
2177         }
2178         else { spot = &iter->xhv_name_u.xhvnameu_name; iter->xhv_name_count = 0; }
2179     } else {
2180         if (name == 0)
2181             return;
2182
2183         iter = hv_auxinit(hv);
2184         spot = &iter->xhv_name_u.xhvnameu_name;
2185     }
2186     PERL_HASH(hash, name, len);
2187     *spot = name ? share_hek(name, flags & SVf_UTF8 ? -(I32)len : (I32)len, hash) : NULL;
2188 }
2189
2190 /*
2191 This is basically sv_eq_flags() in sv.c, but we avoid the magic
2192 and bytes checking.
2193 */
2194
2195 STATIC I32
2196 hek_eq_pvn_flags(pTHX_ const HEK *hek, const char* pv, const I32 pvlen, const U32 flags) {
2197     if ( (HEK_UTF8(hek) ? 1 : 0) != (flags & SVf_UTF8 ? 1 : 0) ) {
2198         if (flags & SVf_UTF8)
2199             return (bytes_cmp_utf8(
2200                         (const U8*)HEK_KEY(hek), HEK_LEN(hek),
2201                         (const U8*)pv, pvlen) == 0);
2202         else
2203             return (bytes_cmp_utf8(
2204                         (const U8*)pv, pvlen,
2205                         (const U8*)HEK_KEY(hek), HEK_LEN(hek)) == 0);
2206     }
2207     else
2208         return HEK_LEN(hek) == pvlen && ((HEK_KEY(hek) == pv)
2209                     || memEQ(HEK_KEY(hek), pv, pvlen));
2210 }
2211
2212 /*
2213 =for apidoc hv_ename_add
2214
2215 Adds a name to a stash's internal list of effective names.  See
2216 C<hv_ename_delete>.
2217
2218 This is called when a stash is assigned to a new location in the symbol
2219 table.
2220
2221 =cut
2222 */
2223
2224 void
2225 Perl_hv_ename_add(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2226 {
2227     dVAR;
2228     struct xpvhv_aux *aux = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2229     U32 hash;
2230
2231     PERL_ARGS_ASSERT_HV_ENAME_ADD;
2232
2233     if (len > I32_MAX)
2234         Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
2235
2236     PERL_HASH(hash, name, len);
2237
2238     if (aux->xhv_name_count) {
2239         HEK ** const xhv_name = aux->xhv_name_u.xhvnameu_names;
2240         I32 count = aux->xhv_name_count;
2241         HEK **hekp = xhv_name + (count < 0 ? -count : count);
2242         while (hekp-- > xhv_name)
2243             if (
2244                  (HEK_UTF8(*hekp) || (flags & SVf_UTF8)) 
2245                     ? hek_eq_pvn_flags(aTHX_ *hekp, name, (I32)len, flags)
2246                     : (HEK_LEN(*hekp) == (I32)len && memEQ(HEK_KEY(*hekp), name, len))
2247                ) {
2248                 if (hekp == xhv_name && count < 0)
2249                     aux->xhv_name_count = -count;
2250                 return;
2251             }
2252         if (count < 0) aux->xhv_name_count--, count = -count;
2253         else aux->xhv_name_count++;
2254         Renew(aux->xhv_name_u.xhvnameu_names, count + 1, HEK *);
2255         (aux->xhv_name_u.xhvnameu_names)[count] = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
2256     }
2257     else {
2258         HEK *existing_name = aux->xhv_name_u.xhvnameu_name;
2259         if (
2260             existing_name && (
2261              (HEK_UTF8(existing_name) || (flags & SVf_UTF8))
2262                 ? hek_eq_pvn_flags(aTHX_ existing_name, name, (I32)len, flags)
2263                 : (HEK_LEN(existing_name) == (I32)len && memEQ(HEK_KEY(existing_name), name, len))
2264             )
2265         ) return;
2266         Newx(aux->xhv_name_u.xhvnameu_names, 2, HEK *);
2267         aux->xhv_name_count = existing_name ? 2 : -2;
2268         *aux->xhv_name_u.xhvnameu_names = existing_name;
2269         (aux->xhv_name_u.xhvnameu_names)[1] = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
2270     }
2271 }
2272
2273 /*
2274 =for apidoc hv_ename_delete
2275
2276 Removes a name from a stash's internal list of effective names.  If this is
2277 the name returned by C<HvENAME>, then another name in the list will take
2278 its place (C<HvENAME> will use it).
2279
2280 This is called when a stash is deleted from the symbol table.
2281
2282 =cut
2283 */
2284
2285 void
2286 Perl_hv_ename_delete(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2287 {
2288     dVAR;
2289     struct xpvhv_aux *aux;
2290
2291     PERL_ARGS_ASSERT_HV_ENAME_DELETE;
2292
2293     if (len > I32_MAX)
2294         Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
2295
2296     if (!SvOOK(hv)) return;
2297
2298     aux = HvAUX(hv);
2299     if (!aux->xhv_name_u.xhvnameu_name) return;
2300
2301     if (aux->xhv_name_count) {
2302         HEK ** const namep = aux->xhv_name_u.xhvnameu_names;
2303         I32 const count = aux->xhv_name_count;
2304         HEK **victim = namep + (count < 0 ? -count : count);
2305         while (victim-- > namep + 1)
2306             if (
2307              (HEK_UTF8(*victim) || (flags & SVf_UTF8)) 
2308                 ? hek_eq_pvn_flags(aTHX_ *victim, name, (I32)len, flags)
2309                 : (HEK_LEN(*victim) == (I32)len && memEQ(HEK_KEY(*victim), name, len))
2310             ) {
2311                 unshare_hek_or_pvn(*victim, 0, 0, 0);
2312                 if (count < 0) ++aux->xhv_name_count;
2313                 else --aux->xhv_name_count;
2314                 if (
2315                     (aux->xhv_name_count == 1 || aux->xhv_name_count == -1)
2316                  && !*namep
2317                 ) {  /* if there are none left */
2318                     Safefree(namep);
2319                     aux->xhv_name_u.xhvnameu_names = NULL;
2320                     aux->xhv_name_count = 0;
2321                 }
2322                 else {
2323                     /* Move the last one back to fill the empty slot. It
2324                        does not matter what order they are in. */
2325                     *victim = *(namep + (count < 0 ? -count : count) - 1);
2326                 }
2327                 return;
2328             }
2329         if (
2330             count > 0 && (HEK_UTF8(*namep) || (flags & SVf_UTF8)) 
2331                 ? hek_eq_pvn_flags(aTHX_ *namep, name, (I32)len, flags)
2332                 : (HEK_LEN(*namep) == (I32)len && memEQ(HEK_KEY(*namep), name, len))
2333         ) {
2334             aux->xhv_name_count = -count;
2335         }
2336     }
2337     else if(
2338         (HEK_UTF8(aux->xhv_name_u.xhvnameu_name) || (flags & SVf_UTF8)) 
2339                 ? hek_eq_pvn_flags(aTHX_ aux->xhv_name_u.xhvnameu_name, name, (I32)len, flags)
2340                 : (HEK_LEN(aux->xhv_name_u.xhvnameu_name) == (I32)len &&
2341                             memEQ(HEK_KEY(aux->xhv_name_u.xhvnameu_name), name, len))
2342     ) {
2343         HEK * const namehek = aux->xhv_name_u.xhvnameu_name;
2344         Newx(aux->xhv_name_u.xhvnameu_names, 1, HEK *);
2345         *aux->xhv_name_u.xhvnameu_names = namehek;
2346         aux->xhv_name_count = -1;
2347     }
2348 }
2349
2350 AV **
2351 Perl_hv_backreferences_p(pTHX_ HV *hv) {
2352     struct xpvhv_aux * const iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2353
2354     PERL_ARGS_ASSERT_HV_BACKREFERENCES_P;
2355     PERL_UNUSED_CONTEXT;
2356
2357     return &(iter->xhv_backreferences);
2358 }
2359
2360 void
2361 Perl_hv_kill_backrefs(pTHX_ HV *hv) {
2362     AV *av;
2363
2364     PERL_ARGS_ASSERT_HV_KILL_BACKREFS;
2365
2366     if (!SvOOK(hv))
2367         return;
2368
2369     av = HvAUX(hv)->xhv_backreferences;
2370
2371     if (av) {
2372         HvAUX(hv)->xhv_backreferences = 0;
2373         Perl_sv_kill_backrefs(aTHX_ MUTABLE_SV(hv), av);
2374         if (SvTYPE(av) == SVt_PVAV)
2375             SvREFCNT_dec_NN(av);
2376     }
2377 }
2378
2379 /*
2380 hv_iternext is implemented as a macro in hv.h
2381
2382 =for apidoc hv_iternext
2383
2384 Returns entries from a hash iterator.  See C<hv_iterinit>.
2385
2386 You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
2387 iterator currently points to, without losing your place or invalidating your
2388 iterator.  Note that in this case the current entry is deleted from the hash
2389 with your iterator holding the last reference to it.  Your iterator is flagged
2390 to free the entry on the next call to C<hv_iternext>, so you must not discard
2391 your iterator immediately else the entry will leak - call C<hv_iternext> to
2392 trigger the resource deallocation.
2393
2394 =for apidoc hv_iternext_flags
2395
2396 Returns entries from a hash iterator.  See C<hv_iterinit> and C<hv_iternext>.
2397 The C<flags> value will normally be zero; if HV_ITERNEXT_WANTPLACEHOLDERS is
2398 set the placeholders keys (for restricted hashes) will be returned in addition
2399 to normal keys.  By default placeholders are automatically skipped over.
2400 Currently a placeholder is implemented with a value that is
2401 C<&PL_sv_placeholder>.  Note that the implementation of placeholders and
2402 restricted hashes may change, and the implementation currently is
2403 insufficiently abstracted for any change to be tidy.
2404
2405 =cut
2406 */
2407
2408 HE *
2409 Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
2410 {
2411     dVAR;
2412     XPVHV* xhv;
2413     HE *entry;
2414     HE *oldentry;
2415     MAGIC* mg;
2416     struct xpvhv_aux *iter;
2417
2418     PERL_ARGS_ASSERT_HV_ITERNEXT_FLAGS;
2419
2420     if (!hv)
2421         Perl_croak(aTHX_ "Bad hash");
2422
2423     xhv = (XPVHV*)SvANY(hv);
2424
2425     if (!SvOOK(hv)) {
2426         /* Too many things (well, pp_each at least) merrily assume that you can
2427            call hv_iternext without calling hv_iterinit, so we'll have to deal
2428            with it.  */
2429         hv_iterinit(hv);
2430     }
2431     iter = HvAUX(hv);
2432
2433     oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2434     if (SvMAGICAL(hv) && SvRMAGICAL(hv)) {
2435         if ( ( mg = mg_find((const SV *)hv, PERL_MAGIC_tied) ) ) {
2436             SV * const key = sv_newmortal();
2437             if (entry) {
2438                 sv_setsv(key, HeSVKEY_force(entry));
2439                 SvREFCNT_dec(HeSVKEY(entry));       /* get rid of previous key */
2440                 HeSVKEY_set(entry, NULL);
2441             }
2442             else {
2443                 char *k;
2444                 HEK *hek;
2445
2446                 /* one HE per MAGICAL hash */
2447                 iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
2448                 HvLAZYDEL_on(hv); /* make sure entry gets freed */
2449                 Zero(entry, 1, HE);
2450                 Newxz(k, HEK_BASESIZE + sizeof(const SV *), char);
2451                 hek = (HEK*)k;
2452                 HeKEY_hek(entry) = hek;
2453                 HeKLEN(entry) = HEf_SVKEY;
2454             }
2455             magic_nextpack(MUTABLE_SV(hv),mg,key);
2456             if (SvOK(key)) {
2457                 /* force key to stay around until next time */
2458                 HeSVKEY_set(entry, SvREFCNT_inc_simple_NN(key));
2459                 return entry;               /* beware, hent_val is not set */
2460             }
2461             SvREFCNT_dec(HeVAL(entry));
2462             Safefree(HeKEY_hek(entry));
2463             del_HE(entry);
2464             iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
2465             HvLAZYDEL_off(hv);
2466             return NULL;
2467         }
2468     }
2469 #if defined(DYNAMIC_ENV_FETCH) && !defined(__riscos__)  /* set up %ENV for iteration */
2470     if (!entry && SvRMAGICAL((const SV *)hv)
2471         && mg_find((const SV *)hv, PERL_MAGIC_env)) {
2472         prime_env_iter();
2473 #ifdef VMS
2474         /* The prime_env_iter() on VMS just loaded up new hash values
2475          * so the iteration count needs to be reset back to the beginning
2476          */
2477         hv_iterinit(hv);
2478         iter = HvAUX(hv);
2479         oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2480 #endif
2481     }
2482 #endif
2483
2484     /* hv_iterinit now ensures this.  */
2485     assert (HvARRAY(hv));
2486
2487     /* At start of hash, entry is NULL.  */
2488     if (entry)
2489     {
2490         entry = HeNEXT(entry);
2491         if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2492             /*
2493              * Skip past any placeholders -- don't want to include them in
2494              * any iteration.
2495              */
2496             while (entry && HeVAL(entry) == &PL_sv_placeholder) {
2497                 entry = HeNEXT(entry);
2498             }
2499         }
2500     }
2501
2502 #ifdef PERL_HASH_RANDOMIZE_KEYS
2503     if (iter->xhv_last_rand != iter->xhv_rand) {
2504         if (iter->xhv_riter != -1) {
2505             Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
2506                              "Use of each() on hash after insertion without resetting hash iterator results in undefined behavior"
2507                              pTHX__FORMAT
2508                              pTHX__VALUE);
2509         }
2510         iter->xhv_last_rand = iter->xhv_rand;
2511     }
2512 #endif
2513
2514     /* Skip the entire loop if the hash is empty.   */
2515     if ((flags & HV_ITERNEXT_WANTPLACEHOLDERS)
2516         ? HvTOTALKEYS(hv) : HvUSEDKEYS(hv)) {
2517         while (!entry) {
2518             /* OK. Come to the end of the current list.  Grab the next one.  */
2519
2520             iter->xhv_riter++; /* HvRITER(hv)++ */
2521             if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
2522                 /* There is no next one.  End of the hash.  */
2523                 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2524 #ifdef PERL_HASH_RANDOMIZE_KEYS
2525                 iter->xhv_last_rand = iter->xhv_rand; /* reset xhv_last_rand so we can detect inserts during traversal */
2526 #endif
2527                 break;
2528             }
2529             entry = (HvARRAY(hv))[ PERL_HASH_ITER_BUCKET(iter) & xhv->xhv_max ];
2530
2531             if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2532                 /* If we have an entry, but it's a placeholder, don't count it.
2533                    Try the next.  */
2534                 while (entry && HeVAL(entry) == &PL_sv_placeholder)
2535                     entry = HeNEXT(entry);
2536             }
2537             /* Will loop again if this linked list starts NULL
2538                (for HV_ITERNEXT_WANTPLACEHOLDERS)
2539                or if we run through it and find only placeholders.  */
2540         }
2541     }
2542     else {
2543         iter->xhv_riter = -1;
2544 #ifdef PERL_HASH_RANDOMIZE_KEYS
2545         iter->xhv_last_rand = iter->xhv_rand;
2546 #endif
2547     }
2548
2549     if (oldentry && HvLAZYDEL(hv)) {            /* was deleted earlier? */
2550         HvLAZYDEL_off(hv);
2551         hv_free_ent(hv, oldentry);
2552     }
2553
2554     iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
2555     return entry;
2556 }
2557
2558 /*
2559 =for apidoc hv_iterkey
2560
2561 Returns the key from the current position of the hash iterator.  See
2562 C<hv_iterinit>.
2563
2564 =cut
2565 */
2566
2567 char *
2568 Perl_hv_iterkey(pTHX_ HE *entry, I32 *retlen)
2569 {
2570     PERL_ARGS_ASSERT_HV_ITERKEY;
2571
2572     if (HeKLEN(entry) == HEf_SVKEY) {
2573         STRLEN len;
2574         char * const p = SvPV(HeKEY_sv(entry), len);
2575         *retlen = len;
2576         return p;
2577     }
2578     else {
2579         *retlen = HeKLEN(entry);
2580         return HeKEY(entry);
2581     }
2582 }
2583
2584 /* unlike hv_iterval(), this always returns a mortal copy of the key */
2585 /*
2586 =for apidoc hv_iterkeysv
2587
2588 Returns the key as an C<SV*> from the current position of the hash
2589 iterator.  The return value will always be a mortal copy of the key.  Also
2590 see C<hv_iterinit>.
2591
2592 =cut
2593 */
2594
2595 SV *
2596 Perl_hv_iterkeysv(pTHX_ HE *entry)
2597 {
2598     PERL_ARGS_ASSERT_HV_ITERKEYSV;
2599
2600     return sv_2mortal(newSVhek(HeKEY_hek(entry)));
2601 }
2602
2603 /*
2604 =for apidoc hv_iterval
2605
2606 Returns the value from the current position of the hash iterator.  See
2607 C<hv_iterkey>.
2608
2609 =cut
2610 */
2611
2612 SV *
2613 Perl_hv_iterval(pTHX_ HV *hv, HE *entry)
2614 {
2615     PERL_ARGS_ASSERT_HV_ITERVAL;
2616
2617     if (SvRMAGICAL(hv)) {
2618         if (mg_find((const SV *)hv, PERL_MAGIC_tied)) {
2619             SV* const sv = sv_newmortal();
2620             if (HeKLEN(entry) == HEf_SVKEY)
2621                 mg_copy(MUTABLE_SV(hv), sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
2622             else
2623                 mg_copy(MUTABLE_SV(hv), sv, HeKEY(entry), HeKLEN(entry));
2624             return sv;
2625         }
2626     }
2627     return HeVAL(entry);
2628 }
2629
2630 /*
2631 =for apidoc hv_iternextsv
2632
2633 Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2634 operation.
2635
2636 =cut
2637 */
2638
2639 SV *
2640 Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
2641 {
2642     HE * const he = hv_iternext_flags(hv, 0);
2643
2644     PERL_ARGS_ASSERT_HV_ITERNEXTSV;
2645
2646     if (!he)
2647         return NULL;
2648     *key = hv_iterkey(he, retlen);
2649     return hv_iterval(hv, he);
2650 }
2651
2652 /*
2653
2654 Now a macro in hv.h
2655
2656 =for apidoc hv_magic
2657
2658 Adds magic to a hash.  See C<sv_magic>.
2659
2660 =cut
2661 */
2662
2663 /* possibly free a shared string if no one has access to it
2664  * len and hash must both be valid for str.
2665  */
2666 void
2667 Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
2668 {
2669     unshare_hek_or_pvn (NULL, str, len, hash);
2670 }
2671
2672
2673 void
2674 Perl_unshare_hek(pTHX_ HEK *hek)
2675 {
2676     assert(hek);
2677     unshare_hek_or_pvn(hek, NULL, 0, 0);
2678 }
2679
2680 /* possibly free a shared string if no one has access to it
2681    hek if non-NULL takes priority over the other 3, else str, len and hash
2682    are used.  If so, len and hash must both be valid for str.
2683  */
2684 STATIC void
2685 S_unshare_hek_or_pvn(pTHX_ const HEK *hek, const char *str, I32 len, U32 hash)
2686 {
2687     dVAR;
2688     XPVHV* xhv;
2689     HE *entry;
2690     HE **oentry;
2691     bool is_utf8 = FALSE;
2692     int k_flags = 0;
2693     const char * const save = str;
2694     struct shared_he *he = NULL;
2695
2696     if (hek) {
2697         /* Find the shared he which is just before us in memory.  */
2698         he = (struct shared_he *)(((char *)hek)
2699                                   - STRUCT_OFFSET(struct shared_he,
2700                                                   shared_he_hek));
2701
2702         /* Assert that the caller passed us a genuine (or at least consistent)
2703            shared hek  */
2704         assert (he->shared_he_he.hent_hek == hek);
2705
2706         if (he->shared_he_he.he_valu.hent_refcount - 1) {
2707             --he->shared_he_he.he_valu.hent_refcount;
2708             return;
2709         }
2710
2711         hash = HEK_HASH(hek);
2712     } else if (len < 0) {
2713         STRLEN tmplen = -len;
2714         is_utf8 = TRUE;
2715         /* See the note in hv_fetch(). --jhi */
2716         str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2717         len = tmplen;
2718         if (is_utf8)
2719             k_flags = HVhek_UTF8;
2720         if (str != save)
2721             k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2722     }
2723
2724     /* what follows was the moral equivalent of:
2725     if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
2726         if (--*Svp == NULL)
2727             hv_delete(PL_strtab, str, len, G_DISCARD, hash);
2728     } */
2729     xhv = (XPVHV*)SvANY(PL_strtab);
2730     /* assert(xhv_array != 0) */
2731     oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2732     if (he) {
2733         const HE *const he_he = &(he->shared_he_he);
2734         for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2735             if (entry == he_he)
2736                 break;
2737         }
2738     } else {
2739         const int flags_masked = k_flags & HVhek_MASK;
2740         for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2741             if (HeHASH(entry) != hash)          /* strings can't be equal */
2742                 continue;
2743             if (HeKLEN(entry) != len)
2744                 continue;
2745             if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len))     /* is this it? */
2746                 continue;
2747             if (HeKFLAGS(entry) != flags_masked)
2748                 continue;
2749             break;
2750         }
2751     }
2752
2753     if (entry) {
2754         if (--entry->he_valu.hent_refcount == 0) {
2755             *oentry = HeNEXT(entry);
2756             Safefree(entry);
2757             xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
2758         }
2759     }
2760
2761     if (!entry)
2762         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
2763                          "Attempt to free nonexistent shared string '%s'%s"
2764                          pTHX__FORMAT,
2765                          hek ? HEK_KEY(hek) : str,
2766                          ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
2767     if (k_flags & HVhek_FREEKEY)
2768         Safefree(str);
2769 }
2770
2771 /* get a (constant) string ptr from the global string table
2772  * string will get added if it is not already there.
2773  * len and hash must both be valid for str.
2774  */
2775 HEK *
2776 Perl_share_hek(pTHX_ const char *str, I32 len, U32 hash)
2777 {
2778     bool is_utf8 = FALSE;
2779     int flags = 0;
2780     const char * const save = str;
2781
2782     PERL_ARGS_ASSERT_SHARE_HEK;
2783
2784     if (len < 0) {
2785       STRLEN tmplen = -len;
2786       is_utf8 = TRUE;
2787       /* See the note in hv_fetch(). --jhi */
2788       str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2789       len = tmplen;
2790       /* If we were able to downgrade here, then than means that we were passed
2791          in a key which only had chars 0-255, but was utf8 encoded.  */
2792       if (is_utf8)
2793           flags = HVhek_UTF8;
2794       /* If we found we were able to downgrade the string to bytes, then
2795          we should flag that it needs upgrading on keys or each.  Also flag
2796          that we need share_hek_flags to free the string.  */
2797       if (str != save) {
2798           dVAR;
2799           PERL_HASH(hash, str, len);
2800           flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2801       }
2802     }
2803
2804     return share_hek_flags (str, len, hash, flags);
2805 }
2806
2807 STATIC HEK *
2808 S_share_hek_flags(pTHX_ const char *str, I32 len, U32 hash, int flags)
2809 {
2810     dVAR;
2811     HE *entry;
2812     const int flags_masked = flags & HVhek_MASK;
2813     const U32 hindex = hash & (I32) HvMAX(PL_strtab);
2814     XPVHV * const xhv = (XPVHV*)SvANY(PL_strtab);
2815
2816     PERL_ARGS_ASSERT_SHARE_HEK_FLAGS;
2817
2818     /* what follows is the moral equivalent of:
2819
2820     if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
2821         hv_store(PL_strtab, str, len, NULL, hash);
2822
2823         Can't rehash the shared string table, so not sure if it's worth
2824         counting the number of entries in the linked list
2825     */
2826
2827     /* assert(xhv_array != 0) */
2828     entry = (HvARRAY(PL_strtab))[hindex];
2829     for (;entry; entry = HeNEXT(entry)) {
2830         if (HeHASH(entry) != hash)              /* strings can't be equal */
2831             continue;
2832         if (HeKLEN(entry) != len)
2833             continue;
2834         if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2835             continue;
2836         if (HeKFLAGS(entry) != flags_masked)
2837             continue;
2838         break;
2839     }
2840
2841     if (!entry) {
2842         /* What used to be head of the list.
2843            If this is NULL, then we're the first entry for this slot, which
2844            means we need to increate fill.  */
2845         struct shared_he *new_entry;
2846         HEK *hek;
2847         char *k;
2848         HE **const head = &HvARRAY(PL_strtab)[hindex];
2849         HE *const next = *head;
2850
2851         /* We don't actually store a HE from the arena and a regular HEK.
2852            Instead we allocate one chunk of memory big enough for both,
2853            and put the HEK straight after the HE. This way we can find the
2854            HE directly from the HEK.
2855         */
2856
2857         Newx(k, STRUCT_OFFSET(struct shared_he,
2858                                 shared_he_hek.hek_key[0]) + len + 2, char);
2859         new_entry = (struct shared_he *)k;
2860         entry = &(new_entry->shared_he_he);
2861         hek = &(new_entry->shared_he_hek);
2862
2863         Copy(str, HEK_KEY(hek), len, char);
2864         HEK_KEY(hek)[len] = 0;
2865         HEK_LEN(hek) = len;
2866         HEK_HASH(hek) = hash;
2867         HEK_FLAGS(hek) = (unsigned char)flags_masked;
2868
2869         /* Still "point" to the HEK, so that other code need not know what
2870            we're up to.  */
2871         HeKEY_hek(entry) = hek;
2872         entry->he_valu.hent_refcount = 0;
2873         HeNEXT(entry) = next;
2874         *head = entry;
2875
2876         xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
2877         if (!next) {                    /* initial entry? */
2878         } else if ( DO_HSPLIT(xhv) ) {
2879             const STRLEN oldsize = xhv->xhv_max + 1;
2880             hsplit(PL_strtab, oldsize, oldsize * 2);
2881         }
2882     }
2883
2884     ++entry->he_valu.hent_refcount;
2885
2886     if (flags & HVhek_FREEKEY)
2887         Safefree(str);
2888
2889     return HeKEY_hek(entry);
2890 }
2891
2892 SSize_t *
2893 Perl_hv_placeholders_p(pTHX_ HV *hv)
2894 {
2895     dVAR;
2896     MAGIC *mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
2897
2898     PERL_ARGS_ASSERT_HV_PLACEHOLDERS_P;
2899
2900     if (!mg) {
2901         mg = sv_magicext(MUTABLE_SV(hv), 0, PERL_MAGIC_rhash, 0, 0, 0);
2902
2903         if (!mg) {
2904             Perl_die(aTHX_ "panic: hv_placeholders_p");
2905         }
2906     }
2907     return &(mg->mg_len);
2908 }
2909
2910
2911 I32
2912 Perl_hv_placeholders_get(pTHX_ const HV *hv)
2913 {
2914     dVAR;
2915     MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
2916
2917     PERL_ARGS_ASSERT_HV_PLACEHOLDERS_GET;
2918
2919     return mg ? mg->mg_len : 0;
2920 }
2921
2922 void
2923 Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
2924 {
2925     dVAR;
2926     MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
2927
2928     PERL_ARGS_ASSERT_HV_PLACEHOLDERS_SET;
2929
2930     if (mg) {
2931         mg->mg_len = ph;
2932     } else if (ph) {
2933         if (!sv_magicext(MUTABLE_SV(hv), 0, PERL_MAGIC_rhash, 0, 0, ph))
2934             Perl_die(aTHX_ "panic: hv_placeholders_set");
2935     }
2936     /* else we don't need to add magic to record 0 placeholders.  */
2937 }
2938
2939 STATIC SV *
2940 S_refcounted_he_value(pTHX_ const struct refcounted_he *he)
2941 {
2942     dVAR;
2943     SV *value;
2944
2945     PERL_ARGS_ASSERT_REFCOUNTED_HE_VALUE;
2946
2947     switch(he->refcounted_he_data[0] & HVrhek_typemask) {
2948     case HVrhek_undef:
2949         value = newSV(0);
2950         break;
2951     case HVrhek_delete:
2952         value = &PL_sv_placeholder;
2953         break;
2954     case HVrhek_IV:
2955         value = newSViv(he->refcounted_he_val.refcounted_he_u_iv);
2956         break;
2957     case HVrhek_UV:
2958         value = newSVuv(he->refcounted_he_val.refcounted_he_u_uv);
2959         break;
2960     case HVrhek_PV:
2961     case HVrhek_PV_UTF8:
2962         /* Create a string SV that directly points to the bytes in our
2963            structure.  */
2964         value = newSV_type(SVt_PV);
2965         SvPV_set(value, (char *) he->refcounted_he_data + 1);
2966         SvCUR_set(value, he->refcounted_he_val.refcounted_he_u_len);
2967         /* This stops anything trying to free it  */
2968         SvLEN_set(value, 0);
2969         SvPOK_on(value);
2970         SvREADONLY_on(value);
2971         if ((he->refcounted_he_data[0] & HVrhek_typemask) == HVrhek_PV_UTF8)
2972             SvUTF8_on(value);
2973         break;
2974     default:
2975         Perl_croak(aTHX_ "panic: refcounted_he_value bad flags %"UVxf,
2976                    (UV)he->refcounted_he_data[0]);
2977     }
2978     return value;
2979 }
2980
2981 /*
2982 =for apidoc m|HV *|refcounted_he_chain_2hv|const struct refcounted_he *c|U32 flags
2983
2984 Generates and returns a C<HV *> representing the content of a
2985 C<refcounted_he> chain.
2986 I<flags> is currently unused and must be zero.
2987
2988 =cut
2989 */
2990 HV *
2991 Perl_refcounted_he_chain_2hv(pTHX_ const struct refcounted_he *chain, U32 flags)
2992 {
2993     dVAR;
2994     HV *hv;
2995     U32 placeholders, max;
2996
2997     if (flags)
2998         Perl_croak(aTHX_ "panic: refcounted_he_chain_2hv bad flags %"UVxf,
2999             (UV)flags);
3000
3001     /* We could chase the chain once to get an idea of the number of keys,
3002        and call ksplit.  But for now we'll make a potentially inefficient
3003        hash with only 8 entries in its array.  */
3004     hv = newHV();
3005     max = HvMAX(hv);
3006     if (!HvARRAY(hv)) {
3007         char *array;
3008         Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(max + 1), char);
3009         HvARRAY(hv) = (HE**)array;
3010     }
3011
3012     placeholders = 0;
3013     while (chain) {
3014 #ifdef USE_ITHREADS
3015         U32 hash = chain->refcounted_he_hash;
3016 #else
3017         U32 hash = HEK_HASH(chain->refcounted_he_hek);
3018 #endif
3019         HE **oentry = &((HvARRAY(hv))[hash & max]);
3020         HE *entry = *oentry;
3021         SV *value;
3022
3023         for (; entry; entry = HeNEXT(entry)) {
3024             if (HeHASH(entry) == hash) {
3025                 /* We might have a duplicate key here.  If so, entry is older
3026                    than the key we've already put in the hash, so if they are
3027                    the same, skip adding entry.  */
3028 #ifdef USE_ITHREADS
3029                 const STRLEN klen = HeKLEN(entry);
3030                 const char *const key = HeKEY(entry);
3031                 if (klen == chain->refcounted_he_keylen
3032                     && (!!HeKUTF8(entry)
3033                         == !!(chain->refcounted_he_data[0] & HVhek_UTF8))
3034                     && memEQ(key, REF_HE_KEY(chain), klen))
3035                     goto next_please;
3036 #else
3037                 if (HeKEY_hek(entry) == chain->refcounted_he_hek)
3038                     goto next_please;
3039                 if (HeKLEN(entry) == HEK_LEN(chain->refcounted_he_hek)
3040                     && HeKUTF8(entry) == HEK_UTF8(chain->refcounted_he_hek)
3041                     && memEQ(HeKEY(entry), HEK_KEY(chain->refcounted_he_hek),
3042                              HeKLEN(entry)))
3043                     goto next_please;
3044 #endif
3045             }
3046         }
3047         assert (!entry);
3048         entry = new_HE();
3049
3050 #ifdef USE_ITHREADS
3051         HeKEY_hek(entry)
3052             = share_hek_flags(REF_HE_KEY(chain),
3053                               chain->refcounted_he_keylen,
3054                               chain->refcounted_he_hash,
3055                               (chain->refcounted_he_data[0]
3056                                & (HVhek_UTF8|HVhek_WASUTF8)));
3057 #else
3058         HeKEY_hek(entry) = share_hek_hek(chain->refcounted_he_hek);
3059 #endif
3060         value = refcounted_he_value(chain);
3061         if (value == &PL_sv_placeholder)
3062             placeholders++;
3063         HeVAL(entry) = value;
3064
3065         /* Link it into the chain.  */
3066         HeNEXT(entry) = *oentry;
3067         *oentry = entry;
3068
3069         HvTOTALKEYS(hv)++;
3070
3071     next_please:
3072         chain = chain->refcounted_he_next;
3073     }
3074
3075     if (placeholders) {
3076         clear_placeholders(hv, placeholders);
3077         HvTOTALKEYS(hv) -= placeholders;
3078     }
3079
3080     /* We could check in the loop to see if we encounter any keys with key
3081        flags, but it's probably not worth it, as this per-hash flag is only
3082        really meant as an optimisation for things like Storable.  */
3083     HvHASKFLAGS_on(hv);
3084     DEBUG_A(Perl_hv_assert(aTHX_ hv));
3085
3086     return hv;
3087 }
3088
3089 /*
3090 =for apidoc m|SV *|refcounted_he_fetch_pvn|const struct refcounted_he *chain|const char *keypv|STRLEN keylen|U32 hash|U32 flags
3091
3092 Search along a C<refcounted_he> chain for an entry with the key specified
3093 by I<keypv> and I<keylen>.  If I<flags> has the C<REFCOUNTED_HE_KEY_UTF8>
3094 bit set, the key octets are interpreted as UTF-8, otherwise they
3095 are interpreted as Latin-1.  I<hash> is a precomputed hash of the key
3096 string, or zero if it has not been precomputed.  Returns a mortal scalar
3097 representing the value associated with the key, or C<&PL_sv_placeholder>
3098 if there is no value associated with the key.
3099
3100 =cut
3101 */
3102
3103 SV *
3104 Perl_refcounted_he_fetch_pvn(pTHX_ const struct refcounted_he *chain,
3105                          const char *keypv, STRLEN keylen, U32 hash, U32 flags)
3106 {
3107     dVAR;
3108     U8 utf8_flag;
3109     PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_PVN;
3110
3111     if (flags & ~(REFCOUNTED_HE_KEY_UTF8|REFCOUNTED_HE_EXISTS))
3112         Perl_croak(aTHX_ "panic: refcounted_he_fetch_pvn bad flags %"UVxf,
3113             (UV)flags);
3114     if (!chain)
3115         return &PL_sv_placeholder;
3116     if (flags & REFCOUNTED_HE_KEY_UTF8) {
3117         /* For searching purposes, canonicalise to Latin-1 where possible. */
3118         const char *keyend = keypv + keylen, *p;
3119         STRLEN nonascii_count = 0;
3120         for (p = keypv; p != keyend; p++) {
3121             if (! UTF8_IS_INVARIANT(*p)) {
3122                 if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(p, keyend)) {
3123                     goto canonicalised_key;
3124                 }
3125                 nonascii_count++;
3126                 p++;
3127             }
3128         }
3129         if (nonascii_count) {
3130             char *q;
3131             const char *p = keypv, *keyend = keypv + keylen;
3132             keylen -= nonascii_count;
3133             Newx(q, keylen, char);
3134             SAVEFREEPV(q);
3135             keypv = q;
3136             for (; p != keyend; p++, q++) {
3137                 U8 c = (U8)*p;
3138                 if (UTF8_IS_INVARIANT(c)) {
3139                     *q = (char) c;
3140                 }
3141                 else {
3142                     p++;
3143                     *q = (char) TWO_BYTE_UTF8_TO_NATIVE(c, *p);
3144                 }
3145             }
3146         }
3147         flags &= ~REFCOUNTED_HE_KEY_UTF8;
3148         canonicalised_key: ;
3149     }
3150     utf8_flag = (flags & REFCOUNTED_HE_KEY_UTF8) ? HVhek_UTF8 : 0;
3151     if (!hash)
3152         PERL_HASH(hash, keypv, keylen);
3153
3154     for (; chain; chain = chain->refcounted_he_next) {
3155         if (
3156 #ifdef USE_ITHREADS
3157             hash == chain->refcounted_he_hash &&
3158             keylen == chain->refcounted_he_keylen &&
3159             memEQ(REF_HE_KEY(chain), keypv, keylen) &&
3160             utf8_flag == (chain->refcounted_he_data[0] & HVhek_UTF8)
3161 #else
3162             hash == HEK_HASH(chain->refcounted_he_hek) &&
3163             keylen == (STRLEN)HEK_LEN(chain->refcounted_he_hek) &&
3164             memEQ(HEK_KEY(chain->refcounted_he_hek), keypv, keylen) &&
3165             utf8_flag == (HEK_FLAGS(chain->refcounted_he_hek) & HVhek_UTF8)
3166 #endif
3167         ) {
3168             if (flags & REFCOUNTED_HE_EXISTS)
3169                 return (chain->refcounted_he_data[0] & HVrhek_typemask)
3170                     == HVrhek_delete
3171                     ? NULL : &PL_sv_yes;
3172             return sv_2mortal(refcounted_he_value(chain));
3173         }
3174     }
3175     return flags & REFCOUNTED_HE_EXISTS ? NULL : &PL_sv_placeholder;
3176 }
3177
3178 /*
3179 =for apidoc m|SV *|refcounted_he_fetch_pv|const struct refcounted_he *chain|const char *key|U32 hash|U32 flags
3180
3181 Like L</refcounted_he_fetch_pvn>, but takes a nul-terminated string
3182 instead of a string/length pair.
3183
3184 =cut
3185 */
3186
3187 SV *
3188 Perl_refcounted_he_fetch_pv(pTHX_ const struct refcounted_he *chain,
3189                          const char *key, U32 hash, U32 flags)
3190 {
3191     PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_PV;
3192     return refcounted_he_fetch_pvn(chain, key, strlen(key), hash, flags);
3193 }
3194
3195 /*
3196 =for apidoc m|SV *|refcounted_he_fetch_sv|const struct refcounted_he *chain|SV *key|U32 hash|U32 flags
3197
3198 Like L</refcounted_he_fetch_pvn>, but takes a Perl scalar instead of a
3199 string/length pair.
3200
3201 =cut
3202 */
3203
3204 SV *
3205 Perl_refcounted_he_fetch_sv(pTHX_ const struct refcounted_he *chain,
3206                          SV *key, U32 hash, U32 flags)
3207 {
3208     const char *keypv;
3209     STRLEN keylen;
3210     PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_SV;
3211     if (flags & REFCOUNTED_HE_KEY_UTF8)
3212         Perl_croak(aTHX_ "panic: refcounted_he_fetch_sv bad flags %"UVxf,
3213             (UV)flags);
3214     keypv = SvPV_const(key, keylen);
3215     if (SvUTF8(key))
3216         flags |= REFCOUNTED_HE_KEY_UTF8;
3217     if (!hash && SvIsCOW_shared_hash(key))
3218         hash = SvSHARED_HASH(key);
3219     return refcounted_he_fetch_pvn(chain, keypv, keylen, hash, flags);
3220 }
3221
3222 /*
3223 =for apidoc m|struct refcounted_he *|refcounted_he_new_pvn|struct refcounted_he *parent|const char *keypv|STRLEN keylen|U32 hash|SV *value|U32 flags
3224
3225 Creates a new C<refcounted_he>.  This consists of a single key/value
3226 pair and a reference to an existing C<refcounted_he> chain (which may
3227 be empty), and thus forms a longer chain.  When using the longer chain,
3228 the new key/value pair takes precedence over any entry for the same key
3229 further along the chain.
3230
3231 The new key is specified by I<keypv> and I<keylen>.  If I<flags> has
3232 the C<REFCOUNTED_HE_KEY_UTF8> bit set, the key octets are interpreted
3233 as UTF-8, otherwise they are interpreted as Latin-1.  I<hash> is
3234 a precomputed hash of the key string, or zero if it has not been
3235 precomputed.
3236
3237 I<value> is the scalar value to store for this key.  I<value> is copied
3238 by this function, which thus does not take ownership of any reference
3239 to it, and later changes to the scalar will not be reflected in the
3240 value visible in the C<refcounted_he>.  Complex types of scalar will not
3241 be stored with referential integrity, but will be coerced to strings.
3242 I<value> may be either null or C<&PL_sv_placeholder> to indicate that no
3243 value is to be associated with the key; this, as with any non-null value,
3244 takes precedence over the existence of a value for the key further along
3245 the chain.
3246
3247 I<parent> points to the rest of the C<refcounted_he> chain to be
3248 attached to the new C<refcounted_he>.  This function takes ownership
3249 of one reference to I<parent>, and returns one reference to the new
3250 C<refcounted_he>.
3251
3252 =cut
3253 */
3254
3255 struct refcounted_he *
3256 Perl_refcounted_he_new_pvn(pTHX_ struct refcounted_he *parent,
3257         const char *keypv, STRLEN keylen, U32 hash, SV *value, U32 flags)
3258 {
3259     dVAR;
3260     STRLEN value_len = 0;
3261     const char *value_p = NULL;
3262     bool is_pv;
3263     char value_type;
3264     char hekflags;
3265     STRLEN key_offset = 1;
3266     struct refcounted_he *he;
3267     PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_PVN;
3268
3269     if (!value || value == &PL_sv_placeholder) {
3270         value_type = HVrhek_delete;
3271     } else if (SvPOK(value)) {
3272         value_type = HVrhek_PV;
3273     } else if (SvIOK(value)) {
3274         value_type = SvUOK((const SV *)value) ? HVrhek_UV : HVrhek_IV;
3275     } else if (!SvOK(value)) {
3276         value_type = HVrhek_undef;
3277     } else {
3278         value_type = HVrhek_PV;
3279     }
3280     is_pv = value_type == HVrhek_PV;
3281     if (is_pv) {
3282         /* Do it this way so that the SvUTF8() test is after the SvPV, in case
3283            the value is overloaded, and doesn't yet have the UTF-8flag set.  */
3284         value_p = SvPV_const(value, value_len);
3285         if (SvUTF8(value))
3286             value_type = HVrhek_PV_UTF8;
3287         key_offset = value_len + 2;
3288     }
3289     hekflags = value_type;
3290
3291     if (flags & REFCOUNTED_HE_KEY_UTF8) {
3292         /* Canonicalise to Latin-1 where possible. */
3293         const char *keyend = keypv + keylen, *p;
3294         STRLEN nonascii_count = 0;
3295         for (p = keypv; p != keyend; p++) {
3296             if (! UTF8_IS_INVARIANT(*p)) {
3297                 if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(p, keyend)) {
3298                     goto canonicalised_key;
3299                 }
3300                 nonascii_count++;
3301                 p++;
3302             }
3303         }
3304         if (nonascii_count) {
3305             char *q;
3306             const char *p = keypv, *keyend = keypv + keylen;
3307             keylen -= nonascii_count;
3308             Newx(q, keylen, char);
3309             SAVEFREEPV(q);
3310             keypv = q;
3311             for (; p != keyend; p++, q++) {
3312                 U8 c = (U8)*p;
3313                 if (UTF8_IS_INVARIANT(c)) {
3314                     *q = (char) c;
3315                 }
3316                 else {
3317                     p++;
3318                     *q = (char) TWO_BYTE_UTF8_TO_NATIVE(c, *p);
3319                 }
3320             }
3321         }
3322         flags &= ~REFCOUNTED_HE_KEY_UTF8;
3323         canonicalised_key: ;
3324     }
3325     if (flags & REFCOUNTED_HE_KEY_UTF8)
3326         hekflags |= HVhek_UTF8;
3327     if (!hash)
3328         PERL_HASH(hash, keypv, keylen);
3329
3330 #ifdef USE_ITHREADS
3331     he = (struct refcounted_he*)
3332         PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
3333                              + keylen
3334                              + key_offset);
3335 #else
3336     he = (struct refcounted_he*)
3337         PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
3338                              + key_offset);
3339 #endif
3340
3341     he->refcounted_he_next = parent;
3342
3343     if (is_pv) {
3344         Copy(value_p, he->refcounted_he_data + 1, value_len + 1, char);
3345         he->refcounted_he_val.refcounted_he_u_len = value_len;
3346     } else if (value_type == HVrhek_IV) {
3347         he->refcounted_he_val.refcounted_he_u_iv = SvIVX(value);
3348     } else if (value_type == HVrhek_UV) {
3349         he->refcounted_he_val.refcounted_he_u_uv = SvUVX(value);
3350     }
3351
3352 #ifdef USE_ITHREADS
3353     he->refcounted_he_hash = hash;
3354     he->refcounted_he_keylen = keylen;
3355     Copy(keypv, he->refcounted_he_data + key_offset, keylen, char);
3356 #else
3357     he->refcounted_he_hek = share_hek_flags(keypv, keylen, hash, hekflags);
3358 #endif
3359
3360     he->refcounted_he_data[0] = hekflags;
3361     he->refcounted_he_refcnt = 1;
3362
3363     return he;
3364 }
3365
3366 /*
3367 =for apidoc m|struct refcounted_he *|refcounted_he_new_pv|struct refcounted_he *parent|const char *key|U32 hash|SV *value|U32 flags
3368
3369 Like L</refcounted_he_new_pvn>, but takes a nul-terminated string instead
3370 of a string/length pair.
3371
3372 =cut
3373 */
3374
3375 struct refcounted_he *
3376 Perl_refcounted_he_new_pv(pTHX_ struct refcounted_he *parent,
3377         const char *key, U32 hash, SV *value, U32 flags)
3378 {
3379     PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_PV;
3380     return refcounted_he_new_pvn(parent, key, strlen(key), hash, value, flags);
3381 }
3382
3383 /*
3384 =for apidoc m|struct refcounted_he *|refcounted_he_new_sv|struct refcounted_he *parent|SV *key|U32 hash|SV *value|U32 flags
3385
3386 Like L</refcounted_he_new_pvn>, but takes a Perl scalar instead of a
3387 string/length pair.
3388
3389 =cut
3390 */
3391
3392 struct refcounted_he *
3393 Perl_refcounted_he_new_sv(pTHX_ struct refcounted_he *parent,
3394         SV *key, U32 hash, SV *value, U32 flags)
3395 {
3396     const char *keypv;
3397     STRLEN keylen;
3398     PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_SV;
3399     if (flags & REFCOUNTED_HE_KEY_UTF8)
3400         Perl_croak(aTHX_ "panic: refcounted_he_new_sv bad flags %"UVxf,
3401             (UV)flags);
3402     keypv = SvPV_const(key, keylen);
3403     if (SvUTF8(key))
3404         flags |= REFCOUNTED_HE_KEY_UTF8;
3405     if (!hash && SvIsCOW_shared_hash(key))
3406         hash = SvSHARED_HASH(key);
3407     return refcounted_he_new_pvn(parent, keypv, keylen, hash, value, flags);
3408 }
3409
3410 /*
3411 =for apidoc m|void|refcounted_he_free|struct refcounted_he *he
3412
3413 Decrements the reference count of a C<refcounted_he> by one.  If the
3414 reference count reaches zero the structure's memory is freed, which
3415 (recursively) causes a reduction of its parent C<refcounted_he>'s
3416 reference count.  It is safe to pass a null pointer to this function:
3417 no action occurs in this case.
3418
3419 =cut
3420 */
3421
3422 void
3423 Perl_refcounted_he_free(pTHX_ struct refcounted_he *he) {
3424     dVAR;
3425     PERL_UNUSED_CONTEXT;
3426
3427     while (he) {
3428         struct refcounted_he *copy;
3429         U32 new_count;
3430
3431         HINTS_REFCNT_LOCK;
3432         new_count = --he->refcounted_he_refcnt;
3433         HINTS_REFCNT_UNLOCK;
3434         
3435         if (new_count) {
3436             return;
3437         }
3438
3439 #ifndef USE_ITHREADS
3440         unshare_hek_or_pvn (he->refcounted_he_hek, 0, 0, 0);
3441 #endif
3442         copy = he;
3443         he = he->refcounted_he_next;
3444         PerlMemShared_free(copy);
3445     }
3446 }
3447
3448 /*
3449 =for apidoc m|struct refcounted_he *|refcounted_he_inc|struct refcounted_he *he
3450
3451 Increment the reference count of a C<refcounted_he>.  The pointer to the
3452 C<refcounted_he> is also returned.  It is safe to pass a null pointer
3453 to this function: no action occurs and a null pointer is returned.
3454
3455 =cut
3456 */
3457
3458 struct refcounted_he *
3459 Perl_refcounted_he_inc(pTHX_ struct refcounted_he *he)
3460 {
3461     dVAR;
3462     if (he) {
3463         HINTS_REFCNT_LOCK;
3464         he->refcounted_he_refcnt++;
3465         HINTS_REFCNT_UNLOCK;
3466     }
3467     return he;
3468 }
3469
3470 /*
3471 =for apidoc cop_fetch_label
3472
3473 Returns the label attached to a cop.
3474 The flags pointer may be set to C<SVf_UTF8> or 0.
3475
3476 =cut
3477 */
3478
3479 /* pp_entereval is aware that labels are stored with a key ':' at the top of
3480    the linked list.  */
3481 const char *
3482 Perl_cop_fetch_label(pTHX_ COP *const cop, STRLEN *len, U32 *flags) {
3483     struct refcounted_he *const chain = cop->cop_hints_hash;
3484
3485     PERL_ARGS_ASSERT_COP_FETCH_LABEL;
3486
3487     if (!chain)
3488         return NULL;
3489 #ifdef USE_ITHREADS
3490     if (chain->refcounted_he_keylen != 1)
3491         return NULL;
3492     if (*REF_HE_KEY(chain) != ':')
3493         return NULL;
3494 #else
3495     if ((STRLEN)HEK_LEN(chain->refcounted_he_hek) != 1)
3496         return NULL;
3497     if (*HEK_KEY(chain->refcounted_he_hek) != ':')
3498         return NULL;
3499 #endif
3500     /* Stop anyone trying to really mess us up by adding their own value for
3501        ':' into %^H  */
3502     if ((chain->refcounted_he_data[0] & HVrhek_typemask) != HVrhek_PV
3503         && (chain->refcounted_he_data[0] & HVrhek_typemask) != HVrhek_PV_UTF8)
3504         return NULL;
3505
3506     if (len)
3507         *len = chain->refcounted_he_val.refcounted_he_u_len;
3508     if (flags) {
3509         *flags = ((chain->refcounted_he_data[0] & HVrhek_typemask)
3510                   == HVrhek_PV_UTF8) ? SVf_UTF8 : 0;
3511     }
3512     return chain->refcounted_he_data + 1;
3513 }
3514
3515 /*
3516 =for apidoc cop_store_label
3517
3518 Save a label into a C<cop_hints_hash>.
3519 You need to set flags to C<SVf_UTF8>
3520 for a utf-8 label.
3521
3522 =cut
3523 */
3524
3525 void
3526 Perl_cop_store_label(pTHX_ COP *const cop, const char *label, STRLEN len,
3527                      U32 flags)
3528 {
3529     SV *labelsv;
3530     PERL_ARGS_ASSERT_COP_STORE_LABEL;
3531
3532     if (flags & ~(SVf_UTF8))
3533         Perl_croak(aTHX_ "panic: cop_store_label illegal flag bits 0x%" UVxf,
3534                    (UV)flags);
3535     labelsv = newSVpvn_flags(label, len, SVs_TEMP);
3536     if (flags & SVf_UTF8)
3537         SvUTF8_on(labelsv);
3538     cop->cop_hints_hash
3539         = refcounted_he_new_pvs(cop->cop_hints_hash, ":", labelsv, 0);
3540 }
3541
3542 /*
3543 =for apidoc hv_assert
3544
3545 Check that a hash is in an internally consistent state.
3546
3547 =cut
3548 */
3549
3550 #ifdef DEBUGGING
3551
3552 void
3553 Perl_hv_assert(pTHX_ HV *hv)
3554 {
3555     dVAR;
3556     HE* entry;
3557     int withflags = 0;
3558     int placeholders = 0;
3559     int real = 0;
3560     int bad = 0;
3561     const I32 riter = HvRITER_get(hv);
3562     HE *eiter = HvEITER_get(hv);
3563
3564     PERL_ARGS_ASSERT_HV_ASSERT;
3565
3566     (void)hv_iterinit(hv);
3567
3568     while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
3569         /* sanity check the values */
3570         if (HeVAL(entry) == &PL_sv_placeholder)
3571             placeholders++;
3572         else
3573             real++;
3574         /* sanity check the keys */
3575         if (HeSVKEY(entry)) {
3576             NOOP;   /* Don't know what to check on SV keys.  */
3577         } else if (HeKUTF8(entry)) {
3578             withflags++;
3579             if (HeKWASUTF8(entry)) {
3580                 PerlIO_printf(Perl_debug_log,
3581                             "hash key has both WASUTF8 and UTF8: '%.*s'\n",
3582                             (int) HeKLEN(entry),  HeKEY(entry));
3583                 bad = 1;
3584             }
3585         } else if (HeKWASUTF8(entry))
3586             withflags++;
3587     }
3588     if (!SvTIED_mg((const SV *)hv, PERL_MAGIC_tied)) {
3589         static const char bad_count[] = "Count %d %s(s), but hash reports %d\n";
3590         const int nhashkeys = HvUSEDKEYS(hv);
3591         const int nhashplaceholders = HvPLACEHOLDERS_get(hv);
3592
3593         if (nhashkeys != real) {
3594             PerlIO_printf(Perl_debug_log, bad_count, real, "keys", nhashkeys );
3595             bad = 1;
3596         }
3597         if (nhashplaceholders != placeholders) {
3598             PerlIO_printf(Perl_debug_log, bad_count, placeholders, "placeholder", nhashplaceholders );
3599             bad = 1;
3600         }
3601     }
3602     if (withflags && ! HvHASKFLAGS(hv)) {
3603         PerlIO_printf(Perl_debug_log,
3604                     "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
3605                     withflags);
3606         bad = 1;
3607     }
3608     if (bad) {
3609         sv_dump(MUTABLE_SV(hv));
3610     }
3611     HvRITER_set(hv, riter);             /* Restore hash iterator state */
3612     HvEITER_set(hv, eiter);
3613 }
3614
3615 #endif
3616
3617 /*
3618  * Local variables:
3619  * c-indentation-style: bsd
3620  * c-basic-offset: 4
3621  * indent-tabs-mode: nil
3622  * End:
3623  *
3624  * ex: set ts=8 sts=4 sw=4 et:
3625  */