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