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