This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Add a key flag HVhek_KEYCANONICAL for Perl_hv_common(), which signals that the
[perl5.git] / hv.c
CommitLineData
a0d0e21e 1/* hv.c
79072805 2 *
285be2d0
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/*
95f66cd4
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
cac9b346
NC
43STATIC void
44S_more_he(pTHX)
45{
97aff369 46 dVAR;
c744a122
DM
47 /* We could generate this at compile time via (another) auxiliary C
48 program? */
49 const size_t arena_size = Perl_malloc_good_size(PERL_ARENA_SIZE);
50 HE* he = (HE*) Perl_get_arena(aTHX_ arena_size, HE_SVSLOT);
51 HE * const heend = &he[arena_size / sizeof(HE) - 1];
cac9b346 52
d2a0f284 53 PL_body_roots[HE_SVSLOT] = he;
cac9b346
NC
54 while (he < heend) {
55 HeNEXT(he) = (HE*)(he + 1);
56 he++;
57 }
58 HeNEXT(he) = 0;
59}
60
c941fb51
NC
61#ifdef PURIFY
62
63#define new_HE() (HE*)safemalloc(sizeof(HE))
64#define del_HE(p) safefree((char*)p)
65
66#else
67
76e3520e 68STATIC HE*
cea2e8a9 69S_new_he(pTHX)
4633a7c4 70{
97aff369 71 dVAR;
4633a7c4 72 HE* he;
0bd48802 73 void ** const root = &PL_body_roots[HE_SVSLOT];
6a93a7e5 74
6a93a7e5 75 if (!*root)
cac9b346 76 S_more_he(aTHX);
10edeb5d 77 he = (HE*) *root;
ce3e5c45 78 assert(he);
6a93a7e5 79 *root = HeNEXT(he);
333f433b 80 return he;
4633a7c4
LW
81}
82
c941fb51
NC
83#define new_HE() new_he()
84#define del_HE(p) \
85 STMT_START { \
6a93a7e5
NC
86 HeNEXT(p) = (HE*)(PL_body_roots[HE_SVSLOT]); \
87 PL_body_roots[HE_SVSLOT] = p; \
c941fb51 88 } STMT_END
d33b2eba 89
d33b2eba 90
d33b2eba
GS
91
92#endif
93
76e3520e 94STATIC HEK *
5f66b61c 95S_save_hek_flags(const char *str, I32 len, U32 hash, int flags)
bbce6d69 96{
35a4481c 97 const int flags_masked = flags & HVhek_MASK;
bbce6d69 98 char *k;
99 register HEK *hek;
1c846c1f 100
a02a5408 101 Newx(k, HEK_BASESIZE + len + 2, char);
bbce6d69 102 hek = (HEK*)k;
ff68c719 103 Copy(str, HEK_KEY(hek), len, char);
e05949c7 104 HEK_KEY(hek)[len] = 0;
ff68c719 105 HEK_LEN(hek) = len;
106 HEK_HASH(hek) = hash;
45e34800 107 HEK_FLAGS(hek) = (unsigned char)flags_masked | HVhek_UNSHARED;
dcf933a4
NC
108
109 if (flags & HVhek_FREEKEY)
110 Safefree(str);
bbce6d69 111 return hek;
112}
113
4a31713e 114/* free the pool of temporary HE/HEK pairs returned by hv_fetch_ent
dd28f7bb
DM
115 * for tied hashes */
116
117void
118Perl_free_tied_hv_pool(pTHX)
119{
97aff369 120 dVAR;
dd28f7bb
DM
121 HE *he = PL_hv_fetch_ent_mh;
122 while (he) {
9d4ba2ae 123 HE * const ohe = he;
dd28f7bb 124 Safefree(HeKEY_hek(he));
dd28f7bb
DM
125 he = HeNEXT(he);
126 del_HE(ohe);
127 }
4608196e 128 PL_hv_fetch_ent_mh = NULL;
dd28f7bb
DM
129}
130
d18c6117 131#if defined(USE_ITHREADS)
0bff533c
NC
132HEK *
133Perl_hek_dup(pTHX_ HEK *source, CLONE_PARAMS* param)
134{
658b4a4a 135 HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
9d4ba2ae
AL
136
137 PERL_UNUSED_ARG(param);
0bff533c
NC
138
139 if (shared) {
140 /* We already shared this hash key. */
454f1e26 141 (void)share_hek_hek(shared);
0bff533c
NC
142 }
143 else {
658b4a4a 144 shared
6e838c70
NC
145 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
146 HEK_HASH(source), HEK_FLAGS(source));
658b4a4a 147 ptr_table_store(PL_ptr_table, source, shared);
0bff533c 148 }
658b4a4a 149 return shared;
0bff533c
NC
150}
151
d18c6117 152HE *
5c4138a0 153Perl_he_dup(pTHX_ const HE *e, bool shared, CLONE_PARAMS* param)
d18c6117
GS
154{
155 HE *ret;
156
157 if (!e)
4608196e 158 return NULL;
7766f137
GS
159 /* look for it in the table first */
160 ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
161 if (ret)
162 return ret;
163
164 /* create anew and remember what it is */
d33b2eba 165 ret = new_HE();
7766f137
GS
166 ptr_table_store(PL_ptr_table, e, ret);
167
d2d73c3e 168 HeNEXT(ret) = he_dup(HeNEXT(e),shared, param);
dd28f7bb
DM
169 if (HeKLEN(e) == HEf_SVKEY) {
170 char *k;
a02a5408 171 Newx(k, HEK_BASESIZE + sizeof(SV*), char);
dd28f7bb 172 HeKEY_hek(ret) = (HEK*)k;
d2d73c3e 173 HeKEY_sv(ret) = SvREFCNT_inc(sv_dup(HeKEY_sv(e), param));
dd28f7bb 174 }
c21d1a0f 175 else if (shared) {
0bff533c
NC
176 /* This is hek_dup inlined, which seems to be important for speed
177 reasons. */
1b6737cc 178 HEK * const source = HeKEY_hek(e);
658b4a4a 179 HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
c21d1a0f
NC
180
181 if (shared) {
182 /* We already shared this hash key. */
454f1e26 183 (void)share_hek_hek(shared);
c21d1a0f
NC
184 }
185 else {
658b4a4a 186 shared
6e838c70
NC
187 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
188 HEK_HASH(source), HEK_FLAGS(source));
658b4a4a 189 ptr_table_store(PL_ptr_table, source, shared);
c21d1a0f 190 }
658b4a4a 191 HeKEY_hek(ret) = shared;
c21d1a0f 192 }
d18c6117 193 else
19692e8d
NC
194 HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
195 HeKFLAGS(e));
d2d73c3e 196 HeVAL(ret) = SvREFCNT_inc(sv_dup(HeVAL(e), param));
d18c6117
GS
197 return ret;
198}
199#endif /* USE_ITHREADS */
200
1b1f1335 201static void
2393f1b9
JH
202S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
203 const char *msg)
1b1f1335 204{
1b6737cc 205 SV * const sv = sv_newmortal();
19692e8d 206 if (!(flags & HVhek_FREEKEY)) {
1b1f1335
NIS
207 sv_setpvn(sv, key, klen);
208 }
209 else {
210 /* Need to free saved eventually assign to mortal SV */
34c3c4e3 211 /* XXX is this line an error ???: SV *sv = sv_newmortal(); */
1b1f1335
NIS
212 sv_usepvn(sv, (char *) key, klen);
213 }
19692e8d 214 if (flags & HVhek_UTF8) {
1b1f1335
NIS
215 SvUTF8_on(sv);
216 }
be2597df 217 Perl_croak(aTHX_ msg, SVfARG(sv));
1b1f1335
NIS
218}
219
fde52b5c 220/* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
221 * contains an SV* */
222
34a6f7b4
NC
223/*
224=for apidoc hv_store
225
226Stores an SV in a hash. The hash key is specified as C<key> and C<klen> is
227the length of the key. The C<hash> parameter is the precomputed hash
228value; if it is zero then Perl will compute it. The return value will be
229NULL if the operation failed or if the value did not need to be actually
230stored within the hash (as in the case of tied hashes). Otherwise it can
231be dereferenced to get the original C<SV*>. Note that the caller is
232responsible for suitably incrementing the reference count of C<val> before
233the call, and decrementing it if the function returned NULL. Effectively
234a successful hv_store takes ownership of one reference to C<val>. This is
235usually what you want; a newly created SV has a reference count of one, so
236if all your code does is create SVs then store them in a hash, hv_store
237will own the only reference to the new SV, and your code doesn't need to do
238anything further to tidy up. hv_store is not implemented as a call to
239hv_store_ent, and does not create a temporary SV for the key, so if your
240key data is not already in SV form then use hv_store in preference to
241hv_store_ent.
242
243See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
244information on how to use this function on tied hashes.
245
34a6f7b4
NC
246=for apidoc hv_store_ent
247
248Stores C<val> in a hash. The hash key is specified as C<key>. The C<hash>
249parameter is the precomputed hash value; if it is zero then Perl will
250compute it. The return value is the new hash entry so created. It will be
251NULL if the operation failed or if the value did not need to be actually
252stored within the hash (as in the case of tied hashes). Otherwise the
253contents of the return value can be accessed using the C<He?> macros
254described here. Note that the caller is responsible for suitably
255incrementing the reference count of C<val> before the call, and
256decrementing it if the function returned NULL. Effectively a successful
257hv_store_ent takes ownership of one reference to C<val>. This is
258usually what you want; a newly created SV has a reference count of one, so
259if all your code does is create SVs then store them in a hash, hv_store
260will own the only reference to the new SV, and your code doesn't need to do
261anything further to tidy up. Note that hv_store_ent only reads the C<key>;
262unlike C<val> it does not take ownership of it, so maintaining the correct
263reference count on C<key> is entirely the caller's responsibility. hv_store
264is not implemented as a call to hv_store_ent, and does not create a temporary
265SV for the key, so if your key data is not already in SV form then use
266hv_store in preference to hv_store_ent.
267
268See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
269information on how to use this function on tied hashes.
270
34a6f7b4
NC
271=for apidoc hv_exists
272
273Returns a boolean indicating whether the specified hash key exists. The
274C<klen> is the length of the key.
275
954c1994
GS
276=for apidoc hv_fetch
277
278Returns the SV which corresponds to the specified key in the hash. The
279C<klen> is the length of the key. If C<lval> is set then the fetch will be
280part of a store. Check that the return value is non-null before
d1be9408 281dereferencing 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
304accessing it. The return value when C<tb> is a tied hash is a pointer to a
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
322 if (klen_i32 < 0) {
323 klen = -klen_i32;
324 flags = HVhek_UTF8;
325 } else {
326 klen = klen_i32;
327 flags = 0;
328 }
329 return hv_common(hv, NULL, key, klen, flags, action, val, hash);
330}
331
63c89345 332void *
d3ba3f5c
NC
333Perl_hv_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
334 int flags, int action, SV *val, register U32 hash)
113738bb 335{
27da23d5 336 dVAR;
b2c64049 337 XPVHV* xhv;
b2c64049
NC
338 HE *entry;
339 HE **oentry;
fde52b5c 340 SV *sv;
da58a35d 341 bool is_utf8;
113738bb 342 int masked_flags;
3c84c864 343 const int return_svp = action & HV_FETCH_JUST_SV;
fde52b5c 344
345 if (!hv)
a4fc7abc 346 return NULL;
8265e3d1
NC
347 if (SvTYPE(hv) == SVTYPEMASK)
348 return NULL;
349
350 assert(SvTYPE(hv) == SVt_PVHV);
fde52b5c 351
bdee33e4 352 if (SvSMAGICAL(hv) && SvGMAGICAL(hv) && !(action & HV_DISABLE_UVAR_XKEY)) {
fda2d18a
NC
353 MAGIC* mg;
354 if ((mg = mg_find((SV*)hv, PERL_MAGIC_uvar))) {
355 struct ufuncs * const uf = (struct ufuncs *)mg->mg_ptr;
356 if (uf->uf_set == NULL) {
357 SV* obj = mg->mg_obj;
358
359 if (!keysv) {
26d21c42
NC
360 keysv = newSVpvn_flags(key, klen, SVs_TEMP |
361 ((flags & HVhek_UTF8)
362 ? SVf_UTF8 : 0));
fda2d18a
NC
363 }
364
365 mg->mg_obj = keysv; /* pass key */
366 uf->uf_index = action; /* pass action */
367 magic_getuvar((SV*)hv, mg);
368 keysv = mg->mg_obj; /* may have changed */
369 mg->mg_obj = obj;
370
371 /* If the key may have changed, then we need to invalidate
372 any passed-in computed hash value. */
373 hash = 0;
374 }
375 }
bdee33e4 376 }
113738bb 377 if (keysv) {
e593d2fe
AE
378 if (flags & HVhek_FREEKEY)
379 Safefree(key);
5c144d81 380 key = SvPV_const(keysv, klen);
113738bb 381 is_utf8 = (SvUTF8(keysv) != 0);
a29ea114
NC
382 if (SvIsCOW_shared_hash(keysv)) {
383 flags = HVhek_KEYCANONICAL | (is_utf8 ? HVhek_UTF8 : 0);
384 } else {
385 flags = 0;
386 }
113738bb 387 } else {
c1fe5510 388 is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
113738bb 389 }
113738bb 390
9dbc5603 391 if (action & HV_DELETE) {
3c84c864
NC
392 return (void *) hv_delete_common(hv, keysv, key, klen,
393 flags | (is_utf8 ? HVhek_UTF8 : 0),
394 action, hash);
9dbc5603
NC
395 }
396
b2c64049 397 xhv = (XPVHV*)SvANY(hv);
7f66fda2 398 if (SvMAGICAL(hv)) {
6136c704 399 if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS))) {
44a2ac75 400 if ( mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv))
e62cc96a 401 {
3c84c864 402 /* FIXME should be able to skimp on the HE/HEK here when
7f66fda2 403 HV_FETCH_JUST_SV is true. */
7f66fda2 404 if (!keysv) {
26d21c42
NC
405 keysv = newSVpvn_utf8(key, klen, is_utf8);
406 } else {
7f66fda2 407 keysv = newSVsv(keysv);
113738bb 408 }
44a2ac75
YO
409 sv = sv_newmortal();
410 mg_copy((SV*)hv, sv, (char *)keysv, HEf_SVKEY);
7f66fda2
NC
411
412 /* grab a fake HE/HEK pair from the pool or make a new one */
413 entry = PL_hv_fetch_ent_mh;
414 if (entry)
415 PL_hv_fetch_ent_mh = HeNEXT(entry);
416 else {
417 char *k;
418 entry = new_HE();
a02a5408 419 Newx(k, HEK_BASESIZE + sizeof(SV*), char);
7f66fda2
NC
420 HeKEY_hek(entry) = (HEK*)k;
421 }
4608196e 422 HeNEXT(entry) = NULL;
7f66fda2
NC
423 HeSVKEY_set(entry, keysv);
424 HeVAL(entry) = sv;
425 sv_upgrade(sv, SVt_PVLV);
426 LvTYPE(sv) = 'T';
427 /* so we can free entry when freeing sv */
428 LvTARG(sv) = (SV*)entry;
429
430 /* XXX remove at some point? */
431 if (flags & HVhek_FREEKEY)
432 Safefree(key);
433
3c84c864
NC
434 if (return_svp) {
435 return entry ? (void *) &HeVAL(entry) : NULL;
436 }
437 return (void *) entry;
113738bb 438 }
7f66fda2
NC
439#ifdef ENV_IS_CASELESS
440 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
441 U32 i;
442 for (i = 0; i < klen; ++i)
443 if (isLOWER(key[i])) {
086cb327
NC
444 /* Would be nice if we had a routine to do the
445 copy and upercase in a single pass through. */
0bd48802 446 const char * const nkey = strupr(savepvn(key,klen));
086cb327
NC
447 /* Note that this fetch is for nkey (the uppercased
448 key) whereas the store is for key (the original) */
63c89345
NC
449 void *result = hv_common(hv, NULL, nkey, klen,
450 HVhek_FREEKEY, /* free nkey */
451 0 /* non-LVAL fetch */
3c84c864
NC
452 | HV_DISABLE_UVAR_XKEY
453 | return_svp,
63c89345
NC
454 NULL /* no value */,
455 0 /* compute hash */);
26488bcf 456 if (!result && (action & HV_FETCH_LVALUE)) {
086cb327
NC
457 /* This call will free key if necessary.
458 Do it this way to encourage compiler to tail
459 call optimise. */
63c89345
NC
460 result = hv_common(hv, keysv, key, klen, flags,
461 HV_FETCH_ISSTORE
3c84c864
NC
462 | HV_DISABLE_UVAR_XKEY
463 | return_svp,
63c89345 464 newSV(0), hash);
086cb327
NC
465 } else {
466 if (flags & HVhek_FREEKEY)
467 Safefree(key);
468 }
63c89345 469 return result;
7f66fda2 470 }
902173a3 471 }
7f66fda2
NC
472#endif
473 } /* ISFETCH */
474 else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
475 if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
b2c64049
NC
476 /* I don't understand why hv_exists_ent has svret and sv,
477 whereas hv_exists only had one. */
9d4ba2ae 478 SV * const svret = sv_newmortal();
b2c64049 479 sv = sv_newmortal();
7f66fda2
NC
480
481 if (keysv || is_utf8) {
482 if (!keysv) {
26d21c42 483 keysv = newSVpvn_utf8(key, klen, TRUE);
7f66fda2
NC
484 } else {
485 keysv = newSVsv(keysv);
486 }
b2c64049
NC
487 mg_copy((SV*)hv, sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
488 } else {
489 mg_copy((SV*)hv, sv, key, klen);
7f66fda2 490 }
b2c64049
NC
491 if (flags & HVhek_FREEKEY)
492 Safefree(key);
7f66fda2
NC
493 magic_existspack(svret, mg_find(sv, PERL_MAGIC_tiedelem));
494 /* This cast somewhat evil, but I'm merely using NULL/
495 not NULL to return the boolean exists.
496 And I know hv is not NULL. */
3c84c864 497 return SvTRUE(svret) ? (void *)hv : NULL;
e7152ba2 498 }
7f66fda2
NC
499#ifdef ENV_IS_CASELESS
500 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
501 /* XXX This code isn't UTF8 clean. */
a15d23f8 502 char * const keysave = (char * const)key;
b2c64049
NC
503 /* Will need to free this, so set FREEKEY flag. */
504 key = savepvn(key,klen);
505 key = (const char*)strupr((char*)key);
6136c704 506 is_utf8 = FALSE;
7f66fda2 507 hash = 0;
8b4f7dd5 508 keysv = 0;
b2c64049
NC
509
510 if (flags & HVhek_FREEKEY) {
511 Safefree(keysave);
512 }
513 flags |= HVhek_FREEKEY;
7f66fda2 514 }
902173a3 515#endif
7f66fda2 516 } /* ISEXISTS */
b2c64049
NC
517 else if (action & HV_FETCH_ISSTORE) {
518 bool needs_copy;
519 bool needs_store;
520 hv_magic_check (hv, &needs_copy, &needs_store);
521 if (needs_copy) {
a3b680e6 522 const bool save_taint = PL_tainted;
b2c64049
NC
523 if (keysv || is_utf8) {
524 if (!keysv) {
26d21c42 525 keysv = newSVpvn_utf8(key, klen, TRUE);
b2c64049
NC
526 }
527 if (PL_tainting)
528 PL_tainted = SvTAINTED(keysv);
529 keysv = sv_2mortal(newSVsv(keysv));
530 mg_copy((SV*)hv, val, (char*)keysv, HEf_SVKEY);
531 } else {
532 mg_copy((SV*)hv, val, key, klen);
533 }
534
535 TAINT_IF(save_taint);
1baaf5d7 536 if (!needs_store) {
b2c64049
NC
537 if (flags & HVhek_FREEKEY)
538 Safefree(key);
4608196e 539 return NULL;
b2c64049
NC
540 }
541#ifdef ENV_IS_CASELESS
542 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
543 /* XXX This code isn't UTF8 clean. */
544 const char *keysave = key;
545 /* Will need to free this, so set FREEKEY flag. */
546 key = savepvn(key,klen);
547 key = (const char*)strupr((char*)key);
6136c704 548 is_utf8 = FALSE;
b2c64049 549 hash = 0;
8b4f7dd5 550 keysv = 0;
b2c64049
NC
551
552 if (flags & HVhek_FREEKEY) {
553 Safefree(keysave);
554 }
555 flags |= HVhek_FREEKEY;
556 }
557#endif
558 }
559 } /* ISSTORE */
7f66fda2 560 } /* SvMAGICAL */
fde52b5c 561
7b2c381c 562 if (!HvARRAY(hv)) {
b2c64049 563 if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
fde52b5c 564#ifdef DYNAMIC_ENV_FETCH /* if it's an %ENV lookup, we may get it on the fly */
8aacddc1 565 || (SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
fde52b5c 566#endif
d58e6666
NC
567 ) {
568 char *array;
a02a5408 569 Newxz(array,
cbec9347 570 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
d58e6666
NC
571 char);
572 HvARRAY(hv) = (HE**)array;
573 }
7f66fda2
NC
574#ifdef DYNAMIC_ENV_FETCH
575 else if (action & HV_FETCH_ISEXISTS) {
576 /* for an %ENV exists, if we do an insert it's by a recursive
577 store call, so avoid creating HvARRAY(hv) right now. */
578 }
579#endif
113738bb
NC
580 else {
581 /* XXX remove at some point? */
582 if (flags & HVhek_FREEKEY)
583 Safefree(key);
584
3c84c864 585 return NULL;
113738bb 586 }
fde52b5c 587 }
588
a29ea114 589 if (is_utf8 & !(flags & HVhek_KEYCANONICAL)) {
41d88b63 590 char * const keysave = (char *)key;
f9a63242 591 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
19692e8d 592 if (is_utf8)
c1fe5510
NC
593 flags |= HVhek_UTF8;
594 else
595 flags &= ~HVhek_UTF8;
7f66fda2
NC
596 if (key != keysave) {
597 if (flags & HVhek_FREEKEY)
598 Safefree(keysave);
19692e8d 599 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
7f66fda2 600 }
19692e8d 601 }
f9a63242 602
4b5190b5
NC
603 if (HvREHASH(hv)) {
604 PERL_HASH_INTERNAL(hash, key, klen);
b2c64049
NC
605 /* We don't have a pointer to the hv, so we have to replicate the
606 flag into every HEK, so that hv_iterkeysv can see it. */
607 /* And yes, you do need this even though you are not "storing" because
fdcd69b6
NC
608 you can flip the flags below if doing an lval lookup. (And that
609 was put in to give the semantics Andreas was expecting.) */
610 flags |= HVhek_REHASH;
4b5190b5 611 } else if (!hash) {
113738bb 612 if (keysv && (SvIsCOW_shared_hash(keysv))) {
c158a4fd 613 hash = SvSHARED_HASH(keysv);
46187eeb
NC
614 } else {
615 PERL_HASH(hash, key, klen);
616 }
617 }
effa1e2d 618
113738bb
NC
619 masked_flags = (flags & HVhek_MASK);
620
7f66fda2 621#ifdef DYNAMIC_ENV_FETCH
4608196e 622 if (!HvARRAY(hv)) entry = NULL;
7f66fda2
NC
623 else
624#endif
b2c64049 625 {
7b2c381c 626 entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
b2c64049 627 }
0298d7b9 628 for (; entry; entry = HeNEXT(entry)) {
fde52b5c 629 if (HeHASH(entry) != hash) /* strings can't be equal */
630 continue;
eb160463 631 if (HeKLEN(entry) != (I32)klen)
fde52b5c 632 continue;
1c846c1f 633 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
fde52b5c 634 continue;
113738bb 635 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
c3654f1a 636 continue;
b2c64049
NC
637
638 if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
639 if (HeKFLAGS(entry) != masked_flags) {
640 /* We match if HVhek_UTF8 bit in our flags and hash key's
641 match. But if entry was set previously with HVhek_WASUTF8
642 and key now doesn't (or vice versa) then we should change
643 the key's flag, as this is assignment. */
644 if (HvSHAREKEYS(hv)) {
645 /* Need to swap the key we have for a key with the flags we
646 need. As keys are shared we can't just write to the
647 flag, so we share the new one, unshare the old one. */
6136c704 648 HEK * const new_hek = share_hek_flags(key, klen, hash,
6e838c70 649 masked_flags);
b2c64049
NC
650 unshare_hek (HeKEY_hek(entry));
651 HeKEY_hek(entry) = new_hek;
652 }
5d2b1485
NC
653 else if (hv == PL_strtab) {
654 /* PL_strtab is usually the only hash without HvSHAREKEYS,
655 so putting this test here is cheap */
656 if (flags & HVhek_FREEKEY)
657 Safefree(key);
658 Perl_croak(aTHX_ S_strtab_error,
659 action & HV_FETCH_LVALUE ? "fetch" : "store");
660 }
b2c64049
NC
661 else
662 HeKFLAGS(entry) = masked_flags;
663 if (masked_flags & HVhek_ENABLEHVKFLAGS)
664 HvHASKFLAGS_on(hv);
665 }
666 if (HeVAL(entry) == &PL_sv_placeholder) {
667 /* yes, can store into placeholder slot */
668 if (action & HV_FETCH_LVALUE) {
669 if (SvMAGICAL(hv)) {
670 /* This preserves behaviour with the old hv_fetch
671 implementation which at this point would bail out
672 with a break; (at "if we find a placeholder, we
673 pretend we haven't found anything")
674
675 That break mean that if a placeholder were found, it
676 caused a call into hv_store, which in turn would
677 check magic, and if there is no magic end up pretty
678 much back at this point (in hv_store's code). */
679 break;
680 }
681 /* LVAL fetch which actaully needs a store. */
561b68a9 682 val = newSV(0);
ca732855 683 HvPLACEHOLDERS(hv)--;
b2c64049
NC
684 } else {
685 /* store */
686 if (val != &PL_sv_placeholder)
ca732855 687 HvPLACEHOLDERS(hv)--;
b2c64049
NC
688 }
689 HeVAL(entry) = val;
690 } else if (action & HV_FETCH_ISSTORE) {
691 SvREFCNT_dec(HeVAL(entry));
692 HeVAL(entry) = val;
693 }
27bcc0a7 694 } else if (HeVAL(entry) == &PL_sv_placeholder) {
b2c64049
NC
695 /* if we find a placeholder, we pretend we haven't found
696 anything */
8aacddc1 697 break;
b2c64049 698 }
113738bb
NC
699 if (flags & HVhek_FREEKEY)
700 Safefree(key);
3c84c864
NC
701 if (return_svp) {
702 return entry ? (void *) &HeVAL(entry) : NULL;
703 }
fde52b5c 704 return entry;
705 }
706#ifdef DYNAMIC_ENV_FETCH /* %ENV lookup? If so, try to fetch the value now */
0ed29950
NC
707 if (!(action & HV_FETCH_ISSTORE)
708 && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
a6c40364 709 unsigned long len;
9d4ba2ae 710 const char * const env = PerlEnv_ENVgetenv_len(key,&len);
a6c40364
GS
711 if (env) {
712 sv = newSVpvn(env,len);
713 SvTAINTED_on(sv);
d3ba3f5c 714 return hv_common(hv, keysv, key, klen, flags,
3c84c864
NC
715 HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
716 sv, hash);
a6c40364 717 }
fde52b5c 718 }
719#endif
7f66fda2
NC
720
721 if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
c445ea15 722 hv_notallowed(flags, key, klen,
c8cd6465
NC
723 "Attempt to access disallowed key '%"SVf"' in"
724 " a restricted hash");
1b1f1335 725 }
b2c64049
NC
726 if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
727 /* Not doing some form of store, so return failure. */
728 if (flags & HVhek_FREEKEY)
729 Safefree(key);
3c84c864 730 return NULL;
b2c64049 731 }
113738bb 732 if (action & HV_FETCH_LVALUE) {
561b68a9 733 val = newSV(0);
b2c64049
NC
734 if (SvMAGICAL(hv)) {
735 /* At this point the old hv_fetch code would call to hv_store,
736 which in turn might do some tied magic. So we need to make that
737 magic check happen. */
738 /* gonna assign to this, so it better be there */
fda2d18a
NC
739 /* If a fetch-as-store fails on the fetch, then the action is to
740 recurse once into "hv_store". If we didn't do this, then that
741 recursive call would call the key conversion routine again.
742 However, as we replace the original key with the converted
743 key, this would result in a double conversion, which would show
744 up as a bug if the conversion routine is not idempotent. */
d3ba3f5c 745 return hv_common(hv, keysv, key, klen, flags,
3c84c864
NC
746 HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
747 val, hash);
b2c64049
NC
748 /* XXX Surely that could leak if the fetch-was-store fails?
749 Just like the hv_fetch. */
113738bb
NC
750 }
751 }
752
b2c64049
NC
753 /* Welcome to hv_store... */
754
7b2c381c 755 if (!HvARRAY(hv)) {
b2c64049
NC
756 /* Not sure if we can get here. I think the only case of oentry being
757 NULL is for %ENV with dynamic env fetch. But that should disappear
758 with magic in the previous code. */
d58e6666 759 char *array;
a02a5408 760 Newxz(array,
b2c64049 761 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
d58e6666
NC
762 char);
763 HvARRAY(hv) = (HE**)array;
b2c64049
NC
764 }
765
7b2c381c 766 oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
ab4af705 767
b2c64049
NC
768 entry = new_HE();
769 /* share_hek_flags will do the free for us. This might be considered
770 bad API design. */
771 if (HvSHAREKEYS(hv))
6e838c70 772 HeKEY_hek(entry) = share_hek_flags(key, klen, hash, flags);
5d2b1485
NC
773 else if (hv == PL_strtab) {
774 /* PL_strtab is usually the only hash without HvSHAREKEYS, so putting
775 this test here is cheap */
776 if (flags & HVhek_FREEKEY)
777 Safefree(key);
778 Perl_croak(aTHX_ S_strtab_error,
779 action & HV_FETCH_LVALUE ? "fetch" : "store");
780 }
b2c64049
NC
781 else /* gotta do the real thing */
782 HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
783 HeVAL(entry) = val;
784 HeNEXT(entry) = *oentry;
785 *oentry = entry;
786
787 if (val == &PL_sv_placeholder)
ca732855 788 HvPLACEHOLDERS(hv)++;
b2c64049
NC
789 if (masked_flags & HVhek_ENABLEHVKFLAGS)
790 HvHASKFLAGS_on(hv);
791
0298d7b9
NC
792 {
793 const HE *counter = HeNEXT(entry);
794
4c7185a0 795 xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
0298d7b9
NC
796 if (!counter) { /* initial entry? */
797 xhv->xhv_fill++; /* HvFILL(hv)++ */
798 } else if (xhv->xhv_keys > (IV)xhv->xhv_max) {
799 hsplit(hv);
800 } else if(!HvREHASH(hv)) {
801 U32 n_links = 1;
802
803 while ((counter = HeNEXT(counter)))
804 n_links++;
805
806 if (n_links > HV_MAX_LENGTH_BEFORE_SPLIT) {
807 /* Use only the old HvKEYS(hv) > HvMAX(hv) condition to limit
808 bucket splits on a rehashed hash, as we're not going to
809 split it again, and if someone is lucky (evil) enough to
810 get all the keys in one list they could exhaust our memory
811 as we repeatedly double the number of buckets on every
812 entry. Linear search feels a less worse thing to do. */
813 hsplit(hv);
814 }
815 }
fde52b5c 816 }
b2c64049 817
3c84c864
NC
818 if (return_svp) {
819 return entry ? (void *) &HeVAL(entry) : NULL;
820 }
821 return (void *) entry;
fde52b5c 822}
823
864dbfa3 824STATIC void
b0e6ae5b 825S_hv_magic_check(HV *hv, bool *needs_copy, bool *needs_store)
d0066dc7 826{
a3b680e6 827 const MAGIC *mg = SvMAGIC(hv);
d0066dc7
OT
828 *needs_copy = FALSE;
829 *needs_store = TRUE;
830 while (mg) {
831 if (isUPPER(mg->mg_type)) {
832 *needs_copy = TRUE;
d60c5a05 833 if (mg->mg_type == PERL_MAGIC_tied) {
d0066dc7 834 *needs_store = FALSE;
4ab2a30b 835 return; /* We've set all there is to set. */
d0066dc7
OT
836 }
837 }
838 mg = mg->mg_moremagic;
839 }
840}
841
954c1994 842/*
a3bcc51e
TP
843=for apidoc hv_scalar
844
845Evaluates the hash in scalar context and returns the result. Handles magic when the hash is tied.
846
847=cut
848*/
849
850SV *
851Perl_hv_scalar(pTHX_ HV *hv)
852{
a3bcc51e 853 SV *sv;
823a54a3
AL
854
855 if (SvRMAGICAL(hv)) {
856 MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_tied);
857 if (mg)
858 return magic_scalarpack(hv, mg);
859 }
a3bcc51e
TP
860
861 sv = sv_newmortal();
862 if (HvFILL((HV*)hv))
863 Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
864 (long)HvFILL(hv), (long)HvMAX(hv) + 1);
865 else
866 sv_setiv(sv, 0);
867
868 return sv;
869}
870
871/*
954c1994
GS
872=for apidoc hv_delete
873
874Deletes a key/value pair in the hash. The value SV is removed from the
1c846c1f 875hash and returned to the caller. The C<klen> is the length of the key.
954c1994
GS
876The C<flags> value will normally be zero; if set to G_DISCARD then NULL
877will be returned.
878
954c1994
GS
879=for apidoc hv_delete_ent
880
881Deletes a key/value pair in the hash. The value SV is removed from the
882hash and returned to the caller. The C<flags> value will normally be zero;
883if set to G_DISCARD then NULL will be returned. C<hash> can be a valid
884precomputed hash value, or 0 to ask for it to be computed.
885
886=cut
887*/
888
8f8d40ab 889STATIC SV *
cd6d36ac
NC
890S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
891 int k_flags, I32 d_flags, U32 hash)
f1317c8d 892{
27da23d5 893 dVAR;
cbec9347 894 register XPVHV* xhv;
fde52b5c 895 register HE *entry;
896 register HE **oentry;
9e720f71 897 HE *const *first_entry;
9dbc5603 898 bool is_utf8 = (k_flags & HVhek_UTF8) ? TRUE : FALSE;
7a9669ca 899 int masked_flags;
1c846c1f 900
fde52b5c 901 if (SvRMAGICAL(hv)) {
0a0bb7c7
OT
902 bool needs_copy;
903 bool needs_store;
904 hv_magic_check (hv, &needs_copy, &needs_store);
905
f1317c8d 906 if (needs_copy) {
6136c704 907 SV *sv;
63c89345
NC
908 entry = (HE *) hv_common(hv, keysv, key, klen,
909 k_flags & ~HVhek_FREEKEY,
910 HV_FETCH_LVALUE|HV_DISABLE_UVAR_XKEY,
911 NULL, hash);
7a9669ca 912 sv = entry ? HeVAL(entry) : NULL;
f1317c8d
NC
913 if (sv) {
914 if (SvMAGICAL(sv)) {
915 mg_clear(sv);
916 }
917 if (!needs_store) {
918 if (mg_find(sv, PERL_MAGIC_tiedelem)) {
919 /* No longer an element */
920 sv_unmagic(sv, PERL_MAGIC_tiedelem);
921 return sv;
922 }
a0714e2c 923 return NULL; /* element cannot be deleted */
f1317c8d 924 }
902173a3 925#ifdef ENV_IS_CASELESS
8167a60a
NC
926 else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
927 /* XXX This code isn't UTF8 clean. */
26d21c42 928 keysv = newSVpvn_flags(key, klen, SVs_TEMP);
8167a60a
NC
929 if (k_flags & HVhek_FREEKEY) {
930 Safefree(key);
931 }
932 key = strupr(SvPVX(keysv));
933 is_utf8 = 0;
934 k_flags = 0;
935 hash = 0;
7f66fda2 936 }
510ac311 937#endif
2fd1c6b8 938 }
2fd1c6b8 939 }
fde52b5c 940 }
cbec9347 941 xhv = (XPVHV*)SvANY(hv);
7b2c381c 942 if (!HvARRAY(hv))
a0714e2c 943 return NULL;
fde52b5c 944
19692e8d 945 if (is_utf8) {
c445ea15 946 const char * const keysave = key;
b464bac0 947 key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
cd6d36ac 948
19692e8d 949 if (is_utf8)
cd6d36ac
NC
950 k_flags |= HVhek_UTF8;
951 else
952 k_flags &= ~HVhek_UTF8;
7f66fda2
NC
953 if (key != keysave) {
954 if (k_flags & HVhek_FREEKEY) {
955 /* This shouldn't happen if our caller does what we expect,
956 but strictly the API allows it. */
957 Safefree(keysave);
958 }
959 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
960 }
cd6d36ac 961 HvHASKFLAGS_on((SV*)hv);
19692e8d 962 }
f9a63242 963
4b5190b5
NC
964 if (HvREHASH(hv)) {
965 PERL_HASH_INTERNAL(hash, key, klen);
966 } else if (!hash) {
7a9669ca 967 if (keysv && (SvIsCOW_shared_hash(keysv))) {
c158a4fd 968 hash = SvSHARED_HASH(keysv);
7a9669ca
NC
969 } else {
970 PERL_HASH(hash, key, klen);
971 }
4b5190b5 972 }
fde52b5c 973
7a9669ca
NC
974 masked_flags = (k_flags & HVhek_MASK);
975
9e720f71 976 first_entry = oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
fde52b5c 977 entry = *oentry;
9e720f71 978 for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
6136c704 979 SV *sv;
fde52b5c 980 if (HeHASH(entry) != hash) /* strings can't be equal */
981 continue;
eb160463 982 if (HeKLEN(entry) != (I32)klen)
fde52b5c 983 continue;
1c846c1f 984 if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen)) /* is this it? */
fde52b5c 985 continue;
7a9669ca 986 if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
c3654f1a 987 continue;
8aacddc1 988
5d2b1485
NC
989 if (hv == PL_strtab) {
990 if (k_flags & HVhek_FREEKEY)
991 Safefree(key);
992 Perl_croak(aTHX_ S_strtab_error, "delete");
993 }
994
8aacddc1 995 /* if placeholder is here, it's already been deleted.... */
6136c704
AL
996 if (HeVAL(entry) == &PL_sv_placeholder) {
997 if (k_flags & HVhek_FREEKEY)
998 Safefree(key);
999 return NULL;
8aacddc1 1000 }
6136c704 1001 if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
d4c19fe8 1002 hv_notallowed(k_flags, key, klen,
c8cd6465
NC
1003 "Attempt to delete readonly key '%"SVf"' from"
1004 " a restricted hash");
8aacddc1 1005 }
b84d0860
NC
1006 if (k_flags & HVhek_FREEKEY)
1007 Safefree(key);
8aacddc1 1008
cd6d36ac 1009 if (d_flags & G_DISCARD)
a0714e2c 1010 sv = NULL;
94f7643d 1011 else {
79d01fbf 1012 sv = sv_2mortal(HeVAL(entry));
7996736c 1013 HeVAL(entry) = &PL_sv_placeholder;
94f7643d 1014 }
8aacddc1
NIS
1015
1016 /*
1017 * If a restricted hash, rather than really deleting the entry, put
1018 * a placeholder there. This marks the key as being "approved", so
1019 * we can still access via not-really-existing key without raising
1020 * an error.
1021 */
1022 if (SvREADONLY(hv)) {
754604c4 1023 SvREFCNT_dec(HeVAL(entry));
7996736c 1024 HeVAL(entry) = &PL_sv_placeholder;
8aacddc1
NIS
1025 /* We'll be saving this slot, so the number of allocated keys
1026 * doesn't go down, but the number placeholders goes up */
ca732855 1027 HvPLACEHOLDERS(hv)++;
8aacddc1 1028 } else {
a26e96df 1029 *oentry = HeNEXT(entry);
9e720f71 1030 if(!*first_entry) {
a26e96df 1031 xhv->xhv_fill--; /* HvFILL(hv)-- */
9e720f71 1032 }
b79f7545 1033 if (SvOOK(hv) && entry == HvAUX(hv)->xhv_eiter /* HvEITER(hv) */)
8aacddc1
NIS
1034 HvLAZYDEL_on(hv);
1035 else
1036 hv_free_ent(hv, entry);
4c7185a0 1037 xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
574c8022 1038 if (xhv->xhv_keys == 0)
19692e8d 1039 HvHASKFLAGS_off(hv);
8aacddc1 1040 }
79072805
LW
1041 return sv;
1042 }
8aacddc1 1043 if (SvREADONLY(hv)) {
d4c19fe8 1044 hv_notallowed(k_flags, key, klen,
c8cd6465
NC
1045 "Attempt to delete disallowed key '%"SVf"' from"
1046 " a restricted hash");
8aacddc1
NIS
1047 }
1048
19692e8d 1049 if (k_flags & HVhek_FREEKEY)
f9a63242 1050 Safefree(key);
a0714e2c 1051 return NULL;
79072805
LW
1052}
1053
76e3520e 1054STATIC void
cea2e8a9 1055S_hsplit(pTHX_ HV *hv)
79072805 1056{
97aff369 1057 dVAR;
1e05feb3 1058 register XPVHV* const xhv = (XPVHV*)SvANY(hv);
a3b680e6 1059 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
79072805
LW
1060 register I32 newsize = oldsize * 2;
1061 register I32 i;
7b2c381c 1062 char *a = (char*) HvARRAY(hv);
72311751 1063 register HE **aep;
79072805 1064 register HE **oentry;
4b5190b5
NC
1065 int longest_chain = 0;
1066 int was_shared;
79072805 1067
18026298 1068 /*PerlIO_printf(PerlIO_stderr(), "hsplit called for %p which had %d\n",
6c9570dc 1069 (void*)hv, (int) oldsize);*/
18026298 1070
5d88ecd7 1071 if (HvPLACEHOLDERS_get(hv) && !SvREADONLY(hv)) {
18026298
NC
1072 /* Can make this clear any placeholders first for non-restricted hashes,
1073 even though Storable rebuilds restricted hashes by putting in all the
1074 placeholders (first) before turning on the readonly flag, because
1075 Storable always pre-splits the hash. */
1076 hv_clear_placeholders(hv);
1077 }
1078
3280af22 1079 PL_nomemok = TRUE;
8d6dde3e 1080#if defined(STRANGE_MALLOC) || defined(MYMALLOC)
b79f7545
NC
1081 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1082 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
422a93e5 1083 if (!a) {
4a33f861 1084 PL_nomemok = FALSE;
422a93e5
GA
1085 return;
1086 }
b79f7545 1087 if (SvOOK(hv)) {
0c7c143d 1088 Move(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
b79f7545 1089 }
4633a7c4 1090#else
a02a5408 1091 Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
b79f7545 1092 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
422a93e5 1093 if (!a) {
3280af22 1094 PL_nomemok = FALSE;
422a93e5
GA
1095 return;
1096 }
7b2c381c 1097 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
b79f7545
NC
1098 if (SvOOK(hv)) {
1099 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1100 }
fba3b22e 1101 if (oldsize >= 64) {
7b2c381c 1102 offer_nice_chunk(HvARRAY(hv),
b79f7545
NC
1103 PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
1104 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
4633a7c4
LW
1105 }
1106 else
7b2c381c 1107 Safefree(HvARRAY(hv));
4633a7c4
LW
1108#endif
1109
3280af22 1110 PL_nomemok = FALSE;
72311751 1111 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
cbec9347 1112 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
7b2c381c 1113 HvARRAY(hv) = (HE**) a;
72311751 1114 aep = (HE**)a;
79072805 1115
72311751 1116 for (i=0; i<oldsize; i++,aep++) {
4b5190b5
NC
1117 int left_length = 0;
1118 int right_length = 0;
a3b680e6
AL
1119 register HE *entry;
1120 register HE **bep;
4b5190b5 1121
72311751 1122 if (!*aep) /* non-existent */
79072805 1123 continue;
72311751
GS
1124 bep = aep+oldsize;
1125 for (oentry = aep, entry = *aep; entry; entry = *oentry) {
eb160463 1126 if ((HeHASH(entry) & newsize) != (U32)i) {
fde52b5c 1127 *oentry = HeNEXT(entry);
72311751
GS
1128 HeNEXT(entry) = *bep;
1129 if (!*bep)
cbec9347 1130 xhv->xhv_fill++; /* HvFILL(hv)++ */
72311751 1131 *bep = entry;
4b5190b5 1132 right_length++;
79072805
LW
1133 continue;
1134 }
4b5190b5 1135 else {
fde52b5c 1136 oentry = &HeNEXT(entry);
4b5190b5
NC
1137 left_length++;
1138 }
79072805 1139 }
72311751 1140 if (!*aep) /* everything moved */
cbec9347 1141 xhv->xhv_fill--; /* HvFILL(hv)-- */
4b5190b5
NC
1142 /* I think we don't actually need to keep track of the longest length,
1143 merely flag if anything is too long. But for the moment while
1144 developing this code I'll track it. */
1145 if (left_length > longest_chain)
1146 longest_chain = left_length;
1147 if (right_length > longest_chain)
1148 longest_chain = right_length;
1149 }
1150
1151
1152 /* Pick your policy for "hashing isn't working" here: */
fdcd69b6 1153 if (longest_chain <= HV_MAX_LENGTH_BEFORE_SPLIT /* split worked? */
4b5190b5
NC
1154 || HvREHASH(hv)) {
1155 return;
79072805 1156 }
4b5190b5
NC
1157
1158 if (hv == PL_strtab) {
1159 /* Urg. Someone is doing something nasty to the string table.
1160 Can't win. */
1161 return;
1162 }
1163
1164 /* Awooga. Awooga. Pathological data. */
6c9570dc 1165 /*PerlIO_printf(PerlIO_stderr(), "%p %d of %d with %d/%d buckets\n", (void*)hv,
4b5190b5
NC
1166 longest_chain, HvTOTALKEYS(hv), HvFILL(hv), 1+HvMAX(hv));*/
1167
1168 ++newsize;
a02a5408 1169 Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
b79f7545
NC
1170 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1171 if (SvOOK(hv)) {
1172 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1173 }
1174
4b5190b5
NC
1175 was_shared = HvSHAREKEYS(hv);
1176
1177 xhv->xhv_fill = 0;
1178 HvSHAREKEYS_off(hv);
1179 HvREHASH_on(hv);
1180
7b2c381c 1181 aep = HvARRAY(hv);
4b5190b5
NC
1182
1183 for (i=0; i<newsize; i++,aep++) {
a3b680e6 1184 register HE *entry = *aep;
4b5190b5
NC
1185 while (entry) {
1186 /* We're going to trash this HE's next pointer when we chain it
1187 into the new hash below, so store where we go next. */
9d4ba2ae 1188 HE * const next = HeNEXT(entry);
4b5190b5 1189 UV hash;
a3b680e6 1190 HE **bep;
4b5190b5
NC
1191
1192 /* Rehash it */
1193 PERL_HASH_INTERNAL(hash, HeKEY(entry), HeKLEN(entry));
1194
1195 if (was_shared) {
1196 /* Unshare it. */
aec46f14 1197 HEK * const new_hek
4b5190b5
NC
1198 = save_hek_flags(HeKEY(entry), HeKLEN(entry),
1199 hash, HeKFLAGS(entry));
1200 unshare_hek (HeKEY_hek(entry));
1201 HeKEY_hek(entry) = new_hek;
1202 } else {
1203 /* Not shared, so simply write the new hash in. */
1204 HeHASH(entry) = hash;
1205 }
1206 /*PerlIO_printf(PerlIO_stderr(), "%d ", HeKFLAGS(entry));*/
1207 HEK_REHASH_on(HeKEY_hek(entry));
1208 /*PerlIO_printf(PerlIO_stderr(), "%d\n", HeKFLAGS(entry));*/
1209
1210 /* Copy oentry to the correct new chain. */
1211 bep = ((HE**)a) + (hash & (I32) xhv->xhv_max);
1212 if (!*bep)
1213 xhv->xhv_fill++; /* HvFILL(hv)++ */
1214 HeNEXT(entry) = *bep;
1215 *bep = entry;
1216
1217 entry = next;
1218 }
1219 }
7b2c381c
NC
1220 Safefree (HvARRAY(hv));
1221 HvARRAY(hv) = (HE **)a;
79072805
LW
1222}
1223
72940dca 1224void
864dbfa3 1225Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
72940dca 1226{
97aff369 1227 dVAR;
cbec9347 1228 register XPVHV* xhv = (XPVHV*)SvANY(hv);
a3b680e6 1229 const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
72940dca 1230 register I32 newsize;
1231 register I32 i;
72311751
GS
1232 register char *a;
1233 register HE **aep;
72940dca 1234 register HE *entry;
1235 register HE **oentry;
1236
1237 newsize = (I32) newmax; /* possible truncation here */
1238 if (newsize != newmax || newmax <= oldsize)
1239 return;
1240 while ((newsize & (1 + ~newsize)) != newsize) {
1241 newsize &= ~(newsize & (1 + ~newsize)); /* get proper power of 2 */
1242 }
1243 if (newsize < newmax)
1244 newsize *= 2;
1245 if (newsize < newmax)
1246 return; /* overflow detection */
1247
7b2c381c 1248 a = (char *) HvARRAY(hv);
72940dca 1249 if (a) {
3280af22 1250 PL_nomemok = TRUE;
8d6dde3e 1251#if defined(STRANGE_MALLOC) || defined(MYMALLOC)
b79f7545
NC
1252 Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1253 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
8aacddc1 1254 if (!a) {
4a33f861 1255 PL_nomemok = FALSE;
422a93e5
GA
1256 return;
1257 }
b79f7545 1258 if (SvOOK(hv)) {
7a9b70e9 1259 Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
b79f7545 1260 }
72940dca 1261#else
a02a5408 1262 Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
b79f7545 1263 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
8aacddc1 1264 if (!a) {
3280af22 1265 PL_nomemok = FALSE;
422a93e5
GA
1266 return;
1267 }
7b2c381c 1268 Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
b79f7545
NC
1269 if (SvOOK(hv)) {
1270 Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1271 }
fba3b22e 1272 if (oldsize >= 64) {
7b2c381c 1273 offer_nice_chunk(HvARRAY(hv),
b79f7545
NC
1274 PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
1275 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
72940dca 1276 }
1277 else
7b2c381c 1278 Safefree(HvARRAY(hv));
72940dca 1279#endif
3280af22 1280 PL_nomemok = FALSE;
72311751 1281 Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
72940dca 1282 }
1283 else {
a02a5408 1284 Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
72940dca 1285 }
cbec9347 1286 xhv->xhv_max = --newsize; /* HvMAX(hv) = --newsize */
7b2c381c 1287 HvARRAY(hv) = (HE **) a;
cbec9347 1288 if (!xhv->xhv_fill /* !HvFILL(hv) */) /* skip rest if no entries */
72940dca 1289 return;
1290
72311751
GS
1291 aep = (HE**)a;
1292 for (i=0; i<oldsize; i++,aep++) {
1293 if (!*aep) /* non-existent */
72940dca 1294 continue;
72311751 1295 for (oentry = aep, entry = *aep; entry; entry = *oentry) {
6136c704
AL
1296 register I32 j = (HeHASH(entry) & newsize);
1297
1298 if (j != i) {
72940dca 1299 j -= i;
1300 *oentry = HeNEXT(entry);
72311751 1301 if (!(HeNEXT(entry) = aep[j]))
cbec9347 1302 xhv->xhv_fill++; /* HvFILL(hv)++ */
72311751 1303 aep[j] = entry;
72940dca 1304 continue;
1305 }
1306 else
1307 oentry = &HeNEXT(entry);
1308 }
72311751 1309 if (!*aep) /* everything moved */
cbec9347 1310 xhv->xhv_fill--; /* HvFILL(hv)-- */
72940dca 1311 }
1312}
1313
954c1994
GS
1314/*
1315=for apidoc newHV
1316
1317Creates a new HV. The reference count is set to 1.
1318
1319=cut
1320*/
1321
79072805 1322HV *
864dbfa3 1323Perl_newHV(pTHX)
79072805 1324{
cbec9347 1325 register XPVHV* xhv;
b9f83d2f 1326 HV * const hv = (HV*)newSV_type(SVt_PVHV);
cbec9347 1327 xhv = (XPVHV*)SvANY(hv);
ce5d0612 1328 assert(!SvOK(hv));
1c846c1f 1329#ifndef NODEFAULT_SHAREKEYS
fde52b5c 1330 HvSHAREKEYS_on(hv); /* key-sharing on by default */
1c846c1f 1331#endif
4b5190b5 1332
cbec9347
JH
1333 xhv->xhv_max = 7; /* HvMAX(hv) = 7 (start with 8 buckets) */
1334 xhv->xhv_fill = 0; /* HvFILL(hv) = 0 */
79072805
LW
1335 return hv;
1336}
1337
b3ac6de7 1338HV *
864dbfa3 1339Perl_newHVhv(pTHX_ HV *ohv)
b3ac6de7 1340{
9d4ba2ae 1341 HV * const hv = newHV();
4beac62f 1342 STRLEN hv_max, hv_fill;
4beac62f
AMS
1343
1344 if (!ohv || (hv_fill = HvFILL(ohv)) == 0)
1345 return hv;
4beac62f 1346 hv_max = HvMAX(ohv);
b3ac6de7 1347
b56ba0bf
AMS
1348 if (!SvMAGICAL((SV *)ohv)) {
1349 /* It's an ordinary hash, so copy it fast. AMS 20010804 */
eb160463 1350 STRLEN i;
a3b680e6 1351 const bool shared = !!HvSHAREKEYS(ohv);
aec46f14 1352 HE **ents, ** const oents = (HE **)HvARRAY(ohv);
ff875642 1353 char *a;
a02a5408 1354 Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
ff875642 1355 ents = (HE**)a;
b56ba0bf
AMS
1356
1357 /* In each bucket... */
1358 for (i = 0; i <= hv_max; i++) {
6136c704 1359 HE *prev = NULL;
aec46f14 1360 HE *oent = oents[i];
b56ba0bf
AMS
1361
1362 if (!oent) {
1363 ents[i] = NULL;
1364 continue;
1365 }
1366
1367 /* Copy the linked list of entries. */
aec46f14 1368 for (; oent; oent = HeNEXT(oent)) {
a3b680e6
AL
1369 const U32 hash = HeHASH(oent);
1370 const char * const key = HeKEY(oent);
1371 const STRLEN len = HeKLEN(oent);
1372 const int flags = HeKFLAGS(oent);
6136c704 1373 HE * const ent = new_HE();
b56ba0bf 1374
45dea987 1375 HeVAL(ent) = newSVsv(HeVAL(oent));
19692e8d 1376 HeKEY_hek(ent)
6e838c70 1377 = shared ? share_hek_flags(key, len, hash, flags)
19692e8d 1378 : save_hek_flags(key, len, hash, flags);
b56ba0bf
AMS
1379 if (prev)
1380 HeNEXT(prev) = ent;
1381 else
1382 ents[i] = ent;
1383 prev = ent;
1384 HeNEXT(ent) = NULL;
1385 }
1386 }
1387
1388 HvMAX(hv) = hv_max;
1389 HvFILL(hv) = hv_fill;
8aacddc1 1390 HvTOTALKEYS(hv) = HvTOTALKEYS(ohv);
b56ba0bf 1391 HvARRAY(hv) = ents;
aec46f14 1392 } /* not magical */
b56ba0bf
AMS
1393 else {
1394 /* Iterate over ohv, copying keys and values one at a time. */
b3ac6de7 1395 HE *entry;
bfcb3514
NC
1396 const I32 riter = HvRITER_get(ohv);
1397 HE * const eiter = HvEITER_get(ohv);
b56ba0bf
AMS
1398
1399 /* Can we use fewer buckets? (hv_max is always 2^n-1) */
1400 while (hv_max && hv_max + 1 >= hv_fill * 2)
1401 hv_max = hv_max / 2;
1402 HvMAX(hv) = hv_max;
1403
4a76a316 1404 hv_iterinit(ohv);
e16e2ff8 1405 while ((entry = hv_iternext_flags(ohv, 0))) {
04fe65b0
RGS
1406 (void)hv_store_flags(hv, HeKEY(entry), HeKLEN(entry),
1407 newSVsv(HeVAL(entry)), HeHASH(entry),
1408 HeKFLAGS(entry));
b3ac6de7 1409 }
bfcb3514
NC
1410 HvRITER_set(ohv, riter);
1411 HvEITER_set(ohv, eiter);
b3ac6de7 1412 }
1c846c1f 1413
b3ac6de7
IZ
1414 return hv;
1415}
1416
5b9c0671
NC
1417/* A rather specialised version of newHVhv for copying %^H, ensuring all the
1418 magic stays on it. */
1419HV *
1420Perl_hv_copy_hints_hv(pTHX_ HV *const ohv)
1421{
1422 HV * const hv = newHV();
1423 STRLEN hv_fill;
1424
1425 if (ohv && (hv_fill = HvFILL(ohv))) {
1426 STRLEN hv_max = HvMAX(ohv);
1427 HE *entry;
1428 const I32 riter = HvRITER_get(ohv);
1429 HE * const eiter = HvEITER_get(ohv);
1430
1431 while (hv_max && hv_max + 1 >= hv_fill * 2)
1432 hv_max = hv_max / 2;
1433 HvMAX(hv) = hv_max;
1434
1435 hv_iterinit(ohv);
1436 while ((entry = hv_iternext_flags(ohv, 0))) {
1437 SV *const sv = newSVsv(HeVAL(entry));
1438 sv_magic(sv, NULL, PERL_MAGIC_hintselem,
1439 (char *)newSVhek (HeKEY_hek(entry)), HEf_SVKEY);
04fe65b0
RGS
1440 (void)hv_store_flags(hv, HeKEY(entry), HeKLEN(entry),
1441 sv, HeHASH(entry), HeKFLAGS(entry));
5b9c0671
NC
1442 }
1443 HvRITER_set(ohv, riter);
1444 HvEITER_set(ohv, eiter);
1445 }
1446 hv_magic(hv, NULL, PERL_MAGIC_hints);
1447 return hv;
1448}
1449
79072805 1450void
864dbfa3 1451Perl_hv_free_ent(pTHX_ HV *hv, register HE *entry)
79072805 1452{
97aff369 1453 dVAR;
16bdeea2
GS
1454 SV *val;
1455
68dc0745 1456 if (!entry)
79072805 1457 return;
16bdeea2 1458 val = HeVAL(entry);
a5a709ec 1459 if (val && isGV(val) && isGV_with_GP(val) && GvCVu(val) && HvNAME_get(hv))
0fa56319 1460 mro_method_changed_in(hv); /* deletion of method from stash */
16bdeea2 1461 SvREFCNT_dec(val);
68dc0745 1462 if (HeKLEN(entry) == HEf_SVKEY) {
1463 SvREFCNT_dec(HeKEY_sv(entry));
8aacddc1 1464 Safefree(HeKEY_hek(entry));
44a8e56a 1465 }
1466 else if (HvSHAREKEYS(hv))
68dc0745 1467 unshare_hek(HeKEY_hek(entry));
fde52b5c 1468 else
68dc0745 1469 Safefree(HeKEY_hek(entry));
d33b2eba 1470 del_HE(entry);
79072805
LW
1471}
1472
1473void
864dbfa3 1474Perl_hv_delayfree_ent(pTHX_ HV *hv, register HE *entry)
79072805 1475{
97aff369 1476 dVAR;
68dc0745 1477 if (!entry)
79072805 1478 return;
bc4947fc
NC
1479 /* SvREFCNT_inc to counter the SvREFCNT_dec in hv_free_ent */
1480 sv_2mortal(SvREFCNT_inc(HeVAL(entry))); /* free between statements */
68dc0745 1481 if (HeKLEN(entry) == HEf_SVKEY) {
bc4947fc 1482 sv_2mortal(SvREFCNT_inc(HeKEY_sv(entry)));
44a8e56a 1483 }
bc4947fc 1484 hv_free_ent(hv, entry);
79072805
LW
1485}
1486
954c1994
GS
1487/*
1488=for apidoc hv_clear
1489
1490Clears a hash, making it empty.
1491
1492=cut
1493*/
1494
79072805 1495void
864dbfa3 1496Perl_hv_clear(pTHX_ HV *hv)
79072805 1497{
27da23d5 1498 dVAR;
cbec9347 1499 register XPVHV* xhv;
79072805
LW
1500 if (!hv)
1501 return;
49293501 1502
ecae49c0
NC
1503 DEBUG_A(Perl_hv_assert(aTHX_ hv));
1504
34c3c4e3
DM
1505 xhv = (XPVHV*)SvANY(hv);
1506
7b2c381c 1507 if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
34c3c4e3 1508 /* restricted hash: convert all keys to placeholders */
b464bac0
AL
1509 STRLEN i;
1510 for (i = 0; i <= xhv->xhv_max; i++) {
7b2c381c 1511 HE *entry = (HvARRAY(hv))[i];
3a676441
JH
1512 for (; entry; entry = HeNEXT(entry)) {
1513 /* not already placeholder */
7996736c 1514 if (HeVAL(entry) != &PL_sv_placeholder) {
3a676441 1515 if (HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
6136c704 1516 SV* const keysv = hv_iterkeysv(entry);
3a676441 1517 Perl_croak(aTHX_
95b63a38
JH
1518 "Attempt to delete readonly key '%"SVf"' from a restricted hash",
1519 (void*)keysv);
3a676441
JH
1520 }
1521 SvREFCNT_dec(HeVAL(entry));
7996736c 1522 HeVAL(entry) = &PL_sv_placeholder;
ca732855 1523 HvPLACEHOLDERS(hv)++;
3a676441 1524 }
34c3c4e3
DM
1525 }
1526 }
df8c6964 1527 goto reset;
49293501
MS
1528 }
1529
463ee0b2 1530 hfreeentries(hv);
ca732855 1531 HvPLACEHOLDERS_set(hv, 0);
7b2c381c 1532 if (HvARRAY(hv))
41f62432 1533 Zero(HvARRAY(hv), xhv->xhv_max+1 /* HvMAX(hv)+1 */, HE*);
a0d0e21e
LW
1534
1535 if (SvRMAGICAL(hv))
1c846c1f 1536 mg_clear((SV*)hv);
574c8022 1537
19692e8d 1538 HvHASKFLAGS_off(hv);
bb443f97 1539 HvREHASH_off(hv);
df8c6964 1540 reset:
b79f7545 1541 if (SvOOK(hv)) {
dd69841b
BB
1542 if(HvNAME_get(hv))
1543 mro_isa_changed_in(hv);
bfcb3514
NC
1544 HvEITER_set(hv, NULL);
1545 }
79072805
LW
1546}
1547
3540d4ce
AB
1548/*
1549=for apidoc hv_clear_placeholders
1550
1551Clears any placeholders from a hash. If a restricted hash has any of its keys
1552marked as readonly and the key is subsequently deleted, the key is not actually
1553deleted but is marked by assigning it a value of &PL_sv_placeholder. This tags
1554it so it will be ignored by future operations such as iterating over the hash,
4cdaeff7 1555but will still allow the hash to have a value reassigned to the key at some
3540d4ce
AB
1556future point. This function clears any such placeholder keys from the hash.
1557See Hash::Util::lock_keys() for an example of its use.
1558
1559=cut
1560*/
1561
1562void
1563Perl_hv_clear_placeholders(pTHX_ HV *hv)
1564{
27da23d5 1565 dVAR;
b3ca2e83
NC
1566 const U32 items = (U32)HvPLACEHOLDERS_get(hv);
1567
1568 if (items)
1569 clear_placeholders(hv, items);
1570}
1571
1572static void
1573S_clear_placeholders(pTHX_ HV *hv, U32 items)
1574{
1575 dVAR;
b464bac0 1576 I32 i;
d3677389
NC
1577
1578 if (items == 0)
1579 return;
1580
b464bac0 1581 i = HvMAX(hv);
d3677389
NC
1582 do {
1583 /* Loop down the linked list heads */
6136c704 1584 bool first = TRUE;
d3677389 1585 HE **oentry = &(HvARRAY(hv))[i];
cf6db12b 1586 HE *entry;
d3677389 1587
cf6db12b 1588 while ((entry = *oentry)) {
d3677389
NC
1589 if (HeVAL(entry) == &PL_sv_placeholder) {
1590 *oentry = HeNEXT(entry);
1591 if (first && !*oentry)
1592 HvFILL(hv)--; /* This linked list is now empty. */
2e58978b 1593 if (entry == HvEITER_get(hv))
d3677389
NC
1594 HvLAZYDEL_on(hv);
1595 else
1596 hv_free_ent(hv, entry);
1597
1598 if (--items == 0) {
1599 /* Finished. */
5d88ecd7 1600 HvTOTALKEYS(hv) -= (IV)HvPLACEHOLDERS_get(hv);
d3677389
NC
1601 if (HvKEYS(hv) == 0)
1602 HvHASKFLAGS_off(hv);
5d88ecd7 1603 HvPLACEHOLDERS_set(hv, 0);
d3677389
NC
1604 return;
1605 }
213ce8b3
NC
1606 } else {
1607 oentry = &HeNEXT(entry);
6136c704 1608 first = FALSE;
d3677389
NC
1609 }
1610 }
1611 } while (--i >= 0);
1612 /* You can't get here, hence assertion should always fail. */
1613 assert (items == 0);
1614 assert (0);
3540d4ce
AB
1615}
1616
76e3520e 1617STATIC void
cea2e8a9 1618S_hfreeentries(pTHX_ HV *hv)
79072805 1619{
23976bdd 1620 /* This is the array that we're going to restore */
fd7de8a8 1621 HE **const orig_array = HvARRAY(hv);
23976bdd
NC
1622 HEK *name;
1623 int attempts = 100;
3abe233e 1624
fd7de8a8 1625 if (!orig_array)
79072805 1626 return;
a0d0e21e 1627
23976bdd
NC
1628 if (SvOOK(hv)) {
1629 /* If the hash is actually a symbol table with a name, look after the
1630 name. */
1631 struct xpvhv_aux *iter = HvAUX(hv);
1632
1633 name = iter->xhv_name;
1634 iter->xhv_name = NULL;
1635 } else {
1636 name = NULL;
1637 }
1638
23976bdd
NC
1639 /* orig_array remains unchanged throughout the loop. If after freeing all
1640 the entries it turns out that one of the little blighters has triggered
1641 an action that has caused HvARRAY to be re-allocated, then we set
1642 array to the new HvARRAY, and try again. */
1643
1644 while (1) {
1645 /* This is the one we're going to try to empty. First time round
1646 it's the original array. (Hopefully there will only be 1 time
1647 round) */
6136c704 1648 HE ** const array = HvARRAY(hv);
7440661e 1649 I32 i = HvMAX(hv);
23976bdd
NC
1650
1651 /* Because we have taken xhv_name out, the only allocated pointer
1652 in the aux structure that might exist is the backreference array.
1653 */
1654
1655 if (SvOOK(hv)) {
7440661e 1656 HE *entry;
e1a479c5 1657 struct mro_meta *meta;
23976bdd
NC
1658 struct xpvhv_aux *iter = HvAUX(hv);
1659 /* If there are weak references to this HV, we need to avoid
1660 freeing them up here. In particular we need to keep the AV
1661 visible as what we're deleting might well have weak references
1662 back to this HV, so the for loop below may well trigger
1663 the removal of backreferences from this array. */
1664
1665 if (iter->xhv_backreferences) {
1666 /* So donate them to regular backref magic to keep them safe.
1667 The sv_magic will increase the reference count of the AV,
1668 so we need to drop it first. */
5b285ea4 1669 SvREFCNT_dec(iter->xhv_backreferences);
23976bdd
NC
1670 if (AvFILLp(iter->xhv_backreferences) == -1) {
1671 /* Turns out that the array is empty. Just free it. */
1672 SvREFCNT_dec(iter->xhv_backreferences);
1b8791d1 1673
23976bdd
NC
1674 } else {
1675 sv_magic((SV*)hv, (SV*)iter->xhv_backreferences,
1676 PERL_MAGIC_backref, NULL, 0);
1677 }
1678 iter->xhv_backreferences = NULL;
5b285ea4 1679 }
86f55936 1680
23976bdd
NC
1681 entry = iter->xhv_eiter; /* HvEITER(hv) */
1682 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1683 HvLAZYDEL_off(hv);
1684 hv_free_ent(hv, entry);
1685 }
1686 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
4608196e 1687 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
b79f7545 1688
e1a479c5
BB
1689 if((meta = iter->xhv_mro_meta)) {
1690 if(meta->mro_linear_dfs) SvREFCNT_dec(meta->mro_linear_dfs);
1691 if(meta->mro_linear_c3) SvREFCNT_dec(meta->mro_linear_c3);
e1a479c5
BB
1692 if(meta->mro_nextmethod) SvREFCNT_dec(meta->mro_nextmethod);
1693 Safefree(meta);
1694 iter->xhv_mro_meta = NULL;
1695 }
1696
23976bdd 1697 /* There are now no allocated pointers in the aux structure. */
2f86008e 1698
23976bdd
NC
1699 SvFLAGS(hv) &= ~SVf_OOK; /* Goodbye, aux structure. */
1700 /* What aux structure? */
a0d0e21e 1701 }
bfcb3514 1702
23976bdd
NC
1703 /* make everyone else think the array is empty, so that the destructors
1704 * called for freed entries can't recusively mess with us */
1705 HvARRAY(hv) = NULL;
1706 HvFILL(hv) = 0;
1707 ((XPVHV*) SvANY(hv))->xhv_keys = 0;
1708
7440661e
NC
1709
1710 do {
1711 /* Loop down the linked list heads */
1712 HE *entry = array[i];
1713
1714 while (entry) {
23976bdd
NC
1715 register HE * const oentry = entry;
1716 entry = HeNEXT(entry);
1717 hv_free_ent(hv, oentry);
1718 }
7440661e 1719 } while (--i >= 0);
b79f7545 1720
23976bdd
NC
1721 /* As there are no allocated pointers in the aux structure, it's now
1722 safe to free the array we just cleaned up, if it's not the one we're
1723 going to put back. */
1724 if (array != orig_array) {
1725 Safefree(array);
1726 }
b79f7545 1727
23976bdd
NC
1728 if (!HvARRAY(hv)) {
1729 /* Good. No-one added anything this time round. */
1730 break;
bfcb3514 1731 }
b79f7545 1732
23976bdd
NC
1733 if (SvOOK(hv)) {
1734 /* Someone attempted to iterate or set the hash name while we had
1735 the array set to 0. We'll catch backferences on the next time
1736 round the while loop. */
1737 assert(HvARRAY(hv));
1b8791d1 1738
23976bdd
NC
1739 if (HvAUX(hv)->xhv_name) {
1740 unshare_hek_or_pvn(HvAUX(hv)->xhv_name, 0, 0, 0);
1741 }
1742 }
1743
1744 if (--attempts == 0) {
1745 Perl_die(aTHX_ "panic: hfreeentries failed to free hash - something is repeatedly re-creating entries");
1746 }
6136c704 1747 }
23976bdd
NC
1748
1749 HvARRAY(hv) = orig_array;
1750
1751 /* If the hash was actually a symbol table, put the name back. */
1752 if (name) {
1753 /* We have restored the original array. If name is non-NULL, then
1754 the original array had an aux structure at the end. So this is
1755 valid: */
1756 SvFLAGS(hv) |= SVf_OOK;
1757 HvAUX(hv)->xhv_name = name;
1b8791d1 1758 }
79072805
LW
1759}
1760
954c1994
GS
1761/*
1762=for apidoc hv_undef
1763
1764Undefines the hash.
1765
1766=cut
1767*/
1768
79072805 1769void
864dbfa3 1770Perl_hv_undef(pTHX_ HV *hv)
79072805 1771{
97aff369 1772 dVAR;
cbec9347 1773 register XPVHV* xhv;
bfcb3514 1774 const char *name;
86f55936 1775
79072805
LW
1776 if (!hv)
1777 return;
ecae49c0 1778 DEBUG_A(Perl_hv_assert(aTHX_ hv));
cbec9347 1779 xhv = (XPVHV*)SvANY(hv);
dd69841b 1780
0fa56319 1781 if ((name = HvNAME_get(hv)) && !PL_dirty)
dd69841b
BB
1782 mro_isa_changed_in(hv);
1783
463ee0b2 1784 hfreeentries(hv);
dd69841b 1785 if (name) {
04fe65b0
RGS
1786 if (PL_stashcache)
1787 (void)hv_delete(PL_stashcache, name, HvNAMELEN_get(hv), G_DISCARD);
bd61b366 1788 hv_name_set(hv, NULL, 0, 0);
85e6fe83 1789 }
b79f7545
NC
1790 SvFLAGS(hv) &= ~SVf_OOK;
1791 Safefree(HvARRAY(hv));
cbec9347 1792 xhv->xhv_max = 7; /* HvMAX(hv) = 7 (it's a normal hash) */
7b2c381c 1793 HvARRAY(hv) = 0;
ca732855 1794 HvPLACEHOLDERS_set(hv, 0);
a0d0e21e
LW
1795
1796 if (SvRMAGICAL(hv))
1c846c1f 1797 mg_clear((SV*)hv);
79072805
LW
1798}
1799
b464bac0 1800static struct xpvhv_aux*
5f66b61c 1801S_hv_auxinit(HV *hv) {
bfcb3514 1802 struct xpvhv_aux *iter;
b79f7545 1803 char *array;
bfcb3514 1804
b79f7545 1805 if (!HvARRAY(hv)) {
a02a5408 1806 Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
b79f7545
NC
1807 + sizeof(struct xpvhv_aux), char);
1808 } else {
1809 array = (char *) HvARRAY(hv);
1810 Renew(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1811 + sizeof(struct xpvhv_aux), char);
1812 }
1813 HvARRAY(hv) = (HE**) array;
1814 /* SvOOK_on(hv) attacks the IV flags. */
1815 SvFLAGS(hv) |= SVf_OOK;
1816 iter = HvAUX(hv);
bfcb3514
NC
1817
1818 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
4608196e 1819 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
bfcb3514 1820 iter->xhv_name = 0;
86f55936 1821 iter->xhv_backreferences = 0;
e1a479c5 1822 iter->xhv_mro_meta = NULL;
bfcb3514
NC
1823 return iter;
1824}
1825
954c1994
GS
1826/*
1827=for apidoc hv_iterinit
1828
1829Prepares a starting point to traverse a hash table. Returns the number of
1830keys in the hash (i.e. the same as C<HvKEYS(tb)>). The return value is
1c846c1f 1831currently only meaningful for hashes without tie magic.
954c1994
GS
1832
1833NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
1834hash buckets that happen to be in use. If you still need that esoteric
1835value, you can get it through the macro C<HvFILL(tb)>.
1836
e16e2ff8 1837
954c1994
GS
1838=cut
1839*/
1840
79072805 1841I32
864dbfa3 1842Perl_hv_iterinit(pTHX_ HV *hv)
79072805 1843{
aa689395 1844 if (!hv)
cea2e8a9 1845 Perl_croak(aTHX_ "Bad hash");
bfcb3514 1846
b79f7545 1847 if (SvOOK(hv)) {
6136c704 1848 struct xpvhv_aux * const iter = HvAUX(hv);
0bd48802 1849 HE * const entry = iter->xhv_eiter; /* HvEITER(hv) */
bfcb3514
NC
1850 if (entry && HvLAZYDEL(hv)) { /* was deleted earlier? */
1851 HvLAZYDEL_off(hv);
1852 hv_free_ent(hv, entry);
1853 }
1854 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
4608196e 1855 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
bfcb3514 1856 } else {
6136c704 1857 hv_auxinit(hv);
72940dca 1858 }
44a2ac75 1859
cbec9347 1860 /* used to be xhv->xhv_fill before 5.004_65 */
5d88ecd7 1861 return HvTOTALKEYS(hv);
79072805 1862}
bfcb3514
NC
1863
1864I32 *
1865Perl_hv_riter_p(pTHX_ HV *hv) {
1866 struct xpvhv_aux *iter;
1867
1868 if (!hv)
1869 Perl_croak(aTHX_ "Bad hash");
1870
6136c704 1871 iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
bfcb3514
NC
1872 return &(iter->xhv_riter);
1873}
1874
1875HE **
1876Perl_hv_eiter_p(pTHX_ HV *hv) {
1877 struct xpvhv_aux *iter;
1878
1879 if (!hv)
1880 Perl_croak(aTHX_ "Bad hash");
1881
6136c704 1882 iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
bfcb3514
NC
1883 return &(iter->xhv_eiter);
1884}
1885
1886void
1887Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
1888 struct xpvhv_aux *iter;
1889
1890 if (!hv)
1891 Perl_croak(aTHX_ "Bad hash");
1892
b79f7545
NC
1893 if (SvOOK(hv)) {
1894 iter = HvAUX(hv);
1895 } else {
bfcb3514
NC
1896 if (riter == -1)
1897 return;
1898
6136c704 1899 iter = hv_auxinit(hv);
bfcb3514
NC
1900 }
1901 iter->xhv_riter = riter;
1902}
1903
1904void
1905Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
1906 struct xpvhv_aux *iter;
1907
1908 if (!hv)
1909 Perl_croak(aTHX_ "Bad hash");
1910
b79f7545
NC
1911 if (SvOOK(hv)) {
1912 iter = HvAUX(hv);
1913 } else {
bfcb3514
NC
1914 /* 0 is the default so don't go malloc()ing a new structure just to
1915 hold 0. */
1916 if (!eiter)
1917 return;
1918
6136c704 1919 iter = hv_auxinit(hv);
bfcb3514
NC
1920 }
1921 iter->xhv_eiter = eiter;
1922}
1923
bfcb3514 1924void
4164be69 1925Perl_hv_name_set(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
bfcb3514 1926{
97aff369 1927 dVAR;
b79f7545 1928 struct xpvhv_aux *iter;
7423f6db 1929 U32 hash;
46c461b5
AL
1930
1931 PERL_UNUSED_ARG(flags);
bfcb3514 1932
4164be69
NC
1933 if (len > I32_MAX)
1934 Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
1935
b79f7545
NC
1936 if (SvOOK(hv)) {
1937 iter = HvAUX(hv);
7423f6db
NC
1938 if (iter->xhv_name) {
1939 unshare_hek_or_pvn(iter->xhv_name, 0, 0, 0);
1940 }
16580ff5 1941 } else {
bfcb3514
NC
1942 if (name == 0)
1943 return;
1944
6136c704 1945 iter = hv_auxinit(hv);
bfcb3514 1946 }
7423f6db 1947 PERL_HASH(hash, name, len);
adf4e37a 1948 iter->xhv_name = name ? share_hek(name, len, hash) : NULL;
bfcb3514
NC
1949}
1950
86f55936
NC
1951AV **
1952Perl_hv_backreferences_p(pTHX_ HV *hv) {
6136c704 1953 struct xpvhv_aux * const iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
96a5add6 1954 PERL_UNUSED_CONTEXT;
86f55936
NC
1955 return &(iter->xhv_backreferences);
1956}
1957
1958void
1959Perl_hv_kill_backrefs(pTHX_ HV *hv) {
1960 AV *av;
1961
1962 if (!SvOOK(hv))
1963 return;
1964
1965 av = HvAUX(hv)->xhv_backreferences;
1966
1967 if (av) {
1968 HvAUX(hv)->xhv_backreferences = 0;
1969 Perl_sv_kill_backrefs(aTHX_ (SV*) hv, av);
281b372a 1970 SvREFCNT_dec(av);
86f55936
NC
1971 }
1972}
1973
954c1994 1974/*
7a7b9979
NC
1975hv_iternext is implemented as a macro in hv.h
1976
954c1994
GS
1977=for apidoc hv_iternext
1978
1979Returns entries from a hash iterator. See C<hv_iterinit>.
1980
fe7bca90
NC
1981You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
1982iterator currently points to, without losing your place or invalidating your
1983iterator. Note that in this case the current entry is deleted from the hash
1984with your iterator holding the last reference to it. Your iterator is flagged
1985to free the entry on the next call to C<hv_iternext>, so you must not discard
1986your iterator immediately else the entry will leak - call C<hv_iternext> to
1987trigger the resource deallocation.
1988
fe7bca90
NC
1989=for apidoc hv_iternext_flags
1990
1991Returns entries from a hash iterator. See C<hv_iterinit> and C<hv_iternext>.
1992The C<flags> value will normally be zero; if HV_ITERNEXT_WANTPLACEHOLDERS is
1993set the placeholders keys (for restricted hashes) will be returned in addition
1994to normal keys. By default placeholders are automatically skipped over.
7996736c
MHM
1995Currently a placeholder is implemented with a value that is
1996C<&Perl_sv_placeholder>. Note that the implementation of placeholders and
fe7bca90
NC
1997restricted hashes may change, and the implementation currently is
1998insufficiently abstracted for any change to be tidy.
e16e2ff8 1999
fe7bca90 2000=cut
e16e2ff8
NC
2001*/
2002
2003HE *
2004Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
2005{
27da23d5 2006 dVAR;
cbec9347 2007 register XPVHV* xhv;
79072805 2008 register HE *entry;
a0d0e21e 2009 HE *oldentry;
463ee0b2 2010 MAGIC* mg;
bfcb3514 2011 struct xpvhv_aux *iter;
79072805
LW
2012
2013 if (!hv)
cea2e8a9 2014 Perl_croak(aTHX_ "Bad hash");
81714fb9 2015
cbec9347 2016 xhv = (XPVHV*)SvANY(hv);
bfcb3514 2017
b79f7545 2018 if (!SvOOK(hv)) {
bfcb3514
NC
2019 /* Too many things (well, pp_each at least) merrily assume that you can
2020 call iv_iternext without calling hv_iterinit, so we'll have to deal
2021 with it. */
2022 hv_iterinit(hv);
bfcb3514 2023 }
b79f7545 2024 iter = HvAUX(hv);
bfcb3514
NC
2025
2026 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
e62cc96a 2027 if (SvMAGICAL(hv) && SvRMAGICAL(hv)) {
44a2ac75 2028 if ( ( mg = mg_find((SV*)hv, PERL_MAGIC_tied) ) ) {
e62cc96a
YO
2029 SV * const key = sv_newmortal();
2030 if (entry) {
2031 sv_setsv(key, HeSVKEY_force(entry));
2032 SvREFCNT_dec(HeSVKEY(entry)); /* get rid of previous key */
2033 }
2034 else {
2035 char *k;
2036 HEK *hek;
2037
2038 /* one HE per MAGICAL hash */
2039 iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
2040 Zero(entry, 1, HE);
2041 Newxz(k, HEK_BASESIZE + sizeof(SV*), char);
2042 hek = (HEK*)k;
2043 HeKEY_hek(entry) = hek;
2044 HeKLEN(entry) = HEf_SVKEY;
2045 }
2046 magic_nextpack((SV*) hv,mg,key);
2047 if (SvOK(key)) {
2048 /* force key to stay around until next time */
2049 HeSVKEY_set(entry, SvREFCNT_inc_simple_NN(key));
2050 return entry; /* beware, hent_val is not set */
2051 }
2052 if (HeVAL(entry))
2053 SvREFCNT_dec(HeVAL(entry));
2054 Safefree(HeKEY_hek(entry));
2055 del_HE(entry);
2056 iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
2057 return NULL;
81714fb9 2058 }
79072805 2059 }
7ee146b1 2060#if defined(DYNAMIC_ENV_FETCH) && !defined(__riscos__) /* set up %ENV for iteration */
03026e68 2061 if (!entry && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
f675dbe5 2062 prime_env_iter();
03026e68
JM
2063#ifdef VMS
2064 /* The prime_env_iter() on VMS just loaded up new hash values
2065 * so the iteration count needs to be reset back to the beginning
2066 */
2067 hv_iterinit(hv);
2068 iter = HvAUX(hv);
2069 oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2070#endif
2071 }
f675dbe5 2072#endif
463ee0b2 2073
b79f7545
NC
2074 /* hv_iterint now ensures this. */
2075 assert (HvARRAY(hv));
2076
015a5f36 2077 /* At start of hash, entry is NULL. */
fde52b5c 2078 if (entry)
8aacddc1 2079 {
fde52b5c 2080 entry = HeNEXT(entry);
e16e2ff8
NC
2081 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2082 /*
2083 * Skip past any placeholders -- don't want to include them in
2084 * any iteration.
2085 */
7996736c 2086 while (entry && HeVAL(entry) == &PL_sv_placeholder) {
e16e2ff8
NC
2087 entry = HeNEXT(entry);
2088 }
8aacddc1
NIS
2089 }
2090 }
fde52b5c 2091 while (!entry) {
015a5f36
NC
2092 /* OK. Come to the end of the current list. Grab the next one. */
2093
bfcb3514
NC
2094 iter->xhv_riter++; /* HvRITER(hv)++ */
2095 if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
015a5f36 2096 /* There is no next one. End of the hash. */
bfcb3514 2097 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
fde52b5c 2098 break;
79072805 2099 }
7b2c381c 2100 entry = (HvARRAY(hv))[iter->xhv_riter];
8aacddc1 2101
e16e2ff8 2102 if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
015a5f36
NC
2103 /* If we have an entry, but it's a placeholder, don't count it.
2104 Try the next. */
7996736c 2105 while (entry && HeVAL(entry) == &PL_sv_placeholder)
015a5f36
NC
2106 entry = HeNEXT(entry);
2107 }
2108 /* Will loop again if this linked list starts NULL
2109 (for HV_ITERNEXT_WANTPLACEHOLDERS)
2110 or if we run through it and find only placeholders. */
fde52b5c 2111 }
79072805 2112
72940dca 2113 if (oldentry && HvLAZYDEL(hv)) { /* was deleted earlier? */
2114 HvLAZYDEL_off(hv);
68dc0745 2115 hv_free_ent(hv, oldentry);
72940dca 2116 }
a0d0e21e 2117
fdcd69b6 2118 /*if (HvREHASH(hv) && entry && !HeKREHASH(entry))
6c9570dc 2119 PerlIO_printf(PerlIO_stderr(), "Awooga %p %p\n", (void*)hv, (void*)entry);*/
fdcd69b6 2120
bfcb3514 2121 iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
79072805
LW
2122 return entry;
2123}
2124
954c1994
GS
2125/*
2126=for apidoc hv_iterkey
2127
2128Returns the key from the current position of the hash iterator. See
2129C<hv_iterinit>.
2130
2131=cut
2132*/
2133
79072805 2134char *
864dbfa3 2135Perl_hv_iterkey(pTHX_ register HE *entry, I32 *retlen)
79072805 2136{
fde52b5c 2137 if (HeKLEN(entry) == HEf_SVKEY) {
fb73857a 2138 STRLEN len;
0bd48802 2139 char * const p = SvPV(HeKEY_sv(entry), len);
fb73857a 2140 *retlen = len;
2141 return p;
fde52b5c 2142 }
2143 else {
2144 *retlen = HeKLEN(entry);
2145 return HeKEY(entry);
2146 }
2147}
2148
2149/* unlike hv_iterval(), this always returns a mortal copy of the key */
954c1994
GS
2150/*
2151=for apidoc hv_iterkeysv
2152
2153Returns the key as an C<SV*> from the current position of the hash
2154iterator. The return value will always be a mortal copy of the key. Also
2155see C<hv_iterinit>.
2156
2157=cut
2158*/
2159
fde52b5c 2160SV *
864dbfa3 2161Perl_hv_iterkeysv(pTHX_ register HE *entry)
fde52b5c 2162{
c1b02ed8 2163 return sv_2mortal(newSVhek(HeKEY_hek(entry)));
79072805
LW
2164}
2165
954c1994
GS
2166/*
2167=for apidoc hv_iterval
2168
2169Returns the value from the current position of the hash iterator. See
2170C<hv_iterkey>.
2171
2172=cut
2173*/
2174
79072805 2175SV *
864dbfa3 2176Perl_hv_iterval(pTHX_ HV *hv, register HE *entry)
79072805 2177{
8990e307 2178 if (SvRMAGICAL(hv)) {
14befaf4 2179 if (mg_find((SV*)hv, PERL_MAGIC_tied)) {
c4420975 2180 SV* const sv = sv_newmortal();
bbce6d69 2181 if (HeKLEN(entry) == HEf_SVKEY)
2182 mg_copy((SV*)hv, sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
a3b680e6
AL
2183 else
2184 mg_copy((SV*)hv, sv, HeKEY(entry), HeKLEN(entry));
463ee0b2
LW
2185 return sv;
2186 }
79072805 2187 }
fde52b5c 2188 return HeVAL(entry);
79072805
LW
2189}
2190
954c1994
GS
2191/*
2192=for apidoc hv_iternextsv
2193
2194Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2195operation.
2196
2197=cut
2198*/
2199
a0d0e21e 2200SV *
864dbfa3 2201Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
a0d0e21e 2202{
0bd48802
AL
2203 HE * const he = hv_iternext_flags(hv, 0);
2204
2205 if (!he)
a0d0e21e
LW
2206 return NULL;
2207 *key = hv_iterkey(he, retlen);
2208 return hv_iterval(hv, he);
2209}
2210
954c1994 2211/*
bc5cdc23
NC
2212
2213Now a macro in hv.h
2214
954c1994
GS
2215=for apidoc hv_magic
2216
2217Adds magic to a hash. See C<sv_magic>.
2218
2219=cut
2220*/
2221
bbce6d69 2222/* possibly free a shared string if no one has access to it
fde52b5c 2223 * len and hash must both be valid for str.
2224 */
bbce6d69 2225void
864dbfa3 2226Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
fde52b5c 2227{
19692e8d
NC
2228 unshare_hek_or_pvn (NULL, str, len, hash);
2229}
2230
2231
2232void
2233Perl_unshare_hek(pTHX_ HEK *hek)
2234{
bf11fd37 2235 assert(hek);
19692e8d
NC
2236 unshare_hek_or_pvn(hek, NULL, 0, 0);
2237}
2238
2239/* possibly free a shared string if no one has access to it
2240 hek if non-NULL takes priority over the other 3, else str, len and hash
2241 are used. If so, len and hash must both be valid for str.
2242 */
df132699 2243STATIC void
97ddebaf 2244S_unshare_hek_or_pvn(pTHX_ const HEK *hek, const char *str, I32 len, U32 hash)
19692e8d 2245{
97aff369 2246 dVAR;
cbec9347 2247 register XPVHV* xhv;
20454177 2248 HE *entry;
fde52b5c 2249 register HE **oentry;
45d1cc86 2250 HE **first;
c3654f1a 2251 bool is_utf8 = FALSE;
19692e8d 2252 int k_flags = 0;
aec46f14 2253 const char * const save = str;
cbbf8932 2254 struct shared_he *he = NULL;
c3654f1a 2255
19692e8d 2256 if (hek) {
cbae3960
NC
2257 /* Find the shared he which is just before us in memory. */
2258 he = (struct shared_he *)(((char *)hek)
2259 - STRUCT_OFFSET(struct shared_he,
2260 shared_he_hek));
2261
2262 /* Assert that the caller passed us a genuine (or at least consistent)
2263 shared hek */
2264 assert (he->shared_he_he.hent_hek == hek);
29404ae0
NC
2265
2266 LOCK_STRTAB_MUTEX;
de616631
NC
2267 if (he->shared_he_he.he_valu.hent_refcount - 1) {
2268 --he->shared_he_he.he_valu.hent_refcount;
29404ae0
NC
2269 UNLOCK_STRTAB_MUTEX;
2270 return;
2271 }
2272 UNLOCK_STRTAB_MUTEX;
2273
19692e8d
NC
2274 hash = HEK_HASH(hek);
2275 } else if (len < 0) {
2276 STRLEN tmplen = -len;
2277 is_utf8 = TRUE;
2278 /* See the note in hv_fetch(). --jhi */
2279 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2280 len = tmplen;
2281 if (is_utf8)
2282 k_flags = HVhek_UTF8;
2283 if (str != save)
2284 k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
c3654f1a 2285 }
1c846c1f 2286
de616631 2287 /* what follows was the moral equivalent of:
6b88bc9c 2288 if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
a0714e2c 2289 if (--*Svp == NULL)
6b88bc9c 2290 hv_delete(PL_strtab, str, len, G_DISCARD, hash);
bbce6d69 2291 } */
cbec9347 2292 xhv = (XPVHV*)SvANY(PL_strtab);
fde52b5c 2293 /* assert(xhv_array != 0) */
5f08fbcd 2294 LOCK_STRTAB_MUTEX;
45d1cc86 2295 first = oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
6c1b96a1
NC
2296 if (he) {
2297 const HE *const he_he = &(he->shared_he_he);
45d1cc86 2298 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
35ab5632
NC
2299 if (entry == he_he)
2300 break;
19692e8d
NC
2301 }
2302 } else {
35a4481c 2303 const int flags_masked = k_flags & HVhek_MASK;
45d1cc86 2304 for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
19692e8d
NC
2305 if (HeHASH(entry) != hash) /* strings can't be equal */
2306 continue;
2307 if (HeKLEN(entry) != len)
2308 continue;
2309 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2310 continue;
2311 if (HeKFLAGS(entry) != flags_masked)
2312 continue;
19692e8d
NC
2313 break;
2314 }
2315 }
2316
35ab5632
NC
2317 if (entry) {
2318 if (--entry->he_valu.hent_refcount == 0) {
19692e8d 2319 *oentry = HeNEXT(entry);
45d1cc86
NC
2320 if (!*first) {
2321 /* There are now no entries in our slot. */
19692e8d 2322 xhv->xhv_fill--; /* HvFILL(hv)-- */
45d1cc86 2323 }
cbae3960 2324 Safefree(entry);
4c7185a0 2325 xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
19692e8d 2326 }
fde52b5c 2327 }
19692e8d 2328
333f433b 2329 UNLOCK_STRTAB_MUTEX;
35ab5632 2330 if (!entry && ckWARN_d(WARN_INTERNAL))
19692e8d 2331 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
472d47bc
SB
2332 "Attempt to free non-existent shared string '%s'%s"
2333 pTHX__FORMAT,
19692e8d 2334 hek ? HEK_KEY(hek) : str,
472d47bc 2335 ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
19692e8d
NC
2336 if (k_flags & HVhek_FREEKEY)
2337 Safefree(str);
fde52b5c 2338}
2339
bbce6d69 2340/* get a (constant) string ptr from the global string table
2341 * string will get added if it is not already there.
fde52b5c 2342 * len and hash must both be valid for str.
2343 */
bbce6d69 2344HEK *
864dbfa3 2345Perl_share_hek(pTHX_ const char *str, I32 len, register U32 hash)
fde52b5c 2346{
da58a35d 2347 bool is_utf8 = FALSE;
19692e8d 2348 int flags = 0;
aec46f14 2349 const char * const save = str;
da58a35d
JH
2350
2351 if (len < 0) {
77caf834 2352 STRLEN tmplen = -len;
da58a35d 2353 is_utf8 = TRUE;
77caf834
JH
2354 /* See the note in hv_fetch(). --jhi */
2355 str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2356 len = tmplen;
19692e8d
NC
2357 /* If we were able to downgrade here, then than means that we were passed
2358 in a key which only had chars 0-255, but was utf8 encoded. */
2359 if (is_utf8)
2360 flags = HVhek_UTF8;
2361 /* If we found we were able to downgrade the string to bytes, then
2362 we should flag that it needs upgrading on keys or each. Also flag
2363 that we need share_hek_flags to free the string. */
2364 if (str != save)
2365 flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2366 }
2367
6e838c70 2368 return share_hek_flags (str, len, hash, flags);
19692e8d
NC
2369}
2370
6e838c70 2371STATIC HEK *
19692e8d
NC
2372S_share_hek_flags(pTHX_ const char *str, I32 len, register U32 hash, int flags)
2373{
97aff369 2374 dVAR;
19692e8d 2375 register HE *entry;
35a4481c 2376 const int flags_masked = flags & HVhek_MASK;
263cb4a6 2377 const U32 hindex = hash & (I32) HvMAX(PL_strtab);
bbce6d69 2378
fde52b5c 2379 /* what follows is the moral equivalent of:
1c846c1f 2380
6b88bc9c 2381 if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
a0714e2c 2382 hv_store(PL_strtab, str, len, NULL, hash);
fdcd69b6
NC
2383
2384 Can't rehash the shared string table, so not sure if it's worth
2385 counting the number of entries in the linked list
bbce6d69 2386 */
1b6737cc 2387 register XPVHV * const xhv = (XPVHV*)SvANY(PL_strtab);
fde52b5c 2388 /* assert(xhv_array != 0) */
5f08fbcd 2389 LOCK_STRTAB_MUTEX;
263cb4a6
NC
2390 entry = (HvARRAY(PL_strtab))[hindex];
2391 for (;entry; entry = HeNEXT(entry)) {
fde52b5c 2392 if (HeHASH(entry) != hash) /* strings can't be equal */
2393 continue;
2394 if (HeKLEN(entry) != len)
2395 continue;
1c846c1f 2396 if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
fde52b5c 2397 continue;
19692e8d 2398 if (HeKFLAGS(entry) != flags_masked)
c3654f1a 2399 continue;
fde52b5c 2400 break;
2401 }
263cb4a6
NC
2402
2403 if (!entry) {
45d1cc86
NC
2404 /* What used to be head of the list.
2405 If this is NULL, then we're the first entry for this slot, which
2406 means we need to increate fill. */
cbae3960
NC
2407 struct shared_he *new_entry;
2408 HEK *hek;
2409 char *k;
263cb4a6
NC
2410 HE **const head = &HvARRAY(PL_strtab)[hindex];
2411 HE *const next = *head;
cbae3960
NC
2412
2413 /* We don't actually store a HE from the arena and a regular HEK.
2414 Instead we allocate one chunk of memory big enough for both,
2415 and put the HEK straight after the HE. This way we can find the
2416 HEK directly from the HE.
2417 */
2418
a02a5408 2419 Newx(k, STRUCT_OFFSET(struct shared_he,
cbae3960
NC
2420 shared_he_hek.hek_key[0]) + len + 2, char);
2421 new_entry = (struct shared_he *)k;
2422 entry = &(new_entry->shared_he_he);
2423 hek = &(new_entry->shared_he_hek);
2424
2425 Copy(str, HEK_KEY(hek), len, char);
2426 HEK_KEY(hek)[len] = 0;
2427 HEK_LEN(hek) = len;
2428 HEK_HASH(hek) = hash;
2429 HEK_FLAGS(hek) = (unsigned char)flags_masked;
2430
2431 /* Still "point" to the HEK, so that other code need not know what
2432 we're up to. */
2433 HeKEY_hek(entry) = hek;
de616631 2434 entry->he_valu.hent_refcount = 0;
263cb4a6
NC
2435 HeNEXT(entry) = next;
2436 *head = entry;
cbae3960 2437
4c7185a0 2438 xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
263cb4a6 2439 if (!next) { /* initial entry? */
cbec9347 2440 xhv->xhv_fill++; /* HvFILL(hv)++ */
4c9cc595 2441 } else if (xhv->xhv_keys > (IV)xhv->xhv_max /* HvKEYS(hv) > HvMAX(hv) */) {
cbec9347 2442 hsplit(PL_strtab);
bbce6d69 2443 }
2444 }
2445
de616631 2446 ++entry->he_valu.hent_refcount;
5f08fbcd 2447 UNLOCK_STRTAB_MUTEX;
19692e8d
NC
2448
2449 if (flags & HVhek_FREEKEY)
f9a63242 2450 Safefree(str);
19692e8d 2451
6e838c70 2452 return HeKEY_hek(entry);
fde52b5c 2453}
ecae49c0 2454
ca732855
NC
2455I32 *
2456Perl_hv_placeholders_p(pTHX_ HV *hv)
2457{
2458 dVAR;
2459 MAGIC *mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
2460
2461 if (!mg) {
2462 mg = sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, 0);
2463
2464 if (!mg) {
2465 Perl_die(aTHX_ "panic: hv_placeholders_p");
2466 }
2467 }
2468 return &(mg->mg_len);
2469}
2470
2471
2472I32
2473Perl_hv_placeholders_get(pTHX_ HV *hv)
2474{
2475 dVAR;
b464bac0 2476 MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
ca732855
NC
2477
2478 return mg ? mg->mg_len : 0;
2479}
2480
2481void
ac1e784a 2482Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
ca732855
NC
2483{
2484 dVAR;
b464bac0 2485 MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
ca732855
NC
2486
2487 if (mg) {
2488 mg->mg_len = ph;
2489 } else if (ph) {
2490 if (!sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, ph))
2491 Perl_die(aTHX_ "panic: hv_placeholders_set");
2492 }
2493 /* else we don't need to add magic to record 0 placeholders. */
2494}
ecae49c0 2495
2a49f0f5 2496STATIC SV *
7b0bddfa
NC
2497S_refcounted_he_value(pTHX_ const struct refcounted_he *he)
2498{
0b2d3faa 2499 dVAR;
7b0bddfa
NC
2500 SV *value;
2501 switch(he->refcounted_he_data[0] & HVrhek_typemask) {
2502 case HVrhek_undef:
2503 value = newSV(0);
2504 break;
2505 case HVrhek_delete:
2506 value = &PL_sv_placeholder;
2507 break;
2508 case HVrhek_IV:
44ebaf21
NC
2509 value = newSViv(he->refcounted_he_val.refcounted_he_u_iv);
2510 break;
2511 case HVrhek_UV:
2512 value = newSVuv(he->refcounted_he_val.refcounted_he_u_uv);
7b0bddfa
NC
2513 break;
2514 case HVrhek_PV:
44ebaf21 2515 case HVrhek_PV_UTF8:
7b0bddfa
NC
2516 /* Create a string SV that directly points to the bytes in our
2517 structure. */
b9f83d2f 2518 value = newSV_type(SVt_PV);
7b0bddfa
NC
2519 SvPV_set(value, (char *) he->refcounted_he_data + 1);
2520 SvCUR_set(value, he->refcounted_he_val.refcounted_he_u_len);
2521 /* This stops anything trying to free it */
2522 SvLEN_set(value, 0);
2523 SvPOK_on(value);
2524 SvREADONLY_on(value);
44ebaf21 2525 if ((he->refcounted_he_data[0] & HVrhek_typemask) == HVrhek_PV_UTF8)
7b0bddfa
NC
2526 SvUTF8_on(value);
2527 break;
2528 default:
2529 Perl_croak(aTHX_ "panic: refcounted_he_value bad flags %x",
2530 he->refcounted_he_data[0]);
2531 }
2532 return value;
2533}
2534
ecae49c0 2535/*
b3ca2e83
NC
2536=for apidoc refcounted_he_chain_2hv
2537
abc25d8c 2538Generates and returns a C<HV *> by walking up the tree starting at the passed
b3ca2e83
NC
2539in C<struct refcounted_he *>.
2540
2541=cut
2542*/
2543HV *
2544Perl_refcounted_he_chain_2hv(pTHX_ const struct refcounted_he *chain)
2545{
7a89be66 2546 dVAR;
b3ca2e83
NC
2547 HV *hv = newHV();
2548 U32 placeholders = 0;
2549 /* We could chase the chain once to get an idea of the number of keys,
2550 and call ksplit. But for now we'll make a potentially inefficient
2551 hash with only 8 entries in its array. */
2552 const U32 max = HvMAX(hv);
2553
2554 if (!HvARRAY(hv)) {
2555 char *array;
2556 Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(max + 1), char);
2557 HvARRAY(hv) = (HE**)array;
2558 }
2559
2560 while (chain) {
cbb1fbea 2561#ifdef USE_ITHREADS
b6bbf3fa 2562 U32 hash = chain->refcounted_he_hash;
cbb1fbea
NC
2563#else
2564 U32 hash = HEK_HASH(chain->refcounted_he_hek);
2565#endif
b3ca2e83
NC
2566 HE **oentry = &((HvARRAY(hv))[hash & max]);
2567 HE *entry = *oentry;
b6bbf3fa 2568 SV *value;
cbb1fbea 2569
b3ca2e83
NC
2570 for (; entry; entry = HeNEXT(entry)) {
2571 if (HeHASH(entry) == hash) {
9f769845
NC
2572 /* We might have a duplicate key here. If so, entry is older
2573 than the key we've already put in the hash, so if they are
2574 the same, skip adding entry. */
2575#ifdef USE_ITHREADS
2576 const STRLEN klen = HeKLEN(entry);
2577 const char *const key = HeKEY(entry);
2578 if (klen == chain->refcounted_he_keylen
2579 && (!!HeKUTF8(entry)
2580 == !!(chain->refcounted_he_data[0] & HVhek_UTF8))
2581 && memEQ(key, REF_HE_KEY(chain), klen))
2582 goto next_please;
2583#else
2584 if (HeKEY_hek(entry) == chain->refcounted_he_hek)
2585 goto next_please;
2586 if (HeKLEN(entry) == HEK_LEN(chain->refcounted_he_hek)
2587 && HeKUTF8(entry) == HEK_UTF8(chain->refcounted_he_hek)
2588 && memEQ(HeKEY(entry), HEK_KEY(chain->refcounted_he_hek),
2589 HeKLEN(entry)))
2590 goto next_please;
2591#endif
b3ca2e83
NC
2592 }
2593 }
2594 assert (!entry);
2595 entry = new_HE();
2596
cbb1fbea
NC
2597#ifdef USE_ITHREADS
2598 HeKEY_hek(entry)
7b0bddfa 2599 = share_hek_flags(REF_HE_KEY(chain),
b6bbf3fa
NC
2600 chain->refcounted_he_keylen,
2601 chain->refcounted_he_hash,
2602 (chain->refcounted_he_data[0]
2603 & (HVhek_UTF8|HVhek_WASUTF8)));
cbb1fbea 2604#else
71ad1b0c 2605 HeKEY_hek(entry) = share_hek_hek(chain->refcounted_he_hek);
cbb1fbea 2606#endif
7b0bddfa
NC
2607 value = refcounted_he_value(chain);
2608 if (value == &PL_sv_placeholder)
b3ca2e83 2609 placeholders++;
b6bbf3fa 2610 HeVAL(entry) = value;
b3ca2e83
NC
2611
2612 /* Link it into the chain. */
2613 HeNEXT(entry) = *oentry;
2614 if (!HeNEXT(entry)) {
2615 /* initial entry. */
2616 HvFILL(hv)++;
2617 }
2618 *oentry = entry;
2619
2620 HvTOTALKEYS(hv)++;
2621
2622 next_please:
71ad1b0c 2623 chain = chain->refcounted_he_next;
b3ca2e83
NC
2624 }
2625
2626 if (placeholders) {
2627 clear_placeholders(hv, placeholders);
2628 HvTOTALKEYS(hv) -= placeholders;
2629 }
2630
2631 /* We could check in the loop to see if we encounter any keys with key
2632 flags, but it's probably not worth it, as this per-hash flag is only
2633 really meant as an optimisation for things like Storable. */
2634 HvHASKFLAGS_on(hv);
def9038f 2635 DEBUG_A(Perl_hv_assert(aTHX_ hv));
b3ca2e83
NC
2636
2637 return hv;
2638}
2639
7b0bddfa
NC
2640SV *
2641Perl_refcounted_he_fetch(pTHX_ const struct refcounted_he *chain, SV *keysv,
2642 const char *key, STRLEN klen, int flags, U32 hash)
2643{
0b2d3faa 2644 dVAR;
7b0bddfa
NC
2645 /* Just to be awkward, if you're using this interface the UTF-8-or-not-ness
2646 of your key has to exactly match that which is stored. */
2647 SV *value = &PL_sv_placeholder;
7b0bddfa 2648
a1472311
DM
2649 if (chain) {
2650 /* No point in doing any of this if there's nothing to find. */
2651 bool is_utf8;
7b0bddfa 2652
a1472311
DM
2653 if (keysv) {
2654 if (flags & HVhek_FREEKEY)
2655 Safefree(key);
2656 key = SvPV_const(keysv, klen);
2657 flags = 0;
2658 is_utf8 = (SvUTF8(keysv) != 0);
2659 } else {
2660 is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
2661 }
2662
2663 if (!hash) {
2664 if (keysv && (SvIsCOW_shared_hash(keysv))) {
2665 hash = SvSHARED_HASH(keysv);
2666 } else {
2667 PERL_HASH(hash, key, klen);
2668 }
2669 }
7b0bddfa 2670
a1472311 2671 for (; chain; chain = chain->refcounted_he_next) {
7b0bddfa 2672#ifdef USE_ITHREADS
a1472311
DM
2673 if (hash != chain->refcounted_he_hash)
2674 continue;
2675 if (klen != chain->refcounted_he_keylen)
2676 continue;
2677 if (memNE(REF_HE_KEY(chain),key,klen))
2678 continue;
2679 if (!!is_utf8 != !!(chain->refcounted_he_data[0] & HVhek_UTF8))
2680 continue;
7b0bddfa 2681#else
a1472311
DM
2682 if (hash != HEK_HASH(chain->refcounted_he_hek))
2683 continue;
2684 if (klen != (STRLEN)HEK_LEN(chain->refcounted_he_hek))
2685 continue;
2686 if (memNE(HEK_KEY(chain->refcounted_he_hek),key,klen))
2687 continue;
2688 if (!!is_utf8 != !!HEK_UTF8(chain->refcounted_he_hek))
2689 continue;
7b0bddfa
NC
2690#endif
2691
a1472311
DM
2692 value = sv_2mortal(refcounted_he_value(chain));
2693 break;
2694 }
7b0bddfa
NC
2695 }
2696
2697 if (flags & HVhek_FREEKEY)
2698 Safefree(key);
2699
2700 return value;
2701}
2702
b3ca2e83
NC
2703/*
2704=for apidoc refcounted_he_new
2705
ec2a1de7
NC
2706Creates a new C<struct refcounted_he>. As S<key> is copied, and value is
2707stored in a compact form, all references remain the property of the caller.
2708The C<struct refcounted_he> is returned with a reference count of 1.
b3ca2e83
NC
2709
2710=cut
2711*/
2712
2713struct refcounted_he *
2714Perl_refcounted_he_new(pTHX_ struct refcounted_he *const parent,
2715 SV *const key, SV *const value) {
7a89be66 2716 dVAR;
b3ca2e83 2717 struct refcounted_he *he;
b6bbf3fa
NC
2718 STRLEN key_len;
2719 const char *key_p = SvPV_const(key, key_len);
2720 STRLEN value_len = 0;
95b63a38 2721 const char *value_p = NULL;
b6bbf3fa
NC
2722 char value_type;
2723 char flags;
2724 STRLEN key_offset;
b3ca2e83 2725 U32 hash;
d8c5b3c5 2726 bool is_utf8 = SvUTF8(key) ? TRUE : FALSE;
b6bbf3fa
NC
2727
2728 if (SvPOK(value)) {
2729 value_type = HVrhek_PV;
2730 } else if (SvIOK(value)) {
2731 value_type = HVrhek_IV;
2732 } else if (value == &PL_sv_placeholder) {
2733 value_type = HVrhek_delete;
2734 } else if (!SvOK(value)) {
2735 value_type = HVrhek_undef;
2736 } else {
2737 value_type = HVrhek_PV;
2738 }
b3ca2e83 2739
b6bbf3fa
NC
2740 if (value_type == HVrhek_PV) {
2741 value_p = SvPV_const(value, value_len);
2742 key_offset = value_len + 2;
2743 } else {
2744 value_len = 0;
2745 key_offset = 1;
2746 }
b6bbf3fa 2747
b6bbf3fa 2748#ifdef USE_ITHREADS
10edeb5d
JH
2749 he = (struct refcounted_he*)
2750 PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
2751 + key_len
2752 + key_offset);
6cef672b 2753#else
10edeb5d
JH
2754 he = (struct refcounted_he*)
2755 PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
2756 + key_offset);
6cef672b 2757#endif
b3ca2e83 2758
b3ca2e83 2759
71ad1b0c 2760 he->refcounted_he_next = parent;
b6bbf3fa
NC
2761
2762 if (value_type == HVrhek_PV) {
2763 Copy(value_p, he->refcounted_he_data + 1, value_len + 1, char);
2764 he->refcounted_he_val.refcounted_he_u_len = value_len;
44ebaf21
NC
2765 /* Do it this way so that the SvUTF8() test is after the SvPV, in case
2766 the value is overloaded, and doesn't yet have the UTF-8flag set. */
2767 if (SvUTF8(value))
2768 value_type = HVrhek_PV_UTF8;
b6bbf3fa
NC
2769 } else if (value_type == HVrhek_IV) {
2770 if (SvUOK(value)) {
2771 he->refcounted_he_val.refcounted_he_u_uv = SvUVX(value);
44ebaf21 2772 value_type = HVrhek_UV;
b6bbf3fa
NC
2773 } else {
2774 he->refcounted_he_val.refcounted_he_u_iv = SvIVX(value);
2775 }
2776 }
44ebaf21 2777 flags = value_type;
b6bbf3fa
NC
2778
2779 if (is_utf8) {
2780 /* Hash keys are always stored normalised to (yes) ISO-8859-1.
2781 As we're going to be building hash keys from this value in future,
2782 normalise it now. */
2783 key_p = (char*)bytes_from_utf8((const U8*)key_p, &key_len, &is_utf8);
2784 flags |= is_utf8 ? HVhek_UTF8 : HVhek_WASUTF8;
2785 }
2786 PERL_HASH(hash, key_p, key_len);
2787
cbb1fbea 2788#ifdef USE_ITHREADS
b6bbf3fa
NC
2789 he->refcounted_he_hash = hash;
2790 he->refcounted_he_keylen = key_len;
2791 Copy(key_p, he->refcounted_he_data + key_offset, key_len, char);
cbb1fbea 2792#else
b6bbf3fa 2793 he->refcounted_he_hek = share_hek_flags(key_p, key_len, hash, flags);
cbb1fbea 2794#endif
b6bbf3fa
NC
2795
2796 if (flags & HVhek_WASUTF8) {
2797 /* If it was downgraded from UTF-8, then the pointer returned from
2798 bytes_from_utf8 is an allocated pointer that we must free. */
2799 Safefree(key_p);
2800 }
2801
2802 he->refcounted_he_data[0] = flags;
b3ca2e83
NC
2803 he->refcounted_he_refcnt = 1;
2804
2805 return he;
2806}
2807
2808/*
2809=for apidoc refcounted_he_free
2810
2811Decrements the reference count of the passed in C<struct refcounted_he *>
2812by one. If the reference count reaches zero the structure's memory is freed,
2813and C<refcounted_he_free> iterates onto the parent node.
2814
2815=cut
2816*/
2817
2818void
2819Perl_refcounted_he_free(pTHX_ struct refcounted_he *he) {
53d44271 2820 dVAR;
57ca3b03
AL
2821 PERL_UNUSED_CONTEXT;
2822
b3ca2e83
NC
2823 while (he) {
2824 struct refcounted_he *copy;
cbb1fbea 2825 U32 new_count;
b3ca2e83 2826
cbb1fbea
NC
2827 HINTS_REFCNT_LOCK;
2828 new_count = --he->refcounted_he_refcnt;
2829 HINTS_REFCNT_UNLOCK;
2830
2831 if (new_count) {
b3ca2e83 2832 return;
cbb1fbea 2833 }
b3ca2e83 2834
b6bbf3fa 2835#ifndef USE_ITHREADS
71ad1b0c 2836 unshare_hek_or_pvn (he->refcounted_he_hek, 0, 0, 0);
cbb1fbea 2837#endif
b3ca2e83 2838 copy = he;
71ad1b0c 2839 he = he->refcounted_he_next;
b6bbf3fa 2840 PerlMemShared_free(copy);
b3ca2e83
NC
2841 }
2842}
2843
b3ca2e83 2844/*
ecae49c0
NC
2845=for apidoc hv_assert
2846
2847Check that a hash is in an internally consistent state.
2848
2849=cut
2850*/
2851
943795c2
NC
2852#ifdef DEBUGGING
2853
ecae49c0
NC
2854void
2855Perl_hv_assert(pTHX_ HV *hv)
2856{
57ca3b03
AL
2857 dVAR;
2858 HE* entry;
2859 int withflags = 0;
2860 int placeholders = 0;
2861 int real = 0;
2862 int bad = 0;
2863 const I32 riter = HvRITER_get(hv);
2864 HE *eiter = HvEITER_get(hv);
2865
2866 (void)hv_iterinit(hv);
2867
2868 while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
2869 /* sanity check the values */
2870 if (HeVAL(entry) == &PL_sv_placeholder)
2871 placeholders++;
2872 else
2873 real++;
2874 /* sanity check the keys */
2875 if (HeSVKEY(entry)) {
6f207bd3 2876 NOOP; /* Don't know what to check on SV keys. */
57ca3b03
AL
2877 } else if (HeKUTF8(entry)) {
2878 withflags++;
2879 if (HeKWASUTF8(entry)) {
2880 PerlIO_printf(Perl_debug_log,
d2a455e7 2881 "hash key has both WASUTF8 and UTF8: '%.*s'\n",
57ca3b03
AL
2882 (int) HeKLEN(entry), HeKEY(entry));
2883 bad = 1;
2884 }
2885 } else if (HeKWASUTF8(entry))
2886 withflags++;
2887 }
2888 if (!SvTIED_mg((SV*)hv, PERL_MAGIC_tied)) {
2889 static const char bad_count[] = "Count %d %s(s), but hash reports %d\n";
2890 const int nhashkeys = HvUSEDKEYS(hv);
2891 const int nhashplaceholders = HvPLACEHOLDERS_get(hv);
2892
2893 if (nhashkeys != real) {
2894 PerlIO_printf(Perl_debug_log, bad_count, real, "keys", nhashkeys );
2895 bad = 1;
2896 }
2897 if (nhashplaceholders != placeholders) {
2898 PerlIO_printf(Perl_debug_log, bad_count, placeholders, "placeholder", nhashplaceholders );
2899 bad = 1;
2900 }
2901 }
2902 if (withflags && ! HvHASKFLAGS(hv)) {
2903 PerlIO_printf(Perl_debug_log,
2904 "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
2905 withflags);
2906 bad = 1;
2907 }
2908 if (bad) {
2909 sv_dump((SV *)hv);
2910 }
2911 HvRITER_set(hv, riter); /* Restore hash iterator state */
2912 HvEITER_set(hv, eiter);
ecae49c0 2913}
af3babe4 2914
943795c2
NC
2915#endif
2916
af3babe4
NC
2917/*
2918 * Local variables:
2919 * c-indentation-style: bsd
2920 * c-basic-offset: 4
2921 * indent-tabs-mode: t
2922 * End:
2923 *
37442d52
RGS
2924 * ex: set ts=8 sts=4 sw=4 noet:
2925 */