3 * Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 * 2000, 2001, 2002, 2003, 2004, 2005, by Larry Wall and others
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
12 * "I sit beside the fire and think of all that I have seen." --Bilbo
16 =head1 Hash Manipulation Functions
18 A HV structure represents a Perl hash. It consists mainly of an array
19 of pointers, each of which points to a linked list of HE structures. The
20 array is indexed by the hash function of the key, so each linked list
21 represents all the hash entries with the same hash value. Each HE contains
22 a pointer to the actual value, plus a pointer to a HEK structure which
23 holds the key and hash value.
31 #define PERL_HASH_INTERNAL_ACCESS
34 #define HV_MAX_LENGTH_BEFORE_SPLIT 14
36 static const char *const S_strtab_error
37 = "Cannot modify shared string table in hv_%s";
44 New(54, he, PERL_ARENA_SIZE/sizeof(HE), HE);
45 HeNEXT(he) = PL_he_arenaroot;
48 heend = &he[PERL_ARENA_SIZE / sizeof(HE) - 1];
51 HeNEXT(he) = (HE*)(he + 1);
65 PL_he_root = HeNEXT(he);
74 HeNEXT(p) = (HE*)PL_he_root;
81 #define new_HE() (HE*)safemalloc(sizeof(HE))
82 #define del_HE(p) safefree((char*)p)
86 #define new_HE() new_he()
87 #define del_HE(p) del_he(p)
92 S_save_hek_flags(pTHX_ const char *str, I32 len, U32 hash, int flags)
94 const int flags_masked = flags & HVhek_MASK;
98 New(54, k, HEK_BASESIZE + len + 2, char);
100 Copy(str, HEK_KEY(hek), len, char);
101 HEK_KEY(hek)[len] = 0;
103 HEK_HASH(hek) = hash;
104 HEK_FLAGS(hek) = (unsigned char)flags_masked;
106 if (flags & HVhek_FREEKEY)
111 /* free the pool of temporary HE/HEK pairs retunrned by hv_fetch_ent
115 Perl_free_tied_hv_pool(pTHX)
117 HE *he = PL_hv_fetch_ent_mh;
120 Safefree(HeKEY_hek(he));
124 PL_hv_fetch_ent_mh = Nullhe;
127 #if defined(USE_ITHREADS)
129 Perl_hek_dup(pTHX_ HEK *source, CLONE_PARAMS* param)
131 HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
133 PERL_UNUSED_ARG(param);
136 /* We already shared this hash key. */
137 (void)share_hek_hek(shared);
141 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
142 HEK_HASH(source), HEK_FLAGS(source));
143 ptr_table_store(PL_ptr_table, source, shared);
149 Perl_he_dup(pTHX_ HE *e, bool shared, CLONE_PARAMS* param)
155 /* look for it in the table first */
156 ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
160 /* create anew and remember what it is */
162 ptr_table_store(PL_ptr_table, e, ret);
164 HeNEXT(ret) = he_dup(HeNEXT(e),shared, param);
165 if (HeKLEN(e) == HEf_SVKEY) {
167 New(54, k, HEK_BASESIZE + sizeof(SV*), char);
168 HeKEY_hek(ret) = (HEK*)k;
169 HeKEY_sv(ret) = SvREFCNT_inc(sv_dup(HeKEY_sv(e), param));
172 /* This is hek_dup inlined, which seems to be important for speed
174 HEK * const source = HeKEY_hek(e);
175 HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
178 /* We already shared this hash key. */
179 (void)share_hek_hek(shared);
183 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
184 HEK_HASH(source), HEK_FLAGS(source));
185 ptr_table_store(PL_ptr_table, source, shared);
187 HeKEY_hek(ret) = shared;
190 HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
192 HeVAL(ret) = SvREFCNT_inc(sv_dup(HeVAL(e), param));
195 #endif /* USE_ITHREADS */
198 S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
201 SV * const sv = sv_newmortal();
202 if (!(flags & HVhek_FREEKEY)) {
203 sv_setpvn(sv, key, klen);
206 /* Need to free saved eventually assign to mortal SV */
207 /* XXX is this line an error ???: SV *sv = sv_newmortal(); */
208 sv_usepvn(sv, (char *) key, klen);
210 if (flags & HVhek_UTF8) {
213 Perl_croak(aTHX_ msg, sv);
216 /* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
219 #define HV_FETCH_ISSTORE 0x01
220 #define HV_FETCH_ISEXISTS 0x02
221 #define HV_FETCH_LVALUE 0x04
222 #define HV_FETCH_JUST_SV 0x08
227 Stores an SV in a hash. The hash key is specified as C<key> and C<klen> is
228 the length of the key. The C<hash> parameter is the precomputed hash
229 value; if it is zero then Perl will compute it. The return value will be
230 NULL if the operation failed or if the value did not need to be actually
231 stored within the hash (as in the case of tied hashes). Otherwise it can
232 be dereferenced to get the original C<SV*>. Note that the caller is
233 responsible for suitably incrementing the reference count of C<val> before
234 the call, and decrementing it if the function returned NULL. Effectively
235 a successful hv_store takes ownership of one reference to C<val>. This is
236 usually what you want; a newly created SV has a reference count of one, so
237 if all your code does is create SVs then store them in a hash, hv_store
238 will own the only reference to the new SV, and your code doesn't need to do
239 anything further to tidy up. hv_store is not implemented as a call to
240 hv_store_ent, and does not create a temporary SV for the key, so if your
241 key data is not already in SV form then use hv_store in preference to
244 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
245 information on how to use this function on tied hashes.
251 Perl_hv_store(pTHX_ HV *hv, const char *key, I32 klen_i32, SV *val, U32 hash)
264 hek = hv_fetch_common (hv, NULL, key, klen, flags,
265 (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
266 return hek ? &HeVAL(hek) : NULL;
270 Perl_hv_store_flags(pTHX_ HV *hv, const char *key, I32 klen, SV *val,
271 register U32 hash, int flags)
273 HE * const hek = hv_fetch_common (hv, NULL, key, klen, flags,
274 (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
275 return hek ? &HeVAL(hek) : NULL;
279 =for apidoc hv_store_ent
281 Stores C<val> in a hash. The hash key is specified as C<key>. The C<hash>
282 parameter is the precomputed hash value; if it is zero then Perl will
283 compute it. The return value is the new hash entry so created. It will be
284 NULL if the operation failed or if the value did not need to be actually
285 stored within the hash (as in the case of tied hashes). Otherwise the
286 contents of the return value can be accessed using the C<He?> macros
287 described here. Note that the caller is responsible for suitably
288 incrementing the reference count of C<val> before the call, and
289 decrementing it if the function returned NULL. Effectively a successful
290 hv_store_ent takes ownership of one reference to C<val>. This is
291 usually what you want; a newly created SV has a reference count of one, so
292 if all your code does is create SVs then store them in a hash, hv_store
293 will own the only reference to the new SV, and your code doesn't need to do
294 anything further to tidy up. Note that hv_store_ent only reads the C<key>;
295 unlike C<val> it does not take ownership of it, so maintaining the correct
296 reference count on C<key> is entirely the caller's responsibility. hv_store
297 is not implemented as a call to hv_store_ent, and does not create a temporary
298 SV for the key, so if your key data is not already in SV form then use
299 hv_store in preference to hv_store_ent.
301 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
302 information on how to use this function on tied hashes.
308 Perl_hv_store_ent(pTHX_ HV *hv, SV *keysv, SV *val, U32 hash)
310 return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISSTORE, val, hash);
314 =for apidoc hv_exists
316 Returns a boolean indicating whether the specified hash key exists. The
317 C<klen> is the length of the key.
323 Perl_hv_exists(pTHX_ HV *hv, const char *key, I32 klen_i32)
335 return hv_fetch_common(hv, NULL, key, klen, flags, HV_FETCH_ISEXISTS, 0, 0)
342 Returns the SV which corresponds to the specified key in the hash. The
343 C<klen> is the length of the key. If C<lval> is set then the fetch will be
344 part of a store. Check that the return value is non-null before
345 dereferencing it to an C<SV*>.
347 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
348 information on how to use this function on tied hashes.
354 Perl_hv_fetch(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 lval)
367 hek = hv_fetch_common (hv, NULL, key, klen, flags,
368 HV_FETCH_JUST_SV | (lval ? HV_FETCH_LVALUE : 0),
370 return hek ? &HeVAL(hek) : NULL;
374 =for apidoc hv_exists_ent
376 Returns a boolean indicating whether the specified hash key exists. C<hash>
377 can be a valid precomputed hash value, or 0 to ask for it to be
384 Perl_hv_exists_ent(pTHX_ HV *hv, SV *keysv, U32 hash)
386 return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISEXISTS, 0, hash)
390 /* returns an HE * structure with the all fields set */
391 /* note that hent_val will be a mortal sv for MAGICAL hashes */
393 =for apidoc hv_fetch_ent
395 Returns the hash entry which corresponds to the specified key in the hash.
396 C<hash> must be a valid precomputed hash number for the given C<key>, or 0
397 if you want the function to compute it. IF C<lval> is set then the fetch
398 will be part of a store. Make sure the return value is non-null before
399 accessing it. The return value when C<tb> is a tied hash is a pointer to a
400 static location, so be sure to make a copy of the structure if you need to
403 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
404 information on how to use this function on tied hashes.
410 Perl_hv_fetch_ent(pTHX_ HV *hv, SV *keysv, I32 lval, register U32 hash)
412 return hv_fetch_common(hv, keysv, NULL, 0, 0,
413 (lval ? HV_FETCH_LVALUE : 0), Nullsv, hash);
417 S_hv_fetch_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
418 int flags, int action, SV *val, register U32 hash)
432 if (flags & HVhek_FREEKEY)
434 key = SvPV_const(keysv, klen);
436 is_utf8 = (SvUTF8(keysv) != 0);
438 is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
441 xhv = (XPVHV*)SvANY(hv);
443 if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS)))
445 if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
448 /* XXX should be able to skimp on the HE/HEK here when
449 HV_FETCH_JUST_SV is true. */
452 keysv = newSVpvn(key, klen);
457 keysv = newSVsv(keysv);
459 mg_copy((SV*)hv, sv, (char *)keysv, HEf_SVKEY);
461 /* grab a fake HE/HEK pair from the pool or make a new one */
462 entry = PL_hv_fetch_ent_mh;
464 PL_hv_fetch_ent_mh = HeNEXT(entry);
468 New(54, k, HEK_BASESIZE + sizeof(SV*), char);
469 HeKEY_hek(entry) = (HEK*)k;
471 HeNEXT(entry) = Nullhe;
472 HeSVKEY_set(entry, keysv);
474 sv_upgrade(sv, SVt_PVLV);
476 /* so we can free entry when freeing sv */
477 LvTARG(sv) = (SV*)entry;
479 /* XXX remove at some point? */
480 if (flags & HVhek_FREEKEY)
485 #ifdef ENV_IS_CASELESS
486 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
488 for (i = 0; i < klen; ++i)
489 if (isLOWER(key[i])) {
490 /* Would be nice if we had a routine to do the
491 copy and upercase in a single pass through. */
492 const char *nkey = strupr(savepvn(key,klen));
493 /* Note that this fetch is for nkey (the uppercased
494 key) whereas the store is for key (the original) */
495 entry = hv_fetch_common(hv, Nullsv, nkey, klen,
496 HVhek_FREEKEY, /* free nkey */
497 0 /* non-LVAL fetch */,
498 Nullsv /* no value */,
499 0 /* compute hash */);
500 if (!entry && (action & HV_FETCH_LVALUE)) {
501 /* This call will free key if necessary.
502 Do it this way to encourage compiler to tail
504 entry = hv_fetch_common(hv, keysv, key, klen,
505 flags, HV_FETCH_ISSTORE,
508 if (flags & HVhek_FREEKEY)
516 else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
517 if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
518 /* I don't understand why hv_exists_ent has svret and sv,
519 whereas hv_exists only had one. */
520 SV * const svret = sv_newmortal();
523 if (keysv || is_utf8) {
525 keysv = newSVpvn(key, klen);
528 keysv = newSVsv(keysv);
530 mg_copy((SV*)hv, sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
532 mg_copy((SV*)hv, sv, key, klen);
534 if (flags & HVhek_FREEKEY)
536 magic_existspack(svret, mg_find(sv, PERL_MAGIC_tiedelem));
537 /* This cast somewhat evil, but I'm merely using NULL/
538 not NULL to return the boolean exists.
539 And I know hv is not NULL. */
540 return SvTRUE(svret) ? (HE *)hv : NULL;
542 #ifdef ENV_IS_CASELESS
543 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
544 /* XXX This code isn't UTF8 clean. */
545 char * const keysave = (char * const)key;
546 /* Will need to free this, so set FREEKEY flag. */
547 key = savepvn(key,klen);
548 key = (const char*)strupr((char*)key);
553 if (flags & HVhek_FREEKEY) {
556 flags |= HVhek_FREEKEY;
560 else if (action & HV_FETCH_ISSTORE) {
563 hv_magic_check (hv, &needs_copy, &needs_store);
565 const bool save_taint = PL_tainted;
566 if (keysv || is_utf8) {
568 keysv = newSVpvn(key, klen);
572 PL_tainted = SvTAINTED(keysv);
573 keysv = sv_2mortal(newSVsv(keysv));
574 mg_copy((SV*)hv, val, (char*)keysv, HEf_SVKEY);
576 mg_copy((SV*)hv, val, key, klen);
579 TAINT_IF(save_taint);
580 if (!HvARRAY(hv) && !needs_store) {
581 if (flags & HVhek_FREEKEY)
585 #ifdef ENV_IS_CASELESS
586 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
587 /* XXX This code isn't UTF8 clean. */
588 const char *keysave = key;
589 /* Will need to free this, so set FREEKEY flag. */
590 key = savepvn(key,klen);
591 key = (const char*)strupr((char*)key);
596 if (flags & HVhek_FREEKEY) {
599 flags |= HVhek_FREEKEY;
607 if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
608 #ifdef DYNAMIC_ENV_FETCH /* if it's an %ENV lookup, we may get it on the fly */
609 || (SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
614 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
616 HvARRAY(hv) = (HE**)array;
618 #ifdef DYNAMIC_ENV_FETCH
619 else if (action & HV_FETCH_ISEXISTS) {
620 /* for an %ENV exists, if we do an insert it's by a recursive
621 store call, so avoid creating HvARRAY(hv) right now. */
625 /* XXX remove at some point? */
626 if (flags & HVhek_FREEKEY)
634 char * const keysave = (char * const)key;
635 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
639 flags &= ~HVhek_UTF8;
640 if (key != keysave) {
641 if (flags & HVhek_FREEKEY)
643 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
648 PERL_HASH_INTERNAL(hash, key, klen);
649 /* We don't have a pointer to the hv, so we have to replicate the
650 flag into every HEK, so that hv_iterkeysv can see it. */
651 /* And yes, you do need this even though you are not "storing" because
652 you can flip the flags below if doing an lval lookup. (And that
653 was put in to give the semantics Andreas was expecting.) */
654 flags |= HVhek_REHASH;
656 if (keysv && (SvIsCOW_shared_hash(keysv))) {
657 hash = SvSHARED_HASH(keysv);
659 PERL_HASH(hash, key, klen);
663 masked_flags = (flags & HVhek_MASK);
665 #ifdef DYNAMIC_ENV_FETCH
666 if (!HvARRAY(hv)) entry = Null(HE*);
670 entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
672 for (; entry; entry = HeNEXT(entry)) {
673 if (HeHASH(entry) != hash) /* strings can't be equal */
675 if (HeKLEN(entry) != (I32)klen)
677 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
679 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
682 if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
683 if (HeKFLAGS(entry) != masked_flags) {
684 /* We match if HVhek_UTF8 bit in our flags and hash key's
685 match. But if entry was set previously with HVhek_WASUTF8
686 and key now doesn't (or vice versa) then we should change
687 the key's flag, as this is assignment. */
688 if (HvSHAREKEYS(hv)) {
689 /* Need to swap the key we have for a key with the flags we
690 need. As keys are shared we can't just write to the
691 flag, so we share the new one, unshare the old one. */
692 HEK *new_hek = share_hek_flags(key, klen, hash,
694 unshare_hek (HeKEY_hek(entry));
695 HeKEY_hek(entry) = new_hek;
697 else if (hv == PL_strtab) {
698 /* PL_strtab is usually the only hash without HvSHAREKEYS,
699 so putting this test here is cheap */
700 if (flags & HVhek_FREEKEY)
702 Perl_croak(aTHX_ S_strtab_error,
703 action & HV_FETCH_LVALUE ? "fetch" : "store");
706 HeKFLAGS(entry) = masked_flags;
707 if (masked_flags & HVhek_ENABLEHVKFLAGS)
710 if (HeVAL(entry) == &PL_sv_placeholder) {
711 /* yes, can store into placeholder slot */
712 if (action & HV_FETCH_LVALUE) {
714 /* This preserves behaviour with the old hv_fetch
715 implementation which at this point would bail out
716 with a break; (at "if we find a placeholder, we
717 pretend we haven't found anything")
719 That break mean that if a placeholder were found, it
720 caused a call into hv_store, which in turn would
721 check magic, and if there is no magic end up pretty
722 much back at this point (in hv_store's code). */
725 /* LVAL fetch which actaully needs a store. */
727 HvPLACEHOLDERS(hv)--;
730 if (val != &PL_sv_placeholder)
731 HvPLACEHOLDERS(hv)--;
734 } else if (action & HV_FETCH_ISSTORE) {
735 SvREFCNT_dec(HeVAL(entry));
738 } else if (HeVAL(entry) == &PL_sv_placeholder) {
739 /* if we find a placeholder, we pretend we haven't found
743 if (flags & HVhek_FREEKEY)
747 #ifdef DYNAMIC_ENV_FETCH /* %ENV lookup? If so, try to fetch the value now */
748 if (!(action & HV_FETCH_ISSTORE)
749 && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
751 const char * const env = PerlEnv_ENVgetenv_len(key,&len);
753 sv = newSVpvn(env,len);
755 return hv_fetch_common(hv,keysv,key,klen,flags,HV_FETCH_ISSTORE,sv,
761 if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
762 S_hv_notallowed(aTHX_ flags, key, klen,
763 "Attempt to access disallowed key '%"SVf"' in"
764 " a restricted hash");
766 if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
767 /* Not doing some form of store, so return failure. */
768 if (flags & HVhek_FREEKEY)
772 if (action & HV_FETCH_LVALUE) {
775 /* At this point the old hv_fetch code would call to hv_store,
776 which in turn might do some tied magic. So we need to make that
777 magic check happen. */
778 /* gonna assign to this, so it better be there */
779 return hv_fetch_common(hv, keysv, key, klen, flags,
780 HV_FETCH_ISSTORE, val, hash);
781 /* XXX Surely that could leak if the fetch-was-store fails?
782 Just like the hv_fetch. */
786 /* Welcome to hv_store... */
789 /* Not sure if we can get here. I think the only case of oentry being
790 NULL is for %ENV with dynamic env fetch. But that should disappear
791 with magic in the previous code. */
794 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
796 HvARRAY(hv) = (HE**)array;
799 oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
802 /* share_hek_flags will do the free for us. This might be considered
805 HeKEY_hek(entry) = share_hek_flags(key, klen, hash, flags);
806 else if (hv == PL_strtab) {
807 /* PL_strtab is usually the only hash without HvSHAREKEYS, so putting
808 this test here is cheap */
809 if (flags & HVhek_FREEKEY)
811 Perl_croak(aTHX_ S_strtab_error,
812 action & HV_FETCH_LVALUE ? "fetch" : "store");
814 else /* gotta do the real thing */
815 HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
817 HeNEXT(entry) = *oentry;
820 if (val == &PL_sv_placeholder)
821 HvPLACEHOLDERS(hv)++;
822 if (masked_flags & HVhek_ENABLEHVKFLAGS)
826 const HE *counter = HeNEXT(entry);
828 xhv->xhv_keys++; /* HvKEYS(hv)++ */
829 if (!counter) { /* initial entry? */
830 xhv->xhv_fill++; /* HvFILL(hv)++ */
831 } else if (xhv->xhv_keys > (IV)xhv->xhv_max) {
833 } else if(!HvREHASH(hv)) {
836 while ((counter = HeNEXT(counter)))
839 if (n_links > HV_MAX_LENGTH_BEFORE_SPLIT) {
840 /* Use only the old HvKEYS(hv) > HvMAX(hv) condition to limit
841 bucket splits on a rehashed hash, as we're not going to
842 split it again, and if someone is lucky (evil) enough to
843 get all the keys in one list they could exhaust our memory
844 as we repeatedly double the number of buckets on every
845 entry. Linear search feels a less worse thing to do. */
855 S_hv_magic_check(pTHX_ HV *hv, bool *needs_copy, bool *needs_store)
857 const MAGIC *mg = SvMAGIC(hv);
861 if (isUPPER(mg->mg_type)) {
863 switch (mg->mg_type) {
864 case PERL_MAGIC_tied:
866 *needs_store = FALSE;
867 return; /* We've set all there is to set. */
870 mg = mg->mg_moremagic;
875 =for apidoc hv_scalar
877 Evaluates the hash in scalar context and returns the result. Handles magic when the hash is tied.
883 Perl_hv_scalar(pTHX_ HV *hv)
888 if ((SvRMAGICAL(hv) && (mg = mg_find((SV*)hv, PERL_MAGIC_tied)))) {
889 sv = magic_scalarpack(hv, mg);
895 Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
896 (long)HvFILL(hv), (long)HvMAX(hv) + 1);
904 =for apidoc hv_delete
906 Deletes a key/value pair in the hash. The value SV is removed from the
907 hash and returned to the caller. The C<klen> is the length of the key.
908 The C<flags> value will normally be zero; if set to G_DISCARD then NULL
915 Perl_hv_delete(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 flags)
922 k_flags |= HVhek_UTF8;
926 return hv_delete_common(hv, NULL, key, klen, k_flags, flags, 0);
930 =for apidoc hv_delete_ent
932 Deletes a key/value pair in the hash. The value SV is removed from the
933 hash and returned to the caller. The C<flags> value will normally be zero;
934 if set to G_DISCARD then NULL will be returned. C<hash> can be a valid
935 precomputed hash value, or 0 to ask for it to be computed.
941 Perl_hv_delete_ent(pTHX_ HV *hv, SV *keysv, I32 flags, U32 hash)
943 return hv_delete_common(hv, keysv, NULL, 0, 0, flags, hash);
947 S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
948 int k_flags, I32 d_flags, U32 hash)
953 register HE **oentry;
954 HE *const *first_entry;
963 if (k_flags & HVhek_FREEKEY)
965 key = SvPV_const(keysv, klen);
967 is_utf8 = (SvUTF8(keysv) != 0);
969 is_utf8 = ((k_flags & HVhek_UTF8) ? TRUE : FALSE);
972 if (SvRMAGICAL(hv)) {
975 hv_magic_check (hv, &needs_copy, &needs_store);
978 entry = hv_fetch_common(hv, keysv, key, klen,
979 k_flags & ~HVhek_FREEKEY, HV_FETCH_LVALUE,
981 sv = entry ? HeVAL(entry) : NULL;
987 if (mg_find(sv, PERL_MAGIC_tiedelem)) {
988 /* No longer an element */
989 sv_unmagic(sv, PERL_MAGIC_tiedelem);
992 return Nullsv; /* element cannot be deleted */
994 #ifdef ENV_IS_CASELESS
995 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
996 /* XXX This code isn't UTF8 clean. */
997 keysv = sv_2mortal(newSVpvn(key,klen));
998 if (k_flags & HVhek_FREEKEY) {
1001 key = strupr(SvPVX(keysv));
1010 xhv = (XPVHV*)SvANY(hv);
1015 const char *keysave = key;
1016 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
1019 k_flags |= HVhek_UTF8;
1021 k_flags &= ~HVhek_UTF8;
1022 if (key != keysave) {
1023 if (k_flags & HVhek_FREEKEY) {
1024 /* This shouldn't happen if our caller does what we expect,
1025 but strictly the API allows it. */
1028 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
1030 HvHASKFLAGS_on((SV*)hv);
1034 PERL_HASH_INTERNAL(hash, key, klen);
1036 if (keysv && (SvIsCOW_shared_hash(keysv))) {
1037 hash = SvSHARED_HASH(keysv);
1039 PERL_HASH(hash, key, klen);
1043 masked_flags = (k_flags & HVhek_MASK);
1045 first_entry = oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
1047 for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
1048 if (HeHASH(entry) != hash) /* strings can't be equal */
1050 if (HeKLEN(entry) != (I32)klen)
1052 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
1054 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
1057 if (hv == PL_strtab) {
1058 if (k_flags & HVhek_FREEKEY)
1060 Perl_croak(aTHX_ S_strtab_error, "delete");
1063 /* if placeholder is here, it's already been deleted.... */
1064 if (HeVAL(entry) == &PL_sv_placeholder)
1066 if (k_flags & HVhek_FREEKEY)
1070 else if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1071 S_hv_notallowed(aTHX_ k_flags, key, klen,
1072 "Attempt to delete readonly key '%"SVf"' from"
1073 " a restricted hash");
1075 if (k_flags & HVhek_FREEKEY)
1078 if (d_flags & G_DISCARD)
1081 sv = sv_2mortal(HeVAL(entry));
1082 HeVAL(entry) = &PL_sv_placeholder;
1086 * If a restricted hash, rather than really deleting the entry, put
1087 * a placeholder there. This marks the key as being "approved", so
1088 * we can still access via not-really-existing key without raising
1091 if (SvREADONLY(hv)) {
1092 SvREFCNT_dec(HeVAL(entry));
1093 HeVAL(entry) = &PL_sv_placeholder;
1094 /* We'll be saving this slot, so the number of allocated keys
1095 * doesn't go down, but the number placeholders goes up */
1096 HvPLACEHOLDERS(hv)++;
1098 *oentry = HeNEXT(entry);
1100 xhv->xhv_fill--; /* HvFILL(hv)-- */
1102 if (SvOOK(hv) && entry == HvAUX(hv)->xhv_eiter /* HvEITER(hv) */)
1105 hv_free_ent(hv, entry);
1106 xhv->xhv_keys--; /* HvKEYS(hv)-- */
1107 if (xhv->xhv_keys == 0)
1108 HvHASKFLAGS_off(hv);
1112 if (SvREADONLY(hv)) {
1113 S_hv_notallowed(aTHX_ k_flags, key, klen,
1114 "Attempt to delete disallowed key '%"SVf"' from"
1115 " a restricted hash");
1118 if (k_flags & HVhek_FREEKEY)
1124 S_hsplit(pTHX_ HV *hv)
1126 register XPVHV* xhv = (XPVHV*)SvANY(hv);
1127 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1128 register I32 newsize = oldsize * 2;
1130 char *a = (char*) HvARRAY(hv);
1132 register HE **oentry;
1133 int longest_chain = 0;
1136 /*PerlIO_printf(PerlIO_stderr(), "hsplit called for %p which had %d\n",
1137 hv, (int) oldsize);*/
1139 if (HvPLACEHOLDERS_get(hv) && !SvREADONLY(hv)) {
1140 /* Can make this clear any placeholders first for non-restricted hashes,
1141 even though Storable rebuilds restricted hashes by putting in all the
1142 placeholders (first) before turning on the readonly flag, because
1143 Storable always pre-splits the hash. */
1144 hv_clear_placeholders(hv);
1148 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1149 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1150 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1156 Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1159 New(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1160 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1165 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1167 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1169 if (oldsize >= 64) {
1170 offer_nice_chunk(HvARRAY(hv),
1171 PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
1172 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
1175 Safefree(HvARRAY(hv));
1179 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1180 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
1181 HvARRAY(hv) = (HE**) a;
1184 for (i=0; i<oldsize; i++,aep++) {
1185 int left_length = 0;
1186 int right_length = 0;
1190 if (!*aep) /* non-existent */
1193 for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1194 if ((HeHASH(entry) & newsize) != (U32)i) {
1195 *oentry = HeNEXT(entry);
1196 HeNEXT(entry) = *bep;
1198 xhv->xhv_fill++; /* HvFILL(hv)++ */
1204 oentry = &HeNEXT(entry);
1208 if (!*aep) /* everything moved */
1209 xhv->xhv_fill--; /* HvFILL(hv)-- */
1210 /* I think we don't actually need to keep track of the longest length,
1211 merely flag if anything is too long. But for the moment while
1212 developing this code I'll track it. */
1213 if (left_length > longest_chain)
1214 longest_chain = left_length;
1215 if (right_length > longest_chain)
1216 longest_chain = right_length;
1220 /* Pick your policy for "hashing isn't working" here: */
1221 if (longest_chain <= HV_MAX_LENGTH_BEFORE_SPLIT /* split worked? */
1226 if (hv == PL_strtab) {
1227 /* Urg. Someone is doing something nasty to the string table.
1232 /* Awooga. Awooga. Pathological data. */
1233 /*PerlIO_printf(PerlIO_stderr(), "%p %d of %d with %d/%d buckets\n", hv,
1234 longest_chain, HvTOTALKEYS(hv), HvFILL(hv), 1+HvMAX(hv));*/
1237 Newz(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1238 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1240 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1243 was_shared = HvSHAREKEYS(hv);
1246 HvSHAREKEYS_off(hv);
1251 for (i=0; i<newsize; i++,aep++) {
1252 register HE *entry = *aep;
1254 /* We're going to trash this HE's next pointer when we chain it
1255 into the new hash below, so store where we go next. */
1256 HE * const next = HeNEXT(entry);
1261 PERL_HASH_INTERNAL(hash, HeKEY(entry), HeKLEN(entry));
1266 = save_hek_flags(HeKEY(entry), HeKLEN(entry),
1267 hash, HeKFLAGS(entry));
1268 unshare_hek (HeKEY_hek(entry));
1269 HeKEY_hek(entry) = new_hek;
1271 /* Not shared, so simply write the new hash in. */
1272 HeHASH(entry) = hash;
1274 /*PerlIO_printf(PerlIO_stderr(), "%d ", HeKFLAGS(entry));*/
1275 HEK_REHASH_on(HeKEY_hek(entry));
1276 /*PerlIO_printf(PerlIO_stderr(), "%d\n", HeKFLAGS(entry));*/
1278 /* Copy oentry to the correct new chain. */
1279 bep = ((HE**)a) + (hash & (I32) xhv->xhv_max);
1281 xhv->xhv_fill++; /* HvFILL(hv)++ */
1282 HeNEXT(entry) = *bep;
1288 Safefree (HvARRAY(hv));
1289 HvARRAY(hv) = (HE **)a;
1293 Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
1295 register XPVHV* xhv = (XPVHV*)SvANY(hv);
1296 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1297 register I32 newsize;
1302 register HE **oentry;
1304 newsize = (I32) newmax; /* possible truncation here */
1305 if (newsize != newmax || newmax <= oldsize)
1307 while ((newsize & (1 + ~newsize)) != newsize) {
1308 newsize &= ~(newsize & (1 + ~newsize)); /* get proper power of 2 */
1310 if (newsize < newmax)
1312 if (newsize < newmax)
1313 return; /* overflow detection */
1315 a = (char *) HvARRAY(hv);
1318 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1319 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1320 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1326 Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1329 New(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1330 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1335 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1337 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1339 if (oldsize >= 64) {
1340 offer_nice_chunk(HvARRAY(hv),
1341 PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
1342 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
1345 Safefree(HvARRAY(hv));
1348 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1351 Newz(0, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1353 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
1354 HvARRAY(hv) = (HE **) a;
1355 if (!xhv->xhv_fill /* !HvFILL(hv) */) /* skip rest if no entries */
1359 for (i=0; i<oldsize; i++,aep++) {
1360 if (!*aep) /* non-existent */
1362 for (oentry = aep, entry = *aep; entry; entry = *oentry) {
1364 if ((j = (HeHASH(entry) & newsize)) != i) {
1366 *oentry = HeNEXT(entry);
1367 if (!(HeNEXT(entry) = aep[j]))
1368 xhv->xhv_fill++; /* HvFILL(hv)++ */
1373 oentry = &HeNEXT(entry);
1375 if (!*aep) /* everything moved */
1376 xhv->xhv_fill--; /* HvFILL(hv)-- */
1383 Creates a new HV. The reference count is set to 1.
1391 register XPVHV* xhv;
1392 HV * const hv = (HV*)NEWSV(502,0);
1394 sv_upgrade((SV *)hv, SVt_PVHV);
1395 xhv = (XPVHV*)SvANY(hv);
1398 #ifndef NODEFAULT_SHAREKEYS
1399 HvSHAREKEYS_on(hv); /* key-sharing on by default */
1402 xhv->xhv_max = 7; /* HvMAX(hv) = 7 (start with 8 buckets) */
1403 xhv->xhv_fill = 0; /* HvFILL(hv) = 0 */
1408 Perl_newHVhv(pTHX_ HV *ohv)
1410 HV * const hv = newHV();
1411 STRLEN hv_max, hv_fill;
1413 if (!ohv || (hv_fill = HvFILL(ohv)) == 0)
1415 hv_max = HvMAX(ohv);
1417 if (!SvMAGICAL((SV *)ohv)) {
1418 /* It's an ordinary hash, so copy it fast. AMS 20010804 */
1420 const bool shared = !!HvSHAREKEYS(ohv);
1421 HE **ents, **oents = (HE **)HvARRAY(ohv);
1423 New(0, a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
1426 /* In each bucket... */
1427 for (i = 0; i <= hv_max; i++) {
1428 HE *prev = NULL, *ent = NULL, *oent = oents[i];
1435 /* Copy the linked list of entries. */
1436 for (oent = oents[i]; oent; oent = HeNEXT(oent)) {
1437 const U32 hash = HeHASH(oent);
1438 const char * const key = HeKEY(oent);
1439 const STRLEN len = HeKLEN(oent);
1440 const int flags = HeKFLAGS(oent);
1443 HeVAL(ent) = newSVsv(HeVAL(oent));
1445 = shared ? share_hek_flags(key, len, hash, flags)
1446 : save_hek_flags(key, len, hash, flags);
1457 HvFILL(hv) = hv_fill;
1458 HvTOTALKEYS(hv) = HvTOTALKEYS(ohv);
1462 /* Iterate over ohv, copying keys and values one at a time. */
1464 const I32 riter = HvRITER_get(ohv);
1465 HE * const eiter = HvEITER_get(ohv);
1467 /* Can we use fewer buckets? (hv_max is always 2^n-1) */
1468 while (hv_max && hv_max + 1 >= hv_fill * 2)
1469 hv_max = hv_max / 2;
1473 while ((entry = hv_iternext_flags(ohv, 0))) {
1474 hv_store_flags(hv, HeKEY(entry), HeKLEN(entry),
1475 newSVsv(HeVAL(entry)), HeHASH(entry),
1478 HvRITER_set(ohv, riter);
1479 HvEITER_set(ohv, eiter);
1486 Perl_hv_free_ent(pTHX_ HV *hv, register HE *entry)
1493 if (val && isGV(val) && GvCVu(val) && HvNAME_get(hv))
1494 PL_sub_generation++; /* may be deletion of method from stash */
1496 if (HeKLEN(entry) == HEf_SVKEY) {
1497 SvREFCNT_dec(HeKEY_sv(entry));
1498 Safefree(HeKEY_hek(entry));
1500 else if (HvSHAREKEYS(hv))
1501 unshare_hek(HeKEY_hek(entry));
1503 Safefree(HeKEY_hek(entry));
1508 Perl_hv_delayfree_ent(pTHX_ HV *hv, register HE *entry)
1512 if (isGV(HeVAL(entry)) && GvCVu(HeVAL(entry)) && HvNAME_get(hv))
1513 PL_sub_generation++; /* may be deletion of method from stash */
1514 sv_2mortal(HeVAL(entry)); /* free between statements */
1515 if (HeKLEN(entry) == HEf_SVKEY) {
1516 sv_2mortal(HeKEY_sv(entry));
1517 Safefree(HeKEY_hek(entry));
1519 else if (HvSHAREKEYS(hv))
1520 unshare_hek(HeKEY_hek(entry));
1522 Safefree(HeKEY_hek(entry));
1527 =for apidoc hv_clear
1529 Clears a hash, making it empty.
1535 Perl_hv_clear(pTHX_ HV *hv)
1538 register XPVHV* xhv;
1542 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1544 xhv = (XPVHV*)SvANY(hv);
1546 if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
1547 /* restricted hash: convert all keys to placeholders */
1549 for (i = 0; i <= xhv->xhv_max; i++) {
1550 HE *entry = (HvARRAY(hv))[i];
1551 for (; entry; entry = HeNEXT(entry)) {
1552 /* not already placeholder */
1553 if (HeVAL(entry) != &PL_sv_placeholder) {
1554 if (HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1555 SV* keysv = hv_iterkeysv(entry);
1557 "Attempt to delete readonly key '%"SVf"' from a restricted hash",
1560 SvREFCNT_dec(HeVAL(entry));
1561 HeVAL(entry) = &PL_sv_placeholder;
1562 HvPLACEHOLDERS(hv)++;
1570 HvPLACEHOLDERS_set(hv, 0);
1572 (void)memzero(HvARRAY(hv),
1573 (xhv->xhv_max+1 /* HvMAX(hv)+1 */) * sizeof(HE*));
1578 HvHASKFLAGS_off(hv);
1582 HvEITER_set(hv, NULL);
1587 =for apidoc hv_clear_placeholders
1589 Clears any placeholders from a hash. If a restricted hash has any of its keys
1590 marked as readonly and the key is subsequently deleted, the key is not actually
1591 deleted but is marked by assigning it a value of &PL_sv_placeholder. This tags
1592 it so it will be ignored by future operations such as iterating over the hash,
1593 but will still allow the hash to have a value reassigned to the key at some
1594 future point. This function clears any such placeholder keys from the hash.
1595 See Hash::Util::lock_keys() for an example of its use.
1601 Perl_hv_clear_placeholders(pTHX_ HV *hv)
1604 I32 items = (I32)HvPLACEHOLDERS_get(hv);
1612 /* Loop down the linked list heads */
1614 HE **oentry = &(HvARRAY(hv))[i];
1615 HE *entry = *oentry;
1620 for (; entry; entry = *oentry) {
1621 if (HeVAL(entry) == &PL_sv_placeholder) {
1622 *oentry = HeNEXT(entry);
1623 if (first && !*oentry)
1624 HvFILL(hv)--; /* This linked list is now empty. */
1625 if (HvEITER_get(hv))
1628 hv_free_ent(hv, entry);
1632 HvTOTALKEYS(hv) -= (IV)HvPLACEHOLDERS_get(hv);
1633 if (HvKEYS(hv) == 0)
1634 HvHASKFLAGS_off(hv);
1635 HvPLACEHOLDERS_set(hv, 0);
1639 oentry = &HeNEXT(entry);
1644 /* You can't get here, hence assertion should always fail. */
1645 assert (items == 0);
1650 S_hfreeentries(pTHX_ HV *hv)
1652 register HE **array;
1656 struct xpvhv_aux *iter;
1662 iter = SvOOK(hv) ? HvAUX(hv) : 0;
1666 array = HvARRAY(hv);
1667 /* make everyone else think the array is empty, so that the destructors
1668 * called for freed entries can't recusively mess with us */
1669 HvARRAY(hv) = Null(HE**);
1670 SvFLAGS(hv) &= ~SVf_OOK;
1673 ((XPVHV*) SvANY(hv))->xhv_keys = 0;
1678 register HE *oentry = entry;
1679 entry = HeNEXT(entry);
1680 hv_free_ent(hv, oentry);
1685 entry = array[riter];
1690 /* Someone attempted to iterate or set the hash name while we had
1691 the array set to 0. */
1692 assert(HvARRAY(hv));
1694 if (HvAUX(hv)->xhv_name)
1695 unshare_hek_or_pvn(HvAUX(hv)->xhv_name, 0, 0, 0);
1696 /* SvOOK_off calls sv_backoff, which isn't correct. */
1698 Safefree(HvARRAY(hv));
1700 SvFLAGS(hv) &= ~SVf_OOK;
1703 /* FIXME - things will still go horribly wrong (or at least leak) if
1704 people attempt to add elements to the hash while we're undef()ing it */
1706 entry = iter->xhv_eiter; /* HvEITER(hv) */
1707 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1709 hv_free_ent(hv, entry);
1711 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1712 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1713 SvFLAGS(hv) |= SVf_OOK;
1716 HvARRAY(hv) = array;
1720 =for apidoc hv_undef
1728 Perl_hv_undef(pTHX_ HV *hv)
1730 register XPVHV* xhv;
1734 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1735 xhv = (XPVHV*)SvANY(hv);
1737 if ((name = HvNAME_get(hv))) {
1739 hv_delete(PL_stashcache, name, HvNAMELEN_get(hv), G_DISCARD);
1740 Perl_hv_name_set(aTHX_ hv, 0, 0, 0);
1742 SvFLAGS(hv) &= ~SVf_OOK;
1743 Safefree(HvARRAY(hv));
1744 xhv->xhv_max = 7; /* HvMAX(hv) = 7 (it's a normal hash) */
1746 HvPLACEHOLDERS_set(hv, 0);
1752 static struct xpvhv_aux*
1753 S_hv_auxinit(pTHX_ HV *hv) {
1754 struct xpvhv_aux *iter;
1758 Newz(0, array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1759 + sizeof(struct xpvhv_aux), char);
1761 array = (char *) HvARRAY(hv);
1762 Renew(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1763 + sizeof(struct xpvhv_aux), char);
1765 HvARRAY(hv) = (HE**) array;
1766 /* SvOOK_on(hv) attacks the IV flags. */
1767 SvFLAGS(hv) |= SVf_OOK;
1770 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1771 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1778 =for apidoc hv_iterinit
1780 Prepares a starting point to traverse a hash table. Returns the number of
1781 keys in the hash (i.e. the same as C<HvKEYS(tb)>). The return value is
1782 currently only meaningful for hashes without tie magic.
1784 NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
1785 hash buckets that happen to be in use. If you still need that esoteric
1786 value, you can get it through the macro C<HvFILL(tb)>.
1793 Perl_hv_iterinit(pTHX_ HV *hv)
1798 Perl_croak(aTHX_ "Bad hash");
1801 struct xpvhv_aux *iter = HvAUX(hv);
1802 entry = iter->xhv_eiter; /* HvEITER(hv) */
1803 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1805 hv_free_ent(hv, entry);
1807 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1808 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1810 S_hv_auxinit(aTHX_ hv);
1813 /* used to be xhv->xhv_fill before 5.004_65 */
1814 return HvTOTALKEYS(hv);
1818 Perl_hv_riter_p(pTHX_ HV *hv) {
1819 struct xpvhv_aux *iter;
1822 Perl_croak(aTHX_ "Bad hash");
1824 iter = SvOOK(hv) ? HvAUX(hv) : S_hv_auxinit(aTHX_ hv);
1825 return &(iter->xhv_riter);
1829 Perl_hv_eiter_p(pTHX_ HV *hv) {
1830 struct xpvhv_aux *iter;
1833 Perl_croak(aTHX_ "Bad hash");
1835 iter = SvOOK(hv) ? HvAUX(hv) : S_hv_auxinit(aTHX_ hv);
1836 return &(iter->xhv_eiter);
1840 Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
1841 struct xpvhv_aux *iter;
1844 Perl_croak(aTHX_ "Bad hash");
1852 iter = S_hv_auxinit(aTHX_ hv);
1854 iter->xhv_riter = riter;
1858 Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
1859 struct xpvhv_aux *iter;
1862 Perl_croak(aTHX_ "Bad hash");
1867 /* 0 is the default so don't go malloc()ing a new structure just to
1872 iter = S_hv_auxinit(aTHX_ hv);
1874 iter->xhv_eiter = eiter;
1878 Perl_hv_name_set(pTHX_ HV *hv, const char *name, I32 len, int flags)
1880 struct xpvhv_aux *iter;
1886 if (iter->xhv_name) {
1887 unshare_hek_or_pvn(iter->xhv_name, 0, 0, 0);
1893 iter = S_hv_auxinit(aTHX_ hv);
1895 PERL_HASH(hash, name, len);
1896 iter->xhv_name = name ? share_hek(name, len, hash) : 0;
1900 =for apidoc hv_iternext
1902 Returns entries from a hash iterator. See C<hv_iterinit>.
1904 You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
1905 iterator currently points to, without losing your place or invalidating your
1906 iterator. Note that in this case the current entry is deleted from the hash
1907 with your iterator holding the last reference to it. Your iterator is flagged
1908 to free the entry on the next call to C<hv_iternext>, so you must not discard
1909 your iterator immediately else the entry will leak - call C<hv_iternext> to
1910 trigger the resource deallocation.
1916 Perl_hv_iternext(pTHX_ HV *hv)
1918 return hv_iternext_flags(hv, 0);
1922 =for apidoc hv_iternext_flags
1924 Returns entries from a hash iterator. See C<hv_iterinit> and C<hv_iternext>.
1925 The C<flags> value will normally be zero; if HV_ITERNEXT_WANTPLACEHOLDERS is
1926 set the placeholders keys (for restricted hashes) will be returned in addition
1927 to normal keys. By default placeholders are automatically skipped over.
1928 Currently a placeholder is implemented with a value that is
1929 C<&Perl_sv_placeholder>. Note that the implementation of placeholders and
1930 restricted hashes may change, and the implementation currently is
1931 insufficiently abstracted for any change to be tidy.
1937 Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
1940 register XPVHV* xhv;
1944 struct xpvhv_aux *iter;
1947 Perl_croak(aTHX_ "Bad hash");
1948 xhv = (XPVHV*)SvANY(hv);
1951 /* Too many things (well, pp_each at least) merrily assume that you can
1952 call iv_iternext without calling hv_iterinit, so we'll have to deal
1958 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
1960 if ((mg = SvTIED_mg((SV*)hv, PERL_MAGIC_tied))) {
1961 SV *key = sv_newmortal();
1963 sv_setsv(key, HeSVKEY_force(entry));
1964 SvREFCNT_dec(HeSVKEY(entry)); /* get rid of previous key */
1970 /* one HE per MAGICAL hash */
1971 iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
1973 Newz(54, k, HEK_BASESIZE + sizeof(SV*), char);
1975 HeKEY_hek(entry) = hek;
1976 HeKLEN(entry) = HEf_SVKEY;
1978 magic_nextpack((SV*) hv,mg,key);
1980 /* force key to stay around until next time */
1981 HeSVKEY_set(entry, SvREFCNT_inc(key));
1982 return entry; /* beware, hent_val is not set */
1985 SvREFCNT_dec(HeVAL(entry));
1986 Safefree(HeKEY_hek(entry));
1988 iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
1991 #ifdef DYNAMIC_ENV_FETCH /* set up %ENV for iteration */
1992 if (!entry && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
1996 /* hv_iterint now ensures this. */
1997 assert (HvARRAY(hv));
1999 /* At start of hash, entry is NULL. */
2002 entry = HeNEXT(entry);
2003 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2005 * Skip past any placeholders -- don't want to include them in
2008 while (entry && HeVAL(entry) == &PL_sv_placeholder) {
2009 entry = HeNEXT(entry);
2014 /* OK. Come to the end of the current list. Grab the next one. */
2016 iter->xhv_riter++; /* HvRITER(hv)++ */
2017 if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
2018 /* There is no next one. End of the hash. */
2019 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2022 entry = (HvARRAY(hv))[iter->xhv_riter];
2024 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2025 /* If we have an entry, but it's a placeholder, don't count it.
2027 while (entry && HeVAL(entry) == &PL_sv_placeholder)
2028 entry = HeNEXT(entry);
2030 /* Will loop again if this linked list starts NULL
2031 (for HV_ITERNEXT_WANTPLACEHOLDERS)
2032 or if we run through it and find only placeholders. */
2035 if (oldentry && HvLAZYDEL(hv)) { /* was deleted earlier? */
2037 hv_free_ent(hv, oldentry);
2040 /*if (HvREHASH(hv) && entry && !HeKREHASH(entry))
2041 PerlIO_printf(PerlIO_stderr(), "Awooga %p %p\n", hv, entry);*/
2043 iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
2048 =for apidoc hv_iterkey
2050 Returns the key from the current position of the hash iterator. See
2057 Perl_hv_iterkey(pTHX_ register HE *entry, I32 *retlen)
2059 if (HeKLEN(entry) == HEf_SVKEY) {
2061 char *p = SvPV(HeKEY_sv(entry), len);
2066 *retlen = HeKLEN(entry);
2067 return HeKEY(entry);
2071 /* unlike hv_iterval(), this always returns a mortal copy of the key */
2073 =for apidoc hv_iterkeysv
2075 Returns the key as an C<SV*> from the current position of the hash
2076 iterator. The return value will always be a mortal copy of the key. Also
2083 Perl_hv_iterkeysv(pTHX_ register HE *entry)
2085 return sv_2mortal(newSVhek(HeKEY_hek(entry)));
2089 =for apidoc hv_iterval
2091 Returns the value from the current position of the hash iterator. See
2098 Perl_hv_iterval(pTHX_ HV *hv, register HE *entry)
2100 if (SvRMAGICAL(hv)) {
2101 if (mg_find((SV*)hv, PERL_MAGIC_tied)) {
2102 SV* sv = sv_newmortal();
2103 if (HeKLEN(entry) == HEf_SVKEY)
2104 mg_copy((SV*)hv, sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
2106 mg_copy((SV*)hv, sv, HeKEY(entry), HeKLEN(entry));
2110 return HeVAL(entry);
2114 =for apidoc hv_iternextsv
2116 Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2123 Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
2126 if ( (he = hv_iternext_flags(hv, 0)) == NULL)
2128 *key = hv_iterkey(he, retlen);
2129 return hv_iterval(hv, he);
2133 =for apidoc hv_magic
2135 Adds magic to a hash. See C<sv_magic>.
2141 Perl_hv_magic(pTHX_ HV *hv, GV *gv, int how)
2143 sv_magic((SV*)hv, (SV*)gv, how, Nullch, 0);
2146 #if 0 /* use the macro from hv.h instead */
2149 Perl_sharepvn(pTHX_ const char *sv, I32 len, U32 hash)
2151 return HEK_KEY(share_hek(sv, len, hash));
2156 /* possibly free a shared string if no one has access to it
2157 * len and hash must both be valid for str.
2160 Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
2162 unshare_hek_or_pvn (NULL, str, len, hash);
2167 Perl_unshare_hek(pTHX_ HEK *hek)
2169 unshare_hek_or_pvn(hek, NULL, 0, 0);
2172 /* possibly free a shared string if no one has access to it
2173 hek if non-NULL takes priority over the other 3, else str, len and hash
2174 are used. If so, len and hash must both be valid for str.
2177 S_unshare_hek_or_pvn(pTHX_ const HEK *hek, const char *str, I32 len, U32 hash)
2179 register XPVHV* xhv;
2181 register HE **oentry;
2184 bool is_utf8 = FALSE;
2186 const char *save = str;
2187 struct shared_he *he = 0;
2190 /* Find the shared he which is just before us in memory. */
2191 he = (struct shared_he *)(((char *)hek)
2192 - STRUCT_OFFSET(struct shared_he,
2195 /* Assert that the caller passed us a genuine (or at least consistent)
2197 assert (he->shared_he_he.hent_hek == hek);
2200 if (he->shared_he_he.hent_val - 1) {
2201 --he->shared_he_he.hent_val;
2202 UNLOCK_STRTAB_MUTEX;
2205 UNLOCK_STRTAB_MUTEX;
2207 hash = HEK_HASH(hek);
2208 } else if (len < 0) {
2209 STRLEN tmplen = -len;
2211 /* See the note in hv_fetch(). --jhi */
2212 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2215 k_flags = HVhek_UTF8;
2217 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2220 /* what follows is the moral equivalent of:
2221 if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
2222 if (--*Svp == Nullsv)
2223 hv_delete(PL_strtab, str, len, G_DISCARD, hash);
2225 xhv = (XPVHV*)SvANY(PL_strtab);
2226 /* assert(xhv_array != 0) */
2228 first = oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2230 const HE *const he_he = &(he->shared_he_he);
2231 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2238 const int flags_masked = k_flags & HVhek_MASK;
2239 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2240 if (HeHASH(entry) != hash) /* strings can't be equal */
2242 if (HeKLEN(entry) != len)
2244 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2246 if (HeKFLAGS(entry) != flags_masked)
2254 if (--HeVAL(entry) == Nullsv) {
2255 *oentry = HeNEXT(entry);
2257 /* There are now no entries in our slot. */
2258 xhv->xhv_fill--; /* HvFILL(hv)-- */
2261 xhv->xhv_keys--; /* HvKEYS(hv)-- */
2265 UNLOCK_STRTAB_MUTEX;
2266 if (!found && ckWARN_d(WARN_INTERNAL))
2267 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
2268 "Attempt to free non-existent shared string '%s'%s"
2270 hek ? HEK_KEY(hek) : str,
2271 ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
2272 if (k_flags & HVhek_FREEKEY)
2276 /* get a (constant) string ptr from the global string table
2277 * string will get added if it is not already there.
2278 * len and hash must both be valid for str.
2281 Perl_share_hek(pTHX_ const char *str, I32 len, register U32 hash)
2283 bool is_utf8 = FALSE;
2285 const char *save = str;
2288 STRLEN tmplen = -len;
2290 /* See the note in hv_fetch(). --jhi */
2291 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2293 /* If we were able to downgrade here, then than means that we were passed
2294 in a key which only had chars 0-255, but was utf8 encoded. */
2297 /* If we found we were able to downgrade the string to bytes, then
2298 we should flag that it needs upgrading on keys or each. Also flag
2299 that we need share_hek_flags to free the string. */
2301 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2304 return share_hek_flags (str, len, hash, flags);
2308 S_share_hek_flags(pTHX_ const char *str, I32 len, register U32 hash, int flags)
2311 register HE **oentry;
2313 const int flags_masked = flags & HVhek_MASK;
2315 /* what follows is the moral equivalent of:
2317 if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
2318 hv_store(PL_strtab, str, len, Nullsv, hash);
2320 Can't rehash the shared string table, so not sure if it's worth
2321 counting the number of entries in the linked list
2323 register XPVHV * const xhv = (XPVHV*)SvANY(PL_strtab);
2324 /* assert(xhv_array != 0) */
2326 oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2327 for (entry = *oentry; entry; entry = HeNEXT(entry)) {
2328 if (HeHASH(entry) != hash) /* strings can't be equal */
2330 if (HeKLEN(entry) != len)
2332 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2334 if (HeKFLAGS(entry) != flags_masked)
2340 /* What used to be head of the list.
2341 If this is NULL, then we're the first entry for this slot, which
2342 means we need to increate fill. */
2343 const HE *old_first = *oentry;
2344 struct shared_he *new_entry;
2348 /* We don't actually store a HE from the arena and a regular HEK.
2349 Instead we allocate one chunk of memory big enough for both,
2350 and put the HEK straight after the HE. This way we can find the
2351 HEK directly from the HE.
2354 New(0, k, STRUCT_OFFSET(struct shared_he,
2355 shared_he_hek.hek_key[0]) + len + 2, char);
2356 new_entry = (struct shared_he *)k;
2357 entry = &(new_entry->shared_he_he);
2358 hek = &(new_entry->shared_he_hek);
2360 Copy(str, HEK_KEY(hek), len, char);
2361 HEK_KEY(hek)[len] = 0;
2363 HEK_HASH(hek) = hash;
2364 HEK_FLAGS(hek) = (unsigned char)flags_masked;
2366 /* Still "point" to the HEK, so that other code need not know what
2368 HeKEY_hek(entry) = hek;
2369 HeVAL(entry) = Nullsv;
2370 HeNEXT(entry) = *oentry;
2373 xhv->xhv_keys++; /* HvKEYS(hv)++ */
2374 if (!old_first) { /* initial entry? */
2375 xhv->xhv_fill++; /* HvFILL(hv)++ */
2376 } else if (xhv->xhv_keys > (IV)xhv->xhv_max /* HvKEYS(hv) > HvMAX(hv) */) {
2381 ++HeVAL(entry); /* use value slot as REFCNT */
2382 UNLOCK_STRTAB_MUTEX;
2384 if (flags & HVhek_FREEKEY)
2387 return HeKEY_hek(entry);
2391 Perl_hv_placeholders_p(pTHX_ HV *hv)
2394 MAGIC *mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2397 mg = sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, 0);
2400 Perl_die(aTHX_ "panic: hv_placeholders_p");
2403 return &(mg->mg_len);
2408 Perl_hv_placeholders_get(pTHX_ HV *hv)
2411 MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2413 return mg ? mg->mg_len : 0;
2417 Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
2420 MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2425 if (!sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, ph))
2426 Perl_die(aTHX_ "panic: hv_placeholders_set");
2428 /* else we don't need to add magic to record 0 placeholders. */
2432 =for apidoc hv_assert
2434 Check that a hash is in an internally consistent state.
2440 Perl_hv_assert(pTHX_ HV *hv)
2445 int placeholders = 0;
2448 const I32 riter = HvRITER_get(hv);
2449 HE *eiter = HvEITER_get(hv);
2451 (void)hv_iterinit(hv);
2453 while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
2454 /* sanity check the values */
2455 if (HeVAL(entry) == &PL_sv_placeholder) {
2460 /* sanity check the keys */
2461 if (HeSVKEY(entry)) {
2462 /* Don't know what to check on SV keys. */
2463 } else if (HeKUTF8(entry)) {
2465 if (HeKWASUTF8(entry)) {
2466 PerlIO_printf(Perl_debug_log,
2467 "hash key has both WASUFT8 and UTF8: '%.*s'\n",
2468 (int) HeKLEN(entry), HeKEY(entry));
2471 } else if (HeKWASUTF8(entry)) {
2475 if (!SvTIED_mg((SV*)hv, PERL_MAGIC_tied)) {
2476 if (HvUSEDKEYS(hv) != real) {
2477 PerlIO_printf(Perl_debug_log, "Count %d key(s), but hash reports %d\n",
2478 (int) real, (int) HvUSEDKEYS(hv));
2481 if (HvPLACEHOLDERS_get(hv) != placeholders) {
2482 PerlIO_printf(Perl_debug_log,
2483 "Count %d placeholder(s), but hash reports %d\n",
2484 (int) placeholders, (int) HvPLACEHOLDERS_get(hv));
2488 if (withflags && ! HvHASKFLAGS(hv)) {
2489 PerlIO_printf(Perl_debug_log,
2490 "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
2497 HvRITER_set(hv, riter); /* Restore hash iterator state */
2498 HvEITER_set(hv, eiter);
2503 * c-indentation-style: bsd
2505 * indent-tabs-mode: t
2508 * ex: set ts=8 sts=4 sw=4 noet: