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