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