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