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