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