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 HV_MAX_LENGTH_BEFORE_SPLIT 14
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, register 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);
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 | (is_utf8 ? HVhek_UTF8 : 0),
403 xhv = (XPVHV*)SvANY(hv);
405 if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS))) {
406 if (mg_find((const SV *)hv, PERL_MAGIC_tied)
407 || SvGMAGICAL((const SV *)hv))
409 /* FIXME should be able to skimp on the HE/HEK here when
410 HV_FETCH_JUST_SV is true. */
412 keysv = newSVpvn_utf8(key, klen, is_utf8);
414 keysv = newSVsv(keysv);
417 mg_copy(MUTABLE_SV(hv), sv, (char *)keysv, HEf_SVKEY);
419 /* grab a fake HE/HEK pair from the pool or make a new one */
420 entry = PL_hv_fetch_ent_mh;
422 PL_hv_fetch_ent_mh = HeNEXT(entry);
426 Newx(k, HEK_BASESIZE + sizeof(const SV *), char);
427 HeKEY_hek(entry) = (HEK*)k;
429 HeNEXT(entry) = NULL;
430 HeSVKEY_set(entry, keysv);
432 sv_upgrade(sv, SVt_PVLV);
434 /* so we can free entry when freeing sv */
435 LvTARG(sv) = MUTABLE_SV(entry);
437 /* XXX remove at some point? */
438 if (flags & HVhek_FREEKEY)
442 return entry ? (void *) &HeVAL(entry) : NULL;
444 return (void *) entry;
446 #ifdef ENV_IS_CASELESS
447 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
449 for (i = 0; i < klen; ++i)
450 if (isLOWER(key[i])) {
451 /* Would be nice if we had a routine to do the
452 copy and upercase in a single pass through. */
453 const char * const nkey = strupr(savepvn(key,klen));
454 /* Note that this fetch is for nkey (the uppercased
455 key) whereas the store is for key (the original) */
456 void *result = hv_common(hv, NULL, nkey, klen,
457 HVhek_FREEKEY, /* free nkey */
458 0 /* non-LVAL fetch */
459 | HV_DISABLE_UVAR_XKEY
462 0 /* compute hash */);
463 if (!result && (action & HV_FETCH_LVALUE)) {
464 /* This call will free key if necessary.
465 Do it this way to encourage compiler to tail
467 result = hv_common(hv, keysv, key, klen, flags,
469 | HV_DISABLE_UVAR_XKEY
473 if (flags & HVhek_FREEKEY)
481 else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
482 if (mg_find((const SV *)hv, PERL_MAGIC_tied)
483 || SvGMAGICAL((const SV *)hv)) {
484 /* I don't understand why hv_exists_ent has svret and sv,
485 whereas hv_exists only had one. */
486 SV * const svret = sv_newmortal();
489 if (keysv || is_utf8) {
491 keysv = newSVpvn_utf8(key, klen, TRUE);
493 keysv = newSVsv(keysv);
495 mg_copy(MUTABLE_SV(hv), sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
497 mg_copy(MUTABLE_SV(hv), sv, key, klen);
499 if (flags & HVhek_FREEKEY)
501 magic_existspack(svret, mg_find(sv, PERL_MAGIC_tiedelem));
502 /* This cast somewhat evil, but I'm merely using NULL/
503 not NULL to return the boolean exists.
504 And I know hv is not NULL. */
505 return SvTRUE(svret) ? (void *)hv : NULL;
507 #ifdef ENV_IS_CASELESS
508 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
509 /* XXX This code isn't UTF8 clean. */
510 char * const keysave = (char * const)key;
511 /* Will need to free this, so set FREEKEY flag. */
512 key = savepvn(key,klen);
513 key = (const char*)strupr((char*)key);
518 if (flags & HVhek_FREEKEY) {
521 flags |= HVhek_FREEKEY;
525 else if (action & HV_FETCH_ISSTORE) {
528 hv_magic_check (hv, &needs_copy, &needs_store);
530 const bool save_taint = PL_tainted;
531 if (keysv || is_utf8) {
533 keysv = newSVpvn_utf8(key, klen, TRUE);
536 PL_tainted = SvTAINTED(keysv);
537 keysv = sv_2mortal(newSVsv(keysv));
538 mg_copy(MUTABLE_SV(hv), val, (char*)keysv, HEf_SVKEY);
540 mg_copy(MUTABLE_SV(hv), val, key, klen);
543 TAINT_IF(save_taint);
545 if (flags & HVhek_FREEKEY)
549 #ifdef ENV_IS_CASELESS
550 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
551 /* XXX This code isn't UTF8 clean. */
552 const char *keysave = key;
553 /* Will need to free this, so set FREEKEY flag. */
554 key = savepvn(key,klen);
555 key = (const char*)strupr((char*)key);
560 if (flags & HVhek_FREEKEY) {
563 flags |= HVhek_FREEKEY;
571 if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
572 #ifdef DYNAMIC_ENV_FETCH /* if it's an %ENV lookup, we may get it on the fly */
573 || (SvRMAGICAL((const SV *)hv)
574 && mg_find((const SV *)hv, PERL_MAGIC_env))
579 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
581 HvARRAY(hv) = (HE**)array;
583 #ifdef DYNAMIC_ENV_FETCH
584 else if (action & HV_FETCH_ISEXISTS) {
585 /* for an %ENV exists, if we do an insert it's by a recursive
586 store call, so avoid creating HvARRAY(hv) right now. */
590 /* XXX remove at some point? */
591 if (flags & HVhek_FREEKEY)
598 if (is_utf8 & !(flags & HVhek_KEYCANONICAL)) {
599 char * const keysave = (char *)key;
600 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
604 flags &= ~HVhek_UTF8;
605 if (key != keysave) {
606 if (flags & HVhek_FREEKEY)
608 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
609 /* If the caller calculated a hash, it was on the sequence of
610 octets that are the UTF-8 form. We've now changed the sequence
611 of octets stored to that of the equivalent byte representation,
612 so the hash we need is different. */
617 if (HvREHASH(hv) || (!hash && !(keysv && (SvIsCOW_shared_hash(keysv)))))
618 PERL_HASH_INTERNAL_(hash, key, klen, HvREHASH(hv));
620 hash = SvSHARED_HASH(keysv);
622 /* We don't have a pointer to the hv, so we have to replicate the
623 flag into every HEK, so that hv_iterkeysv can see it.
624 And yes, you do need this even though you are not "storing" because
625 you can flip the flags below if doing an lval lookup. (And that
626 was put in to give the semantics Andreas was expecting.) */
628 flags |= HVhek_REHASH;
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)];
639 for (; entry; entry = HeNEXT(entry)) {
640 if (HeHASH(entry) != hash) /* strings can't be equal */
642 if (HeKLEN(entry) != (I32)klen)
644 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
646 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
649 if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
650 if (HeKFLAGS(entry) != masked_flags) {
651 /* We match if HVhek_UTF8 bit in our flags and hash key's
652 match. But if entry was set previously with HVhek_WASUTF8
653 and key now doesn't (or vice versa) then we should change
654 the key's flag, as this is assignment. */
655 if (HvSHAREKEYS(hv)) {
656 /* Need to swap the key we have for a key with the flags we
657 need. As keys are shared we can't just write to the
658 flag, so we share the new one, unshare the old one. */
659 HEK * const new_hek = share_hek_flags(key, klen, hash,
661 unshare_hek (HeKEY_hek(entry));
662 HeKEY_hek(entry) = new_hek;
664 else if (hv == PL_strtab) {
665 /* PL_strtab is usually the only hash without HvSHAREKEYS,
666 so putting this test here is cheap */
667 if (flags & HVhek_FREEKEY)
669 Perl_croak(aTHX_ S_strtab_error,
670 action & HV_FETCH_LVALUE ? "fetch" : "store");
673 HeKFLAGS(entry) = masked_flags;
674 if (masked_flags & HVhek_ENABLEHVKFLAGS)
677 if (HeVAL(entry) == &PL_sv_placeholder) {
678 /* yes, can store into placeholder slot */
679 if (action & HV_FETCH_LVALUE) {
681 /* This preserves behaviour with the old hv_fetch
682 implementation which at this point would bail out
683 with a break; (at "if we find a placeholder, we
684 pretend we haven't found anything")
686 That break mean that if a placeholder were found, it
687 caused a call into hv_store, which in turn would
688 check magic, and if there is no magic end up pretty
689 much back at this point (in hv_store's code). */
692 /* LVAL fetch which actually needs a store. */
694 HvPLACEHOLDERS(hv)--;
697 if (val != &PL_sv_placeholder)
698 HvPLACEHOLDERS(hv)--;
701 } else if (action & HV_FETCH_ISSTORE) {
702 SvREFCNT_dec(HeVAL(entry));
705 } else if (HeVAL(entry) == &PL_sv_placeholder) {
706 /* if we find a placeholder, we pretend we haven't found
710 if (flags & HVhek_FREEKEY)
713 return entry ? (void *) &HeVAL(entry) : NULL;
717 #ifdef DYNAMIC_ENV_FETCH /* %ENV lookup? If so, try to fetch the value now */
718 if (!(action & HV_FETCH_ISSTORE)
719 && SvRMAGICAL((const SV *)hv)
720 && mg_find((const SV *)hv, PERL_MAGIC_env)) {
722 const char * const env = PerlEnv_ENVgetenv_len(key,&len);
724 sv = newSVpvn(env,len);
726 return hv_common(hv, keysv, key, klen, flags,
727 HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
733 if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
734 hv_notallowed(flags, key, klen,
735 "Attempt to access disallowed key '%"SVf"' in"
736 " a restricted hash");
738 if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
739 /* Not doing some form of store, so return failure. */
740 if (flags & HVhek_FREEKEY)
744 if (action & HV_FETCH_LVALUE) {
745 val = action & HV_FETCH_EMPTY_HE ? NULL : newSV(0);
747 /* At this point the old hv_fetch code would call to hv_store,
748 which in turn might do some tied magic. So we need to make that
749 magic check happen. */
750 /* gonna assign to this, so it better be there */
751 /* If a fetch-as-store fails on the fetch, then the action is to
752 recurse once into "hv_store". If we didn't do this, then that
753 recursive call would call the key conversion routine again.
754 However, as we replace the original key with the converted
755 key, this would result in a double conversion, which would show
756 up as a bug if the conversion routine is not idempotent. */
757 return hv_common(hv, keysv, key, klen, flags,
758 HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
760 /* XXX Surely that could leak if the fetch-was-store fails?
761 Just like the hv_fetch. */
765 /* Welcome to hv_store... */
768 /* Not sure if we can get here. I think the only case of oentry being
769 NULL is for %ENV with dynamic env fetch. But that should disappear
770 with magic in the previous code. */
773 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
775 HvARRAY(hv) = (HE**)array;
778 oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
781 /* share_hek_flags will do the free for us. This might be considered
784 HeKEY_hek(entry) = share_hek_flags(key, klen, hash, flags);
785 else if (hv == PL_strtab) {
786 /* PL_strtab is usually the only hash without HvSHAREKEYS, so putting
787 this test here is cheap */
788 if (flags & HVhek_FREEKEY)
790 Perl_croak(aTHX_ S_strtab_error,
791 action & HV_FETCH_LVALUE ? "fetch" : "store");
793 else /* gotta do the real thing */
794 HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
796 HeNEXT(entry) = *oentry;
799 if (val == &PL_sv_placeholder)
800 HvPLACEHOLDERS(hv)++;
801 if (masked_flags & HVhek_ENABLEHVKFLAGS)
805 const HE *counter = HeNEXT(entry);
807 xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
808 if (!counter) { /* initial entry? */
809 } else if (xhv->xhv_keys > xhv->xhv_max) {
810 /* Use only the old HvUSEDKEYS(hv) > HvMAX(hv) condition to limit
811 bucket splits on a rehashed hash, as we're not going to
812 split it again, and if someone is lucky (evil) enough to
813 get all the keys in one list they could exhaust our memory
814 as we repeatedly double the number of buckets on every
815 entry. Linear search feels a less worse thing to do. */
817 } else if(!HvREHASH(hv)) {
820 while ((counter = HeNEXT(counter)))
823 if (n_links > HV_MAX_LENGTH_BEFORE_SPLIT) {
830 return entry ? (void *) &HeVAL(entry) : NULL;
832 return (void *) entry;
836 S_hv_magic_check(HV *hv, bool *needs_copy, bool *needs_store)
838 const MAGIC *mg = SvMAGIC(hv);
840 PERL_ARGS_ASSERT_HV_MAGIC_CHECK;
845 if (isUPPER(mg->mg_type)) {
847 if (mg->mg_type == PERL_MAGIC_tied) {
848 *needs_store = FALSE;
849 return; /* We've set all there is to set. */
852 mg = mg->mg_moremagic;
857 =for apidoc hv_scalar
859 Evaluates the hash in scalar context and returns the result. Handles magic when the hash is tied.
865 Perl_hv_scalar(pTHX_ HV *hv)
869 PERL_ARGS_ASSERT_HV_SCALAR;
871 if (SvRMAGICAL(hv)) {
872 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_tied);
874 return magic_scalarpack(hv, mg);
878 if (HvTOTALKEYS((const HV *)hv))
879 Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
880 (long)HvFILL(hv), (long)HvMAX(hv) + 1);
888 =for apidoc hv_delete
890 Deletes a key/value pair in the hash. The value's SV is removed from
891 the hash, made mortal, and returned to the caller. The absolute
892 value of C<klen> is the length of the key. If C<klen> is negative the
893 key is assumed to be in UTF-8-encoded Unicode. The C<flags> value
894 will normally be zero; if set to G_DISCARD then NULL will be returned.
895 NULL will also be returned if the key is not found.
897 =for apidoc hv_delete_ent
899 Deletes a key/value pair in the hash. The value SV is removed from the hash,
900 made mortal, and returned to the caller. The C<flags> value will normally be
901 zero; if set to G_DISCARD then NULL will be returned. NULL will also be
902 returned if the key is not found. C<hash> can be a valid precomputed hash
903 value, or 0 to ask for it to be computed.
909 S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
910 int k_flags, I32 d_flags, U32 hash)
916 bool is_utf8 = (k_flags & HVhek_UTF8) ? TRUE : FALSE;
919 if (SvRMAGICAL(hv)) {
922 hv_magic_check (hv, &needs_copy, &needs_store);
926 entry = (HE *) hv_common(hv, keysv, key, klen,
927 k_flags & ~HVhek_FREEKEY,
928 HV_FETCH_LVALUE|HV_DISABLE_UVAR_XKEY,
930 sv = entry ? HeVAL(entry) : NULL;
936 if (mg_find(sv, PERL_MAGIC_tiedelem)) {
937 /* No longer an element */
938 sv_unmagic(sv, PERL_MAGIC_tiedelem);
941 return NULL; /* element cannot be deleted */
943 #ifdef ENV_IS_CASELESS
944 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
945 /* XXX This code isn't UTF8 clean. */
946 keysv = newSVpvn_flags(key, klen, SVs_TEMP);
947 if (k_flags & HVhek_FREEKEY) {
950 key = strupr(SvPVX(keysv));
959 xhv = (XPVHV*)SvANY(hv);
964 const char * const keysave = key;
965 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
968 k_flags |= HVhek_UTF8;
970 k_flags &= ~HVhek_UTF8;
971 if (key != keysave) {
972 if (k_flags & HVhek_FREEKEY) {
973 /* This shouldn't happen if our caller does what we expect,
974 but strictly the API allows it. */
977 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
979 HvHASKFLAGS_on(MUTABLE_SV(hv));
982 if (HvREHASH(hv) || (!hash && !(keysv && (SvIsCOW_shared_hash(keysv)))))
983 PERL_HASH_INTERNAL_(hash, key, klen, HvREHASH(hv));
985 hash = SvSHARED_HASH(keysv);
987 masked_flags = (k_flags & HVhek_MASK);
989 oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
991 for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
993 U8 mro_changes = 0; /* 1 = isa; 2 = package moved */
997 if (HeHASH(entry) != hash) /* strings can't be equal */
999 if (HeKLEN(entry) != (I32)klen)
1001 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
1003 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
1006 if (hv == PL_strtab) {
1007 if (k_flags & HVhek_FREEKEY)
1009 Perl_croak(aTHX_ S_strtab_error, "delete");
1012 /* if placeholder is here, it's already been deleted.... */
1013 if (HeVAL(entry) == &PL_sv_placeholder) {
1014 if (k_flags & HVhek_FREEKEY)
1018 if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))
1019 && !SvIsCOW(HeVAL(entry))) {
1020 hv_notallowed(k_flags, key, klen,
1021 "Attempt to delete readonly key '%"SVf"' from"
1022 " a restricted hash");
1024 if (k_flags & HVhek_FREEKEY)
1027 /* If this is a stash and the key ends with ::, then someone is
1028 * deleting a package.
1030 if (HeVAL(entry) && HvENAME_get(hv)) {
1031 gv = (GV *)HeVAL(entry);
1032 if (keysv) key = SvPV(keysv, klen);
1034 (klen > 1 && key[klen-2] == ':' && key[klen-1] == ':')
1036 (klen == 1 && key[0] == ':')
1038 && (klen != 6 || hv!=PL_defstash || memNE(key,"main::",6))
1039 && SvTYPE(gv) == SVt_PVGV && (stash = GvHV((GV *)gv))
1040 && HvENAME_get(stash)) {
1041 /* A previous version of this code checked that the
1042 * GV was still in the symbol table by fetching the
1043 * GV with its name. That is not necessary (and
1044 * sometimes incorrect), as HvENAME cannot be set
1045 * on hv if it is not in the symtab. */
1047 /* Hang on to it for a bit. */
1048 SvREFCNT_inc_simple_void_NN(
1049 sv_2mortal((SV *)gv)
1052 else if (klen == 3 && strnEQ(key, "ISA", 3))
1056 sv = d_flags & G_DISCARD ? HeVAL(entry) : sv_2mortal(HeVAL(entry));
1057 HeVAL(entry) = &PL_sv_placeholder;
1059 /* deletion of method from stash */
1060 if (isGV(sv) && isGV_with_GP(sv) && GvCVu(sv)
1062 mro_method_changed_in(hv);
1066 * If a restricted hash, rather than really deleting the entry, put
1067 * a placeholder there. This marks the key as being "approved", so
1068 * we can still access via not-really-existing key without raising
1072 /* We'll be saving this slot, so the number of allocated keys
1073 * doesn't go down, but the number placeholders goes up */
1074 HvPLACEHOLDERS(hv)++;
1076 *oentry = HeNEXT(entry);
1077 if (SvOOK(hv) && entry == HvAUX(hv)->xhv_eiter /* HvEITER(hv) */)
1080 if (SvOOK(hv) && HvLAZYDEL(hv) &&
1081 entry == HeNEXT(HvAUX(hv)->xhv_eiter))
1082 HeNEXT(HvAUX(hv)->xhv_eiter) = HeNEXT(entry);
1083 hv_free_ent(hv, entry);
1085 xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
1086 if (xhv->xhv_keys == 0)
1087 HvHASKFLAGS_off(hv);
1090 if (d_flags & G_DISCARD) {
1095 if (mro_changes == 1) mro_isa_changed_in(hv);
1096 else if (mro_changes == 2)
1097 mro_package_moved(NULL, stash, gv, 1);
1101 if (SvREADONLY(hv)) {
1102 hv_notallowed(k_flags, key, klen,
1103 "Attempt to delete disallowed key '%"SVf"' from"
1104 " a restricted hash");
1107 if (k_flags & HVhek_FREEKEY)
1113 S_hsplit(pTHX_ HV *hv)
1116 XPVHV* const xhv = (XPVHV*)SvANY(hv);
1117 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1118 I32 newsize = oldsize * 2;
1120 char *a = (char*) HvARRAY(hv);
1122 int longest_chain = 0;
1125 PERL_ARGS_ASSERT_HSPLIT;
1127 /*PerlIO_printf(PerlIO_stderr(), "hsplit called for %p which had %d\n",
1128 (void*)hv, (int) oldsize);*/
1130 if (HvPLACEHOLDERS_get(hv) && !SvREADONLY(hv)) {
1131 /* Can make this clear any placeholders first for non-restricted hashes,
1132 even though Storable rebuilds restricted hashes by putting in all the
1133 placeholders (first) before turning on the readonly flag, because
1134 Storable always pre-splits the hash. */
1135 hv_clear_placeholders(hv);
1139 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1140 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1141 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1147 Move(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1150 Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1151 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1156 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1158 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1160 Safefree(HvARRAY(hv));
1164 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1165 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
1166 HvARRAY(hv) = (HE**) a;
1169 for (i=0; i<oldsize; i++,aep++) {
1170 int left_length = 0;
1171 int right_length = 0;
1176 if (!entry) /* non-existent */
1180 if ((HeHASH(entry) & newsize) != (U32)i) {
1181 *oentry = HeNEXT(entry);
1182 HeNEXT(entry) = *bep;
1187 oentry = &HeNEXT(entry);
1192 /* I think we don't actually need to keep track of the longest length,
1193 merely flag if anything is too long. But for the moment while
1194 developing this code I'll track it. */
1195 if (left_length > longest_chain)
1196 longest_chain = left_length;
1197 if (right_length > longest_chain)
1198 longest_chain = right_length;
1202 /* Pick your policy for "hashing isn't working" here: */
1203 if (longest_chain <= HV_MAX_LENGTH_BEFORE_SPLIT /* split worked? */
1208 if (hv == PL_strtab) {
1209 /* Urg. Someone is doing something nasty to the string table.
1214 /* Awooga. Awooga. Pathological data. */
1215 /*PerlIO_printf(PerlIO_stderr(), "%p %d of %d with %d/%d buckets\n", (void*)hv,
1216 longest_chain, HvTOTALKEYS(hv), HvFILL(hv), 1+HvMAX(hv));*/
1219 Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1220 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1222 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1225 was_shared = HvSHAREKEYS(hv);
1227 HvSHAREKEYS_off(hv);
1232 for (i=0; i<newsize; i++,aep++) {
1235 /* We're going to trash this HE's next pointer when we chain it
1236 into the new hash below, so store where we go next. */
1237 HE * const next = HeNEXT(entry);
1242 PERL_HASH_INTERNAL(hash, HeKEY(entry), HeKLEN(entry));
1247 = save_hek_flags(HeKEY(entry), HeKLEN(entry),
1248 hash, HeKFLAGS(entry));
1249 unshare_hek (HeKEY_hek(entry));
1250 HeKEY_hek(entry) = new_hek;
1252 /* Not shared, so simply write the new hash in. */
1253 HeHASH(entry) = hash;
1255 /*PerlIO_printf(PerlIO_stderr(), "%d ", HeKFLAGS(entry));*/
1256 HEK_REHASH_on(HeKEY_hek(entry));
1257 /*PerlIO_printf(PerlIO_stderr(), "%d\n", HeKFLAGS(entry));*/
1259 /* Copy oentry to the correct new chain. */
1260 bep = ((HE**)a) + (hash & (I32) xhv->xhv_max);
1261 HeNEXT(entry) = *bep;
1267 Safefree (HvARRAY(hv));
1268 HvARRAY(hv) = (HE **)a;
1272 Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
1275 XPVHV* xhv = (XPVHV*)SvANY(hv);
1276 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1282 PERL_ARGS_ASSERT_HV_KSPLIT;
1284 newsize = (I32) newmax; /* possible truncation here */
1285 if (newsize != newmax || newmax <= oldsize)
1287 while ((newsize & (1 + ~newsize)) != newsize) {
1288 newsize &= ~(newsize & (1 + ~newsize)); /* get proper power of 2 */
1290 if (newsize < newmax)
1292 if (newsize < newmax)
1293 return; /* overflow detection */
1295 a = (char *) HvARRAY(hv);
1298 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1299 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1300 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1306 Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1309 Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1310 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1315 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1317 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1319 Safefree(HvARRAY(hv));
1322 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1325 Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1327 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
1328 HvARRAY(hv) = (HE **) a;
1329 if (!xhv->xhv_keys /* !HvTOTALKEYS(hv) */) /* skip rest if no entries */
1333 for (i=0; i<oldsize; i++,aep++) {
1337 if (!entry) /* non-existent */
1340 I32 j = (HeHASH(entry) & newsize);
1344 *oentry = HeNEXT(entry);
1345 HeNEXT(entry) = aep[j];
1349 oentry = &HeNEXT(entry);
1356 Perl_newHVhv(pTHX_ HV *ohv)
1359 HV * const hv = newHV();
1362 if (!ohv || (!HvTOTALKEYS(ohv) && !SvMAGICAL((const SV *)ohv)))
1364 hv_max = HvMAX(ohv);
1366 if (!SvMAGICAL((const SV *)ohv)) {
1367 /* It's an ordinary hash, so copy it fast. AMS 20010804 */
1369 const bool shared = !!HvSHAREKEYS(ohv);
1370 HE **ents, ** const oents = (HE **)HvARRAY(ohv);
1372 Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
1375 /* In each bucket... */
1376 for (i = 0; i <= hv_max; i++) {
1378 HE *oent = oents[i];
1385 /* Copy the linked list of entries. */
1386 for (; oent; oent = HeNEXT(oent)) {
1387 const U32 hash = HeHASH(oent);
1388 const char * const key = HeKEY(oent);
1389 const STRLEN len = HeKLEN(oent);
1390 const int flags = HeKFLAGS(oent);
1391 HE * const ent = new_HE();
1392 SV *const val = HeVAL(oent);
1394 HeVAL(ent) = SvIMMORTAL(val) ? val : newSVsv(val);
1396 = shared ? share_hek_flags(key, len, hash, flags)
1397 : save_hek_flags(key, len, hash, flags);
1408 HvTOTALKEYS(hv) = HvTOTALKEYS(ohv);
1412 /* Iterate over ohv, copying keys and values one at a time. */
1414 const I32 riter = HvRITER_get(ohv);
1415 HE * const eiter = HvEITER_get(ohv);
1416 STRLEN hv_fill = HvFILL(ohv);
1418 /* Can we use fewer buckets? (hv_max is always 2^n-1) */
1419 while (hv_max && hv_max + 1 >= hv_fill * 2)
1420 hv_max = hv_max / 2;
1424 while ((entry = hv_iternext_flags(ohv, 0))) {
1425 SV *val = hv_iterval(ohv,entry);
1426 SV * const keysv = HeSVKEY(entry);
1427 val = SvIMMORTAL(val) ? val : newSVsv(val);
1429 (void)hv_store_ent(hv, keysv, val, 0);
1431 (void)hv_store_flags(hv, HeKEY(entry), HeKLEN(entry), val,
1432 HeHASH(entry), HeKFLAGS(entry));
1434 HvRITER_set(ohv, riter);
1435 HvEITER_set(ohv, eiter);
1442 =for apidoc Am|HV *|hv_copy_hints_hv|HV *ohv
1444 A specialised version of L</newHVhv> for copying C<%^H>. I<ohv> must be
1445 a pointer to a hash (which may have C<%^H> magic, but should be generally
1446 non-magical), or C<NULL> (interpreted as an empty hash). The content
1447 of I<ohv> is copied to a new hash, which has the C<%^H>-specific magic
1448 added to it. A pointer to the new hash is returned.
1454 Perl_hv_copy_hints_hv(pTHX_ HV *const ohv)
1456 HV * const hv = newHV();
1459 STRLEN hv_max = HvMAX(ohv);
1460 STRLEN hv_fill = HvFILL(ohv);
1462 const I32 riter = HvRITER_get(ohv);
1463 HE * const eiter = HvEITER_get(ohv);
1468 while (hv_max && hv_max + 1 >= hv_fill * 2)
1469 hv_max = hv_max / 2;
1473 while ((entry = hv_iternext_flags(ohv, 0))) {
1474 SV *const sv = newSVsv(hv_iterval(ohv,entry));
1475 SV *heksv = HeSVKEY(entry);
1476 if (!heksv && sv) heksv = newSVhek(HeKEY_hek(entry));
1477 if (sv) sv_magic(sv, NULL, PERL_MAGIC_hintselem,
1478 (char *)heksv, HEf_SVKEY);
1479 if (heksv == HeSVKEY(entry))
1480 (void)hv_store_ent(hv, heksv, sv, 0);
1482 (void)hv_common(hv, heksv, HeKEY(entry), HeKLEN(entry),
1483 HeKFLAGS(entry), HV_FETCH_ISSTORE|HV_FETCH_JUST_SV, sv, HeHASH(entry));
1484 SvREFCNT_dec(heksv);
1487 HvRITER_set(ohv, riter);
1488 HvEITER_set(ohv, eiter);
1490 SvREFCNT_inc_simple_void_NN(hv);
1493 hv_magic(hv, NULL, PERL_MAGIC_hints);
1497 /* like hv_free_ent, but returns the SV rather than freeing it */
1499 S_hv_free_ent_ret(pTHX_ HV *hv, register HE *entry)
1504 PERL_ARGS_ASSERT_HV_FREE_ENT_RET;
1509 if (HeKLEN(entry) == HEf_SVKEY) {
1510 SvREFCNT_dec(HeKEY_sv(entry));
1511 Safefree(HeKEY_hek(entry));
1513 else if (HvSHAREKEYS(hv))
1514 unshare_hek(HeKEY_hek(entry));
1516 Safefree(HeKEY_hek(entry));
1523 Perl_hv_free_ent(pTHX_ HV *hv, register HE *entry)
1528 PERL_ARGS_ASSERT_HV_FREE_ENT;
1532 val = hv_free_ent_ret(hv, entry);
1538 Perl_hv_delayfree_ent(pTHX_ HV *hv, register HE *entry)
1542 PERL_ARGS_ASSERT_HV_DELAYFREE_ENT;
1546 /* SvREFCNT_inc to counter the SvREFCNT_dec in hv_free_ent */
1547 sv_2mortal(SvREFCNT_inc(HeVAL(entry))); /* free between statements */
1548 if (HeKLEN(entry) == HEf_SVKEY) {
1549 sv_2mortal(SvREFCNT_inc(HeKEY_sv(entry)));
1551 hv_free_ent(hv, entry);
1555 =for apidoc hv_clear
1557 Frees the all the elements of a hash, leaving it empty.
1558 The XS equivalent of C<%hash = ()>. See also L</hv_undef>.
1560 If any destructors are triggered as a result, the hv itself may
1567 Perl_hv_clear(pTHX_ HV *hv)
1574 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1576 xhv = (XPVHV*)SvANY(hv);
1579 SAVEFREESV(SvREFCNT_inc_simple_NN(hv));
1580 if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
1581 /* restricted hash: convert all keys to placeholders */
1583 for (i = 0; i <= xhv->xhv_max; i++) {
1584 HE *entry = (HvARRAY(hv))[i];
1585 for (; entry; entry = HeNEXT(entry)) {
1586 /* not already placeholder */
1587 if (HeVAL(entry) != &PL_sv_placeholder) {
1588 if (HeVAL(entry) && SvREADONLY(HeVAL(entry))
1589 && !SvIsCOW(HeVAL(entry))) {
1590 SV* const keysv = hv_iterkeysv(entry);
1592 "Attempt to delete readonly key '%"SVf"' from a restricted hash",
1595 SvREFCNT_dec(HeVAL(entry));
1596 HeVAL(entry) = &PL_sv_placeholder;
1597 HvPLACEHOLDERS(hv)++;
1604 HvPLACEHOLDERS_set(hv, 0);
1607 mg_clear(MUTABLE_SV(hv));
1609 HvHASKFLAGS_off(hv);
1614 mro_isa_changed_in(hv);
1615 HvEITER_set(hv, NULL);
1621 =for apidoc hv_clear_placeholders
1623 Clears any placeholders from a hash. If a restricted hash has any of its keys
1624 marked as readonly and the key is subsequently deleted, the key is not actually
1625 deleted but is marked by assigning it a value of &PL_sv_placeholder. This tags
1626 it so it will be ignored by future operations such as iterating over the hash,
1627 but will still allow the hash to have a value reassigned to the key at some
1628 future point. This function clears any such placeholder keys from the hash.
1629 See Hash::Util::lock_keys() for an example of its use.
1635 Perl_hv_clear_placeholders(pTHX_ HV *hv)
1638 const U32 items = (U32)HvPLACEHOLDERS_get(hv);
1640 PERL_ARGS_ASSERT_HV_CLEAR_PLACEHOLDERS;
1643 clear_placeholders(hv, items);
1647 S_clear_placeholders(pTHX_ HV *hv, U32 items)
1652 PERL_ARGS_ASSERT_CLEAR_PLACEHOLDERS;
1659 /* Loop down the linked list heads */
1660 HE **oentry = &(HvARRAY(hv))[i];
1663 while ((entry = *oentry)) {
1664 if (HeVAL(entry) == &PL_sv_placeholder) {
1665 *oentry = HeNEXT(entry);
1666 if (entry == HvEITER_get(hv))
1669 if (SvOOK(hv) && HvLAZYDEL(hv) &&
1670 entry == HeNEXT(HvAUX(hv)->xhv_eiter))
1671 HeNEXT(HvAUX(hv)->xhv_eiter) = HeNEXT(entry);
1672 hv_free_ent(hv, entry);
1677 HvTOTALKEYS(hv) -= (IV)HvPLACEHOLDERS_get(hv);
1678 if (HvUSEDKEYS(hv) == 0)
1679 HvHASKFLAGS_off(hv);
1680 HvPLACEHOLDERS_set(hv, 0);
1684 oentry = &HeNEXT(entry);
1688 /* You can't get here, hence assertion should always fail. */
1689 assert (items == 0);
1694 S_hfreeentries(pTHX_ HV *hv)
1697 XPVHV * const xhv = (XPVHV*)SvANY(hv);
1700 PERL_ARGS_ASSERT_HFREEENTRIES;
1702 while ((sv = Perl_hfree_next_entry(aTHX_ hv, &index))||xhv->xhv_keys) {
1708 /* hfree_next_entry()
1709 * For use only by S_hfreeentries() and sv_clear().
1710 * Delete the next available HE from hv and return the associated SV.
1711 * Returns null on empty hash. Nevertheless null is not a reliable
1712 * indicator that the hash is empty, as the deleted entry may have a
1714 * indexp is a pointer to the current index into HvARRAY. The index should
1715 * initially be set to 0. hfree_next_entry() may update it. */
1718 Perl_hfree_next_entry(pTHX_ HV *hv, STRLEN *indexp)
1720 struct xpvhv_aux *iter;
1724 STRLEN orig_index = *indexp;
1727 PERL_ARGS_ASSERT_HFREE_NEXT_ENTRY;
1729 if (SvOOK(hv) && ((iter = HvAUX(hv)))
1730 && ((entry = iter->xhv_eiter)) )
1732 /* the iterator may get resurrected after each
1733 * destructor call, so check each time */
1734 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1736 hv_free_ent(hv, entry);
1737 /* warning: at this point HvARRAY may have been
1738 * re-allocated, HvMAX changed etc */
1740 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1741 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
1744 if (!((XPVHV*)SvANY(hv))->xhv_keys)
1747 array = HvARRAY(hv);
1749 while ( ! ((entry = array[*indexp])) ) {
1750 if ((*indexp)++ >= HvMAX(hv))
1752 assert(*indexp != orig_index);
1754 array[*indexp] = HeNEXT(entry);
1755 ((XPVHV*) SvANY(hv))->xhv_keys--;
1757 if ( PL_phase != PERL_PHASE_DESTRUCT && HvENAME(hv)
1758 && HeVAL(entry) && isGV(HeVAL(entry))
1759 && GvHV(HeVAL(entry)) && HvENAME(GvHV(HeVAL(entry)))
1762 const char * const key = HePV(entry,klen);
1763 if ((klen > 1 && key[klen-1]==':' && key[klen-2]==':')
1764 || (klen == 1 && key[0] == ':')) {
1766 NULL, GvHV(HeVAL(entry)),
1767 (GV *)HeVAL(entry), 0
1771 return hv_free_ent_ret(hv, entry);
1776 =for apidoc hv_undef
1778 Undefines the hash. The XS equivalent of C<undef(%hash)>.
1780 As well as freeing all the elements of the hash (like hv_clear()), this
1781 also frees any auxiliary data and storage associated with the hash.
1783 If any destructors are triggered as a result, the hv itself may
1786 See also L</hv_clear>.
1792 Perl_hv_undef_flags(pTHX_ HV *hv, U32 flags)
1797 const bool save = !!SvREFCNT(hv);
1801 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1802 xhv = (XPVHV*)SvANY(hv);
1804 /* The name must be deleted before the call to hfreeeeentries so that
1805 CVs are anonymised properly. But the effective name must be pre-
1806 served until after that call (and only deleted afterwards if the
1807 call originated from sv_clear). For stashes with one name that is
1808 both the canonical name and the effective name, hv_name_set has to
1809 allocate an array for storing the effective name. We can skip that
1810 during global destruction, as it does not matter where the CVs point
1811 if they will be freed anyway. */
1812 /* note that the code following prior to hfreeentries is duplicated
1813 * in sv_clear(), and changes here should be done there too */
1814 if (PL_phase != PERL_PHASE_DESTRUCT && (name = HvNAME(hv))) {
1816 (void)hv_delete(PL_stashcache, name,
1817 HEK_UTF8(HvNAME_HEK(hv)) ? -HvNAMELEN_get(hv) : HvNAMELEN_get(hv),
1820 hv_name_set(hv, NULL, 0, 0);
1824 SAVEFREESV(SvREFCNT_inc_simple_NN(hv));
1828 struct xpvhv_aux * const aux = HvAUX(hv);
1829 struct mro_meta *meta;
1831 if ((name = HvENAME_get(hv))) {
1832 if (PL_phase != PERL_PHASE_DESTRUCT)
1833 mro_isa_changed_in(hv);
1836 PL_stashcache, name,
1837 HEK_UTF8(HvENAME_HEK(hv)) ? -HvENAMELEN_get(hv) : HvENAMELEN_get(hv),
1842 /* If this call originated from sv_clear, then we must check for
1843 * effective names that need freeing, as well as the usual name. */
1845 if (flags & HV_NAME_SETALL ? !!aux->xhv_name_u.xhvnameu_name : !!name) {
1846 if (name && PL_stashcache)
1847 (void)hv_delete(PL_stashcache, name, (HEK_UTF8(HvNAME_HEK(hv)) ? -HvNAMELEN_get(hv) : HvNAMELEN_get(hv)), G_DISCARD);
1848 hv_name_set(hv, NULL, 0, flags);
1850 if((meta = aux->xhv_mro_meta)) {
1851 if (meta->mro_linear_all) {
1852 SvREFCNT_dec(MUTABLE_SV(meta->mro_linear_all));
1853 meta->mro_linear_all = NULL;
1854 /* This is just acting as a shortcut pointer. */
1855 meta->mro_linear_current = NULL;
1856 } else if (meta->mro_linear_current) {
1857 /* Only the current MRO is stored, so this owns the data.
1859 SvREFCNT_dec(meta->mro_linear_current);
1860 meta->mro_linear_current = NULL;
1862 SvREFCNT_dec(meta->mro_nextmethod);
1863 SvREFCNT_dec(meta->isa);
1865 aux->xhv_mro_meta = NULL;
1867 SvREFCNT_dec(aux->xhv_super);
1868 if (!aux->xhv_name_u.xhvnameu_name && ! aux->xhv_backreferences)
1869 SvFLAGS(hv) &= ~SVf_OOK;
1872 Safefree(HvARRAY(hv));
1873 xhv->xhv_max = 7; /* HvMAX(hv) = 7 (it's a normal hash) */
1876 /* if we're freeing the HV, the SvMAGIC field has been reused for
1877 * other purposes, and so there can't be any placeholder magic */
1879 HvPLACEHOLDERS_set(hv, 0);
1882 mg_clear(MUTABLE_SV(hv));
1889 Returns the number of hash buckets that happen to be in use. This function is
1890 wrapped by the macro C<HvFILL>.
1892 Previously this value was stored in the HV structure, rather than being
1893 calculated on demand.
1899 Perl_hv_fill(pTHX_ HV const *const hv)
1902 HE **ents = HvARRAY(hv);
1904 PERL_ARGS_ASSERT_HV_FILL;
1907 HE *const *const last = ents + HvMAX(hv);
1908 count = last + 1 - ents;
1913 } while (++ents <= last);
1918 static struct xpvhv_aux*
1919 S_hv_auxinit(HV *hv) {
1920 struct xpvhv_aux *iter;
1923 PERL_ARGS_ASSERT_HV_AUXINIT;
1926 Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1927 + sizeof(struct xpvhv_aux), char);
1929 array = (char *) HvARRAY(hv);
1930 Renew(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1931 + sizeof(struct xpvhv_aux), char);
1933 HvARRAY(hv) = (HE**) array;
1937 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1938 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
1939 iter->xhv_name_u.xhvnameu_name = 0;
1940 iter->xhv_name_count = 0;
1941 iter->xhv_backreferences = 0;
1942 iter->xhv_mro_meta = NULL;
1943 iter->xhv_super = NULL;
1948 =for apidoc hv_iterinit
1950 Prepares a starting point to traverse a hash table. Returns the number of
1951 keys in the hash (i.e. the same as C<HvUSEDKEYS(hv)>). The return value is
1952 currently only meaningful for hashes without tie magic.
1954 NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
1955 hash buckets that happen to be in use. If you still need that esoteric
1956 value, you can get it through the macro C<HvFILL(hv)>.
1963 Perl_hv_iterinit(pTHX_ HV *hv)
1965 PERL_ARGS_ASSERT_HV_ITERINIT;
1967 /* FIXME: Are we not NULL, or do we croak? Place bets now! */
1970 Perl_croak(aTHX_ "Bad hash");
1973 struct xpvhv_aux * const iter = HvAUX(hv);
1974 HE * const entry = iter->xhv_eiter; /* HvEITER(hv) */
1975 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1977 hv_free_ent(hv, entry);
1979 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1980 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
1985 /* used to be xhv->xhv_fill before 5.004_65 */
1986 return HvTOTALKEYS(hv);
1990 Perl_hv_riter_p(pTHX_ HV *hv) {
1991 struct xpvhv_aux *iter;
1993 PERL_ARGS_ASSERT_HV_RITER_P;
1996 Perl_croak(aTHX_ "Bad hash");
1998 iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
1999 return &(iter->xhv_riter);
2003 Perl_hv_eiter_p(pTHX_ HV *hv) {
2004 struct xpvhv_aux *iter;
2006 PERL_ARGS_ASSERT_HV_EITER_P;
2009 Perl_croak(aTHX_ "Bad hash");
2011 iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2012 return &(iter->xhv_eiter);
2016 Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
2017 struct xpvhv_aux *iter;
2019 PERL_ARGS_ASSERT_HV_RITER_SET;
2022 Perl_croak(aTHX_ "Bad hash");
2030 iter = hv_auxinit(hv);
2032 iter->xhv_riter = riter;
2036 Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
2037 struct xpvhv_aux *iter;
2039 PERL_ARGS_ASSERT_HV_EITER_SET;
2042 Perl_croak(aTHX_ "Bad hash");
2047 /* 0 is the default so don't go malloc()ing a new structure just to
2052 iter = hv_auxinit(hv);
2054 iter->xhv_eiter = eiter;
2058 Perl_hv_name_set(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2061 struct xpvhv_aux *iter;
2065 PERL_ARGS_ASSERT_HV_NAME_SET;
2068 Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
2072 if (iter->xhv_name_u.xhvnameu_name) {
2073 if(iter->xhv_name_count) {
2074 if(flags & HV_NAME_SETALL) {
2075 HEK ** const name = HvAUX(hv)->xhv_name_u.xhvnameu_names;
2076 HEK **hekp = name + (
2077 iter->xhv_name_count < 0
2078 ? -iter->xhv_name_count
2079 : iter->xhv_name_count
2081 while(hekp-- > name+1)
2082 unshare_hek_or_pvn(*hekp, 0, 0, 0);
2083 /* The first elem may be null. */
2084 if(*name) unshare_hek_or_pvn(*name, 0, 0, 0);
2086 spot = &iter->xhv_name_u.xhvnameu_name;
2087 iter->xhv_name_count = 0;
2090 if(iter->xhv_name_count > 0) {
2091 /* shift some things over */
2093 iter->xhv_name_u.xhvnameu_names, iter->xhv_name_count + 1, HEK *
2095 spot = iter->xhv_name_u.xhvnameu_names;
2096 spot[iter->xhv_name_count] = spot[1];
2098 iter->xhv_name_count = -(iter->xhv_name_count + 1);
2100 else if(*(spot = iter->xhv_name_u.xhvnameu_names)) {
2101 unshare_hek_or_pvn(*spot, 0, 0, 0);
2105 else if (flags & HV_NAME_SETALL) {
2106 unshare_hek_or_pvn(iter->xhv_name_u.xhvnameu_name, 0, 0, 0);
2107 spot = &iter->xhv_name_u.xhvnameu_name;
2110 HEK * const existing_name = iter->xhv_name_u.xhvnameu_name;
2111 Newx(iter->xhv_name_u.xhvnameu_names, 2, HEK *);
2112 iter->xhv_name_count = -2;
2113 spot = iter->xhv_name_u.xhvnameu_names;
2114 spot[1] = existing_name;
2117 else { spot = &iter->xhv_name_u.xhvnameu_name; iter->xhv_name_count = 0; }
2122 iter = hv_auxinit(hv);
2123 spot = &iter->xhv_name_u.xhvnameu_name;
2125 PERL_HASH(hash, name, len);
2126 *spot = name ? share_hek(name, flags & SVf_UTF8 ? -(I32)len : (I32)len, hash) : NULL;
2130 This is basically sv_eq_flags() in sv.c, but we avoid the magic
2135 hek_eq_pvn_flags(pTHX_ const HEK *hek, const char* pv, const I32 pvlen, const U32 flags) {
2136 if ( (HEK_UTF8(hek) ? 1 : 0) != (flags & SVf_UTF8 ? 1 : 0) ) {
2137 if (flags & SVf_UTF8)
2138 return (bytes_cmp_utf8(
2139 (const U8*)HEK_KEY(hek), HEK_LEN(hek),
2140 (const U8*)pv, pvlen) == 0);
2142 return (bytes_cmp_utf8(
2143 (const U8*)pv, pvlen,
2144 (const U8*)HEK_KEY(hek), HEK_LEN(hek)) == 0);
2147 return HEK_LEN(hek) == pvlen && ((HEK_KEY(hek) == pv)
2148 || memEQ(HEK_KEY(hek), pv, pvlen));
2152 =for apidoc hv_ename_add
2154 Adds a name to a stash's internal list of effective names. See
2157 This is called when a stash is assigned to a new location in the symbol
2164 Perl_hv_ename_add(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2167 struct xpvhv_aux *aux = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2170 PERL_ARGS_ASSERT_HV_ENAME_ADD;
2173 Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
2175 PERL_HASH(hash, name, len);
2177 if (aux->xhv_name_count) {
2178 HEK ** const xhv_name = aux->xhv_name_u.xhvnameu_names;
2179 I32 count = aux->xhv_name_count;
2180 HEK **hekp = xhv_name + (count < 0 ? -count : count);
2181 while (hekp-- > xhv_name)
2183 (HEK_UTF8(*hekp) || (flags & SVf_UTF8))
2184 ? hek_eq_pvn_flags(aTHX_ *hekp, name, (I32)len, flags)
2185 : (HEK_LEN(*hekp) == (I32)len && memEQ(HEK_KEY(*hekp), name, len))
2187 if (hekp == xhv_name && count < 0)
2188 aux->xhv_name_count = -count;
2191 if (count < 0) aux->xhv_name_count--, count = -count;
2192 else aux->xhv_name_count++;
2193 Renew(aux->xhv_name_u.xhvnameu_names, count + 1, HEK *);
2194 (aux->xhv_name_u.xhvnameu_names)[count] = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
2197 HEK *existing_name = aux->xhv_name_u.xhvnameu_name;
2200 (HEK_UTF8(existing_name) || (flags & SVf_UTF8))
2201 ? hek_eq_pvn_flags(aTHX_ existing_name, name, (I32)len, flags)
2202 : (HEK_LEN(existing_name) == (I32)len && memEQ(HEK_KEY(existing_name), name, len))
2205 Newx(aux->xhv_name_u.xhvnameu_names, 2, HEK *);
2206 aux->xhv_name_count = existing_name ? 2 : -2;
2207 *aux->xhv_name_u.xhvnameu_names = existing_name;
2208 (aux->xhv_name_u.xhvnameu_names)[1] = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
2213 =for apidoc hv_ename_delete
2215 Removes a name from a stash's internal list of effective names. If this is
2216 the name returned by C<HvENAME>, then another name in the list will take
2217 its place (C<HvENAME> will use it).
2219 This is called when a stash is deleted from the symbol table.
2225 Perl_hv_ename_delete(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2228 struct xpvhv_aux *aux;
2230 PERL_ARGS_ASSERT_HV_ENAME_DELETE;
2233 Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
2235 if (!SvOOK(hv)) return;
2238 if (!aux->xhv_name_u.xhvnameu_name) return;
2240 if (aux->xhv_name_count) {
2241 HEK ** const namep = aux->xhv_name_u.xhvnameu_names;
2242 I32 const count = aux->xhv_name_count;
2243 HEK **victim = namep + (count < 0 ? -count : count);
2244 while (victim-- > namep + 1)
2246 (HEK_UTF8(*victim) || (flags & SVf_UTF8))
2247 ? hek_eq_pvn_flags(aTHX_ *victim, name, (I32)len, flags)
2248 : (HEK_LEN(*victim) == (I32)len && memEQ(HEK_KEY(*victim), name, len))
2250 unshare_hek_or_pvn(*victim, 0, 0, 0);
2251 if (count < 0) ++aux->xhv_name_count;
2252 else --aux->xhv_name_count;
2254 (aux->xhv_name_count == 1 || aux->xhv_name_count == -1)
2256 ) { /* if there are none left */
2258 aux->xhv_name_u.xhvnameu_names = NULL;
2259 aux->xhv_name_count = 0;
2262 /* Move the last one back to fill the empty slot. It
2263 does not matter what order they are in. */
2264 *victim = *(namep + (count < 0 ? -count : count) - 1);
2269 count > 0 && (HEK_UTF8(*namep) || (flags & SVf_UTF8))
2270 ? hek_eq_pvn_flags(aTHX_ *namep, name, (I32)len, flags)
2271 : (HEK_LEN(*namep) == (I32)len && memEQ(HEK_KEY(*namep), name, len))
2273 aux->xhv_name_count = -count;
2277 (HEK_UTF8(aux->xhv_name_u.xhvnameu_name) || (flags & SVf_UTF8))
2278 ? hek_eq_pvn_flags(aTHX_ aux->xhv_name_u.xhvnameu_name, name, (I32)len, flags)
2279 : (HEK_LEN(aux->xhv_name_u.xhvnameu_name) == (I32)len &&
2280 memEQ(HEK_KEY(aux->xhv_name_u.xhvnameu_name), name, len))
2282 HEK * const namehek = aux->xhv_name_u.xhvnameu_name;
2283 Newx(aux->xhv_name_u.xhvnameu_names, 1, HEK *);
2284 *aux->xhv_name_u.xhvnameu_names = namehek;
2285 aux->xhv_name_count = -1;
2290 Perl_hv_backreferences_p(pTHX_ HV *hv) {
2291 struct xpvhv_aux * const iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2293 PERL_ARGS_ASSERT_HV_BACKREFERENCES_P;
2294 PERL_UNUSED_CONTEXT;
2296 return &(iter->xhv_backreferences);
2300 Perl_hv_kill_backrefs(pTHX_ HV *hv) {
2303 PERL_ARGS_ASSERT_HV_KILL_BACKREFS;
2308 av = HvAUX(hv)->xhv_backreferences;
2311 HvAUX(hv)->xhv_backreferences = 0;
2312 Perl_sv_kill_backrefs(aTHX_ MUTABLE_SV(hv), av);
2313 if (SvTYPE(av) == SVt_PVAV)
2319 hv_iternext is implemented as a macro in hv.h
2321 =for apidoc hv_iternext
2323 Returns entries from a hash iterator. See C<hv_iterinit>.
2325 You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
2326 iterator currently points to, without losing your place or invalidating your
2327 iterator. Note that in this case the current entry is deleted from the hash
2328 with your iterator holding the last reference to it. Your iterator is flagged
2329 to free the entry on the next call to C<hv_iternext>, so you must not discard
2330 your iterator immediately else the entry will leak - call C<hv_iternext> to
2331 trigger the resource deallocation.
2333 =for apidoc hv_iternext_flags
2335 Returns entries from a hash iterator. See C<hv_iterinit> and C<hv_iternext>.
2336 The C<flags> value will normally be zero; if HV_ITERNEXT_WANTPLACEHOLDERS is
2337 set the placeholders keys (for restricted hashes) will be returned in addition
2338 to normal keys. By default placeholders are automatically skipped over.
2339 Currently a placeholder is implemented with a value that is
2340 C<&PL_sv_placeholder>. Note that the implementation of placeholders and
2341 restricted hashes may change, and the implementation currently is
2342 insufficiently abstracted for any change to be tidy.
2348 Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
2355 struct xpvhv_aux *iter;
2357 PERL_ARGS_ASSERT_HV_ITERNEXT_FLAGS;
2360 Perl_croak(aTHX_ "Bad hash");
2362 xhv = (XPVHV*)SvANY(hv);
2365 /* Too many things (well, pp_each at least) merrily assume that you can
2366 call hv_iternext without calling hv_iterinit, so we'll have to deal
2372 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2373 if (SvMAGICAL(hv) && SvRMAGICAL(hv)) {
2374 if ( ( mg = mg_find((const SV *)hv, PERL_MAGIC_tied) ) ) {
2375 SV * const key = sv_newmortal();
2377 sv_setsv(key, HeSVKEY_force(entry));
2378 SvREFCNT_dec(HeSVKEY(entry)); /* get rid of previous key */
2379 HeSVKEY_set(entry, NULL);
2385 /* one HE per MAGICAL hash */
2386 iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
2387 HvLAZYDEL_on(hv); /* make sure entry gets freed */
2389 Newxz(k, HEK_BASESIZE + sizeof(const SV *), char);
2391 HeKEY_hek(entry) = hek;
2392 HeKLEN(entry) = HEf_SVKEY;
2394 magic_nextpack(MUTABLE_SV(hv),mg,key);
2396 /* force key to stay around until next time */
2397 HeSVKEY_set(entry, SvREFCNT_inc_simple_NN(key));
2398 return entry; /* beware, hent_val is not set */
2400 SvREFCNT_dec(HeVAL(entry));
2401 Safefree(HeKEY_hek(entry));
2403 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
2408 #if defined(DYNAMIC_ENV_FETCH) && !defined(__riscos__) /* set up %ENV for iteration */
2409 if (!entry && SvRMAGICAL((const SV *)hv)
2410 && mg_find((const SV *)hv, PERL_MAGIC_env)) {
2413 /* The prime_env_iter() on VMS just loaded up new hash values
2414 * so the iteration count needs to be reset back to the beginning
2418 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2423 /* hv_iterinit now ensures this. */
2424 assert (HvARRAY(hv));
2426 /* At start of hash, entry is NULL. */
2429 entry = HeNEXT(entry);
2430 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2432 * Skip past any placeholders -- don't want to include them in
2435 while (entry && HeVAL(entry) == &PL_sv_placeholder) {
2436 entry = HeNEXT(entry);
2441 /* Skip the entire loop if the hash is empty. */
2442 if ((flags & HV_ITERNEXT_WANTPLACEHOLDERS)
2443 ? HvTOTALKEYS(hv) : HvUSEDKEYS(hv)) {
2445 /* OK. Come to the end of the current list. Grab the next one. */
2447 iter->xhv_riter++; /* HvRITER(hv)++ */
2448 if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
2449 /* There is no next one. End of the hash. */
2450 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2453 entry = (HvARRAY(hv))[iter->xhv_riter];
2455 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2456 /* If we have an entry, but it's a placeholder, don't count it.
2458 while (entry && HeVAL(entry) == &PL_sv_placeholder)
2459 entry = HeNEXT(entry);
2461 /* Will loop again if this linked list starts NULL
2462 (for HV_ITERNEXT_WANTPLACEHOLDERS)
2463 or if we run through it and find only placeholders. */
2466 else iter->xhv_riter = -1;
2468 if (oldentry && HvLAZYDEL(hv)) { /* was deleted earlier? */
2470 hv_free_ent(hv, oldentry);
2473 /*if (HvREHASH(hv) && entry && !HeKREHASH(entry))
2474 PerlIO_printf(PerlIO_stderr(), "Awooga %p %p\n", (void*)hv, (void*)entry);*/
2476 iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
2481 =for apidoc hv_iterkey
2483 Returns the key from the current position of the hash iterator. See
2490 Perl_hv_iterkey(pTHX_ register HE *entry, I32 *retlen)
2492 PERL_ARGS_ASSERT_HV_ITERKEY;
2494 if (HeKLEN(entry) == HEf_SVKEY) {
2496 char * const p = SvPV(HeKEY_sv(entry), len);
2501 *retlen = HeKLEN(entry);
2502 return HeKEY(entry);
2506 /* unlike hv_iterval(), this always returns a mortal copy of the key */
2508 =for apidoc hv_iterkeysv
2510 Returns the key as an C<SV*> from the current position of the hash
2511 iterator. The return value will always be a mortal copy of the key. Also
2518 Perl_hv_iterkeysv(pTHX_ register HE *entry)
2520 PERL_ARGS_ASSERT_HV_ITERKEYSV;
2522 return sv_2mortal(newSVhek(HeKEY_hek(entry)));
2526 =for apidoc hv_iterval
2528 Returns the value from the current position of the hash iterator. See
2535 Perl_hv_iterval(pTHX_ HV *hv, register HE *entry)
2537 PERL_ARGS_ASSERT_HV_ITERVAL;
2539 if (SvRMAGICAL(hv)) {
2540 if (mg_find((const SV *)hv, PERL_MAGIC_tied)) {
2541 SV* const sv = sv_newmortal();
2542 if (HeKLEN(entry) == HEf_SVKEY)
2543 mg_copy(MUTABLE_SV(hv), sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
2545 mg_copy(MUTABLE_SV(hv), sv, HeKEY(entry), HeKLEN(entry));
2549 return HeVAL(entry);
2553 =for apidoc hv_iternextsv
2555 Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2562 Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
2564 HE * const he = hv_iternext_flags(hv, 0);
2566 PERL_ARGS_ASSERT_HV_ITERNEXTSV;
2570 *key = hv_iterkey(he, retlen);
2571 return hv_iterval(hv, he);
2578 =for apidoc hv_magic
2580 Adds magic to a hash. See C<sv_magic>.
2585 /* possibly free a shared string if no one has access to it
2586 * len and hash must both be valid for str.
2589 Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
2591 unshare_hek_or_pvn (NULL, str, len, hash);
2596 Perl_unshare_hek(pTHX_ HEK *hek)
2599 unshare_hek_or_pvn(hek, NULL, 0, 0);
2602 /* possibly free a shared string if no one has access to it
2603 hek if non-NULL takes priority over the other 3, else str, len and hash
2604 are used. If so, len and hash must both be valid for str.
2607 S_unshare_hek_or_pvn(pTHX_ const HEK *hek, const char *str, I32 len, U32 hash)
2613 bool is_utf8 = FALSE;
2615 const char * const save = str;
2616 struct shared_he *he = NULL;
2619 /* Find the shared he which is just before us in memory. */
2620 he = (struct shared_he *)(((char *)hek)
2621 - STRUCT_OFFSET(struct shared_he,
2624 /* Assert that the caller passed us a genuine (or at least consistent)
2626 assert (he->shared_he_he.hent_hek == hek);
2628 if (he->shared_he_he.he_valu.hent_refcount - 1) {
2629 --he->shared_he_he.he_valu.hent_refcount;
2633 hash = HEK_HASH(hek);
2634 } else if (len < 0) {
2635 STRLEN tmplen = -len;
2637 /* See the note in hv_fetch(). --jhi */
2638 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2641 k_flags = HVhek_UTF8;
2643 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2646 /* what follows was the moral equivalent of:
2647 if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
2649 hv_delete(PL_strtab, str, len, G_DISCARD, hash);
2651 xhv = (XPVHV*)SvANY(PL_strtab);
2652 /* assert(xhv_array != 0) */
2653 oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2655 const HE *const he_he = &(he->shared_he_he);
2656 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2661 const int flags_masked = k_flags & HVhek_MASK;
2662 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2663 if (HeHASH(entry) != hash) /* strings can't be equal */
2665 if (HeKLEN(entry) != len)
2667 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2669 if (HeKFLAGS(entry) != flags_masked)
2676 if (--entry->he_valu.hent_refcount == 0) {
2677 *oentry = HeNEXT(entry);
2679 xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
2684 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
2685 "Attempt to free nonexistent shared string '%s'%s"
2687 hek ? HEK_KEY(hek) : str,
2688 ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
2689 if (k_flags & HVhek_FREEKEY)
2693 /* get a (constant) string ptr from the global string table
2694 * string will get added if it is not already there.
2695 * len and hash must both be valid for str.
2698 Perl_share_hek(pTHX_ const char *str, I32 len, register U32 hash)
2700 bool is_utf8 = FALSE;
2702 const char * const save = str;
2704 PERL_ARGS_ASSERT_SHARE_HEK;
2707 STRLEN tmplen = -len;
2709 /* See the note in hv_fetch(). --jhi */
2710 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2712 /* If we were able to downgrade here, then than means that we were passed
2713 in a key which only had chars 0-255, but was utf8 encoded. */
2716 /* If we found we were able to downgrade the string to bytes, then
2717 we should flag that it needs upgrading on keys or each. Also flag
2718 that we need share_hek_flags to free the string. */
2720 PERL_HASH(hash, str, len);
2721 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2725 return share_hek_flags (str, len, hash, flags);
2729 S_share_hek_flags(pTHX_ const char *str, I32 len, register U32 hash, int flags)
2733 const int flags_masked = flags & HVhek_MASK;
2734 const U32 hindex = hash & (I32) HvMAX(PL_strtab);
2735 XPVHV * const xhv = (XPVHV*)SvANY(PL_strtab);
2737 PERL_ARGS_ASSERT_SHARE_HEK_FLAGS;
2739 /* what follows is the moral equivalent of:
2741 if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
2742 hv_store(PL_strtab, str, len, NULL, hash);
2744 Can't rehash the shared string table, so not sure if it's worth
2745 counting the number of entries in the linked list
2748 /* assert(xhv_array != 0) */
2749 entry = (HvARRAY(PL_strtab))[hindex];
2750 for (;entry; entry = HeNEXT(entry)) {
2751 if (HeHASH(entry) != hash) /* strings can't be equal */
2753 if (HeKLEN(entry) != len)
2755 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2757 if (HeKFLAGS(entry) != flags_masked)
2763 /* What used to be head of the list.
2764 If this is NULL, then we're the first entry for this slot, which
2765 means we need to increate fill. */
2766 struct shared_he *new_entry;
2769 HE **const head = &HvARRAY(PL_strtab)[hindex];
2770 HE *const next = *head;
2772 /* We don't actually store a HE from the arena and a regular HEK.
2773 Instead we allocate one chunk of memory big enough for both,
2774 and put the HEK straight after the HE. This way we can find the
2775 HE directly from the HEK.
2778 Newx(k, STRUCT_OFFSET(struct shared_he,
2779 shared_he_hek.hek_key[0]) + len + 2, char);
2780 new_entry = (struct shared_he *)k;
2781 entry = &(new_entry->shared_he_he);
2782 hek = &(new_entry->shared_he_hek);
2784 Copy(str, HEK_KEY(hek), len, char);
2785 HEK_KEY(hek)[len] = 0;
2787 HEK_HASH(hek) = hash;
2788 HEK_FLAGS(hek) = (unsigned char)flags_masked;
2790 /* Still "point" to the HEK, so that other code need not know what
2792 HeKEY_hek(entry) = hek;
2793 entry->he_valu.hent_refcount = 0;
2794 HeNEXT(entry) = next;
2797 xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
2798 if (!next) { /* initial entry? */
2799 } else if (xhv->xhv_keys > xhv->xhv_max /* HvUSEDKEYS(hv) > HvMAX(hv) */) {
2804 ++entry->he_valu.hent_refcount;
2806 if (flags & HVhek_FREEKEY)
2809 return HeKEY_hek(entry);
2813 Perl_hv_placeholders_p(pTHX_ HV *hv)
2816 MAGIC *mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
2818 PERL_ARGS_ASSERT_HV_PLACEHOLDERS_P;
2821 mg = sv_magicext(MUTABLE_SV(hv), 0, PERL_MAGIC_rhash, 0, 0, 0);
2824 Perl_die(aTHX_ "panic: hv_placeholders_p");
2827 return &(mg->mg_len);
2832 Perl_hv_placeholders_get(pTHX_ const HV *hv)
2835 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
2837 PERL_ARGS_ASSERT_HV_PLACEHOLDERS_GET;
2839 return mg ? mg->mg_len : 0;
2843 Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
2846 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
2848 PERL_ARGS_ASSERT_HV_PLACEHOLDERS_SET;
2853 if (!sv_magicext(MUTABLE_SV(hv), 0, PERL_MAGIC_rhash, 0, 0, ph))
2854 Perl_die(aTHX_ "panic: hv_placeholders_set");
2856 /* else we don't need to add magic to record 0 placeholders. */
2860 S_refcounted_he_value(pTHX_ const struct refcounted_he *he)
2865 PERL_ARGS_ASSERT_REFCOUNTED_HE_VALUE;
2867 switch(he->refcounted_he_data[0] & HVrhek_typemask) {
2872 value = &PL_sv_placeholder;
2875 value = newSViv(he->refcounted_he_val.refcounted_he_u_iv);
2878 value = newSVuv(he->refcounted_he_val.refcounted_he_u_uv);
2881 case HVrhek_PV_UTF8:
2882 /* Create a string SV that directly points to the bytes in our
2884 value = newSV_type(SVt_PV);
2885 SvPV_set(value, (char *) he->refcounted_he_data + 1);
2886 SvCUR_set(value, he->refcounted_he_val.refcounted_he_u_len);
2887 /* This stops anything trying to free it */
2888 SvLEN_set(value, 0);
2890 SvREADONLY_on(value);
2891 if ((he->refcounted_he_data[0] & HVrhek_typemask) == HVrhek_PV_UTF8)
2895 Perl_croak(aTHX_ "panic: refcounted_he_value bad flags %"UVxf,
2896 (UV)he->refcounted_he_data[0]);
2902 =for apidoc m|HV *|refcounted_he_chain_2hv|const struct refcounted_he *c|U32 flags
2904 Generates and returns a C<HV *> representing the content of a
2905 C<refcounted_he> chain.
2906 I<flags> is currently unused and must be zero.
2911 Perl_refcounted_he_chain_2hv(pTHX_ const struct refcounted_he *chain, U32 flags)
2915 U32 placeholders, max;
2918 Perl_croak(aTHX_ "panic: refcounted_he_chain_2hv bad flags %"UVxf,
2921 /* We could chase the chain once to get an idea of the number of keys,
2922 and call ksplit. But for now we'll make a potentially inefficient
2923 hash with only 8 entries in its array. */
2928 Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(max + 1), char);
2929 HvARRAY(hv) = (HE**)array;
2935 U32 hash = chain->refcounted_he_hash;
2937 U32 hash = HEK_HASH(chain->refcounted_he_hek);
2939 HE **oentry = &((HvARRAY(hv))[hash & max]);
2940 HE *entry = *oentry;
2943 for (; entry; entry = HeNEXT(entry)) {
2944 if (HeHASH(entry) == hash) {
2945 /* We might have a duplicate key here. If so, entry is older
2946 than the key we've already put in the hash, so if they are
2947 the same, skip adding entry. */
2949 const STRLEN klen = HeKLEN(entry);
2950 const char *const key = HeKEY(entry);
2951 if (klen == chain->refcounted_he_keylen
2952 && (!!HeKUTF8(entry)
2953 == !!(chain->refcounted_he_data[0] & HVhek_UTF8))
2954 && memEQ(key, REF_HE_KEY(chain), klen))
2957 if (HeKEY_hek(entry) == chain->refcounted_he_hek)
2959 if (HeKLEN(entry) == HEK_LEN(chain->refcounted_he_hek)
2960 && HeKUTF8(entry) == HEK_UTF8(chain->refcounted_he_hek)
2961 && memEQ(HeKEY(entry), HEK_KEY(chain->refcounted_he_hek),
2972 = share_hek_flags(REF_HE_KEY(chain),
2973 chain->refcounted_he_keylen,
2974 chain->refcounted_he_hash,
2975 (chain->refcounted_he_data[0]
2976 & (HVhek_UTF8|HVhek_WASUTF8)));
2978 HeKEY_hek(entry) = share_hek_hek(chain->refcounted_he_hek);
2980 value = refcounted_he_value(chain);
2981 if (value == &PL_sv_placeholder)
2983 HeVAL(entry) = value;
2985 /* Link it into the chain. */
2986 HeNEXT(entry) = *oentry;
2992 chain = chain->refcounted_he_next;
2996 clear_placeholders(hv, placeholders);
2997 HvTOTALKEYS(hv) -= placeholders;
3000 /* We could check in the loop to see if we encounter any keys with key
3001 flags, but it's probably not worth it, as this per-hash flag is only
3002 really meant as an optimisation for things like Storable. */
3004 DEBUG_A(Perl_hv_assert(aTHX_ hv));
3010 =for apidoc m|SV *|refcounted_he_fetch_pvn|const struct refcounted_he *chain|const char *keypv|STRLEN keylen|U32 hash|U32 flags
3012 Search along a C<refcounted_he> chain for an entry with the key specified
3013 by I<keypv> and I<keylen>. If I<flags> has the C<REFCOUNTED_HE_KEY_UTF8>
3014 bit set, the key octets are interpreted as UTF-8, otherwise they
3015 are interpreted as Latin-1. I<hash> is a precomputed hash of the key
3016 string, or zero if it has not been precomputed. Returns a mortal scalar
3017 representing the value associated with the key, or C<&PL_sv_placeholder>
3018 if there is no value associated with the key.
3024 Perl_refcounted_he_fetch_pvn(pTHX_ const struct refcounted_he *chain,
3025 const char *keypv, STRLEN keylen, U32 hash, U32 flags)
3029 PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_PVN;
3031 if (flags & ~(REFCOUNTED_HE_KEY_UTF8|REFCOUNTED_HE_EXISTS))
3032 Perl_croak(aTHX_ "panic: refcounted_he_fetch_pvn bad flags %"UVxf,
3035 return &PL_sv_placeholder;
3036 if (flags & REFCOUNTED_HE_KEY_UTF8) {
3037 /* For searching purposes, canonicalise to Latin-1 where possible. */
3038 const char *keyend = keypv + keylen, *p;
3039 STRLEN nonascii_count = 0;
3040 for (p = keypv; p != keyend; p++) {
3043 if (!((c & 0xfe) == 0xc2 && ++p != keyend &&
3044 (((U8)*p) & 0xc0) == 0x80))
3045 goto canonicalised_key;
3049 if (nonascii_count) {
3051 const char *p = keypv, *keyend = keypv + keylen;
3052 keylen -= nonascii_count;
3053 Newx(q, keylen, char);
3056 for (; p != keyend; p++, q++) {
3059 ((c & 0x80) ? ((c & 0x03) << 6) | (((U8)*++p) & 0x3f) : c);
3062 flags &= ~REFCOUNTED_HE_KEY_UTF8;
3063 canonicalised_key: ;
3065 utf8_flag = (flags & REFCOUNTED_HE_KEY_UTF8) ? HVhek_UTF8 : 0;
3067 PERL_HASH(hash, keypv, keylen);
3069 for (; chain; chain = chain->refcounted_he_next) {
3072 hash == chain->refcounted_he_hash &&
3073 keylen == chain->refcounted_he_keylen &&
3074 memEQ(REF_HE_KEY(chain), keypv, keylen) &&
3075 utf8_flag == (chain->refcounted_he_data[0] & HVhek_UTF8)
3077 hash == HEK_HASH(chain->refcounted_he_hek) &&
3078 keylen == (STRLEN)HEK_LEN(chain->refcounted_he_hek) &&
3079 memEQ(HEK_KEY(chain->refcounted_he_hek), keypv, keylen) &&
3080 utf8_flag == (HEK_FLAGS(chain->refcounted_he_hek) & HVhek_UTF8)
3083 if (flags & REFCOUNTED_HE_EXISTS)
3084 return (chain->refcounted_he_data[0] & HVrhek_typemask)
3086 ? NULL : &PL_sv_yes;
3087 return sv_2mortal(refcounted_he_value(chain));
3090 return flags & REFCOUNTED_HE_EXISTS ? NULL : &PL_sv_placeholder;
3094 =for apidoc m|SV *|refcounted_he_fetch_pv|const struct refcounted_he *chain|const char *key|U32 hash|U32 flags
3096 Like L</refcounted_he_fetch_pvn>, but takes a nul-terminated string
3097 instead of a string/length pair.
3103 Perl_refcounted_he_fetch_pv(pTHX_ const struct refcounted_he *chain,
3104 const char *key, U32 hash, U32 flags)
3106 PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_PV;
3107 return refcounted_he_fetch_pvn(chain, key, strlen(key), hash, flags);
3111 =for apidoc m|SV *|refcounted_he_fetch_sv|const struct refcounted_he *chain|SV *key|U32 hash|U32 flags
3113 Like L</refcounted_he_fetch_pvn>, but takes a Perl scalar instead of a
3120 Perl_refcounted_he_fetch_sv(pTHX_ const struct refcounted_he *chain,
3121 SV *key, U32 hash, U32 flags)
3125 PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_SV;
3126 if (flags & REFCOUNTED_HE_KEY_UTF8)
3127 Perl_croak(aTHX_ "panic: refcounted_he_fetch_sv bad flags %"UVxf,
3129 keypv = SvPV_const(key, keylen);
3131 flags |= REFCOUNTED_HE_KEY_UTF8;
3132 if (!hash && SvIsCOW_shared_hash(key))
3133 hash = SvSHARED_HASH(key);
3134 return refcounted_he_fetch_pvn(chain, keypv, keylen, hash, flags);
3138 =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
3140 Creates a new C<refcounted_he>. This consists of a single key/value
3141 pair and a reference to an existing C<refcounted_he> chain (which may
3142 be empty), and thus forms a longer chain. When using the longer chain,
3143 the new key/value pair takes precedence over any entry for the same key
3144 further along the chain.
3146 The new key is specified by I<keypv> and I<keylen>. If I<flags> has
3147 the C<REFCOUNTED_HE_KEY_UTF8> bit set, the key octets are interpreted
3148 as UTF-8, otherwise they are interpreted as Latin-1. I<hash> is
3149 a precomputed hash of the key string, or zero if it has not been
3152 I<value> is the scalar value to store for this key. I<value> is copied
3153 by this function, which thus does not take ownership of any reference
3154 to it, and later changes to the scalar will not be reflected in the
3155 value visible in the C<refcounted_he>. Complex types of scalar will not
3156 be stored with referential integrity, but will be coerced to strings.
3157 I<value> may be either null or C<&PL_sv_placeholder> to indicate that no
3158 value is to be associated with the key; this, as with any non-null value,
3159 takes precedence over the existence of a value for the key further along
3162 I<parent> points to the rest of the C<refcounted_he> chain to be
3163 attached to the new C<refcounted_he>. This function takes ownership
3164 of one reference to I<parent>, and returns one reference to the new
3170 struct refcounted_he *
3171 Perl_refcounted_he_new_pvn(pTHX_ struct refcounted_he *parent,
3172 const char *keypv, STRLEN keylen, U32 hash, SV *value, U32 flags)
3175 STRLEN value_len = 0;
3176 const char *value_p = NULL;
3180 STRLEN key_offset = 1;
3181 struct refcounted_he *he;
3182 PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_PVN;
3184 if (!value || value == &PL_sv_placeholder) {
3185 value_type = HVrhek_delete;
3186 } else if (SvPOK(value)) {
3187 value_type = HVrhek_PV;
3188 } else if (SvIOK(value)) {
3189 value_type = SvUOK((const SV *)value) ? HVrhek_UV : HVrhek_IV;
3190 } else if (!SvOK(value)) {
3191 value_type = HVrhek_undef;
3193 value_type = HVrhek_PV;
3195 is_pv = value_type == HVrhek_PV;
3197 /* Do it this way so that the SvUTF8() test is after the SvPV, in case
3198 the value is overloaded, and doesn't yet have the UTF-8flag set. */
3199 value_p = SvPV_const(value, value_len);
3201 value_type = HVrhek_PV_UTF8;
3202 key_offset = value_len + 2;
3204 hekflags = value_type;
3206 if (flags & REFCOUNTED_HE_KEY_UTF8) {
3207 /* Canonicalise to Latin-1 where possible. */
3208 const char *keyend = keypv + keylen, *p;
3209 STRLEN nonascii_count = 0;
3210 for (p = keypv; p != keyend; p++) {
3213 if (!((c & 0xfe) == 0xc2 && ++p != keyend &&
3214 (((U8)*p) & 0xc0) == 0x80))
3215 goto canonicalised_key;
3219 if (nonascii_count) {
3221 const char *p = keypv, *keyend = keypv + keylen;
3222 keylen -= nonascii_count;
3223 Newx(q, keylen, char);
3226 for (; p != keyend; p++, q++) {
3229 ((c & 0x80) ? ((c & 0x03) << 6) | (((U8)*++p) & 0x3f) : c);
3232 flags &= ~REFCOUNTED_HE_KEY_UTF8;
3233 canonicalised_key: ;
3235 if (flags & REFCOUNTED_HE_KEY_UTF8)
3236 hekflags |= HVhek_UTF8;
3238 PERL_HASH(hash, keypv, keylen);
3241 he = (struct refcounted_he*)
3242 PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
3246 he = (struct refcounted_he*)
3247 PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
3251 he->refcounted_he_next = parent;
3254 Copy(value_p, he->refcounted_he_data + 1, value_len + 1, char);
3255 he->refcounted_he_val.refcounted_he_u_len = value_len;
3256 } else if (value_type == HVrhek_IV) {
3257 he->refcounted_he_val.refcounted_he_u_iv = SvIVX(value);
3258 } else if (value_type == HVrhek_UV) {
3259 he->refcounted_he_val.refcounted_he_u_uv = SvUVX(value);
3263 he->refcounted_he_hash = hash;
3264 he->refcounted_he_keylen = keylen;
3265 Copy(keypv, he->refcounted_he_data + key_offset, keylen, char);
3267 he->refcounted_he_hek = share_hek_flags(keypv, keylen, hash, hekflags);
3270 he->refcounted_he_data[0] = hekflags;
3271 he->refcounted_he_refcnt = 1;
3277 =for apidoc m|struct refcounted_he *|refcounted_he_new_pv|struct refcounted_he *parent|const char *key|U32 hash|SV *value|U32 flags
3279 Like L</refcounted_he_new_pvn>, but takes a nul-terminated string instead
3280 of a string/length pair.
3285 struct refcounted_he *
3286 Perl_refcounted_he_new_pv(pTHX_ struct refcounted_he *parent,
3287 const char *key, U32 hash, SV *value, U32 flags)
3289 PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_PV;
3290 return refcounted_he_new_pvn(parent, key, strlen(key), hash, value, flags);
3294 =for apidoc m|struct refcounted_he *|refcounted_he_new_sv|struct refcounted_he *parent|SV *key|U32 hash|SV *value|U32 flags
3296 Like L</refcounted_he_new_pvn>, but takes a Perl scalar instead of a
3302 struct refcounted_he *
3303 Perl_refcounted_he_new_sv(pTHX_ struct refcounted_he *parent,
3304 SV *key, U32 hash, SV *value, U32 flags)
3308 PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_SV;
3309 if (flags & REFCOUNTED_HE_KEY_UTF8)
3310 Perl_croak(aTHX_ "panic: refcounted_he_new_sv bad flags %"UVxf,
3312 keypv = SvPV_const(key, keylen);
3314 flags |= REFCOUNTED_HE_KEY_UTF8;
3315 if (!hash && SvIsCOW_shared_hash(key))
3316 hash = SvSHARED_HASH(key);
3317 return refcounted_he_new_pvn(parent, keypv, keylen, hash, value, flags);
3321 =for apidoc m|void|refcounted_he_free|struct refcounted_he *he
3323 Decrements the reference count of a C<refcounted_he> by one. If the
3324 reference count reaches zero the structure's memory is freed, which
3325 (recursively) causes a reduction of its parent C<refcounted_he>'s
3326 reference count. It is safe to pass a null pointer to this function:
3327 no action occurs in this case.
3333 Perl_refcounted_he_free(pTHX_ struct refcounted_he *he) {
3335 PERL_UNUSED_CONTEXT;
3338 struct refcounted_he *copy;
3342 new_count = --he->refcounted_he_refcnt;
3343 HINTS_REFCNT_UNLOCK;
3349 #ifndef USE_ITHREADS
3350 unshare_hek_or_pvn (he->refcounted_he_hek, 0, 0, 0);
3353 he = he->refcounted_he_next;
3354 PerlMemShared_free(copy);
3359 =for apidoc m|struct refcounted_he *|refcounted_he_inc|struct refcounted_he *he
3361 Increment the reference count of a C<refcounted_he>. The pointer to the
3362 C<refcounted_he> is also returned. It is safe to pass a null pointer
3363 to this function: no action occurs and a null pointer is returned.
3368 struct refcounted_he *
3369 Perl_refcounted_he_inc(pTHX_ struct refcounted_he *he)
3374 he->refcounted_he_refcnt++;
3375 HINTS_REFCNT_UNLOCK;
3381 =for apidoc cop_fetch_label
3383 Returns the label attached to a cop.
3384 The flags pointer may be set to C<SVf_UTF8> or 0.
3389 /* pp_entereval is aware that labels are stored with a key ':' at the top of
3392 Perl_cop_fetch_label(pTHX_ COP *const cop, STRLEN *len, U32 *flags) {
3393 struct refcounted_he *const chain = cop->cop_hints_hash;
3395 PERL_ARGS_ASSERT_COP_FETCH_LABEL;
3400 if (chain->refcounted_he_keylen != 1)
3402 if (*REF_HE_KEY(chain) != ':')
3405 if ((STRLEN)HEK_LEN(chain->refcounted_he_hek) != 1)
3407 if (*HEK_KEY(chain->refcounted_he_hek) != ':')
3410 /* Stop anyone trying to really mess us up by adding their own value for
3412 if ((chain->refcounted_he_data[0] & HVrhek_typemask) != HVrhek_PV
3413 && (chain->refcounted_he_data[0] & HVrhek_typemask) != HVrhek_PV_UTF8)
3417 *len = chain->refcounted_he_val.refcounted_he_u_len;
3419 *flags = ((chain->refcounted_he_data[0] & HVrhek_typemask)
3420 == HVrhek_PV_UTF8) ? SVf_UTF8 : 0;
3422 return chain->refcounted_he_data + 1;
3426 =for apidoc cop_store_label
3428 Save a label into a C<cop_hints_hash>. You need to set flags to C<SVf_UTF8>
3435 Perl_cop_store_label(pTHX_ COP *const cop, const char *label, STRLEN len,
3439 PERL_ARGS_ASSERT_COP_STORE_LABEL;
3441 if (flags & ~(SVf_UTF8))
3442 Perl_croak(aTHX_ "panic: cop_store_label illegal flag bits 0x%" UVxf,
3444 labelsv = newSVpvn_flags(label, len, SVs_TEMP);
3445 if (flags & SVf_UTF8)
3448 = refcounted_he_new_pvs(cop->cop_hints_hash, ":", labelsv, 0);
3452 =for apidoc hv_assert
3454 Check that a hash is in an internally consistent state.
3462 Perl_hv_assert(pTHX_ HV *hv)
3467 int placeholders = 0;
3470 const I32 riter = HvRITER_get(hv);
3471 HE *eiter = HvEITER_get(hv);
3473 PERL_ARGS_ASSERT_HV_ASSERT;
3475 (void)hv_iterinit(hv);
3477 while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
3478 /* sanity check the values */
3479 if (HeVAL(entry) == &PL_sv_placeholder)
3483 /* sanity check the keys */
3484 if (HeSVKEY(entry)) {
3485 NOOP; /* Don't know what to check on SV keys. */
3486 } else if (HeKUTF8(entry)) {
3488 if (HeKWASUTF8(entry)) {
3489 PerlIO_printf(Perl_debug_log,
3490 "hash key has both WASUTF8 and UTF8: '%.*s'\n",
3491 (int) HeKLEN(entry), HeKEY(entry));
3494 } else if (HeKWASUTF8(entry))
3497 if (!SvTIED_mg((const SV *)hv, PERL_MAGIC_tied)) {
3498 static const char bad_count[] = "Count %d %s(s), but hash reports %d\n";
3499 const int nhashkeys = HvUSEDKEYS(hv);
3500 const int nhashplaceholders = HvPLACEHOLDERS_get(hv);
3502 if (nhashkeys != real) {
3503 PerlIO_printf(Perl_debug_log, bad_count, real, "keys", nhashkeys );
3506 if (nhashplaceholders != placeholders) {
3507 PerlIO_printf(Perl_debug_log, bad_count, placeholders, "placeholder", nhashplaceholders );
3511 if (withflags && ! HvHASKFLAGS(hv)) {
3512 PerlIO_printf(Perl_debug_log,
3513 "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
3518 sv_dump(MUTABLE_SV(hv));
3520 HvRITER_set(hv, riter); /* Restore hash iterator state */
3521 HvEITER_set(hv, eiter);
3528 * c-indentation-style: bsd
3530 * indent-tabs-mode: nil
3533 * ex: set ts=8 sts=4 sw=4 et: