reentr.pl should be using regen_lib.pl and unlinking files before it
[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 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_const(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 = SvSHARED_HASH(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_const(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 = SvSHARED_HASH(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     HE *entry;
1771
1772     if (!hv)
1773         Perl_croak(aTHX_ "Bad hash");
1774
1775     if (SvOOK(hv)) {
1776         struct xpvhv_aux *iter = HvAUX(hv);
1777         entry = iter->xhv_eiter; /* HvEITER(hv) */
1778         if (entry && HvLAZYDEL(hv)) {   /* was deleted earlier? */
1779             HvLAZYDEL_off(hv);
1780             hv_free_ent(hv, entry);
1781         }
1782         iter->xhv_riter = -1;   /* HvRITER(hv) = -1 */
1783         iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1784     } else {
1785         S_hv_auxinit(aTHX_ hv);
1786     }
1787
1788     /* used to be xhv->xhv_fill before 5.004_65 */
1789     return HvTOTALKEYS(hv);
1790 }
1791
1792 I32 *
1793 Perl_hv_riter_p(pTHX_ HV *hv) {
1794     struct xpvhv_aux *iter;
1795
1796     if (!hv)
1797         Perl_croak(aTHX_ "Bad hash");
1798
1799     iter = SvOOK(hv) ? HvAUX(hv) : S_hv_auxinit(aTHX_ hv);
1800     return &(iter->xhv_riter);
1801 }
1802
1803 HE **
1804 Perl_hv_eiter_p(pTHX_ HV *hv) {
1805     struct xpvhv_aux *iter;
1806
1807     if (!hv)
1808         Perl_croak(aTHX_ "Bad hash");
1809
1810     iter = SvOOK(hv) ? HvAUX(hv) : S_hv_auxinit(aTHX_ hv);
1811     return &(iter->xhv_eiter);
1812 }
1813
1814 void
1815 Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
1816     struct xpvhv_aux *iter;
1817
1818     if (!hv)
1819         Perl_croak(aTHX_ "Bad hash");
1820
1821     if (SvOOK(hv)) {
1822         iter = HvAUX(hv);
1823     } else {
1824         if (riter == -1)
1825             return;
1826
1827         iter = S_hv_auxinit(aTHX_ hv);
1828     }
1829     iter->xhv_riter = riter;
1830 }
1831
1832 void
1833 Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
1834     struct xpvhv_aux *iter;
1835
1836     if (!hv)
1837         Perl_croak(aTHX_ "Bad hash");
1838
1839     if (SvOOK(hv)) {
1840         iter = HvAUX(hv);
1841     } else {
1842         /* 0 is the default so don't go malloc()ing a new structure just to
1843            hold 0.  */
1844         if (!eiter)
1845             return;
1846
1847         iter = S_hv_auxinit(aTHX_ hv);
1848     }
1849     iter->xhv_eiter = eiter;
1850 }
1851
1852 void
1853 Perl_hv_name_set(pTHX_ HV *hv, const char *name, I32 len, int flags)
1854 {
1855     struct xpvhv_aux *iter;
1856     U32 hash;
1857     (void)flags;
1858
1859     if (SvOOK(hv)) {
1860         iter = HvAUX(hv);
1861         if (iter->xhv_name) {
1862             unshare_hek_or_pvn(iter->xhv_name, 0, 0, 0);
1863         }
1864     } else {
1865         if (name == 0)
1866             return;
1867
1868         iter = S_hv_auxinit(aTHX_ hv);
1869     }
1870     PERL_HASH(hash, name, len);
1871     iter->xhv_name = name ? share_hek(name, len, hash) : 0;
1872 }
1873
1874 /*
1875 =for apidoc hv_iternext
1876
1877 Returns entries from a hash iterator.  See C<hv_iterinit>.
1878
1879 You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
1880 iterator currently points to, without losing your place or invalidating your
1881 iterator.  Note that in this case the current entry is deleted from the hash
1882 with your iterator holding the last reference to it.  Your iterator is flagged
1883 to free the entry on the next call to C<hv_iternext>, so you must not discard
1884 your iterator immediately else the entry will leak - call C<hv_iternext> to
1885 trigger the resource deallocation.
1886
1887 =cut
1888 */
1889
1890 HE *
1891 Perl_hv_iternext(pTHX_ HV *hv)
1892 {
1893     return hv_iternext_flags(hv, 0);
1894 }
1895
1896 /*
1897 =for apidoc hv_iternext_flags
1898
1899 Returns entries from a hash iterator.  See C<hv_iterinit> and C<hv_iternext>.
1900 The C<flags> value will normally be zero; if HV_ITERNEXT_WANTPLACEHOLDERS is
1901 set the placeholders keys (for restricted hashes) will be returned in addition
1902 to normal keys. By default placeholders are automatically skipped over.
1903 Currently a placeholder is implemented with a value that is
1904 C<&Perl_sv_placeholder>. Note that the implementation of placeholders and
1905 restricted hashes may change, and the implementation currently is
1906 insufficiently abstracted for any change to be tidy.
1907
1908 =cut
1909 */
1910
1911 HE *
1912 Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
1913 {
1914     dVAR;
1915     register XPVHV* xhv;
1916     register HE *entry;
1917     HE *oldentry;
1918     MAGIC* mg;
1919     struct xpvhv_aux *iter;
1920
1921     if (!hv)
1922         Perl_croak(aTHX_ "Bad hash");
1923     xhv = (XPVHV*)SvANY(hv);
1924
1925     if (!SvOOK(hv)) {
1926         /* Too many things (well, pp_each at least) merrily assume that you can
1927            call iv_iternext without calling hv_iterinit, so we'll have to deal
1928            with it.  */
1929         hv_iterinit(hv);
1930     }
1931     iter = HvAUX(hv);
1932
1933     oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
1934
1935     if ((mg = SvTIED_mg((SV*)hv, PERL_MAGIC_tied))) {
1936         SV *key = sv_newmortal();
1937         if (entry) {
1938             sv_setsv(key, HeSVKEY_force(entry));
1939             SvREFCNT_dec(HeSVKEY(entry));       /* get rid of previous key */
1940         }
1941         else {
1942             char *k;
1943             HEK *hek;
1944
1945             /* one HE per MAGICAL hash */
1946             iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
1947             Zero(entry, 1, HE);
1948             Newz(54, k, HEK_BASESIZE + sizeof(SV*), char);
1949             hek = (HEK*)k;
1950             HeKEY_hek(entry) = hek;
1951             HeKLEN(entry) = HEf_SVKEY;
1952         }
1953         magic_nextpack((SV*) hv,mg,key);
1954         if (SvOK(key)) {
1955             /* force key to stay around until next time */
1956             HeSVKEY_set(entry, SvREFCNT_inc(key));
1957             return entry;               /* beware, hent_val is not set */
1958         }
1959         if (HeVAL(entry))
1960             SvREFCNT_dec(HeVAL(entry));
1961         Safefree(HeKEY_hek(entry));
1962         del_HE(entry);
1963         iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1964         return Null(HE*);
1965     }
1966 #ifdef DYNAMIC_ENV_FETCH  /* set up %ENV for iteration */
1967     if (!entry && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
1968         prime_env_iter();
1969 #endif
1970
1971     /* hv_iterint now ensures this.  */
1972     assert (HvARRAY(hv));
1973
1974     /* At start of hash, entry is NULL.  */
1975     if (entry)
1976     {
1977         entry = HeNEXT(entry);
1978         if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
1979             /*
1980              * Skip past any placeholders -- don't want to include them in
1981              * any iteration.
1982              */
1983             while (entry && HeVAL(entry) == &PL_sv_placeholder) {
1984                 entry = HeNEXT(entry);
1985             }
1986         }
1987     }
1988     while (!entry) {
1989         /* OK. Come to the end of the current list.  Grab the next one.  */
1990
1991         iter->xhv_riter++; /* HvRITER(hv)++ */
1992         if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
1993             /* There is no next one.  End of the hash.  */
1994             iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1995             break;
1996         }
1997         entry = (HvARRAY(hv))[iter->xhv_riter];
1998
1999         if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2000             /* If we have an entry, but it's a placeholder, don't count it.
2001                Try the next.  */
2002             while (entry && HeVAL(entry) == &PL_sv_placeholder)
2003                 entry = HeNEXT(entry);
2004         }
2005         /* Will loop again if this linked list starts NULL
2006            (for HV_ITERNEXT_WANTPLACEHOLDERS)
2007            or if we run through it and find only placeholders.  */
2008     }
2009
2010     if (oldentry && HvLAZYDEL(hv)) {            /* was deleted earlier? */
2011         HvLAZYDEL_off(hv);
2012         hv_free_ent(hv, oldentry);
2013     }
2014
2015     /*if (HvREHASH(hv) && entry && !HeKREHASH(entry))
2016       PerlIO_printf(PerlIO_stderr(), "Awooga %p %p\n", hv, entry);*/
2017
2018     iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
2019     return entry;
2020 }
2021
2022 /*
2023 =for apidoc hv_iterkey
2024
2025 Returns the key from the current position of the hash iterator.  See
2026 C<hv_iterinit>.
2027
2028 =cut
2029 */
2030
2031 char *
2032 Perl_hv_iterkey(pTHX_ register HE *entry, I32 *retlen)
2033 {
2034     if (HeKLEN(entry) == HEf_SVKEY) {
2035         STRLEN len;
2036         char *p = SvPV(HeKEY_sv(entry), len);
2037         *retlen = len;
2038         return p;
2039     }
2040     else {
2041         *retlen = HeKLEN(entry);
2042         return HeKEY(entry);
2043     }
2044 }
2045
2046 /* unlike hv_iterval(), this always returns a mortal copy of the key */
2047 /*
2048 =for apidoc hv_iterkeysv
2049
2050 Returns the key as an C<SV*> from the current position of the hash
2051 iterator.  The return value will always be a mortal copy of the key.  Also
2052 see C<hv_iterinit>.
2053
2054 =cut
2055 */
2056
2057 SV *
2058 Perl_hv_iterkeysv(pTHX_ register HE *entry)
2059 {
2060     return sv_2mortal(newSVhek(HeKEY_hek(entry)));
2061 }
2062
2063 /*
2064 =for apidoc hv_iterval
2065
2066 Returns the value from the current position of the hash iterator.  See
2067 C<hv_iterkey>.
2068
2069 =cut
2070 */
2071
2072 SV *
2073 Perl_hv_iterval(pTHX_ HV *hv, register HE *entry)
2074 {
2075     if (SvRMAGICAL(hv)) {
2076         if (mg_find((SV*)hv, PERL_MAGIC_tied)) {
2077             SV* sv = sv_newmortal();
2078             if (HeKLEN(entry) == HEf_SVKEY)
2079                 mg_copy((SV*)hv, sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
2080             else
2081                 mg_copy((SV*)hv, sv, HeKEY(entry), HeKLEN(entry));
2082             return sv;
2083         }
2084     }
2085     return HeVAL(entry);
2086 }
2087
2088 /*
2089 =for apidoc hv_iternextsv
2090
2091 Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2092 operation.
2093
2094 =cut
2095 */
2096
2097 SV *
2098 Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
2099 {
2100     HE *he;
2101     if ( (he = hv_iternext_flags(hv, 0)) == NULL)
2102         return NULL;
2103     *key = hv_iterkey(he, retlen);
2104     return hv_iterval(hv, he);
2105 }
2106
2107 /*
2108 =for apidoc hv_magic
2109
2110 Adds magic to a hash.  See C<sv_magic>.
2111
2112 =cut
2113 */
2114
2115 void
2116 Perl_hv_magic(pTHX_ HV *hv, GV *gv, int how)
2117 {
2118     sv_magic((SV*)hv, (SV*)gv, how, Nullch, 0);
2119 }
2120
2121 #if 0 /* use the macro from hv.h instead */
2122
2123 char*   
2124 Perl_sharepvn(pTHX_ const char *sv, I32 len, U32 hash)
2125 {
2126     return HEK_KEY(share_hek(sv, len, hash));
2127 }
2128
2129 #endif
2130
2131 /* possibly free a shared string if no one has access to it
2132  * len and hash must both be valid for str.
2133  */
2134 void
2135 Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
2136 {
2137     unshare_hek_or_pvn (NULL, str, len, hash);
2138 }
2139
2140
2141 void
2142 Perl_unshare_hek(pTHX_ HEK *hek)
2143 {
2144     unshare_hek_or_pvn(hek, NULL, 0, 0);
2145 }
2146
2147 /* possibly free a shared string if no one has access to it
2148    hek if non-NULL takes priority over the other 3, else str, len and hash
2149    are used.  If so, len and hash must both be valid for str.
2150  */
2151 STATIC void
2152 S_unshare_hek_or_pvn(pTHX_ HEK *hek, const char *str, I32 len, U32 hash)
2153 {
2154     register XPVHV* xhv;
2155     register HE *entry;
2156     register HE **oentry;
2157     HE **first;
2158     bool found = 0;
2159     bool is_utf8 = FALSE;
2160     int k_flags = 0;
2161     const char *save = str;
2162
2163     if (hek) {
2164         hash = HEK_HASH(hek);
2165     } else if (len < 0) {
2166         STRLEN tmplen = -len;
2167         is_utf8 = TRUE;
2168         /* See the note in hv_fetch(). --jhi */
2169         str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2170         len = tmplen;
2171         if (is_utf8)
2172             k_flags = HVhek_UTF8;
2173         if (str != save)
2174             k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2175     }
2176
2177     /* what follows is the moral equivalent of:
2178     if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
2179         if (--*Svp == Nullsv)
2180             hv_delete(PL_strtab, str, len, G_DISCARD, hash);
2181     } */
2182     xhv = (XPVHV*)SvANY(PL_strtab);
2183     /* assert(xhv_array != 0) */
2184     LOCK_STRTAB_MUTEX;
2185     first = oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2186     if (hek) {
2187         for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2188             if (HeKEY_hek(entry) != hek)
2189                 continue;
2190             found = 1;
2191             break;
2192         }
2193     } else {
2194         const int flags_masked = k_flags & HVhek_MASK;
2195         for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2196             if (HeHASH(entry) != hash)          /* strings can't be equal */
2197                 continue;
2198             if (HeKLEN(entry) != len)
2199                 continue;
2200             if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len))     /* is this it? */
2201                 continue;
2202             if (HeKFLAGS(entry) != flags_masked)
2203                 continue;
2204             found = 1;
2205             break;
2206         }
2207     }
2208
2209     if (found) {
2210         if (--HeVAL(entry) == Nullsv) {
2211             *oentry = HeNEXT(entry);
2212             if (!*first) {
2213                 /* There are now no entries in our slot.  */
2214                 xhv->xhv_fill--; /* HvFILL(hv)-- */
2215             }
2216             Safefree(HeKEY_hek(entry));
2217             del_HE(entry);
2218             xhv->xhv_keys--; /* HvKEYS(hv)-- */
2219         }
2220     }
2221
2222     UNLOCK_STRTAB_MUTEX;
2223     if (!found && ckWARN_d(WARN_INTERNAL))
2224         Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
2225                     "Attempt to free non-existent shared string '%s'%s"
2226                     pTHX__FORMAT,
2227                     hek ? HEK_KEY(hek) : str,
2228                     ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
2229     if (k_flags & HVhek_FREEKEY)
2230         Safefree(str);
2231 }
2232
2233 /* get a (constant) string ptr from the global string table
2234  * string will get added if it is not already there.
2235  * len and hash must both be valid for str.
2236  */
2237 HEK *
2238 Perl_share_hek(pTHX_ const char *str, I32 len, register U32 hash)
2239 {
2240     bool is_utf8 = FALSE;
2241     int flags = 0;
2242     const char *save = str;
2243
2244     if (len < 0) {
2245       STRLEN tmplen = -len;
2246       is_utf8 = TRUE;
2247       /* See the note in hv_fetch(). --jhi */
2248       str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2249       len = tmplen;
2250       /* If we were able to downgrade here, then than means that we were passed
2251          in a key which only had chars 0-255, but was utf8 encoded.  */
2252       if (is_utf8)
2253           flags = HVhek_UTF8;
2254       /* If we found we were able to downgrade the string to bytes, then
2255          we should flag that it needs upgrading on keys or each.  Also flag
2256          that we need share_hek_flags to free the string.  */
2257       if (str != save)
2258           flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2259     }
2260
2261     return HeKEY_hek(share_hek_flags (str, len, hash, flags));
2262 }
2263
2264 STATIC HE *
2265 S_share_hek_flags(pTHX_ const char *str, I32 len, register U32 hash, int flags)
2266 {
2267     register XPVHV* xhv;
2268     register HE *entry;
2269     register HE **oentry;
2270     I32 found = 0;
2271     const int flags_masked = flags & HVhek_MASK;
2272
2273     /* what follows is the moral equivalent of:
2274
2275     if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
2276         hv_store(PL_strtab, str, len, Nullsv, hash);
2277
2278         Can't rehash the shared string table, so not sure if it's worth
2279         counting the number of entries in the linked list
2280     */
2281     xhv = (XPVHV*)SvANY(PL_strtab);
2282     /* assert(xhv_array != 0) */
2283     LOCK_STRTAB_MUTEX;
2284     oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2285     for (entry = *oentry; entry; entry = HeNEXT(entry)) {
2286         if (HeHASH(entry) != hash)              /* strings can't be equal */
2287             continue;
2288         if (HeKLEN(entry) != len)
2289             continue;
2290         if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2291             continue;
2292         if (HeKFLAGS(entry) != flags_masked)
2293             continue;
2294         found = 1;
2295         break;
2296     }
2297     if (!found) {
2298         /* What used to be head of the list.
2299            If this is NULL, then we're the first entry for this slot, which
2300            means we need to increate fill.  */
2301         const HE *old_first = *oentry;
2302         entry = new_HE();
2303         HeKEY_hek(entry) = save_hek_flags(str, len, hash, flags_masked);
2304         HeVAL(entry) = Nullsv;
2305         HeNEXT(entry) = *oentry;
2306         *oentry = entry;
2307         xhv->xhv_keys++; /* HvKEYS(hv)++ */
2308         if (!old_first) {                       /* initial entry? */
2309             xhv->xhv_fill++; /* HvFILL(hv)++ */
2310         } else if (xhv->xhv_keys > (IV)xhv->xhv_max /* HvKEYS(hv) > HvMAX(hv) */) {
2311                 hsplit(PL_strtab);
2312         }
2313     }
2314
2315     ++HeVAL(entry);                             /* use value slot as REFCNT */
2316     UNLOCK_STRTAB_MUTEX;
2317
2318     if (flags & HVhek_FREEKEY)
2319         Safefree(str);
2320
2321     return entry;
2322 }
2323
2324 I32 *
2325 Perl_hv_placeholders_p(pTHX_ HV *hv)
2326 {
2327     dVAR;
2328     MAGIC *mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2329
2330     if (!mg) {
2331         mg = sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, 0);
2332
2333         if (!mg) {
2334             Perl_die(aTHX_ "panic: hv_placeholders_p");
2335         }
2336     }
2337     return &(mg->mg_len);
2338 }
2339
2340
2341 I32
2342 Perl_hv_placeholders_get(pTHX_ HV *hv)
2343 {
2344     dVAR;
2345     MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2346
2347     return mg ? mg->mg_len : 0;
2348 }
2349
2350 void
2351 Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
2352 {
2353     dVAR;
2354     MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2355
2356     if (mg) {
2357         mg->mg_len = ph;
2358     } else if (ph) {
2359         if (!sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, ph))
2360             Perl_die(aTHX_ "panic: hv_placeholders_set");
2361     }
2362     /* else we don't need to add magic to record 0 placeholders.  */
2363 }
2364
2365 /*
2366 =for apidoc hv_assert
2367
2368 Check that a hash is in an internally consistent state.
2369
2370 =cut
2371 */
2372
2373 void
2374 Perl_hv_assert(pTHX_ HV *hv)
2375 {
2376   dVAR;
2377   HE* entry;
2378   int withflags = 0;
2379   int placeholders = 0;
2380   int real = 0;
2381   int bad = 0;
2382   const I32 riter = HvRITER_get(hv);
2383   HE *eiter = HvEITER_get(hv);
2384
2385   (void)hv_iterinit(hv);
2386
2387   while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
2388     /* sanity check the values */
2389     if (HeVAL(entry) == &PL_sv_placeholder) {
2390       placeholders++;
2391     } else {
2392       real++;
2393     }
2394     /* sanity check the keys */
2395     if (HeSVKEY(entry)) {
2396       /* Don't know what to check on SV keys.  */
2397     } else if (HeKUTF8(entry)) {
2398       withflags++;
2399        if (HeKWASUTF8(entry)) {
2400          PerlIO_printf(Perl_debug_log,
2401                        "hash key has both WASUFT8 and UTF8: '%.*s'\n",
2402                        (int) HeKLEN(entry),  HeKEY(entry));
2403          bad = 1;
2404        }
2405     } else if (HeKWASUTF8(entry)) {
2406       withflags++;
2407     }
2408   }
2409   if (!SvTIED_mg((SV*)hv, PERL_MAGIC_tied)) {
2410     if (HvUSEDKEYS(hv) != real) {
2411       PerlIO_printf(Perl_debug_log, "Count %d key(s), but hash reports %d\n",
2412                     (int) real, (int) HvUSEDKEYS(hv));
2413       bad = 1;
2414     }
2415     if (HvPLACEHOLDERS_get(hv) != placeholders) {
2416       PerlIO_printf(Perl_debug_log,
2417                     "Count %d placeholder(s), but hash reports %d\n",
2418                     (int) placeholders, (int) HvPLACEHOLDERS_get(hv));
2419       bad = 1;
2420     }
2421   }
2422   if (withflags && ! HvHASKFLAGS(hv)) {
2423     PerlIO_printf(Perl_debug_log,
2424                   "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
2425                   withflags);
2426     bad = 1;
2427   }
2428   if (bad) {
2429     sv_dump((SV *)hv);
2430   }
2431   HvRITER_set(hv, riter);               /* Restore hash iterator state */
2432   HvEITER_set(hv, eiter);
2433 }
2434
2435 /*
2436  * Local variables:
2437  * c-indentation-style: bsd
2438  * c-basic-offset: 4
2439  * indent-tabs-mode: t
2440  * End:
2441  *
2442  * ex: set ts=8 sts=4 sw=4 noet:
2443  */