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