Send all delete()/delete_ent() calls via S_hv_fetch_common().
[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, 2004, 2005, 2006, 2007, 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 A HV structure represents a Perl hash. It consists mainly of an array
19 of pointers, each of which points to a linked list of HE structures. The
20 array is indexed by the hash function of the key, so each linked list
21 represents all the hash entries with the same hash value. Each HE contains
22 a pointer to the actual value, plus a pointer to a HEK structure which
23 holds the key and hash value.
24
25 =cut
26
27 */
28
29 #include "EXTERN.h"
30 #define PERL_IN_HV_C
31 #define PERL_HASH_INTERNAL_ACCESS
32 #include "perl.h"
33
34 #define HV_MAX_LENGTH_BEFORE_SPLIT 14
35
36 static const char S_strtab_error[]
37     = "Cannot modify shared string table in hv_%s";
38
39 STATIC void
40 S_more_he(pTHX)
41 {
42     dVAR;
43     HE* he = (HE*) Perl_get_arena(aTHX_ PERL_ARENA_SIZE, HE_SVSLOT);
44     HE * const heend = &he[PERL_ARENA_SIZE / sizeof(HE) - 1];
45
46     PL_body_roots[HE_SVSLOT] = he;
47     while (he < heend) {
48         HeNEXT(he) = (HE*)(he + 1);
49         he++;
50     }
51     HeNEXT(he) = 0;
52 }
53
54 #ifdef PURIFY
55
56 #define new_HE() (HE*)safemalloc(sizeof(HE))
57 #define del_HE(p) safefree((char*)p)
58
59 #else
60
61 STATIC HE*
62 S_new_he(pTHX)
63 {
64     dVAR;
65     HE* he;
66     void ** const root = &PL_body_roots[HE_SVSLOT];
67
68     if (!*root)
69         S_more_he(aTHX);
70     he = (HE*) *root;
71     assert(he);
72     *root = HeNEXT(he);
73     return he;
74 }
75
76 #define new_HE() new_he()
77 #define del_HE(p) \
78     STMT_START { \
79         HeNEXT(p) = (HE*)(PL_body_roots[HE_SVSLOT]);    \
80         PL_body_roots[HE_SVSLOT] = p; \
81     } STMT_END
82
83
84
85 #endif
86
87 STATIC HEK *
88 S_save_hek_flags(const char *str, I32 len, U32 hash, int flags)
89 {
90     const int flags_masked = flags & HVhek_MASK;
91     char *k;
92     register HEK *hek;
93
94     Newx(k, HEK_BASESIZE + len + 2, char);
95     hek = (HEK*)k;
96     Copy(str, HEK_KEY(hek), len, char);
97     HEK_KEY(hek)[len] = 0;
98     HEK_LEN(hek) = len;
99     HEK_HASH(hek) = hash;
100     HEK_FLAGS(hek) = (unsigned char)flags_masked | HVhek_UNSHARED;
101
102     if (flags & HVhek_FREEKEY)
103         Safefree(str);
104     return hek;
105 }
106
107 /* free the pool of temporary HE/HEK pairs returned by hv_fetch_ent
108  * for tied hashes */
109
110 void
111 Perl_free_tied_hv_pool(pTHX)
112 {
113     dVAR;
114     HE *he = PL_hv_fetch_ent_mh;
115     while (he) {
116         HE * const ohe = he;
117         Safefree(HeKEY_hek(he));
118         he = HeNEXT(he);
119         del_HE(ohe);
120     }
121     PL_hv_fetch_ent_mh = NULL;
122 }
123
124 #if defined(USE_ITHREADS)
125 HEK *
126 Perl_hek_dup(pTHX_ HEK *source, CLONE_PARAMS* param)
127 {
128     HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
129
130     PERL_UNUSED_ARG(param);
131
132     if (shared) {
133         /* We already shared this hash key.  */
134         (void)share_hek_hek(shared);
135     }
136     else {
137         shared
138             = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
139                               HEK_HASH(source), HEK_FLAGS(source));
140         ptr_table_store(PL_ptr_table, source, shared);
141     }
142     return shared;
143 }
144
145 HE *
146 Perl_he_dup(pTHX_ const HE *e, bool shared, CLONE_PARAMS* param)
147 {
148     HE *ret;
149
150     if (!e)
151         return NULL;
152     /* look for it in the table first */
153     ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
154     if (ret)
155         return ret;
156
157     /* create anew and remember what it is */
158     ret = new_HE();
159     ptr_table_store(PL_ptr_table, e, ret);
160
161     HeNEXT(ret) = he_dup(HeNEXT(e),shared, param);
162     if (HeKLEN(e) == HEf_SVKEY) {
163         char *k;
164         Newx(k, HEK_BASESIZE + sizeof(SV*), char);
165         HeKEY_hek(ret) = (HEK*)k;
166         HeKEY_sv(ret) = SvREFCNT_inc(sv_dup(HeKEY_sv(e), param));
167     }
168     else if (shared) {
169         /* This is hek_dup inlined, which seems to be important for speed
170            reasons.  */
171         HEK * const source = HeKEY_hek(e);
172         HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
173
174         if (shared) {
175             /* We already shared this hash key.  */
176             (void)share_hek_hek(shared);
177         }
178         else {
179             shared
180                 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
181                                   HEK_HASH(source), HEK_FLAGS(source));
182             ptr_table_store(PL_ptr_table, source, shared);
183         }
184         HeKEY_hek(ret) = shared;
185     }
186     else
187         HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
188                                         HeKFLAGS(e));
189     HeVAL(ret) = SvREFCNT_inc(sv_dup(HeVAL(e), param));
190     return ret;
191 }
192 #endif  /* USE_ITHREADS */
193
194 static void
195 S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
196                 const char *msg)
197 {
198     SV * const sv = sv_newmortal();
199     if (!(flags & HVhek_FREEKEY)) {
200         sv_setpvn(sv, key, klen);
201     }
202     else {
203         /* Need to free saved eventually assign to mortal SV */
204         /* XXX is this line an error ???:  SV *sv = sv_newmortal(); */
205         sv_usepvn(sv, (char *) key, klen);
206     }
207     if (flags & HVhek_UTF8) {
208         SvUTF8_on(sv);
209     }
210     Perl_croak(aTHX_ msg, SVfARG(sv));
211 }
212
213 /* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
214  * contains an SV* */
215
216 /*
217 =for apidoc hv_store
218
219 Stores an SV in a hash.  The hash key is specified as C<key> and C<klen> is
220 the length of the key.  The C<hash> parameter is the precomputed hash
221 value; if it is zero then Perl will compute it.  The return value will be
222 NULL if the operation failed or if the value did not need to be actually
223 stored within the hash (as in the case of tied hashes).  Otherwise it can
224 be dereferenced to get the original C<SV*>.  Note that the caller is
225 responsible for suitably incrementing the reference count of C<val> before
226 the call, and decrementing it if the function returned NULL.  Effectively
227 a successful hv_store takes ownership of one reference to C<val>.  This is
228 usually what you want; a newly created SV has a reference count of one, so
229 if all your code does is create SVs then store them in a hash, hv_store
230 will own the only reference to the new SV, and your code doesn't need to do
231 anything further to tidy up.  hv_store is not implemented as a call to
232 hv_store_ent, and does not create a temporary SV for the key, so if your
233 key data is not already in SV form then use hv_store in preference to
234 hv_store_ent.
235
236 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
237 information on how to use this function on tied hashes.
238
239 =cut
240 */
241
242 SV**
243 Perl_hv_store(pTHX_ HV *hv, const char *key, I32 klen_i32, SV *val, U32 hash)
244 {
245     HE *hek;
246     STRLEN klen;
247     int flags;
248
249     if (klen_i32 < 0) {
250         klen = -klen_i32;
251         flags = HVhek_UTF8;
252     } else {
253         klen = klen_i32;
254         flags = 0;
255     }
256     hek = hv_fetch_common (hv, NULL, key, klen, flags,
257                            (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
258     return hek ? &HeVAL(hek) : NULL;
259 }
260
261 /* XXX This looks like an ideal candidate to inline */
262 SV**
263 Perl_hv_store_flags(pTHX_ HV *hv, const char *key, I32 klen, SV *val,
264                  register U32 hash, int flags)
265 {
266     HE * const hek = hv_fetch_common (hv, NULL, key, klen, flags,
267                                (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
268     return hek ? &HeVAL(hek) : NULL;
269 }
270
271 /*
272 =for apidoc hv_store_ent
273
274 Stores C<val> in a hash.  The hash key is specified as C<key>.  The C<hash>
275 parameter is the precomputed hash value; if it is zero then Perl will
276 compute it.  The return value is the new hash entry so created.  It will be
277 NULL if the operation failed or if the value did not need to be actually
278 stored within the hash (as in the case of tied hashes).  Otherwise the
279 contents of the return value can be accessed using the C<He?> macros
280 described here.  Note that the caller is responsible for suitably
281 incrementing the reference count of C<val> before the call, and
282 decrementing it if the function returned NULL.  Effectively a successful
283 hv_store_ent takes ownership of one reference to C<val>.  This is
284 usually what you want; a newly created SV has a reference count of one, so
285 if all your code does is create SVs then store them in a hash, hv_store
286 will own the only reference to the new SV, and your code doesn't need to do
287 anything further to tidy up.  Note that hv_store_ent only reads the C<key>;
288 unlike C<val> it does not take ownership of it, so maintaining the correct
289 reference count on C<key> is entirely the caller's responsibility.  hv_store
290 is not implemented as a call to hv_store_ent, and does not create a temporary
291 SV for the key, so if your key data is not already in SV form then use
292 hv_store in preference to hv_store_ent.
293
294 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
295 information on how to use this function on tied hashes.
296
297 =cut
298 */
299
300 /* XXX This looks like an ideal candidate to inline */
301 HE *
302 Perl_hv_store_ent(pTHX_ HV *hv, SV *keysv, SV *val, U32 hash)
303 {
304   return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISSTORE, val, hash);
305 }
306
307 /*
308 =for apidoc hv_exists
309
310 Returns a boolean indicating whether the specified hash key exists.  The
311 C<klen> is the length of the key.
312
313 =cut
314 */
315
316 bool
317 Perl_hv_exists(pTHX_ HV *hv, const char *key, I32 klen_i32)
318 {
319     STRLEN klen;
320     int flags;
321
322     if (klen_i32 < 0) {
323         klen = -klen_i32;
324         flags = HVhek_UTF8;
325     } else {
326         klen = klen_i32;
327         flags = 0;
328     }
329     return hv_fetch_common(hv, NULL, key, klen, flags, HV_FETCH_ISEXISTS, 0, 0)
330         ? TRUE : FALSE;
331 }
332
333 /*
334 =for apidoc hv_fetch
335
336 Returns the SV which corresponds to the specified key in the hash.  The
337 C<klen> is the length of the key.  If C<lval> is set then the fetch will be
338 part of a store.  Check that the return value is non-null before
339 dereferencing it to an C<SV*>.
340
341 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
342 information on how to use this function on tied hashes.
343
344 =cut
345 */
346
347 SV**
348 Perl_hv_fetch(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 lval)
349 {
350     HE *hek;
351     STRLEN klen;
352     int flags;
353
354     if (klen_i32 < 0) {
355         klen = -klen_i32;
356         flags = HVhek_UTF8;
357     } else {
358         klen = klen_i32;
359         flags = 0;
360     }
361     hek = hv_fetch_common (hv, NULL, key, klen, flags,
362                            lval ? (HV_FETCH_JUST_SV | HV_FETCH_LVALUE) : HV_FETCH_JUST_SV,
363                            NULL, 0);
364     return hek ? &HeVAL(hek) : NULL;
365 }
366
367 /*
368 =for apidoc hv_exists_ent
369
370 Returns a boolean indicating whether the specified hash key exists. C<hash>
371 can be a valid precomputed hash value, or 0 to ask for it to be
372 computed.
373
374 =cut
375 */
376
377 /* XXX This looks like an ideal candidate to inline */
378 bool
379 Perl_hv_exists_ent(pTHX_ HV *hv, SV *keysv, U32 hash)
380 {
381     return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISEXISTS, 0, hash)
382         ? TRUE : FALSE;
383 }
384
385 /* returns an HE * structure with the all fields set */
386 /* note that hent_val will be a mortal sv for MAGICAL hashes */
387 /*
388 =for apidoc hv_fetch_ent
389
390 Returns the hash entry which corresponds to the specified key in the hash.
391 C<hash> must be a valid precomputed hash number for the given C<key>, or 0
392 if you want the function to compute it.  IF C<lval> is set then the fetch
393 will be part of a store.  Make sure the return value is non-null before
394 accessing it.  The return value when C<tb> is a tied hash is a pointer to a
395 static location, so be sure to make a copy of the structure if you need to
396 store it somewhere.
397
398 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
399 information on how to use this function on tied hashes.
400
401 =cut
402 */
403
404 HE *
405 Perl_hv_fetch_ent(pTHX_ HV *hv, SV *keysv, I32 lval, register U32 hash)
406 {
407     return hv_fetch_common(hv, keysv, NULL, 0, 0, 
408                            (lval ? HV_FETCH_LVALUE : 0), NULL, hash);
409 }
410
411 STATIC HE *
412 S_hv_fetch_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
413                   int flags, int action, SV *val, register U32 hash)
414 {
415     dVAR;
416     XPVHV* xhv;
417     HE *entry;
418     HE **oentry;
419     SV *sv;
420     bool is_utf8;
421     int masked_flags;
422
423     if (!hv)
424         return NULL;
425
426     if (SvSMAGICAL(hv) && SvGMAGICAL(hv) && !(action & HV_DISABLE_UVAR_XKEY)) {
427         keysv = hv_magic_uvar_xkey(hv, keysv, key, klen, flags, action);
428         /* If a fetch-as-store fails on the fetch, then the action is to
429            recurse once into "hv_store". If we didn't do this, then that
430            recursive call would call the key conversion routine again.
431            However, as we replace the original key with the converted
432            key, this would result in a double conversion, which would show
433            up as a bug if the conversion routine is not idempotent.  */
434         hash = 0;
435     }
436     if (keysv) {
437         if (flags & HVhek_FREEKEY)
438             Safefree(key);
439         key = SvPV_const(keysv, klen);
440         flags = 0;
441         is_utf8 = (SvUTF8(keysv) != 0);
442     } else {
443         is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
444     }
445
446     if (action & HV_DELETE) {
447         return (HE *) hv_delete_common(hv, keysv, key, klen,
448                                        flags | (is_utf8 ? HVhek_UTF8 : 0),
449                                        action, hash);
450     }
451
452     xhv = (XPVHV*)SvANY(hv);
453     if (SvMAGICAL(hv)) {
454         if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS))) {
455             if ( mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv))
456             {
457                 /* XXX should be able to skimp on the HE/HEK here when
458                    HV_FETCH_JUST_SV is true.  */
459                 if (!keysv) {
460                     keysv = newSVpvn(key, klen);
461                     if (is_utf8) {
462                         SvUTF8_on(keysv);
463                     }
464                 } else {
465                     keysv = newSVsv(keysv);
466                 }
467                 sv = sv_newmortal();
468                 mg_copy((SV*)hv, sv, (char *)keysv, HEf_SVKEY);
469
470                 /* grab a fake HE/HEK pair from the pool or make a new one */
471                 entry = PL_hv_fetch_ent_mh;
472                 if (entry)
473                     PL_hv_fetch_ent_mh = HeNEXT(entry);
474                 else {
475                     char *k;
476                     entry = new_HE();
477                     Newx(k, HEK_BASESIZE + sizeof(SV*), char);
478                     HeKEY_hek(entry) = (HEK*)k;
479                 }
480                 HeNEXT(entry) = NULL;
481                 HeSVKEY_set(entry, keysv);
482                 HeVAL(entry) = sv;
483                 sv_upgrade(sv, SVt_PVLV);
484                 LvTYPE(sv) = 'T';
485                  /* so we can free entry when freeing sv */
486                 LvTARG(sv) = (SV*)entry;
487
488                 /* XXX remove at some point? */
489                 if (flags & HVhek_FREEKEY)
490                     Safefree(key);
491
492                 return entry;
493             }
494 #ifdef ENV_IS_CASELESS
495             else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
496                 U32 i;
497                 for (i = 0; i < klen; ++i)
498                     if (isLOWER(key[i])) {
499                         /* Would be nice if we had a routine to do the
500                            copy and upercase in a single pass through.  */
501                         const char * const nkey = strupr(savepvn(key,klen));
502                         /* Note that this fetch is for nkey (the uppercased
503                            key) whereas the store is for key (the original)  */
504                         entry = hv_fetch_common(hv, NULL, nkey, klen,
505                                                 HVhek_FREEKEY, /* free nkey */
506                                                 0 /* non-LVAL fetch */
507                                                 | HV_DISABLE_UVAR_XKEY,
508                                                 NULL /* no value */,
509                                                 0 /* compute hash */);
510                         if (!entry && (action & HV_FETCH_LVALUE)) {
511                             /* This call will free key if necessary.
512                                Do it this way to encourage compiler to tail
513                                call optimise.  */
514                             entry = hv_fetch_common(hv, keysv, key, klen,
515                                                     flags,
516                                                     HV_FETCH_ISSTORE
517                                                     | HV_DISABLE_UVAR_XKEY,
518                                                     newSV(0), hash);
519                         } else {
520                             if (flags & HVhek_FREEKEY)
521                                 Safefree(key);
522                         }
523                         return entry;
524                     }
525             }
526 #endif
527         } /* ISFETCH */
528         else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
529             if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
530                 /* I don't understand why hv_exists_ent has svret and sv,
531                    whereas hv_exists only had one.  */
532                 SV * const svret = sv_newmortal();
533                 sv = sv_newmortal();
534
535                 if (keysv || is_utf8) {
536                     if (!keysv) {
537                         keysv = newSVpvn(key, klen);
538                         SvUTF8_on(keysv);
539                     } else {
540                         keysv = newSVsv(keysv);
541                     }
542                     mg_copy((SV*)hv, sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
543                 } else {
544                     mg_copy((SV*)hv, sv, key, klen);
545                 }
546                 if (flags & HVhek_FREEKEY)
547                     Safefree(key);
548                 magic_existspack(svret, mg_find(sv, PERL_MAGIC_tiedelem));
549                 /* This cast somewhat evil, but I'm merely using NULL/
550                    not NULL to return the boolean exists.
551                    And I know hv is not NULL.  */
552                 return SvTRUE(svret) ? (HE *)hv : NULL;
553                 }
554 #ifdef ENV_IS_CASELESS
555             else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
556                 /* XXX This code isn't UTF8 clean.  */
557                 char * const keysave = (char * const)key;
558                 /* Will need to free this, so set FREEKEY flag.  */
559                 key = savepvn(key,klen);
560                 key = (const char*)strupr((char*)key);
561                 is_utf8 = FALSE;
562                 hash = 0;
563                 keysv = 0;
564
565                 if (flags & HVhek_FREEKEY) {
566                     Safefree(keysave);
567                 }
568                 flags |= HVhek_FREEKEY;
569             }
570 #endif
571         } /* ISEXISTS */
572         else if (action & HV_FETCH_ISSTORE) {
573             bool needs_copy;
574             bool needs_store;
575             hv_magic_check (hv, &needs_copy, &needs_store);
576             if (needs_copy) {
577                 const bool save_taint = PL_tainted;
578                 if (keysv || is_utf8) {
579                     if (!keysv) {
580                         keysv = newSVpvn(key, klen);
581                         SvUTF8_on(keysv);
582                     }
583                     if (PL_tainting)
584                         PL_tainted = SvTAINTED(keysv);
585                     keysv = sv_2mortal(newSVsv(keysv));
586                     mg_copy((SV*)hv, val, (char*)keysv, HEf_SVKEY);
587                 } else {
588                     mg_copy((SV*)hv, val, key, klen);
589                 }
590
591                 TAINT_IF(save_taint);
592                 if (!needs_store) {
593                     if (flags & HVhek_FREEKEY)
594                         Safefree(key);
595                     return NULL;
596                 }
597 #ifdef ENV_IS_CASELESS
598                 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
599                     /* XXX This code isn't UTF8 clean.  */
600                     const char *keysave = key;
601                     /* Will need to free this, so set FREEKEY flag.  */
602                     key = savepvn(key,klen);
603                     key = (const char*)strupr((char*)key);
604                     is_utf8 = FALSE;
605                     hash = 0;
606                     keysv = 0;
607
608                     if (flags & HVhek_FREEKEY) {
609                         Safefree(keysave);
610                     }
611                     flags |= HVhek_FREEKEY;
612                 }
613 #endif
614             }
615         } /* ISSTORE */
616     } /* SvMAGICAL */
617
618     if (!HvARRAY(hv)) {
619         if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
620 #ifdef DYNAMIC_ENV_FETCH  /* if it's an %ENV lookup, we may get it on the fly */
621                  || (SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
622 #endif
623                                                                   ) {
624             char *array;
625             Newxz(array,
626                  PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
627                  char);
628             HvARRAY(hv) = (HE**)array;
629         }
630 #ifdef DYNAMIC_ENV_FETCH
631         else if (action & HV_FETCH_ISEXISTS) {
632             /* for an %ENV exists, if we do an insert it's by a recursive
633                store call, so avoid creating HvARRAY(hv) right now.  */
634         }
635 #endif
636         else {
637             /* XXX remove at some point? */
638             if (flags & HVhek_FREEKEY)
639                 Safefree(key);
640
641             return 0;
642         }
643     }
644
645     if (is_utf8) {
646         char * const keysave = (char *)key;
647         key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
648         if (is_utf8)
649             flags |= HVhek_UTF8;
650         else
651             flags &= ~HVhek_UTF8;
652         if (key != keysave) {
653             if (flags & HVhek_FREEKEY)
654                 Safefree(keysave);
655             flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
656         }
657     }
658
659     if (HvREHASH(hv)) {
660         PERL_HASH_INTERNAL(hash, key, klen);
661         /* We don't have a pointer to the hv, so we have to replicate the
662            flag into every HEK, so that hv_iterkeysv can see it.  */
663         /* And yes, you do need this even though you are not "storing" because
664            you can flip the flags below if doing an lval lookup.  (And that
665            was put in to give the semantics Andreas was expecting.)  */
666         flags |= HVhek_REHASH;
667     } else if (!hash) {
668         if (keysv && (SvIsCOW_shared_hash(keysv))) {
669             hash = SvSHARED_HASH(keysv);
670         } else {
671             PERL_HASH(hash, key, klen);
672         }
673     }
674
675     masked_flags = (flags & HVhek_MASK);
676
677 #ifdef DYNAMIC_ENV_FETCH
678     if (!HvARRAY(hv)) entry = NULL;
679     else
680 #endif
681     {
682         entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
683     }
684     for (; entry; entry = HeNEXT(entry)) {
685         if (HeHASH(entry) != hash)              /* strings can't be equal */
686             continue;
687         if (HeKLEN(entry) != (I32)klen)
688             continue;
689         if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen))        /* is this it? */
690             continue;
691         if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
692             continue;
693
694         if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
695             if (HeKFLAGS(entry) != masked_flags) {
696                 /* We match if HVhek_UTF8 bit in our flags and hash key's
697                    match.  But if entry was set previously with HVhek_WASUTF8
698                    and key now doesn't (or vice versa) then we should change
699                    the key's flag, as this is assignment.  */
700                 if (HvSHAREKEYS(hv)) {
701                     /* Need to swap the key we have for a key with the flags we
702                        need. As keys are shared we can't just write to the
703                        flag, so we share the new one, unshare the old one.  */
704                     HEK * const new_hek = share_hek_flags(key, klen, hash,
705                                                    masked_flags);
706                     unshare_hek (HeKEY_hek(entry));
707                     HeKEY_hek(entry) = new_hek;
708                 }
709                 else if (hv == PL_strtab) {
710                     /* PL_strtab is usually the only hash without HvSHAREKEYS,
711                        so putting this test here is cheap  */
712                     if (flags & HVhek_FREEKEY)
713                         Safefree(key);
714                     Perl_croak(aTHX_ S_strtab_error,
715                                action & HV_FETCH_LVALUE ? "fetch" : "store");
716                 }
717                 else
718                     HeKFLAGS(entry) = masked_flags;
719                 if (masked_flags & HVhek_ENABLEHVKFLAGS)
720                     HvHASKFLAGS_on(hv);
721             }
722             if (HeVAL(entry) == &PL_sv_placeholder) {
723                 /* yes, can store into placeholder slot */
724                 if (action & HV_FETCH_LVALUE) {
725                     if (SvMAGICAL(hv)) {
726                         /* This preserves behaviour with the old hv_fetch
727                            implementation which at this point would bail out
728                            with a break; (at "if we find a placeholder, we
729                            pretend we haven't found anything")
730
731                            That break mean that if a placeholder were found, it
732                            caused a call into hv_store, which in turn would
733                            check magic, and if there is no magic end up pretty
734                            much back at this point (in hv_store's code).  */
735                         break;
736                     }
737                     /* LVAL fetch which actaully needs a store.  */
738                     val = newSV(0);
739                     HvPLACEHOLDERS(hv)--;
740                 } else {
741                     /* store */
742                     if (val != &PL_sv_placeholder)
743                         HvPLACEHOLDERS(hv)--;
744                 }
745                 HeVAL(entry) = val;
746             } else if (action & HV_FETCH_ISSTORE) {
747                 SvREFCNT_dec(HeVAL(entry));
748                 HeVAL(entry) = val;
749             }
750         } else if (HeVAL(entry) == &PL_sv_placeholder) {
751             /* if we find a placeholder, we pretend we haven't found
752                anything */
753             break;
754         }
755         if (flags & HVhek_FREEKEY)
756             Safefree(key);
757         return entry;
758     }
759 #ifdef DYNAMIC_ENV_FETCH  /* %ENV lookup?  If so, try to fetch the value now */
760     if (!(action & HV_FETCH_ISSTORE) 
761         && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
762         unsigned long len;
763         const char * const env = PerlEnv_ENVgetenv_len(key,&len);
764         if (env) {
765             sv = newSVpvn(env,len);
766             SvTAINTED_on(sv);
767             return hv_fetch_common(hv, keysv, key, klen, flags,
768                                    HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY, sv,
769                                    hash);
770         }
771     }
772 #endif
773
774     if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
775         hv_notallowed(flags, key, klen,
776                         "Attempt to access disallowed key '%"SVf"' in"
777                         " a restricted hash");
778     }
779     if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
780         /* Not doing some form of store, so return failure.  */
781         if (flags & HVhek_FREEKEY)
782             Safefree(key);
783         return 0;
784     }
785     if (action & HV_FETCH_LVALUE) {
786         val = newSV(0);
787         if (SvMAGICAL(hv)) {
788             /* At this point the old hv_fetch code would call to hv_store,
789                which in turn might do some tied magic. So we need to make that
790                magic check happen.  */
791             /* gonna assign to this, so it better be there */
792             return hv_fetch_common(hv, keysv, key, klen, flags,
793                                    HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY, val,
794                                    hash);
795             /* XXX Surely that could leak if the fetch-was-store fails?
796                Just like the hv_fetch.  */
797         }
798     }
799
800     /* Welcome to hv_store...  */
801
802     if (!HvARRAY(hv)) {
803         /* Not sure if we can get here.  I think the only case of oentry being
804            NULL is for %ENV with dynamic env fetch.  But that should disappear
805            with magic in the previous code.  */
806         char *array;
807         Newxz(array,
808              PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
809              char);
810         HvARRAY(hv) = (HE**)array;
811     }
812
813     oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
814
815     entry = new_HE();
816     /* share_hek_flags will do the free for us.  This might be considered
817        bad API design.  */
818     if (HvSHAREKEYS(hv))
819         HeKEY_hek(entry) = share_hek_flags(key, klen, hash, flags);
820     else if (hv == PL_strtab) {
821         /* PL_strtab is usually the only hash without HvSHAREKEYS, so putting
822            this test here is cheap  */
823         if (flags & HVhek_FREEKEY)
824             Safefree(key);
825         Perl_croak(aTHX_ S_strtab_error,
826                    action & HV_FETCH_LVALUE ? "fetch" : "store");
827     }
828     else                                       /* gotta do the real thing */
829         HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
830     HeVAL(entry) = val;
831     HeNEXT(entry) = *oentry;
832     *oentry = entry;
833
834     if (val == &PL_sv_placeholder)
835         HvPLACEHOLDERS(hv)++;
836     if (masked_flags & HVhek_ENABLEHVKFLAGS)
837         HvHASKFLAGS_on(hv);
838
839     {
840         const HE *counter = HeNEXT(entry);
841
842         xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
843         if (!counter) {                         /* initial entry? */
844             xhv->xhv_fill++; /* HvFILL(hv)++ */
845         } else if (xhv->xhv_keys > (IV)xhv->xhv_max) {
846             hsplit(hv);
847         } else if(!HvREHASH(hv)) {
848             U32 n_links = 1;
849
850             while ((counter = HeNEXT(counter)))
851                 n_links++;
852
853             if (n_links > HV_MAX_LENGTH_BEFORE_SPLIT) {
854                 /* Use only the old HvKEYS(hv) > HvMAX(hv) condition to limit
855                    bucket splits on a rehashed hash, as we're not going to
856                    split it again, and if someone is lucky (evil) enough to
857                    get all the keys in one list they could exhaust our memory
858                    as we repeatedly double the number of buckets on every
859                    entry. Linear search feels a less worse thing to do.  */
860                 hsplit(hv);
861             }
862         }
863     }
864
865     return entry;
866 }
867
868 STATIC void
869 S_hv_magic_check(HV *hv, bool *needs_copy, bool *needs_store)
870 {
871     const MAGIC *mg = SvMAGIC(hv);
872     *needs_copy = FALSE;
873     *needs_store = TRUE;
874     while (mg) {
875         if (isUPPER(mg->mg_type)) {
876             *needs_copy = TRUE;
877             if (mg->mg_type == PERL_MAGIC_tied) {
878                 *needs_store = FALSE;
879                 return; /* We've set all there is to set. */
880             }
881         }
882         mg = mg->mg_moremagic;
883     }
884 }
885
886 /*
887 =for apidoc hv_scalar
888
889 Evaluates the hash in scalar context and returns the result. Handles magic when the hash is tied.
890
891 =cut
892 */
893
894 SV *
895 Perl_hv_scalar(pTHX_ HV *hv)
896 {
897     SV *sv;
898
899     if (SvRMAGICAL(hv)) {
900         MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_tied);
901         if (mg)
902             return magic_scalarpack(hv, mg);
903     }
904
905     sv = sv_newmortal();
906     if (HvFILL((HV*)hv)) 
907         Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
908                 (long)HvFILL(hv), (long)HvMAX(hv) + 1);
909     else
910         sv_setiv(sv, 0);
911     
912     return sv;
913 }
914
915 /*
916 =for apidoc hv_delete
917
918 Deletes a key/value pair in the hash.  The value SV is removed from the
919 hash and returned to the caller.  The C<klen> is the length of the key.
920 The C<flags> value will normally be zero; if set to G_DISCARD then NULL
921 will be returned.
922
923 =cut
924 */
925
926 SV *
927 Perl_hv_delete(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 flags)
928 {
929     STRLEN klen;
930     int k_flags;
931
932     if (klen_i32 < 0) {
933         klen = -klen_i32;
934         k_flags = HVhek_UTF8;
935     } else {
936         klen = klen_i32;
937         k_flags = 0;
938     }
939     return (SV *) hv_fetch_common(hv, NULL, key, klen, k_flags,
940                                   flags | HV_DELETE, NULL, 0);
941 }
942
943 /*
944 =for apidoc hv_delete_ent
945
946 Deletes a key/value pair in the hash.  The value SV is removed from the
947 hash and returned to the caller.  The C<flags> value will normally be zero;
948 if set to G_DISCARD then NULL will be returned.  C<hash> can be a valid
949 precomputed hash value, or 0 to ask for it to be computed.
950
951 =cut
952 */
953
954 /* XXX This looks like an ideal candidate to inline */
955 SV *
956 Perl_hv_delete_ent(pTHX_ HV *hv, SV *keysv, I32 flags, U32 hash)
957 {
958     return (SV *) hv_fetch_common(hv, keysv, NULL, 0, 0, flags | HV_DELETE,
959                                   NULL, hash);
960 }
961
962 STATIC SV *
963 S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
964                    int k_flags, I32 d_flags, U32 hash)
965 {
966     dVAR;
967     register XPVHV* xhv;
968     register HE *entry;
969     register HE **oentry;
970     HE *const *first_entry;
971     bool is_utf8 = (k_flags & HVhek_UTF8) ? TRUE : FALSE;
972     int masked_flags;
973
974     if (SvRMAGICAL(hv)) {
975         bool needs_copy;
976         bool needs_store;
977         hv_magic_check (hv, &needs_copy, &needs_store);
978
979         if (needs_copy) {
980             SV *sv;
981             entry = hv_fetch_common(hv, keysv, key, klen,
982                                     k_flags & ~HVhek_FREEKEY,
983                                     HV_FETCH_LVALUE|HV_DISABLE_UVAR_XKEY,
984                                     NULL, hash);
985             sv = entry ? HeVAL(entry) : NULL;
986             if (sv) {
987                 if (SvMAGICAL(sv)) {
988                     mg_clear(sv);
989                 }
990                 if (!needs_store) {
991                     if (mg_find(sv, PERL_MAGIC_tiedelem)) {
992                         /* No longer an element */
993                         sv_unmagic(sv, PERL_MAGIC_tiedelem);
994                         return sv;
995                     }           
996                     return NULL;                /* element cannot be deleted */
997                 }
998 #ifdef ENV_IS_CASELESS
999                 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
1000                     /* XXX This code isn't UTF8 clean.  */
1001                     keysv = sv_2mortal(newSVpvn(key,klen));
1002                     if (k_flags & HVhek_FREEKEY) {
1003                         Safefree(key);
1004                     }
1005                     key = strupr(SvPVX(keysv));
1006                     is_utf8 = 0;
1007                     k_flags = 0;
1008                     hash = 0;
1009                 }
1010 #endif
1011             }
1012         }
1013     }
1014     xhv = (XPVHV*)SvANY(hv);
1015     if (!HvARRAY(hv))
1016         return NULL;
1017
1018     if (is_utf8) {
1019         const char * const keysave = key;
1020         key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
1021
1022         if (is_utf8)
1023             k_flags |= HVhek_UTF8;
1024         else
1025             k_flags &= ~HVhek_UTF8;
1026         if (key != keysave) {
1027             if (k_flags & HVhek_FREEKEY) {
1028                 /* This shouldn't happen if our caller does what we expect,
1029                    but strictly the API allows it.  */
1030                 Safefree(keysave);
1031             }
1032             k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
1033         }
1034         HvHASKFLAGS_on((SV*)hv);
1035     }
1036
1037     if (HvREHASH(hv)) {
1038         PERL_HASH_INTERNAL(hash, key, klen);
1039     } else if (!hash) {
1040         if (keysv && (SvIsCOW_shared_hash(keysv))) {
1041             hash = SvSHARED_HASH(keysv);
1042         } else {
1043             PERL_HASH(hash, key, klen);
1044         }
1045     }
1046
1047     masked_flags = (k_flags & HVhek_MASK);
1048
1049     first_entry = oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
1050     entry = *oentry;
1051     for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
1052         SV *sv;
1053         if (HeHASH(entry) != hash)              /* strings can't be equal */
1054             continue;
1055         if (HeKLEN(entry) != (I32)klen)
1056             continue;
1057         if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen))        /* is this it? */
1058             continue;
1059         if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
1060             continue;
1061
1062         if (hv == PL_strtab) {
1063             if (k_flags & HVhek_FREEKEY)
1064                 Safefree(key);
1065             Perl_croak(aTHX_ S_strtab_error, "delete");
1066         }
1067
1068         /* if placeholder is here, it's already been deleted.... */
1069         if (HeVAL(entry) == &PL_sv_placeholder) {
1070             if (k_flags & HVhek_FREEKEY)
1071                 Safefree(key);
1072             return NULL;
1073         }
1074         if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1075             hv_notallowed(k_flags, key, klen,
1076                             "Attempt to delete readonly key '%"SVf"' from"
1077                             " a restricted hash");
1078         }
1079         if (k_flags & HVhek_FREEKEY)
1080             Safefree(key);
1081
1082         if (d_flags & G_DISCARD)
1083             sv = NULL;
1084         else {
1085             sv = sv_2mortal(HeVAL(entry));
1086             HeVAL(entry) = &PL_sv_placeholder;
1087         }
1088
1089         /*
1090          * If a restricted hash, rather than really deleting the entry, put
1091          * a placeholder there. This marks the key as being "approved", so
1092          * we can still access via not-really-existing key without raising
1093          * an error.
1094          */
1095         if (SvREADONLY(hv)) {
1096             SvREFCNT_dec(HeVAL(entry));
1097             HeVAL(entry) = &PL_sv_placeholder;
1098             /* We'll be saving this slot, so the number of allocated keys
1099              * doesn't go down, but the number placeholders goes up */
1100             HvPLACEHOLDERS(hv)++;
1101         } else {
1102             *oentry = HeNEXT(entry);
1103             if(!*first_entry) {
1104                 xhv->xhv_fill--; /* HvFILL(hv)-- */
1105             }
1106             if (SvOOK(hv) && entry == HvAUX(hv)->xhv_eiter /* HvEITER(hv) */)
1107                 HvLAZYDEL_on(hv);
1108             else
1109                 hv_free_ent(hv, entry);
1110             xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
1111             if (xhv->xhv_keys == 0)
1112                 HvHASKFLAGS_off(hv);
1113         }
1114         return sv;
1115     }
1116     if (SvREADONLY(hv)) {
1117         hv_notallowed(k_flags, key, klen,
1118                         "Attempt to delete disallowed key '%"SVf"' from"
1119                         " a restricted hash");
1120     }
1121
1122     if (k_flags & HVhek_FREEKEY)
1123         Safefree(key);
1124     return NULL;
1125 }
1126
1127 STATIC void
1128 S_hsplit(pTHX_ HV *hv)
1129 {
1130     dVAR;
1131     register XPVHV* const xhv = (XPVHV*)SvANY(hv);
1132     const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1133     register I32 newsize = oldsize * 2;
1134     register I32 i;
1135     char *a = (char*) HvARRAY(hv);
1136     register HE **aep;
1137     register HE **oentry;
1138     int longest_chain = 0;
1139     int was_shared;
1140
1141     /*PerlIO_printf(PerlIO_stderr(), "hsplit called for %p which had %d\n",
1142       (void*)hv, (int) oldsize);*/
1143
1144     if (HvPLACEHOLDERS_get(hv) && !SvREADONLY(hv)) {
1145       /* Can make this clear any placeholders first for non-restricted hashes,
1146          even though Storable rebuilds restricted hashes by putting in all the
1147          placeholders (first) before turning on the readonly flag, because
1148          Storable always pre-splits the hash.  */
1149       hv_clear_placeholders(hv);
1150     }
1151                
1152     PL_nomemok = TRUE;
1153 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1154     Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1155           + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1156     if (!a) {
1157       PL_nomemok = FALSE;
1158       return;
1159     }
1160     if (SvOOK(hv)) {
1161         Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1162     }
1163 #else
1164     Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1165         + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1166     if (!a) {
1167       PL_nomemok = FALSE;
1168       return;
1169     }
1170     Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1171     if (SvOOK(hv)) {
1172         Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1173     }
1174     if (oldsize >= 64) {
1175         offer_nice_chunk(HvARRAY(hv),
1176                          PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
1177                          + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
1178     }
1179     else
1180         Safefree(HvARRAY(hv));
1181 #endif
1182
1183     PL_nomemok = FALSE;
1184     Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char);     /* zero 2nd half*/
1185     xhv->xhv_max = --newsize;   /* HvMAX(hv) = --newsize */
1186     HvARRAY(hv) = (HE**) a;
1187     aep = (HE**)a;
1188
1189     for (i=0; i<oldsize; i++,aep++) {
1190         int left_length = 0;
1191         int right_length = 0;
1192         register HE *entry;
1193         register HE **bep;
1194
1195         if (!*aep)                              /* non-existent */
1196             continue;
1197         bep = aep+oldsize;
1198         for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1199             if ((HeHASH(entry) & newsize) != (U32)i) {
1200                 *oentry = HeNEXT(entry);
1201                 HeNEXT(entry) = *bep;
1202                 if (!*bep)
1203                     xhv->xhv_fill++; /* HvFILL(hv)++ */
1204                 *bep = entry;
1205                 right_length++;
1206                 continue;
1207             }
1208             else {
1209                 oentry = &HeNEXT(entry);
1210                 left_length++;
1211             }
1212         }
1213         if (!*aep)                              /* everything moved */
1214             xhv->xhv_fill--; /* HvFILL(hv)-- */
1215         /* I think we don't actually need to keep track of the longest length,
1216            merely flag if anything is too long. But for the moment while
1217            developing this code I'll track it.  */
1218         if (left_length > longest_chain)
1219             longest_chain = left_length;
1220         if (right_length > longest_chain)
1221             longest_chain = right_length;
1222     }
1223
1224
1225     /* Pick your policy for "hashing isn't working" here:  */
1226     if (longest_chain <= HV_MAX_LENGTH_BEFORE_SPLIT /* split worked?  */
1227         || HvREHASH(hv)) {
1228         return;
1229     }
1230
1231     if (hv == PL_strtab) {
1232         /* Urg. Someone is doing something nasty to the string table.
1233            Can't win.  */
1234         return;
1235     }
1236
1237     /* Awooga. Awooga. Pathological data.  */
1238     /*PerlIO_printf(PerlIO_stderr(), "%p %d of %d with %d/%d buckets\n", (void*)hv,
1239       longest_chain, HvTOTALKEYS(hv), HvFILL(hv),  1+HvMAX(hv));*/
1240
1241     ++newsize;
1242     Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1243          + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1244     if (SvOOK(hv)) {
1245         Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1246     }
1247
1248     was_shared = HvSHAREKEYS(hv);
1249
1250     xhv->xhv_fill = 0;
1251     HvSHAREKEYS_off(hv);
1252     HvREHASH_on(hv);
1253
1254     aep = HvARRAY(hv);
1255
1256     for (i=0; i<newsize; i++,aep++) {
1257         register HE *entry = *aep;
1258         while (entry) {
1259             /* We're going to trash this HE's next pointer when we chain it
1260                into the new hash below, so store where we go next.  */
1261             HE * const next = HeNEXT(entry);
1262             UV hash;
1263             HE **bep;
1264
1265             /* Rehash it */
1266             PERL_HASH_INTERNAL(hash, HeKEY(entry), HeKLEN(entry));
1267
1268             if (was_shared) {
1269                 /* Unshare it.  */
1270                 HEK * const new_hek
1271                     = save_hek_flags(HeKEY(entry), HeKLEN(entry),
1272                                      hash, HeKFLAGS(entry));
1273                 unshare_hek (HeKEY_hek(entry));
1274                 HeKEY_hek(entry) = new_hek;
1275             } else {
1276                 /* Not shared, so simply write the new hash in. */
1277                 HeHASH(entry) = hash;
1278             }
1279             /*PerlIO_printf(PerlIO_stderr(), "%d ", HeKFLAGS(entry));*/
1280             HEK_REHASH_on(HeKEY_hek(entry));
1281             /*PerlIO_printf(PerlIO_stderr(), "%d\n", HeKFLAGS(entry));*/
1282
1283             /* Copy oentry to the correct new chain.  */
1284             bep = ((HE**)a) + (hash & (I32) xhv->xhv_max);
1285             if (!*bep)
1286                     xhv->xhv_fill++; /* HvFILL(hv)++ */
1287             HeNEXT(entry) = *bep;
1288             *bep = entry;
1289
1290             entry = next;
1291         }
1292     }
1293     Safefree (HvARRAY(hv));
1294     HvARRAY(hv) = (HE **)a;
1295 }
1296
1297 void
1298 Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
1299 {
1300     dVAR;
1301     register XPVHV* xhv = (XPVHV*)SvANY(hv);
1302     const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1303     register I32 newsize;
1304     register I32 i;
1305     register char *a;
1306     register HE **aep;
1307     register HE *entry;
1308     register HE **oentry;
1309
1310     newsize = (I32) newmax;                     /* possible truncation here */
1311     if (newsize != newmax || newmax <= oldsize)
1312         return;
1313     while ((newsize & (1 + ~newsize)) != newsize) {
1314         newsize &= ~(newsize & (1 + ~newsize)); /* get proper power of 2 */
1315     }
1316     if (newsize < newmax)
1317         newsize *= 2;
1318     if (newsize < newmax)
1319         return;                                 /* overflow detection */
1320
1321     a = (char *) HvARRAY(hv);
1322     if (a) {
1323         PL_nomemok = TRUE;
1324 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1325         Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1326               + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1327         if (!a) {
1328           PL_nomemok = FALSE;
1329           return;
1330         }
1331         if (SvOOK(hv)) {
1332             Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1333         }
1334 #else
1335         Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1336             + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1337         if (!a) {
1338           PL_nomemok = FALSE;
1339           return;
1340         }
1341         Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1342         if (SvOOK(hv)) {
1343             Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1344         }
1345         if (oldsize >= 64) {
1346             offer_nice_chunk(HvARRAY(hv),
1347                              PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
1348                              + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
1349         }
1350         else
1351             Safefree(HvARRAY(hv));
1352 #endif
1353         PL_nomemok = FALSE;
1354         Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1355     }
1356     else {
1357         Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1358     }
1359     xhv->xhv_max = --newsize;   /* HvMAX(hv) = --newsize */
1360     HvARRAY(hv) = (HE **) a;
1361     if (!xhv->xhv_fill /* !HvFILL(hv) */)       /* skip rest if no entries */
1362         return;
1363
1364     aep = (HE**)a;
1365     for (i=0; i<oldsize; i++,aep++) {
1366         if (!*aep)                              /* non-existent */
1367             continue;
1368         for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1369             register I32 j = (HeHASH(entry) & newsize);
1370
1371             if (j != i) {
1372                 j -= i;
1373                 *oentry = HeNEXT(entry);
1374                 if (!(HeNEXT(entry) = aep[j]))
1375                     xhv->xhv_fill++; /* HvFILL(hv)++ */
1376                 aep[j] = entry;
1377                 continue;
1378             }
1379             else
1380                 oentry = &HeNEXT(entry);
1381         }
1382         if (!*aep)                              /* everything moved */
1383             xhv->xhv_fill--; /* HvFILL(hv)-- */
1384     }
1385 }
1386
1387 /*
1388 =for apidoc newHV
1389
1390 Creates a new HV.  The reference count is set to 1.
1391
1392 =cut
1393 */
1394
1395 HV *
1396 Perl_newHV(pTHX)
1397 {
1398     register XPVHV* xhv;
1399     HV * const hv = (HV*)newSV_type(SVt_PVHV);
1400     xhv = (XPVHV*)SvANY(hv);
1401     assert(!SvOK(hv));
1402 #ifndef NODEFAULT_SHAREKEYS
1403     HvSHAREKEYS_on(hv);         /* key-sharing on by default */
1404 #endif
1405
1406     xhv->xhv_max    = 7;        /* HvMAX(hv) = 7 (start with 8 buckets) */
1407     xhv->xhv_fill   = 0;        /* HvFILL(hv) = 0 */
1408     return hv;
1409 }
1410
1411 HV *
1412 Perl_newHVhv(pTHX_ HV *ohv)
1413 {
1414     HV * const hv = newHV();
1415     STRLEN hv_max, hv_fill;
1416
1417     if (!ohv || (hv_fill = HvFILL(ohv)) == 0)
1418         return hv;
1419     hv_max = HvMAX(ohv);
1420
1421     if (!SvMAGICAL((SV *)ohv)) {
1422         /* It's an ordinary hash, so copy it fast. AMS 20010804 */
1423         STRLEN i;
1424         const bool shared = !!HvSHAREKEYS(ohv);
1425         HE **ents, ** const oents = (HE **)HvARRAY(ohv);
1426         char *a;
1427         Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
1428         ents = (HE**)a;
1429
1430         /* In each bucket... */
1431         for (i = 0; i <= hv_max; i++) {
1432             HE *prev = NULL;
1433             HE *oent = oents[i];
1434
1435             if (!oent) {
1436                 ents[i] = NULL;
1437                 continue;
1438             }
1439
1440             /* Copy the linked list of entries. */
1441             for (; oent; oent = HeNEXT(oent)) {
1442                 const U32 hash   = HeHASH(oent);
1443                 const char * const key = HeKEY(oent);
1444                 const STRLEN len = HeKLEN(oent);
1445                 const int flags  = HeKFLAGS(oent);
1446                 HE * const ent   = new_HE();
1447
1448                 HeVAL(ent)     = newSVsv(HeVAL(oent));
1449                 HeKEY_hek(ent)
1450                     = shared ? share_hek_flags(key, len, hash, flags)
1451                              :  save_hek_flags(key, len, hash, flags);
1452                 if (prev)
1453                     HeNEXT(prev) = ent;
1454                 else
1455                     ents[i] = ent;
1456                 prev = ent;
1457                 HeNEXT(ent) = NULL;
1458             }
1459         }
1460
1461         HvMAX(hv)   = hv_max;
1462         HvFILL(hv)  = hv_fill;
1463         HvTOTALKEYS(hv)  = HvTOTALKEYS(ohv);
1464         HvARRAY(hv) = ents;
1465     } /* not magical */
1466     else {
1467         /* Iterate over ohv, copying keys and values one at a time. */
1468         HE *entry;
1469         const I32 riter = HvRITER_get(ohv);
1470         HE * const eiter = HvEITER_get(ohv);
1471
1472         /* Can we use fewer buckets? (hv_max is always 2^n-1) */
1473         while (hv_max && hv_max + 1 >= hv_fill * 2)
1474             hv_max = hv_max / 2;
1475         HvMAX(hv) = hv_max;
1476
1477         hv_iterinit(ohv);
1478         while ((entry = hv_iternext_flags(ohv, 0))) {
1479             hv_store_flags(hv, HeKEY(entry), HeKLEN(entry),
1480                            newSVsv(HeVAL(entry)), HeHASH(entry),
1481                            HeKFLAGS(entry));
1482         }
1483         HvRITER_set(ohv, riter);
1484         HvEITER_set(ohv, eiter);
1485     }
1486
1487     return hv;
1488 }
1489
1490 /* A rather specialised version of newHVhv for copying %^H, ensuring all the
1491    magic stays on it.  */
1492 HV *
1493 Perl_hv_copy_hints_hv(pTHX_ HV *const ohv)
1494 {
1495     HV * const hv = newHV();
1496     STRLEN hv_fill;
1497
1498     if (ohv && (hv_fill = HvFILL(ohv))) {
1499         STRLEN hv_max = HvMAX(ohv);
1500         HE *entry;
1501         const I32 riter = HvRITER_get(ohv);
1502         HE * const eiter = HvEITER_get(ohv);
1503
1504         while (hv_max && hv_max + 1 >= hv_fill * 2)
1505             hv_max = hv_max / 2;
1506         HvMAX(hv) = hv_max;
1507
1508         hv_iterinit(ohv);
1509         while ((entry = hv_iternext_flags(ohv, 0))) {
1510             SV *const sv = newSVsv(HeVAL(entry));
1511             sv_magic(sv, NULL, PERL_MAGIC_hintselem,
1512                      (char *)newSVhek (HeKEY_hek(entry)), HEf_SVKEY);
1513             hv_store_flags(hv, HeKEY(entry), HeKLEN(entry),
1514                            sv, HeHASH(entry), HeKFLAGS(entry));
1515         }
1516         HvRITER_set(ohv, riter);
1517         HvEITER_set(ohv, eiter);
1518     }
1519     hv_magic(hv, NULL, PERL_MAGIC_hints);
1520     return hv;
1521 }
1522
1523 void
1524 Perl_hv_free_ent(pTHX_ HV *hv, register HE *entry)
1525 {
1526     dVAR;
1527     SV *val;
1528
1529     if (!entry)
1530         return;
1531     val = HeVAL(entry);
1532     if (val && isGV(val) && GvCVu(val) && HvNAME_get(hv))
1533         mro_method_changed_in(hv);      /* deletion of method from stash */
1534     SvREFCNT_dec(val);
1535     if (HeKLEN(entry) == HEf_SVKEY) {
1536         SvREFCNT_dec(HeKEY_sv(entry));
1537         Safefree(HeKEY_hek(entry));
1538     }
1539     else if (HvSHAREKEYS(hv))
1540         unshare_hek(HeKEY_hek(entry));
1541     else
1542         Safefree(HeKEY_hek(entry));
1543     del_HE(entry);
1544 }
1545
1546 void
1547 Perl_hv_delayfree_ent(pTHX_ HV *hv, register HE *entry)
1548 {
1549     dVAR;
1550     if (!entry)
1551         return;
1552     /* SvREFCNT_inc to counter the SvREFCNT_dec in hv_free_ent  */
1553     sv_2mortal(SvREFCNT_inc(HeVAL(entry)));     /* free between statements */
1554     if (HeKLEN(entry) == HEf_SVKEY) {
1555         sv_2mortal(SvREFCNT_inc(HeKEY_sv(entry)));
1556     }
1557     hv_free_ent(hv, entry);
1558 }
1559
1560 /*
1561 =for apidoc hv_clear
1562
1563 Clears a hash, making it empty.
1564
1565 =cut
1566 */
1567
1568 void
1569 Perl_hv_clear(pTHX_ HV *hv)
1570 {
1571     dVAR;
1572     register XPVHV* xhv;
1573     if (!hv)
1574         return;
1575
1576     DEBUG_A(Perl_hv_assert(aTHX_ hv));
1577
1578     xhv = (XPVHV*)SvANY(hv);
1579
1580     if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
1581         /* restricted hash: convert all keys to placeholders */
1582         STRLEN i;
1583         for (i = 0; i <= xhv->xhv_max; i++) {
1584             HE *entry = (HvARRAY(hv))[i];
1585             for (; entry; entry = HeNEXT(entry)) {
1586                 /* not already placeholder */
1587                 if (HeVAL(entry) != &PL_sv_placeholder) {
1588                     if (HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1589                         SV* const keysv = hv_iterkeysv(entry);
1590                         Perl_croak(aTHX_
1591                                    "Attempt to delete readonly key '%"SVf"' from a restricted hash",
1592                                    (void*)keysv);
1593                     }
1594                     SvREFCNT_dec(HeVAL(entry));
1595                     HeVAL(entry) = &PL_sv_placeholder;
1596                     HvPLACEHOLDERS(hv)++;
1597                 }
1598             }
1599         }
1600         goto reset;
1601     }
1602
1603     hfreeentries(hv);
1604     HvPLACEHOLDERS_set(hv, 0);
1605     if (HvARRAY(hv))
1606         Zero(HvARRAY(hv), xhv->xhv_max+1 /* HvMAX(hv)+1 */, HE*);
1607
1608     if (SvRMAGICAL(hv))
1609         mg_clear((SV*)hv);
1610
1611     HvHASKFLAGS_off(hv);
1612     HvREHASH_off(hv);
1613     reset:
1614     if (SvOOK(hv)) {
1615         if(HvNAME_get(hv))
1616             mro_isa_changed_in(hv);
1617         HvEITER_set(hv, NULL);
1618     }
1619 }
1620
1621 /*
1622 =for apidoc hv_clear_placeholders
1623
1624 Clears any placeholders from a hash.  If a restricted hash has any of its keys
1625 marked as readonly and the key is subsequently deleted, the key is not actually
1626 deleted but is marked by assigning it a value of &PL_sv_placeholder.  This tags
1627 it so it will be ignored by future operations such as iterating over the hash,
1628 but will still allow the hash to have a value reassigned to the key at some
1629 future point.  This function clears any such placeholder keys from the hash.
1630 See Hash::Util::lock_keys() for an example of its use.
1631
1632 =cut
1633 */
1634
1635 void
1636 Perl_hv_clear_placeholders(pTHX_ HV *hv)
1637 {
1638     dVAR;
1639     const U32 items = (U32)HvPLACEHOLDERS_get(hv);
1640
1641     if (items)
1642         clear_placeholders(hv, items);
1643 }
1644
1645 static void
1646 S_clear_placeholders(pTHX_ HV *hv, U32 items)
1647 {
1648     dVAR;
1649     I32 i;
1650
1651     if (items == 0)
1652         return;
1653
1654     i = HvMAX(hv);
1655     do {
1656         /* Loop down the linked list heads  */
1657         bool first = TRUE;
1658         HE **oentry = &(HvARRAY(hv))[i];
1659         HE *entry;
1660
1661         while ((entry = *oentry)) {
1662             if (HeVAL(entry) == &PL_sv_placeholder) {
1663                 *oentry = HeNEXT(entry);
1664                 if (first && !*oentry)
1665                     HvFILL(hv)--; /* This linked list is now empty.  */
1666                 if (entry == HvEITER_get(hv))
1667                     HvLAZYDEL_on(hv);
1668                 else
1669                     hv_free_ent(hv, entry);
1670
1671                 if (--items == 0) {
1672                     /* Finished.  */
1673                     HvTOTALKEYS(hv) -= (IV)HvPLACEHOLDERS_get(hv);
1674                     if (HvKEYS(hv) == 0)
1675                         HvHASKFLAGS_off(hv);
1676                     HvPLACEHOLDERS_set(hv, 0);
1677                     return;
1678                 }
1679             } else {
1680                 oentry = &HeNEXT(entry);
1681                 first = FALSE;
1682             }
1683         }
1684     } while (--i >= 0);
1685     /* You can't get here, hence assertion should always fail.  */
1686     assert (items == 0);
1687     assert (0);
1688 }
1689
1690 STATIC void
1691 S_hfreeentries(pTHX_ HV *hv)
1692 {
1693     /* This is the array that we're going to restore  */
1694     HE **const orig_array = HvARRAY(hv);
1695     HEK *name;
1696     int attempts = 100;
1697
1698     if (!orig_array)
1699         return;
1700
1701     if (SvOOK(hv)) {
1702         /* If the hash is actually a symbol table with a name, look after the
1703            name.  */
1704         struct xpvhv_aux *iter = HvAUX(hv);
1705
1706         name = iter->xhv_name;
1707         iter->xhv_name = NULL;
1708     } else {
1709         name = NULL;
1710     }
1711
1712     /* orig_array remains unchanged throughout the loop. If after freeing all
1713        the entries it turns out that one of the little blighters has triggered
1714        an action that has caused HvARRAY to be re-allocated, then we set
1715        array to the new HvARRAY, and try again.  */
1716
1717     while (1) {
1718         /* This is the one we're going to try to empty.  First time round
1719            it's the original array.  (Hopefully there will only be 1 time
1720            round) */
1721         HE ** const array = HvARRAY(hv);
1722         I32 i = HvMAX(hv);
1723
1724         /* Because we have taken xhv_name out, the only allocated pointer
1725            in the aux structure that might exist is the backreference array.
1726         */
1727
1728         if (SvOOK(hv)) {
1729             HE *entry;
1730             struct mro_meta *meta;
1731             struct xpvhv_aux *iter = HvAUX(hv);
1732             /* If there are weak references to this HV, we need to avoid
1733                freeing them up here.  In particular we need to keep the AV
1734                visible as what we're deleting might well have weak references
1735                back to this HV, so the for loop below may well trigger
1736                the removal of backreferences from this array.  */
1737
1738             if (iter->xhv_backreferences) {
1739                 /* So donate them to regular backref magic to keep them safe.
1740                    The sv_magic will increase the reference count of the AV,
1741                    so we need to drop it first. */
1742                 SvREFCNT_dec(iter->xhv_backreferences);
1743                 if (AvFILLp(iter->xhv_backreferences) == -1) {
1744                     /* Turns out that the array is empty. Just free it.  */
1745                     SvREFCNT_dec(iter->xhv_backreferences);
1746
1747                 } else {
1748                     sv_magic((SV*)hv, (SV*)iter->xhv_backreferences,
1749                              PERL_MAGIC_backref, NULL, 0);
1750                 }
1751                 iter->xhv_backreferences = NULL;
1752             }
1753
1754             entry = iter->xhv_eiter; /* HvEITER(hv) */
1755             if (entry && HvLAZYDEL(hv)) {       /* was deleted earlier? */
1756                 HvLAZYDEL_off(hv);
1757                 hv_free_ent(hv, entry);
1758             }
1759             iter->xhv_riter = -1;       /* HvRITER(hv) = -1 */
1760             iter->xhv_eiter = NULL;     /* HvEITER(hv) = NULL */
1761
1762             if((meta = iter->xhv_mro_meta)) {
1763                 if(meta->mro_linear_dfs) SvREFCNT_dec(meta->mro_linear_dfs);
1764                 if(meta->mro_linear_c3)  SvREFCNT_dec(meta->mro_linear_c3);
1765                 if(meta->mro_nextmethod) SvREFCNT_dec(meta->mro_nextmethod);
1766                 Safefree(meta);
1767                 iter->xhv_mro_meta = NULL;
1768             }
1769
1770             /* There are now no allocated pointers in the aux structure.  */
1771
1772             SvFLAGS(hv) &= ~SVf_OOK; /* Goodbye, aux structure.  */
1773             /* What aux structure?  */
1774         }
1775
1776         /* make everyone else think the array is empty, so that the destructors
1777          * called for freed entries can't recusively mess with us */
1778         HvARRAY(hv) = NULL;
1779         HvFILL(hv) = 0;
1780         ((XPVHV*) SvANY(hv))->xhv_keys = 0;
1781
1782
1783         do {
1784             /* Loop down the linked list heads  */
1785             HE *entry = array[i];
1786
1787             while (entry) {
1788                 register HE * const oentry = entry;
1789                 entry = HeNEXT(entry);
1790                 hv_free_ent(hv, oentry);
1791             }
1792         } while (--i >= 0);
1793
1794         /* As there are no allocated pointers in the aux structure, it's now
1795            safe to free the array we just cleaned up, if it's not the one we're
1796            going to put back.  */
1797         if (array != orig_array) {
1798             Safefree(array);
1799         }
1800
1801         if (!HvARRAY(hv)) {
1802             /* Good. No-one added anything this time round.  */
1803             break;
1804         }
1805
1806         if (SvOOK(hv)) {
1807             /* Someone attempted to iterate or set the hash name while we had
1808                the array set to 0.  We'll catch backferences on the next time
1809                round the while loop.  */
1810             assert(HvARRAY(hv));
1811
1812             if (HvAUX(hv)->xhv_name) {
1813                 unshare_hek_or_pvn(HvAUX(hv)->xhv_name, 0, 0, 0);
1814             }
1815         }
1816
1817         if (--attempts == 0) {
1818             Perl_die(aTHX_ "panic: hfreeentries failed to free hash - something is repeatedly re-creating entries");
1819         }
1820     }
1821         
1822     HvARRAY(hv) = orig_array;
1823
1824     /* If the hash was actually a symbol table, put the name back.  */
1825     if (name) {
1826         /* We have restored the original array.  If name is non-NULL, then
1827            the original array had an aux structure at the end. So this is
1828            valid:  */
1829         SvFLAGS(hv) |= SVf_OOK;
1830         HvAUX(hv)->xhv_name = name;
1831     }
1832 }
1833
1834 /*
1835 =for apidoc hv_undef
1836
1837 Undefines the hash.
1838
1839 =cut
1840 */
1841
1842 void
1843 Perl_hv_undef(pTHX_ HV *hv)
1844 {
1845     dVAR;
1846     register XPVHV* xhv;
1847     const char *name;
1848
1849     if (!hv)
1850         return;
1851     DEBUG_A(Perl_hv_assert(aTHX_ hv));
1852     xhv = (XPVHV*)SvANY(hv);
1853
1854     if ((name = HvNAME_get(hv)) && !PL_dirty)
1855         mro_isa_changed_in(hv);
1856
1857     hfreeentries(hv);
1858     if (name) {
1859         if(PL_stashcache)
1860             hv_delete(PL_stashcache, name, HvNAMELEN_get(hv), G_DISCARD);
1861         hv_name_set(hv, NULL, 0, 0);
1862     }
1863     SvFLAGS(hv) &= ~SVf_OOK;
1864     Safefree(HvARRAY(hv));
1865     xhv->xhv_max   = 7; /* HvMAX(hv) = 7 (it's a normal hash) */
1866     HvARRAY(hv) = 0;
1867     HvPLACEHOLDERS_set(hv, 0);
1868
1869     if (SvRMAGICAL(hv))
1870         mg_clear((SV*)hv);
1871 }
1872
1873 static struct xpvhv_aux*
1874 S_hv_auxinit(HV *hv) {
1875     struct xpvhv_aux *iter;
1876     char *array;
1877
1878     if (!HvARRAY(hv)) {
1879         Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1880             + sizeof(struct xpvhv_aux), char);
1881     } else {
1882         array = (char *) HvARRAY(hv);
1883         Renew(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1884               + sizeof(struct xpvhv_aux), char);
1885     }
1886     HvARRAY(hv) = (HE**) array;
1887     /* SvOOK_on(hv) attacks the IV flags.  */
1888     SvFLAGS(hv) |= SVf_OOK;
1889     iter = HvAUX(hv);
1890
1891     iter->xhv_riter = -1;       /* HvRITER(hv) = -1 */
1892     iter->xhv_eiter = NULL;     /* HvEITER(hv) = NULL */
1893     iter->xhv_name = 0;
1894     iter->xhv_backreferences = 0;
1895     iter->xhv_mro_meta = NULL;
1896     return iter;
1897 }
1898
1899 /*
1900 =for apidoc hv_iterinit
1901
1902 Prepares a starting point to traverse a hash table.  Returns the number of
1903 keys in the hash (i.e. the same as C<HvKEYS(tb)>).  The return value is
1904 currently only meaningful for hashes without tie magic.
1905
1906 NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
1907 hash buckets that happen to be in use.  If you still need that esoteric
1908 value, you can get it through the macro C<HvFILL(tb)>.
1909
1910
1911 =cut
1912 */
1913
1914 I32
1915 Perl_hv_iterinit(pTHX_ HV *hv)
1916 {
1917     if (!hv)
1918         Perl_croak(aTHX_ "Bad hash");
1919
1920     if (SvOOK(hv)) {
1921         struct xpvhv_aux * const iter = HvAUX(hv);
1922         HE * const entry = iter->xhv_eiter; /* HvEITER(hv) */
1923         if (entry && HvLAZYDEL(hv)) {   /* was deleted earlier? */
1924             HvLAZYDEL_off(hv);
1925             hv_free_ent(hv, entry);
1926         }
1927         iter->xhv_riter = -1;   /* HvRITER(hv) = -1 */
1928         iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
1929     } else {
1930         hv_auxinit(hv);
1931     }
1932
1933     /* used to be xhv->xhv_fill before 5.004_65 */
1934     return HvTOTALKEYS(hv);
1935 }
1936
1937 I32 *
1938 Perl_hv_riter_p(pTHX_ HV *hv) {
1939     struct xpvhv_aux *iter;
1940
1941     if (!hv)
1942         Perl_croak(aTHX_ "Bad hash");
1943
1944     iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
1945     return &(iter->xhv_riter);
1946 }
1947
1948 HE **
1949 Perl_hv_eiter_p(pTHX_ HV *hv) {
1950     struct xpvhv_aux *iter;
1951
1952     if (!hv)
1953         Perl_croak(aTHX_ "Bad hash");
1954
1955     iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
1956     return &(iter->xhv_eiter);
1957 }
1958
1959 void
1960 Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
1961     struct xpvhv_aux *iter;
1962
1963     if (!hv)
1964         Perl_croak(aTHX_ "Bad hash");
1965
1966     if (SvOOK(hv)) {
1967         iter = HvAUX(hv);
1968     } else {
1969         if (riter == -1)
1970             return;
1971
1972         iter = hv_auxinit(hv);
1973     }
1974     iter->xhv_riter = riter;
1975 }
1976
1977 void
1978 Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
1979     struct xpvhv_aux *iter;
1980
1981     if (!hv)
1982         Perl_croak(aTHX_ "Bad hash");
1983
1984     if (SvOOK(hv)) {
1985         iter = HvAUX(hv);
1986     } else {
1987         /* 0 is the default so don't go malloc()ing a new structure just to
1988            hold 0.  */
1989         if (!eiter)
1990             return;
1991
1992         iter = hv_auxinit(hv);
1993     }
1994     iter->xhv_eiter = eiter;
1995 }
1996
1997 void
1998 Perl_hv_name_set(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
1999 {
2000     dVAR;
2001     struct xpvhv_aux *iter;
2002     U32 hash;
2003
2004     PERL_UNUSED_ARG(flags);
2005
2006     if (len > I32_MAX)
2007         Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
2008
2009     if (SvOOK(hv)) {
2010         iter = HvAUX(hv);
2011         if (iter->xhv_name) {
2012             unshare_hek_or_pvn(iter->xhv_name, 0, 0, 0);
2013         }
2014     } else {
2015         if (name == 0)
2016             return;
2017
2018         iter = hv_auxinit(hv);
2019     }
2020     PERL_HASH(hash, name, len);
2021     iter->xhv_name = name ? share_hek(name, len, hash) : NULL;
2022 }
2023
2024 AV **
2025 Perl_hv_backreferences_p(pTHX_ HV *hv) {
2026     struct xpvhv_aux * const iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2027     PERL_UNUSED_CONTEXT;
2028     return &(iter->xhv_backreferences);
2029 }
2030
2031 void
2032 Perl_hv_kill_backrefs(pTHX_ HV *hv) {
2033     AV *av;
2034
2035     if (!SvOOK(hv))
2036         return;
2037
2038     av = HvAUX(hv)->xhv_backreferences;
2039
2040     if (av) {
2041         HvAUX(hv)->xhv_backreferences = 0;
2042         Perl_sv_kill_backrefs(aTHX_ (SV*) hv, av);
2043     }
2044 }
2045
2046 /*
2047 hv_iternext is implemented as a macro in hv.h
2048
2049 =for apidoc hv_iternext
2050
2051 Returns entries from a hash iterator.  See C<hv_iterinit>.
2052
2053 You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
2054 iterator currently points to, without losing your place or invalidating your
2055 iterator.  Note that in this case the current entry is deleted from the hash
2056 with your iterator holding the last reference to it.  Your iterator is flagged
2057 to free the entry on the next call to C<hv_iternext>, so you must not discard
2058 your iterator immediately else the entry will leak - call C<hv_iternext> to
2059 trigger the resource deallocation.
2060
2061 =for apidoc hv_iternext_flags
2062
2063 Returns entries from a hash iterator.  See C<hv_iterinit> and C<hv_iternext>.
2064 The C<flags> value will normally be zero; if HV_ITERNEXT_WANTPLACEHOLDERS is
2065 set the placeholders keys (for restricted hashes) will be returned in addition
2066 to normal keys. By default placeholders are automatically skipped over.
2067 Currently a placeholder is implemented with a value that is
2068 C<&Perl_sv_placeholder>. Note that the implementation of placeholders and
2069 restricted hashes may change, and the implementation currently is
2070 insufficiently abstracted for any change to be tidy.
2071
2072 =cut
2073 */
2074
2075 HE *
2076 Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
2077 {
2078     dVAR;
2079     register XPVHV* xhv;
2080     register HE *entry;
2081     HE *oldentry;
2082     MAGIC* mg;
2083     struct xpvhv_aux *iter;
2084
2085     if (!hv)
2086         Perl_croak(aTHX_ "Bad hash");
2087
2088     xhv = (XPVHV*)SvANY(hv);
2089
2090     if (!SvOOK(hv)) {
2091         /* Too many things (well, pp_each at least) merrily assume that you can
2092            call iv_iternext without calling hv_iterinit, so we'll have to deal
2093            with it.  */
2094         hv_iterinit(hv);
2095     }
2096     iter = HvAUX(hv);
2097
2098     oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2099     if (SvMAGICAL(hv) && SvRMAGICAL(hv)) {
2100         if ( ( mg = mg_find((SV*)hv, PERL_MAGIC_tied) ) ) {
2101             SV * const key = sv_newmortal();
2102             if (entry) {
2103                 sv_setsv(key, HeSVKEY_force(entry));
2104                 SvREFCNT_dec(HeSVKEY(entry));       /* get rid of previous key */
2105             }
2106             else {
2107                 char *k;
2108                 HEK *hek;
2109
2110                 /* one HE per MAGICAL hash */
2111                 iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
2112                 Zero(entry, 1, HE);
2113                 Newxz(k, HEK_BASESIZE + sizeof(SV*), char);
2114                 hek = (HEK*)k;
2115                 HeKEY_hek(entry) = hek;
2116                 HeKLEN(entry) = HEf_SVKEY;
2117             }
2118             magic_nextpack((SV*) hv,mg,key);
2119             if (SvOK(key)) {
2120                 /* force key to stay around until next time */
2121                 HeSVKEY_set(entry, SvREFCNT_inc_simple_NN(key));
2122                 return entry;               /* beware, hent_val is not set */
2123             }
2124             if (HeVAL(entry))
2125                 SvREFCNT_dec(HeVAL(entry));
2126             Safefree(HeKEY_hek(entry));
2127             del_HE(entry);
2128             iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
2129             return NULL;
2130         }
2131     }
2132 #if defined(DYNAMIC_ENV_FETCH) && !defined(__riscos__)  /* set up %ENV for iteration */
2133     if (!entry && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
2134         prime_env_iter();
2135 #ifdef VMS
2136         /* The prime_env_iter() on VMS just loaded up new hash values
2137          * so the iteration count needs to be reset back to the beginning
2138          */
2139         hv_iterinit(hv);
2140         iter = HvAUX(hv);
2141         oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2142 #endif
2143     }
2144 #endif
2145
2146     /* hv_iterint now ensures this.  */
2147     assert (HvARRAY(hv));
2148
2149     /* At start of hash, entry is NULL.  */
2150     if (entry)
2151     {
2152         entry = HeNEXT(entry);
2153         if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2154             /*
2155              * Skip past any placeholders -- don't want to include them in
2156              * any iteration.
2157              */
2158             while (entry && HeVAL(entry) == &PL_sv_placeholder) {
2159                 entry = HeNEXT(entry);
2160             }
2161         }
2162     }
2163     while (!entry) {
2164         /* OK. Come to the end of the current list.  Grab the next one.  */
2165
2166         iter->xhv_riter++; /* HvRITER(hv)++ */
2167         if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
2168             /* There is no next one.  End of the hash.  */
2169             iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2170             break;
2171         }
2172         entry = (HvARRAY(hv))[iter->xhv_riter];
2173
2174         if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2175             /* If we have an entry, but it's a placeholder, don't count it.
2176                Try the next.  */
2177             while (entry && HeVAL(entry) == &PL_sv_placeholder)
2178                 entry = HeNEXT(entry);
2179         }
2180         /* Will loop again if this linked list starts NULL
2181            (for HV_ITERNEXT_WANTPLACEHOLDERS)
2182            or if we run through it and find only placeholders.  */
2183     }
2184
2185     if (oldentry && HvLAZYDEL(hv)) {            /* was deleted earlier? */
2186         HvLAZYDEL_off(hv);
2187         hv_free_ent(hv, oldentry);
2188     }
2189
2190     /*if (HvREHASH(hv) && entry && !HeKREHASH(entry))
2191       PerlIO_printf(PerlIO_stderr(), "Awooga %p %p\n", (void*)hv, (void*)entry);*/
2192
2193     iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
2194     return entry;
2195 }
2196
2197 /*
2198 =for apidoc hv_iterkey
2199
2200 Returns the key from the current position of the hash iterator.  See
2201 C<hv_iterinit>.
2202
2203 =cut
2204 */
2205
2206 char *
2207 Perl_hv_iterkey(pTHX_ register HE *entry, I32 *retlen)
2208 {
2209     if (HeKLEN(entry) == HEf_SVKEY) {
2210         STRLEN len;
2211         char * const p = SvPV(HeKEY_sv(entry), len);
2212         *retlen = len;
2213         return p;
2214     }
2215     else {
2216         *retlen = HeKLEN(entry);
2217         return HeKEY(entry);
2218     }
2219 }
2220
2221 /* unlike hv_iterval(), this always returns a mortal copy of the key */
2222 /*
2223 =for apidoc hv_iterkeysv
2224
2225 Returns the key as an C<SV*> from the current position of the hash
2226 iterator.  The return value will always be a mortal copy of the key.  Also
2227 see C<hv_iterinit>.
2228
2229 =cut
2230 */
2231
2232 SV *
2233 Perl_hv_iterkeysv(pTHX_ register HE *entry)
2234 {
2235     return sv_2mortal(newSVhek(HeKEY_hek(entry)));
2236 }
2237
2238 /*
2239 =for apidoc hv_iterval
2240
2241 Returns the value from the current position of the hash iterator.  See
2242 C<hv_iterkey>.
2243
2244 =cut
2245 */
2246
2247 SV *
2248 Perl_hv_iterval(pTHX_ HV *hv, register HE *entry)
2249 {
2250     if (SvRMAGICAL(hv)) {
2251         if (mg_find((SV*)hv, PERL_MAGIC_tied)) {
2252             SV* const sv = sv_newmortal();
2253             if (HeKLEN(entry) == HEf_SVKEY)
2254                 mg_copy((SV*)hv, sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
2255             else
2256                 mg_copy((SV*)hv, sv, HeKEY(entry), HeKLEN(entry));
2257             return sv;
2258         }
2259     }
2260     return HeVAL(entry);
2261 }
2262
2263 /*
2264 =for apidoc hv_iternextsv
2265
2266 Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2267 operation.
2268
2269 =cut
2270 */
2271
2272 SV *
2273 Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
2274 {
2275     HE * const he = hv_iternext_flags(hv, 0);
2276
2277     if (!he)
2278         return NULL;
2279     *key = hv_iterkey(he, retlen);
2280     return hv_iterval(hv, he);
2281 }
2282
2283 /*
2284
2285 Now a macro in hv.h
2286
2287 =for apidoc hv_magic
2288
2289 Adds magic to a hash.  See C<sv_magic>.
2290
2291 =cut
2292 */
2293
2294 /* possibly free a shared string if no one has access to it
2295  * len and hash must both be valid for str.
2296  */
2297 void
2298 Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
2299 {
2300     unshare_hek_or_pvn (NULL, str, len, hash);
2301 }
2302
2303
2304 void
2305 Perl_unshare_hek(pTHX_ HEK *hek)
2306 {
2307     assert(hek);
2308     unshare_hek_or_pvn(hek, NULL, 0, 0);
2309 }
2310
2311 /* possibly free a shared string if no one has access to it
2312    hek if non-NULL takes priority over the other 3, else str, len and hash
2313    are used.  If so, len and hash must both be valid for str.
2314  */
2315 STATIC void
2316 S_unshare_hek_or_pvn(pTHX_ const HEK *hek, const char *str, I32 len, U32 hash)
2317 {
2318     dVAR;
2319     register XPVHV* xhv;
2320     HE *entry;
2321     register HE **oentry;
2322     HE **first;
2323     bool is_utf8 = FALSE;
2324     int k_flags = 0;
2325     const char * const save = str;
2326     struct shared_he *he = NULL;
2327
2328     if (hek) {
2329         /* Find the shared he which is just before us in memory.  */
2330         he = (struct shared_he *)(((char *)hek)
2331                                   - STRUCT_OFFSET(struct shared_he,
2332                                                   shared_he_hek));
2333
2334         /* Assert that the caller passed us a genuine (or at least consistent)
2335            shared hek  */
2336         assert (he->shared_he_he.hent_hek == hek);
2337
2338         LOCK_STRTAB_MUTEX;
2339         if (he->shared_he_he.he_valu.hent_refcount - 1) {
2340             --he->shared_he_he.he_valu.hent_refcount;
2341             UNLOCK_STRTAB_MUTEX;
2342             return;
2343         }
2344         UNLOCK_STRTAB_MUTEX;
2345
2346         hash = HEK_HASH(hek);
2347     } else if (len < 0) {
2348         STRLEN tmplen = -len;
2349         is_utf8 = TRUE;
2350         /* See the note in hv_fetch(). --jhi */
2351         str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2352         len = tmplen;
2353         if (is_utf8)
2354             k_flags = HVhek_UTF8;
2355         if (str != save)
2356             k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2357     }
2358
2359     /* what follows was the moral equivalent of:
2360     if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
2361         if (--*Svp == NULL)
2362             hv_delete(PL_strtab, str, len, G_DISCARD, hash);
2363     } */
2364     xhv = (XPVHV*)SvANY(PL_strtab);
2365     /* assert(xhv_array != 0) */
2366     LOCK_STRTAB_MUTEX;
2367     first = oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2368     if (he) {
2369         const HE *const he_he = &(he->shared_he_he);
2370         for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2371             if (entry == he_he)
2372                 break;
2373         }
2374     } else {
2375         const int flags_masked = k_flags & HVhek_MASK;
2376         for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2377             if (HeHASH(entry) != hash)          /* strings can't be equal */
2378                 continue;
2379             if (HeKLEN(entry) != len)
2380                 continue;
2381             if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len))     /* is this it? */
2382                 continue;
2383             if (HeKFLAGS(entry) != flags_masked)
2384                 continue;
2385             break;
2386         }
2387     }
2388
2389     if (entry) {
2390         if (--entry->he_valu.hent_refcount == 0) {
2391             *oentry = HeNEXT(entry);
2392             if (!*first) {
2393                 /* There are now no entries in our slot.  */
2394                 xhv->xhv_fill--; /* HvFILL(hv)-- */
2395             }
2396             Safefree(entry);
2397             xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
2398         }
2399     }
2400
2401     UNLOCK_STRTAB_MUTEX;
2402     if (!entry && ckWARN_d(WARN_INTERNAL))
2403         Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
2404                     "Attempt to free non-existent shared string '%s'%s"
2405                     pTHX__FORMAT,
2406                     hek ? HEK_KEY(hek) : str,
2407                     ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
2408     if (k_flags & HVhek_FREEKEY)
2409         Safefree(str);
2410 }
2411
2412 /* get a (constant) string ptr from the global string table
2413  * string will get added if it is not already there.
2414  * len and hash must both be valid for str.
2415  */
2416 HEK *
2417 Perl_share_hek(pTHX_ const char *str, I32 len, register U32 hash)
2418 {
2419     bool is_utf8 = FALSE;
2420     int flags = 0;
2421     const char * const save = str;
2422
2423     if (len < 0) {
2424       STRLEN tmplen = -len;
2425       is_utf8 = TRUE;
2426       /* See the note in hv_fetch(). --jhi */
2427       str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2428       len = tmplen;
2429       /* If we were able to downgrade here, then than means that we were passed
2430          in a key which only had chars 0-255, but was utf8 encoded.  */
2431       if (is_utf8)
2432           flags = HVhek_UTF8;
2433       /* If we found we were able to downgrade the string to bytes, then
2434          we should flag that it needs upgrading on keys or each.  Also flag
2435          that we need share_hek_flags to free the string.  */
2436       if (str != save)
2437           flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2438     }
2439
2440     return share_hek_flags (str, len, hash, flags);
2441 }
2442
2443 STATIC HEK *
2444 S_share_hek_flags(pTHX_ const char *str, I32 len, register U32 hash, int flags)
2445 {
2446     dVAR;
2447     register HE *entry;
2448     const int flags_masked = flags & HVhek_MASK;
2449     const U32 hindex = hash & (I32) HvMAX(PL_strtab);
2450
2451     /* what follows is the moral equivalent of:
2452
2453     if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
2454         hv_store(PL_strtab, str, len, NULL, hash);
2455
2456         Can't rehash the shared string table, so not sure if it's worth
2457         counting the number of entries in the linked list
2458     */
2459     register XPVHV * const xhv = (XPVHV*)SvANY(PL_strtab);
2460     /* assert(xhv_array != 0) */
2461     LOCK_STRTAB_MUTEX;
2462     entry = (HvARRAY(PL_strtab))[hindex];
2463     for (;entry; entry = HeNEXT(entry)) {
2464         if (HeHASH(entry) != hash)              /* strings can't be equal */
2465             continue;
2466         if (HeKLEN(entry) != len)
2467             continue;
2468         if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2469             continue;
2470         if (HeKFLAGS(entry) != flags_masked)
2471             continue;
2472         break;
2473     }
2474
2475     if (!entry) {
2476         /* What used to be head of the list.
2477            If this is NULL, then we're the first entry for this slot, which
2478            means we need to increate fill.  */
2479         struct shared_he *new_entry;
2480         HEK *hek;
2481         char *k;
2482         HE **const head = &HvARRAY(PL_strtab)[hindex];
2483         HE *const next = *head;
2484
2485         /* We don't actually store a HE from the arena and a regular HEK.
2486            Instead we allocate one chunk of memory big enough for both,
2487            and put the HEK straight after the HE. This way we can find the
2488            HEK directly from the HE.
2489         */
2490
2491         Newx(k, STRUCT_OFFSET(struct shared_he,
2492                                 shared_he_hek.hek_key[0]) + len + 2, char);
2493         new_entry = (struct shared_he *)k;
2494         entry = &(new_entry->shared_he_he);
2495         hek = &(new_entry->shared_he_hek);
2496
2497         Copy(str, HEK_KEY(hek), len, char);
2498         HEK_KEY(hek)[len] = 0;
2499         HEK_LEN(hek) = len;
2500         HEK_HASH(hek) = hash;
2501         HEK_FLAGS(hek) = (unsigned char)flags_masked;
2502
2503         /* Still "point" to the HEK, so that other code need not know what
2504            we're up to.  */
2505         HeKEY_hek(entry) = hek;
2506         entry->he_valu.hent_refcount = 0;
2507         HeNEXT(entry) = next;
2508         *head = entry;
2509
2510         xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
2511         if (!next) {                    /* initial entry? */
2512             xhv->xhv_fill++; /* HvFILL(hv)++ */
2513         } else if (xhv->xhv_keys > (IV)xhv->xhv_max /* HvKEYS(hv) > HvMAX(hv) */) {
2514                 hsplit(PL_strtab);
2515         }
2516     }
2517
2518     ++entry->he_valu.hent_refcount;
2519     UNLOCK_STRTAB_MUTEX;
2520
2521     if (flags & HVhek_FREEKEY)
2522         Safefree(str);
2523
2524     return HeKEY_hek(entry);
2525 }
2526
2527 STATIC SV *
2528 S_hv_magic_uvar_xkey(pTHX_ HV* hv, SV* keysv, const char *const key,
2529                      const STRLEN klen, const int k_flags, int action)
2530 {
2531     MAGIC* mg;
2532     if ((mg = mg_find((SV*)hv, PERL_MAGIC_uvar))) {
2533         struct ufuncs * const uf = (struct ufuncs *)mg->mg_ptr;
2534         if (uf->uf_set == NULL) {
2535             SV* obj = mg->mg_obj;
2536
2537             if (!keysv) {
2538                 keysv = sv_2mortal(newSVpvn(key, klen));
2539                 if (k_flags & HVhek_UTF8)
2540                     SvUTF8_on(keysv);
2541             }
2542                 
2543             mg->mg_obj = keysv;         /* pass key */
2544             uf->uf_index = action;      /* pass action */
2545             magic_getuvar((SV*)hv, mg);
2546             keysv = mg->mg_obj;         /* may have changed */
2547             mg->mg_obj = obj;
2548         }
2549     }
2550     return keysv;
2551 }
2552
2553 I32 *
2554 Perl_hv_placeholders_p(pTHX_ HV *hv)
2555 {
2556     dVAR;
2557     MAGIC *mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2558
2559     if (!mg) {
2560         mg = sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, 0);
2561
2562         if (!mg) {
2563             Perl_die(aTHX_ "panic: hv_placeholders_p");
2564         }
2565     }
2566     return &(mg->mg_len);
2567 }
2568
2569
2570 I32
2571 Perl_hv_placeholders_get(pTHX_ HV *hv)
2572 {
2573     dVAR;
2574     MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2575
2576     return mg ? mg->mg_len : 0;
2577 }
2578
2579 void
2580 Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
2581 {
2582     dVAR;
2583     MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2584
2585     if (mg) {
2586         mg->mg_len = ph;
2587     } else if (ph) {
2588         if (!sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, ph))
2589             Perl_die(aTHX_ "panic: hv_placeholders_set");
2590     }
2591     /* else we don't need to add magic to record 0 placeholders.  */
2592 }
2593
2594 STATIC SV *
2595 S_refcounted_he_value(pTHX_ const struct refcounted_he *he)
2596 {
2597     dVAR;
2598     SV *value;
2599     switch(he->refcounted_he_data[0] & HVrhek_typemask) {
2600     case HVrhek_undef:
2601         value = newSV(0);
2602         break;
2603     case HVrhek_delete:
2604         value = &PL_sv_placeholder;
2605         break;
2606     case HVrhek_IV:
2607         value = newSViv(he->refcounted_he_val.refcounted_he_u_iv);
2608         break;
2609     case HVrhek_UV:
2610         value = newSVuv(he->refcounted_he_val.refcounted_he_u_uv);
2611         break;
2612     case HVrhek_PV:
2613     case HVrhek_PV_UTF8:
2614         /* Create a string SV that directly points to the bytes in our
2615            structure.  */
2616         value = newSV_type(SVt_PV);
2617         SvPV_set(value, (char *) he->refcounted_he_data + 1);
2618         SvCUR_set(value, he->refcounted_he_val.refcounted_he_u_len);
2619         /* This stops anything trying to free it  */
2620         SvLEN_set(value, 0);
2621         SvPOK_on(value);
2622         SvREADONLY_on(value);
2623         if ((he->refcounted_he_data[0] & HVrhek_typemask) == HVrhek_PV_UTF8)
2624             SvUTF8_on(value);
2625         break;
2626     default:
2627         Perl_croak(aTHX_ "panic: refcounted_he_value bad flags %x",
2628                    he->refcounted_he_data[0]);
2629     }
2630     return value;
2631 }
2632
2633 /*
2634 =for apidoc refcounted_he_chain_2hv
2635
2636 Generates and returns a C<HV *> by walking up the tree starting at the passed
2637 in C<struct refcounted_he *>.
2638
2639 =cut
2640 */
2641 HV *
2642 Perl_refcounted_he_chain_2hv(pTHX_ const struct refcounted_he *chain)
2643 {
2644     dVAR;
2645     HV *hv = newHV();
2646     U32 placeholders = 0;
2647     /* We could chase the chain once to get an idea of the number of keys,
2648        and call ksplit.  But for now we'll make a potentially inefficient
2649        hash with only 8 entries in its array.  */
2650     const U32 max = HvMAX(hv);
2651
2652     if (!HvARRAY(hv)) {
2653         char *array;
2654         Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(max + 1), char);
2655         HvARRAY(hv) = (HE**)array;
2656     }
2657
2658     while (chain) {
2659 #ifdef USE_ITHREADS
2660         U32 hash = chain->refcounted_he_hash;
2661 #else
2662         U32 hash = HEK_HASH(chain->refcounted_he_hek);
2663 #endif
2664         HE **oentry = &((HvARRAY(hv))[hash & max]);
2665         HE *entry = *oentry;
2666         SV *value;
2667
2668         for (; entry; entry = HeNEXT(entry)) {
2669             if (HeHASH(entry) == hash) {
2670                 /* We might have a duplicate key here.  If so, entry is older
2671                    than the key we've already put in the hash, so if they are
2672                    the same, skip adding entry.  */
2673 #ifdef USE_ITHREADS
2674                 const STRLEN klen = HeKLEN(entry);
2675                 const char *const key = HeKEY(entry);
2676                 if (klen == chain->refcounted_he_keylen
2677                     && (!!HeKUTF8(entry)
2678                         == !!(chain->refcounted_he_data[0] & HVhek_UTF8))
2679                     && memEQ(key, REF_HE_KEY(chain), klen))
2680                     goto next_please;
2681 #else
2682                 if (HeKEY_hek(entry) == chain->refcounted_he_hek)
2683                     goto next_please;
2684                 if (HeKLEN(entry) == HEK_LEN(chain->refcounted_he_hek)
2685                     && HeKUTF8(entry) == HEK_UTF8(chain->refcounted_he_hek)
2686                     && memEQ(HeKEY(entry), HEK_KEY(chain->refcounted_he_hek),
2687                              HeKLEN(entry)))
2688                     goto next_please;
2689 #endif
2690             }
2691         }
2692         assert (!entry);
2693         entry = new_HE();
2694
2695 #ifdef USE_ITHREADS
2696         HeKEY_hek(entry)
2697             = share_hek_flags(REF_HE_KEY(chain),
2698                               chain->refcounted_he_keylen,
2699                               chain->refcounted_he_hash,
2700                               (chain->refcounted_he_data[0]
2701                                & (HVhek_UTF8|HVhek_WASUTF8)));
2702 #else
2703         HeKEY_hek(entry) = share_hek_hek(chain->refcounted_he_hek);
2704 #endif
2705         value = refcounted_he_value(chain);
2706         if (value == &PL_sv_placeholder)
2707             placeholders++;
2708         HeVAL(entry) = value;
2709
2710         /* Link it into the chain.  */
2711         HeNEXT(entry) = *oentry;
2712         if (!HeNEXT(entry)) {
2713             /* initial entry.   */
2714             HvFILL(hv)++;
2715         }
2716         *oentry = entry;
2717
2718         HvTOTALKEYS(hv)++;
2719
2720     next_please:
2721         chain = chain->refcounted_he_next;
2722     }
2723
2724     if (placeholders) {
2725         clear_placeholders(hv, placeholders);
2726         HvTOTALKEYS(hv) -= placeholders;
2727     }
2728
2729     /* We could check in the loop to see if we encounter any keys with key
2730        flags, but it's probably not worth it, as this per-hash flag is only
2731        really meant as an optimisation for things like Storable.  */
2732     HvHASKFLAGS_on(hv);
2733     DEBUG_A(Perl_hv_assert(aTHX_ hv));
2734
2735     return hv;
2736 }
2737
2738 SV *
2739 Perl_refcounted_he_fetch(pTHX_ const struct refcounted_he *chain, SV *keysv,
2740                          const char *key, STRLEN klen, int flags, U32 hash)
2741 {
2742     dVAR;
2743     /* Just to be awkward, if you're using this interface the UTF-8-or-not-ness
2744        of your key has to exactly match that which is stored.  */
2745     SV *value = &PL_sv_placeholder;
2746     bool is_utf8;
2747
2748     if (keysv) {
2749         if (flags & HVhek_FREEKEY)
2750             Safefree(key);
2751         key = SvPV_const(keysv, klen);
2752         flags = 0;
2753         is_utf8 = (SvUTF8(keysv) != 0);
2754     } else {
2755         is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
2756     }
2757
2758     if (!hash) {
2759         if (keysv && (SvIsCOW_shared_hash(keysv))) {
2760             hash = SvSHARED_HASH(keysv);
2761         } else {
2762             PERL_HASH(hash, key, klen);
2763         }
2764     }
2765
2766     for (; chain; chain = chain->refcounted_he_next) {
2767 #ifdef USE_ITHREADS
2768         if (hash != chain->refcounted_he_hash)
2769             continue;
2770         if (klen != chain->refcounted_he_keylen)
2771             continue;
2772         if (memNE(REF_HE_KEY(chain),key,klen))
2773             continue;
2774         if (!!is_utf8 != !!(chain->refcounted_he_data[0] & HVhek_UTF8))
2775             continue;
2776 #else
2777         if (hash != HEK_HASH(chain->refcounted_he_hek))
2778             continue;
2779         if (klen != (STRLEN)HEK_LEN(chain->refcounted_he_hek))
2780             continue;
2781         if (memNE(HEK_KEY(chain->refcounted_he_hek),key,klen))
2782             continue;
2783         if (!!is_utf8 != !!HEK_UTF8(chain->refcounted_he_hek))
2784             continue;
2785 #endif
2786
2787         value = sv_2mortal(refcounted_he_value(chain));
2788         break;
2789     }
2790
2791     if (flags & HVhek_FREEKEY)
2792         Safefree(key);
2793
2794     return value;
2795 }
2796
2797 /*
2798 =for apidoc refcounted_he_new
2799
2800 Creates a new C<struct refcounted_he>. As S<key> is copied, and value is
2801 stored in a compact form, all references remain the property of the caller.
2802 The C<struct refcounted_he> is returned with a reference count of 1.
2803
2804 =cut
2805 */
2806
2807 struct refcounted_he *
2808 Perl_refcounted_he_new(pTHX_ struct refcounted_he *const parent,
2809                        SV *const key, SV *const value) {
2810     dVAR;
2811     struct refcounted_he *he;
2812     STRLEN key_len;
2813     const char *key_p = SvPV_const(key, key_len);
2814     STRLEN value_len = 0;
2815     const char *value_p = NULL;
2816     char value_type;
2817     char flags;
2818     STRLEN key_offset;
2819     U32 hash;
2820     bool is_utf8 = SvUTF8(key) ? TRUE : FALSE;
2821
2822     if (SvPOK(value)) {
2823         value_type = HVrhek_PV;
2824     } else if (SvIOK(value)) {
2825         value_type = HVrhek_IV;
2826     } else if (value == &PL_sv_placeholder) {
2827         value_type = HVrhek_delete;
2828     } else if (!SvOK(value)) {
2829         value_type = HVrhek_undef;
2830     } else {
2831         value_type = HVrhek_PV;
2832     }
2833
2834     if (value_type == HVrhek_PV) {
2835         value_p = SvPV_const(value, value_len);
2836         key_offset = value_len + 2;
2837     } else {
2838         value_len = 0;
2839         key_offset = 1;
2840     }
2841
2842 #ifdef USE_ITHREADS
2843     he = (struct refcounted_he*)
2844         PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
2845                              + key_len
2846                              + key_offset);
2847 #else
2848     he = (struct refcounted_he*)
2849         PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
2850                              + key_offset);
2851 #endif
2852
2853
2854     he->refcounted_he_next = parent;
2855
2856     if (value_type == HVrhek_PV) {
2857         Copy(value_p, he->refcounted_he_data + 1, value_len + 1, char);
2858         he->refcounted_he_val.refcounted_he_u_len = value_len;
2859         /* Do it this way so that the SvUTF8() test is after the SvPV, in case
2860            the value is overloaded, and doesn't yet have the UTF-8flag set.  */
2861         if (SvUTF8(value))
2862             value_type = HVrhek_PV_UTF8;
2863     } else if (value_type == HVrhek_IV) {
2864         if (SvUOK(value)) {
2865             he->refcounted_he_val.refcounted_he_u_uv = SvUVX(value);
2866             value_type = HVrhek_UV;
2867         } else {
2868             he->refcounted_he_val.refcounted_he_u_iv = SvIVX(value);
2869         }
2870     }
2871     flags = value_type;
2872
2873     if (is_utf8) {
2874         /* Hash keys are always stored normalised to (yes) ISO-8859-1.
2875            As we're going to be building hash keys from this value in future,
2876            normalise it now.  */
2877         key_p = (char*)bytes_from_utf8((const U8*)key_p, &key_len, &is_utf8);
2878         flags |= is_utf8 ? HVhek_UTF8 : HVhek_WASUTF8;
2879     }
2880     PERL_HASH(hash, key_p, key_len);
2881
2882 #ifdef USE_ITHREADS
2883     he->refcounted_he_hash = hash;
2884     he->refcounted_he_keylen = key_len;
2885     Copy(key_p, he->refcounted_he_data + key_offset, key_len, char);
2886 #else
2887     he->refcounted_he_hek = share_hek_flags(key_p, key_len, hash, flags);
2888 #endif
2889
2890     if (flags & HVhek_WASUTF8) {
2891         /* If it was downgraded from UTF-8, then the pointer returned from
2892            bytes_from_utf8 is an allocated pointer that we must free.  */
2893         Safefree(key_p);
2894     }
2895
2896     he->refcounted_he_data[0] = flags;
2897     he->refcounted_he_refcnt = 1;
2898
2899     return he;
2900 }
2901
2902 /*
2903 =for apidoc refcounted_he_free
2904
2905 Decrements the reference count of the passed in C<struct refcounted_he *>
2906 by one. If the reference count reaches zero the structure's memory is freed,
2907 and C<refcounted_he_free> iterates onto the parent node.
2908
2909 =cut
2910 */
2911
2912 void
2913 Perl_refcounted_he_free(pTHX_ struct refcounted_he *he) {
2914     dVAR;
2915     PERL_UNUSED_CONTEXT;
2916
2917     while (he) {
2918         struct refcounted_he *copy;
2919         U32 new_count;
2920
2921         HINTS_REFCNT_LOCK;
2922         new_count = --he->refcounted_he_refcnt;
2923         HINTS_REFCNT_UNLOCK;
2924         
2925         if (new_count) {
2926             return;
2927         }
2928
2929 #ifndef USE_ITHREADS
2930         unshare_hek_or_pvn (he->refcounted_he_hek, 0, 0, 0);
2931 #endif
2932         copy = he;
2933         he = he->refcounted_he_next;
2934         PerlMemShared_free(copy);
2935     }
2936 }
2937
2938 /*
2939 =for apidoc hv_assert
2940
2941 Check that a hash is in an internally consistent state.
2942
2943 =cut
2944 */
2945
2946 #ifdef DEBUGGING
2947
2948 void
2949 Perl_hv_assert(pTHX_ HV *hv)
2950 {
2951     dVAR;
2952     HE* entry;
2953     int withflags = 0;
2954     int placeholders = 0;
2955     int real = 0;
2956     int bad = 0;
2957     const I32 riter = HvRITER_get(hv);
2958     HE *eiter = HvEITER_get(hv);
2959
2960     (void)hv_iterinit(hv);
2961
2962     while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
2963         /* sanity check the values */
2964         if (HeVAL(entry) == &PL_sv_placeholder)
2965             placeholders++;
2966         else
2967             real++;
2968         /* sanity check the keys */
2969         if (HeSVKEY(entry)) {
2970             NOOP;   /* Don't know what to check on SV keys.  */
2971         } else if (HeKUTF8(entry)) {
2972             withflags++;
2973             if (HeKWASUTF8(entry)) {
2974                 PerlIO_printf(Perl_debug_log,
2975                             "hash key has both WASUTF8 and UTF8: '%.*s'\n",
2976                             (int) HeKLEN(entry),  HeKEY(entry));
2977                 bad = 1;
2978             }
2979         } else if (HeKWASUTF8(entry))
2980             withflags++;
2981     }
2982     if (!SvTIED_mg((SV*)hv, PERL_MAGIC_tied)) {
2983         static const char bad_count[] = "Count %d %s(s), but hash reports %d\n";
2984         const int nhashkeys = HvUSEDKEYS(hv);
2985         const int nhashplaceholders = HvPLACEHOLDERS_get(hv);
2986
2987         if (nhashkeys != real) {
2988             PerlIO_printf(Perl_debug_log, bad_count, real, "keys", nhashkeys );
2989             bad = 1;
2990         }
2991         if (nhashplaceholders != placeholders) {
2992             PerlIO_printf(Perl_debug_log, bad_count, placeholders, "placeholder", nhashplaceholders );
2993             bad = 1;
2994         }
2995     }
2996     if (withflags && ! HvHASKFLAGS(hv)) {
2997         PerlIO_printf(Perl_debug_log,
2998                     "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
2999                     withflags);
3000         bad = 1;
3001     }
3002     if (bad) {
3003         sv_dump((SV *)hv);
3004     }
3005     HvRITER_set(hv, riter);             /* Restore hash iterator state */
3006     HvEITER_set(hv, eiter);
3007 }
3008
3009 #endif
3010
3011 /*
3012  * Local variables:
3013  * c-indentation-style: bsd
3014  * c-basic-offset: 4
3015  * indent-tabs-mode: t
3016  * End:
3017  *
3018  * ex: set ts=8 sts=4 sw=4 noet:
3019  */