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