3 * Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4 * 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
12 * I sit beside the fire and think
13 * of all that I have seen.
16 * [p.278 of _The Lord of the Rings_, II/iii: "The Ring Goes South"]
20 =head1 Hash Manipulation Functions
22 A HV structure represents a Perl hash. It consists mainly of an array
23 of pointers, each of which points to a linked list of HE structures. The
24 array is indexed by the hash function of the key, so each linked list
25 represents all the hash entries with the same hash value. Each HE contains
26 a pointer to the actual value, plus a pointer to a HEK structure which
27 holds the key and hash value.
35 #define PERL_HASH_INTERNAL_ACCESS
38 #define DO_HSPLIT(xhv) ((xhv)->xhv_keys > (xhv)->xhv_max) /* HvTOTALKEYS(hv) > HvMAX(hv) */
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)
55 void ** const root = &PL_body_roots[HE_SVSLOT];
58 Perl_more_bodies(aTHX_ HE_SVSLOT, sizeof(HE), PERL_ARENA_SIZE);
65 #define new_HE() new_he()
68 HeNEXT(p) = (HE*)(PL_body_roots[HE_SVSLOT]); \
69 PL_body_roots[HE_SVSLOT] = p; \
77 S_save_hek_flags(const char *str, I32 len, U32 hash, int flags)
79 const int flags_masked = flags & HVhek_MASK;
83 PERL_ARGS_ASSERT_SAVE_HEK_FLAGS;
85 Newx(k, HEK_BASESIZE + len + 2, char);
87 Copy(str, HEK_KEY(hek), len, char);
88 HEK_KEY(hek)[len] = 0;
91 HEK_FLAGS(hek) = (unsigned char)flags_masked | HVhek_UNSHARED;
93 if (flags & HVhek_FREEKEY)
98 /* free the pool of temporary HE/HEK pairs returned by hv_fetch_ent
102 Perl_free_tied_hv_pool(pTHX)
105 HE *he = PL_hv_fetch_ent_mh;
108 Safefree(HeKEY_hek(he));
112 PL_hv_fetch_ent_mh = NULL;
115 #if defined(USE_ITHREADS)
117 Perl_hek_dup(pTHX_ HEK *source, CLONE_PARAMS* param)
121 PERL_ARGS_ASSERT_HEK_DUP;
122 PERL_UNUSED_ARG(param);
127 shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
129 /* We already shared this hash key. */
130 (void)share_hek_hek(shared);
134 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
135 HEK_HASH(source), HEK_FLAGS(source));
136 ptr_table_store(PL_ptr_table, source, shared);
142 Perl_he_dup(pTHX_ const HE *e, bool shared, CLONE_PARAMS* param)
146 PERL_ARGS_ASSERT_HE_DUP;
150 /* look for it in the table first */
151 ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
155 /* create anew and remember what it is */
157 ptr_table_store(PL_ptr_table, e, ret);
159 HeNEXT(ret) = he_dup(HeNEXT(e),shared, param);
160 if (HeKLEN(e) == HEf_SVKEY) {
162 Newx(k, HEK_BASESIZE + sizeof(const SV *), char);
163 HeKEY_hek(ret) = (HEK*)k;
164 HeKEY_sv(ret) = sv_dup_inc(HeKEY_sv(e), param);
167 /* This is hek_dup inlined, which seems to be important for speed
169 HEK * const source = HeKEY_hek(e);
170 HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
173 /* We already shared this hash key. */
174 (void)share_hek_hek(shared);
178 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
179 HEK_HASH(source), HEK_FLAGS(source));
180 ptr_table_store(PL_ptr_table, source, shared);
182 HeKEY_hek(ret) = shared;
185 HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
187 HeVAL(ret) = sv_dup_inc(HeVAL(e), param);
190 #endif /* USE_ITHREADS */
193 S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
196 SV * const sv = sv_newmortal();
198 PERL_ARGS_ASSERT_HV_NOTALLOWED;
200 if (!(flags & HVhek_FREEKEY)) {
201 sv_setpvn(sv, key, klen);
204 /* Need to free saved eventually assign to mortal SV */
205 /* XXX is this line an error ???: SV *sv = sv_newmortal(); */
206 sv_usepvn(sv, (char *) key, klen);
208 if (flags & HVhek_UTF8) {
211 Perl_croak(aTHX_ msg, SVfARG(sv));
214 /* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
220 Stores an SV in a hash. The hash key is specified as C<key> and the
221 absolute value of C<klen> is the length of the key. If C<klen> is
222 negative the key is assumed to be in UTF-8-encoded Unicode. The
223 C<hash> parameter is the precomputed hash value; if it is zero then
224 Perl will compute it.
226 The return value will be
227 NULL if the operation failed or if the value did not need to be actually
228 stored within the hash (as in the case of tied hashes). Otherwise it can
229 be dereferenced to get the original C<SV*>. Note that the caller is
230 responsible for suitably incrementing the reference count of C<val> before
231 the call, and decrementing it if the function returned NULL. Effectively
232 a successful hv_store takes ownership of one reference to C<val>. This is
233 usually what you want; a newly created SV has a reference count of one, so
234 if all your code does is create SVs then store them in a hash, hv_store
235 will own the only reference to the new SV, and your code doesn't need to do
236 anything further to tidy up. hv_store is not implemented as a call to
237 hv_store_ent, and does not create a temporary SV for the key, so if your
238 key data is not already in SV form then use hv_store in preference to
241 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
242 information on how to use this function on tied hashes.
244 =for apidoc hv_store_ent
246 Stores C<val> in a hash. The hash key is specified as C<key>. The C<hash>
247 parameter is the precomputed hash value; if it is zero then Perl will
248 compute it. The return value is the new hash entry so created. It will be
249 NULL if the operation failed or if the value did not need to be actually
250 stored within the hash (as in the case of tied hashes). Otherwise the
251 contents of the return value can be accessed using the C<He?> macros
252 described here. Note that the caller is responsible for suitably
253 incrementing the reference count of C<val> before the call, and
254 decrementing it if the function returned NULL. Effectively a successful
255 hv_store_ent takes ownership of one reference to C<val>. This is
256 usually what you want; a newly created SV has a reference count of one, so
257 if all your code does is create SVs then store them in a hash, hv_store
258 will own the only reference to the new SV, and your code doesn't need to do
259 anything further to tidy up. Note that hv_store_ent only reads the C<key>;
260 unlike C<val> it does not take ownership of it, so maintaining the correct
261 reference count on C<key> is entirely the caller's responsibility. hv_store
262 is not implemented as a call to hv_store_ent, and does not create a temporary
263 SV for the key, so if your key data is not already in SV form then use
264 hv_store in preference to hv_store_ent.
266 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
267 information on how to use this function on tied hashes.
269 =for apidoc hv_exists
271 Returns a boolean indicating whether the specified hash key exists. The
272 absolute value of C<klen> is the length of the key. If C<klen> is
273 negative the key is assumed to be in UTF-8-encoded Unicode.
277 Returns the SV which corresponds to the specified key in the hash.
278 The absolute value of C<klen> is the length of the key. If C<klen> is
279 negative the key is assumed to be in UTF-8-encoded Unicode. If
280 C<lval> is set then the fetch will be part of a store. This means that if
281 there is no value in the hash associated with the given key, then one is
282 created and a pointer to it is returned. The C<SV*> it points to can be
283 assigned to. But always check that the
284 return value is non-null before dereferencing it to an C<SV*>.
286 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
287 information on how to use this function on tied hashes.
289 =for apidoc hv_exists_ent
291 Returns a boolean indicating whether
292 the specified hash key exists. C<hash>
293 can be a valid precomputed hash value, or 0 to ask for it to be
299 /* returns an HE * structure with the all fields set */
300 /* note that hent_val will be a mortal sv for MAGICAL hashes */
302 =for apidoc hv_fetch_ent
304 Returns the hash entry which corresponds to the specified key in the hash.
305 C<hash> must be a valid precomputed hash number for the given C<key>, or 0
306 if you want the function to compute it. IF C<lval> is set then the fetch
307 will be part of a store. Make sure the return value is non-null before
308 accessing it. The return value when C<hv> is a tied hash is a pointer to a
309 static location, so be sure to make a copy of the structure if you need to
312 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
313 information on how to use this function on tied hashes.
318 /* Common code for hv_delete()/hv_exists()/hv_fetch()/hv_store() */
320 Perl_hv_common_key_len(pTHX_ HV *hv, const char *key, I32 klen_i32,
321 const int action, SV *val, const U32 hash)
326 PERL_ARGS_ASSERT_HV_COMMON_KEY_LEN;
335 return hv_common(hv, NULL, key, klen, flags, action, val, hash);
339 Perl_hv_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
340 int flags, int action, SV *val, U32 hash)
349 const int return_svp = action & HV_FETCH_JUST_SV;
353 if (SvTYPE(hv) == (svtype)SVTYPEMASK)
356 assert(SvTYPE(hv) == SVt_PVHV);
358 if (SvSMAGICAL(hv) && SvGMAGICAL(hv) && !(action & HV_DISABLE_UVAR_XKEY)) {
360 if ((mg = mg_find((const SV *)hv, PERL_MAGIC_uvar))) {
361 struct ufuncs * const uf = (struct ufuncs *)mg->mg_ptr;
362 if (uf->uf_set == NULL) {
363 SV* obj = mg->mg_obj;
366 keysv = newSVpvn_flags(key, klen, SVs_TEMP |
367 ((flags & HVhek_UTF8)
371 mg->mg_obj = keysv; /* pass key */
372 uf->uf_index = action; /* pass action */
373 magic_getuvar(MUTABLE_SV(hv), mg);
374 keysv = mg->mg_obj; /* may have changed */
377 /* If the key may have changed, then we need to invalidate
378 any passed-in computed hash value. */
384 if (flags & HVhek_FREEKEY)
386 key = SvPV_const(keysv, klen);
387 is_utf8 = (SvUTF8(keysv) != 0);
388 if (SvIsCOW_shared_hash(keysv)) {
389 flags = HVhek_KEYCANONICAL | (is_utf8 ? HVhek_UTF8 : 0);
391 flags = is_utf8 ? HVhek_UTF8 : 0;
394 is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
397 if (action & HV_DELETE) {
398 return (void *) hv_delete_common(hv, keysv, key, klen,
399 flags, action, hash);
402 xhv = (XPVHV*)SvANY(hv);
404 if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS))) {
405 if (mg_find((const SV *)hv, PERL_MAGIC_tied)
406 || SvGMAGICAL((const SV *)hv))
408 /* FIXME should be able to skimp on the HE/HEK here when
409 HV_FETCH_JUST_SV is true. */
411 keysv = newSVpvn_utf8(key, klen, is_utf8);
413 keysv = newSVsv(keysv);
416 mg_copy(MUTABLE_SV(hv), sv, (char *)keysv, HEf_SVKEY);
418 /* grab a fake HE/HEK pair from the pool or make a new one */
419 entry = PL_hv_fetch_ent_mh;
421 PL_hv_fetch_ent_mh = HeNEXT(entry);
425 Newx(k, HEK_BASESIZE + sizeof(const SV *), char);
426 HeKEY_hek(entry) = (HEK*)k;
428 HeNEXT(entry) = NULL;
429 HeSVKEY_set(entry, keysv);
431 sv_upgrade(sv, SVt_PVLV);
433 /* so we can free entry when freeing sv */
434 LvTARG(sv) = MUTABLE_SV(entry);
436 /* XXX remove at some point? */
437 if (flags & HVhek_FREEKEY)
441 return entry ? (void *) &HeVAL(entry) : NULL;
443 return (void *) entry;
445 #ifdef ENV_IS_CASELESS
446 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
448 for (i = 0; i < klen; ++i)
449 if (isLOWER(key[i])) {
450 /* Would be nice if we had a routine to do the
451 copy and upercase in a single pass through. */
452 const char * const nkey = strupr(savepvn(key,klen));
453 /* Note that this fetch is for nkey (the uppercased
454 key) whereas the store is for key (the original) */
455 void *result = hv_common(hv, NULL, nkey, klen,
456 HVhek_FREEKEY, /* free nkey */
457 0 /* non-LVAL fetch */
458 | HV_DISABLE_UVAR_XKEY
461 0 /* compute hash */);
462 if (!result && (action & HV_FETCH_LVALUE)) {
463 /* This call will free key if necessary.
464 Do it this way to encourage compiler to tail
466 result = hv_common(hv, keysv, key, klen, flags,
468 | HV_DISABLE_UVAR_XKEY
472 if (flags & HVhek_FREEKEY)
480 else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
481 if (mg_find((const SV *)hv, PERL_MAGIC_tied)
482 || SvGMAGICAL((const SV *)hv)) {
483 /* I don't understand why hv_exists_ent has svret and sv,
484 whereas hv_exists only had one. */
485 SV * const svret = sv_newmortal();
488 if (keysv || is_utf8) {
490 keysv = newSVpvn_utf8(key, klen, TRUE);
492 keysv = newSVsv(keysv);
494 mg_copy(MUTABLE_SV(hv), sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
496 mg_copy(MUTABLE_SV(hv), sv, key, klen);
498 if (flags & HVhek_FREEKEY)
500 magic_existspack(svret, mg_find(sv, PERL_MAGIC_tiedelem));
501 /* This cast somewhat evil, but I'm merely using NULL/
502 not NULL to return the boolean exists.
503 And I know hv is not NULL. */
504 return SvTRUE(svret) ? (void *)hv : NULL;
506 #ifdef ENV_IS_CASELESS
507 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
508 /* XXX This code isn't UTF8 clean. */
509 char * const keysave = (char * const)key;
510 /* Will need to free this, so set FREEKEY flag. */
511 key = savepvn(key,klen);
512 key = (const char*)strupr((char*)key);
517 if (flags & HVhek_FREEKEY) {
520 flags |= HVhek_FREEKEY;
524 else if (action & HV_FETCH_ISSTORE) {
527 hv_magic_check (hv, &needs_copy, &needs_store);
529 const bool save_taint = TAINT_get; /* Unused var warning under NO_TAINT_SUPPORT */
530 if (keysv || is_utf8) {
532 keysv = newSVpvn_utf8(key, klen, TRUE);
535 TAINT_set(SvTAINTED(keysv));
536 keysv = sv_2mortal(newSVsv(keysv));
537 mg_copy(MUTABLE_SV(hv), val, (char*)keysv, HEf_SVKEY);
539 mg_copy(MUTABLE_SV(hv), val, key, klen);
542 TAINT_IF(save_taint);
544 if (flags & HVhek_FREEKEY)
548 #ifdef ENV_IS_CASELESS
549 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
550 /* XXX This code isn't UTF8 clean. */
551 const char *keysave = key;
552 /* Will need to free this, so set FREEKEY flag. */
553 key = savepvn(key,klen);
554 key = (const char*)strupr((char*)key);
559 if (flags & HVhek_FREEKEY) {
562 flags |= HVhek_FREEKEY;
570 if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
571 #ifdef DYNAMIC_ENV_FETCH /* if it's an %ENV lookup, we may get it on the fly */
572 || (SvRMAGICAL((const SV *)hv)
573 && mg_find((const SV *)hv, PERL_MAGIC_env))
578 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
580 HvARRAY(hv) = (HE**)array;
582 #ifdef DYNAMIC_ENV_FETCH
583 else if (action & HV_FETCH_ISEXISTS) {
584 /* for an %ENV exists, if we do an insert it's by a recursive
585 store call, so avoid creating HvARRAY(hv) right now. */
589 /* XXX remove at some point? */
590 if (flags & HVhek_FREEKEY)
597 if (is_utf8 && !(flags & HVhek_KEYCANONICAL)) {
598 char * const keysave = (char *)key;
599 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
603 flags &= ~HVhek_UTF8;
604 if (key != keysave) {
605 if (flags & HVhek_FREEKEY)
607 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
608 /* If the caller calculated a hash, it was on the sequence of
609 octets that are the UTF-8 form. We've now changed the sequence
610 of octets stored to that of the equivalent byte representation,
611 so the hash we need is different. */
617 if (keysv && (SvIsCOW_shared_hash(keysv)))
618 hash = SvSHARED_HASH(keysv);
620 PERL_HASH(hash, key, klen);
623 masked_flags = (flags & HVhek_MASK);
625 #ifdef DYNAMIC_ENV_FETCH
626 if (!HvARRAY(hv)) entry = NULL;
630 entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
632 for (; entry; entry = HeNEXT(entry)) {
633 if (HeHASH(entry) != hash) /* strings can't be equal */
635 if (HeKLEN(entry) != (I32)klen)
637 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
639 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
642 if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
643 if (HeKFLAGS(entry) != masked_flags) {
644 /* We match if HVhek_UTF8 bit in our flags and hash key's
645 match. But if entry was set previously with HVhek_WASUTF8
646 and key now doesn't (or vice versa) then we should change
647 the key's flag, as this is assignment. */
648 if (HvSHAREKEYS(hv)) {
649 /* Need to swap the key we have for a key with the flags we
650 need. As keys are shared we can't just write to the
651 flag, so we share the new one, unshare the old one. */
652 HEK * const new_hek = share_hek_flags(key, klen, hash,
654 unshare_hek (HeKEY_hek(entry));
655 HeKEY_hek(entry) = new_hek;
657 else if (hv == PL_strtab) {
658 /* PL_strtab is usually the only hash without HvSHAREKEYS,
659 so putting this test here is cheap */
660 if (flags & HVhek_FREEKEY)
662 Perl_croak(aTHX_ S_strtab_error,
663 action & HV_FETCH_LVALUE ? "fetch" : "store");
666 HeKFLAGS(entry) = masked_flags;
667 if (masked_flags & HVhek_ENABLEHVKFLAGS)
670 if (HeVAL(entry) == &PL_sv_placeholder) {
671 /* yes, can store into placeholder slot */
672 if (action & HV_FETCH_LVALUE) {
674 /* This preserves behaviour with the old hv_fetch
675 implementation which at this point would bail out
676 with a break; (at "if we find a placeholder, we
677 pretend we haven't found anything")
679 That break mean that if a placeholder were found, it
680 caused a call into hv_store, which in turn would
681 check magic, and if there is no magic end up pretty
682 much back at this point (in hv_store's code). */
685 /* LVAL fetch which actually needs a store. */
687 HvPLACEHOLDERS(hv)--;
690 if (val != &PL_sv_placeholder)
691 HvPLACEHOLDERS(hv)--;
694 } else if (action & HV_FETCH_ISSTORE) {
695 SvREFCNT_dec(HeVAL(entry));
698 } else if (HeVAL(entry) == &PL_sv_placeholder) {
699 /* if we find a placeholder, we pretend we haven't found
703 if (flags & HVhek_FREEKEY)
706 return entry ? (void *) &HeVAL(entry) : NULL;
710 #ifdef DYNAMIC_ENV_FETCH /* %ENV lookup? If so, try to fetch the value now */
711 if (!(action & HV_FETCH_ISSTORE)
712 && SvRMAGICAL((const SV *)hv)
713 && mg_find((const SV *)hv, PERL_MAGIC_env)) {
715 const char * const env = PerlEnv_ENVgetenv_len(key,&len);
717 sv = newSVpvn(env,len);
719 return hv_common(hv, keysv, key, klen, flags,
720 HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
726 if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
727 hv_notallowed(flags, key, klen,
728 "Attempt to access disallowed key '%"SVf"' in"
729 " a restricted hash");
731 if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
732 /* Not doing some form of store, so return failure. */
733 if (flags & HVhek_FREEKEY)
737 if (action & HV_FETCH_LVALUE) {
738 val = action & HV_FETCH_EMPTY_HE ? NULL : newSV(0);
740 /* At this point the old hv_fetch code would call to hv_store,
741 which in turn might do some tied magic. So we need to make that
742 magic check happen. */
743 /* gonna assign to this, so it better be there */
744 /* If a fetch-as-store fails on the fetch, then the action is to
745 recurse once into "hv_store". If we didn't do this, then that
746 recursive call would call the key conversion routine again.
747 However, as we replace the original key with the converted
748 key, this would result in a double conversion, which would show
749 up as a bug if the conversion routine is not idempotent. */
750 return hv_common(hv, keysv, key, klen, flags,
751 HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
753 /* XXX Surely that could leak if the fetch-was-store fails?
754 Just like the hv_fetch. */
758 /* Welcome to hv_store... */
761 /* Not sure if we can get here. I think the only case of oentry being
762 NULL is for %ENV with dynamic env fetch. But that should disappear
763 with magic in the previous code. */
766 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
768 HvARRAY(hv) = (HE**)array;
771 oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
774 /* share_hek_flags will do the free for us. This might be considered
777 HeKEY_hek(entry) = share_hek_flags(key, klen, hash, flags);
778 else if (hv == PL_strtab) {
779 /* PL_strtab is usually the only hash without HvSHAREKEYS, so putting
780 this test here is cheap */
781 if (flags & HVhek_FREEKEY)
783 Perl_croak(aTHX_ S_strtab_error,
784 action & HV_FETCH_LVALUE ? "fetch" : "store");
786 else /* gotta do the real thing */
787 HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
790 /* This logic semi-randomizes the insert order in a bucket.
791 * Either we insert into the top, or the slot below the top,
792 * making it harder to see if there is a collision. We also
793 * reset the iterator randomizer if there is one.
796 HvAUX(hv)->xhv_rand= (U32)PL_hash_rand_bits;
797 PL_hash_rand_bits += (PTRV)entry ^ hash; /* we don't bother to use ptr_hash here */
798 PL_hash_rand_bits= ROTL_UV(PL_hash_rand_bits,1);
799 if ( !*oentry || (PL_hash_rand_bits & 1) ) {
800 HeNEXT(entry) = *oentry;
803 HeNEXT(entry) = HeNEXT(*oentry);
804 HeNEXT(*oentry) = entry;
807 if (val == &PL_sv_placeholder)
808 HvPLACEHOLDERS(hv)++;
809 if (masked_flags & HVhek_ENABLEHVKFLAGS)
812 xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
813 if ( DO_HSPLIT(xhv) ) {
814 const STRLEN oldsize = xhv->xhv_max + 1;
815 const U32 items = (U32)HvPLACEHOLDERS_get(hv);
817 if (items /* hash has placeholders */
818 && !SvREADONLY(hv) /* but is not a restricted hash */) {
819 /* If this hash previously was a "restricted hash" and had
820 placeholders, but the "restricted" flag has been turned off,
821 then the placeholders no longer serve any useful purpose.
822 However, they have the downsides of taking up RAM, and adding
823 extra steps when finding used values. It's safe to clear them
824 at this point, even though Storable rebuilds restricted hashes by
825 putting in all the placeholders (first) before turning on the
826 readonly flag, because Storable always pre-splits the hash.
827 If we're lucky, then we may clear sufficient placeholders to
828 avoid needing to split the hash at all. */
829 clear_placeholders(hv, items);
831 hsplit(hv, oldsize, oldsize * 2);
833 hsplit(hv, oldsize, oldsize * 2);
837 return entry ? (void *) &HeVAL(entry) : NULL;
839 return (void *) entry;
843 S_hv_magic_check(HV *hv, bool *needs_copy, bool *needs_store)
845 const MAGIC *mg = SvMAGIC(hv);
847 PERL_ARGS_ASSERT_HV_MAGIC_CHECK;
852 if (isUPPER(mg->mg_type)) {
854 if (mg->mg_type == PERL_MAGIC_tied) {
855 *needs_store = FALSE;
856 return; /* We've set all there is to set. */
859 mg = mg->mg_moremagic;
864 =for apidoc hv_scalar
866 Evaluates the hash in scalar context and returns the result. Handles magic when the hash is tied.
872 Perl_hv_scalar(pTHX_ HV *hv)
876 PERL_ARGS_ASSERT_HV_SCALAR;
878 if (SvRMAGICAL(hv)) {
879 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_tied);
881 return magic_scalarpack(hv, mg);
885 if (HvTOTALKEYS((const HV *)hv))
886 Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
887 (long)HvFILL(hv), (long)HvMAX(hv) + 1);
895 =for apidoc hv_delete
897 Deletes a key/value pair in the hash. The value's SV is removed from
898 the hash, made mortal, and returned to the caller. The absolute
899 value of C<klen> is the length of the key. If C<klen> is negative the
900 key is assumed to be in UTF-8-encoded Unicode. The C<flags> value
901 will normally be zero; if set to G_DISCARD then NULL will be returned.
902 NULL will also be returned if the key is not found.
904 =for apidoc hv_delete_ent
906 Deletes a key/value pair in the hash. The value SV is removed from the hash,
907 made mortal, and returned to the caller. The C<flags> value will normally be
908 zero; if set to G_DISCARD then NULL will be returned. NULL will also be
909 returned if the key is not found. C<hash> can be a valid precomputed hash
910 value, or 0 to ask for it to be computed.
916 S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
917 int k_flags, I32 d_flags, U32 hash)
923 bool is_utf8 = (k_flags & HVhek_UTF8) ? TRUE : FALSE;
926 if (SvRMAGICAL(hv)) {
929 hv_magic_check (hv, &needs_copy, &needs_store);
933 entry = (HE *) hv_common(hv, keysv, key, klen,
934 k_flags & ~HVhek_FREEKEY,
935 HV_FETCH_LVALUE|HV_DISABLE_UVAR_XKEY,
937 sv = entry ? HeVAL(entry) : NULL;
943 if (mg_find(sv, PERL_MAGIC_tiedelem)) {
944 /* No longer an element */
945 sv_unmagic(sv, PERL_MAGIC_tiedelem);
948 return NULL; /* element cannot be deleted */
950 #ifdef ENV_IS_CASELESS
951 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
952 /* XXX This code isn't UTF8 clean. */
953 keysv = newSVpvn_flags(key, klen, SVs_TEMP);
954 if (k_flags & HVhek_FREEKEY) {
957 key = strupr(SvPVX(keysv));
966 xhv = (XPVHV*)SvANY(hv);
970 if (is_utf8 && !(k_flags & HVhek_KEYCANONICAL)) {
971 const char * const keysave = key;
972 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
975 k_flags |= HVhek_UTF8;
977 k_flags &= ~HVhek_UTF8;
978 if (key != keysave) {
979 if (k_flags & HVhek_FREEKEY) {
980 /* This shouldn't happen if our caller does what we expect,
981 but strictly the API allows it. */
984 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
986 HvHASKFLAGS_on(MUTABLE_SV(hv));
990 if (keysv && (SvIsCOW_shared_hash(keysv)))
991 hash = SvSHARED_HASH(keysv);
993 PERL_HASH(hash, key, klen);
996 masked_flags = (k_flags & HVhek_MASK);
998 oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
1000 for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
1002 U8 mro_changes = 0; /* 1 = isa; 2 = package moved */
1006 if (HeHASH(entry) != hash) /* strings can't be equal */
1008 if (HeKLEN(entry) != (I32)klen)
1010 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
1012 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
1015 if (hv == PL_strtab) {
1016 if (k_flags & HVhek_FREEKEY)
1018 Perl_croak(aTHX_ S_strtab_error, "delete");
1021 /* if placeholder is here, it's already been deleted.... */
1022 if (HeVAL(entry) == &PL_sv_placeholder) {
1023 if (k_flags & HVhek_FREEKEY)
1027 if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))
1028 && !SvIsCOW(HeVAL(entry))) {
1029 hv_notallowed(k_flags, key, klen,
1030 "Attempt to delete readonly key '%"SVf"' from"
1031 " a restricted hash");
1033 if (k_flags & HVhek_FREEKEY)
1036 /* If this is a stash and the key ends with ::, then someone is
1037 * deleting a package.
1039 if (HeVAL(entry) && HvENAME_get(hv)) {
1040 gv = (GV *)HeVAL(entry);
1041 if (keysv) key = SvPV(keysv, klen);
1043 (klen > 1 && key[klen-2] == ':' && key[klen-1] == ':')
1045 (klen == 1 && key[0] == ':')
1047 && (klen != 6 || hv!=PL_defstash || memNE(key,"main::",6))
1048 && SvTYPE(gv) == SVt_PVGV && (stash = GvHV((GV *)gv))
1049 && HvENAME_get(stash)) {
1050 /* A previous version of this code checked that the
1051 * GV was still in the symbol table by fetching the
1052 * GV with its name. That is not necessary (and
1053 * sometimes incorrect), as HvENAME cannot be set
1054 * on hv if it is not in the symtab. */
1056 /* Hang on to it for a bit. */
1057 SvREFCNT_inc_simple_void_NN(
1058 sv_2mortal((SV *)gv)
1061 else if (klen == 3 && strnEQ(key, "ISA", 3))
1065 sv = d_flags & G_DISCARD ? HeVAL(entry) : sv_2mortal(HeVAL(entry));
1066 HeVAL(entry) = &PL_sv_placeholder;
1068 /* deletion of method from stash */
1069 if (isGV(sv) && isGV_with_GP(sv) && GvCVu(sv)
1071 mro_method_changed_in(hv);
1075 * If a restricted hash, rather than really deleting the entry, put
1076 * a placeholder there. This marks the key as being "approved", so
1077 * we can still access via not-really-existing key without raising
1081 /* We'll be saving this slot, so the number of allocated keys
1082 * doesn't go down, but the number placeholders goes up */
1083 HvPLACEHOLDERS(hv)++;
1085 *oentry = HeNEXT(entry);
1086 if (SvOOK(hv) && entry == HvAUX(hv)->xhv_eiter /* HvEITER(hv) */)
1089 if (SvOOK(hv) && HvLAZYDEL(hv) &&
1090 entry == HeNEXT(HvAUX(hv)->xhv_eiter))
1091 HeNEXT(HvAUX(hv)->xhv_eiter) = HeNEXT(entry);
1092 hv_free_ent(hv, entry);
1094 xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
1095 if (xhv->xhv_keys == 0)
1096 HvHASKFLAGS_off(hv);
1099 if (d_flags & G_DISCARD) {
1104 if (mro_changes == 1) mro_isa_changed_in(hv);
1105 else if (mro_changes == 2)
1106 mro_package_moved(NULL, stash, gv, 1);
1110 if (SvREADONLY(hv)) {
1111 hv_notallowed(k_flags, key, klen,
1112 "Attempt to delete disallowed key '%"SVf"' from"
1113 " a restricted hash");
1116 if (k_flags & HVhek_FREEKEY)
1122 S_hsplit(pTHX_ HV *hv, STRLEN const oldsize, STRLEN newsize)
1126 char *a = (char*) HvARRAY(hv);
1129 PERL_ARGS_ASSERT_HSPLIT;
1131 /*PerlIO_printf(PerlIO_stderr(), "hsplit called for %p which had %d\n",
1132 (void*)hv, (int) oldsize);*/
1135 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1136 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1141 /* the idea of this is that we create a "random" value by hashing the address of
1142 * the array, we then use the low bit to decide if we insert at the top, or insert
1143 * second from top. After each such insert we rotate the hashed value. So we can
1144 * use the same hashed value over and over, and in normal build environments use
1145 * very few ops to do so. ROTL32() should produce a single machine operation. */
1146 PL_hash_rand_bits += ptr_hash((PTRV)a);
1147 PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,1);
1150 struct xpvhv_aux *const dest
1151 = (struct xpvhv_aux*) &a[newsize * sizeof(HE*)];
1152 Move(&a[oldsize * sizeof(HE*)], dest, 1, struct xpvhv_aux);
1153 /* we reset the iterator's xhv_rand as well, so they get a totally new ordering */
1154 dest->xhv_rand = (U32)PL_hash_rand_bits;
1158 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1159 HvMAX(hv) = --newsize;
1160 HvARRAY(hv) = (HE**) a;
1162 if (!HvTOTALKEYS(hv)) /* skip rest if no entries */
1167 HE **oentry = aep + i;
1170 if (!entry) /* non-existent */
1173 U32 j = (HeHASH(entry) & newsize);
1175 *oentry = HeNEXT(entry);
1176 /* if the target cell is empty insert to top, otherwise
1177 * rotate the bucket rand 1 bit, and use the new low bit
1178 * to decide if we insert at top, or next from top.
1179 * IOW, we rotate only if we are dealing with colliding
1181 if (!aep[j] || ((PL_hash_rand_bits= ROTL_UV(PL_hash_rand_bits,1)) & 1)) {
1182 HeNEXT(entry) = aep[j];
1185 HeNEXT(entry)= HeNEXT(aep[j]);
1186 HeNEXT(aep[j])= entry;
1190 oentry = &HeNEXT(entry);
1194 } while (i++ < oldsize);
1198 Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
1201 XPVHV* xhv = (XPVHV*)SvANY(hv);
1202 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1206 PERL_ARGS_ASSERT_HV_KSPLIT;
1208 newsize = (I32) newmax; /* possible truncation here */
1209 if (newsize != newmax || newmax <= oldsize)
1211 while ((newsize & (1 + ~newsize)) != newsize) {
1212 newsize &= ~(newsize & (1 + ~newsize)); /* get proper power of 2 */
1214 if (newsize < newmax)
1216 if (newsize < newmax)
1217 return; /* overflow detection */
1219 a = (char *) HvARRAY(hv);
1221 hsplit(hv, oldsize, newsize);
1223 Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1224 xhv->xhv_max = --newsize;
1225 HvARRAY(hv) = (HE **) a;
1230 Perl_newHVhv(pTHX_ HV *ohv)
1233 HV * const hv = newHV();
1236 if (!ohv || (!HvTOTALKEYS(ohv) && !SvMAGICAL((const SV *)ohv)))
1238 hv_max = HvMAX(ohv);
1240 if (!SvMAGICAL((const SV *)ohv)) {
1241 /* It's an ordinary hash, so copy it fast. AMS 20010804 */
1243 const bool shared = !!HvSHAREKEYS(ohv);
1244 HE **ents, ** const oents = (HE **)HvARRAY(ohv);
1246 Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
1249 /* In each bucket... */
1250 for (i = 0; i <= hv_max; i++) {
1252 HE *oent = oents[i];
1259 /* Copy the linked list of entries. */
1260 for (; oent; oent = HeNEXT(oent)) {
1261 const U32 hash = HeHASH(oent);
1262 const char * const key = HeKEY(oent);
1263 const STRLEN len = HeKLEN(oent);
1264 const int flags = HeKFLAGS(oent);
1265 HE * const ent = new_HE();
1266 SV *const val = HeVAL(oent);
1268 HeVAL(ent) = SvIMMORTAL(val) ? val : newSVsv(val);
1270 = shared ? share_hek_flags(key, len, hash, flags)
1271 : save_hek_flags(key, len, hash, flags);
1282 HvTOTALKEYS(hv) = HvTOTALKEYS(ohv);
1286 /* Iterate over ohv, copying keys and values one at a time. */
1288 const I32 riter = HvRITER_get(ohv);
1289 HE * const eiter = HvEITER_get(ohv);
1290 STRLEN hv_fill = HvFILL(ohv);
1292 /* Can we use fewer buckets? (hv_max is always 2^n-1) */
1293 while (hv_max && hv_max + 1 >= hv_fill * 2)
1294 hv_max = hv_max / 2;
1298 while ((entry = hv_iternext_flags(ohv, 0))) {
1299 SV *val = hv_iterval(ohv,entry);
1300 SV * const keysv = HeSVKEY(entry);
1301 val = SvIMMORTAL(val) ? val : newSVsv(val);
1303 (void)hv_store_ent(hv, keysv, val, 0);
1305 (void)hv_store_flags(hv, HeKEY(entry), HeKLEN(entry), val,
1306 HeHASH(entry), HeKFLAGS(entry));
1308 HvRITER_set(ohv, riter);
1309 HvEITER_set(ohv, eiter);
1316 =for apidoc Am|HV *|hv_copy_hints_hv|HV *ohv
1318 A specialised version of L</newHVhv> for copying C<%^H>. I<ohv> must be
1319 a pointer to a hash (which may have C<%^H> magic, but should be generally
1320 non-magical), or C<NULL> (interpreted as an empty hash). The content
1321 of I<ohv> is copied to a new hash, which has the C<%^H>-specific magic
1322 added to it. A pointer to the new hash is returned.
1328 Perl_hv_copy_hints_hv(pTHX_ HV *const ohv)
1330 HV * const hv = newHV();
1333 STRLEN hv_max = HvMAX(ohv);
1334 STRLEN hv_fill = HvFILL(ohv);
1336 const I32 riter = HvRITER_get(ohv);
1337 HE * const eiter = HvEITER_get(ohv);
1342 while (hv_max && hv_max + 1 >= hv_fill * 2)
1343 hv_max = hv_max / 2;
1347 while ((entry = hv_iternext_flags(ohv, 0))) {
1348 SV *const sv = newSVsv(hv_iterval(ohv,entry));
1349 SV *heksv = HeSVKEY(entry);
1350 if (!heksv && sv) heksv = newSVhek(HeKEY_hek(entry));
1351 if (sv) sv_magic(sv, NULL, PERL_MAGIC_hintselem,
1352 (char *)heksv, HEf_SVKEY);
1353 if (heksv == HeSVKEY(entry))
1354 (void)hv_store_ent(hv, heksv, sv, 0);
1356 (void)hv_common(hv, heksv, HeKEY(entry), HeKLEN(entry),
1357 HeKFLAGS(entry), HV_FETCH_ISSTORE|HV_FETCH_JUST_SV, sv, HeHASH(entry));
1358 SvREFCNT_dec_NN(heksv);
1361 HvRITER_set(ohv, riter);
1362 HvEITER_set(ohv, eiter);
1364 SvREFCNT_inc_simple_void_NN(hv);
1367 hv_magic(hv, NULL, PERL_MAGIC_hints);
1371 /* like hv_free_ent, but returns the SV rather than freeing it */
1373 S_hv_free_ent_ret(pTHX_ HV *hv, HE *entry)
1378 PERL_ARGS_ASSERT_HV_FREE_ENT_RET;
1381 if (HeKLEN(entry) == HEf_SVKEY) {
1382 SvREFCNT_dec(HeKEY_sv(entry));
1383 Safefree(HeKEY_hek(entry));
1385 else if (HvSHAREKEYS(hv))
1386 unshare_hek(HeKEY_hek(entry));
1388 Safefree(HeKEY_hek(entry));
1395 Perl_hv_free_ent(pTHX_ HV *hv, HE *entry)
1400 PERL_ARGS_ASSERT_HV_FREE_ENT;
1404 val = hv_free_ent_ret(hv, entry);
1410 Perl_hv_delayfree_ent(pTHX_ HV *hv, HE *entry)
1414 PERL_ARGS_ASSERT_HV_DELAYFREE_ENT;
1418 /* SvREFCNT_inc to counter the SvREFCNT_dec in hv_free_ent */
1419 sv_2mortal(SvREFCNT_inc(HeVAL(entry))); /* free between statements */
1420 if (HeKLEN(entry) == HEf_SVKEY) {
1421 sv_2mortal(SvREFCNT_inc(HeKEY_sv(entry)));
1423 hv_free_ent(hv, entry);
1427 =for apidoc hv_clear
1429 Frees the all the elements of a hash, leaving it empty.
1430 The XS equivalent of C<%hash = ()>. See also L</hv_undef>.
1432 If any destructors are triggered as a result, the hv itself may
1439 Perl_hv_clear(pTHX_ HV *hv)
1446 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1448 xhv = (XPVHV*)SvANY(hv);
1451 SAVEFREESV(SvREFCNT_inc_simple_NN(hv));
1452 if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
1453 /* restricted hash: convert all keys to placeholders */
1455 for (i = 0; i <= xhv->xhv_max; i++) {
1456 HE *entry = (HvARRAY(hv))[i];
1457 for (; entry; entry = HeNEXT(entry)) {
1458 /* not already placeholder */
1459 if (HeVAL(entry) != &PL_sv_placeholder) {
1461 if (SvREADONLY(HeVAL(entry)) && !SvIsCOW(HeVAL(entry))) {
1462 SV* const keysv = hv_iterkeysv(entry);
1463 Perl_croak_nocontext(
1464 "Attempt to delete readonly key '%"SVf"' from a restricted hash",
1467 SvREFCNT_dec_NN(HeVAL(entry));
1469 HeVAL(entry) = &PL_sv_placeholder;
1470 HvPLACEHOLDERS(hv)++;
1477 HvPLACEHOLDERS_set(hv, 0);
1480 mg_clear(MUTABLE_SV(hv));
1482 HvHASKFLAGS_off(hv);
1486 mro_isa_changed_in(hv);
1487 HvEITER_set(hv, NULL);
1493 =for apidoc hv_clear_placeholders
1495 Clears any placeholders from a hash. If a restricted hash has any of its keys
1496 marked as readonly and the key is subsequently deleted, the key is not actually
1497 deleted but is marked by assigning it a value of &PL_sv_placeholder. This tags
1498 it so it will be ignored by future operations such as iterating over the hash,
1499 but will still allow the hash to have a value reassigned to the key at some
1500 future point. This function clears any such placeholder keys from the hash.
1501 See Hash::Util::lock_keys() for an example of its use.
1507 Perl_hv_clear_placeholders(pTHX_ HV *hv)
1510 const U32 items = (U32)HvPLACEHOLDERS_get(hv);
1512 PERL_ARGS_ASSERT_HV_CLEAR_PLACEHOLDERS;
1515 clear_placeholders(hv, items);
1519 S_clear_placeholders(pTHX_ HV *hv, U32 items)
1524 PERL_ARGS_ASSERT_CLEAR_PLACEHOLDERS;
1531 /* Loop down the linked list heads */
1532 HE **oentry = &(HvARRAY(hv))[i];
1535 while ((entry = *oentry)) {
1536 if (HeVAL(entry) == &PL_sv_placeholder) {
1537 *oentry = HeNEXT(entry);
1538 if (entry == HvEITER_get(hv))
1541 if (SvOOK(hv) && HvLAZYDEL(hv) &&
1542 entry == HeNEXT(HvAUX(hv)->xhv_eiter))
1543 HeNEXT(HvAUX(hv)->xhv_eiter) = HeNEXT(entry);
1544 hv_free_ent(hv, entry);
1549 HvTOTALKEYS(hv) -= (IV)HvPLACEHOLDERS_get(hv);
1550 if (HvUSEDKEYS(hv) == 0)
1551 HvHASKFLAGS_off(hv);
1552 HvPLACEHOLDERS_set(hv, 0);
1556 oentry = &HeNEXT(entry);
1560 /* You can't get here, hence assertion should always fail. */
1561 assert (items == 0);
1566 S_hfreeentries(pTHX_ HV *hv)
1569 XPVHV * const xhv = (XPVHV*)SvANY(hv);
1572 PERL_ARGS_ASSERT_HFREEENTRIES;
1574 while ((sv = Perl_hfree_next_entry(aTHX_ hv, &index))||xhv->xhv_keys) {
1580 /* hfree_next_entry()
1581 * For use only by S_hfreeentries() and sv_clear().
1582 * Delete the next available HE from hv and return the associated SV.
1583 * Returns null on empty hash. Nevertheless null is not a reliable
1584 * indicator that the hash is empty, as the deleted entry may have a
1586 * indexp is a pointer to the current index into HvARRAY. The index should
1587 * initially be set to 0. hfree_next_entry() may update it. */
1590 Perl_hfree_next_entry(pTHX_ HV *hv, STRLEN *indexp)
1592 struct xpvhv_aux *iter;
1596 STRLEN orig_index = *indexp;
1599 PERL_ARGS_ASSERT_HFREE_NEXT_ENTRY;
1601 if (SvOOK(hv) && ((iter = HvAUX(hv)))
1602 && ((entry = iter->xhv_eiter)) )
1604 /* the iterator may get resurrected after each
1605 * destructor call, so check each time */
1606 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1608 hv_free_ent(hv, entry);
1609 /* warning: at this point HvARRAY may have been
1610 * re-allocated, HvMAX changed etc */
1612 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1613 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
1614 iter->xhv_last_rand = iter->xhv_rand;
1617 if (!((XPVHV*)SvANY(hv))->xhv_keys)
1620 array = HvARRAY(hv);
1622 while ( ! ((entry = array[*indexp])) ) {
1623 if ((*indexp)++ >= HvMAX(hv))
1625 assert(*indexp != orig_index);
1627 array[*indexp] = HeNEXT(entry);
1628 ((XPVHV*) SvANY(hv))->xhv_keys--;
1630 if ( PL_phase != PERL_PHASE_DESTRUCT && HvENAME(hv)
1631 && HeVAL(entry) && isGV(HeVAL(entry))
1632 && GvHV(HeVAL(entry)) && HvENAME(GvHV(HeVAL(entry)))
1635 const char * const key = HePV(entry,klen);
1636 if ((klen > 1 && key[klen-1]==':' && key[klen-2]==':')
1637 || (klen == 1 && key[0] == ':')) {
1639 NULL, GvHV(HeVAL(entry)),
1640 (GV *)HeVAL(entry), 0
1644 return hv_free_ent_ret(hv, entry);
1649 =for apidoc hv_undef
1651 Undefines the hash. The XS equivalent of C<undef(%hash)>.
1653 As well as freeing all the elements of the hash (like hv_clear()), this
1654 also frees any auxiliary data and storage associated with the hash.
1656 If any destructors are triggered as a result, the hv itself may
1659 See also L</hv_clear>.
1665 Perl_hv_undef_flags(pTHX_ HV *hv, U32 flags)
1670 const bool save = !!SvREFCNT(hv);
1674 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1675 xhv = (XPVHV*)SvANY(hv);
1677 /* The name must be deleted before the call to hfreeeeentries so that
1678 CVs are anonymised properly. But the effective name must be pre-
1679 served until after that call (and only deleted afterwards if the
1680 call originated from sv_clear). For stashes with one name that is
1681 both the canonical name and the effective name, hv_name_set has to
1682 allocate an array for storing the effective name. We can skip that
1683 during global destruction, as it does not matter where the CVs point
1684 if they will be freed anyway. */
1685 /* note that the code following prior to hfreeentries is duplicated
1686 * in sv_clear(), and changes here should be done there too */
1687 if (PL_phase != PERL_PHASE_DESTRUCT && (name = HvNAME(hv))) {
1688 if (PL_stashcache) {
1689 DEBUG_o(Perl_deb(aTHX_ "hv_undef_flags clearing PL_stashcache for '%"
1690 HEKf"'\n", HvNAME_HEK(hv)));
1691 (void)hv_delete(PL_stashcache, name,
1692 HEK_UTF8(HvNAME_HEK(hv)) ? -HvNAMELEN_get(hv) : HvNAMELEN_get(hv),
1696 hv_name_set(hv, NULL, 0, 0);
1700 SAVEFREESV(SvREFCNT_inc_simple_NN(hv));
1704 struct xpvhv_aux * const aux = HvAUX(hv);
1705 struct mro_meta *meta;
1707 if ((name = HvENAME_get(hv))) {
1708 if (PL_phase != PERL_PHASE_DESTRUCT)
1709 mro_isa_changed_in(hv);
1710 if (PL_stashcache) {
1711 DEBUG_o(Perl_deb(aTHX_ "hv_undef_flags clearing PL_stashcache for effective name '%"
1712 HEKf"'\n", HvENAME_HEK(hv)));
1714 PL_stashcache, name,
1715 HEK_UTF8(HvENAME_HEK(hv)) ? -HvENAMELEN_get(hv) : HvENAMELEN_get(hv),
1721 /* If this call originated from sv_clear, then we must check for
1722 * effective names that need freeing, as well as the usual name. */
1724 if (flags & HV_NAME_SETALL ? !!aux->xhv_name_u.xhvnameu_name : !!name) {
1725 if (name && PL_stashcache) {
1726 DEBUG_o(Perl_deb(aTHX_ "hv_undef_flags clearing PL_stashcache for name '%"
1727 HEKf"'\n", HvNAME_HEK(hv)));
1728 (void)hv_delete(PL_stashcache, name, (HEK_UTF8(HvNAME_HEK(hv)) ? -HvNAMELEN_get(hv) : HvNAMELEN_get(hv)), G_DISCARD);
1730 hv_name_set(hv, NULL, 0, flags);
1732 if((meta = aux->xhv_mro_meta)) {
1733 if (meta->mro_linear_all) {
1734 SvREFCNT_dec_NN(meta->mro_linear_all);
1735 /* mro_linear_current is just acting as a shortcut pointer,
1739 /* Only the current MRO is stored, so this owns the data.
1741 SvREFCNT_dec(meta->mro_linear_current);
1742 SvREFCNT_dec(meta->mro_nextmethod);
1743 SvREFCNT_dec(meta->isa);
1745 aux->xhv_mro_meta = NULL;
1747 SvREFCNT_dec(aux->xhv_super);
1748 if (!aux->xhv_name_u.xhvnameu_name && ! aux->xhv_backreferences)
1749 SvFLAGS(hv) &= ~SVf_OOK;
1752 Safefree(HvARRAY(hv));
1753 xhv->xhv_max = 7; /* HvMAX(hv) = 7 (it's a normal hash) */
1756 /* if we're freeing the HV, the SvMAGIC field has been reused for
1757 * other purposes, and so there can't be any placeholder magic */
1759 HvPLACEHOLDERS_set(hv, 0);
1762 mg_clear(MUTABLE_SV(hv));
1769 Returns the number of hash buckets that happen to be in use. This function is
1770 wrapped by the macro C<HvFILL>.
1772 Previously this value was stored in the HV structure, rather than being
1773 calculated on demand.
1779 Perl_hv_fill(pTHX_ HV const *const hv)
1782 HE **ents = HvARRAY(hv);
1784 PERL_ARGS_ASSERT_HV_FILL;
1787 HE *const *const last = ents + HvMAX(hv);
1788 count = last + 1 - ents;
1793 } while (++ents <= last);
1798 /* hash a pointer to a U32 - Used in the hash traversal randomization
1799 * and bucket order randomization code
1801 * this code was derived from Sereal, which was derived from autobox.
1804 PERL_STATIC_INLINE U32 S_ptr_hash(PTRV u) {
1807 * This is one of Thomas Wang's hash functions for 64-bit integers from:
1808 * http://www.concentric.net/~Ttwang/tech/inthash.htm
1810 u = (~u) + (u << 18);
1818 * This is one of Bob Jenkins' hash functions for 32-bit integers
1819 * from: http://burtleburtle.net/bob/hash/integer.html
1821 u = (u + 0x7ed55d16) + (u << 12);
1822 u = (u ^ 0xc761c23c) ^ (u >> 19);
1823 u = (u + 0x165667b1) + (u << 5);
1824 u = (u + 0xd3a2646c) ^ (u << 9);
1825 u = (u + 0xfd7046c5) + (u << 3);
1826 u = (u ^ 0xb55a4f09) ^ (u >> 16);
1832 static struct xpvhv_aux*
1833 S_hv_auxinit(pTHX_ HV *hv) {
1834 struct xpvhv_aux *iter;
1837 PERL_ARGS_ASSERT_HV_AUXINIT;
1841 Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1842 + sizeof(struct xpvhv_aux), char);
1844 array = (char *) HvARRAY(hv);
1845 Renew(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1846 + sizeof(struct xpvhv_aux), char);
1848 HvARRAY(hv) = (HE**)array;
1850 PL_hash_rand_bits += ptr_hash((PTRV)array);
1851 PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,1);
1853 iter->xhv_rand = (U32)PL_hash_rand_bits;
1858 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1859 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
1860 iter->xhv_last_rand = iter->xhv_rand;
1861 iter->xhv_name_u.xhvnameu_name = 0;
1862 iter->xhv_name_count = 0;
1863 iter->xhv_backreferences = 0;
1864 iter->xhv_mro_meta = NULL;
1865 iter->xhv_super = NULL;
1870 =for apidoc hv_iterinit
1872 Prepares a starting point to traverse a hash table. Returns the number of
1873 keys in the hash (i.e. the same as C<HvUSEDKEYS(hv)>). The return value is
1874 currently only meaningful for hashes without tie magic.
1876 NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
1877 hash buckets that happen to be in use. If you still need that esoteric
1878 value, you can get it through the macro C<HvFILL(hv)>.
1885 Perl_hv_iterinit(pTHX_ HV *hv)
1887 PERL_ARGS_ASSERT_HV_ITERINIT;
1889 /* FIXME: Are we not NULL, or do we croak? Place bets now! */
1892 Perl_croak(aTHX_ "Bad hash");
1895 struct xpvhv_aux * const iter = HvAUX(hv);
1896 HE * const entry = iter->xhv_eiter; /* HvEITER(hv) */
1897 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1899 hv_free_ent(hv, entry);
1901 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1902 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
1903 iter->xhv_last_rand = iter->xhv_rand;
1908 /* used to be xhv->xhv_fill before 5.004_65 */
1909 return HvTOTALKEYS(hv);
1913 Perl_hv_riter_p(pTHX_ HV *hv) {
1914 struct xpvhv_aux *iter;
1916 PERL_ARGS_ASSERT_HV_RITER_P;
1919 Perl_croak(aTHX_ "Bad hash");
1921 iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
1922 return &(iter->xhv_riter);
1926 Perl_hv_eiter_p(pTHX_ HV *hv) {
1927 struct xpvhv_aux *iter;
1929 PERL_ARGS_ASSERT_HV_EITER_P;
1932 Perl_croak(aTHX_ "Bad hash");
1934 iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
1935 return &(iter->xhv_eiter);
1939 Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
1940 struct xpvhv_aux *iter;
1942 PERL_ARGS_ASSERT_HV_RITER_SET;
1945 Perl_croak(aTHX_ "Bad hash");
1953 iter = hv_auxinit(hv);
1955 iter->xhv_riter = riter;
1959 Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
1960 struct xpvhv_aux *iter;
1962 PERL_ARGS_ASSERT_HV_EITER_SET;
1965 Perl_croak(aTHX_ "Bad hash");
1970 /* 0 is the default so don't go malloc()ing a new structure just to
1975 iter = hv_auxinit(hv);
1977 iter->xhv_eiter = eiter;
1981 Perl_hv_name_set(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
1984 struct xpvhv_aux *iter;
1988 PERL_ARGS_ASSERT_HV_NAME_SET;
1991 Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
1995 if (iter->xhv_name_u.xhvnameu_name) {
1996 if(iter->xhv_name_count) {
1997 if(flags & HV_NAME_SETALL) {
1998 HEK ** const name = HvAUX(hv)->xhv_name_u.xhvnameu_names;
1999 HEK **hekp = name + (
2000 iter->xhv_name_count < 0
2001 ? -iter->xhv_name_count
2002 : iter->xhv_name_count
2004 while(hekp-- > name+1)
2005 unshare_hek_or_pvn(*hekp, 0, 0, 0);
2006 /* The first elem may be null. */
2007 if(*name) unshare_hek_or_pvn(*name, 0, 0, 0);
2009 spot = &iter->xhv_name_u.xhvnameu_name;
2010 iter->xhv_name_count = 0;
2013 if(iter->xhv_name_count > 0) {
2014 /* shift some things over */
2016 iter->xhv_name_u.xhvnameu_names, iter->xhv_name_count + 1, HEK *
2018 spot = iter->xhv_name_u.xhvnameu_names;
2019 spot[iter->xhv_name_count] = spot[1];
2021 iter->xhv_name_count = -(iter->xhv_name_count + 1);
2023 else if(*(spot = iter->xhv_name_u.xhvnameu_names)) {
2024 unshare_hek_or_pvn(*spot, 0, 0, 0);
2028 else if (flags & HV_NAME_SETALL) {
2029 unshare_hek_or_pvn(iter->xhv_name_u.xhvnameu_name, 0, 0, 0);
2030 spot = &iter->xhv_name_u.xhvnameu_name;
2033 HEK * const existing_name = iter->xhv_name_u.xhvnameu_name;
2034 Newx(iter->xhv_name_u.xhvnameu_names, 2, HEK *);
2035 iter->xhv_name_count = -2;
2036 spot = iter->xhv_name_u.xhvnameu_names;
2037 spot[1] = existing_name;
2040 else { spot = &iter->xhv_name_u.xhvnameu_name; iter->xhv_name_count = 0; }
2045 iter = hv_auxinit(hv);
2046 spot = &iter->xhv_name_u.xhvnameu_name;
2048 PERL_HASH(hash, name, len);
2049 *spot = name ? share_hek(name, flags & SVf_UTF8 ? -(I32)len : (I32)len, hash) : NULL;
2053 This is basically sv_eq_flags() in sv.c, but we avoid the magic
2058 hek_eq_pvn_flags(pTHX_ const HEK *hek, const char* pv, const I32 pvlen, const U32 flags) {
2059 if ( (HEK_UTF8(hek) ? 1 : 0) != (flags & SVf_UTF8 ? 1 : 0) ) {
2060 if (flags & SVf_UTF8)
2061 return (bytes_cmp_utf8(
2062 (const U8*)HEK_KEY(hek), HEK_LEN(hek),
2063 (const U8*)pv, pvlen) == 0);
2065 return (bytes_cmp_utf8(
2066 (const U8*)pv, pvlen,
2067 (const U8*)HEK_KEY(hek), HEK_LEN(hek)) == 0);
2070 return HEK_LEN(hek) == pvlen && ((HEK_KEY(hek) == pv)
2071 || memEQ(HEK_KEY(hek), pv, pvlen));
2075 =for apidoc hv_ename_add
2077 Adds a name to a stash's internal list of effective names. See
2080 This is called when a stash is assigned to a new location in the symbol
2087 Perl_hv_ename_add(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2090 struct xpvhv_aux *aux = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2093 PERL_ARGS_ASSERT_HV_ENAME_ADD;
2096 Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
2098 PERL_HASH(hash, name, len);
2100 if (aux->xhv_name_count) {
2101 HEK ** const xhv_name = aux->xhv_name_u.xhvnameu_names;
2102 I32 count = aux->xhv_name_count;
2103 HEK **hekp = xhv_name + (count < 0 ? -count : count);
2104 while (hekp-- > xhv_name)
2106 (HEK_UTF8(*hekp) || (flags & SVf_UTF8))
2107 ? hek_eq_pvn_flags(aTHX_ *hekp, name, (I32)len, flags)
2108 : (HEK_LEN(*hekp) == (I32)len && memEQ(HEK_KEY(*hekp), name, len))
2110 if (hekp == xhv_name && count < 0)
2111 aux->xhv_name_count = -count;
2114 if (count < 0) aux->xhv_name_count--, count = -count;
2115 else aux->xhv_name_count++;
2116 Renew(aux->xhv_name_u.xhvnameu_names, count + 1, HEK *);
2117 (aux->xhv_name_u.xhvnameu_names)[count] = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
2120 HEK *existing_name = aux->xhv_name_u.xhvnameu_name;
2123 (HEK_UTF8(existing_name) || (flags & SVf_UTF8))
2124 ? hek_eq_pvn_flags(aTHX_ existing_name, name, (I32)len, flags)
2125 : (HEK_LEN(existing_name) == (I32)len && memEQ(HEK_KEY(existing_name), name, len))
2128 Newx(aux->xhv_name_u.xhvnameu_names, 2, HEK *);
2129 aux->xhv_name_count = existing_name ? 2 : -2;
2130 *aux->xhv_name_u.xhvnameu_names = existing_name;
2131 (aux->xhv_name_u.xhvnameu_names)[1] = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
2136 =for apidoc hv_ename_delete
2138 Removes a name from a stash's internal list of effective names. If this is
2139 the name returned by C<HvENAME>, then another name in the list will take
2140 its place (C<HvENAME> will use it).
2142 This is called when a stash is deleted from the symbol table.
2148 Perl_hv_ename_delete(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2151 struct xpvhv_aux *aux;
2153 PERL_ARGS_ASSERT_HV_ENAME_DELETE;
2156 Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
2158 if (!SvOOK(hv)) return;
2161 if (!aux->xhv_name_u.xhvnameu_name) return;
2163 if (aux->xhv_name_count) {
2164 HEK ** const namep = aux->xhv_name_u.xhvnameu_names;
2165 I32 const count = aux->xhv_name_count;
2166 HEK **victim = namep + (count < 0 ? -count : count);
2167 while (victim-- > namep + 1)
2169 (HEK_UTF8(*victim) || (flags & SVf_UTF8))
2170 ? hek_eq_pvn_flags(aTHX_ *victim, name, (I32)len, flags)
2171 : (HEK_LEN(*victim) == (I32)len && memEQ(HEK_KEY(*victim), name, len))
2173 unshare_hek_or_pvn(*victim, 0, 0, 0);
2174 if (count < 0) ++aux->xhv_name_count;
2175 else --aux->xhv_name_count;
2177 (aux->xhv_name_count == 1 || aux->xhv_name_count == -1)
2179 ) { /* if there are none left */
2181 aux->xhv_name_u.xhvnameu_names = NULL;
2182 aux->xhv_name_count = 0;
2185 /* Move the last one back to fill the empty slot. It
2186 does not matter what order they are in. */
2187 *victim = *(namep + (count < 0 ? -count : count) - 1);
2192 count > 0 && (HEK_UTF8(*namep) || (flags & SVf_UTF8))
2193 ? hek_eq_pvn_flags(aTHX_ *namep, name, (I32)len, flags)
2194 : (HEK_LEN(*namep) == (I32)len && memEQ(HEK_KEY(*namep), name, len))
2196 aux->xhv_name_count = -count;
2200 (HEK_UTF8(aux->xhv_name_u.xhvnameu_name) || (flags & SVf_UTF8))
2201 ? hek_eq_pvn_flags(aTHX_ aux->xhv_name_u.xhvnameu_name, name, (I32)len, flags)
2202 : (HEK_LEN(aux->xhv_name_u.xhvnameu_name) == (I32)len &&
2203 memEQ(HEK_KEY(aux->xhv_name_u.xhvnameu_name), name, len))
2205 HEK * const namehek = aux->xhv_name_u.xhvnameu_name;
2206 Newx(aux->xhv_name_u.xhvnameu_names, 1, HEK *);
2207 *aux->xhv_name_u.xhvnameu_names = namehek;
2208 aux->xhv_name_count = -1;
2213 Perl_hv_backreferences_p(pTHX_ HV *hv) {
2214 struct xpvhv_aux * const iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2216 PERL_ARGS_ASSERT_HV_BACKREFERENCES_P;
2217 PERL_UNUSED_CONTEXT;
2219 return &(iter->xhv_backreferences);
2223 Perl_hv_kill_backrefs(pTHX_ HV *hv) {
2226 PERL_ARGS_ASSERT_HV_KILL_BACKREFS;
2231 av = HvAUX(hv)->xhv_backreferences;
2234 HvAUX(hv)->xhv_backreferences = 0;
2235 Perl_sv_kill_backrefs(aTHX_ MUTABLE_SV(hv), av);
2236 if (SvTYPE(av) == SVt_PVAV)
2237 SvREFCNT_dec_NN(av);
2242 hv_iternext is implemented as a macro in hv.h
2244 =for apidoc hv_iternext
2246 Returns entries from a hash iterator. See C<hv_iterinit>.
2248 You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
2249 iterator currently points to, without losing your place or invalidating your
2250 iterator. Note that in this case the current entry is deleted from the hash
2251 with your iterator holding the last reference to it. Your iterator is flagged
2252 to free the entry on the next call to C<hv_iternext>, so you must not discard
2253 your iterator immediately else the entry will leak - call C<hv_iternext> to
2254 trigger the resource deallocation.
2256 =for apidoc hv_iternext_flags
2258 Returns entries from a hash iterator. See C<hv_iterinit> and C<hv_iternext>.
2259 The C<flags> value will normally be zero; if HV_ITERNEXT_WANTPLACEHOLDERS is
2260 set the placeholders keys (for restricted hashes) will be returned in addition
2261 to normal keys. By default placeholders are automatically skipped over.
2262 Currently a placeholder is implemented with a value that is
2263 C<&PL_sv_placeholder>. Note that the implementation of placeholders and
2264 restricted hashes may change, and the implementation currently is
2265 insufficiently abstracted for any change to be tidy.
2271 Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
2278 struct xpvhv_aux *iter;
2280 PERL_ARGS_ASSERT_HV_ITERNEXT_FLAGS;
2283 Perl_croak(aTHX_ "Bad hash");
2285 xhv = (XPVHV*)SvANY(hv);
2288 /* Too many things (well, pp_each at least) merrily assume that you can
2289 call hv_iternext without calling hv_iterinit, so we'll have to deal
2295 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2296 if (SvMAGICAL(hv) && SvRMAGICAL(hv)) {
2297 if ( ( mg = mg_find((const SV *)hv, PERL_MAGIC_tied) ) ) {
2298 SV * const key = sv_newmortal();
2300 sv_setsv(key, HeSVKEY_force(entry));
2301 SvREFCNT_dec(HeSVKEY(entry)); /* get rid of previous key */
2302 HeSVKEY_set(entry, NULL);
2308 /* one HE per MAGICAL hash */
2309 iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
2310 HvLAZYDEL_on(hv); /* make sure entry gets freed */
2312 Newxz(k, HEK_BASESIZE + sizeof(const SV *), char);
2314 HeKEY_hek(entry) = hek;
2315 HeKLEN(entry) = HEf_SVKEY;
2317 magic_nextpack(MUTABLE_SV(hv),mg,key);
2319 /* force key to stay around until next time */
2320 HeSVKEY_set(entry, SvREFCNT_inc_simple_NN(key));
2321 return entry; /* beware, hent_val is not set */
2323 SvREFCNT_dec(HeVAL(entry));
2324 Safefree(HeKEY_hek(entry));
2326 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
2331 #if defined(DYNAMIC_ENV_FETCH) && !defined(__riscos__) /* set up %ENV for iteration */
2332 if (!entry && SvRMAGICAL((const SV *)hv)
2333 && mg_find((const SV *)hv, PERL_MAGIC_env)) {
2336 /* The prime_env_iter() on VMS just loaded up new hash values
2337 * so the iteration count needs to be reset back to the beginning
2341 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2346 /* hv_iterinit now ensures this. */
2347 assert (HvARRAY(hv));
2349 /* At start of hash, entry is NULL. */
2352 entry = HeNEXT(entry);
2353 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2355 * Skip past any placeholders -- don't want to include them in
2358 while (entry && HeVAL(entry) == &PL_sv_placeholder) {
2359 entry = HeNEXT(entry);
2363 if (iter->xhv_last_rand != iter->xhv_rand) {
2364 if (iter->xhv_riter != -1) {
2365 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
2366 "Use of each() on hash after insertion without resetting hash iterator results in undefined behavior"
2370 iter->xhv_last_rand = iter->xhv_rand;
2373 /* Skip the entire loop if the hash is empty. */
2374 if ((flags & HV_ITERNEXT_WANTPLACEHOLDERS)
2375 ? HvTOTALKEYS(hv) : HvUSEDKEYS(hv)) {
2377 /* OK. Come to the end of the current list. Grab the next one. */
2379 iter->xhv_riter++; /* HvRITER(hv)++ */
2380 if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
2381 /* There is no next one. End of the hash. */
2382 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2383 iter->xhv_last_rand = iter->xhv_rand;
2386 entry = (HvARRAY(hv))[(iter->xhv_riter ^ iter->xhv_rand) & xhv->xhv_max];
2388 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2389 /* If we have an entry, but it's a placeholder, don't count it.
2391 while (entry && HeVAL(entry) == &PL_sv_placeholder)
2392 entry = HeNEXT(entry);
2394 /* Will loop again if this linked list starts NULL
2395 (for HV_ITERNEXT_WANTPLACEHOLDERS)
2396 or if we run through it and find only placeholders. */
2400 iter->xhv_riter = -1;
2401 iter->xhv_last_rand = iter->xhv_rand;
2404 if (oldentry && HvLAZYDEL(hv)) { /* was deleted earlier? */
2406 hv_free_ent(hv, oldentry);
2409 iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
2414 =for apidoc hv_iterkey
2416 Returns the key from the current position of the hash iterator. See
2423 Perl_hv_iterkey(pTHX_ HE *entry, I32 *retlen)
2425 PERL_ARGS_ASSERT_HV_ITERKEY;
2427 if (HeKLEN(entry) == HEf_SVKEY) {
2429 char * const p = SvPV(HeKEY_sv(entry), len);
2434 *retlen = HeKLEN(entry);
2435 return HeKEY(entry);
2439 /* unlike hv_iterval(), this always returns a mortal copy of the key */
2441 =for apidoc hv_iterkeysv
2443 Returns the key as an C<SV*> from the current position of the hash
2444 iterator. The return value will always be a mortal copy of the key. Also
2451 Perl_hv_iterkeysv(pTHX_ HE *entry)
2453 PERL_ARGS_ASSERT_HV_ITERKEYSV;
2455 return sv_2mortal(newSVhek(HeKEY_hek(entry)));
2459 =for apidoc hv_iterval
2461 Returns the value from the current position of the hash iterator. See
2468 Perl_hv_iterval(pTHX_ HV *hv, HE *entry)
2470 PERL_ARGS_ASSERT_HV_ITERVAL;
2472 if (SvRMAGICAL(hv)) {
2473 if (mg_find((const SV *)hv, PERL_MAGIC_tied)) {
2474 SV* const sv = sv_newmortal();
2475 if (HeKLEN(entry) == HEf_SVKEY)
2476 mg_copy(MUTABLE_SV(hv), sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
2478 mg_copy(MUTABLE_SV(hv), sv, HeKEY(entry), HeKLEN(entry));
2482 return HeVAL(entry);
2486 =for apidoc hv_iternextsv
2488 Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2495 Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
2497 HE * const he = hv_iternext_flags(hv, 0);
2499 PERL_ARGS_ASSERT_HV_ITERNEXTSV;
2503 *key = hv_iterkey(he, retlen);
2504 return hv_iterval(hv, he);
2511 =for apidoc hv_magic
2513 Adds magic to a hash. See C<sv_magic>.
2518 /* possibly free a shared string if no one has access to it
2519 * len and hash must both be valid for str.
2522 Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
2524 unshare_hek_or_pvn (NULL, str, len, hash);
2529 Perl_unshare_hek(pTHX_ HEK *hek)
2532 unshare_hek_or_pvn(hek, NULL, 0, 0);
2535 /* possibly free a shared string if no one has access to it
2536 hek if non-NULL takes priority over the other 3, else str, len and hash
2537 are used. If so, len and hash must both be valid for str.
2540 S_unshare_hek_or_pvn(pTHX_ const HEK *hek, const char *str, I32 len, U32 hash)
2546 bool is_utf8 = FALSE;
2548 const char * const save = str;
2549 struct shared_he *he = NULL;
2552 /* Find the shared he which is just before us in memory. */
2553 he = (struct shared_he *)(((char *)hek)
2554 - STRUCT_OFFSET(struct shared_he,
2557 /* Assert that the caller passed us a genuine (or at least consistent)
2559 assert (he->shared_he_he.hent_hek == hek);
2561 if (he->shared_he_he.he_valu.hent_refcount - 1) {
2562 --he->shared_he_he.he_valu.hent_refcount;
2566 hash = HEK_HASH(hek);
2567 } else if (len < 0) {
2568 STRLEN tmplen = -len;
2570 /* See the note in hv_fetch(). --jhi */
2571 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2574 k_flags = HVhek_UTF8;
2576 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2579 /* what follows was the moral equivalent of:
2580 if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
2582 hv_delete(PL_strtab, str, len, G_DISCARD, hash);
2584 xhv = (XPVHV*)SvANY(PL_strtab);
2585 /* assert(xhv_array != 0) */
2586 oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2588 const HE *const he_he = &(he->shared_he_he);
2589 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2594 const int flags_masked = k_flags & HVhek_MASK;
2595 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2596 if (HeHASH(entry) != hash) /* strings can't be equal */
2598 if (HeKLEN(entry) != len)
2600 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2602 if (HeKFLAGS(entry) != flags_masked)
2609 if (--entry->he_valu.hent_refcount == 0) {
2610 *oentry = HeNEXT(entry);
2612 xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
2617 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
2618 "Attempt to free nonexistent shared string '%s'%s"
2620 hek ? HEK_KEY(hek) : str,
2621 ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
2622 if (k_flags & HVhek_FREEKEY)
2626 /* get a (constant) string ptr from the global string table
2627 * string will get added if it is not already there.
2628 * len and hash must both be valid for str.
2631 Perl_share_hek(pTHX_ const char *str, I32 len, U32 hash)
2633 bool is_utf8 = FALSE;
2635 const char * const save = str;
2637 PERL_ARGS_ASSERT_SHARE_HEK;
2640 STRLEN tmplen = -len;
2642 /* See the note in hv_fetch(). --jhi */
2643 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2645 /* If we were able to downgrade here, then than means that we were passed
2646 in a key which only had chars 0-255, but was utf8 encoded. */
2649 /* If we found we were able to downgrade the string to bytes, then
2650 we should flag that it needs upgrading on keys or each. Also flag
2651 that we need share_hek_flags to free the string. */
2654 PERL_HASH(hash, str, len);
2655 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2659 return share_hek_flags (str, len, hash, flags);
2663 S_share_hek_flags(pTHX_ const char *str, I32 len, U32 hash, int flags)
2667 const int flags_masked = flags & HVhek_MASK;
2668 const U32 hindex = hash & (I32) HvMAX(PL_strtab);
2669 XPVHV * const xhv = (XPVHV*)SvANY(PL_strtab);
2671 PERL_ARGS_ASSERT_SHARE_HEK_FLAGS;
2673 /* what follows is the moral equivalent of:
2675 if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
2676 hv_store(PL_strtab, str, len, NULL, hash);
2678 Can't rehash the shared string table, so not sure if it's worth
2679 counting the number of entries in the linked list
2682 /* assert(xhv_array != 0) */
2683 entry = (HvARRAY(PL_strtab))[hindex];
2684 for (;entry; entry = HeNEXT(entry)) {
2685 if (HeHASH(entry) != hash) /* strings can't be equal */
2687 if (HeKLEN(entry) != len)
2689 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2691 if (HeKFLAGS(entry) != flags_masked)
2697 /* What used to be head of the list.
2698 If this is NULL, then we're the first entry for this slot, which
2699 means we need to increate fill. */
2700 struct shared_he *new_entry;
2703 HE **const head = &HvARRAY(PL_strtab)[hindex];
2704 HE *const next = *head;
2706 /* We don't actually store a HE from the arena and a regular HEK.
2707 Instead we allocate one chunk of memory big enough for both,
2708 and put the HEK straight after the HE. This way we can find the
2709 HE directly from the HEK.
2712 Newx(k, STRUCT_OFFSET(struct shared_he,
2713 shared_he_hek.hek_key[0]) + len + 2, char);
2714 new_entry = (struct shared_he *)k;
2715 entry = &(new_entry->shared_he_he);
2716 hek = &(new_entry->shared_he_hek);
2718 Copy(str, HEK_KEY(hek), len, char);
2719 HEK_KEY(hek)[len] = 0;
2721 HEK_HASH(hek) = hash;
2722 HEK_FLAGS(hek) = (unsigned char)flags_masked;
2724 /* Still "point" to the HEK, so that other code need not know what
2726 HeKEY_hek(entry) = hek;
2727 entry->he_valu.hent_refcount = 0;
2728 HeNEXT(entry) = next;
2731 xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
2732 if (!next) { /* initial entry? */
2733 } else if ( DO_HSPLIT(xhv) ) {
2734 const STRLEN oldsize = xhv->xhv_max + 1;
2735 hsplit(PL_strtab, oldsize, oldsize * 2);
2739 ++entry->he_valu.hent_refcount;
2741 if (flags & HVhek_FREEKEY)
2744 return HeKEY_hek(entry);
2748 Perl_hv_placeholders_p(pTHX_ HV *hv)
2751 MAGIC *mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
2753 PERL_ARGS_ASSERT_HV_PLACEHOLDERS_P;
2756 mg = sv_magicext(MUTABLE_SV(hv), 0, PERL_MAGIC_rhash, 0, 0, 0);
2759 Perl_die(aTHX_ "panic: hv_placeholders_p");
2762 return &(mg->mg_len);
2767 Perl_hv_placeholders_get(pTHX_ const HV *hv)
2770 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
2772 PERL_ARGS_ASSERT_HV_PLACEHOLDERS_GET;
2774 return mg ? mg->mg_len : 0;
2778 Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
2781 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
2783 PERL_ARGS_ASSERT_HV_PLACEHOLDERS_SET;
2788 if (!sv_magicext(MUTABLE_SV(hv), 0, PERL_MAGIC_rhash, 0, 0, ph))
2789 Perl_die(aTHX_ "panic: hv_placeholders_set");
2791 /* else we don't need to add magic to record 0 placeholders. */
2795 S_refcounted_he_value(pTHX_ const struct refcounted_he *he)
2800 PERL_ARGS_ASSERT_REFCOUNTED_HE_VALUE;
2802 switch(he->refcounted_he_data[0] & HVrhek_typemask) {
2807 value = &PL_sv_placeholder;
2810 value = newSViv(he->refcounted_he_val.refcounted_he_u_iv);
2813 value = newSVuv(he->refcounted_he_val.refcounted_he_u_uv);
2816 case HVrhek_PV_UTF8:
2817 /* Create a string SV that directly points to the bytes in our
2819 value = newSV_type(SVt_PV);
2820 SvPV_set(value, (char *) he->refcounted_he_data + 1);
2821 SvCUR_set(value, he->refcounted_he_val.refcounted_he_u_len);
2822 /* This stops anything trying to free it */
2823 SvLEN_set(value, 0);
2825 SvREADONLY_on(value);
2826 if ((he->refcounted_he_data[0] & HVrhek_typemask) == HVrhek_PV_UTF8)
2830 Perl_croak(aTHX_ "panic: refcounted_he_value bad flags %"UVxf,
2831 (UV)he->refcounted_he_data[0]);
2837 =for apidoc m|HV *|refcounted_he_chain_2hv|const struct refcounted_he *c|U32 flags
2839 Generates and returns a C<HV *> representing the content of a
2840 C<refcounted_he> chain.
2841 I<flags> is currently unused and must be zero.
2846 Perl_refcounted_he_chain_2hv(pTHX_ const struct refcounted_he *chain, U32 flags)
2850 U32 placeholders, max;
2853 Perl_croak(aTHX_ "panic: refcounted_he_chain_2hv bad flags %"UVxf,
2856 /* We could chase the chain once to get an idea of the number of keys,
2857 and call ksplit. But for now we'll make a potentially inefficient
2858 hash with only 8 entries in its array. */
2863 Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(max + 1), char);
2864 HvARRAY(hv) = (HE**)array;
2870 U32 hash = chain->refcounted_he_hash;
2872 U32 hash = HEK_HASH(chain->refcounted_he_hek);
2874 HE **oentry = &((HvARRAY(hv))[hash & max]);
2875 HE *entry = *oentry;
2878 for (; entry; entry = HeNEXT(entry)) {
2879 if (HeHASH(entry) == hash) {
2880 /* We might have a duplicate key here. If so, entry is older
2881 than the key we've already put in the hash, so if they are
2882 the same, skip adding entry. */
2884 const STRLEN klen = HeKLEN(entry);
2885 const char *const key = HeKEY(entry);
2886 if (klen == chain->refcounted_he_keylen
2887 && (!!HeKUTF8(entry)
2888 == !!(chain->refcounted_he_data[0] & HVhek_UTF8))
2889 && memEQ(key, REF_HE_KEY(chain), klen))
2892 if (HeKEY_hek(entry) == chain->refcounted_he_hek)
2894 if (HeKLEN(entry) == HEK_LEN(chain->refcounted_he_hek)
2895 && HeKUTF8(entry) == HEK_UTF8(chain->refcounted_he_hek)
2896 && memEQ(HeKEY(entry), HEK_KEY(chain->refcounted_he_hek),
2907 = share_hek_flags(REF_HE_KEY(chain),
2908 chain->refcounted_he_keylen,
2909 chain->refcounted_he_hash,
2910 (chain->refcounted_he_data[0]
2911 & (HVhek_UTF8|HVhek_WASUTF8)));
2913 HeKEY_hek(entry) = share_hek_hek(chain->refcounted_he_hek);
2915 value = refcounted_he_value(chain);
2916 if (value == &PL_sv_placeholder)
2918 HeVAL(entry) = value;
2920 /* Link it into the chain. */
2921 HeNEXT(entry) = *oentry;
2927 chain = chain->refcounted_he_next;
2931 clear_placeholders(hv, placeholders);
2932 HvTOTALKEYS(hv) -= placeholders;
2935 /* We could check in the loop to see if we encounter any keys with key
2936 flags, but it's probably not worth it, as this per-hash flag is only
2937 really meant as an optimisation for things like Storable. */
2939 DEBUG_A(Perl_hv_assert(aTHX_ hv));
2945 =for apidoc m|SV *|refcounted_he_fetch_pvn|const struct refcounted_he *chain|const char *keypv|STRLEN keylen|U32 hash|U32 flags
2947 Search along a C<refcounted_he> chain for an entry with the key specified
2948 by I<keypv> and I<keylen>. If I<flags> has the C<REFCOUNTED_HE_KEY_UTF8>
2949 bit set, the key octets are interpreted as UTF-8, otherwise they
2950 are interpreted as Latin-1. I<hash> is a precomputed hash of the key
2951 string, or zero if it has not been precomputed. Returns a mortal scalar
2952 representing the value associated with the key, or C<&PL_sv_placeholder>
2953 if there is no value associated with the key.
2959 Perl_refcounted_he_fetch_pvn(pTHX_ const struct refcounted_he *chain,
2960 const char *keypv, STRLEN keylen, U32 hash, U32 flags)
2964 PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_PVN;
2966 if (flags & ~(REFCOUNTED_HE_KEY_UTF8|REFCOUNTED_HE_EXISTS))
2967 Perl_croak(aTHX_ "panic: refcounted_he_fetch_pvn bad flags %"UVxf,
2970 return &PL_sv_placeholder;
2971 if (flags & REFCOUNTED_HE_KEY_UTF8) {
2972 /* For searching purposes, canonicalise to Latin-1 where possible. */
2973 const char *keyend = keypv + keylen, *p;
2974 STRLEN nonascii_count = 0;
2975 for (p = keypv; p != keyend; p++) {
2978 if (!((c & 0xfe) == 0xc2 && ++p != keyend &&
2979 (((U8)*p) & 0xc0) == 0x80))
2980 goto canonicalised_key;
2984 if (nonascii_count) {
2986 const char *p = keypv, *keyend = keypv + keylen;
2987 keylen -= nonascii_count;
2988 Newx(q, keylen, char);
2991 for (; p != keyend; p++, q++) {
2994 ((c & 0x80) ? ((c & 0x03) << 6) | (((U8)*++p) & 0x3f) : c);
2997 flags &= ~REFCOUNTED_HE_KEY_UTF8;
2998 canonicalised_key: ;
3000 utf8_flag = (flags & REFCOUNTED_HE_KEY_UTF8) ? HVhek_UTF8 : 0;
3002 PERL_HASH(hash, keypv, keylen);
3004 for (; chain; chain = chain->refcounted_he_next) {
3007 hash == chain->refcounted_he_hash &&
3008 keylen == chain->refcounted_he_keylen &&
3009 memEQ(REF_HE_KEY(chain), keypv, keylen) &&
3010 utf8_flag == (chain->refcounted_he_data[0] & HVhek_UTF8)
3012 hash == HEK_HASH(chain->refcounted_he_hek) &&
3013 keylen == (STRLEN)HEK_LEN(chain->refcounted_he_hek) &&
3014 memEQ(HEK_KEY(chain->refcounted_he_hek), keypv, keylen) &&
3015 utf8_flag == (HEK_FLAGS(chain->refcounted_he_hek) & HVhek_UTF8)
3018 if (flags & REFCOUNTED_HE_EXISTS)
3019 return (chain->refcounted_he_data[0] & HVrhek_typemask)
3021 ? NULL : &PL_sv_yes;
3022 return sv_2mortal(refcounted_he_value(chain));
3025 return flags & REFCOUNTED_HE_EXISTS ? NULL : &PL_sv_placeholder;
3029 =for apidoc m|SV *|refcounted_he_fetch_pv|const struct refcounted_he *chain|const char *key|U32 hash|U32 flags
3031 Like L</refcounted_he_fetch_pvn>, but takes a nul-terminated string
3032 instead of a string/length pair.
3038 Perl_refcounted_he_fetch_pv(pTHX_ const struct refcounted_he *chain,
3039 const char *key, U32 hash, U32 flags)
3041 PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_PV;
3042 return refcounted_he_fetch_pvn(chain, key, strlen(key), hash, flags);
3046 =for apidoc m|SV *|refcounted_he_fetch_sv|const struct refcounted_he *chain|SV *key|U32 hash|U32 flags
3048 Like L</refcounted_he_fetch_pvn>, but takes a Perl scalar instead of a
3055 Perl_refcounted_he_fetch_sv(pTHX_ const struct refcounted_he *chain,
3056 SV *key, U32 hash, U32 flags)
3060 PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_SV;
3061 if (flags & REFCOUNTED_HE_KEY_UTF8)
3062 Perl_croak(aTHX_ "panic: refcounted_he_fetch_sv bad flags %"UVxf,
3064 keypv = SvPV_const(key, keylen);
3066 flags |= REFCOUNTED_HE_KEY_UTF8;
3067 if (!hash && SvIsCOW_shared_hash(key))
3068 hash = SvSHARED_HASH(key);
3069 return refcounted_he_fetch_pvn(chain, keypv, keylen, hash, flags);
3073 =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
3075 Creates a new C<refcounted_he>. This consists of a single key/value
3076 pair and a reference to an existing C<refcounted_he> chain (which may
3077 be empty), and thus forms a longer chain. When using the longer chain,
3078 the new key/value pair takes precedence over any entry for the same key
3079 further along the chain.
3081 The new key is specified by I<keypv> and I<keylen>. If I<flags> has
3082 the C<REFCOUNTED_HE_KEY_UTF8> bit set, the key octets are interpreted
3083 as UTF-8, otherwise they are interpreted as Latin-1. I<hash> is
3084 a precomputed hash of the key string, or zero if it has not been
3087 I<value> is the scalar value to store for this key. I<value> is copied
3088 by this function, which thus does not take ownership of any reference
3089 to it, and later changes to the scalar will not be reflected in the
3090 value visible in the C<refcounted_he>. Complex types of scalar will not
3091 be stored with referential integrity, but will be coerced to strings.
3092 I<value> may be either null or C<&PL_sv_placeholder> to indicate that no
3093 value is to be associated with the key; this, as with any non-null value,
3094 takes precedence over the existence of a value for the key further along
3097 I<parent> points to the rest of the C<refcounted_he> chain to be
3098 attached to the new C<refcounted_he>. This function takes ownership
3099 of one reference to I<parent>, and returns one reference to the new
3105 struct refcounted_he *
3106 Perl_refcounted_he_new_pvn(pTHX_ struct refcounted_he *parent,
3107 const char *keypv, STRLEN keylen, U32 hash, SV *value, U32 flags)
3110 STRLEN value_len = 0;
3111 const char *value_p = NULL;
3115 STRLEN key_offset = 1;
3116 struct refcounted_he *he;
3117 PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_PVN;
3119 if (!value || value == &PL_sv_placeholder) {
3120 value_type = HVrhek_delete;
3121 } else if (SvPOK(value)) {
3122 value_type = HVrhek_PV;
3123 } else if (SvIOK(value)) {
3124 value_type = SvUOK((const SV *)value) ? HVrhek_UV : HVrhek_IV;
3125 } else if (!SvOK(value)) {
3126 value_type = HVrhek_undef;
3128 value_type = HVrhek_PV;
3130 is_pv = value_type == HVrhek_PV;
3132 /* Do it this way so that the SvUTF8() test is after the SvPV, in case
3133 the value is overloaded, and doesn't yet have the UTF-8flag set. */
3134 value_p = SvPV_const(value, value_len);
3136 value_type = HVrhek_PV_UTF8;
3137 key_offset = value_len + 2;
3139 hekflags = value_type;
3141 if (flags & REFCOUNTED_HE_KEY_UTF8) {
3142 /* Canonicalise to Latin-1 where possible. */
3143 const char *keyend = keypv + keylen, *p;
3144 STRLEN nonascii_count = 0;
3145 for (p = keypv; p != keyend; p++) {
3148 if (!((c & 0xfe) == 0xc2 && ++p != keyend &&
3149 (((U8)*p) & 0xc0) == 0x80))
3150 goto canonicalised_key;
3154 if (nonascii_count) {
3156 const char *p = keypv, *keyend = keypv + keylen;
3157 keylen -= nonascii_count;
3158 Newx(q, keylen, char);
3161 for (; p != keyend; p++, q++) {
3164 ((c & 0x80) ? ((c & 0x03) << 6) | (((U8)*++p) & 0x3f) : c);
3167 flags &= ~REFCOUNTED_HE_KEY_UTF8;
3168 canonicalised_key: ;
3170 if (flags & REFCOUNTED_HE_KEY_UTF8)
3171 hekflags |= HVhek_UTF8;
3173 PERL_HASH(hash, keypv, keylen);
3176 he = (struct refcounted_he*)
3177 PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
3181 he = (struct refcounted_he*)
3182 PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
3186 he->refcounted_he_next = parent;
3189 Copy(value_p, he->refcounted_he_data + 1, value_len + 1, char);
3190 he->refcounted_he_val.refcounted_he_u_len = value_len;
3191 } else if (value_type == HVrhek_IV) {
3192 he->refcounted_he_val.refcounted_he_u_iv = SvIVX(value);
3193 } else if (value_type == HVrhek_UV) {
3194 he->refcounted_he_val.refcounted_he_u_uv = SvUVX(value);
3198 he->refcounted_he_hash = hash;
3199 he->refcounted_he_keylen = keylen;
3200 Copy(keypv, he->refcounted_he_data + key_offset, keylen, char);
3202 he->refcounted_he_hek = share_hek_flags(keypv, keylen, hash, hekflags);
3205 he->refcounted_he_data[0] = hekflags;
3206 he->refcounted_he_refcnt = 1;
3212 =for apidoc m|struct refcounted_he *|refcounted_he_new_pv|struct refcounted_he *parent|const char *key|U32 hash|SV *value|U32 flags
3214 Like L</refcounted_he_new_pvn>, but takes a nul-terminated string instead
3215 of a string/length pair.
3220 struct refcounted_he *
3221 Perl_refcounted_he_new_pv(pTHX_ struct refcounted_he *parent,
3222 const char *key, U32 hash, SV *value, U32 flags)
3224 PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_PV;
3225 return refcounted_he_new_pvn(parent, key, strlen(key), hash, value, flags);
3229 =for apidoc m|struct refcounted_he *|refcounted_he_new_sv|struct refcounted_he *parent|SV *key|U32 hash|SV *value|U32 flags
3231 Like L</refcounted_he_new_pvn>, but takes a Perl scalar instead of a
3237 struct refcounted_he *
3238 Perl_refcounted_he_new_sv(pTHX_ struct refcounted_he *parent,
3239 SV *key, U32 hash, SV *value, U32 flags)
3243 PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_SV;
3244 if (flags & REFCOUNTED_HE_KEY_UTF8)
3245 Perl_croak(aTHX_ "panic: refcounted_he_new_sv bad flags %"UVxf,
3247 keypv = SvPV_const(key, keylen);
3249 flags |= REFCOUNTED_HE_KEY_UTF8;
3250 if (!hash && SvIsCOW_shared_hash(key))
3251 hash = SvSHARED_HASH(key);
3252 return refcounted_he_new_pvn(parent, keypv, keylen, hash, value, flags);
3256 =for apidoc m|void|refcounted_he_free|struct refcounted_he *he
3258 Decrements the reference count of a C<refcounted_he> by one. If the
3259 reference count reaches zero the structure's memory is freed, which
3260 (recursively) causes a reduction of its parent C<refcounted_he>'s
3261 reference count. It is safe to pass a null pointer to this function:
3262 no action occurs in this case.
3268 Perl_refcounted_he_free(pTHX_ struct refcounted_he *he) {
3270 PERL_UNUSED_CONTEXT;
3273 struct refcounted_he *copy;
3277 new_count = --he->refcounted_he_refcnt;
3278 HINTS_REFCNT_UNLOCK;
3284 #ifndef USE_ITHREADS
3285 unshare_hek_or_pvn (he->refcounted_he_hek, 0, 0, 0);
3288 he = he->refcounted_he_next;
3289 PerlMemShared_free(copy);
3294 =for apidoc m|struct refcounted_he *|refcounted_he_inc|struct refcounted_he *he
3296 Increment the reference count of a C<refcounted_he>. The pointer to the
3297 C<refcounted_he> is also returned. It is safe to pass a null pointer
3298 to this function: no action occurs and a null pointer is returned.
3303 struct refcounted_he *
3304 Perl_refcounted_he_inc(pTHX_ struct refcounted_he *he)
3309 he->refcounted_he_refcnt++;
3310 HINTS_REFCNT_UNLOCK;
3316 =for apidoc cop_fetch_label
3318 Returns the label attached to a cop.
3319 The flags pointer may be set to C<SVf_UTF8> or 0.
3324 /* pp_entereval is aware that labels are stored with a key ':' at the top of
3327 Perl_cop_fetch_label(pTHX_ COP *const cop, STRLEN *len, U32 *flags) {
3328 struct refcounted_he *const chain = cop->cop_hints_hash;
3330 PERL_ARGS_ASSERT_COP_FETCH_LABEL;
3335 if (chain->refcounted_he_keylen != 1)
3337 if (*REF_HE_KEY(chain) != ':')
3340 if ((STRLEN)HEK_LEN(chain->refcounted_he_hek) != 1)
3342 if (*HEK_KEY(chain->refcounted_he_hek) != ':')
3345 /* Stop anyone trying to really mess us up by adding their own value for
3347 if ((chain->refcounted_he_data[0] & HVrhek_typemask) != HVrhek_PV
3348 && (chain->refcounted_he_data[0] & HVrhek_typemask) != HVrhek_PV_UTF8)
3352 *len = chain->refcounted_he_val.refcounted_he_u_len;
3354 *flags = ((chain->refcounted_he_data[0] & HVrhek_typemask)
3355 == HVrhek_PV_UTF8) ? SVf_UTF8 : 0;
3357 return chain->refcounted_he_data + 1;
3361 =for apidoc cop_store_label
3363 Save a label into a C<cop_hints_hash>. You need to set flags to C<SVf_UTF8>
3370 Perl_cop_store_label(pTHX_ COP *const cop, const char *label, STRLEN len,
3374 PERL_ARGS_ASSERT_COP_STORE_LABEL;
3376 if (flags & ~(SVf_UTF8))
3377 Perl_croak(aTHX_ "panic: cop_store_label illegal flag bits 0x%" UVxf,
3379 labelsv = newSVpvn_flags(label, len, SVs_TEMP);
3380 if (flags & SVf_UTF8)
3383 = refcounted_he_new_pvs(cop->cop_hints_hash, ":", labelsv, 0);
3387 =for apidoc hv_assert
3389 Check that a hash is in an internally consistent state.
3397 Perl_hv_assert(pTHX_ HV *hv)
3402 int placeholders = 0;
3405 const I32 riter = HvRITER_get(hv);
3406 HE *eiter = HvEITER_get(hv);
3408 PERL_ARGS_ASSERT_HV_ASSERT;
3410 (void)hv_iterinit(hv);
3412 while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
3413 /* sanity check the values */
3414 if (HeVAL(entry) == &PL_sv_placeholder)
3418 /* sanity check the keys */
3419 if (HeSVKEY(entry)) {
3420 NOOP; /* Don't know what to check on SV keys. */
3421 } else if (HeKUTF8(entry)) {
3423 if (HeKWASUTF8(entry)) {
3424 PerlIO_printf(Perl_debug_log,
3425 "hash key has both WASUTF8 and UTF8: '%.*s'\n",
3426 (int) HeKLEN(entry), HeKEY(entry));
3429 } else if (HeKWASUTF8(entry))
3432 if (!SvTIED_mg((const SV *)hv, PERL_MAGIC_tied)) {
3433 static const char bad_count[] = "Count %d %s(s), but hash reports %d\n";
3434 const int nhashkeys = HvUSEDKEYS(hv);
3435 const int nhashplaceholders = HvPLACEHOLDERS_get(hv);
3437 if (nhashkeys != real) {
3438 PerlIO_printf(Perl_debug_log, bad_count, real, "keys", nhashkeys );
3441 if (nhashplaceholders != placeholders) {
3442 PerlIO_printf(Perl_debug_log, bad_count, placeholders, "placeholder", nhashplaceholders );
3446 if (withflags && ! HvHASKFLAGS(hv)) {
3447 PerlIO_printf(Perl_debug_log,
3448 "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
3453 sv_dump(MUTABLE_SV(hv));
3455 HvRITER_set(hv, riter); /* Restore hash iterator state */
3456 HvEITER_set(hv, eiter);
3463 * c-indentation-style: bsd
3465 * indent-tabs-mode: nil
3468 * ex: set ts=8 sts=4 sw=4 et: