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 HE *shared = (HE*)ptr_table_fetch(PL_shared_hek_table, source);
132 /* We already shared this hash key. */
136 shared = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
137 HEK_HASH(source), HEK_FLAGS(source));
138 ptr_table_store(PL_shared_hek_table, source, shared);
140 return HeKEY_hek(shared);
144 Perl_he_dup(pTHX_ HE *e, bool shared, CLONE_PARAMS* param)
150 /* look for it in the table first */
151 ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
155 /* create anew and remember what it is */
157 ptr_table_store(PL_ptr_table, e, ret);
159 HeNEXT(ret) = he_dup(HeNEXT(e),shared, param);
160 if (HeKLEN(e) == HEf_SVKEY) {
162 New(54, k, HEK_BASESIZE + sizeof(SV*), char);
163 HeKEY_hek(ret) = (HEK*)k;
164 HeKEY_sv(ret) = SvREFCNT_inc(sv_dup(HeKEY_sv(e), param));
167 /* This is hek_dup inlined, which seems to be important for speed
169 HEK *source = HeKEY_hek(e);
170 HE *shared = (HE*)ptr_table_fetch(PL_shared_hek_table, source);
173 /* We already shared this hash key. */
177 shared = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
178 HEK_HASH(source), HEK_FLAGS(source));
179 ptr_table_store(PL_shared_hek_table, source, shared);
181 HeKEY_hek(ret) = HeKEY_hek(shared);
184 HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
186 HeVAL(ret) = SvREFCNT_inc(sv_dup(HeVAL(e), param));
189 #endif /* USE_ITHREADS */
192 S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
195 SV *sv = sv_newmortal();
196 if (!(flags & HVhek_FREEKEY)) {
197 sv_setpvn(sv, key, klen);
200 /* Need to free saved eventually assign to mortal SV */
201 /* XXX is this line an error ???: SV *sv = sv_newmortal(); */
202 sv_usepvn(sv, (char *) key, klen);
204 if (flags & HVhek_UTF8) {
207 Perl_croak(aTHX_ msg, sv);
210 /* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
213 #define HV_FETCH_ISSTORE 0x01
214 #define HV_FETCH_ISEXISTS 0x02
215 #define HV_FETCH_LVALUE 0x04
216 #define HV_FETCH_JUST_SV 0x08
221 Stores an SV in a hash. The hash key is specified as C<key> and C<klen> is
222 the length of the key. The C<hash> parameter is the precomputed hash
223 value; if it is zero then Perl will compute it. The return value will be
224 NULL if the operation failed or if the value did not need to be actually
225 stored within the hash (as in the case of tied hashes). Otherwise it can
226 be dereferenced to get the original C<SV*>. Note that the caller is
227 responsible for suitably incrementing the reference count of C<val> before
228 the call, and decrementing it if the function returned NULL. Effectively
229 a successful hv_store takes ownership of one reference to C<val>. This is
230 usually what you want; a newly created SV has a reference count of one, so
231 if all your code does is create SVs then store them in a hash, hv_store
232 will own the only reference to the new SV, and your code doesn't need to do
233 anything further to tidy up. hv_store is not implemented as a call to
234 hv_store_ent, and does not create a temporary SV for the key, so if your
235 key data is not already in SV form then use hv_store in preference to
238 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
239 information on how to use this function on tied hashes.
245 Perl_hv_store(pTHX_ HV *hv, const char *key, I32 klen_i32, SV *val, U32 hash)
258 hek = hv_fetch_common (hv, NULL, key, klen, flags,
259 (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
260 return hek ? &HeVAL(hek) : NULL;
264 Perl_hv_store_flags(pTHX_ HV *hv, const char *key, I32 klen, SV *val,
265 register U32 hash, int flags)
267 HE *hek = hv_fetch_common (hv, NULL, key, klen, flags,
268 (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
269 return hek ? &HeVAL(hek) : NULL;
273 =for apidoc hv_store_ent
275 Stores C<val> in a hash. The hash key is specified as C<key>. The C<hash>
276 parameter is the precomputed hash value; if it is zero then Perl will
277 compute it. The return value is the new hash entry so created. It will be
278 NULL if the operation failed or if the value did not need to be actually
279 stored within the hash (as in the case of tied hashes). Otherwise the
280 contents of the return value can be accessed using the C<He?> macros
281 described here. Note that the caller is responsible for suitably
282 incrementing the reference count of C<val> before the call, and
283 decrementing it if the function returned NULL. Effectively a successful
284 hv_store_ent takes ownership of one reference to C<val>. This is
285 usually what you want; a newly created SV has a reference count of one, so
286 if all your code does is create SVs then store them in a hash, hv_store
287 will own the only reference to the new SV, and your code doesn't need to do
288 anything further to tidy up. Note that hv_store_ent only reads the C<key>;
289 unlike C<val> it does not take ownership of it, so maintaining the correct
290 reference count on C<key> is entirely the caller's responsibility. hv_store
291 is not implemented as a call to hv_store_ent, and does not create a temporary
292 SV for the key, so if your key data is not already in SV form then use
293 hv_store in preference to hv_store_ent.
295 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
296 information on how to use this function on tied hashes.
302 Perl_hv_store_ent(pTHX_ HV *hv, SV *keysv, SV *val, U32 hash)
304 return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISSTORE, val, hash);
308 =for apidoc hv_exists
310 Returns a boolean indicating whether the specified hash key exists. The
311 C<klen> is the length of the key.
317 Perl_hv_exists(pTHX_ HV *hv, const char *key, I32 klen_i32)
329 return hv_fetch_common(hv, NULL, key, klen, flags, HV_FETCH_ISEXISTS, 0, 0)
336 Returns the SV which corresponds to the specified key in the hash. The
337 C<klen> is the length of the key. If C<lval> is set then the fetch will be
338 part of a store. Check that the return value is non-null before
339 dereferencing it to an C<SV*>.
341 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
342 information on how to use this function on tied hashes.
348 Perl_hv_fetch(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 lval)
361 hek = hv_fetch_common (hv, NULL, key, klen, flags,
362 HV_FETCH_JUST_SV | (lval ? HV_FETCH_LVALUE : 0),
364 return hek ? &HeVAL(hek) : NULL;
368 =for apidoc hv_exists_ent
370 Returns a boolean indicating whether the specified hash key exists. C<hash>
371 can be a valid precomputed hash value, or 0 to ask for it to be
378 Perl_hv_exists_ent(pTHX_ HV *hv, SV *keysv, U32 hash)
380 return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISEXISTS, 0, hash)
384 /* returns an HE * structure with the all fields set */
385 /* note that hent_val will be a mortal sv for MAGICAL hashes */
387 =for apidoc hv_fetch_ent
389 Returns the hash entry which corresponds to the specified key in the hash.
390 C<hash> must be a valid precomputed hash number for the given C<key>, or 0
391 if you want the function to compute it. IF C<lval> is set then the fetch
392 will be part of a store. Make sure the return value is non-null before
393 accessing it. The return value when C<tb> is a tied hash is a pointer to a
394 static location, so be sure to make a copy of the structure if you need to
397 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
398 information on how to use this function on tied hashes.
404 Perl_hv_fetch_ent(pTHX_ HV *hv, SV *keysv, I32 lval, register U32 hash)
406 return hv_fetch_common(hv, keysv, NULL, 0, 0,
407 (lval ? HV_FETCH_LVALUE : 0), Nullsv, hash);
411 S_hv_fetch_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
412 int flags, int action, SV *val, register U32 hash)
426 if (flags & HVhek_FREEKEY)
428 key = SvPV(keysv, klen);
430 is_utf8 = (SvUTF8(keysv) != 0);
432 is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
435 xhv = (XPVHV*)SvANY(hv);
437 if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS)))
439 if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
442 /* XXX should be able to skimp on the HE/HEK here when
443 HV_FETCH_JUST_SV is true. */
446 keysv = newSVpvn(key, klen);
451 keysv = newSVsv(keysv);
453 mg_copy((SV*)hv, sv, (char *)keysv, HEf_SVKEY);
455 /* grab a fake HE/HEK pair from the pool or make a new one */
456 entry = PL_hv_fetch_ent_mh;
458 PL_hv_fetch_ent_mh = HeNEXT(entry);
462 New(54, k, HEK_BASESIZE + sizeof(SV*), char);
463 HeKEY_hek(entry) = (HEK*)k;
465 HeNEXT(entry) = Nullhe;
466 HeSVKEY_set(entry, keysv);
468 sv_upgrade(sv, SVt_PVLV);
470 /* so we can free entry when freeing sv */
471 LvTARG(sv) = (SV*)entry;
473 /* XXX remove at some point? */
474 if (flags & HVhek_FREEKEY)
479 #ifdef ENV_IS_CASELESS
480 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
482 for (i = 0; i < klen; ++i)
483 if (isLOWER(key[i])) {
484 /* Would be nice if we had a routine to do the
485 copy and upercase in a single pass through. */
486 const char *nkey = strupr(savepvn(key,klen));
487 /* Note that this fetch is for nkey (the uppercased
488 key) whereas the store is for key (the original) */
489 entry = hv_fetch_common(hv, Nullsv, nkey, klen,
490 HVhek_FREEKEY, /* free nkey */
491 0 /* non-LVAL fetch */,
492 Nullsv /* no value */,
493 0 /* compute hash */);
494 if (!entry && (action & HV_FETCH_LVALUE)) {
495 /* This call will free key if necessary.
496 Do it this way to encourage compiler to tail
498 entry = hv_fetch_common(hv, keysv, key, klen,
499 flags, HV_FETCH_ISSTORE,
502 if (flags & HVhek_FREEKEY)
510 else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
511 if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
513 /* I don't understand why hv_exists_ent has svret and sv,
514 whereas hv_exists only had one. */
515 svret = sv_newmortal();
518 if (keysv || is_utf8) {
520 keysv = newSVpvn(key, klen);
523 keysv = newSVsv(keysv);
525 mg_copy((SV*)hv, sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
527 mg_copy((SV*)hv, sv, key, klen);
529 if (flags & HVhek_FREEKEY)
531 magic_existspack(svret, mg_find(sv, PERL_MAGIC_tiedelem));
532 /* This cast somewhat evil, but I'm merely using NULL/
533 not NULL to return the boolean exists.
534 And I know hv is not NULL. */
535 return SvTRUE(svret) ? (HE *)hv : NULL;
537 #ifdef ENV_IS_CASELESS
538 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
539 /* XXX This code isn't UTF8 clean. */
540 const char *keysave = key;
541 /* Will need to free this, so set FREEKEY flag. */
542 key = savepvn(key,klen);
543 key = (const char*)strupr((char*)key);
548 if (flags & HVhek_FREEKEY) {
551 flags |= HVhek_FREEKEY;
555 else if (action & HV_FETCH_ISSTORE) {
558 hv_magic_check (hv, &needs_copy, &needs_store);
560 const bool save_taint = PL_tainted;
561 if (keysv || is_utf8) {
563 keysv = newSVpvn(key, klen);
567 PL_tainted = SvTAINTED(keysv);
568 keysv = sv_2mortal(newSVsv(keysv));
569 mg_copy((SV*)hv, val, (char*)keysv, HEf_SVKEY);
571 mg_copy((SV*)hv, val, key, klen);
574 TAINT_IF(save_taint);
575 if (!HvARRAY(hv) && !needs_store) {
576 if (flags & HVhek_FREEKEY)
580 #ifdef ENV_IS_CASELESS
581 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
582 /* XXX This code isn't UTF8 clean. */
583 const char *keysave = key;
584 /* Will need to free this, so set FREEKEY flag. */
585 key = savepvn(key,klen);
586 key = (const char*)strupr((char*)key);
591 if (flags & HVhek_FREEKEY) {
594 flags |= HVhek_FREEKEY;
602 if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
603 #ifdef DYNAMIC_ENV_FETCH /* if it's an %ENV lookup, we may get it on the fly */
604 || (SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
609 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
611 HvARRAY(hv) = (HE**)array;
613 #ifdef DYNAMIC_ENV_FETCH
614 else if (action & HV_FETCH_ISEXISTS) {
615 /* for an %ENV exists, if we do an insert it's by a recursive
616 store call, so avoid creating HvARRAY(hv) right now. */
620 /* XXX remove at some point? */
621 if (flags & HVhek_FREEKEY)
629 const char *keysave = key;
630 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
634 flags &= ~HVhek_UTF8;
635 if (key != keysave) {
636 if (flags & HVhek_FREEKEY)
638 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
643 PERL_HASH_INTERNAL(hash, key, klen);
644 /* We don't have a pointer to the hv, so we have to replicate the
645 flag into every HEK, so that hv_iterkeysv can see it. */
646 /* And yes, you do need this even though you are not "storing" because
647 you can flip the flags below if doing an lval lookup. (And that
648 was put in to give the semantics Andreas was expecting.) */
649 flags |= HVhek_REHASH;
651 if (keysv && (SvIsCOW_shared_hash(keysv))) {
654 PERL_HASH(hash, key, klen);
658 masked_flags = (flags & HVhek_MASK);
660 #ifdef DYNAMIC_ENV_FETCH
661 if (!HvARRAY(hv)) entry = Null(HE*);
665 entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
667 for (; entry; entry = HeNEXT(entry)) {
668 if (HeHASH(entry) != hash) /* strings can't be equal */
670 if (HeKLEN(entry) != (I32)klen)
672 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
674 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
677 if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
678 if (HeKFLAGS(entry) != masked_flags) {
679 /* We match if HVhek_UTF8 bit in our flags and hash key's
680 match. But if entry was set previously with HVhek_WASUTF8
681 and key now doesn't (or vice versa) then we should change
682 the key's flag, as this is assignment. */
683 if (HvSHAREKEYS(hv)) {
684 /* Need to swap the key we have for a key with the flags we
685 need. As keys are shared we can't just write to the
686 flag, so we share the new one, unshare the old one. */
687 HEK *new_hek = HeKEY_hek(share_hek_flags(key, klen, hash,
689 unshare_hek (HeKEY_hek(entry));
690 HeKEY_hek(entry) = new_hek;
693 HeKFLAGS(entry) = masked_flags;
694 if (masked_flags & HVhek_ENABLEHVKFLAGS)
697 if (HeVAL(entry) == &PL_sv_placeholder) {
698 /* yes, can store into placeholder slot */
699 if (action & HV_FETCH_LVALUE) {
701 /* This preserves behaviour with the old hv_fetch
702 implementation which at this point would bail out
703 with a break; (at "if we find a placeholder, we
704 pretend we haven't found anything")
706 That break mean that if a placeholder were found, it
707 caused a call into hv_store, which in turn would
708 check magic, and if there is no magic end up pretty
709 much back at this point (in hv_store's code). */
712 /* LVAL fetch which actaully needs a store. */
714 HvPLACEHOLDERS(hv)--;
717 if (val != &PL_sv_placeholder)
718 HvPLACEHOLDERS(hv)--;
721 } else if (action & HV_FETCH_ISSTORE) {
722 SvREFCNT_dec(HeVAL(entry));
725 } else if (HeVAL(entry) == &PL_sv_placeholder) {
726 /* if we find a placeholder, we pretend we haven't found
730 if (flags & HVhek_FREEKEY)
734 #ifdef DYNAMIC_ENV_FETCH /* %ENV lookup? If so, try to fetch the value now */
735 if (!(action & HV_FETCH_ISSTORE)
736 && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
738 char *env = PerlEnv_ENVgetenv_len(key,&len);
740 sv = newSVpvn(env,len);
742 return hv_fetch_common(hv,keysv,key,klen,flags,HV_FETCH_ISSTORE,sv,
748 if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
749 S_hv_notallowed(aTHX_ flags, key, klen,
750 "Attempt to access disallowed key '%"SVf"' in"
751 " a restricted hash");
753 if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
754 /* Not doing some form of store, so return failure. */
755 if (flags & HVhek_FREEKEY)
759 if (action & HV_FETCH_LVALUE) {
762 /* At this point the old hv_fetch code would call to hv_store,
763 which in turn might do some tied magic. So we need to make that
764 magic check happen. */
765 /* gonna assign to this, so it better be there */
766 return hv_fetch_common(hv, keysv, key, klen, flags,
767 HV_FETCH_ISSTORE, val, hash);
768 /* XXX Surely that could leak if the fetch-was-store fails?
769 Just like the hv_fetch. */
773 /* Welcome to hv_store... */
776 /* Not sure if we can get here. I think the only case of oentry being
777 NULL is for %ENV with dynamic env fetch. But that should disappear
778 with magic in the previous code. */
781 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
783 HvARRAY(hv) = (HE**)array;
786 oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
789 /* share_hek_flags will do the free for us. This might be considered
792 HeKEY_hek(entry) = HeKEY_hek(share_hek_flags(key, klen, hash, flags));
793 else /* gotta do the real thing */
794 HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
796 HeNEXT(entry) = *oentry;
799 if (val == &PL_sv_placeholder)
800 HvPLACEHOLDERS(hv)++;
801 if (masked_flags & HVhek_ENABLEHVKFLAGS)
805 const HE *counter = HeNEXT(entry);
807 xhv->xhv_keys++; /* HvKEYS(hv)++ */
808 if (!counter) { /* initial entry? */
809 xhv->xhv_fill++; /* HvFILL(hv)++ */
810 } else if (xhv->xhv_keys > (IV)xhv->xhv_max) {
812 } else if(!HvREHASH(hv)) {
815 while ((counter = HeNEXT(counter)))
818 if (n_links > HV_MAX_LENGTH_BEFORE_SPLIT) {
819 /* Use only the old HvKEYS(hv) > HvMAX(hv) condition to limit
820 bucket splits on a rehashed hash, as we're not going to
821 split it again, and if someone is lucky (evil) enough to
822 get all the keys in one list they could exhaust our memory
823 as we repeatedly double the number of buckets on every
824 entry. Linear search feels a less worse thing to do. */
834 S_hv_magic_check(pTHX_ HV *hv, bool *needs_copy, bool *needs_store)
836 const MAGIC *mg = SvMAGIC(hv);
840 if (isUPPER(mg->mg_type)) {
842 switch (mg->mg_type) {
843 case PERL_MAGIC_tied:
845 *needs_store = FALSE;
846 return; /* We've set all there is to set. */
849 mg = mg->mg_moremagic;
854 =for apidoc hv_scalar
856 Evaluates the hash in scalar context and returns the result. Handles magic when the hash is tied.
862 Perl_hv_scalar(pTHX_ HV *hv)
867 if ((SvRMAGICAL(hv) && (mg = mg_find((SV*)hv, PERL_MAGIC_tied)))) {
868 sv = magic_scalarpack(hv, mg);
874 Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
875 (long)HvFILL(hv), (long)HvMAX(hv) + 1);
883 =for apidoc hv_delete
885 Deletes a key/value pair in the hash. The value SV is removed from the
886 hash and returned to the caller. The C<klen> is the length of the key.
887 The C<flags> value will normally be zero; if set to G_DISCARD then NULL
894 Perl_hv_delete(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 flags)
901 k_flags |= HVhek_UTF8;
905 return hv_delete_common(hv, NULL, key, klen, k_flags, flags, 0);
909 =for apidoc hv_delete_ent
911 Deletes a key/value pair in the hash. The value SV is removed from the
912 hash and returned to the caller. The C<flags> value will normally be zero;
913 if set to G_DISCARD then NULL will be returned. C<hash> can be a valid
914 precomputed hash value, or 0 to ask for it to be computed.
920 Perl_hv_delete_ent(pTHX_ HV *hv, SV *keysv, I32 flags, U32 hash)
922 return hv_delete_common(hv, keysv, NULL, 0, 0, flags, hash);
926 S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
927 int k_flags, I32 d_flags, U32 hash)
932 register HE **oentry;
933 HE *const *first_entry;
942 if (k_flags & HVhek_FREEKEY)
944 key = SvPV(keysv, klen);
946 is_utf8 = (SvUTF8(keysv) != 0);
948 is_utf8 = ((k_flags & HVhek_UTF8) ? TRUE : FALSE);
951 if (SvRMAGICAL(hv)) {
954 hv_magic_check (hv, &needs_copy, &needs_store);
957 entry = hv_fetch_common(hv, keysv, key, klen,
958 k_flags & ~HVhek_FREEKEY, HV_FETCH_LVALUE,
960 sv = entry ? HeVAL(entry) : NULL;
966 if (mg_find(sv, PERL_MAGIC_tiedelem)) {
967 /* No longer an element */
968 sv_unmagic(sv, PERL_MAGIC_tiedelem);
971 return Nullsv; /* element cannot be deleted */
973 #ifdef ENV_IS_CASELESS
974 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
975 /* XXX This code isn't UTF8 clean. */
976 keysv = sv_2mortal(newSVpvn(key,klen));
977 if (k_flags & HVhek_FREEKEY) {
980 key = strupr(SvPVX(keysv));
989 xhv = (XPVHV*)SvANY(hv);
994 const char *keysave = key;
995 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
998 k_flags |= HVhek_UTF8;
1000 k_flags &= ~HVhek_UTF8;
1001 if (key != keysave) {
1002 if (k_flags & HVhek_FREEKEY) {
1003 /* This shouldn't happen if our caller does what we expect,
1004 but strictly the API allows it. */
1007 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
1009 HvHASKFLAGS_on((SV*)hv);
1013 PERL_HASH_INTERNAL(hash, key, klen);
1015 if (keysv && (SvIsCOW_shared_hash(keysv))) {
1016 hash = SvUVX(keysv);
1018 PERL_HASH(hash, key, klen);
1022 masked_flags = (k_flags & HVhek_MASK);
1024 first_entry = oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
1026 for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
1027 if (HeHASH(entry) != hash) /* strings can't be equal */
1029 if (HeKLEN(entry) != (I32)klen)
1031 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
1033 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
1036 /* if placeholder is here, it's already been deleted.... */
1037 if (HeVAL(entry) == &PL_sv_placeholder)
1039 if (k_flags & HVhek_FREEKEY)
1043 else if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1044 S_hv_notallowed(aTHX_ k_flags, key, klen,
1045 "Attempt to delete readonly key '%"SVf"' from"
1046 " a restricted hash");
1048 if (k_flags & HVhek_FREEKEY)
1051 if (d_flags & G_DISCARD)
1054 sv = sv_2mortal(HeVAL(entry));
1055 HeVAL(entry) = &PL_sv_placeholder;
1059 * If a restricted hash, rather than really deleting the entry, put
1060 * a placeholder there. This marks the key as being "approved", so
1061 * we can still access via not-really-existing key without raising
1064 if (SvREADONLY(hv)) {
1065 SvREFCNT_dec(HeVAL(entry));
1066 HeVAL(entry) = &PL_sv_placeholder;
1067 /* We'll be saving this slot, so the number of allocated keys
1068 * doesn't go down, but the number placeholders goes up */
1069 HvPLACEHOLDERS(hv)++;
1071 *oentry = HeNEXT(entry);
1073 xhv->xhv_fill--; /* HvFILL(hv)-- */
1075 if (SvOOK(hv) && entry == HvAUX(hv)->xhv_eiter /* HvEITER(hv) */)
1078 hv_free_ent(hv, entry);
1079 xhv->xhv_keys--; /* HvKEYS(hv)-- */
1080 if (xhv->xhv_keys == 0)
1081 HvHASKFLAGS_off(hv);
1085 if (SvREADONLY(hv)) {
1086 S_hv_notallowed(aTHX_ k_flags, key, klen,
1087 "Attempt to delete disallowed key '%"SVf"' from"
1088 " a restricted hash");
1091 if (k_flags & HVhek_FREEKEY)
1097 S_hsplit(pTHX_ HV *hv)
1099 register XPVHV* xhv = (XPVHV*)SvANY(hv);
1100 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1101 register I32 newsize = oldsize * 2;
1103 char *a = (char*) HvARRAY(hv);
1105 register HE **oentry;
1106 int longest_chain = 0;
1109 /*PerlIO_printf(PerlIO_stderr(), "hsplit called for %p which had %d\n",
1110 hv, (int) oldsize);*/
1112 if (HvPLACEHOLDERS_get(hv) && !SvREADONLY(hv)) {
1113 /* Can make this clear any placeholders first for non-restricted hashes,
1114 even though Storable rebuilds restricted hashes by putting in all the
1115 placeholders (first) before turning on the readonly flag, because
1116 Storable always pre-splits the hash. */
1117 hv_clear_placeholders(hv);
1121 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1122 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1123 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1129 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1132 New(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1133 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1138 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1140 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1142 if (oldsize >= 64) {
1143 offer_nice_chunk(HvARRAY(hv),
1144 PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
1145 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
1148 Safefree(HvARRAY(hv));
1152 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1153 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
1154 HvARRAY(hv) = (HE**) a;
1157 for (i=0; i<oldsize; i++,aep++) {
1158 int left_length = 0;
1159 int right_length = 0;
1163 if (!*aep) /* non-existent */
1166 for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1167 if ((HeHASH(entry) & newsize) != (U32)i) {
1168 *oentry = HeNEXT(entry);
1169 HeNEXT(entry) = *bep;
1171 xhv->xhv_fill++; /* HvFILL(hv)++ */
1177 oentry = &HeNEXT(entry);
1181 if (!*aep) /* everything moved */
1182 xhv->xhv_fill--; /* HvFILL(hv)-- */
1183 /* I think we don't actually need to keep track of the longest length,
1184 merely flag if anything is too long. But for the moment while
1185 developing this code I'll track it. */
1186 if (left_length > longest_chain)
1187 longest_chain = left_length;
1188 if (right_length > longest_chain)
1189 longest_chain = right_length;
1193 /* Pick your policy for "hashing isn't working" here: */
1194 if (longest_chain <= HV_MAX_LENGTH_BEFORE_SPLIT /* split worked? */
1199 if (hv == PL_strtab) {
1200 /* Urg. Someone is doing something nasty to the string table.
1205 /* Awooga. Awooga. Pathological data. */
1206 /*PerlIO_printf(PerlIO_stderr(), "%p %d of %d with %d/%d buckets\n", hv,
1207 longest_chain, HvTOTALKEYS(hv), HvFILL(hv), 1+HvMAX(hv));*/
1210 Newz(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1211 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1213 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1216 was_shared = HvSHAREKEYS(hv);
1219 HvSHAREKEYS_off(hv);
1224 for (i=0; i<newsize; i++,aep++) {
1225 register HE *entry = *aep;
1227 /* We're going to trash this HE's next pointer when we chain it
1228 into the new hash below, so store where we go next. */
1229 HE *next = HeNEXT(entry);
1234 PERL_HASH_INTERNAL(hash, HeKEY(entry), HeKLEN(entry));
1239 = save_hek_flags(HeKEY(entry), HeKLEN(entry),
1240 hash, HeKFLAGS(entry));
1241 unshare_hek (HeKEY_hek(entry));
1242 HeKEY_hek(entry) = new_hek;
1244 /* Not shared, so simply write the new hash in. */
1245 HeHASH(entry) = hash;
1247 /*PerlIO_printf(PerlIO_stderr(), "%d ", HeKFLAGS(entry));*/
1248 HEK_REHASH_on(HeKEY_hek(entry));
1249 /*PerlIO_printf(PerlIO_stderr(), "%d\n", HeKFLAGS(entry));*/
1251 /* Copy oentry to the correct new chain. */
1252 bep = ((HE**)a) + (hash & (I32) xhv->xhv_max);
1254 xhv->xhv_fill++; /* HvFILL(hv)++ */
1255 HeNEXT(entry) = *bep;
1261 Safefree (HvARRAY(hv));
1262 HvARRAY(hv) = (HE **)a;
1266 Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
1268 register XPVHV* xhv = (XPVHV*)SvANY(hv);
1269 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1270 register I32 newsize;
1275 register HE **oentry;
1277 newsize = (I32) newmax; /* possible truncation here */
1278 if (newsize != newmax || newmax <= oldsize)
1280 while ((newsize & (1 + ~newsize)) != newsize) {
1281 newsize &= ~(newsize & (1 + ~newsize)); /* get proper power of 2 */
1283 if (newsize < newmax)
1285 if (newsize < newmax)
1286 return; /* overflow detection */
1288 a = (char *) HvARRAY(hv);
1291 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1292 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1293 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1299 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1302 New(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1303 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1308 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1310 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1312 if (oldsize >= 64) {
1313 offer_nice_chunk(HvARRAY(hv),
1314 PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
1315 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
1318 Safefree(HvARRAY(hv));
1321 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1324 Newz(0, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1326 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
1327 HvARRAY(hv) = (HE **) a;
1328 if (!xhv->xhv_fill /* !HvFILL(hv) */) /* skip rest if no entries */
1332 for (i=0; i<oldsize; i++,aep++) {
1333 if (!*aep) /* non-existent */
1335 for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1337 if ((j = (HeHASH(entry) & newsize)) != i) {
1339 *oentry = HeNEXT(entry);
1340 if (!(HeNEXT(entry) = aep[j]))
1341 xhv->xhv_fill++; /* HvFILL(hv)++ */
1346 oentry = &HeNEXT(entry);
1348 if (!*aep) /* everything moved */
1349 xhv->xhv_fill--; /* HvFILL(hv)-- */
1356 Creates a new HV. The reference count is set to 1.
1365 register XPVHV* xhv;
1367 hv = (HV*)NEWSV(502,0);
1368 sv_upgrade((SV *)hv, SVt_PVHV);
1369 xhv = (XPVHV*)SvANY(hv);
1372 #ifndef NODEFAULT_SHAREKEYS
1373 HvSHAREKEYS_on(hv); /* key-sharing on by default */
1376 xhv->xhv_max = 7; /* HvMAX(hv) = 7 (start with 8 buckets) */
1377 xhv->xhv_fill = 0; /* HvFILL(hv) = 0 */
1382 Perl_newHVhv(pTHX_ HV *ohv)
1385 STRLEN hv_max, hv_fill;
1387 if (!ohv || (hv_fill = HvFILL(ohv)) == 0)
1389 hv_max = HvMAX(ohv);
1391 if (!SvMAGICAL((SV *)ohv)) {
1392 /* It's an ordinary hash, so copy it fast. AMS 20010804 */
1394 const bool shared = !!HvSHAREKEYS(ohv);
1395 HE **ents, **oents = (HE **)HvARRAY(ohv);
1397 New(0, a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
1400 /* In each bucket... */
1401 for (i = 0; i <= hv_max; i++) {
1402 HE *prev = NULL, *ent = NULL, *oent = oents[i];
1409 /* Copy the linked list of entries. */
1410 for (oent = oents[i]; oent; oent = HeNEXT(oent)) {
1411 const U32 hash = HeHASH(oent);
1412 const char * const key = HeKEY(oent);
1413 const STRLEN len = HeKLEN(oent);
1414 const int flags = HeKFLAGS(oent);
1417 HeVAL(ent) = newSVsv(HeVAL(oent));
1419 = shared ? HeKEY_hek(share_hek_flags(key, len, hash, flags))
1420 : save_hek_flags(key, len, hash, flags);
1431 HvFILL(hv) = hv_fill;
1432 HvTOTALKEYS(hv) = HvTOTALKEYS(ohv);
1436 /* Iterate over ohv, copying keys and values one at a time. */
1438 const I32 riter = HvRITER_get(ohv);
1439 HE * const eiter = HvEITER_get(ohv);
1441 /* Can we use fewer buckets? (hv_max is always 2^n-1) */
1442 while (hv_max && hv_max + 1 >= hv_fill * 2)
1443 hv_max = hv_max / 2;
1447 while ((entry = hv_iternext_flags(ohv, 0))) {
1448 hv_store_flags(hv, HeKEY(entry), HeKLEN(entry),
1449 newSVsv(HeVAL(entry)), HeHASH(entry),
1452 HvRITER_set(ohv, riter);
1453 HvEITER_set(ohv, eiter);
1460 Perl_hv_free_ent(pTHX_ HV *hv, register HE *entry)
1467 if (val && isGV(val) && GvCVu(val) && HvNAME_get(hv))
1468 PL_sub_generation++; /* may be deletion of method from stash */
1470 if (HeKLEN(entry) == HEf_SVKEY) {
1471 SvREFCNT_dec(HeKEY_sv(entry));
1472 Safefree(HeKEY_hek(entry));
1474 else if (HvSHAREKEYS(hv))
1475 unshare_hek(HeKEY_hek(entry));
1477 Safefree(HeKEY_hek(entry));
1482 Perl_hv_delayfree_ent(pTHX_ HV *hv, register HE *entry)
1486 if (isGV(HeVAL(entry)) && GvCVu(HeVAL(entry)) && HvNAME_get(hv))
1487 PL_sub_generation++; /* may be deletion of method from stash */
1488 sv_2mortal(HeVAL(entry)); /* free between statements */
1489 if (HeKLEN(entry) == HEf_SVKEY) {
1490 sv_2mortal(HeKEY_sv(entry));
1491 Safefree(HeKEY_hek(entry));
1493 else if (HvSHAREKEYS(hv))
1494 unshare_hek(HeKEY_hek(entry));
1496 Safefree(HeKEY_hek(entry));
1501 =for apidoc hv_clear
1503 Clears a hash, making it empty.
1509 Perl_hv_clear(pTHX_ HV *hv)
1512 register XPVHV* xhv;
1516 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1518 xhv = (XPVHV*)SvANY(hv);
1520 if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
1521 /* restricted hash: convert all keys to placeholders */
1523 for (i = 0; i <= (I32) xhv->xhv_max; i++) {
1524 HE *entry = (HvARRAY(hv))[i];
1525 for (; entry; entry = HeNEXT(entry)) {
1526 /* not already placeholder */
1527 if (HeVAL(entry) != &PL_sv_placeholder) {
1528 if (HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1529 SV* keysv = hv_iterkeysv(entry);
1531 "Attempt to delete readonly key '%"SVf"' from a restricted hash",
1534 SvREFCNT_dec(HeVAL(entry));
1535 HeVAL(entry) = &PL_sv_placeholder;
1536 HvPLACEHOLDERS(hv)++;
1544 HvPLACEHOLDERS_set(hv, 0);
1546 (void)memzero(HvARRAY(hv),
1547 (xhv->xhv_max+1 /* HvMAX(hv)+1 */) * sizeof(HE*));
1552 HvHASKFLAGS_off(hv);
1556 HvEITER_set(hv, NULL);
1561 =for apidoc hv_clear_placeholders
1563 Clears any placeholders from a hash. If a restricted hash has any of its keys
1564 marked as readonly and the key is subsequently deleted, the key is not actually
1565 deleted but is marked by assigning it a value of &PL_sv_placeholder. This tags
1566 it so it will be ignored by future operations such as iterating over the hash,
1567 but will still allow the hash to have a value reassigned to the key at some
1568 future point. This function clears any such placeholder keys from the hash.
1569 See Hash::Util::lock_keys() for an example of its use.
1575 Perl_hv_clear_placeholders(pTHX_ HV *hv)
1578 I32 items = (I32)HvPLACEHOLDERS_get(hv);
1585 /* Loop down the linked list heads */
1587 HE **oentry = &(HvARRAY(hv))[i];
1588 HE *entry = *oentry;
1593 for (; entry; entry = *oentry) {
1594 if (HeVAL(entry) == &PL_sv_placeholder) {
1595 *oentry = HeNEXT(entry);
1596 if (first && !*oentry)
1597 HvFILL(hv)--; /* This linked list is now empty. */
1598 if (HvEITER_get(hv))
1601 hv_free_ent(hv, entry);
1605 HvTOTALKEYS(hv) -= (IV)HvPLACEHOLDERS_get(hv);
1606 if (HvKEYS(hv) == 0)
1607 HvHASKFLAGS_off(hv);
1608 HvPLACEHOLDERS_set(hv, 0);
1612 oentry = &HeNEXT(entry);
1617 /* You can't get here, hence assertion should always fail. */
1618 assert (items == 0);
1623 S_hfreeentries(pTHX_ HV *hv)
1625 register HE **array;
1629 struct xpvhv_aux *iter;
1635 iter = SvOOK(hv) ? HvAUX(hv) : 0;
1639 array = HvARRAY(hv);
1640 /* make everyone else think the array is empty, so that the destructors
1641 * called for freed entries can't recusively mess with us */
1642 HvARRAY(hv) = Null(HE**);
1643 SvFLAGS(hv) &= ~SVf_OOK;
1646 ((XPVHV*) SvANY(hv))->xhv_keys = 0;
1651 register HE *oentry = entry;
1652 entry = HeNEXT(entry);
1653 hv_free_ent(hv, oentry);
1658 entry = array[riter];
1663 /* Someone attempted to iterate or set the hash name while we had
1664 the array set to 0. */
1665 assert(HvARRAY(hv));
1667 if (HvAUX(hv)->xhv_name)
1668 unshare_hek_or_pvn(HvAUX(hv)->xhv_name, 0, 0, 0);
1669 /* SvOOK_off calls sv_backoff, which isn't correct. */
1671 Safefree(HvARRAY(hv));
1673 SvFLAGS(hv) &= ~SVf_OOK;
1676 /* FIXME - things will still go horribly wrong (or at least leak) if
1677 people attempt to add elements to the hash while we're undef()ing it */
1679 entry = iter->xhv_eiter; /* HvEITER(hv) */
1680 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1682 hv_free_ent(hv, entry);
1684 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1685 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1686 SvFLAGS(hv) |= SVf_OOK;
1689 HvARRAY(hv) = array;
1693 =for apidoc hv_undef
1701 Perl_hv_undef(pTHX_ HV *hv)
1703 register XPVHV* xhv;
1707 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1708 xhv = (XPVHV*)SvANY(hv);
1710 if ((name = HvNAME_get(hv))) {
1712 hv_delete(PL_stashcache, name, HvNAMELEN_get(hv), G_DISCARD);
1713 Perl_hv_name_set(aTHX_ hv, 0, 0, 0);
1715 SvFLAGS(hv) &= ~SVf_OOK;
1716 Safefree(HvARRAY(hv));
1717 xhv->xhv_max = 7; /* HvMAX(hv) = 7 (it's a normal hash) */
1719 HvPLACEHOLDERS_set(hv, 0);
1726 S_hv_auxinit(pTHX_ HV *hv) {
1727 struct xpvhv_aux *iter;
1731 Newz(0, array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1732 + sizeof(struct xpvhv_aux), char);
1734 array = (char *) HvARRAY(hv);
1735 Renew(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1736 + sizeof(struct xpvhv_aux), char);
1738 HvARRAY(hv) = (HE**) array;
1739 /* SvOOK_on(hv) attacks the IV flags. */
1740 SvFLAGS(hv) |= SVf_OOK;
1743 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1744 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1751 =for apidoc hv_iterinit
1753 Prepares a starting point to traverse a hash table. Returns the number of
1754 keys in the hash (i.e. the same as C<HvKEYS(tb)>). The return value is
1755 currently only meaningful for hashes without tie magic.
1757 NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
1758 hash buckets that happen to be in use. If you still need that esoteric
1759 value, you can get it through the macro C<HvFILL(tb)>.
1766 Perl_hv_iterinit(pTHX_ HV *hv)
1768 register XPVHV* xhv;
1772 Perl_croak(aTHX_ "Bad hash");
1773 xhv = (XPVHV*)SvANY(hv);
1776 struct xpvhv_aux *iter = HvAUX(hv);
1777 entry = iter->xhv_eiter; /* HvEITER(hv) */
1778 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1780 hv_free_ent(hv, entry);
1782 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1783 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1785 S_hv_auxinit(aTHX_ hv);
1788 /* used to be xhv->xhv_fill before 5.004_65 */
1789 return HvTOTALKEYS(hv);
1793 Perl_hv_riter_p(pTHX_ HV *hv) {
1794 struct xpvhv_aux *iter;
1797 Perl_croak(aTHX_ "Bad hash");
1799 iter = SvOOK(hv) ? HvAUX(hv) : S_hv_auxinit(aTHX_ hv);
1800 return &(iter->xhv_riter);
1804 Perl_hv_eiter_p(pTHX_ HV *hv) {
1805 struct xpvhv_aux *iter;
1808 Perl_croak(aTHX_ "Bad hash");
1810 iter = SvOOK(hv) ? HvAUX(hv) : S_hv_auxinit(aTHX_ hv);
1811 return &(iter->xhv_eiter);
1815 Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
1816 struct xpvhv_aux *iter;
1819 Perl_croak(aTHX_ "Bad hash");
1827 iter = S_hv_auxinit(aTHX_ hv);
1829 iter->xhv_riter = riter;
1833 Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
1834 struct xpvhv_aux *iter;
1837 Perl_croak(aTHX_ "Bad hash");
1842 /* 0 is the default so don't go malloc()ing a new structure just to
1847 iter = S_hv_auxinit(aTHX_ hv);
1849 iter->xhv_eiter = eiter;
1853 Perl_hv_name_set(pTHX_ HV *hv, const char *name, I32 len, int flags)
1855 struct xpvhv_aux *iter;
1860 if (iter->xhv_name) {
1861 unshare_hek_or_pvn(iter->xhv_name, 0, 0, 0);
1867 iter = S_hv_auxinit(aTHX_ hv);
1869 PERL_HASH(hash, name, len);
1870 iter->xhv_name = name ? share_hek(name, len, hash) : 0;
1874 =for apidoc hv_iternext
1876 Returns entries from a hash iterator. See C<hv_iterinit>.
1878 You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
1879 iterator currently points to, without losing your place or invalidating your
1880 iterator. Note that in this case the current entry is deleted from the hash
1881 with your iterator holding the last reference to it. Your iterator is flagged
1882 to free the entry on the next call to C<hv_iternext>, so you must not discard
1883 your iterator immediately else the entry will leak - call C<hv_iternext> to
1884 trigger the resource deallocation.
1890 Perl_hv_iternext(pTHX_ HV *hv)
1892 return hv_iternext_flags(hv, 0);
1896 =for apidoc hv_iternext_flags
1898 Returns entries from a hash iterator. See C<hv_iterinit> and C<hv_iternext>.
1899 The C<flags> value will normally be zero; if HV_ITERNEXT_WANTPLACEHOLDERS is
1900 set the placeholders keys (for restricted hashes) will be returned in addition
1901 to normal keys. By default placeholders are automatically skipped over.
1902 Currently a placeholder is implemented with a value that is
1903 C<&Perl_sv_placeholder>. Note that the implementation of placeholders and
1904 restricted hashes may change, and the implementation currently is
1905 insufficiently abstracted for any change to be tidy.
1911 Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
1914 register XPVHV* xhv;
1918 struct xpvhv_aux *iter;
1921 Perl_croak(aTHX_ "Bad hash");
1922 xhv = (XPVHV*)SvANY(hv);
1925 /* Too many things (well, pp_each at least) merrily assume that you can
1926 call iv_iternext without calling hv_iterinit, so we'll have to deal
1932 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
1934 if ((mg = SvTIED_mg((SV*)hv, PERL_MAGIC_tied))) {
1935 SV *key = sv_newmortal();
1937 sv_setsv(key, HeSVKEY_force(entry));
1938 SvREFCNT_dec(HeSVKEY(entry)); /* get rid of previous key */
1944 /* one HE per MAGICAL hash */
1945 iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
1947 Newz(54, k, HEK_BASESIZE + sizeof(SV*), char);
1949 HeKEY_hek(entry) = hek;
1950 HeKLEN(entry) = HEf_SVKEY;
1952 magic_nextpack((SV*) hv,mg,key);
1954 /* force key to stay around until next time */
1955 HeSVKEY_set(entry, SvREFCNT_inc(key));
1956 return entry; /* beware, hent_val is not set */
1959 SvREFCNT_dec(HeVAL(entry));
1960 Safefree(HeKEY_hek(entry));
1962 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1965 #ifdef DYNAMIC_ENV_FETCH /* set up %ENV for iteration */
1966 if (!entry && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
1970 /* hv_iterint now ensures this. */
1971 assert (HvARRAY(hv));
1973 /* At start of hash, entry is NULL. */
1976 entry = HeNEXT(entry);
1977 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
1979 * Skip past any placeholders -- don't want to include them in
1982 while (entry && HeVAL(entry) == &PL_sv_placeholder) {
1983 entry = HeNEXT(entry);
1988 /* OK. Come to the end of the current list. Grab the next one. */
1990 iter->xhv_riter++; /* HvRITER(hv)++ */
1991 if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
1992 /* There is no next one. End of the hash. */
1993 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1996 entry = (HvARRAY(hv))[iter->xhv_riter];
1998 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
1999 /* If we have an entry, but it's a placeholder, don't count it.
2001 while (entry && HeVAL(entry) == &PL_sv_placeholder)
2002 entry = HeNEXT(entry);
2004 /* Will loop again if this linked list starts NULL
2005 (for HV_ITERNEXT_WANTPLACEHOLDERS)
2006 or if we run through it and find only placeholders. */
2009 if (oldentry && HvLAZYDEL(hv)) { /* was deleted earlier? */
2011 hv_free_ent(hv, oldentry);
2014 /*if (HvREHASH(hv) && entry && !HeKREHASH(entry))
2015 PerlIO_printf(PerlIO_stderr(), "Awooga %p %p\n", hv, entry);*/
2017 iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
2022 =for apidoc hv_iterkey
2024 Returns the key from the current position of the hash iterator. See
2031 Perl_hv_iterkey(pTHX_ register HE *entry, I32 *retlen)
2033 if (HeKLEN(entry) == HEf_SVKEY) {
2035 char *p = SvPV(HeKEY_sv(entry), len);
2040 *retlen = HeKLEN(entry);
2041 return HeKEY(entry);
2045 /* unlike hv_iterval(), this always returns a mortal copy of the key */
2047 =for apidoc hv_iterkeysv
2049 Returns the key as an C<SV*> from the current position of the hash
2050 iterator. The return value will always be a mortal copy of the key. Also
2057 Perl_hv_iterkeysv(pTHX_ register HE *entry)
2059 if (HeKLEN(entry) != HEf_SVKEY) {
2060 HEK *hek = HeKEY_hek(entry);
2061 const int flags = HEK_FLAGS(hek);
2064 if (flags & HVhek_WASUTF8) {
2066 Andreas would like keys he put in as utf8 to come back as utf8
2068 STRLEN utf8_len = HEK_LEN(hek);
2069 U8 *as_utf8 = bytes_to_utf8 ((U8*)HEK_KEY(hek), &utf8_len);
2071 sv = newSVpvn ((char*)as_utf8, utf8_len);
2073 Safefree (as_utf8); /* bytes_to_utf8() allocates a new string */
2074 } else if (flags & HVhek_REHASH) {
2075 /* We don't have a pointer to the hv, so we have to replicate the
2076 flag into every HEK. This hv is using custom a hasing
2077 algorithm. Hence we can't return a shared string scalar, as
2078 that would contain the (wrong) hash value, and might get passed
2079 into an hv routine with a regular hash */
2081 sv = newSVpvn (HEK_KEY(hek), HEK_LEN(hek));
2085 sv = newSVpvn_share(HEK_KEY(hek),
2086 (HEK_UTF8(hek) ? -HEK_LEN(hek) : HEK_LEN(hek)),
2089 return sv_2mortal(sv);
2091 return sv_mortalcopy(HeKEY_sv(entry));
2095 =for apidoc hv_iterval
2097 Returns the value from the current position of the hash iterator. See
2104 Perl_hv_iterval(pTHX_ HV *hv, register HE *entry)
2106 if (SvRMAGICAL(hv)) {
2107 if (mg_find((SV*)hv, PERL_MAGIC_tied)) {
2108 SV* sv = sv_newmortal();
2109 if (HeKLEN(entry) == HEf_SVKEY)
2110 mg_copy((SV*)hv, sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
2112 mg_copy((SV*)hv, sv, HeKEY(entry), HeKLEN(entry));
2116 return HeVAL(entry);
2120 =for apidoc hv_iternextsv
2122 Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2129 Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
2132 if ( (he = hv_iternext_flags(hv, 0)) == NULL)
2134 *key = hv_iterkey(he, retlen);
2135 return hv_iterval(hv, he);
2139 =for apidoc hv_magic
2141 Adds magic to a hash. See C<sv_magic>.
2147 Perl_hv_magic(pTHX_ HV *hv, GV *gv, int how)
2149 sv_magic((SV*)hv, (SV*)gv, how, Nullch, 0);
2152 #if 0 /* use the macro from hv.h instead */
2155 Perl_sharepvn(pTHX_ const char *sv, I32 len, U32 hash)
2157 return HEK_KEY(share_hek(sv, len, hash));
2162 /* possibly free a shared string if no one has access to it
2163 * len and hash must both be valid for str.
2166 Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
2168 unshare_hek_or_pvn (NULL, str, len, hash);
2173 Perl_unshare_hek(pTHX_ HEK *hek)
2175 unshare_hek_or_pvn(hek, NULL, 0, 0);
2178 /* possibly free a shared string if no one has access to it
2179 hek if non-NULL takes priority over the other 3, else str, len and hash
2180 are used. If so, len and hash must both be valid for str.
2183 S_unshare_hek_or_pvn(pTHX_ HEK *hek, const char *str, I32 len, U32 hash)
2185 register XPVHV* xhv;
2187 register HE **oentry;
2190 bool is_utf8 = FALSE;
2192 const char *save = str;
2195 hash = HEK_HASH(hek);
2196 } else if (len < 0) {
2197 STRLEN tmplen = -len;
2199 /* See the note in hv_fetch(). --jhi */
2200 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2203 k_flags = HVhek_UTF8;
2205 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2208 /* what follows is the moral equivalent of:
2209 if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
2210 if (--*Svp == Nullsv)
2211 hv_delete(PL_strtab, str, len, G_DISCARD, hash);
2213 xhv = (XPVHV*)SvANY(PL_strtab);
2214 /* assert(xhv_array != 0) */
2216 first = oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2218 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2219 if (HeKEY_hek(entry) != hek)
2225 const int flags_masked = k_flags & HVhek_MASK;
2226 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2227 if (HeHASH(entry) != hash) /* strings can't be equal */
2229 if (HeKLEN(entry) != len)
2231 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2233 if (HeKFLAGS(entry) != flags_masked)
2241 if (--HeVAL(entry) == Nullsv) {
2242 *oentry = HeNEXT(entry);
2244 /* There are now no entries in our slot. */
2245 xhv->xhv_fill--; /* HvFILL(hv)-- */
2247 Safefree(HeKEY_hek(entry));
2249 xhv->xhv_keys--; /* HvKEYS(hv)-- */
2253 UNLOCK_STRTAB_MUTEX;
2254 if (!found && ckWARN_d(WARN_INTERNAL))
2255 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
2256 "Attempt to free non-existent shared string '%s'%s"
2258 hek ? HEK_KEY(hek) : str,
2259 ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
2260 if (k_flags & HVhek_FREEKEY)
2264 /* get a (constant) string ptr from the global string table
2265 * string will get added if it is not already there.
2266 * len and hash must both be valid for str.
2269 Perl_share_hek(pTHX_ const char *str, I32 len, register U32 hash)
2271 bool is_utf8 = FALSE;
2273 const char *save = str;
2276 STRLEN tmplen = -len;
2278 /* See the note in hv_fetch(). --jhi */
2279 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2281 /* If we were able to downgrade here, then than means that we were passed
2282 in a key which only had chars 0-255, but was utf8 encoded. */
2285 /* If we found we were able to downgrade the string to bytes, then
2286 we should flag that it needs upgrading on keys or each. Also flag
2287 that we need share_hek_flags to free the string. */
2289 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2292 return HeKEY_hek(share_hek_flags (str, len, hash, flags));
2296 S_share_hek_flags(pTHX_ const char *str, I32 len, register U32 hash, int flags)
2298 register XPVHV* xhv;
2300 register HE **oentry;
2302 const int flags_masked = flags & HVhek_MASK;
2304 /* what follows is the moral equivalent of:
2306 if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
2307 hv_store(PL_strtab, str, len, Nullsv, hash);
2309 Can't rehash the shared string table, so not sure if it's worth
2310 counting the number of entries in the linked list
2312 xhv = (XPVHV*)SvANY(PL_strtab);
2313 /* assert(xhv_array != 0) */
2315 oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2316 for (entry = *oentry; entry; entry = HeNEXT(entry)) {
2317 if (HeHASH(entry) != hash) /* strings can't be equal */
2319 if (HeKLEN(entry) != len)
2321 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2323 if (HeKFLAGS(entry) != flags_masked)
2329 /* What used to be head of the list.
2330 If this is NULL, then we're the first entry for this slot, which
2331 means we need to increate fill. */
2332 const HE *old_first = *oentry;
2334 HeKEY_hek(entry) = save_hek_flags(str, len, hash, flags_masked);
2335 HeVAL(entry) = Nullsv;
2336 HeNEXT(entry) = *oentry;
2338 xhv->xhv_keys++; /* HvKEYS(hv)++ */
2339 if (!old_first) { /* initial entry? */
2340 xhv->xhv_fill++; /* HvFILL(hv)++ */
2341 } else if (xhv->xhv_keys > (IV)xhv->xhv_max /* HvKEYS(hv) > HvMAX(hv) */) {
2346 ++HeVAL(entry); /* use value slot as REFCNT */
2347 UNLOCK_STRTAB_MUTEX;
2349 if (flags & HVhek_FREEKEY)
2356 Perl_hv_placeholders_p(pTHX_ HV *hv)
2359 MAGIC *mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2362 mg = sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, 0);
2365 Perl_die(aTHX_ "panic: hv_placeholders_p");
2368 return &(mg->mg_len);
2373 Perl_hv_placeholders_get(pTHX_ HV *hv)
2376 MAGIC *mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2378 return mg ? mg->mg_len : 0;
2382 Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
2385 MAGIC *mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2390 if (!sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, ph))
2391 Perl_die(aTHX_ "panic: hv_placeholders_set");
2393 /* else we don't need to add magic to record 0 placeholders. */
2397 =for apidoc hv_assert
2399 Check that a hash is in an internally consistent state.
2405 Perl_hv_assert(pTHX_ HV *hv)
2410 int placeholders = 0;
2413 const I32 riter = HvRITER_get(hv);
2414 HE *eiter = HvEITER_get(hv);
2416 (void)hv_iterinit(hv);
2418 while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
2419 /* sanity check the values */
2420 if (HeVAL(entry) == &PL_sv_placeholder) {
2425 /* sanity check the keys */
2426 if (HeSVKEY(entry)) {
2427 /* Don't know what to check on SV keys. */
2428 } else if (HeKUTF8(entry)) {
2430 if (HeKWASUTF8(entry)) {
2431 PerlIO_printf(Perl_debug_log,
2432 "hash key has both WASUFT8 and UTF8: '%.*s'\n",
2433 (int) HeKLEN(entry), HeKEY(entry));
2436 } else if (HeKWASUTF8(entry)) {
2440 if (!SvTIED_mg((SV*)hv, PERL_MAGIC_tied)) {
2441 if (HvUSEDKEYS(hv) != real) {
2442 PerlIO_printf(Perl_debug_log, "Count %d key(s), but hash reports %d\n",
2443 (int) real, (int) HvUSEDKEYS(hv));
2446 if (HvPLACEHOLDERS_get(hv) != placeholders) {
2447 PerlIO_printf(Perl_debug_log,
2448 "Count %d placeholder(s), but hash reports %d\n",
2449 (int) placeholders, (int) HvPLACEHOLDERS_get(hv));
2453 if (withflags && ! HvHASKFLAGS(hv)) {
2454 PerlIO_printf(Perl_debug_log,
2455 "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
2462 HvRITER_set(hv, riter); /* Restore hash iterator state */
2463 HvEITER_set(hv, eiter);
2468 * c-indentation-style: bsd
2470 * indent-tabs-mode: t
2473 * ex: set ts=8 sts=4 sw=4 noet: