3 * Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 * 2000, 2001, 2002, 2003, 2004, 2005, by Larry Wall and others
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
12 * "I sit beside the fire and think of all that I have seen." --Bilbo
16 =head1 Hash Manipulation Functions
18 A HV structure represents a Perl hash. It consists mainly of an array
19 of pointers, each of which points to a linked list of HE structures. The
20 array is indexed by the hash function of the key, so each linked list
21 represents all the hash entries with the same hash value. Each HE contains
22 a pointer to the actual value, plus a pointer to a HEK structure which
23 holds the key and hash value.
31 #define PERL_HASH_INTERNAL_ACCESS
34 #define HV_MAX_LENGTH_BEFORE_SPLIT 14
41 New(54, he, PERL_ARENA_SIZE/sizeof(HE), HE);
42 HeNEXT(he) = PL_he_arenaroot;
45 heend = &he[PERL_ARENA_SIZE / sizeof(HE) - 1];
48 HeNEXT(he) = (HE*)(he + 1);
62 PL_he_root = HeNEXT(he);
71 HeNEXT(p) = (HE*)PL_he_root;
78 #define new_HE() (HE*)safemalloc(sizeof(HE))
79 #define del_HE(p) safefree((char*)p)
83 #define new_HE() new_he()
84 #define del_HE(p) del_he(p)
89 S_save_hek_flags(pTHX_ const char *str, I32 len, U32 hash, int flags)
91 const int flags_masked = flags & HVhek_MASK;
95 New(54, k, HEK_BASESIZE + len + 2, char);
97 Copy(str, HEK_KEY(hek), len, char);
98 HEK_KEY(hek)[len] = 0;
100 HEK_HASH(hek) = hash;
101 HEK_FLAGS(hek) = (unsigned char)flags_masked;
103 if (flags & HVhek_FREEKEY)
108 /* free the pool of temporary HE/HEK pairs retunrned by hv_fetch_ent
112 Perl_free_tied_hv_pool(pTHX)
115 HE *he = PL_hv_fetch_ent_mh;
117 Safefree(HeKEY_hek(he));
122 PL_hv_fetch_ent_mh = Nullhe;
125 #if defined(USE_ITHREADS)
127 Perl_hek_dup(pTHX_ HEK *source, CLONE_PARAMS* param)
129 HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
133 /* We already shared this hash key. */
134 share_hek_hek(shared);
138 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
139 HEK_HASH(source), HEK_FLAGS(source));
140 ptr_table_store(PL_ptr_table, source, shared);
146 Perl_he_dup(pTHX_ HE *e, bool shared, CLONE_PARAMS* param)
152 /* look for it in the table first */
153 ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
157 /* create anew and remember what it is */
159 ptr_table_store(PL_ptr_table, e, ret);
161 HeNEXT(ret) = he_dup(HeNEXT(e),shared, param);
162 if (HeKLEN(e) == HEf_SVKEY) {
164 New(54, k, HEK_BASESIZE + sizeof(SV*), char);
165 HeKEY_hek(ret) = (HEK*)k;
166 HeKEY_sv(ret) = SvREFCNT_inc(sv_dup(HeKEY_sv(e), param));
169 /* This is hek_dup inlined, which seems to be important for speed
171 HEK *source = HeKEY_hek(e);
172 HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
175 /* We already shared this hash key. */
176 share_hek_hek(shared);
180 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
181 HEK_HASH(source), HEK_FLAGS(source));
182 ptr_table_store(PL_ptr_table, source, shared);
184 HeKEY_hek(ret) = shared;
187 HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
189 HeVAL(ret) = SvREFCNT_inc(sv_dup(HeVAL(e), param));
192 #endif /* USE_ITHREADS */
195 S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
198 SV *sv = sv_newmortal();
199 if (!(flags & HVhek_FREEKEY)) {
200 sv_setpvn(sv, key, klen);
203 /* Need to free saved eventually assign to mortal SV */
204 /* XXX is this line an error ???: SV *sv = sv_newmortal(); */
205 sv_usepvn(sv, (char *) key, klen);
207 if (flags & HVhek_UTF8) {
210 Perl_croak(aTHX_ msg, sv);
213 /* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
216 #define HV_FETCH_ISSTORE 0x01
217 #define HV_FETCH_ISEXISTS 0x02
218 #define HV_FETCH_LVALUE 0x04
219 #define HV_FETCH_JUST_SV 0x08
224 Stores an SV in a hash. The hash key is specified as C<key> and C<klen> is
225 the length of the key. The C<hash> parameter is the precomputed hash
226 value; if it is zero then Perl will compute it. The return value will be
227 NULL if the operation failed or if the value did not need to be actually
228 stored within the hash (as in the case of tied hashes). Otherwise it can
229 be dereferenced to get the original C<SV*>. Note that the caller is
230 responsible for suitably incrementing the reference count of C<val> before
231 the call, and decrementing it if the function returned NULL. Effectively
232 a successful hv_store takes ownership of one reference to C<val>. This is
233 usually what you want; a newly created SV has a reference count of one, so
234 if all your code does is create SVs then store them in a hash, hv_store
235 will own the only reference to the new SV, and your code doesn't need to do
236 anything further to tidy up. hv_store is not implemented as a call to
237 hv_store_ent, and does not create a temporary SV for the key, so if your
238 key data is not already in SV form then use hv_store in preference to
241 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
242 information on how to use this function on tied hashes.
248 Perl_hv_store(pTHX_ HV *hv, const char *key, I32 klen_i32, SV *val, U32 hash)
261 hek = hv_fetch_common (hv, NULL, key, klen, flags,
262 (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
263 return hek ? &HeVAL(hek) : NULL;
267 Perl_hv_store_flags(pTHX_ HV *hv, const char *key, I32 klen, SV *val,
268 register U32 hash, int flags)
270 HE *hek = hv_fetch_common (hv, NULL, key, klen, flags,
271 (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
272 return hek ? &HeVAL(hek) : NULL;
276 =for apidoc hv_store_ent
278 Stores C<val> in a hash. The hash key is specified as C<key>. The C<hash>
279 parameter is the precomputed hash value; if it is zero then Perl will
280 compute it. The return value is the new hash entry so created. It will be
281 NULL if the operation failed or if the value did not need to be actually
282 stored within the hash (as in the case of tied hashes). Otherwise the
283 contents of the return value can be accessed using the C<He?> macros
284 described here. Note that the caller is responsible for suitably
285 incrementing the reference count of C<val> before the call, and
286 decrementing it if the function returned NULL. Effectively a successful
287 hv_store_ent takes ownership of one reference to C<val>. This is
288 usually what you want; a newly created SV has a reference count of one, so
289 if all your code does is create SVs then store them in a hash, hv_store
290 will own the only reference to the new SV, and your code doesn't need to do
291 anything further to tidy up. Note that hv_store_ent only reads the C<key>;
292 unlike C<val> it does not take ownership of it, so maintaining the correct
293 reference count on C<key> is entirely the caller's responsibility. hv_store
294 is not implemented as a call to hv_store_ent, and does not create a temporary
295 SV for the key, so if your key data is not already in SV form then use
296 hv_store in preference to hv_store_ent.
298 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
299 information on how to use this function on tied hashes.
305 Perl_hv_store_ent(pTHX_ HV *hv, SV *keysv, SV *val, U32 hash)
307 return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISSTORE, val, hash);
311 =for apidoc hv_exists
313 Returns a boolean indicating whether the specified hash key exists. The
314 C<klen> is the length of the key.
320 Perl_hv_exists(pTHX_ HV *hv, const char *key, I32 klen_i32)
332 return hv_fetch_common(hv, NULL, key, klen, flags, HV_FETCH_ISEXISTS, 0, 0)
339 Returns the SV which corresponds to the specified key in the hash. The
340 C<klen> is the length of the key. If C<lval> is set then the fetch will be
341 part of a store. Check that the return value is non-null before
342 dereferencing it to an C<SV*>.
344 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
345 information on how to use this function on tied hashes.
351 Perl_hv_fetch(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 lval)
364 hek = hv_fetch_common (hv, NULL, key, klen, flags,
365 HV_FETCH_JUST_SV | (lval ? HV_FETCH_LVALUE : 0),
367 return hek ? &HeVAL(hek) : NULL;
371 =for apidoc hv_exists_ent
373 Returns a boolean indicating whether the specified hash key exists. C<hash>
374 can be a valid precomputed hash value, or 0 to ask for it to be
381 Perl_hv_exists_ent(pTHX_ HV *hv, SV *keysv, U32 hash)
383 return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISEXISTS, 0, hash)
387 /* returns an HE * structure with the all fields set */
388 /* note that hent_val will be a mortal sv for MAGICAL hashes */
390 =for apidoc hv_fetch_ent
392 Returns the hash entry which corresponds to the specified key in the hash.
393 C<hash> must be a valid precomputed hash number for the given C<key>, or 0
394 if you want the function to compute it. IF C<lval> is set then the fetch
395 will be part of a store. Make sure the return value is non-null before
396 accessing it. The return value when C<tb> is a tied hash is a pointer to a
397 static location, so be sure to make a copy of the structure if you need to
400 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
401 information on how to use this function on tied hashes.
407 Perl_hv_fetch_ent(pTHX_ HV *hv, SV *keysv, I32 lval, register U32 hash)
409 return hv_fetch_common(hv, keysv, NULL, 0, 0,
410 (lval ? HV_FETCH_LVALUE : 0), Nullsv, hash);
414 S_hv_fetch_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
415 int flags, int action, SV *val, register U32 hash)
429 if (flags & HVhek_FREEKEY)
431 key = SvPV_const(keysv, klen);
433 is_utf8 = (SvUTF8(keysv) != 0);
435 is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
438 xhv = (XPVHV*)SvANY(hv);
440 if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS)))
442 if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
445 /* XXX should be able to skimp on the HE/HEK here when
446 HV_FETCH_JUST_SV is true. */
449 keysv = newSVpvn(key, klen);
454 keysv = newSVsv(keysv);
456 mg_copy((SV*)hv, sv, (char *)keysv, HEf_SVKEY);
458 /* grab a fake HE/HEK pair from the pool or make a new one */
459 entry = PL_hv_fetch_ent_mh;
461 PL_hv_fetch_ent_mh = HeNEXT(entry);
465 New(54, k, HEK_BASESIZE + sizeof(SV*), char);
466 HeKEY_hek(entry) = (HEK*)k;
468 HeNEXT(entry) = Nullhe;
469 HeSVKEY_set(entry, keysv);
471 sv_upgrade(sv, SVt_PVLV);
473 /* so we can free entry when freeing sv */
474 LvTARG(sv) = (SV*)entry;
476 /* XXX remove at some point? */
477 if (flags & HVhek_FREEKEY)
482 #ifdef ENV_IS_CASELESS
483 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
485 for (i = 0; i < klen; ++i)
486 if (isLOWER(key[i])) {
487 /* Would be nice if we had a routine to do the
488 copy and upercase in a single pass through. */
489 const char *nkey = strupr(savepvn(key,klen));
490 /* Note that this fetch is for nkey (the uppercased
491 key) whereas the store is for key (the original) */
492 entry = hv_fetch_common(hv, Nullsv, nkey, klen,
493 HVhek_FREEKEY, /* free nkey */
494 0 /* non-LVAL fetch */,
495 Nullsv /* no value */,
496 0 /* compute hash */);
497 if (!entry && (action & HV_FETCH_LVALUE)) {
498 /* This call will free key if necessary.
499 Do it this way to encourage compiler to tail
501 entry = hv_fetch_common(hv, keysv, key, klen,
502 flags, HV_FETCH_ISSTORE,
505 if (flags & HVhek_FREEKEY)
513 else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
514 if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
516 /* I don't understand why hv_exists_ent has svret and sv,
517 whereas hv_exists only had one. */
518 svret = sv_newmortal();
521 if (keysv || is_utf8) {
523 keysv = newSVpvn(key, klen);
526 keysv = newSVsv(keysv);
528 mg_copy((SV*)hv, sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
530 mg_copy((SV*)hv, sv, key, klen);
532 if (flags & HVhek_FREEKEY)
534 magic_existspack(svret, mg_find(sv, PERL_MAGIC_tiedelem));
535 /* This cast somewhat evil, but I'm merely using NULL/
536 not NULL to return the boolean exists.
537 And I know hv is not NULL. */
538 return SvTRUE(svret) ? (HE *)hv : NULL;
540 #ifdef ENV_IS_CASELESS
541 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
542 /* XXX This code isn't UTF8 clean. */
543 const char *keysave = key;
544 /* Will need to free this, so set FREEKEY flag. */
545 key = savepvn(key,klen);
546 key = (const char*)strupr((char*)key);
551 if (flags & HVhek_FREEKEY) {
554 flags |= HVhek_FREEKEY;
558 else if (action & HV_FETCH_ISSTORE) {
561 hv_magic_check (hv, &needs_copy, &needs_store);
563 const bool save_taint = PL_tainted;
564 if (keysv || is_utf8) {
566 keysv = newSVpvn(key, klen);
570 PL_tainted = SvTAINTED(keysv);
571 keysv = sv_2mortal(newSVsv(keysv));
572 mg_copy((SV*)hv, val, (char*)keysv, HEf_SVKEY);
574 mg_copy((SV*)hv, val, key, klen);
577 TAINT_IF(save_taint);
578 if (!HvARRAY(hv) && !needs_store) {
579 if (flags & HVhek_FREEKEY)
583 #ifdef ENV_IS_CASELESS
584 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
585 /* XXX This code isn't UTF8 clean. */
586 const char *keysave = key;
587 /* Will need to free this, so set FREEKEY flag. */
588 key = savepvn(key,klen);
589 key = (const char*)strupr((char*)key);
594 if (flags & HVhek_FREEKEY) {
597 flags |= HVhek_FREEKEY;
605 if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
606 #ifdef DYNAMIC_ENV_FETCH /* if it's an %ENV lookup, we may get it on the fly */
607 || (SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
612 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
614 HvARRAY(hv) = (HE**)array;
616 #ifdef DYNAMIC_ENV_FETCH
617 else if (action & HV_FETCH_ISEXISTS) {
618 /* for an %ENV exists, if we do an insert it's by a recursive
619 store call, so avoid creating HvARRAY(hv) right now. */
623 /* XXX remove at some point? */
624 if (flags & HVhek_FREEKEY)
632 const char *keysave = key;
633 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
637 flags &= ~HVhek_UTF8;
638 if (key != keysave) {
639 if (flags & HVhek_FREEKEY)
641 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
646 PERL_HASH_INTERNAL(hash, key, klen);
647 /* We don't have a pointer to the hv, so we have to replicate the
648 flag into every HEK, so that hv_iterkeysv can see it. */
649 /* And yes, you do need this even though you are not "storing" because
650 you can flip the flags below if doing an lval lookup. (And that
651 was put in to give the semantics Andreas was expecting.) */
652 flags |= HVhek_REHASH;
654 if (keysv && (SvIsCOW_shared_hash(keysv))) {
655 hash = SvSHARED_HASH(keysv);
657 PERL_HASH(hash, key, klen);
661 masked_flags = (flags & HVhek_MASK);
663 #ifdef DYNAMIC_ENV_FETCH
664 if (!HvARRAY(hv)) entry = Null(HE*);
668 entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
670 for (; entry; entry = HeNEXT(entry)) {
671 if (HeHASH(entry) != hash) /* strings can't be equal */
673 if (HeKLEN(entry) != (I32)klen)
675 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
677 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
680 if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
681 if (HeKFLAGS(entry) != masked_flags) {
682 /* We match if HVhek_UTF8 bit in our flags and hash key's
683 match. But if entry was set previously with HVhek_WASUTF8
684 and key now doesn't (or vice versa) then we should change
685 the key's flag, as this is assignment. */
686 if (HvSHAREKEYS(hv)) {
687 /* Need to swap the key we have for a key with the flags we
688 need. As keys are shared we can't just write to the
689 flag, so we share the new one, unshare the old one. */
690 HEK *new_hek = share_hek_flags(key, klen, hash,
692 unshare_hek (HeKEY_hek(entry));
693 HeKEY_hek(entry) = new_hek;
696 HeKFLAGS(entry) = masked_flags;
697 if (masked_flags & HVhek_ENABLEHVKFLAGS)
700 if (HeVAL(entry) == &PL_sv_placeholder) {
701 /* yes, can store into placeholder slot */
702 if (action & HV_FETCH_LVALUE) {
704 /* This preserves behaviour with the old hv_fetch
705 implementation which at this point would bail out
706 with a break; (at "if we find a placeholder, we
707 pretend we haven't found anything")
709 That break mean that if a placeholder were found, it
710 caused a call into hv_store, which in turn would
711 check magic, and if there is no magic end up pretty
712 much back at this point (in hv_store's code). */
715 /* LVAL fetch which actaully needs a store. */
717 HvPLACEHOLDERS(hv)--;
720 if (val != &PL_sv_placeholder)
721 HvPLACEHOLDERS(hv)--;
724 } else if (action & HV_FETCH_ISSTORE) {
725 SvREFCNT_dec(HeVAL(entry));
728 } else if (HeVAL(entry) == &PL_sv_placeholder) {
729 /* if we find a placeholder, we pretend we haven't found
733 if (flags & HVhek_FREEKEY)
737 #ifdef DYNAMIC_ENV_FETCH /* %ENV lookup? If so, try to fetch the value now */
738 if (!(action & HV_FETCH_ISSTORE)
739 && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
741 char *env = PerlEnv_ENVgetenv_len(key,&len);
743 sv = newSVpvn(env,len);
745 return hv_fetch_common(hv,keysv,key,klen,flags,HV_FETCH_ISSTORE,sv,
751 if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
752 S_hv_notallowed(aTHX_ flags, key, klen,
753 "Attempt to access disallowed key '%"SVf"' in"
754 " a restricted hash");
756 if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
757 /* Not doing some form of store, so return failure. */
758 if (flags & HVhek_FREEKEY)
762 if (action & HV_FETCH_LVALUE) {
765 /* At this point the old hv_fetch code would call to hv_store,
766 which in turn might do some tied magic. So we need to make that
767 magic check happen. */
768 /* gonna assign to this, so it better be there */
769 return hv_fetch_common(hv, keysv, key, klen, flags,
770 HV_FETCH_ISSTORE, val, hash);
771 /* XXX Surely that could leak if the fetch-was-store fails?
772 Just like the hv_fetch. */
776 /* Welcome to hv_store... */
779 /* Not sure if we can get here. I think the only case of oentry being
780 NULL is for %ENV with dynamic env fetch. But that should disappear
781 with magic in the previous code. */
784 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
786 HvARRAY(hv) = (HE**)array;
789 oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
792 /* share_hek_flags will do the free for us. This might be considered
795 HeKEY_hek(entry) = share_hek_flags(key, klen, hash, flags);
796 else /* gotta do the real thing */
797 HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
799 HeNEXT(entry) = *oentry;
802 if (val == &PL_sv_placeholder)
803 HvPLACEHOLDERS(hv)++;
804 if (masked_flags & HVhek_ENABLEHVKFLAGS)
808 const HE *counter = HeNEXT(entry);
810 xhv->xhv_keys++; /* HvKEYS(hv)++ */
811 if (!counter) { /* initial entry? */
812 xhv->xhv_fill++; /* HvFILL(hv)++ */
813 } else if (xhv->xhv_keys > (IV)xhv->xhv_max) {
815 } else if(!HvREHASH(hv)) {
818 while ((counter = HeNEXT(counter)))
821 if (n_links > HV_MAX_LENGTH_BEFORE_SPLIT) {
822 /* Use only the old HvKEYS(hv) > HvMAX(hv) condition to limit
823 bucket splits on a rehashed hash, as we're not going to
824 split it again, and if someone is lucky (evil) enough to
825 get all the keys in one list they could exhaust our memory
826 as we repeatedly double the number of buckets on every
827 entry. Linear search feels a less worse thing to do. */
837 S_hv_magic_check(pTHX_ HV *hv, bool *needs_copy, bool *needs_store)
839 const MAGIC *mg = SvMAGIC(hv);
843 if (isUPPER(mg->mg_type)) {
845 switch (mg->mg_type) {
846 case PERL_MAGIC_tied:
848 *needs_store = FALSE;
849 return; /* We've set all there is to set. */
852 mg = mg->mg_moremagic;
857 =for apidoc hv_scalar
859 Evaluates the hash in scalar context and returns the result. Handles magic when the hash is tied.
865 Perl_hv_scalar(pTHX_ HV *hv)
870 if ((SvRMAGICAL(hv) && (mg = mg_find((SV*)hv, PERL_MAGIC_tied)))) {
871 sv = magic_scalarpack(hv, mg);
877 Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
878 (long)HvFILL(hv), (long)HvMAX(hv) + 1);
886 =for apidoc hv_delete
888 Deletes a key/value pair in the hash. The value SV is removed from the
889 hash and returned to the caller. The C<klen> is the length of the key.
890 The C<flags> value will normally be zero; if set to G_DISCARD then NULL
897 Perl_hv_delete(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 flags)
904 k_flags |= HVhek_UTF8;
908 return hv_delete_common(hv, NULL, key, klen, k_flags, flags, 0);
912 =for apidoc hv_delete_ent
914 Deletes a key/value pair in the hash. The value SV is removed from the
915 hash and returned to the caller. The C<flags> value will normally be zero;
916 if set to G_DISCARD then NULL will be returned. C<hash> can be a valid
917 precomputed hash value, or 0 to ask for it to be computed.
923 Perl_hv_delete_ent(pTHX_ HV *hv, SV *keysv, I32 flags, U32 hash)
925 return hv_delete_common(hv, keysv, NULL, 0, 0, flags, hash);
929 S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
930 int k_flags, I32 d_flags, U32 hash)
935 register HE **oentry;
936 HE *const *first_entry;
945 if (k_flags & HVhek_FREEKEY)
947 key = SvPV_const(keysv, klen);
949 is_utf8 = (SvUTF8(keysv) != 0);
951 is_utf8 = ((k_flags & HVhek_UTF8) ? TRUE : FALSE);
954 if (SvRMAGICAL(hv)) {
957 hv_magic_check (hv, &needs_copy, &needs_store);
960 entry = hv_fetch_common(hv, keysv, key, klen,
961 k_flags & ~HVhek_FREEKEY, HV_FETCH_LVALUE,
963 sv = entry ? HeVAL(entry) : NULL;
969 if (mg_find(sv, PERL_MAGIC_tiedelem)) {
970 /* No longer an element */
971 sv_unmagic(sv, PERL_MAGIC_tiedelem);
974 return Nullsv; /* element cannot be deleted */
976 #ifdef ENV_IS_CASELESS
977 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
978 /* XXX This code isn't UTF8 clean. */
979 keysv = sv_2mortal(newSVpvn(key,klen));
980 if (k_flags & HVhek_FREEKEY) {
983 key = strupr(SvPVX(keysv));
992 xhv = (XPVHV*)SvANY(hv);
997 const char *keysave = key;
998 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
1001 k_flags |= HVhek_UTF8;
1003 k_flags &= ~HVhek_UTF8;
1004 if (key != keysave) {
1005 if (k_flags & HVhek_FREEKEY) {
1006 /* This shouldn't happen if our caller does what we expect,
1007 but strictly the API allows it. */
1010 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
1012 HvHASKFLAGS_on((SV*)hv);
1016 PERL_HASH_INTERNAL(hash, key, klen);
1018 if (keysv && (SvIsCOW_shared_hash(keysv))) {
1019 hash = SvSHARED_HASH(keysv);
1021 PERL_HASH(hash, key, klen);
1025 masked_flags = (k_flags & HVhek_MASK);
1027 first_entry = oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
1029 for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
1030 if (HeHASH(entry) != hash) /* strings can't be equal */
1032 if (HeKLEN(entry) != (I32)klen)
1034 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
1036 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
1039 /* if placeholder is here, it's already been deleted.... */
1040 if (HeVAL(entry) == &PL_sv_placeholder)
1042 if (k_flags & HVhek_FREEKEY)
1046 else if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1047 S_hv_notallowed(aTHX_ k_flags, key, klen,
1048 "Attempt to delete readonly key '%"SVf"' from"
1049 " a restricted hash");
1051 if (k_flags & HVhek_FREEKEY)
1054 if (d_flags & G_DISCARD)
1057 sv = sv_2mortal(HeVAL(entry));
1058 HeVAL(entry) = &PL_sv_placeholder;
1062 * If a restricted hash, rather than really deleting the entry, put
1063 * a placeholder there. This marks the key as being "approved", so
1064 * we can still access via not-really-existing key without raising
1067 if (SvREADONLY(hv)) {
1068 SvREFCNT_dec(HeVAL(entry));
1069 HeVAL(entry) = &PL_sv_placeholder;
1070 /* We'll be saving this slot, so the number of allocated keys
1071 * doesn't go down, but the number placeholders goes up */
1072 HvPLACEHOLDERS(hv)++;
1074 *oentry = HeNEXT(entry);
1076 xhv->xhv_fill--; /* HvFILL(hv)-- */
1078 if (SvOOK(hv) && entry == HvAUX(hv)->xhv_eiter /* HvEITER(hv) */)
1081 hv_free_ent(hv, entry);
1082 xhv->xhv_keys--; /* HvKEYS(hv)-- */
1083 if (xhv->xhv_keys == 0)
1084 HvHASKFLAGS_off(hv);
1088 if (SvREADONLY(hv)) {
1089 S_hv_notallowed(aTHX_ k_flags, key, klen,
1090 "Attempt to delete disallowed key '%"SVf"' from"
1091 " a restricted hash");
1094 if (k_flags & HVhek_FREEKEY)
1100 S_hsplit(pTHX_ HV *hv)
1102 register XPVHV* xhv = (XPVHV*)SvANY(hv);
1103 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1104 register I32 newsize = oldsize * 2;
1106 char *a = (char*) HvARRAY(hv);
1108 register HE **oentry;
1109 int longest_chain = 0;
1112 /*PerlIO_printf(PerlIO_stderr(), "hsplit called for %p which had %d\n",
1113 hv, (int) oldsize);*/
1115 if (HvPLACEHOLDERS_get(hv) && !SvREADONLY(hv)) {
1116 /* Can make this clear any placeholders first for non-restricted hashes,
1117 even though Storable rebuilds restricted hashes by putting in all the
1118 placeholders (first) before turning on the readonly flag, because
1119 Storable always pre-splits the hash. */
1120 hv_clear_placeholders(hv);
1124 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1125 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1126 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1132 Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1135 New(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1136 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1141 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1143 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1145 if (oldsize >= 64) {
1146 offer_nice_chunk(HvARRAY(hv),
1147 PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
1148 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
1151 Safefree(HvARRAY(hv));
1155 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1156 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
1157 HvARRAY(hv) = (HE**) a;
1160 for (i=0; i<oldsize; i++,aep++) {
1161 int left_length = 0;
1162 int right_length = 0;
1166 if (!*aep) /* non-existent */
1169 for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1170 if ((HeHASH(entry) & newsize) != (U32)i) {
1171 *oentry = HeNEXT(entry);
1172 HeNEXT(entry) = *bep;
1174 xhv->xhv_fill++; /* HvFILL(hv)++ */
1180 oentry = &HeNEXT(entry);
1184 if (!*aep) /* everything moved */
1185 xhv->xhv_fill--; /* HvFILL(hv)-- */
1186 /* I think we don't actually need to keep track of the longest length,
1187 merely flag if anything is too long. But for the moment while
1188 developing this code I'll track it. */
1189 if (left_length > longest_chain)
1190 longest_chain = left_length;
1191 if (right_length > longest_chain)
1192 longest_chain = right_length;
1196 /* Pick your policy for "hashing isn't working" here: */
1197 if (longest_chain <= HV_MAX_LENGTH_BEFORE_SPLIT /* split worked? */
1202 if (hv == PL_strtab) {
1203 /* Urg. Someone is doing something nasty to the string table.
1208 /* Awooga. Awooga. Pathological data. */
1209 /*PerlIO_printf(PerlIO_stderr(), "%p %d of %d with %d/%d buckets\n", hv,
1210 longest_chain, HvTOTALKEYS(hv), HvFILL(hv), 1+HvMAX(hv));*/
1213 Newz(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1214 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1216 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1219 was_shared = HvSHAREKEYS(hv);
1222 HvSHAREKEYS_off(hv);
1227 for (i=0; i<newsize; i++,aep++) {
1228 register HE *entry = *aep;
1230 /* We're going to trash this HE's next pointer when we chain it
1231 into the new hash below, so store where we go next. */
1232 HE *next = HeNEXT(entry);
1237 PERL_HASH_INTERNAL(hash, HeKEY(entry), HeKLEN(entry));
1242 = save_hek_flags(HeKEY(entry), HeKLEN(entry),
1243 hash, HeKFLAGS(entry));
1244 unshare_hek (HeKEY_hek(entry));
1245 HeKEY_hek(entry) = new_hek;
1247 /* Not shared, so simply write the new hash in. */
1248 HeHASH(entry) = hash;
1250 /*PerlIO_printf(PerlIO_stderr(), "%d ", HeKFLAGS(entry));*/
1251 HEK_REHASH_on(HeKEY_hek(entry));
1252 /*PerlIO_printf(PerlIO_stderr(), "%d\n", HeKFLAGS(entry));*/
1254 /* Copy oentry to the correct new chain. */
1255 bep = ((HE**)a) + (hash & (I32) xhv->xhv_max);
1257 xhv->xhv_fill++; /* HvFILL(hv)++ */
1258 HeNEXT(entry) = *bep;
1264 Safefree (HvARRAY(hv));
1265 HvARRAY(hv) = (HE **)a;
1269 Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
1271 register XPVHV* xhv = (XPVHV*)SvANY(hv);
1272 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1273 register I32 newsize;
1278 register HE **oentry;
1280 newsize = (I32) newmax; /* possible truncation here */
1281 if (newsize != newmax || newmax <= oldsize)
1283 while ((newsize & (1 + ~newsize)) != newsize) {
1284 newsize &= ~(newsize & (1 + ~newsize)); /* get proper power of 2 */
1286 if (newsize < newmax)
1288 if (newsize < newmax)
1289 return; /* overflow detection */
1291 a = (char *) HvARRAY(hv);
1294 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1295 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1296 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1302 Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1305 New(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1306 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1311 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1313 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1315 if (oldsize >= 64) {
1316 offer_nice_chunk(HvARRAY(hv),
1317 PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
1318 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
1321 Safefree(HvARRAY(hv));
1324 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1327 Newz(0, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1329 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
1330 HvARRAY(hv) = (HE **) a;
1331 if (!xhv->xhv_fill /* !HvFILL(hv) */) /* skip rest if no entries */
1335 for (i=0; i<oldsize; i++,aep++) {
1336 if (!*aep) /* non-existent */
1338 for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1340 if ((j = (HeHASH(entry) & newsize)) != i) {
1342 *oentry = HeNEXT(entry);
1343 if (!(HeNEXT(entry) = aep[j]))
1344 xhv->xhv_fill++; /* HvFILL(hv)++ */
1349 oentry = &HeNEXT(entry);
1351 if (!*aep) /* everything moved */
1352 xhv->xhv_fill--; /* HvFILL(hv)-- */
1359 Creates a new HV. The reference count is set to 1.
1368 register XPVHV* xhv;
1370 hv = (HV*)NEWSV(502,0);
1371 sv_upgrade((SV *)hv, SVt_PVHV);
1372 xhv = (XPVHV*)SvANY(hv);
1375 #ifndef NODEFAULT_SHAREKEYS
1376 HvSHAREKEYS_on(hv); /* key-sharing on by default */
1379 xhv->xhv_max = 7; /* HvMAX(hv) = 7 (start with 8 buckets) */
1380 xhv->xhv_fill = 0; /* HvFILL(hv) = 0 */
1385 Perl_newHVhv(pTHX_ HV *ohv)
1388 STRLEN hv_max, hv_fill;
1390 if (!ohv || (hv_fill = HvFILL(ohv)) == 0)
1392 hv_max = HvMAX(ohv);
1394 if (!SvMAGICAL((SV *)ohv)) {
1395 /* It's an ordinary hash, so copy it fast. AMS 20010804 */
1397 const bool shared = !!HvSHAREKEYS(ohv);
1398 HE **ents, **oents = (HE **)HvARRAY(ohv);
1400 New(0, a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
1403 /* In each bucket... */
1404 for (i = 0; i <= hv_max; i++) {
1405 HE *prev = NULL, *ent = NULL, *oent = oents[i];
1412 /* Copy the linked list of entries. */
1413 for (oent = oents[i]; oent; oent = HeNEXT(oent)) {
1414 const U32 hash = HeHASH(oent);
1415 const char * const key = HeKEY(oent);
1416 const STRLEN len = HeKLEN(oent);
1417 const int flags = HeKFLAGS(oent);
1420 HeVAL(ent) = newSVsv(HeVAL(oent));
1422 = shared ? share_hek_flags(key, len, hash, flags)
1423 : save_hek_flags(key, len, hash, flags);
1434 HvFILL(hv) = hv_fill;
1435 HvTOTALKEYS(hv) = HvTOTALKEYS(ohv);
1439 /* Iterate over ohv, copying keys and values one at a time. */
1441 const I32 riter = HvRITER_get(ohv);
1442 HE * const eiter = HvEITER_get(ohv);
1444 /* Can we use fewer buckets? (hv_max is always 2^n-1) */
1445 while (hv_max && hv_max + 1 >= hv_fill * 2)
1446 hv_max = hv_max / 2;
1450 while ((entry = hv_iternext_flags(ohv, 0))) {
1451 hv_store_flags(hv, HeKEY(entry), HeKLEN(entry),
1452 newSVsv(HeVAL(entry)), HeHASH(entry),
1455 HvRITER_set(ohv, riter);
1456 HvEITER_set(ohv, eiter);
1463 Perl_hv_free_ent(pTHX_ HV *hv, register HE *entry)
1470 if (val && isGV(val) && GvCVu(val) && HvNAME_get(hv))
1471 PL_sub_generation++; /* may be deletion of method from stash */
1473 if (HeKLEN(entry) == HEf_SVKEY) {
1474 SvREFCNT_dec(HeKEY_sv(entry));
1475 Safefree(HeKEY_hek(entry));
1477 else if (HvSHAREKEYS(hv))
1478 unshare_hek(HeKEY_hek(entry));
1480 Safefree(HeKEY_hek(entry));
1485 Perl_hv_delayfree_ent(pTHX_ HV *hv, register HE *entry)
1489 if (isGV(HeVAL(entry)) && GvCVu(HeVAL(entry)) && HvNAME_get(hv))
1490 PL_sub_generation++; /* may be deletion of method from stash */
1491 sv_2mortal(HeVAL(entry)); /* free between statements */
1492 if (HeKLEN(entry) == HEf_SVKEY) {
1493 sv_2mortal(HeKEY_sv(entry));
1494 Safefree(HeKEY_hek(entry));
1496 else if (HvSHAREKEYS(hv))
1497 unshare_hek(HeKEY_hek(entry));
1499 Safefree(HeKEY_hek(entry));
1504 =for apidoc hv_clear
1506 Clears a hash, making it empty.
1512 Perl_hv_clear(pTHX_ HV *hv)
1515 register XPVHV* xhv;
1519 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1521 xhv = (XPVHV*)SvANY(hv);
1523 if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
1524 /* restricted hash: convert all keys to placeholders */
1526 for (i = 0; i <= xhv->xhv_max; i++) {
1527 HE *entry = (HvARRAY(hv))[i];
1528 for (; entry; entry = HeNEXT(entry)) {
1529 /* not already placeholder */
1530 if (HeVAL(entry) != &PL_sv_placeholder) {
1531 if (HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1532 SV* keysv = hv_iterkeysv(entry);
1534 "Attempt to delete readonly key '%"SVf"' from a restricted hash",
1537 SvREFCNT_dec(HeVAL(entry));
1538 HeVAL(entry) = &PL_sv_placeholder;
1539 HvPLACEHOLDERS(hv)++;
1547 HvPLACEHOLDERS_set(hv, 0);
1549 (void)memzero(HvARRAY(hv),
1550 (xhv->xhv_max+1 /* HvMAX(hv)+1 */) * sizeof(HE*));
1555 HvHASKFLAGS_off(hv);
1559 HvEITER_set(hv, NULL);
1564 =for apidoc hv_clear_placeholders
1566 Clears any placeholders from a hash. If a restricted hash has any of its keys
1567 marked as readonly and the key is subsequently deleted, the key is not actually
1568 deleted but is marked by assigning it a value of &PL_sv_placeholder. This tags
1569 it so it will be ignored by future operations such as iterating over the hash,
1570 but will still allow the hash to have a value reassigned to the key at some
1571 future point. This function clears any such placeholder keys from the hash.
1572 See Hash::Util::lock_keys() for an example of its use.
1578 Perl_hv_clear_placeholders(pTHX_ HV *hv)
1581 I32 items = (I32)HvPLACEHOLDERS_get(hv);
1589 /* Loop down the linked list heads */
1591 HE **oentry = &(HvARRAY(hv))[i];
1592 HE *entry = *oentry;
1597 for (; entry; entry = *oentry) {
1598 if (HeVAL(entry) == &PL_sv_placeholder) {
1599 *oentry = HeNEXT(entry);
1600 if (first && !*oentry)
1601 HvFILL(hv)--; /* This linked list is now empty. */
1602 if (HvEITER_get(hv))
1605 hv_free_ent(hv, entry);
1609 HvTOTALKEYS(hv) -= (IV)HvPLACEHOLDERS_get(hv);
1610 if (HvKEYS(hv) == 0)
1611 HvHASKFLAGS_off(hv);
1612 HvPLACEHOLDERS_set(hv, 0);
1616 oentry = &HeNEXT(entry);
1621 /* You can't get here, hence assertion should always fail. */
1622 assert (items == 0);
1627 S_hfreeentries(pTHX_ HV *hv)
1629 register HE **array;
1633 struct xpvhv_aux *iter;
1639 iter = SvOOK(hv) ? HvAUX(hv) : 0;
1643 array = HvARRAY(hv);
1644 /* make everyone else think the array is empty, so that the destructors
1645 * called for freed entries can't recusively mess with us */
1646 HvARRAY(hv) = Null(HE**);
1647 SvFLAGS(hv) &= ~SVf_OOK;
1650 ((XPVHV*) SvANY(hv))->xhv_keys = 0;
1655 register HE *oentry = entry;
1656 entry = HeNEXT(entry);
1657 hv_free_ent(hv, oentry);
1662 entry = array[riter];
1667 /* Someone attempted to iterate or set the hash name while we had
1668 the array set to 0. */
1669 assert(HvARRAY(hv));
1671 if (HvAUX(hv)->xhv_name)
1672 unshare_hek_or_pvn(HvAUX(hv)->xhv_name, 0, 0, 0);
1673 /* SvOOK_off calls sv_backoff, which isn't correct. */
1675 Safefree(HvARRAY(hv));
1677 SvFLAGS(hv) &= ~SVf_OOK;
1680 /* FIXME - things will still go horribly wrong (or at least leak) if
1681 people attempt to add elements to the hash while we're undef()ing it */
1683 entry = iter->xhv_eiter; /* HvEITER(hv) */
1684 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1686 hv_free_ent(hv, entry);
1688 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1689 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1690 SvFLAGS(hv) |= SVf_OOK;
1693 HvARRAY(hv) = array;
1697 =for apidoc hv_undef
1705 Perl_hv_undef(pTHX_ HV *hv)
1707 register XPVHV* xhv;
1711 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1712 xhv = (XPVHV*)SvANY(hv);
1714 if ((name = HvNAME_get(hv))) {
1716 hv_delete(PL_stashcache, name, HvNAMELEN_get(hv), G_DISCARD);
1717 Perl_hv_name_set(aTHX_ hv, 0, 0, 0);
1719 SvFLAGS(hv) &= ~SVf_OOK;
1720 Safefree(HvARRAY(hv));
1721 xhv->xhv_max = 7; /* HvMAX(hv) = 7 (it's a normal hash) */
1723 HvPLACEHOLDERS_set(hv, 0);
1729 static struct xpvhv_aux*
1730 S_hv_auxinit(pTHX_ HV *hv) {
1731 struct xpvhv_aux *iter;
1735 Newz(0, array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1736 + sizeof(struct xpvhv_aux), char);
1738 array = (char *) HvARRAY(hv);
1739 Renew(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1740 + sizeof(struct xpvhv_aux), char);
1742 HvARRAY(hv) = (HE**) array;
1743 /* SvOOK_on(hv) attacks the IV flags. */
1744 SvFLAGS(hv) |= SVf_OOK;
1747 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1748 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1755 =for apidoc hv_iterinit
1757 Prepares a starting point to traverse a hash table. Returns the number of
1758 keys in the hash (i.e. the same as C<HvKEYS(tb)>). The return value is
1759 currently only meaningful for hashes without tie magic.
1761 NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
1762 hash buckets that happen to be in use. If you still need that esoteric
1763 value, you can get it through the macro C<HvFILL(tb)>.
1770 Perl_hv_iterinit(pTHX_ HV *hv)
1775 Perl_croak(aTHX_ "Bad hash");
1778 struct xpvhv_aux *iter = HvAUX(hv);
1779 entry = iter->xhv_eiter; /* HvEITER(hv) */
1780 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1782 hv_free_ent(hv, entry);
1784 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1785 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1787 S_hv_auxinit(aTHX_ hv);
1790 /* used to be xhv->xhv_fill before 5.004_65 */
1791 return HvTOTALKEYS(hv);
1795 Perl_hv_riter_p(pTHX_ HV *hv) {
1796 struct xpvhv_aux *iter;
1799 Perl_croak(aTHX_ "Bad hash");
1801 iter = SvOOK(hv) ? HvAUX(hv) : S_hv_auxinit(aTHX_ hv);
1802 return &(iter->xhv_riter);
1806 Perl_hv_eiter_p(pTHX_ HV *hv) {
1807 struct xpvhv_aux *iter;
1810 Perl_croak(aTHX_ "Bad hash");
1812 iter = SvOOK(hv) ? HvAUX(hv) : S_hv_auxinit(aTHX_ hv);
1813 return &(iter->xhv_eiter);
1817 Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
1818 struct xpvhv_aux *iter;
1821 Perl_croak(aTHX_ "Bad hash");
1829 iter = S_hv_auxinit(aTHX_ hv);
1831 iter->xhv_riter = riter;
1835 Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
1836 struct xpvhv_aux *iter;
1839 Perl_croak(aTHX_ "Bad hash");
1844 /* 0 is the default so don't go malloc()ing a new structure just to
1849 iter = S_hv_auxinit(aTHX_ hv);
1851 iter->xhv_eiter = eiter;
1855 Perl_hv_name_set(pTHX_ HV *hv, const char *name, I32 len, int flags)
1857 struct xpvhv_aux *iter;
1863 if (iter->xhv_name) {
1864 unshare_hek_or_pvn(iter->xhv_name, 0, 0, 0);
1870 iter = S_hv_auxinit(aTHX_ hv);
1872 PERL_HASH(hash, name, len);
1873 iter->xhv_name = name ? share_hek(name, len, hash) : 0;
1877 =for apidoc hv_iternext
1879 Returns entries from a hash iterator. See C<hv_iterinit>.
1881 You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
1882 iterator currently points to, without losing your place or invalidating your
1883 iterator. Note that in this case the current entry is deleted from the hash
1884 with your iterator holding the last reference to it. Your iterator is flagged
1885 to free the entry on the next call to C<hv_iternext>, so you must not discard
1886 your iterator immediately else the entry will leak - call C<hv_iternext> to
1887 trigger the resource deallocation.
1893 Perl_hv_iternext(pTHX_ HV *hv)
1895 return hv_iternext_flags(hv, 0);
1899 =for apidoc hv_iternext_flags
1901 Returns entries from a hash iterator. See C<hv_iterinit> and C<hv_iternext>.
1902 The C<flags> value will normally be zero; if HV_ITERNEXT_WANTPLACEHOLDERS is
1903 set the placeholders keys (for restricted hashes) will be returned in addition
1904 to normal keys. By default placeholders are automatically skipped over.
1905 Currently a placeholder is implemented with a value that is
1906 C<&Perl_sv_placeholder>. Note that the implementation of placeholders and
1907 restricted hashes may change, and the implementation currently is
1908 insufficiently abstracted for any change to be tidy.
1914 Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
1917 register XPVHV* xhv;
1921 struct xpvhv_aux *iter;
1924 Perl_croak(aTHX_ "Bad hash");
1925 xhv = (XPVHV*)SvANY(hv);
1928 /* Too many things (well, pp_each at least) merrily assume that you can
1929 call iv_iternext without calling hv_iterinit, so we'll have to deal
1935 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
1937 if ((mg = SvTIED_mg((SV*)hv, PERL_MAGIC_tied))) {
1938 SV *key = sv_newmortal();
1940 sv_setsv(key, HeSVKEY_force(entry));
1941 SvREFCNT_dec(HeSVKEY(entry)); /* get rid of previous key */
1947 /* one HE per MAGICAL hash */
1948 iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
1950 Newz(54, k, HEK_BASESIZE + sizeof(SV*), char);
1952 HeKEY_hek(entry) = hek;
1953 HeKLEN(entry) = HEf_SVKEY;
1955 magic_nextpack((SV*) hv,mg,key);
1957 /* force key to stay around until next time */
1958 HeSVKEY_set(entry, SvREFCNT_inc(key));
1959 return entry; /* beware, hent_val is not set */
1962 SvREFCNT_dec(HeVAL(entry));
1963 Safefree(HeKEY_hek(entry));
1965 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1968 #ifdef DYNAMIC_ENV_FETCH /* set up %ENV for iteration */
1969 if (!entry && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
1973 /* hv_iterint now ensures this. */
1974 assert (HvARRAY(hv));
1976 /* At start of hash, entry is NULL. */
1979 entry = HeNEXT(entry);
1980 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
1982 * Skip past any placeholders -- don't want to include them in
1985 while (entry && HeVAL(entry) == &PL_sv_placeholder) {
1986 entry = HeNEXT(entry);
1991 /* OK. Come to the end of the current list. Grab the next one. */
1993 iter->xhv_riter++; /* HvRITER(hv)++ */
1994 if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
1995 /* There is no next one. End of the hash. */
1996 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1999 entry = (HvARRAY(hv))[iter->xhv_riter];
2001 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2002 /* If we have an entry, but it's a placeholder, don't count it.
2004 while (entry && HeVAL(entry) == &PL_sv_placeholder)
2005 entry = HeNEXT(entry);
2007 /* Will loop again if this linked list starts NULL
2008 (for HV_ITERNEXT_WANTPLACEHOLDERS)
2009 or if we run through it and find only placeholders. */
2012 if (oldentry && HvLAZYDEL(hv)) { /* was deleted earlier? */
2014 hv_free_ent(hv, oldentry);
2017 /*if (HvREHASH(hv) && entry && !HeKREHASH(entry))
2018 PerlIO_printf(PerlIO_stderr(), "Awooga %p %p\n", hv, entry);*/
2020 iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
2025 =for apidoc hv_iterkey
2027 Returns the key from the current position of the hash iterator. See
2034 Perl_hv_iterkey(pTHX_ register HE *entry, I32 *retlen)
2036 if (HeKLEN(entry) == HEf_SVKEY) {
2038 char *p = SvPV(HeKEY_sv(entry), len);
2043 *retlen = HeKLEN(entry);
2044 return HeKEY(entry);
2048 /* unlike hv_iterval(), this always returns a mortal copy of the key */
2050 =for apidoc hv_iterkeysv
2052 Returns the key as an C<SV*> from the current position of the hash
2053 iterator. The return value will always be a mortal copy of the key. Also
2060 Perl_hv_iterkeysv(pTHX_ register HE *entry)
2062 return sv_2mortal(newSVhek(HeKEY_hek(entry)));
2066 =for apidoc hv_iterval
2068 Returns the value from the current position of the hash iterator. See
2075 Perl_hv_iterval(pTHX_ HV *hv, register HE *entry)
2077 if (SvRMAGICAL(hv)) {
2078 if (mg_find((SV*)hv, PERL_MAGIC_tied)) {
2079 SV* sv = sv_newmortal();
2080 if (HeKLEN(entry) == HEf_SVKEY)
2081 mg_copy((SV*)hv, sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
2083 mg_copy((SV*)hv, sv, HeKEY(entry), HeKLEN(entry));
2087 return HeVAL(entry);
2091 =for apidoc hv_iternextsv
2093 Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2100 Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
2103 if ( (he = hv_iternext_flags(hv, 0)) == NULL)
2105 *key = hv_iterkey(he, retlen);
2106 return hv_iterval(hv, he);
2110 =for apidoc hv_magic
2112 Adds magic to a hash. See C<sv_magic>.
2118 Perl_hv_magic(pTHX_ HV *hv, GV *gv, int how)
2120 sv_magic((SV*)hv, (SV*)gv, how, Nullch, 0);
2123 #if 0 /* use the macro from hv.h instead */
2126 Perl_sharepvn(pTHX_ const char *sv, I32 len, U32 hash)
2128 return HEK_KEY(share_hek(sv, len, hash));
2133 /* possibly free a shared string if no one has access to it
2134 * len and hash must both be valid for str.
2137 Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
2139 unshare_hek_or_pvn (NULL, str, len, hash);
2144 Perl_unshare_hek(pTHX_ HEK *hek)
2146 unshare_hek_or_pvn(hek, NULL, 0, 0);
2149 /* possibly free a shared string if no one has access to it
2150 hek if non-NULL takes priority over the other 3, else str, len and hash
2151 are used. If so, len and hash must both be valid for str.
2154 S_unshare_hek_or_pvn(pTHX_ const HEK *hek, const char *str, I32 len, U32 hash)
2156 register XPVHV* xhv;
2158 register HE **oentry;
2161 bool is_utf8 = FALSE;
2163 const char *save = str;
2164 struct shared_he *he = 0;
2167 /* Find the shared he which is just before us in memory. */
2168 he = (struct shared_he *)(((char *)hek)
2169 - STRUCT_OFFSET(struct shared_he,
2172 /* Assert that the caller passed us a genuine (or at least consistent)
2174 assert (he->shared_he_he.hent_hek == hek);
2177 if (he->shared_he_he.hent_val - 1) {
2178 --he->shared_he_he.hent_val;
2179 UNLOCK_STRTAB_MUTEX;
2182 UNLOCK_STRTAB_MUTEX;
2184 hash = HEK_HASH(hek);
2185 } else if (len < 0) {
2186 STRLEN tmplen = -len;
2188 /* See the note in hv_fetch(). --jhi */
2189 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2192 k_flags = HVhek_UTF8;
2194 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2197 /* what follows is the moral equivalent of:
2198 if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
2199 if (--*Svp == Nullsv)
2200 hv_delete(PL_strtab, str, len, G_DISCARD, hash);
2202 xhv = (XPVHV*)SvANY(PL_strtab);
2203 /* assert(xhv_array != 0) */
2205 first = oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2207 const HE *const he_he = &(he->shared_he_he);
2208 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2215 const int flags_masked = k_flags & HVhek_MASK;
2216 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2217 if (HeHASH(entry) != hash) /* strings can't be equal */
2219 if (HeKLEN(entry) != len)
2221 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2223 if (HeKFLAGS(entry) != flags_masked)
2231 if (--HeVAL(entry) == Nullsv) {
2232 *oentry = HeNEXT(entry);
2234 /* There are now no entries in our slot. */
2235 xhv->xhv_fill--; /* HvFILL(hv)-- */
2238 xhv->xhv_keys--; /* HvKEYS(hv)-- */
2242 UNLOCK_STRTAB_MUTEX;
2243 if (!found && ckWARN_d(WARN_INTERNAL))
2244 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
2245 "Attempt to free non-existent shared string '%s'%s"
2247 hek ? HEK_KEY(hek) : str,
2248 ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
2249 if (k_flags & HVhek_FREEKEY)
2253 /* get a (constant) string ptr from the global string table
2254 * string will get added if it is not already there.
2255 * len and hash must both be valid for str.
2258 Perl_share_hek(pTHX_ const char *str, I32 len, register U32 hash)
2260 bool is_utf8 = FALSE;
2262 const char *save = str;
2265 STRLEN tmplen = -len;
2267 /* See the note in hv_fetch(). --jhi */
2268 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2270 /* If we were able to downgrade here, then than means that we were passed
2271 in a key which only had chars 0-255, but was utf8 encoded. */
2274 /* If we found we were able to downgrade the string to bytes, then
2275 we should flag that it needs upgrading on keys or each. Also flag
2276 that we need share_hek_flags to free the string. */
2278 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2281 return share_hek_flags (str, len, hash, flags);
2285 S_share_hek_flags(pTHX_ const char *str, I32 len, register U32 hash, int flags)
2287 register XPVHV* xhv;
2289 register HE **oentry;
2291 const int flags_masked = flags & HVhek_MASK;
2293 /* what follows is the moral equivalent of:
2295 if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
2296 hv_store(PL_strtab, str, len, Nullsv, hash);
2298 Can't rehash the shared string table, so not sure if it's worth
2299 counting the number of entries in the linked list
2301 xhv = (XPVHV*)SvANY(PL_strtab);
2302 /* assert(xhv_array != 0) */
2304 oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2305 for (entry = *oentry; entry; entry = HeNEXT(entry)) {
2306 if (HeHASH(entry) != hash) /* strings can't be equal */
2308 if (HeKLEN(entry) != len)
2310 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2312 if (HeKFLAGS(entry) != flags_masked)
2318 /* What used to be head of the list.
2319 If this is NULL, then we're the first entry for this slot, which
2320 means we need to increate fill. */
2321 const HE *old_first = *oentry;
2322 struct shared_he *new_entry;
2326 /* We don't actually store a HE from the arena and a regular HEK.
2327 Instead we allocate one chunk of memory big enough for both,
2328 and put the HEK straight after the HE. This way we can find the
2329 HEK directly from the HE.
2332 New(0, k, STRUCT_OFFSET(struct shared_he,
2333 shared_he_hek.hek_key[0]) + len + 2, char);
2334 new_entry = (struct shared_he *)k;
2335 entry = &(new_entry->shared_he_he);
2336 hek = &(new_entry->shared_he_hek);
2338 Copy(str, HEK_KEY(hek), len, char);
2339 HEK_KEY(hek)[len] = 0;
2341 HEK_HASH(hek) = hash;
2342 HEK_FLAGS(hek) = (unsigned char)flags_masked;
2344 /* Still "point" to the HEK, so that other code need not know what
2346 HeKEY_hek(entry) = hek;
2347 HeVAL(entry) = Nullsv;
2348 HeNEXT(entry) = *oentry;
2351 xhv->xhv_keys++; /* HvKEYS(hv)++ */
2352 if (!old_first) { /* initial entry? */
2353 xhv->xhv_fill++; /* HvFILL(hv)++ */
2354 } else if (xhv->xhv_keys > (IV)xhv->xhv_max /* HvKEYS(hv) > HvMAX(hv) */) {
2359 ++HeVAL(entry); /* use value slot as REFCNT */
2360 UNLOCK_STRTAB_MUTEX;
2362 if (flags & HVhek_FREEKEY)
2365 return HeKEY_hek(entry);
2369 Perl_hv_placeholders_p(pTHX_ HV *hv)
2372 MAGIC *mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2375 mg = sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, 0);
2378 Perl_die(aTHX_ "panic: hv_placeholders_p");
2381 return &(mg->mg_len);
2386 Perl_hv_placeholders_get(pTHX_ HV *hv)
2389 MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2391 return mg ? mg->mg_len : 0;
2395 Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
2398 MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2403 if (!sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, ph))
2404 Perl_die(aTHX_ "panic: hv_placeholders_set");
2406 /* else we don't need to add magic to record 0 placeholders. */
2410 =for apidoc hv_assert
2412 Check that a hash is in an internally consistent state.
2418 Perl_hv_assert(pTHX_ HV *hv)
2423 int placeholders = 0;
2426 const I32 riter = HvRITER_get(hv);
2427 HE *eiter = HvEITER_get(hv);
2429 (void)hv_iterinit(hv);
2431 while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
2432 /* sanity check the values */
2433 if (HeVAL(entry) == &PL_sv_placeholder) {
2438 /* sanity check the keys */
2439 if (HeSVKEY(entry)) {
2440 /* Don't know what to check on SV keys. */
2441 } else if (HeKUTF8(entry)) {
2443 if (HeKWASUTF8(entry)) {
2444 PerlIO_printf(Perl_debug_log,
2445 "hash key has both WASUFT8 and UTF8: '%.*s'\n",
2446 (int) HeKLEN(entry), HeKEY(entry));
2449 } else if (HeKWASUTF8(entry)) {
2453 if (!SvTIED_mg((SV*)hv, PERL_MAGIC_tied)) {
2454 if (HvUSEDKEYS(hv) != real) {
2455 PerlIO_printf(Perl_debug_log, "Count %d key(s), but hash reports %d\n",
2456 (int) real, (int) HvUSEDKEYS(hv));
2459 if (HvPLACEHOLDERS_get(hv) != placeholders) {
2460 PerlIO_printf(Perl_debug_log,
2461 "Count %d placeholder(s), but hash reports %d\n",
2462 (int) placeholders, (int) HvPLACEHOLDERS_get(hv));
2466 if (withflags && ! HvHASKFLAGS(hv)) {
2467 PerlIO_printf(Perl_debug_log,
2468 "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
2475 HvRITER_set(hv, riter); /* Restore hash iterator state */
2476 HvEITER_set(hv, eiter);
2481 * c-indentation-style: bsd
2483 * indent-tabs-mode: t
2486 * ex: set ts=8 sts=4 sw=4 noet: