Ooops. left an XXX comment in, and worse still it's a // comment
[p5sagit/p5-mst-13.2.git] / hv.c
1 /*    hv.c
2  *
3  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4  *    2000, 2001, 2002, 2003, 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 of all that I have seen."  --Bilbo
13  */
14
15 /* 
16 =head1 Hash Manipulation Functions
17 */
18
19 #include "EXTERN.h"
20 #define PERL_IN_HV_C
21 #define PERL_HASH_INTERNAL_ACCESS
22 #include "perl.h"
23
24 #define HV_MAX_LENGTH_BEFORE_SPLIT 14
25
26 STATIC HE*
27 S_new_he(pTHX)
28 {
29     HE* he;
30     LOCK_SV_MUTEX;
31     if (!PL_he_root)
32         more_he();
33     he = PL_he_root;
34     PL_he_root = HeNEXT(he);
35     UNLOCK_SV_MUTEX;
36     return he;
37 }
38
39 STATIC void
40 S_del_he(pTHX_ HE *p)
41 {
42     LOCK_SV_MUTEX;
43     HeNEXT(p) = (HE*)PL_he_root;
44     PL_he_root = p;
45     UNLOCK_SV_MUTEX;
46 }
47
48 STATIC void
49 S_more_he(pTHX)
50 {
51     register HE* he;
52     register HE* heend;
53     XPV *ptr;
54     New(54, ptr, 1008/sizeof(XPV), XPV);
55     ptr->xpv_pv = (char*)PL_he_arenaroot;
56     PL_he_arenaroot = ptr;
57
58     he = (HE*)ptr;
59     heend = &he[1008 / sizeof(HE) - 1];
60     PL_he_root = ++he;
61     while (he < heend) {
62         HeNEXT(he) = (HE*)(he + 1);
63         he++;
64     }
65     HeNEXT(he) = 0;
66 }
67
68 #ifdef PURIFY
69
70 #define new_HE() (HE*)safemalloc(sizeof(HE))
71 #define del_HE(p) safefree((char*)p)
72
73 #else
74
75 #define new_HE() new_he()
76 #define del_HE(p) del_he(p)
77
78 #endif
79
80 STATIC HEK *
81 S_save_hek_flags(pTHX_ const char *str, I32 len, U32 hash, int flags)
82 {
83     char *k;
84     register HEK *hek;
85
86     New(54, k, HEK_BASESIZE + len + 2, char);
87     hek = (HEK*)k;
88     Copy(str, HEK_KEY(hek), len, char);
89     HEK_KEY(hek)[len] = 0;
90     HEK_LEN(hek) = len;
91     HEK_HASH(hek) = hash;
92     HEK_FLAGS(hek) = (unsigned char)flags;
93     return hek;
94 }
95
96 /* free the pool of temporary HE/HEK pairs retunrned by hv_fetch_ent
97  * for tied hashes */
98
99 void
100 Perl_free_tied_hv_pool(pTHX)
101 {
102     HE *ohe;
103     HE *he = PL_hv_fetch_ent_mh;
104     while (he) {
105         Safefree(HeKEY_hek(he));
106         ohe = he;
107         he = HeNEXT(he);
108         del_HE(ohe);
109     }
110     PL_hv_fetch_ent_mh = Nullhe;
111 }
112
113 #if defined(USE_ITHREADS)
114 HE *
115 Perl_he_dup(pTHX_ HE *e, bool shared, CLONE_PARAMS* param)
116 {
117     HE *ret;
118
119     if (!e)
120         return Nullhe;
121     /* look for it in the table first */
122     ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
123     if (ret)
124         return ret;
125
126     /* create anew and remember what it is */
127     ret = new_HE();
128     ptr_table_store(PL_ptr_table, e, ret);
129
130     HeNEXT(ret) = he_dup(HeNEXT(e),shared, param);
131     if (HeKLEN(e) == HEf_SVKEY) {
132         char *k;
133         New(54, k, HEK_BASESIZE + sizeof(SV*), char);
134         HeKEY_hek(ret) = (HEK*)k;
135         HeKEY_sv(ret) = SvREFCNT_inc(sv_dup(HeKEY_sv(e), param));
136     }
137     else if (shared)
138         HeKEY_hek(ret) = share_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
139                                          HeKFLAGS(e));
140     else
141         HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
142                                         HeKFLAGS(e));
143     HeVAL(ret) = SvREFCNT_inc(sv_dup(HeVAL(e), param));
144     return ret;
145 }
146 #endif  /* USE_ITHREADS */
147
148 static void
149 S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
150                 const char *msg)
151 {
152     SV *sv = sv_newmortal(), *esv = sv_newmortal();
153     if (!(flags & HVhek_FREEKEY)) {
154         sv_setpvn(sv, key, klen);
155     }
156     else {
157         /* Need to free saved eventually assign to mortal SV */
158         /* XXX is this line an error ???:  SV *sv = sv_newmortal(); */
159         sv_usepvn(sv, (char *) key, klen);
160     }
161     if (flags & HVhek_UTF8) {
162         SvUTF8_on(sv);
163     }
164     Perl_sv_setpvf(aTHX_ esv, "Attempt to %s a restricted hash", msg);
165     Perl_croak(aTHX_ SvPVX(esv), sv);
166 }
167
168 /* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
169  * contains an SV* */
170
171 /*
172 =for apidoc hv_fetch
173
174 Returns the SV which corresponds to the specified key in the hash.  The
175 C<klen> is the length of the key.  If C<lval> is set then the fetch will be
176 part of a store.  Check that the return value is non-null before
177 dereferencing it to an C<SV*>.
178
179 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
180 information on how to use this function on tied hashes.
181
182 =cut
183 */
184
185
186 SV**
187 Perl_hv_fetch(pTHX_ HV *hv, const char *key, I32 klen, I32 lval)
188 {
189     bool is_utf8 = FALSE;
190     const char *keysave = key;
191     int flags = 0;
192
193     if (klen < 0) {
194       klen = -klen;
195       is_utf8 = TRUE;
196     }
197
198     if (is_utf8) {
199         STRLEN tmplen = klen;
200         /* Just casting the &klen to (STRLEN) won't work well
201          * if STRLEN and I32 are of different widths. --jhi */
202         key = (char*)bytes_from_utf8((U8*)key, &tmplen, &is_utf8);
203         klen = tmplen;
204         /* If we were able to downgrade here, then than means that we were
205            passed in a key which only had chars 0-255, but was utf8 encoded.  */
206         if (is_utf8)
207             flags = HVhek_UTF8;
208         /* If we found we were able to downgrade the string to bytes, then
209            we should flag that it needs upgrading on keys or each.  */
210         if (key != keysave)
211             flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
212     }
213
214     return hv_fetch_flags (hv, key, klen, lval, flags);
215 }
216
217 STATIC SV**
218 S_hv_fetch_flags(pTHX_ HV *hv, const char *key, I32 klen, I32 lval, int flags)
219 {
220     register XPVHV* xhv;
221     register U32 hash;
222     register HE *entry;
223     SV *sv;
224
225     if (!hv)
226         return 0;
227
228     if (SvRMAGICAL(hv)) {
229         if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
230             sv = sv_newmortal();
231             sv_upgrade(sv, SVt_PVLV);
232             if (flags & HVhek_UTF8) {
233                 /* This hack based on the code in hv_exists_ent seems to be
234                    the easiest way to pass the utf8 flag through and fix
235                    the bug in hv_exists for tied hashes with utf8 keys.  */
236                 SV *keysv = sv_2mortal(newSVpvn(key, klen));
237                 SvUTF8_on(keysv);
238                 mg_copy((SV*)hv, sv, (char *)keysv, HEf_SVKEY);
239             } else {
240                 mg_copy((SV*)hv, sv, key, klen);
241             }
242             if (flags & HVhek_FREEKEY)
243                 Safefree(key);
244             LvTYPE(sv) = 't';
245             LvTARG(sv) = sv; /* fake (SV**) */
246             return &(LvTARG(sv));
247         }
248 #ifdef ENV_IS_CASELESS
249         else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
250             I32 i;
251             for (i = 0; i < klen; ++i)
252                 if (isLOWER(key[i])) {
253                     char *nkey = strupr(SvPVX(sv_2mortal(newSVpvn(key,klen))));
254                     SV **ret = hv_fetch(hv, nkey, klen, 0);
255                     if (!ret && lval) {
256                         ret = hv_store_flags(hv, key, klen, NEWSV(61,0), 0,
257                                              flags);
258                     } else if (flags & HVhek_FREEKEY)
259                         Safefree(key);
260                     return ret;
261                 }
262         }
263 #endif
264     }
265
266     /* We use xhv->xhv_foo fields directly instead of HvFOO(hv) to
267        avoid unnecessary pointer dereferencing. */
268     xhv = (XPVHV*)SvANY(hv);
269     if (!xhv->xhv_array /* !HvARRAY(hv) */) {
270         if (lval
271 #ifdef DYNAMIC_ENV_FETCH  /* if it's an %ENV lookup, we may get it on the fly */
272                  || (SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
273 #endif
274                                                                   )
275             Newz(503, xhv->xhv_array /* HvARRAY(hv) */,
276                  PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
277                  char);
278         else {
279             if (flags & HVhek_FREEKEY)
280                 Safefree(key);
281             return 0;
282         }
283     }
284
285     if (HvREHASH(hv)) {
286         PERL_HASH_INTERNAL(hash, key, klen);
287         /* Yes, you do need this even though you are not "storing" because
288            you can flip the flags below if doing an lval lookup.  (And that
289            was put in to give the semantics Andreas was expecting.)  */
290         flags |= HVhek_REHASH;
291     } else {
292         PERL_HASH(hash, key, klen);
293     }
294
295     /* entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)]; */
296     entry = ((HE**)xhv->xhv_array)[hash & (I32) xhv->xhv_max];
297     for (; entry; entry = HeNEXT(entry)) {
298         if (!HeKEY_hek(entry))
299             continue;
300         if (HeHASH(entry) != hash)              /* strings can't be equal */
301             continue;
302         if (HeKLEN(entry) != (I32)klen)
303             continue;
304         if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen))        /* is this it? */
305             continue;
306         /* flags is 0 if not utf8. need HeKFLAGS(entry) also 0.
307            flags is 1 if utf8. need HeKFLAGS(entry) also 1.
308            xor is true if bits differ, in which case this isn't a match.  */
309         if ((HeKFLAGS(entry) ^ flags) & HVhek_UTF8)
310             continue;
311         if (lval && HeKFLAGS(entry) != flags) {
312             /* We match if HVhek_UTF8 bit in our flags and hash key's match.
313                But if entry was set previously with HVhek_WASUTF8 and key now
314                doesn't (or vice versa) then we should change the key's flag,
315                as this is assignment.  */
316             if (HvSHAREKEYS(hv)) {
317                 /* Need to swap the key we have for a key with the flags we
318                    need. As keys are shared we can't just write to the flag,
319                    so we share the new one, unshare the old one.  */
320                 int flags_nofree = flags & ~HVhek_FREEKEY;
321                 HEK *new_hek = share_hek_flags(key, klen, hash, flags_nofree);
322                 unshare_hek (HeKEY_hek(entry));
323                 HeKEY_hek(entry) = new_hek;
324             }
325             else
326                 HeKFLAGS(entry) = flags;
327             if (flags & HVhek_ENABLEHVKFLAGS)
328                 HvHASKFLAGS_on(hv);
329         }
330         if (flags & HVhek_FREEKEY)
331             Safefree(key);
332         /* if we find a placeholder, we pretend we haven't found anything */
333         if (HeVAL(entry) == &PL_sv_placeholder)
334             break;
335         return &HeVAL(entry);
336
337     }
338 #ifdef DYNAMIC_ENV_FETCH  /* %ENV lookup?  If so, try to fetch the value now */
339     if (SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
340         unsigned long len;
341         char *env = PerlEnv_ENVgetenv_len(key,&len);
342         if (env) {
343             sv = newSVpvn(env,len);
344             SvTAINTED_on(sv);
345             if (flags & HVhek_FREEKEY)
346                 Safefree(key);
347             return hv_store(hv,key,klen,sv,hash);
348         }
349     }
350 #endif
351     if (!entry && SvREADONLY(hv)) {
352         S_hv_notallowed(aTHX_ flags, key, klen,
353                         "access disallowed key '%"SVf"' in"
354                         );
355     }
356     if (lval) {         /* gonna assign to this, so it better be there */
357         sv = NEWSV(61,0);
358         return hv_store_flags(hv,key,klen,sv,hash,flags);
359     }
360     if (flags & HVhek_FREEKEY)
361         Safefree(key);
362     return 0;
363 }
364
365 /* returns an HE * structure with the all fields set */
366 /* note that hent_val will be a mortal sv for MAGICAL hashes */
367 /*
368 =for apidoc hv_fetch_ent
369
370 Returns the hash entry which corresponds to the specified key in the hash.
371 C<hash> must be a valid precomputed hash number for the given C<key>, or 0
372 if you want the function to compute it.  IF C<lval> is set then the fetch
373 will be part of a store.  Make sure the return value is non-null before
374 accessing it.  The return value when C<tb> is a tied hash is a pointer to a
375 static location, so be sure to make a copy of the structure if you need to
376 store it somewhere.
377
378 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
379 information on how to use this function on tied hashes.
380
381 =cut
382 */
383
384 HE *
385 Perl_hv_fetch_ent(pTHX_ HV *hv, SV *keysv, I32 lval, register U32 hash)
386 {
387     register XPVHV* xhv;
388     register char *key;
389     STRLEN klen;
390     register HE *entry;
391     SV *sv;
392     bool is_utf8;
393     int flags = 0;
394     char *keysave;
395
396     if (!hv)
397         return 0;
398
399     if (SvRMAGICAL(hv)) {
400         if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
401             sv = sv_newmortal();
402             keysv = newSVsv(keysv);
403             mg_copy((SV*)hv, sv, (char*)keysv, HEf_SVKEY);
404             /* grab a fake HE/HEK pair from the pool or make a new one */
405             entry = PL_hv_fetch_ent_mh;
406             if (entry)
407                 PL_hv_fetch_ent_mh = HeNEXT(entry);
408             else {
409                 char *k;
410                 entry = new_HE();
411                 New(54, k, HEK_BASESIZE + sizeof(SV*), char);
412                 HeKEY_hek(entry) = (HEK*)k;
413             }
414             HeNEXT(entry) = Nullhe;
415             HeSVKEY_set(entry, keysv);
416             HeVAL(entry) = sv;
417             sv_upgrade(sv, SVt_PVLV);
418             LvTYPE(sv) = 'T';
419             LvTARG(sv) = (SV*)entry; /* so we can free entry when freeing sv */
420             return entry;
421         }
422 #ifdef ENV_IS_CASELESS
423         else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
424             U32 i;
425             key = SvPV(keysv, klen);
426             for (i = 0; i < klen; ++i)
427                 if (isLOWER(key[i])) {
428                     SV *nkeysv = sv_2mortal(newSVpvn(key,klen));
429                     (void)strupr(SvPVX(nkeysv));
430                     entry = hv_fetch_ent(hv, nkeysv, 0, 0);
431                     if (!entry && lval)
432                         entry = hv_store_ent(hv, keysv, NEWSV(61,0), hash);
433                     return entry;
434                 }
435         }
436 #endif
437     }
438
439     keysave = key = SvPV(keysv, klen);
440     xhv = (XPVHV*)SvANY(hv);
441     if (!xhv->xhv_array /* !HvARRAY(hv) */) {
442         if (lval
443 #ifdef DYNAMIC_ENV_FETCH  /* if it's an %ENV lookup, we may get it on the fly */
444                  || (SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
445 #endif
446                                                                   )
447             Newz(503, xhv->xhv_array /* HvARRAY(hv) */,
448                  PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
449                  char);
450         else
451             return 0;
452     }
453
454     is_utf8 = (SvUTF8(keysv)!=0);
455
456     if (is_utf8) {
457         key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
458         if (is_utf8)
459             flags = HVhek_UTF8;
460         if (key != keysave)
461             flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
462     }
463
464     if (HvREHASH(hv)) {
465         PERL_HASH_INTERNAL(hash, key, klen);
466         /* Yes, you do need this even though you are not "storing" because
467            you can flip the flags below if doing an lval lookup.  (And that
468            was put in to give the semantics Andreas was expecting.)  */
469         flags |= HVhek_REHASH;
470     } else if (!hash) {
471         if SvIsCOW_shared_hash(keysv) {
472             hash = SvUVX(keysv);
473         } else {
474             PERL_HASH(hash, key, klen);
475         }
476     }
477
478     /* entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)]; */
479     entry = ((HE**)xhv->xhv_array)[hash & (I32) xhv->xhv_max];
480     for (; entry; entry = HeNEXT(entry)) {
481         if (HeHASH(entry) != hash)              /* strings can't be equal */
482             continue;
483         if (HeKLEN(entry) != (I32)klen)
484             continue;
485         if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen))        /* is this it? */
486             continue;
487         if ((HeKFLAGS(entry) ^ flags) & HVhek_UTF8)
488             continue;
489         if (lval && HeKFLAGS(entry) != flags) {
490             /* We match if HVhek_UTF8 bit in our flags and hash key's match.
491                But if entry was set previously with HVhek_WASUTF8 and key now
492                doesn't (or vice versa) then we should change the key's flag,
493                as this is assignment.  */
494             if (HvSHAREKEYS(hv)) {
495                 /* Need to swap the key we have for a key with the flags we
496                    need. As keys are shared we can't just write to the flag,
497                    so we share the new one, unshare the old one.  */
498                 int flags_nofree = flags & ~HVhek_FREEKEY;
499                 HEK *new_hek = share_hek_flags(key, klen, hash, flags_nofree);
500                 unshare_hek (HeKEY_hek(entry));
501                 HeKEY_hek(entry) = new_hek;
502             }
503             else
504                 HeKFLAGS(entry) = flags;
505             if (flags & HVhek_ENABLEHVKFLAGS)
506                 HvHASKFLAGS_on(hv);
507         }
508         if (key != keysave)
509             Safefree(key);
510         /* if we find a placeholder, we pretend we haven't found anything */
511         if (HeVAL(entry) == &PL_sv_placeholder)
512             break;
513         return entry;
514     }
515 #ifdef DYNAMIC_ENV_FETCH  /* %ENV lookup?  If so, try to fetch the value now */
516     if (SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
517         unsigned long len;
518         char *env = PerlEnv_ENVgetenv_len(key,&len);
519         if (env) {
520             sv = newSVpvn(env,len);
521             SvTAINTED_on(sv);
522             return hv_store_ent(hv,keysv,sv,hash);
523         }
524     }
525 #endif
526     if (!entry && SvREADONLY(hv)) {
527         S_hv_notallowed(aTHX_ flags, key, klen,
528                         "access disallowed key '%"SVf"' in"
529                         );
530     }
531     if (flags & HVhek_FREEKEY)
532         Safefree(key);
533     if (lval) {         /* gonna assign to this, so it better be there */
534         sv = NEWSV(61,0);
535         return hv_store_ent(hv,keysv,sv,hash);
536     }
537     return 0;
538 }
539
540 STATIC void
541 S_hv_magic_check(pTHX_ HV *hv, bool *needs_copy, bool *needs_store)
542 {
543     MAGIC *mg = SvMAGIC(hv);
544     *needs_copy = FALSE;
545     *needs_store = TRUE;
546     while (mg) {
547         if (isUPPER(mg->mg_type)) {
548             *needs_copy = TRUE;
549             switch (mg->mg_type) {
550             case PERL_MAGIC_tied:
551             case PERL_MAGIC_sig:
552                 *needs_store = FALSE;
553             }
554         }
555         mg = mg->mg_moremagic;
556     }
557 }
558
559 /*
560 =for apidoc hv_store
561
562 Stores an SV in a hash.  The hash key is specified as C<key> and C<klen> is
563 the length of the key.  The C<hash> parameter is the precomputed hash
564 value; if it is zero then Perl will compute it.  The return value will be
565 NULL if the operation failed or if the value did not need to be actually
566 stored within the hash (as in the case of tied hashes).  Otherwise it can
567 be dereferenced to get the original C<SV*>.  Note that the caller is
568 responsible for suitably incrementing the reference count of C<val> before
569 the call, and decrementing it if the function returned NULL.  Effectively
570 a successful hv_store takes ownership of one reference to C<val>.  This is
571 usually what you want; a newly created SV has a reference count of one, so
572 if all your code does is create SVs then store them in a hash, hv_store
573 will own the only reference to the new SV, and your code doesn't need to do
574 anything further to tidy up.  hv_store is not implemented as a call to
575 hv_store_ent, and does not create a temporary SV for the key, so if your
576 key data is not already in SV form then use hv_store in preference to
577 hv_store_ent.
578
579 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
580 information on how to use this function on tied hashes.
581
582 =cut
583 */
584
585 SV**
586 Perl_hv_store(pTHX_ HV *hv, const char *key, I32 klen, SV *val, U32 hash)
587 {
588     bool is_utf8 = FALSE;
589     const char *keysave = key;
590     int flags = 0;
591
592     if (klen < 0) {
593       klen = -klen;
594       is_utf8 = TRUE;
595     }
596
597     if (is_utf8) {
598         STRLEN tmplen = klen;
599         /* Just casting the &klen to (STRLEN) won't work well
600          * if STRLEN and I32 are of different widths. --jhi */
601         key = (char*)bytes_from_utf8((U8*)key, &tmplen, &is_utf8);
602         klen = tmplen;
603         /* If we were able to downgrade here, then than means that we were
604            passed in a key which only had chars 0-255, but was utf8 encoded.  */
605         if (is_utf8)
606             flags = HVhek_UTF8;
607         /* If we found we were able to downgrade the string to bytes, then
608            we should flag that it needs upgrading on keys or each.  */
609         if (key != keysave)
610             flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
611     }
612
613     return hv_store_flags (hv, key, klen, val, hash, flags);
614 }
615
616 SV**
617 Perl_hv_store_flags(pTHX_ HV *hv, const char *key, I32 klen, SV *val,
618                  register U32 hash, int flags)
619 {
620     register XPVHV* xhv;
621     register U32 n_links;
622     register HE *entry;
623     register HE **oentry;
624
625     if (!hv)
626         return 0;
627
628     xhv = (XPVHV*)SvANY(hv);
629     if (SvMAGICAL(hv)) {
630         bool needs_copy;
631         bool needs_store;
632         hv_magic_check (hv, &needs_copy, &needs_store);
633         if (needs_copy) {
634             if (flags & HVhek_UTF8) {
635                 /* This hack based on the code in hv_exists_ent seems to be
636                    the easiest way to pass the utf8 flag through and fix
637                    the bug in hv_exists for tied hashes with utf8 keys.  */
638                 SV *keysv = sv_2mortal(newSVpvn(key, klen));
639                 SvUTF8_on(keysv);
640                 mg_copy((SV*)hv, val, (char *)keysv, HEf_SVKEY);
641             } else {
642                 mg_copy((SV*)hv, val, key, klen);
643             }
644             if (!xhv->xhv_array /* !HvARRAY */ && !needs_store) {
645                 if (flags & HVhek_FREEKEY)
646                     Safefree(key);
647                 return 0;
648             }
649 #ifdef ENV_IS_CASELESS
650             else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
651                 key = savepvn(key,klen);
652                 key = (const char*)strupr((char*)key);
653                 hash = 0;
654             }
655 #endif
656         }
657     }
658
659     if (flags)
660         HvHASKFLAGS_on((SV*)hv);
661
662     if (HvREHASH(hv)) {
663         /* We don't have a pointer to the hv, so we have to replicate the
664            flag into every HEK, so that hv_iterkeysv can see it.  */
665         flags |= HVhek_REHASH;
666         PERL_HASH_INTERNAL(hash, key, klen);
667     } else if (!hash)
668         PERL_HASH(hash, key, klen);
669
670     if (!xhv->xhv_array /* !HvARRAY(hv) */)
671         Newz(505, xhv->xhv_array /* HvARRAY(hv) */,
672              PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
673              char);
674
675     /* oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)]; */
676     oentry = &((HE**)xhv->xhv_array)[hash & (I32) xhv->xhv_max];
677
678     n_links = 0;
679
680     for (entry = *oentry; entry; ++n_links, entry = HeNEXT(entry)) {
681         if (HeHASH(entry) != hash)              /* strings can't be equal */
682             continue;
683         if (HeKLEN(entry) != (I32)klen)
684             continue;
685         if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen))        /* is this it? */
686             continue;
687         if ((HeKFLAGS(entry) ^ flags) & HVhek_UTF8)
688             continue;
689         if (HeVAL(entry) == &PL_sv_placeholder)
690             xhv->xhv_placeholders--; /* yes, can store into placeholder slot */
691         else
692             SvREFCNT_dec(HeVAL(entry));
693         if (flags & HVhek_PLACEHOLD) {
694             /* We have been requested to insert a placeholder. Currently
695                only Storable is allowed to do this.  */
696             xhv->xhv_placeholders++;
697             HeVAL(entry) = &PL_sv_placeholder;
698         } else
699             HeVAL(entry) = val;
700
701         if (HeKFLAGS(entry) != flags) {
702             /* We match if HVhek_UTF8 bit in our flags and hash key's match.
703                But if entry was set previously with HVhek_WASUTF8 and key now
704                doesn't (or vice versa) then we should change the key's flag,
705                as this is assignment.  */
706             if (HvSHAREKEYS(hv)) {
707                 /* Need to swap the key we have for a key with the flags we
708                    need. As keys are shared we can't just write to the flag,
709                    so we share the new one, unshare the old one.  */
710                 int flags_nofree = flags & ~HVhek_FREEKEY;
711                 HEK *new_hek = share_hek_flags(key, klen, hash, flags_nofree);
712                 unshare_hek (HeKEY_hek(entry));
713                 HeKEY_hek(entry) = new_hek;
714             }
715             else
716                 HeKFLAGS(entry) = flags;
717         }
718         if (flags & HVhek_FREEKEY)
719             Safefree(key);
720         return &HeVAL(entry);
721     }
722
723     if (SvREADONLY(hv)) {
724         S_hv_notallowed(aTHX_ flags, key, klen,
725                         "access disallowed key '%"SVf"' to"
726                         );
727     }
728
729     entry = new_HE();
730     /* share_hek_flags will do the free for us.  This might be considered
731        bad API design.  */
732     if (HvSHAREKEYS(hv))
733         HeKEY_hek(entry) = share_hek_flags(key, klen, hash, flags);
734     else                                       /* gotta do the real thing */
735         HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
736     if (flags & HVhek_PLACEHOLD) {
737         /* We have been requested to insert a placeholder. Currently
738            only Storable is allowed to do this.  */
739         xhv->xhv_placeholders++;
740         HeVAL(entry) = &PL_sv_placeholder;
741     } else
742         HeVAL(entry) = val;
743     HeNEXT(entry) = *oentry;
744     *oentry = entry;
745
746     xhv->xhv_keys++; /* HvKEYS(hv)++ */
747     if (!n_links) {                             /* initial entry? */
748         xhv->xhv_fill++; /* HvFILL(hv)++ */
749     } else if ((xhv->xhv_keys > (IV)xhv->xhv_max)
750                || ((n_links > HV_MAX_LENGTH_BEFORE_SPLIT) && !HvREHASH(hv))) {
751         /* Use the old HvKEYS(hv) > HvMAX(hv) condition to limit bucket
752            splits on a rehashed hash, as we're not going to split it again,
753            and if someone is lucky (evil) enough to get all the keys in one
754            list they could exhaust our memory as we repeatedly double the
755            number of buckets on every entry. Linear search feels a less worse
756            thing to do.  */
757         hsplit(hv);
758     }
759
760     return &HeVAL(entry);
761 }
762
763 /*
764 =for apidoc hv_store_ent
765
766 Stores C<val> in a hash.  The hash key is specified as C<key>.  The C<hash>
767 parameter is the precomputed hash value; if it is zero then Perl will
768 compute it.  The return value is the new hash entry so created.  It will be
769 NULL if the operation failed or if the value did not need to be actually
770 stored within the hash (as in the case of tied hashes).  Otherwise the
771 contents of the return value can be accessed using the C<He?> macros
772 described here.  Note that the caller is responsible for suitably
773 incrementing the reference count of C<val> before the call, and
774 decrementing it if the function returned NULL.  Effectively a successful
775 hv_store_ent takes ownership of one reference to C<val>.  This is
776 usually what you want; a newly created SV has a reference count of one, so
777 if all your code does is create SVs then store them in a hash, hv_store
778 will own the only reference to the new SV, and your code doesn't need to do
779 anything further to tidy up.  Note that hv_store_ent only reads the C<key>;
780 unlike C<val> it does not take ownership of it, so maintaining the correct
781 reference count on C<key> is entirely the caller's responsibility.  hv_store
782 is not implemented as a call to hv_store_ent, and does not create a temporary
783 SV for the key, so if your key data is not already in SV form then use
784 hv_store in preference to hv_store_ent.
785
786 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
787 information on how to use this function on tied hashes.
788
789 =cut
790 */
791
792 HE *
793 Perl_hv_store_ent(pTHX_ HV *hv, SV *keysv, SV *val, U32 hash)
794 {
795     XPVHV* xhv;
796     char *key;
797     STRLEN klen;
798     U32 n_links;
799     HE *entry;
800     HE **oentry;
801     bool is_utf8;
802     int flags = 0;
803     char *keysave;
804
805     if (!hv)
806         return 0;
807
808     xhv = (XPVHV*)SvANY(hv);
809     if (SvMAGICAL(hv)) {
810         bool needs_copy;
811         bool needs_store;
812         hv_magic_check (hv, &needs_copy, &needs_store);
813         if (needs_copy) {
814             bool save_taint = PL_tainted;
815             if (PL_tainting)
816                 PL_tainted = SvTAINTED(keysv);
817             keysv = sv_2mortal(newSVsv(keysv));
818             mg_copy((SV*)hv, val, (char*)keysv, HEf_SVKEY);
819             TAINT_IF(save_taint);
820             if (!xhv->xhv_array /* !HvARRAY(hv) */ && !needs_store)
821                 return Nullhe;
822 #ifdef ENV_IS_CASELESS
823             else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
824                 key = SvPV(keysv, klen);
825                 keysv = sv_2mortal(newSVpvn(key,klen));
826                 (void)strupr(SvPVX(keysv));
827                 hash = 0;
828             }
829 #endif
830         }
831     }
832
833     keysave = key = SvPV(keysv, klen);
834     is_utf8 = (SvUTF8(keysv) != 0);
835
836     if (is_utf8) {
837         key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
838         if (is_utf8)
839             flags = HVhek_UTF8;
840         if (key != keysave)
841             flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
842         HvHASKFLAGS_on((SV*)hv);
843     }
844
845     if (HvREHASH(hv)) {
846         /* We don't have a pointer to the hv, so we have to replicate the
847            flag into every HEK, so that hv_iterkeysv can see it.  */
848         flags |= HVhek_REHASH;
849         PERL_HASH_INTERNAL(hash, key, klen);
850     } else if (!hash) {
851         if SvIsCOW_shared_hash(keysv) {
852             hash = SvUVX(keysv);
853         } else {
854             PERL_HASH(hash, key, klen);
855         }
856     }
857
858     if (!xhv->xhv_array /* !HvARRAY(hv) */)
859         Newz(505, xhv->xhv_array /* HvARRAY(hv) */,
860              PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
861              char);
862
863     /* oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)]; */
864     oentry = &((HE**)xhv->xhv_array)[hash & (I32) xhv->xhv_max];
865     n_links = 0;
866     entry = *oentry;
867     for (; entry; ++n_links, entry = HeNEXT(entry)) {
868         if (HeHASH(entry) != hash)              /* strings can't be equal */
869             continue;
870         if (HeKLEN(entry) != (I32)klen)
871             continue;
872         if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen))        /* is this it? */
873             continue;
874         if ((HeKFLAGS(entry) ^ flags) & HVhek_UTF8)
875             continue;
876         if (HeVAL(entry) == &PL_sv_placeholder)
877             xhv->xhv_placeholders--; /* yes, can store into placeholder slot */
878         else
879             SvREFCNT_dec(HeVAL(entry));
880         HeVAL(entry) = val;
881         if (HeKFLAGS(entry) != flags) {
882             /* We match if HVhek_UTF8 bit in our flags and hash key's match.
883                But if entry was set previously with HVhek_WASUTF8 and key now
884                doesn't (or vice versa) then we should change the key's flag,
885                as this is assignment.  */
886             if (HvSHAREKEYS(hv)) {
887                 /* Need to swap the key we have for a key with the flags we
888                    need. As keys are shared we can't just write to the flag,
889                    so we share the new one, unshare the old one.  */
890                 int flags_nofree = flags & ~HVhek_FREEKEY;
891                 HEK *new_hek = share_hek_flags(key, klen, hash, flags_nofree);
892                 unshare_hek (HeKEY_hek(entry));
893                 HeKEY_hek(entry) = new_hek;
894             }
895             else
896                 HeKFLAGS(entry) = flags;
897         }
898         if (flags & HVhek_FREEKEY)
899             Safefree(key);
900         return entry;
901     }
902
903     if (SvREADONLY(hv)) {
904         S_hv_notallowed(aTHX_ flags, key, klen,
905                         "access disallowed key '%"SVf"' to"
906                         );
907     }
908
909     entry = new_HE();
910     /* share_hek_flags will do the free for us.  This might be considered
911        bad API design.  */
912     if (HvSHAREKEYS(hv))
913         HeKEY_hek(entry) = share_hek_flags(key, klen, hash, flags);
914     else                                       /* gotta do the real thing */
915         HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
916     HeVAL(entry) = val;
917     HeNEXT(entry) = *oentry;
918     *oentry = entry;
919
920     xhv->xhv_keys++; /* HvKEYS(hv)++ */
921     if (!n_links) {                             /* initial entry? */
922         xhv->xhv_fill++; /* HvFILL(hv)++ */
923     } else if ((xhv->xhv_keys > (IV)xhv->xhv_max)
924                || ((n_links > HV_MAX_LENGTH_BEFORE_SPLIT) && !HvREHASH(hv))) {
925         /* Use only the old HvKEYS(hv) > HvMAX(hv) condition to limit bucket
926            splits on a rehashed hash, as we're not going to split it again,
927            and if someone is lucky (evil) enough to get all the keys in one
928            list they could exhaust our memory as we repeatedly double the
929            number of buckets on every entry. Linear search feels a less worse
930            thing to do.  */
931         hsplit(hv);
932     }
933
934     return entry;
935 }
936
937 /*
938 =for apidoc hv_delete
939
940 Deletes a key/value pair in the hash.  The value SV is removed from the
941 hash and returned to the caller.  The C<klen> is the length of the key.
942 The C<flags> value will normally be zero; if set to G_DISCARD then NULL
943 will be returned.
944
945 =cut
946 */
947
948 SV *
949 Perl_hv_delete(pTHX_ HV *hv, const char *key, I32 klen, I32 flags)
950 {
951     register XPVHV* xhv;
952     register I32 i;
953     register U32 hash;
954     register HE *entry;
955     register HE **oentry;
956     SV **svp;
957     SV *sv;
958     bool is_utf8 = FALSE;
959     int k_flags = 0;
960     const char *keysave = key;
961
962     if (!hv)
963         return Nullsv;
964     if (klen < 0) {
965         klen = -klen;
966         is_utf8 = TRUE;
967     }
968     if (SvRMAGICAL(hv)) {
969         bool needs_copy;
970         bool needs_store;
971         hv_magic_check (hv, &needs_copy, &needs_store);
972
973         if (needs_copy
974             && (svp = hv_fetch(hv, key, is_utf8 ? -klen : klen, TRUE))) {
975             sv = *svp;
976             if (SvMAGICAL(sv)) {
977                 mg_clear(sv);
978             }
979             if (!needs_store) {
980                 if (mg_find(sv, PERL_MAGIC_tiedelem)) {
981                     /* No longer an element */
982                     sv_unmagic(sv, PERL_MAGIC_tiedelem);
983                     return sv;
984                 }
985                 return Nullsv;          /* element cannot be deleted */
986             }
987 #ifdef ENV_IS_CASELESS
988             else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
989                 sv = sv_2mortal(newSVpvn(key,klen));
990                 key = strupr(SvPVX(sv));
991             }
992 #endif
993         }
994     }
995     xhv = (XPVHV*)SvANY(hv);
996     if (!xhv->xhv_array /* !HvARRAY(hv) */)
997         return Nullsv;
998
999     if (is_utf8) {
1000         STRLEN tmplen = klen;
1001         /* See the note in hv_fetch(). --jhi */
1002         key = (char*)bytes_from_utf8((U8*)key, &tmplen, &is_utf8);
1003         klen = tmplen;
1004         if (is_utf8)
1005             k_flags = HVhek_UTF8;
1006         if (key != keysave)
1007             k_flags |= HVhek_FREEKEY;
1008     }
1009
1010     if (HvREHASH(hv)) {
1011         PERL_HASH_INTERNAL(hash, key, klen);
1012     } else {
1013         PERL_HASH(hash, key, klen);
1014     }
1015
1016     /* oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)]; */
1017     oentry = &((HE**)xhv->xhv_array)[hash & (I32) xhv->xhv_max];
1018     entry = *oentry;
1019     i = 1;
1020     for (; entry; i=0, oentry = &HeNEXT(entry), entry = *oentry) {
1021         if (HeHASH(entry) != hash)              /* strings can't be equal */
1022             continue;
1023         if (HeKLEN(entry) != (I32)klen)
1024             continue;
1025         if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen))        /* is this it? */
1026             continue;
1027         if ((HeKFLAGS(entry) ^ k_flags) & HVhek_UTF8)
1028             continue;
1029         if (k_flags & HVhek_FREEKEY)
1030             Safefree(key);
1031         /* if placeholder is here, it's already been deleted.... */
1032         if (HeVAL(entry) == &PL_sv_placeholder)
1033         {
1034             if (SvREADONLY(hv))
1035                 return Nullsv;  /* if still SvREADONLY, leave it deleted. */
1036             else {
1037                 /* okay, really delete the placeholder... */
1038                 *oentry = HeNEXT(entry);
1039                 if (i && !*oentry)
1040                     xhv->xhv_fill--; /* HvFILL(hv)-- */
1041                 if (entry == xhv->xhv_eiter /* HvEITER(hv) */)
1042                     HvLAZYDEL_on(hv);
1043                 else
1044                     hv_free_ent(hv, entry);
1045                 xhv->xhv_keys--; /* HvKEYS(hv)-- */
1046                 if (xhv->xhv_keys == 0)
1047                     HvHASKFLAGS_off(hv);
1048                 xhv->xhv_placeholders--;
1049                 return Nullsv;
1050             }
1051         }
1052         else if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1053             S_hv_notallowed(aTHX_ k_flags, key, klen,
1054                             "delete readonly key '%"SVf"' from"
1055                             );
1056         }
1057
1058         if (flags & G_DISCARD)
1059             sv = Nullsv;
1060         else {
1061             sv = sv_2mortal(HeVAL(entry));
1062             HeVAL(entry) = &PL_sv_placeholder;
1063         }
1064
1065         /*
1066          * If a restricted hash, rather than really deleting the entry, put
1067          * a placeholder there. This marks the key as being "approved", so
1068          * we can still access via not-really-existing key without raising
1069          * an error.
1070          */
1071         if (SvREADONLY(hv)) {
1072             HeVAL(entry) = &PL_sv_placeholder;
1073             /* We'll be saving this slot, so the number of allocated keys
1074              * doesn't go down, but the number placeholders goes up */
1075             xhv->xhv_placeholders++; /* HvPLACEHOLDERS(hv)++ */
1076         } else {
1077             *oentry = HeNEXT(entry);
1078             if (i && !*oentry)
1079                 xhv->xhv_fill--; /* HvFILL(hv)-- */
1080             if (entry == xhv->xhv_eiter /* HvEITER(hv) */)
1081                 HvLAZYDEL_on(hv);
1082             else
1083                 hv_free_ent(hv, entry);
1084             xhv->xhv_keys--; /* HvKEYS(hv)-- */
1085             if (xhv->xhv_keys == 0)
1086                 HvHASKFLAGS_off(hv);
1087         }
1088         return sv;
1089     }
1090     if (SvREADONLY(hv)) {
1091         S_hv_notallowed(aTHX_ k_flags, key, klen,
1092                         "access disallowed key '%"SVf"' from"
1093                         );
1094     }
1095
1096     if (k_flags & HVhek_FREEKEY)
1097         Safefree(key);
1098     return Nullsv;
1099 }
1100
1101 /*
1102 =for apidoc hv_delete_ent
1103
1104 Deletes a key/value pair in the hash.  The value SV is removed from the
1105 hash and returned to the caller.  The C<flags> value will normally be zero;
1106 if set to G_DISCARD then NULL will be returned.  C<hash> can be a valid
1107 precomputed hash value, or 0 to ask for it to be computed.
1108
1109 =cut
1110 */
1111
1112 SV *
1113 Perl_hv_delete_ent(pTHX_ HV *hv, SV *keysv, I32 flags, U32 hash)
1114 {
1115     register XPVHV* xhv;
1116     register I32 i;
1117     register char *key;
1118     STRLEN klen;
1119     register HE *entry;
1120     register HE **oentry;
1121     SV *sv;
1122     bool is_utf8;
1123     int k_flags = 0;
1124     char *keysave;
1125
1126     if (!hv)
1127         return Nullsv;
1128     if (SvRMAGICAL(hv)) {
1129         bool needs_copy;
1130         bool needs_store;
1131         hv_magic_check (hv, &needs_copy, &needs_store);
1132
1133         if (needs_copy && (entry = hv_fetch_ent(hv, keysv, TRUE, hash))) {
1134             sv = HeVAL(entry);
1135             if (SvMAGICAL(sv)) {
1136                 mg_clear(sv);
1137             }
1138             if (!needs_store) {
1139                 if (mg_find(sv, PERL_MAGIC_tiedelem)) {
1140                     /* No longer an element */
1141                     sv_unmagic(sv, PERL_MAGIC_tiedelem);
1142                     return sv;
1143                 }               
1144                 return Nullsv;          /* element cannot be deleted */
1145             }
1146 #ifdef ENV_IS_CASELESS
1147             else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
1148                 key = SvPV(keysv, klen);
1149                 keysv = sv_2mortal(newSVpvn(key,klen));
1150                 (void)strupr(SvPVX(keysv));
1151                 hash = 0;
1152             }
1153 #endif
1154         }
1155     }
1156     xhv = (XPVHV*)SvANY(hv);
1157     if (!xhv->xhv_array /* !HvARRAY(hv) */)
1158         return Nullsv;
1159
1160     keysave = key = SvPV(keysv, klen);
1161     is_utf8 = (SvUTF8(keysv) != 0);
1162
1163     if (is_utf8) {
1164         key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
1165         if (is_utf8)
1166             k_flags = HVhek_UTF8;
1167         if (key != keysave)
1168             k_flags |= HVhek_FREEKEY;
1169     }
1170
1171     if (HvREHASH(hv)) {
1172         PERL_HASH_INTERNAL(hash, key, klen);
1173     } else if (!hash) {
1174         PERL_HASH(hash, key, klen);
1175     }
1176
1177     /* oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)]; */
1178     oentry = &((HE**)xhv->xhv_array)[hash & (I32) xhv->xhv_max];
1179     entry = *oentry;
1180     i = 1;
1181     for (; entry; i=0, oentry = &HeNEXT(entry), entry = *oentry) {
1182         if (HeHASH(entry) != hash)              /* strings can't be equal */
1183             continue;
1184         if (HeKLEN(entry) != (I32)klen)
1185             continue;
1186         if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen))        /* is this it? */
1187             continue;
1188         if ((HeKFLAGS(entry) ^ k_flags) & HVhek_UTF8)
1189             continue;
1190         if (k_flags & HVhek_FREEKEY)
1191             Safefree(key);
1192
1193         /* if placeholder is here, it's already been deleted.... */
1194         if (HeVAL(entry) == &PL_sv_placeholder)
1195         {
1196             if (SvREADONLY(hv))
1197                 return Nullsv; /* if still SvREADONLY, leave it deleted. */
1198
1199            /* okay, really delete the placeholder. */
1200            *oentry = HeNEXT(entry);
1201            if (i && !*oentry)
1202                xhv->xhv_fill--; /* HvFILL(hv)-- */
1203            if (entry == xhv->xhv_eiter /* HvEITER(hv) */)
1204                HvLAZYDEL_on(hv);
1205            else
1206                hv_free_ent(hv, entry);
1207            xhv->xhv_keys--; /* HvKEYS(hv)-- */
1208            if (xhv->xhv_keys == 0)
1209                HvHASKFLAGS_off(hv);
1210            xhv->xhv_placeholders--;
1211            return Nullsv;
1212         }
1213         else if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1214             S_hv_notallowed(aTHX_ k_flags, key, klen,
1215                             "delete readonly key '%"SVf"' from"
1216                             );
1217         }
1218
1219         if (flags & G_DISCARD)
1220             sv = Nullsv;
1221         else {
1222             sv = sv_2mortal(HeVAL(entry));
1223             HeVAL(entry) = &PL_sv_placeholder;
1224         }
1225
1226         /*
1227          * If a restricted hash, rather than really deleting the entry, put
1228          * a placeholder there. This marks the key as being "approved", so
1229          * we can still access via not-really-existing key without raising
1230          * an error.
1231          */
1232         if (SvREADONLY(hv)) {
1233             HeVAL(entry) = &PL_sv_placeholder;
1234             /* We'll be saving this slot, so the number of allocated keys
1235              * doesn't go down, but the number placeholders goes up */
1236             xhv->xhv_placeholders++; /* HvPLACEHOLDERS(hv)++ */
1237         } else {
1238             *oentry = HeNEXT(entry);
1239             if (i && !*oentry)
1240                 xhv->xhv_fill--; /* HvFILL(hv)-- */
1241             if (entry == xhv->xhv_eiter /* HvEITER(hv) */)
1242                 HvLAZYDEL_on(hv);
1243             else
1244                 hv_free_ent(hv, entry);
1245             xhv->xhv_keys--; /* HvKEYS(hv)-- */
1246             if (xhv->xhv_keys == 0)
1247                 HvHASKFLAGS_off(hv);
1248         }
1249         return sv;
1250     }
1251     if (SvREADONLY(hv)) {
1252         S_hv_notallowed(aTHX_ k_flags, key, klen,
1253                         "delete disallowed key '%"SVf"' from"
1254                         );
1255     }
1256
1257     if (k_flags & HVhek_FREEKEY)
1258         Safefree(key);
1259     return Nullsv;
1260 }
1261
1262 /*
1263 =for apidoc hv_exists
1264
1265 Returns a boolean indicating whether the specified hash key exists.  The
1266 C<klen> is the length of the key.
1267
1268 =cut
1269 */
1270
1271 bool
1272 Perl_hv_exists(pTHX_ HV *hv, const char *key, I32 klen)
1273 {
1274     register XPVHV* xhv;
1275     register U32 hash;
1276     register HE *entry;
1277     SV *sv;
1278     bool is_utf8 = FALSE;
1279     const char *keysave = key;
1280     int k_flags = 0;
1281
1282     if (!hv)
1283         return 0;
1284
1285     if (klen < 0) {
1286       klen = -klen;
1287       is_utf8 = TRUE;
1288     }
1289
1290     if (SvRMAGICAL(hv)) {
1291         if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
1292             sv = sv_newmortal();
1293             if (is_utf8) {
1294                 /* This hack based on the code in hv_exists_ent seems to be
1295                    the easiest way to pass the utf8 flag through and fix
1296                    the bug in hv_exists for tied hashes with utf8 keys.  */
1297                 SV *keysv = sv_2mortal(newSVpvn(key, klen));
1298                 SvUTF8_on(keysv);
1299                 key = (char *)keysv;
1300                 klen = HEf_SVKEY;
1301             }
1302             mg_copy((SV*)hv, sv, key, klen);
1303             magic_existspack(sv, mg_find(sv, PERL_MAGIC_tiedelem));
1304             return (bool)SvTRUE(sv);
1305         }
1306 #ifdef ENV_IS_CASELESS
1307         else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
1308             sv = sv_2mortal(newSVpvn(key,klen));
1309             key = strupr(SvPVX(sv));
1310         }
1311 #endif
1312     }
1313
1314     xhv = (XPVHV*)SvANY(hv);
1315 #ifndef DYNAMIC_ENV_FETCH
1316     if (!xhv->xhv_array /* !HvARRAY(hv) */)
1317         return 0;
1318 #endif
1319
1320     if (is_utf8) {
1321         STRLEN tmplen = klen;
1322         /* See the note in hv_fetch(). --jhi */
1323         key = (char*)bytes_from_utf8((U8*)key, &tmplen, &is_utf8);
1324         klen = tmplen;
1325         if (is_utf8)
1326             k_flags = HVhek_UTF8;
1327         if (key != keysave)
1328             k_flags |= HVhek_FREEKEY;
1329     }
1330
1331     if (HvREHASH(hv)) {
1332         PERL_HASH_INTERNAL(hash, key, klen);
1333     } else {
1334         PERL_HASH(hash, key, klen);
1335     }
1336
1337 #ifdef DYNAMIC_ENV_FETCH
1338     if (!xhv->xhv_array /* !HvARRAY(hv) */) entry = Null(HE*);
1339     else
1340 #endif
1341     /* entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)]; */
1342     entry = ((HE**)xhv->xhv_array)[hash & (I32) xhv->xhv_max];
1343     for (; entry; entry = HeNEXT(entry)) {
1344         if (HeHASH(entry) != hash)              /* strings can't be equal */
1345             continue;
1346         if (HeKLEN(entry) != klen)
1347             continue;
1348         if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen))        /* is this it? */
1349             continue;
1350         if ((HeKFLAGS(entry) ^ k_flags) & HVhek_UTF8)
1351             continue;
1352         if (k_flags & HVhek_FREEKEY)
1353             Safefree(key);
1354         /* If we find the key, but the value is a placeholder, return false. */
1355         if (HeVAL(entry) == &PL_sv_placeholder)
1356             return FALSE;
1357
1358         return TRUE;
1359     }
1360 #ifdef DYNAMIC_ENV_FETCH  /* is it out there? */
1361     if (SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
1362         unsigned long len;
1363         char *env = PerlEnv_ENVgetenv_len(key,&len);
1364         if (env) {
1365             sv = newSVpvn(env,len);
1366             SvTAINTED_on(sv);
1367             (void)hv_store(hv,key,klen,sv,hash);
1368             if (k_flags & HVhek_FREEKEY)
1369                 Safefree(key);
1370             return TRUE;
1371         }
1372     }
1373 #endif
1374     if (k_flags & HVhek_FREEKEY)
1375         Safefree(key);
1376     return FALSE;
1377 }
1378
1379
1380 /*
1381 =for apidoc hv_exists_ent
1382
1383 Returns a boolean indicating whether the specified hash key exists. C<hash>
1384 can be a valid precomputed hash value, or 0 to ask for it to be
1385 computed.
1386
1387 =cut
1388 */
1389
1390 bool
1391 Perl_hv_exists_ent(pTHX_ HV *hv, SV *keysv, U32 hash)
1392 {
1393     register XPVHV* xhv;
1394     register char *key;
1395     STRLEN klen;
1396     register HE *entry;
1397     SV *sv;
1398     bool is_utf8;
1399     char *keysave;
1400     int k_flags = 0;
1401
1402     if (!hv)
1403         return 0;
1404
1405     if (SvRMAGICAL(hv)) {
1406         if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
1407            SV* svret = sv_newmortal();
1408             sv = sv_newmortal();
1409             keysv = sv_2mortal(newSVsv(keysv));
1410             mg_copy((SV*)hv, sv, (char*)keysv, HEf_SVKEY);
1411            magic_existspack(svret, mg_find(sv, PERL_MAGIC_tiedelem));
1412            return (bool)SvTRUE(svret);
1413         }
1414 #ifdef ENV_IS_CASELESS
1415         else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
1416             key = SvPV(keysv, klen);
1417             keysv = sv_2mortal(newSVpvn(key,klen));
1418             (void)strupr(SvPVX(keysv));
1419             hash = 0;
1420         }
1421 #endif
1422     }
1423
1424     xhv = (XPVHV*)SvANY(hv);
1425 #ifndef DYNAMIC_ENV_FETCH
1426     if (!xhv->xhv_array /* !HvARRAY(hv) */)
1427         return 0;
1428 #endif
1429
1430     keysave = key = SvPV(keysv, klen);
1431     is_utf8 = (SvUTF8(keysv) != 0);
1432     if (is_utf8) {
1433         key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
1434         if (is_utf8)
1435             k_flags = HVhek_UTF8;
1436         if (key != keysave)
1437             k_flags |= HVhek_FREEKEY;
1438     }
1439     if (HvREHASH(hv)) {
1440         PERL_HASH_INTERNAL(hash, key, klen);
1441     } else if (!hash)
1442         PERL_HASH(hash, key, klen);
1443
1444 #ifdef DYNAMIC_ENV_FETCH
1445     if (!xhv->xhv_array /* !HvARRAY(hv) */) entry = Null(HE*);
1446     else
1447 #endif
1448     /* entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)]; */
1449     entry = ((HE**)xhv->xhv_array)[hash & (I32) xhv->xhv_max];
1450     for (; entry; entry = HeNEXT(entry)) {
1451         if (HeHASH(entry) != hash)              /* strings can't be equal */
1452             continue;
1453         if (HeKLEN(entry) != (I32)klen)
1454             continue;
1455         if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen))        /* is this it? */
1456             continue;
1457         if ((HeKFLAGS(entry) ^ k_flags) & HVhek_UTF8)
1458             continue;
1459         if (k_flags & HVhek_FREEKEY)
1460             Safefree(key);
1461         /* If we find the key, but the value is a placeholder, return false. */
1462         if (HeVAL(entry) == &PL_sv_placeholder)
1463             return FALSE;
1464         return TRUE;
1465     }
1466 #ifdef DYNAMIC_ENV_FETCH  /* is it out there? */
1467     if (SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
1468         unsigned long len;
1469         char *env = PerlEnv_ENVgetenv_len(key,&len);
1470         if (env) {
1471             sv = newSVpvn(env,len);
1472             SvTAINTED_on(sv);
1473             (void)hv_store_ent(hv,keysv,sv,hash);
1474             if (k_flags & HVhek_FREEKEY)
1475                 Safefree(key);
1476             return TRUE;
1477         }
1478     }
1479 #endif
1480     if (k_flags & HVhek_FREEKEY)
1481         Safefree(key);
1482     return FALSE;
1483 }
1484
1485 STATIC void
1486 S_hsplit(pTHX_ HV *hv)
1487 {
1488     register XPVHV* xhv = (XPVHV*)SvANY(hv);
1489     I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1490     register I32 newsize = oldsize * 2;
1491     register I32 i;
1492     register char *a = xhv->xhv_array; /* HvARRAY(hv) */
1493     register HE **aep;
1494     register HE **bep;
1495     register HE *entry;
1496     register HE **oentry;
1497     int longest_chain = 0;
1498     int was_shared;
1499
1500     PL_nomemok = TRUE;
1501 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1502     Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1503     if (!a) {
1504       PL_nomemok = FALSE;
1505       return;
1506     }
1507 #else
1508     New(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1509     if (!a) {
1510       PL_nomemok = FALSE;
1511       return;
1512     }
1513     Copy(xhv->xhv_array /* HvARRAY(hv) */, a, oldsize * sizeof(HE*), char);
1514     if (oldsize >= 64) {
1515         offer_nice_chunk(xhv->xhv_array /* HvARRAY(hv) */,
1516                         PERL_HV_ARRAY_ALLOC_BYTES(oldsize));
1517     }
1518     else
1519         Safefree(xhv->xhv_array /* HvARRAY(hv) */);
1520 #endif
1521
1522     PL_nomemok = FALSE;
1523     Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char);     /* zero 2nd half*/
1524     xhv->xhv_max = --newsize;   /* HvMAX(hv) = --newsize */
1525     xhv->xhv_array = a;         /* HvARRAY(hv) = a */
1526     aep = (HE**)a;
1527
1528     for (i=0; i<oldsize; i++,aep++) {
1529         int left_length = 0;
1530         int right_length = 0;
1531
1532         if (!*aep)                              /* non-existent */
1533             continue;
1534         bep = aep+oldsize;
1535         for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1536             if ((HeHASH(entry) & newsize) != (U32)i) {
1537                 *oentry = HeNEXT(entry);
1538                 HeNEXT(entry) = *bep;
1539                 if (!*bep)
1540                     xhv->xhv_fill++; /* HvFILL(hv)++ */
1541                 *bep = entry;
1542                 right_length++;
1543                 continue;
1544             }
1545             else {
1546                 oentry = &HeNEXT(entry);
1547                 left_length++;
1548             }
1549         }
1550         if (!*aep)                              /* everything moved */
1551             xhv->xhv_fill--; /* HvFILL(hv)-- */
1552         /* I think we don't actually need to keep track of the longest length,
1553            merely flag if anything is too long. But for the moment while
1554            developing this code I'll track it.  */
1555         if (left_length > longest_chain)
1556             longest_chain = left_length;
1557         if (right_length > longest_chain)
1558             longest_chain = right_length;
1559     }
1560
1561
1562     /* Pick your policy for "hashing isn't working" here:  */
1563     if (longest_chain <= HV_MAX_LENGTH_BEFORE_SPLIT /* split worked?  */
1564         || HvREHASH(hv)) {
1565         return;
1566     }
1567
1568     if (hv == PL_strtab) {
1569         /* Urg. Someone is doing something nasty to the string table.
1570            Can't win.  */
1571         return;
1572     }
1573
1574     /* Awooga. Awooga. Pathological data.  */
1575     /*PerlIO_printf(PerlIO_stderr(), "%p %d of %d with %d/%d buckets\n", hv,
1576       longest_chain, HvTOTALKEYS(hv), HvFILL(hv),  1+HvMAX(hv));*/
1577
1578     ++newsize;
1579     Newz(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1580     was_shared = HvSHAREKEYS(hv);
1581
1582     xhv->xhv_fill = 0;
1583     HvSHAREKEYS_off(hv);
1584     HvREHASH_on(hv);
1585
1586     aep = (HE **) xhv->xhv_array;
1587
1588     for (i=0; i<newsize; i++,aep++) {
1589         entry = *aep;
1590         while (entry) {
1591             /* We're going to trash this HE's next pointer when we chain it
1592                into the new hash below, so store where we go next.  */
1593             HE *next = HeNEXT(entry);
1594             UV hash;
1595
1596             /* Rehash it */
1597             PERL_HASH_INTERNAL(hash, HeKEY(entry), HeKLEN(entry));
1598
1599             if (was_shared) {
1600                 /* Unshare it.  */
1601                 HEK *new_hek
1602                     = save_hek_flags(HeKEY(entry), HeKLEN(entry),
1603                                      hash, HeKFLAGS(entry));
1604                 unshare_hek (HeKEY_hek(entry));
1605                 HeKEY_hek(entry) = new_hek;
1606             } else {
1607                 /* Not shared, so simply write the new hash in. */
1608                 HeHASH(entry) = hash;
1609             }
1610             /*PerlIO_printf(PerlIO_stderr(), "%d ", HeKFLAGS(entry));*/
1611             HEK_REHASH_on(HeKEY_hek(entry));
1612             /*PerlIO_printf(PerlIO_stderr(), "%d\n", HeKFLAGS(entry));*/
1613
1614             /* Copy oentry to the correct new chain.  */
1615             bep = ((HE**)a) + (hash & (I32) xhv->xhv_max);
1616             if (!*bep)
1617                     xhv->xhv_fill++; /* HvFILL(hv)++ */
1618             HeNEXT(entry) = *bep;
1619             *bep = entry;
1620
1621             entry = next;
1622         }
1623     }
1624     Safefree (xhv->xhv_array);
1625     xhv->xhv_array = a;         /* HvARRAY(hv) = a */
1626 }
1627
1628 void
1629 Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
1630 {
1631     register XPVHV* xhv = (XPVHV*)SvANY(hv);
1632     I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1633     register I32 newsize;
1634     register I32 i;
1635     register I32 j;
1636     register char *a;
1637     register HE **aep;
1638     register HE *entry;
1639     register HE **oentry;
1640
1641     newsize = (I32) newmax;                     /* possible truncation here */
1642     if (newsize != newmax || newmax <= oldsize)
1643         return;
1644     while ((newsize & (1 + ~newsize)) != newsize) {
1645         newsize &= ~(newsize & (1 + ~newsize)); /* get proper power of 2 */
1646     }
1647     if (newsize < newmax)
1648         newsize *= 2;
1649     if (newsize < newmax)
1650         return;                                 /* overflow detection */
1651
1652     a = xhv->xhv_array; /* HvARRAY(hv) */
1653     if (a) {
1654         PL_nomemok = TRUE;
1655 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1656         Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1657         if (!a) {
1658           PL_nomemok = FALSE;
1659           return;
1660         }
1661 #else
1662         New(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1663         if (!a) {
1664           PL_nomemok = FALSE;
1665           return;
1666         }
1667         Copy(xhv->xhv_array /* HvARRAY(hv) */, a, oldsize * sizeof(HE*), char);
1668         if (oldsize >= 64) {
1669             offer_nice_chunk(xhv->xhv_array /* HvARRAY(hv) */,
1670                             PERL_HV_ARRAY_ALLOC_BYTES(oldsize));
1671         }
1672         else
1673             Safefree(xhv->xhv_array /* HvARRAY(hv) */);
1674 #endif
1675         PL_nomemok = FALSE;
1676         Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1677     }
1678     else {
1679         Newz(0, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1680     }
1681     xhv->xhv_max = --newsize;   /* HvMAX(hv) = --newsize */
1682     xhv->xhv_array = a;         /* HvARRAY(hv) = a */
1683     if (!xhv->xhv_fill /* !HvFILL(hv) */)       /* skip rest if no entries */
1684         return;
1685
1686     aep = (HE**)a;
1687     for (i=0; i<oldsize; i++,aep++) {
1688         if (!*aep)                              /* non-existent */
1689             continue;
1690         for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1691             if ((j = (HeHASH(entry) & newsize)) != i) {
1692                 j -= i;
1693                 *oentry = HeNEXT(entry);
1694                 if (!(HeNEXT(entry) = aep[j]))
1695                     xhv->xhv_fill++; /* HvFILL(hv)++ */
1696                 aep[j] = entry;
1697                 continue;
1698             }
1699             else
1700                 oentry = &HeNEXT(entry);
1701         }
1702         if (!*aep)                              /* everything moved */
1703             xhv->xhv_fill--; /* HvFILL(hv)-- */
1704     }
1705 }
1706
1707 /*
1708 =for apidoc newHV
1709
1710 Creates a new HV.  The reference count is set to 1.
1711
1712 =cut
1713 */
1714
1715 HV *
1716 Perl_newHV(pTHX)
1717 {
1718     register HV *hv;
1719     register XPVHV* xhv;
1720
1721     hv = (HV*)NEWSV(502,0);
1722     sv_upgrade((SV *)hv, SVt_PVHV);
1723     xhv = (XPVHV*)SvANY(hv);
1724     SvPOK_off(hv);
1725     SvNOK_off(hv);
1726 #ifndef NODEFAULT_SHAREKEYS
1727     HvSHAREKEYS_on(hv);         /* key-sharing on by default */
1728 #endif
1729
1730     xhv->xhv_max    = 7;        /* HvMAX(hv) = 7 (start with 8 buckets) */
1731     xhv->xhv_fill   = 0;        /* HvFILL(hv) = 0 */
1732     xhv->xhv_pmroot = 0;        /* HvPMROOT(hv) = 0 */
1733     (void)hv_iterinit(hv);      /* so each() will start off right */
1734     return hv;
1735 }
1736
1737 HV *
1738 Perl_newHVhv(pTHX_ HV *ohv)
1739 {
1740     HV *hv = newHV();
1741     STRLEN hv_max, hv_fill;
1742
1743     if (!ohv || (hv_fill = HvFILL(ohv)) == 0)
1744         return hv;
1745     hv_max = HvMAX(ohv);
1746
1747     if (!SvMAGICAL((SV *)ohv)) {
1748         /* It's an ordinary hash, so copy it fast. AMS 20010804 */
1749         STRLEN i;
1750         bool shared = !!HvSHAREKEYS(ohv);
1751         HE **ents, **oents = (HE **)HvARRAY(ohv);
1752         char *a;
1753         New(0, a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
1754         ents = (HE**)a;
1755
1756         /* In each bucket... */
1757         for (i = 0; i <= hv_max; i++) {
1758             HE *prev = NULL, *ent = NULL, *oent = oents[i];
1759
1760             if (!oent) {
1761                 ents[i] = NULL;
1762                 continue;
1763             }
1764
1765             /* Copy the linked list of entries. */
1766             for (oent = oents[i]; oent; oent = HeNEXT(oent)) {
1767                 U32 hash   = HeHASH(oent);
1768                 char *key  = HeKEY(oent);
1769                 STRLEN len = HeKLEN(oent);
1770                 int flags  = HeKFLAGS(oent);
1771
1772                 ent = new_HE();
1773                 HeVAL(ent)     = newSVsv(HeVAL(oent));
1774                 HeKEY_hek(ent)
1775                     = shared ? share_hek_flags(key, len, hash, flags)
1776                              :  save_hek_flags(key, len, hash, flags);
1777                 if (prev)
1778                     HeNEXT(prev) = ent;
1779                 else
1780                     ents[i] = ent;
1781                 prev = ent;
1782                 HeNEXT(ent) = NULL;
1783             }
1784         }
1785
1786         HvMAX(hv)   = hv_max;
1787         HvFILL(hv)  = hv_fill;
1788         HvTOTALKEYS(hv)  = HvTOTALKEYS(ohv);
1789         HvARRAY(hv) = ents;
1790     }
1791     else {
1792         /* Iterate over ohv, copying keys and values one at a time. */
1793         HE *entry;
1794         I32 riter = HvRITER(ohv);
1795         HE *eiter = HvEITER(ohv);
1796
1797         /* Can we use fewer buckets? (hv_max is always 2^n-1) */
1798         while (hv_max && hv_max + 1 >= hv_fill * 2)
1799             hv_max = hv_max / 2;
1800         HvMAX(hv) = hv_max;
1801
1802         hv_iterinit(ohv);
1803         while ((entry = hv_iternext_flags(ohv, 0))) {
1804             hv_store_flags(hv, HeKEY(entry), HeKLEN(entry),
1805                            newSVsv(HeVAL(entry)), HeHASH(entry),
1806                            HeKFLAGS(entry));
1807         }
1808         HvRITER(ohv) = riter;
1809         HvEITER(ohv) = eiter;
1810     }
1811
1812     return hv;
1813 }
1814
1815 void
1816 Perl_hv_free_ent(pTHX_ HV *hv, register HE *entry)
1817 {
1818     SV *val;
1819
1820     if (!entry)
1821         return;
1822     val = HeVAL(entry);
1823     if (val && isGV(val) && GvCVu(val) && HvNAME(hv))
1824         PL_sub_generation++;    /* may be deletion of method from stash */
1825     SvREFCNT_dec(val);
1826     if (HeKLEN(entry) == HEf_SVKEY) {
1827         SvREFCNT_dec(HeKEY_sv(entry));
1828         Safefree(HeKEY_hek(entry));
1829     }
1830     else if (HvSHAREKEYS(hv))
1831         unshare_hek(HeKEY_hek(entry));
1832     else
1833         Safefree(HeKEY_hek(entry));
1834     del_HE(entry);
1835 }
1836
1837 void
1838 Perl_hv_delayfree_ent(pTHX_ HV *hv, register HE *entry)
1839 {
1840     if (!entry)
1841         return;
1842     if (isGV(HeVAL(entry)) && GvCVu(HeVAL(entry)) && HvNAME(hv))
1843         PL_sub_generation++;    /* may be deletion of method from stash */
1844     sv_2mortal(HeVAL(entry));   /* free between statements */
1845     if (HeKLEN(entry) == HEf_SVKEY) {
1846         sv_2mortal(HeKEY_sv(entry));
1847         Safefree(HeKEY_hek(entry));
1848     }
1849     else if (HvSHAREKEYS(hv))
1850         unshare_hek(HeKEY_hek(entry));
1851     else
1852         Safefree(HeKEY_hek(entry));
1853     del_HE(entry);
1854 }
1855
1856 /*
1857 =for apidoc hv_clear
1858
1859 Clears a hash, making it empty.
1860
1861 =cut
1862 */
1863
1864 void
1865 Perl_hv_clear(pTHX_ HV *hv)
1866 {
1867     register XPVHV* xhv;
1868     if (!hv)
1869         return;
1870
1871     DEBUG_A(Perl_hv_assert(aTHX_ hv));
1872
1873     xhv = (XPVHV*)SvANY(hv);
1874
1875     if (SvREADONLY(hv)) {
1876         /* restricted hash: convert all keys to placeholders */
1877         I32 i;
1878         HE* entry;
1879         for (i = 0; i <= (I32) xhv->xhv_max; i++) {
1880             entry = ((HE**)xhv->xhv_array)[i];
1881             for (; entry; entry = HeNEXT(entry)) {
1882                 /* not already placeholder */
1883                 if (HeVAL(entry) != &PL_sv_placeholder) {
1884                     if (HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1885                         SV* keysv = hv_iterkeysv(entry);
1886                         Perl_croak(aTHX_
1887         "Attempt to delete readonly key '%"SVf"' from a restricted hash",
1888                                    keysv);
1889                     }
1890                     SvREFCNT_dec(HeVAL(entry));
1891                     HeVAL(entry) = &PL_sv_placeholder;
1892                     xhv->xhv_placeholders++; /* HvPLACEHOLDERS(hv)++ */
1893                 }
1894             }
1895         }
1896         return;
1897     }
1898
1899     hfreeentries(hv);
1900     xhv->xhv_placeholders = 0; /* HvPLACEHOLDERS(hv) = 0 */
1901     if (xhv->xhv_array /* HvARRAY(hv) */)
1902         (void)memzero(xhv->xhv_array /* HvARRAY(hv) */,
1903                       (xhv->xhv_max+1 /* HvMAX(hv)+1 */) * sizeof(HE*));
1904
1905     if (SvRMAGICAL(hv))
1906         mg_clear((SV*)hv);
1907
1908     HvHASKFLAGS_off(hv);
1909     HvREHASH_off(hv);
1910 }
1911
1912 STATIC void
1913 S_hfreeentries(pTHX_ HV *hv)
1914 {
1915     register HE **array;
1916     register HE *entry;
1917     register HE *oentry = Null(HE*);
1918     I32 riter;
1919     I32 max;
1920
1921     if (!hv)
1922         return;
1923     if (!HvARRAY(hv))
1924         return;
1925
1926     riter = 0;
1927     max = HvMAX(hv);
1928     array = HvARRAY(hv);
1929     /* make everyone else think the array is empty, so that the destructors
1930      * called for freed entries can't recusively mess with us */
1931     HvARRAY(hv) = Null(HE**); 
1932     HvFILL(hv) = 0;
1933     ((XPVHV*) SvANY(hv))->xhv_keys = 0;
1934
1935     entry = array[0];
1936     for (;;) {
1937         if (entry) {
1938             oentry = entry;
1939             entry = HeNEXT(entry);
1940             hv_free_ent(hv, oentry);
1941         }
1942         if (!entry) {
1943             if (++riter > max)
1944                 break;
1945             entry = array[riter];
1946         }
1947     }
1948     HvARRAY(hv) = array;
1949     (void)hv_iterinit(hv);
1950 }
1951
1952 /*
1953 =for apidoc hv_undef
1954
1955 Undefines the hash.
1956
1957 =cut
1958 */
1959
1960 void
1961 Perl_hv_undef(pTHX_ HV *hv)
1962 {
1963     register XPVHV* xhv;
1964     if (!hv)
1965         return;
1966     DEBUG_A(Perl_hv_assert(aTHX_ hv));
1967     xhv = (XPVHV*)SvANY(hv);
1968     hfreeentries(hv);
1969     Safefree(xhv->xhv_array /* HvARRAY(hv) */);
1970     if (HvNAME(hv)) {
1971         if(PL_stashcache)
1972             hv_delete(PL_stashcache, HvNAME(hv), strlen(HvNAME(hv)), G_DISCARD);
1973         Safefree(HvNAME(hv));
1974         HvNAME(hv) = 0;
1975     }
1976     xhv->xhv_max   = 7; /* HvMAX(hv) = 7 (it's a normal hash) */
1977     xhv->xhv_array = 0; /* HvARRAY(hv) = 0 */
1978     xhv->xhv_placeholders = 0; /* HvPLACEHOLDERS(hv) = 0 */
1979
1980     if (SvRMAGICAL(hv))
1981         mg_clear((SV*)hv);
1982 }
1983
1984 /*
1985 =for apidoc hv_iterinit
1986
1987 Prepares a starting point to traverse a hash table.  Returns the number of
1988 keys in the hash (i.e. the same as C<HvKEYS(tb)>).  The return value is
1989 currently only meaningful for hashes without tie magic.
1990
1991 NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
1992 hash buckets that happen to be in use.  If you still need that esoteric
1993 value, you can get it through the macro C<HvFILL(tb)>.
1994
1995
1996 =cut
1997 */
1998
1999 I32
2000 Perl_hv_iterinit(pTHX_ HV *hv)
2001 {
2002     register XPVHV* xhv;
2003     HE *entry;
2004
2005     if (!hv)
2006         Perl_croak(aTHX_ "Bad hash");
2007     xhv = (XPVHV*)SvANY(hv);
2008     entry = xhv->xhv_eiter; /* HvEITER(hv) */
2009     if (entry && HvLAZYDEL(hv)) {       /* was deleted earlier? */
2010         HvLAZYDEL_off(hv);
2011         hv_free_ent(hv, entry);
2012     }
2013     xhv->xhv_riter = -1;        /* HvRITER(hv) = -1 */
2014     xhv->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
2015     /* used to be xhv->xhv_fill before 5.004_65 */
2016     return XHvTOTALKEYS(xhv);
2017 }
2018 /*
2019 =for apidoc hv_iternext
2020
2021 Returns entries from a hash iterator.  See C<hv_iterinit>.
2022
2023 You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
2024 iterator currently points to, without losing your place or invalidating your
2025 iterator.  Note that in this case the current entry is deleted from the hash
2026 with your iterator holding the last reference to it.  Your iterator is flagged
2027 to free the entry on the next call to C<hv_iternext>, so you must not discard
2028 your iterator immediately else the entry will leak - call C<hv_iternext> to
2029 trigger the resource deallocation.
2030
2031 =cut
2032 */
2033
2034 HE *
2035 Perl_hv_iternext(pTHX_ HV *hv)
2036 {
2037     return hv_iternext_flags(hv, 0);
2038 }
2039
2040 /*
2041 =for apidoc hv_iternext_flags
2042
2043 Returns entries from a hash iterator.  See C<hv_iterinit> and C<hv_iternext>.
2044 The C<flags> value will normally be zero; if HV_ITERNEXT_WANTPLACEHOLDERS is
2045 set the placeholders keys (for restricted hashes) will be returned in addition
2046 to normal keys. By default placeholders are automatically skipped over.
2047 Currently a placeholder is implemented with a value that is
2048 C<&Perl_sv_placeholder>. Note that the implementation of placeholders and
2049 restricted hashes may change, and the implementation currently is
2050 insufficiently abstracted for any change to be tidy.
2051
2052 =cut
2053 */
2054
2055 HE *
2056 Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
2057 {
2058     register XPVHV* xhv;
2059     register HE *entry;
2060     HE *oldentry;
2061     MAGIC* mg;
2062
2063     if (!hv)
2064         Perl_croak(aTHX_ "Bad hash");
2065     xhv = (XPVHV*)SvANY(hv);
2066     oldentry = entry = xhv->xhv_eiter; /* HvEITER(hv) */
2067
2068     if ((mg = SvTIED_mg((SV*)hv, PERL_MAGIC_tied))) {
2069         SV *key = sv_newmortal();
2070         if (entry) {
2071             sv_setsv(key, HeSVKEY_force(entry));
2072             SvREFCNT_dec(HeSVKEY(entry));       /* get rid of previous key */
2073         }
2074         else {
2075             char *k;
2076             HEK *hek;
2077
2078             /* one HE per MAGICAL hash */
2079             xhv->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
2080             Zero(entry, 1, HE);
2081             Newz(54, k, HEK_BASESIZE + sizeof(SV*), char);
2082             hek = (HEK*)k;
2083             HeKEY_hek(entry) = hek;
2084             HeKLEN(entry) = HEf_SVKEY;
2085         }
2086         magic_nextpack((SV*) hv,mg,key);
2087         if (SvOK(key)) {
2088             /* force key to stay around until next time */
2089             HeSVKEY_set(entry, SvREFCNT_inc(key));
2090             return entry;               /* beware, hent_val is not set */
2091         }
2092         if (HeVAL(entry))
2093             SvREFCNT_dec(HeVAL(entry));
2094         Safefree(HeKEY_hek(entry));
2095         del_HE(entry);
2096         xhv->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
2097         return Null(HE*);
2098     }
2099 #ifdef DYNAMIC_ENV_FETCH  /* set up %ENV for iteration */
2100     if (!entry && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
2101         prime_env_iter();
2102 #endif
2103
2104     if (!xhv->xhv_array /* !HvARRAY(hv) */)
2105         Newz(506, xhv->xhv_array /* HvARRAY(hv) */,
2106              PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
2107              char);
2108     /* At start of hash, entry is NULL.  */
2109     if (entry)
2110     {
2111         entry = HeNEXT(entry);
2112         if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2113             /*
2114              * Skip past any placeholders -- don't want to include them in
2115              * any iteration.
2116              */
2117             while (entry && HeVAL(entry) == &PL_sv_placeholder) {
2118                 entry = HeNEXT(entry);
2119             }
2120         }
2121     }
2122     while (!entry) {
2123         /* OK. Come to the end of the current list.  Grab the next one.  */
2124
2125         xhv->xhv_riter++; /* HvRITER(hv)++ */
2126         if (xhv->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
2127             /* There is no next one.  End of the hash.  */
2128             xhv->xhv_riter = -1; /* HvRITER(hv) = -1 */
2129             break;
2130         }
2131         /* entry = (HvARRAY(hv))[HvRITER(hv)]; */
2132         entry = ((HE**)xhv->xhv_array)[xhv->xhv_riter];
2133
2134         if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2135             /* If we have an entry, but it's a placeholder, don't count it.
2136                Try the next.  */
2137             while (entry && HeVAL(entry) == &PL_sv_placeholder)
2138                 entry = HeNEXT(entry);
2139         }
2140         /* Will loop again if this linked list starts NULL
2141            (for HV_ITERNEXT_WANTPLACEHOLDERS)
2142            or if we run through it and find only placeholders.  */
2143     }
2144
2145     if (oldentry && HvLAZYDEL(hv)) {            /* was deleted earlier? */
2146         HvLAZYDEL_off(hv);
2147         hv_free_ent(hv, oldentry);
2148     }
2149
2150     /*if (HvREHASH(hv) && entry && !HeKREHASH(entry))
2151       PerlIO_printf(PerlIO_stderr(), "Awooga %p %p\n", hv, entry);*/
2152
2153     xhv->xhv_eiter = entry; /* HvEITER(hv) = entry */
2154     return entry;
2155 }
2156
2157 /*
2158 =for apidoc hv_iterkey
2159
2160 Returns the key from the current position of the hash iterator.  See
2161 C<hv_iterinit>.
2162
2163 =cut
2164 */
2165
2166 char *
2167 Perl_hv_iterkey(pTHX_ register HE *entry, I32 *retlen)
2168 {
2169     if (HeKLEN(entry) == HEf_SVKEY) {
2170         STRLEN len;
2171         char *p = SvPV(HeKEY_sv(entry), len);
2172         *retlen = len;
2173         return p;
2174     }
2175     else {
2176         *retlen = HeKLEN(entry);
2177         return HeKEY(entry);
2178     }
2179 }
2180
2181 /* unlike hv_iterval(), this always returns a mortal copy of the key */
2182 /*
2183 =for apidoc hv_iterkeysv
2184
2185 Returns the key as an C<SV*> from the current position of the hash
2186 iterator.  The return value will always be a mortal copy of the key.  Also
2187 see C<hv_iterinit>.
2188
2189 =cut
2190 */
2191
2192 SV *
2193 Perl_hv_iterkeysv(pTHX_ register HE *entry)
2194 {
2195     if (HeKLEN(entry) != HEf_SVKEY) {
2196         HEK *hek = HeKEY_hek(entry);
2197         int flags = HEK_FLAGS(hek);
2198         SV *sv;
2199
2200         if (flags & HVhek_WASUTF8) {
2201             /* Trouble :-)
2202                Andreas would like keys he put in as utf8 to come back as utf8
2203             */
2204             STRLEN utf8_len = HEK_LEN(hek);
2205             U8 *as_utf8 = bytes_to_utf8 ((U8*)HEK_KEY(hek), &utf8_len);
2206
2207             sv = newSVpvn ((char*)as_utf8, utf8_len);
2208             SvUTF8_on (sv);
2209             Safefree (as_utf8); /* bytes_to_utf8() allocates a new string */
2210         } else if (flags & HVhek_REHASH) {
2211             /* We don't have a pointer to the hv, so we have to replicate the
2212                flag into every HEK. This hv is using custom a hasing
2213                algorithm. Hence we can't return a shared string scalar, as
2214                that would contain the (wrong) hash value, and might get passed
2215                into an hv routine with a regular hash  */
2216
2217             sv = newSVpvn (HEK_KEY(hek), HEK_LEN(hek));
2218             if (HEK_UTF8(hek))
2219                 SvUTF8_on (sv);
2220         } else {
2221             sv = newSVpvn_share(HEK_KEY(hek),
2222                                 (HEK_UTF8(hek) ? -HEK_LEN(hek) : HEK_LEN(hek)),
2223                                 HEK_HASH(hek));
2224         }
2225         return sv_2mortal(sv);
2226     }
2227     return sv_mortalcopy(HeKEY_sv(entry));
2228 }
2229
2230 /*
2231 =for apidoc hv_iterval
2232
2233 Returns the value from the current position of the hash iterator.  See
2234 C<hv_iterkey>.
2235
2236 =cut
2237 */
2238
2239 SV *
2240 Perl_hv_iterval(pTHX_ HV *hv, register HE *entry)
2241 {
2242     if (SvRMAGICAL(hv)) {
2243         if (mg_find((SV*)hv, PERL_MAGIC_tied)) {
2244             SV* sv = sv_newmortal();
2245             if (HeKLEN(entry) == HEf_SVKEY)
2246                 mg_copy((SV*)hv, sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
2247             else mg_copy((SV*)hv, sv, HeKEY(entry), HeKLEN(entry));
2248             return sv;
2249         }
2250     }
2251     return HeVAL(entry);
2252 }
2253
2254 /*
2255 =for apidoc hv_iternextsv
2256
2257 Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2258 operation.
2259
2260 =cut
2261 */
2262
2263 SV *
2264 Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
2265 {
2266     HE *he;
2267     if ( (he = hv_iternext_flags(hv, 0)) == NULL)
2268         return NULL;
2269     *key = hv_iterkey(he, retlen);
2270     return hv_iterval(hv, he);
2271 }
2272
2273 /*
2274 =for apidoc hv_magic
2275
2276 Adds magic to a hash.  See C<sv_magic>.
2277
2278 =cut
2279 */
2280
2281 void
2282 Perl_hv_magic(pTHX_ HV *hv, GV *gv, int how)
2283 {
2284     sv_magic((SV*)hv, (SV*)gv, how, Nullch, 0);
2285 }
2286
2287 #if 0 /* use the macro from hv.h instead */
2288
2289 char*   
2290 Perl_sharepvn(pTHX_ const char *sv, I32 len, U32 hash)
2291 {
2292     return HEK_KEY(share_hek(sv, len, hash));
2293 }
2294
2295 #endif
2296
2297 /* possibly free a shared string if no one has access to it
2298  * len and hash must both be valid for str.
2299  */
2300 void
2301 Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
2302 {
2303     unshare_hek_or_pvn (NULL, str, len, hash);
2304 }
2305
2306
2307 void
2308 Perl_unshare_hek(pTHX_ HEK *hek)
2309 {
2310     unshare_hek_or_pvn(hek, NULL, 0, 0);
2311 }
2312
2313 /* possibly free a shared string if no one has access to it
2314    hek if non-NULL takes priority over the other 3, else str, len and hash
2315    are used.  If so, len and hash must both be valid for str.
2316  */
2317 STATIC void
2318 S_unshare_hek_or_pvn(pTHX_ HEK *hek, const char *str, I32 len, U32 hash)
2319 {
2320     register XPVHV* xhv;
2321     register HE *entry;
2322     register HE **oentry;
2323     register I32 i = 1;
2324     I32 found = 0;
2325     bool is_utf8 = FALSE;
2326     int k_flags = 0;
2327     const char *save = str;
2328
2329     if (hek) {
2330         hash = HEK_HASH(hek);
2331     } else if (len < 0) {
2332         STRLEN tmplen = -len;
2333         is_utf8 = TRUE;
2334         /* See the note in hv_fetch(). --jhi */
2335         str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2336         len = tmplen;
2337         if (is_utf8)
2338             k_flags = HVhek_UTF8;
2339         if (str != save)
2340             k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2341     }
2342
2343     /* what follows is the moral equivalent of:
2344     if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
2345         if (--*Svp == Nullsv)
2346             hv_delete(PL_strtab, str, len, G_DISCARD, hash);
2347     } */
2348     xhv = (XPVHV*)SvANY(PL_strtab);
2349     /* assert(xhv_array != 0) */
2350     LOCK_STRTAB_MUTEX;
2351     /* oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)]; */
2352     oentry = &((HE**)xhv->xhv_array)[hash & (I32) xhv->xhv_max];
2353     if (hek) {
2354         for (entry = *oentry; entry; i=0, oentry = &HeNEXT(entry), entry = *oentry) {
2355             if (HeKEY_hek(entry) != hek)
2356                 continue;
2357             found = 1;
2358             break;
2359         }
2360     } else {
2361         int flags_masked = k_flags & HVhek_MASK;
2362         for (entry = *oentry; entry; i=0, oentry = &HeNEXT(entry), entry = *oentry) {
2363             if (HeHASH(entry) != hash)          /* strings can't be equal */
2364                 continue;
2365             if (HeKLEN(entry) != len)
2366                 continue;
2367             if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len))     /* is this it? */
2368                 continue;
2369             if (HeKFLAGS(entry) != flags_masked)
2370                 continue;
2371             found = 1;
2372             break;
2373         }
2374     }
2375
2376     if (found) {
2377         if (--HeVAL(entry) == Nullsv) {
2378             *oentry = HeNEXT(entry);
2379             if (i && !*oentry)
2380                 xhv->xhv_fill--; /* HvFILL(hv)-- */
2381             Safefree(HeKEY_hek(entry));
2382             del_HE(entry);
2383             xhv->xhv_keys--; /* HvKEYS(hv)-- */
2384         }
2385     }
2386
2387     UNLOCK_STRTAB_MUTEX;
2388     if (!found && ckWARN_d(WARN_INTERNAL))
2389         Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
2390                     "Attempt to free non-existent shared string '%s'%s",
2391                     hek ? HEK_KEY(hek) : str,
2392                     (k_flags & HVhek_UTF8) ? " (utf8)" : "");
2393     if (k_flags & HVhek_FREEKEY)
2394         Safefree(str);
2395 }
2396
2397 /* get a (constant) string ptr from the global string table
2398  * string will get added if it is not already there.
2399  * len and hash must both be valid for str.
2400  */
2401 HEK *
2402 Perl_share_hek(pTHX_ const char *str, I32 len, register U32 hash)
2403 {
2404     bool is_utf8 = FALSE;
2405     int flags = 0;
2406     const char *save = str;
2407
2408     if (len < 0) {
2409       STRLEN tmplen = -len;
2410       is_utf8 = TRUE;
2411       /* See the note in hv_fetch(). --jhi */
2412       str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2413       len = tmplen;
2414       /* If we were able to downgrade here, then than means that we were passed
2415          in a key which only had chars 0-255, but was utf8 encoded.  */
2416       if (is_utf8)
2417           flags = HVhek_UTF8;
2418       /* If we found we were able to downgrade the string to bytes, then
2419          we should flag that it needs upgrading on keys or each.  Also flag
2420          that we need share_hek_flags to free the string.  */
2421       if (str != save)
2422           flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2423     }
2424
2425     return share_hek_flags (str, len, hash, flags);
2426 }
2427
2428 STATIC HEK *
2429 S_share_hek_flags(pTHX_ const char *str, I32 len, register U32 hash, int flags)
2430 {
2431     register XPVHV* xhv;
2432     register HE *entry;
2433     register HE **oentry;
2434     register I32 i = 1;
2435     I32 found = 0;
2436     int flags_masked = flags & HVhek_MASK;
2437
2438     /* what follows is the moral equivalent of:
2439
2440     if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
2441         hv_store(PL_strtab, str, len, Nullsv, hash);
2442
2443         Can't rehash the shared string table, so not sure if it's worth
2444         counting the number of entries in the linked list
2445     */
2446     xhv = (XPVHV*)SvANY(PL_strtab);
2447     /* assert(xhv_array != 0) */
2448     LOCK_STRTAB_MUTEX;
2449     /* oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)]; */
2450     oentry = &((HE**)xhv->xhv_array)[hash & (I32) xhv->xhv_max];
2451     for (entry = *oentry; entry; i=0, entry = HeNEXT(entry)) {
2452         if (HeHASH(entry) != hash)              /* strings can't be equal */
2453             continue;
2454         if (HeKLEN(entry) != len)
2455             continue;
2456         if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2457             continue;
2458         if (HeKFLAGS(entry) != flags_masked)
2459             continue;
2460         found = 1;
2461         break;
2462     }
2463     if (!found) {
2464         entry = new_HE();
2465         HeKEY_hek(entry) = save_hek_flags(str, len, hash, flags);
2466         HeVAL(entry) = Nullsv;
2467         HeNEXT(entry) = *oentry;
2468         *oentry = entry;
2469         xhv->xhv_keys++; /* HvKEYS(hv)++ */
2470         if (i) {                                /* initial entry? */
2471             xhv->xhv_fill++; /* HvFILL(hv)++ */
2472         } else if (xhv->xhv_keys > (IV)xhv->xhv_max /* HvKEYS(hv) > HvMAX(hv) */) {
2473                 hsplit(PL_strtab);
2474         }
2475     }
2476
2477     ++HeVAL(entry);                             /* use value slot as REFCNT */
2478     UNLOCK_STRTAB_MUTEX;
2479
2480     if (flags & HVhek_FREEKEY)
2481         Safefree(str);
2482
2483     return HeKEY_hek(entry);
2484 }
2485
2486
2487 /*
2488 =for apidoc hv_assert
2489
2490 Check that a hash is in an internally consistent state.
2491
2492 =cut
2493 */
2494
2495 void
2496 Perl_hv_assert(pTHX_ HV *hv)
2497 {
2498   HE* entry;
2499   int withflags = 0;
2500   int placeholders = 0;
2501   int real = 0;
2502   int bad = 0;
2503   I32 riter = HvRITER(hv);
2504   HE *eiter = HvEITER(hv);
2505
2506   (void)hv_iterinit(hv);
2507
2508   while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
2509     /* sanity check the values */
2510     if (HeVAL(entry) == &PL_sv_placeholder) {
2511       placeholders++;
2512     } else {
2513       real++;
2514     }
2515     /* sanity check the keys */
2516     if (HeSVKEY(entry)) {
2517       /* Don't know what to check on SV keys.  */
2518     } else if (HeKUTF8(entry)) {
2519       withflags++;
2520        if (HeKWASUTF8(entry)) {
2521          PerlIO_printf(Perl_debug_log,
2522                        "hash key has both WASUFT8 and UTF8: '%.*s'\n",
2523                        (int) HeKLEN(entry),  HeKEY(entry));
2524          bad = 1;
2525        }
2526     } else if (HeKWASUTF8(entry)) {
2527       withflags++;
2528     }
2529   }
2530   if (!SvTIED_mg((SV*)hv, PERL_MAGIC_tied)) {
2531     if (HvUSEDKEYS(hv) != real) {
2532       PerlIO_printf(Perl_debug_log, "Count %d key(s), but hash reports %d\n",
2533                     (int) real, (int) HvUSEDKEYS(hv));
2534       bad = 1;
2535     }
2536     if (HvPLACEHOLDERS(hv) != placeholders) {
2537       PerlIO_printf(Perl_debug_log,
2538                     "Count %d placeholder(s), but hash reports %d\n",
2539                     (int) placeholders, (int) HvPLACEHOLDERS(hv));
2540       bad = 1;
2541     }
2542   }
2543   if (withflags && ! HvHASKFLAGS(hv)) {
2544     PerlIO_printf(Perl_debug_log,
2545                   "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
2546                   withflags);
2547     bad = 1;
2548   }
2549   if (bad) {
2550     sv_dump((SV *)hv);
2551   }
2552   HvRITER(hv) = riter;          /* Restore hash iterator state */
2553   HvEITER(hv) = eiter;
2554 }