3 * Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4 * 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
12 * I sit beside the fire and think
13 * of all that I have seen.
16 * [p.278 of _The Lord of the Rings_, II/iii: "The Ring Goes South"]
20 =head1 Hash Manipulation Functions
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 #define DO_HSPLIT(xhv) ((xhv)->xhv_keys > (xhv)->xhv_max) /* HvTOTALKEYS(hv) > HvMAX(hv) */
38 #define HV_FILL_THRESHOLD 31
40 static const char S_strtab_error[]
41 = "Cannot modify shared string table in hv_%s";
45 #define new_HE() (HE*)safemalloc(sizeof(HE))
46 #define del_HE(p) safefree((char*)p)
54 void ** const root = &PL_body_roots[HE_SVSLOT];
57 Perl_more_bodies(aTHX_ HE_SVSLOT, sizeof(HE), PERL_ARENA_SIZE);
64 #define new_HE() new_he()
67 HeNEXT(p) = (HE*)(PL_body_roots[HE_SVSLOT]); \
68 PL_body_roots[HE_SVSLOT] = p; \
76 S_save_hek_flags(const char *str, I32 len, U32 hash, int flags)
78 const int flags_masked = flags & HVhek_MASK;
82 PERL_ARGS_ASSERT_SAVE_HEK_FLAGS;
84 Newx(k, HEK_BASESIZE + len + 2, char);
86 Copy(str, HEK_KEY(hek), len, char);
87 HEK_KEY(hek)[len] = 0;
90 HEK_FLAGS(hek) = (unsigned char)flags_masked | HVhek_UNSHARED;
92 if (flags & HVhek_FREEKEY)
97 /* free the pool of temporary HE/HEK pairs returned by hv_fetch_ent
101 Perl_free_tied_hv_pool(pTHX)
103 HE *he = PL_hv_fetch_ent_mh;
106 Safefree(HeKEY_hek(he));
110 PL_hv_fetch_ent_mh = NULL;
113 #if defined(USE_ITHREADS)
115 Perl_hek_dup(pTHX_ HEK *source, CLONE_PARAMS* param)
119 PERL_ARGS_ASSERT_HEK_DUP;
120 PERL_UNUSED_ARG(param);
125 shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
127 /* We already shared this hash key. */
128 (void)share_hek_hek(shared);
132 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
133 HEK_HASH(source), HEK_FLAGS(source));
134 ptr_table_store(PL_ptr_table, source, shared);
140 Perl_he_dup(pTHX_ const HE *e, bool shared, CLONE_PARAMS* param)
144 PERL_ARGS_ASSERT_HE_DUP;
148 /* look for it in the table first */
149 ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
153 /* create anew and remember what it is */
155 ptr_table_store(PL_ptr_table, e, ret);
157 HeNEXT(ret) = he_dup(HeNEXT(e),shared, param);
158 if (HeKLEN(e) == HEf_SVKEY) {
160 Newx(k, HEK_BASESIZE + sizeof(const SV *), char);
161 HeKEY_hek(ret) = (HEK*)k;
162 HeKEY_sv(ret) = sv_dup_inc(HeKEY_sv(e), param);
165 /* This is hek_dup inlined, which seems to be important for speed
167 HEK * const source = HeKEY_hek(e);
168 HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
171 /* We already shared this hash key. */
172 (void)share_hek_hek(shared);
176 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
177 HEK_HASH(source), HEK_FLAGS(source));
178 ptr_table_store(PL_ptr_table, source, shared);
180 HeKEY_hek(ret) = shared;
183 HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
185 HeVAL(ret) = sv_dup_inc(HeVAL(e), param);
188 #endif /* USE_ITHREADS */
191 S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
194 SV * const sv = sv_newmortal();
196 PERL_ARGS_ASSERT_HV_NOTALLOWED;
198 if (!(flags & HVhek_FREEKEY)) {
199 sv_setpvn(sv, key, klen);
202 /* Need to free saved eventually assign to mortal SV */
203 /* XXX is this line an error ???: SV *sv = sv_newmortal(); */
204 sv_usepvn(sv, (char *) key, klen);
206 if (flags & HVhek_UTF8) {
209 Perl_croak(aTHX_ msg, SVfARG(sv));
212 /* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
218 Stores an SV in a hash. The hash key is specified as C<key> and the
219 absolute value of C<klen> is the length of the key. If C<klen> is
220 negative the key is assumed to be in UTF-8-encoded Unicode. The
221 C<hash> parameter is the precomputed hash value; if it is zero then
222 Perl will compute it.
224 The return value will be
225 C<NULL> if the operation failed or if the value did not need to be actually
226 stored within the hash (as in the case of tied hashes). Otherwise it can
227 be dereferenced to get the original C<SV*>. Note that the caller is
228 responsible for suitably incrementing the reference count of C<val> before
229 the call, and decrementing it if the function returned C<NULL>. Effectively
230 a successful C<hv_store> takes ownership of one reference to C<val>. This is
231 usually what you want; a newly created SV has a reference count of one, so
232 if all your code does is create SVs then store them in a hash, C<hv_store>
233 will own the only reference to the new SV, and your code doesn't need to do
234 anything further to tidy up. C<hv_store> is not implemented as a call to
235 C<hv_store_ent>, and does not create a temporary SV for the key, so if your
236 key data is not already in SV form then use C<hv_store> in preference to
239 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
240 information on how to use this function on tied hashes.
242 =for apidoc hv_store_ent
244 Stores C<val> in a hash. The hash key is specified as C<key>. The C<hash>
245 parameter is the precomputed hash value; if it is zero then Perl will
246 compute it. The return value is the new hash entry so created. It will be
247 C<NULL> if the operation failed or if the value did not need to be actually
248 stored within the hash (as in the case of tied hashes). Otherwise the
249 contents of the return value can be accessed using the C<He?> macros
250 described here. Note that the caller is responsible for suitably
251 incrementing the reference count of C<val> before the call, and
252 decrementing it if the function returned NULL. Effectively a successful
253 C<hv_store_ent> takes ownership of one reference to C<val>. This is
254 usually what you want; a newly created SV has a reference count of one, so
255 if all your code does is create SVs then store them in a hash, C<hv_store>
256 will own the only reference to the new SV, and your code doesn't need to do
257 anything further to tidy up. Note that C<hv_store_ent> only reads the C<key>;
258 unlike C<val> it does not take ownership of it, so maintaining the correct
259 reference count on C<key> is entirely the caller's responsibility. C<hv_store>
260 is not implemented as a call to C<hv_store_ent>, and does not create a temporary
261 SV for the key, so if your key data is not already in SV form then use
262 C<hv_store> in preference to C<hv_store_ent>.
264 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
265 information on how to use this function on tied hashes.
267 =for apidoc hv_exists
269 Returns a boolean indicating whether the specified hash key exists. The
270 absolute value of C<klen> is the length of the key. If C<klen> is
271 negative the key is assumed to be in UTF-8-encoded Unicode.
275 Returns the SV which corresponds to the specified key in the hash.
276 The absolute value of C<klen> is the length of the key. If C<klen> is
277 negative the key is assumed to be in UTF-8-encoded Unicode. If
278 C<lval> is set then the fetch will be part of a store. This means that if
279 there is no value in the hash associated with the given key, then one is
280 created and a pointer to it is returned. The C<SV*> it points to can be
281 assigned to. But always check that the
282 return value is non-null before dereferencing it to an C<SV*>.
284 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
285 information on how to use this function on tied hashes.
287 =for apidoc hv_exists_ent
289 Returns a boolean indicating whether
290 the specified hash key exists. C<hash>
291 can be a valid precomputed hash value, or 0 to ask for it to be
297 /* returns an HE * structure with the all fields set */
298 /* note that hent_val will be a mortal sv for MAGICAL hashes */
300 =for apidoc hv_fetch_ent
302 Returns the hash entry which corresponds to the specified key in the hash.
303 C<hash> must be a valid precomputed hash number for the given C<key>, or 0
304 if you want the function to compute it. IF C<lval> is set then the fetch
305 will be part of a store. Make sure the return value is non-null before
306 accessing it. The return value when C<hv> is a tied hash is a pointer to a
307 static location, so be sure to make a copy of the structure if you need to
310 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
311 information on how to use this function on tied hashes.
316 /* Common code for hv_delete()/hv_exists()/hv_fetch()/hv_store() */
318 Perl_hv_common_key_len(pTHX_ HV *hv, const char *key, I32 klen_i32,
319 const int action, SV *val, const U32 hash)
324 PERL_ARGS_ASSERT_HV_COMMON_KEY_LEN;
333 return hv_common(hv, NULL, key, klen, flags, action, val, hash);
337 Perl_hv_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
338 int flags, int action, SV *val, U32 hash)
347 const int return_svp = action & HV_FETCH_JUST_SV;
348 HEK *keysv_hek = NULL;
352 if (SvTYPE(hv) == (svtype)SVTYPEMASK)
355 assert(SvTYPE(hv) == SVt_PVHV);
357 if (SvSMAGICAL(hv) && SvGMAGICAL(hv) && !(action & HV_DISABLE_UVAR_XKEY)) {
359 if ((mg = mg_find((const SV *)hv, PERL_MAGIC_uvar))) {
360 struct ufuncs * const uf = (struct ufuncs *)mg->mg_ptr;
361 if (uf->uf_set == NULL) {
362 SV* obj = mg->mg_obj;
365 keysv = newSVpvn_flags(key, klen, SVs_TEMP |
366 ((flags & HVhek_UTF8)
370 mg->mg_obj = keysv; /* pass key */
371 uf->uf_index = action; /* pass action */
372 magic_getuvar(MUTABLE_SV(hv), mg);
373 keysv = mg->mg_obj; /* may have changed */
376 /* If the key may have changed, then we need to invalidate
377 any passed-in computed hash value. */
383 if (flags & HVhek_FREEKEY)
385 key = SvPV_const(keysv, klen);
386 is_utf8 = (SvUTF8(keysv) != 0);
387 if (SvIsCOW_shared_hash(keysv)) {
388 flags = HVhek_KEYCANONICAL | (is_utf8 ? HVhek_UTF8 : 0);
390 flags = is_utf8 ? HVhek_UTF8 : 0;
393 is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
396 if (action & HV_DELETE) {
397 return (void *) hv_delete_common(hv, keysv, key, klen,
398 flags, action, hash);
401 xhv = (XPVHV*)SvANY(hv);
403 if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS))) {
404 if (mg_find((const SV *)hv, PERL_MAGIC_tied)
405 || SvGMAGICAL((const SV *)hv))
407 /* FIXME should be able to skimp on the HE/HEK here when
408 HV_FETCH_JUST_SV is true. */
410 keysv = newSVpvn_utf8(key, klen, is_utf8);
412 keysv = newSVsv(keysv);
415 mg_copy(MUTABLE_SV(hv), sv, (char *)keysv, HEf_SVKEY);
417 /* grab a fake HE/HEK pair from the pool or make a new one */
418 entry = PL_hv_fetch_ent_mh;
420 PL_hv_fetch_ent_mh = HeNEXT(entry);
424 Newx(k, HEK_BASESIZE + sizeof(const SV *), char);
425 HeKEY_hek(entry) = (HEK*)k;
427 HeNEXT(entry) = NULL;
428 HeSVKEY_set(entry, keysv);
430 sv_upgrade(sv, SVt_PVLV);
432 /* so we can free entry when freeing sv */
433 LvTARG(sv) = MUTABLE_SV(entry);
435 /* XXX remove at some point? */
436 if (flags & HVhek_FREEKEY)
440 return entry ? (void *) &HeVAL(entry) : NULL;
442 return (void *) entry;
444 #ifdef ENV_IS_CASELESS
445 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
447 for (i = 0; i < klen; ++i)
448 if (isLOWER(key[i])) {
449 /* Would be nice if we had a routine to do the
450 copy and upercase in a single pass through. */
451 const char * const nkey = strupr(savepvn(key,klen));
452 /* Note that this fetch is for nkey (the uppercased
453 key) whereas the store is for key (the original) */
454 void *result = hv_common(hv, NULL, nkey, klen,
455 HVhek_FREEKEY, /* free nkey */
456 0 /* non-LVAL fetch */
457 | HV_DISABLE_UVAR_XKEY
460 0 /* compute hash */);
461 if (!result && (action & HV_FETCH_LVALUE)) {
462 /* This call will free key if necessary.
463 Do it this way to encourage compiler to tail
465 result = hv_common(hv, keysv, key, klen, flags,
467 | HV_DISABLE_UVAR_XKEY
471 if (flags & HVhek_FREEKEY)
479 else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
480 if (mg_find((const SV *)hv, PERL_MAGIC_tied)
481 || SvGMAGICAL((const SV *)hv)) {
482 /* I don't understand why hv_exists_ent has svret and sv,
483 whereas hv_exists only had one. */
484 SV * const svret = sv_newmortal();
487 if (keysv || is_utf8) {
489 keysv = newSVpvn_utf8(key, klen, TRUE);
491 keysv = newSVsv(keysv);
493 mg_copy(MUTABLE_SV(hv), sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
495 mg_copy(MUTABLE_SV(hv), sv, key, klen);
497 if (flags & HVhek_FREEKEY)
500 MAGIC * const mg = mg_find(sv, PERL_MAGIC_tiedelem);
502 magic_existspack(svret, mg);
504 /* This cast somewhat evil, but I'm merely using NULL/
505 not NULL to return the boolean exists.
506 And I know hv is not NULL. */
507 return SvTRUE(svret) ? (void *)hv : NULL;
509 #ifdef ENV_IS_CASELESS
510 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
511 /* XXX This code isn't UTF8 clean. */
512 char * const keysave = (char * const)key;
513 /* Will need to free this, so set FREEKEY flag. */
514 key = savepvn(key,klen);
515 key = (const char*)strupr((char*)key);
520 if (flags & HVhek_FREEKEY) {
523 flags |= HVhek_FREEKEY;
527 else if (action & HV_FETCH_ISSTORE) {
530 hv_magic_check (hv, &needs_copy, &needs_store);
532 const bool save_taint = TAINT_get;
533 if (keysv || is_utf8) {
535 keysv = newSVpvn_utf8(key, klen, TRUE);
538 TAINT_set(SvTAINTED(keysv));
539 keysv = sv_2mortal(newSVsv(keysv));
540 mg_copy(MUTABLE_SV(hv), val, (char*)keysv, HEf_SVKEY);
542 mg_copy(MUTABLE_SV(hv), val, key, klen);
545 TAINT_IF(save_taint);
546 #ifdef NO_TAINT_SUPPORT
547 PERL_UNUSED_VAR(save_taint);
550 if (flags & HVhek_FREEKEY)
554 #ifdef ENV_IS_CASELESS
555 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
556 /* XXX This code isn't UTF8 clean. */
557 const char *keysave = key;
558 /* Will need to free this, so set FREEKEY flag. */
559 key = savepvn(key,klen);
560 key = (const char*)strupr((char*)key);
565 if (flags & HVhek_FREEKEY) {
568 flags |= HVhek_FREEKEY;
576 if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
577 #ifdef DYNAMIC_ENV_FETCH /* if it's an %ENV lookup, we may get it on the fly */
578 || (SvRMAGICAL((const SV *)hv)
579 && mg_find((const SV *)hv, PERL_MAGIC_env))
584 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
586 HvARRAY(hv) = (HE**)array;
588 #ifdef DYNAMIC_ENV_FETCH
589 else if (action & HV_FETCH_ISEXISTS) {
590 /* for an %ENV exists, if we do an insert it's by a recursive
591 store call, so avoid creating HvARRAY(hv) right now. */
595 /* XXX remove at some point? */
596 if (flags & HVhek_FREEKEY)
603 if (is_utf8 && !(flags & HVhek_KEYCANONICAL)) {
604 char * const keysave = (char *)key;
605 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
609 flags &= ~HVhek_UTF8;
610 if (key != keysave) {
611 if (flags & HVhek_FREEKEY)
613 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
614 /* If the caller calculated a hash, it was on the sequence of
615 octets that are the UTF-8 form. We've now changed the sequence
616 of octets stored to that of the equivalent byte representation,
617 so the hash we need is different. */
622 if (keysv && (SvIsCOW_shared_hash(keysv))) {
624 keysv_hek = SvSHARED_HEK_FROM_PV(SvPVX_const(keysv));
625 hash = SvSHARED_HASH(keysv);
628 PERL_HASH(hash, key, klen);
630 masked_flags = (flags & HVhek_MASK);
632 #ifdef DYNAMIC_ENV_FETCH
633 if (!HvARRAY(hv)) entry = NULL;
637 entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
644 /* keysv is actually a HEK in disguise, so we can match just by
645 * comparing the HEK pointers in the HE chain. There is a slight
646 * caveat: on something like "\x80", which has both plain and utf8
647 * representations, perl's hashes do encoding-insensitive lookups,
648 * but preserve the encoding of the stored key. Thus a particular
649 * key could map to two different HEKs in PL_strtab. We only
650 * conclude 'not found' if all the flags are the same; otherwise
651 * we fall back to a full search (this should only happen in rare
654 int keysv_flags = HEK_FLAGS(keysv_hek);
655 HE *orig_entry = entry;
657 for (; entry; entry = HeNEXT(entry)) {
658 HEK *hek = HeKEY_hek(entry);
659 if (hek == keysv_hek)
661 if (HEK_FLAGS(hek) != keysv_flags)
662 break; /* need to do full match */
666 /* failed on shortcut - do full search loop */
670 for (; entry; entry = HeNEXT(entry)) {
671 if (HeHASH(entry) != hash) /* strings can't be equal */
673 if (HeKLEN(entry) != (I32)klen)
675 if (memNE(HeKEY(entry),key,klen)) /* is this it? */
677 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
681 if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
682 if (HeKFLAGS(entry) != masked_flags) {
683 /* We match if HVhek_UTF8 bit in our flags and hash key's
684 match. But if entry was set previously with HVhek_WASUTF8
685 and key now doesn't (or vice versa) then we should change
686 the key's flag, as this is assignment. */
687 if (HvSHAREKEYS(hv)) {
688 /* Need to swap the key we have for a key with the flags we
689 need. As keys are shared we can't just write to the
690 flag, so we share the new one, unshare the old one. */
691 HEK * const new_hek = share_hek_flags(key, klen, hash,
693 unshare_hek (HeKEY_hek(entry));
694 HeKEY_hek(entry) = new_hek;
696 else if (hv == PL_strtab) {
697 /* PL_strtab is usually the only hash without HvSHAREKEYS,
698 so putting this test here is cheap */
699 if (flags & HVhek_FREEKEY)
701 Perl_croak(aTHX_ S_strtab_error,
702 action & HV_FETCH_LVALUE ? "fetch" : "store");
705 HeKFLAGS(entry) = masked_flags;
706 if (masked_flags & HVhek_ENABLEHVKFLAGS)
709 if (HeVAL(entry) == &PL_sv_placeholder) {
710 /* yes, can store into placeholder slot */
711 if (action & HV_FETCH_LVALUE) {
713 /* This preserves behaviour with the old hv_fetch
714 implementation which at this point would bail out
715 with a break; (at "if we find a placeholder, we
716 pretend we haven't found anything")
718 That break mean that if a placeholder were found, it
719 caused a call into hv_store, which in turn would
720 check magic, and if there is no magic end up pretty
721 much back at this point (in hv_store's code). */
724 /* LVAL fetch which actually needs a store. */
726 HvPLACEHOLDERS(hv)--;
729 if (val != &PL_sv_placeholder)
730 HvPLACEHOLDERS(hv)--;
733 } else if (action & HV_FETCH_ISSTORE) {
734 SvREFCNT_dec(HeVAL(entry));
737 } else if (HeVAL(entry) == &PL_sv_placeholder) {
738 /* if we find a placeholder, we pretend we haven't found
742 if (flags & HVhek_FREEKEY)
745 return (void *) &HeVAL(entry);
751 #ifdef DYNAMIC_ENV_FETCH /* %ENV lookup? If so, try to fetch the value now */
752 if (!(action & HV_FETCH_ISSTORE)
753 && SvRMAGICAL((const SV *)hv)
754 && mg_find((const SV *)hv, PERL_MAGIC_env)) {
756 const char * const env = PerlEnv_ENVgetenv_len(key,&len);
758 sv = newSVpvn(env,len);
760 return hv_common(hv, keysv, key, klen, flags,
761 HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
767 if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
768 hv_notallowed(flags, key, klen,
769 "Attempt to access disallowed key '%"SVf"' in"
770 " a restricted hash");
772 if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
773 /* Not doing some form of store, so return failure. */
774 if (flags & HVhek_FREEKEY)
778 if (action & HV_FETCH_LVALUE) {
779 val = action & HV_FETCH_EMPTY_HE ? NULL : newSV(0);
781 /* At this point the old hv_fetch code would call to hv_store,
782 which in turn might do some tied magic. So we need to make that
783 magic check happen. */
784 /* gonna assign to this, so it better be there */
785 /* If a fetch-as-store fails on the fetch, then the action is to
786 recurse once into "hv_store". If we didn't do this, then that
787 recursive call would call the key conversion routine again.
788 However, as we replace the original key with the converted
789 key, this would result in a double conversion, which would show
790 up as a bug if the conversion routine is not idempotent.
791 Hence the use of HV_DISABLE_UVAR_XKEY. */
792 return hv_common(hv, keysv, key, klen, flags,
793 HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
795 /* XXX Surely that could leak if the fetch-was-store fails?
796 Just like the hv_fetch. */
800 /* Welcome to hv_store... */
803 /* Not sure if we can get here. I think the only case of oentry being
804 NULL is for %ENV with dynamic env fetch. But that should disappear
805 with magic in the previous code. */
808 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
810 HvARRAY(hv) = (HE**)array;
813 oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
816 /* share_hek_flags will do the free for us. This might be considered
819 HeKEY_hek(entry) = share_hek_flags(key, klen, hash, flags);
820 else if (hv == PL_strtab) {
821 /* PL_strtab is usually the only hash without HvSHAREKEYS, so putting
822 this test here is cheap */
823 if (flags & HVhek_FREEKEY)
825 Perl_croak(aTHX_ S_strtab_error,
826 action & HV_FETCH_LVALUE ? "fetch" : "store");
828 else /* gotta do the real thing */
829 HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
832 #ifdef PERL_HASH_RANDOMIZE_KEYS
833 /* This logic semi-randomizes the insert order in a bucket.
834 * Either we insert into the top, or the slot below the top,
835 * making it harder to see if there is a collision. We also
836 * reset the iterator randomizer if there is one.
838 if ( *oentry && PL_HASH_RAND_BITS_ENABLED) {
840 PL_hash_rand_bits= ROTL_UV(PL_hash_rand_bits,1);
841 if ( PL_hash_rand_bits & 1 ) {
842 HeNEXT(entry) = HeNEXT(*oentry);
843 HeNEXT(*oentry) = entry;
845 HeNEXT(entry) = *oentry;
851 HeNEXT(entry) = *oentry;
854 #ifdef PERL_HASH_RANDOMIZE_KEYS
856 /* Currently this makes various tests warn in annoying ways.
857 * So Silenced for now. - Yves | bogus end of comment =>* /
858 if (HvAUX(hv)->xhv_riter != -1) {
859 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
860 "[TESTING] Inserting into a hash during each() traversal results in undefined behavior"
865 if (PL_HASH_RAND_BITS_ENABLED) {
866 if (PL_HASH_RAND_BITS_ENABLED == 1)
867 PL_hash_rand_bits += (PTRV)entry + 1; /* we don't bother to use ptr_hash here */
868 PL_hash_rand_bits= ROTL_UV(PL_hash_rand_bits,1);
870 HvAUX(hv)->xhv_rand= (U32)PL_hash_rand_bits;
874 if (val == &PL_sv_placeholder)
875 HvPLACEHOLDERS(hv)++;
876 if (masked_flags & HVhek_ENABLEHVKFLAGS)
879 xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
880 if ( DO_HSPLIT(xhv) ) {
881 const STRLEN oldsize = xhv->xhv_max + 1;
882 const U32 items = (U32)HvPLACEHOLDERS_get(hv);
884 if (items /* hash has placeholders */
885 && !SvREADONLY(hv) /* but is not a restricted hash */) {
886 /* If this hash previously was a "restricted hash" and had
887 placeholders, but the "restricted" flag has been turned off,
888 then the placeholders no longer serve any useful purpose.
889 However, they have the downsides of taking up RAM, and adding
890 extra steps when finding used values. It's safe to clear them
891 at this point, even though Storable rebuilds restricted hashes by
892 putting in all the placeholders (first) before turning on the
893 readonly flag, because Storable always pre-splits the hash.
894 If we're lucky, then we may clear sufficient placeholders to
895 avoid needing to split the hash at all. */
896 clear_placeholders(hv, items);
898 hsplit(hv, oldsize, oldsize * 2);
900 hsplit(hv, oldsize, oldsize * 2);
904 return entry ? (void *) &HeVAL(entry) : NULL;
906 return (void *) entry;
910 S_hv_magic_check(HV *hv, bool *needs_copy, bool *needs_store)
912 const MAGIC *mg = SvMAGIC(hv);
914 PERL_ARGS_ASSERT_HV_MAGIC_CHECK;
919 if (isUPPER(mg->mg_type)) {
921 if (mg->mg_type == PERL_MAGIC_tied) {
922 *needs_store = FALSE;
923 return; /* We've set all there is to set. */
926 mg = mg->mg_moremagic;
931 =for apidoc hv_scalar
933 Evaluates the hash in scalar context and returns the result.
935 When the hash is tied dispatches through to the SCALAR method,
936 otherwise returns a mortal SV containing the number of keys
939 Note, prior to 5.25 this function returned what is now
940 returned by the hv_bucket_ratio() function.
946 Perl_hv_scalar(pTHX_ HV *hv)
950 PERL_ARGS_ASSERT_HV_SCALAR;
952 if (SvRMAGICAL(hv)) {
953 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_tied);
955 return magic_scalarpack(hv, mg);
959 sv_setuv(sv, HvUSEDKEYS(hv));
965 =for apidoc hv_bucket_ratio
967 If the hash is tied dispatches through to the SCALAR tied method,
968 otherwise if the hash contains no keys returns 0, otherwise returns
969 a mortal sv containing a string specifying the number of used buckets,
970 followed by a slash, followed by the number of available buckets.
972 This function is expensive, it must scan all of the buckets
973 to determine which are used, and the count is NOT cached.
974 In a large hash this could be a lot of buckets.
980 Perl_hv_bucket_ratio(pTHX_ HV *hv)
984 PERL_ARGS_ASSERT_HV_BUCKET_RATIO;
986 if (SvRMAGICAL(hv)) {
987 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_tied);
989 return magic_scalarpack(hv, mg);
993 if (HvUSEDKEYS((const HV *)hv))
994 Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
995 (long)HvFILL(hv), (long)HvMAX(hv) + 1);
1003 =for apidoc hv_delete
1005 Deletes a key/value pair in the hash. The value's SV is removed from
1006 the hash, made mortal, and returned to the caller. The absolute
1007 value of C<klen> is the length of the key. If C<klen> is negative the
1008 key is assumed to be in UTF-8-encoded Unicode. The C<flags> value
1009 will normally be zero; if set to C<G_DISCARD> then C<NULL> will be returned.
1010 C<NULL> will also be returned if the key is not found.
1012 =for apidoc hv_delete_ent
1014 Deletes a key/value pair in the hash. The value SV is removed from the hash,
1015 made mortal, and returned to the caller. The C<flags> value will normally be
1016 zero; if set to C<G_DISCARD> then C<NULL> will be returned. C<NULL> will also
1017 be returned if the key is not found. C<hash> can be a valid precomputed hash
1018 value, or 0 to ask for it to be computed.
1024 S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
1025 int k_flags, I32 d_flags, U32 hash)
1032 bool is_utf8 = (k_flags & HVhek_UTF8) ? TRUE : FALSE;
1034 HEK *keysv_hek = NULL;
1035 U8 mro_changes = 0; /* 1 = isa; 2 = package moved */
1040 if (SvRMAGICAL(hv)) {
1043 hv_magic_check (hv, &needs_copy, &needs_store);
1047 entry = (HE *) hv_common(hv, keysv, key, klen,
1048 k_flags & ~HVhek_FREEKEY,
1049 HV_FETCH_LVALUE|HV_DISABLE_UVAR_XKEY,
1051 sv = entry ? HeVAL(entry) : NULL;
1053 if (SvMAGICAL(sv)) {
1057 if (mg_find(sv, PERL_MAGIC_tiedelem)) {
1058 /* No longer an element */
1059 sv_unmagic(sv, PERL_MAGIC_tiedelem);
1062 return NULL; /* element cannot be deleted */
1064 #ifdef ENV_IS_CASELESS
1065 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
1066 /* XXX This code isn't UTF8 clean. */
1067 keysv = newSVpvn_flags(key, klen, SVs_TEMP);
1068 if (k_flags & HVhek_FREEKEY) {
1071 key = strupr(SvPVX(keysv));
1080 xhv = (XPVHV*)SvANY(hv);
1084 if (is_utf8 && !(k_flags & HVhek_KEYCANONICAL)) {
1085 const char * const keysave = key;
1086 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
1089 k_flags |= HVhek_UTF8;
1091 k_flags &= ~HVhek_UTF8;
1092 if (key != keysave) {
1093 if (k_flags & HVhek_FREEKEY) {
1094 /* This shouldn't happen if our caller does what we expect,
1095 but strictly the API allows it. */
1098 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
1100 HvHASKFLAGS_on(MUTABLE_SV(hv));
1103 if (keysv && (SvIsCOW_shared_hash(keysv))) {
1104 if (HvSHAREKEYS(hv))
1105 keysv_hek = SvSHARED_HEK_FROM_PV(SvPVX_const(keysv));
1106 hash = SvSHARED_HASH(keysv);
1109 PERL_HASH(hash, key, klen);
1111 masked_flags = (k_flags & HVhek_MASK);
1113 first_entry = oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
1120 /* keysv is actually a HEK in disguise, so we can match just by
1121 * comparing the HEK pointers in the HE chain. There is a slight
1122 * caveat: on something like "\x80", which has both plain and utf8
1123 * representations, perl's hashes do encoding-insensitive lookups,
1124 * but preserve the encoding of the stored key. Thus a particular
1125 * key could map to two different HEKs in PL_strtab. We only
1126 * conclude 'not found' if all the flags are the same; otherwise
1127 * we fall back to a full search (this should only happen in rare
1130 int keysv_flags = HEK_FLAGS(keysv_hek);
1132 for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
1133 HEK *hek = HeKEY_hek(entry);
1134 if (hek == keysv_hek)
1136 if (HEK_FLAGS(hek) != keysv_flags)
1137 break; /* need to do full match */
1141 /* failed on shortcut - do full search loop */
1142 oentry = first_entry;
1146 for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
1147 if (HeHASH(entry) != hash) /* strings can't be equal */
1149 if (HeKLEN(entry) != (I32)klen)
1151 if (memNE(HeKEY(entry),key,klen)) /* is this it? */
1153 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
1157 if (hv == PL_strtab) {
1158 if (k_flags & HVhek_FREEKEY)
1160 Perl_croak(aTHX_ S_strtab_error, "delete");
1163 /* if placeholder is here, it's already been deleted.... */
1164 if (HeVAL(entry) == &PL_sv_placeholder) {
1165 if (k_flags & HVhek_FREEKEY)
1169 if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
1170 hv_notallowed(k_flags, key, klen,
1171 "Attempt to delete readonly key '%"SVf"' from"
1172 " a restricted hash");
1174 if (k_flags & HVhek_FREEKEY)
1177 /* If this is a stash and the key ends with ::, then someone is
1178 * deleting a package.
1180 if (HeVAL(entry) && HvENAME_get(hv)) {
1181 gv = (GV *)HeVAL(entry);
1182 if (keysv) key = SvPV(keysv, klen);
1184 (klen > 1 && key[klen-2] == ':' && key[klen-1] == ':')
1186 (klen == 1 && key[0] == ':')
1188 && (klen != 6 || hv!=PL_defstash || memNE(key,"main::",6))
1189 && SvTYPE(gv) == SVt_PVGV && (stash = GvHV((GV *)gv))
1190 && HvENAME_get(stash)) {
1191 /* A previous version of this code checked that the
1192 * GV was still in the symbol table by fetching the
1193 * GV with its name. That is not necessary (and
1194 * sometimes incorrect), as HvENAME cannot be set
1195 * on hv if it is not in the symtab. */
1197 /* Hang on to it for a bit. */
1198 SvREFCNT_inc_simple_void_NN(
1199 sv_2mortal((SV *)gv)
1202 else if (klen == 3 && strnEQ(key, "ISA", 3) && GvAV(gv)) {
1204 MAGIC *mg = mg_find((SV*)isa, PERL_MAGIC_isa);
1208 if (mg->mg_obj == (SV*)gv) {
1209 /* This is the only stash this ISA was used for.
1210 * The isaelem magic asserts if there's no
1211 * isa magic on the array, so explicitly
1212 * remove the magic on both the array and its
1213 * elements. @ISA shouldn't be /too/ large.
1218 end = svp + AvFILLp(isa)+1;
1221 mg_free_type(*svp, PERL_MAGIC_isaelem);
1224 mg_free_type((SV*)GvAV(gv), PERL_MAGIC_isa);
1227 /* mg_obj is an array of stashes
1228 Note that the array doesn't keep a reference
1229 count on the stashes.
1231 AV *av = (AV*)mg->mg_obj;
1236 assert(SvTYPE(mg->mg_obj) == SVt_PVAV);
1238 /* remove the stash from the magic array */
1239 arrayp = svp = AvARRAY(av);
1240 items = AvFILLp(av) + 1;
1242 assert(*arrayp == (SV *)gv);
1244 /* avoid a double free on the last stash */
1246 /* The magic isn't MGf_REFCOUNTED, so release
1247 * the array manually.
1249 SvREFCNT_dec_NN(av);
1254 if (*svp == (SV*)gv)
1258 index = svp - arrayp;
1259 assert(index >= 0 && index <= AvFILLp(av));
1260 if (index < AvFILLp(av)) {
1261 arrayp[index] = arrayp[AvFILLp(av)];
1263 arrayp[AvFILLp(av)] = NULL;
1271 sv = d_flags & G_DISCARD ? HeVAL(entry) : sv_2mortal(HeVAL(entry));
1272 HeVAL(entry) = &PL_sv_placeholder;
1274 /* deletion of method from stash */
1275 if (isGV(sv) && isGV_with_GP(sv) && GvCVu(sv)
1277 mro_method_changed_in(hv);
1281 * If a restricted hash, rather than really deleting the entry, put
1282 * a placeholder there. This marks the key as being "approved", so
1283 * we can still access via not-really-existing key without raising
1287 /* We'll be saving this slot, so the number of allocated keys
1288 * doesn't go down, but the number placeholders goes up */
1289 HvPLACEHOLDERS(hv)++;
1291 *oentry = HeNEXT(entry);
1292 if (SvOOK(hv) && entry == HvAUX(hv)->xhv_eiter /* HvEITER(hv) */)
1295 if (SvOOK(hv) && HvLAZYDEL(hv) &&
1296 entry == HeNEXT(HvAUX(hv)->xhv_eiter))
1297 HeNEXT(HvAUX(hv)->xhv_eiter) = HeNEXT(entry);
1298 hv_free_ent(hv, entry);
1300 xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
1301 if (xhv->xhv_keys == 0)
1302 HvHASKFLAGS_off(hv);
1305 if (d_flags & G_DISCARD) {
1310 if (mro_changes == 1) mro_isa_changed_in(hv);
1311 else if (mro_changes == 2)
1312 mro_package_moved(NULL, stash, gv, 1);
1318 if (SvREADONLY(hv)) {
1319 hv_notallowed(k_flags, key, klen,
1320 "Attempt to delete disallowed key '%"SVf"' from"
1321 " a restricted hash");
1324 if (k_flags & HVhek_FREEKEY)
1331 S_hsplit(pTHX_ HV *hv, STRLEN const oldsize, STRLEN newsize)
1334 char *a = (char*) HvARRAY(hv);
1338 /* already have an HvAUX(hv) so we have to move it */
1340 /* no HvAUX() but array we are going to allocate is large enough
1341 * there is no point in saving the space for the iterator, and
1342 * speeds up later traversals. */
1343 ( ( hv != PL_strtab ) && ( newsize >= PERL_HV_ALLOC_AUX_SIZE ) )
1346 PERL_ARGS_ASSERT_HSPLIT;
1349 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1350 + (do_aux ? sizeof(struct xpvhv_aux) : 0), char);
1356 #ifdef PERL_HASH_RANDOMIZE_KEYS
1357 /* the idea of this is that we create a "random" value by hashing the address of
1358 * the array, we then use the low bit to decide if we insert at the top, or insert
1359 * second from top. After each such insert we rotate the hashed value. So we can
1360 * use the same hashed value over and over, and in normal build environments use
1361 * very few ops to do so. ROTL32() should produce a single machine operation. */
1362 if (PL_HASH_RAND_BITS_ENABLED) {
1363 if (PL_HASH_RAND_BITS_ENABLED == 1)
1364 PL_hash_rand_bits += ptr_hash((PTRV)a);
1365 PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,1);
1368 HvARRAY(hv) = (HE**) a;
1369 HvMAX(hv) = newsize - 1;
1370 /* before we zero the newly added memory, we
1371 * need to deal with the aux struct that may be there
1372 * or have been allocated by us*/
1374 struct xpvhv_aux *const dest
1375 = (struct xpvhv_aux*) &a[newsize * sizeof(HE*)];
1377 /* alread have an aux, copy the old one in place. */
1378 Move(&a[oldsize * sizeof(HE*)], dest, 1, struct xpvhv_aux);
1379 /* we reset the iterator's xhv_rand as well, so they get a totally new ordering */
1380 #ifdef PERL_HASH_RANDOMIZE_KEYS
1381 dest->xhv_rand = (U32)PL_hash_rand_bits;
1384 /* no existing aux structure, but we allocated space for one
1385 * so initialize it properly. This unrolls hv_auxinit() a bit,
1386 * since we have to do the realloc anyway. */
1387 /* first we set the iterator's xhv_rand so it can be copied into lastrand below */
1388 #ifdef PERL_HASH_RANDOMIZE_KEYS
1389 dest->xhv_rand = (U32)PL_hash_rand_bits;
1391 /* this is the "non realloc" part of the hv_auxinit() */
1392 (void)hv_auxinit_internal(dest);
1393 /* Turn on the OOK flag */
1397 /* now we can safely clear the second half */
1398 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1400 if (!HvTOTALKEYS(hv)) /* skip rest if no entries */
1406 HE **oentry = aep + i;
1409 if (!entry) /* non-existent */
1412 U32 j = (HeHASH(entry) & newsize);
1414 *oentry = HeNEXT(entry);
1415 #ifdef PERL_HASH_RANDOMIZE_KEYS
1416 /* if the target cell is empty or PL_HASH_RAND_BITS_ENABLED is false
1417 * insert to top, otherwise rotate the bucket rand 1 bit,
1418 * and use the new low bit to decide if we insert at top,
1419 * or next from top. IOW, we only rotate on a collision.*/
1420 if (aep[j] && PL_HASH_RAND_BITS_ENABLED) {
1421 PL_hash_rand_bits+= ROTL32(HeHASH(entry), 17);
1422 PL_hash_rand_bits= ROTL_UV(PL_hash_rand_bits,1);
1423 if (PL_hash_rand_bits & 1) {
1424 HeNEXT(entry)= HeNEXT(aep[j]);
1425 HeNEXT(aep[j])= entry;
1427 /* Note, this is structured in such a way as the optimizer
1428 * should eliminate the duplicated code here and below without
1429 * us needing to explicitly use a goto. */
1430 HeNEXT(entry) = aep[j];
1436 /* see comment above about duplicated code */
1437 HeNEXT(entry) = aep[j];
1442 oentry = &HeNEXT(entry);
1446 } while (i++ < oldsize);
1450 Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
1452 XPVHV* xhv = (XPVHV*)SvANY(hv);
1453 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1457 PERL_ARGS_ASSERT_HV_KSPLIT;
1459 newsize = (I32) newmax; /* possible truncation here */
1460 if (newsize != newmax || newmax <= oldsize)
1462 while ((newsize & (1 + ~newsize)) != newsize) {
1463 newsize &= ~(newsize & (1 + ~newsize)); /* get proper power of 2 */
1465 if (newsize < newmax)
1467 if (newsize < newmax)
1468 return; /* overflow detection */
1470 a = (char *) HvARRAY(hv);
1472 hsplit(hv, oldsize, newsize);
1474 Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1475 xhv->xhv_max = --newsize;
1476 HvARRAY(hv) = (HE **) a;
1480 /* IMO this should also handle cases where hv_max is smaller than hv_keys
1481 * as tied hashes could play silly buggers and mess us around. We will
1482 * do the right thing during hv_store() afterwards, but still - Yves */
1483 #define HV_SET_MAX_ADJUSTED_FOR_KEYS(hv,hv_max,hv_keys) STMT_START {\
1484 /* Can we use fewer buckets? (hv_max is always 2^n-1) */ \
1485 if (hv_max < PERL_HASH_DEFAULT_HvMAX) { \
1486 hv_max = PERL_HASH_DEFAULT_HvMAX; \
1488 while (hv_max > PERL_HASH_DEFAULT_HvMAX && hv_max + 1 >= hv_keys * 2) \
1489 hv_max = hv_max / 2; \
1491 HvMAX(hv) = hv_max; \
1496 Perl_newHVhv(pTHX_ HV *ohv)
1499 HV * const hv = newHV();
1502 if (!ohv || (!HvTOTALKEYS(ohv) && !SvMAGICAL((const SV *)ohv)))
1504 hv_max = HvMAX(ohv);
1506 if (!SvMAGICAL((const SV *)ohv)) {
1507 /* It's an ordinary hash, so copy it fast. AMS 20010804 */
1509 const bool shared = !!HvSHAREKEYS(ohv);
1510 HE **ents, ** const oents = (HE **)HvARRAY(ohv);
1512 Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
1515 /* In each bucket... */
1516 for (i = 0; i <= hv_max; i++) {
1518 HE *oent = oents[i];
1525 /* Copy the linked list of entries. */
1526 for (; oent; oent = HeNEXT(oent)) {
1527 const U32 hash = HeHASH(oent);
1528 const char * const key = HeKEY(oent);
1529 const STRLEN len = HeKLEN(oent);
1530 const int flags = HeKFLAGS(oent);
1531 HE * const ent = new_HE();
1532 SV *const val = HeVAL(oent);
1534 HeVAL(ent) = SvIMMORTAL(val) ? val : newSVsv(val);
1536 = shared ? share_hek_flags(key, len, hash, flags)
1537 : save_hek_flags(key, len, hash, flags);
1548 HvTOTALKEYS(hv) = HvTOTALKEYS(ohv);
1552 /* Iterate over ohv, copying keys and values one at a time. */
1554 const I32 riter = HvRITER_get(ohv);
1555 HE * const eiter = HvEITER_get(ohv);
1556 STRLEN hv_keys = HvTOTALKEYS(ohv);
1558 HV_SET_MAX_ADJUSTED_FOR_KEYS(hv,hv_max,hv_keys);
1561 while ((entry = hv_iternext_flags(ohv, 0))) {
1562 SV *val = hv_iterval(ohv,entry);
1563 SV * const keysv = HeSVKEY(entry);
1564 val = SvIMMORTAL(val) ? val : newSVsv(val);
1566 (void)hv_store_ent(hv, keysv, val, 0);
1568 (void)hv_store_flags(hv, HeKEY(entry), HeKLEN(entry), val,
1569 HeHASH(entry), HeKFLAGS(entry));
1571 HvRITER_set(ohv, riter);
1572 HvEITER_set(ohv, eiter);
1579 =for apidoc Am|HV *|hv_copy_hints_hv|HV *ohv
1581 A specialised version of L</newHVhv> for copying C<%^H>. C<ohv> must be
1582 a pointer to a hash (which may have C<%^H> magic, but should be generally
1583 non-magical), or C<NULL> (interpreted as an empty hash). The content
1584 of C<ohv> is copied to a new hash, which has the C<%^H>-specific magic
1585 added to it. A pointer to the new hash is returned.
1591 Perl_hv_copy_hints_hv(pTHX_ HV *const ohv)
1593 HV * const hv = newHV();
1596 STRLEN hv_max = HvMAX(ohv);
1597 STRLEN hv_keys = HvTOTALKEYS(ohv);
1599 const I32 riter = HvRITER_get(ohv);
1600 HE * const eiter = HvEITER_get(ohv);
1605 HV_SET_MAX_ADJUSTED_FOR_KEYS(hv,hv_max,hv_keys);
1608 while ((entry = hv_iternext_flags(ohv, 0))) {
1609 SV *const sv = newSVsv(hv_iterval(ohv,entry));
1610 SV *heksv = HeSVKEY(entry);
1611 if (!heksv && sv) heksv = newSVhek(HeKEY_hek(entry));
1612 if (sv) sv_magic(sv, NULL, PERL_MAGIC_hintselem,
1613 (char *)heksv, HEf_SVKEY);
1614 if (heksv == HeSVKEY(entry))
1615 (void)hv_store_ent(hv, heksv, sv, 0);
1617 (void)hv_common(hv, heksv, HeKEY(entry), HeKLEN(entry),
1618 HeKFLAGS(entry), HV_FETCH_ISSTORE|HV_FETCH_JUST_SV, sv, HeHASH(entry));
1619 SvREFCNT_dec_NN(heksv);
1622 HvRITER_set(ohv, riter);
1623 HvEITER_set(ohv, eiter);
1625 SvREFCNT_inc_simple_void_NN(hv);
1628 hv_magic(hv, NULL, PERL_MAGIC_hints);
1631 #undef HV_SET_MAX_ADJUSTED_FOR_KEYS
1633 /* like hv_free_ent, but returns the SV rather than freeing it */
1635 S_hv_free_ent_ret(pTHX_ HV *hv, HE *entry)
1639 PERL_ARGS_ASSERT_HV_FREE_ENT_RET;
1642 if (HeKLEN(entry) == HEf_SVKEY) {
1643 SvREFCNT_dec(HeKEY_sv(entry));
1644 Safefree(HeKEY_hek(entry));
1646 else if (HvSHAREKEYS(hv))
1647 unshare_hek(HeKEY_hek(entry));
1649 Safefree(HeKEY_hek(entry));
1656 Perl_hv_free_ent(pTHX_ HV *hv, HE *entry)
1660 PERL_ARGS_ASSERT_HV_FREE_ENT;
1664 val = hv_free_ent_ret(hv, entry);
1670 Perl_hv_delayfree_ent(pTHX_ HV *hv, HE *entry)
1672 PERL_ARGS_ASSERT_HV_DELAYFREE_ENT;
1676 /* SvREFCNT_inc to counter the SvREFCNT_dec in hv_free_ent */
1677 sv_2mortal(SvREFCNT_inc(HeVAL(entry))); /* free between statements */
1678 if (HeKLEN(entry) == HEf_SVKEY) {
1679 sv_2mortal(SvREFCNT_inc(HeKEY_sv(entry)));
1681 hv_free_ent(hv, entry);
1685 =for apidoc hv_clear
1687 Frees the all the elements of a hash, leaving it empty.
1688 The XS equivalent of C<%hash = ()>. See also L</hv_undef>.
1690 See L</av_clear> for a note about the hash possibly being invalid on
1697 Perl_hv_clear(pTHX_ HV *hv)
1704 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1706 xhv = (XPVHV*)SvANY(hv);
1709 SAVEFREESV(SvREFCNT_inc_simple_NN(hv));
1710 if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
1711 /* restricted hash: convert all keys to placeholders */
1713 for (i = 0; i <= xhv->xhv_max; i++) {
1714 HE *entry = (HvARRAY(hv))[i];
1715 for (; entry; entry = HeNEXT(entry)) {
1716 /* not already placeholder */
1717 if (HeVAL(entry) != &PL_sv_placeholder) {
1719 if (SvREADONLY(HeVAL(entry))) {
1720 SV* const keysv = hv_iterkeysv(entry);
1721 Perl_croak_nocontext(
1722 "Attempt to delete readonly key '%"SVf"' from a restricted hash",
1725 SvREFCNT_dec_NN(HeVAL(entry));
1727 HeVAL(entry) = &PL_sv_placeholder;
1728 HvPLACEHOLDERS(hv)++;
1735 HvPLACEHOLDERS_set(hv, 0);
1738 mg_clear(MUTABLE_SV(hv));
1740 HvHASKFLAGS_off(hv);
1744 mro_isa_changed_in(hv);
1745 HvEITER_set(hv, NULL);
1751 =for apidoc hv_clear_placeholders
1753 Clears any placeholders from a hash. If a restricted hash has any of its keys
1754 marked as readonly and the key is subsequently deleted, the key is not actually
1755 deleted but is marked by assigning it a value of C<&PL_sv_placeholder>. This tags
1756 it so it will be ignored by future operations such as iterating over the hash,
1757 but will still allow the hash to have a value reassigned to the key at some
1758 future point. This function clears any such placeholder keys from the hash.
1759 See C<L<Hash::Util::lock_keys()|Hash::Util/lock_keys>> for an example of its
1766 Perl_hv_clear_placeholders(pTHX_ HV *hv)
1768 const U32 items = (U32)HvPLACEHOLDERS_get(hv);
1770 PERL_ARGS_ASSERT_HV_CLEAR_PLACEHOLDERS;
1773 clear_placeholders(hv, items);
1777 S_clear_placeholders(pTHX_ HV *hv, U32 items)
1782 PERL_ARGS_ASSERT_CLEAR_PLACEHOLDERS;
1789 /* Loop down the linked list heads */
1790 HE **oentry = &(HvARRAY(hv))[i];
1793 while ((entry = *oentry)) {
1794 if (HeVAL(entry) == &PL_sv_placeholder) {
1795 *oentry = HeNEXT(entry);
1796 if (entry == HvEITER_get(hv))
1799 if (SvOOK(hv) && HvLAZYDEL(hv) &&
1800 entry == HeNEXT(HvAUX(hv)->xhv_eiter))
1801 HeNEXT(HvAUX(hv)->xhv_eiter) = HeNEXT(entry);
1802 hv_free_ent(hv, entry);
1807 I32 placeholders = HvPLACEHOLDERS_get(hv);
1808 HvTOTALKEYS(hv) -= (IV)placeholders;
1809 /* HvUSEDKEYS expanded */
1810 if ((HvTOTALKEYS(hv) - placeholders) == 0)
1811 HvHASKFLAGS_off(hv);
1812 HvPLACEHOLDERS_set(hv, 0);
1816 oentry = &HeNEXT(entry);
1820 /* You can't get here, hence assertion should always fail. */
1821 assert (items == 0);
1822 NOT_REACHED; /* NOTREACHED */
1826 S_hfreeentries(pTHX_ HV *hv)
1829 XPVHV * const xhv = (XPVHV*)SvANY(hv);
1832 PERL_ARGS_ASSERT_HFREEENTRIES;
1834 while ((sv = Perl_hfree_next_entry(aTHX_ hv, &index))||xhv->xhv_keys) {
1840 /* hfree_next_entry()
1841 * For use only by S_hfreeentries() and sv_clear().
1842 * Delete the next available HE from hv and return the associated SV.
1843 * Returns null on empty hash. Nevertheless null is not a reliable
1844 * indicator that the hash is empty, as the deleted entry may have a
1846 * indexp is a pointer to the current index into HvARRAY. The index should
1847 * initially be set to 0. hfree_next_entry() may update it. */
1850 Perl_hfree_next_entry(pTHX_ HV *hv, STRLEN *indexp)
1852 struct xpvhv_aux *iter;
1856 STRLEN orig_index = *indexp;
1859 PERL_ARGS_ASSERT_HFREE_NEXT_ENTRY;
1861 if (SvOOK(hv) && ((iter = HvAUX(hv)))) {
1862 if ((entry = iter->xhv_eiter)) {
1863 /* the iterator may get resurrected after each
1864 * destructor call, so check each time */
1865 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1867 hv_free_ent(hv, entry);
1868 /* warning: at this point HvARRAY may have been
1869 * re-allocated, HvMAX changed etc */
1871 iter = HvAUX(hv); /* may have been realloced */
1872 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1873 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
1874 #ifdef PERL_HASH_RANDOMIZE_KEYS
1875 iter->xhv_last_rand = iter->xhv_rand;
1880 if (!((XPVHV*)SvANY(hv))->xhv_keys)
1883 array = HvARRAY(hv);
1885 while ( ! ((entry = array[*indexp])) ) {
1886 if ((*indexp)++ >= HvMAX(hv))
1888 assert(*indexp != orig_index);
1890 array[*indexp] = HeNEXT(entry);
1891 ((XPVHV*) SvANY(hv))->xhv_keys--;
1893 if ( PL_phase != PERL_PHASE_DESTRUCT && HvENAME(hv)
1894 && HeVAL(entry) && isGV(HeVAL(entry))
1895 && GvHV(HeVAL(entry)) && HvENAME(GvHV(HeVAL(entry)))
1898 const char * const key = HePV(entry,klen);
1899 if ((klen > 1 && key[klen-1]==':' && key[klen-2]==':')
1900 || (klen == 1 && key[0] == ':')) {
1902 NULL, GvHV(HeVAL(entry)),
1903 (GV *)HeVAL(entry), 0
1907 return hv_free_ent_ret(hv, entry);
1912 =for apidoc hv_undef
1914 Undefines the hash. The XS equivalent of C<undef(%hash)>.
1916 As well as freeing all the elements of the hash (like C<hv_clear()>), this
1917 also frees any auxiliary data and storage associated with the hash.
1919 See L</av_clear> for a note about the hash possibly being invalid on
1926 Perl_hv_undef_flags(pTHX_ HV *hv, U32 flags)
1933 save = !!SvREFCNT(hv);
1934 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1935 xhv = (XPVHV*)SvANY(hv);
1937 /* The name must be deleted before the call to hfreeeeentries so that
1938 CVs are anonymised properly. But the effective name must be pre-
1939 served until after that call (and only deleted afterwards if the
1940 call originated from sv_clear). For stashes with one name that is
1941 both the canonical name and the effective name, hv_name_set has to
1942 allocate an array for storing the effective name. We can skip that
1943 during global destruction, as it does not matter where the CVs point
1944 if they will be freed anyway. */
1945 /* note that the code following prior to hfreeentries is duplicated
1946 * in sv_clear(), and changes here should be done there too */
1947 if (PL_phase != PERL_PHASE_DESTRUCT && HvNAME(hv)) {
1948 if (PL_stashcache) {
1949 DEBUG_o(Perl_deb(aTHX_ "hv_undef_flags clearing PL_stashcache for '%"
1950 HEKf"'\n", HEKfARG(HvNAME_HEK(hv))));
1951 (void)hv_deletehek(PL_stashcache, HvNAME_HEK(hv), G_DISCARD);
1953 hv_name_set(hv, NULL, 0, 0);
1957 SAVEFREESV(SvREFCNT_inc_simple_NN(hv));
1961 struct mro_meta *meta;
1964 if (HvENAME_get(hv)) {
1965 if (PL_phase != PERL_PHASE_DESTRUCT)
1966 mro_isa_changed_in(hv);
1967 if (PL_stashcache) {
1968 DEBUG_o(Perl_deb(aTHX_ "hv_undef_flags clearing PL_stashcache for effective name '%"
1969 HEKf"'\n", HEKfARG(HvENAME_HEK(hv))));
1970 (void)hv_deletehek(PL_stashcache, HvENAME_HEK(hv), G_DISCARD);
1974 /* If this call originated from sv_clear, then we must check for
1975 * effective names that need freeing, as well as the usual name. */
1977 if (flags & HV_NAME_SETALL ? !!HvAUX(hv)->xhv_name_u.xhvnameu_name : !!name) {
1978 if (name && PL_stashcache) {
1979 DEBUG_o(Perl_deb(aTHX_ "hv_undef_flags clearing PL_stashcache for name '%"
1980 HEKf"'\n", HEKfARG(HvNAME_HEK(hv))));
1981 (void)hv_deletehek(PL_stashcache, HvNAME_HEK(hv), G_DISCARD);
1983 hv_name_set(hv, NULL, 0, flags);
1985 if((meta = HvAUX(hv)->xhv_mro_meta)) {
1986 if (meta->mro_linear_all) {
1987 SvREFCNT_dec_NN(meta->mro_linear_all);
1988 /* mro_linear_current is just acting as a shortcut pointer,
1992 /* Only the current MRO is stored, so this owns the data.
1994 SvREFCNT_dec(meta->mro_linear_current);
1995 SvREFCNT_dec(meta->mro_nextmethod);
1996 SvREFCNT_dec(meta->isa);
1997 SvREFCNT_dec(meta->super);
1999 HvAUX(hv)->xhv_mro_meta = NULL;
2001 if (!HvAUX(hv)->xhv_name_u.xhvnameu_name && ! HvAUX(hv)->xhv_backreferences)
2002 SvFLAGS(hv) &= ~SVf_OOK;
2005 Safefree(HvARRAY(hv));
2006 xhv->xhv_max = PERL_HASH_DEFAULT_HvMAX; /* HvMAX(hv) = 7 (it's a normal hash) */
2009 /* if we're freeing the HV, the SvMAGIC field has been reused for
2010 * other purposes, and so there can't be any placeholder magic */
2012 HvPLACEHOLDERS_set(hv, 0);
2015 mg_clear(MUTABLE_SV(hv));
2022 Returns the number of hash buckets that happen to be in use.
2024 This function is wrapped by the macro C<HvFILL>.
2026 As of perl 5.25 this function is used only for debugging
2027 purposes, and the number of used hash buckets is not
2028 in any way cached, thus this function can be costly
2029 to execute as it must iterate over all the buckets in the
2036 Perl_hv_fill(pTHX_ HV *const hv)
2039 HE **ents = HvARRAY(hv);
2041 PERL_ARGS_ASSERT_HV_FILL;
2043 /* No keys implies no buckets used.
2044 One key can only possibly mean one bucket used. */
2045 if (HvTOTALKEYS(hv) < 2)
2046 return HvTOTALKEYS(hv);
2049 /* I wonder why we count down here...
2050 * Is it some micro-optimisation?
2051 * I would have thought counting up was better.
2054 HE *const *const last = ents + HvMAX(hv);
2055 count = last + 1 - ents;
2060 } while (++ents <= last);
2065 /* hash a pointer to a U32 - Used in the hash traversal randomization
2066 * and bucket order randomization code
2068 * this code was derived from Sereal, which was derived from autobox.
2071 PERL_STATIC_INLINE U32 S_ptr_hash(PTRV u) {
2074 * This is one of Thomas Wang's hash functions for 64-bit integers from:
2075 * http://www.concentric.net/~Ttwang/tech/inthash.htm
2077 u = (~u) + (u << 18);
2085 * This is one of Bob Jenkins' hash functions for 32-bit integers
2086 * from: http://burtleburtle.net/bob/hash/integer.html
2088 u = (u + 0x7ed55d16) + (u << 12);
2089 u = (u ^ 0xc761c23c) ^ (u >> 19);
2090 u = (u + 0x165667b1) + (u << 5);
2091 u = (u + 0xd3a2646c) ^ (u << 9);
2092 u = (u + 0xfd7046c5) + (u << 3);
2093 u = (u ^ 0xb55a4f09) ^ (u >> 16);
2098 static struct xpvhv_aux*
2099 S_hv_auxinit_internal(struct xpvhv_aux *iter) {
2100 PERL_ARGS_ASSERT_HV_AUXINIT_INTERNAL;
2101 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2102 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
2103 #ifdef PERL_HASH_RANDOMIZE_KEYS
2104 iter->xhv_last_rand = iter->xhv_rand;
2106 iter->xhv_name_u.xhvnameu_name = 0;
2107 iter->xhv_name_count = 0;
2108 iter->xhv_backreferences = 0;
2109 iter->xhv_mro_meta = NULL;
2110 iter->xhv_aux_flags = 0;
2115 static struct xpvhv_aux*
2116 S_hv_auxinit(pTHX_ HV *hv) {
2117 struct xpvhv_aux *iter;
2120 PERL_ARGS_ASSERT_HV_AUXINIT;
2124 Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
2125 + sizeof(struct xpvhv_aux), char);
2127 array = (char *) HvARRAY(hv);
2128 Renew(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
2129 + sizeof(struct xpvhv_aux), char);
2131 HvARRAY(hv) = (HE**)array;
2134 #ifdef PERL_HASH_RANDOMIZE_KEYS
2135 if (PL_HASH_RAND_BITS_ENABLED) {
2136 /* mix in some new state to PL_hash_rand_bits to "randomize" the traversal order*/
2137 if (PL_HASH_RAND_BITS_ENABLED == 1)
2138 PL_hash_rand_bits += ptr_hash((PTRV)array);
2139 PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,1);
2141 iter->xhv_rand = (U32)PL_hash_rand_bits;
2147 return hv_auxinit_internal(iter);
2151 =for apidoc hv_iterinit
2153 Prepares a starting point to traverse a hash table. Returns the number of
2154 keys in the hash (i.e. the same as C<HvUSEDKEYS(hv)>). The return value is
2155 currently only meaningful for hashes without tie magic.
2157 NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
2158 hash buckets that happen to be in use. If you still need that esoteric
2159 value, you can get it through the macro C<HvFILL(hv)>.
2166 Perl_hv_iterinit(pTHX_ HV *hv)
2168 PERL_ARGS_ASSERT_HV_ITERINIT;
2171 struct xpvhv_aux * iter = HvAUX(hv);
2172 HE * const entry = iter->xhv_eiter; /* HvEITER(hv) */
2173 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
2175 hv_free_ent(hv, entry);
2177 iter = HvAUX(hv); /* may have been reallocated */
2178 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2179 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
2180 #ifdef PERL_HASH_RANDOMIZE_KEYS
2181 iter->xhv_last_rand = iter->xhv_rand;
2187 /* note this includes placeholders! */
2188 return HvTOTALKEYS(hv);
2192 Perl_hv_riter_p(pTHX_ HV *hv) {
2193 struct xpvhv_aux *iter;
2195 PERL_ARGS_ASSERT_HV_RITER_P;
2197 iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2198 return &(iter->xhv_riter);
2202 Perl_hv_eiter_p(pTHX_ HV *hv) {
2203 struct xpvhv_aux *iter;
2205 PERL_ARGS_ASSERT_HV_EITER_P;
2207 iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2208 return &(iter->xhv_eiter);
2212 Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
2213 struct xpvhv_aux *iter;
2215 PERL_ARGS_ASSERT_HV_RITER_SET;
2223 iter = hv_auxinit(hv);
2225 iter->xhv_riter = riter;
2229 Perl_hv_rand_set(pTHX_ HV *hv, U32 new_xhv_rand) {
2230 struct xpvhv_aux *iter;
2232 PERL_ARGS_ASSERT_HV_RAND_SET;
2234 #ifdef PERL_HASH_RANDOMIZE_KEYS
2238 iter = hv_auxinit(hv);
2240 iter->xhv_rand = new_xhv_rand;
2242 Perl_croak(aTHX_ "This Perl has not been built with support for randomized hash key traversal but something called Perl_hv_rand_set().");
2247 Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
2248 struct xpvhv_aux *iter;
2250 PERL_ARGS_ASSERT_HV_EITER_SET;
2255 /* 0 is the default so don't go malloc()ing a new structure just to
2260 iter = hv_auxinit(hv);
2262 iter->xhv_eiter = eiter;
2266 Perl_hv_name_set(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2269 struct xpvhv_aux *iter;
2273 PERL_ARGS_ASSERT_HV_NAME_SET;
2276 Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
2280 if (iter->xhv_name_u.xhvnameu_name) {
2281 if(iter->xhv_name_count) {
2282 if(flags & HV_NAME_SETALL) {
2283 HEK ** const name = HvAUX(hv)->xhv_name_u.xhvnameu_names;
2284 HEK **hekp = name + (
2285 iter->xhv_name_count < 0
2286 ? -iter->xhv_name_count
2287 : iter->xhv_name_count
2289 while(hekp-- > name+1)
2290 unshare_hek_or_pvn(*hekp, 0, 0, 0);
2291 /* The first elem may be null. */
2292 if(*name) unshare_hek_or_pvn(*name, 0, 0, 0);
2294 iter = HvAUX(hv); /* may been realloced */
2295 spot = &iter->xhv_name_u.xhvnameu_name;
2296 iter->xhv_name_count = 0;
2299 if(iter->xhv_name_count > 0) {
2300 /* shift some things over */
2302 iter->xhv_name_u.xhvnameu_names, iter->xhv_name_count + 1, HEK *
2304 spot = iter->xhv_name_u.xhvnameu_names;
2305 spot[iter->xhv_name_count] = spot[1];
2307 iter->xhv_name_count = -(iter->xhv_name_count + 1);
2309 else if(*(spot = iter->xhv_name_u.xhvnameu_names)) {
2310 unshare_hek_or_pvn(*spot, 0, 0, 0);
2314 else if (flags & HV_NAME_SETALL) {
2315 unshare_hek_or_pvn(iter->xhv_name_u.xhvnameu_name, 0, 0, 0);
2316 iter = HvAUX(hv); /* may been realloced */
2317 spot = &iter->xhv_name_u.xhvnameu_name;
2320 HEK * const existing_name = iter->xhv_name_u.xhvnameu_name;
2321 Newx(iter->xhv_name_u.xhvnameu_names, 2, HEK *);
2322 iter->xhv_name_count = -2;
2323 spot = iter->xhv_name_u.xhvnameu_names;
2324 spot[1] = existing_name;
2327 else { spot = &iter->xhv_name_u.xhvnameu_name; iter->xhv_name_count = 0; }
2332 iter = hv_auxinit(hv);
2333 spot = &iter->xhv_name_u.xhvnameu_name;
2335 PERL_HASH(hash, name, len);
2336 *spot = name ? share_hek(name, flags & SVf_UTF8 ? -(I32)len : (I32)len, hash) : NULL;
2340 This is basically sv_eq_flags() in sv.c, but we avoid the magic
2345 hek_eq_pvn_flags(pTHX_ const HEK *hek, const char* pv, const I32 pvlen, const U32 flags) {
2346 if ( (HEK_UTF8(hek) ? 1 : 0) != (flags & SVf_UTF8 ? 1 : 0) ) {
2347 if (flags & SVf_UTF8)
2348 return (bytes_cmp_utf8(
2349 (const U8*)HEK_KEY(hek), HEK_LEN(hek),
2350 (const U8*)pv, pvlen) == 0);
2352 return (bytes_cmp_utf8(
2353 (const U8*)pv, pvlen,
2354 (const U8*)HEK_KEY(hek), HEK_LEN(hek)) == 0);
2357 return HEK_LEN(hek) == pvlen && ((HEK_KEY(hek) == pv)
2358 || memEQ(HEK_KEY(hek), pv, pvlen));
2362 =for apidoc hv_ename_add
2364 Adds a name to a stash's internal list of effective names. See
2365 C<L</hv_ename_delete>>.
2367 This is called when a stash is assigned to a new location in the symbol
2374 Perl_hv_ename_add(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2377 struct xpvhv_aux *aux = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2380 PERL_ARGS_ASSERT_HV_ENAME_ADD;
2383 Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
2385 PERL_HASH(hash, name, len);
2387 if (aux->xhv_name_count) {
2388 I32 count = aux->xhv_name_count;
2389 HEK ** const xhv_name = aux->xhv_name_u.xhvnameu_names + (count<0);
2390 HEK **hekp = xhv_name + (count < 0 ? -count - 1 : count);
2391 while (hekp-- > xhv_name)
2395 (HEK_UTF8(*hekp) || (flags & SVf_UTF8))
2396 ? hek_eq_pvn_flags(aTHX_ *hekp, name, (I32)len, flags)
2397 : (HEK_LEN(*hekp) == (I32)len && memEQ(HEK_KEY(*hekp), name, len))
2399 if (hekp == xhv_name && count < 0)
2400 aux->xhv_name_count = -count;
2404 if (count < 0) aux->xhv_name_count--, count = -count;
2405 else aux->xhv_name_count++;
2406 Renew(aux->xhv_name_u.xhvnameu_names, count + 1, HEK *);
2407 (aux->xhv_name_u.xhvnameu_names)[count] = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
2410 HEK *existing_name = aux->xhv_name_u.xhvnameu_name;
2413 (HEK_UTF8(existing_name) || (flags & SVf_UTF8))
2414 ? hek_eq_pvn_flags(aTHX_ existing_name, name, (I32)len, flags)
2415 : (HEK_LEN(existing_name) == (I32)len && memEQ(HEK_KEY(existing_name), name, len))
2418 Newx(aux->xhv_name_u.xhvnameu_names, 2, HEK *);
2419 aux->xhv_name_count = existing_name ? 2 : -2;
2420 *aux->xhv_name_u.xhvnameu_names = existing_name;
2421 (aux->xhv_name_u.xhvnameu_names)[1] = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
2426 =for apidoc hv_ename_delete
2428 Removes a name from a stash's internal list of effective names. If this is
2429 the name returned by C<HvENAME>, then another name in the list will take
2430 its place (C<HvENAME> will use it).
2432 This is called when a stash is deleted from the symbol table.
2438 Perl_hv_ename_delete(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2440 struct xpvhv_aux *aux;
2442 PERL_ARGS_ASSERT_HV_ENAME_DELETE;
2445 Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
2447 if (!SvOOK(hv)) return;
2450 if (!aux->xhv_name_u.xhvnameu_name) return;
2452 if (aux->xhv_name_count) {
2453 HEK ** const namep = aux->xhv_name_u.xhvnameu_names;
2454 I32 const count = aux->xhv_name_count;
2455 HEK **victim = namep + (count < 0 ? -count : count);
2456 while (victim-- > namep + 1)
2458 (HEK_UTF8(*victim) || (flags & SVf_UTF8))
2459 ? hek_eq_pvn_flags(aTHX_ *victim, name, (I32)len, flags)
2460 : (HEK_LEN(*victim) == (I32)len && memEQ(HEK_KEY(*victim), name, len))
2462 unshare_hek_or_pvn(*victim, 0, 0, 0);
2463 aux = HvAUX(hv); /* may been realloced */
2464 if (count < 0) ++aux->xhv_name_count;
2465 else --aux->xhv_name_count;
2467 (aux->xhv_name_count == 1 || aux->xhv_name_count == -1)
2469 ) { /* if there are none left */
2471 aux->xhv_name_u.xhvnameu_names = NULL;
2472 aux->xhv_name_count = 0;
2475 /* Move the last one back to fill the empty slot. It
2476 does not matter what order they are in. */
2477 *victim = *(namep + (count < 0 ? -count : count) - 1);
2482 count > 0 && ((HEK_UTF8(*namep) || (flags & SVf_UTF8))
2483 ? hek_eq_pvn_flags(aTHX_ *namep, name, (I32)len, flags)
2484 : (HEK_LEN(*namep) == (I32)len && memEQ(HEK_KEY(*namep), name, len))
2487 aux->xhv_name_count = -count;
2491 (HEK_UTF8(aux->xhv_name_u.xhvnameu_name) || (flags & SVf_UTF8))
2492 ? hek_eq_pvn_flags(aTHX_ aux->xhv_name_u.xhvnameu_name, name, (I32)len, flags)
2493 : (HEK_LEN(aux->xhv_name_u.xhvnameu_name) == (I32)len &&
2494 memEQ(HEK_KEY(aux->xhv_name_u.xhvnameu_name), name, len))
2496 HEK * const namehek = aux->xhv_name_u.xhvnameu_name;
2497 Newx(aux->xhv_name_u.xhvnameu_names, 1, HEK *);
2498 *aux->xhv_name_u.xhvnameu_names = namehek;
2499 aux->xhv_name_count = -1;
2504 Perl_hv_backreferences_p(pTHX_ HV *hv) {
2505 PERL_ARGS_ASSERT_HV_BACKREFERENCES_P;
2506 /* See also Perl_sv_get_backrefs in sv.c where this logic is unrolled */
2508 struct xpvhv_aux * const iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2509 return &(iter->xhv_backreferences);
2514 Perl_hv_kill_backrefs(pTHX_ HV *hv) {
2517 PERL_ARGS_ASSERT_HV_KILL_BACKREFS;
2522 av = HvAUX(hv)->xhv_backreferences;
2525 HvAUX(hv)->xhv_backreferences = 0;
2526 Perl_sv_kill_backrefs(aTHX_ MUTABLE_SV(hv), av);
2527 if (SvTYPE(av) == SVt_PVAV)
2528 SvREFCNT_dec_NN(av);
2533 hv_iternext is implemented as a macro in hv.h
2535 =for apidoc hv_iternext
2537 Returns entries from a hash iterator. See C<L</hv_iterinit>>.
2539 You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
2540 iterator currently points to, without losing your place or invalidating your
2541 iterator. Note that in this case the current entry is deleted from the hash
2542 with your iterator holding the last reference to it. Your iterator is flagged
2543 to free the entry on the next call to C<hv_iternext>, so you must not discard
2544 your iterator immediately else the entry will leak - call C<hv_iternext> to
2545 trigger the resource deallocation.
2547 =for apidoc hv_iternext_flags
2549 Returns entries from a hash iterator. See C<L</hv_iterinit>> and
2551 The C<flags> value will normally be zero; if C<HV_ITERNEXT_WANTPLACEHOLDERS> is
2552 set the placeholders keys (for restricted hashes) will be returned in addition
2553 to normal keys. By default placeholders are automatically skipped over.
2554 Currently a placeholder is implemented with a value that is
2555 C<&PL_sv_placeholder>. Note that the implementation of placeholders and
2556 restricted hashes may change, and the implementation currently is
2557 insufficiently abstracted for any change to be tidy.
2563 Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
2570 struct xpvhv_aux *iter;
2572 PERL_ARGS_ASSERT_HV_ITERNEXT_FLAGS;
2574 xhv = (XPVHV*)SvANY(hv);
2577 /* Too many things (well, pp_each at least) merrily assume that you can
2578 call hv_iternext without calling hv_iterinit, so we'll have to deal
2584 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2585 if (SvMAGICAL(hv) && SvRMAGICAL(hv)) {
2586 if ( ( mg = mg_find((const SV *)hv, PERL_MAGIC_tied) ) ) {
2587 SV * const key = sv_newmortal();
2589 sv_setsv(key, HeSVKEY_force(entry));
2590 SvREFCNT_dec(HeSVKEY(entry)); /* get rid of previous key */
2591 HeSVKEY_set(entry, NULL);
2597 /* one HE per MAGICAL hash */
2598 iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
2599 HvLAZYDEL_on(hv); /* make sure entry gets freed */
2601 Newxz(k, HEK_BASESIZE + sizeof(const SV *), char);
2603 HeKEY_hek(entry) = hek;
2604 HeKLEN(entry) = HEf_SVKEY;
2606 magic_nextpack(MUTABLE_SV(hv),mg,key);
2608 /* force key to stay around until next time */
2609 HeSVKEY_set(entry, SvREFCNT_inc_simple_NN(key));
2610 return entry; /* beware, hent_val is not set */
2612 SvREFCNT_dec(HeVAL(entry));
2613 Safefree(HeKEY_hek(entry));
2615 iter = HvAUX(hv); /* may been realloced */
2616 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
2621 #if defined(DYNAMIC_ENV_FETCH) && !defined(__riscos__) /* set up %ENV for iteration */
2622 if (!entry && SvRMAGICAL((const SV *)hv)
2623 && mg_find((const SV *)hv, PERL_MAGIC_env)) {
2626 /* The prime_env_iter() on VMS just loaded up new hash values
2627 * so the iteration count needs to be reset back to the beginning
2631 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2636 /* hv_iterinit now ensures this. */
2637 assert (HvARRAY(hv));
2639 /* At start of hash, entry is NULL. */
2642 entry = HeNEXT(entry);
2643 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2645 * Skip past any placeholders -- don't want to include them in
2648 while (entry && HeVAL(entry) == &PL_sv_placeholder) {
2649 entry = HeNEXT(entry);
2654 #ifdef PERL_HASH_RANDOMIZE_KEYS
2655 if (iter->xhv_last_rand != iter->xhv_rand) {
2656 if (iter->xhv_riter != -1) {
2657 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
2658 "Use of each() on hash after insertion without resetting hash iterator results in undefined behavior"
2662 iter = HvAUX(hv); /* may been realloced */
2663 iter->xhv_last_rand = iter->xhv_rand;
2667 /* Skip the entire loop if the hash is empty. */
2668 if ((flags & HV_ITERNEXT_WANTPLACEHOLDERS)
2669 ? HvTOTALKEYS(hv) : HvUSEDKEYS(hv)) {
2671 /* OK. Come to the end of the current list. Grab the next one. */
2673 iter->xhv_riter++; /* HvRITER(hv)++ */
2674 if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
2675 /* There is no next one. End of the hash. */
2676 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2677 #ifdef PERL_HASH_RANDOMIZE_KEYS
2678 iter->xhv_last_rand = iter->xhv_rand; /* reset xhv_last_rand so we can detect inserts during traversal */
2682 entry = (HvARRAY(hv))[ PERL_HASH_ITER_BUCKET(iter) & xhv->xhv_max ];
2684 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2685 /* If we have an entry, but it's a placeholder, don't count it.
2687 while (entry && HeVAL(entry) == &PL_sv_placeholder)
2688 entry = HeNEXT(entry);
2690 /* Will loop again if this linked list starts NULL
2691 (for HV_ITERNEXT_WANTPLACEHOLDERS)
2692 or if we run through it and find only placeholders. */
2696 iter->xhv_riter = -1;
2697 #ifdef PERL_HASH_RANDOMIZE_KEYS
2698 iter->xhv_last_rand = iter->xhv_rand;
2702 if (oldentry && HvLAZYDEL(hv)) { /* was deleted earlier? */
2704 hv_free_ent(hv, oldentry);
2707 iter = HvAUX(hv); /* may been realloced */
2708 iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
2713 =for apidoc hv_iterkey
2715 Returns the key from the current position of the hash iterator. See
2722 Perl_hv_iterkey(pTHX_ HE *entry, I32 *retlen)
2724 PERL_ARGS_ASSERT_HV_ITERKEY;
2726 if (HeKLEN(entry) == HEf_SVKEY) {
2728 char * const p = SvPV(HeKEY_sv(entry), len);
2733 *retlen = HeKLEN(entry);
2734 return HeKEY(entry);
2738 /* unlike hv_iterval(), this always returns a mortal copy of the key */
2740 =for apidoc hv_iterkeysv
2742 Returns the key as an C<SV*> from the current position of the hash
2743 iterator. The return value will always be a mortal copy of the key. Also
2744 see C<L</hv_iterinit>>.
2750 Perl_hv_iterkeysv(pTHX_ HE *entry)
2752 PERL_ARGS_ASSERT_HV_ITERKEYSV;
2754 return sv_2mortal(newSVhek(HeKEY_hek(entry)));
2758 =for apidoc hv_iterval
2760 Returns the value from the current position of the hash iterator. See
2767 Perl_hv_iterval(pTHX_ HV *hv, HE *entry)
2769 PERL_ARGS_ASSERT_HV_ITERVAL;
2771 if (SvRMAGICAL(hv)) {
2772 if (mg_find((const SV *)hv, PERL_MAGIC_tied)) {
2773 SV* const sv = sv_newmortal();
2774 if (HeKLEN(entry) == HEf_SVKEY)
2775 mg_copy(MUTABLE_SV(hv), sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
2777 mg_copy(MUTABLE_SV(hv), sv, HeKEY(entry), HeKLEN(entry));
2781 return HeVAL(entry);
2785 =for apidoc hv_iternextsv
2787 Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2794 Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
2796 HE * const he = hv_iternext_flags(hv, 0);
2798 PERL_ARGS_ASSERT_HV_ITERNEXTSV;
2802 *key = hv_iterkey(he, retlen);
2803 return hv_iterval(hv, he);
2810 =for apidoc hv_magic
2812 Adds magic to a hash. See C<L</sv_magic>>.
2817 /* possibly free a shared string if no one has access to it
2818 * len and hash must both be valid for str.
2821 Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
2823 unshare_hek_or_pvn (NULL, str, len, hash);
2828 Perl_unshare_hek(pTHX_ HEK *hek)
2831 unshare_hek_or_pvn(hek, NULL, 0, 0);
2834 /* possibly free a shared string if no one has access to it
2835 hek if non-NULL takes priority over the other 3, else str, len and hash
2836 are used. If so, len and hash must both be valid for str.
2839 S_unshare_hek_or_pvn(pTHX_ const HEK *hek, const char *str, I32 len, U32 hash)
2844 bool is_utf8 = FALSE;
2846 const char * const save = str;
2847 struct shared_he *he = NULL;
2850 /* Find the shared he which is just before us in memory. */
2851 he = (struct shared_he *)(((char *)hek)
2852 - STRUCT_OFFSET(struct shared_he,
2855 /* Assert that the caller passed us a genuine (or at least consistent)
2857 assert (he->shared_he_he.hent_hek == hek);
2859 if (he->shared_he_he.he_valu.hent_refcount - 1) {
2860 --he->shared_he_he.he_valu.hent_refcount;
2864 hash = HEK_HASH(hek);
2865 } else if (len < 0) {
2866 STRLEN tmplen = -len;
2868 /* See the note in hv_fetch(). --jhi */
2869 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2872 k_flags = HVhek_UTF8;
2874 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2877 /* what follows was the moral equivalent of:
2878 if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
2880 hv_delete(PL_strtab, str, len, G_DISCARD, hash);
2882 xhv = (XPVHV*)SvANY(PL_strtab);
2883 /* assert(xhv_array != 0) */
2884 oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2886 const HE *const he_he = &(he->shared_he_he);
2887 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2892 const int flags_masked = k_flags & HVhek_MASK;
2893 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2894 if (HeHASH(entry) != hash) /* strings can't be equal */
2896 if (HeKLEN(entry) != len)
2898 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2900 if (HeKFLAGS(entry) != flags_masked)
2907 if (--entry->he_valu.hent_refcount == 0) {
2908 *oentry = HeNEXT(entry);
2910 xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
2915 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
2916 "Attempt to free nonexistent shared string '%s'%s"
2918 hek ? HEK_KEY(hek) : str,
2919 ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
2920 if (k_flags & HVhek_FREEKEY)
2924 /* get a (constant) string ptr from the global string table
2925 * string will get added if it is not already there.
2926 * len and hash must both be valid for str.
2929 Perl_share_hek(pTHX_ const char *str, I32 len, U32 hash)
2931 bool is_utf8 = FALSE;
2933 const char * const save = str;
2935 PERL_ARGS_ASSERT_SHARE_HEK;
2938 STRLEN tmplen = -len;
2940 /* See the note in hv_fetch(). --jhi */
2941 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2943 /* If we were able to downgrade here, then than means that we were passed
2944 in a key which only had chars 0-255, but was utf8 encoded. */
2947 /* If we found we were able to downgrade the string to bytes, then
2948 we should flag that it needs upgrading on keys or each. Also flag
2949 that we need share_hek_flags to free the string. */
2952 PERL_HASH(hash, str, len);
2953 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2957 return share_hek_flags (str, len, hash, flags);
2961 S_share_hek_flags(pTHX_ const char *str, I32 len, U32 hash, int flags)
2964 const int flags_masked = flags & HVhek_MASK;
2965 const U32 hindex = hash & (I32) HvMAX(PL_strtab);
2966 XPVHV * const xhv = (XPVHV*)SvANY(PL_strtab);
2968 PERL_ARGS_ASSERT_SHARE_HEK_FLAGS;
2970 /* what follows is the moral equivalent of:
2972 if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
2973 hv_store(PL_strtab, str, len, NULL, hash);
2975 Can't rehash the shared string table, so not sure if it's worth
2976 counting the number of entries in the linked list
2979 /* assert(xhv_array != 0) */
2980 entry = (HvARRAY(PL_strtab))[hindex];
2981 for (;entry; entry = HeNEXT(entry)) {
2982 if (HeHASH(entry) != hash) /* strings can't be equal */
2984 if (HeKLEN(entry) != len)
2986 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2988 if (HeKFLAGS(entry) != flags_masked)
2994 /* What used to be head of the list.
2995 If this is NULL, then we're the first entry for this slot, which
2996 means we need to increate fill. */
2997 struct shared_he *new_entry;
3000 HE **const head = &HvARRAY(PL_strtab)[hindex];
3001 HE *const next = *head;
3003 /* We don't actually store a HE from the arena and a regular HEK.
3004 Instead we allocate one chunk of memory big enough for both,
3005 and put the HEK straight after the HE. This way we can find the
3006 HE directly from the HEK.
3009 Newx(k, STRUCT_OFFSET(struct shared_he,
3010 shared_he_hek.hek_key[0]) + len + 2, char);
3011 new_entry = (struct shared_he *)k;
3012 entry = &(new_entry->shared_he_he);
3013 hek = &(new_entry->shared_he_hek);
3015 Copy(str, HEK_KEY(hek), len, char);
3016 HEK_KEY(hek)[len] = 0;
3018 HEK_HASH(hek) = hash;
3019 HEK_FLAGS(hek) = (unsigned char)flags_masked;
3021 /* Still "point" to the HEK, so that other code need not know what
3023 HeKEY_hek(entry) = hek;
3024 entry->he_valu.hent_refcount = 0;
3025 HeNEXT(entry) = next;
3028 xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
3029 if (!next) { /* initial entry? */
3030 } else if ( DO_HSPLIT(xhv) ) {
3031 const STRLEN oldsize = xhv->xhv_max + 1;
3032 hsplit(PL_strtab, oldsize, oldsize * 2);
3036 ++entry->he_valu.hent_refcount;
3038 if (flags & HVhek_FREEKEY)
3041 return HeKEY_hek(entry);
3045 Perl_hv_placeholders_p(pTHX_ HV *hv)
3047 MAGIC *mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
3049 PERL_ARGS_ASSERT_HV_PLACEHOLDERS_P;
3052 mg = sv_magicext(MUTABLE_SV(hv), 0, PERL_MAGIC_rhash, 0, 0, 0);
3055 Perl_die(aTHX_ "panic: hv_placeholders_p");
3058 return &(mg->mg_len);
3063 Perl_hv_placeholders_get(pTHX_ const HV *hv)
3065 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
3067 PERL_ARGS_ASSERT_HV_PLACEHOLDERS_GET;
3068 PERL_UNUSED_CONTEXT;
3070 return mg ? mg->mg_len : 0;
3074 Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
3076 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
3078 PERL_ARGS_ASSERT_HV_PLACEHOLDERS_SET;
3083 if (!sv_magicext(MUTABLE_SV(hv), 0, PERL_MAGIC_rhash, 0, 0, ph))
3084 Perl_die(aTHX_ "panic: hv_placeholders_set");
3086 /* else we don't need to add magic to record 0 placeholders. */
3090 S_refcounted_he_value(pTHX_ const struct refcounted_he *he)
3095 PERL_ARGS_ASSERT_REFCOUNTED_HE_VALUE;
3097 switch(he->refcounted_he_data[0] & HVrhek_typemask) {
3102 value = &PL_sv_placeholder;
3105 value = newSViv(he->refcounted_he_val.refcounted_he_u_iv);
3108 value = newSVuv(he->refcounted_he_val.refcounted_he_u_uv);
3111 case HVrhek_PV_UTF8:
3112 /* Create a string SV that directly points to the bytes in our
3114 value = newSV_type(SVt_PV);
3115 SvPV_set(value, (char *) he->refcounted_he_data + 1);
3116 SvCUR_set(value, he->refcounted_he_val.refcounted_he_u_len);
3117 /* This stops anything trying to free it */
3118 SvLEN_set(value, 0);
3120 SvREADONLY_on(value);
3121 if ((he->refcounted_he_data[0] & HVrhek_typemask) == HVrhek_PV_UTF8)
3125 Perl_croak(aTHX_ "panic: refcounted_he_value bad flags %"UVxf,
3126 (UV)he->refcounted_he_data[0]);
3132 =for apidoc m|HV *|refcounted_he_chain_2hv|const struct refcounted_he *c|U32 flags
3134 Generates and returns a C<HV *> representing the content of a
3135 C<refcounted_he> chain.
3136 C<flags> is currently unused and must be zero.
3141 Perl_refcounted_he_chain_2hv(pTHX_ const struct refcounted_he *chain, U32 flags)
3145 U32 placeholders, max;
3148 Perl_croak(aTHX_ "panic: refcounted_he_chain_2hv bad flags %"UVxf,
3151 /* We could chase the chain once to get an idea of the number of keys,
3152 and call ksplit. But for now we'll make a potentially inefficient
3153 hash with only 8 entries in its array. */
3158 Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(max + 1), char);
3159 HvARRAY(hv) = (HE**)array;
3165 U32 hash = chain->refcounted_he_hash;
3167 U32 hash = HEK_HASH(chain->refcounted_he_hek);
3169 HE **oentry = &((HvARRAY(hv))[hash & max]);
3170 HE *entry = *oentry;
3173 for (; entry; entry = HeNEXT(entry)) {
3174 if (HeHASH(entry) == hash) {
3175 /* We might have a duplicate key here. If so, entry is older
3176 than the key we've already put in the hash, so if they are
3177 the same, skip adding entry. */
3179 const STRLEN klen = HeKLEN(entry);
3180 const char *const key = HeKEY(entry);
3181 if (klen == chain->refcounted_he_keylen
3182 && (!!HeKUTF8(entry)
3183 == !!(chain->refcounted_he_data[0] & HVhek_UTF8))
3184 && memEQ(key, REF_HE_KEY(chain), klen))
3187 if (HeKEY_hek(entry) == chain->refcounted_he_hek)
3189 if (HeKLEN(entry) == HEK_LEN(chain->refcounted_he_hek)
3190 && HeKUTF8(entry) == HEK_UTF8(chain->refcounted_he_hek)
3191 && memEQ(HeKEY(entry), HEK_KEY(chain->refcounted_he_hek),
3202 = share_hek_flags(REF_HE_KEY(chain),
3203 chain->refcounted_he_keylen,
3204 chain->refcounted_he_hash,
3205 (chain->refcounted_he_data[0]
3206 & (HVhek_UTF8|HVhek_WASUTF8)));
3208 HeKEY_hek(entry) = share_hek_hek(chain->refcounted_he_hek);
3210 value = refcounted_he_value(chain);
3211 if (value == &PL_sv_placeholder)
3213 HeVAL(entry) = value;
3215 /* Link it into the chain. */
3216 HeNEXT(entry) = *oentry;
3222 chain = chain->refcounted_he_next;
3226 clear_placeholders(hv, placeholders);
3227 HvTOTALKEYS(hv) -= placeholders;
3230 /* We could check in the loop to see if we encounter any keys with key
3231 flags, but it's probably not worth it, as this per-hash flag is only
3232 really meant as an optimisation for things like Storable. */
3234 DEBUG_A(Perl_hv_assert(aTHX_ hv));
3240 =for apidoc m|SV *|refcounted_he_fetch_pvn|const struct refcounted_he *chain|const char *keypv|STRLEN keylen|U32 hash|U32 flags
3242 Search along a C<refcounted_he> chain for an entry with the key specified
3243 by C<keypv> and C<keylen>. If C<flags> has the C<REFCOUNTED_HE_KEY_UTF8>
3244 bit set, the key octets are interpreted as UTF-8, otherwise they
3245 are interpreted as Latin-1. C<hash> is a precomputed hash of the key
3246 string, or zero if it has not been precomputed. Returns a mortal scalar
3247 representing the value associated with the key, or C<&PL_sv_placeholder>
3248 if there is no value associated with the key.
3254 Perl_refcounted_he_fetch_pvn(pTHX_ const struct refcounted_he *chain,
3255 const char *keypv, STRLEN keylen, U32 hash, U32 flags)
3259 PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_PVN;
3261 if (flags & ~(REFCOUNTED_HE_KEY_UTF8|REFCOUNTED_HE_EXISTS))
3262 Perl_croak(aTHX_ "panic: refcounted_he_fetch_pvn bad flags %"UVxf,
3266 if (flags & REFCOUNTED_HE_KEY_UTF8) {
3267 /* For searching purposes, canonicalise to Latin-1 where possible. */
3268 const char *keyend = keypv + keylen, *p;
3269 STRLEN nonascii_count = 0;
3270 for (p = keypv; p != keyend; p++) {
3271 if (! UTF8_IS_INVARIANT(*p)) {
3272 if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(p, keyend)) {
3273 goto canonicalised_key;
3279 if (nonascii_count) {
3281 const char *p = keypv, *keyend = keypv + keylen;
3282 keylen -= nonascii_count;
3283 Newx(q, keylen, char);
3286 for (; p != keyend; p++, q++) {
3288 if (UTF8_IS_INVARIANT(c)) {
3293 *q = (char) EIGHT_BIT_UTF8_TO_NATIVE(c, *p);
3297 flags &= ~REFCOUNTED_HE_KEY_UTF8;
3298 canonicalised_key: ;
3300 utf8_flag = (flags & REFCOUNTED_HE_KEY_UTF8) ? HVhek_UTF8 : 0;
3302 PERL_HASH(hash, keypv, keylen);
3304 for (; chain; chain = chain->refcounted_he_next) {
3307 hash == chain->refcounted_he_hash &&
3308 keylen == chain->refcounted_he_keylen &&
3309 memEQ(REF_HE_KEY(chain), keypv, keylen) &&
3310 utf8_flag == (chain->refcounted_he_data[0] & HVhek_UTF8)
3312 hash == HEK_HASH(chain->refcounted_he_hek) &&
3313 keylen == (STRLEN)HEK_LEN(chain->refcounted_he_hek) &&
3314 memEQ(HEK_KEY(chain->refcounted_he_hek), keypv, keylen) &&
3315 utf8_flag == (HEK_FLAGS(chain->refcounted_he_hek) & HVhek_UTF8)
3318 if (flags & REFCOUNTED_HE_EXISTS)
3319 return (chain->refcounted_he_data[0] & HVrhek_typemask)
3321 ? NULL : &PL_sv_yes;
3322 return sv_2mortal(refcounted_he_value(chain));
3326 return flags & REFCOUNTED_HE_EXISTS ? NULL : &PL_sv_placeholder;
3330 =for apidoc m|SV *|refcounted_he_fetch_pv|const struct refcounted_he *chain|const char *key|U32 hash|U32 flags
3332 Like L</refcounted_he_fetch_pvn>, but takes a nul-terminated string
3333 instead of a string/length pair.
3339 Perl_refcounted_he_fetch_pv(pTHX_ const struct refcounted_he *chain,
3340 const char *key, U32 hash, U32 flags)
3342 PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_PV;
3343 return refcounted_he_fetch_pvn(chain, key, strlen(key), hash, flags);
3347 =for apidoc m|SV *|refcounted_he_fetch_sv|const struct refcounted_he *chain|SV *key|U32 hash|U32 flags
3349 Like L</refcounted_he_fetch_pvn>, but takes a Perl scalar instead of a
3356 Perl_refcounted_he_fetch_sv(pTHX_ const struct refcounted_he *chain,
3357 SV *key, U32 hash, U32 flags)
3361 PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_SV;
3362 if (flags & REFCOUNTED_HE_KEY_UTF8)
3363 Perl_croak(aTHX_ "panic: refcounted_he_fetch_sv bad flags %"UVxf,
3365 keypv = SvPV_const(key, keylen);
3367 flags |= REFCOUNTED_HE_KEY_UTF8;
3368 if (!hash && SvIsCOW_shared_hash(key))
3369 hash = SvSHARED_HASH(key);
3370 return refcounted_he_fetch_pvn(chain, keypv, keylen, hash, flags);
3374 =for apidoc m|struct refcounted_he *|refcounted_he_new_pvn|struct refcounted_he *parent|const char *keypv|STRLEN keylen|U32 hash|SV *value|U32 flags
3376 Creates a new C<refcounted_he>. This consists of a single key/value
3377 pair and a reference to an existing C<refcounted_he> chain (which may
3378 be empty), and thus forms a longer chain. When using the longer chain,
3379 the new key/value pair takes precedence over any entry for the same key
3380 further along the chain.
3382 The new key is specified by C<keypv> and C<keylen>. If C<flags> has
3383 the C<REFCOUNTED_HE_KEY_UTF8> bit set, the key octets are interpreted
3384 as UTF-8, otherwise they are interpreted as Latin-1. C<hash> is
3385 a precomputed hash of the key string, or zero if it has not been
3388 C<value> is the scalar value to store for this key. C<value> is copied
3389 by this function, which thus does not take ownership of any reference
3390 to it, and later changes to the scalar will not be reflected in the
3391 value visible in the C<refcounted_he>. Complex types of scalar will not
3392 be stored with referential integrity, but will be coerced to strings.
3393 C<value> may be either null or C<&PL_sv_placeholder> to indicate that no
3394 value is to be associated with the key; this, as with any non-null value,
3395 takes precedence over the existence of a value for the key further along
3398 C<parent> points to the rest of the C<refcounted_he> chain to be
3399 attached to the new C<refcounted_he>. This function takes ownership
3400 of one reference to C<parent>, and returns one reference to the new
3406 struct refcounted_he *
3407 Perl_refcounted_he_new_pvn(pTHX_ struct refcounted_he *parent,
3408 const char *keypv, STRLEN keylen, U32 hash, SV *value, U32 flags)
3411 STRLEN value_len = 0;
3412 const char *value_p = NULL;
3416 STRLEN key_offset = 1;
3417 struct refcounted_he *he;
3418 PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_PVN;
3420 if (!value || value == &PL_sv_placeholder) {
3421 value_type = HVrhek_delete;
3422 } else if (SvPOK(value)) {
3423 value_type = HVrhek_PV;
3424 } else if (SvIOK(value)) {
3425 value_type = SvUOK((const SV *)value) ? HVrhek_UV : HVrhek_IV;
3426 } else if (!SvOK(value)) {
3427 value_type = HVrhek_undef;
3429 value_type = HVrhek_PV;
3431 is_pv = value_type == HVrhek_PV;
3433 /* Do it this way so that the SvUTF8() test is after the SvPV, in case
3434 the value is overloaded, and doesn't yet have the UTF-8flag set. */
3435 value_p = SvPV_const(value, value_len);
3437 value_type = HVrhek_PV_UTF8;
3438 key_offset = value_len + 2;
3440 hekflags = value_type;
3442 if (flags & REFCOUNTED_HE_KEY_UTF8) {
3443 /* Canonicalise to Latin-1 where possible. */
3444 const char *keyend = keypv + keylen, *p;
3445 STRLEN nonascii_count = 0;
3446 for (p = keypv; p != keyend; p++) {
3447 if (! UTF8_IS_INVARIANT(*p)) {
3448 if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(p, keyend)) {
3449 goto canonicalised_key;
3455 if (nonascii_count) {
3457 const char *p = keypv, *keyend = keypv + keylen;
3458 keylen -= nonascii_count;
3459 Newx(q, keylen, char);
3462 for (; p != keyend; p++, q++) {
3464 if (UTF8_IS_INVARIANT(c)) {
3469 *q = (char) EIGHT_BIT_UTF8_TO_NATIVE(c, *p);
3473 flags &= ~REFCOUNTED_HE_KEY_UTF8;
3474 canonicalised_key: ;
3476 if (flags & REFCOUNTED_HE_KEY_UTF8)
3477 hekflags |= HVhek_UTF8;
3479 PERL_HASH(hash, keypv, keylen);
3482 he = (struct refcounted_he*)
3483 PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
3487 he = (struct refcounted_he*)
3488 PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
3492 he->refcounted_he_next = parent;
3495 Copy(value_p, he->refcounted_he_data + 1, value_len + 1, char);
3496 he->refcounted_he_val.refcounted_he_u_len = value_len;
3497 } else if (value_type == HVrhek_IV) {
3498 he->refcounted_he_val.refcounted_he_u_iv = SvIVX(value);
3499 } else if (value_type == HVrhek_UV) {
3500 he->refcounted_he_val.refcounted_he_u_uv = SvUVX(value);
3504 he->refcounted_he_hash = hash;
3505 he->refcounted_he_keylen = keylen;
3506 Copy(keypv, he->refcounted_he_data + key_offset, keylen, char);
3508 he->refcounted_he_hek = share_hek_flags(keypv, keylen, hash, hekflags);
3511 he->refcounted_he_data[0] = hekflags;
3512 he->refcounted_he_refcnt = 1;
3518 =for apidoc m|struct refcounted_he *|refcounted_he_new_pv|struct refcounted_he *parent|const char *key|U32 hash|SV *value|U32 flags
3520 Like L</refcounted_he_new_pvn>, but takes a nul-terminated string instead
3521 of a string/length pair.
3526 struct refcounted_he *
3527 Perl_refcounted_he_new_pv(pTHX_ struct refcounted_he *parent,
3528 const char *key, U32 hash, SV *value, U32 flags)
3530 PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_PV;
3531 return refcounted_he_new_pvn(parent, key, strlen(key), hash, value, flags);
3535 =for apidoc m|struct refcounted_he *|refcounted_he_new_sv|struct refcounted_he *parent|SV *key|U32 hash|SV *value|U32 flags
3537 Like L</refcounted_he_new_pvn>, but takes a Perl scalar instead of a
3543 struct refcounted_he *
3544 Perl_refcounted_he_new_sv(pTHX_ struct refcounted_he *parent,
3545 SV *key, U32 hash, SV *value, U32 flags)
3549 PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_SV;
3550 if (flags & REFCOUNTED_HE_KEY_UTF8)
3551 Perl_croak(aTHX_ "panic: refcounted_he_new_sv bad flags %"UVxf,
3553 keypv = SvPV_const(key, keylen);
3555 flags |= REFCOUNTED_HE_KEY_UTF8;
3556 if (!hash && SvIsCOW_shared_hash(key))
3557 hash = SvSHARED_HASH(key);
3558 return refcounted_he_new_pvn(parent, keypv, keylen, hash, value, flags);
3562 =for apidoc m|void|refcounted_he_free|struct refcounted_he *he
3564 Decrements the reference count of a C<refcounted_he> by one. If the
3565 reference count reaches zero the structure's memory is freed, which
3566 (recursively) causes a reduction of its parent C<refcounted_he>'s
3567 reference count. It is safe to pass a null pointer to this function:
3568 no action occurs in this case.
3574 Perl_refcounted_he_free(pTHX_ struct refcounted_he *he) {
3578 PERL_UNUSED_CONTEXT;
3581 struct refcounted_he *copy;
3585 new_count = --he->refcounted_he_refcnt;
3586 HINTS_REFCNT_UNLOCK;
3592 #ifndef USE_ITHREADS
3593 unshare_hek_or_pvn (he->refcounted_he_hek, 0, 0, 0);
3596 he = he->refcounted_he_next;
3597 PerlMemShared_free(copy);
3602 =for apidoc m|struct refcounted_he *|refcounted_he_inc|struct refcounted_he *he
3604 Increment the reference count of a C<refcounted_he>. The pointer to the
3605 C<refcounted_he> is also returned. It is safe to pass a null pointer
3606 to this function: no action occurs and a null pointer is returned.
3611 struct refcounted_he *
3612 Perl_refcounted_he_inc(pTHX_ struct refcounted_he *he)
3617 PERL_UNUSED_CONTEXT;
3620 he->refcounted_he_refcnt++;
3621 HINTS_REFCNT_UNLOCK;
3627 =for apidoc cop_fetch_label
3629 Returns the label attached to a cop.
3630 The flags pointer may be set to C<SVf_UTF8> or 0.
3635 /* pp_entereval is aware that labels are stored with a key ':' at the top of
3638 Perl_cop_fetch_label(pTHX_ COP *const cop, STRLEN *len, U32 *flags) {
3639 struct refcounted_he *const chain = cop->cop_hints_hash;
3641 PERL_ARGS_ASSERT_COP_FETCH_LABEL;
3642 PERL_UNUSED_CONTEXT;
3647 if (chain->refcounted_he_keylen != 1)
3649 if (*REF_HE_KEY(chain) != ':')
3652 if ((STRLEN)HEK_LEN(chain->refcounted_he_hek) != 1)
3654 if (*HEK_KEY(chain->refcounted_he_hek) != ':')
3657 /* Stop anyone trying to really mess us up by adding their own value for
3659 if ((chain->refcounted_he_data[0] & HVrhek_typemask) != HVrhek_PV
3660 && (chain->refcounted_he_data[0] & HVrhek_typemask) != HVrhek_PV_UTF8)
3664 *len = chain->refcounted_he_val.refcounted_he_u_len;
3666 *flags = ((chain->refcounted_he_data[0] & HVrhek_typemask)
3667 == HVrhek_PV_UTF8) ? SVf_UTF8 : 0;
3669 return chain->refcounted_he_data + 1;
3673 =for apidoc cop_store_label
3675 Save a label into a C<cop_hints_hash>.
3676 You need to set flags to C<SVf_UTF8>
3683 Perl_cop_store_label(pTHX_ COP *const cop, const char *label, STRLEN len,
3687 PERL_ARGS_ASSERT_COP_STORE_LABEL;
3689 if (flags & ~(SVf_UTF8))
3690 Perl_croak(aTHX_ "panic: cop_store_label illegal flag bits 0x%" UVxf,
3692 labelsv = newSVpvn_flags(label, len, SVs_TEMP);
3693 if (flags & SVf_UTF8)
3696 = refcounted_he_new_pvs(cop->cop_hints_hash, ":", labelsv, 0);
3700 =for apidoc hv_assert
3702 Check that a hash is in an internally consistent state.
3710 Perl_hv_assert(pTHX_ HV *hv)
3715 int placeholders = 0;
3718 const I32 riter = HvRITER_get(hv);
3719 HE *eiter = HvEITER_get(hv);
3721 PERL_ARGS_ASSERT_HV_ASSERT;
3723 (void)hv_iterinit(hv);
3725 while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
3726 /* sanity check the values */
3727 if (HeVAL(entry) == &PL_sv_placeholder)
3731 /* sanity check the keys */
3732 if (HeSVKEY(entry)) {
3733 NOOP; /* Don't know what to check on SV keys. */
3734 } else if (HeKUTF8(entry)) {
3736 if (HeKWASUTF8(entry)) {
3737 PerlIO_printf(Perl_debug_log,
3738 "hash key has both WASUTF8 and UTF8: '%.*s'\n",
3739 (int) HeKLEN(entry), HeKEY(entry));
3742 } else if (HeKWASUTF8(entry))
3745 if (!SvTIED_mg((const SV *)hv, PERL_MAGIC_tied)) {
3746 static const char bad_count[] = "Count %d %s(s), but hash reports %d\n";
3747 const int nhashkeys = HvUSEDKEYS(hv);
3748 const int nhashplaceholders = HvPLACEHOLDERS_get(hv);
3750 if (nhashkeys != real) {
3751 PerlIO_printf(Perl_debug_log, bad_count, real, "keys", nhashkeys );
3754 if (nhashplaceholders != placeholders) {
3755 PerlIO_printf(Perl_debug_log, bad_count, placeholders, "placeholder", nhashplaceholders );
3759 if (withflags && ! HvHASKFLAGS(hv)) {
3760 PerlIO_printf(Perl_debug_log,
3761 "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
3766 sv_dump(MUTABLE_SV(hv));
3768 HvRITER_set(hv, riter); /* Restore hash iterator state */
3769 HvEITER_set(hv, eiter);
3775 * ex: set ts=8 sts=4 sw=4 et: