This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
The binmode in t/iop/utf8.t doesn't need to be conditional on ${^OPEN}
[perl5.git] / hv.c
1 /*    hv.c
2  *
3  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4  *    2000, 2001, 2002, 2003, 2004, 2005, 2006, by Larry Wall and others
5  *
6  *    You may distribute under the terms of either the GNU General Public
7  *    License or the Artistic License, as specified in the README file.
8  *
9  */
10
11 /*
12  * "I sit beside the fire and think of all that I have seen."  --Bilbo
13  */
14
15 /* 
16 =head1 Hash Manipulation Functions
17
18 A HV structure represents a Perl hash. It consists mainly of an array
19 of pointers, each of which points to a linked list of HE structures. The
20 array is indexed by the hash function of the key, so each linked list
21 represents all the hash entries with the same hash value. Each HE contains
22 a pointer to the actual value, plus a pointer to a HEK structure which
23 holds the key and hash value.
24
25 =cut
26
27 */
28
29 #include "EXTERN.h"
30 #define PERL_IN_HV_C
31 #define PERL_HASH_INTERNAL_ACCESS
32 #include "perl.h"
33
34 #define HV_MAX_LENGTH_BEFORE_SPLIT 14
35
36 static const char S_strtab_error[]
37     = "Cannot modify shared string table in hv_%s";
38
39 STATIC void
40 S_more_he(pTHX)
41 {
42     dVAR;
43     HE* he;
44     HE* heend;
45
46     he = (HE*) Perl_get_arena(aTHX_ PERL_ARENA_SIZE);
47
48     heend = &he[PERL_ARENA_SIZE / sizeof(HE) - 1];
49     PL_body_roots[HE_SVSLOT] = he;
50     while (he < heend) {
51         HeNEXT(he) = (HE*)(he + 1);
52         he++;
53     }
54     HeNEXT(he) = 0;
55 }
56
57 #ifdef PURIFY
58
59 #define new_HE() (HE*)safemalloc(sizeof(HE))
60 #define del_HE(p) safefree((char*)p)
61
62 #else
63
64 STATIC HE*
65 S_new_he(pTHX)
66 {
67     dVAR;
68     HE* he;
69     void ** const root = &PL_body_roots[HE_SVSLOT];
70
71     LOCK_SV_MUTEX;
72     if (!*root)
73         S_more_he(aTHX);
74     he = *root;
75     assert(he);
76     *root = HeNEXT(he);
77     UNLOCK_SV_MUTEX;
78     return he;
79 }
80
81 #define new_HE() new_he()
82 #define del_HE(p) \
83     STMT_START { \
84         LOCK_SV_MUTEX; \
85         HeNEXT(p) = (HE*)(PL_body_roots[HE_SVSLOT]);    \
86         PL_body_roots[HE_SVSLOT] = p; \
87         UNLOCK_SV_MUTEX; \
88     } STMT_END
89
90
91
92 #endif
93
94 STATIC HEK *
95 S_save_hek_flags(const char *str, I32 len, U32 hash, int flags)
96 {
97     const int flags_masked = flags & HVhek_MASK;
98     char *k;
99     register HEK *hek;
100
101     Newx(k, HEK_BASESIZE + len + 2, char);
102     hek = (HEK*)k;
103     Copy(str, HEK_KEY(hek), len, char);
104     HEK_KEY(hek)[len] = 0;
105     HEK_LEN(hek) = len;
106     HEK_HASH(hek) = hash;
107     HEK_FLAGS(hek) = (unsigned char)flags_masked | HVhek_UNSHARED;
108
109     if (flags & HVhek_FREEKEY)
110         Safefree(str);
111     return hek;
112 }
113
114 /* free the pool of temporary HE/HEK pairs returned by hv_fetch_ent
115  * for tied hashes */
116
117 void
118 Perl_free_tied_hv_pool(pTHX)
119 {
120     dVAR;
121     HE *he = PL_hv_fetch_ent_mh;
122     while (he) {
123         HE * const ohe = he;
124         Safefree(HeKEY_hek(he));
125         he = HeNEXT(he);
126         del_HE(ohe);
127     }
128     PL_hv_fetch_ent_mh = NULL;
129 }
130
131 #if defined(USE_ITHREADS)
132 HEK *
133 Perl_hek_dup(pTHX_ HEK *source, CLONE_PARAMS* param)
134 {
135     HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
136
137     PERL_UNUSED_ARG(param);
138
139     if (shared) {
140         /* We already shared this hash key.  */
141         (void)share_hek_hek(shared);
142     }
143     else {
144         shared
145             = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
146                               HEK_HASH(source), HEK_FLAGS(source));
147         ptr_table_store(PL_ptr_table, source, shared);
148     }
149     return shared;
150 }
151
152 HE *
153 Perl_he_dup(pTHX_ const HE *e, bool shared, CLONE_PARAMS* param)
154 {
155     HE *ret;
156
157     if (!e)
158         return NULL;
159     /* look for it in the table first */
160     ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
161     if (ret)
162         return ret;
163
164     /* create anew and remember what it is */
165     ret = new_HE();
166     ptr_table_store(PL_ptr_table, e, ret);
167
168     HeNEXT(ret) = he_dup(HeNEXT(e),shared, param);
169     if (HeKLEN(e) == HEf_SVKEY) {
170         char *k;
171         Newx(k, HEK_BASESIZE + sizeof(SV*), char);
172         HeKEY_hek(ret) = (HEK*)k;
173         HeKEY_sv(ret) = SvREFCNT_inc(sv_dup(HeKEY_sv(e), param));
174     }
175     else if (shared) {
176         /* This is hek_dup inlined, which seems to be important for speed
177            reasons.  */
178         HEK * const source = HeKEY_hek(e);
179         HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
180
181         if (shared) {
182             /* We already shared this hash key.  */
183             (void)share_hek_hek(shared);
184         }
185         else {
186             shared
187                 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
188                                   HEK_HASH(source), HEK_FLAGS(source));
189             ptr_table_store(PL_ptr_table, source, shared);
190         }
191         HeKEY_hek(ret) = shared;
192     }
193     else
194         HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
195                                         HeKFLAGS(e));
196     HeVAL(ret) = SvREFCNT_inc(sv_dup(HeVAL(e), param));
197     return ret;
198 }
199 #endif  /* USE_ITHREADS */
200
201 static void
202 S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
203                 const char *msg)
204 {
205     SV * const sv = sv_newmortal();
206     if (!(flags & HVhek_FREEKEY)) {
207         sv_setpvn(sv, key, klen);
208     }
209     else {
210         /* Need to free saved eventually assign to mortal SV */
211         /* XXX is this line an error ???:  SV *sv = sv_newmortal(); */
212         sv_usepvn(sv, (char *) key, klen);
213     }
214     if (flags & HVhek_UTF8) {
215         SvUTF8_on(sv);
216     }
217     Perl_croak(aTHX_ msg, sv);
218 }
219
220 /* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
221  * contains an SV* */
222
223 #define HV_FETCH_ISSTORE   0x01
224 #define HV_FETCH_ISEXISTS  0x02
225 #define HV_FETCH_LVALUE    0x04
226 #define HV_FETCH_JUST_SV   0x08
227
228 /*
229 =for apidoc hv_store
230
231 Stores an SV in a hash.  The hash key is specified as C<key> and C<klen> is
232 the length of the key.  The C<hash> parameter is the precomputed hash
233 value; if it is zero then Perl will compute it.  The return value will be
234 NULL if the operation failed or if the value did not need to be actually
235 stored within the hash (as in the case of tied hashes).  Otherwise it can
236 be dereferenced to get the original C<SV*>.  Note that the caller is
237 responsible for suitably incrementing the reference count of C<val> before
238 the call, and decrementing it if the function returned NULL.  Effectively
239 a successful hv_store takes ownership of one reference to C<val>.  This is
240 usually what you want; a newly created SV has a reference count of one, so
241 if all your code does is create SVs then store them in a hash, hv_store
242 will own the only reference to the new SV, and your code doesn't need to do
243 anything further to tidy up.  hv_store is not implemented as a call to
244 hv_store_ent, and does not create a temporary SV for the key, so if your
245 key data is not already in SV form then use hv_store in preference to
246 hv_store_ent.
247
248 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
249 information on how to use this function on tied hashes.
250
251 =cut
252 */
253
254 SV**
255 Perl_hv_store(pTHX_ HV *hv, const char *key, I32 klen_i32, SV *val, U32 hash)
256 {
257     HE *hek;
258     STRLEN klen;
259     int flags;
260
261     if (klen_i32 < 0) {
262         klen = -klen_i32;
263         flags = HVhek_UTF8;
264     } else {
265         klen = klen_i32;
266         flags = 0;
267     }
268     hek = hv_fetch_common (hv, NULL, key, klen, flags,
269                            (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
270     return hek ? &HeVAL(hek) : NULL;
271 }
272
273 /* XXX This looks like an ideal candidate to inline */
274 SV**
275 Perl_hv_store_flags(pTHX_ HV *hv, const char *key, I32 klen, SV *val,
276                  register U32 hash, int flags)
277 {
278     HE * const hek = hv_fetch_common (hv, NULL, key, klen, flags,
279                                (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
280     return hek ? &HeVAL(hek) : NULL;
281 }
282
283 /*
284 =for apidoc hv_store_ent
285
286 Stores C<val> in a hash.  The hash key is specified as C<key>.  The C<hash>
287 parameter is the precomputed hash value; if it is zero then Perl will
288 compute it.  The return value is the new hash entry so created.  It will be
289 NULL if the operation failed or if the value did not need to be actually
290 stored within the hash (as in the case of tied hashes).  Otherwise the
291 contents of the return value can be accessed using the C<He?> macros
292 described here.  Note that the caller is responsible for suitably
293 incrementing the reference count of C<val> before the call, and
294 decrementing it if the function returned NULL.  Effectively a successful
295 hv_store_ent takes ownership of one reference to C<val>.  This is
296 usually what you want; a newly created SV has a reference count of one, so
297 if all your code does is create SVs then store them in a hash, hv_store
298 will own the only reference to the new SV, and your code doesn't need to do
299 anything further to tidy up.  Note that hv_store_ent only reads the C<key>;
300 unlike C<val> it does not take ownership of it, so maintaining the correct
301 reference count on C<key> is entirely the caller's responsibility.  hv_store
302 is not implemented as a call to hv_store_ent, and does not create a temporary
303 SV for the key, so if your key data is not already in SV form then use
304 hv_store in preference to hv_store_ent.
305
306 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
307 information on how to use this function on tied hashes.
308
309 =cut
310 */
311
312 /* XXX This looks like an ideal candidate to inline */
313 HE *
314 Perl_hv_store_ent(pTHX_ HV *hv, SV *keysv, SV *val, U32 hash)
315 {
316   return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISSTORE, val, hash);
317 }
318
319 /*
320 =for apidoc hv_exists
321
322 Returns a boolean indicating whether the specified hash key exists.  The
323 C<klen> is the length of the key.
324
325 =cut
326 */
327
328 bool
329 Perl_hv_exists(pTHX_ HV *hv, const char *key, I32 klen_i32)
330 {
331     STRLEN klen;
332     int flags;
333
334     if (klen_i32 < 0) {
335         klen = -klen_i32;
336         flags = HVhek_UTF8;
337     } else {
338         klen = klen_i32;
339         flags = 0;
340     }
341     return hv_fetch_common(hv, NULL, key, klen, flags, HV_FETCH_ISEXISTS, 0, 0)
342         ? TRUE : FALSE;
343 }
344
345 /*
346 =for apidoc hv_fetch
347
348 Returns the SV which corresponds to the specified key in the hash.  The
349 C<klen> is the length of the key.  If C<lval> is set then the fetch will be
350 part of a store.  Check that the return value is non-null before
351 dereferencing it to an C<SV*>.
352
353 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
354 information on how to use this function on tied hashes.
355
356 =cut
357 */
358
359 SV**
360 Perl_hv_fetch(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 lval)
361 {
362     HE *hek;
363     STRLEN klen;
364     int flags;
365
366     if (klen_i32 < 0) {
367         klen = -klen_i32;
368         flags = HVhek_UTF8;
369     } else {
370         klen = klen_i32;
371         flags = 0;
372     }
373     hek = hv_fetch_common (hv, NULL, key, klen, flags,
374                            lval ? (HV_FETCH_JUST_SV | HV_FETCH_LVALUE) : HV_FETCH_JUST_SV,
375                            NULL, 0);
376     return hek ? &HeVAL(hek) : NULL;
377 }
378
379 /*
380 =for apidoc hv_exists_ent
381
382 Returns a boolean indicating whether the specified hash key exists. C<hash>
383 can be a valid precomputed hash value, or 0 to ask for it to be
384 computed.
385
386 =cut
387 */
388
389 /* XXX This looks like an ideal candidate to inline */
390 bool
391 Perl_hv_exists_ent(pTHX_ HV *hv, SV *keysv, U32 hash)
392 {
393     return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISEXISTS, 0, hash)
394         ? TRUE : FALSE;
395 }
396
397 /* returns an HE * structure with the all fields set */
398 /* note that hent_val will be a mortal sv for MAGICAL hashes */
399 /*
400 =for apidoc hv_fetch_ent
401
402 Returns the hash entry which corresponds to the specified key in the hash.
403 C<hash> must be a valid precomputed hash number for the given C<key>, or 0
404 if you want the function to compute it.  IF C<lval> is set then the fetch
405 will be part of a store.  Make sure the return value is non-null before
406 accessing it.  The return value when C<tb> is a tied hash is a pointer to a
407 static location, so be sure to make a copy of the structure if you need to
408 store it somewhere.
409
410 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
411 information on how to use this function on tied hashes.
412
413 =cut
414 */
415
416 HE *
417 Perl_hv_fetch_ent(pTHX_ HV *hv, SV *keysv, I32 lval, register U32 hash)
418 {
419     return hv_fetch_common(hv, keysv, NULL, 0, 0, 
420                            (lval ? HV_FETCH_LVALUE : 0), NULL, hash);
421 }
422
423 STATIC HE *
424 S_hv_fetch_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
425                   int flags, int action, SV *val, register U32 hash)
426 {
427     dVAR;
428     XPVHV* xhv;
429     HE *entry;
430     HE **oentry;
431     SV *sv;
432     bool is_utf8;
433     int masked_flags;
434
435     if (!hv)
436         return NULL;
437
438     if (keysv) {
439         if (flags & HVhek_FREEKEY)
440             Safefree(key);
441         key = SvPV_const(keysv, klen);
442         flags = 0;
443         is_utf8 = (SvUTF8(keysv) != 0);
444     } else {
445         is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
446     }
447
448     xhv = (XPVHV*)SvANY(hv);
449     if (SvMAGICAL(hv)) {
450         if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS))) {
451             if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
452                 sv = sv_newmortal();
453
454                 /* XXX should be able to skimp on the HE/HEK here when
455                    HV_FETCH_JUST_SV is true.  */
456
457                 if (!keysv) {
458                     keysv = newSVpvn(key, klen);
459                     if (is_utf8) {
460                         SvUTF8_on(keysv);
461                     }
462                 } else {
463                     keysv = newSVsv(keysv);
464                 }
465                 mg_copy((SV*)hv, sv, (char *)keysv, HEf_SVKEY);
466
467                 /* grab a fake HE/HEK pair from the pool or make a new one */
468                 entry = PL_hv_fetch_ent_mh;
469                 if (entry)
470                     PL_hv_fetch_ent_mh = HeNEXT(entry);
471                 else {
472                     char *k;
473                     entry = new_HE();
474                     Newx(k, HEK_BASESIZE + sizeof(SV*), char);
475                     HeKEY_hek(entry) = (HEK*)k;
476                 }
477                 HeNEXT(entry) = NULL;
478                 HeSVKEY_set(entry, keysv);
479                 HeVAL(entry) = sv;
480                 sv_upgrade(sv, SVt_PVLV);
481                 LvTYPE(sv) = 'T';
482                  /* so we can free entry when freeing sv */
483                 LvTARG(sv) = (SV*)entry;
484
485                 /* XXX remove at some point? */
486                 if (flags & HVhek_FREEKEY)
487                     Safefree(key);
488
489                 return entry;
490             }
491 #ifdef ENV_IS_CASELESS
492             else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
493                 U32 i;
494                 for (i = 0; i < klen; ++i)
495                     if (isLOWER(key[i])) {
496                         /* Would be nice if we had a routine to do the
497                            copy and upercase in a single pass through.  */
498                         const char * const nkey = strupr(savepvn(key,klen));
499                         /* Note that this fetch is for nkey (the uppercased
500                            key) whereas the store is for key (the original)  */
501                         entry = hv_fetch_common(hv, NULL, nkey, klen,
502                                                 HVhek_FREEKEY, /* free nkey */
503                                                 0 /* non-LVAL fetch */,
504                                                 NULL /* no value */,
505                                                 0 /* compute hash */);
506                         if (!entry && (action & HV_FETCH_LVALUE)) {
507                             /* This call will free key if necessary.
508                                Do it this way to encourage compiler to tail
509                                call optimise.  */
510                             entry = hv_fetch_common(hv, keysv, key, klen,
511                                                     flags, HV_FETCH_ISSTORE,
512                                                     newSV(0), hash);
513                         } else {
514                             if (flags & HVhek_FREEKEY)
515                                 Safefree(key);
516                         }
517                         return entry;
518                     }
519             }
520 #endif
521         } /* ISFETCH */
522         else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
523             if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
524                 /* I don't understand why hv_exists_ent has svret and sv,
525                    whereas hv_exists only had one.  */
526                 SV * const svret = sv_newmortal();
527                 sv = sv_newmortal();
528
529                 if (keysv || is_utf8) {
530                     if (!keysv) {
531                         keysv = newSVpvn(key, klen);
532                         SvUTF8_on(keysv);
533                     } else {
534                         keysv = newSVsv(keysv);
535                     }
536                     mg_copy((SV*)hv, sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
537                 } else {
538                     mg_copy((SV*)hv, sv, key, klen);
539                 }
540                 if (flags & HVhek_FREEKEY)
541                     Safefree(key);
542                 magic_existspack(svret, mg_find(sv, PERL_MAGIC_tiedelem));
543                 /* This cast somewhat evil, but I'm merely using NULL/
544                    not NULL to return the boolean exists.
545                    And I know hv is not NULL.  */
546                 return SvTRUE(svret) ? (HE *)hv : NULL;
547                 }
548 #ifdef ENV_IS_CASELESS
549             else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
550                 /* XXX This code isn't UTF8 clean.  */
551                 char * const keysave = (char * const)key;
552                 /* Will need to free this, so set FREEKEY flag.  */
553                 key = savepvn(key,klen);
554                 key = (const char*)strupr((char*)key);
555                 is_utf8 = FALSE;
556                 hash = 0;
557                 keysv = 0;
558
559                 if (flags & HVhek_FREEKEY) {
560                     Safefree(keysave);
561                 }
562                 flags |= HVhek_FREEKEY;
563             }
564 #endif
565         } /* ISEXISTS */
566         else if (action & HV_FETCH_ISSTORE) {
567             bool needs_copy;
568             bool needs_store;
569             hv_magic_check (hv, &needs_copy, &needs_store);
570             if (needs_copy) {
571                 const bool save_taint = PL_tainted;
572                 if (keysv || is_utf8) {
573                     if (!keysv) {
574                         keysv = newSVpvn(key, klen);
575                         SvUTF8_on(keysv);
576                     }
577                     if (PL_tainting)
578                         PL_tainted = SvTAINTED(keysv);
579                     keysv = sv_2mortal(newSVsv(keysv));
580                     mg_copy((SV*)hv, val, (char*)keysv, HEf_SVKEY);
581                 } else {
582                     mg_copy((SV*)hv, val, key, klen);
583                 }
584
585                 TAINT_IF(save_taint);
586                 if (!needs_store) {
587                     if (flags & HVhek_FREEKEY)
588                         Safefree(key);
589                     return NULL;
590                 }
591 #ifdef ENV_IS_CASELESS
592                 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
593                     /* XXX This code isn't UTF8 clean.  */
594                     const char *keysave = key;
595                     /* Will need to free this, so set FREEKEY flag.  */
596                     key = savepvn(key,klen);
597                     key = (const char*)strupr((char*)key);
598                     is_utf8 = FALSE;
599                     hash = 0;
600                     keysv = 0;
601
602                     if (flags & HVhek_FREEKEY) {
603                         Safefree(keysave);
604                     }
605                     flags |= HVhek_FREEKEY;
606                 }
607 #endif
608             }
609         } /* ISSTORE */
610     } /* SvMAGICAL */
611
612     if (!HvARRAY(hv)) {
613         if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
614 #ifdef DYNAMIC_ENV_FETCH  /* if it's an %ENV lookup, we may get it on the fly */
615                  || (SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
616 #endif
617                                                                   ) {
618             char *array;
619             Newxz(array,
620                  PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
621                  char);
622             HvARRAY(hv) = (HE**)array;
623         }
624 #ifdef DYNAMIC_ENV_FETCH
625         else if (action & HV_FETCH_ISEXISTS) {
626             /* for an %ENV exists, if we do an insert it's by a recursive
627                store call, so avoid creating HvARRAY(hv) right now.  */
628         }
629 #endif
630         else {
631             /* XXX remove at some point? */
632             if (flags & HVhek_FREEKEY)
633                 Safefree(key);
634
635             return 0;
636         }
637     }
638
639     if (is_utf8) {
640         char * const keysave = (char *)key;
641         key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
642         if (is_utf8)
643             flags |= HVhek_UTF8;
644         else
645             flags &= ~HVhek_UTF8;
646         if (key != keysave) {
647             if (flags & HVhek_FREEKEY)
648                 Safefree(keysave);
649             flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
650         }
651     }
652
653     if (HvREHASH(hv)) {
654         PERL_HASH_INTERNAL(hash, key, klen);
655         /* We don't have a pointer to the hv, so we have to replicate the
656            flag into every HEK, so that hv_iterkeysv can see it.  */
657         /* And yes, you do need this even though you are not "storing" because
658            you can flip the flags below if doing an lval lookup.  (And that
659            was put in to give the semantics Andreas was expecting.)  */
660         flags |= HVhek_REHASH;
661     } else if (!hash) {
662         if (keysv && (SvIsCOW_shared_hash(keysv))) {
663             hash = SvSHARED_HASH(keysv);
664         } else {
665             PERL_HASH(hash, key, klen);
666         }
667     }
668
669     masked_flags = (flags & HVhek_MASK);
670
671 #ifdef DYNAMIC_ENV_FETCH
672     if (!HvARRAY(hv)) entry = NULL;
673     else
674 #endif
675     {
676         entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
677     }
678     for (; entry; entry = HeNEXT(entry)) {
679         if (HeHASH(entry) != hash)              /* strings can't be equal */
680             continue;
681         if (HeKLEN(entry) != (I32)klen)
682             continue;
683         if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen))        /* is this it? */
684             continue;
685         if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
686             continue;
687
688         if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
689             if (HeKFLAGS(entry) != masked_flags) {
690                 /* We match if HVhek_UTF8 bit in our flags and hash key's
691                    match.  But if entry was set previously with HVhek_WASUTF8
692                    and key now doesn't (or vice versa) then we should change
693                    the key's flag, as this is assignment.  */
694                 if (HvSHAREKEYS(hv)) {
695                     /* Need to swap the key we have for a key with the flags we
696                        need. As keys are shared we can't just write to the
697                        flag, so we share the new one, unshare the old one.  */
698                     HEK * const new_hek = share_hek_flags(key, klen, hash,
699                                                    masked_flags);
700                     unshare_hek (HeKEY_hek(entry));
701                     HeKEY_hek(entry) = new_hek;
702                 }
703                 else if (hv == PL_strtab) {
704                     /* PL_strtab is usually the only hash without HvSHAREKEYS,
705                        so putting this test here is cheap  */
706                     if (flags & HVhek_FREEKEY)
707                         Safefree(key);
708                     Perl_croak(aTHX_ S_strtab_error,
709                                action & HV_FETCH_LVALUE ? "fetch" : "store");
710                 }
711                 else
712                     HeKFLAGS(entry) = masked_flags;
713                 if (masked_flags & HVhek_ENABLEHVKFLAGS)
714                     HvHASKFLAGS_on(hv);
715             }
716             if (HeVAL(entry) == &PL_sv_placeholder) {
717                 /* yes, can store into placeholder slot */
718                 if (action & HV_FETCH_LVALUE) {
719                     if (SvMAGICAL(hv)) {
720                         /* This preserves behaviour with the old hv_fetch
721                            implementation which at this point would bail out
722                            with a break; (at "if we find a placeholder, we
723                            pretend we haven't found anything")
724
725                            That break mean that if a placeholder were found, it
726                            caused a call into hv_store, which in turn would
727                            check magic, and if there is no magic end up pretty
728                            much back at this point (in hv_store's code).  */
729                         break;
730                     }
731                     /* LVAL fetch which actaully needs a store.  */
732                     val = newSV(0);
733                     HvPLACEHOLDERS(hv)--;
734                 } else {
735                     /* store */
736                     if (val != &PL_sv_placeholder)
737                         HvPLACEHOLDERS(hv)--;
738                 }
739                 HeVAL(entry) = val;
740             } else if (action & HV_FETCH_ISSTORE) {
741                 SvREFCNT_dec(HeVAL(entry));
742                 HeVAL(entry) = val;
743             }
744         } else if (HeVAL(entry) == &PL_sv_placeholder) {
745             /* if we find a placeholder, we pretend we haven't found
746                anything */
747             break;
748         }
749         if (flags & HVhek_FREEKEY)
750             Safefree(key);
751         return entry;
752     }
753 #ifdef DYNAMIC_ENV_FETCH  /* %ENV lookup?  If so, try to fetch the value now */
754     if (!(action & HV_FETCH_ISSTORE) 
755         && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
756         unsigned long len;
757         const char * const env = PerlEnv_ENVgetenv_len(key,&len);
758         if (env) {
759             sv = newSVpvn(env,len);
760             SvTAINTED_on(sv);
761             return hv_fetch_common(hv,keysv,key,klen,flags,HV_FETCH_ISSTORE,sv,
762                                    hash);
763         }
764     }
765 #endif
766
767     if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
768         hv_notallowed(flags, key, klen,
769                         "Attempt to access disallowed key '%"SVf"' in"
770                         " a restricted hash");
771     }
772     if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
773         /* Not doing some form of store, so return failure.  */
774         if (flags & HVhek_FREEKEY)
775             Safefree(key);
776         return 0;
777     }
778     if (action & HV_FETCH_LVALUE) {
779         val = newSV(0);
780         if (SvMAGICAL(hv)) {
781             /* At this point the old hv_fetch code would call to hv_store,
782                which in turn might do some tied magic. So we need to make that
783                magic check happen.  */
784             /* gonna assign to this, so it better be there */
785             return hv_fetch_common(hv, keysv, key, klen, flags,
786                                    HV_FETCH_ISSTORE, val, hash);
787             /* XXX Surely that could leak if the fetch-was-store fails?
788                Just like the hv_fetch.  */
789         }
790     }
791
792     /* Welcome to hv_store...  */
793
794     if (!HvARRAY(hv)) {
795         /* Not sure if we can get here.  I think the only case of oentry being
796            NULL is for %ENV with dynamic env fetch.  But that should disappear
797            with magic in the previous code.  */
798         char *array;
799         Newxz(array,
800              PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
801              char);
802         HvARRAY(hv) = (HE**)array;
803     }
804
805     oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
806
807     entry = new_HE();
808     /* share_hek_flags will do the free for us.  This might be considered
809        bad API design.  */
810     if (HvSHAREKEYS(hv))
811         HeKEY_hek(entry) = share_hek_flags(key, klen, hash, flags);
812     else if (hv == PL_strtab) {
813         /* PL_strtab is usually the only hash without HvSHAREKEYS, so putting
814            this test here is cheap  */
815         if (flags & HVhek_FREEKEY)
816             Safefree(key);
817         Perl_croak(aTHX_ S_strtab_error,
818                    action & HV_FETCH_LVALUE ? "fetch" : "store");
819     }
820     else                                       /* gotta do the real thing */
821         HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
822     HeVAL(entry) = val;
823     HeNEXT(entry) = *oentry;
824     *oentry = entry;
825
826     if (val == &PL_sv_placeholder)
827         HvPLACEHOLDERS(hv)++;
828     if (masked_flags & HVhek_ENABLEHVKFLAGS)
829         HvHASKFLAGS_on(hv);
830
831     {
832         const HE *counter = HeNEXT(entry);
833
834         xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
835         if (!counter) {                         /* initial entry? */
836             xhv->xhv_fill++; /* HvFILL(hv)++ */
837         } else if (xhv->xhv_keys > (IV)xhv->xhv_max) {
838             hsplit(hv);
839         } else if(!HvREHASH(hv)) {
840             U32 n_links = 1;
841
842             while ((counter = HeNEXT(counter)))
843                 n_links++;
844
845             if (n_links > HV_MAX_LENGTH_BEFORE_SPLIT) {
846                 /* Use only the old HvKEYS(hv) > HvMAX(hv) condition to limit
847                    bucket splits on a rehashed hash, as we're not going to
848                    split it again, and if someone is lucky (evil) enough to
849                    get all the keys in one list they could exhaust our memory
850                    as we repeatedly double the number of buckets on every
851                    entry. Linear search feels a less worse thing to do.  */
852                 hsplit(hv);
853             }
854         }
855     }
856
857     return entry;
858 }
859
860 STATIC void
861 S_hv_magic_check(HV *hv, bool *needs_copy, bool *needs_store)
862 {
863     const MAGIC *mg = SvMAGIC(hv);
864     *needs_copy = FALSE;
865     *needs_store = TRUE;
866     while (mg) {
867         if (isUPPER(mg->mg_type)) {
868             *needs_copy = TRUE;
869             if (mg->mg_type == PERL_MAGIC_tied) {
870                 *needs_store = FALSE;
871                 return; /* We've set all there is to set. */
872             }
873         }
874         mg = mg->mg_moremagic;
875     }
876 }
877
878 /*
879 =for apidoc hv_scalar
880
881 Evaluates the hash in scalar context and returns the result. Handles magic when the hash is tied.
882
883 =cut
884 */
885
886 SV *
887 Perl_hv_scalar(pTHX_ HV *hv)
888 {
889     SV *sv;
890
891     if (SvRMAGICAL(hv)) {
892         MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_tied);
893         if (mg)
894             return magic_scalarpack(hv, mg);
895     }
896
897     sv = sv_newmortal();
898     if (HvFILL((HV*)hv)) 
899         Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
900                 (long)HvFILL(hv), (long)HvMAX(hv) + 1);
901     else
902         sv_setiv(sv, 0);
903     
904     return sv;
905 }
906
907 /*
908 =for apidoc hv_delete
909
910 Deletes a key/value pair in the hash.  The value SV is removed from the
911 hash and returned to the caller.  The C<klen> is the length of the key.
912 The C<flags> value will normally be zero; if set to G_DISCARD then NULL
913 will be returned.
914
915 =cut
916 */
917
918 SV *
919 Perl_hv_delete(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 flags)
920 {
921     STRLEN klen;
922     int k_flags;
923
924     if (klen_i32 < 0) {
925         klen = -klen_i32;
926         k_flags = HVhek_UTF8;
927     } else {
928         klen = klen_i32;
929         k_flags = 0;
930     }
931     return hv_delete_common(hv, NULL, key, klen, k_flags, flags, 0);
932 }
933
934 /*
935 =for apidoc hv_delete_ent
936
937 Deletes a key/value pair in the hash.  The value SV is removed from the
938 hash and returned to the caller.  The C<flags> value will normally be zero;
939 if set to G_DISCARD then NULL will be returned.  C<hash> can be a valid
940 precomputed hash value, or 0 to ask for it to be computed.
941
942 =cut
943 */
944
945 /* XXX This looks like an ideal candidate to inline */
946 SV *
947 Perl_hv_delete_ent(pTHX_ HV *hv, SV *keysv, I32 flags, U32 hash)
948 {
949     return hv_delete_common(hv, keysv, NULL, 0, 0, flags, hash);
950 }
951
952 STATIC SV *
953 S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
954                    int k_flags, I32 d_flags, U32 hash)
955 {
956     dVAR;
957     register XPVHV* xhv;
958     register HE *entry;
959     register HE **oentry;
960     HE *const *first_entry;
961     bool is_utf8;
962     int masked_flags;
963
964     if (!hv)
965         return NULL;
966
967     if (keysv) {
968         if (k_flags & HVhek_FREEKEY)
969             Safefree(key);
970         key = SvPV_const(keysv, klen);
971         k_flags = 0;
972         is_utf8 = (SvUTF8(keysv) != 0);
973     } else {
974         is_utf8 = ((k_flags & HVhek_UTF8) ? TRUE : FALSE);
975     }
976
977     if (SvRMAGICAL(hv)) {
978         bool needs_copy;
979         bool needs_store;
980         hv_magic_check (hv, &needs_copy, &needs_store);
981
982         if (needs_copy) {
983             SV *sv;
984             entry = hv_fetch_common(hv, keysv, key, klen,
985                                     k_flags & ~HVhek_FREEKEY, HV_FETCH_LVALUE,
986                                     NULL, hash);
987             sv = entry ? HeVAL(entry) : NULL;
988             if (sv) {
989                 if (SvMAGICAL(sv)) {
990                     mg_clear(sv);
991                 }
992                 if (!needs_store) {
993                     if (mg_find(sv, PERL_MAGIC_tiedelem)) {
994                         /* No longer an element */
995                         sv_unmagic(sv, PERL_MAGIC_tiedelem);
996                         return sv;
997                     }           
998                     return NULL;                /* element cannot be deleted */
999                 }
1000 #ifdef ENV_IS_CASELESS
1001                 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
1002                     /* XXX This code isn't UTF8 clean.  */
1003                     keysv = sv_2mortal(newSVpvn(key,klen));
1004                     if (k_flags & HVhek_FREEKEY) {
1005                         Safefree(key);
1006                     }
1007                     key = strupr(SvPVX(keysv));
1008                     is_utf8 = 0;
1009                     k_flags = 0;
1010                     hash = 0;
1011                 }
1012 #endif
1013             }
1014         }
1015     }
1016     xhv = (XPVHV*)SvANY(hv);
1017     if (!HvARRAY(hv))
1018         return NULL;
1019
1020     if (is_utf8) {
1021         const char * const keysave = key;
1022         key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
1023
1024         if (is_utf8)
1025             k_flags |= HVhek_UTF8;
1026         else
1027             k_flags &= ~HVhek_UTF8;
1028         if (key != keysave) {
1029             if (k_flags & HVhek_FREEKEY) {
1030                 /* This shouldn't happen if our caller does what we expect,
1031                    but strictly the API allows it.  */
1032                 Safefree(keysave);
1033             }
1034             k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
1035         }
1036         HvHASKFLAGS_on((SV*)hv);
1037     }
1038
1039     if (HvREHASH(hv)) {
1040         PERL_HASH_INTERNAL(hash, key, klen);
1041     } else if (!hash) {
1042         if (keysv && (SvIsCOW_shared_hash(keysv))) {
1043             hash = SvSHARED_HASH(keysv);
1044         } else {
1045             PERL_HASH(hash, key, klen);
1046         }
1047     }
1048
1049     masked_flags = (k_flags & HVhek_MASK);
1050
1051     first_entry = oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
1052     entry = *oentry;
1053     for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
1054         SV *sv;
1055         if (HeHASH(entry) != hash)              /* strings can't be equal */
1056             continue;
1057         if (HeKLEN(entry) != (I32)klen)
1058             continue;
1059         if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen))        /* is this it? */
1060             continue;
1061         if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
1062             continue;
1063
1064         if (hv == PL_strtab) {
1065             if (k_flags & HVhek_FREEKEY)
1066                 Safefree(key);
1067             Perl_croak(aTHX_ S_strtab_error, "delete");
1068         }
1069
1070         /* if placeholder is here, it's already been deleted.... */
1071         if (HeVAL(entry) == &PL_sv_placeholder) {
1072             if (k_flags & HVhek_FREEKEY)
1073                 Safefree(key);
1074             return NULL;
1075         }
1076         if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1077             hv_notallowed(k_flags, key, klen,
1078                             "Attempt to delete readonly key '%"SVf"' from"
1079                             " a restricted hash");
1080         }
1081         if (k_flags & HVhek_FREEKEY)
1082             Safefree(key);
1083
1084         if (d_flags & G_DISCARD)
1085             sv = NULL;
1086         else {
1087             sv = sv_2mortal(HeVAL(entry));
1088             HeVAL(entry) = &PL_sv_placeholder;
1089         }
1090
1091         /*
1092          * If a restricted hash, rather than really deleting the entry, put
1093          * a placeholder there. This marks the key as being "approved", so
1094          * we can still access via not-really-existing key without raising
1095          * an error.
1096          */
1097         if (SvREADONLY(hv)) {
1098             SvREFCNT_dec(HeVAL(entry));
1099             HeVAL(entry) = &PL_sv_placeholder;
1100             /* We'll be saving this slot, so the number of allocated keys
1101              * doesn't go down, but the number placeholders goes up */
1102             HvPLACEHOLDERS(hv)++;
1103         } else {
1104             *oentry = HeNEXT(entry);
1105             if(!*first_entry) {
1106                 xhv->xhv_fill--; /* HvFILL(hv)-- */
1107             }
1108             if (SvOOK(hv) && entry == HvAUX(hv)->xhv_eiter /* HvEITER(hv) */)
1109                 HvLAZYDEL_on(hv);
1110             else
1111                 hv_free_ent(hv, entry);
1112             xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
1113             if (xhv->xhv_keys == 0)
1114                 HvHASKFLAGS_off(hv);
1115         }
1116         return sv;
1117     }
1118     if (SvREADONLY(hv)) {
1119         hv_notallowed(k_flags, key, klen,
1120                         "Attempt to delete disallowed key '%"SVf"' from"
1121                         " a restricted hash");
1122     }
1123
1124     if (k_flags & HVhek_FREEKEY)
1125         Safefree(key);
1126     return NULL;
1127 }
1128
1129 STATIC void
1130 S_hsplit(pTHX_ HV *hv)
1131 {
1132     dVAR;
1133     register XPVHV* xhv = (XPVHV*)SvANY(hv);
1134     const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1135     register I32 newsize = oldsize * 2;
1136     register I32 i;
1137     char *a = (char*) HvARRAY(hv);
1138     register HE **aep;
1139     register HE **oentry;
1140     int longest_chain = 0;
1141     int was_shared;
1142
1143     /*PerlIO_printf(PerlIO_stderr(), "hsplit called for %p which had %d\n",
1144       hv, (int) oldsize);*/
1145
1146     if (HvPLACEHOLDERS_get(hv) && !SvREADONLY(hv)) {
1147       /* Can make this clear any placeholders first for non-restricted hashes,
1148          even though Storable rebuilds restricted hashes by putting in all the
1149          placeholders (first) before turning on the readonly flag, because
1150          Storable always pre-splits the hash.  */
1151       hv_clear_placeholders(hv);
1152     }
1153                
1154     PL_nomemok = TRUE;
1155 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1156     Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1157           + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1158     if (!a) {
1159       PL_nomemok = FALSE;
1160       return;
1161     }
1162     if (SvOOK(hv)) {
1163         Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1164     }
1165 #else
1166     Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1167         + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1168     if (!a) {
1169       PL_nomemok = FALSE;
1170       return;
1171     }
1172     Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1173     if (SvOOK(hv)) {
1174         Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1175     }
1176     if (oldsize >= 64) {
1177         offer_nice_chunk(HvARRAY(hv),
1178                          PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
1179                          + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
1180     }
1181     else
1182         Safefree(HvARRAY(hv));
1183 #endif
1184
1185     PL_nomemok = FALSE;
1186     Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char);     /* zero 2nd half*/
1187     xhv->xhv_max = --newsize;   /* HvMAX(hv) = --newsize */
1188     HvARRAY(hv) = (HE**) a;
1189     aep = (HE**)a;
1190
1191     for (i=0; i<oldsize; i++,aep++) {
1192         int left_length = 0;
1193         int right_length = 0;
1194         register HE *entry;
1195         register HE **bep;
1196
1197         if (!*aep)                              /* non-existent */
1198             continue;
1199         bep = aep+oldsize;
1200         for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1201             if ((HeHASH(entry) & newsize) != (U32)i) {
1202                 *oentry = HeNEXT(entry);
1203                 HeNEXT(entry) = *bep;
1204                 if (!*bep)
1205                     xhv->xhv_fill++; /* HvFILL(hv)++ */
1206                 *bep = entry;
1207                 right_length++;
1208                 continue;
1209             }
1210             else {
1211                 oentry = &HeNEXT(entry);
1212                 left_length++;
1213             }
1214         }
1215         if (!*aep)                              /* everything moved */
1216             xhv->xhv_fill--; /* HvFILL(hv)-- */
1217         /* I think we don't actually need to keep track of the longest length,
1218            merely flag if anything is too long. But for the moment while
1219            developing this code I'll track it.  */
1220         if (left_length > longest_chain)
1221             longest_chain = left_length;
1222         if (right_length > longest_chain)
1223             longest_chain = right_length;
1224     }
1225
1226
1227     /* Pick your policy for "hashing isn't working" here:  */
1228     if (longest_chain <= HV_MAX_LENGTH_BEFORE_SPLIT /* split worked?  */
1229         || HvREHASH(hv)) {
1230         return;
1231     }
1232
1233     if (hv == PL_strtab) {
1234         /* Urg. Someone is doing something nasty to the string table.
1235            Can't win.  */
1236         return;
1237     }
1238
1239     /* Awooga. Awooga. Pathological data.  */
1240     /*PerlIO_printf(PerlIO_stderr(), "%p %d of %d with %d/%d buckets\n", hv,
1241       longest_chain, HvTOTALKEYS(hv), HvFILL(hv),  1+HvMAX(hv));*/
1242
1243     ++newsize;
1244     Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1245          + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1246     if (SvOOK(hv)) {
1247         Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1248     }
1249
1250     was_shared = HvSHAREKEYS(hv);
1251
1252     xhv->xhv_fill = 0;
1253     HvSHAREKEYS_off(hv);
1254     HvREHASH_on(hv);
1255
1256     aep = HvARRAY(hv);
1257
1258     for (i=0; i<newsize; i++,aep++) {
1259         register HE *entry = *aep;
1260         while (entry) {
1261             /* We're going to trash this HE's next pointer when we chain it
1262                into the new hash below, so store where we go next.  */
1263             HE * const next = HeNEXT(entry);
1264             UV hash;
1265             HE **bep;
1266
1267             /* Rehash it */
1268             PERL_HASH_INTERNAL(hash, HeKEY(entry), HeKLEN(entry));
1269
1270             if (was_shared) {
1271                 /* Unshare it.  */
1272                 HEK * const new_hek
1273                     = save_hek_flags(HeKEY(entry), HeKLEN(entry),
1274                                      hash, HeKFLAGS(entry));
1275                 unshare_hek (HeKEY_hek(entry));
1276                 HeKEY_hek(entry) = new_hek;
1277             } else {
1278                 /* Not shared, so simply write the new hash in. */
1279                 HeHASH(entry) = hash;
1280             }
1281             /*PerlIO_printf(PerlIO_stderr(), "%d ", HeKFLAGS(entry));*/
1282             HEK_REHASH_on(HeKEY_hek(entry));
1283             /*PerlIO_printf(PerlIO_stderr(), "%d\n", HeKFLAGS(entry));*/
1284
1285             /* Copy oentry to the correct new chain.  */
1286             bep = ((HE**)a) + (hash & (I32) xhv->xhv_max);
1287             if (!*bep)
1288                     xhv->xhv_fill++; /* HvFILL(hv)++ */
1289             HeNEXT(entry) = *bep;
1290             *bep = entry;
1291
1292             entry = next;
1293         }
1294     }
1295     Safefree (HvARRAY(hv));
1296     HvARRAY(hv) = (HE **)a;
1297 }
1298
1299 void
1300 Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
1301 {
1302     dVAR;
1303     register XPVHV* xhv = (XPVHV*)SvANY(hv);
1304     const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1305     register I32 newsize;
1306     register I32 i;
1307     register char *a;
1308     register HE **aep;
1309     register HE *entry;
1310     register HE **oentry;
1311
1312     newsize = (I32) newmax;                     /* possible truncation here */
1313     if (newsize != newmax || newmax <= oldsize)
1314         return;
1315     while ((newsize & (1 + ~newsize)) != newsize) {
1316         newsize &= ~(newsize & (1 + ~newsize)); /* get proper power of 2 */
1317     }
1318     if (newsize < newmax)
1319         newsize *= 2;
1320     if (newsize < newmax)
1321         return;                                 /* overflow detection */
1322
1323     a = (char *) HvARRAY(hv);
1324     if (a) {
1325         PL_nomemok = TRUE;
1326 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1327         Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1328               + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1329         if (!a) {
1330           PL_nomemok = FALSE;
1331           return;
1332         }
1333         if (SvOOK(hv)) {
1334             Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1335         }
1336 #else
1337         Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1338             + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1339         if (!a) {
1340           PL_nomemok = FALSE;
1341           return;
1342         }
1343         Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1344         if (SvOOK(hv)) {
1345             Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1346         }
1347         if (oldsize >= 64) {
1348             offer_nice_chunk(HvARRAY(hv),
1349                              PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
1350                              + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
1351         }
1352         else
1353             Safefree(HvARRAY(hv));
1354 #endif
1355         PL_nomemok = FALSE;
1356         Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1357     }
1358     else {
1359         Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1360     }
1361     xhv->xhv_max = --newsize;   /* HvMAX(hv) = --newsize */
1362     HvARRAY(hv) = (HE **) a;
1363     if (!xhv->xhv_fill /* !HvFILL(hv) */)       /* skip rest if no entries */
1364         return;
1365
1366     aep = (HE**)a;
1367     for (i=0; i<oldsize; i++,aep++) {
1368         if (!*aep)                              /* non-existent */
1369             continue;
1370         for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1371             register I32 j = (HeHASH(entry) & newsize);
1372
1373             if (j != i) {
1374                 j -= i;
1375                 *oentry = HeNEXT(entry);
1376                 if (!(HeNEXT(entry) = aep[j]))
1377                     xhv->xhv_fill++; /* HvFILL(hv)++ */
1378                 aep[j] = entry;
1379                 continue;
1380             }
1381             else
1382                 oentry = &HeNEXT(entry);
1383         }
1384         if (!*aep)                              /* everything moved */
1385             xhv->xhv_fill--; /* HvFILL(hv)-- */
1386     }
1387 }
1388
1389 /*
1390 =for apidoc newHV
1391
1392 Creates a new HV.  The reference count is set to 1.
1393
1394 =cut
1395 */
1396
1397 HV *
1398 Perl_newHV(pTHX)
1399 {
1400     register XPVHV* xhv;
1401     HV * const hv = (HV*)newSV(0);
1402
1403     sv_upgrade((SV *)hv, SVt_PVHV);
1404     xhv = (XPVHV*)SvANY(hv);
1405     SvPOK_off(hv);
1406     SvNOK_off(hv);
1407 #ifndef NODEFAULT_SHAREKEYS
1408     HvSHAREKEYS_on(hv);         /* key-sharing on by default */
1409 #endif
1410
1411     xhv->xhv_max    = 7;        /* HvMAX(hv) = 7 (start with 8 buckets) */
1412     xhv->xhv_fill   = 0;        /* HvFILL(hv) = 0 */
1413     return hv;
1414 }
1415
1416 HV *
1417 Perl_newHVhv(pTHX_ HV *ohv)
1418 {
1419     HV * const hv = newHV();
1420     STRLEN hv_max, hv_fill;
1421
1422     if (!ohv || (hv_fill = HvFILL(ohv)) == 0)
1423         return hv;
1424     hv_max = HvMAX(ohv);
1425
1426     if (!SvMAGICAL((SV *)ohv)) {
1427         /* It's an ordinary hash, so copy it fast. AMS 20010804 */
1428         STRLEN i;
1429         const bool shared = !!HvSHAREKEYS(ohv);
1430         HE **ents, ** const oents = (HE **)HvARRAY(ohv);
1431         char *a;
1432         Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
1433         ents = (HE**)a;
1434
1435         /* In each bucket... */
1436         for (i = 0; i <= hv_max; i++) {
1437             HE *prev = NULL;
1438             HE *oent = oents[i];
1439
1440             if (!oent) {
1441                 ents[i] = NULL;
1442                 continue;
1443             }
1444
1445             /* Copy the linked list of entries. */
1446             for (; oent; oent = HeNEXT(oent)) {
1447                 const U32 hash   = HeHASH(oent);
1448                 const char * const key = HeKEY(oent);
1449                 const STRLEN len = HeKLEN(oent);
1450                 const int flags  = HeKFLAGS(oent);
1451                 HE * const ent   = new_HE();
1452
1453                 HeVAL(ent)     = newSVsv(HeVAL(oent));
1454                 HeKEY_hek(ent)
1455                     = shared ? share_hek_flags(key, len, hash, flags)
1456                              :  save_hek_flags(key, len, hash, flags);
1457                 if (prev)
1458                     HeNEXT(prev) = ent;
1459                 else
1460                     ents[i] = ent;
1461                 prev = ent;
1462                 HeNEXT(ent) = NULL;
1463             }
1464         }
1465
1466         HvMAX(hv)   = hv_max;
1467         HvFILL(hv)  = hv_fill;
1468         HvTOTALKEYS(hv)  = HvTOTALKEYS(ohv);
1469         HvARRAY(hv) = ents;
1470     } /* not magical */
1471     else {
1472         /* Iterate over ohv, copying keys and values one at a time. */
1473         HE *entry;
1474         const I32 riter = HvRITER_get(ohv);
1475         HE * const eiter = HvEITER_get(ohv);
1476
1477         /* Can we use fewer buckets? (hv_max is always 2^n-1) */
1478         while (hv_max && hv_max + 1 >= hv_fill * 2)
1479             hv_max = hv_max / 2;
1480         HvMAX(hv) = hv_max;
1481
1482         hv_iterinit(ohv);
1483         while ((entry = hv_iternext_flags(ohv, 0))) {
1484             hv_store_flags(hv, HeKEY(entry), HeKLEN(entry),
1485                            newSVsv(HeVAL(entry)), HeHASH(entry),
1486                            HeKFLAGS(entry));
1487         }
1488         HvRITER_set(ohv, riter);
1489         HvEITER_set(ohv, eiter);
1490     }
1491
1492     return hv;
1493 }
1494
1495 /* A rather specialised version of newHVhv for copying %^H, ensuring all the
1496    magic stays on it.  */
1497 HV *
1498 Perl_hv_copy_hints_hv(pTHX_ HV *const ohv)
1499 {
1500     HV * const hv = newHV();
1501     STRLEN hv_fill;
1502
1503     if (ohv && (hv_fill = HvFILL(ohv))) {
1504         STRLEN hv_max = HvMAX(ohv);
1505         HE *entry;
1506         const I32 riter = HvRITER_get(ohv);
1507         HE * const eiter = HvEITER_get(ohv);
1508
1509         while (hv_max && hv_max + 1 >= hv_fill * 2)
1510             hv_max = hv_max / 2;
1511         HvMAX(hv) = hv_max;
1512
1513         hv_iterinit(ohv);
1514         while ((entry = hv_iternext_flags(ohv, 0))) {
1515             SV *const sv = newSVsv(HeVAL(entry));
1516             sv_magic(sv, NULL, PERL_MAGIC_hintselem,
1517                      (char *)newSVhek (HeKEY_hek(entry)), HEf_SVKEY);
1518             hv_store_flags(hv, HeKEY(entry), HeKLEN(entry),
1519                            sv, HeHASH(entry), HeKFLAGS(entry));
1520         }
1521         HvRITER_set(ohv, riter);
1522         HvEITER_set(ohv, eiter);
1523     }
1524     hv_magic(hv, NULL, PERL_MAGIC_hints);
1525     return hv;
1526 }
1527
1528 void
1529 Perl_hv_free_ent(pTHX_ HV *hv, register HE *entry)
1530 {
1531     dVAR;
1532     SV *val;
1533
1534     if (!entry)
1535         return;
1536     val = HeVAL(entry);
1537     if (val && isGV(val) && GvCVu(val) && HvNAME_get(hv))
1538         PL_sub_generation++;    /* may be deletion of method from stash */
1539     SvREFCNT_dec(val);
1540     if (HeKLEN(entry) == HEf_SVKEY) {
1541         SvREFCNT_dec(HeKEY_sv(entry));
1542         Safefree(HeKEY_hek(entry));
1543     }
1544     else if (HvSHAREKEYS(hv))
1545         unshare_hek(HeKEY_hek(entry));
1546     else
1547         Safefree(HeKEY_hek(entry));
1548     del_HE(entry);
1549 }
1550
1551 void
1552 Perl_hv_delayfree_ent(pTHX_ HV *hv, register HE *entry)
1553 {
1554     dVAR;
1555     if (!entry)
1556         return;
1557     /* SvREFCNT_inc to counter the SvREFCNT_dec in hv_free_ent  */
1558     sv_2mortal(SvREFCNT_inc(HeVAL(entry)));     /* free between statements */
1559     if (HeKLEN(entry) == HEf_SVKEY) {
1560         sv_2mortal(SvREFCNT_inc(HeKEY_sv(entry)));
1561     }
1562     hv_free_ent(hv, entry);
1563 }
1564
1565 /*
1566 =for apidoc hv_clear
1567
1568 Clears a hash, making it empty.
1569
1570 =cut
1571 */
1572
1573 void
1574 Perl_hv_clear(pTHX_ HV *hv)
1575 {
1576     dVAR;
1577     register XPVHV* xhv;
1578     if (!hv)
1579         return;
1580
1581     DEBUG_A(Perl_hv_assert(aTHX_ hv));
1582
1583     xhv = (XPVHV*)SvANY(hv);
1584
1585     if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
1586         /* restricted hash: convert all keys to placeholders */
1587         STRLEN i;
1588         for (i = 0; i <= xhv->xhv_max; i++) {
1589             HE *entry = (HvARRAY(hv))[i];
1590             for (; entry; entry = HeNEXT(entry)) {
1591                 /* not already placeholder */
1592                 if (HeVAL(entry) != &PL_sv_placeholder) {
1593                     if (HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1594                         SV* const keysv = hv_iterkeysv(entry);
1595                         Perl_croak(aTHX_
1596                                    "Attempt to delete readonly key '%"SVf"' from a restricted hash",
1597                                    (void*)keysv);
1598                     }
1599                     SvREFCNT_dec(HeVAL(entry));
1600                     HeVAL(entry) = &PL_sv_placeholder;
1601                     HvPLACEHOLDERS(hv)++;
1602                 }
1603             }
1604         }
1605         goto reset;
1606     }
1607
1608     hfreeentries(hv);
1609     HvPLACEHOLDERS_set(hv, 0);
1610     if (HvARRAY(hv))
1611         Zero(HvARRAY(hv), xhv->xhv_max+1 /* HvMAX(hv)+1 */, HE*);
1612
1613     if (SvRMAGICAL(hv))
1614         mg_clear((SV*)hv);
1615
1616     HvHASKFLAGS_off(hv);
1617     HvREHASH_off(hv);
1618     reset:
1619     if (SvOOK(hv)) {
1620         HvEITER_set(hv, NULL);
1621     }
1622 }
1623
1624 /*
1625 =for apidoc hv_clear_placeholders
1626
1627 Clears any placeholders from a hash.  If a restricted hash has any of its keys
1628 marked as readonly and the key is subsequently deleted, the key is not actually
1629 deleted but is marked by assigning it a value of &PL_sv_placeholder.  This tags
1630 it so it will be ignored by future operations such as iterating over the hash,
1631 but will still allow the hash to have a value reassigned to the key at some
1632 future point.  This function clears any such placeholder keys from the hash.
1633 See Hash::Util::lock_keys() for an example of its use.
1634
1635 =cut
1636 */
1637
1638 void
1639 Perl_hv_clear_placeholders(pTHX_ HV *hv)
1640 {
1641     dVAR;
1642     const U32 items = (U32)HvPLACEHOLDERS_get(hv);
1643
1644     if (items)
1645         clear_placeholders(hv, items);
1646 }
1647
1648 static void
1649 S_clear_placeholders(pTHX_ HV *hv, U32 items)
1650 {
1651     dVAR;
1652     I32 i;
1653
1654     if (items == 0)
1655         return;
1656
1657     i = HvMAX(hv);
1658     do {
1659         /* Loop down the linked list heads  */
1660         bool first = TRUE;
1661         HE **oentry = &(HvARRAY(hv))[i];
1662         HE *entry;
1663
1664         while ((entry = *oentry)) {
1665             if (HeVAL(entry) == &PL_sv_placeholder) {
1666                 *oentry = HeNEXT(entry);
1667                 if (first && !*oentry)
1668                     HvFILL(hv)--; /* This linked list is now empty.  */
1669                 if (entry == HvEITER_get(hv))
1670                     HvLAZYDEL_on(hv);
1671                 else
1672                     hv_free_ent(hv, entry);
1673
1674                 if (--items == 0) {
1675                     /* Finished.  */
1676                     HvTOTALKEYS(hv) -= (IV)HvPLACEHOLDERS_get(hv);
1677                     if (HvKEYS(hv) == 0)
1678                         HvHASKFLAGS_off(hv);
1679                     HvPLACEHOLDERS_set(hv, 0);
1680                     return;
1681                 }
1682             } else {
1683                 oentry = &HeNEXT(entry);
1684                 first = FALSE;
1685             }
1686         }
1687     } while (--i >= 0);
1688     /* You can't get here, hence assertion should always fail.  */
1689     assert (items == 0);
1690     assert (0);
1691 }
1692
1693 STATIC void
1694 S_hfreeentries(pTHX_ HV *hv)
1695 {
1696     /* This is the array that we're going to restore  */
1697     HE **orig_array;
1698     HEK *name;
1699     int attempts = 100;
1700
1701     if (!HvARRAY(hv))
1702         return;
1703
1704     if (SvOOK(hv)) {
1705         /* If the hash is actually a symbol table with a name, look after the
1706            name.  */
1707         struct xpvhv_aux *iter = HvAUX(hv);
1708
1709         name = iter->xhv_name;
1710         iter->xhv_name = NULL;
1711     } else {
1712         name = NULL;
1713     }
1714
1715     orig_array = HvARRAY(hv);
1716     /* orig_array remains unchanged throughout the loop. If after freeing all
1717        the entries it turns out that one of the little blighters has triggered
1718        an action that has caused HvARRAY to be re-allocated, then we set
1719        array to the new HvARRAY, and try again.  */
1720
1721     while (1) {
1722         /* This is the one we're going to try to empty.  First time round
1723            it's the original array.  (Hopefully there will only be 1 time
1724            round) */
1725         HE ** const array = HvARRAY(hv);
1726         I32 i = HvMAX(hv);
1727
1728         /* Because we have taken xhv_name out, the only allocated pointer
1729            in the aux structure that might exist is the backreference array.
1730         */
1731
1732         if (SvOOK(hv)) {
1733             HE *entry;
1734             struct xpvhv_aux *iter = HvAUX(hv);
1735             /* If there are weak references to this HV, we need to avoid
1736                freeing them up here.  In particular we need to keep the AV
1737                visible as what we're deleting might well have weak references
1738                back to this HV, so the for loop below may well trigger
1739                the removal of backreferences from this array.  */
1740
1741             if (iter->xhv_backreferences) {
1742                 /* So donate them to regular backref magic to keep them safe.
1743                    The sv_magic will increase the reference count of the AV,
1744                    so we need to drop it first. */
1745                 SvREFCNT_dec(iter->xhv_backreferences);
1746                 if (AvFILLp(iter->xhv_backreferences) == -1) {
1747                     /* Turns out that the array is empty. Just free it.  */
1748                     SvREFCNT_dec(iter->xhv_backreferences);
1749
1750                 } else {
1751                     sv_magic((SV*)hv, (SV*)iter->xhv_backreferences,
1752                              PERL_MAGIC_backref, NULL, 0);
1753                 }
1754                 iter->xhv_backreferences = NULL;
1755             }
1756
1757             entry = iter->xhv_eiter; /* HvEITER(hv) */
1758             if (entry && HvLAZYDEL(hv)) {       /* was deleted earlier? */
1759                 HvLAZYDEL_off(hv);
1760                 hv_free_ent(hv, entry);
1761             }
1762             iter->xhv_riter = -1;       /* HvRITER(hv) = -1 */
1763             iter->xhv_eiter = NULL;     /* HvEITER(hv) = NULL */
1764
1765             /* There are now no allocated pointers in the aux structure.  */
1766
1767             SvFLAGS(hv) &= ~SVf_OOK; /* Goodbye, aux structure.  */
1768             /* What aux structure?  */
1769         }
1770
1771         /* make everyone else think the array is empty, so that the destructors
1772          * called for freed entries can't recusively mess with us */
1773         HvARRAY(hv) = NULL;
1774         HvFILL(hv) = 0;
1775         ((XPVHV*) SvANY(hv))->xhv_keys = 0;
1776
1777
1778         do {
1779             /* Loop down the linked list heads  */
1780             HE *entry = array[i];
1781
1782             while (entry) {
1783                 register HE * const oentry = entry;
1784                 entry = HeNEXT(entry);
1785                 hv_free_ent(hv, oentry);
1786             }
1787         } while (--i >= 0);
1788
1789         /* As there are no allocated pointers in the aux structure, it's now
1790            safe to free the array we just cleaned up, if it's not the one we're
1791            going to put back.  */
1792         if (array != orig_array) {
1793             Safefree(array);
1794         }
1795
1796         if (!HvARRAY(hv)) {
1797             /* Good. No-one added anything this time round.  */
1798             break;
1799         }
1800
1801         if (SvOOK(hv)) {
1802             /* Someone attempted to iterate or set the hash name while we had
1803                the array set to 0.  We'll catch backferences on the next time
1804                round the while loop.  */
1805             assert(HvARRAY(hv));
1806
1807             if (HvAUX(hv)->xhv_name) {
1808                 unshare_hek_or_pvn(HvAUX(hv)->xhv_name, 0, 0, 0);
1809             }
1810         }
1811
1812         if (--attempts == 0) {
1813             Perl_die(aTHX_ "panic: hfreeentries failed to free hash - something is repeatedly re-creating entries");
1814         }
1815     }
1816         
1817     HvARRAY(hv) = orig_array;
1818
1819     /* If the hash was actually a symbol table, put the name back.  */
1820     if (name) {
1821         /* We have restored the original array.  If name is non-NULL, then
1822            the original array had an aux structure at the end. So this is
1823            valid:  */
1824         SvFLAGS(hv) |= SVf_OOK;
1825         HvAUX(hv)->xhv_name = name;
1826     }
1827 }
1828
1829 /*
1830 =for apidoc hv_undef
1831
1832 Undefines the hash.
1833
1834 =cut
1835 */
1836
1837 void
1838 Perl_hv_undef(pTHX_ HV *hv)
1839 {
1840     dVAR;
1841     register XPVHV* xhv;
1842     const char *name;
1843
1844     if (!hv)
1845         return;
1846     DEBUG_A(Perl_hv_assert(aTHX_ hv));
1847     xhv = (XPVHV*)SvANY(hv);
1848     hfreeentries(hv);
1849     if ((name = HvNAME_get(hv))) {
1850         if(PL_stashcache)
1851             hv_delete(PL_stashcache, name, HvNAMELEN_get(hv), G_DISCARD);
1852         hv_name_set(hv, NULL, 0, 0);
1853     }
1854     SvFLAGS(hv) &= ~SVf_OOK;
1855     Safefree(HvARRAY(hv));
1856     xhv->xhv_max   = 7; /* HvMAX(hv) = 7 (it's a normal hash) */
1857     HvARRAY(hv) = 0;
1858     HvPLACEHOLDERS_set(hv, 0);
1859
1860     if (SvRMAGICAL(hv))
1861         mg_clear((SV*)hv);
1862 }
1863
1864 static struct xpvhv_aux*
1865 S_hv_auxinit(HV *hv) {
1866     struct xpvhv_aux *iter;
1867     char *array;
1868
1869     if (!HvARRAY(hv)) {
1870         Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1871             + sizeof(struct xpvhv_aux), char);
1872     } else {
1873         array = (char *) HvARRAY(hv);
1874         Renew(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1875               + sizeof(struct xpvhv_aux), char);
1876     }
1877     HvARRAY(hv) = (HE**) array;
1878     /* SvOOK_on(hv) attacks the IV flags.  */
1879     SvFLAGS(hv) |= SVf_OOK;
1880     iter = HvAUX(hv);
1881
1882     iter->xhv_riter = -1;       /* HvRITER(hv) = -1 */
1883     iter->xhv_eiter = NULL;     /* HvEITER(hv) = NULL */
1884     iter->xhv_name = 0;
1885     iter->xhv_backreferences = 0;
1886     return iter;
1887 }
1888
1889 /*
1890 =for apidoc hv_iterinit
1891
1892 Prepares a starting point to traverse a hash table.  Returns the number of
1893 keys in the hash (i.e. the same as C<HvKEYS(tb)>).  The return value is
1894 currently only meaningful for hashes without tie magic.
1895
1896 NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
1897 hash buckets that happen to be in use.  If you still need that esoteric
1898 value, you can get it through the macro C<HvFILL(tb)>.
1899
1900
1901 =cut
1902 */
1903
1904 I32
1905 Perl_hv_iterinit(pTHX_ HV *hv)
1906 {
1907     if (!hv)
1908         Perl_croak(aTHX_ "Bad hash");
1909
1910     if (SvOOK(hv)) {
1911         struct xpvhv_aux * const iter = HvAUX(hv);
1912         HE * const entry = iter->xhv_eiter; /* HvEITER(hv) */
1913         if (entry && HvLAZYDEL(hv)) {   /* was deleted earlier? */
1914             HvLAZYDEL_off(hv);
1915             hv_free_ent(hv, entry);
1916         }
1917         iter->xhv_riter = -1;   /* HvRITER(hv) = -1 */
1918         iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
1919     } else {
1920         hv_auxinit(hv);
1921     }
1922
1923     /* used to be xhv->xhv_fill before 5.004_65 */
1924     return HvTOTALKEYS(hv);
1925 }
1926
1927 I32 *
1928 Perl_hv_riter_p(pTHX_ HV *hv) {
1929     struct xpvhv_aux *iter;
1930
1931     if (!hv)
1932         Perl_croak(aTHX_ "Bad hash");
1933
1934     iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
1935     return &(iter->xhv_riter);
1936 }
1937
1938 HE **
1939 Perl_hv_eiter_p(pTHX_ HV *hv) {
1940     struct xpvhv_aux *iter;
1941
1942     if (!hv)
1943         Perl_croak(aTHX_ "Bad hash");
1944
1945     iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
1946     return &(iter->xhv_eiter);
1947 }
1948
1949 void
1950 Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
1951     struct xpvhv_aux *iter;
1952
1953     if (!hv)
1954         Perl_croak(aTHX_ "Bad hash");
1955
1956     if (SvOOK(hv)) {
1957         iter = HvAUX(hv);
1958     } else {
1959         if (riter == -1)
1960             return;
1961
1962         iter = hv_auxinit(hv);
1963     }
1964     iter->xhv_riter = riter;
1965 }
1966
1967 void
1968 Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
1969     struct xpvhv_aux *iter;
1970
1971     if (!hv)
1972         Perl_croak(aTHX_ "Bad hash");
1973
1974     if (SvOOK(hv)) {
1975         iter = HvAUX(hv);
1976     } else {
1977         /* 0 is the default so don't go malloc()ing a new structure just to
1978            hold 0.  */
1979         if (!eiter)
1980             return;
1981
1982         iter = hv_auxinit(hv);
1983     }
1984     iter->xhv_eiter = eiter;
1985 }
1986
1987 void
1988 Perl_hv_name_set(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
1989 {
1990     dVAR;
1991     struct xpvhv_aux *iter;
1992     U32 hash;
1993
1994     PERL_UNUSED_ARG(flags);
1995
1996     if (len > I32_MAX)
1997         Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
1998
1999     if (SvOOK(hv)) {
2000         iter = HvAUX(hv);
2001         if (iter->xhv_name) {
2002             unshare_hek_or_pvn(iter->xhv_name, 0, 0, 0);
2003         }
2004     } else {
2005         if (name == 0)
2006             return;
2007
2008         iter = hv_auxinit(hv);
2009     }
2010     PERL_HASH(hash, name, len);
2011     iter->xhv_name = name ? share_hek(name, len, hash) : 0;
2012 }
2013
2014 AV **
2015 Perl_hv_backreferences_p(pTHX_ HV *hv) {
2016     struct xpvhv_aux * const iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2017     PERL_UNUSED_CONTEXT;
2018     return &(iter->xhv_backreferences);
2019 }
2020
2021 void
2022 Perl_hv_kill_backrefs(pTHX_ HV *hv) {
2023     AV *av;
2024
2025     if (!SvOOK(hv))
2026         return;
2027
2028     av = HvAUX(hv)->xhv_backreferences;
2029
2030     if (av) {
2031         HvAUX(hv)->xhv_backreferences = 0;
2032         Perl_sv_kill_backrefs(aTHX_ (SV*) hv, av);
2033     }
2034 }
2035
2036 /*
2037 hv_iternext is implemented as a macro in hv.h
2038
2039 =for apidoc hv_iternext
2040
2041 Returns entries from a hash iterator.  See C<hv_iterinit>.
2042
2043 You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
2044 iterator currently points to, without losing your place or invalidating your
2045 iterator.  Note that in this case the current entry is deleted from the hash
2046 with your iterator holding the last reference to it.  Your iterator is flagged
2047 to free the entry on the next call to C<hv_iternext>, so you must not discard
2048 your iterator immediately else the entry will leak - call C<hv_iternext> to
2049 trigger the resource deallocation.
2050
2051 =for apidoc hv_iternext_flags
2052
2053 Returns entries from a hash iterator.  See C<hv_iterinit> and C<hv_iternext>.
2054 The C<flags> value will normally be zero; if HV_ITERNEXT_WANTPLACEHOLDERS is
2055 set the placeholders keys (for restricted hashes) will be returned in addition
2056 to normal keys. By default placeholders are automatically skipped over.
2057 Currently a placeholder is implemented with a value that is
2058 C<&Perl_sv_placeholder>. Note that the implementation of placeholders and
2059 restricted hashes may change, and the implementation currently is
2060 insufficiently abstracted for any change to be tidy.
2061
2062 =cut
2063 */
2064
2065 HE *
2066 Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
2067 {
2068     dVAR;
2069     register XPVHV* xhv;
2070     register HE *entry;
2071     HE *oldentry;
2072     MAGIC* mg;
2073     struct xpvhv_aux *iter;
2074
2075     if (!hv)
2076         Perl_croak(aTHX_ "Bad hash");
2077     xhv = (XPVHV*)SvANY(hv);
2078
2079     if (!SvOOK(hv)) {
2080         /* Too many things (well, pp_each at least) merrily assume that you can
2081            call iv_iternext without calling hv_iterinit, so we'll have to deal
2082            with it.  */
2083         hv_iterinit(hv);
2084     }
2085     iter = HvAUX(hv);
2086
2087     oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2088
2089     if ((mg = SvTIED_mg((SV*)hv, PERL_MAGIC_tied))) {
2090         SV * const key = sv_newmortal();
2091         if (entry) {
2092             sv_setsv(key, HeSVKEY_force(entry));
2093             SvREFCNT_dec(HeSVKEY(entry));       /* get rid of previous key */
2094         }
2095         else {
2096             char *k;
2097             HEK *hek;
2098
2099             /* one HE per MAGICAL hash */
2100             iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
2101             Zero(entry, 1, HE);
2102             Newxz(k, HEK_BASESIZE + sizeof(SV*), char);
2103             hek = (HEK*)k;
2104             HeKEY_hek(entry) = hek;
2105             HeKLEN(entry) = HEf_SVKEY;
2106         }
2107         magic_nextpack((SV*) hv,mg,key);
2108         if (SvOK(key)) {
2109             /* force key to stay around until next time */
2110             HeSVKEY_set(entry, SvREFCNT_inc_simple_NN(key));
2111             return entry;               /* beware, hent_val is not set */
2112         }
2113         if (HeVAL(entry))
2114             SvREFCNT_dec(HeVAL(entry));
2115         Safefree(HeKEY_hek(entry));
2116         del_HE(entry);
2117         iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
2118         return NULL;
2119     }
2120 #if defined(DYNAMIC_ENV_FETCH) && !defined(__riscos__)  /* set up %ENV for iteration */
2121     if (!entry && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
2122         prime_env_iter();
2123 #ifdef VMS
2124         /* The prime_env_iter() on VMS just loaded up new hash values
2125          * so the iteration count needs to be reset back to the beginning
2126          */
2127         hv_iterinit(hv);
2128         iter = HvAUX(hv);
2129         oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2130 #endif
2131     }
2132 #endif
2133
2134     /* hv_iterint now ensures this.  */
2135     assert (HvARRAY(hv));
2136
2137     /* At start of hash, entry is NULL.  */
2138     if (entry)
2139     {
2140         entry = HeNEXT(entry);
2141         if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2142             /*
2143              * Skip past any placeholders -- don't want to include them in
2144              * any iteration.
2145              */
2146             while (entry && HeVAL(entry) == &PL_sv_placeholder) {
2147                 entry = HeNEXT(entry);
2148             }
2149         }
2150     }
2151     while (!entry) {
2152         /* OK. Come to the end of the current list.  Grab the next one.  */
2153
2154         iter->xhv_riter++; /* HvRITER(hv)++ */
2155         if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
2156             /* There is no next one.  End of the hash.  */
2157             iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2158             break;
2159         }
2160         entry = (HvARRAY(hv))[iter->xhv_riter];
2161
2162         if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2163             /* If we have an entry, but it's a placeholder, don't count it.
2164                Try the next.  */
2165             while (entry && HeVAL(entry) == &PL_sv_placeholder)
2166                 entry = HeNEXT(entry);
2167         }
2168         /* Will loop again if this linked list starts NULL
2169            (for HV_ITERNEXT_WANTPLACEHOLDERS)
2170            or if we run through it and find only placeholders.  */
2171     }
2172
2173     if (oldentry && HvLAZYDEL(hv)) {            /* was deleted earlier? */
2174         HvLAZYDEL_off(hv);
2175         hv_free_ent(hv, oldentry);
2176     }
2177
2178     /*if (HvREHASH(hv) && entry && !HeKREHASH(entry))
2179       PerlIO_printf(PerlIO_stderr(), "Awooga %p %p\n", hv, entry);*/
2180
2181     iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
2182     return entry;
2183 }
2184
2185 /*
2186 =for apidoc hv_iterkey
2187
2188 Returns the key from the current position of the hash iterator.  See
2189 C<hv_iterinit>.
2190
2191 =cut
2192 */
2193
2194 char *
2195 Perl_hv_iterkey(pTHX_ register HE *entry, I32 *retlen)
2196 {
2197     if (HeKLEN(entry) == HEf_SVKEY) {
2198         STRLEN len;
2199         char * const p = SvPV(HeKEY_sv(entry), len);
2200         *retlen = len;
2201         return p;
2202     }
2203     else {
2204         *retlen = HeKLEN(entry);
2205         return HeKEY(entry);
2206     }
2207 }
2208
2209 /* unlike hv_iterval(), this always returns a mortal copy of the key */
2210 /*
2211 =for apidoc hv_iterkeysv
2212
2213 Returns the key as an C<SV*> from the current position of the hash
2214 iterator.  The return value will always be a mortal copy of the key.  Also
2215 see C<hv_iterinit>.
2216
2217 =cut
2218 */
2219
2220 SV *
2221 Perl_hv_iterkeysv(pTHX_ register HE *entry)
2222 {
2223     return sv_2mortal(newSVhek(HeKEY_hek(entry)));
2224 }
2225
2226 /*
2227 =for apidoc hv_iterval
2228
2229 Returns the value from the current position of the hash iterator.  See
2230 C<hv_iterkey>.
2231
2232 =cut
2233 */
2234
2235 SV *
2236 Perl_hv_iterval(pTHX_ HV *hv, register HE *entry)
2237 {
2238     if (SvRMAGICAL(hv)) {
2239         if (mg_find((SV*)hv, PERL_MAGIC_tied)) {
2240             SV* const sv = sv_newmortal();
2241             if (HeKLEN(entry) == HEf_SVKEY)
2242                 mg_copy((SV*)hv, sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
2243             else
2244                 mg_copy((SV*)hv, sv, HeKEY(entry), HeKLEN(entry));
2245             return sv;
2246         }
2247     }
2248     return HeVAL(entry);
2249 }
2250
2251 /*
2252 =for apidoc hv_iternextsv
2253
2254 Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2255 operation.
2256
2257 =cut
2258 */
2259
2260 SV *
2261 Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
2262 {
2263     HE * const he = hv_iternext_flags(hv, 0);
2264
2265     if (!he)
2266         return NULL;
2267     *key = hv_iterkey(he, retlen);
2268     return hv_iterval(hv, he);
2269 }
2270
2271 /*
2272
2273 Now a macro in hv.h
2274
2275 =for apidoc hv_magic
2276
2277 Adds magic to a hash.  See C<sv_magic>.
2278
2279 =cut
2280 */
2281
2282 /* possibly free a shared string if no one has access to it
2283  * len and hash must both be valid for str.
2284  */
2285 void
2286 Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
2287 {
2288     unshare_hek_or_pvn (NULL, str, len, hash);
2289 }
2290
2291
2292 void
2293 Perl_unshare_hek(pTHX_ HEK *hek)
2294 {
2295     unshare_hek_or_pvn(hek, NULL, 0, 0);
2296 }
2297
2298 /* possibly free a shared string if no one has access to it
2299    hek if non-NULL takes priority over the other 3, else str, len and hash
2300    are used.  If so, len and hash must both be valid for str.
2301  */
2302 STATIC void
2303 S_unshare_hek_or_pvn(pTHX_ const HEK *hek, const char *str, I32 len, U32 hash)
2304 {
2305     dVAR;
2306     register XPVHV* xhv;
2307     HE *entry;
2308     register HE **oentry;
2309     HE **first;
2310     bool is_utf8 = FALSE;
2311     int k_flags = 0;
2312     const char * const save = str;
2313     struct shared_he *he = NULL;
2314
2315     if (hek) {
2316         /* Find the shared he which is just before us in memory.  */
2317         he = (struct shared_he *)(((char *)hek)
2318                                   - STRUCT_OFFSET(struct shared_he,
2319                                                   shared_he_hek));
2320
2321         /* Assert that the caller passed us a genuine (or at least consistent)
2322            shared hek  */
2323         assert (he->shared_he_he.hent_hek == hek);
2324
2325         LOCK_STRTAB_MUTEX;
2326         if (he->shared_he_he.he_valu.hent_refcount - 1) {
2327             --he->shared_he_he.he_valu.hent_refcount;
2328             UNLOCK_STRTAB_MUTEX;
2329             return;
2330         }
2331         UNLOCK_STRTAB_MUTEX;
2332
2333         hash = HEK_HASH(hek);
2334     } else if (len < 0) {
2335         STRLEN tmplen = -len;
2336         is_utf8 = TRUE;
2337         /* See the note in hv_fetch(). --jhi */
2338         str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2339         len = tmplen;
2340         if (is_utf8)
2341             k_flags = HVhek_UTF8;
2342         if (str != save)
2343             k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2344     }
2345
2346     /* what follows was the moral equivalent of:
2347     if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
2348         if (--*Svp == NULL)
2349             hv_delete(PL_strtab, str, len, G_DISCARD, hash);
2350     } */
2351     xhv = (XPVHV*)SvANY(PL_strtab);
2352     /* assert(xhv_array != 0) */
2353     LOCK_STRTAB_MUTEX;
2354     first = oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2355     if (he) {
2356         const HE *const he_he = &(he->shared_he_he);
2357         for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2358             if (entry == he_he)
2359                 break;
2360         }
2361     } else {
2362         const int flags_masked = k_flags & HVhek_MASK;
2363         for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2364             if (HeHASH(entry) != hash)          /* strings can't be equal */
2365                 continue;
2366             if (HeKLEN(entry) != len)
2367                 continue;
2368             if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len))     /* is this it? */
2369                 continue;
2370             if (HeKFLAGS(entry) != flags_masked)
2371                 continue;
2372             break;
2373         }
2374     }
2375
2376     if (entry) {
2377         if (--entry->he_valu.hent_refcount == 0) {
2378             *oentry = HeNEXT(entry);
2379             if (!*first) {
2380                 /* There are now no entries in our slot.  */
2381                 xhv->xhv_fill--; /* HvFILL(hv)-- */
2382             }
2383             Safefree(entry);
2384             xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
2385         }
2386     }
2387
2388     UNLOCK_STRTAB_MUTEX;
2389     if (!entry && ckWARN_d(WARN_INTERNAL))
2390         Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
2391                     "Attempt to free non-existent shared string '%s'%s"
2392                     pTHX__FORMAT,
2393                     hek ? HEK_KEY(hek) : str,
2394                     ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
2395     if (k_flags & HVhek_FREEKEY)
2396         Safefree(str);
2397 }
2398
2399 /* get a (constant) string ptr from the global string table
2400  * string will get added if it is not already there.
2401  * len and hash must both be valid for str.
2402  */
2403 HEK *
2404 Perl_share_hek(pTHX_ const char *str, I32 len, register U32 hash)
2405 {
2406     bool is_utf8 = FALSE;
2407     int flags = 0;
2408     const char * const save = str;
2409
2410     if (len < 0) {
2411       STRLEN tmplen = -len;
2412       is_utf8 = TRUE;
2413       /* See the note in hv_fetch(). --jhi */
2414       str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2415       len = tmplen;
2416       /* If we were able to downgrade here, then than means that we were passed
2417          in a key which only had chars 0-255, but was utf8 encoded.  */
2418       if (is_utf8)
2419           flags = HVhek_UTF8;
2420       /* If we found we were able to downgrade the string to bytes, then
2421          we should flag that it needs upgrading on keys or each.  Also flag
2422          that we need share_hek_flags to free the string.  */
2423       if (str != save)
2424           flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2425     }
2426
2427     return share_hek_flags (str, len, hash, flags);
2428 }
2429
2430 STATIC HEK *
2431 S_share_hek_flags(pTHX_ const char *str, I32 len, register U32 hash, int flags)
2432 {
2433     dVAR;
2434     register HE *entry;
2435     const int flags_masked = flags & HVhek_MASK;
2436     const U32 hindex = hash & (I32) HvMAX(PL_strtab);
2437
2438     /* what follows is the moral equivalent of:
2439
2440     if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
2441         hv_store(PL_strtab, str, len, NULL, hash);
2442
2443         Can't rehash the shared string table, so not sure if it's worth
2444         counting the number of entries in the linked list
2445     */
2446     register XPVHV * const xhv = (XPVHV*)SvANY(PL_strtab);
2447     /* assert(xhv_array != 0) */
2448     LOCK_STRTAB_MUTEX;
2449     entry = (HvARRAY(PL_strtab))[hindex];
2450     for (;entry; entry = HeNEXT(entry)) {
2451         if (HeHASH(entry) != hash)              /* strings can't be equal */
2452             continue;
2453         if (HeKLEN(entry) != len)
2454             continue;
2455         if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2456             continue;
2457         if (HeKFLAGS(entry) != flags_masked)
2458             continue;
2459         break;
2460     }
2461
2462     if (!entry) {
2463         /* What used to be head of the list.
2464            If this is NULL, then we're the first entry for this slot, which
2465            means we need to increate fill.  */
2466         struct shared_he *new_entry;
2467         HEK *hek;
2468         char *k;
2469         HE **const head = &HvARRAY(PL_strtab)[hindex];
2470         HE *const next = *head;
2471
2472         /* We don't actually store a HE from the arena and a regular HEK.
2473            Instead we allocate one chunk of memory big enough for both,
2474            and put the HEK straight after the HE. This way we can find the
2475            HEK directly from the HE.
2476         */
2477
2478         Newx(k, STRUCT_OFFSET(struct shared_he,
2479                                 shared_he_hek.hek_key[0]) + len + 2, char);
2480         new_entry = (struct shared_he *)k;
2481         entry = &(new_entry->shared_he_he);
2482         hek = &(new_entry->shared_he_hek);
2483
2484         Copy(str, HEK_KEY(hek), len, char);
2485         HEK_KEY(hek)[len] = 0;
2486         HEK_LEN(hek) = len;
2487         HEK_HASH(hek) = hash;
2488         HEK_FLAGS(hek) = (unsigned char)flags_masked;
2489
2490         /* Still "point" to the HEK, so that other code need not know what
2491            we're up to.  */
2492         HeKEY_hek(entry) = hek;
2493         entry->he_valu.hent_refcount = 0;
2494         HeNEXT(entry) = next;
2495         *head = entry;
2496
2497         xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
2498         if (!next) {                    /* initial entry? */
2499             xhv->xhv_fill++; /* HvFILL(hv)++ */
2500         } else if (xhv->xhv_keys > (IV)xhv->xhv_max /* HvKEYS(hv) > HvMAX(hv) */) {
2501                 hsplit(PL_strtab);
2502         }
2503     }
2504
2505     ++entry->he_valu.hent_refcount;
2506     UNLOCK_STRTAB_MUTEX;
2507
2508     if (flags & HVhek_FREEKEY)
2509         Safefree(str);
2510
2511     return HeKEY_hek(entry);
2512 }
2513
2514 I32 *
2515 Perl_hv_placeholders_p(pTHX_ HV *hv)
2516 {
2517     dVAR;
2518     MAGIC *mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2519
2520     if (!mg) {
2521         mg = sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, 0);
2522
2523         if (!mg) {
2524             Perl_die(aTHX_ "panic: hv_placeholders_p");
2525         }
2526     }
2527     return &(mg->mg_len);
2528 }
2529
2530
2531 I32
2532 Perl_hv_placeholders_get(pTHX_ HV *hv)
2533 {
2534     dVAR;
2535     MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2536
2537     return mg ? mg->mg_len : 0;
2538 }
2539
2540 void
2541 Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
2542 {
2543     dVAR;
2544     MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2545
2546     if (mg) {
2547         mg->mg_len = ph;
2548     } else if (ph) {
2549         if (!sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, ph))
2550             Perl_die(aTHX_ "panic: hv_placeholders_set");
2551     }
2552     /* else we don't need to add magic to record 0 placeholders.  */
2553 }
2554
2555 SV *
2556 S_refcounted_he_value(pTHX_ const struct refcounted_he *he)
2557 {
2558     SV *value;
2559     switch(he->refcounted_he_data[0] & HVrhek_typemask) {
2560     case HVrhek_undef:
2561         value = newSV(0);
2562         break;
2563     case HVrhek_delete:
2564         value = &PL_sv_placeholder;
2565         break;
2566     case HVrhek_IV:
2567         value = (he->refcounted_he_data[0] & HVrhek_UV)
2568             ? newSVuv(he->refcounted_he_val.refcounted_he_u_iv)
2569             : newSViv(he->refcounted_he_val.refcounted_he_u_uv);
2570         break;
2571     case HVrhek_PV:
2572         /* Create a string SV that directly points to the bytes in our
2573            structure.  */
2574         value = newSV(0);
2575         sv_upgrade(value, SVt_PV);
2576         SvPV_set(value, (char *) he->refcounted_he_data + 1);
2577         SvCUR_set(value, he->refcounted_he_val.refcounted_he_u_len);
2578         /* This stops anything trying to free it  */
2579         SvLEN_set(value, 0);
2580         SvPOK_on(value);
2581         SvREADONLY_on(value);
2582         if (he->refcounted_he_data[0] & HVrhek_UTF8)
2583             SvUTF8_on(value);
2584         break;
2585     default:
2586         Perl_croak(aTHX_ "panic: refcounted_he_value bad flags %x",
2587                    he->refcounted_he_data[0]);
2588     }
2589     return value;
2590 }
2591
2592 #ifdef USE_ITHREADS
2593 /* A big expression to find the key offset */
2594 #define REF_HE_KEY(chain) \
2595         ((((chain->refcounted_he_data[0] & HVrhek_typemask) == HVrhek_PV) \
2596             ? chain->refcounted_he_val.refcounted_he_u_len + 1 : 0)       \
2597          + 1 + chain->refcounted_he_data)
2598 #endif
2599
2600 /*
2601 =for apidoc refcounted_he_chain_2hv
2602
2603 Generates an returns a C<HV *> by walking up the tree starting at the passed
2604 in C<struct refcounted_he *>.
2605
2606 =cut
2607 */
2608 HV *
2609 Perl_refcounted_he_chain_2hv(pTHX_ const struct refcounted_he *chain)
2610 {
2611     dVAR;
2612     HV *hv = newHV();
2613     U32 placeholders = 0;
2614     /* We could chase the chain once to get an idea of the number of keys,
2615        and call ksplit.  But for now we'll make a potentially inefficient
2616        hash with only 8 entries in its array.  */
2617     const U32 max = HvMAX(hv);
2618
2619     if (!HvARRAY(hv)) {
2620         char *array;
2621         Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(max + 1), char);
2622         HvARRAY(hv) = (HE**)array;
2623     }
2624
2625     while (chain) {
2626 #ifdef USE_ITHREADS
2627         U32 hash = chain->refcounted_he_hash;
2628 #else
2629         U32 hash = HEK_HASH(chain->refcounted_he_hek);
2630 #endif
2631         HE **oentry = &((HvARRAY(hv))[hash & max]);
2632         HE *entry = *oentry;
2633         SV *value;
2634
2635         for (; entry; entry = HeNEXT(entry)) {
2636             if (HeHASH(entry) == hash) {
2637                 /* We might have a duplicate key here.  If so, entry is older
2638                    than the key we've already put in the hash, so if they are
2639                    the same, skip adding entry.  */
2640 #ifdef USE_ITHREADS
2641                 const STRLEN klen = HeKLEN(entry);
2642                 const char *const key = HeKEY(entry);
2643                 if (klen == chain->refcounted_he_keylen
2644                     && (!!HeKUTF8(entry)
2645                         == !!(chain->refcounted_he_data[0] & HVhek_UTF8))
2646                     && memEQ(key, REF_HE_KEY(chain), klen))
2647                     goto next_please;
2648 #else
2649                 if (HeKEY_hek(entry) == chain->refcounted_he_hek)
2650                     goto next_please;
2651                 if (HeKLEN(entry) == HEK_LEN(chain->refcounted_he_hek)
2652                     && HeKUTF8(entry) == HEK_UTF8(chain->refcounted_he_hek)
2653                     && memEQ(HeKEY(entry), HEK_KEY(chain->refcounted_he_hek),
2654                              HeKLEN(entry)))
2655                     goto next_please;
2656 #endif
2657             }
2658         }
2659         assert (!entry);
2660         entry = new_HE();
2661
2662 #ifdef USE_ITHREADS
2663         HeKEY_hek(entry)
2664             = share_hek_flags(REF_HE_KEY(chain),
2665                               chain->refcounted_he_keylen,
2666                               chain->refcounted_he_hash,
2667                               (chain->refcounted_he_data[0]
2668                                & (HVhek_UTF8|HVhek_WASUTF8)));
2669 #else
2670         HeKEY_hek(entry) = share_hek_hek(chain->refcounted_he_hek);
2671 #endif
2672         value = refcounted_he_value(chain);
2673         if (value == &PL_sv_placeholder)
2674             placeholders++;
2675         HeVAL(entry) = value;
2676
2677         /* Link it into the chain.  */
2678         HeNEXT(entry) = *oentry;
2679         if (!HeNEXT(entry)) {
2680             /* initial entry.   */
2681             HvFILL(hv)++;
2682         }
2683         *oentry = entry;
2684
2685         HvTOTALKEYS(hv)++;
2686
2687     next_please:
2688         chain = chain->refcounted_he_next;
2689     }
2690
2691     if (placeholders) {
2692         clear_placeholders(hv, placeholders);
2693         HvTOTALKEYS(hv) -= placeholders;
2694     }
2695
2696     /* We could check in the loop to see if we encounter any keys with key
2697        flags, but it's probably not worth it, as this per-hash flag is only
2698        really meant as an optimisation for things like Storable.  */
2699     HvHASKFLAGS_on(hv);
2700     DEBUG_A(Perl_hv_assert(aTHX_ hv));
2701
2702     return hv;
2703 }
2704
2705 SV *
2706 Perl_refcounted_he_fetch(pTHX_ const struct refcounted_he *chain, SV *keysv,
2707                          const char *key, STRLEN klen, int flags, U32 hash)
2708 {
2709     /* Just to be awkward, if you're using this interface the UTF-8-or-not-ness
2710        of your key has to exactly match that which is stored.  */
2711     SV *value = &PL_sv_placeholder;
2712     bool is_utf8;
2713
2714     if (keysv) {
2715         if (flags & HVhek_FREEKEY)
2716             Safefree(key);
2717         key = SvPV_const(keysv, klen);
2718         flags = 0;
2719         is_utf8 = (SvUTF8(keysv) != 0);
2720     } else {
2721         is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
2722     }
2723
2724     if (!hash) {
2725         if (keysv && (SvIsCOW_shared_hash(keysv))) {
2726             hash = SvSHARED_HASH(keysv);
2727         } else {
2728             PERL_HASH(hash, key, klen);
2729         }
2730     }
2731
2732     for (; chain; chain = chain->refcounted_he_next) {
2733 #ifdef USE_ITHREADS
2734         if (hash != chain->refcounted_he_hash)
2735             continue;
2736         if (klen != chain->refcounted_he_keylen)
2737             continue;
2738         if (memNE(REF_HE_KEY(chain),key,klen))
2739             continue;
2740         if (!!is_utf8 != !!(chain->refcounted_he_data[0] & HVhek_UTF8))
2741             continue;
2742 #else
2743         if (hash != HEK_HASH(chain->refcounted_he_hek))
2744             continue;
2745         if (klen != HEK_LEN(chain->refcounted_he_hek))
2746             continue;
2747         if (memNE(HEK_KEY(chain->refcounted_he_hek),key,klen))
2748             continue;
2749         if (!!is_utf8 != !!HEK_UTF8(chain->refcounted_he_hek))
2750             continue;
2751 #endif
2752
2753         value = sv_2mortal(refcounted_he_value(chain));
2754         break;
2755     }
2756
2757     if (flags & HVhek_FREEKEY)
2758         Safefree(key);
2759
2760     return value;
2761 }
2762
2763 /*
2764 =for apidoc refcounted_he_new
2765
2766 Creates a new C<struct refcounted_he>. As S<key> is copied, and value is
2767 stored in a compact form, all references remain the property of the caller.
2768 The C<struct refcounted_he> is returned with a reference count of 1.
2769
2770 =cut
2771 */
2772
2773 struct refcounted_he *
2774 Perl_refcounted_he_new(pTHX_ struct refcounted_he *const parent,
2775                        SV *const key, SV *const value) {
2776     dVAR;
2777     struct refcounted_he *he;
2778     STRLEN key_len;
2779     const char *key_p = SvPV_const(key, key_len);
2780     STRLEN value_len = 0;
2781     const char *value_p = NULL;
2782     char value_type;
2783     char flags;
2784     STRLEN key_offset;
2785     U32 hash;
2786     bool is_utf8 = SvUTF8(key) ? TRUE : FALSE;
2787
2788     if (SvPOK(value)) {
2789         value_type = HVrhek_PV;
2790     } else if (SvIOK(value)) {
2791         value_type = HVrhek_IV;
2792     } else if (value == &PL_sv_placeholder) {
2793         value_type = HVrhek_delete;
2794     } else if (!SvOK(value)) {
2795         value_type = HVrhek_undef;
2796     } else {
2797         value_type = HVrhek_PV;
2798     }
2799
2800     if (value_type == HVrhek_PV) {
2801         value_p = SvPV_const(value, value_len);
2802         key_offset = value_len + 2;
2803     } else {
2804         value_len = 0;
2805         key_offset = 1;
2806     }
2807     flags = value_type;
2808
2809 #ifdef USE_ITHREADS
2810     he = PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
2811                               + key_len
2812                               + key_offset);
2813 #else
2814     he = PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
2815                               + key_offset);
2816 #endif
2817
2818
2819     he->refcounted_he_next = parent;
2820
2821     if (value_type == HVrhek_PV) {
2822         Copy(value_p, he->refcounted_he_data + 1, value_len + 1, char);
2823         he->refcounted_he_val.refcounted_he_u_len = value_len;
2824         if (SvUTF8(value)) {
2825             flags |= HVrhek_UTF8;
2826         }
2827     } else if (value_type == HVrhek_IV) {
2828         if (SvUOK(value)) {
2829             he->refcounted_he_val.refcounted_he_u_uv = SvUVX(value);
2830             flags |= HVrhek_UV;
2831         } else {
2832             he->refcounted_he_val.refcounted_he_u_iv = SvIVX(value);
2833         }
2834     }
2835
2836     if (is_utf8) {
2837         /* Hash keys are always stored normalised to (yes) ISO-8859-1.
2838            As we're going to be building hash keys from this value in future,
2839            normalise it now.  */
2840         key_p = (char*)bytes_from_utf8((const U8*)key_p, &key_len, &is_utf8);
2841         flags |= is_utf8 ? HVhek_UTF8 : HVhek_WASUTF8;
2842     }
2843     PERL_HASH(hash, key_p, key_len);
2844
2845 #ifdef USE_ITHREADS
2846     he->refcounted_he_hash = hash;
2847     he->refcounted_he_keylen = key_len;
2848     Copy(key_p, he->refcounted_he_data + key_offset, key_len, char);
2849 #else
2850     he->refcounted_he_hek = share_hek_flags(key_p, key_len, hash, flags);
2851 #endif
2852
2853     if (flags & HVhek_WASUTF8) {
2854         /* If it was downgraded from UTF-8, then the pointer returned from
2855            bytes_from_utf8 is an allocated pointer that we must free.  */
2856         Safefree(key_p);
2857     }
2858
2859     he->refcounted_he_data[0] = flags;
2860     he->refcounted_he_refcnt = 1;
2861
2862     return he;
2863 }
2864
2865 /*
2866 =for apidoc refcounted_he_free
2867
2868 Decrements the reference count of the passed in C<struct refcounted_he *>
2869 by one. If the reference count reaches zero the structure's memory is freed,
2870 and C<refcounted_he_free> iterates onto the parent node.
2871
2872 =cut
2873 */
2874
2875 void
2876 Perl_refcounted_he_free(pTHX_ struct refcounted_he *he) {
2877     PERL_UNUSED_CONTEXT;
2878
2879     while (he) {
2880         struct refcounted_he *copy;
2881         U32 new_count;
2882
2883         HINTS_REFCNT_LOCK;
2884         new_count = --he->refcounted_he_refcnt;
2885         HINTS_REFCNT_UNLOCK;
2886         
2887         if (new_count) {
2888             return;
2889         }
2890
2891 #ifndef USE_ITHREADS
2892         unshare_hek_or_pvn (he->refcounted_he_hek, 0, 0, 0);
2893 #endif
2894         copy = he;
2895         he = he->refcounted_he_next;
2896         PerlMemShared_free(copy);
2897     }
2898 }
2899
2900 /*
2901 =for apidoc hv_assert
2902
2903 Check that a hash is in an internally consistent state.
2904
2905 =cut
2906 */
2907
2908 #ifdef DEBUGGING
2909
2910 void
2911 Perl_hv_assert(pTHX_ HV *hv)
2912 {
2913     dVAR;
2914     HE* entry;
2915     int withflags = 0;
2916     int placeholders = 0;
2917     int real = 0;
2918     int bad = 0;
2919     const I32 riter = HvRITER_get(hv);
2920     HE *eiter = HvEITER_get(hv);
2921
2922     (void)hv_iterinit(hv);
2923
2924     while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
2925         /* sanity check the values */
2926         if (HeVAL(entry) == &PL_sv_placeholder)
2927             placeholders++;
2928         else
2929             real++;
2930         /* sanity check the keys */
2931         if (HeSVKEY(entry)) {
2932             NOOP;   /* Don't know what to check on SV keys.  */
2933         } else if (HeKUTF8(entry)) {
2934             withflags++;
2935             if (HeKWASUTF8(entry)) {
2936                 PerlIO_printf(Perl_debug_log,
2937                             "hash key has both WASUFT8 and UTF8: '%.*s'\n",
2938                             (int) HeKLEN(entry),  HeKEY(entry));
2939                 bad = 1;
2940             }
2941         } else if (HeKWASUTF8(entry))
2942             withflags++;
2943     }
2944     if (!SvTIED_mg((SV*)hv, PERL_MAGIC_tied)) {
2945         static const char bad_count[] = "Count %d %s(s), but hash reports %d\n";
2946         const int nhashkeys = HvUSEDKEYS(hv);
2947         const int nhashplaceholders = HvPLACEHOLDERS_get(hv);
2948
2949         if (nhashkeys != real) {
2950             PerlIO_printf(Perl_debug_log, bad_count, real, "keys", nhashkeys );
2951             bad = 1;
2952         }
2953         if (nhashplaceholders != placeholders) {
2954             PerlIO_printf(Perl_debug_log, bad_count, placeholders, "placeholder", nhashplaceholders );
2955             bad = 1;
2956         }
2957     }
2958     if (withflags && ! HvHASKFLAGS(hv)) {
2959         PerlIO_printf(Perl_debug_log,
2960                     "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
2961                     withflags);
2962         bad = 1;
2963     }
2964     if (bad) {
2965         sv_dump((SV *)hv);
2966     }
2967     HvRITER_set(hv, riter);             /* Restore hash iterator state */
2968     HvEITER_set(hv, eiter);
2969 }
2970
2971 #endif
2972
2973 /*
2974  * Local variables:
2975  * c-indentation-style: bsd
2976  * c-basic-offset: 4
2977  * indent-tabs-mode: t
2978  * End:
2979  *
2980  * ex: set ts=8 sts=4 sw=4 noet:
2981  */