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()
42 /* MAX_BUCKET_MAX is the maximum max bucket index, at which point we stop growing the
45 #define MAX_BUCKET_MAX ((1<<26)-1)
46 #define DO_HSPLIT(xhv) ( ( ((xhv)->xhv_keys + ((xhv)->xhv_keys >> 1)) > (xhv)->xhv_max ) && \
47 ((xhv)->xhv_max < MAX_BUCKET_MAX) )
49 static const char S_strtab_error[]
50 = "Cannot modify shared string table in hv_%s";
54 #define new_HE() (HE*)safemalloc(sizeof(HE))
55 #define del_HE(p) safefree((char*)p)
63 void ** const root = &PL_body_roots[HE_SVSLOT];
66 Perl_more_bodies(aTHX_ HE_SVSLOT, sizeof(HE), PERL_ARENA_SIZE);
73 #define new_HE() new_he()
76 HeNEXT(p) = (HE*)(PL_body_roots[HE_SVSLOT]); \
77 PL_body_roots[HE_SVSLOT] = p; \
85 S_save_hek_flags(const char *str, I32 len, U32 hash, int flags)
87 const int flags_masked = flags & HVhek_MASK;
91 PERL_ARGS_ASSERT_SAVE_HEK_FLAGS;
93 Newx(k, HEK_BASESIZE + len + 2, char);
95 Copy(str, HEK_KEY(hek), len, char);
96 HEK_KEY(hek)[len] = 0;
99 HEK_FLAGS(hek) = (unsigned char)flags_masked | HVhek_UNSHARED;
101 if (flags & HVhek_FREEKEY)
106 /* free the pool of temporary HE/HEK pairs returned by hv_fetch_ent
110 Perl_free_tied_hv_pool(pTHX)
112 HE *he = PL_hv_fetch_ent_mh;
115 Safefree(HeKEY_hek(he));
119 PL_hv_fetch_ent_mh = NULL;
122 #if defined(USE_ITHREADS)
124 Perl_hek_dup(pTHX_ HEK *source, CLONE_PARAMS* param)
128 PERL_ARGS_ASSERT_HEK_DUP;
129 PERL_UNUSED_ARG(param);
134 shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
136 /* We already shared this hash key. */
137 (void)share_hek_hek(shared);
141 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
142 HEK_HASH(source), HEK_FLAGS(source));
143 ptr_table_store(PL_ptr_table, source, shared);
149 Perl_he_dup(pTHX_ const HE *e, bool shared, CLONE_PARAMS* param)
153 PERL_ARGS_ASSERT_HE_DUP;
157 /* look for it in the table first */
158 ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
162 /* create anew and remember what it is */
164 ptr_table_store(PL_ptr_table, e, ret);
166 HeNEXT(ret) = he_dup(HeNEXT(e),shared, param);
167 if (HeKLEN(e) == HEf_SVKEY) {
169 Newx(k, HEK_BASESIZE + sizeof(const SV *), char);
170 HeKEY_hek(ret) = (HEK*)k;
171 HeKEY_sv(ret) = sv_dup_inc(HeKEY_sv(e), param);
174 /* This is hek_dup inlined, which seems to be important for speed
176 HEK * const source = HeKEY_hek(e);
177 HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
180 /* We already shared this hash key. */
181 (void)share_hek_hek(shared);
185 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
186 HEK_HASH(source), HEK_FLAGS(source));
187 ptr_table_store(PL_ptr_table, source, shared);
189 HeKEY_hek(ret) = shared;
192 HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
194 HeVAL(ret) = sv_dup_inc(HeVAL(e), param);
197 #endif /* USE_ITHREADS */
200 S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
203 SV * const sv = sv_newmortal();
205 PERL_ARGS_ASSERT_HV_NOTALLOWED;
207 if (!(flags & HVhek_FREEKEY)) {
208 sv_setpvn(sv, key, klen);
211 /* Need to free saved eventually assign to mortal SV */
212 /* XXX is this line an error ???: SV *sv = sv_newmortal(); */
213 sv_usepvn(sv, (char *) key, klen);
215 if (flags & HVhek_UTF8) {
218 Perl_croak(aTHX_ msg, SVfARG(sv));
221 /* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
227 Stores an SV in a hash. The hash key is specified as C<key> and the
228 absolute value of C<klen> is the length of the key. If C<klen> is
229 negative the key is assumed to be in UTF-8-encoded Unicode. The
230 C<hash> parameter is the precomputed hash value; if it is zero then
231 Perl will compute it.
233 The return value will be
234 C<NULL> if the operation failed or if the value did not need to be actually
235 stored within the hash (as in the case of tied hashes). Otherwise it can
236 be dereferenced to get the original C<SV*>. Note that the caller is
237 responsible for suitably incrementing the reference count of C<val> before
238 the call, and decrementing it if the function returned C<NULL>. Effectively
239 a successful C<hv_store> takes ownership of one reference to C<val>. This is
240 usually what you want; a newly created SV has a reference count of one, so
241 if all your code does is create SVs then store them in a hash, C<hv_store>
242 will own the only reference to the new SV, and your code doesn't need to do
243 anything further to tidy up. C<hv_store> is not implemented as a call to
244 C<hv_store_ent>, and does not create a temporary SV for the key, so if your
245 key data is not already in SV form then use C<hv_store> in preference to
248 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
249 information on how to use this function on tied hashes.
251 =for apidoc hv_store_ent
253 Stores C<val> in a hash. The hash key is specified as C<key>. The C<hash>
254 parameter is the precomputed hash value; if it is zero then Perl will
255 compute it. The return value is the new hash entry so created. It will be
256 C<NULL> if the operation failed or if the value did not need to be actually
257 stored within the hash (as in the case of tied hashes). Otherwise the
258 contents of the return value can be accessed using the C<He?> macros
259 described here. Note that the caller is responsible for suitably
260 incrementing the reference count of C<val> before the call, and
261 decrementing it if the function returned NULL. Effectively a successful
262 C<hv_store_ent> takes ownership of one reference to C<val>. This is
263 usually what you want; a newly created SV has a reference count of one, so
264 if all your code does is create SVs then store them in a hash, C<hv_store>
265 will own the only reference to the new SV, and your code doesn't need to do
266 anything further to tidy up. Note that C<hv_store_ent> only reads the C<key>;
267 unlike C<val> it does not take ownership of it, so maintaining the correct
268 reference count on C<key> is entirely the caller's responsibility. The reason
269 it does not take ownership, is that C<key> is not used after this function
270 returns, and so can be freed immediately. C<hv_store>
271 is not implemented as a call to C<hv_store_ent>, and does not create a temporary
272 SV for the key, so if your key data is not already in SV form then use
273 C<hv_store> in preference to C<hv_store_ent>.
275 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
276 information on how to use this function on tied hashes.
278 =for apidoc hv_exists
280 Returns a boolean indicating whether the specified hash key exists. The
281 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.
286 Returns the SV which corresponds to the specified key in the hash.
287 The absolute value of C<klen> is the length of the key. If C<klen> is
288 negative the key is assumed to be in UTF-8-encoded Unicode. If
289 C<lval> is set then the fetch will be part of a store. This means that if
290 there is no value in the hash associated with the given key, then one is
291 created and a pointer to it is returned. The C<SV*> it points to can be
292 assigned to. But always check that the
293 return value is non-null before dereferencing it to an C<SV*>.
295 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
296 information on how to use this function on tied hashes.
298 =for apidoc hv_exists_ent
300 Returns a boolean indicating whether
301 the specified hash key exists. C<hash>
302 can be a valid precomputed hash value, or 0 to ask for it to be
308 /* returns an HE * structure with the all fields set */
309 /* note that hent_val will be a mortal sv for MAGICAL hashes */
311 =for apidoc hv_fetch_ent
313 Returns the hash entry which corresponds to the specified key in the hash.
314 C<hash> must be a valid precomputed hash number for the given C<key>, or 0
315 if you want the function to compute it. IF C<lval> is set then the fetch
316 will be part of a store. Make sure the return value is non-null before
317 accessing it. The return value when C<hv> is a tied hash is a pointer to a
318 static location, so be sure to make a copy of the structure if you need to
321 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
322 information on how to use this function on tied hashes.
327 /* Common code for hv_delete()/hv_exists()/hv_fetch()/hv_store() */
329 Perl_hv_common_key_len(pTHX_ HV *hv, const char *key, I32 klen_i32,
330 const int action, SV *val, const U32 hash)
335 PERL_ARGS_ASSERT_HV_COMMON_KEY_LEN;
344 return hv_common(hv, NULL, key, klen, flags, action, val, hash);
348 Perl_hv_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
349 int flags, int action, SV *val, U32 hash)
358 const int return_svp = action & HV_FETCH_JUST_SV;
359 HEK *keysv_hek = NULL;
363 if (SvTYPE(hv) == (svtype)SVTYPEMASK)
366 assert(SvTYPE(hv) == SVt_PVHV);
368 if (SvSMAGICAL(hv) && SvGMAGICAL(hv) && !(action & HV_DISABLE_UVAR_XKEY)) {
370 if ((mg = mg_find((const SV *)hv, PERL_MAGIC_uvar))) {
371 struct ufuncs * const uf = (struct ufuncs *)mg->mg_ptr;
372 if (uf->uf_set == NULL) {
373 SV* obj = mg->mg_obj;
376 keysv = newSVpvn_flags(key, klen, SVs_TEMP |
377 ((flags & HVhek_UTF8)
381 mg->mg_obj = keysv; /* pass key */
382 uf->uf_index = action; /* pass action */
383 magic_getuvar(MUTABLE_SV(hv), mg);
384 keysv = mg->mg_obj; /* may have changed */
387 /* If the key may have changed, then we need to invalidate
388 any passed-in computed hash value. */
394 if (flags & HVhek_FREEKEY)
396 key = SvPV_const(keysv, klen);
397 is_utf8 = (SvUTF8(keysv) != 0);
398 if (SvIsCOW_shared_hash(keysv)) {
399 flags = HVhek_KEYCANONICAL | (is_utf8 ? HVhek_UTF8 : 0);
404 is_utf8 = cBOOL(flags & HVhek_UTF8);
407 if (action & HV_DELETE) {
408 return (void *) hv_delete_common(hv, keysv, key, klen,
409 flags | (is_utf8 ? HVhek_UTF8 : 0),
413 xhv = (XPVHV*)SvANY(hv);
415 if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS))) {
416 if (mg_find((const SV *)hv, PERL_MAGIC_tied)
417 || SvGMAGICAL((const SV *)hv))
419 /* FIXME should be able to skimp on the HE/HEK here when
420 HV_FETCH_JUST_SV is true. */
422 keysv = newSVpvn_utf8(key, klen, is_utf8);
424 keysv = newSVsv(keysv);
427 mg_copy(MUTABLE_SV(hv), sv, (char *)keysv, HEf_SVKEY);
429 /* grab a fake HE/HEK pair from the pool or make a new one */
430 entry = PL_hv_fetch_ent_mh;
432 PL_hv_fetch_ent_mh = HeNEXT(entry);
436 Newx(k, HEK_BASESIZE + sizeof(const SV *), char);
437 HeKEY_hek(entry) = (HEK*)k;
439 HeNEXT(entry) = NULL;
440 HeSVKEY_set(entry, keysv);
442 sv_upgrade(sv, SVt_PVLV);
444 /* so we can free entry when freeing sv */
445 LvTARG(sv) = MUTABLE_SV(entry);
447 /* XXX remove at some point? */
448 if (flags & HVhek_FREEKEY)
452 return entry ? (void *) &HeVAL(entry) : NULL;
454 return (void *) entry;
456 #ifdef ENV_IS_CASELESS
457 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
459 for (i = 0; i < klen; ++i)
460 if (isLOWER(key[i])) {
461 /* Would be nice if we had a routine to do the
462 copy and upercase in a single pass through. */
463 const char * const nkey = strupr(savepvn(key,klen));
464 /* Note that this fetch is for nkey (the uppercased
465 key) whereas the store is for key (the original) */
466 void *result = hv_common(hv, NULL, nkey, klen,
467 HVhek_FREEKEY, /* free nkey */
468 0 /* non-LVAL fetch */
469 | HV_DISABLE_UVAR_XKEY
472 0 /* compute hash */);
473 if (!result && (action & HV_FETCH_LVALUE)) {
474 /* This call will free key if necessary.
475 Do it this way to encourage compiler to tail
477 result = hv_common(hv, keysv, key, klen, flags,
479 | HV_DISABLE_UVAR_XKEY
483 if (flags & HVhek_FREEKEY)
491 else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
492 if (mg_find((const SV *)hv, PERL_MAGIC_tied)
493 || SvGMAGICAL((const SV *)hv)) {
494 /* I don't understand why hv_exists_ent has svret and sv,
495 whereas hv_exists only had one. */
496 SV * const svret = sv_newmortal();
499 if (keysv || is_utf8) {
501 keysv = newSVpvn_utf8(key, klen, TRUE);
503 keysv = newSVsv(keysv);
505 mg_copy(MUTABLE_SV(hv), sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
507 mg_copy(MUTABLE_SV(hv), sv, key, klen);
509 if (flags & HVhek_FREEKEY)
512 MAGIC * const mg = mg_find(sv, PERL_MAGIC_tiedelem);
514 magic_existspack(svret, mg);
516 /* This cast somewhat evil, but I'm merely using NULL/
517 not NULL to return the boolean exists.
518 And I know hv is not NULL. */
519 return SvTRUE_NN(svret) ? (void *)hv : NULL;
521 #ifdef ENV_IS_CASELESS
522 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
523 /* XXX This code isn't UTF8 clean. */
524 char * const keysave = (char * const)key;
525 /* Will need to free this, so set FREEKEY flag. */
526 key = savepvn(key,klen);
527 key = (const char*)strupr((char*)key);
532 if (flags & HVhek_FREEKEY) {
535 flags |= HVhek_FREEKEY;
539 else if (action & HV_FETCH_ISSTORE) {
542 hv_magic_check (hv, &needs_copy, &needs_store);
544 const bool save_taint = TAINT_get;
545 if (keysv || is_utf8) {
547 keysv = newSVpvn_utf8(key, klen, TRUE);
550 TAINT_set(SvTAINTED(keysv));
551 keysv = sv_2mortal(newSVsv(keysv));
552 mg_copy(MUTABLE_SV(hv), val, (char*)keysv, HEf_SVKEY);
554 mg_copy(MUTABLE_SV(hv), val, key, klen);
557 TAINT_IF(save_taint);
558 #ifdef NO_TAINT_SUPPORT
559 PERL_UNUSED_VAR(save_taint);
562 if (flags & HVhek_FREEKEY)
566 #ifdef ENV_IS_CASELESS
567 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
568 /* XXX This code isn't UTF8 clean. */
569 const char *keysave = key;
570 /* Will need to free this, so set FREEKEY flag. */
571 key = savepvn(key,klen);
572 key = (const char*)strupr((char*)key);
577 if (flags & HVhek_FREEKEY) {
580 flags |= HVhek_FREEKEY;
588 if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
589 #ifdef DYNAMIC_ENV_FETCH /* if it's an %ENV lookup, we may get it on the fly */
590 || (SvRMAGICAL((const SV *)hv)
591 && mg_find((const SV *)hv, PERL_MAGIC_env))
596 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
598 HvARRAY(hv) = (HE**)array;
600 #ifdef DYNAMIC_ENV_FETCH
601 else if (action & HV_FETCH_ISEXISTS) {
602 /* for an %ENV exists, if we do an insert it's by a recursive
603 store call, so avoid creating HvARRAY(hv) right now. */
607 /* XXX remove at some point? */
608 if (flags & HVhek_FREEKEY)
615 if (is_utf8 && !(flags & HVhek_KEYCANONICAL)) {
616 char * const keysave = (char *)key;
617 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
621 flags &= ~HVhek_UTF8;
622 if (key != keysave) {
623 if (flags & HVhek_FREEKEY)
625 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
626 /* If the caller calculated a hash, it was on the sequence of
627 octets that are the UTF-8 form. We've now changed the sequence
628 of octets stored to that of the equivalent byte representation,
629 so the hash we need is different. */
634 if (keysv && (SvIsCOW_shared_hash(keysv))) {
636 keysv_hek = SvSHARED_HEK_FROM_PV(SvPVX_const(keysv));
637 hash = SvSHARED_HASH(keysv);
640 PERL_HASH(hash, key, klen);
642 masked_flags = (flags & HVhek_MASK);
644 #ifdef DYNAMIC_ENV_FETCH
645 if (!HvARRAY(hv)) entry = NULL;
649 entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
656 /* keysv is actually a HEK in disguise, so we can match just by
657 * comparing the HEK pointers in the HE chain. There is a slight
658 * caveat: on something like "\x80", which has both plain and utf8
659 * representations, perl's hashes do encoding-insensitive lookups,
660 * but preserve the encoding of the stored key. Thus a particular
661 * key could map to two different HEKs in PL_strtab. We only
662 * conclude 'not found' if all the flags are the same; otherwise
663 * we fall back to a full search (this should only happen in rare
666 int keysv_flags = HEK_FLAGS(keysv_hek);
667 HE *orig_entry = entry;
669 for (; entry; entry = HeNEXT(entry)) {
670 HEK *hek = HeKEY_hek(entry);
671 if (hek == keysv_hek)
673 if (HEK_FLAGS(hek) != keysv_flags)
674 break; /* need to do full match */
678 /* failed on shortcut - do full search loop */
682 for (; entry; entry = HeNEXT(entry)) {
683 if (HeHASH(entry) != hash) /* strings can't be equal */
685 if (HeKLEN(entry) != (I32)klen)
687 if (memNE(HeKEY(entry),key,klen)) /* is this it? */
689 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
693 if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
694 if (HeKFLAGS(entry) != masked_flags) {
695 /* We match if HVhek_UTF8 bit in our flags and hash key's
696 match. But if entry was set previously with HVhek_WASUTF8
697 and key now doesn't (or vice versa) then we should change
698 the key's flag, as this is assignment. */
699 if (HvSHAREKEYS(hv)) {
700 /* Need to swap the key we have for a key with the flags we
701 need. As keys are shared we can't just write to the
702 flag, so we share the new one, unshare the old one. */
703 HEK * const new_hek = share_hek_flags(key, klen, hash,
705 unshare_hek (HeKEY_hek(entry));
706 HeKEY_hek(entry) = new_hek;
708 else if (hv == PL_strtab) {
709 /* PL_strtab is usually the only hash without HvSHAREKEYS,
710 so putting this test here is cheap */
711 if (flags & HVhek_FREEKEY)
713 Perl_croak(aTHX_ S_strtab_error,
714 action & HV_FETCH_LVALUE ? "fetch" : "store");
717 HeKFLAGS(entry) = masked_flags;
718 if (masked_flags & HVhek_ENABLEHVKFLAGS)
721 if (HeVAL(entry) == &PL_sv_placeholder) {
722 /* yes, can store into placeholder slot */
723 if (action & HV_FETCH_LVALUE) {
725 /* This preserves behaviour with the old hv_fetch
726 implementation which at this point would bail out
727 with a break; (at "if we find a placeholder, we
728 pretend we haven't found anything")
730 That break mean that if a placeholder were found, it
731 caused a call into hv_store, which in turn would
732 check magic, and if there is no magic end up pretty
733 much back at this point (in hv_store's code). */
736 /* LVAL fetch which actually needs a store. */
738 HvPLACEHOLDERS(hv)--;
741 if (val != &PL_sv_placeholder)
742 HvPLACEHOLDERS(hv)--;
745 } else if (action & HV_FETCH_ISSTORE) {
746 SvREFCNT_dec(HeVAL(entry));
749 } else if (HeVAL(entry) == &PL_sv_placeholder) {
750 /* if we find a placeholder, we pretend we haven't found
754 if (flags & HVhek_FREEKEY)
757 return (void *) &HeVAL(entry);
763 #ifdef DYNAMIC_ENV_FETCH /* %ENV lookup? If so, try to fetch the value now */
764 if (!(action & HV_FETCH_ISSTORE)
765 && SvRMAGICAL((const SV *)hv)
766 && mg_find((const SV *)hv, PERL_MAGIC_env)) {
768 const char * const env = PerlEnv_ENVgetenv_len(key,&len);
770 sv = newSVpvn(env,len);
772 return hv_common(hv, keysv, key, klen, flags,
773 HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
779 if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
780 hv_notallowed(flags, key, klen,
781 "Attempt to access disallowed key '%" SVf "' in"
782 " a restricted hash");
784 if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
785 /* Not doing some form of store, so return failure. */
786 if (flags & HVhek_FREEKEY)
790 if (action & HV_FETCH_LVALUE) {
791 val = action & HV_FETCH_EMPTY_HE ? NULL : newSV(0);
793 /* At this point the old hv_fetch code would call to hv_store,
794 which in turn might do some tied magic. So we need to make that
795 magic check happen. */
796 /* gonna assign to this, so it better be there */
797 /* If a fetch-as-store fails on the fetch, then the action is to
798 recurse once into "hv_store". If we didn't do this, then that
799 recursive call would call the key conversion routine again.
800 However, as we replace the original key with the converted
801 key, this would result in a double conversion, which would show
802 up as a bug if the conversion routine is not idempotent.
803 Hence the use of HV_DISABLE_UVAR_XKEY. */
804 return hv_common(hv, keysv, key, klen, flags,
805 HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
807 /* XXX Surely that could leak if the fetch-was-store fails?
808 Just like the hv_fetch. */
812 /* Welcome to hv_store... */
815 /* Not sure if we can get here. I think the only case of oentry being
816 NULL is for %ENV with dynamic env fetch. But that should disappear
817 with magic in the previous code. */
820 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
822 HvARRAY(hv) = (HE**)array;
825 oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
828 /* share_hek_flags will do the free for us. This might be considered
831 HeKEY_hek(entry) = share_hek_flags(key, klen, hash, flags);
832 else if (hv == PL_strtab) {
833 /* PL_strtab is usually the only hash without HvSHAREKEYS, so putting
834 this test here is cheap */
835 if (flags & HVhek_FREEKEY)
837 Perl_croak(aTHX_ S_strtab_error,
838 action & HV_FETCH_LVALUE ? "fetch" : "store");
840 else /* gotta do the real thing */
841 HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
844 #ifdef PERL_HASH_RANDOMIZE_KEYS
845 /* This logic semi-randomizes the insert order in a bucket.
846 * Either we insert into the top, or the slot below the top,
847 * making it harder to see if there is a collision. We also
848 * reset the iterator randomizer if there is one.
850 in_collision = *oentry != NULL;
851 if ( *oentry && PL_HASH_RAND_BITS_ENABLED) {
853 PL_hash_rand_bits= ROTL_UV(PL_hash_rand_bits,1);
854 if ( PL_hash_rand_bits & 1 ) {
855 HeNEXT(entry) = HeNEXT(*oentry);
856 HeNEXT(*oentry) = entry;
858 HeNEXT(entry) = *oentry;
864 HeNEXT(entry) = *oentry;
867 #ifdef PERL_HASH_RANDOMIZE_KEYS
869 /* Currently this makes various tests warn in annoying ways.
870 * So Silenced for now. - Yves | bogus end of comment =>* /
871 if (HvAUX(hv)->xhv_riter != -1) {
872 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
873 "[TESTING] Inserting into a hash during each() traversal results in undefined behavior"
878 if (PL_HASH_RAND_BITS_ENABLED) {
879 if (PL_HASH_RAND_BITS_ENABLED == 1)
880 PL_hash_rand_bits += (PTRV)entry + 1; /* we don't bother to use ptr_hash here */
881 PL_hash_rand_bits= ROTL_UV(PL_hash_rand_bits,1);
883 HvAUX(hv)->xhv_rand= (U32)PL_hash_rand_bits;
887 if (val == &PL_sv_placeholder)
888 HvPLACEHOLDERS(hv)++;
889 if (masked_flags & HVhek_ENABLEHVKFLAGS)
892 xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
893 if ( in_collision && DO_HSPLIT(xhv) ) {
894 const STRLEN oldsize = xhv->xhv_max + 1;
895 const U32 items = (U32)HvPLACEHOLDERS_get(hv);
897 if (items /* hash has placeholders */
898 && !SvREADONLY(hv) /* but is not a restricted hash */) {
899 /* If this hash previously was a "restricted hash" and had
900 placeholders, but the "restricted" flag has been turned off,
901 then the placeholders no longer serve any useful purpose.
902 However, they have the downsides of taking up RAM, and adding
903 extra steps when finding used values. It's safe to clear them
904 at this point, even though Storable rebuilds restricted hashes by
905 putting in all the placeholders (first) before turning on the
906 readonly flag, because Storable always pre-splits the hash.
907 If we're lucky, then we may clear sufficient placeholders to
908 avoid needing to split the hash at all. */
909 clear_placeholders(hv, items);
911 hsplit(hv, oldsize, oldsize * 2);
913 hsplit(hv, oldsize, oldsize * 2);
917 return entry ? (void *) &HeVAL(entry) : NULL;
919 return (void *) entry;
923 S_hv_magic_check(HV *hv, bool *needs_copy, bool *needs_store)
925 const MAGIC *mg = SvMAGIC(hv);
927 PERL_ARGS_ASSERT_HV_MAGIC_CHECK;
932 if (isUPPER(mg->mg_type)) {
934 if (mg->mg_type == PERL_MAGIC_tied) {
935 *needs_store = FALSE;
936 return; /* We've set all there is to set. */
939 mg = mg->mg_moremagic;
944 =for apidoc hv_scalar
946 Evaluates the hash in scalar context and returns the result.
948 When the hash is tied dispatches through to the SCALAR method,
949 otherwise returns a mortal SV containing the number of keys
952 Note, prior to 5.25 this function returned what is now
953 returned by the hv_bucket_ratio() function.
959 Perl_hv_scalar(pTHX_ HV *hv)
963 PERL_ARGS_ASSERT_HV_SCALAR;
965 if (SvRMAGICAL(hv)) {
966 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_tied);
968 return magic_scalarpack(hv, mg);
972 sv_setuv(sv, HvUSEDKEYS(hv));
979 hv_pushkv(): push all the keys and/or values of a hash onto the stack.
980 The rough Perl equivalents:
985 Resets the hash's iterator.
987 flags : 1 = push keys
989 1|2 = push keys and values
990 XXX use symbolic flag constants at some point?
991 I might unroll the non-tied hv_iternext() in here at some point - DAPM
995 Perl_hv_pushkv(pTHX_ HV *hv, U32 flags)
998 bool tied = SvRMAGICAL(hv) && (mg_find(MUTABLE_SV(hv), PERL_MAGIC_tied)
999 #ifdef DYNAMIC_ENV_FETCH /* might not know number of keys yet */
1000 || mg_find(MUTABLE_SV(hv), PERL_MAGIC_env)
1005 PERL_ARGS_ASSERT_HV_PUSHKV;
1006 assert(flags); /* must be pushing at least one of keys and values */
1008 (void)hv_iterinit(hv);
1011 SSize_t ext = (flags == 3) ? 2 : 1;
1012 while ((entry = hv_iternext(hv))) {
1015 PUSHs(hv_iterkeysv(entry));
1017 PUSHs(hv_iterval(hv, entry));
1021 Size_t nkeys = HvUSEDKEYS(hv);
1027 /* 2*nkeys() should never be big enough to truncate or wrap */
1028 assert(nkeys <= (SSize_t_MAX >> 1));
1029 ext = nkeys * ((flags == 3) ? 2 : 1);
1031 EXTEND_MORTAL(nkeys);
1034 while ((entry = hv_iternext(hv))) {
1036 SV *keysv = newSVhek(HeKEY_hek(entry));
1038 PL_tmps_stack[++PL_tmps_ix] = keysv;
1042 PUSHs(HeVAL(entry));
1051 =for apidoc hv_bucket_ratio
1053 If the hash is tied dispatches through to the SCALAR tied method,
1054 otherwise if the hash contains no keys returns 0, otherwise returns
1055 a mortal sv containing a string specifying the number of used buckets,
1056 followed by a slash, followed by the number of available buckets.
1058 This function is expensive, it must scan all of the buckets
1059 to determine which are used, and the count is NOT cached.
1060 In a large hash this could be a lot of buckets.
1066 Perl_hv_bucket_ratio(pTHX_ HV *hv)
1070 PERL_ARGS_ASSERT_HV_BUCKET_RATIO;
1072 if (SvRMAGICAL(hv)) {
1073 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_tied);
1075 return magic_scalarpack(hv, mg);
1078 if (HvUSEDKEYS((HV *)hv)) {
1079 sv = sv_newmortal();
1080 Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
1081 (long)HvFILL(hv), (long)HvMAX(hv) + 1);
1090 =for apidoc hv_delete
1092 Deletes a key/value pair in the hash. The value's SV is removed from
1093 the hash, made mortal, and returned to the caller. The absolute
1094 value of C<klen> is the length of the key. If C<klen> is negative the
1095 key is assumed to be in UTF-8-encoded Unicode. The C<flags> value
1096 will normally be zero; if set to C<G_DISCARD> then C<NULL> will be returned.
1097 C<NULL> will also be returned if the key is not found.
1099 =for apidoc hv_delete_ent
1101 Deletes a key/value pair in the hash. The value SV is removed from the hash,
1102 made mortal, and returned to the caller. The C<flags> value will normally be
1103 zero; if set to C<G_DISCARD> then C<NULL> will be returned. C<NULL> will also
1104 be returned if the key is not found. C<hash> can be a valid precomputed hash
1105 value, or 0 to ask for it to be computed.
1111 S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
1112 int k_flags, I32 d_flags, U32 hash)
1118 bool is_utf8 = cBOOL(k_flags & HVhek_UTF8);
1120 HEK *keysv_hek = NULL;
1121 U8 mro_changes = 0; /* 1 = isa; 2 = package moved */
1126 if (SvMAGICAL(hv)) {
1129 hv_magic_check (hv, &needs_copy, &needs_store);
1133 entry = (HE *) hv_common(hv, keysv, key, klen,
1134 k_flags & ~HVhek_FREEKEY,
1135 HV_FETCH_LVALUE|HV_DISABLE_UVAR_XKEY,
1137 sv = entry ? HeVAL(entry) : NULL;
1139 if (SvMAGICAL(sv)) {
1143 if (mg_find(sv, PERL_MAGIC_tiedelem)) {
1144 /* No longer an element */
1145 sv_unmagic(sv, PERL_MAGIC_tiedelem);
1148 return NULL; /* element cannot be deleted */
1150 #ifdef ENV_IS_CASELESS
1151 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
1152 /* XXX This code isn't UTF8 clean. */
1153 keysv = newSVpvn_flags(key, klen, SVs_TEMP);
1154 if (k_flags & HVhek_FREEKEY) {
1157 key = strupr(SvPVX(keysv));
1166 xhv = (XPVHV*)SvANY(hv);
1170 if (is_utf8 && !(k_flags & HVhek_KEYCANONICAL)) {
1171 const char * const keysave = key;
1172 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
1175 k_flags |= HVhek_UTF8;
1177 k_flags &= ~HVhek_UTF8;
1178 if (key != keysave) {
1179 if (k_flags & HVhek_FREEKEY) {
1180 /* This shouldn't happen if our caller does what we expect,
1181 but strictly the API allows it. */
1184 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
1186 HvHASKFLAGS_on(MUTABLE_SV(hv));
1189 if (keysv && (SvIsCOW_shared_hash(keysv))) {
1190 if (HvSHAREKEYS(hv))
1191 keysv_hek = SvSHARED_HEK_FROM_PV(SvPVX_const(keysv));
1192 hash = SvSHARED_HASH(keysv);
1195 PERL_HASH(hash, key, klen);
1197 masked_flags = (k_flags & HVhek_MASK);
1199 first_entry = oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
1206 /* keysv is actually a HEK in disguise, so we can match just by
1207 * comparing the HEK pointers in the HE chain. There is a slight
1208 * caveat: on something like "\x80", which has both plain and utf8
1209 * representations, perl's hashes do encoding-insensitive lookups,
1210 * but preserve the encoding of the stored key. Thus a particular
1211 * key could map to two different HEKs in PL_strtab. We only
1212 * conclude 'not found' if all the flags are the same; otherwise
1213 * we fall back to a full search (this should only happen in rare
1216 int keysv_flags = HEK_FLAGS(keysv_hek);
1218 for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
1219 HEK *hek = HeKEY_hek(entry);
1220 if (hek == keysv_hek)
1222 if (HEK_FLAGS(hek) != keysv_flags)
1223 break; /* need to do full match */
1227 /* failed on shortcut - do full search loop */
1228 oentry = first_entry;
1232 for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
1233 if (HeHASH(entry) != hash) /* strings can't be equal */
1235 if (HeKLEN(entry) != (I32)klen)
1237 if (memNE(HeKEY(entry),key,klen)) /* is this it? */
1239 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
1243 if (hv == PL_strtab) {
1244 if (k_flags & HVhek_FREEKEY)
1246 Perl_croak(aTHX_ S_strtab_error, "delete");
1249 /* if placeholder is here, it's already been deleted.... */
1250 if (HeVAL(entry) == &PL_sv_placeholder) {
1251 if (k_flags & HVhek_FREEKEY)
1255 if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1256 hv_notallowed(k_flags, key, klen,
1257 "Attempt to delete readonly key '%" SVf "' from"
1258 " a restricted hash");
1260 if (k_flags & HVhek_FREEKEY)
1263 /* If this is a stash and the key ends with ::, then someone is
1264 * deleting a package.
1266 if (HeVAL(entry) && HvENAME_get(hv)) {
1267 gv = (GV *)HeVAL(entry);
1268 if (keysv) key = SvPV(keysv, klen);
1270 (klen > 1 && key[klen-2] == ':' && key[klen-1] == ':')
1272 (klen == 1 && key[0] == ':')
1274 && (klen != 6 || hv!=PL_defstash || memNE(key,"main::",6))
1275 && SvTYPE(gv) == SVt_PVGV && (stash = GvHV((GV *)gv))
1276 && HvENAME_get(stash)) {
1277 /* A previous version of this code checked that the
1278 * GV was still in the symbol table by fetching the
1279 * GV with its name. That is not necessary (and
1280 * sometimes incorrect), as HvENAME cannot be set
1281 * on hv if it is not in the symtab. */
1283 /* Hang on to it for a bit. */
1284 SvREFCNT_inc_simple_void_NN(
1285 sv_2mortal((SV *)gv)
1288 else if (memEQs(key, klen, "ISA") && GvAV(gv)) {
1290 MAGIC *mg = mg_find((SV*)isa, PERL_MAGIC_isa);
1294 if (mg->mg_obj == (SV*)gv) {
1295 /* This is the only stash this ISA was used for.
1296 * The isaelem magic asserts if there's no
1297 * isa magic on the array, so explicitly
1298 * remove the magic on both the array and its
1299 * elements. @ISA shouldn't be /too/ large.
1304 end = svp + (AvFILLp(isa)+1);
1307 mg_free_type(*svp, PERL_MAGIC_isaelem);
1310 mg_free_type((SV*)GvAV(gv), PERL_MAGIC_isa);
1313 /* mg_obj is an array of stashes
1314 Note that the array doesn't keep a reference
1315 count on the stashes.
1317 AV *av = (AV*)mg->mg_obj;
1322 assert(SvTYPE(mg->mg_obj) == SVt_PVAV);
1324 /* remove the stash from the magic array */
1325 arrayp = svp = AvARRAY(av);
1326 items = AvFILLp(av) + 1;
1328 assert(*arrayp == (SV *)gv);
1330 /* avoid a double free on the last stash */
1332 /* The magic isn't MGf_REFCOUNTED, so release
1333 * the array manually.
1335 SvREFCNT_dec_NN(av);
1340 if (*svp == (SV*)gv)
1344 index = svp - arrayp;
1345 assert(index >= 0 && index <= AvFILLp(av));
1346 if (index < AvFILLp(av)) {
1347 arrayp[index] = arrayp[AvFILLp(av)];
1349 arrayp[AvFILLp(av)] = NULL;
1357 sv = d_flags & G_DISCARD ? HeVAL(entry) : sv_2mortal(HeVAL(entry));
1358 HeVAL(entry) = &PL_sv_placeholder;
1360 /* deletion of method from stash */
1361 if (isGV(sv) && isGV_with_GP(sv) && GvCVu(sv)
1363 mro_method_changed_in(hv);
1367 * If a restricted hash, rather than really deleting the entry, put
1368 * a placeholder there. This marks the key as being "approved", so
1369 * we can still access via not-really-existing key without raising
1373 /* We'll be saving this slot, so the number of allocated keys
1374 * doesn't go down, but the number placeholders goes up */
1375 HvPLACEHOLDERS(hv)++;
1377 *oentry = HeNEXT(entry);
1378 if (SvOOK(hv) && entry == HvAUX(hv)->xhv_eiter /* HvEITER(hv) */)
1381 if (SvOOK(hv) && HvLAZYDEL(hv) &&
1382 entry == HeNEXT(HvAUX(hv)->xhv_eiter))
1383 HeNEXT(HvAUX(hv)->xhv_eiter) = HeNEXT(entry);
1384 hv_free_ent(hv, entry);
1386 xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
1387 if (xhv->xhv_keys == 0)
1388 HvHASKFLAGS_off(hv);
1391 if (d_flags & G_DISCARD) {
1396 if (mro_changes == 1) mro_isa_changed_in(hv);
1397 else if (mro_changes == 2)
1398 mro_package_moved(NULL, stash, gv, 1);
1404 if (SvREADONLY(hv)) {
1405 hv_notallowed(k_flags, key, klen,
1406 "Attempt to delete disallowed key '%" SVf "' from"
1407 " a restricted hash");
1410 if (k_flags & HVhek_FREEKEY)
1417 S_hsplit(pTHX_ HV *hv, STRLEN const oldsize, STRLEN newsize)
1420 char *a = (char*) HvARRAY(hv);
1424 /* already have an HvAUX(hv) so we have to move it */
1426 /* no HvAUX() but array we are going to allocate is large enough
1427 * there is no point in saving the space for the iterator, and
1428 * speeds up later traversals. */
1429 ( ( hv != PL_strtab ) && ( newsize >= PERL_HV_ALLOC_AUX_SIZE ) )
1432 PERL_ARGS_ASSERT_HSPLIT;
1433 if (newsize > MAX_BUCKET_MAX+1)
1437 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1438 + (do_aux ? sizeof(struct xpvhv_aux) : 0), char);
1444 #ifdef PERL_HASH_RANDOMIZE_KEYS
1445 /* the idea of this is that we create a "random" value by hashing the address of
1446 * the array, we then use the low bit to decide if we insert at the top, or insert
1447 * second from top. After each such insert we rotate the hashed value. So we can
1448 * use the same hashed value over and over, and in normal build environments use
1449 * very few ops to do so. ROTL32() should produce a single machine operation. */
1450 if (PL_HASH_RAND_BITS_ENABLED) {
1451 if (PL_HASH_RAND_BITS_ENABLED == 1)
1452 PL_hash_rand_bits += ptr_hash((PTRV)a);
1453 PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,1);
1456 HvARRAY(hv) = (HE**) a;
1457 HvMAX(hv) = newsize - 1;
1458 /* before we zero the newly added memory, we
1459 * need to deal with the aux struct that may be there
1460 * or have been allocated by us*/
1462 struct xpvhv_aux *const dest
1463 = (struct xpvhv_aux*) &a[newsize * sizeof(HE*)];
1465 /* alread have an aux, copy the old one in place. */
1466 Move(&a[oldsize * sizeof(HE*)], dest, 1, struct xpvhv_aux);
1467 /* we reset the iterator's xhv_rand as well, so they get a totally new ordering */
1468 #ifdef PERL_HASH_RANDOMIZE_KEYS
1469 dest->xhv_rand = (U32)PL_hash_rand_bits;
1472 /* no existing aux structure, but we allocated space for one
1473 * so initialize it properly. This unrolls hv_auxinit() a bit,
1474 * since we have to do the realloc anyway. */
1475 /* first we set the iterator's xhv_rand so it can be copied into lastrand below */
1476 #ifdef PERL_HASH_RANDOMIZE_KEYS
1477 dest->xhv_rand = (U32)PL_hash_rand_bits;
1479 /* this is the "non realloc" part of the hv_auxinit() */
1480 (void)hv_auxinit_internal(dest);
1481 /* Turn on the OOK flag */
1485 /* now we can safely clear the second half */
1486 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1488 if (!HvTOTALKEYS(hv)) /* skip rest if no entries */
1494 HE **oentry = aep + i;
1497 if (!entry) /* non-existent */
1500 U32 j = (HeHASH(entry) & newsize);
1502 *oentry = HeNEXT(entry);
1503 #ifdef PERL_HASH_RANDOMIZE_KEYS
1504 /* if the target cell is empty or PL_HASH_RAND_BITS_ENABLED is false
1505 * insert to top, otherwise rotate the bucket rand 1 bit,
1506 * and use the new low bit to decide if we insert at top,
1507 * or next from top. IOW, we only rotate on a collision.*/
1508 if (aep[j] && PL_HASH_RAND_BITS_ENABLED) {
1509 PL_hash_rand_bits+= ROTL32(HeHASH(entry), 17);
1510 PL_hash_rand_bits= ROTL_UV(PL_hash_rand_bits,1);
1511 if (PL_hash_rand_bits & 1) {
1512 HeNEXT(entry)= HeNEXT(aep[j]);
1513 HeNEXT(aep[j])= entry;
1515 /* Note, this is structured in such a way as the optimizer
1516 * should eliminate the duplicated code here and below without
1517 * us needing to explicitly use a goto. */
1518 HeNEXT(entry) = aep[j];
1524 /* see comment above about duplicated code */
1525 HeNEXT(entry) = aep[j];
1530 oentry = &HeNEXT(entry);
1534 } while (i++ < oldsize);
1538 Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
1540 XPVHV* xhv = (XPVHV*)SvANY(hv);
1541 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 */
1547 PERL_ARGS_ASSERT_HV_KSPLIT;
1549 wantsize = (I32) newmax; /* possible truncation here */
1550 if (wantsize != newmax)
1553 wantsize= wantsize + (wantsize >> 1); /* wantsize *= 1.5 */
1554 if (wantsize < newmax) /* overflow detection */
1558 while (wantsize > newsize) {
1559 trysize = newsize << 1;
1560 if (trysize > newsize) {
1568 if (newsize <= oldsize)
1569 return; /* overflow detection */
1571 a = (char *) HvARRAY(hv);
1573 hsplit(hv, oldsize, newsize);
1575 Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1576 xhv->xhv_max = newsize - 1;
1577 HvARRAY(hv) = (HE **) a;
1581 /* IMO this should also handle cases where hv_max is smaller than hv_keys
1582 * as tied hashes could play silly buggers and mess us around. We will
1583 * do the right thing during hv_store() afterwards, but still - Yves */
1584 #define HV_SET_MAX_ADJUSTED_FOR_KEYS(hv,hv_max,hv_keys) STMT_START {\
1585 /* Can we use fewer buckets? (hv_max is always 2^n-1) */ \
1586 if (hv_max < PERL_HASH_DEFAULT_HvMAX) { \
1587 hv_max = PERL_HASH_DEFAULT_HvMAX; \
1589 while (hv_max > PERL_HASH_DEFAULT_HvMAX && hv_max + 1 >= hv_keys * 2) \
1590 hv_max = hv_max / 2; \
1592 HvMAX(hv) = hv_max; \
1597 Perl_newHVhv(pTHX_ HV *ohv)
1599 HV * const hv = newHV();
1602 if (!ohv || (!HvTOTALKEYS(ohv) && !SvMAGICAL((const SV *)ohv)))
1604 hv_max = HvMAX(ohv);
1606 if (!SvMAGICAL((const SV *)ohv)) {
1607 /* It's an ordinary hash, so copy it fast. AMS 20010804 */
1609 const bool shared = !!HvSHAREKEYS(ohv);
1610 HE **ents, ** const oents = (HE **)HvARRAY(ohv);
1612 Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
1615 /* In each bucket... */
1616 for (i = 0; i <= hv_max; i++) {
1618 HE *oent = oents[i];
1625 /* Copy the linked list of entries. */
1626 for (; oent; oent = HeNEXT(oent)) {
1627 const U32 hash = HeHASH(oent);
1628 const char * const key = HeKEY(oent);
1629 const STRLEN len = HeKLEN(oent);
1630 const int flags = HeKFLAGS(oent);
1631 HE * const ent = new_HE();
1632 SV *const val = HeVAL(oent);
1634 HeVAL(ent) = SvIMMORTAL(val) ? val : newSVsv(val);
1636 = shared ? share_hek_flags(key, len, hash, flags)
1637 : save_hek_flags(key, len, hash, flags);
1648 HvTOTALKEYS(hv) = HvTOTALKEYS(ohv);
1652 /* Iterate over ohv, copying keys and values one at a time. */
1654 const I32 riter = HvRITER_get(ohv);
1655 HE * const eiter = HvEITER_get(ohv);
1656 STRLEN hv_keys = HvTOTALKEYS(ohv);
1658 HV_SET_MAX_ADJUSTED_FOR_KEYS(hv,hv_max,hv_keys);
1661 while ((entry = hv_iternext_flags(ohv, 0))) {
1662 SV *val = hv_iterval(ohv,entry);
1663 SV * const keysv = HeSVKEY(entry);
1664 val = SvIMMORTAL(val) ? val : newSVsv(val);
1666 (void)hv_store_ent(hv, keysv, val, 0);
1668 (void)hv_store_flags(hv, HeKEY(entry), HeKLEN(entry), val,
1669 HeHASH(entry), HeKFLAGS(entry));
1671 HvRITER_set(ohv, riter);
1672 HvEITER_set(ohv, eiter);
1679 =for apidoc hv_copy_hints_hv
1681 A specialised version of L</newHVhv> for copying C<%^H>. C<ohv> must be
1682 a pointer to a hash (which may have C<%^H> magic, but should be generally
1683 non-magical), or C<NULL> (interpreted as an empty hash). The content
1684 of C<ohv> is copied to a new hash, which has the C<%^H>-specific magic
1685 added to it. A pointer to the new hash is returned.
1691 Perl_hv_copy_hints_hv(pTHX_ HV *const ohv)
1693 HV * const hv = newHV();
1696 STRLEN hv_max = HvMAX(ohv);
1697 STRLEN hv_keys = HvTOTALKEYS(ohv);
1699 const I32 riter = HvRITER_get(ohv);
1700 HE * const eiter = HvEITER_get(ohv);
1705 HV_SET_MAX_ADJUSTED_FOR_KEYS(hv,hv_max,hv_keys);
1708 while ((entry = hv_iternext_flags(ohv, 0))) {
1709 SV *const sv = newSVsv(hv_iterval(ohv,entry));
1710 SV *heksv = HeSVKEY(entry);
1711 if (!heksv && sv) heksv = newSVhek(HeKEY_hek(entry));
1712 if (sv) sv_magic(sv, NULL, PERL_MAGIC_hintselem,
1713 (char *)heksv, HEf_SVKEY);
1714 if (heksv == HeSVKEY(entry))
1715 (void)hv_store_ent(hv, heksv, sv, 0);
1717 (void)hv_common(hv, heksv, HeKEY(entry), HeKLEN(entry),
1718 HeKFLAGS(entry), HV_FETCH_ISSTORE|HV_FETCH_JUST_SV, sv, HeHASH(entry));
1719 SvREFCNT_dec_NN(heksv);
1722 HvRITER_set(ohv, riter);
1723 HvEITER_set(ohv, eiter);
1725 SvREFCNT_inc_simple_void_NN(hv);
1728 hv_magic(hv, NULL, PERL_MAGIC_hints);
1731 #undef HV_SET_MAX_ADJUSTED_FOR_KEYS
1733 /* like hv_free_ent, but returns the SV rather than freeing it */
1735 S_hv_free_ent_ret(pTHX_ HV *hv, HE *entry)
1739 PERL_ARGS_ASSERT_HV_FREE_ENT_RET;
1742 if (HeKLEN(entry) == HEf_SVKEY) {
1743 SvREFCNT_dec(HeKEY_sv(entry));
1744 Safefree(HeKEY_hek(entry));
1746 else if (HvSHAREKEYS(hv))
1747 unshare_hek(HeKEY_hek(entry));
1749 Safefree(HeKEY_hek(entry));
1756 Perl_hv_free_ent(pTHX_ HV *hv, HE *entry)
1760 PERL_ARGS_ASSERT_HV_FREE_ENT;
1764 val = hv_free_ent_ret(hv, entry);
1770 Perl_hv_delayfree_ent(pTHX_ HV *hv, HE *entry)
1772 PERL_ARGS_ASSERT_HV_DELAYFREE_ENT;
1776 /* SvREFCNT_inc to counter the SvREFCNT_dec in hv_free_ent */
1777 sv_2mortal(SvREFCNT_inc(HeVAL(entry))); /* free between statements */
1778 if (HeKLEN(entry) == HEf_SVKEY) {
1779 sv_2mortal(SvREFCNT_inc(HeKEY_sv(entry)));
1781 hv_free_ent(hv, entry);
1785 =for apidoc hv_clear
1787 Frees all the elements of a hash, leaving it empty.
1788 The XS equivalent of C<%hash = ()>. See also L</hv_undef>.
1790 See L</av_clear> for a note about the hash possibly being invalid on
1797 Perl_hv_clear(pTHX_ HV *hv)
1805 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1807 xhv = (XPVHV*)SvANY(hv);
1809 /* avoid hv being freed when calling destructors below */
1811 PL_tmps_stack[++PL_tmps_ix] = SvREFCNT_inc_simple_NN(hv);
1812 orig_ix = PL_tmps_ix;
1813 if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
1814 /* restricted hash: convert all keys to placeholders */
1816 for (i = 0; i <= xhv->xhv_max; i++) {
1817 HE *entry = (HvARRAY(hv))[i];
1818 for (; entry; entry = HeNEXT(entry)) {
1819 /* not already placeholder */
1820 if (HeVAL(entry) != &PL_sv_placeholder) {
1822 if (SvREADONLY(HeVAL(entry))) {
1823 SV* const keysv = hv_iterkeysv(entry);
1824 Perl_croak_nocontext(
1825 "Attempt to delete readonly key '%" SVf "' from a restricted hash",
1828 SvREFCNT_dec_NN(HeVAL(entry));
1830 HeVAL(entry) = &PL_sv_placeholder;
1831 HvPLACEHOLDERS(hv)++;
1837 hv_free_entries(hv);
1838 HvPLACEHOLDERS_set(hv, 0);
1841 mg_clear(MUTABLE_SV(hv));
1843 HvHASKFLAGS_off(hv);
1847 mro_isa_changed_in(hv);
1848 HvEITER_set(hv, NULL);
1850 /* disarm hv's premature free guard */
1851 if (LIKELY(PL_tmps_ix == orig_ix))
1854 PL_tmps_stack[orig_ix] = &PL_sv_undef;
1855 SvREFCNT_dec_NN(hv);
1859 =for apidoc hv_clear_placeholders
1861 Clears any placeholders from a hash. If a restricted hash has any of its keys
1862 marked as readonly and the key is subsequently deleted, the key is not actually
1863 deleted but is marked by assigning it a value of C<&PL_sv_placeholder>. This tags
1864 it so it will be ignored by future operations such as iterating over the hash,
1865 but will still allow the hash to have a value reassigned to the key at some
1866 future point. This function clears any such placeholder keys from the hash.
1867 See C<L<Hash::Util::lock_keys()|Hash::Util/lock_keys>> for an example of its
1874 Perl_hv_clear_placeholders(pTHX_ HV *hv)
1876 const U32 items = (U32)HvPLACEHOLDERS_get(hv);
1878 PERL_ARGS_ASSERT_HV_CLEAR_PLACEHOLDERS;
1881 clear_placeholders(hv, items);
1885 S_clear_placeholders(pTHX_ HV *hv, U32 items)
1889 PERL_ARGS_ASSERT_CLEAR_PLACEHOLDERS;
1896 /* Loop down the linked list heads */
1897 HE **oentry = &(HvARRAY(hv))[i];
1900 while ((entry = *oentry)) {
1901 if (HeVAL(entry) == &PL_sv_placeholder) {
1902 *oentry = HeNEXT(entry);
1903 if (entry == HvEITER_get(hv))
1906 if (SvOOK(hv) && HvLAZYDEL(hv) &&
1907 entry == HeNEXT(HvAUX(hv)->xhv_eiter))
1908 HeNEXT(HvAUX(hv)->xhv_eiter) = HeNEXT(entry);
1909 hv_free_ent(hv, entry);
1914 I32 placeholders = HvPLACEHOLDERS_get(hv);
1915 HvTOTALKEYS(hv) -= (IV)placeholders;
1916 /* HvUSEDKEYS expanded */
1917 if ((HvTOTALKEYS(hv) - placeholders) == 0)
1918 HvHASKFLAGS_off(hv);
1919 HvPLACEHOLDERS_set(hv, 0);
1923 oentry = &HeNEXT(entry);
1927 /* You can't get here, hence assertion should always fail. */
1928 assert (items == 0);
1929 NOT_REACHED; /* NOTREACHED */
1933 S_hv_free_entries(pTHX_ HV *hv)
1936 XPVHV * const xhv = (XPVHV*)SvANY(hv);
1939 PERL_ARGS_ASSERT_HV_FREE_ENTRIES;
1941 while ((sv = Perl_hfree_next_entry(aTHX_ hv, &index))||xhv->xhv_keys) {
1947 /* hfree_next_entry()
1948 * For use only by S_hv_free_entries() and sv_clear().
1949 * Delete the next available HE from hv and return the associated SV.
1950 * Returns null on empty hash. Nevertheless null is not a reliable
1951 * indicator that the hash is empty, as the deleted entry may have a
1953 * indexp is a pointer to the current index into HvARRAY. The index should
1954 * initially be set to 0. hfree_next_entry() may update it. */
1957 Perl_hfree_next_entry(pTHX_ HV *hv, STRLEN *indexp)
1959 struct xpvhv_aux *iter;
1963 STRLEN orig_index = *indexp;
1966 PERL_ARGS_ASSERT_HFREE_NEXT_ENTRY;
1968 if (SvOOK(hv) && ((iter = HvAUX(hv)))) {
1969 if ((entry = iter->xhv_eiter)) {
1970 /* the iterator may get resurrected after each
1971 * destructor call, so check each time */
1972 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1974 hv_free_ent(hv, entry);
1975 /* warning: at this point HvARRAY may have been
1976 * re-allocated, HvMAX changed etc */
1978 iter = HvAUX(hv); /* may have been realloced */
1979 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1980 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
1981 #ifdef PERL_HASH_RANDOMIZE_KEYS
1982 iter->xhv_last_rand = iter->xhv_rand;
1987 if (!((XPVHV*)SvANY(hv))->xhv_keys)
1990 array = HvARRAY(hv);
1992 while ( ! ((entry = array[*indexp])) ) {
1993 if ((*indexp)++ >= HvMAX(hv))
1995 assert(*indexp != orig_index);
1997 array[*indexp] = HeNEXT(entry);
1998 ((XPVHV*) SvANY(hv))->xhv_keys--;
2000 if ( PL_phase != PERL_PHASE_DESTRUCT && HvENAME(hv)
2001 && HeVAL(entry) && isGV(HeVAL(entry))
2002 && GvHV(HeVAL(entry)) && HvENAME(GvHV(HeVAL(entry)))
2005 const char * const key = HePV(entry,klen);
2006 if ((klen > 1 && key[klen-1]==':' && key[klen-2]==':')
2007 || (klen == 1 && key[0] == ':')) {
2009 NULL, GvHV(HeVAL(entry)),
2010 (GV *)HeVAL(entry), 0
2014 return hv_free_ent_ret(hv, entry);
2019 =for apidoc hv_undef
2021 Undefines the hash. The XS equivalent of C<undef(%hash)>.
2023 As well as freeing all the elements of the hash (like C<hv_clear()>), this
2024 also frees any auxiliary data and storage associated with the hash.
2026 See L</av_clear> for a note about the hash possibly being invalid on
2033 Perl_hv_undef_flags(pTHX_ HV *hv, U32 flags)
2037 SSize_t orig_ix = PL_tmps_ix; /* silence compiler warning about unitialized vars */
2041 save = cBOOL(SvREFCNT(hv));
2042 DEBUG_A(Perl_hv_assert(aTHX_ hv));
2043 xhv = (XPVHV*)SvANY(hv);
2045 /* The name must be deleted before the call to hv_free_entries so that
2046 CVs are anonymised properly. But the effective name must be pre-
2047 served until after that call (and only deleted afterwards if the
2048 call originated from sv_clear). For stashes with one name that is
2049 both the canonical name and the effective name, hv_name_set has to
2050 allocate an array for storing the effective name. We can skip that
2051 during global destruction, as it does not matter where the CVs point
2052 if they will be freed anyway. */
2053 /* note that the code following prior to hv_free_entries is duplicated
2054 * in sv_clear(), and changes here should be done there too */
2055 if (PL_phase != PERL_PHASE_DESTRUCT && HvNAME(hv)) {
2056 if (PL_stashcache) {
2057 DEBUG_o(Perl_deb(aTHX_ "hv_undef_flags clearing PL_stashcache for '%"
2058 HEKf "'\n", HEKfARG(HvNAME_HEK(hv))));
2059 (void)hv_deletehek(PL_stashcache, HvNAME_HEK(hv), G_DISCARD);
2061 hv_name_set(hv, NULL, 0, 0);
2064 /* avoid hv being freed when calling destructors below */
2066 PL_tmps_stack[++PL_tmps_ix] = SvREFCNT_inc_simple_NN(hv);
2067 orig_ix = PL_tmps_ix;
2069 hv_free_entries(hv);
2071 struct mro_meta *meta;
2074 if (HvENAME_get(hv)) {
2075 if (PL_phase != PERL_PHASE_DESTRUCT)
2076 mro_isa_changed_in(hv);
2077 if (PL_stashcache) {
2078 DEBUG_o(Perl_deb(aTHX_ "hv_undef_flags clearing PL_stashcache for effective name '%"
2079 HEKf "'\n", HEKfARG(HvENAME_HEK(hv))));
2080 (void)hv_deletehek(PL_stashcache, HvENAME_HEK(hv), G_DISCARD);
2084 /* If this call originated from sv_clear, then we must check for
2085 * effective names that need freeing, as well as the usual name. */
2087 if (flags & HV_NAME_SETALL ? !!HvAUX(hv)->xhv_name_u.xhvnameu_name : !!name) {
2088 if (name && PL_stashcache) {
2089 DEBUG_o(Perl_deb(aTHX_ "hv_undef_flags clearing PL_stashcache for name '%"
2090 HEKf "'\n", HEKfARG(HvNAME_HEK(hv))));
2091 (void)hv_deletehek(PL_stashcache, HvNAME_HEK(hv), G_DISCARD);
2093 hv_name_set(hv, NULL, 0, flags);
2095 if((meta = HvAUX(hv)->xhv_mro_meta)) {
2096 if (meta->mro_linear_all) {
2097 SvREFCNT_dec_NN(meta->mro_linear_all);
2098 /* mro_linear_current is just acting as a shortcut pointer,
2102 /* Only the current MRO is stored, so this owns the data.
2104 SvREFCNT_dec(meta->mro_linear_current);
2105 SvREFCNT_dec(meta->mro_nextmethod);
2106 SvREFCNT_dec(meta->isa);
2107 SvREFCNT_dec(meta->super);
2109 HvAUX(hv)->xhv_mro_meta = NULL;
2111 if (!HvAUX(hv)->xhv_name_u.xhvnameu_name && ! HvAUX(hv)->xhv_backreferences)
2112 SvFLAGS(hv) &= ~SVf_OOK;
2115 Safefree(HvARRAY(hv));
2116 xhv->xhv_max = PERL_HASH_DEFAULT_HvMAX; /* HvMAX(hv) = 7 (it's a normal hash) */
2119 /* if we're freeing the HV, the SvMAGIC field has been reused for
2120 * other purposes, and so there can't be any placeholder magic */
2122 HvPLACEHOLDERS_set(hv, 0);
2125 mg_clear(MUTABLE_SV(hv));
2128 /* disarm hv's premature free guard */
2129 if (LIKELY(PL_tmps_ix == orig_ix))
2132 PL_tmps_stack[orig_ix] = &PL_sv_undef;
2133 SvREFCNT_dec_NN(hv);
2140 Returns the number of hash buckets that happen to be in use.
2142 This function is wrapped by the macro C<HvFILL>.
2144 As of perl 5.25 this function is used only for debugging
2145 purposes, and the number of used hash buckets is not
2146 in any way cached, thus this function can be costly
2147 to execute as it must iterate over all the buckets in the
2154 Perl_hv_fill(pTHX_ HV *const hv)
2157 HE **ents = HvARRAY(hv);
2159 PERL_UNUSED_CONTEXT;
2160 PERL_ARGS_ASSERT_HV_FILL;
2162 /* No keys implies no buckets used.
2163 One key can only possibly mean one bucket used. */
2164 if (HvTOTALKEYS(hv) < 2)
2165 return HvTOTALKEYS(hv);
2168 /* I wonder why we count down here...
2169 * Is it some micro-optimisation?
2170 * I would have thought counting up was better.
2173 HE *const *const last = ents + HvMAX(hv);
2174 count = last + 1 - ents;
2179 } while (++ents <= last);
2184 /* hash a pointer to a U32 - Used in the hash traversal randomization
2185 * and bucket order randomization code
2187 * this code was derived from Sereal, which was derived from autobox.
2190 PERL_STATIC_INLINE U32 S_ptr_hash(PTRV u) {
2193 * This is one of Thomas Wang's hash functions for 64-bit integers from:
2194 * http://www.concentric.net/~Ttwang/tech/inthash.htm
2196 u = (~u) + (u << 18);
2204 * This is one of Bob Jenkins' hash functions for 32-bit integers
2205 * from: http://burtleburtle.net/bob/hash/integer.html
2207 u = (u + 0x7ed55d16) + (u << 12);
2208 u = (u ^ 0xc761c23c) ^ (u >> 19);
2209 u = (u + 0x165667b1) + (u << 5);
2210 u = (u + 0xd3a2646c) ^ (u << 9);
2211 u = (u + 0xfd7046c5) + (u << 3);
2212 u = (u ^ 0xb55a4f09) ^ (u >> 16);
2217 static struct xpvhv_aux*
2218 S_hv_auxinit_internal(struct xpvhv_aux *iter) {
2219 PERL_ARGS_ASSERT_HV_AUXINIT_INTERNAL;
2220 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2221 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
2222 #ifdef PERL_HASH_RANDOMIZE_KEYS
2223 iter->xhv_last_rand = iter->xhv_rand;
2225 iter->xhv_name_u.xhvnameu_name = 0;
2226 iter->xhv_name_count = 0;
2227 iter->xhv_backreferences = 0;
2228 iter->xhv_mro_meta = NULL;
2229 iter->xhv_aux_flags = 0;
2234 static struct xpvhv_aux*
2235 S_hv_auxinit(pTHX_ HV *hv) {
2236 struct xpvhv_aux *iter;
2239 PERL_ARGS_ASSERT_HV_AUXINIT;
2243 Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
2244 + sizeof(struct xpvhv_aux), char);
2246 array = (char *) HvARRAY(hv);
2247 Renew(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
2248 + sizeof(struct xpvhv_aux), char);
2250 HvARRAY(hv) = (HE**)array;
2253 #ifdef PERL_HASH_RANDOMIZE_KEYS
2254 if (PL_HASH_RAND_BITS_ENABLED) {
2255 /* mix in some new state to PL_hash_rand_bits to "randomize" the traversal order*/
2256 if (PL_HASH_RAND_BITS_ENABLED == 1)
2257 PL_hash_rand_bits += ptr_hash((PTRV)array);
2258 PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,1);
2260 iter->xhv_rand = (U32)PL_hash_rand_bits;
2266 return hv_auxinit_internal(iter);
2270 =for apidoc hv_iterinit
2272 Prepares a starting point to traverse a hash table. Returns the number of
2273 keys in the hash, including placeholders (i.e. the same as C<HvTOTALKEYS(hv)>).
2274 The return value is currently only meaningful for hashes without tie magic.
2276 NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
2277 hash buckets that happen to be in use. If you still need that esoteric
2278 value, you can get it through the macro C<HvFILL(hv)>.
2285 Perl_hv_iterinit(pTHX_ HV *hv)
2287 PERL_ARGS_ASSERT_HV_ITERINIT;
2290 struct xpvhv_aux * iter = HvAUX(hv);
2291 HE * const entry = iter->xhv_eiter; /* HvEITER(hv) */
2292 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
2294 hv_free_ent(hv, entry);
2296 iter = HvAUX(hv); /* may have been reallocated */
2297 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2298 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
2299 #ifdef PERL_HASH_RANDOMIZE_KEYS
2300 iter->xhv_last_rand = iter->xhv_rand;
2306 /* note this includes placeholders! */
2307 return HvTOTALKEYS(hv);
2311 Perl_hv_riter_p(pTHX_ HV *hv) {
2312 struct xpvhv_aux *iter;
2314 PERL_ARGS_ASSERT_HV_RITER_P;
2316 iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2317 return &(iter->xhv_riter);
2321 Perl_hv_eiter_p(pTHX_ HV *hv) {
2322 struct xpvhv_aux *iter;
2324 PERL_ARGS_ASSERT_HV_EITER_P;
2326 iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2327 return &(iter->xhv_eiter);
2331 Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
2332 struct xpvhv_aux *iter;
2334 PERL_ARGS_ASSERT_HV_RITER_SET;
2342 iter = hv_auxinit(hv);
2344 iter->xhv_riter = riter;
2348 Perl_hv_rand_set(pTHX_ HV *hv, U32 new_xhv_rand) {
2349 struct xpvhv_aux *iter;
2351 PERL_ARGS_ASSERT_HV_RAND_SET;
2353 #ifdef PERL_HASH_RANDOMIZE_KEYS
2357 iter = hv_auxinit(hv);
2359 iter->xhv_rand = new_xhv_rand;
2361 Perl_croak(aTHX_ "This Perl has not been built with support for randomized hash key traversal but something called Perl_hv_rand_set().");
2366 Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
2367 struct xpvhv_aux *iter;
2369 PERL_ARGS_ASSERT_HV_EITER_SET;
2374 /* 0 is the default so don't go malloc()ing a new structure just to
2379 iter = hv_auxinit(hv);
2381 iter->xhv_eiter = eiter;
2385 Perl_hv_name_set(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2387 struct xpvhv_aux *iter;
2391 PERL_ARGS_ASSERT_HV_NAME_SET;
2394 Perl_croak(aTHX_ "panic: hv name too long (%" UVuf ")", (UV) len);
2398 if (iter->xhv_name_u.xhvnameu_name) {
2399 if(iter->xhv_name_count) {
2400 if(flags & HV_NAME_SETALL) {
2401 HEK ** const this_name = HvAUX(hv)->xhv_name_u.xhvnameu_names;
2402 HEK **hekp = this_name + (
2403 iter->xhv_name_count < 0
2404 ? -iter->xhv_name_count
2405 : iter->xhv_name_count
2407 while(hekp-- > this_name+1)
2408 unshare_hek_or_pvn(*hekp, 0, 0, 0);
2409 /* The first elem may be null. */
2410 if(*this_name) unshare_hek_or_pvn(*this_name, 0, 0, 0);
2411 Safefree(this_name);
2412 iter = HvAUX(hv); /* may been realloced */
2413 spot = &iter->xhv_name_u.xhvnameu_name;
2414 iter->xhv_name_count = 0;
2417 if(iter->xhv_name_count > 0) {
2418 /* shift some things over */
2420 iter->xhv_name_u.xhvnameu_names, iter->xhv_name_count + 1, HEK *
2422 spot = iter->xhv_name_u.xhvnameu_names;
2423 spot[iter->xhv_name_count] = spot[1];
2425 iter->xhv_name_count = -(iter->xhv_name_count + 1);
2427 else if(*(spot = iter->xhv_name_u.xhvnameu_names)) {
2428 unshare_hek_or_pvn(*spot, 0, 0, 0);
2432 else if (flags & HV_NAME_SETALL) {
2433 unshare_hek_or_pvn(iter->xhv_name_u.xhvnameu_name, 0, 0, 0);
2434 iter = HvAUX(hv); /* may been realloced */
2435 spot = &iter->xhv_name_u.xhvnameu_name;
2438 HEK * const existing_name = iter->xhv_name_u.xhvnameu_name;
2439 Newx(iter->xhv_name_u.xhvnameu_names, 2, HEK *);
2440 iter->xhv_name_count = -2;
2441 spot = iter->xhv_name_u.xhvnameu_names;
2442 spot[1] = existing_name;
2445 else { spot = &iter->xhv_name_u.xhvnameu_name; iter->xhv_name_count = 0; }
2450 iter = hv_auxinit(hv);
2451 spot = &iter->xhv_name_u.xhvnameu_name;
2453 PERL_HASH(hash, name, len);
2454 *spot = name ? share_hek(name, flags & SVf_UTF8 ? -(I32)len : (I32)len, hash) : NULL;
2458 This is basically sv_eq_flags() in sv.c, but we avoid the magic
2463 hek_eq_pvn_flags(pTHX_ const HEK *hek, const char* pv, const I32 pvlen, const U32 flags) {
2464 if ( (HEK_UTF8(hek) ? 1 : 0) != (flags & SVf_UTF8 ? 1 : 0) ) {
2465 if (flags & SVf_UTF8)
2466 return (bytes_cmp_utf8(
2467 (const U8*)HEK_KEY(hek), HEK_LEN(hek),
2468 (const U8*)pv, pvlen) == 0);
2470 return (bytes_cmp_utf8(
2471 (const U8*)pv, pvlen,
2472 (const U8*)HEK_KEY(hek), HEK_LEN(hek)) == 0);
2475 return HEK_LEN(hek) == pvlen && ((HEK_KEY(hek) == pv)
2476 || memEQ(HEK_KEY(hek), pv, pvlen));
2480 =for apidoc hv_ename_add
2482 Adds a name to a stash's internal list of effective names. See
2483 C<L</hv_ename_delete>>.
2485 This is called when a stash is assigned to a new location in the symbol
2492 Perl_hv_ename_add(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2494 struct xpvhv_aux *aux = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2497 PERL_ARGS_ASSERT_HV_ENAME_ADD;
2500 Perl_croak(aTHX_ "panic: hv name too long (%" UVuf ")", (UV) len);
2502 PERL_HASH(hash, name, len);
2504 if (aux->xhv_name_count) {
2505 I32 count = aux->xhv_name_count;
2506 HEK ** const xhv_name = aux->xhv_name_u.xhvnameu_names + (count<0);
2507 HEK **hekp = xhv_name + (count < 0 ? -count - 1 : count);
2508 while (hekp-- > xhv_name)
2512 (HEK_UTF8(*hekp) || (flags & SVf_UTF8))
2513 ? hek_eq_pvn_flags(aTHX_ *hekp, name, (I32)len, flags)
2514 : (HEK_LEN(*hekp) == (I32)len && memEQ(HEK_KEY(*hekp), name, len))
2516 if (hekp == xhv_name && count < 0)
2517 aux->xhv_name_count = -count;
2521 if (count < 0) aux->xhv_name_count--, count = -count;
2522 else aux->xhv_name_count++;
2523 Renew(aux->xhv_name_u.xhvnameu_names, count + 1, HEK *);
2524 (aux->xhv_name_u.xhvnameu_names)[count] = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
2527 HEK *existing_name = aux->xhv_name_u.xhvnameu_name;
2530 (HEK_UTF8(existing_name) || (flags & SVf_UTF8))
2531 ? hek_eq_pvn_flags(aTHX_ existing_name, name, (I32)len, flags)
2532 : (HEK_LEN(existing_name) == (I32)len && memEQ(HEK_KEY(existing_name), name, len))
2535 Newx(aux->xhv_name_u.xhvnameu_names, 2, HEK *);
2536 aux->xhv_name_count = existing_name ? 2 : -2;
2537 *aux->xhv_name_u.xhvnameu_names = existing_name;
2538 (aux->xhv_name_u.xhvnameu_names)[1] = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
2543 =for apidoc hv_ename_delete
2545 Removes a name from a stash's internal list of effective names. If this is
2546 the name returned by C<HvENAME>, then another name in the list will take
2547 its place (C<HvENAME> will use it).
2549 This is called when a stash is deleted from the symbol table.
2555 Perl_hv_ename_delete(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2557 struct xpvhv_aux *aux;
2559 PERL_ARGS_ASSERT_HV_ENAME_DELETE;
2562 Perl_croak(aTHX_ "panic: hv name too long (%" UVuf ")", (UV) len);
2564 if (!SvOOK(hv)) return;
2567 if (!aux->xhv_name_u.xhvnameu_name) return;
2569 if (aux->xhv_name_count) {
2570 HEK ** const namep = aux->xhv_name_u.xhvnameu_names;
2571 I32 const count = aux->xhv_name_count;
2572 HEK **victim = namep + (count < 0 ? -count : count);
2573 while (victim-- > namep + 1)
2575 (HEK_UTF8(*victim) || (flags & SVf_UTF8))
2576 ? hek_eq_pvn_flags(aTHX_ *victim, name, (I32)len, flags)
2577 : (HEK_LEN(*victim) == (I32)len && memEQ(HEK_KEY(*victim), name, len))
2579 unshare_hek_or_pvn(*victim, 0, 0, 0);
2580 aux = HvAUX(hv); /* may been realloced */
2581 if (count < 0) ++aux->xhv_name_count;
2582 else --aux->xhv_name_count;
2584 (aux->xhv_name_count == 1 || aux->xhv_name_count == -1)
2586 ) { /* if there are none left */
2588 aux->xhv_name_u.xhvnameu_names = NULL;
2589 aux->xhv_name_count = 0;
2592 /* Move the last one back to fill the empty slot. It
2593 does not matter what order they are in. */
2594 *victim = *(namep + (count < 0 ? -count : count) - 1);
2599 count > 0 && ((HEK_UTF8(*namep) || (flags & SVf_UTF8))
2600 ? hek_eq_pvn_flags(aTHX_ *namep, name, (I32)len, flags)
2601 : (HEK_LEN(*namep) == (I32)len && memEQ(HEK_KEY(*namep), name, len))
2604 aux->xhv_name_count = -count;
2608 (HEK_UTF8(aux->xhv_name_u.xhvnameu_name) || (flags & SVf_UTF8))
2609 ? hek_eq_pvn_flags(aTHX_ aux->xhv_name_u.xhvnameu_name, name, (I32)len, flags)
2610 : (HEK_LEN(aux->xhv_name_u.xhvnameu_name) == (I32)len &&
2611 memEQ(HEK_KEY(aux->xhv_name_u.xhvnameu_name), name, len))
2613 HEK * const namehek = aux->xhv_name_u.xhvnameu_name;
2614 Newx(aux->xhv_name_u.xhvnameu_names, 1, HEK *);
2615 *aux->xhv_name_u.xhvnameu_names = namehek;
2616 aux->xhv_name_count = -1;
2621 Perl_hv_backreferences_p(pTHX_ HV *hv) {
2622 PERL_ARGS_ASSERT_HV_BACKREFERENCES_P;
2623 /* See also Perl_sv_get_backrefs in sv.c where this logic is unrolled */
2625 struct xpvhv_aux * const iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2626 return &(iter->xhv_backreferences);
2631 Perl_hv_kill_backrefs(pTHX_ HV *hv) {
2634 PERL_ARGS_ASSERT_HV_KILL_BACKREFS;
2639 av = HvAUX(hv)->xhv_backreferences;
2642 HvAUX(hv)->xhv_backreferences = 0;
2643 Perl_sv_kill_backrefs(aTHX_ MUTABLE_SV(hv), av);
2644 if (SvTYPE(av) == SVt_PVAV)
2645 SvREFCNT_dec_NN(av);
2650 hv_iternext is implemented as a macro in hv.h
2652 =for apidoc hv_iternext
2654 Returns entries from a hash iterator. See C<L</hv_iterinit>>.
2656 You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
2657 iterator currently points to, without losing your place or invalidating your
2658 iterator. Note that in this case the current entry is deleted from the hash
2659 with your iterator holding the last reference to it. Your iterator is flagged
2660 to free the entry on the next call to C<hv_iternext>, so you must not discard
2661 your iterator immediately else the entry will leak - call C<hv_iternext> to
2662 trigger the resource deallocation.
2664 =for apidoc hv_iternext_flags
2666 Returns entries from a hash iterator. See C<L</hv_iterinit>> and
2668 The C<flags> value will normally be zero; if C<HV_ITERNEXT_WANTPLACEHOLDERS> is
2669 set the placeholders keys (for restricted hashes) will be returned in addition
2670 to normal keys. By default placeholders are automatically skipped over.
2671 Currently a placeholder is implemented with a value that is
2672 C<&PL_sv_placeholder>. Note that the implementation of placeholders and
2673 restricted hashes may change, and the implementation currently is
2674 insufficiently abstracted for any change to be tidy.
2676 =for apidoc Amnh||HV_ITERNEXT_WANTPLACEHOLDERS
2682 Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
2688 struct xpvhv_aux *iter;
2690 PERL_ARGS_ASSERT_HV_ITERNEXT_FLAGS;
2692 xhv = (XPVHV*)SvANY(hv);
2695 /* Too many things (well, pp_each at least) merrily assume that you can
2696 call hv_iternext without calling hv_iterinit, so we'll have to deal
2702 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2703 if (SvMAGICAL(hv) && SvRMAGICAL(hv)) {
2704 if ( ( mg = mg_find((const SV *)hv, PERL_MAGIC_tied) ) ) {
2705 SV * const key = sv_newmortal();
2707 sv_setsv(key, HeSVKEY_force(entry));
2708 SvREFCNT_dec(HeSVKEY(entry)); /* get rid of previous key */
2709 HeSVKEY_set(entry, NULL);
2715 /* one HE per MAGICAL hash */
2716 iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
2717 HvLAZYDEL_on(hv); /* make sure entry gets freed */
2719 Newxz(k, HEK_BASESIZE + sizeof(const SV *), char);
2721 HeKEY_hek(entry) = hek;
2722 HeKLEN(entry) = HEf_SVKEY;
2724 magic_nextpack(MUTABLE_SV(hv),mg,key);
2726 /* force key to stay around until next time */
2727 HeSVKEY_set(entry, SvREFCNT_inc_simple_NN(key));
2728 return entry; /* beware, hent_val is not set */
2730 SvREFCNT_dec(HeVAL(entry));
2731 Safefree(HeKEY_hek(entry));
2733 iter = HvAUX(hv); /* may been realloced */
2734 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
2739 #if defined(DYNAMIC_ENV_FETCH) && !defined(__riscos__) /* set up %ENV for iteration */
2740 if (!entry && SvRMAGICAL((const SV *)hv)
2741 && mg_find((const SV *)hv, PERL_MAGIC_env)) {
2744 /* The prime_env_iter() on VMS just loaded up new hash values
2745 * so the iteration count needs to be reset back to the beginning
2749 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2754 /* hv_iterinit now ensures this. */
2755 assert (HvARRAY(hv));
2757 /* At start of hash, entry is NULL. */
2760 entry = HeNEXT(entry);
2761 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2763 * Skip past any placeholders -- don't want to include them in
2766 while (entry && HeVAL(entry) == &PL_sv_placeholder) {
2767 entry = HeNEXT(entry);
2772 #ifdef PERL_HASH_RANDOMIZE_KEYS
2773 if (iter->xhv_last_rand != iter->xhv_rand) {
2774 if (iter->xhv_riter != -1) {
2775 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
2776 "Use of each() on hash after insertion without resetting hash iterator results in undefined behavior"
2780 iter = HvAUX(hv); /* may been realloced */
2781 iter->xhv_last_rand = iter->xhv_rand;
2785 /* Skip the entire loop if the hash is empty. */
2786 if ((flags & HV_ITERNEXT_WANTPLACEHOLDERS)
2787 ? HvTOTALKEYS(hv) : HvUSEDKEYS(hv)) {
2789 /* OK. Come to the end of the current list. Grab the next one. */
2791 iter->xhv_riter++; /* HvRITER(hv)++ */
2792 if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
2793 /* There is no next one. End of the hash. */
2794 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2795 #ifdef PERL_HASH_RANDOMIZE_KEYS
2796 iter->xhv_last_rand = iter->xhv_rand; /* reset xhv_last_rand so we can detect inserts during traversal */
2800 entry = (HvARRAY(hv))[ PERL_HASH_ITER_BUCKET(iter) & xhv->xhv_max ];
2802 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2803 /* If we have an entry, but it's a placeholder, don't count it.
2805 while (entry && HeVAL(entry) == &PL_sv_placeholder)
2806 entry = HeNEXT(entry);
2808 /* Will loop again if this linked list starts NULL
2809 (for HV_ITERNEXT_WANTPLACEHOLDERS)
2810 or if we run through it and find only placeholders. */
2814 iter->xhv_riter = -1;
2815 #ifdef PERL_HASH_RANDOMIZE_KEYS
2816 iter->xhv_last_rand = iter->xhv_rand;
2820 if (oldentry && HvLAZYDEL(hv)) { /* was deleted earlier? */
2822 hv_free_ent(hv, oldentry);
2825 iter = HvAUX(hv); /* may been realloced */
2826 iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
2831 =for apidoc hv_iterkey
2833 Returns the key from the current position of the hash iterator. See
2840 Perl_hv_iterkey(pTHX_ HE *entry, I32 *retlen)
2842 PERL_ARGS_ASSERT_HV_ITERKEY;
2844 if (HeKLEN(entry) == HEf_SVKEY) {
2846 char * const p = SvPV(HeKEY_sv(entry), len);
2851 *retlen = HeKLEN(entry);
2852 return HeKEY(entry);
2856 /* unlike hv_iterval(), this always returns a mortal copy of the key */
2858 =for apidoc hv_iterkeysv
2860 Returns the key as an C<SV*> from the current position of the hash
2861 iterator. The return value will always be a mortal copy of the key. Also
2862 see C<L</hv_iterinit>>.
2868 Perl_hv_iterkeysv(pTHX_ HE *entry)
2870 PERL_ARGS_ASSERT_HV_ITERKEYSV;
2872 return sv_2mortal(newSVhek(HeKEY_hek(entry)));
2876 =for apidoc hv_iterval
2878 Returns the value from the current position of the hash iterator. See
2885 Perl_hv_iterval(pTHX_ HV *hv, HE *entry)
2887 PERL_ARGS_ASSERT_HV_ITERVAL;
2889 if (SvRMAGICAL(hv)) {
2890 if (mg_find((const SV *)hv, PERL_MAGIC_tied)) {
2891 SV* const sv = sv_newmortal();
2892 if (HeKLEN(entry) == HEf_SVKEY)
2893 mg_copy(MUTABLE_SV(hv), sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
2895 mg_copy(MUTABLE_SV(hv), sv, HeKEY(entry), HeKLEN(entry));
2899 return HeVAL(entry);
2903 =for apidoc hv_iternextsv
2905 Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2912 Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
2914 HE * const he = hv_iternext_flags(hv, 0);
2916 PERL_ARGS_ASSERT_HV_ITERNEXTSV;
2920 *key = hv_iterkey(he, retlen);
2921 return hv_iterval(hv, he);
2928 =for apidoc hv_magic
2930 Adds magic to a hash. See C<L</sv_magic>>.
2935 /* possibly free a shared string if no one has access to it
2936 * len and hash must both be valid for str.
2939 Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
2941 unshare_hek_or_pvn (NULL, str, len, hash);
2946 Perl_unshare_hek(pTHX_ HEK *hek)
2949 unshare_hek_or_pvn(hek, NULL, 0, 0);
2952 /* possibly free a shared string if no one has access to it
2953 hek if non-NULL takes priority over the other 3, else str, len and hash
2954 are used. If so, len and hash must both be valid for str.
2957 S_unshare_hek_or_pvn(pTHX_ const HEK *hek, const char *str, I32 len, U32 hash)
2962 bool is_utf8 = FALSE;
2964 const char * const save = str;
2965 struct shared_he *he = NULL;
2968 /* Find the shared he which is just before us in memory. */
2969 he = (struct shared_he *)(((char *)hek)
2970 - STRUCT_OFFSET(struct shared_he,
2973 /* Assert that the caller passed us a genuine (or at least consistent)
2975 assert (he->shared_he_he.hent_hek == hek);
2977 if (he->shared_he_he.he_valu.hent_refcount - 1) {
2978 --he->shared_he_he.he_valu.hent_refcount;
2982 hash = HEK_HASH(hek);
2983 } else if (len < 0) {
2984 STRLEN tmplen = -len;
2986 /* See the note in hv_fetch(). --jhi */
2987 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2990 k_flags = HVhek_UTF8;
2992 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2995 /* what follows was the moral equivalent of:
2996 if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
2998 hv_delete(PL_strtab, str, len, G_DISCARD, hash);
3000 xhv = (XPVHV*)SvANY(PL_strtab);
3001 /* assert(xhv_array != 0) */
3002 oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
3004 const HE *const he_he = &(he->shared_he_he);
3005 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
3010 const int flags_masked = k_flags & HVhek_MASK;
3011 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
3012 if (HeHASH(entry) != hash) /* strings can't be equal */
3014 if (HeKLEN(entry) != len)
3016 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
3018 if (HeKFLAGS(entry) != flags_masked)
3025 if (--entry->he_valu.hent_refcount == 0) {
3026 *oentry = HeNEXT(entry);
3028 xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
3033 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
3034 "Attempt to free nonexistent shared string '%s'%s"
3036 hek ? HEK_KEY(hek) : str,
3037 ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
3038 if (k_flags & HVhek_FREEKEY)
3042 /* get a (constant) string ptr from the global string table
3043 * string will get added if it is not already there.
3044 * len and hash must both be valid for str.
3047 Perl_share_hek(pTHX_ const char *str, SSize_t len, U32 hash)
3049 bool is_utf8 = FALSE;
3051 const char * const save = str;
3053 PERL_ARGS_ASSERT_SHARE_HEK;
3056 STRLEN tmplen = -len;
3058 /* See the note in hv_fetch(). --jhi */
3059 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
3061 /* If we were able to downgrade here, then than means that we were passed
3062 in a key which only had chars 0-255, but was utf8 encoded. */
3065 /* If we found we were able to downgrade the string to bytes, then
3066 we should flag that it needs upgrading on keys or each. Also flag
3067 that we need share_hek_flags to free the string. */
3069 PERL_HASH(hash, str, len);
3070 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
3074 return share_hek_flags (str, len, hash, flags);
3078 S_share_hek_flags(pTHX_ const char *str, STRLEN len, U32 hash, int flags)
3081 const int flags_masked = flags & HVhek_MASK;
3082 const U32 hindex = hash & (I32) HvMAX(PL_strtab);
3083 XPVHV * const xhv = (XPVHV*)SvANY(PL_strtab);
3085 PERL_ARGS_ASSERT_SHARE_HEK_FLAGS;
3087 if (UNLIKELY(len > (STRLEN) I32_MAX)) {
3088 Perl_croak_nocontext("Sorry, hash keys must be smaller than 2**31 bytes");
3091 /* what follows is the moral equivalent of:
3093 if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
3094 hv_store(PL_strtab, str, len, NULL, hash);
3096 Can't rehash the shared string table, so not sure if it's worth
3097 counting the number of entries in the linked list
3100 /* assert(xhv_array != 0) */
3101 entry = (HvARRAY(PL_strtab))[hindex];
3102 for (;entry; entry = HeNEXT(entry)) {
3103 if (HeHASH(entry) != hash) /* strings can't be equal */
3105 if (HeKLEN(entry) != (SSize_t) len)
3107 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
3109 if (HeKFLAGS(entry) != flags_masked)
3115 /* What used to be head of the list.
3116 If this is NULL, then we're the first entry for this slot, which
3117 means we need to increate fill. */
3118 struct shared_he *new_entry;
3121 HE **const head = &HvARRAY(PL_strtab)[hindex];
3122 HE *const next = *head;
3124 /* We don't actually store a HE from the arena and a regular HEK.
3125 Instead we allocate one chunk of memory big enough for both,
3126 and put the HEK straight after the HE. This way we can find the
3127 HE directly from the HEK.
3130 Newx(k, STRUCT_OFFSET(struct shared_he,
3131 shared_he_hek.hek_key[0]) + len + 2, char);
3132 new_entry = (struct shared_he *)k;
3133 entry = &(new_entry->shared_he_he);
3134 hek = &(new_entry->shared_he_hek);
3136 Copy(str, HEK_KEY(hek), len, char);
3137 HEK_KEY(hek)[len] = 0;
3139 HEK_HASH(hek) = hash;
3140 HEK_FLAGS(hek) = (unsigned char)flags_masked;
3142 /* Still "point" to the HEK, so that other code need not know what
3144 HeKEY_hek(entry) = hek;
3145 entry->he_valu.hent_refcount = 0;
3146 HeNEXT(entry) = next;
3149 xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
3150 if (!next) { /* initial entry? */
3151 } else if ( DO_HSPLIT(xhv) ) {
3152 const STRLEN oldsize = xhv->xhv_max + 1;
3153 hsplit(PL_strtab, oldsize, oldsize * 2);
3157 ++entry->he_valu.hent_refcount;
3159 if (flags & HVhek_FREEKEY)
3162 return HeKEY_hek(entry);
3166 Perl_hv_placeholders_p(pTHX_ HV *hv)
3168 MAGIC *mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
3170 PERL_ARGS_ASSERT_HV_PLACEHOLDERS_P;
3173 mg = sv_magicext(MUTABLE_SV(hv), 0, PERL_MAGIC_rhash, 0, 0, 0);
3176 Perl_die(aTHX_ "panic: hv_placeholders_p");
3179 return &(mg->mg_len);
3184 Perl_hv_placeholders_get(pTHX_ const HV *hv)
3186 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
3188 PERL_ARGS_ASSERT_HV_PLACEHOLDERS_GET;
3189 PERL_UNUSED_CONTEXT;
3191 return mg ? mg->mg_len : 0;
3195 Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
3197 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
3199 PERL_ARGS_ASSERT_HV_PLACEHOLDERS_SET;
3204 if (!sv_magicext(MUTABLE_SV(hv), 0, PERL_MAGIC_rhash, 0, 0, ph))
3205 Perl_die(aTHX_ "panic: hv_placeholders_set");
3207 /* else we don't need to add magic to record 0 placeholders. */
3211 S_refcounted_he_value(pTHX_ const struct refcounted_he *he)
3215 PERL_ARGS_ASSERT_REFCOUNTED_HE_VALUE;
3217 switch(he->refcounted_he_data[0] & HVrhek_typemask) {
3222 value = &PL_sv_placeholder;
3225 value = newSViv(he->refcounted_he_val.refcounted_he_u_iv);
3228 value = newSVuv(he->refcounted_he_val.refcounted_he_u_uv);
3231 case HVrhek_PV_UTF8:
3232 /* Create a string SV that directly points to the bytes in our
3234 value = newSV_type(SVt_PV);
3235 SvPV_set(value, (char *) he->refcounted_he_data + 1);
3236 SvCUR_set(value, he->refcounted_he_val.refcounted_he_u_len);
3237 /* This stops anything trying to free it */
3238 SvLEN_set(value, 0);
3240 SvREADONLY_on(value);
3241 if ((he->refcounted_he_data[0] & HVrhek_typemask) == HVrhek_PV_UTF8)
3245 Perl_croak(aTHX_ "panic: refcounted_he_value bad flags %" UVxf,
3246 (UV)he->refcounted_he_data[0]);
3252 =for apidoc refcounted_he_chain_2hv
3254 Generates and returns a C<HV *> representing the content of a
3255 C<refcounted_he> chain.
3256 C<flags> is currently unused and must be zero.
3261 Perl_refcounted_he_chain_2hv(pTHX_ const struct refcounted_he *chain, U32 flags)
3264 U32 placeholders, max;
3267 Perl_croak(aTHX_ "panic: refcounted_he_chain_2hv bad flags %" UVxf,
3270 /* We could chase the chain once to get an idea of the number of keys,
3271 and call ksplit. But for now we'll make a potentially inefficient
3272 hash with only 8 entries in its array. */
3277 Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(max + 1), char);
3278 HvARRAY(hv) = (HE**)array;
3284 U32 hash = chain->refcounted_he_hash;
3286 U32 hash = HEK_HASH(chain->refcounted_he_hek);
3288 HE **oentry = &((HvARRAY(hv))[hash & max]);
3289 HE *entry = *oentry;
3292 for (; entry; entry = HeNEXT(entry)) {
3293 if (HeHASH(entry) == hash) {
3294 /* We might have a duplicate key here. If so, entry is older
3295 than the key we've already put in the hash, so if they are
3296 the same, skip adding entry. */
3298 const STRLEN klen = HeKLEN(entry);
3299 const char *const key = HeKEY(entry);
3300 if (klen == chain->refcounted_he_keylen
3301 && (!!HeKUTF8(entry)
3302 == !!(chain->refcounted_he_data[0] & HVhek_UTF8))
3303 && memEQ(key, REF_HE_KEY(chain), klen))
3306 if (HeKEY_hek(entry) == chain->refcounted_he_hek)
3308 if (HeKLEN(entry) == HEK_LEN(chain->refcounted_he_hek)
3309 && HeKUTF8(entry) == HEK_UTF8(chain->refcounted_he_hek)
3310 && memEQ(HeKEY(entry), HEK_KEY(chain->refcounted_he_hek),
3321 = share_hek_flags(REF_HE_KEY(chain),
3322 chain->refcounted_he_keylen,
3323 chain->refcounted_he_hash,
3324 (chain->refcounted_he_data[0]
3325 & (HVhek_UTF8|HVhek_WASUTF8)));
3327 HeKEY_hek(entry) = share_hek_hek(chain->refcounted_he_hek);
3329 value = refcounted_he_value(chain);
3330 if (value == &PL_sv_placeholder)
3332 HeVAL(entry) = value;
3334 /* Link it into the chain. */
3335 HeNEXT(entry) = *oentry;
3341 chain = chain->refcounted_he_next;
3345 clear_placeholders(hv, placeholders);
3346 HvTOTALKEYS(hv) -= placeholders;
3349 /* We could check in the loop to see if we encounter any keys with key
3350 flags, but it's probably not worth it, as this per-hash flag is only
3351 really meant as an optimisation for things like Storable. */
3353 DEBUG_A(Perl_hv_assert(aTHX_ hv));
3359 =for apidoc refcounted_he_fetch_pvn
3361 Search along a C<refcounted_he> chain for an entry with the key specified
3362 by C<keypv> and C<keylen>. If C<flags> has the C<REFCOUNTED_HE_KEY_UTF8>
3363 bit set, the key octets are interpreted as UTF-8, otherwise they
3364 are interpreted as Latin-1. C<hash> is a precomputed hash of the key
3365 string, or zero if it has not been precomputed. Returns a mortal scalar
3366 representing the value associated with the key, or C<&PL_sv_placeholder>
3367 if there is no value associated with the key.
3373 Perl_refcounted_he_fetch_pvn(pTHX_ const struct refcounted_he *chain,
3374 const char *keypv, STRLEN keylen, U32 hash, U32 flags)
3377 PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_PVN;
3379 if (flags & ~(REFCOUNTED_HE_KEY_UTF8|REFCOUNTED_HE_EXISTS))
3380 Perl_croak(aTHX_ "panic: refcounted_he_fetch_pvn bad flags %" UVxf,
3384 if (flags & REFCOUNTED_HE_KEY_UTF8) {
3385 /* For searching purposes, canonicalise to Latin-1 where possible. */
3386 const char *keyend = keypv + keylen, *p;
3387 STRLEN nonascii_count = 0;
3388 for (p = keypv; p != keyend; p++) {
3389 if (! UTF8_IS_INVARIANT(*p)) {
3390 if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(p, keyend)) {
3391 goto canonicalised_key;
3397 if (nonascii_count) {
3399 const char *p = keypv, *keyend = keypv + keylen;
3400 keylen -= nonascii_count;
3401 Newx(q, keylen, char);
3404 for (; p != keyend; p++, q++) {
3406 if (UTF8_IS_INVARIANT(c)) {
3411 *q = (char) EIGHT_BIT_UTF8_TO_NATIVE(c, *p);
3415 flags &= ~REFCOUNTED_HE_KEY_UTF8;
3416 canonicalised_key: ;
3418 utf8_flag = (flags & REFCOUNTED_HE_KEY_UTF8) ? HVhek_UTF8 : 0;
3420 PERL_HASH(hash, keypv, keylen);
3422 for (; chain; chain = chain->refcounted_he_next) {
3425 hash == chain->refcounted_he_hash &&
3426 keylen == chain->refcounted_he_keylen &&
3427 memEQ(REF_HE_KEY(chain), keypv, keylen) &&
3428 utf8_flag == (chain->refcounted_he_data[0] & HVhek_UTF8)
3430 hash == HEK_HASH(chain->refcounted_he_hek) &&
3431 keylen == (STRLEN)HEK_LEN(chain->refcounted_he_hek) &&
3432 memEQ(HEK_KEY(chain->refcounted_he_hek), keypv, keylen) &&
3433 utf8_flag == (HEK_FLAGS(chain->refcounted_he_hek) & HVhek_UTF8)
3436 if (flags & REFCOUNTED_HE_EXISTS)
3437 return (chain->refcounted_he_data[0] & HVrhek_typemask)
3439 ? NULL : &PL_sv_yes;
3440 return sv_2mortal(refcounted_he_value(chain));
3444 return flags & REFCOUNTED_HE_EXISTS ? NULL : &PL_sv_placeholder;
3448 =for apidoc refcounted_he_fetch_pv
3450 Like L</refcounted_he_fetch_pvn>, but takes a nul-terminated string
3451 instead of a string/length pair.
3457 Perl_refcounted_he_fetch_pv(pTHX_ const struct refcounted_he *chain,
3458 const char *key, U32 hash, U32 flags)
3460 PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_PV;
3461 return refcounted_he_fetch_pvn(chain, key, strlen(key), hash, flags);
3465 =for apidoc refcounted_he_fetch_sv
3467 Like L</refcounted_he_fetch_pvn>, but takes a Perl scalar instead of a
3474 Perl_refcounted_he_fetch_sv(pTHX_ const struct refcounted_he *chain,
3475 SV *key, U32 hash, U32 flags)
3479 PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_SV;
3480 if (flags & REFCOUNTED_HE_KEY_UTF8)
3481 Perl_croak(aTHX_ "panic: refcounted_he_fetch_sv bad flags %" UVxf,
3483 keypv = SvPV_const(key, keylen);
3485 flags |= REFCOUNTED_HE_KEY_UTF8;
3486 if (!hash && SvIsCOW_shared_hash(key))
3487 hash = SvSHARED_HASH(key);
3488 return refcounted_he_fetch_pvn(chain, keypv, keylen, hash, flags);
3492 =for apidoc refcounted_he_new_pvn
3494 Creates a new C<refcounted_he>. This consists of a single key/value
3495 pair and a reference to an existing C<refcounted_he> chain (which may
3496 be empty), and thus forms a longer chain. When using the longer chain,
3497 the new key/value pair takes precedence over any entry for the same key
3498 further along the chain.
3500 The new key is specified by C<keypv> and C<keylen>. If C<flags> has
3501 the C<REFCOUNTED_HE_KEY_UTF8> bit set, the key octets are interpreted
3502 as UTF-8, otherwise they are interpreted as Latin-1. C<hash> is
3503 a precomputed hash of the key string, or zero if it has not been
3506 C<value> is the scalar value to store for this key. C<value> is copied
3507 by this function, which thus does not take ownership of any reference
3508 to it, and later changes to the scalar will not be reflected in the
3509 value visible in the C<refcounted_he>. Complex types of scalar will not
3510 be stored with referential integrity, but will be coerced to strings.
3511 C<value> may be either null or C<&PL_sv_placeholder> to indicate that no
3512 value is to be associated with the key; this, as with any non-null value,
3513 takes precedence over the existence of a value for the key further along
3516 C<parent> points to the rest of the C<refcounted_he> chain to be
3517 attached to the new C<refcounted_he>. This function takes ownership
3518 of one reference to C<parent>, and returns one reference to the new
3524 struct refcounted_he *
3525 Perl_refcounted_he_new_pvn(pTHX_ struct refcounted_he *parent,
3526 const char *keypv, STRLEN keylen, U32 hash, SV *value, U32 flags)
3528 STRLEN value_len = 0;
3529 const char *value_p = NULL;
3533 STRLEN key_offset = 1;
3534 struct refcounted_he *he;
3535 PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_PVN;
3537 if (!value || value == &PL_sv_placeholder) {
3538 value_type = HVrhek_delete;
3539 } else if (SvPOK(value)) {
3540 value_type = HVrhek_PV;
3541 } else if (SvIOK(value)) {
3542 value_type = SvUOK((const SV *)value) ? HVrhek_UV : HVrhek_IV;
3543 } else if (!SvOK(value)) {
3544 value_type = HVrhek_undef;
3546 value_type = HVrhek_PV;
3548 is_pv = value_type == HVrhek_PV;
3550 /* Do it this way so that the SvUTF8() test is after the SvPV, in case
3551 the value is overloaded, and doesn't yet have the UTF-8flag set. */
3552 value_p = SvPV_const(value, value_len);
3554 value_type = HVrhek_PV_UTF8;
3555 key_offset = value_len + 2;
3557 hekflags = value_type;
3559 if (flags & REFCOUNTED_HE_KEY_UTF8) {
3560 /* Canonicalise to Latin-1 where possible. */
3561 const char *keyend = keypv + keylen, *p;
3562 STRLEN nonascii_count = 0;
3563 for (p = keypv; p != keyend; p++) {
3564 if (! UTF8_IS_INVARIANT(*p)) {
3565 if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(p, keyend)) {
3566 goto canonicalised_key;
3572 if (nonascii_count) {
3574 const char *p = keypv, *keyend = keypv + keylen;
3575 keylen -= nonascii_count;
3576 Newx(q, keylen, char);
3579 for (; p != keyend; p++, q++) {
3581 if (UTF8_IS_INVARIANT(c)) {
3586 *q = (char) EIGHT_BIT_UTF8_TO_NATIVE(c, *p);
3590 flags &= ~REFCOUNTED_HE_KEY_UTF8;
3591 canonicalised_key: ;
3593 if (flags & REFCOUNTED_HE_KEY_UTF8)
3594 hekflags |= HVhek_UTF8;
3596 PERL_HASH(hash, keypv, keylen);
3599 he = (struct refcounted_he*)
3600 PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
3604 he = (struct refcounted_he*)
3605 PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
3609 he->refcounted_he_next = parent;
3612 Copy(value_p, he->refcounted_he_data + 1, value_len + 1, char);
3613 he->refcounted_he_val.refcounted_he_u_len = value_len;
3614 } else if (value_type == HVrhek_IV) {
3615 he->refcounted_he_val.refcounted_he_u_iv = SvIVX(value);
3616 } else if (value_type == HVrhek_UV) {
3617 he->refcounted_he_val.refcounted_he_u_uv = SvUVX(value);
3621 he->refcounted_he_hash = hash;
3622 he->refcounted_he_keylen = keylen;
3623 Copy(keypv, he->refcounted_he_data + key_offset, keylen, char);
3625 he->refcounted_he_hek = share_hek_flags(keypv, keylen, hash, hekflags);
3628 he->refcounted_he_data[0] = hekflags;
3629 he->refcounted_he_refcnt = 1;
3635 =for apidoc refcounted_he_new_pv
3637 Like L</refcounted_he_new_pvn>, but takes a nul-terminated string instead
3638 of a string/length pair.
3643 struct refcounted_he *
3644 Perl_refcounted_he_new_pv(pTHX_ struct refcounted_he *parent,
3645 const char *key, U32 hash, SV *value, U32 flags)
3647 PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_PV;
3648 return refcounted_he_new_pvn(parent, key, strlen(key), hash, value, flags);
3652 =for apidoc refcounted_he_new_sv
3654 Like L</refcounted_he_new_pvn>, but takes a Perl scalar instead of a
3660 struct refcounted_he *
3661 Perl_refcounted_he_new_sv(pTHX_ struct refcounted_he *parent,
3662 SV *key, U32 hash, SV *value, U32 flags)
3666 PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_SV;
3667 if (flags & REFCOUNTED_HE_KEY_UTF8)
3668 Perl_croak(aTHX_ "panic: refcounted_he_new_sv bad flags %" UVxf,
3670 keypv = SvPV_const(key, keylen);
3672 flags |= REFCOUNTED_HE_KEY_UTF8;
3673 if (!hash && SvIsCOW_shared_hash(key))
3674 hash = SvSHARED_HASH(key);
3675 return refcounted_he_new_pvn(parent, keypv, keylen, hash, value, flags);
3679 =for apidoc refcounted_he_free
3681 Decrements the reference count of a C<refcounted_he> by one. If the
3682 reference count reaches zero the structure's memory is freed, which
3683 (recursively) causes a reduction of its parent C<refcounted_he>'s
3684 reference count. It is safe to pass a null pointer to this function:
3685 no action occurs in this case.
3691 Perl_refcounted_he_free(pTHX_ struct refcounted_he *he) {
3692 PERL_UNUSED_CONTEXT;
3695 struct refcounted_he *copy;
3699 new_count = --he->refcounted_he_refcnt;
3700 HINTS_REFCNT_UNLOCK;
3706 #ifndef USE_ITHREADS
3707 unshare_hek_or_pvn (he->refcounted_he_hek, 0, 0, 0);
3710 he = he->refcounted_he_next;
3711 PerlMemShared_free(copy);
3716 =for apidoc refcounted_he_inc
3718 Increment the reference count of a C<refcounted_he>. The pointer to the
3719 C<refcounted_he> is also returned. It is safe to pass a null pointer
3720 to this function: no action occurs and a null pointer is returned.
3725 struct refcounted_he *
3726 Perl_refcounted_he_inc(pTHX_ struct refcounted_he *he)
3728 PERL_UNUSED_CONTEXT;
3731 he->refcounted_he_refcnt++;
3732 HINTS_REFCNT_UNLOCK;
3738 =for apidoc_section $COP
3739 =for apidoc cop_fetch_label
3741 Returns the label attached to a cop, and stores its length in bytes into
3743 Upon return, C<*flags> will be set to either C<SVf_UTF8> or 0.
3745 Alternatively, use the macro C<L</CopLABEL_len_flags>>;
3746 or if you don't need to know if the label is UTF-8 or not, the macro
3747 C<L</CopLABEL_len>>;
3748 or if you additionally dont need to know the length, C<L</CopLABEL>>.
3753 /* pp_entereval is aware that labels are stored with a key ':' at the top of
3756 Perl_cop_fetch_label(pTHX_ COP *const cop, STRLEN *len, U32 *flags) {
3757 struct refcounted_he *const chain = cop->cop_hints_hash;
3759 PERL_ARGS_ASSERT_COP_FETCH_LABEL;
3760 PERL_UNUSED_CONTEXT;
3765 if (chain->refcounted_he_keylen != 1)
3767 if (*REF_HE_KEY(chain) != ':')
3770 if ((STRLEN)HEK_LEN(chain->refcounted_he_hek) != 1)
3772 if (*HEK_KEY(chain->refcounted_he_hek) != ':')
3775 /* Stop anyone trying to really mess us up by adding their own value for
3777 if ((chain->refcounted_he_data[0] & HVrhek_typemask) != HVrhek_PV
3778 && (chain->refcounted_he_data[0] & HVrhek_typemask) != HVrhek_PV_UTF8)
3782 *len = chain->refcounted_he_val.refcounted_he_u_len;
3784 *flags = ((chain->refcounted_he_data[0] & HVrhek_typemask)
3785 == HVrhek_PV_UTF8) ? SVf_UTF8 : 0;
3787 return chain->refcounted_he_data + 1;
3791 =for apidoc cop_store_label
3793 Save a label into a C<cop_hints_hash>.
3794 You need to set flags to C<SVf_UTF8>
3795 for a UTF-8 label. Any other flag is ignored.
3801 Perl_cop_store_label(pTHX_ COP *const cop, const char *label, STRLEN len,
3805 PERL_ARGS_ASSERT_COP_STORE_LABEL;
3807 if (flags & ~(SVf_UTF8))
3808 Perl_croak(aTHX_ "panic: cop_store_label illegal flag bits 0x%" UVxf,
3810 labelsv = newSVpvn_flags(label, len, SVs_TEMP);
3811 if (flags & SVf_UTF8)
3814 = refcounted_he_new_pvs(cop->cop_hints_hash, ":", labelsv, 0);
3818 =for apidoc_section $HV
3819 =for apidoc hv_assert
3821 Check that a hash is in an internally consistent state.
3829 Perl_hv_assert(pTHX_ HV *hv)
3833 int placeholders = 0;
3836 const I32 riter = HvRITER_get(hv);
3837 HE *eiter = HvEITER_get(hv);
3839 PERL_ARGS_ASSERT_HV_ASSERT;
3841 (void)hv_iterinit(hv);
3843 while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
3844 /* sanity check the values */
3845 if (HeVAL(entry) == &PL_sv_placeholder)
3849 /* sanity check the keys */
3850 if (HeSVKEY(entry)) {
3851 NOOP; /* Don't know what to check on SV keys. */
3852 } else if (HeKUTF8(entry)) {
3854 if (HeKWASUTF8(entry)) {
3855 PerlIO_printf(Perl_debug_log,
3856 "hash key has both WASUTF8 and UTF8: '%.*s'\n",
3857 (int) HeKLEN(entry), HeKEY(entry));
3860 } else if (HeKWASUTF8(entry))
3863 if (!SvTIED_mg((const SV *)hv, PERL_MAGIC_tied)) {
3864 static const char bad_count[] = "Count %d %s(s), but hash reports %d\n";
3865 const int nhashkeys = HvUSEDKEYS(hv);
3866 const int nhashplaceholders = HvPLACEHOLDERS_get(hv);
3868 if (nhashkeys != real) {
3869 PerlIO_printf(Perl_debug_log, bad_count, real, "keys", nhashkeys );
3872 if (nhashplaceholders != placeholders) {
3873 PerlIO_printf(Perl_debug_log, bad_count, placeholders, "placeholder", nhashplaceholders );
3877 if (withflags && ! HvHASKFLAGS(hv)) {
3878 PerlIO_printf(Perl_debug_log,
3879 "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
3884 sv_dump(MUTABLE_SV(hv));
3886 HvRITER_set(hv, riter); /* Restore hash iterator state */
3887 HvEITER_set(hv, eiter);
3893 * ex: set ts=8 sts=4 sw=4 et: