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