This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Document that [ah]v_undef/clear may free the [ah]v
[perl5.git] / hv.c
CommitLineData
a0d0e21e 1/* hv.c
79072805 2 *
1129b882
NC
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
79072805
LW
5 *
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.
8 *
a0d0e21e
LW
9 */
10
11/*
4ac71550
TC
12 * I sit beside the fire and think
13 * of all that I have seen.
14 * --Bilbo
15 *
16 * [p.278 of _The Lord of the Rings_, II/iii: "The Ring Goes South"]
79072805
LW
17 */
18
d5afce77
RB
19/*
20=head1 Hash Manipulation Functions
166f8a29 21
db4fbf16
FC
22A HV structure represents a Perl hash. It consists mainly of an array
23of pointers, each of which points to a linked list of HE structures. The
166f8a29 24array is indexed by the hash function of the key, so each linked list
db4fbf16 25represents all the hash entries with the same hash value. Each HE contains
166f8a29
DM
26a pointer to the actual value, plus a pointer to a HEK structure which
27holds the key and hash value.
28
29=cut
30
d5afce77
RB
31*/
32
79072805 33#include "EXTERN.h"
864dbfa3 34#define PERL_IN_HV_C
3d78eb94 35#define PERL_HASH_INTERNAL_ACCESS
79072805
LW
36#include "perl.h"
37
d8012aaf 38#define HV_MAX_LENGTH_BEFORE_SPLIT 14
fdcd69b6 39
d75ce684 40static const char S_strtab_error[]
5d2b1485
NC
41 = "Cannot modify shared string table in hv_%s";
42
c941fb51
NC
43#ifdef PURIFY
44
45#define new_HE() (HE*)safemalloc(sizeof(HE))
46#define del_HE(p) safefree((char*)p)
47
48#else
49
76e3520e 50STATIC HE*
cea2e8a9 51S_new_he(pTHX)
4633a7c4 52{
97aff369 53 dVAR;
4633a7c4 54 HE* he;
0bd48802 55 void ** const root = &PL_body_roots[HE_SVSLOT];
6a93a7e5 56
6a93a7e5 57 if (!*root)
1e30fcd5 58 Perl_more_bodies(aTHX_ HE_SVSLOT, sizeof(HE), PERL_ARENA_SIZE);
10edeb5d 59 he = (HE*) *root;
ce3e5c45 60 assert(he);
6a93a7e5 61 *root = HeNEXT(he);
333f433b 62 return he;
4633a7c4
LW
63}
64
c941fb51
NC
65#define new_HE() new_he()
66#define del_HE(p) \
67 STMT_START { \
6a93a7e5
NC
68 HeNEXT(p) = (HE*)(PL_body_roots[HE_SVSLOT]); \
69 PL_body_roots[HE_SVSLOT] = p; \
c941fb51 70 } STMT_END
d33b2eba 71
d33b2eba 72
d33b2eba
GS
73
74#endif
75
76e3520e 76STATIC HEK *
5f66b61c 77S_save_hek_flags(const char *str, I32 len, U32 hash, int flags)
bbce6d69 78{
35a4481c 79 const int flags_masked = flags & HVhek_MASK;
bbce6d69 80 char *k;
81 register HEK *hek;
1c846c1f 82
7918f24d
NC
83 PERL_ARGS_ASSERT_SAVE_HEK_FLAGS;
84
a02a5408 85 Newx(k, HEK_BASESIZE + len + 2, char);
bbce6d69 86 hek = (HEK*)k;
ff68c719 87 Copy(str, HEK_KEY(hek), len, char);
e05949c7 88 HEK_KEY(hek)[len] = 0;
ff68c719 89 HEK_LEN(hek) = len;
90 HEK_HASH(hek) = hash;
45e34800 91 HEK_FLAGS(hek) = (unsigned char)flags_masked | HVhek_UNSHARED;
dcf933a4
NC
92
93 if (flags & HVhek_FREEKEY)
94 Safefree(str);
bbce6d69 95 return hek;
96}
97
4a31713e 98/* free the pool of temporary HE/HEK pairs returned by hv_fetch_ent
dd28f7bb
DM
99 * for tied hashes */
100
101void
102Perl_free_tied_hv_pool(pTHX)
103{
97aff369 104 dVAR;
dd28f7bb
DM
105 HE *he = PL_hv_fetch_ent_mh;
106 while (he) {
9d4ba2ae 107 HE * const ohe = he;
dd28f7bb 108 Safefree(HeKEY_hek(he));
dd28f7bb
DM
109 he = HeNEXT(he);
110 del_HE(ohe);
111 }
4608196e 112 PL_hv_fetch_ent_mh = NULL;
dd28f7bb
DM
113}
114
d18c6117 115#if defined(USE_ITHREADS)
0bff533c
NC
116HEK *
117Perl_hek_dup(pTHX_ HEK *source, CLONE_PARAMS* param)
118{
566771cc 119 HEK *shared;
9d4ba2ae 120
7918f24d 121 PERL_ARGS_ASSERT_HEK_DUP;
9d4ba2ae 122 PERL_UNUSED_ARG(param);
0bff533c 123
566771cc
NC
124 if (!source)
125 return NULL;
126
127 shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
0bff533c
NC
128 if (shared) {
129 /* We already shared this hash key. */
454f1e26 130 (void)share_hek_hek(shared);
0bff533c
NC
131 }
132 else {
658b4a4a 133 shared
6e838c70
NC
134 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
135 HEK_HASH(source), HEK_FLAGS(source));
658b4a4a 136 ptr_table_store(PL_ptr_table, source, shared);
0bff533c 137 }
658b4a4a 138 return shared;
0bff533c
NC
139}
140
d18c6117 141HE *
5c4138a0 142Perl_he_dup(pTHX_ const HE *e, bool shared, CLONE_PARAMS* param)
d18c6117
GS
143{
144 HE *ret;
145
7918f24d
NC
146 PERL_ARGS_ASSERT_HE_DUP;
147
d18c6117 148 if (!e)
4608196e 149 return NULL;
7766f137
GS
150 /* look for it in the table first */
151 ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
152 if (ret)
153 return ret;
154
155 /* create anew and remember what it is */
d33b2eba 156 ret = new_HE();
7766f137
GS
157 ptr_table_store(PL_ptr_table, e, ret);
158
d2d73c3e 159 HeNEXT(ret) = he_dup(HeNEXT(e),shared, param);
dd28f7bb
DM
160 if (HeKLEN(e) == HEf_SVKEY) {
161 char *k;
ad64d0ec 162 Newx(k, HEK_BASESIZE + sizeof(const SV *), char);
dd28f7bb 163 HeKEY_hek(ret) = (HEK*)k;
a09252eb 164 HeKEY_sv(ret) = sv_dup_inc(HeKEY_sv(e), param);
dd28f7bb 165 }
c21d1a0f 166 else if (shared) {
0bff533c
NC
167 /* This is hek_dup inlined, which seems to be important for speed
168 reasons. */
1b6737cc 169 HEK * const source = HeKEY_hek(e);
658b4a4a 170 HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
c21d1a0f
NC
171
172 if (shared) {
173 /* We already shared this hash key. */
454f1e26 174 (void)share_hek_hek(shared);
c21d1a0f
NC
175 }
176 else {
658b4a4a 177 shared
6e838c70
NC
178 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
179 HEK_HASH(source), HEK_FLAGS(source));
658b4a4a 180 ptr_table_store(PL_ptr_table, source, shared);
c21d1a0f 181 }
658b4a4a 182 HeKEY_hek(ret) = shared;
c21d1a0f 183 }
d18c6117 184 else
19692e8d
NC
185 HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
186 HeKFLAGS(e));
a09252eb 187 HeVAL(ret) = sv_dup_inc(HeVAL(e), param);
d18c6117
GS
188 return ret;
189}
190#endif /* USE_ITHREADS */
191
1b1f1335 192static void
2393f1b9
JH
193S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
194 const char *msg)
1b1f1335 195{
1b6737cc 196 SV * const sv = sv_newmortal();
7918f24d
NC
197
198 PERL_ARGS_ASSERT_HV_NOTALLOWED;
199
19692e8d 200 if (!(flags & HVhek_FREEKEY)) {
1b1f1335
NIS
201 sv_setpvn(sv, key, klen);
202 }
203 else {
204 /* Need to free saved eventually assign to mortal SV */
34c3c4e3 205 /* XXX is this line an error ???: SV *sv = sv_newmortal(); */
1b1f1335
NIS
206 sv_usepvn(sv, (char *) key, klen);
207 }
19692e8d 208 if (flags & HVhek_UTF8) {
1b1f1335
NIS
209 SvUTF8_on(sv);
210 }
be2597df 211 Perl_croak(aTHX_ msg, SVfARG(sv));
1b1f1335
NIS
212}
213
fde52b5c 214/* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
215 * contains an SV* */
216
34a6f7b4
NC
217/*
218=for apidoc hv_store
219
a05d6c5d
TC
220Stores an SV in a hash. The hash key is specified as C<key> and the
221absolute value of C<klen> is the length of the key. If C<klen> is
222negative the key is assumed to be in UTF-8-encoded Unicode. The
223C<hash> parameter is the precomputed hash value; if it is zero then
224Perl will compute it.
225
226The return value will be
34a6f7b4
NC
227NULL if the operation failed or if the value did not need to be actually
228stored within the hash (as in the case of tied hashes). Otherwise it can
229be dereferenced to get the original C<SV*>. Note that the caller is
230responsible for suitably incrementing the reference count of C<val> before
231the call, and decrementing it if the function returned NULL. Effectively
232a successful hv_store takes ownership of one reference to C<val>. This is
233usually what you want; a newly created SV has a reference count of one, so
234if all your code does is create SVs then store them in a hash, hv_store
235will own the only reference to the new SV, and your code doesn't need to do
236anything further to tidy up. hv_store is not implemented as a call to
237hv_store_ent, and does not create a temporary SV for the key, so if your
238key data is not already in SV form then use hv_store in preference to
239hv_store_ent.
240
241See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
242information on how to use this function on tied hashes.
243
34a6f7b4
NC
244=for apidoc hv_store_ent
245
246Stores C<val> in a hash. The hash key is specified as C<key>. The C<hash>
247parameter is the precomputed hash value; if it is zero then Perl will
248compute it. The return value is the new hash entry so created. It will be
249NULL if the operation failed or if the value did not need to be actually
250stored within the hash (as in the case of tied hashes). Otherwise the
251contents of the return value can be accessed using the C<He?> macros
252described here. Note that the caller is responsible for suitably
253incrementing the reference count of C<val> before the call, and
254decrementing it if the function returned NULL. Effectively a successful
255hv_store_ent takes ownership of one reference to C<val>. This is
256usually what you want; a newly created SV has a reference count of one, so
257if all your code does is create SVs then store them in a hash, hv_store
258will own the only reference to the new SV, and your code doesn't need to do
259anything further to tidy up. Note that hv_store_ent only reads the C<key>;
260unlike C<val> it does not take ownership of it, so maintaining the correct
261reference count on C<key> is entirely the caller's responsibility. hv_store
262is not implemented as a call to hv_store_ent, and does not create a temporary
263SV for the key, so if your key data is not already in SV form then use
264hv_store in preference to hv_store_ent.
265
266See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
267information on how to use this function on tied hashes.
268
34a6f7b4
NC
269=for apidoc hv_exists
270
271Returns a boolean indicating whether the specified hash key exists. The
a05d6c5d
TC
272absolute value of C<klen> is the length of the key. If C<klen> is
273negative the key is assumed to be in UTF-8-encoded Unicode.
34a6f7b4 274
954c1994
GS
275=for apidoc hv_fetch
276
a05d6c5d
TC
277Returns the SV which corresponds to the specified key in the hash.
278The absolute value of C<klen> is the length of the key. If C<klen> is
279negative the key is assumed to be in UTF-8-encoded Unicode. If
280C<lval> is set then the fetch will be part of a store. Check that the
281return value is non-null before dereferencing it to an C<SV*>.
954c1994 282
96f1132b 283See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
954c1994
GS
284information on how to use this function on tied hashes.
285
34a6f7b4
NC
286=for apidoc hv_exists_ent
287
db4fbf16
FC
288Returns a boolean indicating whether
289the specified hash key exists. C<hash>
34a6f7b4
NC
290can be a valid precomputed hash value, or 0 to ask for it to be
291computed.
292
293=cut
294*/
295
d1be9408 296/* returns an HE * structure with the all fields set */
fde52b5c 297/* note that hent_val will be a mortal sv for MAGICAL hashes */
954c1994
GS
298/*
299=for apidoc hv_fetch_ent
300
301Returns the hash entry which corresponds to the specified key in the hash.
302C<hash> must be a valid precomputed hash number for the given C<key>, or 0
303if you want the function to compute it. IF C<lval> is set then the fetch
304will be part of a store. Make sure the return value is non-null before
b24b84ef 305accessing it. The return value when C<hv> is a tied hash is a pointer to a
954c1994 306static location, so be sure to make a copy of the structure if you need to
1c846c1f 307store it somewhere.
954c1994 308
96f1132b 309See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
954c1994
GS
310information on how to use this function on tied hashes.
311
312=cut
313*/
314
a038e571
NC
315/* Common code for hv_delete()/hv_exists()/hv_fetch()/hv_store() */
316void *
317Perl_hv_common_key_len(pTHX_ HV *hv, const char *key, I32 klen_i32,
318 const int action, SV *val, const U32 hash)
319{
320 STRLEN klen;
321 int flags;
322
7918f24d
NC
323 PERL_ARGS_ASSERT_HV_COMMON_KEY_LEN;
324
a038e571
NC
325 if (klen_i32 < 0) {
326 klen = -klen_i32;
327 flags = HVhek_UTF8;
328 } else {
329 klen = klen_i32;
330 flags = 0;
331 }
332 return hv_common(hv, NULL, key, klen, flags, action, val, hash);
333}
334
63c89345 335void *
d3ba3f5c
NC
336Perl_hv_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
337 int flags, int action, SV *val, register U32 hash)
113738bb 338{
27da23d5 339 dVAR;
b2c64049 340 XPVHV* xhv;
b2c64049
NC
341 HE *entry;
342 HE **oentry;
fde52b5c 343 SV *sv;
da58a35d 344 bool is_utf8;
113738bb 345 int masked_flags;
3c84c864 346 const int return_svp = action & HV_FETCH_JUST_SV;
fde52b5c 347
348 if (!hv)
a4fc7abc 349 return NULL;
e4787c0c 350 if (SvTYPE(hv) == (svtype)SVTYPEMASK)
8265e3d1
NC
351 return NULL;
352
353 assert(SvTYPE(hv) == SVt_PVHV);
fde52b5c 354
bdee33e4 355 if (SvSMAGICAL(hv) && SvGMAGICAL(hv) && !(action & HV_DISABLE_UVAR_XKEY)) {
fda2d18a 356 MAGIC* mg;
ad64d0ec 357 if ((mg = mg_find((const SV *)hv, PERL_MAGIC_uvar))) {
fda2d18a
NC
358 struct ufuncs * const uf = (struct ufuncs *)mg->mg_ptr;
359 if (uf->uf_set == NULL) {
360 SV* obj = mg->mg_obj;
361
362 if (!keysv) {
59cd0e26
NC
363 keysv = newSVpvn_flags(key, klen, SVs_TEMP |
364 ((flags & HVhek_UTF8)
365 ? SVf_UTF8 : 0));
fda2d18a
NC
366 }
367
368 mg->mg_obj = keysv; /* pass key */
369 uf->uf_index = action; /* pass action */
ad64d0ec 370 magic_getuvar(MUTABLE_SV(hv), mg);
fda2d18a
NC
371 keysv = mg->mg_obj; /* may have changed */
372 mg->mg_obj = obj;
373
374 /* If the key may have changed, then we need to invalidate
375 any passed-in computed hash value. */
376 hash = 0;
377 }
378 }
bdee33e4 379 }
113738bb 380 if (keysv) {
e593d2fe
AE
381 if (flags & HVhek_FREEKEY)
382 Safefree(key);
5c144d81 383 key = SvPV_const(keysv, klen);
113738bb 384 is_utf8 = (SvUTF8(keysv) != 0);
44b87b50
NC
385 if (SvIsCOW_shared_hash(keysv)) {
386 flags = HVhek_KEYCANONICAL | (is_utf8 ? HVhek_UTF8 : 0);
387 } else {
388 flags = 0;
389 }
113738bb 390 } else {
c1fe5510 391 is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
113738bb 392 }
113738bb 393
9dbc5603 394 if (action & HV_DELETE) {
3c84c864
NC
395 return (void *) hv_delete_common(hv, keysv, key, klen,
396 flags | (is_utf8 ? HVhek_UTF8 : 0),
397 action, hash);
9dbc5603
NC
398 }
399
b2c64049 400 xhv = (XPVHV*)SvANY(hv);
7f66fda2 401 if (SvMAGICAL(hv)) {
6136c704 402 if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS))) {
ad64d0ec
NC
403 if (mg_find((const SV *)hv, PERL_MAGIC_tied)
404 || SvGMAGICAL((const SV *)hv))
e62cc96a 405 {
3c84c864 406 /* FIXME should be able to skimp on the HE/HEK here when
7f66fda2 407 HV_FETCH_JUST_SV is true. */
7f66fda2 408 if (!keysv) {
740cce10
NC
409 keysv = newSVpvn_utf8(key, klen, is_utf8);
410 } else {
7f66fda2 411 keysv = newSVsv(keysv);
113738bb 412 }
44a2ac75 413 sv = sv_newmortal();
ad64d0ec 414 mg_copy(MUTABLE_SV(hv), sv, (char *)keysv, HEf_SVKEY);
7f66fda2
NC
415
416 /* grab a fake HE/HEK pair from the pool or make a new one */
417 entry = PL_hv_fetch_ent_mh;
418 if (entry)
419 PL_hv_fetch_ent_mh = HeNEXT(entry);
420 else {
421 char *k;
422 entry = new_HE();
ad64d0ec 423 Newx(k, HEK_BASESIZE + sizeof(const SV *), char);
7f66fda2
NC
424 HeKEY_hek(entry) = (HEK*)k;
425 }
4608196e 426 HeNEXT(entry) = NULL;
7f66fda2
NC
427 HeSVKEY_set(entry, keysv);
428 HeVAL(entry) = sv;
429 sv_upgrade(sv, SVt_PVLV);
430 LvTYPE(sv) = 'T';
431 /* so we can free entry when freeing sv */
ad64d0ec 432 LvTARG(sv) = MUTABLE_SV(entry);
7f66fda2
NC
433
434 /* XXX remove at some point? */
435 if (flags & HVhek_FREEKEY)
436 Safefree(key);
437
3c84c864
NC
438 if (return_svp) {
439 return entry ? (void *) &HeVAL(entry) : NULL;
440 }
441 return (void *) entry;
113738bb 442 }
7f66fda2 443#ifdef ENV_IS_CASELESS
ad64d0ec 444 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
7f66fda2
NC
445 U32 i;
446 for (i = 0; i < klen; ++i)
447 if (isLOWER(key[i])) {
086cb327
NC
448 /* Would be nice if we had a routine to do the
449 copy and upercase in a single pass through. */
0bd48802 450 const char * const nkey = strupr(savepvn(key,klen));
086cb327
NC
451 /* Note that this fetch is for nkey (the uppercased
452 key) whereas the store is for key (the original) */
63c89345
NC
453 void *result = hv_common(hv, NULL, nkey, klen,
454 HVhek_FREEKEY, /* free nkey */
455 0 /* non-LVAL fetch */
3c84c864
NC
456 | HV_DISABLE_UVAR_XKEY
457 | return_svp,
63c89345
NC
458 NULL /* no value */,
459 0 /* compute hash */);
26488bcf 460 if (!result && (action & HV_FETCH_LVALUE)) {
086cb327
NC
461 /* This call will free key if necessary.
462 Do it this way to encourage compiler to tail
463 call optimise. */
63c89345
NC
464 result = hv_common(hv, keysv, key, klen, flags,
465 HV_FETCH_ISSTORE
3c84c864
NC
466 | HV_DISABLE_UVAR_XKEY
467 | return_svp,
63c89345 468 newSV(0), hash);
086cb327
NC
469 } else {
470 if (flags & HVhek_FREEKEY)
471 Safefree(key);
472 }
63c89345 473 return result;
7f66fda2 474 }
902173a3 475 }
7f66fda2
NC
476#endif
477 } /* ISFETCH */
478 else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
ad64d0ec
NC
479 if (mg_find((const SV *)hv, PERL_MAGIC_tied)
480 || SvGMAGICAL((const SV *)hv)) {
b2c64049
NC
481 /* I don't understand why hv_exists_ent has svret and sv,
482 whereas hv_exists only had one. */
9d4ba2ae 483 SV * const svret = sv_newmortal();
b2c64049 484 sv = sv_newmortal();
7f66fda2
NC
485
486 if (keysv || is_utf8) {
487 if (!keysv) {
740cce10 488 keysv = newSVpvn_utf8(key, klen, TRUE);
7f66fda2
NC
489 } else {
490 keysv = newSVsv(keysv);
491 }
ad64d0ec 492 mg_copy(MUTABLE_SV(hv), sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
b2c64049 493 } else {
ad64d0ec 494 mg_copy(MUTABLE_SV(hv), sv, key, klen);
7f66fda2 495 }
b2c64049
NC
496 if (flags & HVhek_FREEKEY)
497 Safefree(key);
7f66fda2
NC
498 magic_existspack(svret, mg_find(sv, PERL_MAGIC_tiedelem));
499 /* This cast somewhat evil, but I'm merely using NULL/
500 not NULL to return the boolean exists.
501 And I know hv is not NULL. */
3c84c864 502 return SvTRUE(svret) ? (void *)hv : NULL;
e7152ba2 503 }
7f66fda2 504#ifdef ENV_IS_CASELESS
ad64d0ec 505 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
7f66fda2 506 /* XXX This code isn't UTF8 clean. */
a15d23f8 507 char * const keysave = (char * const)key;
b2c64049
NC
508 /* Will need to free this, so set FREEKEY flag. */
509 key = savepvn(key,klen);
510 key = (const char*)strupr((char*)key);
6136c704 511 is_utf8 = FALSE;
7f66fda2 512 hash = 0;
8b4f7dd5 513 keysv = 0;
b2c64049
NC
514
515 if (flags & HVhek_FREEKEY) {
516 Safefree(keysave);
517 }
518 flags |= HVhek_FREEKEY;
7f66fda2 519 }
902173a3 520#endif
7f66fda2 521 } /* ISEXISTS */
b2c64049
NC
522 else if (action & HV_FETCH_ISSTORE) {
523 bool needs_copy;
524 bool needs_store;
525 hv_magic_check (hv, &needs_copy, &needs_store);
526 if (needs_copy) {
a3b680e6 527 const bool save_taint = PL_tainted;
b2c64049
NC
528 if (keysv || is_utf8) {
529 if (!keysv) {
740cce10 530 keysv = newSVpvn_utf8(key, klen, TRUE);
b2c64049
NC
531 }
532 if (PL_tainting)
533 PL_tainted = SvTAINTED(keysv);
534 keysv = sv_2mortal(newSVsv(keysv));
ad64d0ec 535 mg_copy(MUTABLE_SV(hv), val, (char*)keysv, HEf_SVKEY);
b2c64049 536 } else {
ad64d0ec 537 mg_copy(MUTABLE_SV(hv), val, key, klen);
b2c64049
NC
538 }
539
540 TAINT_IF(save_taint);
1baaf5d7 541 if (!needs_store) {
b2c64049
NC
542 if (flags & HVhek_FREEKEY)
543 Safefree(key);
4608196e 544 return NULL;
b2c64049
NC
545 }
546#ifdef ENV_IS_CASELESS
ad64d0ec 547 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
b2c64049
NC
548 /* XXX This code isn't UTF8 clean. */
549 const char *keysave = key;
550 /* Will need to free this, so set FREEKEY flag. */
551 key = savepvn(key,klen);
552 key = (const char*)strupr((char*)key);
6136c704 553 is_utf8 = FALSE;
b2c64049 554 hash = 0;
8b4f7dd5 555 keysv = 0;
b2c64049
NC
556
557 if (flags & HVhek_FREEKEY) {
558 Safefree(keysave);
559 }
560 flags |= HVhek_FREEKEY;
561 }
562#endif
563 }
564 } /* ISSTORE */
7f66fda2 565 } /* SvMAGICAL */
fde52b5c 566
7b2c381c 567 if (!HvARRAY(hv)) {
b2c64049 568 if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
fde52b5c 569#ifdef DYNAMIC_ENV_FETCH /* if it's an %ENV lookup, we may get it on the fly */
ad64d0ec
NC
570 || (SvRMAGICAL((const SV *)hv)
571 && mg_find((const SV *)hv, PERL_MAGIC_env))
fde52b5c 572#endif
d58e6666
NC
573 ) {
574 char *array;
a02a5408 575 Newxz(array,
cbec9347 576 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
d58e6666
NC
577 char);
578 HvARRAY(hv) = (HE**)array;
579 }
7f66fda2
NC
580#ifdef DYNAMIC_ENV_FETCH
581 else if (action & HV_FETCH_ISEXISTS) {
582 /* for an %ENV exists, if we do an insert it's by a recursive
583 store call, so avoid creating HvARRAY(hv) right now. */
584 }
585#endif
113738bb
NC
586 else {
587 /* XXX remove at some point? */
588 if (flags & HVhek_FREEKEY)
589 Safefree(key);
590
3c84c864 591 return NULL;
113738bb 592 }
fde52b5c 593 }
594
44b87b50 595 if (is_utf8 & !(flags & HVhek_KEYCANONICAL)) {
41d88b63 596 char * const keysave = (char *)key;
f9a63242 597 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
19692e8d 598 if (is_utf8)
c1fe5510
NC
599 flags |= HVhek_UTF8;
600 else
601 flags &= ~HVhek_UTF8;
7f66fda2
NC
602 if (key != keysave) {
603 if (flags & HVhek_FREEKEY)
604 Safefree(keysave);
19692e8d 605 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
527df579
NC
606 /* If the caller calculated a hash, it was on the sequence of
607 octets that are the UTF-8 form. We've now changed the sequence
608 of octets stored to that of the equivalent byte representation,
609 so the hash we need is different. */
610 hash = 0;
7f66fda2 611 }
19692e8d 612 }
f9a63242 613
f8d50d94
DM
614 if (HvREHASH(hv) || (!hash && !(keysv && (SvIsCOW_shared_hash(keysv)))))
615 PERL_HASH_INTERNAL_(hash, key, klen, HvREHASH(hv));
616 else if (!hash)
617 hash = SvSHARED_HASH(keysv);
618
619 /* We don't have a pointer to the hv, so we have to replicate the
620 flag into every HEK, so that hv_iterkeysv can see it.
621 And yes, you do need this even though you are not "storing" because
622 you can flip the flags below if doing an lval lookup. (And that
623 was put in to give the semantics Andreas was expecting.) */
624 if (HvREHASH(hv))
fdcd69b6 625 flags |= HVhek_REHASH;
effa1e2d 626
113738bb
NC
627 masked_flags = (flags & HVhek_MASK);
628
7f66fda2 629#ifdef DYNAMIC_ENV_FETCH
4608196e 630 if (!HvARRAY(hv)) entry = NULL;
7f66fda2
NC
631 else
632#endif
b2c64049 633 {
7b2c381c 634 entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
b2c64049 635 }
0298d7b9 636 for (; entry; entry = HeNEXT(entry)) {
fde52b5c 637 if (HeHASH(entry) != hash) /* strings can't be equal */
638 continue;
eb160463 639 if (HeKLEN(entry) != (I32)klen)
fde52b5c 640 continue;
1c846c1f 641 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
fde52b5c 642 continue;
113738bb 643 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
c3654f1a 644 continue;
b2c64049
NC
645
646 if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
647 if (HeKFLAGS(entry) != masked_flags) {
648 /* We match if HVhek_UTF8 bit in our flags and hash key's
649 match. But if entry was set previously with HVhek_WASUTF8
650 and key now doesn't (or vice versa) then we should change
651 the key's flag, as this is assignment. */
652 if (HvSHAREKEYS(hv)) {
653 /* Need to swap the key we have for a key with the flags we
654 need. As keys are shared we can't just write to the
655 flag, so we share the new one, unshare the old one. */
6136c704 656 HEK * const new_hek = share_hek_flags(key, klen, hash,
6e838c70 657 masked_flags);
b2c64049
NC
658 unshare_hek (HeKEY_hek(entry));
659 HeKEY_hek(entry) = new_hek;
660 }
5d2b1485
NC
661 else if (hv == PL_strtab) {
662 /* PL_strtab is usually the only hash without HvSHAREKEYS,
663 so putting this test here is cheap */
664 if (flags & HVhek_FREEKEY)
665 Safefree(key);
666 Perl_croak(aTHX_ S_strtab_error,
667 action & HV_FETCH_LVALUE ? "fetch" : "store");
668 }
b2c64049
NC
669 else
670 HeKFLAGS(entry) = masked_flags;
671 if (masked_flags & HVhek_ENABLEHVKFLAGS)
672 HvHASKFLAGS_on(hv);
673 }
674 if (HeVAL(entry) == &PL_sv_placeholder) {
675 /* yes, can store into placeholder slot */
676 if (action & HV_FETCH_LVALUE) {
677 if (SvMAGICAL(hv)) {
678 /* This preserves behaviour with the old hv_fetch
679 implementation which at this point would bail out
680 with a break; (at "if we find a placeholder, we
681 pretend we haven't found anything")
682
683 That break mean that if a placeholder were found, it
684 caused a call into hv_store, which in turn would
685 check magic, and if there is no magic end up pretty
686 much back at this point (in hv_store's code). */
687 break;
688 }
486ec47a 689 /* LVAL fetch which actually needs a store. */
561b68a9 690 val = newSV(0);
ca732855 691 HvPLACEHOLDERS(hv)--;
b2c64049
NC
692 } else {
693 /* store */
694 if (val != &PL_sv_placeholder)
ca732855 695 HvPLACEHOLDERS(hv)--;
b2c64049
NC
696 }
697 HeVAL(entry) = val;
698 } else if (action & HV_FETCH_ISSTORE) {
cefd5c7c 699 SvREFCNT_dec(HeVAL(entry));
b2c64049
NC
700 HeVAL(entry) = val;
701 }
27bcc0a7 702 } else if (HeVAL(entry) == &PL_sv_placeholder) {
b2c64049
NC
703 /* if we find a placeholder, we pretend we haven't found
704 anything */
8aacddc1 705 break;
b2c64049 706 }
113738bb
NC
707 if (flags & HVhek_FREEKEY)
708 Safefree(key);
3c84c864
NC
709 if (return_svp) {
710 return entry ? (void *) &HeVAL(entry) : NULL;
711 }
fde52b5c 712 return entry;
713 }
714#ifdef DYNAMIC_ENV_FETCH /* %ENV lookup? If so, try to fetch the value now */
0ed29950 715 if (!(action & HV_FETCH_ISSTORE)
ad64d0ec
NC
716 && SvRMAGICAL((const SV *)hv)
717 && mg_find((const SV *)hv, PERL_MAGIC_env)) {
a6c40364 718 unsigned long len;
9d4ba2ae 719 const char * const env = PerlEnv_ENVgetenv_len(key,&len);
a6c40364
GS
720 if (env) {
721 sv = newSVpvn(env,len);
722 SvTAINTED_on(sv);
d3ba3f5c 723 return hv_common(hv, keysv, key, klen, flags,
3c84c864
NC
724 HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
725 sv, hash);
a6c40364 726 }
fde52b5c 727 }
728#endif
7f66fda2
NC
729
730 if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
c445ea15 731 hv_notallowed(flags, key, klen,
c8cd6465
NC
732 "Attempt to access disallowed key '%"SVf"' in"
733 " a restricted hash");
1b1f1335 734 }
b2c64049
NC
735 if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
736 /* Not doing some form of store, so return failure. */
737 if (flags & HVhek_FREEKEY)
738 Safefree(key);
3c84c864 739 return NULL;
b2c64049 740 }
113738bb 741 if (action & HV_FETCH_LVALUE) {
df5f182b 742 val = action & HV_FETCH_EMPTY_HE ? NULL : newSV(0);
b2c64049
NC
743 if (SvMAGICAL(hv)) {
744 /* At this point the old hv_fetch code would call to hv_store,
745 which in turn might do some tied magic. So we need to make that
746 magic check happen. */
747 /* gonna assign to this, so it better be there */
fda2d18a
NC
748 /* If a fetch-as-store fails on the fetch, then the action is to
749 recurse once into "hv_store". If we didn't do this, then that
750 recursive call would call the key conversion routine again.
751 However, as we replace the original key with the converted
752 key, this would result in a double conversion, which would show
753 up as a bug if the conversion routine is not idempotent. */
d3ba3f5c 754 return hv_common(hv, keysv, key, klen, flags,
3c84c864
NC
755 HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
756 val, hash);
b2c64049
NC
757 /* XXX Surely that could leak if the fetch-was-store fails?
758 Just like the hv_fetch. */
113738bb
NC
759 }
760 }
761
b2c64049
NC
762 /* Welcome to hv_store... */
763
7b2c381c 764 if (!HvARRAY(hv)) {
b2c64049
NC
765 /* Not sure if we can get here. I think the only case of oentry being
766 NULL is for %ENV with dynamic env fetch. But that should disappear
767 with magic in the previous code. */
d58e6666 768 char *array;
a02a5408 769 Newxz(array,
b2c64049 770 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
d58e6666
NC
771 char);
772 HvARRAY(hv) = (HE**)array;
b2c64049
NC
773 }
774
7b2c381c 775 oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
ab4af705 776
b2c64049
NC
777 entry = new_HE();
778 /* share_hek_flags will do the free for us. This might be considered
779 bad API design. */
780 if (HvSHAREKEYS(hv))
6e838c70 781 HeKEY_hek(entry) = share_hek_flags(key, klen, hash, flags);
5d2b1485
NC
782 else if (hv == PL_strtab) {
783 /* PL_strtab is usually the only hash without HvSHAREKEYS, so putting
784 this test here is cheap */
785 if (flags & HVhek_FREEKEY)
786 Safefree(key);
787 Perl_croak(aTHX_ S_strtab_error,
788 action & HV_FETCH_LVALUE ? "fetch" : "store");
789 }
b2c64049
NC
790 else /* gotta do the real thing */
791 HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
792 HeVAL(entry) = val;
793 HeNEXT(entry) = *oentry;
794 *oentry = entry;
795
796 if (val == &PL_sv_placeholder)
ca732855 797 HvPLACEHOLDERS(hv)++;
b2c64049
NC
798 if (masked_flags & HVhek_ENABLEHVKFLAGS)
799 HvHASKFLAGS_on(hv);
800
0298d7b9
NC
801 {
802 const HE *counter = HeNEXT(entry);
803
4c7185a0 804 xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
0298d7b9 805 if (!counter) { /* initial entry? */
5ac36297 806 } else if (xhv->xhv_keys > xhv->xhv_max) {
1b95d04f 807 /* Use only the old HvUSEDKEYS(hv) > HvMAX(hv) condition to limit
5b430b36
MW
808 bucket splits on a rehashed hash, as we're not going to
809 split it again, and if someone is lucky (evil) enough to
810 get all the keys in one list they could exhaust our memory
811 as we repeatedly double the number of buckets on every
812 entry. Linear search feels a less worse thing to do. */
0298d7b9
NC
813 hsplit(hv);
814 } else if(!HvREHASH(hv)) {
815 U32 n_links = 1;
816
817 while ((counter = HeNEXT(counter)))
818 n_links++;
819
820 if (n_links > HV_MAX_LENGTH_BEFORE_SPLIT) {
0298d7b9
NC
821 hsplit(hv);
822 }
823 }
fde52b5c 824 }
b2c64049 825
3c84c864
NC
826 if (return_svp) {
827 return entry ? (void *) &HeVAL(entry) : NULL;
828 }
829 return (void *) entry;
fde52b5c 830}
831
864dbfa3 832STATIC void
b0e6ae5b 833S_hv_magic_check(HV *hv, bool *needs_copy, bool *needs_store)
d0066dc7 834{
a3b680e6 835 const MAGIC *mg = SvMAGIC(hv);
7918f24d
NC
836
837 PERL_ARGS_ASSERT_HV_MAGIC_CHECK;
838
d0066dc7
OT
839 *needs_copy = FALSE;
840 *needs_store = TRUE;
841 while (mg) {
842 if (isUPPER(mg->mg_type)) {
843 *needs_copy = TRUE;
d60c5a05 844 if (mg->mg_type == PERL_MAGIC_tied) {
d0066dc7 845 *needs_store = FALSE;
4ab2a30b 846 return; /* We've set all there is to set. */
d0066dc7
OT
847 }
848 }
849 mg = mg->mg_moremagic;
850 }
851}
852
954c1994 853/*
a3bcc51e
TP
854=for apidoc hv_scalar
855
856Evaluates the hash in scalar context and returns the result. Handles magic when the hash is tied.
857
858=cut
859*/
860
861SV *
862Perl_hv_scalar(pTHX_ HV *hv)
863{
a3bcc51e 864 SV *sv;
823a54a3 865
7918f24d
NC
866 PERL_ARGS_ASSERT_HV_SCALAR;
867
823a54a3 868 if (SvRMAGICAL(hv)) {
ad64d0ec 869 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_tied);
823a54a3
AL
870 if (mg)
871 return magic_scalarpack(hv, mg);
872 }
a3bcc51e
TP
873
874 sv = sv_newmortal();
f4431c56 875 if (HvTOTALKEYS((const HV *)hv))
a3bcc51e
TP
876 Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
877 (long)HvFILL(hv), (long)HvMAX(hv) + 1);
878 else
879 sv_setiv(sv, 0);
880
881 return sv;
882}
883
884/*
954c1994
GS
885=for apidoc hv_delete
886
a05d6c5d
TC
887Deletes a key/value pair in the hash. The value's SV is removed from
888the hash, made mortal, and returned to the caller. The absolute
889value of C<klen> is the length of the key. If C<klen> is negative the
890key is assumed to be in UTF-8-encoded Unicode. The C<flags> value
891will normally be zero; if set to G_DISCARD then NULL will be returned.
892NULL will also be returned if the key is not found.
954c1994 893
954c1994
GS
894=for apidoc hv_delete_ent
895
3025a2e4
CS
896Deletes a key/value pair in the hash. The value SV is removed from the hash,
897made mortal, and returned to the caller. The C<flags> value will normally be
898zero; if set to G_DISCARD then NULL will be returned. NULL will also be
899returned if the key is not found. C<hash> can be a valid precomputed hash
900value, or 0 to ask for it to be computed.
954c1994
GS
901
902=cut
903*/
904
8f8d40ab 905STATIC SV *
cd6d36ac
NC
906S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
907 int k_flags, I32 d_flags, U32 hash)
f1317c8d 908{
27da23d5 909 dVAR;
cbec9347 910 register XPVHV* xhv;
fde52b5c 911 register HE *entry;
912 register HE **oentry;
9dbc5603 913 bool is_utf8 = (k_flags & HVhek_UTF8) ? TRUE : FALSE;
7a9669ca 914 int masked_flags;
1c846c1f 915
fde52b5c 916 if (SvRMAGICAL(hv)) {
0a0bb7c7
OT
917 bool needs_copy;
918 bool needs_store;
919 hv_magic_check (hv, &needs_copy, &needs_store);
920
f1317c8d 921 if (needs_copy) {
6136c704 922 SV *sv;
63c89345
NC
923 entry = (HE *) hv_common(hv, keysv, key, klen,
924 k_flags & ~HVhek_FREEKEY,
925 HV_FETCH_LVALUE|HV_DISABLE_UVAR_XKEY,
926 NULL, hash);
7a9669ca 927 sv = entry ? HeVAL(entry) : NULL;
f1317c8d
NC
928 if (sv) {
929 if (SvMAGICAL(sv)) {
930 mg_clear(sv);
931 }
932 if (!needs_store) {
933 if (mg_find(sv, PERL_MAGIC_tiedelem)) {
934 /* No longer an element */
935 sv_unmagic(sv, PERL_MAGIC_tiedelem);
936 return sv;
937 }
a0714e2c 938 return NULL; /* element cannot be deleted */
f1317c8d 939 }
902173a3 940#ifdef ENV_IS_CASELESS
ad64d0ec 941 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
8167a60a 942 /* XXX This code isn't UTF8 clean. */
59cd0e26 943 keysv = newSVpvn_flags(key, klen, SVs_TEMP);
8167a60a
NC
944 if (k_flags & HVhek_FREEKEY) {
945 Safefree(key);
946 }
947 key = strupr(SvPVX(keysv));
948 is_utf8 = 0;
949 k_flags = 0;
950 hash = 0;
7f66fda2 951 }
510ac311 952#endif
2fd1c6b8 953 }
2fd1c6b8 954 }
fde52b5c 955 }
cbec9347 956 xhv = (XPVHV*)SvANY(hv);
7b2c381c 957 if (!HvARRAY(hv))
a0714e2c 958 return NULL;
fde52b5c 959
19692e8d 960 if (is_utf8) {
c445ea15 961 const char * const keysave = key;
b464bac0 962 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
cd6d36ac 963
19692e8d 964 if (is_utf8)
cd6d36ac
NC
965 k_flags |= HVhek_UTF8;
966 else
967 k_flags &= ~HVhek_UTF8;
7f66fda2
NC
968 if (key != keysave) {
969 if (k_flags & HVhek_FREEKEY) {
970 /* This shouldn't happen if our caller does what we expect,
971 but strictly the API allows it. */
972 Safefree(keysave);
973 }
974 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
975 }
ad64d0ec 976 HvHASKFLAGS_on(MUTABLE_SV(hv));
19692e8d 977 }
f9a63242 978
f8d50d94
DM
979 if (HvREHASH(hv) || (!hash && !(keysv && (SvIsCOW_shared_hash(keysv)))))
980 PERL_HASH_INTERNAL_(hash, key, klen, HvREHASH(hv));
981 else if (!hash)
982 hash = SvSHARED_HASH(keysv);
fde52b5c 983
7a9669ca
NC
984 masked_flags = (k_flags & HVhek_MASK);
985
9de10d5c 986 oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
fde52b5c 987 entry = *oentry;
9e720f71 988 for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
6136c704 989 SV *sv;
f3d2f32d 990 U8 mro_changes = 0; /* 1 = isa; 2 = package moved */
0290c710 991 GV *gv = NULL;
0c3bb3c2
FC
992 HV *stash = NULL;
993
fde52b5c 994 if (HeHASH(entry) != hash) /* strings can't be equal */
995 continue;
eb160463 996 if (HeKLEN(entry) != (I32)klen)
fde52b5c 997 continue;
1c846c1f 998 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
fde52b5c 999 continue;
7a9669ca 1000 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
c3654f1a 1001 continue;
8aacddc1 1002
5d2b1485
NC
1003 if (hv == PL_strtab) {
1004 if (k_flags & HVhek_FREEKEY)
1005 Safefree(key);
1006 Perl_croak(aTHX_ S_strtab_error, "delete");
1007 }
1008
8aacddc1 1009 /* if placeholder is here, it's already been deleted.... */
6136c704
AL
1010 if (HeVAL(entry) == &PL_sv_placeholder) {
1011 if (k_flags & HVhek_FREEKEY)
1012 Safefree(key);
1013 return NULL;
8aacddc1 1014 }
e5accad2
FC
1015 if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))
1016 && !SvIsCOW(HeVAL(entry))) {
d4c19fe8 1017 hv_notallowed(k_flags, key, klen,
c8cd6465
NC
1018 "Attempt to delete readonly key '%"SVf"' from"
1019 " a restricted hash");
8aacddc1 1020 }
b84d0860
NC
1021 if (k_flags & HVhek_FREEKEY)
1022 Safefree(key);
8aacddc1 1023
35759254 1024 /* If this is a stash and the key ends with ::, then someone is
0c3bb3c2 1025 * deleting a package.
0c3bb3c2 1026 */
78b79c77 1027 if (HeVAL(entry) && HvENAME_get(hv)) {
0290c710 1028 gv = (GV *)HeVAL(entry);
35759254 1029 if (keysv) key = SvPV(keysv, klen);
1f656fcf
FC
1030 if ((
1031 (klen > 1 && key[klen-2] == ':' && key[klen-1] == ':')
1032 ||
1033 (klen == 1 && key[0] == ':')
1034 )
e0a52395 1035 && (klen != 6 || hv!=PL_defstash || memNE(key,"main::",6))
0290c710 1036 && SvTYPE(gv) == SVt_PVGV && (stash = GvHV((GV *)gv))
0c3bb3c2 1037 && HvENAME_get(stash)) {
0290c710
FC
1038 /* A previous version of this code checked that the
1039 * GV was still in the symbol table by fetching the
1040 * GV with its name. That is not necessary (and
1041 * sometimes incorrect), as HvENAME cannot be set
1042 * on hv if it is not in the symtab. */
f3d2f32d 1043 mro_changes = 2;
0c3bb3c2
FC
1044 /* Hang on to it for a bit. */
1045 SvREFCNT_inc_simple_void_NN(
0290c710 1046 sv_2mortal((SV *)gv)
35759254
FC
1047 );
1048 }
f3d2f32d
FC
1049 else if (klen == 3 && strnEQ(key, "ISA", 3))
1050 mro_changes = 1;
35759254
FC
1051 }
1052
8571a3cc
FC
1053 sv = d_flags & G_DISCARD ? HeVAL(entry) : sv_2mortal(HeVAL(entry));
1054 HeVAL(entry) = &PL_sv_placeholder;
5743f2a3
FC
1055 if (sv) {
1056 /* deletion of method from stash */
1057 if (isGV(sv) && isGV_with_GP(sv) && GvCVu(sv)
1058 && HvENAME_get(hv))
1059 mro_method_changed_in(hv);
5743f2a3 1060 }
8aacddc1
NIS
1061
1062 /*
1063 * If a restricted hash, rather than really deleting the entry, put
1064 * a placeholder there. This marks the key as being "approved", so
1065 * we can still access via not-really-existing key without raising
1066 * an error.
1067 */
f50383f5 1068 if (SvREADONLY(hv))
8aacddc1
NIS
1069 /* We'll be saving this slot, so the number of allocated keys
1070 * doesn't go down, but the number placeholders goes up */
ca732855 1071 HvPLACEHOLDERS(hv)++;
f50383f5 1072 else {
a26e96df 1073 *oentry = HeNEXT(entry);
b79f7545 1074 if (SvOOK(hv) && entry == HvAUX(hv)->xhv_eiter /* HvEITER(hv) */)
8aacddc1 1075 HvLAZYDEL_on(hv);
ae199939
TH
1076 else {
1077 if (SvOOK(hv) && HvLAZYDEL(hv) &&
1078 entry == HeNEXT(HvAUX(hv)->xhv_eiter))
1079 HeNEXT(HvAUX(hv)->xhv_eiter) = HeNEXT(entry);
8aacddc1 1080 hv_free_ent(hv, entry);
ae199939 1081 }
4c7185a0 1082 xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
574c8022 1083 if (xhv->xhv_keys == 0)
19692e8d 1084 HvHASKFLAGS_off(hv);
8aacddc1 1085 }
0c3bb3c2 1086
3b2cd809
FC
1087 if (d_flags & G_DISCARD) {
1088 SvREFCNT_dec(sv);
1089 sv = NULL;
1090 }
1091
f3d2f32d
FC
1092 if (mro_changes == 1) mro_isa_changed_in(hv);
1093 else if (mro_changes == 2)
afdbe55d 1094 mro_package_moved(NULL, stash, gv, 1);
0c3bb3c2 1095
79072805
LW
1096 return sv;
1097 }
8aacddc1 1098 if (SvREADONLY(hv)) {
d4c19fe8 1099 hv_notallowed(k_flags, key, klen,
c8cd6465
NC
1100 "Attempt to delete disallowed key '%"SVf"' from"
1101 " a restricted hash");
8aacddc1
NIS
1102 }
1103
19692e8d 1104 if (k_flags & HVhek_FREEKEY)
f9a63242 1105 Safefree(key);
a0714e2c 1106 return NULL;
79072805
LW
1107}
1108
76e3520e 1109STATIC void
cea2e8a9 1110S_hsplit(pTHX_ HV *hv)
79072805 1111{
97aff369 1112 dVAR;
1e05feb3 1113 register XPVHV* const xhv = (XPVHV*)SvANY(hv);
a3b680e6 1114 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
79072805
LW
1115 register I32 newsize = oldsize * 2;
1116 register I32 i;
7b2c381c 1117 char *a = (char*) HvARRAY(hv);
72311751 1118 register HE **aep;
4b5190b5
NC
1119 int longest_chain = 0;
1120 int was_shared;
79072805 1121
7918f24d
NC
1122 PERL_ARGS_ASSERT_HSPLIT;
1123
18026298 1124 /*PerlIO_printf(PerlIO_stderr(), "hsplit called for %p which had %d\n",
6c9570dc 1125 (void*)hv, (int) oldsize);*/
18026298 1126
5d88ecd7 1127 if (HvPLACEHOLDERS_get(hv) && !SvREADONLY(hv)) {
18026298
NC
1128 /* Can make this clear any placeholders first for non-restricted hashes,
1129 even though Storable rebuilds restricted hashes by putting in all the
1130 placeholders (first) before turning on the readonly flag, because
1131 Storable always pre-splits the hash. */
1132 hv_clear_placeholders(hv);
1133 }
1134
3280af22 1135 PL_nomemok = TRUE;
8d6dde3e 1136#if defined(STRANGE_MALLOC) || defined(MYMALLOC)
b79f7545
NC
1137 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1138 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
422a93e5 1139 if (!a) {
4a33f861 1140 PL_nomemok = FALSE;
422a93e5
GA
1141 return;
1142 }
b79f7545 1143 if (SvOOK(hv)) {
31f0e52e 1144 Move(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
b79f7545 1145 }
4633a7c4 1146#else
a02a5408 1147 Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
b79f7545 1148 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
422a93e5 1149 if (!a) {
3280af22 1150 PL_nomemok = FALSE;
422a93e5
GA
1151 return;
1152 }
7b2c381c 1153 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
b79f7545
NC
1154 if (SvOOK(hv)) {
1155 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1156 }
9a87bd09 1157 Safefree(HvARRAY(hv));
4633a7c4
LW
1158#endif
1159
3280af22 1160 PL_nomemok = FALSE;
72311751 1161 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
cbec9347 1162 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
7b2c381c 1163 HvARRAY(hv) = (HE**) a;
72311751 1164 aep = (HE**)a;
79072805 1165
72311751 1166 for (i=0; i<oldsize; i++,aep++) {
4b5190b5
NC
1167 int left_length = 0;
1168 int right_length = 0;
a50a3493
NC
1169 HE **oentry = aep;
1170 HE *entry = *aep;
a3b680e6 1171 register HE **bep;
4b5190b5 1172
a50a3493 1173 if (!entry) /* non-existent */
79072805 1174 continue;
72311751 1175 bep = aep+oldsize;
4c9d89c5 1176 do {
eb160463 1177 if ((HeHASH(entry) & newsize) != (U32)i) {
fde52b5c 1178 *oentry = HeNEXT(entry);
72311751 1179 HeNEXT(entry) = *bep;
72311751 1180 *bep = entry;
4b5190b5 1181 right_length++;
79072805 1182 }
4b5190b5 1183 else {
fde52b5c 1184 oentry = &HeNEXT(entry);
4b5190b5
NC
1185 left_length++;
1186 }
4c9d89c5
NC
1187 entry = *oentry;
1188 } while (entry);
4b5190b5
NC
1189 /* I think we don't actually need to keep track of the longest length,
1190 merely flag if anything is too long. But for the moment while
1191 developing this code I'll track it. */
1192 if (left_length > longest_chain)
1193 longest_chain = left_length;
1194 if (right_length > longest_chain)
1195 longest_chain = right_length;
1196 }
1197
1198
1199 /* Pick your policy for "hashing isn't working" here: */
fdcd69b6 1200 if (longest_chain <= HV_MAX_LENGTH_BEFORE_SPLIT /* split worked? */
4b5190b5
NC
1201 || HvREHASH(hv)) {
1202 return;
79072805 1203 }
4b5190b5
NC
1204
1205 if (hv == PL_strtab) {
1206 /* Urg. Someone is doing something nasty to the string table.
1207 Can't win. */
1208 return;
1209 }
1210
1211 /* Awooga. Awooga. Pathological data. */
6c9570dc 1212 /*PerlIO_printf(PerlIO_stderr(), "%p %d of %d with %d/%d buckets\n", (void*)hv,
4b5190b5
NC
1213 longest_chain, HvTOTALKEYS(hv), HvFILL(hv), 1+HvMAX(hv));*/
1214
1215 ++newsize;
a02a5408 1216 Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
b79f7545
NC
1217 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1218 if (SvOOK(hv)) {
1219 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1220 }
1221
4b5190b5
NC
1222 was_shared = HvSHAREKEYS(hv);
1223
4b5190b5
NC
1224 HvSHAREKEYS_off(hv);
1225 HvREHASH_on(hv);
1226
7b2c381c 1227 aep = HvARRAY(hv);
4b5190b5
NC
1228
1229 for (i=0; i<newsize; i++,aep++) {
a3b680e6 1230 register HE *entry = *aep;
4b5190b5
NC
1231 while (entry) {
1232 /* We're going to trash this HE's next pointer when we chain it
1233 into the new hash below, so store where we go next. */
9d4ba2ae 1234 HE * const next = HeNEXT(entry);
4b5190b5 1235 UV hash;
a3b680e6 1236 HE **bep;
4b5190b5
NC
1237
1238 /* Rehash it */
1239 PERL_HASH_INTERNAL(hash, HeKEY(entry), HeKLEN(entry));
1240
1241 if (was_shared) {
1242 /* Unshare it. */
aec46f14 1243 HEK * const new_hek
4b5190b5
NC
1244 = save_hek_flags(HeKEY(entry), HeKLEN(entry),
1245 hash, HeKFLAGS(entry));
1246 unshare_hek (HeKEY_hek(entry));
1247 HeKEY_hek(entry) = new_hek;
1248 } else {
1249 /* Not shared, so simply write the new hash in. */
1250 HeHASH(entry) = hash;
1251 }
1252 /*PerlIO_printf(PerlIO_stderr(), "%d ", HeKFLAGS(entry));*/
1253 HEK_REHASH_on(HeKEY_hek(entry));
1254 /*PerlIO_printf(PerlIO_stderr(), "%d\n", HeKFLAGS(entry));*/
1255
1256 /* Copy oentry to the correct new chain. */
1257 bep = ((HE**)a) + (hash & (I32) xhv->xhv_max);
4b5190b5
NC
1258 HeNEXT(entry) = *bep;
1259 *bep = entry;
1260
1261 entry = next;
1262 }
1263 }
7b2c381c
NC
1264 Safefree (HvARRAY(hv));
1265 HvARRAY(hv) = (HE **)a;
79072805
LW
1266}
1267
72940dca 1268void
864dbfa3 1269Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
72940dca 1270{
97aff369 1271 dVAR;
cbec9347 1272 register XPVHV* xhv = (XPVHV*)SvANY(hv);
a3b680e6 1273 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
72940dca 1274 register I32 newsize;
1275 register I32 i;
72311751
GS
1276 register char *a;
1277 register HE **aep;
72940dca 1278
7918f24d
NC
1279 PERL_ARGS_ASSERT_HV_KSPLIT;
1280
72940dca 1281 newsize = (I32) newmax; /* possible truncation here */
1282 if (newsize != newmax || newmax <= oldsize)
1283 return;
1284 while ((newsize & (1 + ~newsize)) != newsize) {
1285 newsize &= ~(newsize & (1 + ~newsize)); /* get proper power of 2 */
1286 }
1287 if (newsize < newmax)
1288 newsize *= 2;
1289 if (newsize < newmax)
1290 return; /* overflow detection */
1291
7b2c381c 1292 a = (char *) HvARRAY(hv);
72940dca 1293 if (a) {
3280af22 1294 PL_nomemok = TRUE;
8d6dde3e 1295#if defined(STRANGE_MALLOC) || defined(MYMALLOC)
b79f7545
NC
1296 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1297 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
8aacddc1 1298 if (!a) {
4a33f861 1299 PL_nomemok = FALSE;
422a93e5
GA
1300 return;
1301 }
b79f7545 1302 if (SvOOK(hv)) {
7a9b70e9 1303 Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
b79f7545 1304 }
72940dca 1305#else
a02a5408 1306 Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
b79f7545 1307 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
8aacddc1 1308 if (!a) {
3280af22 1309 PL_nomemok = FALSE;
422a93e5
GA
1310 return;
1311 }
7b2c381c 1312 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
b79f7545
NC
1313 if (SvOOK(hv)) {
1314 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1315 }
9a87bd09 1316 Safefree(HvARRAY(hv));
72940dca 1317#endif
3280af22 1318 PL_nomemok = FALSE;
72311751 1319 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
72940dca 1320 }
1321 else {
a02a5408 1322 Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
72940dca 1323 }
cbec9347 1324 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
7b2c381c 1325 HvARRAY(hv) = (HE **) a;
f4431c56 1326 if (!xhv->xhv_keys /* !HvTOTALKEYS(hv) */) /* skip rest if no entries */
72940dca 1327 return;
1328
72311751
GS
1329 aep = (HE**)a;
1330 for (i=0; i<oldsize; i++,aep++) {
a50a3493
NC
1331 HE **oentry = aep;
1332 HE *entry = *aep;
1333
1334 if (!entry) /* non-existent */
72940dca 1335 continue;
4c9d89c5 1336 do {
6136c704
AL
1337 register I32 j = (HeHASH(entry) & newsize);
1338
1339 if (j != i) {
72940dca 1340 j -= i;
1341 *oentry = HeNEXT(entry);
4d0fbddd 1342 HeNEXT(entry) = aep[j];
72311751 1343 aep[j] = entry;
72940dca 1344 }
1345 else
1346 oentry = &HeNEXT(entry);
4c9d89c5
NC
1347 entry = *oentry;
1348 } while (entry);
72940dca 1349 }
1350}
1351
b3ac6de7 1352HV *
864dbfa3 1353Perl_newHVhv(pTHX_ HV *ohv)
b3ac6de7 1354{
749123ff 1355 dVAR;
9d4ba2ae 1356 HV * const hv = newHV();
f4431c56 1357 STRLEN hv_max;
4beac62f 1358
3f4d1d78 1359 if (!ohv || (!HvTOTALKEYS(ohv) && !SvMAGICAL((const SV *)ohv)))
4beac62f 1360 return hv;
4beac62f 1361 hv_max = HvMAX(ohv);
b3ac6de7 1362
ad64d0ec 1363 if (!SvMAGICAL((const SV *)ohv)) {
b56ba0bf 1364 /* It's an ordinary hash, so copy it fast. AMS 20010804 */
eb160463 1365 STRLEN i;
a3b680e6 1366 const bool shared = !!HvSHAREKEYS(ohv);
aec46f14 1367 HE **ents, ** const oents = (HE **)HvARRAY(ohv);
ff875642 1368 char *a;
a02a5408 1369 Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
ff875642 1370 ents = (HE**)a;
b56ba0bf
AMS
1371
1372 /* In each bucket... */
1373 for (i = 0; i <= hv_max; i++) {
6136c704 1374 HE *prev = NULL;
aec46f14 1375 HE *oent = oents[i];
b56ba0bf
AMS
1376
1377 if (!oent) {
1378 ents[i] = NULL;
1379 continue;
1380 }
1381
1382 /* Copy the linked list of entries. */
aec46f14 1383 for (; oent; oent = HeNEXT(oent)) {
a3b680e6
AL
1384 const U32 hash = HeHASH(oent);
1385 const char * const key = HeKEY(oent);
1386 const STRLEN len = HeKLEN(oent);
1387 const int flags = HeKFLAGS(oent);
6136c704 1388 HE * const ent = new_HE();
c3acb9e0 1389 SV *const val = HeVAL(oent);
b56ba0bf 1390
c3acb9e0 1391 HeVAL(ent) = SvIMMORTAL(val) ? val : newSVsv(val);
19692e8d 1392 HeKEY_hek(ent)
6e838c70 1393 = shared ? share_hek_flags(key, len, hash, flags)
19692e8d 1394 : save_hek_flags(key, len, hash, flags);
b56ba0bf
AMS
1395 if (prev)
1396 HeNEXT(prev) = ent;
1397 else
1398 ents[i] = ent;
1399 prev = ent;
1400 HeNEXT(ent) = NULL;
1401 }
1402 }
1403
1404 HvMAX(hv) = hv_max;
8aacddc1 1405 HvTOTALKEYS(hv) = HvTOTALKEYS(ohv);
b56ba0bf 1406 HvARRAY(hv) = ents;
aec46f14 1407 } /* not magical */
b56ba0bf
AMS
1408 else {
1409 /* Iterate over ohv, copying keys and values one at a time. */
b3ac6de7 1410 HE *entry;
bfcb3514
NC
1411 const I32 riter = HvRITER_get(ohv);
1412 HE * const eiter = HvEITER_get(ohv);
f4431c56 1413 STRLEN hv_fill = HvFILL(ohv);
b56ba0bf
AMS
1414
1415 /* Can we use fewer buckets? (hv_max is always 2^n-1) */
1416 while (hv_max && hv_max + 1 >= hv_fill * 2)
1417 hv_max = hv_max / 2;
1418 HvMAX(hv) = hv_max;
1419
4a76a316 1420 hv_iterinit(ohv);
e16e2ff8 1421 while ((entry = hv_iternext_flags(ohv, 0))) {
3f4d1d78
FC
1422 SV *val = hv_iterval(ohv,entry);
1423 SV * const keysv = HeSVKEY(entry);
1424 val = SvIMMORTAL(val) ? val : newSVsv(val);
1425 if (keysv)
1426 (void)hv_store_ent(hv, keysv, val, 0);
1427 else
1428 (void)hv_store_flags(hv, HeKEY(entry), HeKLEN(entry), val,
c3acb9e0 1429 HeHASH(entry), HeKFLAGS(entry));
b3ac6de7 1430 }
bfcb3514
NC
1431 HvRITER_set(ohv, riter);
1432 HvEITER_set(ohv, eiter);
b3ac6de7 1433 }
1c846c1f 1434
b3ac6de7
IZ
1435 return hv;
1436}
1437
defdfed5
Z
1438/*
1439=for apidoc Am|HV *|hv_copy_hints_hv|HV *ohv
1440
1441A specialised version of L</newHVhv> for copying C<%^H>. I<ohv> must be
1442a pointer to a hash (which may have C<%^H> magic, but should be generally
1443non-magical), or C<NULL> (interpreted as an empty hash). The content
1444of I<ohv> is copied to a new hash, which has the C<%^H>-specific magic
1445added to it. A pointer to the new hash is returned.
1446
1447=cut
1448*/
1449
5b9c0671
NC
1450HV *
1451Perl_hv_copy_hints_hv(pTHX_ HV *const ohv)
1452{
1453 HV * const hv = newHV();
5b9c0671 1454
cb1f05e8 1455 if (ohv) {
5b9c0671 1456 STRLEN hv_max = HvMAX(ohv);
f4431c56 1457 STRLEN hv_fill = HvFILL(ohv);
5b9c0671
NC
1458 HE *entry;
1459 const I32 riter = HvRITER_get(ohv);
1460 HE * const eiter = HvEITER_get(ohv);
1461
1462 while (hv_max && hv_max + 1 >= hv_fill * 2)
1463 hv_max = hv_max / 2;
1464 HvMAX(hv) = hv_max;
1465
1466 hv_iterinit(ohv);
1467 while ((entry = hv_iternext_flags(ohv, 0))) {
cb1f05e8 1468 SV *const sv = newSVsv(hv_iterval(ohv,entry));
7ef9d42c
FC
1469 SV *heksv = HeSVKEY(entry);
1470 if (!heksv && sv) heksv = newSVhek(HeKEY_hek(entry));
95cf2368 1471 if (sv) sv_magic(sv, NULL, PERL_MAGIC_hintselem,
e3b1b6b1 1472 (char *)heksv, HEf_SVKEY);
7ef9d42c
FC
1473 if (heksv == HeSVKEY(entry))
1474 (void)hv_store_ent(hv, heksv, sv, 0);
1475 else {
1476 (void)hv_common(hv, heksv, HeKEY(entry), HeKLEN(entry),
1477 HeKFLAGS(entry), HV_FETCH_ISSTORE|HV_FETCH_JUST_SV, sv, HeHASH(entry));
1478 SvREFCNT_dec(heksv);
1479 }
5b9c0671
NC
1480 }
1481 HvRITER_set(ohv, riter);
1482 HvEITER_set(ohv, eiter);
1483 }
1484 hv_magic(hv, NULL, PERL_MAGIC_hints);
1485 return hv;
1486}
1487
e0171a1a
DM
1488/* like hv_free_ent, but returns the SV rather than freeing it */
1489STATIC SV*
1490S_hv_free_ent_ret(pTHX_ HV *hv, register HE *entry)
79072805 1491{
97aff369 1492 dVAR;
16bdeea2
GS
1493 SV *val;
1494
e0171a1a 1495 PERL_ARGS_ASSERT_HV_FREE_ENT_RET;
7918f24d 1496
68dc0745 1497 if (!entry)
e0171a1a 1498 return NULL;
16bdeea2 1499 val = HeVAL(entry);
68dc0745 1500 if (HeKLEN(entry) == HEf_SVKEY) {
1501 SvREFCNT_dec(HeKEY_sv(entry));
8aacddc1 1502 Safefree(HeKEY_hek(entry));
44a8e56a 1503 }
1504 else if (HvSHAREKEYS(hv))
68dc0745 1505 unshare_hek(HeKEY_hek(entry));
fde52b5c 1506 else
68dc0745 1507 Safefree(HeKEY_hek(entry));
d33b2eba 1508 del_HE(entry);
e0171a1a
DM
1509 return val;
1510}
1511
1512
1513void
1514Perl_hv_free_ent(pTHX_ HV *hv, register HE *entry)
1515{
1516 dVAR;
1517 SV *val;
1518
1519 PERL_ARGS_ASSERT_HV_FREE_ENT;
1520
1521 if (!entry)
1522 return;
1523 val = hv_free_ent_ret(hv, entry);
272e8453 1524 SvREFCNT_dec(val);
79072805
LW
1525}
1526
f1c32fec 1527
79072805 1528void
864dbfa3 1529Perl_hv_delayfree_ent(pTHX_ HV *hv, register HE *entry)
79072805 1530{
97aff369 1531 dVAR;
7918f24d
NC
1532
1533 PERL_ARGS_ASSERT_HV_DELAYFREE_ENT;
1534
68dc0745 1535 if (!entry)
79072805 1536 return;
bc4947fc
NC
1537 /* SvREFCNT_inc to counter the SvREFCNT_dec in hv_free_ent */
1538 sv_2mortal(SvREFCNT_inc(HeVAL(entry))); /* free between statements */
68dc0745 1539 if (HeKLEN(entry) == HEf_SVKEY) {
bc4947fc 1540 sv_2mortal(SvREFCNT_inc(HeKEY_sv(entry)));
44a8e56a 1541 }
bc4947fc 1542 hv_free_ent(hv, entry);
79072805
LW
1543}
1544
954c1994
GS
1545/*
1546=for apidoc hv_clear
1547
c2217cd3 1548Frees the all the elements of a hash, leaving it empty.
8b9a1153
FC
1549The XS equivalent of C<%hash = ()>. See also L</hv_undef>.
1550
1551If any destructors are triggered as a result, the hv itself may
1552be freed.
954c1994
GS
1553
1554=cut
1555*/
1556
79072805 1557void
864dbfa3 1558Perl_hv_clear(pTHX_ HV *hv)
79072805 1559{
27da23d5 1560 dVAR;
cbec9347 1561 register XPVHV* xhv;
79072805
LW
1562 if (!hv)
1563 return;
49293501 1564
ecae49c0
NC
1565 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1566
34c3c4e3
DM
1567 xhv = (XPVHV*)SvANY(hv);
1568
7b2c381c 1569 if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
34c3c4e3 1570 /* restricted hash: convert all keys to placeholders */
b464bac0
AL
1571 STRLEN i;
1572 for (i = 0; i <= xhv->xhv_max; i++) {
7b2c381c 1573 HE *entry = (HvARRAY(hv))[i];
3a676441
JH
1574 for (; entry; entry = HeNEXT(entry)) {
1575 /* not already placeholder */
7996736c 1576 if (HeVAL(entry) != &PL_sv_placeholder) {
fb2352eb
FC
1577 if (HeVAL(entry) && SvREADONLY(HeVAL(entry))
1578 && !SvIsCOW(HeVAL(entry))) {
6136c704 1579 SV* const keysv = hv_iterkeysv(entry);
3a676441 1580 Perl_croak(aTHX_
95b63a38
JH
1581 "Attempt to delete readonly key '%"SVf"' from a restricted hash",
1582 (void*)keysv);
3a676441
JH
1583 }
1584 SvREFCNT_dec(HeVAL(entry));
7996736c 1585 HeVAL(entry) = &PL_sv_placeholder;
ca732855 1586 HvPLACEHOLDERS(hv)++;
3a676441 1587 }
34c3c4e3
DM
1588 }
1589 }
49293501 1590 }
afbbf215
DM
1591 else {
1592 hfreeentries(hv);
1593 HvPLACEHOLDERS_set(hv, 0);
49293501 1594
afbbf215
DM
1595 if (SvRMAGICAL(hv))
1596 mg_clear(MUTABLE_SV(hv));
574c8022 1597
afbbf215
DM
1598 HvHASKFLAGS_off(hv);
1599 HvREHASH_off(hv);
1600 }
b79f7545 1601 if (SvOOK(hv)) {
00169e2c 1602 if(HvENAME_get(hv))
dd69841b 1603 mro_isa_changed_in(hv);
bfcb3514
NC
1604 HvEITER_set(hv, NULL);
1605 }
79072805
LW
1606}
1607
3540d4ce
AB
1608/*
1609=for apidoc hv_clear_placeholders
1610
1611Clears any placeholders from a hash. If a restricted hash has any of its keys
1612marked as readonly and the key is subsequently deleted, the key is not actually
1613deleted but is marked by assigning it a value of &PL_sv_placeholder. This tags
1614it so it will be ignored by future operations such as iterating over the hash,
4cdaeff7 1615but will still allow the hash to have a value reassigned to the key at some
3540d4ce
AB
1616future point. This function clears any such placeholder keys from the hash.
1617See Hash::Util::lock_keys() for an example of its use.
1618
1619=cut
1620*/
1621
1622void
1623Perl_hv_clear_placeholders(pTHX_ HV *hv)
1624{
27da23d5 1625 dVAR;
b3ca2e83
NC
1626 const U32 items = (U32)HvPLACEHOLDERS_get(hv);
1627
7918f24d
NC
1628 PERL_ARGS_ASSERT_HV_CLEAR_PLACEHOLDERS;
1629
b3ca2e83
NC
1630 if (items)
1631 clear_placeholders(hv, items);
1632}
1633
1634static void
1635S_clear_placeholders(pTHX_ HV *hv, U32 items)
1636{
1637 dVAR;
b464bac0 1638 I32 i;
d3677389 1639
7918f24d
NC
1640 PERL_ARGS_ASSERT_CLEAR_PLACEHOLDERS;
1641
d3677389
NC
1642 if (items == 0)
1643 return;
1644
b464bac0 1645 i = HvMAX(hv);
d3677389
NC
1646 do {
1647 /* Loop down the linked list heads */
d3677389 1648 HE **oentry = &(HvARRAY(hv))[i];
cf6db12b 1649 HE *entry;
d3677389 1650
cf6db12b 1651 while ((entry = *oentry)) {
d3677389
NC
1652 if (HeVAL(entry) == &PL_sv_placeholder) {
1653 *oentry = HeNEXT(entry);
2e58978b 1654 if (entry == HvEITER_get(hv))
d3677389 1655 HvLAZYDEL_on(hv);
ae199939
TH
1656 else {
1657 if (SvOOK(hv) && HvLAZYDEL(hv) &&
1658 entry == HeNEXT(HvAUX(hv)->xhv_eiter))
1659 HeNEXT(HvAUX(hv)->xhv_eiter) = HeNEXT(entry);
d3677389 1660 hv_free_ent(hv, entry);
ae199939 1661 }
d3677389
NC
1662
1663 if (--items == 0) {
1664 /* Finished. */
5d88ecd7 1665 HvTOTALKEYS(hv) -= (IV)HvPLACEHOLDERS_get(hv);
1b95d04f 1666 if (HvUSEDKEYS(hv) == 0)
d3677389 1667 HvHASKFLAGS_off(hv);
5d88ecd7 1668 HvPLACEHOLDERS_set(hv, 0);
d3677389
NC
1669 return;
1670 }
213ce8b3
NC
1671 } else {
1672 oentry = &HeNEXT(entry);
d3677389
NC
1673 }
1674 }
1675 } while (--i >= 0);
1676 /* You can't get here, hence assertion should always fail. */
1677 assert (items == 0);
1678 assert (0);
3540d4ce
AB
1679}
1680
76e3520e 1681STATIC void
cea2e8a9 1682S_hfreeentries(pTHX_ HV *hv)
79072805 1683{
e0171a1a 1684 STRLEN index = 0;
7d6175ef 1685 XPVHV * const xhv = (XPVHV*)SvANY(hv);
6d1c68e6 1686 SV *sv;
60edcf09 1687 const bool save = !!SvREFCNT(hv);
3abe233e 1688
7918f24d
NC
1689 PERL_ARGS_ASSERT_HFREEENTRIES;
1690
60edcf09
FC
1691 if (save) {
1692 ENTER;
1693 SAVEFREESV(SvREFCNT_inc_simple_NN(hv));
1694 }
1695
6d1c68e6
FC
1696 while ((sv = Perl_hfree_next_entry(aTHX_ hv, &index))||xhv->xhv_keys) {
1697 SvREFCNT_dec(sv);
e0171a1a 1698 }
60edcf09
FC
1699
1700 if (save) LEAVE;
e0171a1a 1701}
23976bdd 1702
b79f7545 1703
e0171a1a
DM
1704/* hfree_next_entry()
1705 * For use only by S_hfreeentries() and sv_clear().
1706 * Delete the next available HE from hv and return the associated SV.
7d6175ef
FC
1707 * Returns null on empty hash. Nevertheless null is not a reliable
1708 * indicator that the hash is empty, as the deleted entry may have a
1709 * null value.
e0171a1a
DM
1710 * indexp is a pointer to the current index into HvARRAY. The index should
1711 * initially be set to 0. hfree_next_entry() may update it. */
1712
1713SV*
1714Perl_hfree_next_entry(pTHX_ HV *hv, STRLEN *indexp)
1715{
1716 struct xpvhv_aux *iter;
1717 HE *entry;
1718 HE ** array;
1719#ifdef DEBUGGING
1720 STRLEN orig_index = *indexp;
1721#endif
1722
1723 PERL_ARGS_ASSERT_HFREE_NEXT_ENTRY;
1724
e0171a1a
DM
1725 if (SvOOK(hv) && ((iter = HvAUX(hv)))
1726 && ((entry = iter->xhv_eiter)) )
1727 {
1728 /* the iterator may get resurrected after each
1729 * destructor call, so check each time */
1730 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1731 HvLAZYDEL_off(hv);
922090f4
DM
1732 hv_free_ent(hv, entry);
1733 /* warning: at this point HvARRAY may have been
1734 * re-allocated, HvMAX changed etc */
23976bdd 1735 }
e0171a1a
DM
1736 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
1737 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
1738 }
1739
00a1a643
DM
1740 if (!((XPVHV*)SvANY(hv))->xhv_keys)
1741 return NULL;
1742
e0171a1a
DM
1743 array = HvARRAY(hv);
1744 assert(array);
1745 while ( ! ((entry = array[*indexp])) ) {
1746 if ((*indexp)++ >= HvMAX(hv))
1747 *indexp = 0;
1748 assert(*indexp != orig_index);
1749 }
1750 array[*indexp] = HeNEXT(entry);
1751 ((XPVHV*) SvANY(hv))->xhv_keys--;
1752
1753 if ( PL_phase != PERL_PHASE_DESTRUCT && HvENAME(hv)
1754 && HeVAL(entry) && isGV(HeVAL(entry))
1755 && GvHV(HeVAL(entry)) && HvENAME(GvHV(HeVAL(entry)))
1756 ) {
1757 STRLEN klen;
1758 const char * const key = HePV(entry,klen);
1759 if ((klen > 1 && key[klen-1]==':' && key[klen-2]==':')
1760 || (klen == 1 && key[0] == ':')) {
1761 mro_package_moved(
1762 NULL, GvHV(HeVAL(entry)),
1763 (GV *)HeVAL(entry), 0
1764 );
1765 }
1766 }
1767 return hv_free_ent_ret(hv, entry);
79072805
LW
1768}
1769
e0171a1a 1770
954c1994
GS
1771/*
1772=for apidoc hv_undef
1773
8b9a1153 1774Undefines the hash. The XS equivalent of C<undef(%hash)>.
c2217cd3
DM
1775
1776As well as freeing all the elements of the hash (like hv_clear()), this
1777also frees any auxiliary data and storage associated with the hash.
8b9a1153
FC
1778
1779If any destructors are triggered as a result, the hv itself may
1780be freed.
1781
c2217cd3 1782See also L</hv_clear>.
954c1994
GS
1783
1784=cut
1785*/
1786
79072805 1787void
8581adba 1788Perl_hv_undef_flags(pTHX_ HV *hv, U32 flags)
79072805 1789{
97aff369 1790 dVAR;
cbec9347 1791 register XPVHV* xhv;
bfcb3514 1792 const char *name;
86f55936 1793
79072805
LW
1794 if (!hv)
1795 return;
ecae49c0 1796 DEBUG_A(Perl_hv_assert(aTHX_ hv));
cbec9347 1797 xhv = (XPVHV*)SvANY(hv);
dd69841b 1798
745edda6
FC
1799 /* The name must be deleted before the call to hfreeeeentries so that
1800 CVs are anonymised properly. But the effective name must be pre-
1801 served until after that call (and only deleted afterwards if the
1802 call originated from sv_clear). For stashes with one name that is
1803 both the canonical name and the effective name, hv_name_set has to
1804 allocate an array for storing the effective name. We can skip that
1805 during global destruction, as it does not matter where the CVs point
1806 if they will be freed anyway. */
104d7b69
DM
1807 /* note that the code following prior to hfreeentries is duplicated
1808 * in sv_clear(), and changes here should be done there too */
745edda6 1809 if (PL_phase != PERL_PHASE_DESTRUCT && (name = HvNAME(hv))) {
04fe65b0 1810 if (PL_stashcache)
4643eb69
BF
1811 (void)hv_delete(PL_stashcache, name,
1812 HEK_UTF8(HvNAME_HEK(hv)) ? -HvNAMELEN_get(hv) : HvNAMELEN_get(hv),
1813 G_DISCARD
1814 );
bd61b366 1815 hv_name_set(hv, NULL, 0, 0);
85e6fe83 1816 }
2d0d1ecc 1817 hfreeentries(hv);
47f1cf77
FC
1818 if (SvOOK(hv)) {
1819 struct xpvhv_aux * const aux = HvAUX(hv);
1820 struct mro_meta *meta;
745edda6
FC
1821
1822 if ((name = HvENAME_get(hv))) {
5f243b5f 1823 if (PL_phase != PERL_PHASE_DESTRUCT)
745edda6 1824 mro_isa_changed_in(hv);
745edda6
FC
1825 if (PL_stashcache)
1826 (void)hv_delete(
4643eb69
BF
1827 PL_stashcache, name,
1828 HEK_UTF8(HvENAME_HEK(hv)) ? -HvENAMELEN_get(hv) : HvENAMELEN_get(hv),
1829 G_DISCARD
745edda6
FC
1830 );
1831 }
1832
1833 /* If this call originated from sv_clear, then we must check for
1834 * effective names that need freeing, as well as the usual name. */
1835 name = HvNAME(hv);
15d9236d 1836 if (flags & HV_NAME_SETALL ? !!aux->xhv_name_u.xhvnameu_name : !!name) {
745edda6 1837 if (name && PL_stashcache)
4643eb69 1838 (void)hv_delete(PL_stashcache, name, (HEK_UTF8(HvNAME_HEK(hv)) ? -HvNAMELEN_get(hv) : HvNAMELEN_get(hv)), G_DISCARD);
745edda6 1839 hv_name_set(hv, NULL, 0, flags);
47f1cf77
FC
1840 }
1841 if((meta = aux->xhv_mro_meta)) {
1842 if (meta->mro_linear_all) {
1843 SvREFCNT_dec(MUTABLE_SV(meta->mro_linear_all));
1844 meta->mro_linear_all = NULL;
1845 /* This is just acting as a shortcut pointer. */
1846 meta->mro_linear_current = NULL;
1847 } else if (meta->mro_linear_current) {
1848 /* Only the current MRO is stored, so this owns the data.
1849 */
1850 SvREFCNT_dec(meta->mro_linear_current);
1851 meta->mro_linear_current = NULL;
1852 }
9bfbb681 1853 SvREFCNT_dec(meta->mro_nextmethod);
47f1cf77
FC
1854 SvREFCNT_dec(meta->isa);
1855 Safefree(meta);
1856 aux->xhv_mro_meta = NULL;
1857 }
3b37eb24 1858 if (!aux->xhv_name_u.xhvnameu_name && ! aux->xhv_backreferences)
745edda6 1859 SvFLAGS(hv) &= ~SVf_OOK;
745edda6
FC
1860 }
1861 if (!SvOOK(hv)) {
1862 Safefree(HvARRAY(hv));
1863 xhv->xhv_max = 7; /* HvMAX(hv) = 7 (it's a normal hash) */
1864 HvARRAY(hv) = 0;
2d0d1ecc 1865 }
ca732855 1866 HvPLACEHOLDERS_set(hv, 0);
a0d0e21e
LW
1867
1868 if (SvRMAGICAL(hv))
ad64d0ec 1869 mg_clear(MUTABLE_SV(hv));
79072805
LW
1870}
1871
4d0fbddd
NC
1872/*
1873=for apidoc hv_fill
1874
1875Returns the number of hash buckets that happen to be in use. This function is
1876wrapped by the macro C<HvFILL>.
1877
1878Previously this value was stored in the HV structure, rather than being
1879calculated on demand.
1880
1881=cut
1882*/
1883
1884STRLEN
1885Perl_hv_fill(pTHX_ HV const *const hv)
1886{
1887 STRLEN count = 0;
1888 HE **ents = HvARRAY(hv);
1889
1890 PERL_ARGS_ASSERT_HV_FILL;
1891
1892 if (ents) {
fcd24582
NC
1893 HE *const *const last = ents + HvMAX(hv);
1894 count = last + 1 - ents;
4d0fbddd
NC
1895
1896 do {
fcd24582
NC
1897 if (!*ents)
1898 --count;
1899 } while (++ents <= last);
4d0fbddd
NC
1900 }
1901 return count;
1902}
1903
b464bac0 1904static struct xpvhv_aux*
5f66b61c 1905S_hv_auxinit(HV *hv) {
bfcb3514 1906 struct xpvhv_aux *iter;
b79f7545 1907 char *array;
bfcb3514 1908
7918f24d
NC
1909 PERL_ARGS_ASSERT_HV_AUXINIT;
1910
b79f7545 1911 if (!HvARRAY(hv)) {
a02a5408 1912 Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
b79f7545
NC
1913 + sizeof(struct xpvhv_aux), char);
1914 } else {
1915 array = (char *) HvARRAY(hv);
1916 Renew(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1917 + sizeof(struct xpvhv_aux), char);
1918 }
1919 HvARRAY(hv) = (HE**) array;
a82b195b 1920 SvOOK_on(hv);
b79f7545 1921 iter = HvAUX(hv);
bfcb3514
NC
1922
1923 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
4608196e 1924 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
15d9236d 1925 iter->xhv_name_u.xhvnameu_name = 0;
b7247a80 1926 iter->xhv_name_count = 0;
86f55936 1927 iter->xhv_backreferences = 0;
e1a479c5 1928 iter->xhv_mro_meta = NULL;
bfcb3514
NC
1929 return iter;
1930}
1931
954c1994
GS
1932/*
1933=for apidoc hv_iterinit
1934
1935Prepares a starting point to traverse a hash table. Returns the number of
1b95d04f 1936keys in the hash (i.e. the same as C<HvUSEDKEYS(hv)>). The return value is
1c846c1f 1937currently only meaningful for hashes without tie magic.
954c1994
GS
1938
1939NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
1940hash buckets that happen to be in use. If you still need that esoteric
b24b84ef 1941value, you can get it through the macro C<HvFILL(hv)>.
954c1994 1942
e16e2ff8 1943
954c1994
GS
1944=cut
1945*/
1946
79072805 1947I32
864dbfa3 1948Perl_hv_iterinit(pTHX_ HV *hv)
79072805 1949{
7918f24d
NC
1950 PERL_ARGS_ASSERT_HV_ITERINIT;
1951
1952 /* FIXME: Are we not NULL, or do we croak? Place bets now! */
1953
aa689395 1954 if (!hv)
cea2e8a9 1955 Perl_croak(aTHX_ "Bad hash");
bfcb3514 1956
b79f7545 1957 if (SvOOK(hv)) {
6136c704 1958 struct xpvhv_aux * const iter = HvAUX(hv);
0bd48802 1959 HE * const entry = iter->xhv_eiter; /* HvEITER(hv) */
bfcb3514
NC
1960 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1961 HvLAZYDEL_off(hv);
1962 hv_free_ent(hv, entry);
1963 }
1964 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
4608196e 1965 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
bfcb3514 1966 } else {
6136c704 1967 hv_auxinit(hv);
72940dca 1968 }
44a2ac75 1969
cbec9347 1970 /* used to be xhv->xhv_fill before 5.004_65 */
5d88ecd7 1971 return HvTOTALKEYS(hv);
79072805 1972}
bfcb3514
NC
1973
1974I32 *
1975Perl_hv_riter_p(pTHX_ HV *hv) {
1976 struct xpvhv_aux *iter;
1977
7918f24d
NC
1978 PERL_ARGS_ASSERT_HV_RITER_P;
1979
bfcb3514
NC
1980 if (!hv)
1981 Perl_croak(aTHX_ "Bad hash");
1982
6136c704 1983 iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
bfcb3514
NC
1984 return &(iter->xhv_riter);
1985}
1986
1987HE **
1988Perl_hv_eiter_p(pTHX_ HV *hv) {
1989 struct xpvhv_aux *iter;
1990
7918f24d
NC
1991 PERL_ARGS_ASSERT_HV_EITER_P;
1992
bfcb3514
NC
1993 if (!hv)
1994 Perl_croak(aTHX_ "Bad hash");
1995
6136c704 1996 iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
bfcb3514
NC
1997 return &(iter->xhv_eiter);
1998}
1999
2000void
2001Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
2002 struct xpvhv_aux *iter;
2003
7918f24d
NC
2004 PERL_ARGS_ASSERT_HV_RITER_SET;
2005
bfcb3514
NC
2006 if (!hv)
2007 Perl_croak(aTHX_ "Bad hash");
2008
b79f7545
NC
2009 if (SvOOK(hv)) {
2010 iter = HvAUX(hv);
2011 } else {
bfcb3514
NC
2012 if (riter == -1)
2013 return;
2014
6136c704 2015 iter = hv_auxinit(hv);
bfcb3514
NC
2016 }
2017 iter->xhv_riter = riter;
2018}
2019
2020void
2021Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
2022 struct xpvhv_aux *iter;
2023
7918f24d
NC
2024 PERL_ARGS_ASSERT_HV_EITER_SET;
2025
bfcb3514
NC
2026 if (!hv)
2027 Perl_croak(aTHX_ "Bad hash");
2028
b79f7545
NC
2029 if (SvOOK(hv)) {
2030 iter = HvAUX(hv);
2031 } else {
bfcb3514
NC
2032 /* 0 is the default so don't go malloc()ing a new structure just to
2033 hold 0. */
2034 if (!eiter)
2035 return;
2036
6136c704 2037 iter = hv_auxinit(hv);
bfcb3514
NC
2038 }
2039 iter->xhv_eiter = eiter;
2040}
2041
bfcb3514 2042void
4164be69 2043Perl_hv_name_set(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
bfcb3514 2044{
97aff369 2045 dVAR;
b79f7545 2046 struct xpvhv_aux *iter;
7423f6db 2047 U32 hash;
78b79c77 2048 HEK **spot;
46c461b5 2049
7918f24d 2050 PERL_ARGS_ASSERT_HV_NAME_SET;
bfcb3514 2051
4164be69
NC
2052 if (len > I32_MAX)
2053 Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
2054
b79f7545
NC
2055 if (SvOOK(hv)) {
2056 iter = HvAUX(hv);
15d9236d 2057 if (iter->xhv_name_u.xhvnameu_name) {
b7247a80 2058 if(iter->xhv_name_count) {
745edda6 2059 if(flags & HV_NAME_SETALL) {
15d9236d 2060 HEK ** const name = HvAUX(hv)->xhv_name_u.xhvnameu_names;
78b79c77
FC
2061 HEK **hekp = name + (
2062 iter->xhv_name_count < 0
2063 ? -iter->xhv_name_count
2064 : iter->xhv_name_count
2065 );
2066 while(hekp-- > name+1)
b7247a80 2067 unshare_hek_or_pvn(*hekp, 0, 0, 0);
78b79c77
FC
2068 /* The first elem may be null. */
2069 if(*name) unshare_hek_or_pvn(*name, 0, 0, 0);
b7247a80 2070 Safefree(name);
15d9236d 2071 spot = &iter->xhv_name_u.xhvnameu_name;
78b79c77
FC
2072 iter->xhv_name_count = 0;
2073 }
2074 else {
78b79c77
FC
2075 if(iter->xhv_name_count > 0) {
2076 /* shift some things over */
15d9236d
NC
2077 Renew(
2078 iter->xhv_name_u.xhvnameu_names, iter->xhv_name_count + 1, HEK *
4c2bfb4f 2079 );
15d9236d 2080 spot = iter->xhv_name_u.xhvnameu_names;
4c2bfb4f 2081 spot[iter->xhv_name_count] = spot[1];
78b79c77 2082 spot[1] = spot[0];
4c2bfb4f 2083 iter->xhv_name_count = -(iter->xhv_name_count + 1);
78b79c77 2084 }
15d9236d 2085 else if(*(spot = iter->xhv_name_u.xhvnameu_names)) {
78b79c77
FC
2086 unshare_hek_or_pvn(*spot, 0, 0, 0);
2087 }
2088 }
2089 }
745edda6 2090 else if (flags & HV_NAME_SETALL) {
15d9236d
NC
2091 unshare_hek_or_pvn(iter->xhv_name_u.xhvnameu_name, 0, 0, 0);
2092 spot = &iter->xhv_name_u.xhvnameu_name;
b7247a80 2093 }
745edda6 2094 else {
15d9236d
NC
2095 HEK * const existing_name = iter->xhv_name_u.xhvnameu_name;
2096 Newx(iter->xhv_name_u.xhvnameu_names, 2, HEK *);
745edda6 2097 iter->xhv_name_count = -2;
15d9236d 2098 spot = iter->xhv_name_u.xhvnameu_names;
745edda6
FC
2099 spot[1] = existing_name;
2100 }
7423f6db 2101 }
15d9236d 2102 else { spot = &iter->xhv_name_u.xhvnameu_name; iter->xhv_name_count = 0; }
16580ff5 2103 } else {
bfcb3514
NC
2104 if (name == 0)
2105 return;
2106
6136c704 2107 iter = hv_auxinit(hv);
15d9236d 2108 spot = &iter->xhv_name_u.xhvnameu_name;
bfcb3514 2109 }
7423f6db 2110 PERL_HASH(hash, name, len);
c60dbbc3 2111 *spot = name ? share_hek(name, flags & SVf_UTF8 ? -(I32)len : (I32)len, hash) : NULL;
4643eb69
BF
2112}
2113
2114/*
2115This is basically sv_eq_flags() in sv.c, but we avoid the magic
2116and bytes checking.
2117*/
2118
2119STATIC I32
2120hek_eq_pvn_flags(pTHX_ const HEK *hek, const char* pv, const I32 pvlen, const U32 flags) {
2121 if ( (HEK_UTF8(hek) ? 1 : 0) != (flags & SVf_UTF8 ? 1 : 0) ) {
2122 if (flags & SVf_UTF8)
2123 return (bytes_cmp_utf8(
2124 (const U8*)HEK_KEY(hek), HEK_LEN(hek),
2125 (const U8*)pv, pvlen) == 0);
2126 else
2127 return (bytes_cmp_utf8(
2128 (const U8*)pv, pvlen,
2129 (const U8*)HEK_KEY(hek), HEK_LEN(hek)) == 0);
2130 }
2131 else
d35fec6c 2132 return HEK_LEN(hek) == pvlen && ((HEK_KEY(hek) == pv)
4643eb69 2133 || memEQ(HEK_KEY(hek), pv, pvlen));
bfcb3514
NC
2134}
2135
99206677
FC
2136/*
2137=for apidoc hv_ename_add
2138
db4fbf16 2139Adds a name to a stash's internal list of effective names. See
99206677
FC
2140C<hv_ename_delete>.
2141
2142This is called when a stash is assigned to a new location in the symbol
2143table.
2144
2145=cut
2146*/
2147
ee72b38d 2148void
27a1175b 2149Perl_hv_ename_add(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
ee72b38d
FC
2150{
2151 dVAR;
2152 struct xpvhv_aux *aux = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2153 U32 hash;
2154
78b79c77 2155 PERL_ARGS_ASSERT_HV_ENAME_ADD;
ee72b38d
FC
2156
2157 if (len > I32_MAX)
2158 Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
2159
2160 PERL_HASH(hash, name, len);
2161
ee72b38d 2162 if (aux->xhv_name_count) {
15d9236d 2163 HEK ** const xhv_name = aux->xhv_name_u.xhvnameu_names;
78b79c77
FC
2164 I32 count = aux->xhv_name_count;
2165 HEK **hekp = xhv_name + (count < 0 ? -count : count);
ee72b38d
FC
2166 while (hekp-- > xhv_name)
2167 if (
4643eb69
BF
2168 (HEK_UTF8(*hekp) || (flags & SVf_UTF8))
2169 ? hek_eq_pvn_flags(aTHX_ *hekp, name, (I32)len, flags)
2170 : (HEK_LEN(*hekp) == (I32)len && memEQ(HEK_KEY(*hekp), name, len))
2171 ) {
78b79c77
FC
2172 if (hekp == xhv_name && count < 0)
2173 aux->xhv_name_count = -count;
2174 return;
2175 }
2176 if (count < 0) aux->xhv_name_count--, count = -count;
2177 else aux->xhv_name_count++;
15d9236d 2178 Renew(aux->xhv_name_u.xhvnameu_names, count + 1, HEK *);
c60dbbc3 2179 (aux->xhv_name_u.xhvnameu_names)[count] = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
ee72b38d
FC
2180 }
2181 else {
15d9236d 2182 HEK *existing_name = aux->xhv_name_u.xhvnameu_name;
ee72b38d 2183 if (
4643eb69
BF
2184 existing_name && (
2185 (HEK_UTF8(existing_name) || (flags & SVf_UTF8))
2186 ? hek_eq_pvn_flags(aTHX_ existing_name, name, (I32)len, flags)
2187 : (HEK_LEN(existing_name) == (I32)len && memEQ(HEK_KEY(existing_name), name, len))
2188 )
ee72b38d 2189 ) return;
15d9236d 2190 Newx(aux->xhv_name_u.xhvnameu_names, 2, HEK *);
78b79c77 2191 aux->xhv_name_count = existing_name ? 2 : -2;
15d9236d 2192 *aux->xhv_name_u.xhvnameu_names = existing_name;
c60dbbc3 2193 (aux->xhv_name_u.xhvnameu_names)[1] = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
ee72b38d
FC
2194 }
2195}
2196
99206677
FC
2197/*
2198=for apidoc hv_ename_delete
2199
db4fbf16 2200Removes a name from a stash's internal list of effective names. If this is
99206677
FC
2201the name returned by C<HvENAME>, then another name in the list will take
2202its place (C<HvENAME> will use it).
2203
2204This is called when a stash is deleted from the symbol table.
2205
2206=cut
2207*/
2208
ee72b38d 2209void
27a1175b 2210Perl_hv_ename_delete(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
ee72b38d
FC
2211{
2212 dVAR;
2213 struct xpvhv_aux *aux;
2214
78b79c77 2215 PERL_ARGS_ASSERT_HV_ENAME_DELETE;
ee72b38d
FC
2216
2217 if (len > I32_MAX)
2218 Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
2219
2220 if (!SvOOK(hv)) return;
2221
2222 aux = HvAUX(hv);
15d9236d 2223 if (!aux->xhv_name_u.xhvnameu_name) return;
ee72b38d
FC
2224
2225 if (aux->xhv_name_count) {
15d9236d 2226 HEK ** const namep = aux->xhv_name_u.xhvnameu_names;
78b79c77
FC
2227 I32 const count = aux->xhv_name_count;
2228 HEK **victim = namep + (count < 0 ? -count : count);
2229 while (victim-- > namep + 1)
ee72b38d 2230 if (
4643eb69
BF
2231 (HEK_UTF8(*victim) || (flags & SVf_UTF8))
2232 ? hek_eq_pvn_flags(aTHX_ *victim, name, (I32)len, flags)
2233 : (HEK_LEN(*victim) == (I32)len && memEQ(HEK_KEY(*victim), name, len))
ee72b38d
FC
2234 ) {
2235 unshare_hek_or_pvn(*victim, 0, 0, 0);
78b79c77
FC
2236 if (count < 0) ++aux->xhv_name_count;
2237 else --aux->xhv_name_count;
2238 if (
2239 (aux->xhv_name_count == 1 || aux->xhv_name_count == -1)
2240 && !*namep
2241 ) { /* if there are none left */
ee72b38d 2242 Safefree(namep);
15d9236d 2243 aux->xhv_name_u.xhvnameu_names = NULL;
78b79c77 2244 aux->xhv_name_count = 0;
ee72b38d
FC
2245 }
2246 else {
2247 /* Move the last one back to fill the empty slot. It
2248 does not matter what order they are in. */
78b79c77 2249 *victim = *(namep + (count < 0 ? -count : count) - 1);
ee72b38d
FC
2250 }
2251 return;
2252 }
78b79c77 2253 if (
4643eb69
BF
2254 count > 0 && (HEK_UTF8(*namep) || (flags & SVf_UTF8))
2255 ? hek_eq_pvn_flags(aTHX_ *namep, name, (I32)len, flags)
2256 : (HEK_LEN(*namep) == (I32)len && memEQ(HEK_KEY(*namep), name, len))
78b79c77
FC
2257 ) {
2258 aux->xhv_name_count = -count;
2259 }
ee72b38d
FC
2260 }
2261 else if(
4643eb69
BF
2262 (HEK_UTF8(aux->xhv_name_u.xhvnameu_name) || (flags & SVf_UTF8))
2263 ? hek_eq_pvn_flags(aTHX_ aux->xhv_name_u.xhvnameu_name, name, (I32)len, flags)
2264 : (HEK_LEN(aux->xhv_name_u.xhvnameu_name) == (I32)len &&
2265 memEQ(HEK_KEY(aux->xhv_name_u.xhvnameu_name), name, len))
ee72b38d 2266 ) {
15d9236d
NC
2267 HEK * const namehek = aux->xhv_name_u.xhvnameu_name;
2268 Newx(aux->xhv_name_u.xhvnameu_names, 1, HEK *);
2269 *aux->xhv_name_u.xhvnameu_names = namehek;
3f783763 2270 aux->xhv_name_count = -1;
ee72b38d
FC
2271 }
2272}
2273
86f55936
NC
2274AV **
2275Perl_hv_backreferences_p(pTHX_ HV *hv) {
6136c704 2276 struct xpvhv_aux * const iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
7918f24d
NC
2277
2278 PERL_ARGS_ASSERT_HV_BACKREFERENCES_P;
96a5add6 2279 PERL_UNUSED_CONTEXT;
7918f24d 2280
86f55936
NC
2281 return &(iter->xhv_backreferences);
2282}
2283
09aad8f0
DM
2284void
2285Perl_hv_kill_backrefs(pTHX_ HV *hv) {
2286 AV *av;
2287
2288 PERL_ARGS_ASSERT_HV_KILL_BACKREFS;
2289
2290 if (!SvOOK(hv))
2291 return;
2292
2293 av = HvAUX(hv)->xhv_backreferences;
2294
2295 if (av) {
2296 HvAUX(hv)->xhv_backreferences = 0;
2297 Perl_sv_kill_backrefs(aTHX_ MUTABLE_SV(hv), av);
5648c0ae
DM
2298 if (SvTYPE(av) == SVt_PVAV)
2299 SvREFCNT_dec(av);
09aad8f0
DM
2300 }
2301}
2302
954c1994 2303/*
7a7b9979
NC
2304hv_iternext is implemented as a macro in hv.h
2305
954c1994
GS
2306=for apidoc hv_iternext
2307
2308Returns entries from a hash iterator. See C<hv_iterinit>.
2309
fe7bca90
NC
2310You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
2311iterator currently points to, without losing your place or invalidating your
2312iterator. Note that in this case the current entry is deleted from the hash
2313with your iterator holding the last reference to it. Your iterator is flagged
2314to free the entry on the next call to C<hv_iternext>, so you must not discard
2315your iterator immediately else the entry will leak - call C<hv_iternext> to
2316trigger the resource deallocation.
2317
fe7bca90
NC
2318=for apidoc hv_iternext_flags
2319
2320Returns entries from a hash iterator. See C<hv_iterinit> and C<hv_iternext>.
2321The C<flags> value will normally be zero; if HV_ITERNEXT_WANTPLACEHOLDERS is
2322set the placeholders keys (for restricted hashes) will be returned in addition
2323to normal keys. By default placeholders are automatically skipped over.
7996736c 2324Currently a placeholder is implemented with a value that is
990c89d7 2325C<&PL_sv_placeholder>. Note that the implementation of placeholders and
fe7bca90
NC
2326restricted hashes may change, and the implementation currently is
2327insufficiently abstracted for any change to be tidy.
e16e2ff8 2328
fe7bca90 2329=cut
e16e2ff8
NC
2330*/
2331
2332HE *
2333Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
2334{
27da23d5 2335 dVAR;
cbec9347 2336 register XPVHV* xhv;
79072805 2337 register HE *entry;
a0d0e21e 2338 HE *oldentry;
463ee0b2 2339 MAGIC* mg;
bfcb3514 2340 struct xpvhv_aux *iter;
79072805 2341
7918f24d
NC
2342 PERL_ARGS_ASSERT_HV_ITERNEXT_FLAGS;
2343
79072805 2344 if (!hv)
cea2e8a9 2345 Perl_croak(aTHX_ "Bad hash");
81714fb9 2346
cbec9347 2347 xhv = (XPVHV*)SvANY(hv);
bfcb3514 2348
b79f7545 2349 if (!SvOOK(hv)) {
bfcb3514
NC
2350 /* Too many things (well, pp_each at least) merrily assume that you can
2351 call iv_iternext without calling hv_iterinit, so we'll have to deal
2352 with it. */
2353 hv_iterinit(hv);
bfcb3514 2354 }
b79f7545 2355 iter = HvAUX(hv);
bfcb3514
NC
2356
2357 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
e62cc96a 2358 if (SvMAGICAL(hv) && SvRMAGICAL(hv)) {
ad64d0ec 2359 if ( ( mg = mg_find((const SV *)hv, PERL_MAGIC_tied) ) ) {
e62cc96a
YO
2360 SV * const key = sv_newmortal();
2361 if (entry) {
2362 sv_setsv(key, HeSVKEY_force(entry));
2363 SvREFCNT_dec(HeSVKEY(entry)); /* get rid of previous key */
2364 }
2365 else {
2366 char *k;
2367 HEK *hek;
2368
2369 /* one HE per MAGICAL hash */
2370 iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
2371 Zero(entry, 1, HE);
ad64d0ec 2372 Newxz(k, HEK_BASESIZE + sizeof(const SV *), char);
e62cc96a
YO
2373 hek = (HEK*)k;
2374 HeKEY_hek(entry) = hek;
2375 HeKLEN(entry) = HEf_SVKEY;
2376 }
ad64d0ec 2377 magic_nextpack(MUTABLE_SV(hv),mg,key);
e62cc96a
YO
2378 if (SvOK(key)) {
2379 /* force key to stay around until next time */
2380 HeSVKEY_set(entry, SvREFCNT_inc_simple_NN(key));
2381 return entry; /* beware, hent_val is not set */
2382 }
ef8d46e8 2383 SvREFCNT_dec(HeVAL(entry));
e62cc96a
YO
2384 Safefree(HeKEY_hek(entry));
2385 del_HE(entry);
2386 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
2387 return NULL;
81714fb9 2388 }
79072805 2389 }
7ee146b1 2390#if defined(DYNAMIC_ENV_FETCH) && !defined(__riscos__) /* set up %ENV for iteration */
ad64d0ec
NC
2391 if (!entry && SvRMAGICAL((const SV *)hv)
2392 && mg_find((const SV *)hv, PERL_MAGIC_env)) {
f675dbe5 2393 prime_env_iter();
03026e68
JM
2394#ifdef VMS
2395 /* The prime_env_iter() on VMS just loaded up new hash values
2396 * so the iteration count needs to be reset back to the beginning
2397 */
2398 hv_iterinit(hv);
2399 iter = HvAUX(hv);
2400 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2401#endif
2402 }
f675dbe5 2403#endif
463ee0b2 2404
bfaf5b52 2405 /* hv_iterinit now ensures this. */
b79f7545
NC
2406 assert (HvARRAY(hv));
2407
015a5f36 2408 /* At start of hash, entry is NULL. */
fde52b5c 2409 if (entry)
8aacddc1 2410 {
fde52b5c 2411 entry = HeNEXT(entry);
e16e2ff8
NC
2412 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2413 /*
2414 * Skip past any placeholders -- don't want to include them in
2415 * any iteration.
2416 */
7996736c 2417 while (entry && HeVAL(entry) == &PL_sv_placeholder) {
e16e2ff8
NC
2418 entry = HeNEXT(entry);
2419 }
8aacddc1
NIS
2420 }
2421 }
015a5f36 2422
9eb4ebd1
NC
2423 /* Skip the entire loop if the hash is empty. */
2424 if ((flags & HV_ITERNEXT_WANTPLACEHOLDERS)
2425 ? HvTOTALKEYS(hv) : HvUSEDKEYS(hv)) {
900ac051
MM
2426 while (!entry) {
2427 /* OK. Come to the end of the current list. Grab the next one. */
2428
2429 iter->xhv_riter++; /* HvRITER(hv)++ */
2430 if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
2431 /* There is no next one. End of the hash. */
2432 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2433 break;
2434 }
2435 entry = (HvARRAY(hv))[iter->xhv_riter];
8aacddc1 2436
900ac051
MM
2437 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2438 /* If we have an entry, but it's a placeholder, don't count it.
2439 Try the next. */
2440 while (entry && HeVAL(entry) == &PL_sv_placeholder)
2441 entry = HeNEXT(entry);
2442 }
2443 /* Will loop again if this linked list starts NULL
2444 (for HV_ITERNEXT_WANTPLACEHOLDERS)
2445 or if we run through it and find only placeholders. */
015a5f36 2446 }
fde52b5c 2447 }
41aa816f 2448 else iter->xhv_riter = -1;
79072805 2449
72940dca 2450 if (oldentry && HvLAZYDEL(hv)) { /* was deleted earlier? */
2451 HvLAZYDEL_off(hv);
68dc0745 2452 hv_free_ent(hv, oldentry);
72940dca 2453 }
a0d0e21e 2454
fdcd69b6 2455 /*if (HvREHASH(hv) && entry && !HeKREHASH(entry))
6c9570dc 2456 PerlIO_printf(PerlIO_stderr(), "Awooga %p %p\n", (void*)hv, (void*)entry);*/
fdcd69b6 2457
bfcb3514 2458 iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
79072805
LW
2459 return entry;
2460}
2461
954c1994
GS
2462/*
2463=for apidoc hv_iterkey
2464
2465Returns the key from the current position of the hash iterator. See
2466C<hv_iterinit>.
2467
2468=cut
2469*/
2470
79072805 2471char *
864dbfa3 2472Perl_hv_iterkey(pTHX_ register HE *entry, I32 *retlen)
79072805 2473{
7918f24d
NC
2474 PERL_ARGS_ASSERT_HV_ITERKEY;
2475
fde52b5c 2476 if (HeKLEN(entry) == HEf_SVKEY) {
fb73857a 2477 STRLEN len;
0bd48802 2478 char * const p = SvPV(HeKEY_sv(entry), len);
fb73857a 2479 *retlen = len;
2480 return p;
fde52b5c 2481 }
2482 else {
2483 *retlen = HeKLEN(entry);
2484 return HeKEY(entry);
2485 }
2486}
2487
2488/* unlike hv_iterval(), this always returns a mortal copy of the key */
954c1994
GS
2489/*
2490=for apidoc hv_iterkeysv
2491
2492Returns the key as an C<SV*> from the current position of the hash
2493iterator. The return value will always be a mortal copy of the key. Also
2494see C<hv_iterinit>.
2495
2496=cut
2497*/
2498
fde52b5c 2499SV *
864dbfa3 2500Perl_hv_iterkeysv(pTHX_ register HE *entry)
fde52b5c 2501{
7918f24d
NC
2502 PERL_ARGS_ASSERT_HV_ITERKEYSV;
2503
c1b02ed8 2504 return sv_2mortal(newSVhek(HeKEY_hek(entry)));
79072805
LW
2505}
2506
954c1994
GS
2507/*
2508=for apidoc hv_iterval
2509
2510Returns the value from the current position of the hash iterator. See
2511C<hv_iterkey>.
2512
2513=cut
2514*/
2515
79072805 2516SV *
864dbfa3 2517Perl_hv_iterval(pTHX_ HV *hv, register HE *entry)
79072805 2518{
7918f24d
NC
2519 PERL_ARGS_ASSERT_HV_ITERVAL;
2520
8990e307 2521 if (SvRMAGICAL(hv)) {
ad64d0ec 2522 if (mg_find((const SV *)hv, PERL_MAGIC_tied)) {
c4420975 2523 SV* const sv = sv_newmortal();
bbce6d69 2524 if (HeKLEN(entry) == HEf_SVKEY)
ad64d0ec 2525 mg_copy(MUTABLE_SV(hv), sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
a3b680e6 2526 else
ad64d0ec 2527 mg_copy(MUTABLE_SV(hv), sv, HeKEY(entry), HeKLEN(entry));
463ee0b2
LW
2528 return sv;
2529 }
79072805 2530 }
fde52b5c 2531 return HeVAL(entry);
79072805
LW
2532}
2533
954c1994
GS
2534/*
2535=for apidoc hv_iternextsv
2536
2537Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2538operation.
2539
2540=cut
2541*/
2542
a0d0e21e 2543SV *
864dbfa3 2544Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
a0d0e21e 2545{
0bd48802
AL
2546 HE * const he = hv_iternext_flags(hv, 0);
2547
7918f24d
NC
2548 PERL_ARGS_ASSERT_HV_ITERNEXTSV;
2549
0bd48802 2550 if (!he)
a0d0e21e
LW
2551 return NULL;
2552 *key = hv_iterkey(he, retlen);
2553 return hv_iterval(hv, he);
2554}
2555
954c1994 2556/*
bc5cdc23
NC
2557
2558Now a macro in hv.h
2559
954c1994
GS
2560=for apidoc hv_magic
2561
2562Adds magic to a hash. See C<sv_magic>.
2563
2564=cut
2565*/
2566
bbce6d69 2567/* possibly free a shared string if no one has access to it
fde52b5c 2568 * len and hash must both be valid for str.
2569 */
bbce6d69 2570void
864dbfa3 2571Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
fde52b5c 2572{
19692e8d
NC
2573 unshare_hek_or_pvn (NULL, str, len, hash);
2574}
2575
2576
2577void
2578Perl_unshare_hek(pTHX_ HEK *hek)
2579{
bf11fd37 2580 assert(hek);
19692e8d
NC
2581 unshare_hek_or_pvn(hek, NULL, 0, 0);
2582}
2583
2584/* possibly free a shared string if no one has access to it
2585 hek if non-NULL takes priority over the other 3, else str, len and hash
2586 are used. If so, len and hash must both be valid for str.
2587 */
df132699 2588STATIC void
97ddebaf 2589S_unshare_hek_or_pvn(pTHX_ const HEK *hek, const char *str, I32 len, U32 hash)
19692e8d 2590{
97aff369 2591 dVAR;
cbec9347 2592 register XPVHV* xhv;
20454177 2593 HE *entry;
fde52b5c 2594 register HE **oentry;
c3654f1a 2595 bool is_utf8 = FALSE;
19692e8d 2596 int k_flags = 0;
aec46f14 2597 const char * const save = str;
cbbf8932 2598 struct shared_he *he = NULL;
c3654f1a 2599
19692e8d 2600 if (hek) {
cbae3960
NC
2601 /* Find the shared he which is just before us in memory. */
2602 he = (struct shared_he *)(((char *)hek)
2603 - STRUCT_OFFSET(struct shared_he,
2604 shared_he_hek));
2605
2606 /* Assert that the caller passed us a genuine (or at least consistent)
2607 shared hek */
2608 assert (he->shared_he_he.hent_hek == hek);
29404ae0 2609
de616631
NC
2610 if (he->shared_he_he.he_valu.hent_refcount - 1) {
2611 --he->shared_he_he.he_valu.hent_refcount;
29404ae0
NC
2612 return;
2613 }
29404ae0 2614
19692e8d
NC
2615 hash = HEK_HASH(hek);
2616 } else if (len < 0) {
2617 STRLEN tmplen = -len;
2618 is_utf8 = TRUE;
2619 /* See the note in hv_fetch(). --jhi */
2620 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2621 len = tmplen;
2622 if (is_utf8)
2623 k_flags = HVhek_UTF8;
2624 if (str != save)
2625 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
c3654f1a 2626 }
1c846c1f 2627
de616631 2628 /* what follows was the moral equivalent of:
6b88bc9c 2629 if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
a0714e2c 2630 if (--*Svp == NULL)
6b88bc9c 2631 hv_delete(PL_strtab, str, len, G_DISCARD, hash);
bbce6d69 2632 } */
cbec9347 2633 xhv = (XPVHV*)SvANY(PL_strtab);
fde52b5c 2634 /* assert(xhv_array != 0) */
9de10d5c 2635 oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
6c1b96a1
NC
2636 if (he) {
2637 const HE *const he_he = &(he->shared_he_he);
45d1cc86 2638 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
35ab5632
NC
2639 if (entry == he_he)
2640 break;
19692e8d
NC
2641 }
2642 } else {
35a4481c 2643 const int flags_masked = k_flags & HVhek_MASK;
45d1cc86 2644 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
19692e8d
NC
2645 if (HeHASH(entry) != hash) /* strings can't be equal */
2646 continue;
2647 if (HeKLEN(entry) != len)
2648 continue;
2649 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2650 continue;
2651 if (HeKFLAGS(entry) != flags_masked)
2652 continue;
19692e8d
NC
2653 break;
2654 }
2655 }
2656
35ab5632
NC
2657 if (entry) {
2658 if (--entry->he_valu.hent_refcount == 0) {
19692e8d 2659 *oentry = HeNEXT(entry);
cbae3960 2660 Safefree(entry);
4c7185a0 2661 xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
19692e8d 2662 }
fde52b5c 2663 }
19692e8d 2664
9b387841
NC
2665 if (!entry)
2666 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
12578ffb 2667 "Attempt to free nonexistent shared string '%s'%s"
9b387841
NC
2668 pTHX__FORMAT,
2669 hek ? HEK_KEY(hek) : str,
2670 ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
19692e8d
NC
2671 if (k_flags & HVhek_FREEKEY)
2672 Safefree(str);
fde52b5c 2673}
2674
bbce6d69 2675/* get a (constant) string ptr from the global string table
2676 * string will get added if it is not already there.
fde52b5c 2677 * len and hash must both be valid for str.
2678 */
bbce6d69 2679HEK *
864dbfa3 2680Perl_share_hek(pTHX_ const char *str, I32 len, register U32 hash)
fde52b5c 2681{
da58a35d 2682 bool is_utf8 = FALSE;
19692e8d 2683 int flags = 0;
aec46f14 2684 const char * const save = str;
da58a35d 2685
7918f24d
NC
2686 PERL_ARGS_ASSERT_SHARE_HEK;
2687
da58a35d 2688 if (len < 0) {
77caf834 2689 STRLEN tmplen = -len;
da58a35d 2690 is_utf8 = TRUE;
77caf834
JH
2691 /* See the note in hv_fetch(). --jhi */
2692 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2693 len = tmplen;
19692e8d
NC
2694 /* If we were able to downgrade here, then than means that we were passed
2695 in a key which only had chars 0-255, but was utf8 encoded. */
2696 if (is_utf8)
2697 flags = HVhek_UTF8;
2698 /* If we found we were able to downgrade the string to bytes, then
2699 we should flag that it needs upgrading on keys or each. Also flag
2700 that we need share_hek_flags to free the string. */
4643eb69
BF
2701 if (str != save) {
2702 PERL_HASH(hash, str, len);
19692e8d 2703 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
4643eb69 2704 }
19692e8d
NC
2705 }
2706
6e838c70 2707 return share_hek_flags (str, len, hash, flags);
19692e8d
NC
2708}
2709
6e838c70 2710STATIC HEK *
19692e8d
NC
2711S_share_hek_flags(pTHX_ const char *str, I32 len, register U32 hash, int flags)
2712{
97aff369 2713 dVAR;
19692e8d 2714 register HE *entry;
35a4481c 2715 const int flags_masked = flags & HVhek_MASK;
263cb4a6 2716 const U32 hindex = hash & (I32) HvMAX(PL_strtab);
7918f24d
NC
2717 register XPVHV * const xhv = (XPVHV*)SvANY(PL_strtab);
2718
2719 PERL_ARGS_ASSERT_SHARE_HEK_FLAGS;
bbce6d69 2720
fde52b5c 2721 /* what follows is the moral equivalent of:
1c846c1f 2722
6b88bc9c 2723 if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
a0714e2c 2724 hv_store(PL_strtab, str, len, NULL, hash);
fdcd69b6
NC
2725
2726 Can't rehash the shared string table, so not sure if it's worth
2727 counting the number of entries in the linked list
bbce6d69 2728 */
7918f24d 2729
fde52b5c 2730 /* assert(xhv_array != 0) */
263cb4a6
NC
2731 entry = (HvARRAY(PL_strtab))[hindex];
2732 for (;entry; entry = HeNEXT(entry)) {
fde52b5c 2733 if (HeHASH(entry) != hash) /* strings can't be equal */
2734 continue;
2735 if (HeKLEN(entry) != len)
2736 continue;
1c846c1f 2737 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
fde52b5c 2738 continue;
19692e8d 2739 if (HeKFLAGS(entry) != flags_masked)
c3654f1a 2740 continue;
fde52b5c 2741 break;
2742 }
263cb4a6
NC
2743
2744 if (!entry) {
45d1cc86
NC
2745 /* What used to be head of the list.
2746 If this is NULL, then we're the first entry for this slot, which
2747 means we need to increate fill. */
cbae3960
NC
2748 struct shared_he *new_entry;
2749 HEK *hek;
2750 char *k;
263cb4a6
NC
2751 HE **const head = &HvARRAY(PL_strtab)[hindex];
2752 HE *const next = *head;
cbae3960
NC
2753
2754 /* We don't actually store a HE from the arena and a regular HEK.
2755 Instead we allocate one chunk of memory big enough for both,
2756 and put the HEK straight after the HE. This way we can find the
f52337cf 2757 HE directly from the HEK.
cbae3960
NC
2758 */
2759
a02a5408 2760 Newx(k, STRUCT_OFFSET(struct shared_he,
cbae3960
NC
2761 shared_he_hek.hek_key[0]) + len + 2, char);
2762 new_entry = (struct shared_he *)k;
2763 entry = &(new_entry->shared_he_he);
2764 hek = &(new_entry->shared_he_hek);
2765
2766 Copy(str, HEK_KEY(hek), len, char);
2767 HEK_KEY(hek)[len] = 0;
2768 HEK_LEN(hek) = len;
2769 HEK_HASH(hek) = hash;
2770 HEK_FLAGS(hek) = (unsigned char)flags_masked;
2771
2772 /* Still "point" to the HEK, so that other code need not know what
2773 we're up to. */
2774 HeKEY_hek(entry) = hek;
de616631 2775 entry->he_valu.hent_refcount = 0;
263cb4a6
NC
2776 HeNEXT(entry) = next;
2777 *head = entry;
cbae3960 2778
4c7185a0 2779 xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
263cb4a6 2780 if (!next) { /* initial entry? */
1b95d04f 2781 } else if (xhv->xhv_keys > xhv->xhv_max /* HvUSEDKEYS(hv) > HvMAX(hv) */) {
cbec9347 2782 hsplit(PL_strtab);
bbce6d69 2783 }
2784 }
2785
de616631 2786 ++entry->he_valu.hent_refcount;
19692e8d
NC
2787
2788 if (flags & HVhek_FREEKEY)
f9a63242 2789 Safefree(str);
19692e8d 2790
6e838c70 2791 return HeKEY_hek(entry);
fde52b5c 2792}
ecae49c0 2793
ca732855
NC
2794I32 *
2795Perl_hv_placeholders_p(pTHX_ HV *hv)
2796{
2797 dVAR;
ad64d0ec 2798 MAGIC *mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
ca732855 2799
7918f24d
NC
2800 PERL_ARGS_ASSERT_HV_PLACEHOLDERS_P;
2801
ca732855 2802 if (!mg) {
ad64d0ec 2803 mg = sv_magicext(MUTABLE_SV(hv), 0, PERL_MAGIC_rhash, 0, 0, 0);
ca732855
NC
2804
2805 if (!mg) {
2806 Perl_die(aTHX_ "panic: hv_placeholders_p");
2807 }
2808 }
2809 return &(mg->mg_len);
2810}
2811
2812
2813I32
0c289d13 2814Perl_hv_placeholders_get(pTHX_ const HV *hv)
ca732855
NC
2815{
2816 dVAR;
0c289d13 2817 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
ca732855 2818
7918f24d
NC
2819 PERL_ARGS_ASSERT_HV_PLACEHOLDERS_GET;
2820
ca732855
NC
2821 return mg ? mg->mg_len : 0;
2822}
2823
2824void
ac1e784a 2825Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
ca732855
NC
2826{
2827 dVAR;
ad64d0ec 2828 MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
ca732855 2829
7918f24d
NC
2830 PERL_ARGS_ASSERT_HV_PLACEHOLDERS_SET;
2831
ca732855
NC
2832 if (mg) {
2833 mg->mg_len = ph;
2834 } else if (ph) {
ad64d0ec 2835 if (!sv_magicext(MUTABLE_SV(hv), 0, PERL_MAGIC_rhash, 0, 0, ph))
ca732855
NC
2836 Perl_die(aTHX_ "panic: hv_placeholders_set");
2837 }
2838 /* else we don't need to add magic to record 0 placeholders. */
2839}
ecae49c0 2840
2a49f0f5 2841STATIC SV *
7b0bddfa
NC
2842S_refcounted_he_value(pTHX_ const struct refcounted_he *he)
2843{
0b2d3faa 2844 dVAR;
7b0bddfa 2845 SV *value;
7918f24d
NC
2846
2847 PERL_ARGS_ASSERT_REFCOUNTED_HE_VALUE;
2848
7b0bddfa
NC
2849 switch(he->refcounted_he_data[0] & HVrhek_typemask) {
2850 case HVrhek_undef:
2851 value = newSV(0);
2852 break;
2853 case HVrhek_delete:
2854 value = &PL_sv_placeholder;
2855 break;
2856 case HVrhek_IV:
44ebaf21
NC
2857 value = newSViv(he->refcounted_he_val.refcounted_he_u_iv);
2858 break;
2859 case HVrhek_UV:
2860 value = newSVuv(he->refcounted_he_val.refcounted_he_u_uv);
7b0bddfa
NC
2861 break;
2862 case HVrhek_PV:
44ebaf21 2863 case HVrhek_PV_UTF8:
7b0bddfa
NC
2864 /* Create a string SV that directly points to the bytes in our
2865 structure. */
b9f83d2f 2866 value = newSV_type(SVt_PV);
7b0bddfa
NC
2867 SvPV_set(value, (char *) he->refcounted_he_data + 1);
2868 SvCUR_set(value, he->refcounted_he_val.refcounted_he_u_len);
2869 /* This stops anything trying to free it */
2870 SvLEN_set(value, 0);
2871 SvPOK_on(value);
2872 SvREADONLY_on(value);
44ebaf21 2873 if ((he->refcounted_he_data[0] & HVrhek_typemask) == HVrhek_PV_UTF8)
7b0bddfa
NC
2874 SvUTF8_on(value);
2875 break;
2876 default:
20439bc7
Z
2877 Perl_croak(aTHX_ "panic: refcounted_he_value bad flags %"UVxf,
2878 (UV)he->refcounted_he_data[0]);
7b0bddfa
NC
2879 }
2880 return value;
2881}
2882
ecae49c0 2883/*
20439bc7 2884=for apidoc m|HV *|refcounted_he_chain_2hv|const struct refcounted_he *c|U32 flags
8dff4fc5 2885
20439bc7
Z
2886Generates and returns a C<HV *> representing the content of a
2887C<refcounted_he> chain.
2888I<flags> is currently unused and must be zero.
8dff4fc5
BM
2889
2890=cut
2891*/
2892HV *
20439bc7 2893Perl_refcounted_he_chain_2hv(pTHX_ const struct refcounted_he *chain, U32 flags)
8dff4fc5 2894{
20439bc7
Z
2895 dVAR;
2896 HV *hv;
2897 U32 placeholders, max;
b3ca2e83 2898
20439bc7
Z
2899 if (flags)
2900 Perl_croak(aTHX_ "panic: refcounted_he_chain_2hv bad flags %"UVxf,
2901 (UV)flags);
b3ca2e83 2902
b3ca2e83
NC
2903 /* We could chase the chain once to get an idea of the number of keys,
2904 and call ksplit. But for now we'll make a potentially inefficient
2905 hash with only 8 entries in its array. */
20439bc7
Z
2906 hv = newHV();
2907 max = HvMAX(hv);
b3ca2e83
NC
2908 if (!HvARRAY(hv)) {
2909 char *array;
2910 Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(max + 1), char);
2911 HvARRAY(hv) = (HE**)array;
2912 }
2913
20439bc7 2914 placeholders = 0;
b3ca2e83 2915 while (chain) {
cbb1fbea 2916#ifdef USE_ITHREADS
b6bbf3fa 2917 U32 hash = chain->refcounted_he_hash;
cbb1fbea
NC
2918#else
2919 U32 hash = HEK_HASH(chain->refcounted_he_hek);
2920#endif
b3ca2e83
NC
2921 HE **oentry = &((HvARRAY(hv))[hash & max]);
2922 HE *entry = *oentry;
b6bbf3fa 2923 SV *value;
cbb1fbea 2924
b3ca2e83
NC
2925 for (; entry; entry = HeNEXT(entry)) {
2926 if (HeHASH(entry) == hash) {
9f769845
NC
2927 /* We might have a duplicate key here. If so, entry is older
2928 than the key we've already put in the hash, so if they are
2929 the same, skip adding entry. */
2930#ifdef USE_ITHREADS
2931 const STRLEN klen = HeKLEN(entry);
2932 const char *const key = HeKEY(entry);
2933 if (klen == chain->refcounted_he_keylen
2934 && (!!HeKUTF8(entry)
2935 == !!(chain->refcounted_he_data[0] & HVhek_UTF8))
2936 && memEQ(key, REF_HE_KEY(chain), klen))
2937 goto next_please;
2938#else
2939 if (HeKEY_hek(entry) == chain->refcounted_he_hek)
2940 goto next_please;
2941 if (HeKLEN(entry) == HEK_LEN(chain->refcounted_he_hek)
2942 && HeKUTF8(entry) == HEK_UTF8(chain->refcounted_he_hek)
2943 && memEQ(HeKEY(entry), HEK_KEY(chain->refcounted_he_hek),
2944 HeKLEN(entry)))
2945 goto next_please;
2946#endif
b3ca2e83
NC
2947 }
2948 }
2949 assert (!entry);
2950 entry = new_HE();
2951
cbb1fbea
NC
2952#ifdef USE_ITHREADS
2953 HeKEY_hek(entry)
7b0bddfa 2954 = share_hek_flags(REF_HE_KEY(chain),
b6bbf3fa
NC
2955 chain->refcounted_he_keylen,
2956 chain->refcounted_he_hash,
2957 (chain->refcounted_he_data[0]
2958 & (HVhek_UTF8|HVhek_WASUTF8)));
cbb1fbea 2959#else
71ad1b0c 2960 HeKEY_hek(entry) = share_hek_hek(chain->refcounted_he_hek);
cbb1fbea 2961#endif
7b0bddfa
NC
2962 value = refcounted_he_value(chain);
2963 if (value == &PL_sv_placeholder)
b3ca2e83 2964 placeholders++;
b6bbf3fa 2965 HeVAL(entry) = value;
b3ca2e83
NC
2966
2967 /* Link it into the chain. */
2968 HeNEXT(entry) = *oentry;
b3ca2e83
NC
2969 *oentry = entry;
2970
2971 HvTOTALKEYS(hv)++;
2972
2973 next_please:
71ad1b0c 2974 chain = chain->refcounted_he_next;
b3ca2e83
NC
2975 }
2976
2977 if (placeholders) {
2978 clear_placeholders(hv, placeholders);
2979 HvTOTALKEYS(hv) -= placeholders;
2980 }
2981
2982 /* We could check in the loop to see if we encounter any keys with key
2983 flags, but it's probably not worth it, as this per-hash flag is only
2984 really meant as an optimisation for things like Storable. */
2985 HvHASKFLAGS_on(hv);
def9038f 2986 DEBUG_A(Perl_hv_assert(aTHX_ hv));
b3ca2e83
NC
2987
2988 return hv;
2989}
2990
20439bc7
Z
2991/*
2992=for apidoc m|SV *|refcounted_he_fetch_pvn|const struct refcounted_he *chain|const char *keypv|STRLEN keylen|U32 hash|U32 flags
2993
2994Search along a C<refcounted_he> chain for an entry with the key specified
2995by I<keypv> and I<keylen>. If I<flags> has the C<REFCOUNTED_HE_KEY_UTF8>
2996bit set, the key octets are interpreted as UTF-8, otherwise they
2997are interpreted as Latin-1. I<hash> is a precomputed hash of the key
2998string, or zero if it has not been precomputed. Returns a mortal scalar
2999representing the value associated with the key, or C<&PL_sv_placeholder>
3000if there is no value associated with the key.
3001
3002=cut
3003*/
3004
7b0bddfa 3005SV *
20439bc7
Z
3006Perl_refcounted_he_fetch_pvn(pTHX_ const struct refcounted_he *chain,
3007 const char *keypv, STRLEN keylen, U32 hash, U32 flags)
7b0bddfa 3008{
0b2d3faa 3009 dVAR;
20439bc7
Z
3010 U8 utf8_flag;
3011 PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_PVN;
7b0bddfa 3012
94250aee 3013 if (flags & ~(REFCOUNTED_HE_KEY_UTF8|REFCOUNTED_HE_EXISTS))
20439bc7
Z
3014 Perl_croak(aTHX_ "panic: refcounted_he_fetch_pvn bad flags %"UVxf,
3015 (UV)flags);
3016 if (!chain)
3017 return &PL_sv_placeholder;
3018 if (flags & REFCOUNTED_HE_KEY_UTF8) {
3019 /* For searching purposes, canonicalise to Latin-1 where possible. */
3020 const char *keyend = keypv + keylen, *p;
3021 STRLEN nonascii_count = 0;
3022 for (p = keypv; p != keyend; p++) {
3023 U8 c = (U8)*p;
3024 if (c & 0x80) {
3025 if (!((c & 0xfe) == 0xc2 && ++p != keyend &&
3026 (((U8)*p) & 0xc0) == 0x80))
3027 goto canonicalised_key;
3028 nonascii_count++;
3029 }
cd1d2f8a 3030 }
20439bc7
Z
3031 if (nonascii_count) {
3032 char *q;
3033 const char *p = keypv, *keyend = keypv + keylen;
3034 keylen -= nonascii_count;
3035 Newx(q, keylen, char);
3036 SAVEFREEPV(q);
3037 keypv = q;
3038 for (; p != keyend; p++, q++) {
3039 U8 c = (U8)*p;
3040 *q = (char)
3041 ((c & 0x80) ? ((c & 0x03) << 6) | (((U8)*++p) & 0x3f) : c);
cd1d2f8a
NC
3042 }
3043 }
20439bc7
Z
3044 flags &= ~REFCOUNTED_HE_KEY_UTF8;
3045 canonicalised_key: ;
3046 }
3047 utf8_flag = (flags & REFCOUNTED_HE_KEY_UTF8) ? HVhek_UTF8 : 0;
3048 if (!hash)
3049 PERL_HASH(hash, keypv, keylen);
7b0bddfa 3050
20439bc7
Z
3051 for (; chain; chain = chain->refcounted_he_next) {
3052 if (
7b0bddfa 3053#ifdef USE_ITHREADS
20439bc7
Z
3054 hash == chain->refcounted_he_hash &&
3055 keylen == chain->refcounted_he_keylen &&
3056 memEQ(REF_HE_KEY(chain), keypv, keylen) &&
3057 utf8_flag == (chain->refcounted_he_data[0] & HVhek_UTF8)
7b0bddfa 3058#else
20439bc7
Z
3059 hash == HEK_HASH(chain->refcounted_he_hek) &&
3060 keylen == (STRLEN)HEK_LEN(chain->refcounted_he_hek) &&
3061 memEQ(HEK_KEY(chain->refcounted_he_hek), keypv, keylen) &&
3062 utf8_flag == (HEK_FLAGS(chain->refcounted_he_hek) & HVhek_UTF8)
7b0bddfa 3063#endif
20439bc7 3064 )
94250aee
FC
3065 return
3066 flags & REFCOUNTED_HE_EXISTS
3067 ? (chain->refcounted_he_data[0] & HVrhek_typemask)
3068 == HVrhek_delete
3069 ? NULL
3070 : &PL_sv_yes
3071 : sv_2mortal(refcounted_he_value(chain));
3072 }
3073 return flags & REFCOUNTED_HE_EXISTS ? NULL : &PL_sv_placeholder;
20439bc7 3074}
7b0bddfa 3075
20439bc7
Z
3076/*
3077=for apidoc m|SV *|refcounted_he_fetch_pv|const struct refcounted_he *chain|const char *key|U32 hash|U32 flags
7b0bddfa 3078
20439bc7
Z
3079Like L</refcounted_he_fetch_pvn>, but takes a nul-terminated string
3080instead of a string/length pair.
3081
3082=cut
3083*/
3084
3085SV *
3086Perl_refcounted_he_fetch_pv(pTHX_ const struct refcounted_he *chain,
3087 const char *key, U32 hash, U32 flags)
3088{
3089 PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_PV;
3090 return refcounted_he_fetch_pvn(chain, key, strlen(key), hash, flags);
7b0bddfa
NC
3091}
3092
b3ca2e83 3093/*
20439bc7
Z
3094=for apidoc m|SV *|refcounted_he_fetch_sv|const struct refcounted_he *chain|SV *key|U32 hash|U32 flags
3095
3096Like L</refcounted_he_fetch_pvn>, but takes a Perl scalar instead of a
3097string/length pair.
3098
3099=cut
3100*/
b3ca2e83 3101
20439bc7
Z
3102SV *
3103Perl_refcounted_he_fetch_sv(pTHX_ const struct refcounted_he *chain,
3104 SV *key, U32 hash, U32 flags)
3105{
3106 const char *keypv;
3107 STRLEN keylen;
3108 PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_SV;
3109 if (flags & REFCOUNTED_HE_KEY_UTF8)
3110 Perl_croak(aTHX_ "panic: refcounted_he_fetch_sv bad flags %"UVxf,
3111 (UV)flags);
3112 keypv = SvPV_const(key, keylen);
3113 if (SvUTF8(key))
3114 flags |= REFCOUNTED_HE_KEY_UTF8;
3115 if (!hash && SvIsCOW_shared_hash(key))
3116 hash = SvSHARED_HASH(key);
3117 return refcounted_he_fetch_pvn(chain, keypv, keylen, hash, flags);
3118}
3119
3120/*
3121=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
3122
3123Creates a new C<refcounted_he>. This consists of a single key/value
3124pair and a reference to an existing C<refcounted_he> chain (which may
3125be empty), and thus forms a longer chain. When using the longer chain,
3126the new key/value pair takes precedence over any entry for the same key
3127further along the chain.
3128
3129The new key is specified by I<keypv> and I<keylen>. If I<flags> has
3130the C<REFCOUNTED_HE_KEY_UTF8> bit set, the key octets are interpreted
3131as UTF-8, otherwise they are interpreted as Latin-1. I<hash> is
3132a precomputed hash of the key string, or zero if it has not been
3133precomputed.
3134
3135I<value> is the scalar value to store for this key. I<value> is copied
3136by this function, which thus does not take ownership of any reference
3137to it, and later changes to the scalar will not be reflected in the
3138value visible in the C<refcounted_he>. Complex types of scalar will not
3139be stored with referential integrity, but will be coerced to strings.
3140I<value> may be either null or C<&PL_sv_placeholder> to indicate that no
3141value is to be associated with the key; this, as with any non-null value,
3142takes precedence over the existence of a value for the key further along
3143the chain.
3144
3145I<parent> points to the rest of the C<refcounted_he> chain to be
3146attached to the new C<refcounted_he>. This function takes ownership
3147of one reference to I<parent>, and returns one reference to the new
3148C<refcounted_he>.
b3ca2e83
NC
3149
3150=cut
3151*/
3152
3153struct refcounted_he *
20439bc7
Z
3154Perl_refcounted_he_new_pvn(pTHX_ struct refcounted_he *parent,
3155 const char *keypv, STRLEN keylen, U32 hash, SV *value, U32 flags)
3156{
7a89be66 3157 dVAR;
b6bbf3fa 3158 STRLEN value_len = 0;
95b63a38 3159 const char *value_p = NULL;
20439bc7 3160 bool is_pv;
b6bbf3fa 3161 char value_type;
20439bc7
Z
3162 char hekflags;
3163 STRLEN key_offset = 1;
3164 struct refcounted_he *he;
3165 PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_PVN;
b6bbf3fa 3166
20439bc7
Z
3167 if (!value || value == &PL_sv_placeholder) {
3168 value_type = HVrhek_delete;
3169 } else if (SvPOK(value)) {
b6bbf3fa
NC
3170 value_type = HVrhek_PV;
3171 } else if (SvIOK(value)) {
ad64d0ec 3172 value_type = SvUOK((const SV *)value) ? HVrhek_UV : HVrhek_IV;
b6bbf3fa
NC
3173 } else if (!SvOK(value)) {
3174 value_type = HVrhek_undef;
3175 } else {
3176 value_type = HVrhek_PV;
3177 }
20439bc7
Z
3178 is_pv = value_type == HVrhek_PV;
3179 if (is_pv) {
012da8e5
NC
3180 /* Do it this way so that the SvUTF8() test is after the SvPV, in case
3181 the value is overloaded, and doesn't yet have the UTF-8flag set. */
b6bbf3fa 3182 value_p = SvPV_const(value, value_len);
012da8e5
NC
3183 if (SvUTF8(value))
3184 value_type = HVrhek_PV_UTF8;
20439bc7
Z
3185 key_offset = value_len + 2;
3186 }
3187 hekflags = value_type;
3188
3189 if (flags & REFCOUNTED_HE_KEY_UTF8) {
3190 /* Canonicalise to Latin-1 where possible. */
3191 const char *keyend = keypv + keylen, *p;
3192 STRLEN nonascii_count = 0;
3193 for (p = keypv; p != keyend; p++) {
3194 U8 c = (U8)*p;
3195 if (c & 0x80) {
3196 if (!((c & 0xfe) == 0xc2 && ++p != keyend &&
3197 (((U8)*p) & 0xc0) == 0x80))
3198 goto canonicalised_key;
3199 nonascii_count++;
3200 }
3201 }
3202 if (nonascii_count) {
3203 char *q;
3204 const char *p = keypv, *keyend = keypv + keylen;
3205 keylen -= nonascii_count;
3206 Newx(q, keylen, char);
3207 SAVEFREEPV(q);
3208 keypv = q;
3209 for (; p != keyend; p++, q++) {
3210 U8 c = (U8)*p;
3211 *q = (char)
3212 ((c & 0x80) ? ((c & 0x03) << 6) | (((U8)*++p) & 0x3f) : c);
3213 }
3214 }
3215 flags &= ~REFCOUNTED_HE_KEY_UTF8;
3216 canonicalised_key: ;
b6bbf3fa 3217 }
20439bc7
Z
3218 if (flags & REFCOUNTED_HE_KEY_UTF8)
3219 hekflags |= HVhek_UTF8;
3220 if (!hash)
3221 PERL_HASH(hash, keypv, keylen);
012da8e5 3222
0de694c5 3223#ifdef USE_ITHREADS
10edeb5d
JH
3224 he = (struct refcounted_he*)
3225 PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
20439bc7 3226 + keylen
20439bc7 3227 + key_offset);
0de694c5
NC
3228#else
3229 he = (struct refcounted_he*)
3230 PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
3231 + key_offset);
3232#endif
b3ca2e83 3233
71ad1b0c 3234 he->refcounted_he_next = parent;
b6bbf3fa 3235
012da8e5 3236 if (is_pv) {
20439bc7 3237 Copy(value_p, he->refcounted_he_data + 1, value_len + 1, char);
b6bbf3fa 3238 he->refcounted_he_val.refcounted_he_u_len = value_len;
b6bbf3fa 3239 } else if (value_type == HVrhek_IV) {
20439bc7 3240 he->refcounted_he_val.refcounted_he_u_iv = SvIVX(value);
012da8e5 3241 } else if (value_type == HVrhek_UV) {
20439bc7 3242 he->refcounted_he_val.refcounted_he_u_uv = SvUVX(value);
b6bbf3fa
NC
3243 }
3244
cbb1fbea 3245#ifdef USE_ITHREADS
b6bbf3fa 3246 he->refcounted_he_hash = hash;
20439bc7
Z
3247 he->refcounted_he_keylen = keylen;
3248 Copy(keypv, he->refcounted_he_data + key_offset, keylen, char);
cbb1fbea 3249#else
20439bc7 3250 he->refcounted_he_hek = share_hek_flags(keypv, keylen, hash, hekflags);
cbb1fbea 3251#endif
b6bbf3fa 3252
20439bc7 3253 he->refcounted_he_data[0] = hekflags;
b3ca2e83
NC
3254 he->refcounted_he_refcnt = 1;
3255
3256 return he;
3257}
3258
3259/*
20439bc7 3260=for apidoc m|struct refcounted_he *|refcounted_he_new_pv|struct refcounted_he *parent|const char *key|U32 hash|SV *value|U32 flags
b3ca2e83 3261
20439bc7
Z
3262Like L</refcounted_he_new_pvn>, but takes a nul-terminated string instead
3263of a string/length pair.
3264
3265=cut
3266*/
3267
3268struct refcounted_he *
3269Perl_refcounted_he_new_pv(pTHX_ struct refcounted_he *parent,
3270 const char *key, U32 hash, SV *value, U32 flags)
3271{
3272 PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_PV;
3273 return refcounted_he_new_pvn(parent, key, strlen(key), hash, value, flags);
3274}
3275
3276/*
3277=for apidoc m|struct refcounted_he *|refcounted_he_new_sv|struct refcounted_he *parent|SV *key|U32 hash|SV *value|U32 flags
3278
3279Like L</refcounted_he_new_pvn>, but takes a Perl scalar instead of a
3280string/length pair.
3281
3282=cut
3283*/
3284
3285struct refcounted_he *
3286Perl_refcounted_he_new_sv(pTHX_ struct refcounted_he *parent,
3287 SV *key, U32 hash, SV *value, U32 flags)
3288{
3289 const char *keypv;
3290 STRLEN keylen;
3291 PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_SV;
3292 if (flags & REFCOUNTED_HE_KEY_UTF8)
3293 Perl_croak(aTHX_ "panic: refcounted_he_new_sv bad flags %"UVxf,
3294 (UV)flags);
3295 keypv = SvPV_const(key, keylen);
3296 if (SvUTF8(key))
3297 flags |= REFCOUNTED_HE_KEY_UTF8;
3298 if (!hash && SvIsCOW_shared_hash(key))
3299 hash = SvSHARED_HASH(key);
3300 return refcounted_he_new_pvn(parent, keypv, keylen, hash, value, flags);
3301}
3302
3303/*
3304=for apidoc m|void|refcounted_he_free|struct refcounted_he *he
3305
3306Decrements the reference count of a C<refcounted_he> by one. If the
3307reference count reaches zero the structure's memory is freed, which
3308(recursively) causes a reduction of its parent C<refcounted_he>'s
3309reference count. It is safe to pass a null pointer to this function:
3310no action occurs in this case.
b3ca2e83
NC
3311
3312=cut
3313*/
3314
3315void
3316Perl_refcounted_he_free(pTHX_ struct refcounted_he *he) {
53d44271 3317 dVAR;
57ca3b03
AL
3318 PERL_UNUSED_CONTEXT;
3319
b3ca2e83
NC
3320 while (he) {
3321 struct refcounted_he *copy;
cbb1fbea 3322 U32 new_count;
b3ca2e83 3323
cbb1fbea
NC
3324 HINTS_REFCNT_LOCK;
3325 new_count = --he->refcounted_he_refcnt;
3326 HINTS_REFCNT_UNLOCK;
3327
3328 if (new_count) {
b3ca2e83 3329 return;
cbb1fbea 3330 }
b3ca2e83 3331
b6bbf3fa 3332#ifndef USE_ITHREADS
71ad1b0c 3333 unshare_hek_or_pvn (he->refcounted_he_hek, 0, 0, 0);
cbb1fbea 3334#endif
b3ca2e83 3335 copy = he;
71ad1b0c 3336 he = he->refcounted_he_next;
b6bbf3fa 3337 PerlMemShared_free(copy);
b3ca2e83
NC
3338 }
3339}
3340
20439bc7
Z
3341/*
3342=for apidoc m|struct refcounted_he *|refcounted_he_inc|struct refcounted_he *he
3343
3344Increment the reference count of a C<refcounted_he>. The pointer to the
3345C<refcounted_he> is also returned. It is safe to pass a null pointer
3346to this function: no action occurs and a null pointer is returned.
3347
3348=cut
3349*/
3350
3351struct refcounted_he *
3352Perl_refcounted_he_inc(pTHX_ struct refcounted_he *he)
3353{
09ddd873 3354 dVAR;
20439bc7
Z
3355 if (he) {
3356 HINTS_REFCNT_LOCK;
3357 he->refcounted_he_refcnt++;
3358 HINTS_REFCNT_UNLOCK;
3359 }
3360 return he;
3361}
3362
8375c93e 3363/*
aebc0cbe 3364=for apidoc cop_fetch_label
8375c93e
RU
3365
3366Returns the label attached to a cop.
3367The flags pointer may be set to C<SVf_UTF8> or 0.
3368
3369=cut
3370*/
3371
47550813
NC
3372/* pp_entereval is aware that labels are stored with a key ':' at the top of
3373 the linked list. */
dca6062a 3374const char *
aebc0cbe 3375Perl_cop_fetch_label(pTHX_ COP *const cop, STRLEN *len, U32 *flags) {
d6747b7a
NC
3376 struct refcounted_he *const chain = cop->cop_hints_hash;
3377
aebc0cbe 3378 PERL_ARGS_ASSERT_COP_FETCH_LABEL;
d6747b7a 3379
dca6062a
NC
3380 if (!chain)
3381 return NULL;
3382#ifdef USE_ITHREADS
3383 if (chain->refcounted_he_keylen != 1)
3384 return NULL;
3385 if (*REF_HE_KEY(chain) != ':')
3386 return NULL;
3387#else
3388 if ((STRLEN)HEK_LEN(chain->refcounted_he_hek) != 1)
3389 return NULL;
3390 if (*HEK_KEY(chain->refcounted_he_hek) != ':')
3391 return NULL;
3392#endif
012da8e5
NC
3393 /* Stop anyone trying to really mess us up by adding their own value for
3394 ':' into %^H */
3395 if ((chain->refcounted_he_data[0] & HVrhek_typemask) != HVrhek_PV
3396 && (chain->refcounted_he_data[0] & HVrhek_typemask) != HVrhek_PV_UTF8)
3397 return NULL;
3398
dca6062a
NC
3399 if (len)
3400 *len = chain->refcounted_he_val.refcounted_he_u_len;
3401 if (flags) {
3402 *flags = ((chain->refcounted_he_data[0] & HVrhek_typemask)
3403 == HVrhek_PV_UTF8) ? SVf_UTF8 : 0;
3404 }
3405 return chain->refcounted_he_data + 1;
3406}
3407
8375c93e 3408/*
aebc0cbe 3409=for apidoc cop_store_label
8375c93e
RU
3410
3411Save a label into a C<cop_hints_hash>. You need to set flags to C<SVf_UTF8>
3412for a utf-8 label.
3413
3414=cut
3415*/
3416
a77ac40c 3417void
aebc0cbe 3418Perl_cop_store_label(pTHX_ COP *const cop, const char *label, STRLEN len,
a77ac40c 3419 U32 flags)
012da8e5 3420{
20439bc7 3421 SV *labelsv;
aebc0cbe 3422 PERL_ARGS_ASSERT_COP_STORE_LABEL;
547bb267 3423
a77ac40c 3424 if (flags & ~(SVf_UTF8))
aebc0cbe 3425 Perl_croak(aTHX_ "panic: cop_store_label illegal flag bits 0x%" UVxf,
a77ac40c 3426 (UV)flags);
a3179684 3427 labelsv = newSVpvn_flags(label, len, SVs_TEMP);
20439bc7
Z
3428 if (flags & SVf_UTF8)
3429 SvUTF8_on(labelsv);
a77ac40c 3430 cop->cop_hints_hash
20439bc7 3431 = refcounted_he_new_pvs(cop->cop_hints_hash, ":", labelsv, 0);
012da8e5
NC
3432}
3433
b3ca2e83 3434/*
ecae49c0
NC
3435=for apidoc hv_assert
3436
3437Check that a hash is in an internally consistent state.
3438
3439=cut
3440*/
3441
943795c2
NC
3442#ifdef DEBUGGING
3443
ecae49c0
NC
3444void
3445Perl_hv_assert(pTHX_ HV *hv)
3446{
57ca3b03
AL
3447 dVAR;
3448 HE* entry;
3449 int withflags = 0;
3450 int placeholders = 0;
3451 int real = 0;
3452 int bad = 0;
3453 const I32 riter = HvRITER_get(hv);
3454 HE *eiter = HvEITER_get(hv);
3455
7918f24d
NC
3456 PERL_ARGS_ASSERT_HV_ASSERT;
3457
57ca3b03
AL
3458 (void)hv_iterinit(hv);
3459
3460 while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
3461 /* sanity check the values */
3462 if (HeVAL(entry) == &PL_sv_placeholder)
3463 placeholders++;
3464 else
3465 real++;
3466 /* sanity check the keys */
3467 if (HeSVKEY(entry)) {
6f207bd3 3468 NOOP; /* Don't know what to check on SV keys. */
57ca3b03
AL
3469 } else if (HeKUTF8(entry)) {
3470 withflags++;
3471 if (HeKWASUTF8(entry)) {
3472 PerlIO_printf(Perl_debug_log,
d2a455e7 3473 "hash key has both WASUTF8 and UTF8: '%.*s'\n",
57ca3b03
AL
3474 (int) HeKLEN(entry), HeKEY(entry));
3475 bad = 1;
3476 }
3477 } else if (HeKWASUTF8(entry))
3478 withflags++;
3479 }
ad64d0ec 3480 if (!SvTIED_mg((const SV *)hv, PERL_MAGIC_tied)) {
57ca3b03
AL
3481 static const char bad_count[] = "Count %d %s(s), but hash reports %d\n";
3482 const int nhashkeys = HvUSEDKEYS(hv);
3483 const int nhashplaceholders = HvPLACEHOLDERS_get(hv);
3484
3485 if (nhashkeys != real) {
3486 PerlIO_printf(Perl_debug_log, bad_count, real, "keys", nhashkeys );
3487 bad = 1;
3488 }
3489 if (nhashplaceholders != placeholders) {
3490 PerlIO_printf(Perl_debug_log, bad_count, placeholders, "placeholder", nhashplaceholders );
3491 bad = 1;
3492 }
3493 }
3494 if (withflags && ! HvHASKFLAGS(hv)) {
3495 PerlIO_printf(Perl_debug_log,
3496 "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
3497 withflags);
3498 bad = 1;
3499 }
3500 if (bad) {
ad64d0ec 3501 sv_dump(MUTABLE_SV(hv));
57ca3b03
AL
3502 }
3503 HvRITER_set(hv, riter); /* Restore hash iterator state */
3504 HvEITER_set(hv, eiter);
ecae49c0 3505}
af3babe4 3506
943795c2
NC
3507#endif
3508
af3babe4
NC
3509/*
3510 * Local variables:
3511 * c-indentation-style: bsd
3512 * c-basic-offset: 4
3513 * indent-tabs-mode: t
3514 * End:
3515 *
37442d52
RGS
3516 * ex: set ts=8 sts=4 sw=4 noet:
3517 */