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