3 * Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4 * 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 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
13 * of all that I have seen.
16 * [p.278 of _The Lord of the Rings_, II/iii: "The Ring Goes South"]
20 =head1 Hash Manipulation Functions
22 A HV structure represents a Perl hash. It consists mainly of an array
23 of pointers, each of which points to a linked list of HE structures. The
24 array is indexed by the hash function of the key, so each linked list
25 represents all the hash entries with the same hash value. Each HE contains
26 a pointer to the actual value, plus a pointer to a HEK structure which
27 holds the key and hash value.
35 #define PERL_HASH_INTERNAL_ACCESS
38 #define DO_HSPLIT(xhv) ((xhv)->xhv_keys > (xhv)->xhv_max) /* HvTOTALKEYS(hv) > HvMAX(hv) */
39 #define HV_FILL_THRESHOLD 31
41 static const char S_strtab_error[]
42 = "Cannot modify shared string table in hv_%s";
46 #define new_HE() (HE*)safemalloc(sizeof(HE))
47 #define del_HE(p) safefree((char*)p)
56 void ** const root = &PL_body_roots[HE_SVSLOT];
59 Perl_more_bodies(aTHX_ HE_SVSLOT, sizeof(HE), PERL_ARENA_SIZE);
66 #define new_HE() new_he()
69 HeNEXT(p) = (HE*)(PL_body_roots[HE_SVSLOT]); \
70 PL_body_roots[HE_SVSLOT] = p; \
78 S_save_hek_flags(const char *str, I32 len, U32 hash, int flags)
80 const int flags_masked = flags & HVhek_MASK;
84 PERL_ARGS_ASSERT_SAVE_HEK_FLAGS;
86 Newx(k, HEK_BASESIZE + len + 2, char);
88 Copy(str, HEK_KEY(hek), len, char);
89 HEK_KEY(hek)[len] = 0;
92 HEK_FLAGS(hek) = (unsigned char)flags_masked | HVhek_UNSHARED;
94 if (flags & HVhek_FREEKEY)
99 /* free the pool of temporary HE/HEK pairs returned by hv_fetch_ent
103 Perl_free_tied_hv_pool(pTHX)
106 HE *he = PL_hv_fetch_ent_mh;
109 Safefree(HeKEY_hek(he));
113 PL_hv_fetch_ent_mh = NULL;
116 #if defined(USE_ITHREADS)
118 Perl_hek_dup(pTHX_ HEK *source, CLONE_PARAMS* param)
122 PERL_ARGS_ASSERT_HEK_DUP;
123 PERL_UNUSED_ARG(param);
128 shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
130 /* We already shared this hash key. */
131 (void)share_hek_hek(shared);
135 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
136 HEK_HASH(source), HEK_FLAGS(source));
137 ptr_table_store(PL_ptr_table, source, shared);
143 Perl_he_dup(pTHX_ const HE *e, bool shared, CLONE_PARAMS* param)
147 PERL_ARGS_ASSERT_HE_DUP;
151 /* look for it in the table first */
152 ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
156 /* create anew and remember what it is */
158 ptr_table_store(PL_ptr_table, e, ret);
160 HeNEXT(ret) = he_dup(HeNEXT(e),shared, param);
161 if (HeKLEN(e) == HEf_SVKEY) {
163 Newx(k, HEK_BASESIZE + sizeof(const SV *), char);
164 HeKEY_hek(ret) = (HEK*)k;
165 HeKEY_sv(ret) = sv_dup_inc(HeKEY_sv(e), param);
168 /* This is hek_dup inlined, which seems to be important for speed
170 HEK * const source = HeKEY_hek(e);
171 HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
174 /* We already shared this hash key. */
175 (void)share_hek_hek(shared);
179 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
180 HEK_HASH(source), HEK_FLAGS(source));
181 ptr_table_store(PL_ptr_table, source, shared);
183 HeKEY_hek(ret) = shared;
186 HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
188 HeVAL(ret) = sv_dup_inc(HeVAL(e), param);
191 #endif /* USE_ITHREADS */
194 S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
197 SV * const sv = sv_newmortal();
199 PERL_ARGS_ASSERT_HV_NOTALLOWED;
201 if (!(flags & HVhek_FREEKEY)) {
202 sv_setpvn(sv, key, klen);
205 /* Need to free saved eventually assign to mortal SV */
206 /* XXX is this line an error ???: SV *sv = sv_newmortal(); */
207 sv_usepvn(sv, (char *) key, klen);
209 if (flags & HVhek_UTF8) {
212 Perl_croak(aTHX_ msg, SVfARG(sv));
215 /* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
221 Stores an SV in a hash. The hash key is specified as C<key> and the
222 absolute value of C<klen> is the length of the key. If C<klen> is
223 negative the key is assumed to be in UTF-8-encoded Unicode. The
224 C<hash> parameter is the precomputed hash value; if it is zero then
225 Perl will compute it.
227 The return value will be
228 NULL if the operation failed or if the value did not need to be actually
229 stored within the hash (as in the case of tied hashes). Otherwise it can
230 be dereferenced to get the original C<SV*>. Note that the caller is
231 responsible for suitably incrementing the reference count of C<val> before
232 the call, and decrementing it if the function returned NULL. Effectively
233 a successful hv_store takes ownership of one reference to C<val>. This is
234 usually what you want; a newly created SV has a reference count of one, so
235 if all your code does is create SVs then store them in a hash, hv_store
236 will own the only reference to the new SV, and your code doesn't need to do
237 anything further to tidy up. hv_store is not implemented as a call to
238 hv_store_ent, and does not create a temporary SV for the key, so if your
239 key data is not already in SV form then use hv_store in preference to
242 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
243 information on how to use this function on tied hashes.
245 =for apidoc hv_store_ent
247 Stores C<val> in a hash. The hash key is specified as C<key>. The C<hash>
248 parameter is the precomputed hash value; if it is zero then Perl will
249 compute it. The return value is the new hash entry so created. It will be
250 NULL if the operation failed or if the value did not need to be actually
251 stored within the hash (as in the case of tied hashes). Otherwise the
252 contents of the return value can be accessed using the C<He?> macros
253 described here. Note that the caller is responsible for suitably
254 incrementing the reference count of C<val> before the call, and
255 decrementing it if the function returned NULL. Effectively a successful
256 hv_store_ent takes ownership of one reference to C<val>. This is
257 usually what you want; a newly created SV has a reference count of one, so
258 if all your code does is create SVs then store them in a hash, hv_store
259 will own the only reference to the new SV, and your code doesn't need to do
260 anything further to tidy up. Note that hv_store_ent only reads the C<key>;
261 unlike C<val> it does not take ownership of it, so maintaining the correct
262 reference count on C<key> is entirely the caller's responsibility. hv_store
263 is not implemented as a call to hv_store_ent, and does not create a temporary
264 SV for the key, so if your key data is not already in SV form then use
265 hv_store in preference to hv_store_ent.
267 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
268 information on how to use this function on tied hashes.
270 =for apidoc hv_exists
272 Returns a boolean indicating whether the specified hash key exists. The
273 absolute value of C<klen> is the length of the key. If C<klen> is
274 negative the key is assumed to be in UTF-8-encoded Unicode.
278 Returns the SV which corresponds to the specified key in the hash.
279 The absolute value of C<klen> is the length of the key. If C<klen> is
280 negative the key is assumed to be in UTF-8-encoded Unicode. If
281 C<lval> is set then the fetch will be part of a store. This means that if
282 there is no value in the hash associated with the given key, then one is
283 created and a pointer to it is returned. The C<SV*> it points to can be
284 assigned to. But always check that the
285 return value is non-null before dereferencing it to an C<SV*>.
287 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
288 information on how to use this function on tied hashes.
290 =for apidoc hv_exists_ent
292 Returns a boolean indicating whether
293 the specified hash key exists. C<hash>
294 can be a valid precomputed hash value, or 0 to ask for it to be
300 /* returns an HE * structure with the all fields set */
301 /* note that hent_val will be a mortal sv for MAGICAL hashes */
303 =for apidoc hv_fetch_ent
305 Returns the hash entry which corresponds to the specified key in the hash.
306 C<hash> must be a valid precomputed hash number for the given C<key>, or 0
307 if you want the function to compute it. IF C<lval> is set then the fetch
308 will be part of a store. Make sure the return value is non-null before
309 accessing it. The return value when C<hv> is a tied hash is a pointer to a
310 static location, so be sure to make a copy of the structure if you need to
313 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
314 information on how to use this function on tied hashes.
319 /* Common code for hv_delete()/hv_exists()/hv_fetch()/hv_store() */
321 Perl_hv_common_key_len(pTHX_ HV *hv, const char *key, I32 klen_i32,
322 const int action, SV *val, const U32 hash)
327 PERL_ARGS_ASSERT_HV_COMMON_KEY_LEN;
336 return hv_common(hv, NULL, key, klen, flags, action, val, hash);
340 Perl_hv_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
341 int flags, int action, SV *val, U32 hash)
350 const int return_svp = action & HV_FETCH_JUST_SV;
354 if (SvTYPE(hv) == (svtype)SVTYPEMASK)
357 assert(SvTYPE(hv) == SVt_PVHV);
359 if (SvSMAGICAL(hv) && SvGMAGICAL(hv) && !(action & HV_DISABLE_UVAR_XKEY)) {
361 if ((mg = mg_find((const SV *)hv, PERL_MAGIC_uvar))) {
362 struct ufuncs * const uf = (struct ufuncs *)mg->mg_ptr;
363 if (uf->uf_set == NULL) {
364 SV* obj = mg->mg_obj;
367 keysv = newSVpvn_flags(key, klen, SVs_TEMP |
368 ((flags & HVhek_UTF8)
372 mg->mg_obj = keysv; /* pass key */
373 uf->uf_index = action; /* pass action */
374 magic_getuvar(MUTABLE_SV(hv), mg);
375 keysv = mg->mg_obj; /* may have changed */
378 /* If the key may have changed, then we need to invalidate
379 any passed-in computed hash value. */
385 if (flags & HVhek_FREEKEY)
387 key = SvPV_const(keysv, klen);
388 is_utf8 = (SvUTF8(keysv) != 0);
389 if (SvIsCOW_shared_hash(keysv)) {
390 flags = HVhek_KEYCANONICAL | (is_utf8 ? HVhek_UTF8 : 0);
392 flags = is_utf8 ? HVhek_UTF8 : 0;
395 is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
398 if (action & HV_DELETE) {
399 return (void *) hv_delete_common(hv, keysv, key, klen,
400 flags, action, hash);
403 xhv = (XPVHV*)SvANY(hv);
405 if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS))) {
406 if (mg_find((const SV *)hv, PERL_MAGIC_tied)
407 || SvGMAGICAL((const SV *)hv))
409 /* FIXME should be able to skimp on the HE/HEK here when
410 HV_FETCH_JUST_SV is true. */
412 keysv = newSVpvn_utf8(key, klen, is_utf8);
414 keysv = newSVsv(keysv);
417 mg_copy(MUTABLE_SV(hv), sv, (char *)keysv, HEf_SVKEY);
419 /* grab a fake HE/HEK pair from the pool or make a new one */
420 entry = PL_hv_fetch_ent_mh;
422 PL_hv_fetch_ent_mh = HeNEXT(entry);
426 Newx(k, HEK_BASESIZE + sizeof(const SV *), char);
427 HeKEY_hek(entry) = (HEK*)k;
429 HeNEXT(entry) = NULL;
430 HeSVKEY_set(entry, keysv);
432 sv_upgrade(sv, SVt_PVLV);
434 /* so we can free entry when freeing sv */
435 LvTARG(sv) = MUTABLE_SV(entry);
437 /* XXX remove at some point? */
438 if (flags & HVhek_FREEKEY)
442 return entry ? (void *) &HeVAL(entry) : NULL;
444 return (void *) entry;
446 #ifdef ENV_IS_CASELESS
447 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
449 for (i = 0; i < klen; ++i)
450 if (isLOWER(key[i])) {
451 /* Would be nice if we had a routine to do the
452 copy and upercase in a single pass through. */
453 const char * const nkey = strupr(savepvn(key,klen));
454 /* Note that this fetch is for nkey (the uppercased
455 key) whereas the store is for key (the original) */
456 void *result = hv_common(hv, NULL, nkey, klen,
457 HVhek_FREEKEY, /* free nkey */
458 0 /* non-LVAL fetch */
459 | HV_DISABLE_UVAR_XKEY
462 0 /* compute hash */);
463 if (!result && (action & HV_FETCH_LVALUE)) {
464 /* This call will free key if necessary.
465 Do it this way to encourage compiler to tail
467 result = hv_common(hv, keysv, key, klen, flags,
469 | HV_DISABLE_UVAR_XKEY
473 if (flags & HVhek_FREEKEY)
481 else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
482 if (mg_find((const SV *)hv, PERL_MAGIC_tied)
483 || SvGMAGICAL((const SV *)hv)) {
484 /* I don't understand why hv_exists_ent has svret and sv,
485 whereas hv_exists only had one. */
486 SV * const svret = sv_newmortal();
489 if (keysv || is_utf8) {
491 keysv = newSVpvn_utf8(key, klen, TRUE);
493 keysv = newSVsv(keysv);
495 mg_copy(MUTABLE_SV(hv), sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
497 mg_copy(MUTABLE_SV(hv), sv, key, klen);
499 if (flags & HVhek_FREEKEY)
501 magic_existspack(svret, mg_find(sv, PERL_MAGIC_tiedelem));
502 /* This cast somewhat evil, but I'm merely using NULL/
503 not NULL to return the boolean exists.
504 And I know hv is not NULL. */
505 return SvTRUE(svret) ? (void *)hv : NULL;
507 #ifdef ENV_IS_CASELESS
508 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
509 /* XXX This code isn't UTF8 clean. */
510 char * const keysave = (char * const)key;
511 /* Will need to free this, so set FREEKEY flag. */
512 key = savepvn(key,klen);
513 key = (const char*)strupr((char*)key);
518 if (flags & HVhek_FREEKEY) {
521 flags |= HVhek_FREEKEY;
525 else if (action & HV_FETCH_ISSTORE) {
528 hv_magic_check (hv, &needs_copy, &needs_store);
530 const bool save_taint = TAINT_get;
531 if (keysv || is_utf8) {
533 keysv = newSVpvn_utf8(key, klen, TRUE);
536 TAINT_set(SvTAINTED(keysv));
537 keysv = sv_2mortal(newSVsv(keysv));
538 mg_copy(MUTABLE_SV(hv), val, (char*)keysv, HEf_SVKEY);
540 mg_copy(MUTABLE_SV(hv), val, key, klen);
543 TAINT_IF(save_taint);
544 #ifdef NO_TAINT_SUPPORT
545 PERL_UNUSED_VAR(save_taint);
548 if (flags & HVhek_FREEKEY)
552 #ifdef ENV_IS_CASELESS
553 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
554 /* XXX This code isn't UTF8 clean. */
555 const char *keysave = key;
556 /* Will need to free this, so set FREEKEY flag. */
557 key = savepvn(key,klen);
558 key = (const char*)strupr((char*)key);
563 if (flags & HVhek_FREEKEY) {
566 flags |= HVhek_FREEKEY;
574 if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
575 #ifdef DYNAMIC_ENV_FETCH /* if it's an %ENV lookup, we may get it on the fly */
576 || (SvRMAGICAL((const SV *)hv)
577 && mg_find((const SV *)hv, PERL_MAGIC_env))
582 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
584 HvARRAY(hv) = (HE**)array;
586 #ifdef DYNAMIC_ENV_FETCH
587 else if (action & HV_FETCH_ISEXISTS) {
588 /* for an %ENV exists, if we do an insert it's by a recursive
589 store call, so avoid creating HvARRAY(hv) right now. */
593 /* XXX remove at some point? */
594 if (flags & HVhek_FREEKEY)
601 if (is_utf8 && !(flags & HVhek_KEYCANONICAL)) {
602 char * const keysave = (char *)key;
603 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
607 flags &= ~HVhek_UTF8;
608 if (key != keysave) {
609 if (flags & HVhek_FREEKEY)
611 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
612 /* If the caller calculated a hash, it was on the sequence of
613 octets that are the UTF-8 form. We've now changed the sequence
614 of octets stored to that of the equivalent byte representation,
615 so the hash we need is different. */
621 if (keysv && (SvIsCOW_shared_hash(keysv)))
622 hash = SvSHARED_HASH(keysv);
624 PERL_HASH(hash, key, klen);
627 masked_flags = (flags & HVhek_MASK);
629 #ifdef DYNAMIC_ENV_FETCH
630 if (!HvARRAY(hv)) entry = NULL;
634 entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
636 for (; entry; entry = HeNEXT(entry)) {
637 if (HeHASH(entry) != hash) /* strings can't be equal */
639 if (HeKLEN(entry) != (I32)klen)
641 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
643 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
646 if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
647 if (HeKFLAGS(entry) != masked_flags) {
648 /* We match if HVhek_UTF8 bit in our flags and hash key's
649 match. But if entry was set previously with HVhek_WASUTF8
650 and key now doesn't (or vice versa) then we should change
651 the key's flag, as this is assignment. */
652 if (HvSHAREKEYS(hv)) {
653 /* Need to swap the key we have for a key with the flags we
654 need. As keys are shared we can't just write to the
655 flag, so we share the new one, unshare the old one. */
656 HEK * const new_hek = share_hek_flags(key, klen, hash,
658 unshare_hek (HeKEY_hek(entry));
659 HeKEY_hek(entry) = new_hek;
661 else if (hv == PL_strtab) {
662 /* PL_strtab is usually the only hash without HvSHAREKEYS,
663 so putting this test here is cheap */
664 if (flags & HVhek_FREEKEY)
666 Perl_croak(aTHX_ S_strtab_error,
667 action & HV_FETCH_LVALUE ? "fetch" : "store");
670 HeKFLAGS(entry) = masked_flags;
671 if (masked_flags & HVhek_ENABLEHVKFLAGS)
674 if (HeVAL(entry) == &PL_sv_placeholder) {
675 /* yes, can store into placeholder slot */
676 if (action & HV_FETCH_LVALUE) {
678 /* This preserves behaviour with the old hv_fetch
679 implementation which at this point would bail out
680 with a break; (at "if we find a placeholder, we
681 pretend we haven't found anything")
683 That break mean that if a placeholder were found, it
684 caused a call into hv_store, which in turn would
685 check magic, and if there is no magic end up pretty
686 much back at this point (in hv_store's code). */
689 /* LVAL fetch which actually needs a store. */
691 HvPLACEHOLDERS(hv)--;
694 if (val != &PL_sv_placeholder)
695 HvPLACEHOLDERS(hv)--;
698 } else if (action & HV_FETCH_ISSTORE) {
699 SvREFCNT_dec(HeVAL(entry));
702 } else if (HeVAL(entry) == &PL_sv_placeholder) {
703 /* if we find a placeholder, we pretend we haven't found
707 if (flags & HVhek_FREEKEY)
710 return entry ? (void *) &HeVAL(entry) : NULL;
714 #ifdef DYNAMIC_ENV_FETCH /* %ENV lookup? If so, try to fetch the value now */
715 if (!(action & HV_FETCH_ISSTORE)
716 && SvRMAGICAL((const SV *)hv)
717 && mg_find((const SV *)hv, PERL_MAGIC_env)) {
719 const char * const env = PerlEnv_ENVgetenv_len(key,&len);
721 sv = newSVpvn(env,len);
723 return hv_common(hv, keysv, key, klen, flags,
724 HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
730 if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
731 hv_notallowed(flags, key, klen,
732 "Attempt to access disallowed key '%"SVf"' in"
733 " a restricted hash");
735 if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
736 /* Not doing some form of store, so return failure. */
737 if (flags & HVhek_FREEKEY)
741 if (action & HV_FETCH_LVALUE) {
742 val = action & HV_FETCH_EMPTY_HE ? NULL : newSV(0);
744 /* At this point the old hv_fetch code would call to hv_store,
745 which in turn might do some tied magic. So we need to make that
746 magic check happen. */
747 /* gonna assign to this, so it better be there */
748 /* If a fetch-as-store fails on the fetch, then the action is to
749 recurse once into "hv_store". If we didn't do this, then that
750 recursive call would call the key conversion routine again.
751 However, as we replace the original key with the converted
752 key, this would result in a double conversion, which would show
753 up as a bug if the conversion routine is not idempotent. */
754 return hv_common(hv, keysv, key, klen, flags,
755 HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
757 /* XXX Surely that could leak if the fetch-was-store fails?
758 Just like the hv_fetch. */
762 /* Welcome to hv_store... */
765 /* Not sure if we can get here. I think the only case of oentry being
766 NULL is for %ENV with dynamic env fetch. But that should disappear
767 with magic in the previous code. */
770 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
772 HvARRAY(hv) = (HE**)array;
775 oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
778 /* share_hek_flags will do the free for us. This might be considered
781 HeKEY_hek(entry) = share_hek_flags(key, klen, hash, flags);
782 else if (hv == PL_strtab) {
783 /* PL_strtab is usually the only hash without HvSHAREKEYS, so putting
784 this test here is cheap */
785 if (flags & HVhek_FREEKEY)
787 Perl_croak(aTHX_ S_strtab_error,
788 action & HV_FETCH_LVALUE ? "fetch" : "store");
790 else /* gotta do the real thing */
791 HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
794 if (!*oentry && SvOOK(hv)) {
795 /* initial entry, and aux struct present. */
796 struct xpvhv_aux *const aux = HvAUX(hv);
797 if (aux->xhv_fill_lazy)
798 ++aux->xhv_fill_lazy;
801 #ifdef PERL_HASH_RANDOMIZE_KEYS
802 /* This logic semi-randomizes the insert order in a bucket.
803 * Either we insert into the top, or the slot below the top,
804 * making it harder to see if there is a collision. We also
805 * reset the iterator randomizer if there is one.
807 if ( *oentry && PL_HASH_RAND_BITS_ENABLED) {
809 PL_hash_rand_bits= ROTL_UV(PL_hash_rand_bits,1);
810 if ( PL_hash_rand_bits & 1 ) {
811 HeNEXT(entry) = HeNEXT(*oentry);
812 HeNEXT(*oentry) = entry;
814 HeNEXT(entry) = *oentry;
820 HeNEXT(entry) = *oentry;
823 #ifdef PERL_HASH_RANDOMIZE_KEYS
825 /* Currently this makes various tests warn in annoying ways.
826 * So Silenced for now. - Yves | bogus end of comment =>* /
827 if (HvAUX(hv)->xhv_riter != -1) {
828 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
829 "[TESTING] Inserting into a hash during each() traversal results in undefined behavior"
834 if (PL_HASH_RAND_BITS_ENABLED) {
835 if (PL_HASH_RAND_BITS_ENABLED == 1)
836 PL_hash_rand_bits += (PTRV)entry + 1; /* we don't bother to use ptr_hash here */
837 PL_hash_rand_bits= ROTL_UV(PL_hash_rand_bits,1);
839 HvAUX(hv)->xhv_rand= (U32)PL_hash_rand_bits;
843 if (val == &PL_sv_placeholder)
844 HvPLACEHOLDERS(hv)++;
845 if (masked_flags & HVhek_ENABLEHVKFLAGS)
848 xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
849 if ( DO_HSPLIT(xhv) ) {
850 const STRLEN oldsize = xhv->xhv_max + 1;
851 const U32 items = (U32)HvPLACEHOLDERS_get(hv);
853 if (items /* hash has placeholders */
854 && !SvREADONLY(hv) /* but is not a restricted hash */) {
855 /* If this hash previously was a "restricted hash" and had
856 placeholders, but the "restricted" flag has been turned off,
857 then the placeholders no longer serve any useful purpose.
858 However, they have the downsides of taking up RAM, and adding
859 extra steps when finding used values. It's safe to clear them
860 at this point, even though Storable rebuilds restricted hashes by
861 putting in all the placeholders (first) before turning on the
862 readonly flag, because Storable always pre-splits the hash.
863 If we're lucky, then we may clear sufficient placeholders to
864 avoid needing to split the hash at all. */
865 clear_placeholders(hv, items);
867 hsplit(hv, oldsize, oldsize * 2);
869 hsplit(hv, oldsize, oldsize * 2);
873 return entry ? (void *) &HeVAL(entry) : NULL;
875 return (void *) entry;
879 S_hv_magic_check(HV *hv, bool *needs_copy, bool *needs_store)
881 const MAGIC *mg = SvMAGIC(hv);
883 PERL_ARGS_ASSERT_HV_MAGIC_CHECK;
888 if (isUPPER(mg->mg_type)) {
890 if (mg->mg_type == PERL_MAGIC_tied) {
891 *needs_store = FALSE;
892 return; /* We've set all there is to set. */
895 mg = mg->mg_moremagic;
900 =for apidoc hv_scalar
902 Evaluates the hash in scalar context and returns the result. Handles magic when the hash is tied.
908 Perl_hv_scalar(pTHX_ HV *hv)
912 PERL_ARGS_ASSERT_HV_SCALAR;
914 if (SvRMAGICAL(hv)) {
915 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_tied);
917 return magic_scalarpack(hv, mg);
921 if (HvTOTALKEYS((const HV *)hv))
922 Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
923 (long)HvFILL(hv), (long)HvMAX(hv) + 1);
931 =for apidoc hv_delete
933 Deletes a key/value pair in the hash. The value's SV is removed from
934 the hash, made mortal, and returned to the caller. The absolute
935 value of C<klen> is the length of the key. If C<klen> is negative the
936 key is assumed to be in UTF-8-encoded Unicode. The C<flags> value
937 will normally be zero; if set to G_DISCARD then NULL will be returned.
938 NULL will also be returned if the key is not found.
940 =for apidoc hv_delete_ent
942 Deletes a key/value pair in the hash. The value SV is removed from the hash,
943 made mortal, and returned to the caller. The C<flags> value will normally be
944 zero; if set to G_DISCARD then NULL will be returned. NULL will also be
945 returned if the key is not found. C<hash> can be a valid precomputed hash
946 value, or 0 to ask for it to be computed.
952 S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
953 int k_flags, I32 d_flags, U32 hash)
959 HE *const *first_entry;
960 bool is_utf8 = (k_flags & HVhek_UTF8) ? TRUE : FALSE;
963 if (SvRMAGICAL(hv)) {
966 hv_magic_check (hv, &needs_copy, &needs_store);
970 entry = (HE *) hv_common(hv, keysv, key, klen,
971 k_flags & ~HVhek_FREEKEY,
972 HV_FETCH_LVALUE|HV_DISABLE_UVAR_XKEY,
974 sv = entry ? HeVAL(entry) : NULL;
980 if (mg_find(sv, PERL_MAGIC_tiedelem)) {
981 /* No longer an element */
982 sv_unmagic(sv, PERL_MAGIC_tiedelem);
985 return NULL; /* element cannot be deleted */
987 #ifdef ENV_IS_CASELESS
988 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
989 /* XXX This code isn't UTF8 clean. */
990 keysv = newSVpvn_flags(key, klen, SVs_TEMP);
991 if (k_flags & HVhek_FREEKEY) {
994 key = strupr(SvPVX(keysv));
1003 xhv = (XPVHV*)SvANY(hv);
1007 if (is_utf8 && !(k_flags & HVhek_KEYCANONICAL)) {
1008 const char * const keysave = key;
1009 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
1012 k_flags |= HVhek_UTF8;
1014 k_flags &= ~HVhek_UTF8;
1015 if (key != keysave) {
1016 if (k_flags & HVhek_FREEKEY) {
1017 /* This shouldn't happen if our caller does what we expect,
1018 but strictly the API allows it. */
1021 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
1023 HvHASKFLAGS_on(MUTABLE_SV(hv));
1027 if (keysv && (SvIsCOW_shared_hash(keysv)))
1028 hash = SvSHARED_HASH(keysv);
1030 PERL_HASH(hash, key, klen);
1033 masked_flags = (k_flags & HVhek_MASK);
1035 first_entry = oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
1037 for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
1039 U8 mro_changes = 0; /* 1 = isa; 2 = package moved */
1043 if (HeHASH(entry) != hash) /* strings can't be equal */
1045 if (HeKLEN(entry) != (I32)klen)
1047 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
1049 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
1052 if (hv == PL_strtab) {
1053 if (k_flags & HVhek_FREEKEY)
1055 Perl_croak(aTHX_ S_strtab_error, "delete");
1058 /* if placeholder is here, it's already been deleted.... */
1059 if (HeVAL(entry) == &PL_sv_placeholder) {
1060 if (k_flags & HVhek_FREEKEY)
1064 if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))
1065 && !SvIsCOW(HeVAL(entry))) {
1066 hv_notallowed(k_flags, key, klen,
1067 "Attempt to delete readonly key '%"SVf"' from"
1068 " a restricted hash");
1070 if (k_flags & HVhek_FREEKEY)
1073 /* If this is a stash and the key ends with ::, then someone is
1074 * deleting a package.
1076 if (HeVAL(entry) && HvENAME_get(hv)) {
1077 gv = (GV *)HeVAL(entry);
1078 if (keysv) key = SvPV(keysv, klen);
1080 (klen > 1 && key[klen-2] == ':' && key[klen-1] == ':')
1082 (klen == 1 && key[0] == ':')
1084 && (klen != 6 || hv!=PL_defstash || memNE(key,"main::",6))
1085 && SvTYPE(gv) == SVt_PVGV && (stash = GvHV((GV *)gv))
1086 && HvENAME_get(stash)) {
1087 /* A previous version of this code checked that the
1088 * GV was still in the symbol table by fetching the
1089 * GV with its name. That is not necessary (and
1090 * sometimes incorrect), as HvENAME cannot be set
1091 * on hv if it is not in the symtab. */
1093 /* Hang on to it for a bit. */
1094 SvREFCNT_inc_simple_void_NN(
1095 sv_2mortal((SV *)gv)
1098 else if (klen == 3 && strnEQ(key, "ISA", 3))
1102 sv = d_flags & G_DISCARD ? HeVAL(entry) : sv_2mortal(HeVAL(entry));
1103 HeVAL(entry) = &PL_sv_placeholder;
1105 /* deletion of method from stash */
1106 if (isGV(sv) && isGV_with_GP(sv) && GvCVu(sv)
1108 mro_method_changed_in(hv);
1112 * If a restricted hash, rather than really deleting the entry, put
1113 * a placeholder there. This marks the key as being "approved", so
1114 * we can still access via not-really-existing key without raising
1118 /* We'll be saving this slot, so the number of allocated keys
1119 * doesn't go down, but the number placeholders goes up */
1120 HvPLACEHOLDERS(hv)++;
1122 *oentry = HeNEXT(entry);
1123 if(!*first_entry && SvOOK(hv)) {
1124 /* removed last entry, and aux struct present. */
1125 struct xpvhv_aux *const aux = HvAUX(hv);
1126 if (aux->xhv_fill_lazy)
1127 --aux->xhv_fill_lazy;
1129 if (SvOOK(hv) && entry == HvAUX(hv)->xhv_eiter /* HvEITER(hv) */)
1132 if (SvOOK(hv) && HvLAZYDEL(hv) &&
1133 entry == HeNEXT(HvAUX(hv)->xhv_eiter))
1134 HeNEXT(HvAUX(hv)->xhv_eiter) = HeNEXT(entry);
1135 hv_free_ent(hv, entry);
1137 xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
1138 if (xhv->xhv_keys == 0)
1139 HvHASKFLAGS_off(hv);
1142 if (d_flags & G_DISCARD) {
1147 if (mro_changes == 1) mro_isa_changed_in(hv);
1148 else if (mro_changes == 2)
1149 mro_package_moved(NULL, stash, gv, 1);
1153 if (SvREADONLY(hv)) {
1154 hv_notallowed(k_flags, key, klen,
1155 "Attempt to delete disallowed key '%"SVf"' from"
1156 " a restricted hash");
1159 if (k_flags & HVhek_FREEKEY)
1165 S_hsplit(pTHX_ HV *hv, STRLEN const oldsize, STRLEN newsize)
1169 char *a = (char*) HvARRAY(hv);
1172 PERL_ARGS_ASSERT_HSPLIT;
1174 /*PerlIO_printf(PerlIO_stderr(), "hsplit called for %p which had %d\n",
1175 (void*)hv, (int) oldsize);*/
1178 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1179 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1184 #ifdef PERL_HASH_RANDOMIZE_KEYS
1185 /* the idea of this is that we create a "random" value by hashing the address of
1186 * the array, we then use the low bit to decide if we insert at the top, or insert
1187 * second from top. After each such insert we rotate the hashed value. So we can
1188 * use the same hashed value over and over, and in normal build environments use
1189 * very few ops to do so. ROTL32() should produce a single machine operation. */
1190 if (PL_HASH_RAND_BITS_ENABLED) {
1191 if (PL_HASH_RAND_BITS_ENABLED == 1)
1192 PL_hash_rand_bits += ptr_hash((PTRV)a);
1193 PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,1);
1198 struct xpvhv_aux *const dest
1199 = (struct xpvhv_aux*) &a[newsize * sizeof(HE*)];
1200 Move(&a[oldsize * sizeof(HE*)], dest, 1, struct xpvhv_aux);
1201 /* we reset the iterator's xhv_rand as well, so they get a totally new ordering */
1202 #ifdef PERL_HASH_RANDOMIZE_KEYS
1203 dest->xhv_rand = (U32)PL_hash_rand_bits;
1205 /* For now, just reset the lazy fill counter.
1206 It would be possible to update the counter in the code below
1208 dest->xhv_fill_lazy = 0;
1212 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1213 HvMAX(hv) = --newsize;
1214 HvARRAY(hv) = (HE**) a;
1216 if (!HvTOTALKEYS(hv)) /* skip rest if no entries */
1221 HE **oentry = aep + i;
1224 if (!entry) /* non-existent */
1227 U32 j = (HeHASH(entry) & newsize);
1229 *oentry = HeNEXT(entry);
1230 #ifdef PERL_HASH_RANDOMIZE_KEYS
1231 /* if the target cell is empty or PL_HASH_RAND_BITS_ENABLED is false
1232 * insert to top, otherwise rotate the bucket rand 1 bit,
1233 * and use the new low bit to decide if we insert at top,
1234 * or next from top. IOW, we only rotate on a collision.*/
1235 if (aep[j] && PL_HASH_RAND_BITS_ENABLED) {
1236 PL_hash_rand_bits+= ROTL_UV(HeHASH(entry), 17);
1237 PL_hash_rand_bits= ROTL_UV(PL_hash_rand_bits,1);
1238 if (PL_hash_rand_bits & 1) {
1239 HeNEXT(entry)= HeNEXT(aep[j]);
1240 HeNEXT(aep[j])= entry;
1242 /* Note, this is structured in such a way as the optimizer
1243 * should eliminate the duplicated code here and below without
1244 * us needing to explicitly use a goto. */
1245 HeNEXT(entry) = aep[j];
1251 /* see comment above about duplicated code */
1252 HeNEXT(entry) = aep[j];
1257 oentry = &HeNEXT(entry);
1261 } while (i++ < oldsize);
1265 Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
1268 XPVHV* xhv = (XPVHV*)SvANY(hv);
1269 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1273 PERL_ARGS_ASSERT_HV_KSPLIT;
1275 newsize = (I32) newmax; /* possible truncation here */
1276 if (newsize != newmax || newmax <= oldsize)
1278 while ((newsize & (1 + ~newsize)) != newsize) {
1279 newsize &= ~(newsize & (1 + ~newsize)); /* get proper power of 2 */
1281 if (newsize < newmax)
1283 if (newsize < newmax)
1284 return; /* overflow detection */
1286 a = (char *) HvARRAY(hv);
1288 hsplit(hv, oldsize, newsize);
1290 Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1291 xhv->xhv_max = --newsize;
1292 HvARRAY(hv) = (HE **) a;
1296 /* IMO this should also handle cases where hv_max is smaller than hv_keys
1297 * as tied hashes could play silly buggers and mess us around. We will
1298 * do the right thing during hv_store() afterwards, but still - Yves */
1299 #define HV_SET_MAX_ADJUSTED_FOR_KEYS(hv,hv_max,hv_keys) STMT_START {\
1300 /* Can we use fewer buckets? (hv_max is always 2^n-1) */ \
1301 if (hv_max < PERL_HASH_DEFAULT_HvMAX) { \
1302 hv_max = PERL_HASH_DEFAULT_HvMAX; \
1304 while (hv_max > PERL_HASH_DEFAULT_HvMAX && hv_max + 1 >= hv_keys * 2) \
1305 hv_max = hv_max / 2; \
1307 HvMAX(hv) = hv_max; \
1312 Perl_newHVhv(pTHX_ HV *ohv)
1315 HV * const hv = newHV();
1318 if (!ohv || (!HvTOTALKEYS(ohv) && !SvMAGICAL((const SV *)ohv)))
1320 hv_max = HvMAX(ohv);
1322 if (!SvMAGICAL((const SV *)ohv)) {
1323 /* It's an ordinary hash, so copy it fast. AMS 20010804 */
1325 const bool shared = !!HvSHAREKEYS(ohv);
1326 HE **ents, ** const oents = (HE **)HvARRAY(ohv);
1328 Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
1331 /* In each bucket... */
1332 for (i = 0; i <= hv_max; i++) {
1334 HE *oent = oents[i];
1341 /* Copy the linked list of entries. */
1342 for (; oent; oent = HeNEXT(oent)) {
1343 const U32 hash = HeHASH(oent);
1344 const char * const key = HeKEY(oent);
1345 const STRLEN len = HeKLEN(oent);
1346 const int flags = HeKFLAGS(oent);
1347 HE * const ent = new_HE();
1348 SV *const val = HeVAL(oent);
1350 HeVAL(ent) = SvIMMORTAL(val) ? val : newSVsv(val);
1352 = shared ? share_hek_flags(key, len, hash, flags)
1353 : save_hek_flags(key, len, hash, flags);
1364 HvTOTALKEYS(hv) = HvTOTALKEYS(ohv);
1368 /* Iterate over ohv, copying keys and values one at a time. */
1370 const I32 riter = HvRITER_get(ohv);
1371 HE * const eiter = HvEITER_get(ohv);
1372 STRLEN hv_keys = HvTOTALKEYS(ohv);
1374 HV_SET_MAX_ADJUSTED_FOR_KEYS(hv,hv_max,hv_keys);
1377 while ((entry = hv_iternext_flags(ohv, 0))) {
1378 SV *val = hv_iterval(ohv,entry);
1379 SV * const keysv = HeSVKEY(entry);
1380 val = SvIMMORTAL(val) ? val : newSVsv(val);
1382 (void)hv_store_ent(hv, keysv, val, 0);
1384 (void)hv_store_flags(hv, HeKEY(entry), HeKLEN(entry), val,
1385 HeHASH(entry), HeKFLAGS(entry));
1387 HvRITER_set(ohv, riter);
1388 HvEITER_set(ohv, eiter);
1395 =for apidoc Am|HV *|hv_copy_hints_hv|HV *ohv
1397 A specialised version of L</newHVhv> for copying C<%^H>. I<ohv> must be
1398 a pointer to a hash (which may have C<%^H> magic, but should be generally
1399 non-magical), or C<NULL> (interpreted as an empty hash). The content
1400 of I<ohv> is copied to a new hash, which has the C<%^H>-specific magic
1401 added to it. A pointer to the new hash is returned.
1407 Perl_hv_copy_hints_hv(pTHX_ HV *const ohv)
1409 HV * const hv = newHV();
1412 STRLEN hv_max = HvMAX(ohv);
1413 STRLEN hv_keys = HvTOTALKEYS(ohv);
1415 const I32 riter = HvRITER_get(ohv);
1416 HE * const eiter = HvEITER_get(ohv);
1421 HV_SET_MAX_ADJUSTED_FOR_KEYS(hv,hv_max,hv_keys);
1424 while ((entry = hv_iternext_flags(ohv, 0))) {
1425 SV *const sv = newSVsv(hv_iterval(ohv,entry));
1426 SV *heksv = HeSVKEY(entry);
1427 if (!heksv && sv) heksv = newSVhek(HeKEY_hek(entry));
1428 if (sv) sv_magic(sv, NULL, PERL_MAGIC_hintselem,
1429 (char *)heksv, HEf_SVKEY);
1430 if (heksv == HeSVKEY(entry))
1431 (void)hv_store_ent(hv, heksv, sv, 0);
1433 (void)hv_common(hv, heksv, HeKEY(entry), HeKLEN(entry),
1434 HeKFLAGS(entry), HV_FETCH_ISSTORE|HV_FETCH_JUST_SV, sv, HeHASH(entry));
1435 SvREFCNT_dec_NN(heksv);
1438 HvRITER_set(ohv, riter);
1439 HvEITER_set(ohv, eiter);
1441 SvREFCNT_inc_simple_void_NN(hv);
1444 hv_magic(hv, NULL, PERL_MAGIC_hints);
1447 #undef HV_SET_MAX_ADJUSTED_FOR_KEYS
1449 /* like hv_free_ent, but returns the SV rather than freeing it */
1451 S_hv_free_ent_ret(pTHX_ HV *hv, HE *entry)
1456 PERL_ARGS_ASSERT_HV_FREE_ENT_RET;
1459 if (HeKLEN(entry) == HEf_SVKEY) {
1460 SvREFCNT_dec(HeKEY_sv(entry));
1461 Safefree(HeKEY_hek(entry));
1463 else if (HvSHAREKEYS(hv))
1464 unshare_hek(HeKEY_hek(entry));
1466 Safefree(HeKEY_hek(entry));
1473 Perl_hv_free_ent(pTHX_ HV *hv, HE *entry)
1478 PERL_ARGS_ASSERT_HV_FREE_ENT;
1482 val = hv_free_ent_ret(hv, entry);
1488 Perl_hv_delayfree_ent(pTHX_ HV *hv, HE *entry)
1492 PERL_ARGS_ASSERT_HV_DELAYFREE_ENT;
1496 /* SvREFCNT_inc to counter the SvREFCNT_dec in hv_free_ent */
1497 sv_2mortal(SvREFCNT_inc(HeVAL(entry))); /* free between statements */
1498 if (HeKLEN(entry) == HEf_SVKEY) {
1499 sv_2mortal(SvREFCNT_inc(HeKEY_sv(entry)));
1501 hv_free_ent(hv, entry);
1505 =for apidoc hv_clear
1507 Frees the all the elements of a hash, leaving it empty.
1508 The XS equivalent of C<%hash = ()>. See also L</hv_undef>.
1510 If any destructors are triggered as a result, the hv itself may
1517 Perl_hv_clear(pTHX_ HV *hv)
1524 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1526 xhv = (XPVHV*)SvANY(hv);
1529 SAVEFREESV(SvREFCNT_inc_simple_NN(hv));
1530 if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
1531 /* restricted hash: convert all keys to placeholders */
1533 for (i = 0; i <= xhv->xhv_max; i++) {
1534 HE *entry = (HvARRAY(hv))[i];
1535 for (; entry; entry = HeNEXT(entry)) {
1536 /* not already placeholder */
1537 if (HeVAL(entry) != &PL_sv_placeholder) {
1539 if (SvREADONLY(HeVAL(entry)) && !SvIsCOW(HeVAL(entry))) {
1540 SV* const keysv = hv_iterkeysv(entry);
1541 Perl_croak_nocontext(
1542 "Attempt to delete readonly key '%"SVf"' from a restricted hash",
1545 SvREFCNT_dec_NN(HeVAL(entry));
1547 HeVAL(entry) = &PL_sv_placeholder;
1548 HvPLACEHOLDERS(hv)++;
1555 HvPLACEHOLDERS_set(hv, 0);
1558 mg_clear(MUTABLE_SV(hv));
1560 HvHASKFLAGS_off(hv);
1564 mro_isa_changed_in(hv);
1565 HvEITER_set(hv, NULL);
1571 =for apidoc hv_clear_placeholders
1573 Clears any placeholders from a hash. If a restricted hash has any of its keys
1574 marked as readonly and the key is subsequently deleted, the key is not actually
1575 deleted but is marked by assigning it a value of &PL_sv_placeholder. This tags
1576 it so it will be ignored by future operations such as iterating over the hash,
1577 but will still allow the hash to have a value reassigned to the key at some
1578 future point. This function clears any such placeholder keys from the hash.
1579 See Hash::Util::lock_keys() for an example of its use.
1585 Perl_hv_clear_placeholders(pTHX_ HV *hv)
1588 const U32 items = (U32)HvPLACEHOLDERS_get(hv);
1590 PERL_ARGS_ASSERT_HV_CLEAR_PLACEHOLDERS;
1593 clear_placeholders(hv, items);
1597 S_clear_placeholders(pTHX_ HV *hv, U32 items)
1602 PERL_ARGS_ASSERT_CLEAR_PLACEHOLDERS;
1609 /* Loop down the linked list heads */
1610 HE **oentry = &(HvARRAY(hv))[i];
1613 while ((entry = *oentry)) {
1614 if (HeVAL(entry) == &PL_sv_placeholder) {
1615 *oentry = HeNEXT(entry);
1616 if (entry == HvEITER_get(hv))
1619 if (SvOOK(hv) && HvLAZYDEL(hv) &&
1620 entry == HeNEXT(HvAUX(hv)->xhv_eiter))
1621 HeNEXT(HvAUX(hv)->xhv_eiter) = HeNEXT(entry);
1622 hv_free_ent(hv, entry);
1627 HvTOTALKEYS(hv) -= (IV)HvPLACEHOLDERS_get(hv);
1628 if (HvUSEDKEYS(hv) == 0)
1629 HvHASKFLAGS_off(hv);
1630 HvPLACEHOLDERS_set(hv, 0);
1634 oentry = &HeNEXT(entry);
1638 /* You can't get here, hence assertion should always fail. */
1639 assert (items == 0);
1644 S_hfreeentries(pTHX_ HV *hv)
1647 XPVHV * const xhv = (XPVHV*)SvANY(hv);
1650 PERL_ARGS_ASSERT_HFREEENTRIES;
1652 while ((sv = Perl_hfree_next_entry(aTHX_ hv, &index))||xhv->xhv_keys) {
1658 /* hfree_next_entry()
1659 * For use only by S_hfreeentries() and sv_clear().
1660 * Delete the next available HE from hv and return the associated SV.
1661 * Returns null on empty hash. Nevertheless null is not a reliable
1662 * indicator that the hash is empty, as the deleted entry may have a
1664 * indexp is a pointer to the current index into HvARRAY. The index should
1665 * initially be set to 0. hfree_next_entry() may update it. */
1668 Perl_hfree_next_entry(pTHX_ HV *hv, STRLEN *indexp)
1670 struct xpvhv_aux *iter;
1674 STRLEN orig_index = *indexp;
1677 PERL_ARGS_ASSERT_HFREE_NEXT_ENTRY;
1679 if (SvOOK(hv) && ((iter = HvAUX(hv)))) {
1680 if ((entry = iter->xhv_eiter)) {
1681 /* the iterator may get resurrected after each
1682 * destructor call, so check each time */
1683 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1685 hv_free_ent(hv, entry);
1686 /* warning: at this point HvARRAY may have been
1687 * re-allocated, HvMAX changed etc */
1689 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1690 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
1691 #ifdef PERL_HASH_RANDOMIZE_KEYS
1692 iter->xhv_last_rand = iter->xhv_rand;
1695 /* Reset any cached HvFILL() to "unknown". It's unlikely that anyone
1696 will actually call HvFILL() on a hash under destruction, so it
1697 seems pointless attempting to track the number of keys remaining.
1698 But if they do, we want to reset it again. */
1699 if (iter->xhv_fill_lazy)
1700 iter->xhv_fill_lazy = 0;
1703 if (!((XPVHV*)SvANY(hv))->xhv_keys)
1706 array = HvARRAY(hv);
1708 while ( ! ((entry = array[*indexp])) ) {
1709 if ((*indexp)++ >= HvMAX(hv))
1711 assert(*indexp != orig_index);
1713 array[*indexp] = HeNEXT(entry);
1714 ((XPVHV*) SvANY(hv))->xhv_keys--;
1716 if ( PL_phase != PERL_PHASE_DESTRUCT && HvENAME(hv)
1717 && HeVAL(entry) && isGV(HeVAL(entry))
1718 && GvHV(HeVAL(entry)) && HvENAME(GvHV(HeVAL(entry)))
1721 const char * const key = HePV(entry,klen);
1722 if ((klen > 1 && key[klen-1]==':' && key[klen-2]==':')
1723 || (klen == 1 && key[0] == ':')) {
1725 NULL, GvHV(HeVAL(entry)),
1726 (GV *)HeVAL(entry), 0
1730 return hv_free_ent_ret(hv, entry);
1735 =for apidoc hv_undef
1737 Undefines the hash. The XS equivalent of C<undef(%hash)>.
1739 As well as freeing all the elements of the hash (like hv_clear()), this
1740 also frees any auxiliary data and storage associated with the hash.
1742 If any destructors are triggered as a result, the hv itself may
1745 See also L</hv_clear>.
1751 Perl_hv_undef_flags(pTHX_ HV *hv, U32 flags)
1756 const bool save = !!SvREFCNT(hv);
1760 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1761 xhv = (XPVHV*)SvANY(hv);
1763 /* The name must be deleted before the call to hfreeeeentries so that
1764 CVs are anonymised properly. But the effective name must be pre-
1765 served until after that call (and only deleted afterwards if the
1766 call originated from sv_clear). For stashes with one name that is
1767 both the canonical name and the effective name, hv_name_set has to
1768 allocate an array for storing the effective name. We can skip that
1769 during global destruction, as it does not matter where the CVs point
1770 if they will be freed anyway. */
1771 /* note that the code following prior to hfreeentries is duplicated
1772 * in sv_clear(), and changes here should be done there too */
1773 if (PL_phase != PERL_PHASE_DESTRUCT && (name = HvNAME(hv))) {
1774 if (PL_stashcache) {
1775 DEBUG_o(Perl_deb(aTHX_ "hv_undef_flags clearing PL_stashcache for '%"
1776 HEKf"'\n", HvNAME_HEK(hv)));
1777 (void)hv_delete(PL_stashcache, name,
1778 HEK_UTF8(HvNAME_HEK(hv)) ? -HvNAMELEN_get(hv) : HvNAMELEN_get(hv),
1782 hv_name_set(hv, NULL, 0, 0);
1786 SAVEFREESV(SvREFCNT_inc_simple_NN(hv));
1790 struct xpvhv_aux * const aux = HvAUX(hv);
1791 struct mro_meta *meta;
1793 if ((name = HvENAME_get(hv))) {
1794 if (PL_phase != PERL_PHASE_DESTRUCT)
1795 mro_isa_changed_in(hv);
1796 if (PL_stashcache) {
1797 DEBUG_o(Perl_deb(aTHX_ "hv_undef_flags clearing PL_stashcache for effective name '%"
1798 HEKf"'\n", HvENAME_HEK(hv)));
1800 PL_stashcache, name,
1801 HEK_UTF8(HvENAME_HEK(hv)) ? -HvENAMELEN_get(hv) : HvENAMELEN_get(hv),
1807 /* If this call originated from sv_clear, then we must check for
1808 * effective names that need freeing, as well as the usual name. */
1810 if (flags & HV_NAME_SETALL ? !!aux->xhv_name_u.xhvnameu_name : !!name) {
1811 if (name && PL_stashcache) {
1812 DEBUG_o(Perl_deb(aTHX_ "hv_undef_flags clearing PL_stashcache for name '%"
1813 HEKf"'\n", HvNAME_HEK(hv)));
1814 (void)hv_delete(PL_stashcache, name, (HEK_UTF8(HvNAME_HEK(hv)) ? -HvNAMELEN_get(hv) : HvNAMELEN_get(hv)), G_DISCARD);
1816 hv_name_set(hv, NULL, 0, flags);
1818 if((meta = aux->xhv_mro_meta)) {
1819 if (meta->mro_linear_all) {
1820 SvREFCNT_dec_NN(meta->mro_linear_all);
1821 /* mro_linear_current is just acting as a shortcut pointer,
1825 /* Only the current MRO is stored, so this owns the data.
1827 SvREFCNT_dec(meta->mro_linear_current);
1828 SvREFCNT_dec(meta->mro_nextmethod);
1829 SvREFCNT_dec(meta->isa);
1831 aux->xhv_mro_meta = NULL;
1833 SvREFCNT_dec(aux->xhv_super);
1834 if (!aux->xhv_name_u.xhvnameu_name && ! aux->xhv_backreferences)
1835 SvFLAGS(hv) &= ~SVf_OOK;
1838 Safefree(HvARRAY(hv));
1839 xhv->xhv_max = PERL_HASH_DEFAULT_HvMAX; /* HvMAX(hv) = 7 (it's a normal hash) */
1842 /* if we're freeing the HV, the SvMAGIC field has been reused for
1843 * other purposes, and so there can't be any placeholder magic */
1845 HvPLACEHOLDERS_set(hv, 0);
1848 mg_clear(MUTABLE_SV(hv));
1855 Returns the number of hash buckets that happen to be in use. This function is
1856 wrapped by the macro C<HvFILL>.
1858 Previously this value was always stored in the HV structure, which created an
1859 overhead on every hash (and pretty much every object) for something that was
1860 rarely used. Now we calculate it on demand the first time that it is needed,
1861 and cache it if that calculation is going to be costly to repeat. The cached
1862 value is updated by insertions and deletions, but (currently) discarded if
1869 Perl_hv_fill(pTHX_ HV *const hv)
1872 HE **ents = HvARRAY(hv);
1873 struct xpvhv_aux *aux = SvOOK(hv) ? HvAUX(hv) : NULL;
1875 PERL_ARGS_ASSERT_HV_FILL;
1877 /* No keys implies no buckets used.
1878 One key can only possibly mean one bucket used. */
1879 if (HvTOTALKEYS(hv) < 2)
1880 return HvTOTALKEYS(hv);
1883 if (aux && aux->xhv_fill_lazy)
1884 return aux->xhv_fill_lazy;
1888 HE *const *const last = ents + HvMAX(hv);
1889 count = last + 1 - ents;
1894 } while (++ents <= last);
1898 if (aux->xhv_fill_lazy)
1899 assert(aux->xhv_fill_lazy == count);
1901 aux->xhv_fill_lazy = count;
1902 } else if (HvMAX(hv) >= HV_FILL_THRESHOLD) {
1903 aux = hv_auxinit(hv);
1904 aux->xhv_fill_lazy = count;
1909 /* hash a pointer to a U32 - Used in the hash traversal randomization
1910 * and bucket order randomization code
1912 * this code was derived from Sereal, which was derived from autobox.
1915 PERL_STATIC_INLINE U32 S_ptr_hash(PTRV u) {
1918 * This is one of Thomas Wang's hash functions for 64-bit integers from:
1919 * http://www.concentric.net/~Ttwang/tech/inthash.htm
1921 u = (~u) + (u << 18);
1929 * This is one of Bob Jenkins' hash functions for 32-bit integers
1930 * from: http://burtleburtle.net/bob/hash/integer.html
1932 u = (u + 0x7ed55d16) + (u << 12);
1933 u = (u ^ 0xc761c23c) ^ (u >> 19);
1934 u = (u + 0x165667b1) + (u << 5);
1935 u = (u + 0xd3a2646c) ^ (u << 9);
1936 u = (u + 0xfd7046c5) + (u << 3);
1937 u = (u ^ 0xb55a4f09) ^ (u >> 16);
1943 static struct xpvhv_aux*
1944 S_hv_auxinit(pTHX_ HV *hv) {
1945 struct xpvhv_aux *iter;
1948 PERL_ARGS_ASSERT_HV_AUXINIT;
1952 Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1953 + sizeof(struct xpvhv_aux), char);
1955 array = (char *) HvARRAY(hv);
1956 Renew(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1957 + sizeof(struct xpvhv_aux), char);
1959 HvARRAY(hv) = (HE**)array;
1962 #ifdef PERL_HASH_RANDOMIZE_KEYS
1963 if (PL_HASH_RAND_BITS_ENABLED) {
1964 /* mix in some new state to PL_hash_rand_bits to "randomize" the traversal order*/
1965 if (PL_HASH_RAND_BITS_ENABLED == 1)
1966 PL_hash_rand_bits += ptr_hash((PTRV)array);
1967 PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,1);
1969 iter->xhv_rand = (U32)PL_hash_rand_bits;
1975 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1976 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
1977 #ifdef PERL_HASH_RANDOMIZE_KEYS
1978 iter->xhv_last_rand = iter->xhv_rand;
1980 iter->xhv_fill_lazy = 0;
1981 iter->xhv_name_u.xhvnameu_name = 0;
1982 iter->xhv_name_count = 0;
1983 iter->xhv_backreferences = 0;
1984 iter->xhv_mro_meta = NULL;
1985 iter->xhv_super = NULL;
1990 =for apidoc hv_iterinit
1992 Prepares a starting point to traverse a hash table. Returns the number of
1993 keys in the hash (i.e. the same as C<HvUSEDKEYS(hv)>). The return value is
1994 currently only meaningful for hashes without tie magic.
1996 NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
1997 hash buckets that happen to be in use. If you still need that esoteric
1998 value, you can get it through the macro C<HvFILL(hv)>.
2005 Perl_hv_iterinit(pTHX_ HV *hv)
2007 PERL_ARGS_ASSERT_HV_ITERINIT;
2009 /* FIXME: Are we not NULL, or do we croak? Place bets now! */
2012 Perl_croak(aTHX_ "Bad hash");
2015 struct xpvhv_aux * const iter = HvAUX(hv);
2016 HE * const entry = iter->xhv_eiter; /* HvEITER(hv) */
2017 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
2019 hv_free_ent(hv, entry);
2021 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2022 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
2023 #ifdef PERL_HASH_RANDOMIZE_KEYS
2024 iter->xhv_last_rand = iter->xhv_rand;
2030 /* used to be xhv->xhv_fill before 5.004_65 */
2031 return HvTOTALKEYS(hv);
2035 Perl_hv_riter_p(pTHX_ HV *hv) {
2036 struct xpvhv_aux *iter;
2038 PERL_ARGS_ASSERT_HV_RITER_P;
2041 Perl_croak(aTHX_ "Bad hash");
2043 iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2044 return &(iter->xhv_riter);
2048 Perl_hv_eiter_p(pTHX_ HV *hv) {
2049 struct xpvhv_aux *iter;
2051 PERL_ARGS_ASSERT_HV_EITER_P;
2054 Perl_croak(aTHX_ "Bad hash");
2056 iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2057 return &(iter->xhv_eiter);
2061 Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
2062 struct xpvhv_aux *iter;
2064 PERL_ARGS_ASSERT_HV_RITER_SET;
2067 Perl_croak(aTHX_ "Bad hash");
2075 iter = hv_auxinit(hv);
2077 iter->xhv_riter = riter;
2081 Perl_hv_rand_set(pTHX_ HV *hv, U32 new_xhv_rand) {
2082 struct xpvhv_aux *iter;
2084 PERL_ARGS_ASSERT_HV_RAND_SET;
2086 #ifdef PERL_HASH_RANDOMIZE_KEYS
2088 Perl_croak(aTHX_ "Bad hash");
2093 iter = hv_auxinit(hv);
2095 iter->xhv_rand = new_xhv_rand;
2097 Perl_croak(aTHX_ "This Perl has not been built with support for randomized hash key traversal but something called Perl_hv_rand_set().");
2102 Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
2103 struct xpvhv_aux *iter;
2105 PERL_ARGS_ASSERT_HV_EITER_SET;
2108 Perl_croak(aTHX_ "Bad hash");
2113 /* 0 is the default so don't go malloc()ing a new structure just to
2118 iter = hv_auxinit(hv);
2120 iter->xhv_eiter = eiter;
2124 Perl_hv_name_set(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2127 struct xpvhv_aux *iter;
2131 PERL_ARGS_ASSERT_HV_NAME_SET;
2134 Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
2138 if (iter->xhv_name_u.xhvnameu_name) {
2139 if(iter->xhv_name_count) {
2140 if(flags & HV_NAME_SETALL) {
2141 HEK ** const name = HvAUX(hv)->xhv_name_u.xhvnameu_names;
2142 HEK **hekp = name + (
2143 iter->xhv_name_count < 0
2144 ? -iter->xhv_name_count
2145 : iter->xhv_name_count
2147 while(hekp-- > name+1)
2148 unshare_hek_or_pvn(*hekp, 0, 0, 0);
2149 /* The first elem may be null. */
2150 if(*name) unshare_hek_or_pvn(*name, 0, 0, 0);
2152 spot = &iter->xhv_name_u.xhvnameu_name;
2153 iter->xhv_name_count = 0;
2156 if(iter->xhv_name_count > 0) {
2157 /* shift some things over */
2159 iter->xhv_name_u.xhvnameu_names, iter->xhv_name_count + 1, HEK *
2161 spot = iter->xhv_name_u.xhvnameu_names;
2162 spot[iter->xhv_name_count] = spot[1];
2164 iter->xhv_name_count = -(iter->xhv_name_count + 1);
2166 else if(*(spot = iter->xhv_name_u.xhvnameu_names)) {
2167 unshare_hek_or_pvn(*spot, 0, 0, 0);
2171 else if (flags & HV_NAME_SETALL) {
2172 unshare_hek_or_pvn(iter->xhv_name_u.xhvnameu_name, 0, 0, 0);
2173 spot = &iter->xhv_name_u.xhvnameu_name;
2176 HEK * const existing_name = iter->xhv_name_u.xhvnameu_name;
2177 Newx(iter->xhv_name_u.xhvnameu_names, 2, HEK *);
2178 iter->xhv_name_count = -2;
2179 spot = iter->xhv_name_u.xhvnameu_names;
2180 spot[1] = existing_name;
2183 else { spot = &iter->xhv_name_u.xhvnameu_name; iter->xhv_name_count = 0; }
2188 iter = hv_auxinit(hv);
2189 spot = &iter->xhv_name_u.xhvnameu_name;
2191 PERL_HASH(hash, name, len);
2192 *spot = name ? share_hek(name, flags & SVf_UTF8 ? -(I32)len : (I32)len, hash) : NULL;
2196 This is basically sv_eq_flags() in sv.c, but we avoid the magic
2201 hek_eq_pvn_flags(pTHX_ const HEK *hek, const char* pv, const I32 pvlen, const U32 flags) {
2202 if ( (HEK_UTF8(hek) ? 1 : 0) != (flags & SVf_UTF8 ? 1 : 0) ) {
2203 if (flags & SVf_UTF8)
2204 return (bytes_cmp_utf8(
2205 (const U8*)HEK_KEY(hek), HEK_LEN(hek),
2206 (const U8*)pv, pvlen) == 0);
2208 return (bytes_cmp_utf8(
2209 (const U8*)pv, pvlen,
2210 (const U8*)HEK_KEY(hek), HEK_LEN(hek)) == 0);
2213 return HEK_LEN(hek) == pvlen && ((HEK_KEY(hek) == pv)
2214 || memEQ(HEK_KEY(hek), pv, pvlen));
2218 =for apidoc hv_ename_add
2220 Adds a name to a stash's internal list of effective names. See
2223 This is called when a stash is assigned to a new location in the symbol
2230 Perl_hv_ename_add(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2233 struct xpvhv_aux *aux = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2236 PERL_ARGS_ASSERT_HV_ENAME_ADD;
2239 Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
2241 PERL_HASH(hash, name, len);
2243 if (aux->xhv_name_count) {
2244 HEK ** const xhv_name = aux->xhv_name_u.xhvnameu_names;
2245 I32 count = aux->xhv_name_count;
2246 HEK **hekp = xhv_name + (count < 0 ? -count : count);
2247 while (hekp-- > xhv_name)
2249 (HEK_UTF8(*hekp) || (flags & SVf_UTF8))
2250 ? hek_eq_pvn_flags(aTHX_ *hekp, name, (I32)len, flags)
2251 : (HEK_LEN(*hekp) == (I32)len && memEQ(HEK_KEY(*hekp), name, len))
2253 if (hekp == xhv_name && count < 0)
2254 aux->xhv_name_count = -count;
2257 if (count < 0) aux->xhv_name_count--, count = -count;
2258 else aux->xhv_name_count++;
2259 Renew(aux->xhv_name_u.xhvnameu_names, count + 1, HEK *);
2260 (aux->xhv_name_u.xhvnameu_names)[count] = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
2263 HEK *existing_name = aux->xhv_name_u.xhvnameu_name;
2266 (HEK_UTF8(existing_name) || (flags & SVf_UTF8))
2267 ? hek_eq_pvn_flags(aTHX_ existing_name, name, (I32)len, flags)
2268 : (HEK_LEN(existing_name) == (I32)len && memEQ(HEK_KEY(existing_name), name, len))
2271 Newx(aux->xhv_name_u.xhvnameu_names, 2, HEK *);
2272 aux->xhv_name_count = existing_name ? 2 : -2;
2273 *aux->xhv_name_u.xhvnameu_names = existing_name;
2274 (aux->xhv_name_u.xhvnameu_names)[1] = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
2279 =for apidoc hv_ename_delete
2281 Removes a name from a stash's internal list of effective names. If this is
2282 the name returned by C<HvENAME>, then another name in the list will take
2283 its place (C<HvENAME> will use it).
2285 This is called when a stash is deleted from the symbol table.
2291 Perl_hv_ename_delete(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2294 struct xpvhv_aux *aux;
2296 PERL_ARGS_ASSERT_HV_ENAME_DELETE;
2299 Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
2301 if (!SvOOK(hv)) return;
2304 if (!aux->xhv_name_u.xhvnameu_name) return;
2306 if (aux->xhv_name_count) {
2307 HEK ** const namep = aux->xhv_name_u.xhvnameu_names;
2308 I32 const count = aux->xhv_name_count;
2309 HEK **victim = namep + (count < 0 ? -count : count);
2310 while (victim-- > namep + 1)
2312 (HEK_UTF8(*victim) || (flags & SVf_UTF8))
2313 ? hek_eq_pvn_flags(aTHX_ *victim, name, (I32)len, flags)
2314 : (HEK_LEN(*victim) == (I32)len && memEQ(HEK_KEY(*victim), name, len))
2316 unshare_hek_or_pvn(*victim, 0, 0, 0);
2317 if (count < 0) ++aux->xhv_name_count;
2318 else --aux->xhv_name_count;
2320 (aux->xhv_name_count == 1 || aux->xhv_name_count == -1)
2322 ) { /* if there are none left */
2324 aux->xhv_name_u.xhvnameu_names = NULL;
2325 aux->xhv_name_count = 0;
2328 /* Move the last one back to fill the empty slot. It
2329 does not matter what order they are in. */
2330 *victim = *(namep + (count < 0 ? -count : count) - 1);
2335 count > 0 && (HEK_UTF8(*namep) || (flags & SVf_UTF8))
2336 ? hek_eq_pvn_flags(aTHX_ *namep, name, (I32)len, flags)
2337 : (HEK_LEN(*namep) == (I32)len && memEQ(HEK_KEY(*namep), name, len))
2339 aux->xhv_name_count = -count;
2343 (HEK_UTF8(aux->xhv_name_u.xhvnameu_name) || (flags & SVf_UTF8))
2344 ? hek_eq_pvn_flags(aTHX_ aux->xhv_name_u.xhvnameu_name, name, (I32)len, flags)
2345 : (HEK_LEN(aux->xhv_name_u.xhvnameu_name) == (I32)len &&
2346 memEQ(HEK_KEY(aux->xhv_name_u.xhvnameu_name), name, len))
2348 HEK * const namehek = aux->xhv_name_u.xhvnameu_name;
2349 Newx(aux->xhv_name_u.xhvnameu_names, 1, HEK *);
2350 *aux->xhv_name_u.xhvnameu_names = namehek;
2351 aux->xhv_name_count = -1;
2356 Perl_hv_backreferences_p(pTHX_ HV *hv) {
2357 struct xpvhv_aux * const iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2359 PERL_ARGS_ASSERT_HV_BACKREFERENCES_P;
2360 PERL_UNUSED_CONTEXT;
2362 return &(iter->xhv_backreferences);
2366 Perl_hv_kill_backrefs(pTHX_ HV *hv) {
2369 PERL_ARGS_ASSERT_HV_KILL_BACKREFS;
2374 av = HvAUX(hv)->xhv_backreferences;
2377 HvAUX(hv)->xhv_backreferences = 0;
2378 Perl_sv_kill_backrefs(aTHX_ MUTABLE_SV(hv), av);
2379 if (SvTYPE(av) == SVt_PVAV)
2380 SvREFCNT_dec_NN(av);
2385 hv_iternext is implemented as a macro in hv.h
2387 =for apidoc hv_iternext
2389 Returns entries from a hash iterator. See C<hv_iterinit>.
2391 You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
2392 iterator currently points to, without losing your place or invalidating your
2393 iterator. Note that in this case the current entry is deleted from the hash
2394 with your iterator holding the last reference to it. Your iterator is flagged
2395 to free the entry on the next call to C<hv_iternext>, so you must not discard
2396 your iterator immediately else the entry will leak - call C<hv_iternext> to
2397 trigger the resource deallocation.
2399 =for apidoc hv_iternext_flags
2401 Returns entries from a hash iterator. See C<hv_iterinit> and C<hv_iternext>.
2402 The C<flags> value will normally be zero; if HV_ITERNEXT_WANTPLACEHOLDERS is
2403 set the placeholders keys (for restricted hashes) will be returned in addition
2404 to normal keys. By default placeholders are automatically skipped over.
2405 Currently a placeholder is implemented with a value that is
2406 C<&PL_sv_placeholder>. Note that the implementation of placeholders and
2407 restricted hashes may change, and the implementation currently is
2408 insufficiently abstracted for any change to be tidy.
2414 Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
2421 struct xpvhv_aux *iter;
2423 PERL_ARGS_ASSERT_HV_ITERNEXT_FLAGS;
2426 Perl_croak(aTHX_ "Bad hash");
2428 xhv = (XPVHV*)SvANY(hv);
2431 /* Too many things (well, pp_each at least) merrily assume that you can
2432 call hv_iternext without calling hv_iterinit, so we'll have to deal
2438 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2439 if (SvMAGICAL(hv) && SvRMAGICAL(hv)) {
2440 if ( ( mg = mg_find((const SV *)hv, PERL_MAGIC_tied) ) ) {
2441 SV * const key = sv_newmortal();
2443 sv_setsv(key, HeSVKEY_force(entry));
2444 SvREFCNT_dec(HeSVKEY(entry)); /* get rid of previous key */
2445 HeSVKEY_set(entry, NULL);
2451 /* one HE per MAGICAL hash */
2452 iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
2453 HvLAZYDEL_on(hv); /* make sure entry gets freed */
2455 Newxz(k, HEK_BASESIZE + sizeof(const SV *), char);
2457 HeKEY_hek(entry) = hek;
2458 HeKLEN(entry) = HEf_SVKEY;
2460 magic_nextpack(MUTABLE_SV(hv),mg,key);
2462 /* force key to stay around until next time */
2463 HeSVKEY_set(entry, SvREFCNT_inc_simple_NN(key));
2464 return entry; /* beware, hent_val is not set */
2466 SvREFCNT_dec(HeVAL(entry));
2467 Safefree(HeKEY_hek(entry));
2469 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
2474 #if defined(DYNAMIC_ENV_FETCH) && !defined(__riscos__) /* set up %ENV for iteration */
2475 if (!entry && SvRMAGICAL((const SV *)hv)
2476 && mg_find((const SV *)hv, PERL_MAGIC_env)) {
2479 /* The prime_env_iter() on VMS just loaded up new hash values
2480 * so the iteration count needs to be reset back to the beginning
2484 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2489 /* hv_iterinit now ensures this. */
2490 assert (HvARRAY(hv));
2492 /* At start of hash, entry is NULL. */
2495 entry = HeNEXT(entry);
2496 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2498 * Skip past any placeholders -- don't want to include them in
2501 while (entry && HeVAL(entry) == &PL_sv_placeholder) {
2502 entry = HeNEXT(entry);
2507 #ifdef PERL_HASH_RANDOMIZE_KEYS
2508 if (iter->xhv_last_rand != iter->xhv_rand) {
2509 if (iter->xhv_riter != -1) {
2510 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
2511 "Use of each() on hash after insertion without resetting hash iterator results in undefined behavior"
2515 iter->xhv_last_rand = iter->xhv_rand;
2519 /* Skip the entire loop if the hash is empty. */
2520 if ((flags & HV_ITERNEXT_WANTPLACEHOLDERS)
2521 ? HvTOTALKEYS(hv) : HvUSEDKEYS(hv)) {
2523 /* OK. Come to the end of the current list. Grab the next one. */
2525 iter->xhv_riter++; /* HvRITER(hv)++ */
2526 if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
2527 /* There is no next one. End of the hash. */
2528 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2529 #ifdef PERL_HASH_RANDOMIZE_KEYS
2530 iter->xhv_last_rand = iter->xhv_rand; /* reset xhv_last_rand so we can detect inserts during traversal */
2534 entry = (HvARRAY(hv))[ PERL_HASH_ITER_BUCKET(iter) & xhv->xhv_max ];
2536 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2537 /* If we have an entry, but it's a placeholder, don't count it.
2539 while (entry && HeVAL(entry) == &PL_sv_placeholder)
2540 entry = HeNEXT(entry);
2542 /* Will loop again if this linked list starts NULL
2543 (for HV_ITERNEXT_WANTPLACEHOLDERS)
2544 or if we run through it and find only placeholders. */
2548 iter->xhv_riter = -1;
2549 #ifdef PERL_HASH_RANDOMIZE_KEYS
2550 iter->xhv_last_rand = iter->xhv_rand;
2554 if (oldentry && HvLAZYDEL(hv)) { /* was deleted earlier? */
2556 hv_free_ent(hv, oldentry);
2559 iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
2564 =for apidoc hv_iterkey
2566 Returns the key from the current position of the hash iterator. See
2573 Perl_hv_iterkey(pTHX_ HE *entry, I32 *retlen)
2575 PERL_ARGS_ASSERT_HV_ITERKEY;
2577 if (HeKLEN(entry) == HEf_SVKEY) {
2579 char * const p = SvPV(HeKEY_sv(entry), len);
2584 *retlen = HeKLEN(entry);
2585 return HeKEY(entry);
2589 /* unlike hv_iterval(), this always returns a mortal copy of the key */
2591 =for apidoc hv_iterkeysv
2593 Returns the key as an C<SV*> from the current position of the hash
2594 iterator. The return value will always be a mortal copy of the key. Also
2601 Perl_hv_iterkeysv(pTHX_ HE *entry)
2603 PERL_ARGS_ASSERT_HV_ITERKEYSV;
2605 return sv_2mortal(newSVhek(HeKEY_hek(entry)));
2609 =for apidoc hv_iterval
2611 Returns the value from the current position of the hash iterator. See
2618 Perl_hv_iterval(pTHX_ HV *hv, HE *entry)
2620 PERL_ARGS_ASSERT_HV_ITERVAL;
2622 if (SvRMAGICAL(hv)) {
2623 if (mg_find((const SV *)hv, PERL_MAGIC_tied)) {
2624 SV* const sv = sv_newmortal();
2625 if (HeKLEN(entry) == HEf_SVKEY)
2626 mg_copy(MUTABLE_SV(hv), sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
2628 mg_copy(MUTABLE_SV(hv), sv, HeKEY(entry), HeKLEN(entry));
2632 return HeVAL(entry);
2636 =for apidoc hv_iternextsv
2638 Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2645 Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
2647 HE * const he = hv_iternext_flags(hv, 0);
2649 PERL_ARGS_ASSERT_HV_ITERNEXTSV;
2653 *key = hv_iterkey(he, retlen);
2654 return hv_iterval(hv, he);
2661 =for apidoc hv_magic
2663 Adds magic to a hash. See C<sv_magic>.
2668 /* possibly free a shared string if no one has access to it
2669 * len and hash must both be valid for str.
2672 Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
2674 unshare_hek_or_pvn (NULL, str, len, hash);
2679 Perl_unshare_hek(pTHX_ HEK *hek)
2682 unshare_hek_or_pvn(hek, NULL, 0, 0);
2685 /* possibly free a shared string if no one has access to it
2686 hek if non-NULL takes priority over the other 3, else str, len and hash
2687 are used. If so, len and hash must both be valid for str.
2690 S_unshare_hek_or_pvn(pTHX_ const HEK *hek, const char *str, I32 len, U32 hash)
2696 bool is_utf8 = FALSE;
2698 const char * const save = str;
2699 struct shared_he *he = NULL;
2702 /* Find the shared he which is just before us in memory. */
2703 he = (struct shared_he *)(((char *)hek)
2704 - STRUCT_OFFSET(struct shared_he,
2707 /* Assert that the caller passed us a genuine (or at least consistent)
2709 assert (he->shared_he_he.hent_hek == hek);
2711 if (he->shared_he_he.he_valu.hent_refcount - 1) {
2712 --he->shared_he_he.he_valu.hent_refcount;
2716 hash = HEK_HASH(hek);
2717 } else if (len < 0) {
2718 STRLEN tmplen = -len;
2720 /* See the note in hv_fetch(). --jhi */
2721 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2724 k_flags = HVhek_UTF8;
2726 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2729 /* what follows was the moral equivalent of:
2730 if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
2732 hv_delete(PL_strtab, str, len, G_DISCARD, hash);
2734 xhv = (XPVHV*)SvANY(PL_strtab);
2735 /* assert(xhv_array != 0) */
2736 oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2738 const HE *const he_he = &(he->shared_he_he);
2739 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2744 const int flags_masked = k_flags & HVhek_MASK;
2745 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2746 if (HeHASH(entry) != hash) /* strings can't be equal */
2748 if (HeKLEN(entry) != len)
2750 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2752 if (HeKFLAGS(entry) != flags_masked)
2759 if (--entry->he_valu.hent_refcount == 0) {
2760 *oentry = HeNEXT(entry);
2762 xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
2767 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
2768 "Attempt to free nonexistent shared string '%s'%s"
2770 hek ? HEK_KEY(hek) : str,
2771 ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
2772 if (k_flags & HVhek_FREEKEY)
2776 /* get a (constant) string ptr from the global string table
2777 * string will get added if it is not already there.
2778 * len and hash must both be valid for str.
2781 Perl_share_hek(pTHX_ const char *str, I32 len, U32 hash)
2783 bool is_utf8 = FALSE;
2785 const char * const save = str;
2787 PERL_ARGS_ASSERT_SHARE_HEK;
2790 STRLEN tmplen = -len;
2792 /* See the note in hv_fetch(). --jhi */
2793 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2795 /* If we were able to downgrade here, then than means that we were passed
2796 in a key which only had chars 0-255, but was utf8 encoded. */
2799 /* If we found we were able to downgrade the string to bytes, then
2800 we should flag that it needs upgrading on keys or each. Also flag
2801 that we need share_hek_flags to free the string. */
2804 PERL_HASH(hash, str, len);
2805 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2809 return share_hek_flags (str, len, hash, flags);
2813 S_share_hek_flags(pTHX_ const char *str, I32 len, U32 hash, int flags)
2817 const int flags_masked = flags & HVhek_MASK;
2818 const U32 hindex = hash & (I32) HvMAX(PL_strtab);
2819 XPVHV * const xhv = (XPVHV*)SvANY(PL_strtab);
2821 PERL_ARGS_ASSERT_SHARE_HEK_FLAGS;
2823 /* what follows is the moral equivalent of:
2825 if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
2826 hv_store(PL_strtab, str, len, NULL, hash);
2828 Can't rehash the shared string table, so not sure if it's worth
2829 counting the number of entries in the linked list
2832 /* assert(xhv_array != 0) */
2833 entry = (HvARRAY(PL_strtab))[hindex];
2834 for (;entry; entry = HeNEXT(entry)) {
2835 if (HeHASH(entry) != hash) /* strings can't be equal */
2837 if (HeKLEN(entry) != len)
2839 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2841 if (HeKFLAGS(entry) != flags_masked)
2847 /* What used to be head of the list.
2848 If this is NULL, then we're the first entry for this slot, which
2849 means we need to increate fill. */
2850 struct shared_he *new_entry;
2853 HE **const head = &HvARRAY(PL_strtab)[hindex];
2854 HE *const next = *head;
2856 /* We don't actually store a HE from the arena and a regular HEK.
2857 Instead we allocate one chunk of memory big enough for both,
2858 and put the HEK straight after the HE. This way we can find the
2859 HE directly from the HEK.
2862 Newx(k, STRUCT_OFFSET(struct shared_he,
2863 shared_he_hek.hek_key[0]) + len + 2, char);
2864 new_entry = (struct shared_he *)k;
2865 entry = &(new_entry->shared_he_he);
2866 hek = &(new_entry->shared_he_hek);
2868 Copy(str, HEK_KEY(hek), len, char);
2869 HEK_KEY(hek)[len] = 0;
2871 HEK_HASH(hek) = hash;
2872 HEK_FLAGS(hek) = (unsigned char)flags_masked;
2874 /* Still "point" to the HEK, so that other code need not know what
2876 HeKEY_hek(entry) = hek;
2877 entry->he_valu.hent_refcount = 0;
2878 HeNEXT(entry) = next;
2881 xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
2882 if (!next) { /* initial entry? */
2883 } else if ( DO_HSPLIT(xhv) ) {
2884 const STRLEN oldsize = xhv->xhv_max + 1;
2885 hsplit(PL_strtab, oldsize, oldsize * 2);
2889 ++entry->he_valu.hent_refcount;
2891 if (flags & HVhek_FREEKEY)
2894 return HeKEY_hek(entry);
2898 Perl_hv_placeholders_p(pTHX_ HV *hv)
2901 MAGIC *mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
2903 PERL_ARGS_ASSERT_HV_PLACEHOLDERS_P;
2906 mg = sv_magicext(MUTABLE_SV(hv), 0, PERL_MAGIC_rhash, 0, 0, 0);
2909 Perl_die(aTHX_ "panic: hv_placeholders_p");
2912 return &(mg->mg_len);
2917 Perl_hv_placeholders_get(pTHX_ const HV *hv)
2920 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
2922 PERL_ARGS_ASSERT_HV_PLACEHOLDERS_GET;
2924 return mg ? mg->mg_len : 0;
2928 Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
2931 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
2933 PERL_ARGS_ASSERT_HV_PLACEHOLDERS_SET;
2938 if (!sv_magicext(MUTABLE_SV(hv), 0, PERL_MAGIC_rhash, 0, 0, ph))
2939 Perl_die(aTHX_ "panic: hv_placeholders_set");
2941 /* else we don't need to add magic to record 0 placeholders. */
2945 S_refcounted_he_value(pTHX_ const struct refcounted_he *he)
2950 PERL_ARGS_ASSERT_REFCOUNTED_HE_VALUE;
2952 switch(he->refcounted_he_data[0] & HVrhek_typemask) {
2957 value = &PL_sv_placeholder;
2960 value = newSViv(he->refcounted_he_val.refcounted_he_u_iv);
2963 value = newSVuv(he->refcounted_he_val.refcounted_he_u_uv);
2966 case HVrhek_PV_UTF8:
2967 /* Create a string SV that directly points to the bytes in our
2969 value = newSV_type(SVt_PV);
2970 SvPV_set(value, (char *) he->refcounted_he_data + 1);
2971 SvCUR_set(value, he->refcounted_he_val.refcounted_he_u_len);
2972 /* This stops anything trying to free it */
2973 SvLEN_set(value, 0);
2975 SvREADONLY_on(value);
2976 if ((he->refcounted_he_data[0] & HVrhek_typemask) == HVrhek_PV_UTF8)
2980 Perl_croak(aTHX_ "panic: refcounted_he_value bad flags %"UVxf,
2981 (UV)he->refcounted_he_data[0]);
2987 =for apidoc m|HV *|refcounted_he_chain_2hv|const struct refcounted_he *c|U32 flags
2989 Generates and returns a C<HV *> representing the content of a
2990 C<refcounted_he> chain.
2991 I<flags> is currently unused and must be zero.
2996 Perl_refcounted_he_chain_2hv(pTHX_ const struct refcounted_he *chain, U32 flags)
3000 U32 placeholders, max;
3003 Perl_croak(aTHX_ "panic: refcounted_he_chain_2hv bad flags %"UVxf,
3006 /* We could chase the chain once to get an idea of the number of keys,
3007 and call ksplit. But for now we'll make a potentially inefficient
3008 hash with only 8 entries in its array. */
3013 Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(max + 1), char);
3014 HvARRAY(hv) = (HE**)array;
3020 U32 hash = chain->refcounted_he_hash;
3022 U32 hash = HEK_HASH(chain->refcounted_he_hek);
3024 HE **oentry = &((HvARRAY(hv))[hash & max]);
3025 HE *entry = *oentry;
3028 for (; entry; entry = HeNEXT(entry)) {
3029 if (HeHASH(entry) == hash) {
3030 /* We might have a duplicate key here. If so, entry is older
3031 than the key we've already put in the hash, so if they are
3032 the same, skip adding entry. */
3034 const STRLEN klen = HeKLEN(entry);
3035 const char *const key = HeKEY(entry);
3036 if (klen == chain->refcounted_he_keylen
3037 && (!!HeKUTF8(entry)
3038 == !!(chain->refcounted_he_data[0] & HVhek_UTF8))
3039 && memEQ(key, REF_HE_KEY(chain), klen))
3042 if (HeKEY_hek(entry) == chain->refcounted_he_hek)
3044 if (HeKLEN(entry) == HEK_LEN(chain->refcounted_he_hek)
3045 && HeKUTF8(entry) == HEK_UTF8(chain->refcounted_he_hek)
3046 && memEQ(HeKEY(entry), HEK_KEY(chain->refcounted_he_hek),
3057 = share_hek_flags(REF_HE_KEY(chain),
3058 chain->refcounted_he_keylen,
3059 chain->refcounted_he_hash,
3060 (chain->refcounted_he_data[0]
3061 & (HVhek_UTF8|HVhek_WASUTF8)));
3063 HeKEY_hek(entry) = share_hek_hek(chain->refcounted_he_hek);
3065 value = refcounted_he_value(chain);
3066 if (value == &PL_sv_placeholder)
3068 HeVAL(entry) = value;
3070 /* Link it into the chain. */
3071 HeNEXT(entry) = *oentry;
3077 chain = chain->refcounted_he_next;
3081 clear_placeholders(hv, placeholders);
3082 HvTOTALKEYS(hv) -= placeholders;
3085 /* We could check in the loop to see if we encounter any keys with key
3086 flags, but it's probably not worth it, as this per-hash flag is only
3087 really meant as an optimisation for things like Storable. */
3089 DEBUG_A(Perl_hv_assert(aTHX_ hv));
3095 =for apidoc m|SV *|refcounted_he_fetch_pvn|const struct refcounted_he *chain|const char *keypv|STRLEN keylen|U32 hash|U32 flags
3097 Search along a C<refcounted_he> chain for an entry with the key specified
3098 by I<keypv> and I<keylen>. If I<flags> has the C<REFCOUNTED_HE_KEY_UTF8>
3099 bit set, the key octets are interpreted as UTF-8, otherwise they
3100 are interpreted as Latin-1. I<hash> is a precomputed hash of the key
3101 string, or zero if it has not been precomputed. Returns a mortal scalar
3102 representing the value associated with the key, or C<&PL_sv_placeholder>
3103 if there is no value associated with the key.
3109 Perl_refcounted_he_fetch_pvn(pTHX_ const struct refcounted_he *chain,
3110 const char *keypv, STRLEN keylen, U32 hash, U32 flags)
3114 PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_PVN;
3116 if (flags & ~(REFCOUNTED_HE_KEY_UTF8|REFCOUNTED_HE_EXISTS))
3117 Perl_croak(aTHX_ "panic: refcounted_he_fetch_pvn bad flags %"UVxf,
3120 return &PL_sv_placeholder;
3121 if (flags & REFCOUNTED_HE_KEY_UTF8) {
3122 /* For searching purposes, canonicalise to Latin-1 where possible. */
3123 const char *keyend = keypv + keylen, *p;
3124 STRLEN nonascii_count = 0;
3125 for (p = keypv; p != keyend; p++) {
3128 if (!((c & 0xfe) == 0xc2 && ++p != keyend &&
3129 (((U8)*p) & 0xc0) == 0x80))
3130 goto canonicalised_key;
3134 if (nonascii_count) {
3136 const char *p = keypv, *keyend = keypv + keylen;
3137 keylen -= nonascii_count;
3138 Newx(q, keylen, char);
3141 for (; p != keyend; p++, q++) {
3144 ((c & 0x80) ? ((c & 0x03) << 6) | (((U8)*++p) & 0x3f) : c);
3147 flags &= ~REFCOUNTED_HE_KEY_UTF8;
3148 canonicalised_key: ;
3150 utf8_flag = (flags & REFCOUNTED_HE_KEY_UTF8) ? HVhek_UTF8 : 0;
3152 PERL_HASH(hash, keypv, keylen);
3154 for (; chain; chain = chain->refcounted_he_next) {
3157 hash == chain->refcounted_he_hash &&
3158 keylen == chain->refcounted_he_keylen &&
3159 memEQ(REF_HE_KEY(chain), keypv, keylen) &&
3160 utf8_flag == (chain->refcounted_he_data[0] & HVhek_UTF8)
3162 hash == HEK_HASH(chain->refcounted_he_hek) &&
3163 keylen == (STRLEN)HEK_LEN(chain->refcounted_he_hek) &&
3164 memEQ(HEK_KEY(chain->refcounted_he_hek), keypv, keylen) &&
3165 utf8_flag == (HEK_FLAGS(chain->refcounted_he_hek) & HVhek_UTF8)
3168 if (flags & REFCOUNTED_HE_EXISTS)
3169 return (chain->refcounted_he_data[0] & HVrhek_typemask)
3171 ? NULL : &PL_sv_yes;
3172 return sv_2mortal(refcounted_he_value(chain));
3175 return flags & REFCOUNTED_HE_EXISTS ? NULL : &PL_sv_placeholder;
3179 =for apidoc m|SV *|refcounted_he_fetch_pv|const struct refcounted_he *chain|const char *key|U32 hash|U32 flags
3181 Like L</refcounted_he_fetch_pvn>, but takes a nul-terminated string
3182 instead of a string/length pair.
3188 Perl_refcounted_he_fetch_pv(pTHX_ const struct refcounted_he *chain,
3189 const char *key, U32 hash, U32 flags)
3191 PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_PV;
3192 return refcounted_he_fetch_pvn(chain, key, strlen(key), hash, flags);
3196 =for apidoc m|SV *|refcounted_he_fetch_sv|const struct refcounted_he *chain|SV *key|U32 hash|U32 flags
3198 Like L</refcounted_he_fetch_pvn>, but takes a Perl scalar instead of a
3205 Perl_refcounted_he_fetch_sv(pTHX_ const struct refcounted_he *chain,
3206 SV *key, U32 hash, U32 flags)
3210 PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_SV;
3211 if (flags & REFCOUNTED_HE_KEY_UTF8)
3212 Perl_croak(aTHX_ "panic: refcounted_he_fetch_sv bad flags %"UVxf,
3214 keypv = SvPV_const(key, keylen);
3216 flags |= REFCOUNTED_HE_KEY_UTF8;
3217 if (!hash && SvIsCOW_shared_hash(key))
3218 hash = SvSHARED_HASH(key);
3219 return refcounted_he_fetch_pvn(chain, keypv, keylen, hash, flags);
3223 =for apidoc m|struct refcounted_he *|refcounted_he_new_pvn|struct refcounted_he *parent|const char *keypv|STRLEN keylen|U32 hash|SV *value|U32 flags
3225 Creates a new C<refcounted_he>. This consists of a single key/value
3226 pair and a reference to an existing C<refcounted_he> chain (which may
3227 be empty), and thus forms a longer chain. When using the longer chain,
3228 the new key/value pair takes precedence over any entry for the same key
3229 further along the chain.
3231 The new key is specified by I<keypv> and I<keylen>. If I<flags> has
3232 the C<REFCOUNTED_HE_KEY_UTF8> bit set, the key octets are interpreted
3233 as UTF-8, otherwise they are interpreted as Latin-1. I<hash> is
3234 a precomputed hash of the key string, or zero if it has not been
3237 I<value> is the scalar value to store for this key. I<value> is copied
3238 by this function, which thus does not take ownership of any reference
3239 to it, and later changes to the scalar will not be reflected in the
3240 value visible in the C<refcounted_he>. Complex types of scalar will not
3241 be stored with referential integrity, but will be coerced to strings.
3242 I<value> may be either null or C<&PL_sv_placeholder> to indicate that no
3243 value is to be associated with the key; this, as with any non-null value,
3244 takes precedence over the existence of a value for the key further along
3247 I<parent> points to the rest of the C<refcounted_he> chain to be
3248 attached to the new C<refcounted_he>. This function takes ownership
3249 of one reference to I<parent>, and returns one reference to the new
3255 struct refcounted_he *
3256 Perl_refcounted_he_new_pvn(pTHX_ struct refcounted_he *parent,
3257 const char *keypv, STRLEN keylen, U32 hash, SV *value, U32 flags)
3260 STRLEN value_len = 0;
3261 const char *value_p = NULL;
3265 STRLEN key_offset = 1;
3266 struct refcounted_he *he;
3267 PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_PVN;
3269 if (!value || value == &PL_sv_placeholder) {
3270 value_type = HVrhek_delete;
3271 } else if (SvPOK(value)) {
3272 value_type = HVrhek_PV;
3273 } else if (SvIOK(value)) {
3274 value_type = SvUOK((const SV *)value) ? HVrhek_UV : HVrhek_IV;
3275 } else if (!SvOK(value)) {
3276 value_type = HVrhek_undef;
3278 value_type = HVrhek_PV;
3280 is_pv = value_type == HVrhek_PV;
3282 /* Do it this way so that the SvUTF8() test is after the SvPV, in case
3283 the value is overloaded, and doesn't yet have the UTF-8flag set. */
3284 value_p = SvPV_const(value, value_len);
3286 value_type = HVrhek_PV_UTF8;
3287 key_offset = value_len + 2;
3289 hekflags = value_type;
3291 if (flags & REFCOUNTED_HE_KEY_UTF8) {
3292 /* Canonicalise to Latin-1 where possible. */
3293 const char *keyend = keypv + keylen, *p;
3294 STRLEN nonascii_count = 0;
3295 for (p = keypv; p != keyend; p++) {
3298 if (!((c & 0xfe) == 0xc2 && ++p != keyend &&
3299 (((U8)*p) & 0xc0) == 0x80))
3300 goto canonicalised_key;
3304 if (nonascii_count) {
3306 const char *p = keypv, *keyend = keypv + keylen;
3307 keylen -= nonascii_count;
3308 Newx(q, keylen, char);
3311 for (; p != keyend; p++, q++) {
3314 ((c & 0x80) ? ((c & 0x03) << 6) | (((U8)*++p) & 0x3f) : c);
3317 flags &= ~REFCOUNTED_HE_KEY_UTF8;
3318 canonicalised_key: ;
3320 if (flags & REFCOUNTED_HE_KEY_UTF8)
3321 hekflags |= HVhek_UTF8;
3323 PERL_HASH(hash, keypv, keylen);
3326 he = (struct refcounted_he*)
3327 PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
3331 he = (struct refcounted_he*)
3332 PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
3336 he->refcounted_he_next = parent;
3339 Copy(value_p, he->refcounted_he_data + 1, value_len + 1, char);
3340 he->refcounted_he_val.refcounted_he_u_len = value_len;
3341 } else if (value_type == HVrhek_IV) {
3342 he->refcounted_he_val.refcounted_he_u_iv = SvIVX(value);
3343 } else if (value_type == HVrhek_UV) {
3344 he->refcounted_he_val.refcounted_he_u_uv = SvUVX(value);
3348 he->refcounted_he_hash = hash;
3349 he->refcounted_he_keylen = keylen;
3350 Copy(keypv, he->refcounted_he_data + key_offset, keylen, char);
3352 he->refcounted_he_hek = share_hek_flags(keypv, keylen, hash, hekflags);
3355 he->refcounted_he_data[0] = hekflags;
3356 he->refcounted_he_refcnt = 1;
3362 =for apidoc m|struct refcounted_he *|refcounted_he_new_pv|struct refcounted_he *parent|const char *key|U32 hash|SV *value|U32 flags
3364 Like L</refcounted_he_new_pvn>, but takes a nul-terminated string instead
3365 of a string/length pair.
3370 struct refcounted_he *
3371 Perl_refcounted_he_new_pv(pTHX_ struct refcounted_he *parent,
3372 const char *key, U32 hash, SV *value, U32 flags)
3374 PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_PV;
3375 return refcounted_he_new_pvn(parent, key, strlen(key), hash, value, flags);
3379 =for apidoc m|struct refcounted_he *|refcounted_he_new_sv|struct refcounted_he *parent|SV *key|U32 hash|SV *value|U32 flags
3381 Like L</refcounted_he_new_pvn>, but takes a Perl scalar instead of a
3387 struct refcounted_he *
3388 Perl_refcounted_he_new_sv(pTHX_ struct refcounted_he *parent,
3389 SV *key, U32 hash, SV *value, U32 flags)
3393 PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_SV;
3394 if (flags & REFCOUNTED_HE_KEY_UTF8)
3395 Perl_croak(aTHX_ "panic: refcounted_he_new_sv bad flags %"UVxf,
3397 keypv = SvPV_const(key, keylen);
3399 flags |= REFCOUNTED_HE_KEY_UTF8;
3400 if (!hash && SvIsCOW_shared_hash(key))
3401 hash = SvSHARED_HASH(key);
3402 return refcounted_he_new_pvn(parent, keypv, keylen, hash, value, flags);
3406 =for apidoc m|void|refcounted_he_free|struct refcounted_he *he
3408 Decrements the reference count of a C<refcounted_he> by one. If the
3409 reference count reaches zero the structure's memory is freed, which
3410 (recursively) causes a reduction of its parent C<refcounted_he>'s
3411 reference count. It is safe to pass a null pointer to this function:
3412 no action occurs in this case.
3418 Perl_refcounted_he_free(pTHX_ struct refcounted_he *he) {
3420 PERL_UNUSED_CONTEXT;
3423 struct refcounted_he *copy;
3427 new_count = --he->refcounted_he_refcnt;
3428 HINTS_REFCNT_UNLOCK;
3434 #ifndef USE_ITHREADS
3435 unshare_hek_or_pvn (he->refcounted_he_hek, 0, 0, 0);
3438 he = he->refcounted_he_next;
3439 PerlMemShared_free(copy);
3444 =for apidoc m|struct refcounted_he *|refcounted_he_inc|struct refcounted_he *he
3446 Increment the reference count of a C<refcounted_he>. The pointer to the
3447 C<refcounted_he> is also returned. It is safe to pass a null pointer
3448 to this function: no action occurs and a null pointer is returned.
3453 struct refcounted_he *
3454 Perl_refcounted_he_inc(pTHX_ struct refcounted_he *he)
3459 he->refcounted_he_refcnt++;
3460 HINTS_REFCNT_UNLOCK;
3466 =for apidoc cop_fetch_label
3468 Returns the label attached to a cop.
3469 The flags pointer may be set to C<SVf_UTF8> or 0.
3474 /* pp_entereval is aware that labels are stored with a key ':' at the top of
3477 Perl_cop_fetch_label(pTHX_ COP *const cop, STRLEN *len, U32 *flags) {
3478 struct refcounted_he *const chain = cop->cop_hints_hash;
3480 PERL_ARGS_ASSERT_COP_FETCH_LABEL;
3485 if (chain->refcounted_he_keylen != 1)
3487 if (*REF_HE_KEY(chain) != ':')
3490 if ((STRLEN)HEK_LEN(chain->refcounted_he_hek) != 1)
3492 if (*HEK_KEY(chain->refcounted_he_hek) != ':')
3495 /* Stop anyone trying to really mess us up by adding their own value for
3497 if ((chain->refcounted_he_data[0] & HVrhek_typemask) != HVrhek_PV
3498 && (chain->refcounted_he_data[0] & HVrhek_typemask) != HVrhek_PV_UTF8)
3502 *len = chain->refcounted_he_val.refcounted_he_u_len;
3504 *flags = ((chain->refcounted_he_data[0] & HVrhek_typemask)
3505 == HVrhek_PV_UTF8) ? SVf_UTF8 : 0;
3507 return chain->refcounted_he_data + 1;
3511 =for apidoc cop_store_label
3513 Save a label into a C<cop_hints_hash>. You need to set flags to C<SVf_UTF8>
3520 Perl_cop_store_label(pTHX_ COP *const cop, const char *label, STRLEN len,
3524 PERL_ARGS_ASSERT_COP_STORE_LABEL;
3526 if (flags & ~(SVf_UTF8))
3527 Perl_croak(aTHX_ "panic: cop_store_label illegal flag bits 0x%" UVxf,
3529 labelsv = newSVpvn_flags(label, len, SVs_TEMP);
3530 if (flags & SVf_UTF8)
3533 = refcounted_he_new_pvs(cop->cop_hints_hash, ":", labelsv, 0);
3537 =for apidoc hv_assert
3539 Check that a hash is in an internally consistent state.
3547 Perl_hv_assert(pTHX_ HV *hv)
3552 int placeholders = 0;
3555 const I32 riter = HvRITER_get(hv);
3556 HE *eiter = HvEITER_get(hv);
3558 PERL_ARGS_ASSERT_HV_ASSERT;
3560 (void)hv_iterinit(hv);
3562 while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
3563 /* sanity check the values */
3564 if (HeVAL(entry) == &PL_sv_placeholder)
3568 /* sanity check the keys */
3569 if (HeSVKEY(entry)) {
3570 NOOP; /* Don't know what to check on SV keys. */
3571 } else if (HeKUTF8(entry)) {
3573 if (HeKWASUTF8(entry)) {
3574 PerlIO_printf(Perl_debug_log,
3575 "hash key has both WASUTF8 and UTF8: '%.*s'\n",
3576 (int) HeKLEN(entry), HeKEY(entry));
3579 } else if (HeKWASUTF8(entry))
3582 if (!SvTIED_mg((const SV *)hv, PERL_MAGIC_tied)) {
3583 static const char bad_count[] = "Count %d %s(s), but hash reports %d\n";
3584 const int nhashkeys = HvUSEDKEYS(hv);
3585 const int nhashplaceholders = HvPLACEHOLDERS_get(hv);
3587 if (nhashkeys != real) {
3588 PerlIO_printf(Perl_debug_log, bad_count, real, "keys", nhashkeys );
3591 if (nhashplaceholders != placeholders) {
3592 PerlIO_printf(Perl_debug_log, bad_count, placeholders, "placeholder", nhashplaceholders );
3596 if (withflags && ! HvHASKFLAGS(hv)) {
3597 PerlIO_printf(Perl_debug_log,
3598 "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
3603 sv_dump(MUTABLE_SV(hv));
3605 HvRITER_set(hv, riter); /* Restore hash iterator state */
3606 HvEITER_set(hv, eiter);
3613 * c-indentation-style: bsd
3615 * indent-tabs-mode: nil
3618 * ex: set ts=8 sts=4 sw=4 et: