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 *const S_strtab_error
37 = "Cannot modify shared string table in hv_%s";
44 New(54, he, PERL_ARENA_SIZE/sizeof(HE), HE);
45 HeNEXT(he) = PL_he_arenaroot;
48 heend = &he[PERL_ARENA_SIZE / sizeof(HE) - 1];
51 HeNEXT(he) = (HE*)(he + 1);
65 PL_he_root = HeNEXT(he);
74 HeNEXT(p) = (HE*)PL_he_root;
81 #define new_HE() (HE*)safemalloc(sizeof(HE))
82 #define del_HE(p) safefree((char*)p)
86 #define new_HE() new_he()
87 #define del_HE(p) del_he(p)
92 S_save_hek_flags(pTHX_ const char *str, I32 len, U32 hash, int flags)
94 const int flags_masked = flags & HVhek_MASK;
98 New(54, k, HEK_BASESIZE + len + 2, char);
100 Copy(str, HEK_KEY(hek), len, char);
101 HEK_KEY(hek)[len] = 0;
103 HEK_HASH(hek) = hash;
104 HEK_FLAGS(hek) = (unsigned char)flags_masked;
106 if (flags & HVhek_FREEKEY)
111 /* free the pool of temporary HE/HEK pairs retunrned by hv_fetch_ent
115 Perl_free_tied_hv_pool(pTHX)
118 HE *he = PL_hv_fetch_ent_mh;
120 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);
136 /* We already shared this hash key. */
137 (void)share_hek_hek(shared);
141 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
142 HEK_HASH(source), HEK_FLAGS(source));
143 ptr_table_store(PL_ptr_table, source, shared);
149 Perl_he_dup(pTHX_ HE *e, bool shared, CLONE_PARAMS* param)
155 /* look for it in the table first */
156 ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
160 /* create anew and remember what it is */
162 ptr_table_store(PL_ptr_table, e, ret);
164 HeNEXT(ret) = he_dup(HeNEXT(e),shared, param);
165 if (HeKLEN(e) == HEf_SVKEY) {
167 New(54, k, HEK_BASESIZE + sizeof(SV*), char);
168 HeKEY_hek(ret) = (HEK*)k;
169 HeKEY_sv(ret) = SvREFCNT_inc(sv_dup(HeKEY_sv(e), param));
172 /* This is hek_dup inlined, which seems to be important for speed
174 HEK * const source = HeKEY_hek(e);
175 HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
178 /* We already shared this hash key. */
179 (void)share_hek_hek(shared);
183 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
184 HEK_HASH(source), HEK_FLAGS(source));
185 ptr_table_store(PL_ptr_table, source, shared);
187 HeKEY_hek(ret) = shared;
190 HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
192 HeVAL(ret) = SvREFCNT_inc(sv_dup(HeVAL(e), param));
195 #endif /* USE_ITHREADS */
198 S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
201 SV * const sv = sv_newmortal();
202 if (!(flags & HVhek_FREEKEY)) {
203 sv_setpvn(sv, key, klen);
206 /* Need to free saved eventually assign to mortal SV */
207 /* XXX is this line an error ???: SV *sv = sv_newmortal(); */
208 sv_usepvn(sv, (char *) key, klen);
210 if (flags & HVhek_UTF8) {
213 Perl_croak(aTHX_ msg, sv);
216 /* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
219 #define HV_FETCH_ISSTORE 0x01
220 #define HV_FETCH_ISEXISTS 0x02
221 #define HV_FETCH_LVALUE 0x04
222 #define HV_FETCH_JUST_SV 0x08
227 Stores an SV in a hash. The hash key is specified as C<key> and C<klen> is
228 the length of the key. The C<hash> parameter is the precomputed hash
229 value; if it is zero then Perl will compute it. The return value will be
230 NULL if the operation failed or if the value did not need to be actually
231 stored within the hash (as in the case of tied hashes). Otherwise it can
232 be dereferenced to get the original C<SV*>. Note that the caller is
233 responsible for suitably incrementing the reference count of C<val> before
234 the call, and decrementing it if the function returned NULL. Effectively
235 a successful hv_store takes ownership of one reference to C<val>. This is
236 usually what you want; a newly created SV has a reference count of one, so
237 if all your code does is create SVs then store them in a hash, hv_store
238 will own the only reference to the new SV, and your code doesn't need to do
239 anything further to tidy up. hv_store is not implemented as a call to
240 hv_store_ent, and does not create a temporary SV for the key, so if your
241 key data is not already in SV form then use hv_store in preference to
244 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
245 information on how to use this function on tied hashes.
251 Perl_hv_store(pTHX_ HV *hv, const char *key, I32 klen_i32, SV *val, U32 hash)
264 hek = hv_fetch_common (hv, NULL, key, klen, flags,
265 (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
266 return hek ? &HeVAL(hek) : NULL;
270 Perl_hv_store_flags(pTHX_ HV *hv, const char *key, I32 klen, SV *val,
271 register U32 hash, int flags)
273 HE *hek = hv_fetch_common (hv, NULL, key, klen, flags,
274 (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
275 return hek ? &HeVAL(hek) : NULL;
279 =for apidoc hv_store_ent
281 Stores C<val> in a hash. The hash key is specified as C<key>. The C<hash>
282 parameter is the precomputed hash value; if it is zero then Perl will
283 compute it. The return value is the new hash entry so created. It will be
284 NULL if the operation failed or if the value did not need to be actually
285 stored within the hash (as in the case of tied hashes). Otherwise the
286 contents of the return value can be accessed using the C<He?> macros
287 described here. Note that the caller is responsible for suitably
288 incrementing the reference count of C<val> before the call, and
289 decrementing it if the function returned NULL. Effectively a successful
290 hv_store_ent takes ownership of one reference to C<val>. This is
291 usually what you want; a newly created SV has a reference count of one, so
292 if all your code does is create SVs then store them in a hash, hv_store
293 will own the only reference to the new SV, and your code doesn't need to do
294 anything further to tidy up. Note that hv_store_ent only reads the C<key>;
295 unlike C<val> it does not take ownership of it, so maintaining the correct
296 reference count on C<key> is entirely the caller's responsibility. hv_store
297 is not implemented as a call to hv_store_ent, and does not create a temporary
298 SV for the key, so if your key data is not already in SV form then use
299 hv_store in preference to hv_store_ent.
301 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
302 information on how to use this function on tied hashes.
308 Perl_hv_store_ent(pTHX_ HV *hv, SV *keysv, SV *val, U32 hash)
310 return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISSTORE, val, hash);
314 =for apidoc hv_exists
316 Returns a boolean indicating whether the specified hash key exists. The
317 C<klen> is the length of the key.
323 Perl_hv_exists(pTHX_ HV *hv, const char *key, I32 klen_i32)
335 return hv_fetch_common(hv, NULL, key, klen, flags, HV_FETCH_ISEXISTS, 0, 0)
342 Returns the SV which corresponds to the specified key in the hash. The
343 C<klen> is the length of the key. If C<lval> is set then the fetch will be
344 part of a store. Check that the return value is non-null before
345 dereferencing it to an C<SV*>.
347 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
348 information on how to use this function on tied hashes.
354 Perl_hv_fetch(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 lval)
367 hek = hv_fetch_common (hv, NULL, key, klen, flags,
368 HV_FETCH_JUST_SV | (lval ? HV_FETCH_LVALUE : 0),
370 return hek ? &HeVAL(hek) : NULL;
374 =for apidoc hv_exists_ent
376 Returns a boolean indicating whether the specified hash key exists. C<hash>
377 can be a valid precomputed hash value, or 0 to ask for it to be
384 Perl_hv_exists_ent(pTHX_ HV *hv, SV *keysv, U32 hash)
386 return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISEXISTS, 0, hash)
390 /* returns an HE * structure with the all fields set */
391 /* note that hent_val will be a mortal sv for MAGICAL hashes */
393 =for apidoc hv_fetch_ent
395 Returns the hash entry which corresponds to the specified key in the hash.
396 C<hash> must be a valid precomputed hash number for the given C<key>, or 0
397 if you want the function to compute it. IF C<lval> is set then the fetch
398 will be part of a store. Make sure the return value is non-null before
399 accessing it. The return value when C<tb> is a tied hash is a pointer to a
400 static location, so be sure to make a copy of the structure if you need to
403 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
404 information on how to use this function on tied hashes.
410 Perl_hv_fetch_ent(pTHX_ HV *hv, SV *keysv, I32 lval, register U32 hash)
412 return hv_fetch_common(hv, keysv, NULL, 0, 0,
413 (lval ? HV_FETCH_LVALUE : 0), Nullsv, hash);
417 S_hv_fetch_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
418 int flags, int action, SV *val, register U32 hash)
432 if (flags & HVhek_FREEKEY)
434 key = SvPV_const(keysv, klen);
436 is_utf8 = (SvUTF8(keysv) != 0);
438 is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
441 xhv = (XPVHV*)SvANY(hv);
443 if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS)))
445 if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
448 /* XXX should be able to skimp on the HE/HEK here when
449 HV_FETCH_JUST_SV is true. */
452 keysv = newSVpvn(key, klen);
457 keysv = newSVsv(keysv);
459 mg_copy((SV*)hv, sv, (char *)keysv, HEf_SVKEY);
461 /* grab a fake HE/HEK pair from the pool or make a new one */
462 entry = PL_hv_fetch_ent_mh;
464 PL_hv_fetch_ent_mh = HeNEXT(entry);
468 New(54, k, HEK_BASESIZE + sizeof(SV*), char);
469 HeKEY_hek(entry) = (HEK*)k;
471 HeNEXT(entry) = Nullhe;
472 HeSVKEY_set(entry, keysv);
474 sv_upgrade(sv, SVt_PVLV);
476 /* so we can free entry when freeing sv */
477 LvTARG(sv) = (SV*)entry;
479 /* XXX remove at some point? */
480 if (flags & HVhek_FREEKEY)
485 #ifdef ENV_IS_CASELESS
486 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
488 for (i = 0; i < klen; ++i)
489 if (isLOWER(key[i])) {
490 /* Would be nice if we had a routine to do the
491 copy and upercase in a single pass through. */
492 const char *nkey = strupr(savepvn(key,klen));
493 /* Note that this fetch is for nkey (the uppercased
494 key) whereas the store is for key (the original) */
495 entry = hv_fetch_common(hv, Nullsv, nkey, klen,
496 HVhek_FREEKEY, /* free nkey */
497 0 /* non-LVAL fetch */,
498 Nullsv /* no value */,
499 0 /* compute hash */);
500 if (!entry && (action & HV_FETCH_LVALUE)) {
501 /* This call will free key if necessary.
502 Do it this way to encourage compiler to tail
504 entry = hv_fetch_common(hv, keysv, key, klen,
505 flags, HV_FETCH_ISSTORE,
508 if (flags & HVhek_FREEKEY)
516 else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
517 if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
519 /* I don't understand why hv_exists_ent has svret and sv,
520 whereas hv_exists only had one. */
521 svret = sv_newmortal();
524 if (keysv || is_utf8) {
526 keysv = newSVpvn(key, klen);
529 keysv = newSVsv(keysv);
531 mg_copy((SV*)hv, sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
533 mg_copy((SV*)hv, sv, key, klen);
535 if (flags & HVhek_FREEKEY)
537 magic_existspack(svret, mg_find(sv, PERL_MAGIC_tiedelem));
538 /* This cast somewhat evil, but I'm merely using NULL/
539 not NULL to return the boolean exists.
540 And I know hv is not NULL. */
541 return SvTRUE(svret) ? (HE *)hv : NULL;
543 #ifdef ENV_IS_CASELESS
544 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
545 /* XXX This code isn't UTF8 clean. */
546 const char *keysave = key;
547 /* Will need to free this, so set FREEKEY flag. */
548 key = savepvn(key,klen);
549 key = (const char*)strupr((char*)key);
554 if (flags & HVhek_FREEKEY) {
557 flags |= HVhek_FREEKEY;
561 else if (action & HV_FETCH_ISSTORE) {
564 hv_magic_check (hv, &needs_copy, &needs_store);
566 const bool save_taint = PL_tainted;
567 if (keysv || is_utf8) {
569 keysv = newSVpvn(key, klen);
573 PL_tainted = SvTAINTED(keysv);
574 keysv = sv_2mortal(newSVsv(keysv));
575 mg_copy((SV*)hv, val, (char*)keysv, HEf_SVKEY);
577 mg_copy((SV*)hv, val, key, klen);
580 TAINT_IF(save_taint);
581 if (!HvARRAY(hv) && !needs_store) {
582 if (flags & HVhek_FREEKEY)
586 #ifdef ENV_IS_CASELESS
587 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
588 /* XXX This code isn't UTF8 clean. */
589 const char *keysave = key;
590 /* Will need to free this, so set FREEKEY flag. */
591 key = savepvn(key,klen);
592 key = (const char*)strupr((char*)key);
597 if (flags & HVhek_FREEKEY) {
600 flags |= HVhek_FREEKEY;
608 if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
609 #ifdef DYNAMIC_ENV_FETCH /* if it's an %ENV lookup, we may get it on the fly */
610 || (SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
615 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
617 HvARRAY(hv) = (HE**)array;
619 #ifdef DYNAMIC_ENV_FETCH
620 else if (action & HV_FETCH_ISEXISTS) {
621 /* for an %ENV exists, if we do an insert it's by a recursive
622 store call, so avoid creating HvARRAY(hv) right now. */
626 /* XXX remove at some point? */
627 if (flags & HVhek_FREEKEY)
635 const char *keysave = key;
636 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
640 flags &= ~HVhek_UTF8;
641 if (key != keysave) {
642 if (flags & HVhek_FREEKEY)
644 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
649 PERL_HASH_INTERNAL(hash, key, klen);
650 /* We don't have a pointer to the hv, so we have to replicate the
651 flag into every HEK, so that hv_iterkeysv can see it. */
652 /* And yes, you do need this even though you are not "storing" because
653 you can flip the flags below if doing an lval lookup. (And that
654 was put in to give the semantics Andreas was expecting.) */
655 flags |= HVhek_REHASH;
657 if (keysv && (SvIsCOW_shared_hash(keysv))) {
658 hash = SvSHARED_HASH(keysv);
660 PERL_HASH(hash, key, klen);
664 masked_flags = (flags & HVhek_MASK);
666 #ifdef DYNAMIC_ENV_FETCH
667 if (!HvARRAY(hv)) entry = Null(HE*);
671 entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
673 for (; entry; entry = HeNEXT(entry)) {
674 if (HeHASH(entry) != hash) /* strings can't be equal */
676 if (HeKLEN(entry) != (I32)klen)
678 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
680 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
683 if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
684 if (HeKFLAGS(entry) != masked_flags) {
685 /* We match if HVhek_UTF8 bit in our flags and hash key's
686 match. But if entry was set previously with HVhek_WASUTF8
687 and key now doesn't (or vice versa) then we should change
688 the key's flag, as this is assignment. */
689 if (HvSHAREKEYS(hv)) {
690 /* Need to swap the key we have for a key with the flags we
691 need. As keys are shared we can't just write to the
692 flag, so we share the new one, unshare the old one. */
693 HEK *new_hek = share_hek_flags(key, klen, hash,
695 unshare_hek (HeKEY_hek(entry));
696 HeKEY_hek(entry) = new_hek;
698 else if (hv == PL_strtab) {
699 /* PL_strtab is usually the only hash without HvSHAREKEYS,
700 so putting this test here is cheap */
701 if (flags & HVhek_FREEKEY)
703 Perl_croak(aTHX_ S_strtab_error,
704 action & HV_FETCH_LVALUE ? "fetch" : "store");
707 HeKFLAGS(entry) = masked_flags;
708 if (masked_flags & HVhek_ENABLEHVKFLAGS)
711 if (HeVAL(entry) == &PL_sv_placeholder) {
712 /* yes, can store into placeholder slot */
713 if (action & HV_FETCH_LVALUE) {
715 /* This preserves behaviour with the old hv_fetch
716 implementation which at this point would bail out
717 with a break; (at "if we find a placeholder, we
718 pretend we haven't found anything")
720 That break mean that if a placeholder were found, it
721 caused a call into hv_store, which in turn would
722 check magic, and if there is no magic end up pretty
723 much back at this point (in hv_store's code). */
726 /* LVAL fetch which actaully needs a store. */
728 HvPLACEHOLDERS(hv)--;
731 if (val != &PL_sv_placeholder)
732 HvPLACEHOLDERS(hv)--;
735 } else if (action & HV_FETCH_ISSTORE) {
736 SvREFCNT_dec(HeVAL(entry));
739 } else if (HeVAL(entry) == &PL_sv_placeholder) {
740 /* if we find a placeholder, we pretend we haven't found
744 if (flags & HVhek_FREEKEY)
748 #ifdef DYNAMIC_ENV_FETCH /* %ENV lookup? If so, try to fetch the value now */
749 if (!(action & HV_FETCH_ISSTORE)
750 && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
752 char *env = PerlEnv_ENVgetenv_len(key,&len);
754 sv = newSVpvn(env,len);
756 return hv_fetch_common(hv,keysv,key,klen,flags,HV_FETCH_ISSTORE,sv,
762 if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
763 S_hv_notallowed(aTHX_ flags, key, klen,
764 "Attempt to access disallowed key '%"SVf"' in"
765 " a restricted hash");
767 if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
768 /* Not doing some form of store, so return failure. */
769 if (flags & HVhek_FREEKEY)
773 if (action & HV_FETCH_LVALUE) {
776 /* At this point the old hv_fetch code would call to hv_store,
777 which in turn might do some tied magic. So we need to make that
778 magic check happen. */
779 /* gonna assign to this, so it better be there */
780 return hv_fetch_common(hv, keysv, key, klen, flags,
781 HV_FETCH_ISSTORE, val, hash);
782 /* XXX Surely that could leak if the fetch-was-store fails?
783 Just like the hv_fetch. */
787 /* Welcome to hv_store... */
790 /* Not sure if we can get here. I think the only case of oentry being
791 NULL is for %ENV with dynamic env fetch. But that should disappear
792 with magic in the previous code. */
795 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
797 HvARRAY(hv) = (HE**)array;
800 oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
803 /* share_hek_flags will do the free for us. This might be considered
806 HeKEY_hek(entry) = share_hek_flags(key, klen, hash, flags);
807 else if (hv == PL_strtab) {
808 /* PL_strtab is usually the only hash without HvSHAREKEYS, so putting
809 this test here is cheap */
810 if (flags & HVhek_FREEKEY)
812 Perl_croak(aTHX_ S_strtab_error,
813 action & HV_FETCH_LVALUE ? "fetch" : "store");
815 else /* gotta do the real thing */
816 HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
818 HeNEXT(entry) = *oentry;
821 if (val == &PL_sv_placeholder)
822 HvPLACEHOLDERS(hv)++;
823 if (masked_flags & HVhek_ENABLEHVKFLAGS)
827 const HE *counter = HeNEXT(entry);
829 xhv->xhv_keys++; /* HvKEYS(hv)++ */
830 if (!counter) { /* initial entry? */
831 xhv->xhv_fill++; /* HvFILL(hv)++ */
832 } else if (xhv->xhv_keys > (IV)xhv->xhv_max) {
834 } else if(!HvREHASH(hv)) {
837 while ((counter = HeNEXT(counter)))
840 if (n_links > HV_MAX_LENGTH_BEFORE_SPLIT) {
841 /* Use only the old HvKEYS(hv) > HvMAX(hv) condition to limit
842 bucket splits on a rehashed hash, as we're not going to
843 split it again, and if someone is lucky (evil) enough to
844 get all the keys in one list they could exhaust our memory
845 as we repeatedly double the number of buckets on every
846 entry. Linear search feels a less worse thing to do. */
856 S_hv_magic_check(pTHX_ HV *hv, bool *needs_copy, bool *needs_store)
858 const MAGIC *mg = SvMAGIC(hv);
862 if (isUPPER(mg->mg_type)) {
864 switch (mg->mg_type) {
865 case PERL_MAGIC_tied:
867 *needs_store = FALSE;
868 return; /* We've set all there is to set. */
871 mg = mg->mg_moremagic;
876 =for apidoc hv_scalar
878 Evaluates the hash in scalar context and returns the result. Handles magic when the hash is tied.
884 Perl_hv_scalar(pTHX_ HV *hv)
889 if ((SvRMAGICAL(hv) && (mg = mg_find((SV*)hv, PERL_MAGIC_tied)))) {
890 sv = magic_scalarpack(hv, mg);
896 Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
897 (long)HvFILL(hv), (long)HvMAX(hv) + 1);
905 =for apidoc hv_delete
907 Deletes a key/value pair in the hash. The value SV is removed from the
908 hash and returned to the caller. The C<klen> is the length of the key.
909 The C<flags> value will normally be zero; if set to G_DISCARD then NULL
916 Perl_hv_delete(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 flags)
923 k_flags |= HVhek_UTF8;
927 return hv_delete_common(hv, NULL, key, klen, k_flags, flags, 0);
931 =for apidoc hv_delete_ent
933 Deletes a key/value pair in the hash. The value SV is removed from the
934 hash and returned to the caller. The C<flags> value will normally be zero;
935 if set to G_DISCARD then NULL will be returned. C<hash> can be a valid
936 precomputed hash value, or 0 to ask for it to be computed.
942 Perl_hv_delete_ent(pTHX_ HV *hv, SV *keysv, I32 flags, U32 hash)
944 return hv_delete_common(hv, keysv, NULL, 0, 0, flags, hash);
948 S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
949 int k_flags, I32 d_flags, U32 hash)
954 register HE **oentry;
955 HE *const *first_entry;
964 if (k_flags & HVhek_FREEKEY)
966 key = SvPV_const(keysv, klen);
968 is_utf8 = (SvUTF8(keysv) != 0);
970 is_utf8 = ((k_flags & HVhek_UTF8) ? TRUE : FALSE);
973 if (SvRMAGICAL(hv)) {
976 hv_magic_check (hv, &needs_copy, &needs_store);
979 entry = hv_fetch_common(hv, keysv, key, klen,
980 k_flags & ~HVhek_FREEKEY, HV_FETCH_LVALUE,
982 sv = entry ? HeVAL(entry) : NULL;
988 if (mg_find(sv, PERL_MAGIC_tiedelem)) {
989 /* No longer an element */
990 sv_unmagic(sv, PERL_MAGIC_tiedelem);
993 return Nullsv; /* element cannot be deleted */
995 #ifdef ENV_IS_CASELESS
996 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
997 /* XXX This code isn't UTF8 clean. */
998 keysv = sv_2mortal(newSVpvn(key,klen));
999 if (k_flags & HVhek_FREEKEY) {
1002 key = strupr(SvPVX(keysv));
1011 xhv = (XPVHV*)SvANY(hv);
1016 const char *keysave = key;
1017 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
1020 k_flags |= HVhek_UTF8;
1022 k_flags &= ~HVhek_UTF8;
1023 if (key != keysave) {
1024 if (k_flags & HVhek_FREEKEY) {
1025 /* This shouldn't happen if our caller does what we expect,
1026 but strictly the API allows it. */
1029 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
1031 HvHASKFLAGS_on((SV*)hv);
1035 PERL_HASH_INTERNAL(hash, key, klen);
1037 if (keysv && (SvIsCOW_shared_hash(keysv))) {
1038 hash = SvSHARED_HASH(keysv);
1040 PERL_HASH(hash, key, klen);
1044 masked_flags = (k_flags & HVhek_MASK);
1046 first_entry = oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
1048 for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
1049 if (HeHASH(entry) != hash) /* strings can't be equal */
1051 if (HeKLEN(entry) != (I32)klen)
1053 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
1055 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
1058 if (hv == PL_strtab) {
1059 if (k_flags & HVhek_FREEKEY)
1061 Perl_croak(aTHX_ S_strtab_error, "delete");
1064 /* if placeholder is here, it's already been deleted.... */
1065 if (HeVAL(entry) == &PL_sv_placeholder)
1067 if (k_flags & HVhek_FREEKEY)
1071 else if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1072 S_hv_notallowed(aTHX_ k_flags, key, klen,
1073 "Attempt to delete readonly key '%"SVf"' from"
1074 " a restricted hash");
1076 if (k_flags & HVhek_FREEKEY)
1079 if (d_flags & G_DISCARD)
1082 sv = sv_2mortal(HeVAL(entry));
1083 HeVAL(entry) = &PL_sv_placeholder;
1087 * If a restricted hash, rather than really deleting the entry, put
1088 * a placeholder there. This marks the key as being "approved", so
1089 * we can still access via not-really-existing key without raising
1092 if (SvREADONLY(hv)) {
1093 SvREFCNT_dec(HeVAL(entry));
1094 HeVAL(entry) = &PL_sv_placeholder;
1095 /* We'll be saving this slot, so the number of allocated keys
1096 * doesn't go down, but the number placeholders goes up */
1097 HvPLACEHOLDERS(hv)++;
1099 *oentry = HeNEXT(entry);
1101 xhv->xhv_fill--; /* HvFILL(hv)-- */
1103 if (SvOOK(hv) && entry == HvAUX(hv)->xhv_eiter /* HvEITER(hv) */)
1106 hv_free_ent(hv, entry);
1107 xhv->xhv_keys--; /* HvKEYS(hv)-- */
1108 if (xhv->xhv_keys == 0)
1109 HvHASKFLAGS_off(hv);
1113 if (SvREADONLY(hv)) {
1114 S_hv_notallowed(aTHX_ k_flags, key, klen,
1115 "Attempt to delete disallowed key '%"SVf"' from"
1116 " a restricted hash");
1119 if (k_flags & HVhek_FREEKEY)
1125 S_hsplit(pTHX_ HV *hv)
1127 register XPVHV* xhv = (XPVHV*)SvANY(hv);
1128 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1129 register I32 newsize = oldsize * 2;
1131 char *a = (char*) HvARRAY(hv);
1133 register HE **oentry;
1134 int longest_chain = 0;
1137 /*PerlIO_printf(PerlIO_stderr(), "hsplit called for %p which had %d\n",
1138 hv, (int) oldsize);*/
1140 if (HvPLACEHOLDERS_get(hv) && !SvREADONLY(hv)) {
1141 /* Can make this clear any placeholders first for non-restricted hashes,
1142 even though Storable rebuilds restricted hashes by putting in all the
1143 placeholders (first) before turning on the readonly flag, because
1144 Storable always pre-splits the hash. */
1145 hv_clear_placeholders(hv);
1149 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1150 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1151 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1157 Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1160 New(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1161 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1166 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1168 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1170 if (oldsize >= 64) {
1171 offer_nice_chunk(HvARRAY(hv),
1172 PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
1173 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
1176 Safefree(HvARRAY(hv));
1180 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1181 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
1182 HvARRAY(hv) = (HE**) a;
1185 for (i=0; i<oldsize; i++,aep++) {
1186 int left_length = 0;
1187 int right_length = 0;
1191 if (!*aep) /* non-existent */
1194 for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1195 if ((HeHASH(entry) & newsize) != (U32)i) {
1196 *oentry = HeNEXT(entry);
1197 HeNEXT(entry) = *bep;
1199 xhv->xhv_fill++; /* HvFILL(hv)++ */
1205 oentry = &HeNEXT(entry);
1209 if (!*aep) /* everything moved */
1210 xhv->xhv_fill--; /* HvFILL(hv)-- */
1211 /* I think we don't actually need to keep track of the longest length,
1212 merely flag if anything is too long. But for the moment while
1213 developing this code I'll track it. */
1214 if (left_length > longest_chain)
1215 longest_chain = left_length;
1216 if (right_length > longest_chain)
1217 longest_chain = right_length;
1221 /* Pick your policy for "hashing isn't working" here: */
1222 if (longest_chain <= HV_MAX_LENGTH_BEFORE_SPLIT /* split worked? */
1227 if (hv == PL_strtab) {
1228 /* Urg. Someone is doing something nasty to the string table.
1233 /* Awooga. Awooga. Pathological data. */
1234 /*PerlIO_printf(PerlIO_stderr(), "%p %d of %d with %d/%d buckets\n", hv,
1235 longest_chain, HvTOTALKEYS(hv), HvFILL(hv), 1+HvMAX(hv));*/
1238 Newz(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1239 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1241 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1244 was_shared = HvSHAREKEYS(hv);
1247 HvSHAREKEYS_off(hv);
1252 for (i=0; i<newsize; i++,aep++) {
1253 register HE *entry = *aep;
1255 /* We're going to trash this HE's next pointer when we chain it
1256 into the new hash below, so store where we go next. */
1257 HE *next = HeNEXT(entry);
1262 PERL_HASH_INTERNAL(hash, HeKEY(entry), HeKLEN(entry));
1267 = save_hek_flags(HeKEY(entry), HeKLEN(entry),
1268 hash, HeKFLAGS(entry));
1269 unshare_hek (HeKEY_hek(entry));
1270 HeKEY_hek(entry) = new_hek;
1272 /* Not shared, so simply write the new hash in. */
1273 HeHASH(entry) = hash;
1275 /*PerlIO_printf(PerlIO_stderr(), "%d ", HeKFLAGS(entry));*/
1276 HEK_REHASH_on(HeKEY_hek(entry));
1277 /*PerlIO_printf(PerlIO_stderr(), "%d\n", HeKFLAGS(entry));*/
1279 /* Copy oentry to the correct new chain. */
1280 bep = ((HE**)a) + (hash & (I32) xhv->xhv_max);
1282 xhv->xhv_fill++; /* HvFILL(hv)++ */
1283 HeNEXT(entry) = *bep;
1289 Safefree (HvARRAY(hv));
1290 HvARRAY(hv) = (HE **)a;
1294 Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
1296 register XPVHV* xhv = (XPVHV*)SvANY(hv);
1297 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1298 register I32 newsize;
1303 register HE **oentry;
1305 newsize = (I32) newmax; /* possible truncation here */
1306 if (newsize != newmax || newmax <= oldsize)
1308 while ((newsize & (1 + ~newsize)) != newsize) {
1309 newsize &= ~(newsize & (1 + ~newsize)); /* get proper power of 2 */
1311 if (newsize < newmax)
1313 if (newsize < newmax)
1314 return; /* overflow detection */
1316 a = (char *) HvARRAY(hv);
1319 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1320 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1321 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1327 Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1330 New(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1331 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1336 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1338 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1340 if (oldsize >= 64) {
1341 offer_nice_chunk(HvARRAY(hv),
1342 PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
1343 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
1346 Safefree(HvARRAY(hv));
1349 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1352 Newz(0, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1354 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
1355 HvARRAY(hv) = (HE **) a;
1356 if (!xhv->xhv_fill /* !HvFILL(hv) */) /* skip rest if no entries */
1360 for (i=0; i<oldsize; i++,aep++) {
1361 if (!*aep) /* non-existent */
1363 for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1365 if ((j = (HeHASH(entry) & newsize)) != i) {
1367 *oentry = HeNEXT(entry);
1368 if (!(HeNEXT(entry) = aep[j]))
1369 xhv->xhv_fill++; /* HvFILL(hv)++ */
1374 oentry = &HeNEXT(entry);
1376 if (!*aep) /* everything moved */
1377 xhv->xhv_fill--; /* HvFILL(hv)-- */
1384 Creates a new HV. The reference count is set to 1.
1393 register XPVHV* xhv;
1395 hv = (HV*)NEWSV(502,0);
1396 sv_upgrade((SV *)hv, SVt_PVHV);
1397 xhv = (XPVHV*)SvANY(hv);
1400 #ifndef NODEFAULT_SHAREKEYS
1401 HvSHAREKEYS_on(hv); /* key-sharing on by default */
1404 xhv->xhv_max = 7; /* HvMAX(hv) = 7 (start with 8 buckets) */
1405 xhv->xhv_fill = 0; /* HvFILL(hv) = 0 */
1410 Perl_newHVhv(pTHX_ HV *ohv)
1413 STRLEN hv_max, hv_fill;
1415 if (!ohv || (hv_fill = HvFILL(ohv)) == 0)
1417 hv_max = HvMAX(ohv);
1419 if (!SvMAGICAL((SV *)ohv)) {
1420 /* It's an ordinary hash, so copy it fast. AMS 20010804 */
1422 const bool shared = !!HvSHAREKEYS(ohv);
1423 HE **ents, **oents = (HE **)HvARRAY(ohv);
1425 New(0, a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
1428 /* In each bucket... */
1429 for (i = 0; i <= hv_max; i++) {
1430 HE *prev = NULL, *ent = NULL, *oent = oents[i];
1437 /* Copy the linked list of entries. */
1438 for (oent = oents[i]; oent; oent = HeNEXT(oent)) {
1439 const U32 hash = HeHASH(oent);
1440 const char * const key = HeKEY(oent);
1441 const STRLEN len = HeKLEN(oent);
1442 const int flags = HeKFLAGS(oent);
1445 HeVAL(ent) = newSVsv(HeVAL(oent));
1447 = shared ? share_hek_flags(key, len, hash, flags)
1448 : save_hek_flags(key, len, hash, flags);
1459 HvFILL(hv) = hv_fill;
1460 HvTOTALKEYS(hv) = HvTOTALKEYS(ohv);
1464 /* Iterate over ohv, copying keys and values one at a time. */
1466 const I32 riter = HvRITER_get(ohv);
1467 HE * const eiter = HvEITER_get(ohv);
1469 /* Can we use fewer buckets? (hv_max is always 2^n-1) */
1470 while (hv_max && hv_max + 1 >= hv_fill * 2)
1471 hv_max = hv_max / 2;
1475 while ((entry = hv_iternext_flags(ohv, 0))) {
1476 hv_store_flags(hv, HeKEY(entry), HeKLEN(entry),
1477 newSVsv(HeVAL(entry)), HeHASH(entry),
1480 HvRITER_set(ohv, riter);
1481 HvEITER_set(ohv, eiter);
1488 Perl_hv_free_ent(pTHX_ HV *hv, register HE *entry)
1495 if (val && isGV(val) && GvCVu(val) && HvNAME_get(hv))
1496 PL_sub_generation++; /* may be deletion of method from stash */
1498 if (HeKLEN(entry) == HEf_SVKEY) {
1499 SvREFCNT_dec(HeKEY_sv(entry));
1500 Safefree(HeKEY_hek(entry));
1502 else if (HvSHAREKEYS(hv))
1503 unshare_hek(HeKEY_hek(entry));
1505 Safefree(HeKEY_hek(entry));
1510 Perl_hv_delayfree_ent(pTHX_ HV *hv, register HE *entry)
1514 if (isGV(HeVAL(entry)) && GvCVu(HeVAL(entry)) && HvNAME_get(hv))
1515 PL_sub_generation++; /* may be deletion of method from stash */
1516 sv_2mortal(HeVAL(entry)); /* free between statements */
1517 if (HeKLEN(entry) == HEf_SVKEY) {
1518 sv_2mortal(HeKEY_sv(entry));
1519 Safefree(HeKEY_hek(entry));
1521 else if (HvSHAREKEYS(hv))
1522 unshare_hek(HeKEY_hek(entry));
1524 Safefree(HeKEY_hek(entry));
1529 =for apidoc hv_clear
1531 Clears a hash, making it empty.
1537 Perl_hv_clear(pTHX_ HV *hv)
1540 register XPVHV* xhv;
1544 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1546 xhv = (XPVHV*)SvANY(hv);
1548 if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
1549 /* restricted hash: convert all keys to placeholders */
1551 for (i = 0; i <= xhv->xhv_max; i++) {
1552 HE *entry = (HvARRAY(hv))[i];
1553 for (; entry; entry = HeNEXT(entry)) {
1554 /* not already placeholder */
1555 if (HeVAL(entry) != &PL_sv_placeholder) {
1556 if (HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1557 SV* keysv = hv_iterkeysv(entry);
1559 "Attempt to delete readonly key '%"SVf"' from a restricted hash",
1562 SvREFCNT_dec(HeVAL(entry));
1563 HeVAL(entry) = &PL_sv_placeholder;
1564 HvPLACEHOLDERS(hv)++;
1572 HvPLACEHOLDERS_set(hv, 0);
1574 (void)memzero(HvARRAY(hv),
1575 (xhv->xhv_max+1 /* HvMAX(hv)+1 */) * sizeof(HE*));
1580 HvHASKFLAGS_off(hv);
1584 HvEITER_set(hv, NULL);
1589 =for apidoc hv_clear_placeholders
1591 Clears any placeholders from a hash. If a restricted hash has any of its keys
1592 marked as readonly and the key is subsequently deleted, the key is not actually
1593 deleted but is marked by assigning it a value of &PL_sv_placeholder. This tags
1594 it so it will be ignored by future operations such as iterating over the hash,
1595 but will still allow the hash to have a value reassigned to the key at some
1596 future point. This function clears any such placeholder keys from the hash.
1597 See Hash::Util::lock_keys() for an example of its use.
1603 Perl_hv_clear_placeholders(pTHX_ HV *hv)
1606 I32 items = (I32)HvPLACEHOLDERS_get(hv);
1614 /* Loop down the linked list heads */
1616 HE **oentry = &(HvARRAY(hv))[i];
1617 HE *entry = *oentry;
1622 for (; entry; entry = *oentry) {
1623 if (HeVAL(entry) == &PL_sv_placeholder) {
1624 *oentry = HeNEXT(entry);
1625 if (first && !*oentry)
1626 HvFILL(hv)--; /* This linked list is now empty. */
1627 if (HvEITER_get(hv))
1630 hv_free_ent(hv, entry);
1634 HvTOTALKEYS(hv) -= (IV)HvPLACEHOLDERS_get(hv);
1635 if (HvKEYS(hv) == 0)
1636 HvHASKFLAGS_off(hv);
1637 HvPLACEHOLDERS_set(hv, 0);
1641 oentry = &HeNEXT(entry);
1646 /* You can't get here, hence assertion should always fail. */
1647 assert (items == 0);
1652 S_hfreeentries(pTHX_ HV *hv)
1654 register HE **array;
1658 struct xpvhv_aux *iter;
1664 iter = SvOOK(hv) ? HvAUX(hv) : 0;
1668 array = HvARRAY(hv);
1669 /* make everyone else think the array is empty, so that the destructors
1670 * called for freed entries can't recusively mess with us */
1671 HvARRAY(hv) = Null(HE**);
1672 SvFLAGS(hv) &= ~SVf_OOK;
1675 ((XPVHV*) SvANY(hv))->xhv_keys = 0;
1680 register HE *oentry = entry;
1681 entry = HeNEXT(entry);
1682 hv_free_ent(hv, oentry);
1687 entry = array[riter];
1692 /* Someone attempted to iterate or set the hash name while we had
1693 the array set to 0. */
1694 assert(HvARRAY(hv));
1696 if (HvAUX(hv)->xhv_name)
1697 unshare_hek_or_pvn(HvAUX(hv)->xhv_name, 0, 0, 0);
1698 /* SvOOK_off calls sv_backoff, which isn't correct. */
1700 Safefree(HvARRAY(hv));
1702 SvFLAGS(hv) &= ~SVf_OOK;
1705 /* FIXME - things will still go horribly wrong (or at least leak) if
1706 people attempt to add elements to the hash while we're undef()ing it */
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*) */
1715 SvFLAGS(hv) |= SVf_OOK;
1718 HvARRAY(hv) = array;
1722 =for apidoc hv_undef
1730 Perl_hv_undef(pTHX_ HV *hv)
1732 register XPVHV* xhv;
1736 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1737 xhv = (XPVHV*)SvANY(hv);
1739 if ((name = HvNAME_get(hv))) {
1741 hv_delete(PL_stashcache, name, HvNAMELEN_get(hv), G_DISCARD);
1742 Perl_hv_name_set(aTHX_ hv, 0, 0, 0);
1744 SvFLAGS(hv) &= ~SVf_OOK;
1745 Safefree(HvARRAY(hv));
1746 xhv->xhv_max = 7; /* HvMAX(hv) = 7 (it's a normal hash) */
1748 HvPLACEHOLDERS_set(hv, 0);
1754 static struct xpvhv_aux*
1755 S_hv_auxinit(pTHX_ HV *hv) {
1756 struct xpvhv_aux *iter;
1760 Newz(0, array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1761 + sizeof(struct xpvhv_aux), char);
1763 array = (char *) HvARRAY(hv);
1764 Renew(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1765 + sizeof(struct xpvhv_aux), char);
1767 HvARRAY(hv) = (HE**) array;
1768 /* SvOOK_on(hv) attacks the IV flags. */
1769 SvFLAGS(hv) |= SVf_OOK;
1772 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1773 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1780 =for apidoc hv_iterinit
1782 Prepares a starting point to traverse a hash table. Returns the number of
1783 keys in the hash (i.e. the same as C<HvKEYS(tb)>). The return value is
1784 currently only meaningful for hashes without tie magic.
1786 NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
1787 hash buckets that happen to be in use. If you still need that esoteric
1788 value, you can get it through the macro C<HvFILL(tb)>.
1795 Perl_hv_iterinit(pTHX_ HV *hv)
1800 Perl_croak(aTHX_ "Bad hash");
1803 struct xpvhv_aux *iter = HvAUX(hv);
1804 entry = iter->xhv_eiter; /* HvEITER(hv) */
1805 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1807 hv_free_ent(hv, entry);
1809 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1810 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1812 S_hv_auxinit(aTHX_ hv);
1815 /* used to be xhv->xhv_fill before 5.004_65 */
1816 return HvTOTALKEYS(hv);
1820 Perl_hv_riter_p(pTHX_ HV *hv) {
1821 struct xpvhv_aux *iter;
1824 Perl_croak(aTHX_ "Bad hash");
1826 iter = SvOOK(hv) ? HvAUX(hv) : S_hv_auxinit(aTHX_ hv);
1827 return &(iter->xhv_riter);
1831 Perl_hv_eiter_p(pTHX_ HV *hv) {
1832 struct xpvhv_aux *iter;
1835 Perl_croak(aTHX_ "Bad hash");
1837 iter = SvOOK(hv) ? HvAUX(hv) : S_hv_auxinit(aTHX_ hv);
1838 return &(iter->xhv_eiter);
1842 Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
1843 struct xpvhv_aux *iter;
1846 Perl_croak(aTHX_ "Bad hash");
1854 iter = S_hv_auxinit(aTHX_ hv);
1856 iter->xhv_riter = riter;
1860 Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
1861 struct xpvhv_aux *iter;
1864 Perl_croak(aTHX_ "Bad hash");
1869 /* 0 is the default so don't go malloc()ing a new structure just to
1874 iter = S_hv_auxinit(aTHX_ hv);
1876 iter->xhv_eiter = eiter;
1880 Perl_hv_name_set(pTHX_ HV *hv, const char *name, I32 len, int flags)
1882 struct xpvhv_aux *iter;
1888 if (iter->xhv_name) {
1889 unshare_hek_or_pvn(iter->xhv_name, 0, 0, 0);
1895 iter = S_hv_auxinit(aTHX_ hv);
1897 PERL_HASH(hash, name, len);
1898 iter->xhv_name = name ? share_hek(name, len, hash) : 0;
1902 =for apidoc hv_iternext
1904 Returns entries from a hash iterator. See C<hv_iterinit>.
1906 You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
1907 iterator currently points to, without losing your place or invalidating your
1908 iterator. Note that in this case the current entry is deleted from the hash
1909 with your iterator holding the last reference to it. Your iterator is flagged
1910 to free the entry on the next call to C<hv_iternext>, so you must not discard
1911 your iterator immediately else the entry will leak - call C<hv_iternext> to
1912 trigger the resource deallocation.
1918 Perl_hv_iternext(pTHX_ HV *hv)
1920 return hv_iternext_flags(hv, 0);
1924 =for apidoc hv_iternext_flags
1926 Returns entries from a hash iterator. See C<hv_iterinit> and C<hv_iternext>.
1927 The C<flags> value will normally be zero; if HV_ITERNEXT_WANTPLACEHOLDERS is
1928 set the placeholders keys (for restricted hashes) will be returned in addition
1929 to normal keys. By default placeholders are automatically skipped over.
1930 Currently a placeholder is implemented with a value that is
1931 C<&Perl_sv_placeholder>. Note that the implementation of placeholders and
1932 restricted hashes may change, and the implementation currently is
1933 insufficiently abstracted for any change to be tidy.
1939 Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
1942 register XPVHV* xhv;
1946 struct xpvhv_aux *iter;
1949 Perl_croak(aTHX_ "Bad hash");
1950 xhv = (XPVHV*)SvANY(hv);
1953 /* Too many things (well, pp_each at least) merrily assume that you can
1954 call iv_iternext without calling hv_iterinit, so we'll have to deal
1960 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
1962 if ((mg = SvTIED_mg((SV*)hv, PERL_MAGIC_tied))) {
1963 SV *key = sv_newmortal();
1965 sv_setsv(key, HeSVKEY_force(entry));
1966 SvREFCNT_dec(HeSVKEY(entry)); /* get rid of previous key */
1972 /* one HE per MAGICAL hash */
1973 iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
1975 Newz(54, k, HEK_BASESIZE + sizeof(SV*), char);
1977 HeKEY_hek(entry) = hek;
1978 HeKLEN(entry) = HEf_SVKEY;
1980 magic_nextpack((SV*) hv,mg,key);
1982 /* force key to stay around until next time */
1983 HeSVKEY_set(entry, SvREFCNT_inc(key));
1984 return entry; /* beware, hent_val is not set */
1987 SvREFCNT_dec(HeVAL(entry));
1988 Safefree(HeKEY_hek(entry));
1990 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1993 #ifdef DYNAMIC_ENV_FETCH /* set up %ENV for iteration */
1994 if (!entry && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
1998 /* hv_iterint now ensures this. */
1999 assert (HvARRAY(hv));
2001 /* At start of hash, entry is NULL. */
2004 entry = HeNEXT(entry);
2005 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2007 * Skip past any placeholders -- don't want to include them in
2010 while (entry && HeVAL(entry) == &PL_sv_placeholder) {
2011 entry = HeNEXT(entry);
2016 /* OK. Come to the end of the current list. Grab the next one. */
2018 iter->xhv_riter++; /* HvRITER(hv)++ */
2019 if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
2020 /* There is no next one. End of the hash. */
2021 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2024 entry = (HvARRAY(hv))[iter->xhv_riter];
2026 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2027 /* If we have an entry, but it's a placeholder, don't count it.
2029 while (entry && HeVAL(entry) == &PL_sv_placeholder)
2030 entry = HeNEXT(entry);
2032 /* Will loop again if this linked list starts NULL
2033 (for HV_ITERNEXT_WANTPLACEHOLDERS)
2034 or if we run through it and find only placeholders. */
2037 if (oldentry && HvLAZYDEL(hv)) { /* was deleted earlier? */
2039 hv_free_ent(hv, oldentry);
2042 /*if (HvREHASH(hv) && entry && !HeKREHASH(entry))
2043 PerlIO_printf(PerlIO_stderr(), "Awooga %p %p\n", hv, entry);*/
2045 iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
2050 =for apidoc hv_iterkey
2052 Returns the key from the current position of the hash iterator. See
2059 Perl_hv_iterkey(pTHX_ register HE *entry, I32 *retlen)
2061 if (HeKLEN(entry) == HEf_SVKEY) {
2063 char *p = SvPV(HeKEY_sv(entry), len);
2068 *retlen = HeKLEN(entry);
2069 return HeKEY(entry);
2073 /* unlike hv_iterval(), this always returns a mortal copy of the key */
2075 =for apidoc hv_iterkeysv
2077 Returns the key as an C<SV*> from the current position of the hash
2078 iterator. The return value will always be a mortal copy of the key. Also
2085 Perl_hv_iterkeysv(pTHX_ register HE *entry)
2087 return sv_2mortal(newSVhek(HeKEY_hek(entry)));
2091 =for apidoc hv_iterval
2093 Returns the value from the current position of the hash iterator. See
2100 Perl_hv_iterval(pTHX_ HV *hv, register HE *entry)
2102 if (SvRMAGICAL(hv)) {
2103 if (mg_find((SV*)hv, PERL_MAGIC_tied)) {
2104 SV* sv = sv_newmortal();
2105 if (HeKLEN(entry) == HEf_SVKEY)
2106 mg_copy((SV*)hv, sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
2108 mg_copy((SV*)hv, sv, HeKEY(entry), HeKLEN(entry));
2112 return HeVAL(entry);
2116 =for apidoc hv_iternextsv
2118 Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2125 Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
2128 if ( (he = hv_iternext_flags(hv, 0)) == NULL)
2130 *key = hv_iterkey(he, retlen);
2131 return hv_iterval(hv, he);
2135 =for apidoc hv_magic
2137 Adds magic to a hash. See C<sv_magic>.
2143 Perl_hv_magic(pTHX_ HV *hv, GV *gv, int how)
2145 sv_magic((SV*)hv, (SV*)gv, how, Nullch, 0);
2148 #if 0 /* use the macro from hv.h instead */
2151 Perl_sharepvn(pTHX_ const char *sv, I32 len, U32 hash)
2153 return HEK_KEY(share_hek(sv, len, hash));
2158 /* possibly free a shared string if no one has access to it
2159 * len and hash must both be valid for str.
2162 Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
2164 unshare_hek_or_pvn (NULL, str, len, hash);
2169 Perl_unshare_hek(pTHX_ HEK *hek)
2171 unshare_hek_or_pvn(hek, NULL, 0, 0);
2174 /* possibly free a shared string if no one has access to it
2175 hek if non-NULL takes priority over the other 3, else str, len and hash
2176 are used. If so, len and hash must both be valid for str.
2179 S_unshare_hek_or_pvn(pTHX_ const HEK *hek, const char *str, I32 len, U32 hash)
2181 register XPVHV* xhv;
2183 register HE **oentry;
2186 bool is_utf8 = FALSE;
2188 const char *save = str;
2189 struct shared_he *he = 0;
2192 /* Find the shared he which is just before us in memory. */
2193 he = (struct shared_he *)(((char *)hek)
2194 - STRUCT_OFFSET(struct shared_he,
2197 /* Assert that the caller passed us a genuine (or at least consistent)
2199 assert (he->shared_he_he.hent_hek == hek);
2202 if (he->shared_he_he.hent_val - 1) {
2203 --he->shared_he_he.hent_val;
2204 UNLOCK_STRTAB_MUTEX;
2207 UNLOCK_STRTAB_MUTEX;
2209 hash = HEK_HASH(hek);
2210 } else if (len < 0) {
2211 STRLEN tmplen = -len;
2213 /* See the note in hv_fetch(). --jhi */
2214 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2217 k_flags = HVhek_UTF8;
2219 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2222 /* what follows is the moral equivalent of:
2223 if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
2224 if (--*Svp == Nullsv)
2225 hv_delete(PL_strtab, str, len, G_DISCARD, hash);
2227 xhv = (XPVHV*)SvANY(PL_strtab);
2228 /* assert(xhv_array != 0) */
2230 first = oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2232 const HE *const he_he = &(he->shared_he_he);
2233 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2240 const int flags_masked = k_flags & HVhek_MASK;
2241 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2242 if (HeHASH(entry) != hash) /* strings can't be equal */
2244 if (HeKLEN(entry) != len)
2246 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2248 if (HeKFLAGS(entry) != flags_masked)
2256 if (--HeVAL(entry) == Nullsv) {
2257 *oentry = HeNEXT(entry);
2259 /* There are now no entries in our slot. */
2260 xhv->xhv_fill--; /* HvFILL(hv)-- */
2263 xhv->xhv_keys--; /* HvKEYS(hv)-- */
2267 UNLOCK_STRTAB_MUTEX;
2268 if (!found && ckWARN_d(WARN_INTERNAL))
2269 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
2270 "Attempt to free non-existent shared string '%s'%s"
2272 hek ? HEK_KEY(hek) : str,
2273 ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
2274 if (k_flags & HVhek_FREEKEY)
2278 /* get a (constant) string ptr from the global string table
2279 * string will get added if it is not already there.
2280 * len and hash must both be valid for str.
2283 Perl_share_hek(pTHX_ const char *str, I32 len, register U32 hash)
2285 bool is_utf8 = FALSE;
2287 const char *save = str;
2290 STRLEN tmplen = -len;
2292 /* See the note in hv_fetch(). --jhi */
2293 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2295 /* If we were able to downgrade here, then than means that we were passed
2296 in a key which only had chars 0-255, but was utf8 encoded. */
2299 /* If we found we were able to downgrade the string to bytes, then
2300 we should flag that it needs upgrading on keys or each. Also flag
2301 that we need share_hek_flags to free the string. */
2303 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2306 return share_hek_flags (str, len, hash, flags);
2310 S_share_hek_flags(pTHX_ const char *str, I32 len, register U32 hash, int flags)
2313 register HE **oentry;
2315 const int flags_masked = flags & HVhek_MASK;
2317 /* what follows is the moral equivalent of:
2319 if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
2320 hv_store(PL_strtab, str, len, Nullsv, hash);
2322 Can't rehash the shared string table, so not sure if it's worth
2323 counting the number of entries in the linked list
2325 register XPVHV * const xhv = (XPVHV*)SvANY(PL_strtab);
2326 /* assert(xhv_array != 0) */
2328 oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2329 for (entry = *oentry; entry; entry = HeNEXT(entry)) {
2330 if (HeHASH(entry) != hash) /* strings can't be equal */
2332 if (HeKLEN(entry) != len)
2334 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2336 if (HeKFLAGS(entry) != flags_masked)
2342 /* What used to be head of the list.
2343 If this is NULL, then we're the first entry for this slot, which
2344 means we need to increate fill. */
2345 const HE *old_first = *oentry;
2346 struct shared_he *new_entry;
2350 /* We don't actually store a HE from the arena and a regular HEK.
2351 Instead we allocate one chunk of memory big enough for both,
2352 and put the HEK straight after the HE. This way we can find the
2353 HEK directly from the HE.
2356 New(0, k, STRUCT_OFFSET(struct shared_he,
2357 shared_he_hek.hek_key[0]) + len + 2, char);
2358 new_entry = (struct shared_he *)k;
2359 entry = &(new_entry->shared_he_he);
2360 hek = &(new_entry->shared_he_hek);
2362 Copy(str, HEK_KEY(hek), len, char);
2363 HEK_KEY(hek)[len] = 0;
2365 HEK_HASH(hek) = hash;
2366 HEK_FLAGS(hek) = (unsigned char)flags_masked;
2368 /* Still "point" to the HEK, so that other code need not know what
2370 HeKEY_hek(entry) = hek;
2371 HeVAL(entry) = Nullsv;
2372 HeNEXT(entry) = *oentry;
2375 xhv->xhv_keys++; /* HvKEYS(hv)++ */
2376 if (!old_first) { /* initial entry? */
2377 xhv->xhv_fill++; /* HvFILL(hv)++ */
2378 } else if (xhv->xhv_keys > (IV)xhv->xhv_max /* HvKEYS(hv) > HvMAX(hv) */) {
2383 ++HeVAL(entry); /* use value slot as REFCNT */
2384 UNLOCK_STRTAB_MUTEX;
2386 if (flags & HVhek_FREEKEY)
2389 return HeKEY_hek(entry);
2393 Perl_hv_placeholders_p(pTHX_ HV *hv)
2396 MAGIC *mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2399 mg = sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, 0);
2402 Perl_die(aTHX_ "panic: hv_placeholders_p");
2405 return &(mg->mg_len);
2410 Perl_hv_placeholders_get(pTHX_ HV *hv)
2413 MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2415 return mg ? mg->mg_len : 0;
2419 Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
2422 MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2427 if (!sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, ph))
2428 Perl_die(aTHX_ "panic: hv_placeholders_set");
2430 /* else we don't need to add magic to record 0 placeholders. */
2434 =for apidoc hv_assert
2436 Check that a hash is in an internally consistent state.
2442 Perl_hv_assert(pTHX_ HV *hv)
2447 int placeholders = 0;
2450 const I32 riter = HvRITER_get(hv);
2451 HE *eiter = HvEITER_get(hv);
2453 (void)hv_iterinit(hv);
2455 while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
2456 /* sanity check the values */
2457 if (HeVAL(entry) == &PL_sv_placeholder) {
2462 /* sanity check the keys */
2463 if (HeSVKEY(entry)) {
2464 /* Don't know what to check on SV keys. */
2465 } else if (HeKUTF8(entry)) {
2467 if (HeKWASUTF8(entry)) {
2468 PerlIO_printf(Perl_debug_log,
2469 "hash key has both WASUFT8 and UTF8: '%.*s'\n",
2470 (int) HeKLEN(entry), HeKEY(entry));
2473 } else if (HeKWASUTF8(entry)) {
2477 if (!SvTIED_mg((SV*)hv, PERL_MAGIC_tied)) {
2478 if (HvUSEDKEYS(hv) != real) {
2479 PerlIO_printf(Perl_debug_log, "Count %d key(s), but hash reports %d\n",
2480 (int) real, (int) HvUSEDKEYS(hv));
2483 if (HvPLACEHOLDERS_get(hv) != placeholders) {
2484 PerlIO_printf(Perl_debug_log,
2485 "Count %d placeholder(s), but hash reports %d\n",
2486 (int) placeholders, (int) HvPLACEHOLDERS_get(hv));
2490 if (withflags && ! HvHASKFLAGS(hv)) {
2491 PerlIO_printf(Perl_debug_log,
2492 "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
2499 HvRITER_set(hv, riter); /* Restore hash iterator state */
2500 HvEITER_set(hv, eiter);
2505 * c-indentation-style: bsd
2507 * indent-tabs-mode: t
2510 * ex: set ts=8 sts=4 sw=4 noet: