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