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