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"]
21 A HV structure represents a Perl hash. It consists mainly of an array
22 of pointers, each of which points to a linked list of HE structures. The
23 array is indexed by the hash function of the key, so each linked list
24 represents all the hash entries with the same hash value. Each HE contains
25 a pointer to the actual value, plus a pointer to a HEK structure which
26 holds the key and hash value.
34 #define PERL_HASH_INTERNAL_ACCESS
37 /* we split when we collide and we have a load factor over 0.667.
38 * NOTE if you change this formula so we split earlier than previously
39 * you MUST change the logic in hv_ksplit()
41 #define DO_HSPLIT(xhv) ( ((xhv)->xhv_keys + ((xhv)->xhv_keys >> 1)) > (xhv)->xhv_max )
43 static const char S_strtab_error[]
44 = "Cannot modify shared string table in hv_%s";
48 #define new_HE() (HE*)safemalloc(sizeof(HE))
49 #define del_HE(p) safefree((char*)p)
57 void ** const root = &PL_body_roots[HE_SVSLOT];
60 Perl_more_bodies(aTHX_ HE_SVSLOT, sizeof(HE), PERL_ARENA_SIZE);
67 #define new_HE() new_he()
70 HeNEXT(p) = (HE*)(PL_body_roots[HE_SVSLOT]); \
71 PL_body_roots[HE_SVSLOT] = p; \
79 S_save_hek_flags(const char *str, I32 len, U32 hash, int flags)
81 const int flags_masked = flags & HVhek_MASK;
85 PERL_ARGS_ASSERT_SAVE_HEK_FLAGS;
87 Newx(k, HEK_BASESIZE + len + 2, char);
89 Copy(str, HEK_KEY(hek), len, char);
90 HEK_KEY(hek)[len] = 0;
93 HEK_FLAGS(hek) = (unsigned char)flags_masked | HVhek_UNSHARED;
95 if (flags & HVhek_FREEKEY)
100 /* free the pool of temporary HE/HEK pairs returned by hv_fetch_ent
104 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 C<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 C<NULL>. Effectively
233 a successful C<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, C<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. C<hv_store> is not implemented as a call to
238 C<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 C<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 C<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 C<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, C<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 C<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. The reason
263 it does not take ownership, is that C<key> is not used after this function
264 returns, and so can be freed immediately. C<hv_store>
265 is not implemented as a call to C<hv_store_ent>, and does not create a temporary
266 SV for the key, so if your key data is not already in SV form then use
267 C<hv_store> in preference to C<hv_store_ent>.
269 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
270 information on how to use this function on tied hashes.
272 =for apidoc hv_exists
274 Returns a boolean indicating whether the specified hash key exists. The
275 absolute value of C<klen> is the length of the key. If C<klen> is
276 negative the key is assumed to be in UTF-8-encoded Unicode.
280 Returns the SV which corresponds to the specified key in the hash.
281 The absolute value of C<klen> is the length of the key. If C<klen> is
282 negative the key is assumed to be in UTF-8-encoded Unicode. If
283 C<lval> is set then the fetch will be part of a store. This means that if
284 there is no value in the hash associated with the given key, then one is
285 created and a pointer to it is returned. The C<SV*> it points to can be
286 assigned to. But always check that the
287 return value is non-null before dereferencing it to an C<SV*>.
289 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
290 information on how to use this function on tied hashes.
292 =for apidoc hv_exists_ent
294 Returns a boolean indicating whether
295 the specified hash key exists. C<hash>
296 can be a valid precomputed hash value, or 0 to ask for it to be
302 /* returns an HE * structure with the all fields set */
303 /* note that hent_val will be a mortal sv for MAGICAL hashes */
305 =for apidoc hv_fetch_ent
307 Returns the hash entry which corresponds to the specified key in the hash.
308 C<hash> must be a valid precomputed hash number for the given C<key>, or 0
309 if you want the function to compute it. IF C<lval> is set then the fetch
310 will be part of a store. Make sure the return value is non-null before
311 accessing it. The return value when C<hv> is a tied hash is a pointer to a
312 static location, so be sure to make a copy of the structure if you need to
315 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
316 information on how to use this function on tied hashes.
321 /* Common code for hv_delete()/hv_exists()/hv_fetch()/hv_store() */
323 Perl_hv_common_key_len(pTHX_ HV *hv, const char *key, I32 klen_i32,
324 const int action, SV *val, const U32 hash)
329 PERL_ARGS_ASSERT_HV_COMMON_KEY_LEN;
338 return hv_common(hv, NULL, key, klen, flags, action, val, hash);
342 Perl_hv_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
343 int flags, int action, SV *val, U32 hash)
352 const int return_svp = action & HV_FETCH_JUST_SV;
353 HEK *keysv_hek = NULL;
357 if (SvTYPE(hv) == (svtype)SVTYPEMASK)
360 assert(SvTYPE(hv) == SVt_PVHV);
362 if (SvSMAGICAL(hv) && SvGMAGICAL(hv) && !(action & HV_DISABLE_UVAR_XKEY)) {
364 if ((mg = mg_find((const SV *)hv, PERL_MAGIC_uvar))) {
365 struct ufuncs * const uf = (struct ufuncs *)mg->mg_ptr;
366 if (uf->uf_set == NULL) {
367 SV* obj = mg->mg_obj;
370 keysv = newSVpvn_flags(key, klen, SVs_TEMP |
371 ((flags & HVhek_UTF8)
375 mg->mg_obj = keysv; /* pass key */
376 uf->uf_index = action; /* pass action */
377 magic_getuvar(MUTABLE_SV(hv), mg);
378 keysv = mg->mg_obj; /* may have changed */
381 /* If the key may have changed, then we need to invalidate
382 any passed-in computed hash value. */
388 if (flags & HVhek_FREEKEY)
390 key = SvPV_const(keysv, klen);
391 is_utf8 = (SvUTF8(keysv) != 0);
392 if (SvIsCOW_shared_hash(keysv)) {
393 flags = HVhek_KEYCANONICAL | (is_utf8 ? HVhek_UTF8 : 0);
398 is_utf8 = cBOOL(flags & HVhek_UTF8);
401 if (action & HV_DELETE) {
402 return (void *) hv_delete_common(hv, keysv, key, klen,
403 flags | (is_utf8 ? HVhek_UTF8 : 0),
407 xhv = (XPVHV*)SvANY(hv);
409 if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS))) {
410 if (mg_find((const SV *)hv, PERL_MAGIC_tied)
411 || SvGMAGICAL((const SV *)hv))
413 /* FIXME should be able to skimp on the HE/HEK here when
414 HV_FETCH_JUST_SV is true. */
416 keysv = newSVpvn_utf8(key, klen, is_utf8);
418 keysv = newSVsv(keysv);
421 mg_copy(MUTABLE_SV(hv), sv, (char *)keysv, HEf_SVKEY);
423 /* grab a fake HE/HEK pair from the pool or make a new one */
424 entry = PL_hv_fetch_ent_mh;
426 PL_hv_fetch_ent_mh = HeNEXT(entry);
430 Newx(k, HEK_BASESIZE + sizeof(const SV *), char);
431 HeKEY_hek(entry) = (HEK*)k;
433 HeNEXT(entry) = NULL;
434 HeSVKEY_set(entry, keysv);
436 sv_upgrade(sv, SVt_PVLV);
438 /* so we can free entry when freeing sv */
439 LvTARG(sv) = MUTABLE_SV(entry);
441 /* XXX remove at some point? */
442 if (flags & HVhek_FREEKEY)
446 return entry ? (void *) &HeVAL(entry) : NULL;
448 return (void *) entry;
450 #ifdef ENV_IS_CASELESS
451 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
453 for (i = 0; i < klen; ++i)
454 if (isLOWER(key[i])) {
455 /* Would be nice if we had a routine to do the
456 copy and upercase in a single pass through. */
457 const char * const nkey = strupr(savepvn(key,klen));
458 /* Note that this fetch is for nkey (the uppercased
459 key) whereas the store is for key (the original) */
460 void *result = hv_common(hv, NULL, nkey, klen,
461 HVhek_FREEKEY, /* free nkey */
462 0 /* non-LVAL fetch */
463 | HV_DISABLE_UVAR_XKEY
466 0 /* compute hash */);
467 if (!result && (action & HV_FETCH_LVALUE)) {
468 /* This call will free key if necessary.
469 Do it this way to encourage compiler to tail
471 result = hv_common(hv, keysv, key, klen, flags,
473 | HV_DISABLE_UVAR_XKEY
477 if (flags & HVhek_FREEKEY)
485 else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
486 if (mg_find((const SV *)hv, PERL_MAGIC_tied)
487 || SvGMAGICAL((const SV *)hv)) {
488 /* I don't understand why hv_exists_ent has svret and sv,
489 whereas hv_exists only had one. */
490 SV * const svret = sv_newmortal();
493 if (keysv || is_utf8) {
495 keysv = newSVpvn_utf8(key, klen, TRUE);
497 keysv = newSVsv(keysv);
499 mg_copy(MUTABLE_SV(hv), sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
501 mg_copy(MUTABLE_SV(hv), sv, key, klen);
503 if (flags & HVhek_FREEKEY)
506 MAGIC * const mg = mg_find(sv, PERL_MAGIC_tiedelem);
508 magic_existspack(svret, mg);
510 /* This cast somewhat evil, but I'm merely using NULL/
511 not NULL to return the boolean exists.
512 And I know hv is not NULL. */
513 return SvTRUE_NN(svret) ? (void *)hv : NULL;
515 #ifdef ENV_IS_CASELESS
516 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
517 /* XXX This code isn't UTF8 clean. */
518 char * const keysave = (char * const)key;
519 /* Will need to free this, so set FREEKEY flag. */
520 key = savepvn(key,klen);
521 key = (const char*)strupr((char*)key);
526 if (flags & HVhek_FREEKEY) {
529 flags |= HVhek_FREEKEY;
533 else if (action & HV_FETCH_ISSTORE) {
536 hv_magic_check (hv, &needs_copy, &needs_store);
538 const bool save_taint = TAINT_get;
539 if (keysv || is_utf8) {
541 keysv = newSVpvn_utf8(key, klen, TRUE);
544 TAINT_set(SvTAINTED(keysv));
545 keysv = sv_2mortal(newSVsv(keysv));
546 mg_copy(MUTABLE_SV(hv), val, (char*)keysv, HEf_SVKEY);
548 mg_copy(MUTABLE_SV(hv), val, key, klen);
551 TAINT_IF(save_taint);
552 #ifdef NO_TAINT_SUPPORT
553 PERL_UNUSED_VAR(save_taint);
556 if (flags & HVhek_FREEKEY)
560 #ifdef ENV_IS_CASELESS
561 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
562 /* XXX This code isn't UTF8 clean. */
563 const char *keysave = key;
564 /* Will need to free this, so set FREEKEY flag. */
565 key = savepvn(key,klen);
566 key = (const char*)strupr((char*)key);
571 if (flags & HVhek_FREEKEY) {
574 flags |= HVhek_FREEKEY;
582 if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
583 #ifdef DYNAMIC_ENV_FETCH /* if it's an %ENV lookup, we may get it on the fly */
584 || (SvRMAGICAL((const SV *)hv)
585 && mg_find((const SV *)hv, PERL_MAGIC_env))
590 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
592 HvARRAY(hv) = (HE**)array;
594 #ifdef DYNAMIC_ENV_FETCH
595 else if (action & HV_FETCH_ISEXISTS) {
596 /* for an %ENV exists, if we do an insert it's by a recursive
597 store call, so avoid creating HvARRAY(hv) right now. */
601 /* XXX remove at some point? */
602 if (flags & HVhek_FREEKEY)
609 if (is_utf8 && !(flags & HVhek_KEYCANONICAL)) {
610 char * const keysave = (char *)key;
611 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
615 flags &= ~HVhek_UTF8;
616 if (key != keysave) {
617 if (flags & HVhek_FREEKEY)
619 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
620 /* If the caller calculated a hash, it was on the sequence of
621 octets that are the UTF-8 form. We've now changed the sequence
622 of octets stored to that of the equivalent byte representation,
623 so the hash we need is different. */
628 if (keysv && (SvIsCOW_shared_hash(keysv))) {
630 keysv_hek = SvSHARED_HEK_FROM_PV(SvPVX_const(keysv));
631 hash = SvSHARED_HASH(keysv);
634 PERL_HASH(hash, key, klen);
636 masked_flags = (flags & HVhek_MASK);
638 #ifdef DYNAMIC_ENV_FETCH
639 if (!HvARRAY(hv)) entry = NULL;
643 entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
650 /* keysv is actually a HEK in disguise, so we can match just by
651 * comparing the HEK pointers in the HE chain. There is a slight
652 * caveat: on something like "\x80", which has both plain and utf8
653 * representations, perl's hashes do encoding-insensitive lookups,
654 * but preserve the encoding of the stored key. Thus a particular
655 * key could map to two different HEKs in PL_strtab. We only
656 * conclude 'not found' if all the flags are the same; otherwise
657 * we fall back to a full search (this should only happen in rare
660 int keysv_flags = HEK_FLAGS(keysv_hek);
661 HE *orig_entry = entry;
663 for (; entry; entry = HeNEXT(entry)) {
664 HEK *hek = HeKEY_hek(entry);
665 if (hek == keysv_hek)
667 if (HEK_FLAGS(hek) != keysv_flags)
668 break; /* need to do full match */
672 /* failed on shortcut - do full search loop */
676 for (; entry; entry = HeNEXT(entry)) {
677 if (HeHASH(entry) != hash) /* strings can't be equal */
679 if (HeKLEN(entry) != (I32)klen)
681 if (memNE(HeKEY(entry),key,klen)) /* is this it? */
683 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
687 if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
688 if (HeKFLAGS(entry) != masked_flags) {
689 /* We match if HVhek_UTF8 bit in our flags and hash key's
690 match. But if entry was set previously with HVhek_WASUTF8
691 and key now doesn't (or vice versa) then we should change
692 the key's flag, as this is assignment. */
693 if (HvSHAREKEYS(hv)) {
694 /* Need to swap the key we have for a key with the flags we
695 need. As keys are shared we can't just write to the
696 flag, so we share the new one, unshare the old one. */
697 HEK * const new_hek = share_hek_flags(key, klen, hash,
699 unshare_hek (HeKEY_hek(entry));
700 HeKEY_hek(entry) = new_hek;
702 else if (hv == PL_strtab) {
703 /* PL_strtab is usually the only hash without HvSHAREKEYS,
704 so putting this test here is cheap */
705 if (flags & HVhek_FREEKEY)
707 Perl_croak(aTHX_ S_strtab_error,
708 action & HV_FETCH_LVALUE ? "fetch" : "store");
711 HeKFLAGS(entry) = masked_flags;
712 if (masked_flags & HVhek_ENABLEHVKFLAGS)
715 if (HeVAL(entry) == &PL_sv_placeholder) {
716 /* yes, can store into placeholder slot */
717 if (action & HV_FETCH_LVALUE) {
719 /* This preserves behaviour with the old hv_fetch
720 implementation which at this point would bail out
721 with a break; (at "if we find a placeholder, we
722 pretend we haven't found anything")
724 That break mean that if a placeholder were found, it
725 caused a call into hv_store, which in turn would
726 check magic, and if there is no magic end up pretty
727 much back at this point (in hv_store's code). */
730 /* LVAL fetch which actually needs a store. */
732 HvPLACEHOLDERS(hv)--;
735 if (val != &PL_sv_placeholder)
736 HvPLACEHOLDERS(hv)--;
739 } else if (action & HV_FETCH_ISSTORE) {
740 SvREFCNT_dec(HeVAL(entry));
743 } else if (HeVAL(entry) == &PL_sv_placeholder) {
744 /* if we find a placeholder, we pretend we haven't found
748 if (flags & HVhek_FREEKEY)
751 return (void *) &HeVAL(entry);
757 #ifdef DYNAMIC_ENV_FETCH /* %ENV lookup? If so, try to fetch the value now */
758 if (!(action & HV_FETCH_ISSTORE)
759 && SvRMAGICAL((const SV *)hv)
760 && mg_find((const SV *)hv, PERL_MAGIC_env)) {
762 const char * const env = PerlEnv_ENVgetenv_len(key,&len);
764 sv = newSVpvn(env,len);
766 return hv_common(hv, keysv, key, klen, flags,
767 HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
773 if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
774 hv_notallowed(flags, key, klen,
775 "Attempt to access disallowed key '%" SVf "' in"
776 " a restricted hash");
778 if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
779 /* Not doing some form of store, so return failure. */
780 if (flags & HVhek_FREEKEY)
784 if (action & HV_FETCH_LVALUE) {
785 val = action & HV_FETCH_EMPTY_HE ? NULL : newSV(0);
787 /* At this point the old hv_fetch code would call to hv_store,
788 which in turn might do some tied magic. So we need to make that
789 magic check happen. */
790 /* gonna assign to this, so it better be there */
791 /* If a fetch-as-store fails on the fetch, then the action is to
792 recurse once into "hv_store". If we didn't do this, then that
793 recursive call would call the key conversion routine again.
794 However, as we replace the original key with the converted
795 key, this would result in a double conversion, which would show
796 up as a bug if the conversion routine is not idempotent.
797 Hence the use of HV_DISABLE_UVAR_XKEY. */
798 return hv_common(hv, keysv, key, klen, flags,
799 HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
801 /* XXX Surely that could leak if the fetch-was-store fails?
802 Just like the hv_fetch. */
806 /* Welcome to hv_store... */
809 /* Not sure if we can get here. I think the only case of oentry being
810 NULL is for %ENV with dynamic env fetch. But that should disappear
811 with magic in the previous code. */
814 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
816 HvARRAY(hv) = (HE**)array;
819 oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
822 /* share_hek_flags will do the free for us. This might be considered
825 HeKEY_hek(entry) = share_hek_flags(key, klen, hash, flags);
826 else if (hv == PL_strtab) {
827 /* PL_strtab is usually the only hash without HvSHAREKEYS, so putting
828 this test here is cheap */
829 if (flags & HVhek_FREEKEY)
831 Perl_croak(aTHX_ S_strtab_error,
832 action & HV_FETCH_LVALUE ? "fetch" : "store");
834 else /* gotta do the real thing */
835 HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
838 #ifdef PERL_HASH_RANDOMIZE_KEYS
839 /* This logic semi-randomizes the insert order in a bucket.
840 * Either we insert into the top, or the slot below the top,
841 * making it harder to see if there is a collision. We also
842 * reset the iterator randomizer if there is one.
844 in_collision = *oentry != NULL;
845 if ( *oentry && PL_HASH_RAND_BITS_ENABLED) {
847 PL_hash_rand_bits= ROTL_UV(PL_hash_rand_bits,1);
848 if ( PL_hash_rand_bits & 1 ) {
849 HeNEXT(entry) = HeNEXT(*oentry);
850 HeNEXT(*oentry) = entry;
852 HeNEXT(entry) = *oentry;
858 HeNEXT(entry) = *oentry;
861 #ifdef PERL_HASH_RANDOMIZE_KEYS
863 /* Currently this makes various tests warn in annoying ways.
864 * So Silenced for now. - Yves | bogus end of comment =>* /
865 if (HvAUX(hv)->xhv_riter != -1) {
866 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
867 "[TESTING] Inserting into a hash during each() traversal results in undefined behavior"
872 if (PL_HASH_RAND_BITS_ENABLED) {
873 if (PL_HASH_RAND_BITS_ENABLED == 1)
874 PL_hash_rand_bits += (PTRV)entry + 1; /* we don't bother to use ptr_hash here */
875 PL_hash_rand_bits= ROTL_UV(PL_hash_rand_bits,1);
877 HvAUX(hv)->xhv_rand= (U32)PL_hash_rand_bits;
881 if (val == &PL_sv_placeholder)
882 HvPLACEHOLDERS(hv)++;
883 if (masked_flags & HVhek_ENABLEHVKFLAGS)
886 xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
887 if ( in_collision && DO_HSPLIT(xhv) ) {
888 const STRLEN oldsize = xhv->xhv_max + 1;
889 const U32 items = (U32)HvPLACEHOLDERS_get(hv);
891 if (items /* hash has placeholders */
892 && !SvREADONLY(hv) /* but is not a restricted hash */) {
893 /* If this hash previously was a "restricted hash" and had
894 placeholders, but the "restricted" flag has been turned off,
895 then the placeholders no longer serve any useful purpose.
896 However, they have the downsides of taking up RAM, and adding
897 extra steps when finding used values. It's safe to clear them
898 at this point, even though Storable rebuilds restricted hashes by
899 putting in all the placeholders (first) before turning on the
900 readonly flag, because Storable always pre-splits the hash.
901 If we're lucky, then we may clear sufficient placeholders to
902 avoid needing to split the hash at all. */
903 clear_placeholders(hv, items);
905 hsplit(hv, oldsize, oldsize * 2);
907 hsplit(hv, oldsize, oldsize * 2);
911 return entry ? (void *) &HeVAL(entry) : NULL;
913 return (void *) entry;
917 S_hv_magic_check(HV *hv, bool *needs_copy, bool *needs_store)
919 const MAGIC *mg = SvMAGIC(hv);
921 PERL_ARGS_ASSERT_HV_MAGIC_CHECK;
926 if (isUPPER(mg->mg_type)) {
928 if (mg->mg_type == PERL_MAGIC_tied) {
929 *needs_store = FALSE;
930 return; /* We've set all there is to set. */
933 mg = mg->mg_moremagic;
938 =for apidoc hv_scalar
940 Evaluates the hash in scalar context and returns the result.
942 When the hash is tied dispatches through to the SCALAR method,
943 otherwise returns a mortal SV containing the number of keys
946 Note, prior to 5.25 this function returned what is now
947 returned by the hv_bucket_ratio() function.
953 Perl_hv_scalar(pTHX_ HV *hv)
957 PERL_ARGS_ASSERT_HV_SCALAR;
959 if (SvRMAGICAL(hv)) {
960 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_tied);
962 return magic_scalarpack(hv, mg);
966 sv_setuv(sv, HvUSEDKEYS(hv));
973 hv_pushkv(): push all the keys and/or values of a hash onto the stack.
974 The rough Perl equivalents:
979 Resets the hash's iterator.
981 flags : 1 = push keys
983 1|2 = push keys and values
984 XXX use symbolic flag constants at some point?
985 I might unroll the non-tied hv_iternext() in here at some point - DAPM
989 Perl_hv_pushkv(pTHX_ HV *hv, U32 flags)
992 bool tied = SvRMAGICAL(hv) && (mg_find(MUTABLE_SV(hv), PERL_MAGIC_tied)
993 #ifdef DYNAMIC_ENV_FETCH /* might not know number of keys yet */
994 || mg_find(MUTABLE_SV(hv), PERL_MAGIC_env)
999 PERL_ARGS_ASSERT_HV_PUSHKV;
1000 assert(flags); /* must be pushing at least one of keys and values */
1002 (void)hv_iterinit(hv);
1005 SSize_t ext = (flags == 3) ? 2 : 1;
1006 while ((entry = hv_iternext(hv))) {
1009 PUSHs(hv_iterkeysv(entry));
1011 PUSHs(hv_iterval(hv, entry));
1015 Size_t nkeys = HvUSEDKEYS(hv);
1021 /* 2*nkeys() should never be big enough to truncate or wrap */
1022 assert(nkeys <= (SSize_t_MAX >> 1));
1023 ext = nkeys * ((flags == 3) ? 2 : 1);
1025 EXTEND_MORTAL(nkeys);
1028 while ((entry = hv_iternext(hv))) {
1030 SV *keysv = newSVhek(HeKEY_hek(entry));
1032 PL_tmps_stack[++PL_tmps_ix] = keysv;
1036 PUSHs(HeVAL(entry));
1045 =for apidoc hv_bucket_ratio
1047 If the hash is tied dispatches through to the SCALAR tied method,
1048 otherwise if the hash contains no keys returns 0, otherwise returns
1049 a mortal sv containing a string specifying the number of used buckets,
1050 followed by a slash, followed by the number of available buckets.
1052 This function is expensive, it must scan all of the buckets
1053 to determine which are used, and the count is NOT cached.
1054 In a large hash this could be a lot of buckets.
1060 Perl_hv_bucket_ratio(pTHX_ HV *hv)
1064 PERL_ARGS_ASSERT_HV_BUCKET_RATIO;
1066 if (SvRMAGICAL(hv)) {
1067 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_tied);
1069 return magic_scalarpack(hv, mg);
1072 if (HvUSEDKEYS((HV *)hv)) {
1073 sv = sv_newmortal();
1074 Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
1075 (long)HvFILL(hv), (long)HvMAX(hv) + 1);
1084 =for apidoc hv_delete
1086 Deletes a key/value pair in the hash. The value's SV is removed from
1087 the hash, made mortal, and returned to the caller. The absolute
1088 value of C<klen> is the length of the key. If C<klen> is negative the
1089 key is assumed to be in UTF-8-encoded Unicode. The C<flags> value
1090 will normally be zero; if set to C<G_DISCARD> then C<NULL> will be returned.
1091 C<NULL> will also be returned if the key is not found.
1093 =for apidoc hv_delete_ent
1095 Deletes a key/value pair in the hash. The value SV is removed from the hash,
1096 made mortal, and returned to the caller. The C<flags> value will normally be
1097 zero; if set to C<G_DISCARD> then C<NULL> will be returned. C<NULL> will also
1098 be returned if the key is not found. C<hash> can be a valid precomputed hash
1099 value, or 0 to ask for it to be computed.
1105 S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
1106 int k_flags, I32 d_flags, U32 hash)
1112 bool is_utf8 = cBOOL(k_flags & HVhek_UTF8);
1114 HEK *keysv_hek = NULL;
1115 U8 mro_changes = 0; /* 1 = isa; 2 = package moved */
1120 if (SvRMAGICAL(hv)) {
1123 hv_magic_check (hv, &needs_copy, &needs_store);
1127 entry = (HE *) hv_common(hv, keysv, key, klen,
1128 k_flags & ~HVhek_FREEKEY,
1129 HV_FETCH_LVALUE|HV_DISABLE_UVAR_XKEY,
1131 sv = entry ? HeVAL(entry) : NULL;
1133 if (SvMAGICAL(sv)) {
1137 if (mg_find(sv, PERL_MAGIC_tiedelem)) {
1138 /* No longer an element */
1139 sv_unmagic(sv, PERL_MAGIC_tiedelem);
1142 return NULL; /* element cannot be deleted */
1144 #ifdef ENV_IS_CASELESS
1145 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
1146 /* XXX This code isn't UTF8 clean. */
1147 keysv = newSVpvn_flags(key, klen, SVs_TEMP);
1148 if (k_flags & HVhek_FREEKEY) {
1151 key = strupr(SvPVX(keysv));
1160 xhv = (XPVHV*)SvANY(hv);
1164 if (is_utf8 && !(k_flags & HVhek_KEYCANONICAL)) {
1165 const char * const keysave = key;
1166 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
1169 k_flags |= HVhek_UTF8;
1171 k_flags &= ~HVhek_UTF8;
1172 if (key != keysave) {
1173 if (k_flags & HVhek_FREEKEY) {
1174 /* This shouldn't happen if our caller does what we expect,
1175 but strictly the API allows it. */
1178 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
1180 HvHASKFLAGS_on(MUTABLE_SV(hv));
1183 if (keysv && (SvIsCOW_shared_hash(keysv))) {
1184 if (HvSHAREKEYS(hv))
1185 keysv_hek = SvSHARED_HEK_FROM_PV(SvPVX_const(keysv));
1186 hash = SvSHARED_HASH(keysv);
1189 PERL_HASH(hash, key, klen);
1191 masked_flags = (k_flags & HVhek_MASK);
1193 first_entry = oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
1200 /* keysv is actually a HEK in disguise, so we can match just by
1201 * comparing the HEK pointers in the HE chain. There is a slight
1202 * caveat: on something like "\x80", which has both plain and utf8
1203 * representations, perl's hashes do encoding-insensitive lookups,
1204 * but preserve the encoding of the stored key. Thus a particular
1205 * key could map to two different HEKs in PL_strtab. We only
1206 * conclude 'not found' if all the flags are the same; otherwise
1207 * we fall back to a full search (this should only happen in rare
1210 int keysv_flags = HEK_FLAGS(keysv_hek);
1212 for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
1213 HEK *hek = HeKEY_hek(entry);
1214 if (hek == keysv_hek)
1216 if (HEK_FLAGS(hek) != keysv_flags)
1217 break; /* need to do full match */
1221 /* failed on shortcut - do full search loop */
1222 oentry = first_entry;
1226 for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
1227 if (HeHASH(entry) != hash) /* strings can't be equal */
1229 if (HeKLEN(entry) != (I32)klen)
1231 if (memNE(HeKEY(entry),key,klen)) /* is this it? */
1233 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
1237 if (hv == PL_strtab) {
1238 if (k_flags & HVhek_FREEKEY)
1240 Perl_croak(aTHX_ S_strtab_error, "delete");
1243 /* if placeholder is here, it's already been deleted.... */
1244 if (HeVAL(entry) == &PL_sv_placeholder) {
1245 if (k_flags & HVhek_FREEKEY)
1249 if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1250 hv_notallowed(k_flags, key, klen,
1251 "Attempt to delete readonly key '%" SVf "' from"
1252 " a restricted hash");
1254 if (k_flags & HVhek_FREEKEY)
1257 /* If this is a stash and the key ends with ::, then someone is
1258 * deleting a package.
1260 if (HeVAL(entry) && HvENAME_get(hv)) {
1261 gv = (GV *)HeVAL(entry);
1262 if (keysv) key = SvPV(keysv, klen);
1264 (klen > 1 && key[klen-2] == ':' && key[klen-1] == ':')
1266 (klen == 1 && key[0] == ':')
1268 && (klen != 6 || hv!=PL_defstash || memNE(key,"main::",6))
1269 && SvTYPE(gv) == SVt_PVGV && (stash = GvHV((GV *)gv))
1270 && HvENAME_get(stash)) {
1271 /* A previous version of this code checked that the
1272 * GV was still in the symbol table by fetching the
1273 * GV with its name. That is not necessary (and
1274 * sometimes incorrect), as HvENAME cannot be set
1275 * on hv if it is not in the symtab. */
1277 /* Hang on to it for a bit. */
1278 SvREFCNT_inc_simple_void_NN(
1279 sv_2mortal((SV *)gv)
1282 else if (memEQs(key, klen, "ISA") && GvAV(gv)) {
1284 MAGIC *mg = mg_find((SV*)isa, PERL_MAGIC_isa);
1288 if (mg->mg_obj == (SV*)gv) {
1289 /* This is the only stash this ISA was used for.
1290 * The isaelem magic asserts if there's no
1291 * isa magic on the array, so explicitly
1292 * remove the magic on both the array and its
1293 * elements. @ISA shouldn't be /too/ large.
1298 end = svp + (AvFILLp(isa)+1);
1301 mg_free_type(*svp, PERL_MAGIC_isaelem);
1304 mg_free_type((SV*)GvAV(gv), PERL_MAGIC_isa);
1307 /* mg_obj is an array of stashes
1308 Note that the array doesn't keep a reference
1309 count on the stashes.
1311 AV *av = (AV*)mg->mg_obj;
1316 assert(SvTYPE(mg->mg_obj) == SVt_PVAV);
1318 /* remove the stash from the magic array */
1319 arrayp = svp = AvARRAY(av);
1320 items = AvFILLp(av) + 1;
1322 assert(*arrayp == (SV *)gv);
1324 /* avoid a double free on the last stash */
1326 /* The magic isn't MGf_REFCOUNTED, so release
1327 * the array manually.
1329 SvREFCNT_dec_NN(av);
1334 if (*svp == (SV*)gv)
1338 index = svp - arrayp;
1339 assert(index >= 0 && index <= AvFILLp(av));
1340 if (index < AvFILLp(av)) {
1341 arrayp[index] = arrayp[AvFILLp(av)];
1343 arrayp[AvFILLp(av)] = NULL;
1351 sv = d_flags & G_DISCARD ? HeVAL(entry) : sv_2mortal(HeVAL(entry));
1352 HeVAL(entry) = &PL_sv_placeholder;
1354 /* deletion of method from stash */
1355 if (isGV(sv) && isGV_with_GP(sv) && GvCVu(sv)
1357 mro_method_changed_in(hv);
1361 * If a restricted hash, rather than really deleting the entry, put
1362 * a placeholder there. This marks the key as being "approved", so
1363 * we can still access via not-really-existing key without raising
1367 /* We'll be saving this slot, so the number of allocated keys
1368 * doesn't go down, but the number placeholders goes up */
1369 HvPLACEHOLDERS(hv)++;
1371 *oentry = HeNEXT(entry);
1372 if (SvOOK(hv) && entry == HvAUX(hv)->xhv_eiter /* HvEITER(hv) */)
1375 if (SvOOK(hv) && HvLAZYDEL(hv) &&
1376 entry == HeNEXT(HvAUX(hv)->xhv_eiter))
1377 HeNEXT(HvAUX(hv)->xhv_eiter) = HeNEXT(entry);
1378 hv_free_ent(hv, entry);
1380 xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
1381 if (xhv->xhv_keys == 0)
1382 HvHASKFLAGS_off(hv);
1385 if (d_flags & G_DISCARD) {
1390 if (mro_changes == 1) mro_isa_changed_in(hv);
1391 else if (mro_changes == 2)
1392 mro_package_moved(NULL, stash, gv, 1);
1398 if (SvREADONLY(hv)) {
1399 hv_notallowed(k_flags, key, klen,
1400 "Attempt to delete disallowed key '%" SVf "' from"
1401 " a restricted hash");
1404 if (k_flags & HVhek_FREEKEY)
1411 S_hsplit(pTHX_ HV *hv, STRLEN const oldsize, STRLEN newsize)
1414 char *a = (char*) HvARRAY(hv);
1418 /* already have an HvAUX(hv) so we have to move it */
1420 /* no HvAUX() but array we are going to allocate is large enough
1421 * there is no point in saving the space for the iterator, and
1422 * speeds up later traversals. */
1423 ( ( hv != PL_strtab ) && ( newsize >= PERL_HV_ALLOC_AUX_SIZE ) )
1426 PERL_ARGS_ASSERT_HSPLIT;
1429 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1430 + (do_aux ? sizeof(struct xpvhv_aux) : 0), char);
1436 #ifdef PERL_HASH_RANDOMIZE_KEYS
1437 /* the idea of this is that we create a "random" value by hashing the address of
1438 * the array, we then use the low bit to decide if we insert at the top, or insert
1439 * second from top. After each such insert we rotate the hashed value. So we can
1440 * use the same hashed value over and over, and in normal build environments use
1441 * very few ops to do so. ROTL32() should produce a single machine operation. */
1442 if (PL_HASH_RAND_BITS_ENABLED) {
1443 if (PL_HASH_RAND_BITS_ENABLED == 1)
1444 PL_hash_rand_bits += ptr_hash((PTRV)a);
1445 PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,1);
1448 HvARRAY(hv) = (HE**) a;
1449 HvMAX(hv) = newsize - 1;
1450 /* before we zero the newly added memory, we
1451 * need to deal with the aux struct that may be there
1452 * or have been allocated by us*/
1454 struct xpvhv_aux *const dest
1455 = (struct xpvhv_aux*) &a[newsize * sizeof(HE*)];
1457 /* alread have an aux, copy the old one in place. */
1458 Move(&a[oldsize * sizeof(HE*)], dest, 1, struct xpvhv_aux);
1459 /* we reset the iterator's xhv_rand as well, so they get a totally new ordering */
1460 #ifdef PERL_HASH_RANDOMIZE_KEYS
1461 dest->xhv_rand = (U32)PL_hash_rand_bits;
1464 /* no existing aux structure, but we allocated space for one
1465 * so initialize it properly. This unrolls hv_auxinit() a bit,
1466 * since we have to do the realloc anyway. */
1467 /* first we set the iterator's xhv_rand so it can be copied into lastrand below */
1468 #ifdef PERL_HASH_RANDOMIZE_KEYS
1469 dest->xhv_rand = (U32)PL_hash_rand_bits;
1471 /* this is the "non realloc" part of the hv_auxinit() */
1472 (void)hv_auxinit_internal(dest);
1473 /* Turn on the OOK flag */
1477 /* now we can safely clear the second half */
1478 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1480 if (!HvTOTALKEYS(hv)) /* skip rest if no entries */
1486 HE **oentry = aep + i;
1489 if (!entry) /* non-existent */
1492 U32 j = (HeHASH(entry) & newsize);
1494 *oentry = HeNEXT(entry);
1495 #ifdef PERL_HASH_RANDOMIZE_KEYS
1496 /* if the target cell is empty or PL_HASH_RAND_BITS_ENABLED is false
1497 * insert to top, otherwise rotate the bucket rand 1 bit,
1498 * and use the new low bit to decide if we insert at top,
1499 * or next from top. IOW, we only rotate on a collision.*/
1500 if (aep[j] && PL_HASH_RAND_BITS_ENABLED) {
1501 PL_hash_rand_bits+= ROTL32(HeHASH(entry), 17);
1502 PL_hash_rand_bits= ROTL_UV(PL_hash_rand_bits,1);
1503 if (PL_hash_rand_bits & 1) {
1504 HeNEXT(entry)= HeNEXT(aep[j]);
1505 HeNEXT(aep[j])= entry;
1507 /* Note, this is structured in such a way as the optimizer
1508 * should eliminate the duplicated code here and below without
1509 * us needing to explicitly use a goto. */
1510 HeNEXT(entry) = aep[j];
1516 /* see comment above about duplicated code */
1517 HeNEXT(entry) = aep[j];
1522 oentry = &HeNEXT(entry);
1526 } while (i++ < oldsize);
1530 Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
1532 XPVHV* xhv = (XPVHV*)SvANY(hv);
1533 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 */
1539 PERL_ARGS_ASSERT_HV_KSPLIT;
1541 wantsize = (I32) newmax; /* possible truncation here */
1542 if (wantsize != newmax)
1545 wantsize= wantsize + (wantsize >> 1); /* wantsize *= 1.5 */
1546 if (wantsize < newmax) /* overflow detection */
1550 while (wantsize > newsize) {
1551 trysize = newsize << 1;
1552 if (trysize > newsize) {
1560 if (newsize <= oldsize)
1561 return; /* overflow detection */
1563 a = (char *) HvARRAY(hv);
1565 hsplit(hv, oldsize, newsize);
1567 Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1568 xhv->xhv_max = newsize - 1;
1569 HvARRAY(hv) = (HE **) a;
1573 /* IMO this should also handle cases where hv_max is smaller than hv_keys
1574 * as tied hashes could play silly buggers and mess us around. We will
1575 * do the right thing during hv_store() afterwards, but still - Yves */
1576 #define HV_SET_MAX_ADJUSTED_FOR_KEYS(hv,hv_max,hv_keys) STMT_START {\
1577 /* Can we use fewer buckets? (hv_max is always 2^n-1) */ \
1578 if (hv_max < PERL_HASH_DEFAULT_HvMAX) { \
1579 hv_max = PERL_HASH_DEFAULT_HvMAX; \
1581 while (hv_max > PERL_HASH_DEFAULT_HvMAX && hv_max + 1 >= hv_keys * 2) \
1582 hv_max = hv_max / 2; \
1584 HvMAX(hv) = hv_max; \
1589 Perl_newHVhv(pTHX_ HV *ohv)
1591 HV * const hv = newHV();
1594 if (!ohv || (!HvTOTALKEYS(ohv) && !SvMAGICAL((const SV *)ohv)))
1596 hv_max = HvMAX(ohv);
1598 if (!SvMAGICAL((const SV *)ohv)) {
1599 /* It's an ordinary hash, so copy it fast. AMS 20010804 */
1601 const bool shared = !!HvSHAREKEYS(ohv);
1602 HE **ents, ** const oents = (HE **)HvARRAY(ohv);
1604 Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
1607 /* In each bucket... */
1608 for (i = 0; i <= hv_max; i++) {
1610 HE *oent = oents[i];
1617 /* Copy the linked list of entries. */
1618 for (; oent; oent = HeNEXT(oent)) {
1619 const U32 hash = HeHASH(oent);
1620 const char * const key = HeKEY(oent);
1621 const STRLEN len = HeKLEN(oent);
1622 const int flags = HeKFLAGS(oent);
1623 HE * const ent = new_HE();
1624 SV *const val = HeVAL(oent);
1626 HeVAL(ent) = SvIMMORTAL(val) ? val : newSVsv(val);
1628 = shared ? share_hek_flags(key, len, hash, flags)
1629 : save_hek_flags(key, len, hash, flags);
1640 HvTOTALKEYS(hv) = HvTOTALKEYS(ohv);
1644 /* Iterate over ohv, copying keys and values one at a time. */
1646 const I32 riter = HvRITER_get(ohv);
1647 HE * const eiter = HvEITER_get(ohv);
1648 STRLEN hv_keys = HvTOTALKEYS(ohv);
1650 HV_SET_MAX_ADJUSTED_FOR_KEYS(hv,hv_max,hv_keys);
1653 while ((entry = hv_iternext_flags(ohv, 0))) {
1654 SV *val = hv_iterval(ohv,entry);
1655 SV * const keysv = HeSVKEY(entry);
1656 val = SvIMMORTAL(val) ? val : newSVsv(val);
1658 (void)hv_store_ent(hv, keysv, val, 0);
1660 (void)hv_store_flags(hv, HeKEY(entry), HeKLEN(entry), val,
1661 HeHASH(entry), HeKFLAGS(entry));
1663 HvRITER_set(ohv, riter);
1664 HvEITER_set(ohv, eiter);
1671 =for apidoc hv_copy_hints_hv
1673 A specialised version of L</newHVhv> for copying C<%^H>. C<ohv> must be
1674 a pointer to a hash (which may have C<%^H> magic, but should be generally
1675 non-magical), or C<NULL> (interpreted as an empty hash). The content
1676 of C<ohv> is copied to a new hash, which has the C<%^H>-specific magic
1677 added to it. A pointer to the new hash is returned.
1683 Perl_hv_copy_hints_hv(pTHX_ HV *const ohv)
1685 HV * const hv = newHV();
1688 STRLEN hv_max = HvMAX(ohv);
1689 STRLEN hv_keys = HvTOTALKEYS(ohv);
1691 const I32 riter = HvRITER_get(ohv);
1692 HE * const eiter = HvEITER_get(ohv);
1697 HV_SET_MAX_ADJUSTED_FOR_KEYS(hv,hv_max,hv_keys);
1700 while ((entry = hv_iternext_flags(ohv, 0))) {
1701 SV *const sv = newSVsv(hv_iterval(ohv,entry));
1702 SV *heksv = HeSVKEY(entry);
1703 if (!heksv && sv) heksv = newSVhek(HeKEY_hek(entry));
1704 if (sv) sv_magic(sv, NULL, PERL_MAGIC_hintselem,
1705 (char *)heksv, HEf_SVKEY);
1706 if (heksv == HeSVKEY(entry))
1707 (void)hv_store_ent(hv, heksv, sv, 0);
1709 (void)hv_common(hv, heksv, HeKEY(entry), HeKLEN(entry),
1710 HeKFLAGS(entry), HV_FETCH_ISSTORE|HV_FETCH_JUST_SV, sv, HeHASH(entry));
1711 SvREFCNT_dec_NN(heksv);
1714 HvRITER_set(ohv, riter);
1715 HvEITER_set(ohv, eiter);
1717 SvREFCNT_inc_simple_void_NN(hv);
1720 hv_magic(hv, NULL, PERL_MAGIC_hints);
1723 #undef HV_SET_MAX_ADJUSTED_FOR_KEYS
1725 /* like hv_free_ent, but returns the SV rather than freeing it */
1727 S_hv_free_ent_ret(pTHX_ HV *hv, HE *entry)
1731 PERL_ARGS_ASSERT_HV_FREE_ENT_RET;
1734 if (HeKLEN(entry) == HEf_SVKEY) {
1735 SvREFCNT_dec(HeKEY_sv(entry));
1736 Safefree(HeKEY_hek(entry));
1738 else if (HvSHAREKEYS(hv))
1739 unshare_hek(HeKEY_hek(entry));
1741 Safefree(HeKEY_hek(entry));
1748 Perl_hv_free_ent(pTHX_ HV *hv, HE *entry)
1752 PERL_ARGS_ASSERT_HV_FREE_ENT;
1756 val = hv_free_ent_ret(hv, entry);
1762 Perl_hv_delayfree_ent(pTHX_ HV *hv, HE *entry)
1764 PERL_ARGS_ASSERT_HV_DELAYFREE_ENT;
1768 /* SvREFCNT_inc to counter the SvREFCNT_dec in hv_free_ent */
1769 sv_2mortal(SvREFCNT_inc(HeVAL(entry))); /* free between statements */
1770 if (HeKLEN(entry) == HEf_SVKEY) {
1771 sv_2mortal(SvREFCNT_inc(HeKEY_sv(entry)));
1773 hv_free_ent(hv, entry);
1777 =for apidoc hv_clear
1779 Frees the all the elements of a hash, leaving it empty.
1780 The XS equivalent of C<%hash = ()>. See also L</hv_undef>.
1782 See L</av_clear> for a note about the hash possibly being invalid on
1789 Perl_hv_clear(pTHX_ HV *hv)
1797 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1799 xhv = (XPVHV*)SvANY(hv);
1801 /* avoid hv being freed when calling destructors below */
1803 PL_tmps_stack[++PL_tmps_ix] = SvREFCNT_inc_simple_NN(hv);
1804 orig_ix = PL_tmps_ix;
1805 if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
1806 /* restricted hash: convert all keys to placeholders */
1808 for (i = 0; i <= xhv->xhv_max; i++) {
1809 HE *entry = (HvARRAY(hv))[i];
1810 for (; entry; entry = HeNEXT(entry)) {
1811 /* not already placeholder */
1812 if (HeVAL(entry) != &PL_sv_placeholder) {
1814 if (SvREADONLY(HeVAL(entry))) {
1815 SV* const keysv = hv_iterkeysv(entry);
1816 Perl_croak_nocontext(
1817 "Attempt to delete readonly key '%" SVf "' from a restricted hash",
1820 SvREFCNT_dec_NN(HeVAL(entry));
1822 HeVAL(entry) = &PL_sv_placeholder;
1823 HvPLACEHOLDERS(hv)++;
1829 hv_free_entries(hv);
1830 HvPLACEHOLDERS_set(hv, 0);
1833 mg_clear(MUTABLE_SV(hv));
1835 HvHASKFLAGS_off(hv);
1839 mro_isa_changed_in(hv);
1840 HvEITER_set(hv, NULL);
1842 /* disarm hv's premature free guard */
1843 if (LIKELY(PL_tmps_ix == orig_ix))
1846 PL_tmps_stack[orig_ix] = &PL_sv_undef;
1847 SvREFCNT_dec_NN(hv);
1851 =for apidoc hv_clear_placeholders
1853 Clears any placeholders from a hash. If a restricted hash has any of its keys
1854 marked as readonly and the key is subsequently deleted, the key is not actually
1855 deleted but is marked by assigning it a value of C<&PL_sv_placeholder>. This tags
1856 it so it will be ignored by future operations such as iterating over the hash,
1857 but will still allow the hash to have a value reassigned to the key at some
1858 future point. This function clears any such placeholder keys from the hash.
1859 See C<L<Hash::Util::lock_keys()|Hash::Util/lock_keys>> for an example of its
1866 Perl_hv_clear_placeholders(pTHX_ HV *hv)
1868 const U32 items = (U32)HvPLACEHOLDERS_get(hv);
1870 PERL_ARGS_ASSERT_HV_CLEAR_PLACEHOLDERS;
1873 clear_placeholders(hv, items);
1877 S_clear_placeholders(pTHX_ HV *hv, U32 items)
1881 PERL_ARGS_ASSERT_CLEAR_PLACEHOLDERS;
1888 /* Loop down the linked list heads */
1889 HE **oentry = &(HvARRAY(hv))[i];
1892 while ((entry = *oentry)) {
1893 if (HeVAL(entry) == &PL_sv_placeholder) {
1894 *oentry = HeNEXT(entry);
1895 if (entry == HvEITER_get(hv))
1898 if (SvOOK(hv) && HvLAZYDEL(hv) &&
1899 entry == HeNEXT(HvAUX(hv)->xhv_eiter))
1900 HeNEXT(HvAUX(hv)->xhv_eiter) = HeNEXT(entry);
1901 hv_free_ent(hv, entry);
1906 I32 placeholders = HvPLACEHOLDERS_get(hv);
1907 HvTOTALKEYS(hv) -= (IV)placeholders;
1908 /* HvUSEDKEYS expanded */
1909 if ((HvTOTALKEYS(hv) - placeholders) == 0)
1910 HvHASKFLAGS_off(hv);
1911 HvPLACEHOLDERS_set(hv, 0);
1915 oentry = &HeNEXT(entry);
1919 /* You can't get here, hence assertion should always fail. */
1920 assert (items == 0);
1921 NOT_REACHED; /* NOTREACHED */
1925 S_hv_free_entries(pTHX_ HV *hv)
1928 XPVHV * const xhv = (XPVHV*)SvANY(hv);
1931 PERL_ARGS_ASSERT_HV_FREE_ENTRIES;
1933 while ((sv = Perl_hfree_next_entry(aTHX_ hv, &index))||xhv->xhv_keys) {
1939 /* hfree_next_entry()
1940 * For use only by S_hv_free_entries() and sv_clear().
1941 * Delete the next available HE from hv and return the associated SV.
1942 * Returns null on empty hash. Nevertheless null is not a reliable
1943 * indicator that the hash is empty, as the deleted entry may have a
1945 * indexp is a pointer to the current index into HvARRAY. The index should
1946 * initially be set to 0. hfree_next_entry() may update it. */
1949 Perl_hfree_next_entry(pTHX_ HV *hv, STRLEN *indexp)
1951 struct xpvhv_aux *iter;
1955 STRLEN orig_index = *indexp;
1958 PERL_ARGS_ASSERT_HFREE_NEXT_ENTRY;
1960 if (SvOOK(hv) && ((iter = HvAUX(hv)))) {
1961 if ((entry = iter->xhv_eiter)) {
1962 /* the iterator may get resurrected after each
1963 * destructor call, so check each time */
1964 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1966 hv_free_ent(hv, entry);
1967 /* warning: at this point HvARRAY may have been
1968 * re-allocated, HvMAX changed etc */
1970 iter = HvAUX(hv); /* may have been realloced */
1971 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1972 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
1973 #ifdef PERL_HASH_RANDOMIZE_KEYS
1974 iter->xhv_last_rand = iter->xhv_rand;
1979 if (!((XPVHV*)SvANY(hv))->xhv_keys)
1982 array = HvARRAY(hv);
1984 while ( ! ((entry = array[*indexp])) ) {
1985 if ((*indexp)++ >= HvMAX(hv))
1987 assert(*indexp != orig_index);
1989 array[*indexp] = HeNEXT(entry);
1990 ((XPVHV*) SvANY(hv))->xhv_keys--;
1992 if ( PL_phase != PERL_PHASE_DESTRUCT && HvENAME(hv)
1993 && HeVAL(entry) && isGV(HeVAL(entry))
1994 && GvHV(HeVAL(entry)) && HvENAME(GvHV(HeVAL(entry)))
1997 const char * const key = HePV(entry,klen);
1998 if ((klen > 1 && key[klen-1]==':' && key[klen-2]==':')
1999 || (klen == 1 && key[0] == ':')) {
2001 NULL, GvHV(HeVAL(entry)),
2002 (GV *)HeVAL(entry), 0
2006 return hv_free_ent_ret(hv, entry);
2011 =for apidoc hv_undef
2013 Undefines the hash. The XS equivalent of C<undef(%hash)>.
2015 As well as freeing all the elements of the hash (like C<hv_clear()>), this
2016 also frees any auxiliary data and storage associated with the hash.
2018 See L</av_clear> for a note about the hash possibly being invalid on
2025 Perl_hv_undef_flags(pTHX_ HV *hv, U32 flags)
2029 SSize_t orig_ix = PL_tmps_ix; /* silence compiler warning about unitialized vars */
2033 save = cBOOL(SvREFCNT(hv));
2034 DEBUG_A(Perl_hv_assert(aTHX_ hv));
2035 xhv = (XPVHV*)SvANY(hv);
2037 /* The name must be deleted before the call to hv_free_entries so that
2038 CVs are anonymised properly. But the effective name must be pre-
2039 served until after that call (and only deleted afterwards if the
2040 call originated from sv_clear). For stashes with one name that is
2041 both the canonical name and the effective name, hv_name_set has to
2042 allocate an array for storing the effective name. We can skip that
2043 during global destruction, as it does not matter where the CVs point
2044 if they will be freed anyway. */
2045 /* note that the code following prior to hv_free_entries is duplicated
2046 * in sv_clear(), and changes here should be done there too */
2047 if (PL_phase != PERL_PHASE_DESTRUCT && HvNAME(hv)) {
2048 if (PL_stashcache) {
2049 DEBUG_o(Perl_deb(aTHX_ "hv_undef_flags clearing PL_stashcache for '%"
2050 HEKf "'\n", HEKfARG(HvNAME_HEK(hv))));
2051 (void)hv_deletehek(PL_stashcache, HvNAME_HEK(hv), G_DISCARD);
2053 hv_name_set(hv, NULL, 0, 0);
2056 /* avoid hv being freed when calling destructors below */
2058 PL_tmps_stack[++PL_tmps_ix] = SvREFCNT_inc_simple_NN(hv);
2059 orig_ix = PL_tmps_ix;
2061 hv_free_entries(hv);
2063 struct mro_meta *meta;
2066 if (HvENAME_get(hv)) {
2067 if (PL_phase != PERL_PHASE_DESTRUCT)
2068 mro_isa_changed_in(hv);
2069 if (PL_stashcache) {
2070 DEBUG_o(Perl_deb(aTHX_ "hv_undef_flags clearing PL_stashcache for effective name '%"
2071 HEKf "'\n", HEKfARG(HvENAME_HEK(hv))));
2072 (void)hv_deletehek(PL_stashcache, HvENAME_HEK(hv), G_DISCARD);
2076 /* If this call originated from sv_clear, then we must check for
2077 * effective names that need freeing, as well as the usual name. */
2079 if (flags & HV_NAME_SETALL ? !!HvAUX(hv)->xhv_name_u.xhvnameu_name : !!name) {
2080 if (name && PL_stashcache) {
2081 DEBUG_o(Perl_deb(aTHX_ "hv_undef_flags clearing PL_stashcache for name '%"
2082 HEKf "'\n", HEKfARG(HvNAME_HEK(hv))));
2083 (void)hv_deletehek(PL_stashcache, HvNAME_HEK(hv), G_DISCARD);
2085 hv_name_set(hv, NULL, 0, flags);
2087 if((meta = HvAUX(hv)->xhv_mro_meta)) {
2088 if (meta->mro_linear_all) {
2089 SvREFCNT_dec_NN(meta->mro_linear_all);
2090 /* mro_linear_current is just acting as a shortcut pointer,
2094 /* Only the current MRO is stored, so this owns the data.
2096 SvREFCNT_dec(meta->mro_linear_current);
2097 SvREFCNT_dec(meta->mro_nextmethod);
2098 SvREFCNT_dec(meta->isa);
2099 SvREFCNT_dec(meta->super);
2101 HvAUX(hv)->xhv_mro_meta = NULL;
2103 if (!HvAUX(hv)->xhv_name_u.xhvnameu_name && ! HvAUX(hv)->xhv_backreferences)
2104 SvFLAGS(hv) &= ~SVf_OOK;
2107 Safefree(HvARRAY(hv));
2108 xhv->xhv_max = PERL_HASH_DEFAULT_HvMAX; /* HvMAX(hv) = 7 (it's a normal hash) */
2111 /* if we're freeing the HV, the SvMAGIC field has been reused for
2112 * other purposes, and so there can't be any placeholder magic */
2114 HvPLACEHOLDERS_set(hv, 0);
2117 mg_clear(MUTABLE_SV(hv));
2120 /* disarm hv's premature free guard */
2121 if (LIKELY(PL_tmps_ix == orig_ix))
2124 PL_tmps_stack[orig_ix] = &PL_sv_undef;
2125 SvREFCNT_dec_NN(hv);
2132 Returns the number of hash buckets that happen to be in use.
2134 This function is wrapped by the macro C<HvFILL>.
2136 As of perl 5.25 this function is used only for debugging
2137 purposes, and the number of used hash buckets is not
2138 in any way cached, thus this function can be costly
2139 to execute as it must iterate over all the buckets in the
2146 Perl_hv_fill(pTHX_ HV *const hv)
2149 HE **ents = HvARRAY(hv);
2151 PERL_UNUSED_CONTEXT;
2152 PERL_ARGS_ASSERT_HV_FILL;
2154 /* No keys implies no buckets used.
2155 One key can only possibly mean one bucket used. */
2156 if (HvTOTALKEYS(hv) < 2)
2157 return HvTOTALKEYS(hv);
2160 /* I wonder why we count down here...
2161 * Is it some micro-optimisation?
2162 * I would have thought counting up was better.
2165 HE *const *const last = ents + HvMAX(hv);
2166 count = last + 1 - ents;
2171 } while (++ents <= last);
2176 /* hash a pointer to a U32 - Used in the hash traversal randomization
2177 * and bucket order randomization code
2179 * this code was derived from Sereal, which was derived from autobox.
2182 PERL_STATIC_INLINE U32 S_ptr_hash(PTRV u) {
2185 * This is one of Thomas Wang's hash functions for 64-bit integers from:
2186 * http://www.concentric.net/~Ttwang/tech/inthash.htm
2188 u = (~u) + (u << 18);
2196 * This is one of Bob Jenkins' hash functions for 32-bit integers
2197 * from: http://burtleburtle.net/bob/hash/integer.html
2199 u = (u + 0x7ed55d16) + (u << 12);
2200 u = (u ^ 0xc761c23c) ^ (u >> 19);
2201 u = (u + 0x165667b1) + (u << 5);
2202 u = (u + 0xd3a2646c) ^ (u << 9);
2203 u = (u + 0xfd7046c5) + (u << 3);
2204 u = (u ^ 0xb55a4f09) ^ (u >> 16);
2209 static struct xpvhv_aux*
2210 S_hv_auxinit_internal(struct xpvhv_aux *iter) {
2211 PERL_ARGS_ASSERT_HV_AUXINIT_INTERNAL;
2212 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2213 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
2214 #ifdef PERL_HASH_RANDOMIZE_KEYS
2215 iter->xhv_last_rand = iter->xhv_rand;
2217 iter->xhv_name_u.xhvnameu_name = 0;
2218 iter->xhv_name_count = 0;
2219 iter->xhv_backreferences = 0;
2220 iter->xhv_mro_meta = NULL;
2221 iter->xhv_aux_flags = 0;
2226 static struct xpvhv_aux*
2227 S_hv_auxinit(pTHX_ HV *hv) {
2228 struct xpvhv_aux *iter;
2231 PERL_ARGS_ASSERT_HV_AUXINIT;
2235 Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
2236 + sizeof(struct xpvhv_aux), char);
2238 array = (char *) HvARRAY(hv);
2239 Renew(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
2240 + sizeof(struct xpvhv_aux), char);
2242 HvARRAY(hv) = (HE**)array;
2245 #ifdef PERL_HASH_RANDOMIZE_KEYS
2246 if (PL_HASH_RAND_BITS_ENABLED) {
2247 /* mix in some new state to PL_hash_rand_bits to "randomize" the traversal order*/
2248 if (PL_HASH_RAND_BITS_ENABLED == 1)
2249 PL_hash_rand_bits += ptr_hash((PTRV)array);
2250 PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,1);
2252 iter->xhv_rand = (U32)PL_hash_rand_bits;
2258 return hv_auxinit_internal(iter);
2262 =for apidoc hv_iterinit
2264 Prepares a starting point to traverse a hash table. Returns the number of
2265 keys in the hash, including placeholders (i.e. the same as C<HvTOTALKEYS(hv)>).
2266 The return value is currently only meaningful for hashes without tie magic.
2268 NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
2269 hash buckets that happen to be in use. If you still need that esoteric
2270 value, you can get it through the macro C<HvFILL(hv)>.
2277 Perl_hv_iterinit(pTHX_ HV *hv)
2279 PERL_ARGS_ASSERT_HV_ITERINIT;
2282 struct xpvhv_aux * iter = HvAUX(hv);
2283 HE * const entry = iter->xhv_eiter; /* HvEITER(hv) */
2284 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
2286 hv_free_ent(hv, entry);
2288 iter = HvAUX(hv); /* may have been reallocated */
2289 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2290 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
2291 #ifdef PERL_HASH_RANDOMIZE_KEYS
2292 iter->xhv_last_rand = iter->xhv_rand;
2298 /* note this includes placeholders! */
2299 return HvTOTALKEYS(hv);
2303 Perl_hv_riter_p(pTHX_ HV *hv) {
2304 struct xpvhv_aux *iter;
2306 PERL_ARGS_ASSERT_HV_RITER_P;
2308 iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2309 return &(iter->xhv_riter);
2313 Perl_hv_eiter_p(pTHX_ HV *hv) {
2314 struct xpvhv_aux *iter;
2316 PERL_ARGS_ASSERT_HV_EITER_P;
2318 iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2319 return &(iter->xhv_eiter);
2323 Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
2324 struct xpvhv_aux *iter;
2326 PERL_ARGS_ASSERT_HV_RITER_SET;
2334 iter = hv_auxinit(hv);
2336 iter->xhv_riter = riter;
2340 Perl_hv_rand_set(pTHX_ HV *hv, U32 new_xhv_rand) {
2341 struct xpvhv_aux *iter;
2343 PERL_ARGS_ASSERT_HV_RAND_SET;
2345 #ifdef PERL_HASH_RANDOMIZE_KEYS
2349 iter = hv_auxinit(hv);
2351 iter->xhv_rand = new_xhv_rand;
2353 Perl_croak(aTHX_ "This Perl has not been built with support for randomized hash key traversal but something called Perl_hv_rand_set().");
2358 Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
2359 struct xpvhv_aux *iter;
2361 PERL_ARGS_ASSERT_HV_EITER_SET;
2366 /* 0 is the default so don't go malloc()ing a new structure just to
2371 iter = hv_auxinit(hv);
2373 iter->xhv_eiter = eiter;
2377 Perl_hv_name_set(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2379 struct xpvhv_aux *iter;
2383 PERL_ARGS_ASSERT_HV_NAME_SET;
2386 Perl_croak(aTHX_ "panic: hv name too long (%" UVuf ")", (UV) len);
2390 if (iter->xhv_name_u.xhvnameu_name) {
2391 if(iter->xhv_name_count) {
2392 if(flags & HV_NAME_SETALL) {
2393 HEK ** const this_name = HvAUX(hv)->xhv_name_u.xhvnameu_names;
2394 HEK **hekp = this_name + (
2395 iter->xhv_name_count < 0
2396 ? -iter->xhv_name_count
2397 : iter->xhv_name_count
2399 while(hekp-- > this_name+1)
2400 unshare_hek_or_pvn(*hekp, 0, 0, 0);
2401 /* The first elem may be null. */
2402 if(*this_name) unshare_hek_or_pvn(*this_name, 0, 0, 0);
2403 Safefree(this_name);
2404 iter = HvAUX(hv); /* may been realloced */
2405 spot = &iter->xhv_name_u.xhvnameu_name;
2406 iter->xhv_name_count = 0;
2409 if(iter->xhv_name_count > 0) {
2410 /* shift some things over */
2412 iter->xhv_name_u.xhvnameu_names, iter->xhv_name_count + 1, HEK *
2414 spot = iter->xhv_name_u.xhvnameu_names;
2415 spot[iter->xhv_name_count] = spot[1];
2417 iter->xhv_name_count = -(iter->xhv_name_count + 1);
2419 else if(*(spot = iter->xhv_name_u.xhvnameu_names)) {
2420 unshare_hek_or_pvn(*spot, 0, 0, 0);
2424 else if (flags & HV_NAME_SETALL) {
2425 unshare_hek_or_pvn(iter->xhv_name_u.xhvnameu_name, 0, 0, 0);
2426 iter = HvAUX(hv); /* may been realloced */
2427 spot = &iter->xhv_name_u.xhvnameu_name;
2430 HEK * const existing_name = iter->xhv_name_u.xhvnameu_name;
2431 Newx(iter->xhv_name_u.xhvnameu_names, 2, HEK *);
2432 iter->xhv_name_count = -2;
2433 spot = iter->xhv_name_u.xhvnameu_names;
2434 spot[1] = existing_name;
2437 else { spot = &iter->xhv_name_u.xhvnameu_name; iter->xhv_name_count = 0; }
2442 iter = hv_auxinit(hv);
2443 spot = &iter->xhv_name_u.xhvnameu_name;
2445 PERL_HASH(hash, name, len);
2446 *spot = name ? share_hek(name, flags & SVf_UTF8 ? -(I32)len : (I32)len, hash) : NULL;
2450 This is basically sv_eq_flags() in sv.c, but we avoid the magic
2455 hek_eq_pvn_flags(pTHX_ const HEK *hek, const char* pv, const I32 pvlen, const U32 flags) {
2456 if ( (HEK_UTF8(hek) ? 1 : 0) != (flags & SVf_UTF8 ? 1 : 0) ) {
2457 if (flags & SVf_UTF8)
2458 return (bytes_cmp_utf8(
2459 (const U8*)HEK_KEY(hek), HEK_LEN(hek),
2460 (const U8*)pv, pvlen) == 0);
2462 return (bytes_cmp_utf8(
2463 (const U8*)pv, pvlen,
2464 (const U8*)HEK_KEY(hek), HEK_LEN(hek)) == 0);
2467 return HEK_LEN(hek) == pvlen && ((HEK_KEY(hek) == pv)
2468 || memEQ(HEK_KEY(hek), pv, pvlen));
2472 =for apidoc hv_ename_add
2474 Adds a name to a stash's internal list of effective names. See
2475 C<L</hv_ename_delete>>.
2477 This is called when a stash is assigned to a new location in the symbol
2484 Perl_hv_ename_add(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2486 struct xpvhv_aux *aux = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2489 PERL_ARGS_ASSERT_HV_ENAME_ADD;
2492 Perl_croak(aTHX_ "panic: hv name too long (%" UVuf ")", (UV) len);
2494 PERL_HASH(hash, name, len);
2496 if (aux->xhv_name_count) {
2497 I32 count = aux->xhv_name_count;
2498 HEK ** const xhv_name = aux->xhv_name_u.xhvnameu_names + (count<0);
2499 HEK **hekp = xhv_name + (count < 0 ? -count - 1 : count);
2500 while (hekp-- > xhv_name)
2504 (HEK_UTF8(*hekp) || (flags & SVf_UTF8))
2505 ? hek_eq_pvn_flags(aTHX_ *hekp, name, (I32)len, flags)
2506 : (HEK_LEN(*hekp) == (I32)len && memEQ(HEK_KEY(*hekp), name, len))
2508 if (hekp == xhv_name && count < 0)
2509 aux->xhv_name_count = -count;
2513 if (count < 0) aux->xhv_name_count--, count = -count;
2514 else aux->xhv_name_count++;
2515 Renew(aux->xhv_name_u.xhvnameu_names, count + 1, HEK *);
2516 (aux->xhv_name_u.xhvnameu_names)[count] = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
2519 HEK *existing_name = aux->xhv_name_u.xhvnameu_name;
2522 (HEK_UTF8(existing_name) || (flags & SVf_UTF8))
2523 ? hek_eq_pvn_flags(aTHX_ existing_name, name, (I32)len, flags)
2524 : (HEK_LEN(existing_name) == (I32)len && memEQ(HEK_KEY(existing_name), name, len))
2527 Newx(aux->xhv_name_u.xhvnameu_names, 2, HEK *);
2528 aux->xhv_name_count = existing_name ? 2 : -2;
2529 *aux->xhv_name_u.xhvnameu_names = existing_name;
2530 (aux->xhv_name_u.xhvnameu_names)[1] = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
2535 =for apidoc hv_ename_delete
2537 Removes a name from a stash's internal list of effective names. If this is
2538 the name returned by C<HvENAME>, then another name in the list will take
2539 its place (C<HvENAME> will use it).
2541 This is called when a stash is deleted from the symbol table.
2547 Perl_hv_ename_delete(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2549 struct xpvhv_aux *aux;
2551 PERL_ARGS_ASSERT_HV_ENAME_DELETE;
2554 Perl_croak(aTHX_ "panic: hv name too long (%" UVuf ")", (UV) len);
2556 if (!SvOOK(hv)) return;
2559 if (!aux->xhv_name_u.xhvnameu_name) return;
2561 if (aux->xhv_name_count) {
2562 HEK ** const namep = aux->xhv_name_u.xhvnameu_names;
2563 I32 const count = aux->xhv_name_count;
2564 HEK **victim = namep + (count < 0 ? -count : count);
2565 while (victim-- > namep + 1)
2567 (HEK_UTF8(*victim) || (flags & SVf_UTF8))
2568 ? hek_eq_pvn_flags(aTHX_ *victim, name, (I32)len, flags)
2569 : (HEK_LEN(*victim) == (I32)len && memEQ(HEK_KEY(*victim), name, len))
2571 unshare_hek_or_pvn(*victim, 0, 0, 0);
2572 aux = HvAUX(hv); /* may been realloced */
2573 if (count < 0) ++aux->xhv_name_count;
2574 else --aux->xhv_name_count;
2576 (aux->xhv_name_count == 1 || aux->xhv_name_count == -1)
2578 ) { /* if there are none left */
2580 aux->xhv_name_u.xhvnameu_names = NULL;
2581 aux->xhv_name_count = 0;
2584 /* Move the last one back to fill the empty slot. It
2585 does not matter what order they are in. */
2586 *victim = *(namep + (count < 0 ? -count : count) - 1);
2591 count > 0 && ((HEK_UTF8(*namep) || (flags & SVf_UTF8))
2592 ? hek_eq_pvn_flags(aTHX_ *namep, name, (I32)len, flags)
2593 : (HEK_LEN(*namep) == (I32)len && memEQ(HEK_KEY(*namep), name, len))
2596 aux->xhv_name_count = -count;
2600 (HEK_UTF8(aux->xhv_name_u.xhvnameu_name) || (flags & SVf_UTF8))
2601 ? hek_eq_pvn_flags(aTHX_ aux->xhv_name_u.xhvnameu_name, name, (I32)len, flags)
2602 : (HEK_LEN(aux->xhv_name_u.xhvnameu_name) == (I32)len &&
2603 memEQ(HEK_KEY(aux->xhv_name_u.xhvnameu_name), name, len))
2605 HEK * const namehek = aux->xhv_name_u.xhvnameu_name;
2606 Newx(aux->xhv_name_u.xhvnameu_names, 1, HEK *);
2607 *aux->xhv_name_u.xhvnameu_names = namehek;
2608 aux->xhv_name_count = -1;
2613 Perl_hv_backreferences_p(pTHX_ HV *hv) {
2614 PERL_ARGS_ASSERT_HV_BACKREFERENCES_P;
2615 /* See also Perl_sv_get_backrefs in sv.c where this logic is unrolled */
2617 struct xpvhv_aux * const iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2618 return &(iter->xhv_backreferences);
2623 Perl_hv_kill_backrefs(pTHX_ HV *hv) {
2626 PERL_ARGS_ASSERT_HV_KILL_BACKREFS;
2631 av = HvAUX(hv)->xhv_backreferences;
2634 HvAUX(hv)->xhv_backreferences = 0;
2635 Perl_sv_kill_backrefs(aTHX_ MUTABLE_SV(hv), av);
2636 if (SvTYPE(av) == SVt_PVAV)
2637 SvREFCNT_dec_NN(av);
2642 hv_iternext is implemented as a macro in hv.h
2644 =for apidoc hv_iternext
2646 Returns entries from a hash iterator. See C<L</hv_iterinit>>.
2648 You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
2649 iterator currently points to, without losing your place or invalidating your
2650 iterator. Note that in this case the current entry is deleted from the hash
2651 with your iterator holding the last reference to it. Your iterator is flagged
2652 to free the entry on the next call to C<hv_iternext>, so you must not discard
2653 your iterator immediately else the entry will leak - call C<hv_iternext> to
2654 trigger the resource deallocation.
2656 =for apidoc hv_iternext_flags
2658 Returns entries from a hash iterator. See C<L</hv_iterinit>> and
2660 The C<flags> value will normally be zero; if C<HV_ITERNEXT_WANTPLACEHOLDERS> is
2661 set the placeholders keys (for restricted hashes) will be returned in addition
2662 to normal keys. By default placeholders are automatically skipped over.
2663 Currently a placeholder is implemented with a value that is
2664 C<&PL_sv_placeholder>. Note that the implementation of placeholders and
2665 restricted hashes may change, and the implementation currently is
2666 insufficiently abstracted for any change to be tidy.
2668 =for apidoc Amnh||HV_ITERNEXT_WANTPLACEHOLDERS
2674 Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
2680 struct xpvhv_aux *iter;
2682 PERL_ARGS_ASSERT_HV_ITERNEXT_FLAGS;
2684 xhv = (XPVHV*)SvANY(hv);
2687 /* Too many things (well, pp_each at least) merrily assume that you can
2688 call hv_iternext without calling hv_iterinit, so we'll have to deal
2694 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2695 if (SvMAGICAL(hv) && SvRMAGICAL(hv)) {
2696 if ( ( mg = mg_find((const SV *)hv, PERL_MAGIC_tied) ) ) {
2697 SV * const key = sv_newmortal();
2699 sv_setsv(key, HeSVKEY_force(entry));
2700 SvREFCNT_dec(HeSVKEY(entry)); /* get rid of previous key */
2701 HeSVKEY_set(entry, NULL);
2707 /* one HE per MAGICAL hash */
2708 iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
2709 HvLAZYDEL_on(hv); /* make sure entry gets freed */
2711 Newxz(k, HEK_BASESIZE + sizeof(const SV *), char);
2713 HeKEY_hek(entry) = hek;
2714 HeKLEN(entry) = HEf_SVKEY;
2716 magic_nextpack(MUTABLE_SV(hv),mg,key);
2718 /* force key to stay around until next time */
2719 HeSVKEY_set(entry, SvREFCNT_inc_simple_NN(key));
2720 return entry; /* beware, hent_val is not set */
2722 SvREFCNT_dec(HeVAL(entry));
2723 Safefree(HeKEY_hek(entry));
2725 iter = HvAUX(hv); /* may been realloced */
2726 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
2731 #if defined(DYNAMIC_ENV_FETCH) && !defined(__riscos__) /* set up %ENV for iteration */
2732 if (!entry && SvRMAGICAL((const SV *)hv)
2733 && mg_find((const SV *)hv, PERL_MAGIC_env)) {
2736 /* The prime_env_iter() on VMS just loaded up new hash values
2737 * so the iteration count needs to be reset back to the beginning
2741 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2746 /* hv_iterinit now ensures this. */
2747 assert (HvARRAY(hv));
2749 /* At start of hash, entry is NULL. */
2752 entry = HeNEXT(entry);
2753 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2755 * Skip past any placeholders -- don't want to include them in
2758 while (entry && HeVAL(entry) == &PL_sv_placeholder) {
2759 entry = HeNEXT(entry);
2764 #ifdef PERL_HASH_RANDOMIZE_KEYS
2765 if (iter->xhv_last_rand != iter->xhv_rand) {
2766 if (iter->xhv_riter != -1) {
2767 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
2768 "Use of each() on hash after insertion without resetting hash iterator results in undefined behavior"
2772 iter = HvAUX(hv); /* may been realloced */
2773 iter->xhv_last_rand = iter->xhv_rand;
2777 /* Skip the entire loop if the hash is empty. */
2778 if ((flags & HV_ITERNEXT_WANTPLACEHOLDERS)
2779 ? HvTOTALKEYS(hv) : HvUSEDKEYS(hv)) {
2781 /* OK. Come to the end of the current list. Grab the next one. */
2783 iter->xhv_riter++; /* HvRITER(hv)++ */
2784 if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
2785 /* There is no next one. End of the hash. */
2786 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2787 #ifdef PERL_HASH_RANDOMIZE_KEYS
2788 iter->xhv_last_rand = iter->xhv_rand; /* reset xhv_last_rand so we can detect inserts during traversal */
2792 entry = (HvARRAY(hv))[ PERL_HASH_ITER_BUCKET(iter) & xhv->xhv_max ];
2794 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2795 /* If we have an entry, but it's a placeholder, don't count it.
2797 while (entry && HeVAL(entry) == &PL_sv_placeholder)
2798 entry = HeNEXT(entry);
2800 /* Will loop again if this linked list starts NULL
2801 (for HV_ITERNEXT_WANTPLACEHOLDERS)
2802 or if we run through it and find only placeholders. */
2806 iter->xhv_riter = -1;
2807 #ifdef PERL_HASH_RANDOMIZE_KEYS
2808 iter->xhv_last_rand = iter->xhv_rand;
2812 if (oldentry && HvLAZYDEL(hv)) { /* was deleted earlier? */
2814 hv_free_ent(hv, oldentry);
2817 iter = HvAUX(hv); /* may been realloced */
2818 iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
2823 =for apidoc hv_iterkey
2825 Returns the key from the current position of the hash iterator. See
2832 Perl_hv_iterkey(pTHX_ HE *entry, I32 *retlen)
2834 PERL_ARGS_ASSERT_HV_ITERKEY;
2836 if (HeKLEN(entry) == HEf_SVKEY) {
2838 char * const p = SvPV(HeKEY_sv(entry), len);
2843 *retlen = HeKLEN(entry);
2844 return HeKEY(entry);
2848 /* unlike hv_iterval(), this always returns a mortal copy of the key */
2850 =for apidoc hv_iterkeysv
2852 Returns the key as an C<SV*> from the current position of the hash
2853 iterator. The return value will always be a mortal copy of the key. Also
2854 see C<L</hv_iterinit>>.
2860 Perl_hv_iterkeysv(pTHX_ HE *entry)
2862 PERL_ARGS_ASSERT_HV_ITERKEYSV;
2864 return sv_2mortal(newSVhek(HeKEY_hek(entry)));
2868 =for apidoc hv_iterval
2870 Returns the value from the current position of the hash iterator. See
2877 Perl_hv_iterval(pTHX_ HV *hv, HE *entry)
2879 PERL_ARGS_ASSERT_HV_ITERVAL;
2881 if (SvRMAGICAL(hv)) {
2882 if (mg_find((const SV *)hv, PERL_MAGIC_tied)) {
2883 SV* const sv = sv_newmortal();
2884 if (HeKLEN(entry) == HEf_SVKEY)
2885 mg_copy(MUTABLE_SV(hv), sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
2887 mg_copy(MUTABLE_SV(hv), sv, HeKEY(entry), HeKLEN(entry));
2891 return HeVAL(entry);
2895 =for apidoc hv_iternextsv
2897 Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2904 Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
2906 HE * const he = hv_iternext_flags(hv, 0);
2908 PERL_ARGS_ASSERT_HV_ITERNEXTSV;
2912 *key = hv_iterkey(he, retlen);
2913 return hv_iterval(hv, he);
2920 =for apidoc hv_magic
2922 Adds magic to a hash. See C<L</sv_magic>>.
2927 /* possibly free a shared string if no one has access to it
2928 * len and hash must both be valid for str.
2931 Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
2933 unshare_hek_or_pvn (NULL, str, len, hash);
2938 Perl_unshare_hek(pTHX_ HEK *hek)
2941 unshare_hek_or_pvn(hek, NULL, 0, 0);
2944 /* possibly free a shared string if no one has access to it
2945 hek if non-NULL takes priority over the other 3, else str, len and hash
2946 are used. If so, len and hash must both be valid for str.
2949 S_unshare_hek_or_pvn(pTHX_ const HEK *hek, const char *str, I32 len, U32 hash)
2954 bool is_utf8 = FALSE;
2956 const char * const save = str;
2957 struct shared_he *he = NULL;
2960 /* Find the shared he which is just before us in memory. */
2961 he = (struct shared_he *)(((char *)hek)
2962 - STRUCT_OFFSET(struct shared_he,
2965 /* Assert that the caller passed us a genuine (or at least consistent)
2967 assert (he->shared_he_he.hent_hek == hek);
2969 if (he->shared_he_he.he_valu.hent_refcount - 1) {
2970 --he->shared_he_he.he_valu.hent_refcount;
2974 hash = HEK_HASH(hek);
2975 } else if (len < 0) {
2976 STRLEN tmplen = -len;
2978 /* See the note in hv_fetch(). --jhi */
2979 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2982 k_flags = HVhek_UTF8;
2984 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2987 /* what follows was the moral equivalent of:
2988 if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
2990 hv_delete(PL_strtab, str, len, G_DISCARD, hash);
2992 xhv = (XPVHV*)SvANY(PL_strtab);
2993 /* assert(xhv_array != 0) */
2994 oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2996 const HE *const he_he = &(he->shared_he_he);
2997 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
3002 const int flags_masked = k_flags & HVhek_MASK;
3003 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
3004 if (HeHASH(entry) != hash) /* strings can't be equal */
3006 if (HeKLEN(entry) != len)
3008 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
3010 if (HeKFLAGS(entry) != flags_masked)
3017 if (--entry->he_valu.hent_refcount == 0) {
3018 *oentry = HeNEXT(entry);
3020 xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
3025 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
3026 "Attempt to free nonexistent shared string '%s'%s"
3028 hek ? HEK_KEY(hek) : str,
3029 ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
3030 if (k_flags & HVhek_FREEKEY)
3034 /* get a (constant) string ptr from the global string table
3035 * string will get added if it is not already there.
3036 * len and hash must both be valid for str.
3039 Perl_share_hek(pTHX_ const char *str, SSize_t len, U32 hash)
3041 bool is_utf8 = FALSE;
3043 const char * const save = str;
3045 PERL_ARGS_ASSERT_SHARE_HEK;
3048 STRLEN tmplen = -len;
3050 /* See the note in hv_fetch(). --jhi */
3051 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
3053 /* If we were able to downgrade here, then than means that we were passed
3054 in a key which only had chars 0-255, but was utf8 encoded. */
3057 /* If we found we were able to downgrade the string to bytes, then
3058 we should flag that it needs upgrading on keys or each. Also flag
3059 that we need share_hek_flags to free the string. */
3061 PERL_HASH(hash, str, len);
3062 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
3066 return share_hek_flags (str, len, hash, flags);
3070 S_share_hek_flags(pTHX_ const char *str, STRLEN len, U32 hash, int flags)
3073 const int flags_masked = flags & HVhek_MASK;
3074 const U32 hindex = hash & (I32) HvMAX(PL_strtab);
3075 XPVHV * const xhv = (XPVHV*)SvANY(PL_strtab);
3077 PERL_ARGS_ASSERT_SHARE_HEK_FLAGS;
3079 if (UNLIKELY(len > (STRLEN) I32_MAX)) {
3080 Perl_croak_nocontext("Sorry, hash keys must be smaller than 2**31 bytes");
3083 /* what follows is the moral equivalent of:
3085 if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
3086 hv_store(PL_strtab, str, len, NULL, hash);
3088 Can't rehash the shared string table, so not sure if it's worth
3089 counting the number of entries in the linked list
3092 /* assert(xhv_array != 0) */
3093 entry = (HvARRAY(PL_strtab))[hindex];
3094 for (;entry; entry = HeNEXT(entry)) {
3095 if (HeHASH(entry) != hash) /* strings can't be equal */
3097 if (HeKLEN(entry) != (SSize_t) len)
3099 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
3101 if (HeKFLAGS(entry) != flags_masked)
3107 /* What used to be head of the list.
3108 If this is NULL, then we're the first entry for this slot, which
3109 means we need to increate fill. */
3110 struct shared_he *new_entry;
3113 HE **const head = &HvARRAY(PL_strtab)[hindex];
3114 HE *const next = *head;
3116 /* We don't actually store a HE from the arena and a regular HEK.
3117 Instead we allocate one chunk of memory big enough for both,
3118 and put the HEK straight after the HE. This way we can find the
3119 HE directly from the HEK.
3122 Newx(k, STRUCT_OFFSET(struct shared_he,
3123 shared_he_hek.hek_key[0]) + len + 2, char);
3124 new_entry = (struct shared_he *)k;
3125 entry = &(new_entry->shared_he_he);
3126 hek = &(new_entry->shared_he_hek);
3128 Copy(str, HEK_KEY(hek), len, char);
3129 HEK_KEY(hek)[len] = 0;
3131 HEK_HASH(hek) = hash;
3132 HEK_FLAGS(hek) = (unsigned char)flags_masked;
3134 /* Still "point" to the HEK, so that other code need not know what
3136 HeKEY_hek(entry) = hek;
3137 entry->he_valu.hent_refcount = 0;
3138 HeNEXT(entry) = next;
3141 xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
3142 if (!next) { /* initial entry? */
3143 } else if ( DO_HSPLIT(xhv) ) {
3144 const STRLEN oldsize = xhv->xhv_max + 1;
3145 hsplit(PL_strtab, oldsize, oldsize * 2);
3149 ++entry->he_valu.hent_refcount;
3151 if (flags & HVhek_FREEKEY)
3154 return HeKEY_hek(entry);
3158 Perl_hv_placeholders_p(pTHX_ HV *hv)
3160 MAGIC *mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
3162 PERL_ARGS_ASSERT_HV_PLACEHOLDERS_P;
3165 mg = sv_magicext(MUTABLE_SV(hv), 0, PERL_MAGIC_rhash, 0, 0, 0);
3168 Perl_die(aTHX_ "panic: hv_placeholders_p");
3171 return &(mg->mg_len);
3176 Perl_hv_placeholders_get(pTHX_ const HV *hv)
3178 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
3180 PERL_ARGS_ASSERT_HV_PLACEHOLDERS_GET;
3181 PERL_UNUSED_CONTEXT;
3183 return mg ? mg->mg_len : 0;
3187 Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
3189 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
3191 PERL_ARGS_ASSERT_HV_PLACEHOLDERS_SET;
3196 if (!sv_magicext(MUTABLE_SV(hv), 0, PERL_MAGIC_rhash, 0, 0, ph))
3197 Perl_die(aTHX_ "panic: hv_placeholders_set");
3199 /* else we don't need to add magic to record 0 placeholders. */
3203 S_refcounted_he_value(pTHX_ const struct refcounted_he *he)
3207 PERL_ARGS_ASSERT_REFCOUNTED_HE_VALUE;
3209 switch(he->refcounted_he_data[0] & HVrhek_typemask) {
3214 value = &PL_sv_placeholder;
3217 value = newSViv(he->refcounted_he_val.refcounted_he_u_iv);
3220 value = newSVuv(he->refcounted_he_val.refcounted_he_u_uv);
3223 case HVrhek_PV_UTF8:
3224 /* Create a string SV that directly points to the bytes in our
3226 value = newSV_type(SVt_PV);
3227 SvPV_set(value, (char *) he->refcounted_he_data + 1);
3228 SvCUR_set(value, he->refcounted_he_val.refcounted_he_u_len);
3229 /* This stops anything trying to free it */
3230 SvLEN_set(value, 0);
3232 SvREADONLY_on(value);
3233 if ((he->refcounted_he_data[0] & HVrhek_typemask) == HVrhek_PV_UTF8)
3237 Perl_croak(aTHX_ "panic: refcounted_he_value bad flags %" UVxf,
3238 (UV)he->refcounted_he_data[0]);
3244 =for apidoc refcounted_he_chain_2hv
3246 Generates and returns a C<HV *> representing the content of a
3247 C<refcounted_he> chain.
3248 C<flags> is currently unused and must be zero.
3253 Perl_refcounted_he_chain_2hv(pTHX_ const struct refcounted_he *chain, U32 flags)
3256 U32 placeholders, max;
3259 Perl_croak(aTHX_ "panic: refcounted_he_chain_2hv bad flags %" UVxf,
3262 /* We could chase the chain once to get an idea of the number of keys,
3263 and call ksplit. But for now we'll make a potentially inefficient
3264 hash with only 8 entries in its array. */
3269 Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(max + 1), char);
3270 HvARRAY(hv) = (HE**)array;
3276 U32 hash = chain->refcounted_he_hash;
3278 U32 hash = HEK_HASH(chain->refcounted_he_hek);
3280 HE **oentry = &((HvARRAY(hv))[hash & max]);
3281 HE *entry = *oentry;
3284 for (; entry; entry = HeNEXT(entry)) {
3285 if (HeHASH(entry) == hash) {
3286 /* We might have a duplicate key here. If so, entry is older
3287 than the key we've already put in the hash, so if they are
3288 the same, skip adding entry. */
3290 const STRLEN klen = HeKLEN(entry);
3291 const char *const key = HeKEY(entry);
3292 if (klen == chain->refcounted_he_keylen
3293 && (!!HeKUTF8(entry)
3294 == !!(chain->refcounted_he_data[0] & HVhek_UTF8))
3295 && memEQ(key, REF_HE_KEY(chain), klen))
3298 if (HeKEY_hek(entry) == chain->refcounted_he_hek)
3300 if (HeKLEN(entry) == HEK_LEN(chain->refcounted_he_hek)
3301 && HeKUTF8(entry) == HEK_UTF8(chain->refcounted_he_hek)
3302 && memEQ(HeKEY(entry), HEK_KEY(chain->refcounted_he_hek),
3313 = share_hek_flags(REF_HE_KEY(chain),
3314 chain->refcounted_he_keylen,
3315 chain->refcounted_he_hash,
3316 (chain->refcounted_he_data[0]
3317 & (HVhek_UTF8|HVhek_WASUTF8)));
3319 HeKEY_hek(entry) = share_hek_hek(chain->refcounted_he_hek);
3321 value = refcounted_he_value(chain);
3322 if (value == &PL_sv_placeholder)
3324 HeVAL(entry) = value;
3326 /* Link it into the chain. */
3327 HeNEXT(entry) = *oentry;
3333 chain = chain->refcounted_he_next;
3337 clear_placeholders(hv, placeholders);
3338 HvTOTALKEYS(hv) -= placeholders;
3341 /* We could check in the loop to see if we encounter any keys with key
3342 flags, but it's probably not worth it, as this per-hash flag is only
3343 really meant as an optimisation for things like Storable. */
3345 DEBUG_A(Perl_hv_assert(aTHX_ hv));
3351 =for apidoc refcounted_he_fetch_pvn
3353 Search along a C<refcounted_he> chain for an entry with the key specified
3354 by C<keypv> and C<keylen>. If C<flags> has the C<REFCOUNTED_HE_KEY_UTF8>
3355 bit set, the key octets are interpreted as UTF-8, otherwise they
3356 are interpreted as Latin-1. C<hash> is a precomputed hash of the key
3357 string, or zero if it has not been precomputed. Returns a mortal scalar
3358 representing the value associated with the key, or C<&PL_sv_placeholder>
3359 if there is no value associated with the key.
3365 Perl_refcounted_he_fetch_pvn(pTHX_ const struct refcounted_he *chain,
3366 const char *keypv, STRLEN keylen, U32 hash, U32 flags)
3369 PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_PVN;
3371 if (flags & ~(REFCOUNTED_HE_KEY_UTF8|REFCOUNTED_HE_EXISTS))
3372 Perl_croak(aTHX_ "panic: refcounted_he_fetch_pvn bad flags %" UVxf,
3376 if (flags & REFCOUNTED_HE_KEY_UTF8) {
3377 /* For searching purposes, canonicalise to Latin-1 where possible. */
3378 const char *keyend = keypv + keylen, *p;
3379 STRLEN nonascii_count = 0;
3380 for (p = keypv; p != keyend; p++) {
3381 if (! UTF8_IS_INVARIANT(*p)) {
3382 if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(p, keyend)) {
3383 goto canonicalised_key;
3389 if (nonascii_count) {
3391 const char *p = keypv, *keyend = keypv + keylen;
3392 keylen -= nonascii_count;
3393 Newx(q, keylen, char);
3396 for (; p != keyend; p++, q++) {
3398 if (UTF8_IS_INVARIANT(c)) {
3403 *q = (char) EIGHT_BIT_UTF8_TO_NATIVE(c, *p);
3407 flags &= ~REFCOUNTED_HE_KEY_UTF8;
3408 canonicalised_key: ;
3410 utf8_flag = (flags & REFCOUNTED_HE_KEY_UTF8) ? HVhek_UTF8 : 0;
3412 PERL_HASH(hash, keypv, keylen);
3414 for (; chain; chain = chain->refcounted_he_next) {
3417 hash == chain->refcounted_he_hash &&
3418 keylen == chain->refcounted_he_keylen &&
3419 memEQ(REF_HE_KEY(chain), keypv, keylen) &&
3420 utf8_flag == (chain->refcounted_he_data[0] & HVhek_UTF8)
3422 hash == HEK_HASH(chain->refcounted_he_hek) &&
3423 keylen == (STRLEN)HEK_LEN(chain->refcounted_he_hek) &&
3424 memEQ(HEK_KEY(chain->refcounted_he_hek), keypv, keylen) &&
3425 utf8_flag == (HEK_FLAGS(chain->refcounted_he_hek) & HVhek_UTF8)
3428 if (flags & REFCOUNTED_HE_EXISTS)
3429 return (chain->refcounted_he_data[0] & HVrhek_typemask)
3431 ? NULL : &PL_sv_yes;
3432 return sv_2mortal(refcounted_he_value(chain));
3436 return flags & REFCOUNTED_HE_EXISTS ? NULL : &PL_sv_placeholder;
3440 =for apidoc refcounted_he_fetch_pv
3442 Like L</refcounted_he_fetch_pvn>, but takes a nul-terminated string
3443 instead of a string/length pair.
3449 Perl_refcounted_he_fetch_pv(pTHX_ const struct refcounted_he *chain,
3450 const char *key, U32 hash, U32 flags)
3452 PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_PV;
3453 return refcounted_he_fetch_pvn(chain, key, strlen(key), hash, flags);
3457 =for apidoc refcounted_he_fetch_sv
3459 Like L</refcounted_he_fetch_pvn>, but takes a Perl scalar instead of a
3466 Perl_refcounted_he_fetch_sv(pTHX_ const struct refcounted_he *chain,
3467 SV *key, U32 hash, U32 flags)
3471 PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_SV;
3472 if (flags & REFCOUNTED_HE_KEY_UTF8)
3473 Perl_croak(aTHX_ "panic: refcounted_he_fetch_sv bad flags %" UVxf,
3475 keypv = SvPV_const(key, keylen);
3477 flags |= REFCOUNTED_HE_KEY_UTF8;
3478 if (!hash && SvIsCOW_shared_hash(key))
3479 hash = SvSHARED_HASH(key);
3480 return refcounted_he_fetch_pvn(chain, keypv, keylen, hash, flags);
3484 =for apidoc refcounted_he_new_pvn
3486 Creates a new C<refcounted_he>. This consists of a single key/value
3487 pair and a reference to an existing C<refcounted_he> chain (which may
3488 be empty), and thus forms a longer chain. When using the longer chain,
3489 the new key/value pair takes precedence over any entry for the same key
3490 further along the chain.
3492 The new key is specified by C<keypv> and C<keylen>. If C<flags> has
3493 the C<REFCOUNTED_HE_KEY_UTF8> bit set, the key octets are interpreted
3494 as UTF-8, otherwise they are interpreted as Latin-1. C<hash> is
3495 a precomputed hash of the key string, or zero if it has not been
3498 C<value> is the scalar value to store for this key. C<value> is copied
3499 by this function, which thus does not take ownership of any reference
3500 to it, and later changes to the scalar will not be reflected in the
3501 value visible in the C<refcounted_he>. Complex types of scalar will not
3502 be stored with referential integrity, but will be coerced to strings.
3503 C<value> may be either null or C<&PL_sv_placeholder> to indicate that no
3504 value is to be associated with the key; this, as with any non-null value,
3505 takes precedence over the existence of a value for the key further along
3508 C<parent> points to the rest of the C<refcounted_he> chain to be
3509 attached to the new C<refcounted_he>. This function takes ownership
3510 of one reference to C<parent>, and returns one reference to the new
3516 struct refcounted_he *
3517 Perl_refcounted_he_new_pvn(pTHX_ struct refcounted_he *parent,
3518 const char *keypv, STRLEN keylen, U32 hash, SV *value, U32 flags)
3520 STRLEN value_len = 0;
3521 const char *value_p = NULL;
3525 STRLEN key_offset = 1;
3526 struct refcounted_he *he;
3527 PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_PVN;
3529 if (!value || value == &PL_sv_placeholder) {
3530 value_type = HVrhek_delete;
3531 } else if (SvPOK(value)) {
3532 value_type = HVrhek_PV;
3533 } else if (SvIOK(value)) {
3534 value_type = SvUOK((const SV *)value) ? HVrhek_UV : HVrhek_IV;
3535 } else if (!SvOK(value)) {
3536 value_type = HVrhek_undef;
3538 value_type = HVrhek_PV;
3540 is_pv = value_type == HVrhek_PV;
3542 /* Do it this way so that the SvUTF8() test is after the SvPV, in case
3543 the value is overloaded, and doesn't yet have the UTF-8flag set. */
3544 value_p = SvPV_const(value, value_len);
3546 value_type = HVrhek_PV_UTF8;
3547 key_offset = value_len + 2;
3549 hekflags = value_type;
3551 if (flags & REFCOUNTED_HE_KEY_UTF8) {
3552 /* Canonicalise to Latin-1 where possible. */
3553 const char *keyend = keypv + keylen, *p;
3554 STRLEN nonascii_count = 0;
3555 for (p = keypv; p != keyend; p++) {
3556 if (! UTF8_IS_INVARIANT(*p)) {
3557 if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(p, keyend)) {
3558 goto canonicalised_key;
3564 if (nonascii_count) {
3566 const char *p = keypv, *keyend = keypv + keylen;
3567 keylen -= nonascii_count;
3568 Newx(q, keylen, char);
3571 for (; p != keyend; p++, q++) {
3573 if (UTF8_IS_INVARIANT(c)) {
3578 *q = (char) EIGHT_BIT_UTF8_TO_NATIVE(c, *p);
3582 flags &= ~REFCOUNTED_HE_KEY_UTF8;
3583 canonicalised_key: ;
3585 if (flags & REFCOUNTED_HE_KEY_UTF8)
3586 hekflags |= HVhek_UTF8;
3588 PERL_HASH(hash, keypv, keylen);
3591 he = (struct refcounted_he*)
3592 PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
3596 he = (struct refcounted_he*)
3597 PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
3601 he->refcounted_he_next = parent;
3604 Copy(value_p, he->refcounted_he_data + 1, value_len + 1, char);
3605 he->refcounted_he_val.refcounted_he_u_len = value_len;
3606 } else if (value_type == HVrhek_IV) {
3607 he->refcounted_he_val.refcounted_he_u_iv = SvIVX(value);
3608 } else if (value_type == HVrhek_UV) {
3609 he->refcounted_he_val.refcounted_he_u_uv = SvUVX(value);
3613 he->refcounted_he_hash = hash;
3614 he->refcounted_he_keylen = keylen;
3615 Copy(keypv, he->refcounted_he_data + key_offset, keylen, char);
3617 he->refcounted_he_hek = share_hek_flags(keypv, keylen, hash, hekflags);
3620 he->refcounted_he_data[0] = hekflags;
3621 he->refcounted_he_refcnt = 1;
3627 =for apidoc refcounted_he_new_pv
3629 Like L</refcounted_he_new_pvn>, but takes a nul-terminated string instead
3630 of a string/length pair.
3635 struct refcounted_he *
3636 Perl_refcounted_he_new_pv(pTHX_ struct refcounted_he *parent,
3637 const char *key, U32 hash, SV *value, U32 flags)
3639 PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_PV;
3640 return refcounted_he_new_pvn(parent, key, strlen(key), hash, value, flags);
3644 =for apidoc refcounted_he_new_sv
3646 Like L</refcounted_he_new_pvn>, but takes a Perl scalar instead of a
3652 struct refcounted_he *
3653 Perl_refcounted_he_new_sv(pTHX_ struct refcounted_he *parent,
3654 SV *key, U32 hash, SV *value, U32 flags)
3658 PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_SV;
3659 if (flags & REFCOUNTED_HE_KEY_UTF8)
3660 Perl_croak(aTHX_ "panic: refcounted_he_new_sv bad flags %" UVxf,
3662 keypv = SvPV_const(key, keylen);
3664 flags |= REFCOUNTED_HE_KEY_UTF8;
3665 if (!hash && SvIsCOW_shared_hash(key))
3666 hash = SvSHARED_HASH(key);
3667 return refcounted_he_new_pvn(parent, keypv, keylen, hash, value, flags);
3671 =for apidoc refcounted_he_free
3673 Decrements the reference count of a C<refcounted_he> by one. If the
3674 reference count reaches zero the structure's memory is freed, which
3675 (recursively) causes a reduction of its parent C<refcounted_he>'s
3676 reference count. It is safe to pass a null pointer to this function:
3677 no action occurs in this case.
3683 Perl_refcounted_he_free(pTHX_ struct refcounted_he *he) {
3686 PERL_UNUSED_CONTEXT;
3689 struct refcounted_he *copy;
3693 new_count = --he->refcounted_he_refcnt;
3694 HINTS_REFCNT_UNLOCK;
3700 #ifndef USE_ITHREADS
3701 unshare_hek_or_pvn (he->refcounted_he_hek, 0, 0, 0);
3704 he = he->refcounted_he_next;
3705 PerlMemShared_free(copy);
3710 =for apidoc refcounted_he_inc
3712 Increment the reference count of a C<refcounted_he>. The pointer to the
3713 C<refcounted_he> is also returned. It is safe to pass a null pointer
3714 to this function: no action occurs and a null pointer is returned.
3719 struct refcounted_he *
3720 Perl_refcounted_he_inc(pTHX_ struct refcounted_he *he)
3724 PERL_UNUSED_CONTEXT;
3727 he->refcounted_he_refcnt++;
3728 HINTS_REFCNT_UNLOCK;
3734 =for apidoc_section COP Hint Hashes
3735 =for apidoc cop_fetch_label
3737 Returns the label attached to a cop, and stores its length in bytes into
3739 Upon return, C<*flags> will be set to either C<SVf_UTF8> or 0.
3741 Alternatively, use the macro C<L</CopLABEL_len_flags>>;
3742 or if you don't need to know if the label is UTF-8 or not, the macro
3743 C<L</CopLABEL_len>>;
3744 or if you additionally dont need to know the length, C<L</CopLABEL>>.
3749 /* pp_entereval is aware that labels are stored with a key ':' at the top of
3752 Perl_cop_fetch_label(pTHX_ COP *const cop, STRLEN *len, U32 *flags) {
3753 struct refcounted_he *const chain = cop->cop_hints_hash;
3755 PERL_ARGS_ASSERT_COP_FETCH_LABEL;
3756 PERL_UNUSED_CONTEXT;
3761 if (chain->refcounted_he_keylen != 1)
3763 if (*REF_HE_KEY(chain) != ':')
3766 if ((STRLEN)HEK_LEN(chain->refcounted_he_hek) != 1)
3768 if (*HEK_KEY(chain->refcounted_he_hek) != ':')
3771 /* Stop anyone trying to really mess us up by adding their own value for
3773 if ((chain->refcounted_he_data[0] & HVrhek_typemask) != HVrhek_PV
3774 && (chain->refcounted_he_data[0] & HVrhek_typemask) != HVrhek_PV_UTF8)
3778 *len = chain->refcounted_he_val.refcounted_he_u_len;
3780 *flags = ((chain->refcounted_he_data[0] & HVrhek_typemask)
3781 == HVrhek_PV_UTF8) ? SVf_UTF8 : 0;
3783 return chain->refcounted_he_data + 1;
3787 =for apidoc cop_store_label
3789 Save a label into a C<cop_hints_hash>.
3790 You need to set flags to C<SVf_UTF8>
3791 for a UTF-8 label. Any other flag is ignored.
3797 Perl_cop_store_label(pTHX_ COP *const cop, const char *label, STRLEN len,
3801 PERL_ARGS_ASSERT_COP_STORE_LABEL;
3803 if (flags & ~(SVf_UTF8))
3804 Perl_croak(aTHX_ "panic: cop_store_label illegal flag bits 0x%" UVxf,
3806 labelsv = newSVpvn_flags(label, len, SVs_TEMP);
3807 if (flags & SVf_UTF8)
3810 = refcounted_he_new_pvs(cop->cop_hints_hash, ":", labelsv, 0);
3814 =for apidoc_section HV Handling
3815 =for apidoc hv_assert
3817 Check that a hash is in an internally consistent state.
3825 Perl_hv_assert(pTHX_ HV *hv)
3829 int placeholders = 0;
3832 const I32 riter = HvRITER_get(hv);
3833 HE *eiter = HvEITER_get(hv);
3835 PERL_ARGS_ASSERT_HV_ASSERT;
3837 (void)hv_iterinit(hv);
3839 while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
3840 /* sanity check the values */
3841 if (HeVAL(entry) == &PL_sv_placeholder)
3845 /* sanity check the keys */
3846 if (HeSVKEY(entry)) {
3847 NOOP; /* Don't know what to check on SV keys. */
3848 } else if (HeKUTF8(entry)) {
3850 if (HeKWASUTF8(entry)) {
3851 PerlIO_printf(Perl_debug_log,
3852 "hash key has both WASUTF8 and UTF8: '%.*s'\n",
3853 (int) HeKLEN(entry), HeKEY(entry));
3856 } else if (HeKWASUTF8(entry))
3859 if (!SvTIED_mg((const SV *)hv, PERL_MAGIC_tied)) {
3860 static const char bad_count[] = "Count %d %s(s), but hash reports %d\n";
3861 const int nhashkeys = HvUSEDKEYS(hv);
3862 const int nhashplaceholders = HvPLACEHOLDERS_get(hv);
3864 if (nhashkeys != real) {
3865 PerlIO_printf(Perl_debug_log, bad_count, real, "keys", nhashkeys );
3868 if (nhashplaceholders != placeholders) {
3869 PerlIO_printf(Perl_debug_log, bad_count, placeholders, "placeholder", nhashplaceholders );
3873 if (withflags && ! HvHASKFLAGS(hv)) {
3874 PerlIO_printf(Perl_debug_log,
3875 "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
3880 sv_dump(MUTABLE_SV(hv));
3882 HvRITER_set(hv, riter); /* Restore hash iterator state */
3883 HvEITER_set(hv, eiter);
3889 * ex: set ts=8 sts=4 sw=4 et: