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