3 * Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 * 2000, 2001, 2002, 2003, 2004, 2005, by Larry Wall and others
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.
12 * "I sit beside the fire and think of all that I have seen." --Bilbo
16 =head1 Hash Manipulation Functions
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.
31 #define PERL_HASH_INTERNAL_ACCESS
34 #define HV_MAX_LENGTH_BEFORE_SPLIT 14
41 New(54, he, PERL_ARENA_SIZE/sizeof(HE), HE);
42 HeNEXT(he) = PL_he_arenaroot;
45 heend = &he[PERL_ARENA_SIZE / sizeof(HE) - 1];
48 HeNEXT(he) = (HE*)(he + 1);
62 PL_he_root = HeNEXT(he);
71 HeNEXT(p) = (HE*)PL_he_root;
78 #define new_HE() (HE*)safemalloc(sizeof(HE))
79 #define del_HE(p) safefree((char*)p)
83 #define new_HE() new_he()
84 #define del_HE(p) del_he(p)
89 S_save_hek_flags(pTHX_ const char *str, I32 len, U32 hash, int flags)
91 const int flags_masked = flags & HVhek_MASK;
95 New(54, k, HEK_BASESIZE + len + 2, char);
97 Copy(str, HEK_KEY(hek), len, char);
98 HEK_KEY(hek)[len] = 0;
100 HEK_HASH(hek) = hash;
101 HEK_FLAGS(hek) = (unsigned char)flags_masked;
103 if (flags & HVhek_FREEKEY)
108 /* free the pool of temporary HE/HEK pairs retunrned by hv_fetch_ent
112 Perl_free_tied_hv_pool(pTHX)
115 HE *he = PL_hv_fetch_ent_mh;
117 Safefree(HeKEY_hek(he));
122 PL_hv_fetch_ent_mh = Nullhe;
125 #if defined(USE_ITHREADS)
127 Perl_hek_dup(pTHX_ HEK *source, CLONE_PARAMS* param)
129 HE *shared = (HE*)ptr_table_fetch(PL_shared_hek_table, source);
133 /* We already shared this hash key. */
137 shared = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
138 HEK_HASH(source), HEK_FLAGS(source));
139 ptr_table_store(PL_shared_hek_table, source, shared);
141 return HeKEY_hek(shared);
145 Perl_he_dup(pTHX_ HE *e, bool shared, CLONE_PARAMS* param)
151 /* look for it in the table first */
152 ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
156 /* create anew and remember what it is */
158 ptr_table_store(PL_ptr_table, e, ret);
160 HeNEXT(ret) = he_dup(HeNEXT(e),shared, param);
161 if (HeKLEN(e) == HEf_SVKEY) {
163 New(54, k, HEK_BASESIZE + sizeof(SV*), char);
164 HeKEY_hek(ret) = (HEK*)k;
165 HeKEY_sv(ret) = SvREFCNT_inc(sv_dup(HeKEY_sv(e), param));
168 /* This is hek_dup inlined, which seems to be important for speed
170 HEK *source = HeKEY_hek(e);
171 HE *shared = (HE*)ptr_table_fetch(PL_shared_hek_table, source);
174 /* We already shared this hash key. */
178 shared = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
179 HEK_HASH(source), HEK_FLAGS(source));
180 ptr_table_store(PL_shared_hek_table, source, shared);
182 HeKEY_hek(ret) = HeKEY_hek(shared);
185 HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
187 HeVAL(ret) = SvREFCNT_inc(sv_dup(HeVAL(e), param));
190 #endif /* USE_ITHREADS */
193 S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
196 SV *sv = sv_newmortal();
197 if (!(flags & HVhek_FREEKEY)) {
198 sv_setpvn(sv, key, klen);
201 /* Need to free saved eventually assign to mortal SV */
202 /* XXX is this line an error ???: SV *sv = sv_newmortal(); */
203 sv_usepvn(sv, (char *) key, klen);
205 if (flags & HVhek_UTF8) {
208 Perl_croak(aTHX_ msg, sv);
211 /* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
214 #define HV_FETCH_ISSTORE 0x01
215 #define HV_FETCH_ISEXISTS 0x02
216 #define HV_FETCH_LVALUE 0x04
217 #define HV_FETCH_JUST_SV 0x08
222 Stores an SV in a hash. The hash key is specified as C<key> and C<klen> is
223 the length of the key. The C<hash> parameter is the precomputed hash
224 value; if it is zero then Perl will compute it. The return value will be
225 NULL if the operation failed or if the value did not need to be actually
226 stored within the hash (as in the case of tied hashes). Otherwise it can
227 be dereferenced to get the original C<SV*>. Note that the caller is
228 responsible for suitably incrementing the reference count of C<val> before
229 the call, and decrementing it if the function returned NULL. Effectively
230 a successful hv_store takes ownership of one reference to C<val>. This is
231 usually what you want; a newly created SV has a reference count of one, so
232 if all your code does is create SVs then store them in a hash, hv_store
233 will own the only reference to the new SV, and your code doesn't need to do
234 anything further to tidy up. hv_store is not implemented as a call to
235 hv_store_ent, and does not create a temporary SV for the key, so if your
236 key data is not already in SV form then use hv_store in preference to
239 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
240 information on how to use this function on tied hashes.
246 Perl_hv_store(pTHX_ HV *hv, const char *key, I32 klen_i32, SV *val, U32 hash)
259 hek = hv_fetch_common (hv, NULL, key, klen, flags,
260 (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
261 return hek ? &HeVAL(hek) : NULL;
265 Perl_hv_store_flags(pTHX_ HV *hv, const char *key, I32 klen, SV *val,
266 register U32 hash, int flags)
268 HE *hek = hv_fetch_common (hv, NULL, key, klen, flags,
269 (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
270 return hek ? &HeVAL(hek) : NULL;
274 =for apidoc hv_store_ent
276 Stores C<val> in a hash. The hash key is specified as C<key>. The C<hash>
277 parameter is the precomputed hash value; if it is zero then Perl will
278 compute it. The return value is the new hash entry so created. It will be
279 NULL if the operation failed or if the value did not need to be actually
280 stored within the hash (as in the case of tied hashes). Otherwise the
281 contents of the return value can be accessed using the C<He?> macros
282 described here. Note that the caller is responsible for suitably
283 incrementing the reference count of C<val> before the call, and
284 decrementing it if the function returned NULL. Effectively a successful
285 hv_store_ent takes ownership of one reference to C<val>. This is
286 usually what you want; a newly created SV has a reference count of one, so
287 if all your code does is create SVs then store them in a hash, hv_store
288 will own the only reference to the new SV, and your code doesn't need to do
289 anything further to tidy up. Note that hv_store_ent only reads the C<key>;
290 unlike C<val> it does not take ownership of it, so maintaining the correct
291 reference count on C<key> is entirely the caller's responsibility. hv_store
292 is not implemented as a call to hv_store_ent, and does not create a temporary
293 SV for the key, so if your key data is not already in SV form then use
294 hv_store in preference to hv_store_ent.
296 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
297 information on how to use this function on tied hashes.
303 Perl_hv_store_ent(pTHX_ HV *hv, SV *keysv, SV *val, U32 hash)
305 return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISSTORE, val, hash);
309 =for apidoc hv_exists
311 Returns a boolean indicating whether the specified hash key exists. The
312 C<klen> is the length of the key.
318 Perl_hv_exists(pTHX_ HV *hv, const char *key, I32 klen_i32)
330 return hv_fetch_common(hv, NULL, key, klen, flags, HV_FETCH_ISEXISTS, 0, 0)
337 Returns the SV which corresponds to the specified key in the hash. The
338 C<klen> is the length of the key. If C<lval> is set then the fetch will be
339 part of a store. Check that the return value is non-null before
340 dereferencing it to an C<SV*>.
342 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
343 information on how to use this function on tied hashes.
349 Perl_hv_fetch(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 lval)
362 hek = hv_fetch_common (hv, NULL, key, klen, flags,
363 HV_FETCH_JUST_SV | (lval ? HV_FETCH_LVALUE : 0),
365 return hek ? &HeVAL(hek) : NULL;
369 =for apidoc hv_exists_ent
371 Returns a boolean indicating whether the specified hash key exists. C<hash>
372 can be a valid precomputed hash value, or 0 to ask for it to be
379 Perl_hv_exists_ent(pTHX_ HV *hv, SV *keysv, U32 hash)
381 return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISEXISTS, 0, hash)
385 /* returns an HE * structure with the all fields set */
386 /* note that hent_val will be a mortal sv for MAGICAL hashes */
388 =for apidoc hv_fetch_ent
390 Returns the hash entry which corresponds to the specified key in the hash.
391 C<hash> must be a valid precomputed hash number for the given C<key>, or 0
392 if you want the function to compute it. IF C<lval> is set then the fetch
393 will be part of a store. Make sure the return value is non-null before
394 accessing it. The return value when C<tb> is a tied hash is a pointer to a
395 static location, so be sure to make a copy of the structure if you need to
398 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
399 information on how to use this function on tied hashes.
405 Perl_hv_fetch_ent(pTHX_ HV *hv, SV *keysv, I32 lval, register U32 hash)
407 return hv_fetch_common(hv, keysv, NULL, 0, 0,
408 (lval ? HV_FETCH_LVALUE : 0), Nullsv, hash);
412 S_hv_fetch_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
413 int flags, int action, SV *val, register U32 hash)
427 if (flags & HVhek_FREEKEY)
429 key = SvPV_const(keysv, klen);
431 is_utf8 = (SvUTF8(keysv) != 0);
433 is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
436 xhv = (XPVHV*)SvANY(hv);
438 if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS)))
440 if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
443 /* XXX should be able to skimp on the HE/HEK here when
444 HV_FETCH_JUST_SV is true. */
447 keysv = newSVpvn(key, klen);
452 keysv = newSVsv(keysv);
454 mg_copy((SV*)hv, sv, (char *)keysv, HEf_SVKEY);
456 /* grab a fake HE/HEK pair from the pool or make a new one */
457 entry = PL_hv_fetch_ent_mh;
459 PL_hv_fetch_ent_mh = HeNEXT(entry);
463 New(54, k, HEK_BASESIZE + sizeof(SV*), char);
464 HeKEY_hek(entry) = (HEK*)k;
466 HeNEXT(entry) = Nullhe;
467 HeSVKEY_set(entry, keysv);
469 sv_upgrade(sv, SVt_PVLV);
471 /* so we can free entry when freeing sv */
472 LvTARG(sv) = (SV*)entry;
474 /* XXX remove at some point? */
475 if (flags & HVhek_FREEKEY)
480 #ifdef ENV_IS_CASELESS
481 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
483 for (i = 0; i < klen; ++i)
484 if (isLOWER(key[i])) {
485 /* Would be nice if we had a routine to do the
486 copy and upercase in a single pass through. */
487 const char *nkey = strupr(savepvn(key,klen));
488 /* Note that this fetch is for nkey (the uppercased
489 key) whereas the store is for key (the original) */
490 entry = hv_fetch_common(hv, Nullsv, nkey, klen,
491 HVhek_FREEKEY, /* free nkey */
492 0 /* non-LVAL fetch */,
493 Nullsv /* no value */,
494 0 /* compute hash */);
495 if (!entry && (action & HV_FETCH_LVALUE)) {
496 /* This call will free key if necessary.
497 Do it this way to encourage compiler to tail
499 entry = hv_fetch_common(hv, keysv, key, klen,
500 flags, HV_FETCH_ISSTORE,
503 if (flags & HVhek_FREEKEY)
511 else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
512 if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
514 /* I don't understand why hv_exists_ent has svret and sv,
515 whereas hv_exists only had one. */
516 svret = sv_newmortal();
519 if (keysv || is_utf8) {
521 keysv = newSVpvn(key, klen);
524 keysv = newSVsv(keysv);
526 mg_copy((SV*)hv, sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
528 mg_copy((SV*)hv, sv, key, klen);
530 if (flags & HVhek_FREEKEY)
532 magic_existspack(svret, mg_find(sv, PERL_MAGIC_tiedelem));
533 /* This cast somewhat evil, but I'm merely using NULL/
534 not NULL to return the boolean exists.
535 And I know hv is not NULL. */
536 return SvTRUE(svret) ? (HE *)hv : NULL;
538 #ifdef ENV_IS_CASELESS
539 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
540 /* XXX This code isn't UTF8 clean. */
541 const char *keysave = key;
542 /* Will need to free this, so set FREEKEY flag. */
543 key = savepvn(key,klen);
544 key = (const char*)strupr((char*)key);
549 if (flags & HVhek_FREEKEY) {
552 flags |= HVhek_FREEKEY;
556 else if (action & HV_FETCH_ISSTORE) {
559 hv_magic_check (hv, &needs_copy, &needs_store);
561 const bool save_taint = PL_tainted;
562 if (keysv || is_utf8) {
564 keysv = newSVpvn(key, klen);
568 PL_tainted = SvTAINTED(keysv);
569 keysv = sv_2mortal(newSVsv(keysv));
570 mg_copy((SV*)hv, val, (char*)keysv, HEf_SVKEY);
572 mg_copy((SV*)hv, val, key, klen);
575 TAINT_IF(save_taint);
576 if (!HvARRAY(hv) && !needs_store) {
577 if (flags & HVhek_FREEKEY)
581 #ifdef ENV_IS_CASELESS
582 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
583 /* XXX This code isn't UTF8 clean. */
584 const char *keysave = key;
585 /* Will need to free this, so set FREEKEY flag. */
586 key = savepvn(key,klen);
587 key = (const char*)strupr((char*)key);
592 if (flags & HVhek_FREEKEY) {
595 flags |= HVhek_FREEKEY;
603 if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
604 #ifdef DYNAMIC_ENV_FETCH /* if it's an %ENV lookup, we may get it on the fly */
605 || (SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
610 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
612 HvARRAY(hv) = (HE**)array;
614 #ifdef DYNAMIC_ENV_FETCH
615 else if (action & HV_FETCH_ISEXISTS) {
616 /* for an %ENV exists, if we do an insert it's by a recursive
617 store call, so avoid creating HvARRAY(hv) right now. */
621 /* XXX remove at some point? */
622 if (flags & HVhek_FREEKEY)
630 const char *keysave = key;
631 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
635 flags &= ~HVhek_UTF8;
636 if (key != keysave) {
637 if (flags & HVhek_FREEKEY)
639 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
644 PERL_HASH_INTERNAL(hash, key, klen);
645 /* We don't have a pointer to the hv, so we have to replicate the
646 flag into every HEK, so that hv_iterkeysv can see it. */
647 /* And yes, you do need this even though you are not "storing" because
648 you can flip the flags below if doing an lval lookup. (And that
649 was put in to give the semantics Andreas was expecting.) */
650 flags |= HVhek_REHASH;
652 if (keysv && (SvIsCOW_shared_hash(keysv))) {
653 hash = SvSHARED_HASH(keysv);
655 PERL_HASH(hash, key, klen);
659 masked_flags = (flags & HVhek_MASK);
661 #ifdef DYNAMIC_ENV_FETCH
662 if (!HvARRAY(hv)) entry = Null(HE*);
666 entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
668 for (; entry; entry = HeNEXT(entry)) {
669 if (HeHASH(entry) != hash) /* strings can't be equal */
671 if (HeKLEN(entry) != (I32)klen)
673 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
675 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
678 if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
679 if (HeKFLAGS(entry) != masked_flags) {
680 /* We match if HVhek_UTF8 bit in our flags and hash key's
681 match. But if entry was set previously with HVhek_WASUTF8
682 and key now doesn't (or vice versa) then we should change
683 the key's flag, as this is assignment. */
684 if (HvSHAREKEYS(hv)) {
685 /* Need to swap the key we have for a key with the flags we
686 need. As keys are shared we can't just write to the
687 flag, so we share the new one, unshare the old one. */
688 HEK *new_hek = HeKEY_hek(share_hek_flags(key, klen, hash,
690 unshare_hek (HeKEY_hek(entry));
691 HeKEY_hek(entry) = new_hek;
694 HeKFLAGS(entry) = masked_flags;
695 if (masked_flags & HVhek_ENABLEHVKFLAGS)
698 if (HeVAL(entry) == &PL_sv_placeholder) {
699 /* yes, can store into placeholder slot */
700 if (action & HV_FETCH_LVALUE) {
702 /* This preserves behaviour with the old hv_fetch
703 implementation which at this point would bail out
704 with a break; (at "if we find a placeholder, we
705 pretend we haven't found anything")
707 That break mean that if a placeholder were found, it
708 caused a call into hv_store, which in turn would
709 check magic, and if there is no magic end up pretty
710 much back at this point (in hv_store's code). */
713 /* LVAL fetch which actaully needs a store. */
715 HvPLACEHOLDERS(hv)--;
718 if (val != &PL_sv_placeholder)
719 HvPLACEHOLDERS(hv)--;
722 } else if (action & HV_FETCH_ISSTORE) {
723 SvREFCNT_dec(HeVAL(entry));
726 } else if (HeVAL(entry) == &PL_sv_placeholder) {
727 /* if we find a placeholder, we pretend we haven't found
731 if (flags & HVhek_FREEKEY)
735 #ifdef DYNAMIC_ENV_FETCH /* %ENV lookup? If so, try to fetch the value now */
736 if (!(action & HV_FETCH_ISSTORE)
737 && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
739 char *env = PerlEnv_ENVgetenv_len(key,&len);
741 sv = newSVpvn(env,len);
743 return hv_fetch_common(hv,keysv,key,klen,flags,HV_FETCH_ISSTORE,sv,
749 if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
750 S_hv_notallowed(aTHX_ flags, key, klen,
751 "Attempt to access disallowed key '%"SVf"' in"
752 " a restricted hash");
754 if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
755 /* Not doing some form of store, so return failure. */
756 if (flags & HVhek_FREEKEY)
760 if (action & HV_FETCH_LVALUE) {
763 /* At this point the old hv_fetch code would call to hv_store,
764 which in turn might do some tied magic. So we need to make that
765 magic check happen. */
766 /* gonna assign to this, so it better be there */
767 return hv_fetch_common(hv, keysv, key, klen, flags,
768 HV_FETCH_ISSTORE, val, hash);
769 /* XXX Surely that could leak if the fetch-was-store fails?
770 Just like the hv_fetch. */
774 /* Welcome to hv_store... */
777 /* Not sure if we can get here. I think the only case of oentry being
778 NULL is for %ENV with dynamic env fetch. But that should disappear
779 with magic in the previous code. */
782 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
784 HvARRAY(hv) = (HE**)array;
787 oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
790 /* share_hek_flags will do the free for us. This might be considered
793 HeKEY_hek(entry) = HeKEY_hek(share_hek_flags(key, klen, hash, flags));
794 else /* gotta do the real thing */
795 HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
797 HeNEXT(entry) = *oentry;
800 if (val == &PL_sv_placeholder)
801 HvPLACEHOLDERS(hv)++;
802 if (masked_flags & HVhek_ENABLEHVKFLAGS)
806 const HE *counter = HeNEXT(entry);
808 xhv->xhv_keys++; /* HvKEYS(hv)++ */
809 if (!counter) { /* initial entry? */
810 xhv->xhv_fill++; /* HvFILL(hv)++ */
811 } else if (xhv->xhv_keys > (IV)xhv->xhv_max) {
813 } else if(!HvREHASH(hv)) {
816 while ((counter = HeNEXT(counter)))
819 if (n_links > HV_MAX_LENGTH_BEFORE_SPLIT) {
820 /* Use only the old HvKEYS(hv) > HvMAX(hv) condition to limit
821 bucket splits on a rehashed hash, as we're not going to
822 split it again, and if someone is lucky (evil) enough to
823 get all the keys in one list they could exhaust our memory
824 as we repeatedly double the number of buckets on every
825 entry. Linear search feels a less worse thing to do. */
835 S_hv_magic_check(pTHX_ HV *hv, bool *needs_copy, bool *needs_store)
837 const MAGIC *mg = SvMAGIC(hv);
841 if (isUPPER(mg->mg_type)) {
843 switch (mg->mg_type) {
844 case PERL_MAGIC_tied:
846 *needs_store = FALSE;
847 return; /* We've set all there is to set. */
850 mg = mg->mg_moremagic;
855 =for apidoc hv_scalar
857 Evaluates the hash in scalar context and returns the result. Handles magic when the hash is tied.
863 Perl_hv_scalar(pTHX_ HV *hv)
868 if ((SvRMAGICAL(hv) && (mg = mg_find((SV*)hv, PERL_MAGIC_tied)))) {
869 sv = magic_scalarpack(hv, mg);
875 Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
876 (long)HvFILL(hv), (long)HvMAX(hv) + 1);
884 =for apidoc hv_delete
886 Deletes a key/value pair in the hash. The value SV is removed from the
887 hash and returned to the caller. The C<klen> is the length of the key.
888 The C<flags> value will normally be zero; if set to G_DISCARD then NULL
895 Perl_hv_delete(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 flags)
902 k_flags |= HVhek_UTF8;
906 return hv_delete_common(hv, NULL, key, klen, k_flags, flags, 0);
910 =for apidoc hv_delete_ent
912 Deletes a key/value pair in the hash. The value SV is removed from the
913 hash and returned to the caller. The C<flags> value will normally be zero;
914 if set to G_DISCARD then NULL will be returned. C<hash> can be a valid
915 precomputed hash value, or 0 to ask for it to be computed.
921 Perl_hv_delete_ent(pTHX_ HV *hv, SV *keysv, I32 flags, U32 hash)
923 return hv_delete_common(hv, keysv, NULL, 0, 0, flags, hash);
927 S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
928 int k_flags, I32 d_flags, U32 hash)
933 register HE **oentry;
934 HE *const *first_entry;
943 if (k_flags & HVhek_FREEKEY)
945 key = SvPV_const(keysv, klen);
947 is_utf8 = (SvUTF8(keysv) != 0);
949 is_utf8 = ((k_flags & HVhek_UTF8) ? TRUE : FALSE);
952 if (SvRMAGICAL(hv)) {
955 hv_magic_check (hv, &needs_copy, &needs_store);
958 entry = hv_fetch_common(hv, keysv, key, klen,
959 k_flags & ~HVhek_FREEKEY, HV_FETCH_LVALUE,
961 sv = entry ? HeVAL(entry) : NULL;
967 if (mg_find(sv, PERL_MAGIC_tiedelem)) {
968 /* No longer an element */
969 sv_unmagic(sv, PERL_MAGIC_tiedelem);
972 return Nullsv; /* element cannot be deleted */
974 #ifdef ENV_IS_CASELESS
975 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
976 /* XXX This code isn't UTF8 clean. */
977 keysv = sv_2mortal(newSVpvn(key,klen));
978 if (k_flags & HVhek_FREEKEY) {
981 key = strupr(SvPVX(keysv));
990 xhv = (XPVHV*)SvANY(hv);
995 const char *keysave = key;
996 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
999 k_flags |= HVhek_UTF8;
1001 k_flags &= ~HVhek_UTF8;
1002 if (key != keysave) {
1003 if (k_flags & HVhek_FREEKEY) {
1004 /* This shouldn't happen if our caller does what we expect,
1005 but strictly the API allows it. */
1008 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
1010 HvHASKFLAGS_on((SV*)hv);
1014 PERL_HASH_INTERNAL(hash, key, klen);
1016 if (keysv && (SvIsCOW_shared_hash(keysv))) {
1017 hash = SvSHARED_HASH(keysv);
1019 PERL_HASH(hash, key, klen);
1023 masked_flags = (k_flags & HVhek_MASK);
1025 first_entry = oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
1027 for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
1028 if (HeHASH(entry) != hash) /* strings can't be equal */
1030 if (HeKLEN(entry) != (I32)klen)
1032 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
1034 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
1037 /* if placeholder is here, it's already been deleted.... */
1038 if (HeVAL(entry) == &PL_sv_placeholder)
1040 if (k_flags & HVhek_FREEKEY)
1044 else if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1045 S_hv_notallowed(aTHX_ k_flags, key, klen,
1046 "Attempt to delete readonly key '%"SVf"' from"
1047 " a restricted hash");
1049 if (k_flags & HVhek_FREEKEY)
1052 if (d_flags & G_DISCARD)
1055 sv = sv_2mortal(HeVAL(entry));
1056 HeVAL(entry) = &PL_sv_placeholder;
1060 * If a restricted hash, rather than really deleting the entry, put
1061 * a placeholder there. This marks the key as being "approved", so
1062 * we can still access via not-really-existing key without raising
1065 if (SvREADONLY(hv)) {
1066 SvREFCNT_dec(HeVAL(entry));
1067 HeVAL(entry) = &PL_sv_placeholder;
1068 /* We'll be saving this slot, so the number of allocated keys
1069 * doesn't go down, but the number placeholders goes up */
1070 HvPLACEHOLDERS(hv)++;
1072 *oentry = HeNEXT(entry);
1074 xhv->xhv_fill--; /* HvFILL(hv)-- */
1076 if (SvOOK(hv) && entry == HvAUX(hv)->xhv_eiter /* HvEITER(hv) */)
1079 hv_free_ent(hv, entry);
1080 xhv->xhv_keys--; /* HvKEYS(hv)-- */
1081 if (xhv->xhv_keys == 0)
1082 HvHASKFLAGS_off(hv);
1086 if (SvREADONLY(hv)) {
1087 S_hv_notallowed(aTHX_ k_flags, key, klen,
1088 "Attempt to delete disallowed key '%"SVf"' from"
1089 " a restricted hash");
1092 if (k_flags & HVhek_FREEKEY)
1098 S_hsplit(pTHX_ HV *hv)
1100 register XPVHV* xhv = (XPVHV*)SvANY(hv);
1101 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1102 register I32 newsize = oldsize * 2;
1104 char *a = (char*) HvARRAY(hv);
1106 register HE **oentry;
1107 int longest_chain = 0;
1110 /*PerlIO_printf(PerlIO_stderr(), "hsplit called for %p which had %d\n",
1111 hv, (int) oldsize);*/
1113 if (HvPLACEHOLDERS_get(hv) && !SvREADONLY(hv)) {
1114 /* Can make this clear any placeholders first for non-restricted hashes,
1115 even though Storable rebuilds restricted hashes by putting in all the
1116 placeholders (first) before turning on the readonly flag, because
1117 Storable always pre-splits the hash. */
1118 hv_clear_placeholders(hv);
1122 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1123 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1124 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1130 Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1133 New(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1134 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1139 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1141 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1143 if (oldsize >= 64) {
1144 offer_nice_chunk(HvARRAY(hv),
1145 PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
1146 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
1149 Safefree(HvARRAY(hv));
1153 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1154 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
1155 HvARRAY(hv) = (HE**) a;
1158 for (i=0; i<oldsize; i++,aep++) {
1159 int left_length = 0;
1160 int right_length = 0;
1164 if (!*aep) /* non-existent */
1167 for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1168 if ((HeHASH(entry) & newsize) != (U32)i) {
1169 *oentry = HeNEXT(entry);
1170 HeNEXT(entry) = *bep;
1172 xhv->xhv_fill++; /* HvFILL(hv)++ */
1178 oentry = &HeNEXT(entry);
1182 if (!*aep) /* everything moved */
1183 xhv->xhv_fill--; /* HvFILL(hv)-- */
1184 /* I think we don't actually need to keep track of the longest length,
1185 merely flag if anything is too long. But for the moment while
1186 developing this code I'll track it. */
1187 if (left_length > longest_chain)
1188 longest_chain = left_length;
1189 if (right_length > longest_chain)
1190 longest_chain = right_length;
1194 /* Pick your policy for "hashing isn't working" here: */
1195 if (longest_chain <= HV_MAX_LENGTH_BEFORE_SPLIT /* split worked? */
1200 if (hv == PL_strtab) {
1201 /* Urg. Someone is doing something nasty to the string table.
1206 /* Awooga. Awooga. Pathological data. */
1207 /*PerlIO_printf(PerlIO_stderr(), "%p %d of %d with %d/%d buckets\n", hv,
1208 longest_chain, HvTOTALKEYS(hv), HvFILL(hv), 1+HvMAX(hv));*/
1211 Newz(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1212 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1214 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1217 was_shared = HvSHAREKEYS(hv);
1220 HvSHAREKEYS_off(hv);
1225 for (i=0; i<newsize; i++,aep++) {
1226 register HE *entry = *aep;
1228 /* We're going to trash this HE's next pointer when we chain it
1229 into the new hash below, so store where we go next. */
1230 HE *next = HeNEXT(entry);
1235 PERL_HASH_INTERNAL(hash, HeKEY(entry), HeKLEN(entry));
1240 = save_hek_flags(HeKEY(entry), HeKLEN(entry),
1241 hash, HeKFLAGS(entry));
1242 unshare_hek (HeKEY_hek(entry));
1243 HeKEY_hek(entry) = new_hek;
1245 /* Not shared, so simply write the new hash in. */
1246 HeHASH(entry) = hash;
1248 /*PerlIO_printf(PerlIO_stderr(), "%d ", HeKFLAGS(entry));*/
1249 HEK_REHASH_on(HeKEY_hek(entry));
1250 /*PerlIO_printf(PerlIO_stderr(), "%d\n", HeKFLAGS(entry));*/
1252 /* Copy oentry to the correct new chain. */
1253 bep = ((HE**)a) + (hash & (I32) xhv->xhv_max);
1255 xhv->xhv_fill++; /* HvFILL(hv)++ */
1256 HeNEXT(entry) = *bep;
1262 Safefree (HvARRAY(hv));
1263 HvARRAY(hv) = (HE **)a;
1267 Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
1269 register XPVHV* xhv = (XPVHV*)SvANY(hv);
1270 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1271 register I32 newsize;
1276 register HE **oentry;
1278 newsize = (I32) newmax; /* possible truncation here */
1279 if (newsize != newmax || newmax <= oldsize)
1281 while ((newsize & (1 + ~newsize)) != newsize) {
1282 newsize &= ~(newsize & (1 + ~newsize)); /* get proper power of 2 */
1284 if (newsize < newmax)
1286 if (newsize < newmax)
1287 return; /* overflow detection */
1289 a = (char *) HvARRAY(hv);
1292 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1293 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1294 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1300 Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1303 New(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1304 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1309 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1311 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1313 if (oldsize >= 64) {
1314 offer_nice_chunk(HvARRAY(hv),
1315 PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
1316 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
1319 Safefree(HvARRAY(hv));
1322 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1325 Newz(0, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1327 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
1328 HvARRAY(hv) = (HE **) a;
1329 if (!xhv->xhv_fill /* !HvFILL(hv) */) /* skip rest if no entries */
1333 for (i=0; i<oldsize; i++,aep++) {
1334 if (!*aep) /* non-existent */
1336 for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1338 if ((j = (HeHASH(entry) & newsize)) != i) {
1340 *oentry = HeNEXT(entry);
1341 if (!(HeNEXT(entry) = aep[j]))
1342 xhv->xhv_fill++; /* HvFILL(hv)++ */
1347 oentry = &HeNEXT(entry);
1349 if (!*aep) /* everything moved */
1350 xhv->xhv_fill--; /* HvFILL(hv)-- */
1357 Creates a new HV. The reference count is set to 1.
1366 register XPVHV* xhv;
1368 hv = (HV*)NEWSV(502,0);
1369 sv_upgrade((SV *)hv, SVt_PVHV);
1370 xhv = (XPVHV*)SvANY(hv);
1373 #ifndef NODEFAULT_SHAREKEYS
1374 HvSHAREKEYS_on(hv); /* key-sharing on by default */
1377 xhv->xhv_max = 7; /* HvMAX(hv) = 7 (start with 8 buckets) */
1378 xhv->xhv_fill = 0; /* HvFILL(hv) = 0 */
1383 Perl_newHVhv(pTHX_ HV *ohv)
1386 STRLEN hv_max, hv_fill;
1388 if (!ohv || (hv_fill = HvFILL(ohv)) == 0)
1390 hv_max = HvMAX(ohv);
1392 if (!SvMAGICAL((SV *)ohv)) {
1393 /* It's an ordinary hash, so copy it fast. AMS 20010804 */
1395 const bool shared = !!HvSHAREKEYS(ohv);
1396 HE **ents, **oents = (HE **)HvARRAY(ohv);
1398 New(0, a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
1401 /* In each bucket... */
1402 for (i = 0; i <= hv_max; i++) {
1403 HE *prev = NULL, *ent = NULL, *oent = oents[i];
1410 /* Copy the linked list of entries. */
1411 for (oent = oents[i]; oent; oent = HeNEXT(oent)) {
1412 const U32 hash = HeHASH(oent);
1413 const char * const key = HeKEY(oent);
1414 const STRLEN len = HeKLEN(oent);
1415 const int flags = HeKFLAGS(oent);
1418 HeVAL(ent) = newSVsv(HeVAL(oent));
1420 = shared ? HeKEY_hek(share_hek_flags(key, len, hash, flags))
1421 : save_hek_flags(key, len, hash, flags);
1432 HvFILL(hv) = hv_fill;
1433 HvTOTALKEYS(hv) = HvTOTALKEYS(ohv);
1437 /* Iterate over ohv, copying keys and values one at a time. */
1439 const I32 riter = HvRITER_get(ohv);
1440 HE * const eiter = HvEITER_get(ohv);
1442 /* Can we use fewer buckets? (hv_max is always 2^n-1) */
1443 while (hv_max && hv_max + 1 >= hv_fill * 2)
1444 hv_max = hv_max / 2;
1448 while ((entry = hv_iternext_flags(ohv, 0))) {
1449 hv_store_flags(hv, HeKEY(entry), HeKLEN(entry),
1450 newSVsv(HeVAL(entry)), HeHASH(entry),
1453 HvRITER_set(ohv, riter);
1454 HvEITER_set(ohv, eiter);
1461 Perl_hv_free_ent(pTHX_ HV *hv, register HE *entry)
1468 if (val && isGV(val) && GvCVu(val) && HvNAME_get(hv))
1469 PL_sub_generation++; /* may be deletion of method from stash */
1471 if (HeKLEN(entry) == HEf_SVKEY) {
1472 SvREFCNT_dec(HeKEY_sv(entry));
1473 Safefree(HeKEY_hek(entry));
1475 else if (HvSHAREKEYS(hv))
1476 unshare_hek(HeKEY_hek(entry));
1478 Safefree(HeKEY_hek(entry));
1483 Perl_hv_delayfree_ent(pTHX_ HV *hv, register HE *entry)
1487 if (isGV(HeVAL(entry)) && GvCVu(HeVAL(entry)) && HvNAME_get(hv))
1488 PL_sub_generation++; /* may be deletion of method from stash */
1489 sv_2mortal(HeVAL(entry)); /* free between statements */
1490 if (HeKLEN(entry) == HEf_SVKEY) {
1491 sv_2mortal(HeKEY_sv(entry));
1492 Safefree(HeKEY_hek(entry));
1494 else if (HvSHAREKEYS(hv))
1495 unshare_hek(HeKEY_hek(entry));
1497 Safefree(HeKEY_hek(entry));
1502 =for apidoc hv_clear
1504 Clears a hash, making it empty.
1510 Perl_hv_clear(pTHX_ HV *hv)
1513 register XPVHV* xhv;
1517 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1519 xhv = (XPVHV*)SvANY(hv);
1521 if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
1522 /* restricted hash: convert all keys to placeholders */
1524 for (i = 0; i <= xhv->xhv_max; i++) {
1525 HE *entry = (HvARRAY(hv))[i];
1526 for (; entry; entry = HeNEXT(entry)) {
1527 /* not already placeholder */
1528 if (HeVAL(entry) != &PL_sv_placeholder) {
1529 if (HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1530 SV* keysv = hv_iterkeysv(entry);
1532 "Attempt to delete readonly key '%"SVf"' from a restricted hash",
1535 SvREFCNT_dec(HeVAL(entry));
1536 HeVAL(entry) = &PL_sv_placeholder;
1537 HvPLACEHOLDERS(hv)++;
1545 HvPLACEHOLDERS_set(hv, 0);
1547 (void)memzero(HvARRAY(hv),
1548 (xhv->xhv_max+1 /* HvMAX(hv)+1 */) * sizeof(HE*));
1553 HvHASKFLAGS_off(hv);
1557 HvEITER_set(hv, NULL);
1562 =for apidoc hv_clear_placeholders
1564 Clears any placeholders from a hash. If a restricted hash has any of its keys
1565 marked as readonly and the key is subsequently deleted, the key is not actually
1566 deleted but is marked by assigning it a value of &PL_sv_placeholder. This tags
1567 it so it will be ignored by future operations such as iterating over the hash,
1568 but will still allow the hash to have a value reassigned to the key at some
1569 future point. This function clears any such placeholder keys from the hash.
1570 See Hash::Util::lock_keys() for an example of its use.
1576 Perl_hv_clear_placeholders(pTHX_ HV *hv)
1579 I32 items = (I32)HvPLACEHOLDERS_get(hv);
1587 /* Loop down the linked list heads */
1589 HE **oentry = &(HvARRAY(hv))[i];
1590 HE *entry = *oentry;
1595 for (; entry; entry = *oentry) {
1596 if (HeVAL(entry) == &PL_sv_placeholder) {
1597 *oentry = HeNEXT(entry);
1598 if (first && !*oentry)
1599 HvFILL(hv)--; /* This linked list is now empty. */
1600 if (HvEITER_get(hv))
1603 hv_free_ent(hv, entry);
1607 HvTOTALKEYS(hv) -= (IV)HvPLACEHOLDERS_get(hv);
1608 if (HvKEYS(hv) == 0)
1609 HvHASKFLAGS_off(hv);
1610 HvPLACEHOLDERS_set(hv, 0);
1614 oentry = &HeNEXT(entry);
1619 /* You can't get here, hence assertion should always fail. */
1620 assert (items == 0);
1625 S_hfreeentries(pTHX_ HV *hv)
1627 register HE **array;
1631 struct xpvhv_aux *iter;
1637 iter = SvOOK(hv) ? HvAUX(hv) : 0;
1641 array = HvARRAY(hv);
1642 /* make everyone else think the array is empty, so that the destructors
1643 * called for freed entries can't recusively mess with us */
1644 HvARRAY(hv) = Null(HE**);
1645 SvFLAGS(hv) &= ~SVf_OOK;
1648 ((XPVHV*) SvANY(hv))->xhv_keys = 0;
1653 register HE *oentry = entry;
1654 entry = HeNEXT(entry);
1655 hv_free_ent(hv, oentry);
1660 entry = array[riter];
1665 /* Someone attempted to iterate or set the hash name while we had
1666 the array set to 0. */
1667 assert(HvARRAY(hv));
1669 if (HvAUX(hv)->xhv_name)
1670 unshare_hek_or_pvn(HvAUX(hv)->xhv_name, 0, 0, 0);
1671 /* SvOOK_off calls sv_backoff, which isn't correct. */
1673 Safefree(HvARRAY(hv));
1675 SvFLAGS(hv) &= ~SVf_OOK;
1678 /* FIXME - things will still go horribly wrong (or at least leak) if
1679 people attempt to add elements to the hash while we're undef()ing it */
1681 entry = iter->xhv_eiter; /* HvEITER(hv) */
1682 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1684 hv_free_ent(hv, entry);
1686 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1687 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1688 SvFLAGS(hv) |= SVf_OOK;
1691 HvARRAY(hv) = array;
1695 =for apidoc hv_undef
1703 Perl_hv_undef(pTHX_ HV *hv)
1705 register XPVHV* xhv;
1709 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1710 xhv = (XPVHV*)SvANY(hv);
1712 if ((name = HvNAME_get(hv))) {
1714 hv_delete(PL_stashcache, name, HvNAMELEN_get(hv), G_DISCARD);
1715 Perl_hv_name_set(aTHX_ hv, 0, 0, 0);
1717 SvFLAGS(hv) &= ~SVf_OOK;
1718 Safefree(HvARRAY(hv));
1719 xhv->xhv_max = 7; /* HvMAX(hv) = 7 (it's a normal hash) */
1721 HvPLACEHOLDERS_set(hv, 0);
1727 static struct xpvhv_aux*
1728 S_hv_auxinit(pTHX_ HV *hv) {
1729 struct xpvhv_aux *iter;
1733 Newz(0, array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1734 + sizeof(struct xpvhv_aux), char);
1736 array = (char *) HvARRAY(hv);
1737 Renew(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1738 + sizeof(struct xpvhv_aux), char);
1740 HvARRAY(hv) = (HE**) array;
1741 /* SvOOK_on(hv) attacks the IV flags. */
1742 SvFLAGS(hv) |= SVf_OOK;
1745 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1746 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1753 =for apidoc hv_iterinit
1755 Prepares a starting point to traverse a hash table. Returns the number of
1756 keys in the hash (i.e. the same as C<HvKEYS(tb)>). The return value is
1757 currently only meaningful for hashes without tie magic.
1759 NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
1760 hash buckets that happen to be in use. If you still need that esoteric
1761 value, you can get it through the macro C<HvFILL(tb)>.
1768 Perl_hv_iterinit(pTHX_ HV *hv)
1773 Perl_croak(aTHX_ "Bad hash");
1776 struct xpvhv_aux *iter = HvAUX(hv);
1777 entry = iter->xhv_eiter; /* HvEITER(hv) */
1778 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1780 hv_free_ent(hv, entry);
1782 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1783 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1785 S_hv_auxinit(aTHX_ hv);
1788 /* used to be xhv->xhv_fill before 5.004_65 */
1789 return HvTOTALKEYS(hv);
1793 Perl_hv_riter_p(pTHX_ HV *hv) {
1794 struct xpvhv_aux *iter;
1797 Perl_croak(aTHX_ "Bad hash");
1799 iter = SvOOK(hv) ? HvAUX(hv) : S_hv_auxinit(aTHX_ hv);
1800 return &(iter->xhv_riter);
1804 Perl_hv_eiter_p(pTHX_ HV *hv) {
1805 struct xpvhv_aux *iter;
1808 Perl_croak(aTHX_ "Bad hash");
1810 iter = SvOOK(hv) ? HvAUX(hv) : S_hv_auxinit(aTHX_ hv);
1811 return &(iter->xhv_eiter);
1815 Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
1816 struct xpvhv_aux *iter;
1819 Perl_croak(aTHX_ "Bad hash");
1827 iter = S_hv_auxinit(aTHX_ hv);
1829 iter->xhv_riter = riter;
1833 Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
1834 struct xpvhv_aux *iter;
1837 Perl_croak(aTHX_ "Bad hash");
1842 /* 0 is the default so don't go malloc()ing a new structure just to
1847 iter = S_hv_auxinit(aTHX_ hv);
1849 iter->xhv_eiter = eiter;
1853 Perl_hv_name_set(pTHX_ HV *hv, const char *name, I32 len, int flags)
1855 struct xpvhv_aux *iter;
1861 if (iter->xhv_name) {
1862 unshare_hek_or_pvn(iter->xhv_name, 0, 0, 0);
1868 iter = S_hv_auxinit(aTHX_ hv);
1870 PERL_HASH(hash, name, len);
1871 iter->xhv_name = name ? share_hek(name, len, hash) : 0;
1875 =for apidoc hv_iternext
1877 Returns entries from a hash iterator. See C<hv_iterinit>.
1879 You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
1880 iterator currently points to, without losing your place or invalidating your
1881 iterator. Note that in this case the current entry is deleted from the hash
1882 with your iterator holding the last reference to it. Your iterator is flagged
1883 to free the entry on the next call to C<hv_iternext>, so you must not discard
1884 your iterator immediately else the entry will leak - call C<hv_iternext> to
1885 trigger the resource deallocation.
1891 Perl_hv_iternext(pTHX_ HV *hv)
1893 return hv_iternext_flags(hv, 0);
1897 =for apidoc hv_iternext_flags
1899 Returns entries from a hash iterator. See C<hv_iterinit> and C<hv_iternext>.
1900 The C<flags> value will normally be zero; if HV_ITERNEXT_WANTPLACEHOLDERS is
1901 set the placeholders keys (for restricted hashes) will be returned in addition
1902 to normal keys. By default placeholders are automatically skipped over.
1903 Currently a placeholder is implemented with a value that is
1904 C<&Perl_sv_placeholder>. Note that the implementation of placeholders and
1905 restricted hashes may change, and the implementation currently is
1906 insufficiently abstracted for any change to be tidy.
1912 Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
1915 register XPVHV* xhv;
1919 struct xpvhv_aux *iter;
1922 Perl_croak(aTHX_ "Bad hash");
1923 xhv = (XPVHV*)SvANY(hv);
1926 /* Too many things (well, pp_each at least) merrily assume that you can
1927 call iv_iternext without calling hv_iterinit, so we'll have to deal
1933 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
1935 if ((mg = SvTIED_mg((SV*)hv, PERL_MAGIC_tied))) {
1936 SV *key = sv_newmortal();
1938 sv_setsv(key, HeSVKEY_force(entry));
1939 SvREFCNT_dec(HeSVKEY(entry)); /* get rid of previous key */
1945 /* one HE per MAGICAL hash */
1946 iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
1948 Newz(54, k, HEK_BASESIZE + sizeof(SV*), char);
1950 HeKEY_hek(entry) = hek;
1951 HeKLEN(entry) = HEf_SVKEY;
1953 magic_nextpack((SV*) hv,mg,key);
1955 /* force key to stay around until next time */
1956 HeSVKEY_set(entry, SvREFCNT_inc(key));
1957 return entry; /* beware, hent_val is not set */
1960 SvREFCNT_dec(HeVAL(entry));
1961 Safefree(HeKEY_hek(entry));
1963 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1966 #ifdef DYNAMIC_ENV_FETCH /* set up %ENV for iteration */
1967 if (!entry && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
1971 /* hv_iterint now ensures this. */
1972 assert (HvARRAY(hv));
1974 /* At start of hash, entry is NULL. */
1977 entry = HeNEXT(entry);
1978 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
1980 * Skip past any placeholders -- don't want to include them in
1983 while (entry && HeVAL(entry) == &PL_sv_placeholder) {
1984 entry = HeNEXT(entry);
1989 /* OK. Come to the end of the current list. Grab the next one. */
1991 iter->xhv_riter++; /* HvRITER(hv)++ */
1992 if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
1993 /* There is no next one. End of the hash. */
1994 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1997 entry = (HvARRAY(hv))[iter->xhv_riter];
1999 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2000 /* If we have an entry, but it's a placeholder, don't count it.
2002 while (entry && HeVAL(entry) == &PL_sv_placeholder)
2003 entry = HeNEXT(entry);
2005 /* Will loop again if this linked list starts NULL
2006 (for HV_ITERNEXT_WANTPLACEHOLDERS)
2007 or if we run through it and find only placeholders. */
2010 if (oldentry && HvLAZYDEL(hv)) { /* was deleted earlier? */
2012 hv_free_ent(hv, oldentry);
2015 /*if (HvREHASH(hv) && entry && !HeKREHASH(entry))
2016 PerlIO_printf(PerlIO_stderr(), "Awooga %p %p\n", hv, entry);*/
2018 iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
2023 =for apidoc hv_iterkey
2025 Returns the key from the current position of the hash iterator. See
2032 Perl_hv_iterkey(pTHX_ register HE *entry, I32 *retlen)
2034 if (HeKLEN(entry) == HEf_SVKEY) {
2036 char *p = SvPV(HeKEY_sv(entry), len);
2041 *retlen = HeKLEN(entry);
2042 return HeKEY(entry);
2046 /* unlike hv_iterval(), this always returns a mortal copy of the key */
2048 =for apidoc hv_iterkeysv
2050 Returns the key as an C<SV*> from the current position of the hash
2051 iterator. The return value will always be a mortal copy of the key. Also
2058 Perl_hv_iterkeysv(pTHX_ register HE *entry)
2060 return sv_2mortal(newSVhek(HeKEY_hek(entry)));
2064 =for apidoc hv_iterval
2066 Returns the value from the current position of the hash iterator. See
2073 Perl_hv_iterval(pTHX_ HV *hv, register HE *entry)
2075 if (SvRMAGICAL(hv)) {
2076 if (mg_find((SV*)hv, PERL_MAGIC_tied)) {
2077 SV* sv = sv_newmortal();
2078 if (HeKLEN(entry) == HEf_SVKEY)
2079 mg_copy((SV*)hv, sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
2081 mg_copy((SV*)hv, sv, HeKEY(entry), HeKLEN(entry));
2085 return HeVAL(entry);
2089 =for apidoc hv_iternextsv
2091 Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2098 Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
2101 if ( (he = hv_iternext_flags(hv, 0)) == NULL)
2103 *key = hv_iterkey(he, retlen);
2104 return hv_iterval(hv, he);
2108 =for apidoc hv_magic
2110 Adds magic to a hash. See C<sv_magic>.
2116 Perl_hv_magic(pTHX_ HV *hv, GV *gv, int how)
2118 sv_magic((SV*)hv, (SV*)gv, how, Nullch, 0);
2121 #if 0 /* use the macro from hv.h instead */
2124 Perl_sharepvn(pTHX_ const char *sv, I32 len, U32 hash)
2126 return HEK_KEY(share_hek(sv, len, hash));
2131 /* possibly free a shared string if no one has access to it
2132 * len and hash must both be valid for str.
2135 Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
2137 unshare_hek_or_pvn (NULL, str, len, hash);
2142 Perl_unshare_hek(pTHX_ HEK *hek)
2144 unshare_hek_or_pvn(hek, NULL, 0, 0);
2147 /* possibly free a shared string if no one has access to it
2148 hek if non-NULL takes priority over the other 3, else str, len and hash
2149 are used. If so, len and hash must both be valid for str.
2152 S_unshare_hek_or_pvn(pTHX_ const HEK *hek, const char *str, I32 len, U32 hash)
2154 register XPVHV* xhv;
2156 register HE **oentry;
2159 bool is_utf8 = FALSE;
2161 const char *save = str;
2162 struct shared_he *he = 0;
2165 /* Find the shared he which is just before us in memory. */
2166 he = (struct shared_he *)(((char *)hek)
2167 - STRUCT_OFFSET(struct shared_he,
2170 /* Assert that the caller passed us a genuine (or at least consistent)
2172 assert (he->shared_he_he.hent_hek == hek);
2173 hash = HEK_HASH(hek);
2174 } else if (len < 0) {
2175 STRLEN tmplen = -len;
2177 /* See the note in hv_fetch(). --jhi */
2178 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2181 k_flags = HVhek_UTF8;
2183 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2186 /* what follows is the moral equivalent of:
2187 if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
2188 if (--*Svp == Nullsv)
2189 hv_delete(PL_strtab, str, len, G_DISCARD, hash);
2191 xhv = (XPVHV*)SvANY(PL_strtab);
2192 /* assert(xhv_array != 0) */
2194 first = oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2196 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2197 if (HeKEY_hek(entry) != hek)
2203 const int flags_masked = k_flags & HVhek_MASK;
2204 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2205 if (HeHASH(entry) != hash) /* strings can't be equal */
2207 if (HeKLEN(entry) != len)
2209 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2211 if (HeKFLAGS(entry) != flags_masked)
2219 if (--HeVAL(entry) == Nullsv) {
2220 *oentry = HeNEXT(entry);
2222 /* There are now no entries in our slot. */
2223 xhv->xhv_fill--; /* HvFILL(hv)-- */
2226 xhv->xhv_keys--; /* HvKEYS(hv)-- */
2230 UNLOCK_STRTAB_MUTEX;
2231 if (!found && ckWARN_d(WARN_INTERNAL))
2232 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
2233 "Attempt to free non-existent shared string '%s'%s"
2235 hek ? HEK_KEY(hek) : str,
2236 ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
2237 if (k_flags & HVhek_FREEKEY)
2241 /* get a (constant) string ptr from the global string table
2242 * string will get added if it is not already there.
2243 * len and hash must both be valid for str.
2246 Perl_share_hek(pTHX_ const char *str, I32 len, register U32 hash)
2248 bool is_utf8 = FALSE;
2250 const char *save = str;
2253 STRLEN tmplen = -len;
2255 /* See the note in hv_fetch(). --jhi */
2256 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2258 /* If we were able to downgrade here, then than means that we were passed
2259 in a key which only had chars 0-255, but was utf8 encoded. */
2262 /* If we found we were able to downgrade the string to bytes, then
2263 we should flag that it needs upgrading on keys or each. Also flag
2264 that we need share_hek_flags to free the string. */
2266 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2269 return HeKEY_hek(share_hek_flags (str, len, hash, flags));
2273 S_share_hek_flags(pTHX_ const char *str, I32 len, register U32 hash, int flags)
2275 register XPVHV* xhv;
2277 register HE **oentry;
2279 const int flags_masked = flags & HVhek_MASK;
2281 /* what follows is the moral equivalent of:
2283 if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
2284 hv_store(PL_strtab, str, len, Nullsv, hash);
2286 Can't rehash the shared string table, so not sure if it's worth
2287 counting the number of entries in the linked list
2289 xhv = (XPVHV*)SvANY(PL_strtab);
2290 /* assert(xhv_array != 0) */
2292 oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2293 for (entry = *oentry; entry; entry = HeNEXT(entry)) {
2294 if (HeHASH(entry) != hash) /* strings can't be equal */
2296 if (HeKLEN(entry) != len)
2298 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2300 if (HeKFLAGS(entry) != flags_masked)
2306 /* What used to be head of the list.
2307 If this is NULL, then we're the first entry for this slot, which
2308 means we need to increate fill. */
2309 const HE *old_first = *oentry;
2310 struct shared_he *new_entry;
2314 /* We don't actually store a HE from the arena and a regular HEK.
2315 Instead we allocate one chunk of memory big enough for both,
2316 and put the HEK straight after the HE. This way we can find the
2317 HEK directly from the HE.
2320 New(0, k, STRUCT_OFFSET(struct shared_he,
2321 shared_he_hek.hek_key[0]) + len + 2, char);
2322 new_entry = (struct shared_he *)k;
2323 entry = &(new_entry->shared_he_he);
2324 hek = &(new_entry->shared_he_hek);
2326 Copy(str, HEK_KEY(hek), len, char);
2327 HEK_KEY(hek)[len] = 0;
2329 HEK_HASH(hek) = hash;
2330 HEK_FLAGS(hek) = (unsigned char)flags_masked;
2332 /* Still "point" to the HEK, so that other code need not know what
2334 HeKEY_hek(entry) = hek;
2335 HeVAL(entry) = Nullsv;
2336 HeNEXT(entry) = *oentry;
2339 xhv->xhv_keys++; /* HvKEYS(hv)++ */
2340 if (!old_first) { /* initial entry? */
2341 xhv->xhv_fill++; /* HvFILL(hv)++ */
2342 } else if (xhv->xhv_keys > (IV)xhv->xhv_max /* HvKEYS(hv) > HvMAX(hv) */) {
2347 ++HeVAL(entry); /* use value slot as REFCNT */
2348 UNLOCK_STRTAB_MUTEX;
2350 if (flags & HVhek_FREEKEY)
2357 Perl_hv_placeholders_p(pTHX_ HV *hv)
2360 MAGIC *mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2363 mg = sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, 0);
2366 Perl_die(aTHX_ "panic: hv_placeholders_p");
2369 return &(mg->mg_len);
2374 Perl_hv_placeholders_get(pTHX_ HV *hv)
2377 MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2379 return mg ? mg->mg_len : 0;
2383 Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
2386 MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2391 if (!sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, ph))
2392 Perl_die(aTHX_ "panic: hv_placeholders_set");
2394 /* else we don't need to add magic to record 0 placeholders. */
2398 =for apidoc hv_assert
2400 Check that a hash is in an internally consistent state.
2406 Perl_hv_assert(pTHX_ HV *hv)
2411 int placeholders = 0;
2414 const I32 riter = HvRITER_get(hv);
2415 HE *eiter = HvEITER_get(hv);
2417 (void)hv_iterinit(hv);
2419 while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
2420 /* sanity check the values */
2421 if (HeVAL(entry) == &PL_sv_placeholder) {
2426 /* sanity check the keys */
2427 if (HeSVKEY(entry)) {
2428 /* Don't know what to check on SV keys. */
2429 } else if (HeKUTF8(entry)) {
2431 if (HeKWASUTF8(entry)) {
2432 PerlIO_printf(Perl_debug_log,
2433 "hash key has both WASUFT8 and UTF8: '%.*s'\n",
2434 (int) HeKLEN(entry), HeKEY(entry));
2437 } else if (HeKWASUTF8(entry)) {
2441 if (!SvTIED_mg((SV*)hv, PERL_MAGIC_tied)) {
2442 if (HvUSEDKEYS(hv) != real) {
2443 PerlIO_printf(Perl_debug_log, "Count %d key(s), but hash reports %d\n",
2444 (int) real, (int) HvUSEDKEYS(hv));
2447 if (HvPLACEHOLDERS_get(hv) != placeholders) {
2448 PerlIO_printf(Perl_debug_log,
2449 "Count %d placeholder(s), but hash reports %d\n",
2450 (int) placeholders, (int) HvPLACEHOLDERS_get(hv));
2454 if (withflags && ! HvHASKFLAGS(hv)) {
2455 PerlIO_printf(Perl_debug_log,
2456 "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
2463 HvRITER_set(hv, riter); /* Restore hash iterator state */
2464 HvEITER_set(hv, eiter);
2469 * c-indentation-style: bsd
2471 * indent-tabs-mode: t
2474 * ex: set ts=8 sts=4 sw=4 noet: