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) = PL_he_arenaroot;
48 heend = &he[PERL_ARENA_SIZE / sizeof(HE) - 1];
51 HeNEXT(he) = (HE*)(he + 1);
59 #define new_HE() (HE*)safemalloc(sizeof(HE))
60 #define del_HE(p) safefree((char*)p)
72 PL_he_root = HeNEXT(he);
77 #define new_HE() new_he()
81 HeNEXT(p) = (HE*)PL_he_root; \
91 S_save_hek_flags(pTHX_ const char *str, I32 len, U32 hash, int flags)
93 const int flags_masked = flags & HVhek_MASK;
97 Newx(k, HEK_BASESIZE + len + 2, char);
99 Copy(str, HEK_KEY(hek), len, char);
100 HEK_KEY(hek)[len] = 0;
102 HEK_HASH(hek) = hash;
103 HEK_FLAGS(hek) = (unsigned char)flags_masked;
105 if (flags & HVhek_FREEKEY)
110 /* free the pool of temporary HE/HEK pairs retunrned by hv_fetch_ent
114 Perl_free_tied_hv_pool(pTHX)
116 HE *he = PL_hv_fetch_ent_mh;
119 Safefree(HeKEY_hek(he));
123 PL_hv_fetch_ent_mh = Nullhe;
126 #if defined(USE_ITHREADS)
128 Perl_hek_dup(pTHX_ HEK *source, CLONE_PARAMS* param)
130 HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
132 PERL_UNUSED_ARG(param);
135 /* We already shared this hash key. */
136 (void)share_hek_hek(shared);
140 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
141 HEK_HASH(source), HEK_FLAGS(source));
142 ptr_table_store(PL_ptr_table, source, shared);
148 Perl_he_dup(pTHX_ const HE *e, bool shared, CLONE_PARAMS* param)
154 /* look for it in the table first */
155 ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
159 /* create anew and remember what it is */
161 ptr_table_store(PL_ptr_table, e, ret);
163 HeNEXT(ret) = he_dup(HeNEXT(e),shared, param);
164 if (HeKLEN(e) == HEf_SVKEY) {
166 Newx(k, HEK_BASESIZE + sizeof(SV*), char);
167 HeKEY_hek(ret) = (HEK*)k;
168 HeKEY_sv(ret) = SvREFCNT_inc(sv_dup(HeKEY_sv(e), param));
171 /* This is hek_dup inlined, which seems to be important for speed
173 HEK * const source = HeKEY_hek(e);
174 HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
177 /* We already shared this hash key. */
178 (void)share_hek_hek(shared);
182 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
183 HEK_HASH(source), HEK_FLAGS(source));
184 ptr_table_store(PL_ptr_table, source, shared);
186 HeKEY_hek(ret) = shared;
189 HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
191 HeVAL(ret) = SvREFCNT_inc(sv_dup(HeVAL(e), param));
194 #endif /* USE_ITHREADS */
197 S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
200 SV * const sv = sv_newmortal();
201 if (!(flags & HVhek_FREEKEY)) {
202 sv_setpvn(sv, key, klen);
205 /* Need to free saved eventually assign to mortal SV */
206 /* XXX is this line an error ???: SV *sv = sv_newmortal(); */
207 sv_usepvn(sv, (char *) key, klen);
209 if (flags & HVhek_UTF8) {
212 Perl_croak(aTHX_ msg, sv);
215 /* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
218 #define HV_FETCH_ISSTORE 0x01
219 #define HV_FETCH_ISEXISTS 0x02
220 #define HV_FETCH_LVALUE 0x04
221 #define HV_FETCH_JUST_SV 0x08
226 Stores an SV in a hash. The hash key is specified as C<key> and C<klen> is
227 the length of the key. The C<hash> parameter is the precomputed hash
228 value; if it is zero then Perl will compute it. The return value will be
229 NULL if the operation failed or if the value did not need to be actually
230 stored within the hash (as in the case of tied hashes). Otherwise it can
231 be dereferenced to get the original C<SV*>. Note that the caller is
232 responsible for suitably incrementing the reference count of C<val> before
233 the call, and decrementing it if the function returned NULL. Effectively
234 a successful hv_store takes ownership of one reference to C<val>. This is
235 usually what you want; a newly created SV has a reference count of one, so
236 if all your code does is create SVs then store them in a hash, hv_store
237 will own the only reference to the new SV, and your code doesn't need to do
238 anything further to tidy up. hv_store is not implemented as a call to
239 hv_store_ent, and does not create a temporary SV for the key, so if your
240 key data is not already in SV form then use hv_store in preference to
243 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
244 information on how to use this function on tied hashes.
250 Perl_hv_store(pTHX_ HV *hv, const char *key, I32 klen_i32, SV *val, U32 hash)
263 hek = hv_fetch_common (hv, NULL, key, klen, flags,
264 (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
265 return hek ? &HeVAL(hek) : NULL;
269 Perl_hv_store_flags(pTHX_ HV *hv, const char *key, I32 klen, SV *val,
270 register U32 hash, int flags)
272 HE * const hek = hv_fetch_common (hv, NULL, key, klen, flags,
273 (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
274 return hek ? &HeVAL(hek) : NULL;
278 =for apidoc hv_store_ent
280 Stores C<val> in a hash. The hash key is specified as C<key>. The C<hash>
281 parameter is the precomputed hash value; if it is zero then Perl will
282 compute it. The return value is the new hash entry so created. It will be
283 NULL if the operation failed or if the value did not need to be actually
284 stored within the hash (as in the case of tied hashes). Otherwise the
285 contents of the return value can be accessed using the C<He?> macros
286 described here. Note that the caller is responsible for suitably
287 incrementing the reference count of C<val> before the call, and
288 decrementing it if the function returned NULL. Effectively a successful
289 hv_store_ent takes ownership of one reference to C<val>. This is
290 usually what you want; a newly created SV has a reference count of one, so
291 if all your code does is create SVs then store them in a hash, hv_store
292 will own the only reference to the new SV, and your code doesn't need to do
293 anything further to tidy up. Note that hv_store_ent only reads the C<key>;
294 unlike C<val> it does not take ownership of it, so maintaining the correct
295 reference count on C<key> is entirely the caller's responsibility. hv_store
296 is not implemented as a call to hv_store_ent, and does not create a temporary
297 SV for the key, so if your key data is not already in SV form then use
298 hv_store in preference to hv_store_ent.
300 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
301 information on how to use this function on tied hashes.
307 Perl_hv_store_ent(pTHX_ HV *hv, SV *keysv, SV *val, U32 hash)
309 return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISSTORE, val, hash);
313 =for apidoc hv_exists
315 Returns a boolean indicating whether the specified hash key exists. The
316 C<klen> is the length of the key.
322 Perl_hv_exists(pTHX_ HV *hv, const char *key, I32 klen_i32)
334 return hv_fetch_common(hv, NULL, key, klen, flags, HV_FETCH_ISEXISTS, 0, 0)
341 Returns the SV which corresponds to the specified key in the hash. The
342 C<klen> is the length of the key. If C<lval> is set then the fetch will be
343 part of a store. Check that the return value is non-null before
344 dereferencing it to an C<SV*>.
346 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
347 information on how to use this function on tied hashes.
353 Perl_hv_fetch(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 lval)
366 hek = hv_fetch_common (hv, NULL, key, klen, flags,
367 HV_FETCH_JUST_SV | (lval ? HV_FETCH_LVALUE : 0),
369 return hek ? &HeVAL(hek) : NULL;
373 =for apidoc hv_exists_ent
375 Returns a boolean indicating whether the specified hash key exists. C<hash>
376 can be a valid precomputed hash value, or 0 to ask for it to be
383 Perl_hv_exists_ent(pTHX_ HV *hv, SV *keysv, U32 hash)
385 return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISEXISTS, 0, hash)
389 /* returns an HE * structure with the all fields set */
390 /* note that hent_val will be a mortal sv for MAGICAL hashes */
392 =for apidoc hv_fetch_ent
394 Returns the hash entry which corresponds to the specified key in the hash.
395 C<hash> must be a valid precomputed hash number for the given C<key>, or 0
396 if you want the function to compute it. IF C<lval> is set then the fetch
397 will be part of a store. Make sure the return value is non-null before
398 accessing it. The return value when C<tb> is a tied hash is a pointer to a
399 static location, so be sure to make a copy of the structure if you need to
402 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
403 information on how to use this function on tied hashes.
409 Perl_hv_fetch_ent(pTHX_ HV *hv, SV *keysv, I32 lval, register U32 hash)
411 return hv_fetch_common(hv, keysv, NULL, 0, 0,
412 (lval ? HV_FETCH_LVALUE : 0), Nullsv, hash);
416 S_hv_fetch_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
417 int flags, int action, SV *val, register U32 hash)
431 if (flags & HVhek_FREEKEY)
433 key = SvPV_const(keysv, klen);
435 is_utf8 = (SvUTF8(keysv) != 0);
437 is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
440 xhv = (XPVHV*)SvANY(hv);
442 if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS)))
444 if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
447 /* XXX should be able to skimp on the HE/HEK here when
448 HV_FETCH_JUST_SV is true. */
451 keysv = newSVpvn(key, klen);
456 keysv = newSVsv(keysv);
458 mg_copy((SV*)hv, sv, (char *)keysv, HEf_SVKEY);
460 /* grab a fake HE/HEK pair from the pool or make a new one */
461 entry = PL_hv_fetch_ent_mh;
463 PL_hv_fetch_ent_mh = HeNEXT(entry);
467 Newx(k, HEK_BASESIZE + sizeof(SV*), char);
468 HeKEY_hek(entry) = (HEK*)k;
470 HeNEXT(entry) = Nullhe;
471 HeSVKEY_set(entry, keysv);
473 sv_upgrade(sv, SVt_PVLV);
475 /* so we can free entry when freeing sv */
476 LvTARG(sv) = (SV*)entry;
478 /* XXX remove at some point? */
479 if (flags & HVhek_FREEKEY)
484 #ifdef ENV_IS_CASELESS
485 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
487 for (i = 0; i < klen; ++i)
488 if (isLOWER(key[i])) {
489 /* Would be nice if we had a routine to do the
490 copy and upercase in a single pass through. */
491 const char *nkey = strupr(savepvn(key,klen));
492 /* Note that this fetch is for nkey (the uppercased
493 key) whereas the store is for key (the original) */
494 entry = hv_fetch_common(hv, Nullsv, nkey, klen,
495 HVhek_FREEKEY, /* free nkey */
496 0 /* non-LVAL fetch */,
497 Nullsv /* no value */,
498 0 /* compute hash */);
499 if (!entry && (action & HV_FETCH_LVALUE)) {
500 /* This call will free key if necessary.
501 Do it this way to encourage compiler to tail
503 entry = hv_fetch_common(hv, keysv, key, klen,
504 flags, HV_FETCH_ISSTORE,
507 if (flags & HVhek_FREEKEY)
515 else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
516 if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
517 /* I don't understand why hv_exists_ent has svret and sv,
518 whereas hv_exists only had one. */
519 SV * const svret = sv_newmortal();
522 if (keysv || is_utf8) {
524 keysv = newSVpvn(key, klen);
527 keysv = newSVsv(keysv);
529 mg_copy((SV*)hv, sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
531 mg_copy((SV*)hv, sv, key, klen);
533 if (flags & HVhek_FREEKEY)
535 magic_existspack(svret, mg_find(sv, PERL_MAGIC_tiedelem));
536 /* This cast somewhat evil, but I'm merely using NULL/
537 not NULL to return the boolean exists.
538 And I know hv is not NULL. */
539 return SvTRUE(svret) ? (HE *)hv : NULL;
541 #ifdef ENV_IS_CASELESS
542 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
543 /* XXX This code isn't UTF8 clean. */
544 char * const keysave = (char * const)key;
545 /* Will need to free this, so set FREEKEY flag. */
546 key = savepvn(key,klen);
547 key = (const char*)strupr((char*)key);
552 if (flags & HVhek_FREEKEY) {
555 flags |= HVhek_FREEKEY;
559 else if (action & HV_FETCH_ISSTORE) {
562 hv_magic_check (hv, &needs_copy, &needs_store);
564 const bool save_taint = PL_tainted;
565 if (keysv || is_utf8) {
567 keysv = newSVpvn(key, klen);
571 PL_tainted = SvTAINTED(keysv);
572 keysv = sv_2mortal(newSVsv(keysv));
573 mg_copy((SV*)hv, val, (char*)keysv, HEf_SVKEY);
575 mg_copy((SV*)hv, val, key, klen);
578 TAINT_IF(save_taint);
579 if (!HvARRAY(hv) && !needs_store) {
580 if (flags & HVhek_FREEKEY)
584 #ifdef ENV_IS_CASELESS
585 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
586 /* XXX This code isn't UTF8 clean. */
587 const char *keysave = key;
588 /* Will need to free this, so set FREEKEY flag. */
589 key = savepvn(key,klen);
590 key = (const char*)strupr((char*)key);
595 if (flags & HVhek_FREEKEY) {
598 flags |= HVhek_FREEKEY;
606 if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
607 #ifdef DYNAMIC_ENV_FETCH /* if it's an %ENV lookup, we may get it on the fly */
608 || (SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
613 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
615 HvARRAY(hv) = (HE**)array;
617 #ifdef DYNAMIC_ENV_FETCH
618 else if (action & HV_FETCH_ISEXISTS) {
619 /* for an %ENV exists, if we do an insert it's by a recursive
620 store call, so avoid creating HvARRAY(hv) right now. */
624 /* XXX remove at some point? */
625 if (flags & HVhek_FREEKEY)
633 char * const keysave = (char * const)key;
634 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
638 flags &= ~HVhek_UTF8;
639 if (key != keysave) {
640 if (flags & HVhek_FREEKEY)
642 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
647 PERL_HASH_INTERNAL(hash, key, klen);
648 /* We don't have a pointer to the hv, so we have to replicate the
649 flag into every HEK, so that hv_iterkeysv can see it. */
650 /* And yes, you do need this even though you are not "storing" because
651 you can flip the flags below if doing an lval lookup. (And that
652 was put in to give the semantics Andreas was expecting.) */
653 flags |= HVhek_REHASH;
655 if (keysv && (SvIsCOW_shared_hash(keysv))) {
656 hash = SvSHARED_HASH(keysv);
658 PERL_HASH(hash, key, klen);
662 masked_flags = (flags & HVhek_MASK);
664 #ifdef DYNAMIC_ENV_FETCH
665 if (!HvARRAY(hv)) entry = Null(HE*);
669 entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
671 for (; entry; entry = HeNEXT(entry)) {
672 if (HeHASH(entry) != hash) /* strings can't be equal */
674 if (HeKLEN(entry) != (I32)klen)
676 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
678 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
681 if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
682 if (HeKFLAGS(entry) != masked_flags) {
683 /* We match if HVhek_UTF8 bit in our flags and hash key's
684 match. But if entry was set previously with HVhek_WASUTF8
685 and key now doesn't (or vice versa) then we should change
686 the key's flag, as this is assignment. */
687 if (HvSHAREKEYS(hv)) {
688 /* Need to swap the key we have for a key with the flags we
689 need. As keys are shared we can't just write to the
690 flag, so we share the new one, unshare the old one. */
691 HEK *new_hek = share_hek_flags(key, klen, hash,
693 unshare_hek (HeKEY_hek(entry));
694 HeKEY_hek(entry) = new_hek;
696 else if (hv == PL_strtab) {
697 /* PL_strtab is usually the only hash without HvSHAREKEYS,
698 so putting this test here is cheap */
699 if (flags & HVhek_FREEKEY)
701 Perl_croak(aTHX_ S_strtab_error,
702 action & HV_FETCH_LVALUE ? "fetch" : "store");
705 HeKFLAGS(entry) = masked_flags;
706 if (masked_flags & HVhek_ENABLEHVKFLAGS)
709 if (HeVAL(entry) == &PL_sv_placeholder) {
710 /* yes, can store into placeholder slot */
711 if (action & HV_FETCH_LVALUE) {
713 /* This preserves behaviour with the old hv_fetch
714 implementation which at this point would bail out
715 with a break; (at "if we find a placeholder, we
716 pretend we haven't found anything")
718 That break mean that if a placeholder were found, it
719 caused a call into hv_store, which in turn would
720 check magic, and if there is no magic end up pretty
721 much back at this point (in hv_store's code). */
724 /* LVAL fetch which actaully needs a store. */
726 HvPLACEHOLDERS(hv)--;
729 if (val != &PL_sv_placeholder)
730 HvPLACEHOLDERS(hv)--;
733 } else if (action & HV_FETCH_ISSTORE) {
734 SvREFCNT_dec(HeVAL(entry));
737 } else if (HeVAL(entry) == &PL_sv_placeholder) {
738 /* if we find a placeholder, we pretend we haven't found
742 if (flags & HVhek_FREEKEY)
746 #ifdef DYNAMIC_ENV_FETCH /* %ENV lookup? If so, try to fetch the value now */
747 if (!(action & HV_FETCH_ISSTORE)
748 && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
750 const char * const env = PerlEnv_ENVgetenv_len(key,&len);
752 sv = newSVpvn(env,len);
754 return hv_fetch_common(hv,keysv,key,klen,flags,HV_FETCH_ISSTORE,sv,
760 if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
761 S_hv_notallowed(aTHX_ flags, key, klen,
762 "Attempt to access disallowed key '%"SVf"' in"
763 " a restricted hash");
765 if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
766 /* Not doing some form of store, so return failure. */
767 if (flags & HVhek_FREEKEY)
771 if (action & HV_FETCH_LVALUE) {
774 /* At this point the old hv_fetch code would call to hv_store,
775 which in turn might do some tied magic. So we need to make that
776 magic check happen. */
777 /* gonna assign to this, so it better be there */
778 return hv_fetch_common(hv, keysv, key, klen, flags,
779 HV_FETCH_ISSTORE, val, hash);
780 /* XXX Surely that could leak if the fetch-was-store fails?
781 Just like the hv_fetch. */
785 /* Welcome to hv_store... */
788 /* Not sure if we can get here. I think the only case of oentry being
789 NULL is for %ENV with dynamic env fetch. But that should disappear
790 with magic in the previous code. */
793 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
795 HvARRAY(hv) = (HE**)array;
798 oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
801 /* share_hek_flags will do the free for us. This might be considered
804 HeKEY_hek(entry) = share_hek_flags(key, klen, hash, flags);
805 else if (hv == PL_strtab) {
806 /* PL_strtab is usually the only hash without HvSHAREKEYS, so putting
807 this test here is cheap */
808 if (flags & HVhek_FREEKEY)
810 Perl_croak(aTHX_ S_strtab_error,
811 action & HV_FETCH_LVALUE ? "fetch" : "store");
813 else /* gotta do the real thing */
814 HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
816 HeNEXT(entry) = *oentry;
819 if (val == &PL_sv_placeholder)
820 HvPLACEHOLDERS(hv)++;
821 if (masked_flags & HVhek_ENABLEHVKFLAGS)
825 const HE *counter = HeNEXT(entry);
827 xhv->xhv_keys++; /* HvKEYS(hv)++ */
828 if (!counter) { /* initial entry? */
829 xhv->xhv_fill++; /* HvFILL(hv)++ */
830 } else if (xhv->xhv_keys > (IV)xhv->xhv_max) {
832 } else if(!HvREHASH(hv)) {
835 while ((counter = HeNEXT(counter)))
838 if (n_links > HV_MAX_LENGTH_BEFORE_SPLIT) {
839 /* Use only the old HvKEYS(hv) > HvMAX(hv) condition to limit
840 bucket splits on a rehashed hash, as we're not going to
841 split it again, and if someone is lucky (evil) enough to
842 get all the keys in one list they could exhaust our memory
843 as we repeatedly double the number of buckets on every
844 entry. Linear search feels a less worse thing to do. */
854 S_hv_magic_check(pTHX_ HV *hv, bool *needs_copy, bool *needs_store)
856 const MAGIC *mg = SvMAGIC(hv);
860 if (isUPPER(mg->mg_type)) {
862 if (mg->mg_type == PERL_MAGIC_tied) {
863 *needs_store = FALSE;
864 return; /* We've set all there is to set. */
867 mg = mg->mg_moremagic;
872 =for apidoc hv_scalar
874 Evaluates the hash in scalar context and returns the result. Handles magic when the hash is tied.
880 Perl_hv_scalar(pTHX_ HV *hv)
884 if (SvRMAGICAL(hv)) {
885 MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_tied);
887 return magic_scalarpack(hv, mg);
892 Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
893 (long)HvFILL(hv), (long)HvMAX(hv) + 1);
901 =for apidoc hv_delete
903 Deletes a key/value pair in the hash. The value SV is removed from the
904 hash and returned to the caller. The C<klen> is the length of the key.
905 The C<flags> value will normally be zero; if set to G_DISCARD then NULL
912 Perl_hv_delete(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 flags)
919 k_flags |= HVhek_UTF8;
923 return hv_delete_common(hv, NULL, key, klen, k_flags, flags, 0);
927 =for apidoc hv_delete_ent
929 Deletes a key/value pair in the hash. The value SV is removed from the
930 hash and returned to the caller. The C<flags> value will normally be zero;
931 if set to G_DISCARD then NULL will be returned. C<hash> can be a valid
932 precomputed hash value, or 0 to ask for it to be computed.
938 Perl_hv_delete_ent(pTHX_ HV *hv, SV *keysv, I32 flags, U32 hash)
940 return hv_delete_common(hv, keysv, NULL, 0, 0, flags, hash);
944 S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
945 int k_flags, I32 d_flags, U32 hash)
950 register HE **oentry;
951 HE *const *first_entry;
960 if (k_flags & HVhek_FREEKEY)
962 key = SvPV_const(keysv, klen);
964 is_utf8 = (SvUTF8(keysv) != 0);
966 is_utf8 = ((k_flags & HVhek_UTF8) ? TRUE : FALSE);
969 if (SvRMAGICAL(hv)) {
972 hv_magic_check (hv, &needs_copy, &needs_store);
975 entry = hv_fetch_common(hv, keysv, key, klen,
976 k_flags & ~HVhek_FREEKEY, HV_FETCH_LVALUE,
978 sv = entry ? HeVAL(entry) : NULL;
984 if (mg_find(sv, PERL_MAGIC_tiedelem)) {
985 /* No longer an element */
986 sv_unmagic(sv, PERL_MAGIC_tiedelem);
989 return Nullsv; /* element cannot be deleted */
991 #ifdef ENV_IS_CASELESS
992 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
993 /* XXX This code isn't UTF8 clean. */
994 keysv = sv_2mortal(newSVpvn(key,klen));
995 if (k_flags & HVhek_FREEKEY) {
998 key = strupr(SvPVX(keysv));
1007 xhv = (XPVHV*)SvANY(hv);
1012 const char *keysave = key;
1013 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
1016 k_flags |= HVhek_UTF8;
1018 k_flags &= ~HVhek_UTF8;
1019 if (key != keysave) {
1020 if (k_flags & HVhek_FREEKEY) {
1021 /* This shouldn't happen if our caller does what we expect,
1022 but strictly the API allows it. */
1025 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
1027 HvHASKFLAGS_on((SV*)hv);
1031 PERL_HASH_INTERNAL(hash, key, klen);
1033 if (keysv && (SvIsCOW_shared_hash(keysv))) {
1034 hash = SvSHARED_HASH(keysv);
1036 PERL_HASH(hash, key, klen);
1040 masked_flags = (k_flags & HVhek_MASK);
1042 first_entry = oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
1044 for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
1045 if (HeHASH(entry) != hash) /* strings can't be equal */
1047 if (HeKLEN(entry) != (I32)klen)
1049 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
1051 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
1054 if (hv == PL_strtab) {
1055 if (k_flags & HVhek_FREEKEY)
1057 Perl_croak(aTHX_ S_strtab_error, "delete");
1060 /* if placeholder is here, it's already been deleted.... */
1061 if (HeVAL(entry) == &PL_sv_placeholder)
1063 if (k_flags & HVhek_FREEKEY)
1067 else if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1068 S_hv_notallowed(aTHX_ k_flags, key, klen,
1069 "Attempt to delete readonly key '%"SVf"' from"
1070 " a restricted hash");
1072 if (k_flags & HVhek_FREEKEY)
1075 if (d_flags & G_DISCARD)
1078 sv = sv_2mortal(HeVAL(entry));
1079 HeVAL(entry) = &PL_sv_placeholder;
1083 * If a restricted hash, rather than really deleting the entry, put
1084 * a placeholder there. This marks the key as being "approved", so
1085 * we can still access via not-really-existing key without raising
1088 if (SvREADONLY(hv)) {
1089 SvREFCNT_dec(HeVAL(entry));
1090 HeVAL(entry) = &PL_sv_placeholder;
1091 /* We'll be saving this slot, so the number of allocated keys
1092 * doesn't go down, but the number placeholders goes up */
1093 HvPLACEHOLDERS(hv)++;
1095 *oentry = HeNEXT(entry);
1097 xhv->xhv_fill--; /* HvFILL(hv)-- */
1099 if (SvOOK(hv) && entry == HvAUX(hv)->xhv_eiter /* HvEITER(hv) */)
1102 hv_free_ent(hv, entry);
1103 xhv->xhv_keys--; /* HvKEYS(hv)-- */
1104 if (xhv->xhv_keys == 0)
1105 HvHASKFLAGS_off(hv);
1109 if (SvREADONLY(hv)) {
1110 S_hv_notallowed(aTHX_ k_flags, key, klen,
1111 "Attempt to delete disallowed key '%"SVf"' from"
1112 " a restricted hash");
1115 if (k_flags & HVhek_FREEKEY)
1121 S_hsplit(pTHX_ HV *hv)
1123 register XPVHV* xhv = (XPVHV*)SvANY(hv);
1124 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1125 register I32 newsize = oldsize * 2;
1127 char *a = (char*) HvARRAY(hv);
1129 register HE **oentry;
1130 int longest_chain = 0;
1133 /*PerlIO_printf(PerlIO_stderr(), "hsplit called for %p which had %d\n",
1134 hv, (int) oldsize);*/
1136 if (HvPLACEHOLDERS_get(hv) && !SvREADONLY(hv)) {
1137 /* Can make this clear any placeholders first for non-restricted hashes,
1138 even though Storable rebuilds restricted hashes by putting in all the
1139 placeholders (first) before turning on the readonly flag, because
1140 Storable always pre-splits the hash. */
1141 hv_clear_placeholders(hv);
1145 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1146 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1147 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1153 Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1156 Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1157 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1162 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1164 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1166 if (oldsize >= 64) {
1167 offer_nice_chunk(HvARRAY(hv),
1168 PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
1169 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
1172 Safefree(HvARRAY(hv));
1176 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1177 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
1178 HvARRAY(hv) = (HE**) a;
1181 for (i=0; i<oldsize; i++,aep++) {
1182 int left_length = 0;
1183 int right_length = 0;
1187 if (!*aep) /* non-existent */
1190 for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1191 if ((HeHASH(entry) & newsize) != (U32)i) {
1192 *oentry = HeNEXT(entry);
1193 HeNEXT(entry) = *bep;
1195 xhv->xhv_fill++; /* HvFILL(hv)++ */
1201 oentry = &HeNEXT(entry);
1205 if (!*aep) /* everything moved */
1206 xhv->xhv_fill--; /* HvFILL(hv)-- */
1207 /* I think we don't actually need to keep track of the longest length,
1208 merely flag if anything is too long. But for the moment while
1209 developing this code I'll track it. */
1210 if (left_length > longest_chain)
1211 longest_chain = left_length;
1212 if (right_length > longest_chain)
1213 longest_chain = right_length;
1217 /* Pick your policy for "hashing isn't working" here: */
1218 if (longest_chain <= HV_MAX_LENGTH_BEFORE_SPLIT /* split worked? */
1223 if (hv == PL_strtab) {
1224 /* Urg. Someone is doing something nasty to the string table.
1229 /* Awooga. Awooga. Pathological data. */
1230 /*PerlIO_printf(PerlIO_stderr(), "%p %d of %d with %d/%d buckets\n", hv,
1231 longest_chain, HvTOTALKEYS(hv), HvFILL(hv), 1+HvMAX(hv));*/
1234 Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1235 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1237 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1240 was_shared = HvSHAREKEYS(hv);
1243 HvSHAREKEYS_off(hv);
1248 for (i=0; i<newsize; i++,aep++) {
1249 register HE *entry = *aep;
1251 /* We're going to trash this HE's next pointer when we chain it
1252 into the new hash below, so store where we go next. */
1253 HE * const next = HeNEXT(entry);
1258 PERL_HASH_INTERNAL(hash, HeKEY(entry), HeKLEN(entry));
1263 = save_hek_flags(HeKEY(entry), HeKLEN(entry),
1264 hash, HeKFLAGS(entry));
1265 unshare_hek (HeKEY_hek(entry));
1266 HeKEY_hek(entry) = new_hek;
1268 /* Not shared, so simply write the new hash in. */
1269 HeHASH(entry) = hash;
1271 /*PerlIO_printf(PerlIO_stderr(), "%d ", HeKFLAGS(entry));*/
1272 HEK_REHASH_on(HeKEY_hek(entry));
1273 /*PerlIO_printf(PerlIO_stderr(), "%d\n", HeKFLAGS(entry));*/
1275 /* Copy oentry to the correct new chain. */
1276 bep = ((HE**)a) + (hash & (I32) xhv->xhv_max);
1278 xhv->xhv_fill++; /* HvFILL(hv)++ */
1279 HeNEXT(entry) = *bep;
1285 Safefree (HvARRAY(hv));
1286 HvARRAY(hv) = (HE **)a;
1290 Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
1292 register XPVHV* xhv = (XPVHV*)SvANY(hv);
1293 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1294 register I32 newsize;
1299 register HE **oentry;
1301 newsize = (I32) newmax; /* possible truncation here */
1302 if (newsize != newmax || newmax <= oldsize)
1304 while ((newsize & (1 + ~newsize)) != newsize) {
1305 newsize &= ~(newsize & (1 + ~newsize)); /* get proper power of 2 */
1307 if (newsize < newmax)
1309 if (newsize < newmax)
1310 return; /* overflow detection */
1312 a = (char *) HvARRAY(hv);
1315 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1316 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1317 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1323 Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1326 Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1327 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1332 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1334 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1336 if (oldsize >= 64) {
1337 offer_nice_chunk(HvARRAY(hv),
1338 PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
1339 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
1342 Safefree(HvARRAY(hv));
1345 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1348 Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1350 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
1351 HvARRAY(hv) = (HE **) a;
1352 if (!xhv->xhv_fill /* !HvFILL(hv) */) /* skip rest if no entries */
1356 for (i=0; i<oldsize; i++,aep++) {
1357 if (!*aep) /* non-existent */
1359 for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1361 if ((j = (HeHASH(entry) & newsize)) != i) {
1363 *oentry = HeNEXT(entry);
1364 if (!(HeNEXT(entry) = aep[j]))
1365 xhv->xhv_fill++; /* HvFILL(hv)++ */
1370 oentry = &HeNEXT(entry);
1372 if (!*aep) /* everything moved */
1373 xhv->xhv_fill--; /* HvFILL(hv)-- */
1380 Creates a new HV. The reference count is set to 1.
1388 register XPVHV* xhv;
1389 HV * const hv = (HV*)NEWSV(502,0);
1391 sv_upgrade((SV *)hv, SVt_PVHV);
1392 xhv = (XPVHV*)SvANY(hv);
1395 #ifndef NODEFAULT_SHAREKEYS
1396 HvSHAREKEYS_on(hv); /* key-sharing on by default */
1399 xhv->xhv_max = 7; /* HvMAX(hv) = 7 (start with 8 buckets) */
1400 xhv->xhv_fill = 0; /* HvFILL(hv) = 0 */
1405 Perl_newHVhv(pTHX_ HV *ohv)
1407 HV * const hv = newHV();
1408 STRLEN hv_max, hv_fill;
1410 if (!ohv || (hv_fill = HvFILL(ohv)) == 0)
1412 hv_max = HvMAX(ohv);
1414 if (!SvMAGICAL((SV *)ohv)) {
1415 /* It's an ordinary hash, so copy it fast. AMS 20010804 */
1417 const bool shared = !!HvSHAREKEYS(ohv);
1418 HE **ents, ** const oents = (HE **)HvARRAY(ohv);
1420 Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
1423 /* In each bucket... */
1424 for (i = 0; i <= hv_max; i++) {
1425 HE *prev = NULL, *ent = NULL;
1426 HE *oent = oents[i];
1433 /* Copy the linked list of entries. */
1434 for (; oent; oent = HeNEXT(oent)) {
1435 const U32 hash = HeHASH(oent);
1436 const char * const key = HeKEY(oent);
1437 const STRLEN len = HeKLEN(oent);
1438 const int flags = HeKFLAGS(oent);
1441 HeVAL(ent) = newSVsv(HeVAL(oent));
1443 = shared ? share_hek_flags(key, len, hash, flags)
1444 : save_hek_flags(key, len, hash, flags);
1455 HvFILL(hv) = hv_fill;
1456 HvTOTALKEYS(hv) = HvTOTALKEYS(ohv);
1460 /* Iterate over ohv, copying keys and values one at a time. */
1462 const I32 riter = HvRITER_get(ohv);
1463 HE * const eiter = HvEITER_get(ohv);
1465 /* Can we use fewer buckets? (hv_max is always 2^n-1) */
1466 while (hv_max && hv_max + 1 >= hv_fill * 2)
1467 hv_max = hv_max / 2;
1471 while ((entry = hv_iternext_flags(ohv, 0))) {
1472 hv_store_flags(hv, HeKEY(entry), HeKLEN(entry),
1473 newSVsv(HeVAL(entry)), HeHASH(entry),
1476 HvRITER_set(ohv, riter);
1477 HvEITER_set(ohv, eiter);
1484 Perl_hv_free_ent(pTHX_ HV *hv, register HE *entry)
1491 if (val && isGV(val) && GvCVu(val) && HvNAME_get(hv))
1492 PL_sub_generation++; /* may be deletion of method from stash */
1494 if (HeKLEN(entry) == HEf_SVKEY) {
1495 SvREFCNT_dec(HeKEY_sv(entry));
1496 Safefree(HeKEY_hek(entry));
1498 else if (HvSHAREKEYS(hv))
1499 unshare_hek(HeKEY_hek(entry));
1501 Safefree(HeKEY_hek(entry));
1506 Perl_hv_delayfree_ent(pTHX_ HV *hv, register HE *entry)
1510 /* SvREFCNT_inc to counter the SvREFCNT_dec in hv_free_ent */
1511 sv_2mortal(SvREFCNT_inc(HeVAL(entry))); /* free between statements */
1512 if (HeKLEN(entry) == HEf_SVKEY) {
1513 sv_2mortal(SvREFCNT_inc(HeKEY_sv(entry)));
1515 hv_free_ent(hv, entry);
1519 =for apidoc hv_clear
1521 Clears a hash, making it empty.
1527 Perl_hv_clear(pTHX_ HV *hv)
1530 register XPVHV* xhv;
1534 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1536 xhv = (XPVHV*)SvANY(hv);
1538 if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
1539 /* restricted hash: convert all keys to placeholders */
1541 for (i = 0; i <= xhv->xhv_max; i++) {
1542 HE *entry = (HvARRAY(hv))[i];
1543 for (; entry; entry = HeNEXT(entry)) {
1544 /* not already placeholder */
1545 if (HeVAL(entry) != &PL_sv_placeholder) {
1546 if (HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1547 SV* keysv = hv_iterkeysv(entry);
1549 "Attempt to delete readonly key '%"SVf"' from a restricted hash",
1552 SvREFCNT_dec(HeVAL(entry));
1553 HeVAL(entry) = &PL_sv_placeholder;
1554 HvPLACEHOLDERS(hv)++;
1562 HvPLACEHOLDERS_set(hv, 0);
1564 (void)memzero(HvARRAY(hv),
1565 (xhv->xhv_max+1 /* HvMAX(hv)+1 */) * sizeof(HE*));
1570 HvHASKFLAGS_off(hv);
1574 HvEITER_set(hv, NULL);
1579 =for apidoc hv_clear_placeholders
1581 Clears any placeholders from a hash. If a restricted hash has any of its keys
1582 marked as readonly and the key is subsequently deleted, the key is not actually
1583 deleted but is marked by assigning it a value of &PL_sv_placeholder. This tags
1584 it so it will be ignored by future operations such as iterating over the hash,
1585 but will still allow the hash to have a value reassigned to the key at some
1586 future point. This function clears any such placeholder keys from the hash.
1587 See Hash::Util::lock_keys() for an example of its use.
1593 Perl_hv_clear_placeholders(pTHX_ HV *hv)
1596 I32 items = (I32)HvPLACEHOLDERS_get(hv);
1604 /* Loop down the linked list heads */
1606 HE **oentry = &(HvARRAY(hv))[i];
1607 HE *entry = *oentry;
1612 for (; entry; entry = *oentry) {
1613 if (HeVAL(entry) == &PL_sv_placeholder) {
1614 *oentry = HeNEXT(entry);
1615 if (first && !*oentry)
1616 HvFILL(hv)--; /* This linked list is now empty. */
1617 if (HvEITER_get(hv))
1620 hv_free_ent(hv, entry);
1624 HvTOTALKEYS(hv) -= (IV)HvPLACEHOLDERS_get(hv);
1625 if (HvKEYS(hv) == 0)
1626 HvHASKFLAGS_off(hv);
1627 HvPLACEHOLDERS_set(hv, 0);
1631 oentry = &HeNEXT(entry);
1636 /* You can't get here, hence assertion should always fail. */
1637 assert (items == 0);
1642 S_hfreeentries(pTHX_ HV *hv)
1644 register HE **array;
1648 struct xpvhv_aux *iter;
1653 iter = SvOOK(hv) ? HvAUX(hv) : 0;
1657 array = HvARRAY(hv);
1658 /* make everyone else think the array is empty, so that the destructors
1659 * called for freed entries can't recusively mess with us */
1660 HvARRAY(hv) = Null(HE**);
1661 SvFLAGS(hv) &= ~SVf_OOK;
1664 ((XPVHV*) SvANY(hv))->xhv_keys = 0;
1669 register HE * const oentry = entry;
1670 entry = HeNEXT(entry);
1671 hv_free_ent(hv, oentry);
1676 entry = array[riter];
1681 /* Someone attempted to iterate or set the hash name while we had
1682 the array set to 0. */
1683 assert(HvARRAY(hv));
1685 if (HvAUX(hv)->xhv_name)
1686 unshare_hek_or_pvn(HvAUX(hv)->xhv_name, 0, 0, 0);
1687 /* SvOOK_off calls sv_backoff, which isn't correct. */
1689 Safefree(HvARRAY(hv));
1691 SvFLAGS(hv) &= ~SVf_OOK;
1694 /* FIXME - things will still go horribly wrong (or at least leak) if
1695 people attempt to add elements to the hash while we're undef()ing it */
1697 entry = iter->xhv_eiter; /* HvEITER(hv) */
1698 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1700 hv_free_ent(hv, entry);
1702 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1703 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1704 SvFLAGS(hv) |= SVf_OOK;
1707 HvARRAY(hv) = array;
1711 =for apidoc hv_undef
1719 Perl_hv_undef(pTHX_ HV *hv)
1721 register XPVHV* xhv;
1725 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1726 xhv = (XPVHV*)SvANY(hv);
1728 if ((name = HvNAME_get(hv))) {
1730 hv_delete(PL_stashcache, name, HvNAMELEN_get(hv), G_DISCARD);
1731 hv_name_set(hv, Nullch, 0, 0);
1733 SvFLAGS(hv) &= ~SVf_OOK;
1734 Safefree(HvARRAY(hv));
1735 xhv->xhv_max = 7; /* HvMAX(hv) = 7 (it's a normal hash) */
1737 HvPLACEHOLDERS_set(hv, 0);
1743 static struct xpvhv_aux*
1744 S_hv_auxinit(pTHX_ HV *hv) {
1745 struct xpvhv_aux *iter;
1749 Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1750 + sizeof(struct xpvhv_aux), char);
1752 array = (char *) HvARRAY(hv);
1753 Renew(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1754 + sizeof(struct xpvhv_aux), char);
1756 HvARRAY(hv) = (HE**) array;
1757 /* SvOOK_on(hv) attacks the IV flags. */
1758 SvFLAGS(hv) |= SVf_OOK;
1761 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1762 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1769 =for apidoc hv_iterinit
1771 Prepares a starting point to traverse a hash table. Returns the number of
1772 keys in the hash (i.e. the same as C<HvKEYS(tb)>). The return value is
1773 currently only meaningful for hashes without tie magic.
1775 NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
1776 hash buckets that happen to be in use. If you still need that esoteric
1777 value, you can get it through the macro C<HvFILL(tb)>.
1784 Perl_hv_iterinit(pTHX_ HV *hv)
1789 Perl_croak(aTHX_ "Bad hash");
1792 struct xpvhv_aux *iter = HvAUX(hv);
1793 entry = iter->xhv_eiter; /* HvEITER(hv) */
1794 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1796 hv_free_ent(hv, entry);
1798 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1799 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1801 S_hv_auxinit(aTHX_ hv);
1804 /* used to be xhv->xhv_fill before 5.004_65 */
1805 return HvTOTALKEYS(hv);
1809 Perl_hv_riter_p(pTHX_ HV *hv) {
1810 struct xpvhv_aux *iter;
1813 Perl_croak(aTHX_ "Bad hash");
1815 iter = SvOOK(hv) ? HvAUX(hv) : S_hv_auxinit(aTHX_ hv);
1816 return &(iter->xhv_riter);
1820 Perl_hv_eiter_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_eiter);
1831 Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
1832 struct xpvhv_aux *iter;
1835 Perl_croak(aTHX_ "Bad hash");
1843 iter = S_hv_auxinit(aTHX_ hv);
1845 iter->xhv_riter = riter;
1849 Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
1850 struct xpvhv_aux *iter;
1853 Perl_croak(aTHX_ "Bad hash");
1858 /* 0 is the default so don't go malloc()ing a new structure just to
1863 iter = S_hv_auxinit(aTHX_ hv);
1865 iter->xhv_eiter = eiter;
1869 Perl_hv_name_set(pTHX_ HV *hv, const char *name, I32 len, int flags)
1871 struct xpvhv_aux *iter;
1874 PERL_UNUSED_ARG(flags);
1878 if (iter->xhv_name) {
1879 unshare_hek_or_pvn(iter->xhv_name, 0, 0, 0);
1885 iter = S_hv_auxinit(aTHX_ hv);
1887 PERL_HASH(hash, name, len);
1888 iter->xhv_name = name ? share_hek(name, len, hash) : 0;
1892 =for apidoc hv_iternext
1894 Returns entries from a hash iterator. See C<hv_iterinit>.
1896 You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
1897 iterator currently points to, without losing your place or invalidating your
1898 iterator. Note that in this case the current entry is deleted from the hash
1899 with your iterator holding the last reference to it. Your iterator is flagged
1900 to free the entry on the next call to C<hv_iternext>, so you must not discard
1901 your iterator immediately else the entry will leak - call C<hv_iternext> to
1902 trigger the resource deallocation.
1908 Perl_hv_iternext(pTHX_ HV *hv)
1910 return hv_iternext_flags(hv, 0);
1914 =for apidoc hv_iternext_flags
1916 Returns entries from a hash iterator. See C<hv_iterinit> and C<hv_iternext>.
1917 The C<flags> value will normally be zero; if HV_ITERNEXT_WANTPLACEHOLDERS is
1918 set the placeholders keys (for restricted hashes) will be returned in addition
1919 to normal keys. By default placeholders are automatically skipped over.
1920 Currently a placeholder is implemented with a value that is
1921 C<&Perl_sv_placeholder>. Note that the implementation of placeholders and
1922 restricted hashes may change, and the implementation currently is
1923 insufficiently abstracted for any change to be tidy.
1929 Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
1932 register XPVHV* xhv;
1936 struct xpvhv_aux *iter;
1939 Perl_croak(aTHX_ "Bad hash");
1940 xhv = (XPVHV*)SvANY(hv);
1943 /* Too many things (well, pp_each at least) merrily assume that you can
1944 call iv_iternext without calling hv_iterinit, so we'll have to deal
1950 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
1952 if ((mg = SvTIED_mg((SV*)hv, PERL_MAGIC_tied))) {
1953 SV *key = sv_newmortal();
1955 sv_setsv(key, HeSVKEY_force(entry));
1956 SvREFCNT_dec(HeSVKEY(entry)); /* get rid of previous key */
1962 /* one HE per MAGICAL hash */
1963 iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
1965 Newxz(k, HEK_BASESIZE + sizeof(SV*), char);
1967 HeKEY_hek(entry) = hek;
1968 HeKLEN(entry) = HEf_SVKEY;
1970 magic_nextpack((SV*) hv,mg,key);
1972 /* force key to stay around until next time */
1973 HeSVKEY_set(entry, SvREFCNT_inc(key));
1974 return entry; /* beware, hent_val is not set */
1977 SvREFCNT_dec(HeVAL(entry));
1978 Safefree(HeKEY_hek(entry));
1980 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1983 #ifdef DYNAMIC_ENV_FETCH /* set up %ENV for iteration */
1984 if (!entry && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
1987 /* The prime_env_iter() on VMS just loaded up new hash values
1988 * so the iteration count needs to be reset back to the beginning
1992 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
1997 /* hv_iterint now ensures this. */
1998 assert (HvARRAY(hv));
2000 /* At start of hash, entry is NULL. */
2003 entry = HeNEXT(entry);
2004 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2006 * Skip past any placeholders -- don't want to include them in
2009 while (entry && HeVAL(entry) == &PL_sv_placeholder) {
2010 entry = HeNEXT(entry);
2015 /* OK. Come to the end of the current list. Grab the next one. */
2017 iter->xhv_riter++; /* HvRITER(hv)++ */
2018 if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
2019 /* There is no next one. End of the hash. */
2020 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2023 entry = (HvARRAY(hv))[iter->xhv_riter];
2025 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2026 /* If we have an entry, but it's a placeholder, don't count it.
2028 while (entry && HeVAL(entry) == &PL_sv_placeholder)
2029 entry = HeNEXT(entry);
2031 /* Will loop again if this linked list starts NULL
2032 (for HV_ITERNEXT_WANTPLACEHOLDERS)
2033 or if we run through it and find only placeholders. */
2036 if (oldentry && HvLAZYDEL(hv)) { /* was deleted earlier? */
2038 hv_free_ent(hv, oldentry);
2041 /*if (HvREHASH(hv) && entry && !HeKREHASH(entry))
2042 PerlIO_printf(PerlIO_stderr(), "Awooga %p %p\n", hv, entry);*/
2044 iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
2049 =for apidoc hv_iterkey
2051 Returns the key from the current position of the hash iterator. See
2058 Perl_hv_iterkey(pTHX_ register HE *entry, I32 *retlen)
2060 if (HeKLEN(entry) == HEf_SVKEY) {
2062 char *p = SvPV(HeKEY_sv(entry), len);
2067 *retlen = HeKLEN(entry);
2068 return HeKEY(entry);
2072 /* unlike hv_iterval(), this always returns a mortal copy of the key */
2074 =for apidoc hv_iterkeysv
2076 Returns the key as an C<SV*> from the current position of the hash
2077 iterator. The return value will always be a mortal copy of the key. Also
2084 Perl_hv_iterkeysv(pTHX_ register HE *entry)
2086 return sv_2mortal(newSVhek(HeKEY_hek(entry)));
2090 =for apidoc hv_iterval
2092 Returns the value from the current position of the hash iterator. See
2099 Perl_hv_iterval(pTHX_ HV *hv, register HE *entry)
2101 if (SvRMAGICAL(hv)) {
2102 if (mg_find((SV*)hv, PERL_MAGIC_tied)) {
2103 SV* sv = sv_newmortal();
2104 if (HeKLEN(entry) == HEf_SVKEY)
2105 mg_copy((SV*)hv, sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
2107 mg_copy((SV*)hv, sv, HeKEY(entry), HeKLEN(entry));
2111 return HeVAL(entry);
2115 =for apidoc hv_iternextsv
2117 Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2124 Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
2127 if ( (he = hv_iternext_flags(hv, 0)) == NULL)
2129 *key = hv_iterkey(he, retlen);
2130 return hv_iterval(hv, he);
2134 =for apidoc hv_magic
2136 Adds magic to a hash. See C<sv_magic>.
2142 Perl_hv_magic(pTHX_ HV *hv, GV *gv, int how)
2144 sv_magic((SV*)hv, (SV*)gv, how, Nullch, 0);
2147 #if 0 /* use the macro from hv.h instead */
2150 Perl_sharepvn(pTHX_ const char *sv, I32 len, U32 hash)
2152 return HEK_KEY(share_hek(sv, len, hash));
2157 /* possibly free a shared string if no one has access to it
2158 * len and hash must both be valid for str.
2161 Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
2163 unshare_hek_or_pvn (NULL, str, len, hash);
2168 Perl_unshare_hek(pTHX_ HEK *hek)
2170 unshare_hek_or_pvn(hek, NULL, 0, 0);
2173 /* possibly free a shared string if no one has access to it
2174 hek if non-NULL takes priority over the other 3, else str, len and hash
2175 are used. If so, len and hash must both be valid for str.
2178 S_unshare_hek_or_pvn(pTHX_ const HEK *hek, const char *str, I32 len, U32 hash)
2180 register XPVHV* xhv;
2182 register HE **oentry;
2185 bool is_utf8 = FALSE;
2187 const char * const save = str;
2188 struct shared_he *he = 0;
2191 /* Find the shared he which is just before us in memory. */
2192 he = (struct shared_he *)(((char *)hek)
2193 - STRUCT_OFFSET(struct shared_he,
2196 /* Assert that the caller passed us a genuine (or at least consistent)
2198 assert (he->shared_he_he.hent_hek == hek);
2201 if (he->shared_he_he.hent_val - 1) {
2202 --he->shared_he_he.hent_val;
2203 UNLOCK_STRTAB_MUTEX;
2206 UNLOCK_STRTAB_MUTEX;
2208 hash = HEK_HASH(hek);
2209 } else if (len < 0) {
2210 STRLEN tmplen = -len;
2212 /* See the note in hv_fetch(). --jhi */
2213 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2216 k_flags = HVhek_UTF8;
2218 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2221 /* what follows is the moral equivalent of:
2222 if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
2223 if (--*Svp == Nullsv)
2224 hv_delete(PL_strtab, str, len, G_DISCARD, hash);
2226 xhv = (XPVHV*)SvANY(PL_strtab);
2227 /* assert(xhv_array != 0) */
2229 first = oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2231 const HE *const he_he = &(he->shared_he_he);
2232 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2239 const int flags_masked = k_flags & HVhek_MASK;
2240 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2241 if (HeHASH(entry) != hash) /* strings can't be equal */
2243 if (HeKLEN(entry) != len)
2245 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2247 if (HeKFLAGS(entry) != flags_masked)
2255 if (--HeVAL(entry) == Nullsv) {
2256 *oentry = HeNEXT(entry);
2258 /* There are now no entries in our slot. */
2259 xhv->xhv_fill--; /* HvFILL(hv)-- */
2262 xhv->xhv_keys--; /* HvKEYS(hv)-- */
2266 UNLOCK_STRTAB_MUTEX;
2267 if (!found && ckWARN_d(WARN_INTERNAL))
2268 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
2269 "Attempt to free non-existent shared string '%s'%s"
2271 hek ? HEK_KEY(hek) : str,
2272 ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
2273 if (k_flags & HVhek_FREEKEY)
2277 /* get a (constant) string ptr from the global string table
2278 * string will get added if it is not already there.
2279 * len and hash must both be valid for str.
2282 Perl_share_hek(pTHX_ const char *str, I32 len, register U32 hash)
2284 bool is_utf8 = FALSE;
2286 const char * const save = str;
2289 STRLEN tmplen = -len;
2291 /* See the note in hv_fetch(). --jhi */
2292 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2294 /* If we were able to downgrade here, then than means that we were passed
2295 in a key which only had chars 0-255, but was utf8 encoded. */
2298 /* If we found we were able to downgrade the string to bytes, then
2299 we should flag that it needs upgrading on keys or each. Also flag
2300 that we need share_hek_flags to free the string. */
2302 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2305 return share_hek_flags (str, len, hash, flags);
2309 S_share_hek_flags(pTHX_ const char *str, I32 len, register U32 hash, int flags)
2312 register HE **oentry;
2314 const int flags_masked = flags & HVhek_MASK;
2316 /* what follows is the moral equivalent of:
2318 if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
2319 hv_store(PL_strtab, str, len, Nullsv, hash);
2321 Can't rehash the shared string table, so not sure if it's worth
2322 counting the number of entries in the linked list
2324 register XPVHV * const xhv = (XPVHV*)SvANY(PL_strtab);
2325 /* assert(xhv_array != 0) */
2327 oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2328 for (entry = *oentry; entry; entry = HeNEXT(entry)) {
2329 if (HeHASH(entry) != hash) /* strings can't be equal */
2331 if (HeKLEN(entry) != len)
2333 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2335 if (HeKFLAGS(entry) != flags_masked)
2341 /* What used to be head of the list.
2342 If this is NULL, then we're the first entry for this slot, which
2343 means we need to increate fill. */
2344 const HE *old_first = *oentry;
2345 struct shared_he *new_entry;
2349 /* We don't actually store a HE from the arena and a regular HEK.
2350 Instead we allocate one chunk of memory big enough for both,
2351 and put the HEK straight after the HE. This way we can find the
2352 HEK directly from the HE.
2355 Newx(k, STRUCT_OFFSET(struct shared_he,
2356 shared_he_hek.hek_key[0]) + len + 2, char);
2357 new_entry = (struct shared_he *)k;
2358 entry = &(new_entry->shared_he_he);
2359 hek = &(new_entry->shared_he_hek);
2361 Copy(str, HEK_KEY(hek), len, char);
2362 HEK_KEY(hek)[len] = 0;
2364 HEK_HASH(hek) = hash;
2365 HEK_FLAGS(hek) = (unsigned char)flags_masked;
2367 /* Still "point" to the HEK, so that other code need not know what
2369 HeKEY_hek(entry) = hek;
2370 HeVAL(entry) = Nullsv;
2371 HeNEXT(entry) = *oentry;
2374 xhv->xhv_keys++; /* HvKEYS(hv)++ */
2375 if (!old_first) { /* initial entry? */
2376 xhv->xhv_fill++; /* HvFILL(hv)++ */
2377 } else if (xhv->xhv_keys > (IV)xhv->xhv_max /* HvKEYS(hv) > HvMAX(hv) */) {
2382 ++HeVAL(entry); /* use value slot as REFCNT */
2383 UNLOCK_STRTAB_MUTEX;
2385 if (flags & HVhek_FREEKEY)
2388 return HeKEY_hek(entry);
2392 Perl_hv_placeholders_p(pTHX_ HV *hv)
2395 MAGIC *mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2398 mg = sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, 0);
2401 Perl_die(aTHX_ "panic: hv_placeholders_p");
2404 return &(mg->mg_len);
2409 Perl_hv_placeholders_get(pTHX_ HV *hv)
2412 MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2414 return mg ? mg->mg_len : 0;
2418 Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
2421 MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2426 if (!sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, ph))
2427 Perl_die(aTHX_ "panic: hv_placeholders_set");
2429 /* else we don't need to add magic to record 0 placeholders. */
2433 =for apidoc hv_assert
2435 Check that a hash is in an internally consistent state.
2441 Perl_hv_assert(pTHX_ HV *hv)
2446 int placeholders = 0;
2449 const I32 riter = HvRITER_get(hv);
2450 HE *eiter = HvEITER_get(hv);
2452 (void)hv_iterinit(hv);
2454 while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
2455 /* sanity check the values */
2456 if (HeVAL(entry) == &PL_sv_placeholder) {
2461 /* sanity check the keys */
2462 if (HeSVKEY(entry)) {
2463 /* Don't know what to check on SV keys. */
2464 } else if (HeKUTF8(entry)) {
2466 if (HeKWASUTF8(entry)) {
2467 PerlIO_printf(Perl_debug_log,
2468 "hash key has both WASUFT8 and UTF8: '%.*s'\n",
2469 (int) HeKLEN(entry), HeKEY(entry));
2472 } else if (HeKWASUTF8(entry)) {
2476 if (!SvTIED_mg((SV*)hv, PERL_MAGIC_tied)) {
2477 if (HvUSEDKEYS(hv) != real) {
2478 PerlIO_printf(Perl_debug_log, "Count %d key(s), but hash reports %d\n",
2479 (int) real, (int) HvUSEDKEYS(hv));
2482 if (HvPLACEHOLDERS_get(hv) != placeholders) {
2483 PerlIO_printf(Perl_debug_log,
2484 "Count %d placeholder(s), but hash reports %d\n",
2485 (int) placeholders, (int) HvPLACEHOLDERS_get(hv));
2489 if (withflags && ! HvHASKFLAGS(hv)) {
2490 PerlIO_printf(Perl_debug_log,
2491 "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
2498 HvRITER_set(hv, riter); /* Restore hash iterator state */
2499 HvEITER_set(hv, eiter);
2504 * c-indentation-style: bsd
2506 * indent-tabs-mode: t
2509 * ex: set ts=8 sts=4 sw=4 noet: