3 * Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 * 2000, 2001, 2002, 2003, 2004, 2005, by Larry Wall and others
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
12 * "I sit beside the fire and think of all that I have seen." --Bilbo
16 =head1 Hash Manipulation Functions
18 A HV structure represents a Perl hash. It consists mainly of an array
19 of pointers, each of which points to a linked list of HE structures. The
20 array is indexed by the hash function of the key, so each linked list
21 represents all the hash entries with the same hash value. Each HE contains
22 a pointer to the actual value, plus a pointer to a HEK structure which
23 holds the key and hash value.
31 #define PERL_HASH_INTERNAL_ACCESS
34 #define HV_MAX_LENGTH_BEFORE_SPLIT 14
41 New(54, he, PERL_ARENA_SIZE/sizeof(HE), HE);
42 HeNEXT(he) = PL_he_arenaroot;
45 heend = &he[PERL_ARENA_SIZE / sizeof(HE) - 1];
48 HeNEXT(he) = (HE*)(he + 1);
62 PL_he_root = HeNEXT(he);
71 HeNEXT(p) = (HE*)PL_he_root;
78 #define new_HE() (HE*)safemalloc(sizeof(HE))
79 #define del_HE(p) safefree((char*)p)
83 #define new_HE() new_he()
84 #define del_HE(p) del_he(p)
89 S_save_hek_flags(pTHX_ const char *str, I32 len, U32 hash, int flags)
91 const int flags_masked = flags & HVhek_MASK;
95 New(54, k, HEK_BASESIZE + len + 2, char);
97 Copy(str, HEK_KEY(hek), len, char);
98 HEK_KEY(hek)[len] = 0;
100 HEK_HASH(hek) = hash;
101 HEK_FLAGS(hek) = (unsigned char)flags_masked;
103 if (flags & HVhek_FREEKEY)
108 /* free the pool of temporary HE/HEK pairs retunrned by hv_fetch_ent
112 Perl_free_tied_hv_pool(pTHX)
115 HE *he = PL_hv_fetch_ent_mh;
117 Safefree(HeKEY_hek(he));
122 PL_hv_fetch_ent_mh = Nullhe;
125 #if defined(USE_ITHREADS)
127 Perl_he_dup(pTHX_ HE *e, bool shared, CLONE_PARAMS* param)
133 /* look for it in the table first */
134 ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
138 /* create anew and remember what it is */
140 ptr_table_store(PL_ptr_table, e, ret);
142 HeNEXT(ret) = he_dup(HeNEXT(e),shared, param);
143 if (HeKLEN(e) == HEf_SVKEY) {
145 New(54, k, HEK_BASESIZE + sizeof(SV*), char);
146 HeKEY_hek(ret) = (HEK*)k;
147 HeKEY_sv(ret) = SvREFCNT_inc(sv_dup(HeKEY_sv(e), param));
150 HEK *source = HeKEY_hek(e);
151 HE *shared = (HE*)ptr_table_fetch(PL_shared_hek_table, source);
154 /* We already shared this hash key. */
158 shared = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
159 HEK_HASH(source), HEK_FLAGS(source));
160 ptr_table_store(PL_shared_hek_table, source, shared);
162 HeKEY_hek(ret) = HeKEY_hek(shared);
165 HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
167 HeVAL(ret) = SvREFCNT_inc(sv_dup(HeVAL(e), param));
170 #endif /* USE_ITHREADS */
173 S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
176 SV *sv = sv_newmortal();
177 if (!(flags & HVhek_FREEKEY)) {
178 sv_setpvn(sv, key, klen);
181 /* Need to free saved eventually assign to mortal SV */
182 /* XXX is this line an error ???: SV *sv = sv_newmortal(); */
183 sv_usepvn(sv, (char *) key, klen);
185 if (flags & HVhek_UTF8) {
188 Perl_croak(aTHX_ msg, sv);
191 /* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
194 #define HV_FETCH_ISSTORE 0x01
195 #define HV_FETCH_ISEXISTS 0x02
196 #define HV_FETCH_LVALUE 0x04
197 #define HV_FETCH_JUST_SV 0x08
202 Stores an SV in a hash. The hash key is specified as C<key> and C<klen> is
203 the length of the key. The C<hash> parameter is the precomputed hash
204 value; if it is zero then Perl will compute it. The return value will be
205 NULL if the operation failed or if the value did not need to be actually
206 stored within the hash (as in the case of tied hashes). Otherwise it can
207 be dereferenced to get the original C<SV*>. Note that the caller is
208 responsible for suitably incrementing the reference count of C<val> before
209 the call, and decrementing it if the function returned NULL. Effectively
210 a successful hv_store takes ownership of one reference to C<val>. This is
211 usually what you want; a newly created SV has a reference count of one, so
212 if all your code does is create SVs then store them in a hash, hv_store
213 will own the only reference to the new SV, and your code doesn't need to do
214 anything further to tidy up. hv_store is not implemented as a call to
215 hv_store_ent, and does not create a temporary SV for the key, so if your
216 key data is not already in SV form then use hv_store in preference to
219 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
220 information on how to use this function on tied hashes.
226 Perl_hv_store(pTHX_ HV *hv, const char *key, I32 klen_i32, SV *val, U32 hash)
239 hek = hv_fetch_common (hv, NULL, key, klen, flags,
240 (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
241 return hek ? &HeVAL(hek) : NULL;
245 Perl_hv_store_flags(pTHX_ HV *hv, const char *key, I32 klen, SV *val,
246 register U32 hash, int flags)
248 HE *hek = hv_fetch_common (hv, NULL, key, klen, flags,
249 (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
250 return hek ? &HeVAL(hek) : NULL;
254 =for apidoc hv_store_ent
256 Stores C<val> in a hash. The hash key is specified as C<key>. The C<hash>
257 parameter is the precomputed hash value; if it is zero then Perl will
258 compute it. The return value is the new hash entry so created. It will be
259 NULL if the operation failed or if the value did not need to be actually
260 stored within the hash (as in the case of tied hashes). Otherwise the
261 contents of the return value can be accessed using the C<He?> macros
262 described here. Note that the caller is responsible for suitably
263 incrementing the reference count of C<val> before the call, and
264 decrementing it if the function returned NULL. Effectively a successful
265 hv_store_ent takes ownership of one reference to C<val>. This is
266 usually what you want; a newly created SV has a reference count of one, so
267 if all your code does is create SVs then store them in a hash, hv_store
268 will own the only reference to the new SV, and your code doesn't need to do
269 anything further to tidy up. Note that hv_store_ent only reads the C<key>;
270 unlike C<val> it does not take ownership of it, so maintaining the correct
271 reference count on C<key> is entirely the caller's responsibility. hv_store
272 is not implemented as a call to hv_store_ent, and does not create a temporary
273 SV for the key, so if your key data is not already in SV form then use
274 hv_store in preference to hv_store_ent.
276 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
277 information on how to use this function on tied hashes.
283 Perl_hv_store_ent(pTHX_ HV *hv, SV *keysv, SV *val, U32 hash)
285 return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISSTORE, val, hash);
289 =for apidoc hv_exists
291 Returns a boolean indicating whether the specified hash key exists. The
292 C<klen> is the length of the key.
298 Perl_hv_exists(pTHX_ HV *hv, const char *key, I32 klen_i32)
310 return hv_fetch_common(hv, NULL, key, klen, flags, HV_FETCH_ISEXISTS, 0, 0)
317 Returns the SV which corresponds to the specified key in the hash. The
318 C<klen> is the length of the key. If C<lval> is set then the fetch will be
319 part of a store. Check that the return value is non-null before
320 dereferencing it to an C<SV*>.
322 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
323 information on how to use this function on tied hashes.
329 Perl_hv_fetch(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 lval)
342 hek = hv_fetch_common (hv, NULL, key, klen, flags,
343 HV_FETCH_JUST_SV | (lval ? HV_FETCH_LVALUE : 0),
345 return hek ? &HeVAL(hek) : NULL;
349 =for apidoc hv_exists_ent
351 Returns a boolean indicating whether the specified hash key exists. C<hash>
352 can be a valid precomputed hash value, or 0 to ask for it to be
359 Perl_hv_exists_ent(pTHX_ HV *hv, SV *keysv, U32 hash)
361 return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISEXISTS, 0, hash)
365 /* returns an HE * structure with the all fields set */
366 /* note that hent_val will be a mortal sv for MAGICAL hashes */
368 =for apidoc hv_fetch_ent
370 Returns the hash entry which corresponds to the specified key in the hash.
371 C<hash> must be a valid precomputed hash number for the given C<key>, or 0
372 if you want the function to compute it. IF C<lval> is set then the fetch
373 will be part of a store. Make sure the return value is non-null before
374 accessing it. The return value when C<tb> is a tied hash is a pointer to a
375 static location, so be sure to make a copy of the structure if you need to
378 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
379 information on how to use this function on tied hashes.
385 Perl_hv_fetch_ent(pTHX_ HV *hv, SV *keysv, I32 lval, register U32 hash)
387 return hv_fetch_common(hv, keysv, NULL, 0, 0,
388 (lval ? HV_FETCH_LVALUE : 0), Nullsv, hash);
392 S_hv_fetch_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
393 int flags, int action, SV *val, register U32 hash)
408 if (flags & HVhek_FREEKEY)
410 key = SvPV(keysv, klen);
412 is_utf8 = (SvUTF8(keysv) != 0);
414 is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
417 xhv = (XPVHV*)SvANY(hv);
419 if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS)))
421 if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
424 /* XXX should be able to skimp on the HE/HEK here when
425 HV_FETCH_JUST_SV is true. */
428 keysv = newSVpvn(key, klen);
433 keysv = newSVsv(keysv);
435 mg_copy((SV*)hv, sv, (char *)keysv, HEf_SVKEY);
437 /* grab a fake HE/HEK pair from the pool or make a new one */
438 entry = PL_hv_fetch_ent_mh;
440 PL_hv_fetch_ent_mh = HeNEXT(entry);
444 New(54, k, HEK_BASESIZE + sizeof(SV*), char);
445 HeKEY_hek(entry) = (HEK*)k;
447 HeNEXT(entry) = Nullhe;
448 HeSVKEY_set(entry, keysv);
450 sv_upgrade(sv, SVt_PVLV);
452 /* so we can free entry when freeing sv */
453 LvTARG(sv) = (SV*)entry;
455 /* XXX remove at some point? */
456 if (flags & HVhek_FREEKEY)
461 #ifdef ENV_IS_CASELESS
462 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
464 for (i = 0; i < klen; ++i)
465 if (isLOWER(key[i])) {
466 /* Would be nice if we had a routine to do the
467 copy and upercase in a single pass through. */
468 const char *nkey = strupr(savepvn(key,klen));
469 /* Note that this fetch is for nkey (the uppercased
470 key) whereas the store is for key (the original) */
471 entry = hv_fetch_common(hv, Nullsv, nkey, klen,
472 HVhek_FREEKEY, /* free nkey */
473 0 /* non-LVAL fetch */,
474 Nullsv /* no value */,
475 0 /* compute hash */);
476 if (!entry && (action & HV_FETCH_LVALUE)) {
477 /* This call will free key if necessary.
478 Do it this way to encourage compiler to tail
480 entry = hv_fetch_common(hv, keysv, key, klen,
481 flags, HV_FETCH_ISSTORE,
484 if (flags & HVhek_FREEKEY)
492 else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
493 if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
495 /* I don't understand why hv_exists_ent has svret and sv,
496 whereas hv_exists only had one. */
497 svret = sv_newmortal();
500 if (keysv || is_utf8) {
502 keysv = newSVpvn(key, klen);
505 keysv = newSVsv(keysv);
507 mg_copy((SV*)hv, sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
509 mg_copy((SV*)hv, sv, key, klen);
511 if (flags & HVhek_FREEKEY)
513 magic_existspack(svret, mg_find(sv, PERL_MAGIC_tiedelem));
514 /* This cast somewhat evil, but I'm merely using NULL/
515 not NULL to return the boolean exists.
516 And I know hv is not NULL. */
517 return SvTRUE(svret) ? (HE *)hv : NULL;
519 #ifdef ENV_IS_CASELESS
520 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
521 /* XXX This code isn't UTF8 clean. */
522 const char *keysave = key;
523 /* Will need to free this, so set FREEKEY flag. */
524 key = savepvn(key,klen);
525 key = (const char*)strupr((char*)key);
530 if (flags & HVhek_FREEKEY) {
533 flags |= HVhek_FREEKEY;
537 else if (action & HV_FETCH_ISSTORE) {
540 hv_magic_check (hv, &needs_copy, &needs_store);
542 const bool save_taint = PL_tainted;
543 if (keysv || is_utf8) {
545 keysv = newSVpvn(key, klen);
549 PL_tainted = SvTAINTED(keysv);
550 keysv = sv_2mortal(newSVsv(keysv));
551 mg_copy((SV*)hv, val, (char*)keysv, HEf_SVKEY);
553 mg_copy((SV*)hv, val, key, klen);
556 TAINT_IF(save_taint);
557 if (!HvARRAY(hv) && !needs_store) {
558 if (flags & HVhek_FREEKEY)
562 #ifdef ENV_IS_CASELESS
563 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
564 /* XXX This code isn't UTF8 clean. */
565 const char *keysave = key;
566 /* Will need to free this, so set FREEKEY flag. */
567 key = savepvn(key,klen);
568 key = (const char*)strupr((char*)key);
573 if (flags & HVhek_FREEKEY) {
576 flags |= HVhek_FREEKEY;
584 if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
585 #ifdef DYNAMIC_ENV_FETCH /* if it's an %ENV lookup, we may get it on the fly */
586 || (SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
589 Newz(503, HvARRAY(hv),
590 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
592 #ifdef DYNAMIC_ENV_FETCH
593 else if (action & HV_FETCH_ISEXISTS) {
594 /* for an %ENV exists, if we do an insert it's by a recursive
595 store call, so avoid creating HvARRAY(hv) right now. */
599 /* XXX remove at some point? */
600 if (flags & HVhek_FREEKEY)
608 const char *keysave = key;
609 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
613 flags &= ~HVhek_UTF8;
614 if (key != keysave) {
615 if (flags & HVhek_FREEKEY)
617 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
622 PERL_HASH_INTERNAL(hash, key, klen);
623 /* We don't have a pointer to the hv, so we have to replicate the
624 flag into every HEK, so that hv_iterkeysv can see it. */
625 /* And yes, you do need this even though you are not "storing" because
626 you can flip the flags below if doing an lval lookup. (And that
627 was put in to give the semantics Andreas was expecting.) */
628 flags |= HVhek_REHASH;
630 if (keysv && (SvIsCOW_shared_hash(keysv))) {
633 PERL_HASH(hash, key, klen);
637 masked_flags = (flags & HVhek_MASK);
640 #ifdef DYNAMIC_ENV_FETCH
641 if (!HvARRAY(hv)) entry = Null(HE*);
645 entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
647 for (; entry; ++n_links, entry = HeNEXT(entry)) {
648 if (HeHASH(entry) != hash) /* strings can't be equal */
650 if (HeKLEN(entry) != (I32)klen)
652 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
654 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
657 if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
658 if (HeKFLAGS(entry) != masked_flags) {
659 /* We match if HVhek_UTF8 bit in our flags and hash key's
660 match. But if entry was set previously with HVhek_WASUTF8
661 and key now doesn't (or vice versa) then we should change
662 the key's flag, as this is assignment. */
663 if (HvSHAREKEYS(hv)) {
664 /* Need to swap the key we have for a key with the flags we
665 need. As keys are shared we can't just write to the
666 flag, so we share the new one, unshare the old one. */
667 HEK *new_hek = HeKEY_hek(share_hek_flags(key, klen, hash,
669 unshare_hek (HeKEY_hek(entry));
670 HeKEY_hek(entry) = new_hek;
673 HeKFLAGS(entry) = masked_flags;
674 if (masked_flags & HVhek_ENABLEHVKFLAGS)
677 if (HeVAL(entry) == &PL_sv_placeholder) {
678 /* yes, can store into placeholder slot */
679 if (action & HV_FETCH_LVALUE) {
681 /* This preserves behaviour with the old hv_fetch
682 implementation which at this point would bail out
683 with a break; (at "if we find a placeholder, we
684 pretend we haven't found anything")
686 That break mean that if a placeholder were found, it
687 caused a call into hv_store, which in turn would
688 check magic, and if there is no magic end up pretty
689 much back at this point (in hv_store's code). */
692 /* LVAL fetch which actaully needs a store. */
694 HvPLACEHOLDERS(hv)--;
697 if (val != &PL_sv_placeholder)
698 HvPLACEHOLDERS(hv)--;
701 } else if (action & HV_FETCH_ISSTORE) {
702 SvREFCNT_dec(HeVAL(entry));
705 } else if (HeVAL(entry) == &PL_sv_placeholder) {
706 /* if we find a placeholder, we pretend we haven't found
710 if (flags & HVhek_FREEKEY)
714 #ifdef DYNAMIC_ENV_FETCH /* %ENV lookup? If so, try to fetch the value now */
715 if (!(action & HV_FETCH_ISSTORE)
716 && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
718 char *env = PerlEnv_ENVgetenv_len(key,&len);
720 sv = newSVpvn(env,len);
722 return hv_fetch_common(hv,keysv,key,klen,flags,HV_FETCH_ISSTORE,sv,
728 if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
729 S_hv_notallowed(aTHX_ flags, key, klen,
730 "Attempt to access disallowed key '%"SVf"' in"
731 " a restricted hash");
733 if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
734 /* Not doing some form of store, so return failure. */
735 if (flags & HVhek_FREEKEY)
739 if (action & HV_FETCH_LVALUE) {
742 /* At this point the old hv_fetch code would call to hv_store,
743 which in turn might do some tied magic. So we need to make that
744 magic check happen. */
745 /* gonna assign to this, so it better be there */
746 return hv_fetch_common(hv, keysv, key, klen, flags,
747 HV_FETCH_ISSTORE, val, hash);
748 /* XXX Surely that could leak if the fetch-was-store fails?
749 Just like the hv_fetch. */
753 /* Welcome to hv_store... */
756 /* Not sure if we can get here. I think the only case of oentry being
757 NULL is for %ENV with dynamic env fetch. But that should disappear
758 with magic in the previous code. */
759 Newz(503, HvARRAY(hv),
760 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
764 oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
767 /* share_hek_flags will do the free for us. This might be considered
770 HeKEY_hek(entry) = HeKEY_hek(share_hek_flags(key, klen, hash, flags));
771 else /* gotta do the real thing */
772 HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
774 HeNEXT(entry) = *oentry;
777 if (val == &PL_sv_placeholder)
778 HvPLACEHOLDERS(hv)++;
779 if (masked_flags & HVhek_ENABLEHVKFLAGS)
782 xhv->xhv_keys++; /* HvKEYS(hv)++ */
783 if (!n_links) { /* initial entry? */
784 xhv->xhv_fill++; /* HvFILL(hv)++ */
785 } else if ((xhv->xhv_keys > (IV)xhv->xhv_max)
786 || ((n_links > HV_MAX_LENGTH_BEFORE_SPLIT) && !HvREHASH(hv))) {
787 /* Use only the old HvKEYS(hv) > HvMAX(hv) condition to limit bucket
788 splits on a rehashed hash, as we're not going to split it again,
789 and if someone is lucky (evil) enough to get all the keys in one
790 list they could exhaust our memory as we repeatedly double the
791 number of buckets on every entry. Linear search feels a less worse
800 S_hv_magic_check(pTHX_ HV *hv, bool *needs_copy, bool *needs_store)
802 const MAGIC *mg = SvMAGIC(hv);
806 if (isUPPER(mg->mg_type)) {
808 switch (mg->mg_type) {
809 case PERL_MAGIC_tied:
811 *needs_store = FALSE;
814 mg = mg->mg_moremagic;
819 =for apidoc hv_scalar
821 Evaluates the hash in scalar context and returns the result. Handles magic when the hash is tied.
827 Perl_hv_scalar(pTHX_ HV *hv)
832 if ((SvRMAGICAL(hv) && (mg = mg_find((SV*)hv, PERL_MAGIC_tied)))) {
833 sv = magic_scalarpack(hv, mg);
839 Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
840 (long)HvFILL(hv), (long)HvMAX(hv) + 1);
848 =for apidoc hv_delete
850 Deletes a key/value pair in the hash. The value SV is removed from the
851 hash and returned to the caller. The C<klen> is the length of the key.
852 The C<flags> value will normally be zero; if set to G_DISCARD then NULL
859 Perl_hv_delete(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 flags)
866 k_flags |= HVhek_UTF8;
870 return hv_delete_common(hv, NULL, key, klen, k_flags, flags, 0);
874 =for apidoc hv_delete_ent
876 Deletes a key/value pair in the hash. The value SV is removed from the
877 hash and returned to the caller. The C<flags> value will normally be zero;
878 if set to G_DISCARD then NULL will be returned. C<hash> can be a valid
879 precomputed hash value, or 0 to ask for it to be computed.
885 Perl_hv_delete_ent(pTHX_ HV *hv, SV *keysv, I32 flags, U32 hash)
887 return hv_delete_common(hv, keysv, NULL, 0, 0, flags, hash);
891 S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
892 int k_flags, I32 d_flags, U32 hash)
898 register HE **oentry;
907 if (k_flags & HVhek_FREEKEY)
909 key = SvPV(keysv, klen);
911 is_utf8 = (SvUTF8(keysv) != 0);
913 is_utf8 = ((k_flags & HVhek_UTF8) ? TRUE : FALSE);
916 if (SvRMAGICAL(hv)) {
919 hv_magic_check (hv, &needs_copy, &needs_store);
922 entry = hv_fetch_common(hv, keysv, key, klen,
923 k_flags & ~HVhek_FREEKEY, HV_FETCH_LVALUE,
925 sv = entry ? HeVAL(entry) : NULL;
931 if (mg_find(sv, PERL_MAGIC_tiedelem)) {
932 /* No longer an element */
933 sv_unmagic(sv, PERL_MAGIC_tiedelem);
936 return Nullsv; /* element cannot be deleted */
938 #ifdef ENV_IS_CASELESS
939 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
940 /* XXX This code isn't UTF8 clean. */
941 keysv = sv_2mortal(newSVpvn(key,klen));
942 if (k_flags & HVhek_FREEKEY) {
945 key = strupr(SvPVX(keysv));
954 xhv = (XPVHV*)SvANY(hv);
959 const char *keysave = key;
960 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
963 k_flags |= HVhek_UTF8;
965 k_flags &= ~HVhek_UTF8;
966 if (key != keysave) {
967 if (k_flags & HVhek_FREEKEY) {
968 /* This shouldn't happen if our caller does what we expect,
969 but strictly the API allows it. */
972 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
974 HvHASKFLAGS_on((SV*)hv);
978 PERL_HASH_INTERNAL(hash, key, klen);
980 if (keysv && (SvIsCOW_shared_hash(keysv))) {
983 PERL_HASH(hash, key, klen);
987 masked_flags = (k_flags & HVhek_MASK);
989 oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
992 for (; entry; i=0, oentry = &HeNEXT(entry), entry = *oentry) {
993 if (HeHASH(entry) != hash) /* strings can't be equal */
995 if (HeKLEN(entry) != (I32)klen)
997 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
999 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
1002 /* if placeholder is here, it's already been deleted.... */
1003 if (HeVAL(entry) == &PL_sv_placeholder)
1005 if (k_flags & HVhek_FREEKEY)
1009 else if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1010 S_hv_notallowed(aTHX_ k_flags, key, klen,
1011 "Attempt to delete readonly key '%"SVf"' from"
1012 " a restricted hash");
1014 if (k_flags & HVhek_FREEKEY)
1017 if (d_flags & G_DISCARD)
1020 sv = sv_2mortal(HeVAL(entry));
1021 HeVAL(entry) = &PL_sv_placeholder;
1025 * If a restricted hash, rather than really deleting the entry, put
1026 * a placeholder there. This marks the key as being "approved", so
1027 * we can still access via not-really-existing key without raising
1030 if (SvREADONLY(hv)) {
1031 SvREFCNT_dec(HeVAL(entry));
1032 HeVAL(entry) = &PL_sv_placeholder;
1033 /* We'll be saving this slot, so the number of allocated keys
1034 * doesn't go down, but the number placeholders goes up */
1035 HvPLACEHOLDERS(hv)++;
1037 *oentry = HeNEXT(entry);
1039 xhv->xhv_fill--; /* HvFILL(hv)-- */
1040 if (xhv->xhv_aux && entry
1041 == ((struct xpvhv_aux *)xhv->xhv_aux)->xhv_eiter /* HvEITER(hv) */)
1044 hv_free_ent(hv, entry);
1045 xhv->xhv_keys--; /* HvKEYS(hv)-- */
1046 if (xhv->xhv_keys == 0)
1047 HvHASKFLAGS_off(hv);
1051 if (SvREADONLY(hv)) {
1052 S_hv_notallowed(aTHX_ k_flags, key, klen,
1053 "Attempt to delete disallowed key '%"SVf"' from"
1054 " a restricted hash");
1057 if (k_flags & HVhek_FREEKEY)
1063 S_hsplit(pTHX_ HV *hv)
1065 register XPVHV* xhv = (XPVHV*)SvANY(hv);
1066 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1067 register I32 newsize = oldsize * 2;
1069 char *a = (char*) HvARRAY(hv);
1071 register HE **oentry;
1072 int longest_chain = 0;
1075 /*PerlIO_printf(PerlIO_stderr(), "hsplit called for %p which had %d\n",
1076 hv, (int) oldsize);*/
1078 if (HvPLACEHOLDERS(hv) && !SvREADONLY(hv)) {
1079 /* Can make this clear any placeholders first for non-restricted hashes,
1080 even though Storable rebuilds restricted hashes by putting in all the
1081 placeholders (first) before turning on the readonly flag, because
1082 Storable always pre-splits the hash. */
1083 hv_clear_placeholders(hv);
1087 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1088 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1094 New(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1099 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1100 if (oldsize >= 64) {
1101 offer_nice_chunk(HvARRAY(hv),
1102 PERL_HV_ARRAY_ALLOC_BYTES(oldsize));
1105 Safefree(HvARRAY(hv));
1109 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1110 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
1111 HvARRAY(hv) = (HE**) a;
1114 for (i=0; i<oldsize; i++,aep++) {
1115 int left_length = 0;
1116 int right_length = 0;
1120 if (!*aep) /* non-existent */
1123 for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1124 if ((HeHASH(entry) & newsize) != (U32)i) {
1125 *oentry = HeNEXT(entry);
1126 HeNEXT(entry) = *bep;
1128 xhv->xhv_fill++; /* HvFILL(hv)++ */
1134 oentry = &HeNEXT(entry);
1138 if (!*aep) /* everything moved */
1139 xhv->xhv_fill--; /* HvFILL(hv)-- */
1140 /* I think we don't actually need to keep track of the longest length,
1141 merely flag if anything is too long. But for the moment while
1142 developing this code I'll track it. */
1143 if (left_length > longest_chain)
1144 longest_chain = left_length;
1145 if (right_length > longest_chain)
1146 longest_chain = right_length;
1150 /* Pick your policy for "hashing isn't working" here: */
1151 if (longest_chain <= HV_MAX_LENGTH_BEFORE_SPLIT /* split worked? */
1156 if (hv == PL_strtab) {
1157 /* Urg. Someone is doing something nasty to the string table.
1162 /* Awooga. Awooga. Pathological data. */
1163 /*PerlIO_printf(PerlIO_stderr(), "%p %d of %d with %d/%d buckets\n", hv,
1164 longest_chain, HvTOTALKEYS(hv), HvFILL(hv), 1+HvMAX(hv));*/
1167 Newz(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1168 was_shared = HvSHAREKEYS(hv);
1171 HvSHAREKEYS_off(hv);
1176 for (i=0; i<newsize; i++,aep++) {
1177 register HE *entry = *aep;
1179 /* We're going to trash this HE's next pointer when we chain it
1180 into the new hash below, so store where we go next. */
1181 HE *next = HeNEXT(entry);
1186 PERL_HASH_INTERNAL(hash, HeKEY(entry), HeKLEN(entry));
1191 = save_hek_flags(HeKEY(entry), HeKLEN(entry),
1192 hash, HeKFLAGS(entry));
1193 unshare_hek (HeKEY_hek(entry));
1194 HeKEY_hek(entry) = new_hek;
1196 /* Not shared, so simply write the new hash in. */
1197 HeHASH(entry) = hash;
1199 /*PerlIO_printf(PerlIO_stderr(), "%d ", HeKFLAGS(entry));*/
1200 HEK_REHASH_on(HeKEY_hek(entry));
1201 /*PerlIO_printf(PerlIO_stderr(), "%d\n", HeKFLAGS(entry));*/
1203 /* Copy oentry to the correct new chain. */
1204 bep = ((HE**)a) + (hash & (I32) xhv->xhv_max);
1206 xhv->xhv_fill++; /* HvFILL(hv)++ */
1207 HeNEXT(entry) = *bep;
1213 Safefree (HvARRAY(hv));
1214 HvARRAY(hv) = (HE **)a;
1218 Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
1220 register XPVHV* xhv = (XPVHV*)SvANY(hv);
1221 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1222 register I32 newsize;
1227 register HE **oentry;
1229 newsize = (I32) newmax; /* possible truncation here */
1230 if (newsize != newmax || newmax <= oldsize)
1232 while ((newsize & (1 + ~newsize)) != newsize) {
1233 newsize &= ~(newsize & (1 + ~newsize)); /* get proper power of 2 */
1235 if (newsize < newmax)
1237 if (newsize < newmax)
1238 return; /* overflow detection */
1240 a = (char *) HvARRAY(hv);
1243 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1244 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1250 New(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1255 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1256 if (oldsize >= 64) {
1257 offer_nice_chunk(HvARRAY(hv),
1258 PERL_HV_ARRAY_ALLOC_BYTES(oldsize));
1261 Safefree(HvARRAY(hv));
1264 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1267 Newz(0, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1269 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
1270 HvARRAY(hv) = (HE **) a;
1271 if (!xhv->xhv_fill /* !HvFILL(hv) */) /* skip rest if no entries */
1275 for (i=0; i<oldsize; i++,aep++) {
1276 if (!*aep) /* non-existent */
1278 for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1280 if ((j = (HeHASH(entry) & newsize)) != i) {
1282 *oentry = HeNEXT(entry);
1283 if (!(HeNEXT(entry) = aep[j]))
1284 xhv->xhv_fill++; /* HvFILL(hv)++ */
1289 oentry = &HeNEXT(entry);
1291 if (!*aep) /* everything moved */
1292 xhv->xhv_fill--; /* HvFILL(hv)-- */
1299 Creates a new HV. The reference count is set to 1.
1308 register XPVHV* xhv;
1310 hv = (HV*)NEWSV(502,0);
1311 sv_upgrade((SV *)hv, SVt_PVHV);
1312 xhv = (XPVHV*)SvANY(hv);
1315 #ifndef NODEFAULT_SHAREKEYS
1316 HvSHAREKEYS_on(hv); /* key-sharing on by default */
1319 xhv->xhv_max = 7; /* HvMAX(hv) = 7 (start with 8 buckets) */
1320 xhv->xhv_fill = 0; /* HvFILL(hv) = 0 */
1326 Perl_newHVhv(pTHX_ HV *ohv)
1329 STRLEN hv_max, hv_fill;
1331 if (!ohv || (hv_fill = HvFILL(ohv)) == 0)
1333 hv_max = HvMAX(ohv);
1335 if (!SvMAGICAL((SV *)ohv)) {
1336 /* It's an ordinary hash, so copy it fast. AMS 20010804 */
1338 const bool shared = !!HvSHAREKEYS(ohv);
1339 HE **ents, **oents = (HE **)HvARRAY(ohv);
1341 New(0, a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
1344 /* In each bucket... */
1345 for (i = 0; i <= hv_max; i++) {
1346 HE *prev = NULL, *ent = NULL, *oent = oents[i];
1353 /* Copy the linked list of entries. */
1354 for (oent = oents[i]; oent; oent = HeNEXT(oent)) {
1355 const U32 hash = HeHASH(oent);
1356 const char * const key = HeKEY(oent);
1357 const STRLEN len = HeKLEN(oent);
1358 const int flags = HeKFLAGS(oent);
1361 HeVAL(ent) = newSVsv(HeVAL(oent));
1363 = shared ? HeKEY_hek(share_hek_flags(key, len, hash, flags))
1364 : save_hek_flags(key, len, hash, flags);
1375 HvFILL(hv) = hv_fill;
1376 HvTOTALKEYS(hv) = HvTOTALKEYS(ohv);
1380 /* Iterate over ohv, copying keys and values one at a time. */
1382 const I32 riter = HvRITER_get(ohv);
1383 HE * const eiter = HvEITER_get(ohv);
1385 /* Can we use fewer buckets? (hv_max is always 2^n-1) */
1386 while (hv_max && hv_max + 1 >= hv_fill * 2)
1387 hv_max = hv_max / 2;
1391 while ((entry = hv_iternext_flags(ohv, 0))) {
1392 hv_store_flags(hv, HeKEY(entry), HeKLEN(entry),
1393 newSVsv(HeVAL(entry)), HeHASH(entry),
1396 HvRITER_set(ohv, riter);
1397 HvEITER_set(ohv, eiter);
1404 Perl_hv_free_ent(pTHX_ HV *hv, register HE *entry)
1411 if (val && isGV(val) && GvCVu(val) && HvNAME_get(hv))
1412 PL_sub_generation++; /* may be deletion of method from stash */
1414 if (HeKLEN(entry) == HEf_SVKEY) {
1415 SvREFCNT_dec(HeKEY_sv(entry));
1416 Safefree(HeKEY_hek(entry));
1418 else if (HvSHAREKEYS(hv))
1419 unshare_hek(HeKEY_hek(entry));
1421 Safefree(HeKEY_hek(entry));
1426 Perl_hv_delayfree_ent(pTHX_ HV *hv, register HE *entry)
1430 if (isGV(HeVAL(entry)) && GvCVu(HeVAL(entry)) && HvNAME_get(hv))
1431 PL_sub_generation++; /* may be deletion of method from stash */
1432 sv_2mortal(HeVAL(entry)); /* free between statements */
1433 if (HeKLEN(entry) == HEf_SVKEY) {
1434 sv_2mortal(HeKEY_sv(entry));
1435 Safefree(HeKEY_hek(entry));
1437 else if (HvSHAREKEYS(hv))
1438 unshare_hek(HeKEY_hek(entry));
1440 Safefree(HeKEY_hek(entry));
1445 =for apidoc hv_clear
1447 Clears a hash, making it empty.
1453 Perl_hv_clear(pTHX_ HV *hv)
1456 register XPVHV* xhv;
1460 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1462 xhv = (XPVHV*)SvANY(hv);
1464 if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
1465 /* restricted hash: convert all keys to placeholders */
1467 for (i = 0; i <= (I32) xhv->xhv_max; i++) {
1468 HE *entry = (HvARRAY(hv))[i];
1469 for (; entry; entry = HeNEXT(entry)) {
1470 /* not already placeholder */
1471 if (HeVAL(entry) != &PL_sv_placeholder) {
1472 if (HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1473 SV* keysv = hv_iterkeysv(entry);
1475 "Attempt to delete readonly key '%"SVf"' from a restricted hash",
1478 SvREFCNT_dec(HeVAL(entry));
1479 HeVAL(entry) = &PL_sv_placeholder;
1480 HvPLACEHOLDERS(hv)++;
1488 HvPLACEHOLDERS_set(hv, 0);
1490 (void)memzero(HvARRAY(hv),
1491 (xhv->xhv_max+1 /* HvMAX(hv)+1 */) * sizeof(HE*));
1496 HvHASKFLAGS_off(hv);
1500 HvEITER_set(hv, NULL);
1505 =for apidoc hv_clear_placeholders
1507 Clears any placeholders from a hash. If a restricted hash has any of its keys
1508 marked as readonly and the key is subsequently deleted, the key is not actually
1509 deleted but is marked by assigning it a value of &PL_sv_placeholder. This tags
1510 it so it will be ignored by future operations such as iterating over the hash,
1511 but will still allow the hash to have a value reassigned to the key at some
1512 future point. This function clears any such placeholder keys from the hash.
1513 See Hash::Util::lock_keys() for an example of its use.
1519 Perl_hv_clear_placeholders(pTHX_ HV *hv)
1522 I32 items = (I32)HvPLACEHOLDERS(hv);
1529 /* Loop down the linked list heads */
1531 HE **oentry = &(HvARRAY(hv))[i];
1532 HE *entry = *oentry;
1537 for (; entry; entry = *oentry) {
1538 if (HeVAL(entry) == &PL_sv_placeholder) {
1539 *oentry = HeNEXT(entry);
1540 if (first && !*oentry)
1541 HvFILL(hv)--; /* This linked list is now empty. */
1542 if (HvEITER_get(hv))
1545 hv_free_ent(hv, entry);
1549 HvTOTALKEYS(hv) -= (IV)HvPLACEHOLDERS(hv);
1550 if (HvKEYS(hv) == 0)
1551 HvHASKFLAGS_off(hv);
1552 HvPLACEHOLDERS(hv) = 0;
1556 oentry = &HeNEXT(entry);
1561 /* You can't get here, hence assertion should always fail. */
1562 assert (items == 0);
1567 S_hfreeentries(pTHX_ HV *hv)
1569 register HE **array;
1573 struct xpvhv_aux *iter;
1582 array = HvARRAY(hv);
1583 /* make everyone else think the array is empty, so that the destructors
1584 * called for freed entries can't recusively mess with us */
1585 HvARRAY(hv) = Null(HE**);
1587 ((XPVHV*) SvANY(hv))->xhv_keys = 0;
1592 register HE *oentry = entry;
1593 entry = HeNEXT(entry);
1594 hv_free_ent(hv, oentry);
1599 entry = array[riter];
1602 HvARRAY(hv) = array;
1604 iter = ((XPVHV*) SvANY(hv))->xhv_aux;
1606 entry = iter->xhv_eiter; /* HvEITER(hv) */
1607 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1609 hv_free_ent(hv, entry);
1611 Safefree(iter->xhv_name);
1613 ((XPVHV*) SvANY(hv))->xhv_aux = 0;
1618 =for apidoc hv_undef
1626 Perl_hv_undef(pTHX_ HV *hv)
1628 register XPVHV* xhv;
1632 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1633 xhv = (XPVHV*)SvANY(hv);
1635 Safefree(HvARRAY(hv));
1636 if ((name = HvNAME_get(hv))) {
1637 /* FIXME - strlen HvNAME */
1639 hv_delete(PL_stashcache, name, strlen(name), G_DISCARD);
1640 Perl_hv_name_set(aTHX_ hv, 0, 0, 0);
1642 xhv->xhv_max = 7; /* HvMAX(hv) = 7 (it's a normal hash) */
1644 HvPLACEHOLDERS_set(hv, 0);
1651 S_hv_auxinit(pTHX) {
1652 struct xpvhv_aux *iter;
1654 New(0, iter, 1, struct xpvhv_aux);
1656 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1657 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1664 =for apidoc hv_iterinit
1666 Prepares a starting point to traverse a hash table. Returns the number of
1667 keys in the hash (i.e. the same as C<HvKEYS(tb)>). The return value is
1668 currently only meaningful for hashes without tie magic.
1670 NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
1671 hash buckets that happen to be in use. If you still need that esoteric
1672 value, you can get it through the macro C<HvFILL(tb)>.
1679 Perl_hv_iterinit(pTHX_ HV *hv)
1681 register XPVHV* xhv;
1683 struct xpvhv_aux *iter;
1686 Perl_croak(aTHX_ "Bad hash");
1687 xhv = (XPVHV*)SvANY(hv);
1689 iter = xhv->xhv_aux;
1691 entry = iter->xhv_eiter; /* HvEITER(hv) */
1692 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1694 hv_free_ent(hv, entry);
1696 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1697 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1699 xhv->xhv_aux = S_hv_auxinit(aTHX);
1702 /* used to be xhv->xhv_fill before 5.004_65 */
1703 return XHvTOTALKEYS(xhv);
1707 Perl_hv_riter_p(pTHX_ HV *hv) {
1708 struct xpvhv_aux *iter;
1711 Perl_croak(aTHX_ "Bad hash");
1713 iter = ((XPVHV *)SvANY(hv))->xhv_aux;
1715 ((XPVHV *)SvANY(hv))->xhv_aux = iter = S_hv_auxinit(aTHX);
1717 return &(iter->xhv_riter);
1721 Perl_hv_eiter_p(pTHX_ HV *hv) {
1722 struct xpvhv_aux *iter;
1725 Perl_croak(aTHX_ "Bad hash");
1727 iter = ((XPVHV *)SvANY(hv))->xhv_aux;
1729 ((XPVHV *)SvANY(hv))->xhv_aux = iter = S_hv_auxinit(aTHX);
1731 return &(iter->xhv_eiter);
1735 Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
1736 struct xpvhv_aux *iter;
1739 Perl_croak(aTHX_ "Bad hash");
1742 iter = ((XPVHV *)SvANY(hv))->xhv_aux;
1747 ((XPVHV *)SvANY(hv))->xhv_aux = iter = S_hv_auxinit(aTHX);
1749 iter->xhv_riter = riter;
1753 Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
1754 struct xpvhv_aux *iter;
1757 Perl_croak(aTHX_ "Bad hash");
1759 iter = ((XPVHV *)SvANY(hv))->xhv_aux;
1761 /* 0 is the default so don't go malloc()ing a new structure just to
1766 ((XPVHV *)SvANY(hv))->xhv_aux = iter = S_hv_auxinit(aTHX);
1768 iter->xhv_eiter = eiter;
1773 Perl_hv_name_p(pTHX_ HV *hv)
1775 struct xpvhv_aux *iter = ((XPVHV *)SvANY(hv))->xhv_aux;
1778 ((XPVHV *)SvANY(hv))->xhv_aux = iter = S_hv_auxinit(aTHX);
1780 return &(iter->xhv_name);
1784 Perl_hv_name_set(pTHX_ HV *hv, const char *name, STRLEN len, int flags)
1786 struct xpvhv_aux *iter = ((XPVHV *)SvANY(hv))->xhv_aux;
1789 Safefree(iter->xhv_name);
1794 ((XPVHV *)SvANY(hv))->xhv_aux = iter = S_hv_auxinit(aTHX);
1796 iter->xhv_name = savepvn(name, len);
1800 =for apidoc hv_iternext
1802 Returns entries from a hash iterator. See C<hv_iterinit>.
1804 You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
1805 iterator currently points to, without losing your place or invalidating your
1806 iterator. Note that in this case the current entry is deleted from the hash
1807 with your iterator holding the last reference to it. Your iterator is flagged
1808 to free the entry on the next call to C<hv_iternext>, so you must not discard
1809 your iterator immediately else the entry will leak - call C<hv_iternext> to
1810 trigger the resource deallocation.
1816 Perl_hv_iternext(pTHX_ HV *hv)
1818 return hv_iternext_flags(hv, 0);
1822 =for apidoc hv_iternext_flags
1824 Returns entries from a hash iterator. See C<hv_iterinit> and C<hv_iternext>.
1825 The C<flags> value will normally be zero; if HV_ITERNEXT_WANTPLACEHOLDERS is
1826 set the placeholders keys (for restricted hashes) will be returned in addition
1827 to normal keys. By default placeholders are automatically skipped over.
1828 Currently a placeholder is implemented with a value that is
1829 C<&Perl_sv_placeholder>. Note that the implementation of placeholders and
1830 restricted hashes may change, and the implementation currently is
1831 insufficiently abstracted for any change to be tidy.
1837 Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
1840 register XPVHV* xhv;
1844 struct xpvhv_aux *iter;
1847 Perl_croak(aTHX_ "Bad hash");
1848 xhv = (XPVHV*)SvANY(hv);
1849 iter = xhv->xhv_aux;
1852 /* Too many things (well, pp_each at least) merrily assume that you can
1853 call iv_iternext without calling hv_iterinit, so we'll have to deal
1856 iter = ((XPVHV *)SvANY(hv))->xhv_aux;
1859 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
1861 if ((mg = SvTIED_mg((SV*)hv, PERL_MAGIC_tied))) {
1862 SV *key = sv_newmortal();
1864 sv_setsv(key, HeSVKEY_force(entry));
1865 SvREFCNT_dec(HeSVKEY(entry)); /* get rid of previous key */
1871 /* one HE per MAGICAL hash */
1872 iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
1874 Newz(54, k, HEK_BASESIZE + sizeof(SV*), char);
1876 HeKEY_hek(entry) = hek;
1877 HeKLEN(entry) = HEf_SVKEY;
1879 magic_nextpack((SV*) hv,mg,key);
1881 /* force key to stay around until next time */
1882 HeSVKEY_set(entry, SvREFCNT_inc(key));
1883 return entry; /* beware, hent_val is not set */
1886 SvREFCNT_dec(HeVAL(entry));
1887 Safefree(HeKEY_hek(entry));
1889 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1892 #ifdef DYNAMIC_ENV_FETCH /* set up %ENV for iteration */
1893 if (!entry && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
1900 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
1902 HvARRAY(hv) = (HE**) darray;
1904 /* At start of hash, entry is NULL. */
1907 entry = HeNEXT(entry);
1908 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
1910 * Skip past any placeholders -- don't want to include them in
1913 while (entry && HeVAL(entry) == &PL_sv_placeholder) {
1914 entry = HeNEXT(entry);
1919 /* OK. Come to the end of the current list. Grab the next one. */
1921 iter->xhv_riter++; /* HvRITER(hv)++ */
1922 if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
1923 /* There is no next one. End of the hash. */
1924 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1927 entry = (HvARRAY(hv))[iter->xhv_riter];
1929 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
1930 /* If we have an entry, but it's a placeholder, don't count it.
1932 while (entry && HeVAL(entry) == &PL_sv_placeholder)
1933 entry = HeNEXT(entry);
1935 /* Will loop again if this linked list starts NULL
1936 (for HV_ITERNEXT_WANTPLACEHOLDERS)
1937 or if we run through it and find only placeholders. */
1940 if (oldentry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1942 hv_free_ent(hv, oldentry);
1945 /*if (HvREHASH(hv) && entry && !HeKREHASH(entry))
1946 PerlIO_printf(PerlIO_stderr(), "Awooga %p %p\n", hv, entry);*/
1948 iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
1953 =for apidoc hv_iterkey
1955 Returns the key from the current position of the hash iterator. See
1962 Perl_hv_iterkey(pTHX_ register HE *entry, I32 *retlen)
1964 if (HeKLEN(entry) == HEf_SVKEY) {
1966 char *p = SvPV(HeKEY_sv(entry), len);
1971 *retlen = HeKLEN(entry);
1972 return HeKEY(entry);
1976 /* unlike hv_iterval(), this always returns a mortal copy of the key */
1978 =for apidoc hv_iterkeysv
1980 Returns the key as an C<SV*> from the current position of the hash
1981 iterator. The return value will always be a mortal copy of the key. Also
1988 Perl_hv_iterkeysv(pTHX_ register HE *entry)
1990 if (HeKLEN(entry) != HEf_SVKEY) {
1991 HEK *hek = HeKEY_hek(entry);
1992 const int flags = HEK_FLAGS(hek);
1995 if (flags & HVhek_WASUTF8) {
1997 Andreas would like keys he put in as utf8 to come back as utf8
1999 STRLEN utf8_len = HEK_LEN(hek);
2000 U8 *as_utf8 = bytes_to_utf8 ((U8*)HEK_KEY(hek), &utf8_len);
2002 sv = newSVpvn ((char*)as_utf8, utf8_len);
2004 Safefree (as_utf8); /* bytes_to_utf8() allocates a new string */
2005 } else if (flags & HVhek_REHASH) {
2006 /* We don't have a pointer to the hv, so we have to replicate the
2007 flag into every HEK. This hv is using custom a hasing
2008 algorithm. Hence we can't return a shared string scalar, as
2009 that would contain the (wrong) hash value, and might get passed
2010 into an hv routine with a regular hash */
2012 sv = newSVpvn (HEK_KEY(hek), HEK_LEN(hek));
2016 sv = newSVpvn_share(HEK_KEY(hek),
2017 (HEK_UTF8(hek) ? -HEK_LEN(hek) : HEK_LEN(hek)),
2020 return sv_2mortal(sv);
2022 return sv_mortalcopy(HeKEY_sv(entry));
2026 =for apidoc hv_iterval
2028 Returns the value from the current position of the hash iterator. See
2035 Perl_hv_iterval(pTHX_ HV *hv, register HE *entry)
2037 if (SvRMAGICAL(hv)) {
2038 if (mg_find((SV*)hv, PERL_MAGIC_tied)) {
2039 SV* sv = sv_newmortal();
2040 if (HeKLEN(entry) == HEf_SVKEY)
2041 mg_copy((SV*)hv, sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
2043 mg_copy((SV*)hv, sv, HeKEY(entry), HeKLEN(entry));
2047 return HeVAL(entry);
2051 =for apidoc hv_iternextsv
2053 Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2060 Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
2063 if ( (he = hv_iternext_flags(hv, 0)) == NULL)
2065 *key = hv_iterkey(he, retlen);
2066 return hv_iterval(hv, he);
2070 =for apidoc hv_magic
2072 Adds magic to a hash. See C<sv_magic>.
2078 Perl_hv_magic(pTHX_ HV *hv, GV *gv, int how)
2080 sv_magic((SV*)hv, (SV*)gv, how, Nullch, 0);
2083 #if 0 /* use the macro from hv.h instead */
2086 Perl_sharepvn(pTHX_ const char *sv, I32 len, U32 hash)
2088 return HEK_KEY(share_hek(sv, len, hash));
2093 /* possibly free a shared string if no one has access to it
2094 * len and hash must both be valid for str.
2097 Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
2099 unshare_hek_or_pvn (NULL, str, len, hash);
2104 Perl_unshare_hek(pTHX_ HEK *hek)
2106 unshare_hek_or_pvn(hek, NULL, 0, 0);
2109 /* possibly free a shared string if no one has access to it
2110 hek if non-NULL takes priority over the other 3, else str, len and hash
2111 are used. If so, len and hash must both be valid for str.
2114 S_unshare_hek_or_pvn(pTHX_ HEK *hek, const char *str, I32 len, U32 hash)
2116 register XPVHV* xhv;
2118 register HE **oentry;
2121 bool is_utf8 = FALSE;
2123 const char *save = str;
2126 hash = HEK_HASH(hek);
2127 } else if (len < 0) {
2128 STRLEN tmplen = -len;
2130 /* See the note in hv_fetch(). --jhi */
2131 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2134 k_flags = HVhek_UTF8;
2136 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2139 /* what follows is the moral equivalent of:
2140 if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
2141 if (--*Svp == Nullsv)
2142 hv_delete(PL_strtab, str, len, G_DISCARD, hash);
2144 xhv = (XPVHV*)SvANY(PL_strtab);
2145 /* assert(xhv_array != 0) */
2147 oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2149 for (entry = *oentry; entry; i=0, oentry = &HeNEXT(entry), entry = *oentry) {
2150 if (HeKEY_hek(entry) != hek)
2156 const int flags_masked = k_flags & HVhek_MASK;
2157 for (entry = *oentry; entry; i=0, oentry = &HeNEXT(entry), entry = *oentry) {
2158 if (HeHASH(entry) != hash) /* strings can't be equal */
2160 if (HeKLEN(entry) != len)
2162 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2164 if (HeKFLAGS(entry) != flags_masked)
2172 if (--HeVAL(entry) == Nullsv) {
2173 *oentry = HeNEXT(entry);
2175 xhv->xhv_fill--; /* HvFILL(hv)-- */
2176 Safefree(HeKEY_hek(entry));
2178 xhv->xhv_keys--; /* HvKEYS(hv)-- */
2182 UNLOCK_STRTAB_MUTEX;
2183 if (!found && ckWARN_d(WARN_INTERNAL))
2184 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
2185 "Attempt to free non-existent shared string '%s'%s"
2187 hek ? HEK_KEY(hek) : str,
2188 ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
2189 if (k_flags & HVhek_FREEKEY)
2193 /* get a (constant) string ptr from the global string table
2194 * string will get added if it is not already there.
2195 * len and hash must both be valid for str.
2198 Perl_share_hek(pTHX_ const char *str, I32 len, register U32 hash)
2200 bool is_utf8 = FALSE;
2202 const char *save = str;
2205 STRLEN tmplen = -len;
2207 /* See the note in hv_fetch(). --jhi */
2208 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2210 /* If we were able to downgrade here, then than means that we were passed
2211 in a key which only had chars 0-255, but was utf8 encoded. */
2214 /* If we found we were able to downgrade the string to bytes, then
2215 we should flag that it needs upgrading on keys or each. Also flag
2216 that we need share_hek_flags to free the string. */
2218 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2221 return HeKEY_hek(share_hek_flags (str, len, hash, flags));
2225 S_share_hek_flags(pTHX_ const char *str, I32 len, register U32 hash, int flags)
2227 register XPVHV* xhv;
2229 register HE **oentry;
2232 const int flags_masked = flags & HVhek_MASK;
2234 /* what follows is the moral equivalent of:
2236 if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
2237 hv_store(PL_strtab, str, len, Nullsv, hash);
2239 Can't rehash the shared string table, so not sure if it's worth
2240 counting the number of entries in the linked list
2242 xhv = (XPVHV*)SvANY(PL_strtab);
2243 /* assert(xhv_array != 0) */
2245 oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2246 for (entry = *oentry; entry; i=0, entry = HeNEXT(entry)) {
2247 if (HeHASH(entry) != hash) /* strings can't be equal */
2249 if (HeKLEN(entry) != len)
2251 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2253 if (HeKFLAGS(entry) != flags_masked)
2260 HeKEY_hek(entry) = save_hek_flags(str, len, hash, flags_masked);
2261 HeVAL(entry) = Nullsv;
2262 HeNEXT(entry) = *oentry;
2264 xhv->xhv_keys++; /* HvKEYS(hv)++ */
2265 if (i) { /* initial entry? */
2266 xhv->xhv_fill++; /* HvFILL(hv)++ */
2267 } else if (xhv->xhv_keys > (IV)xhv->xhv_max /* HvKEYS(hv) > HvMAX(hv) */) {
2272 ++HeVAL(entry); /* use value slot as REFCNT */
2273 UNLOCK_STRTAB_MUTEX;
2275 if (flags & HVhek_FREEKEY)
2282 Perl_hv_placeholders_p(pTHX_ HV *hv)
2285 MAGIC *mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2288 mg = sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, 0);
2291 Perl_die(aTHX_ "panic: hv_placeholders_p");
2294 return &(mg->mg_len);
2299 Perl_hv_placeholders_get(pTHX_ HV *hv)
2302 MAGIC *mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2304 return mg ? mg->mg_len : 0;
2308 Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
2311 MAGIC *mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2316 if (!sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, ph))
2317 Perl_die(aTHX_ "panic: hv_placeholders_set");
2319 /* else we don't need to add magic to record 0 placeholders. */
2323 =for apidoc hv_assert
2325 Check that a hash is in an internally consistent state.
2331 Perl_hv_assert(pTHX_ HV *hv)
2336 int placeholders = 0;
2339 const I32 riter = HvRITER_get(hv);
2340 HE *eiter = HvEITER_get(hv);
2342 (void)hv_iterinit(hv);
2344 while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
2345 /* sanity check the values */
2346 if (HeVAL(entry) == &PL_sv_placeholder) {
2351 /* sanity check the keys */
2352 if (HeSVKEY(entry)) {
2353 /* Don't know what to check on SV keys. */
2354 } else if (HeKUTF8(entry)) {
2356 if (HeKWASUTF8(entry)) {
2357 PerlIO_printf(Perl_debug_log,
2358 "hash key has both WASUFT8 and UTF8: '%.*s'\n",
2359 (int) HeKLEN(entry), HeKEY(entry));
2362 } else if (HeKWASUTF8(entry)) {
2366 if (!SvTIED_mg((SV*)hv, PERL_MAGIC_tied)) {
2367 if (HvUSEDKEYS(hv) != real) {
2368 PerlIO_printf(Perl_debug_log, "Count %d key(s), but hash reports %d\n",
2369 (int) real, (int) HvUSEDKEYS(hv));
2372 if (HvPLACEHOLDERS(hv) != placeholders) {
2373 PerlIO_printf(Perl_debug_log,
2374 "Count %d placeholder(s), but hash reports %d\n",
2375 (int) placeholders, (int) HvPLACEHOLDERS(hv));
2379 if (withflags && ! HvHASKFLAGS(hv)) {
2380 PerlIO_printf(Perl_debug_log,
2381 "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
2388 HvRITER_set(hv, riter); /* Restore hash iterator state */
2389 HvEITER_set(hv, eiter);
2394 * c-indentation-style: bsd
2396 * indent-tabs-mode: t
2399 * ex: set ts=8 sts=4 sw=4 noet: