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
36 static const char S_strtab_error[]
37 = "Cannot modify shared string table in hv_%s";
44 Newx(he, PERL_ARENA_SIZE/sizeof(HE), HE);
45 HeNEXT(he) = (HE*) PL_body_arenaroots[HE_SVSLOT];
46 PL_body_arenaroots[HE_SVSLOT] = he;
48 heend = &he[PERL_ARENA_SIZE / sizeof(HE) - 1];
49 PL_body_roots[HE_SVSLOT] = ++he;
51 HeNEXT(he) = (HE*)(he + 1);
59 #define new_HE() (HE*)safemalloc(sizeof(HE))
60 #define del_HE(p) safefree((char*)p)
68 void ** const root = &PL_body_roots[HE_SVSLOT];
79 #define new_HE() new_he()
83 HeNEXT(p) = (HE*)(PL_body_roots[HE_SVSLOT]); \
84 PL_body_roots[HE_SVSLOT] = p; \
93 S_save_hek_flags(pTHX_ const char *str, I32 len, U32 hash, int flags)
95 const int flags_masked = flags & HVhek_MASK;
99 Newx(k, HEK_BASESIZE + len + 2, char);
101 Copy(str, HEK_KEY(hek), len, char);
102 HEK_KEY(hek)[len] = 0;
104 HEK_HASH(hek) = hash;
105 HEK_FLAGS(hek) = (unsigned char)flags_masked;
107 if (flags & HVhek_FREEKEY)
112 /* free the pool of temporary HE/HEK pairs returned by hv_fetch_ent
116 Perl_free_tied_hv_pool(pTHX)
118 HE *he = PL_hv_fetch_ent_mh;
121 Safefree(HeKEY_hek(he));
125 PL_hv_fetch_ent_mh = Nullhe;
128 #if defined(USE_ITHREADS)
130 Perl_hek_dup(pTHX_ HEK *source, CLONE_PARAMS* param)
132 HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
134 PERL_UNUSED_ARG(param);
137 /* We already shared this hash key. */
138 (void)share_hek_hek(shared);
142 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
143 HEK_HASH(source), HEK_FLAGS(source));
144 ptr_table_store(PL_ptr_table, source, shared);
150 Perl_he_dup(pTHX_ const HE *e, bool shared, CLONE_PARAMS* param)
156 /* look for it in the table first */
157 ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
161 /* create anew and remember what it is */
163 ptr_table_store(PL_ptr_table, e, ret);
165 HeNEXT(ret) = he_dup(HeNEXT(e),shared, param);
166 if (HeKLEN(e) == HEf_SVKEY) {
168 Newx(k, HEK_BASESIZE + sizeof(SV*), char);
169 HeKEY_hek(ret) = (HEK*)k;
170 HeKEY_sv(ret) = SvREFCNT_inc(sv_dup(HeKEY_sv(e), param));
173 /* This is hek_dup inlined, which seems to be important for speed
175 HEK * const source = HeKEY_hek(e);
176 HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
179 /* We already shared this hash key. */
180 (void)share_hek_hek(shared);
184 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
185 HEK_HASH(source), HEK_FLAGS(source));
186 ptr_table_store(PL_ptr_table, source, shared);
188 HeKEY_hek(ret) = shared;
191 HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
193 HeVAL(ret) = SvREFCNT_inc(sv_dup(HeVAL(e), param));
196 #endif /* USE_ITHREADS */
199 S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
202 SV * const sv = sv_newmortal();
203 if (!(flags & HVhek_FREEKEY)) {
204 sv_setpvn(sv, key, klen);
207 /* Need to free saved eventually assign to mortal SV */
208 /* XXX is this line an error ???: SV *sv = sv_newmortal(); */
209 sv_usepvn(sv, (char *) key, klen);
211 if (flags & HVhek_UTF8) {
214 Perl_croak(aTHX_ msg, sv);
217 /* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
220 #define HV_FETCH_ISSTORE 0x01
221 #define HV_FETCH_ISEXISTS 0x02
222 #define HV_FETCH_LVALUE 0x04
223 #define HV_FETCH_JUST_SV 0x08
228 Stores an SV in a hash. The hash key is specified as C<key> and C<klen> is
229 the length of the key. The C<hash> parameter is the precomputed hash
230 value; if it is zero then Perl will compute it. The return value will be
231 NULL if the operation failed or if the value did not need to be actually
232 stored within the hash (as in the case of tied hashes). Otherwise it can
233 be dereferenced to get the original C<SV*>. Note that the caller is
234 responsible for suitably incrementing the reference count of C<val> before
235 the call, and decrementing it if the function returned NULL. Effectively
236 a successful hv_store takes ownership of one reference to C<val>. This is
237 usually what you want; a newly created SV has a reference count of one, so
238 if all your code does is create SVs then store them in a hash, hv_store
239 will own the only reference to the new SV, and your code doesn't need to do
240 anything further to tidy up. hv_store is not implemented as a call to
241 hv_store_ent, and does not create a temporary SV for the key, so if your
242 key data is not already in SV form then use hv_store in preference to
245 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
246 information on how to use this function on tied hashes.
252 Perl_hv_store(pTHX_ HV *hv, const char *key, I32 klen_i32, SV *val, U32 hash)
265 hek = hv_fetch_common (hv, NULL, key, klen, flags,
266 (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
267 return hek ? &HeVAL(hek) : NULL;
270 /* XXX This looks like an ideal candidate to inline */
272 Perl_hv_store_flags(pTHX_ HV *hv, const char *key, I32 klen, SV *val,
273 register U32 hash, int flags)
275 HE * const hek = hv_fetch_common (hv, NULL, key, klen, flags,
276 (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
277 return hek ? &HeVAL(hek) : NULL;
281 =for apidoc hv_store_ent
283 Stores C<val> in a hash. The hash key is specified as C<key>. The C<hash>
284 parameter is the precomputed hash value; if it is zero then Perl will
285 compute it. The return value is the new hash entry so created. It will be
286 NULL if the operation failed or if the value did not need to be actually
287 stored within the hash (as in the case of tied hashes). Otherwise the
288 contents of the return value can be accessed using the C<He?> macros
289 described here. Note that the caller is responsible for suitably
290 incrementing the reference count of C<val> before the call, and
291 decrementing it if the function returned NULL. Effectively a successful
292 hv_store_ent takes ownership of one reference to C<val>. This is
293 usually what you want; a newly created SV has a reference count of one, so
294 if all your code does is create SVs then store them in a hash, hv_store
295 will own the only reference to the new SV, and your code doesn't need to do
296 anything further to tidy up. Note that hv_store_ent only reads the C<key>;
297 unlike C<val> it does not take ownership of it, so maintaining the correct
298 reference count on C<key> is entirely the caller's responsibility. hv_store
299 is not implemented as a call to hv_store_ent, and does not create a temporary
300 SV for the key, so if your key data is not already in SV form then use
301 hv_store in preference to hv_store_ent.
303 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
304 information on how to use this function on tied hashes.
309 /* XXX This looks like an ideal candidate to inline */
311 Perl_hv_store_ent(pTHX_ HV *hv, SV *keysv, SV *val, U32 hash)
313 return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISSTORE, val, hash);
317 =for apidoc hv_exists
319 Returns a boolean indicating whether the specified hash key exists. The
320 C<klen> is the length of the key.
326 Perl_hv_exists(pTHX_ HV *hv, const char *key, I32 klen_i32)
338 return hv_fetch_common(hv, NULL, key, klen, flags, HV_FETCH_ISEXISTS, 0, 0)
345 Returns the SV which corresponds to the specified key in the hash. The
346 C<klen> is the length of the key. If C<lval> is set then the fetch will be
347 part of a store. Check that the return value is non-null before
348 dereferencing it to an C<SV*>.
350 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
351 information on how to use this function on tied hashes.
357 Perl_hv_fetch(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 lval)
370 hek = hv_fetch_common (hv, NULL, key, klen, flags,
371 lval ? (HV_FETCH_JUST_SV | HV_FETCH_LVALUE) : HV_FETCH_JUST_SV,
373 return hek ? &HeVAL(hek) : NULL;
377 =for apidoc hv_exists_ent
379 Returns a boolean indicating whether the specified hash key exists. C<hash>
380 can be a valid precomputed hash value, or 0 to ask for it to be
386 /* XXX This looks like an ideal candidate to inline */
388 Perl_hv_exists_ent(pTHX_ HV *hv, SV *keysv, U32 hash)
390 return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISEXISTS, 0, hash)
394 /* returns an HE * structure with the all fields set */
395 /* note that hent_val will be a mortal sv for MAGICAL hashes */
397 =for apidoc hv_fetch_ent
399 Returns the hash entry which corresponds to the specified key in the hash.
400 C<hash> must be a valid precomputed hash number for the given C<key>, or 0
401 if you want the function to compute it. IF C<lval> is set then the fetch
402 will be part of a store. Make sure the return value is non-null before
403 accessing it. The return value when C<tb> is a tied hash is a pointer to a
404 static location, so be sure to make a copy of the structure if you need to
407 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
408 information on how to use this function on tied hashes.
414 Perl_hv_fetch_ent(pTHX_ HV *hv, SV *keysv, I32 lval, register U32 hash)
416 return hv_fetch_common(hv, keysv, NULL, 0, 0,
417 (lval ? HV_FETCH_LVALUE : 0), Nullsv, hash);
421 S_hv_fetch_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
422 int flags, int action, SV *val, register U32 hash)
436 if (flags & HVhek_FREEKEY)
438 key = SvPV_const(keysv, klen);
440 is_utf8 = (SvUTF8(keysv) != 0);
442 is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
445 xhv = (XPVHV*)SvANY(hv);
447 if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS)))
449 if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
452 /* XXX should be able to skimp on the HE/HEK here when
453 HV_FETCH_JUST_SV is true. */
456 keysv = newSVpvn(key, klen);
461 keysv = newSVsv(keysv);
463 mg_copy((SV*)hv, sv, (char *)keysv, HEf_SVKEY);
465 /* grab a fake HE/HEK pair from the pool or make a new one */
466 entry = PL_hv_fetch_ent_mh;
468 PL_hv_fetch_ent_mh = HeNEXT(entry);
472 Newx(k, HEK_BASESIZE + sizeof(SV*), char);
473 HeKEY_hek(entry) = (HEK*)k;
475 HeNEXT(entry) = Nullhe;
476 HeSVKEY_set(entry, keysv);
478 sv_upgrade(sv, SVt_PVLV);
480 /* so we can free entry when freeing sv */
481 LvTARG(sv) = (SV*)entry;
483 /* XXX remove at some point? */
484 if (flags & HVhek_FREEKEY)
489 #ifdef ENV_IS_CASELESS
490 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
492 for (i = 0; i < klen; ++i)
493 if (isLOWER(key[i])) {
494 /* Would be nice if we had a routine to do the
495 copy and upercase in a single pass through. */
496 const char * const nkey = strupr(savepvn(key,klen));
497 /* Note that this fetch is for nkey (the uppercased
498 key) whereas the store is for key (the original) */
499 entry = hv_fetch_common(hv, Nullsv, nkey, klen,
500 HVhek_FREEKEY, /* free nkey */
501 0 /* non-LVAL fetch */,
502 Nullsv /* no value */,
503 0 /* compute hash */);
504 if (!entry && (action & HV_FETCH_LVALUE)) {
505 /* This call will free key if necessary.
506 Do it this way to encourage compiler to tail
508 entry = hv_fetch_common(hv, keysv, key, klen,
509 flags, HV_FETCH_ISSTORE,
512 if (flags & HVhek_FREEKEY)
520 else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
521 if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
522 /* I don't understand why hv_exists_ent has svret and sv,
523 whereas hv_exists only had one. */
524 SV * const svret = sv_newmortal();
527 if (keysv || is_utf8) {
529 keysv = newSVpvn(key, klen);
532 keysv = newSVsv(keysv);
534 mg_copy((SV*)hv, sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
536 mg_copy((SV*)hv, sv, key, klen);
538 if (flags & HVhek_FREEKEY)
540 magic_existspack(svret, mg_find(sv, PERL_MAGIC_tiedelem));
541 /* This cast somewhat evil, but I'm merely using NULL/
542 not NULL to return the boolean exists.
543 And I know hv is not NULL. */
544 return SvTRUE(svret) ? (HE *)hv : NULL;
546 #ifdef ENV_IS_CASELESS
547 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
548 /* XXX This code isn't UTF8 clean. */
549 char * const keysave = (char * const)key;
550 /* Will need to free this, so set FREEKEY flag. */
551 key = savepvn(key,klen);
552 key = (const char*)strupr((char*)key);
557 if (flags & HVhek_FREEKEY) {
560 flags |= HVhek_FREEKEY;
564 else if (action & HV_FETCH_ISSTORE) {
567 hv_magic_check (hv, &needs_copy, &needs_store);
569 const bool save_taint = PL_tainted;
570 if (keysv || is_utf8) {
572 keysv = newSVpvn(key, klen);
576 PL_tainted = SvTAINTED(keysv);
577 keysv = sv_2mortal(newSVsv(keysv));
578 mg_copy((SV*)hv, val, (char*)keysv, HEf_SVKEY);
580 mg_copy((SV*)hv, val, key, klen);
583 TAINT_IF(save_taint);
584 if (!HvARRAY(hv) && !needs_store) {
585 if (flags & HVhek_FREEKEY)
589 #ifdef ENV_IS_CASELESS
590 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
591 /* XXX This code isn't UTF8 clean. */
592 const char *keysave = key;
593 /* Will need to free this, so set FREEKEY flag. */
594 key = savepvn(key,klen);
595 key = (const char*)strupr((char*)key);
600 if (flags & HVhek_FREEKEY) {
603 flags |= HVhek_FREEKEY;
611 if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
612 #ifdef DYNAMIC_ENV_FETCH /* if it's an %ENV lookup, we may get it on the fly */
613 || (SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
618 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
620 HvARRAY(hv) = (HE**)array;
622 #ifdef DYNAMIC_ENV_FETCH
623 else if (action & HV_FETCH_ISEXISTS) {
624 /* for an %ENV exists, if we do an insert it's by a recursive
625 store call, so avoid creating HvARRAY(hv) right now. */
629 /* XXX remove at some point? */
630 if (flags & HVhek_FREEKEY)
638 char * const keysave = (char * const)key;
639 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
643 flags &= ~HVhek_UTF8;
644 if (key != keysave) {
645 if (flags & HVhek_FREEKEY)
647 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
652 PERL_HASH_INTERNAL(hash, key, klen);
653 /* We don't have a pointer to the hv, so we have to replicate the
654 flag into every HEK, so that hv_iterkeysv can see it. */
655 /* And yes, you do need this even though you are not "storing" because
656 you can flip the flags below if doing an lval lookup. (And that
657 was put in to give the semantics Andreas was expecting.) */
658 flags |= HVhek_REHASH;
660 if (keysv && (SvIsCOW_shared_hash(keysv))) {
661 hash = SvSHARED_HASH(keysv);
663 PERL_HASH(hash, key, klen);
667 masked_flags = (flags & HVhek_MASK);
669 #ifdef DYNAMIC_ENV_FETCH
670 if (!HvARRAY(hv)) entry = Null(HE*);
674 entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
676 for (; entry; entry = HeNEXT(entry)) {
677 if (HeHASH(entry) != hash) /* strings can't be equal */
679 if (HeKLEN(entry) != (I32)klen)
681 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
683 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
686 if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
687 if (HeKFLAGS(entry) != masked_flags) {
688 /* We match if HVhek_UTF8 bit in our flags and hash key's
689 match. But if entry was set previously with HVhek_WASUTF8
690 and key now doesn't (or vice versa) then we should change
691 the key's flag, as this is assignment. */
692 if (HvSHAREKEYS(hv)) {
693 /* Need to swap the key we have for a key with the flags we
694 need. As keys are shared we can't just write to the
695 flag, so we share the new one, unshare the old one. */
696 HEK *new_hek = share_hek_flags(key, klen, hash,
698 unshare_hek (HeKEY_hek(entry));
699 HeKEY_hek(entry) = new_hek;
701 else if (hv == PL_strtab) {
702 /* PL_strtab is usually the only hash without HvSHAREKEYS,
703 so putting this test here is cheap */
704 if (flags & HVhek_FREEKEY)
706 Perl_croak(aTHX_ S_strtab_error,
707 action & HV_FETCH_LVALUE ? "fetch" : "store");
710 HeKFLAGS(entry) = masked_flags;
711 if (masked_flags & HVhek_ENABLEHVKFLAGS)
714 if (HeVAL(entry) == &PL_sv_placeholder) {
715 /* yes, can store into placeholder slot */
716 if (action & HV_FETCH_LVALUE) {
718 /* This preserves behaviour with the old hv_fetch
719 implementation which at this point would bail out
720 with a break; (at "if we find a placeholder, we
721 pretend we haven't found anything")
723 That break mean that if a placeholder were found, it
724 caused a call into hv_store, which in turn would
725 check magic, and if there is no magic end up pretty
726 much back at this point (in hv_store's code). */
729 /* LVAL fetch which actaully needs a store. */
731 HvPLACEHOLDERS(hv)--;
734 if (val != &PL_sv_placeholder)
735 HvPLACEHOLDERS(hv)--;
738 } else if (action & HV_FETCH_ISSTORE) {
739 SvREFCNT_dec(HeVAL(entry));
742 } else if (HeVAL(entry) == &PL_sv_placeholder) {
743 /* if we find a placeholder, we pretend we haven't found
747 if (flags & HVhek_FREEKEY)
751 #ifdef DYNAMIC_ENV_FETCH /* %ENV lookup? If so, try to fetch the value now */
752 if (!(action & HV_FETCH_ISSTORE)
753 && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
755 const char * const env = PerlEnv_ENVgetenv_len(key,&len);
757 sv = newSVpvn(env,len);
759 return hv_fetch_common(hv,keysv,key,klen,flags,HV_FETCH_ISSTORE,sv,
765 if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
766 hv_notallowed(flags, key, klen,
767 "Attempt to access disallowed key '%"SVf"' in"
768 " a restricted hash");
770 if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
771 /* Not doing some form of store, so return failure. */
772 if (flags & HVhek_FREEKEY)
776 if (action & HV_FETCH_LVALUE) {
779 /* At this point the old hv_fetch code would call to hv_store,
780 which in turn might do some tied magic. So we need to make that
781 magic check happen. */
782 /* gonna assign to this, so it better be there */
783 return hv_fetch_common(hv, keysv, key, klen, flags,
784 HV_FETCH_ISSTORE, val, hash);
785 /* XXX Surely that could leak if the fetch-was-store fails?
786 Just like the hv_fetch. */
790 /* Welcome to hv_store... */
793 /* Not sure if we can get here. I think the only case of oentry being
794 NULL is for %ENV with dynamic env fetch. But that should disappear
795 with magic in the previous code. */
798 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
800 HvARRAY(hv) = (HE**)array;
803 oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
806 /* share_hek_flags will do the free for us. This might be considered
809 HeKEY_hek(entry) = share_hek_flags(key, klen, hash, flags);
810 else if (hv == PL_strtab) {
811 /* PL_strtab is usually the only hash without HvSHAREKEYS, so putting
812 this test here is cheap */
813 if (flags & HVhek_FREEKEY)
815 Perl_croak(aTHX_ S_strtab_error,
816 action & HV_FETCH_LVALUE ? "fetch" : "store");
818 else /* gotta do the real thing */
819 HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
821 HeNEXT(entry) = *oentry;
824 if (val == &PL_sv_placeholder)
825 HvPLACEHOLDERS(hv)++;
826 if (masked_flags & HVhek_ENABLEHVKFLAGS)
830 const HE *counter = HeNEXT(entry);
832 xhv->xhv_keys++; /* HvKEYS(hv)++ */
833 if (!counter) { /* initial entry? */
834 xhv->xhv_fill++; /* HvFILL(hv)++ */
835 } else if (xhv->xhv_keys > (IV)xhv->xhv_max) {
837 } else if(!HvREHASH(hv)) {
840 while ((counter = HeNEXT(counter)))
843 if (n_links > HV_MAX_LENGTH_BEFORE_SPLIT) {
844 /* Use only the old HvKEYS(hv) > HvMAX(hv) condition to limit
845 bucket splits on a rehashed hash, as we're not going to
846 split it again, and if someone is lucky (evil) enough to
847 get all the keys in one list they could exhaust our memory
848 as we repeatedly double the number of buckets on every
849 entry. Linear search feels a less worse thing to do. */
859 S_hv_magic_check(pTHX_ HV *hv, bool *needs_copy, bool *needs_store)
861 const MAGIC *mg = SvMAGIC(hv);
865 if (isUPPER(mg->mg_type)) {
867 if (mg->mg_type == PERL_MAGIC_tied) {
868 *needs_store = FALSE;
869 return; /* We've set all there is to set. */
872 mg = mg->mg_moremagic;
877 =for apidoc hv_scalar
879 Evaluates the hash in scalar context and returns the result. Handles magic when the hash is tied.
885 Perl_hv_scalar(pTHX_ HV *hv)
889 if (SvRMAGICAL(hv)) {
890 MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_tied);
892 return magic_scalarpack(hv, mg);
897 Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
898 (long)HvFILL(hv), (long)HvMAX(hv) + 1);
906 =for apidoc hv_delete
908 Deletes a key/value pair in the hash. The value SV is removed from the
909 hash and returned to the caller. The C<klen> is the length of the key.
910 The C<flags> value will normally be zero; if set to G_DISCARD then NULL
917 Perl_hv_delete(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 flags)
924 k_flags |= HVhek_UTF8;
928 return hv_delete_common(hv, NULL, key, klen, k_flags, flags, 0);
932 =for apidoc hv_delete_ent
934 Deletes a key/value pair in the hash. The value SV is removed from the
935 hash and returned to the caller. The C<flags> value will normally be zero;
936 if set to G_DISCARD then NULL will be returned. C<hash> can be a valid
937 precomputed hash value, or 0 to ask for it to be computed.
942 /* XXX This looks like an ideal candidate to inline */
944 Perl_hv_delete_ent(pTHX_ HV *hv, SV *keysv, I32 flags, U32 hash)
946 return hv_delete_common(hv, keysv, NULL, 0, 0, flags, hash);
950 S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
951 int k_flags, I32 d_flags, U32 hash)
956 register HE **oentry;
957 HE *const *first_entry;
966 if (k_flags & HVhek_FREEKEY)
968 key = SvPV_const(keysv, klen);
970 is_utf8 = (SvUTF8(keysv) != 0);
972 is_utf8 = ((k_flags & HVhek_UTF8) ? TRUE : FALSE);
975 if (SvRMAGICAL(hv)) {
978 hv_magic_check (hv, &needs_copy, &needs_store);
981 entry = hv_fetch_common(hv, keysv, key, klen,
982 k_flags & ~HVhek_FREEKEY, HV_FETCH_LVALUE,
984 sv = entry ? HeVAL(entry) : NULL;
990 if (mg_find(sv, PERL_MAGIC_tiedelem)) {
991 /* No longer an element */
992 sv_unmagic(sv, PERL_MAGIC_tiedelem);
995 return Nullsv; /* element cannot be deleted */
997 #ifdef ENV_IS_CASELESS
998 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
999 /* XXX This code isn't UTF8 clean. */
1000 keysv = sv_2mortal(newSVpvn(key,klen));
1001 if (k_flags & HVhek_FREEKEY) {
1004 key = strupr(SvPVX(keysv));
1013 xhv = (XPVHV*)SvANY(hv);
1018 const char * const keysave = key;
1019 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
1022 k_flags |= HVhek_UTF8;
1024 k_flags &= ~HVhek_UTF8;
1025 if (key != keysave) {
1026 if (k_flags & HVhek_FREEKEY) {
1027 /* This shouldn't happen if our caller does what we expect,
1028 but strictly the API allows it. */
1031 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
1033 HvHASKFLAGS_on((SV*)hv);
1037 PERL_HASH_INTERNAL(hash, key, klen);
1039 if (keysv && (SvIsCOW_shared_hash(keysv))) {
1040 hash = SvSHARED_HASH(keysv);
1042 PERL_HASH(hash, key, klen);
1046 masked_flags = (k_flags & HVhek_MASK);
1048 first_entry = oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
1050 for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
1051 if (HeHASH(entry) != hash) /* strings can't be equal */
1053 if (HeKLEN(entry) != (I32)klen)
1055 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
1057 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
1060 if (hv == PL_strtab) {
1061 if (k_flags & HVhek_FREEKEY)
1063 Perl_croak(aTHX_ S_strtab_error, "delete");
1066 /* if placeholder is here, it's already been deleted.... */
1067 if (HeVAL(entry) == &PL_sv_placeholder)
1069 if (k_flags & HVhek_FREEKEY)
1073 else if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1074 S_hv_notallowed(aTHX_ k_flags, key, klen,
1075 "Attempt to delete readonly key '%"SVf"' from"
1076 " a restricted hash");
1078 if (k_flags & HVhek_FREEKEY)
1081 if (d_flags & G_DISCARD)
1084 sv = sv_2mortal(HeVAL(entry));
1085 HeVAL(entry) = &PL_sv_placeholder;
1089 * If a restricted hash, rather than really deleting the entry, put
1090 * a placeholder there. This marks the key as being "approved", so
1091 * we can still access via not-really-existing key without raising
1094 if (SvREADONLY(hv)) {
1095 SvREFCNT_dec(HeVAL(entry));
1096 HeVAL(entry) = &PL_sv_placeholder;
1097 /* We'll be saving this slot, so the number of allocated keys
1098 * doesn't go down, but the number placeholders goes up */
1099 HvPLACEHOLDERS(hv)++;
1101 *oentry = HeNEXT(entry);
1103 xhv->xhv_fill--; /* HvFILL(hv)-- */
1105 if (SvOOK(hv) && entry == HvAUX(hv)->xhv_eiter /* HvEITER(hv) */)
1108 hv_free_ent(hv, entry);
1109 xhv->xhv_keys--; /* HvKEYS(hv)-- */
1110 if (xhv->xhv_keys == 0)
1111 HvHASKFLAGS_off(hv);
1115 if (SvREADONLY(hv)) {
1116 S_hv_notallowed(aTHX_ k_flags, key, klen,
1117 "Attempt to delete disallowed key '%"SVf"' from"
1118 " a restricted hash");
1121 if (k_flags & HVhek_FREEKEY)
1127 S_hsplit(pTHX_ HV *hv)
1129 register XPVHV* xhv = (XPVHV*)SvANY(hv);
1130 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1131 register I32 newsize = oldsize * 2;
1133 char *a = (char*) HvARRAY(hv);
1135 register HE **oentry;
1136 int longest_chain = 0;
1139 /*PerlIO_printf(PerlIO_stderr(), "hsplit called for %p which had %d\n",
1140 hv, (int) oldsize);*/
1142 if (HvPLACEHOLDERS_get(hv) && !SvREADONLY(hv)) {
1143 /* Can make this clear any placeholders first for non-restricted hashes,
1144 even though Storable rebuilds restricted hashes by putting in all the
1145 placeholders (first) before turning on the readonly flag, because
1146 Storable always pre-splits the hash. */
1147 hv_clear_placeholders(hv);
1151 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1152 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1153 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1159 Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1162 Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1163 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1168 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1170 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1172 if (oldsize >= 64) {
1173 offer_nice_chunk(HvARRAY(hv),
1174 PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
1175 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
1178 Safefree(HvARRAY(hv));
1182 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1183 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
1184 HvARRAY(hv) = (HE**) a;
1187 for (i=0; i<oldsize; i++,aep++) {
1188 int left_length = 0;
1189 int right_length = 0;
1193 if (!*aep) /* non-existent */
1196 for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1197 if ((HeHASH(entry) & newsize) != (U32)i) {
1198 *oentry = HeNEXT(entry);
1199 HeNEXT(entry) = *bep;
1201 xhv->xhv_fill++; /* HvFILL(hv)++ */
1207 oentry = &HeNEXT(entry);
1211 if (!*aep) /* everything moved */
1212 xhv->xhv_fill--; /* HvFILL(hv)-- */
1213 /* I think we don't actually need to keep track of the longest length,
1214 merely flag if anything is too long. But for the moment while
1215 developing this code I'll track it. */
1216 if (left_length > longest_chain)
1217 longest_chain = left_length;
1218 if (right_length > longest_chain)
1219 longest_chain = right_length;
1223 /* Pick your policy for "hashing isn't working" here: */
1224 if (longest_chain <= HV_MAX_LENGTH_BEFORE_SPLIT /* split worked? */
1229 if (hv == PL_strtab) {
1230 /* Urg. Someone is doing something nasty to the string table.
1235 /* Awooga. Awooga. Pathological data. */
1236 /*PerlIO_printf(PerlIO_stderr(), "%p %d of %d with %d/%d buckets\n", hv,
1237 longest_chain, HvTOTALKEYS(hv), HvFILL(hv), 1+HvMAX(hv));*/
1240 Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1241 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1243 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1246 was_shared = HvSHAREKEYS(hv);
1249 HvSHAREKEYS_off(hv);
1254 for (i=0; i<newsize; i++,aep++) {
1255 register HE *entry = *aep;
1257 /* We're going to trash this HE's next pointer when we chain it
1258 into the new hash below, so store where we go next. */
1259 HE * const next = HeNEXT(entry);
1264 PERL_HASH_INTERNAL(hash, HeKEY(entry), HeKLEN(entry));
1269 = save_hek_flags(HeKEY(entry), HeKLEN(entry),
1270 hash, HeKFLAGS(entry));
1271 unshare_hek (HeKEY_hek(entry));
1272 HeKEY_hek(entry) = new_hek;
1274 /* Not shared, so simply write the new hash in. */
1275 HeHASH(entry) = hash;
1277 /*PerlIO_printf(PerlIO_stderr(), "%d ", HeKFLAGS(entry));*/
1278 HEK_REHASH_on(HeKEY_hek(entry));
1279 /*PerlIO_printf(PerlIO_stderr(), "%d\n", HeKFLAGS(entry));*/
1281 /* Copy oentry to the correct new chain. */
1282 bep = ((HE**)a) + (hash & (I32) xhv->xhv_max);
1284 xhv->xhv_fill++; /* HvFILL(hv)++ */
1285 HeNEXT(entry) = *bep;
1291 Safefree (HvARRAY(hv));
1292 HvARRAY(hv) = (HE **)a;
1296 Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
1298 register XPVHV* xhv = (XPVHV*)SvANY(hv);
1299 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1300 register I32 newsize;
1305 register HE **oentry;
1307 newsize = (I32) newmax; /* possible truncation here */
1308 if (newsize != newmax || newmax <= oldsize)
1310 while ((newsize & (1 + ~newsize)) != newsize) {
1311 newsize &= ~(newsize & (1 + ~newsize)); /* get proper power of 2 */
1313 if (newsize < newmax)
1315 if (newsize < newmax)
1316 return; /* overflow detection */
1318 a = (char *) HvARRAY(hv);
1321 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1322 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1323 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1329 Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1332 Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1333 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1338 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1340 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1342 if (oldsize >= 64) {
1343 offer_nice_chunk(HvARRAY(hv),
1344 PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
1345 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
1348 Safefree(HvARRAY(hv));
1351 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1354 Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1356 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
1357 HvARRAY(hv) = (HE **) a;
1358 if (!xhv->xhv_fill /* !HvFILL(hv) */) /* skip rest if no entries */
1362 for (i=0; i<oldsize; i++,aep++) {
1363 if (!*aep) /* non-existent */
1365 for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1367 if ((j = (HeHASH(entry) & newsize)) != i) {
1369 *oentry = HeNEXT(entry);
1370 if (!(HeNEXT(entry) = aep[j]))
1371 xhv->xhv_fill++; /* HvFILL(hv)++ */
1376 oentry = &HeNEXT(entry);
1378 if (!*aep) /* everything moved */
1379 xhv->xhv_fill--; /* HvFILL(hv)-- */
1386 Creates a new HV. The reference count is set to 1.
1394 register XPVHV* xhv;
1395 HV * const hv = (HV*)NEWSV(502,0);
1397 sv_upgrade((SV *)hv, SVt_PVHV);
1398 xhv = (XPVHV*)SvANY(hv);
1401 #ifndef NODEFAULT_SHAREKEYS
1402 HvSHAREKEYS_on(hv); /* key-sharing on by default */
1405 xhv->xhv_max = 7; /* HvMAX(hv) = 7 (start with 8 buckets) */
1406 xhv->xhv_fill = 0; /* HvFILL(hv) = 0 */
1411 Perl_newHVhv(pTHX_ HV *ohv)
1413 HV * const hv = newHV();
1414 STRLEN hv_max, hv_fill;
1416 if (!ohv || (hv_fill = HvFILL(ohv)) == 0)
1418 hv_max = HvMAX(ohv);
1420 if (!SvMAGICAL((SV *)ohv)) {
1421 /* It's an ordinary hash, so copy it fast. AMS 20010804 */
1423 const bool shared = !!HvSHAREKEYS(ohv);
1424 HE **ents, ** const oents = (HE **)HvARRAY(ohv);
1426 Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
1429 /* In each bucket... */
1430 for (i = 0; i <= hv_max; i++) {
1431 HE *prev = NULL, *ent = NULL;
1432 HE *oent = oents[i];
1439 /* Copy the linked list of entries. */
1440 for (; oent; oent = HeNEXT(oent)) {
1441 const U32 hash = HeHASH(oent);
1442 const char * const key = HeKEY(oent);
1443 const STRLEN len = HeKLEN(oent);
1444 const int flags = HeKFLAGS(oent);
1447 HeVAL(ent) = newSVsv(HeVAL(oent));
1449 = shared ? share_hek_flags(key, len, hash, flags)
1450 : save_hek_flags(key, len, hash, flags);
1461 HvFILL(hv) = hv_fill;
1462 HvTOTALKEYS(hv) = HvTOTALKEYS(ohv);
1466 /* Iterate over ohv, copying keys and values one at a time. */
1468 const I32 riter = HvRITER_get(ohv);
1469 HE * const eiter = HvEITER_get(ohv);
1471 /* Can we use fewer buckets? (hv_max is always 2^n-1) */
1472 while (hv_max && hv_max + 1 >= hv_fill * 2)
1473 hv_max = hv_max / 2;
1477 while ((entry = hv_iternext_flags(ohv, 0))) {
1478 hv_store_flags(hv, HeKEY(entry), HeKLEN(entry),
1479 newSVsv(HeVAL(entry)), HeHASH(entry),
1482 HvRITER_set(ohv, riter);
1483 HvEITER_set(ohv, eiter);
1490 Perl_hv_free_ent(pTHX_ HV *hv, register HE *entry)
1497 if (val && isGV(val) && GvCVu(val) && HvNAME_get(hv))
1498 PL_sub_generation++; /* may be deletion of method from stash */
1500 if (HeKLEN(entry) == HEf_SVKEY) {
1501 SvREFCNT_dec(HeKEY_sv(entry));
1502 Safefree(HeKEY_hek(entry));
1504 else if (HvSHAREKEYS(hv))
1505 unshare_hek(HeKEY_hek(entry));
1507 Safefree(HeKEY_hek(entry));
1512 Perl_hv_delayfree_ent(pTHX_ HV *hv, register HE *entry)
1516 /* SvREFCNT_inc to counter the SvREFCNT_dec in hv_free_ent */
1517 sv_2mortal(SvREFCNT_inc(HeVAL(entry))); /* free between statements */
1518 if (HeKLEN(entry) == HEf_SVKEY) {
1519 sv_2mortal(SvREFCNT_inc(HeKEY_sv(entry)));
1521 hv_free_ent(hv, entry);
1525 =for apidoc hv_clear
1527 Clears a hash, making it empty.
1533 Perl_hv_clear(pTHX_ HV *hv)
1536 register XPVHV* xhv;
1540 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1542 xhv = (XPVHV*)SvANY(hv);
1544 if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
1545 /* restricted hash: convert all keys to placeholders */
1547 for (i = 0; i <= xhv->xhv_max; i++) {
1548 HE *entry = (HvARRAY(hv))[i];
1549 for (; entry; entry = HeNEXT(entry)) {
1550 /* not already placeholder */
1551 if (HeVAL(entry) != &PL_sv_placeholder) {
1552 if (HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1553 SV* keysv = hv_iterkeysv(entry);
1555 "Attempt to delete readonly key '%"SVf"' from a restricted hash",
1558 SvREFCNT_dec(HeVAL(entry));
1559 HeVAL(entry) = &PL_sv_placeholder;
1560 HvPLACEHOLDERS(hv)++;
1568 HvPLACEHOLDERS_set(hv, 0);
1570 (void)memzero(HvARRAY(hv),
1571 (xhv->xhv_max+1 /* HvMAX(hv)+1 */) * sizeof(HE*));
1576 HvHASKFLAGS_off(hv);
1580 HvEITER_set(hv, NULL);
1585 =for apidoc hv_clear_placeholders
1587 Clears any placeholders from a hash. If a restricted hash has any of its keys
1588 marked as readonly and the key is subsequently deleted, the key is not actually
1589 deleted but is marked by assigning it a value of &PL_sv_placeholder. This tags
1590 it so it will be ignored by future operations such as iterating over the hash,
1591 but will still allow the hash to have a value reassigned to the key at some
1592 future point. This function clears any such placeholder keys from the hash.
1593 See Hash::Util::lock_keys() for an example of its use.
1599 Perl_hv_clear_placeholders(pTHX_ HV *hv)
1602 I32 items = (I32)HvPLACEHOLDERS_get(hv);
1610 /* Loop down the linked list heads */
1612 HE **oentry = &(HvARRAY(hv))[i];
1615 while ((entry = *oentry)) {
1616 if (HeVAL(entry) == &PL_sv_placeholder) {
1617 *oentry = HeNEXT(entry);
1618 if (first && !*oentry)
1619 HvFILL(hv)--; /* This linked list is now empty. */
1620 if (entry == HvEITER_get(hv))
1623 hv_free_ent(hv, entry);
1627 HvTOTALKEYS(hv) -= (IV)HvPLACEHOLDERS_get(hv);
1628 if (HvKEYS(hv) == 0)
1629 HvHASKFLAGS_off(hv);
1630 HvPLACEHOLDERS_set(hv, 0);
1634 oentry = &HeNEXT(entry);
1639 /* You can't get here, hence assertion should always fail. */
1640 assert (items == 0);
1645 S_hfreeentries(pTHX_ HV *hv)
1647 /* This is the array that we're going to restore */
1656 /* If the hash is actually a symbol table with a name, look after the
1658 struct xpvhv_aux *iter = HvAUX(hv);
1660 name = iter->xhv_name;
1661 iter->xhv_name = NULL;
1666 orig_array = HvARRAY(hv);
1667 /* orig_array remains unchanged throughout the loop. If after freeing all
1668 the entries it turns out that one of the little blighters has triggered
1669 an action that has caused HvARRAY to be re-allocated, then we set
1670 array to the new HvARRAY, and try again. */
1673 /* This is the one we're going to try to empty. First time round
1674 it's the original array. (Hopefully there will only be 1 time
1676 HE **array = HvARRAY(hv);
1679 /* Because we have taken xhv_name out, the only allocated pointer
1680 in the aux structure that might exist is the backreference array.
1685 struct xpvhv_aux *iter = HvAUX(hv);
1686 /* If there are weak references to this HV, we need to avoid
1687 freeing them up here. In particular we need to keep the AV
1688 visible as what we're deleting might well have weak references
1689 back to this HV, so the for loop below may well trigger
1690 the removal of backreferences from this array. */
1692 if (iter->xhv_backreferences) {
1693 /* So donate them to regular backref magic to keep them safe.
1694 The sv_magic will increase the reference count of the AV,
1695 so we need to drop it first. */
1696 SvREFCNT_dec(iter->xhv_backreferences);
1697 if (AvFILLp(iter->xhv_backreferences) == -1) {
1698 /* Turns out that the array is empty. Just free it. */
1699 SvREFCNT_dec(iter->xhv_backreferences);
1702 sv_magic((SV*)hv, (SV*)iter->xhv_backreferences,
1703 PERL_MAGIC_backref, NULL, 0);
1705 iter->xhv_backreferences = NULL;
1708 entry = iter->xhv_eiter; /* HvEITER(hv) */
1709 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1711 hv_free_ent(hv, entry);
1713 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1714 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1716 /* There are now no allocated pointers in the aux structure. */
1718 SvFLAGS(hv) &= ~SVf_OOK; /* Goodbye, aux structure. */
1719 /* What aux structure? */
1722 /* make everyone else think the array is empty, so that the destructors
1723 * called for freed entries can't recusively mess with us */
1726 ((XPVHV*) SvANY(hv))->xhv_keys = 0;
1730 /* Loop down the linked list heads */
1731 HE *entry = array[i];
1734 register HE * const oentry = entry;
1735 entry = HeNEXT(entry);
1736 hv_free_ent(hv, oentry);
1740 /* As there are no allocated pointers in the aux structure, it's now
1741 safe to free the array we just cleaned up, if it's not the one we're
1742 going to put back. */
1743 if (array != orig_array) {
1748 /* Good. No-one added anything this time round. */
1753 /* Someone attempted to iterate or set the hash name while we had
1754 the array set to 0. We'll catch backferences on the next time
1755 round the while loop. */
1756 assert(HvARRAY(hv));
1758 if (HvAUX(hv)->xhv_name) {
1759 unshare_hek_or_pvn(HvAUX(hv)->xhv_name, 0, 0, 0);
1763 if (--attempts == 0) {
1764 Perl_die(aTHX_ "panic: hfreeentries failed to free hash - something is repeatedly re-creating entries");
1768 HvARRAY(hv) = orig_array;
1770 /* If the hash was actually a symbol table, put the name back. */
1772 /* We have restored the original array. If name is non-NULL, then
1773 the original array had an aux structure at the end. So this is
1775 SvFLAGS(hv) |= SVf_OOK;
1776 HvAUX(hv)->xhv_name = name;
1781 =for apidoc hv_undef
1789 Perl_hv_undef(pTHX_ HV *hv)
1791 register XPVHV* xhv;
1796 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1797 xhv = (XPVHV*)SvANY(hv);
1799 if ((name = HvNAME_get(hv))) {
1801 hv_delete(PL_stashcache, name, HvNAMELEN_get(hv), G_DISCARD);
1802 hv_name_set(hv, Nullch, 0, 0);
1804 SvFLAGS(hv) &= ~SVf_OOK;
1805 Safefree(HvARRAY(hv));
1806 xhv->xhv_max = 7; /* HvMAX(hv) = 7 (it's a normal hash) */
1808 HvPLACEHOLDERS_set(hv, 0);
1814 static struct xpvhv_aux*
1815 S_hv_auxinit(pTHX_ HV *hv) {
1816 struct xpvhv_aux *iter;
1820 Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1821 + sizeof(struct xpvhv_aux), char);
1823 array = (char *) HvARRAY(hv);
1824 Renew(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1825 + sizeof(struct xpvhv_aux), char);
1827 HvARRAY(hv) = (HE**) array;
1828 /* SvOOK_on(hv) attacks the IV flags. */
1829 SvFLAGS(hv) |= SVf_OOK;
1832 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1833 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1835 iter->xhv_backreferences = 0;
1840 =for apidoc hv_iterinit
1842 Prepares a starting point to traverse a hash table. Returns the number of
1843 keys in the hash (i.e. the same as C<HvKEYS(tb)>). The return value is
1844 currently only meaningful for hashes without tie magic.
1846 NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
1847 hash buckets that happen to be in use. If you still need that esoteric
1848 value, you can get it through the macro C<HvFILL(tb)>.
1855 Perl_hv_iterinit(pTHX_ HV *hv)
1858 Perl_croak(aTHX_ "Bad hash");
1861 struct xpvhv_aux *iter = HvAUX(hv);
1862 HE * const entry = iter->xhv_eiter; /* HvEITER(hv) */
1863 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1865 hv_free_ent(hv, entry);
1867 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1868 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1870 S_hv_auxinit(aTHX_ hv);
1873 /* used to be xhv->xhv_fill before 5.004_65 */
1874 return HvTOTALKEYS(hv);
1878 Perl_hv_riter_p(pTHX_ HV *hv) {
1879 struct xpvhv_aux *iter;
1882 Perl_croak(aTHX_ "Bad hash");
1884 iter = SvOOK(hv) ? HvAUX(hv) : S_hv_auxinit(aTHX_ hv);
1885 return &(iter->xhv_riter);
1889 Perl_hv_eiter_p(pTHX_ HV *hv) {
1890 struct xpvhv_aux *iter;
1893 Perl_croak(aTHX_ "Bad hash");
1895 iter = SvOOK(hv) ? HvAUX(hv) : S_hv_auxinit(aTHX_ hv);
1896 return &(iter->xhv_eiter);
1900 Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
1901 struct xpvhv_aux *iter;
1904 Perl_croak(aTHX_ "Bad hash");
1912 iter = S_hv_auxinit(aTHX_ hv);
1914 iter->xhv_riter = riter;
1918 Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
1919 struct xpvhv_aux *iter;
1922 Perl_croak(aTHX_ "Bad hash");
1927 /* 0 is the default so don't go malloc()ing a new structure just to
1932 iter = S_hv_auxinit(aTHX_ hv);
1934 iter->xhv_eiter = eiter;
1938 Perl_hv_name_set(pTHX_ HV *hv, const char *name, I32 len, int flags)
1940 struct xpvhv_aux *iter;
1943 PERL_UNUSED_ARG(flags);
1947 if (iter->xhv_name) {
1948 unshare_hek_or_pvn(iter->xhv_name, 0, 0, 0);
1954 iter = S_hv_auxinit(aTHX_ hv);
1956 PERL_HASH(hash, name, len);
1957 iter->xhv_name = name ? share_hek(name, len, hash) : 0;
1961 Perl_hv_backreferences_p(pTHX_ HV *hv) {
1962 struct xpvhv_aux *iter;
1964 iter = SvOOK(hv) ? HvAUX(hv) : S_hv_auxinit(aTHX_ hv);
1965 return &(iter->xhv_backreferences);
1969 Perl_hv_kill_backrefs(pTHX_ HV *hv) {
1975 av = HvAUX(hv)->xhv_backreferences;
1978 HvAUX(hv)->xhv_backreferences = 0;
1979 Perl_sv_kill_backrefs(aTHX_ (SV*) hv, av);
1984 hv_iternext is implemented as a macro in hv.h
1986 =for apidoc hv_iternext
1988 Returns entries from a hash iterator. See C<hv_iterinit>.
1990 You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
1991 iterator currently points to, without losing your place or invalidating your
1992 iterator. Note that in this case the current entry is deleted from the hash
1993 with your iterator holding the last reference to it. Your iterator is flagged
1994 to free the entry on the next call to C<hv_iternext>, so you must not discard
1995 your iterator immediately else the entry will leak - call C<hv_iternext> to
1996 trigger the resource deallocation.
1998 =for apidoc hv_iternext_flags
2000 Returns entries from a hash iterator. See C<hv_iterinit> and C<hv_iternext>.
2001 The C<flags> value will normally be zero; if HV_ITERNEXT_WANTPLACEHOLDERS is
2002 set the placeholders keys (for restricted hashes) will be returned in addition
2003 to normal keys. By default placeholders are automatically skipped over.
2004 Currently a placeholder is implemented with a value that is
2005 C<&Perl_sv_placeholder>. Note that the implementation of placeholders and
2006 restricted hashes may change, and the implementation currently is
2007 insufficiently abstracted for any change to be tidy.
2013 Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
2016 register XPVHV* xhv;
2020 struct xpvhv_aux *iter;
2023 Perl_croak(aTHX_ "Bad hash");
2024 xhv = (XPVHV*)SvANY(hv);
2027 /* Too many things (well, pp_each at least) merrily assume that you can
2028 call iv_iternext without calling hv_iterinit, so we'll have to deal
2034 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2036 if ((mg = SvTIED_mg((SV*)hv, PERL_MAGIC_tied))) {
2037 SV * const key = sv_newmortal();
2039 sv_setsv(key, HeSVKEY_force(entry));
2040 SvREFCNT_dec(HeSVKEY(entry)); /* get rid of previous key */
2046 /* one HE per MAGICAL hash */
2047 iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
2049 Newxz(k, HEK_BASESIZE + sizeof(SV*), char);
2051 HeKEY_hek(entry) = hek;
2052 HeKLEN(entry) = HEf_SVKEY;
2054 magic_nextpack((SV*) hv,mg,key);
2056 /* force key to stay around until next time */
2057 HeSVKEY_set(entry, SvREFCNT_inc(key));
2058 return entry; /* beware, hent_val is not set */
2061 SvREFCNT_dec(HeVAL(entry));
2062 Safefree(HeKEY_hek(entry));
2064 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
2067 #ifdef DYNAMIC_ENV_FETCH /* set up %ENV for iteration */
2068 if (!entry && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
2071 /* The prime_env_iter() on VMS just loaded up new hash values
2072 * so the iteration count needs to be reset back to the beginning
2076 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2081 /* hv_iterint now ensures this. */
2082 assert (HvARRAY(hv));
2084 /* At start of hash, entry is NULL. */
2087 entry = HeNEXT(entry);
2088 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2090 * Skip past any placeholders -- don't want to include them in
2093 while (entry && HeVAL(entry) == &PL_sv_placeholder) {
2094 entry = HeNEXT(entry);
2099 /* OK. Come to the end of the current list. Grab the next one. */
2101 iter->xhv_riter++; /* HvRITER(hv)++ */
2102 if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
2103 /* There is no next one. End of the hash. */
2104 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2107 entry = (HvARRAY(hv))[iter->xhv_riter];
2109 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2110 /* If we have an entry, but it's a placeholder, don't count it.
2112 while (entry && HeVAL(entry) == &PL_sv_placeholder)
2113 entry = HeNEXT(entry);
2115 /* Will loop again if this linked list starts NULL
2116 (for HV_ITERNEXT_WANTPLACEHOLDERS)
2117 or if we run through it and find only placeholders. */
2120 if (oldentry && HvLAZYDEL(hv)) { /* was deleted earlier? */
2122 hv_free_ent(hv, oldentry);
2125 /*if (HvREHASH(hv) && entry && !HeKREHASH(entry))
2126 PerlIO_printf(PerlIO_stderr(), "Awooga %p %p\n", hv, entry);*/
2128 iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
2133 =for apidoc hv_iterkey
2135 Returns the key from the current position of the hash iterator. See
2142 Perl_hv_iterkey(pTHX_ register HE *entry, I32 *retlen)
2144 if (HeKLEN(entry) == HEf_SVKEY) {
2146 char * const p = SvPV(HeKEY_sv(entry), len);
2151 *retlen = HeKLEN(entry);
2152 return HeKEY(entry);
2156 /* unlike hv_iterval(), this always returns a mortal copy of the key */
2158 =for apidoc hv_iterkeysv
2160 Returns the key as an C<SV*> from the current position of the hash
2161 iterator. The return value will always be a mortal copy of the key. Also
2168 Perl_hv_iterkeysv(pTHX_ register HE *entry)
2170 return sv_2mortal(newSVhek(HeKEY_hek(entry)));
2174 =for apidoc hv_iterval
2176 Returns the value from the current position of the hash iterator. See
2183 Perl_hv_iterval(pTHX_ HV *hv, register HE *entry)
2185 if (SvRMAGICAL(hv)) {
2186 if (mg_find((SV*)hv, PERL_MAGIC_tied)) {
2187 SV* const sv = sv_newmortal();
2188 if (HeKLEN(entry) == HEf_SVKEY)
2189 mg_copy((SV*)hv, sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
2191 mg_copy((SV*)hv, sv, HeKEY(entry), HeKLEN(entry));
2195 return HeVAL(entry);
2199 =for apidoc hv_iternextsv
2201 Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2208 Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
2210 HE * const he = hv_iternext_flags(hv, 0);
2214 *key = hv_iterkey(he, retlen);
2215 return hv_iterval(hv, he);
2222 =for apidoc hv_magic
2224 Adds magic to a hash. See C<sv_magic>.
2229 /* possibly free a shared string if no one has access to it
2230 * len and hash must both be valid for str.
2233 Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
2235 unshare_hek_or_pvn (NULL, str, len, hash);
2240 Perl_unshare_hek(pTHX_ HEK *hek)
2242 unshare_hek_or_pvn(hek, NULL, 0, 0);
2245 /* possibly free a shared string if no one has access to it
2246 hek if non-NULL takes priority over the other 3, else str, len and hash
2247 are used. If so, len and hash must both be valid for str.
2250 S_unshare_hek_or_pvn(pTHX_ const HEK *hek, const char *str, I32 len, U32 hash)
2252 register XPVHV* xhv;
2254 register HE **oentry;
2257 bool is_utf8 = FALSE;
2259 const char * const save = str;
2260 struct shared_he *he = 0;
2263 /* Find the shared he which is just before us in memory. */
2264 he = (struct shared_he *)(((char *)hek)
2265 - STRUCT_OFFSET(struct shared_he,
2268 /* Assert that the caller passed us a genuine (or at least consistent)
2270 assert (he->shared_he_he.hent_hek == hek);
2273 if (he->shared_he_he.hent_val - 1) {
2274 --he->shared_he_he.hent_val;
2275 UNLOCK_STRTAB_MUTEX;
2278 UNLOCK_STRTAB_MUTEX;
2280 hash = HEK_HASH(hek);
2281 } else if (len < 0) {
2282 STRLEN tmplen = -len;
2284 /* See the note in hv_fetch(). --jhi */
2285 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2288 k_flags = HVhek_UTF8;
2290 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2293 /* what follows is the moral equivalent of:
2294 if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
2295 if (--*Svp == Nullsv)
2296 hv_delete(PL_strtab, str, len, G_DISCARD, hash);
2298 xhv = (XPVHV*)SvANY(PL_strtab);
2299 /* assert(xhv_array != 0) */
2301 first = oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2303 const HE *const he_he = &(he->shared_he_he);
2304 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2311 const int flags_masked = k_flags & HVhek_MASK;
2312 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2313 if (HeHASH(entry) != hash) /* strings can't be equal */
2315 if (HeKLEN(entry) != len)
2317 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2319 if (HeKFLAGS(entry) != flags_masked)
2327 if (--HeVAL(entry) == Nullsv) {
2328 *oentry = HeNEXT(entry);
2330 /* There are now no entries in our slot. */
2331 xhv->xhv_fill--; /* HvFILL(hv)-- */
2334 xhv->xhv_keys--; /* HvKEYS(hv)-- */
2338 UNLOCK_STRTAB_MUTEX;
2339 if (!found && ckWARN_d(WARN_INTERNAL))
2340 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
2341 "Attempt to free non-existent shared string '%s'%s"
2343 hek ? HEK_KEY(hek) : str,
2344 ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
2345 if (k_flags & HVhek_FREEKEY)
2349 /* get a (constant) string ptr from the global string table
2350 * string will get added if it is not already there.
2351 * len and hash must both be valid for str.
2354 Perl_share_hek(pTHX_ const char *str, I32 len, register U32 hash)
2356 bool is_utf8 = FALSE;
2358 const char * const save = str;
2361 STRLEN tmplen = -len;
2363 /* See the note in hv_fetch(). --jhi */
2364 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2366 /* If we were able to downgrade here, then than means that we were passed
2367 in a key which only had chars 0-255, but was utf8 encoded. */
2370 /* If we found we were able to downgrade the string to bytes, then
2371 we should flag that it needs upgrading on keys or each. Also flag
2372 that we need share_hek_flags to free the string. */
2374 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2377 return share_hek_flags (str, len, hash, flags);
2381 S_share_hek_flags(pTHX_ const char *str, I32 len, register U32 hash, int flags)
2384 const int flags_masked = flags & HVhek_MASK;
2385 const U32 hindex = hash & (I32) HvMAX(PL_strtab);
2387 /* what follows is the moral equivalent of:
2389 if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
2390 hv_store(PL_strtab, str, len, Nullsv, hash);
2392 Can't rehash the shared string table, so not sure if it's worth
2393 counting the number of entries in the linked list
2395 register XPVHV * const xhv = (XPVHV*)SvANY(PL_strtab);
2396 /* assert(xhv_array != 0) */
2398 entry = (HvARRAY(PL_strtab))[hindex];
2399 for (;entry; entry = HeNEXT(entry)) {
2400 if (HeHASH(entry) != hash) /* strings can't be equal */
2402 if (HeKLEN(entry) != len)
2404 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2406 if (HeKFLAGS(entry) != flags_masked)
2412 /* What used to be head of the list.
2413 If this is NULL, then we're the first entry for this slot, which
2414 means we need to increate fill. */
2415 struct shared_he *new_entry;
2418 HE **const head = &HvARRAY(PL_strtab)[hindex];
2419 HE *const next = *head;
2421 /* We don't actually store a HE from the arena and a regular HEK.
2422 Instead we allocate one chunk of memory big enough for both,
2423 and put the HEK straight after the HE. This way we can find the
2424 HEK directly from the HE.
2427 Newx(k, STRUCT_OFFSET(struct shared_he,
2428 shared_he_hek.hek_key[0]) + len + 2, char);
2429 new_entry = (struct shared_he *)k;
2430 entry = &(new_entry->shared_he_he);
2431 hek = &(new_entry->shared_he_hek);
2433 Copy(str, HEK_KEY(hek), len, char);
2434 HEK_KEY(hek)[len] = 0;
2436 HEK_HASH(hek) = hash;
2437 HEK_FLAGS(hek) = (unsigned char)flags_masked;
2439 /* Still "point" to the HEK, so that other code need not know what
2441 HeKEY_hek(entry) = hek;
2442 HeVAL(entry) = Nullsv;
2443 HeNEXT(entry) = next;
2446 xhv->xhv_keys++; /* HvKEYS(hv)++ */
2447 if (!next) { /* initial entry? */
2448 xhv->xhv_fill++; /* HvFILL(hv)++ */
2449 } else if (xhv->xhv_keys > (IV)xhv->xhv_max /* HvKEYS(hv) > HvMAX(hv) */) {
2454 ++HeVAL(entry); /* use value slot as REFCNT */
2455 UNLOCK_STRTAB_MUTEX;
2457 if (flags & HVhek_FREEKEY)
2460 return HeKEY_hek(entry);
2464 Perl_hv_placeholders_p(pTHX_ HV *hv)
2467 MAGIC *mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2470 mg = sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, 0);
2473 Perl_die(aTHX_ "panic: hv_placeholders_p");
2476 return &(mg->mg_len);
2481 Perl_hv_placeholders_get(pTHX_ HV *hv)
2484 MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2486 return mg ? mg->mg_len : 0;
2490 Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
2493 MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2498 if (!sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, ph))
2499 Perl_die(aTHX_ "panic: hv_placeholders_set");
2501 /* else we don't need to add magic to record 0 placeholders. */
2505 =for apidoc hv_assert
2507 Check that a hash is in an internally consistent state.
2513 Perl_hv_assert(pTHX_ HV *hv)
2518 int placeholders = 0;
2521 const I32 riter = HvRITER_get(hv);
2522 HE *eiter = HvEITER_get(hv);
2524 (void)hv_iterinit(hv);
2526 while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
2527 /* sanity check the values */
2528 if (HeVAL(entry) == &PL_sv_placeholder) {
2533 /* sanity check the keys */
2534 if (HeSVKEY(entry)) {
2535 /* Don't know what to check on SV keys. */
2536 } else if (HeKUTF8(entry)) {
2538 if (HeKWASUTF8(entry)) {
2539 PerlIO_printf(Perl_debug_log,
2540 "hash key has both WASUFT8 and UTF8: '%.*s'\n",
2541 (int) HeKLEN(entry), HeKEY(entry));
2544 } else if (HeKWASUTF8(entry)) {
2548 if (!SvTIED_mg((SV*)hv, PERL_MAGIC_tied)) {
2549 if (HvUSEDKEYS(hv) != real) {
2550 PerlIO_printf(Perl_debug_log, "Count %d key(s), but hash reports %d\n",
2551 (int) real, (int) HvUSEDKEYS(hv));
2554 if (HvPLACEHOLDERS_get(hv) != placeholders) {
2555 PerlIO_printf(Perl_debug_log,
2556 "Count %d placeholder(s), but hash reports %d\n",
2557 (int) placeholders, (int) HvPLACEHOLDERS_get(hv));
2561 if (withflags && ! HvHASKFLAGS(hv)) {
2562 PerlIO_printf(Perl_debug_log,
2563 "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
2570 HvRITER_set(hv, riter); /* Restore hash iterator state */
2571 HvEITER_set(hv, eiter);
2576 * c-indentation-style: bsd
2578 * indent-tabs-mode: t
2581 * ex: set ts=8 sts=4 sw=4 noet: