     1			/*    hv.c
     2			 *
     3			 *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
     4			 *    2000, 2001, 2002, 2003, 2004, 2005, by Larry Wall and others
     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			 *
     9			 */
    10			
    11			/*
    12			 * "I sit beside the fire and think of all that I have seen."  --Bilbo
    13			 */
    14			
    15			/* 
    16			=head1 Hash Manipulation Functions
    17			
    18			A HV structure represents a Perl hash. It consists mainly of an array
    19			of pointers, each of which points to a linked list of HE structures. The
    20			array is indexed by the hash function of the key, so each linked list
    21			represents all the hash entries with the same hash value. Each HE contains
    22			a pointer to the actual value, plus a pointer to a HEK structure which
    23			holds the key and hash value.
    24			
    25			=cut
    26			
    27			*/
    28			
    29			#include "EXTERN.h"
    30			#define PERL_IN_HV_C
    31			#define PERL_HASH_INTERNAL_ACCESS
    32			#include "perl.h"
    33			
    34			#define HV_MAX_LENGTH_BEFORE_SPLIT 14
    35			
    36			static const char *const S_strtab_error
    37			    = "Cannot modify shared string table in hv_%s";
    38			
    39			STATIC void
    40			S_more_he(pTHX)
    41	       14983    {
    42	       14983        HE* he;
    43	       14983        HE* heend;
    44	       14983        New(54, he, PERL_ARENA_SIZE/sizeof(HE), HE);
    45	       14983        HeNEXT(he) = PL_he_arenaroot;
    46	       14983        PL_he_arenaroot = he;
    47			
    48	       14983        heend = &he[PERL_ARENA_SIZE / sizeof(HE) - 1];
    49	       14983        PL_he_root = ++he;
    50	     5079237        while (he < heend) {
    51	     5064254    	HeNEXT(he) = (HE*)(he + 1);
    52	     5064254    	he++;
    53			    }
    54	       14983        HeNEXT(he) = 0;
    55			}
    56			
    57			STATIC HE*
    58			S_new_he(pTHX)
    59	     6636892    {
    60	     6636892        HE* he;
    61			    LOCK_SV_MUTEX;
    62	     6636892        if (!PL_he_root)
    63	       14983    	S_more_he(aTHX);
    64	     6636892        he = PL_he_root;
    65	     6636892        PL_he_root = HeNEXT(he);
    66			    UNLOCK_SV_MUTEX;
    67	     6636892        return he;
    68			}
    69			
    70			STATIC void
    71			S_del_he(pTHX_ HE *p)
    72	     6659114    {
    73			    LOCK_SV_MUTEX;
    74	     6659114        HeNEXT(p) = (HE*)PL_he_root;
    75	     6659114        PL_he_root = p;
    76			    UNLOCK_SV_MUTEX;
    77			}
    78			
    79			#ifdef PURIFY
    80			
    81			#define new_HE() (HE*)safemalloc(sizeof(HE))
    82			#define del_HE(p) safefree((char*)p)
    83			
    84			#else
    85			
    86			#define new_HE() new_he()
    87			#define del_HE(p) del_he(p)
    88			
    89			#endif
    90			
    91			STATIC HEK *
    92			S_save_hek_flags(pTHX_ const char *str, I32 len, U32 hash, int flags)
    93	       32467    {
    94	       32467        const int flags_masked = flags & HVhek_MASK;
    95	       32467        char *k;
    96	       32467        register HEK *hek;
    97			
    98	       32467        New(54, k, HEK_BASESIZE + len + 2, char);
    99	       32467        hek = (HEK*)k;
   100	       32467        Copy(str, HEK_KEY(hek), len, char);
   101	       32467        HEK_KEY(hek)[len] = 0;
   102	       32467        HEK_LEN(hek) = len;
   103	       32467        HEK_HASH(hek) = hash;
   104	       32467        HEK_FLAGS(hek) = (unsigned char)flags_masked;
   105			
   106	       32467        if (flags & HVhek_FREEKEY)
   107	      ######    	Safefree(str);
   108	       32467        return hek;
   109			}
   110			
   111			/* free the pool of temporary HE/HEK pairs retunrned by hv_fetch_ent
   112			 * for tied hashes */
   113			
   114			void
   115			Perl_free_tied_hv_pool(pTHX)
   116	        4549    {
   117	        4549        HE *he = PL_hv_fetch_ent_mh;
   118	        6240        while (he) {
   119	        1691    	HE * const ohe = he;
   120	        1691    	Safefree(HeKEY_hek(he));
   121	        1691    	he = HeNEXT(he);
   122	        1691    	del_HE(ohe);
   123			    }
   124	        4549        PL_hv_fetch_ent_mh = Nullhe;
   125			}
   126			
   127			#if defined(USE_ITHREADS)
   128			HEK *
   129			Perl_hek_dup(pTHX_ HEK *source, CLONE_PARAMS* param)
   130			{
   131			    HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
   132			
   133			    PERL_UNUSED_ARG(param);
   134			
   135			    if (shared) {
   136				/* We already shared this hash key.  */
   137				(void)share_hek_hek(shared);
   138			    }
   139			    else {
   140				shared
   141				    = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
   142						      HEK_HASH(source), HEK_FLAGS(source));
   143				ptr_table_store(PL_ptr_table, source, shared);
   144			    }
   145			    return shared;
   146			}
   147			
   148			HE *
   149			Perl_he_dup(pTHX_ HE *e, bool shared, CLONE_PARAMS* param)
   150			{
   151			    HE *ret;
   152			
   153			    if (!e)
   154				return Nullhe;
   155			    /* look for it in the table first */
   156			    ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
   157			    if (ret)
   158				return ret;
   159			
   160			    /* create anew and remember what it is */
   161			    ret = new_HE();
   162			    ptr_table_store(PL_ptr_table, e, ret);
   163			
   164			    HeNEXT(ret) = he_dup(HeNEXT(e),shared, param);
   165			    if (HeKLEN(e) == HEf_SVKEY) {
   166				char *k;
   167				New(54, k, HEK_BASESIZE + sizeof(SV*), char);
   168				HeKEY_hek(ret) = (HEK*)k;
   169				HeKEY_sv(ret) = SvREFCNT_inc(sv_dup(HeKEY_sv(e), param));
   170			    }
   171			    else if (shared) {
   172				/* This is hek_dup inlined, which seems to be important for speed
   173				   reasons.  */
   174				HEK * const source = HeKEY_hek(e);
   175				HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
   176			
   177				if (shared) {
   178				    /* We already shared this hash key.  */
   179				    (void)share_hek_hek(shared);
   180				}
   181				else {
   182				    shared
   183					= share_hek_flags(HEK_KEY(source), HEK_LEN(source),
   184							  HEK_HASH(source), HEK_FLAGS(source));
   185				    ptr_table_store(PL_ptr_table, source, shared);
   186				}
   187				HeKEY_hek(ret) = shared;
   188			    }
   189			    else
   190				HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
   191			                                        HeKFLAGS(e));
   192			    HeVAL(ret) = SvREFCNT_inc(sv_dup(HeVAL(e), param));
   193			    return ret;
   194			}
   195			#endif	/* USE_ITHREADS */
   196			
   197			static void
   198			S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
   199					const char *msg)
   200	          34    {
   201	          34        SV * const sv = sv_newmortal();
   202	          34        if (!(flags & HVhek_FREEKEY)) {
   203	          34    	sv_setpvn(sv, key, klen);
   204			    }
   205			    else {
   206				/* Need to free saved eventually assign to mortal SV */
   207				/* XXX is this line an error ???:  SV *sv = sv_newmortal(); */
   208	      ######    	sv_usepvn(sv, (char *) key, klen);
   209			    }
   210	          34        if (flags & HVhek_UTF8) {
   211	           1    	SvUTF8_on(sv);
   212			    }
   213	          34        Perl_croak(aTHX_ msg, sv);
   214			}
   215			
   216			/* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
   217			 * contains an SV* */
   218			
   219			#define HV_FETCH_ISSTORE   0x01
   220			#define HV_FETCH_ISEXISTS  0x02
   221			#define HV_FETCH_LVALUE    0x04
   222			#define HV_FETCH_JUST_SV   0x08
   223			
   224			/*
   225			=for apidoc hv_store
   226			
   227			Stores an SV in a hash.  The hash key is specified as C<key> and C<klen> is
   228			the length of the key.  The C<hash> parameter is the precomputed hash
   229			value; if it is zero then Perl will compute it.  The return value will be
   230			NULL if the operation failed or if the value did not need to be actually
   231			stored within the hash (as in the case of tied hashes).  Otherwise it can
   232			be dereferenced to get the original C<SV*>.  Note that the caller is
   233			responsible for suitably incrementing the reference count of C<val> before
   234			the call, and decrementing it if the function returned NULL.  Effectively
   235			a successful hv_store takes ownership of one reference to C<val>.  This is
   236			usually what you want; a newly created SV has a reference count of one, so
   237			if all your code does is create SVs then store them in a hash, hv_store
   238			will own the only reference to the new SV, and your code doesn't need to do
   239			anything further to tidy up.  hv_store is not implemented as a call to
   240			hv_store_ent, and does not create a temporary SV for the key, so if your
   241			key data is not already in SV form then use hv_store in preference to
   242			hv_store_ent.
   243			
   244			See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
   245			information on how to use this function on tied hashes.
   246			
   247			=cut
   248			*/
   249			
   250			SV**
   251			Perl_hv_store(pTHX_ HV *hv, const char *key, I32 klen_i32, SV *val, U32 hash)
   252	      393427    {
   253	      393427        HE *hek;
   254	      393427        STRLEN klen;
   255	      393427        int flags;
   256			
   257	      393427        if (klen_i32 < 0) {
   258	          33    	klen = -klen_i32;
   259	          33    	flags = HVhek_UTF8;
   260			    } else {
   261	      393394    	klen = klen_i32;
   262	      393394    	flags = 0;
   263			    }
   264	      393427        hek = hv_fetch_common (hv, NULL, key, klen, flags,
   265						   (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
   266	      393426        return hek ? &HeVAL(hek) : NULL;
   267			}
   268			
   269			SV**
   270			Perl_hv_store_flags(pTHX_ HV *hv, const char *key, I32 klen, SV *val,
   271			                 register U32 hash, int flags)
   272	         179    {
   273	         179        HE * const hek = hv_fetch_common (hv, NULL, key, klen, flags,
   274	         179    			       (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
   275	         179        return hek ? &HeVAL(hek) : NULL;
   276			}
   277			
   278			/*
   279			=for apidoc hv_store_ent
   280			
   281			Stores C<val> in a hash.  The hash key is specified as C<key>.  The C<hash>
   282			parameter is the precomputed hash value; if it is zero then Perl will
   283			compute it.  The return value is the new hash entry so created.  It will be
   284			NULL if the operation failed or if the value did not need to be actually
   285			stored within the hash (as in the case of tied hashes).  Otherwise the
   286			contents of the return value can be accessed using the C<He?> macros
   287			described here.  Note that the caller is responsible for suitably
   288			incrementing the reference count of C<val> before the call, and
   289			decrementing it if the function returned NULL.  Effectively a successful
   290			hv_store_ent takes ownership of one reference to C<val>.  This is
   291			usually what you want; a newly created SV has a reference count of one, so
   292			if all your code does is create SVs then store them in a hash, hv_store
   293			will own the only reference to the new SV, and your code doesn't need to do
   294			anything further to tidy up.  Note that hv_store_ent only reads the C<key>;
   295			unlike C<val> it does not take ownership of it, so maintaining the correct
   296			reference count on C<key> is entirely the caller's responsibility.  hv_store
   297			is not implemented as a call to hv_store_ent, and does not create a temporary
   298			SV for the key, so if your key data is not already in SV form then use
   299			hv_store in preference to hv_store_ent.
   300			
   301			See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
   302			information on how to use this function on tied hashes.
   303			
   304			=cut
   305			*/
   306			
   307			HE *
   308			Perl_hv_store_ent(pTHX_ HV *hv, SV *keysv, SV *val, U32 hash)
   309	     1632874    {
   310	     1632874      return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISSTORE, val, hash);
   311			}
   312			
   313			/*
   314			=for apidoc hv_exists
   315			
   316			Returns a boolean indicating whether the specified hash key exists.  The
   317			C<klen> is the length of the key.
   318			
   319			=cut
   320			*/
   321			
   322			bool
   323			Perl_hv_exists(pTHX_ HV *hv, const char *key, I32 klen_i32)
   324	       93038    {
   325	       93038        STRLEN klen;
   326	       93038        int flags;
   327			
   328	       93038        if (klen_i32 < 0) {
   329	          44    	klen = -klen_i32;
   330	          44    	flags = HVhek_UTF8;
   331			    } else {
   332	       92994    	klen = klen_i32;
   333	       92994    	flags = 0;
   334			    }
   335	       93038        return hv_fetch_common(hv, NULL, key, klen, flags, HV_FETCH_ISEXISTS, 0, 0)
   336				? TRUE : FALSE;
   337			}
   338			
   339			/*
   340			=for apidoc hv_fetch
   341			
   342			Returns the SV which corresponds to the specified key in the hash.  The
   343			C<klen> is the length of the key.  If C<lval> is set then the fetch will be
   344			part of a store.  Check that the return value is non-null before
   345			dereferencing it to an C<SV*>.
   346			
   347			See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
   348			information on how to use this function on tied hashes.
   349			
   350			=cut
   351			*/
   352			
   353			SV**
   354			Perl_hv_fetch(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 lval)
   355	    24823873    {
   356	    24823873        HE *hek;
   357	    24823873        STRLEN klen;
   358	    24823873        int flags;
   359			
   360	    24823873        if (klen_i32 < 0) {
   361	          48    	klen = -klen_i32;
   362	          48    	flags = HVhek_UTF8;
   363			    } else {
   364	    24823825    	klen = klen_i32;
   365	    24823825    	flags = 0;
   366			    }
   367	    24823873        hek = hv_fetch_common (hv, NULL, key, klen, flags,
   368						   HV_FETCH_JUST_SV | (lval ? HV_FETCH_LVALUE : 0),
   369						   Nullsv, 0);
   370	    24823873        return hek ? &HeVAL(hek) : NULL;
   371			}
   372			
   373			/*
   374			=for apidoc hv_exists_ent
   375			
   376			Returns a boolean indicating whether the specified hash key exists. C<hash>
   377			can be a valid precomputed hash value, or 0 to ask for it to be
   378			computed.
   379			
   380			=cut
   381			*/
   382			
   383			bool
   384			Perl_hv_exists_ent(pTHX_ HV *hv, SV *keysv, U32 hash)
   385	      981051    {
   386	      981051        return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISEXISTS, 0, hash)
   387				? TRUE : FALSE;
   388			}
   389			
   390			/* returns an HE * structure with the all fields set */
   391			/* note that hent_val will be a mortal sv for MAGICAL hashes */
   392			/*
   393			=for apidoc hv_fetch_ent
   394			
   395			Returns the hash entry which corresponds to the specified key in the hash.
   396			C<hash> must be a valid precomputed hash number for the given C<key>, or 0
   397			if you want the function to compute it.  IF C<lval> is set then the fetch
   398			will be part of a store.  Make sure the return value is non-null before
   399			accessing it.  The return value when C<tb> is a tied hash is a pointer to a
   400			static location, so be sure to make a copy of the structure if you need to
   401			store it somewhere.
   402			
   403			See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
   404			information on how to use this function on tied hashes.
   405			
   406			=cut
   407			*/
   408			
   409			HE *
   410			Perl_hv_fetch_ent(pTHX_ HV *hv, SV *keysv, I32 lval, register U32 hash)
   411	    23191424    {
   412	    23191424        return hv_fetch_common(hv, keysv, NULL, 0, 0, 
   413						   (lval ? HV_FETCH_LVALUE : 0), Nullsv, hash);
   414			}
   415			
   416			STATIC HE *
   417			S_hv_fetch_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
   418					  int flags, int action, SV *val, register U32 hash)
   419	    52451536    {
   420			    dVAR;
   421	    52451536        XPVHV* xhv;
   422	    52451536        HE *entry;
   423	    52451536        HE **oentry;
   424	    52451536        SV *sv;
   425	    52451536        bool is_utf8;
   426	    52451536        int masked_flags;
   427			
   428	    52451536        if (!hv)
   429	          23    	return 0;
   430			
   431	    52451513        if (keysv) {
   432	    25809190    	if (flags & HVhek_FREEKEY)
   433	      ######    	    Safefree(key);
   434	    25809190    	key = SvPV_const(keysv, klen);
   435	    25809190    	flags = 0;
   436	    25809190    	is_utf8 = (SvUTF8(keysv) != 0);
   437			    } else {
   438	    26642323    	is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
   439			    }
   440			
   441	    52451513        xhv = (XPVHV*)SvANY(hv);
   442	    52451513        if (SvMAGICAL(hv)) {
   443	    30717605    	if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS)))
   444				  {
   445	    29159015    	    if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
   446	       11530    		sv = sv_newmortal();
   447			
   448					/* XXX should be able to skimp on the HE/HEK here when
   449					   HV_FETCH_JUST_SV is true.  */
   450			
   451	       11530    		if (!keysv) {
   452	          37    		    keysv = newSVpvn(key, klen);
   453	          37    		    if (is_utf8) {
   454	          22    			SvUTF8_on(keysv);
   455					    }
   456					} else {
   457	       11493    		    keysv = newSVsv(keysv);
   458					}
   459	       11530    		mg_copy((SV*)hv, sv, (char *)keysv, HEf_SVKEY);
   460			
   461					/* grab a fake HE/HEK pair from the pool or make a new one */
   462	       11530    		entry = PL_hv_fetch_ent_mh;
   463	       11530    		if (entry)
   464	        9865    		    PL_hv_fetch_ent_mh = HeNEXT(entry);
   465					else {
   466	        1665    		    char *k;
   467	        1665    		    entry = new_HE();
   468	        1665    		    New(54, k, HEK_BASESIZE + sizeof(SV*), char);
   469	        1665    		    HeKEY_hek(entry) = (HEK*)k;
   470					}
   471	       11530    		HeNEXT(entry) = Nullhe;
   472	       11530    		HeSVKEY_set(entry, keysv);
   473	       11530    		HeVAL(entry) = sv;
   474	       11530    		sv_upgrade(sv, SVt_PVLV);
   475	       11530    		LvTYPE(sv) = 'T';
   476					 /* so we can free entry when freeing sv */
   477	       11530    		LvTARG(sv) = (SV*)entry;
   478			
   479					/* XXX remove at some point? */
   480	       11530    		if (flags & HVhek_FREEKEY)
   481	      ######    		    Safefree(key);
   482			
   483	       11530    		return entry;
   484				    }
   485			#ifdef ENV_IS_CASELESS
   486				    else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
   487					U32 i;
   488					for (i = 0; i < klen; ++i)
   489					    if (isLOWER(key[i])) {
   490						/* Would be nice if we had a routine to do the
   491						   copy and upercase in a single pass through.  */
   492						const char *nkey = strupr(savepvn(key,klen));
   493						/* Note that this fetch is for nkey (the uppercased
   494						   key) whereas the store is for key (the original)  */
   495						entry = hv_fetch_common(hv, Nullsv, nkey, klen,
   496									HVhek_FREEKEY, /* free nkey */
   497									0 /* non-LVAL fetch */,
   498									Nullsv /* no value */,
   499									0 /* compute hash */);
   500						if (!entry && (action & HV_FETCH_LVALUE)) {
   501						    /* This call will free key if necessary.
   502						       Do it this way to encourage compiler to tail
   503						       call optimise.  */
   504						    entry = hv_fetch_common(hv, keysv, key, klen,
   505									    flags, HV_FETCH_ISSTORE,
   506									    NEWSV(61,0), hash);
   507						} else {
   508						    if (flags & HVhek_FREEKEY)
   509							Safefree(key);
   510						}
   511						return entry;
   512					    }
   513				    }
   514			#endif
   515				} /* ISFETCH */
   516	     1558590    	else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
   517	        7067    	    if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
   518					/* I don't understand why hv_exists_ent has svret and sv,
   519					   whereas hv_exists only had one.  */
   520	         320    		SV * const svret = sv_newmortal();
   521	         320    		sv = sv_newmortal();
   522			
   523	         320    		if (keysv || is_utf8) {
   524	         308    		    if (!keysv) {
   525	          22    			keysv = newSVpvn(key, klen);
   526	          22    			SvUTF8_on(keysv);
   527					    } else {
   528	         286    			keysv = newSVsv(keysv);
   529					    }
   530	         308    		    mg_copy((SV*)hv, sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
   531					} else {
   532	          12    		    mg_copy((SV*)hv, sv, key, klen);
   533					}
   534	         320    		if (flags & HVhek_FREEKEY)
   535	      ######    		    Safefree(key);
   536	         320    		magic_existspack(svret, mg_find(sv, PERL_MAGIC_tiedelem));
   537					/* This cast somewhat evil, but I'm merely using NULL/
   538					   not NULL to return the boolean exists.
   539					   And I know hv is not NULL.  */
   540	         320    		return SvTRUE(svret) ? (HE *)hv : NULL;
   541					}
   542			#ifdef ENV_IS_CASELESS
   543				    else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
   544					/* XXX This code isn't UTF8 clean.  */
   545					char * const keysave = (char * const)key;
   546					/* Will need to free this, so set FREEKEY flag.  */
   547					key = savepvn(key,klen);
   548					key = (const char*)strupr((char*)key);
   549					is_utf8 = 0;
   550					hash = 0;
   551					keysv = 0;
   552			
   553					if (flags & HVhek_FREEKEY) {
   554					    Safefree(keysave);
   555					}
   556					flags |= HVhek_FREEKEY;
   557				    }
   558			#endif
   559				} /* ISEXISTS */
   560	     1551523    	else if (action & HV_FETCH_ISSTORE) {
   561	     1551286    	    bool needs_copy;
   562	     1551286    	    bool needs_store;
   563	     1551286    	    hv_magic_check (hv, &needs_copy, &needs_store);
   564	     1551286    	    if (needs_copy) {
   565	      353732    		const bool save_taint = PL_tainted;
   566	      353732    		if (keysv || is_utf8) {
   567	        4536    		    if (!keysv) {
   568	          17    			keysv = newSVpvn(key, klen);
   569	          17    			SvUTF8_on(keysv);
   570					    }
   571	        4536    		    if (PL_tainting)
   572	          88    			PL_tainted = SvTAINTED(keysv);
   573	        4536    		    keysv = sv_2mortal(newSVsv(keysv));
   574	        4536    		    mg_copy((SV*)hv, val, (char*)keysv, HEf_SVKEY);
   575					} else {
   576	      349196    		    mg_copy((SV*)hv, val, key, klen);
   577					}
   578			
   579	      353732    		TAINT_IF(save_taint);
   580	      353732    		if (!HvARRAY(hv) && !needs_store) {
   581	          16    		    if (flags & HVhek_FREEKEY)
   582	      ######    			Safefree(key);
   583	          16    		    return Nullhe;
   584					}
   585			#ifdef ENV_IS_CASELESS
   586					else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
   587					    /* XXX This code isn't UTF8 clean.  */
   588					    const char *keysave = key;
   589					    /* Will need to free this, so set FREEKEY flag.  */
   590					    key = savepvn(key,klen);
   591					    key = (const char*)strupr((char*)key);
   592					    is_utf8 = 0;
   593					    hash = 0;
   594					    keysv = 0;
   595			
   596					    if (flags & HVhek_FREEKEY) {
   597						Safefree(keysave);
   598					    }
   599					    flags |= HVhek_FREEKEY;
   600					}
   601			#endif
   602				    }
   603				} /* ISSTORE */
   604			    } /* SvMAGICAL */
   605			
   606	    52439647        if (!HvARRAY(hv)) {
   607	      841933    	if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
   608			#ifdef DYNAMIC_ENV_FETCH  /* if it's an %ENV lookup, we may get it on the fly */
   609					 || (SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
   610			#endif
   611											  ) {
   612	      538643    	    char *array;
   613				    Newz(503, array,
   614					 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
   615	      538643    		 char);
   616	      538643    	    HvARRAY(hv) = (HE**)array;
   617				}
   618			#ifdef DYNAMIC_ENV_FETCH
   619				else if (action & HV_FETCH_ISEXISTS) {
   620				    /* for an %ENV exists, if we do an insert it's by a recursive
   621				       store call, so avoid creating HvARRAY(hv) right now.  */
   622				}
   623			#endif
   624				else {
   625				    /* XXX remove at some point? */
   626	      303290                if (flags & HVhek_FREEKEY)
   627	      ######                    Safefree(key);
   628			
   629	      303290    	    return 0;
   630				}
   631			    }
   632			
   633	    52136357        if (is_utf8) {
   634	        3322    	char * const keysave = (char * const)key;
   635	        3322    	key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
   636	        3322            if (is_utf8)
   637	        2174    	    flags |= HVhek_UTF8;
   638				else
   639	        1148    	    flags &= ~HVhek_UTF8;
   640	        3322            if (key != keysave) {
   641	        1148    	    if (flags & HVhek_FREEKEY)
   642	      ######    		Safefree(keysave);
   643	        1148                flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
   644				}
   645			    }
   646			
   647	    52136357        if (HvREHASH(hv)) {
   648	           6    	PERL_HASH_INTERNAL(hash, key, klen);
   649				/* We don't have a pointer to the hv, so we have to replicate the
   650				   flag into every HEK, so that hv_iterkeysv can see it.  */
   651				/* And yes, you do need this even though you are not "storing" because
   652				   you can flip the flags below if doing an lval lookup.  (And that
   653				   was put in to give the semantics Andreas was expecting.)  */
   654	           6    	flags |= HVhek_REHASH;
   655	    52136351        } else if (!hash) {
   656	    33209329            if (keysv && (SvIsCOW_shared_hash(keysv))) {
   657	      357991                hash = SvSHARED_HASH(keysv);
   658			        } else {
   659	    32851338                PERL_HASH(hash, key, klen);
   660			        }
   661			    }
   662			
   663	    52136357        masked_flags = (flags & HVhek_MASK);
   664			
   665			#ifdef DYNAMIC_ENV_FETCH
   666			    if (!HvARRAY(hv)) entry = Null(HE*);
   667			    else
   668			#endif
   669			    {
   670	    52136357    	entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
   671			    }
   672	    86035607        for (; entry; entry = HeNEXT(entry)) {
   673	    49397003    	if (HeHASH(entry) != hash)		/* strings can't be equal */
   674	    16949330    	    continue;
   675	    32447673    	if (HeKLEN(entry) != (I32)klen)
   676	         185    	    continue;
   677	    32447488    	if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen))	/* is this it? */
   678	      ######    	    continue;
   679	    32447488    	if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
   680	         110    	    continue;
   681			
   682	    32447378            if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
   683	    12693912    	    if (HeKFLAGS(entry) != masked_flags) {
   684					/* We match if HVhek_UTF8 bit in our flags and hash key's
   685					   match.  But if entry was set previously with HVhek_WASUTF8
   686					   and key now doesn't (or vice versa) then we should change
   687					   the key's flag, as this is assignment.  */
   688	           3    		if (HvSHAREKEYS(hv)) {
   689					    /* Need to swap the key we have for a key with the flags we
   690					       need. As keys are shared we can't just write to the
   691					       flag, so we share the new one, unshare the old one.  */
   692	           3    		    HEK *new_hek = share_hek_flags(key, klen, hash,
   693	           3    						   masked_flags);
   694	           3    		    unshare_hek (HeKEY_hek(entry));
   695	           3    		    HeKEY_hek(entry) = new_hek;
   696					}
   697	      ######    		else if (hv == PL_strtab) {
   698					    /* PL_strtab is usually the only hash without HvSHAREKEYS,
   699					       so putting this test here is cheap  */
   700	      ######    		    if (flags & HVhek_FREEKEY)
   701	      ######    			Safefree(key);
   702	      ######    		    Perl_croak(aTHX_ S_strtab_error,
   703						       action & HV_FETCH_LVALUE ? "fetch" : "store");
   704					}
   705					else
   706	      ######    		    HeKFLAGS(entry) = masked_flags;
   707	           3    		if (masked_flags & HVhek_ENABLEHVKFLAGS)
   708	           2    		    HvHASKFLAGS_on(hv);
   709				    }
   710	    12693912    	    if (HeVAL(entry) == &PL_sv_placeholder) {
   711					/* yes, can store into placeholder slot */
   712	         111    		if (action & HV_FETCH_LVALUE) {
   713	         107    		    if (SvMAGICAL(hv)) {
   714						/* This preserves behaviour with the old hv_fetch
   715						   implementation which at this point would bail out
   716						   with a break; (at "if we find a placeholder, we
   717						   pretend we haven't found anything")
   718			
   719						   That break mean that if a placeholder were found, it
   720						   caused a call into hv_store, which in turn would
   721						   check magic, and if there is no magic end up pretty
   722						   much back at this point (in hv_store's code).  */
   723	      ######    			break;
   724					    }
   725					    /* LVAL fetch which actaully needs a store.  */
   726	         107    		    val = NEWSV(61,0);
   727	         107    		    HvPLACEHOLDERS(hv)--;
   728					} else {
   729					    /* store */
   730	           4    		    if (val != &PL_sv_placeholder)
   731	           4    			HvPLACEHOLDERS(hv)--;
   732					}
   733	         111    		HeVAL(entry) = val;
   734	    12693801    	    } else if (action & HV_FETCH_ISSTORE) {
   735	       22595    		SvREFCNT_dec(HeVAL(entry));
   736	       22595    		HeVAL(entry) = val;
   737				    }
   738	    19753466    	} else if (HeVAL(entry) == &PL_sv_placeholder) {
   739				    /* if we find a placeholder, we pretend we haven't found
   740				       anything */
   741	          21    	    break;
   742				}
   743	    32447357    	if (flags & HVhek_FREEKEY)
   744	         319    	    Safefree(key);
   745	    32447357    	return entry;
   746			    }
   747			#ifdef DYNAMIC_ENV_FETCH  /* %ENV lookup?  If so, try to fetch the value now */
   748			    if (!(action & HV_FETCH_ISSTORE) 
   749				&& SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
   750				unsigned long len;
   751				const char * const env = PerlEnv_ENVgetenv_len(key,&len);
   752				if (env) {
   753				    sv = newSVpvn(env,len);
   754				    SvTAINTED_on(sv);
   755				    return hv_fetch_common(hv,keysv,key,klen,flags,HV_FETCH_ISSTORE,sv,
   756							   hash);
   757				}
   758			    }
   759			#endif
   760			
   761	    19689000        if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
   762	          32    	S_hv_notallowed(aTHX_ flags, key, klen,
   763						"Attempt to access disallowed key '%"SVf"' in"
   764						" a restricted hash");
   765			    }
   766	    19688968        if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
   767				/* Not doing some form of store, so return failure.  */
   768	    11720200    	if (flags & HVhek_FREEKEY)
   769	         126    	    Safefree(key);
   770	    11720200    	return 0;
   771			    }
   772	     7968768        if (action & HV_FETCH_LVALUE) {
   773	     4629502    	val = NEWSV(61,0);
   774	     4629502    	if (SvMAGICAL(hv)) {
   775				    /* At this point the old hv_fetch code would call to hv_store,
   776				       which in turn might do some tied magic. So we need to make that
   777				       magic check happen.  */
   778				    /* gonna assign to this, so it better be there */
   779	     1335402    	    return hv_fetch_common(hv, keysv, key, klen, flags,
   780							   HV_FETCH_ISSTORE, val, hash);
   781				    /* XXX Surely that could leak if the fetch-was-store fails?
   782				       Just like the hv_fetch.  */
   783				}
   784			    }
   785			
   786			    /* Welcome to hv_store...  */
   787			
   788	     6633366        if (!HvARRAY(hv)) {
   789				/* Not sure if we can get here.  I think the only case of oentry being
   790				   NULL is for %ENV with dynamic env fetch.  But that should disappear
   791				   with magic in the previous code.  */
   792	      ######    	char *array;
   793				Newz(503, array,
   794				     PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
   795	      ######    	     char);
   796	      ######    	HvARRAY(hv) = (HE**)array;
   797			    }
   798			
   799	     6633366        oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
   800			
   801	     6633366        entry = new_HE();
   802			    /* share_hek_flags will do the free for us.  This might be considered
   803			       bad API design.  */
   804	     6633366        if (HvSHAREKEYS(hv))
   805	     6601008    	HeKEY_hek(entry) = share_hek_flags(key, klen, hash, flags);
   806	       32358        else if (hv == PL_strtab) {
   807				/* PL_strtab is usually the only hash without HvSHAREKEYS, so putting
   808				   this test here is cheap  */
   809	           2    	if (flags & HVhek_FREEKEY)
   810	      ######    	    Safefree(key);
   811	           2    	Perl_croak(aTHX_ S_strtab_error,
   812					   action & HV_FETCH_LVALUE ? "fetch" : "store");
   813			    }
   814			    else                                       /* gotta do the real thing */
   815	       32356    	HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
   816	     6633364        HeVAL(entry) = val;
   817	     6633364        HeNEXT(entry) = *oentry;
   818	     6633364        *oentry = entry;
   819			
   820	     6633364        if (val == &PL_sv_placeholder)
   821	          80    	HvPLACEHOLDERS(hv)++;
   822	     6633364        if (masked_flags & HVhek_ENABLEHVKFLAGS)
   823	        1900    	HvHASKFLAGS_on(hv);
   824			
   825			    {
   826	     6633364    	const HE *counter = HeNEXT(entry);
   827			
   828	     6633364    	xhv->xhv_keys++; /* HvKEYS(hv)++ */
   829	     6633364    	if (!counter) {				/* initial entry? */
   830	     4197308    	    xhv->xhv_fill++; /* HvFILL(hv)++ */
   831	     2436056    	} else if (xhv->xhv_keys > (IV)xhv->xhv_max) {
   832	      256069    	    hsplit(hv);
   833	     2179987    	} else if(!HvREHASH(hv)) {
   834	     2179986    	    U32 n_links = 1;
   835			
   836	     2830443    	    while ((counter = HeNEXT(counter)))
   837	      650457    		n_links++;
   838			
   839	     2179986    	    if (n_links > HV_MAX_LENGTH_BEFORE_SPLIT) {
   840					/* Use only the old HvKEYS(hv) > HvMAX(hv) condition to limit
   841					   bucket splits on a rehashed hash, as we're not going to
   842					   split it again, and if someone is lucky (evil) enough to
   843					   get all the keys in one list they could exhaust our memory
   844					   as we repeatedly double the number of buckets on every
   845					   entry. Linear search feels a less worse thing to do.  */
   846	           1    		hsplit(hv);
   847				    }
   848				}
   849			    }
   850			
   851	     6633364        return entry;
   852			}
   853			
   854			STATIC void
   855			S_hv_magic_check(pTHX_ HV *hv, bool *needs_copy, bool *needs_store)
   856	     1618879    {
   857	     1618879        const MAGIC *mg = SvMAGIC(hv);
   858	     1618879        *needs_copy = FALSE;
   859	     1618879        *needs_store = TRUE;
   860	     3607018        while (mg) {
   861	     2125759    	if (isUPPER(mg->mg_type)) {
   862	      354000    	    *needs_copy = TRUE;
   863	      354000    	    switch (mg->mg_type) {
   864				    case PERL_MAGIC_tied:
   865				    case PERL_MAGIC_sig:
   866	      137620    		*needs_store = FALSE;
   867	      137620    		return; /* We've set all there is to set. */
   868				    }
   869				}
   870	     1988139    	mg = mg->mg_moremagic;
   871			    }
   872			}
   873			
   874			/*
   875			=for apidoc hv_scalar
   876			
   877			Evaluates the hash in scalar context and returns the result. Handles magic when the hash is tied.
   878			
   879			=cut
   880			*/
   881			
   882			SV *
   883			Perl_hv_scalar(pTHX_ HV *hv)
   884	       23571    {
   885	       23571        MAGIC *mg;
   886	       23571        SV *sv;
   887			    
   888	       23571        if ((SvRMAGICAL(hv) && (mg = mg_find((SV*)hv, PERL_MAGIC_tied)))) {
   889	           7            sv = magic_scalarpack(hv, mg);
   890	           7            return sv;
   891			    } 
   892			
   893	       23564        sv = sv_newmortal();
   894	       23564        if (HvFILL((HV*)hv)) 
   895	        2491            Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
   896			                (long)HvFILL(hv), (long)HvMAX(hv) + 1);
   897			    else
   898	       21073            sv_setiv(sv, 0);
   899			    
   900	       23564        return sv;
   901			}
   902			
   903			/*
   904			=for apidoc hv_delete
   905			
   906			Deletes a key/value pair in the hash.  The value SV is removed from the
   907			hash and returned to the caller.  The C<klen> is the length of the key.
   908			The C<flags> value will normally be zero; if set to G_DISCARD then NULL
   909			will be returned.
   910			
   911			=cut
   912			*/
   913			
   914			SV *
   915			Perl_hv_delete(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 flags)
   916	       72390    {
   917	       72390        STRLEN klen;
   918	       72390        int k_flags = 0;
   919			
   920	       72390        if (klen_i32 < 0) {
   921	          44    	klen = -klen_i32;
   922	          44    	k_flags |= HVhek_UTF8;
   923			    } else {
   924	       72346    	klen = klen_i32;
   925			    }
   926	       72390        return hv_delete_common(hv, NULL, key, klen, k_flags, flags, 0);
   927			}
   928			
   929			/*
   930			=for apidoc hv_delete_ent
   931			
   932			Deletes a key/value pair in the hash.  The value SV is removed from the
   933			hash and returned to the caller.  The C<flags> value will normally be zero;
   934			if set to G_DISCARD then NULL will be returned.  C<hash> can be a valid
   935			precomputed hash value, or 0 to ask for it to be computed.
   936			
   937			=cut
   938			*/
   939			
   940			SV *
   941			Perl_hv_delete_ent(pTHX_ HV *hv, SV *keysv, I32 flags, U32 hash)
   942	      125745    {
   943	      125745        return hv_delete_common(hv, keysv, NULL, 0, 0, flags, hash);
   944			}
   945			
   946			STATIC SV *
   947			S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
   948					   int k_flags, I32 d_flags, U32 hash)
   949	      198135    {
   950			    dVAR;
   951	      198135        register XPVHV* xhv;
   952	      198135        register HE *entry;
   953	      198135        register HE **oentry;
   954	      198135        HE *const *first_entry;
   955	      198135        SV *sv;
   956	      198135        bool is_utf8;
   957	      198135        int masked_flags;
   958			
   959	      198135        if (!hv)
   960	      ######    	return Nullsv;
   961			
   962	      198135        if (keysv) {
   963	      125745    	if (k_flags & HVhek_FREEKEY)
   964	      ######    	    Safefree(key);
   965	      125745    	key = SvPV_const(keysv, klen);
   966	      125745    	k_flags = 0;
   967	      125745    	is_utf8 = (SvUTF8(keysv) != 0);
   968			    } else {
   969	       72390    	is_utf8 = ((k_flags & HVhek_UTF8) ? TRUE : FALSE);
   970			    }
   971			
   972	      198135        if (SvRMAGICAL(hv)) {
   973	       67593    	bool needs_copy;
   974	       67593    	bool needs_store;
   975	       67593    	hv_magic_check (hv, &needs_copy, &needs_store);
   976			
   977	       67593    	if (needs_copy) {
   978	         268    	    entry = hv_fetch_common(hv, keysv, key, klen,
   979							    k_flags & ~HVhek_FREEKEY, HV_FETCH_LVALUE,
   980							    Nullsv, hash);
   981	         268    	    sv = entry ? HeVAL(entry) : NULL;
   982	         268    	    if (sv) {
   983	         268    		if (SvMAGICAL(sv)) {
   984	         268    		    mg_clear(sv);
   985					}
   986	         265    		if (!needs_store) {
   987	          78    		    if (mg_find(sv, PERL_MAGIC_tiedelem)) {
   988						/* No longer an element */
   989	          77    			sv_unmagic(sv, PERL_MAGIC_tiedelem);
   990	          77    			return sv;
   991					    }		
   992	           1    		    return Nullsv;		/* element cannot be deleted */
   993					}
   994			#ifdef ENV_IS_CASELESS
   995					else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
   996					    /* XXX This code isn't UTF8 clean.  */
   997					    keysv = sv_2mortal(newSVpvn(key,klen));
   998					    if (k_flags & HVhek_FREEKEY) {
   999						Safefree(key);
  1000					    }
  1001					    key = strupr(SvPVX(keysv));
  1002					    is_utf8 = 0;
  1003					    k_flags = 0;
  1004					    hash = 0;
  1005					}
  1006			#endif
  1007				    }
  1008				}
  1009			    }
  1010	      198054        xhv = (XPVHV*)SvANY(hv);
  1011	      198054        if (!HvARRAY(hv))
  1012	        4667    	return Nullsv;
  1013			
  1014	      193387        if (is_utf8) {
  1015	          99    	const char *keysave = key;
  1016	          99    	key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
  1017			
  1018	          99            if (is_utf8)
  1019	          44                k_flags |= HVhek_UTF8;
  1020				else
  1021	          55                k_flags &= ~HVhek_UTF8;
  1022	          99            if (key != keysave) {
  1023	          55    	    if (k_flags & HVhek_FREEKEY) {
  1024					/* This shouldn't happen if our caller does what we expect,
  1025					   but strictly the API allows it.  */
  1026	      ######    		Safefree(keysave);
  1027				    }
  1028	          55    	    k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
  1029				}
  1030	          99            HvHASKFLAGS_on((SV*)hv);
  1031			    }
  1032			
  1033	      193387        if (HvREHASH(hv)) {
  1034	      ######    	PERL_HASH_INTERNAL(hash, key, klen);
  1035	      193387        } else if (!hash) {
  1036	      193387            if (keysv && (SvIsCOW_shared_hash(keysv))) {
  1037	       23101                hash = SvSHARED_HASH(keysv);
  1038			        } else {
  1039	      170286                PERL_HASH(hash, key, klen);
  1040			        }
  1041			    }
  1042			
  1043	      193387        masked_flags = (k_flags & HVhek_MASK);
  1044			
  1045	      193387        first_entry = oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
  1046	      193387        entry = *oentry;
  1047	      224171        for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
  1048	      127079    	if (HeHASH(entry) != hash)		/* strings can't be equal */
  1049	       15368    	    continue;
  1050	      111711    	if (HeKLEN(entry) != (I32)klen)
  1051	      ######    	    continue;
  1052	      111711    	if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen))	/* is this it? */
  1053	      ######    	    continue;
  1054	      111711    	if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
  1055	          24    	    continue;
  1056			
  1057	      111687    	if (hv == PL_strtab) {
  1058	           1    	    if (k_flags & HVhek_FREEKEY)
  1059	           1    		Safefree(key);
  1060	           1    	    Perl_croak(aTHX_ S_strtab_error, "delete");
  1061				}
  1062			
  1063				/* if placeholder is here, it's already been deleted.... */
  1064	      111686    	if (HeVAL(entry) == &PL_sv_placeholder)
  1065				{
  1066	      ######    	  if (k_flags & HVhek_FREEKEY)
  1067	      ######                Safefree(key);
  1068	      ######    	  return Nullsv;
  1069				}
  1070	      111686    	else if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
  1071	           1    	    S_hv_notallowed(aTHX_ k_flags, key, klen,
  1072						    "Attempt to delete readonly key '%"SVf"' from"
  1073						    " a restricted hash");
  1074				}
  1075	      111685            if (k_flags & HVhek_FREEKEY)
  1076	          22                Safefree(key);
  1077			
  1078	      111685    	if (d_flags & G_DISCARD)
  1079	      105086    	    sv = Nullsv;
  1080				else {
  1081	        6599    	    sv = sv_2mortal(HeVAL(entry));
  1082	        6599    	    HeVAL(entry) = &PL_sv_placeholder;
  1083				}
  1084			
  1085				/*
  1086				 * If a restricted hash, rather than really deleting the entry, put
  1087				 * a placeholder there. This marks the key as being "approved", so
  1088				 * we can still access via not-really-existing key without raising
  1089				 * an error.
  1090				 */
  1091	      111685    	if (SvREADONLY(hv)) {
  1092	         120    	    SvREFCNT_dec(HeVAL(entry));
  1093	         120    	    HeVAL(entry) = &PL_sv_placeholder;
  1094				    /* We'll be saving this slot, so the number of allocated keys
  1095				     * doesn't go down, but the number placeholders goes up */
  1096	         120    	    HvPLACEHOLDERS(hv)++;
  1097				} else {
  1098	      111565    	    *oentry = HeNEXT(entry);
  1099	      111565    	    if(!*first_entry) {
  1100	       55458    		xhv->xhv_fill--; /* HvFILL(hv)-- */
  1101				    }
  1102	      111565    	    if (SvOOK(hv) && entry == HvAUX(hv)->xhv_eiter /* HvEITER(hv) */)
  1103	          10    		HvLAZYDEL_on(hv);
  1104				    else
  1105	      111555    		hv_free_ent(hv, entry);
  1106	      111565    	    xhv->xhv_keys--; /* HvKEYS(hv)-- */
  1107	      111565    	    if (xhv->xhv_keys == 0)
  1108	        1454    	        HvHASKFLAGS_off(hv);
  1109				}
  1110	      111685    	return sv;
  1111			    }
  1112	       81700        if (SvREADONLY(hv)) {
  1113	           1            S_hv_notallowed(aTHX_ k_flags, key, klen,
  1114						"Attempt to delete disallowed key '%"SVf"' from"
  1115						" a restricted hash");
  1116			    }
  1117			
  1118	       81699        if (k_flags & HVhek_FREEKEY)
  1119	          32    	Safefree(key);
  1120	       81699        return Nullsv;
  1121			}
  1122			
  1123			STATIC void
  1124			S_hsplit(pTHX_ HV *hv)
  1125	      258141    {
  1126	      258141        register XPVHV* xhv = (XPVHV*)SvANY(hv);
  1127	      258141        const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
  1128	      258141        register I32 newsize = oldsize * 2;
  1129	      258141        register I32 i;
  1130	      258141        char *a = (char*) HvARRAY(hv);
  1131	      258141        register HE **aep;
  1132	      258141        register HE **oentry;
  1133	      258141        int longest_chain = 0;
  1134	      258141        int was_shared;
  1135			
  1136			    /*PerlIO_printf(PerlIO_stderr(), "hsplit called for %p which had %d\n",
  1137			      hv, (int) oldsize);*/
  1138			
  1139	      258141        if (HvPLACEHOLDERS_get(hv) && !SvREADONLY(hv)) {
  1140			      /* Can make this clear any placeholders first for non-restricted hashes,
  1141				 even though Storable rebuilds restricted hashes by putting in all the
  1142				 placeholders (first) before turning on the readonly flag, because
  1143				 Storable always pre-splits the hash.  */
  1144	      ######          hv_clear_placeholders(hv);
  1145			    }
  1146				       
  1147	      258141        PL_nomemok = TRUE;
  1148			#if defined(STRANGE_MALLOC) || defined(MYMALLOC)
  1149			    Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
  1150				  + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
  1151			    if (!a) {
  1152			      PL_nomemok = FALSE;
  1153			      return;
  1154			    }
  1155			    if (SvOOK(hv)) {
  1156				Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
  1157			    }
  1158			#else
  1159			    New(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
  1160	      258141    	+ (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
  1161	      258141        if (!a) {
  1162	      ######          PL_nomemok = FALSE;
  1163	      ######          return;
  1164			    }
  1165	      258141        Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
  1166	      258141        if (SvOOK(hv)) {
  1167	       80122    	Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
  1168			    }
  1169	      258141        if (oldsize >= 64) {
  1170	       16631    	offer_nice_chunk(HvARRAY(hv),
  1171						 PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
  1172						 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
  1173			    }
  1174			    else
  1175	      241510    	Safefree(HvARRAY(hv));
  1176			#endif
  1177			
  1178	      258141        PL_nomemok = FALSE;
  1179	      258141        Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char);	/* zero 2nd half*/
  1180	      258141        xhv->xhv_max = --newsize;	/* HvMAX(hv) = --newsize */
  1181	      258141        HvARRAY(hv) = (HE**) a;
  1182	      258141        aep = (HE**)a;
  1183			
  1184	     7265883        for (i=0; i<oldsize; i++,aep++) {
  1185	     7007742    	int left_length = 0;
  1186	     7007742    	int right_length = 0;
  1187	     7007742    	register HE *entry;
  1188	     7007742    	register HE **bep;
  1189			
  1190	     7007742    	if (!*aep)				/* non-existent */
  1191	     2518419    	    continue;
  1192	     4489323    	bep = aep+oldsize;
  1193	    11646343    	for (oentry = aep, entry = *aep; entry; entry = *oentry) {
  1194	     7157020    	    if ((HeHASH(entry) & newsize) != (U32)i) {
  1195	     3470130    		*oentry = HeNEXT(entry);
  1196	     3470130    		HeNEXT(entry) = *bep;
  1197	     3470130    		if (!*bep)
  1198	     2688429    		    xhv->xhv_fill++; /* HvFILL(hv)++ */
  1199	     3470130    		*bep = entry;
  1200	     3470130    		right_length++;
  1201	     3470130    		continue;
  1202				    }
  1203				    else {
  1204	     3686890    		oentry = &HeNEXT(entry);
  1205	     3686890    		left_length++;
  1206				    }
  1207				}
  1208	     4489323    	if (!*aep)				/* everything moved */
  1209	     1577442    	    xhv->xhv_fill--; /* HvFILL(hv)-- */
  1210				/* I think we don't actually need to keep track of the longest length,
  1211				   merely flag if anything is too long. But for the moment while
  1212				   developing this code I'll track it.  */
  1213	     4489323    	if (left_length > longest_chain)
  1214	      328225    	    longest_chain = left_length;
  1215	     4489323    	if (right_length > longest_chain)
  1216	      180965    	    longest_chain = right_length;
  1217			    }
  1218			
  1219			
  1220			    /* Pick your policy for "hashing isn't working" here:  */
  1221	      258141        if (longest_chain <= HV_MAX_LENGTH_BEFORE_SPLIT /* split worked?  */
  1222				|| HvREHASH(hv)) {
  1223	           2    	return;
  1224			    }
  1225			
  1226	           2        if (hv == PL_strtab) {
  1227				/* Urg. Someone is doing something nasty to the string table.
  1228				   Can't win.  */
  1229	      ######    	return;
  1230			    }
  1231			
  1232			    /* Awooga. Awooga. Pathological data.  */
  1233			    /*PerlIO_printf(PerlIO_stderr(), "%p %d of %d with %d/%d buckets\n", hv,
  1234			      longest_chain, HvTOTALKEYS(hv), HvFILL(hv),  1+HvMAX(hv));*/
  1235			
  1236	           2        ++newsize;
  1237			    Newz(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
  1238	           2    	 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
  1239	           2        if (SvOOK(hv)) {
  1240	           1    	Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
  1241			    }
  1242			
  1243	           2        was_shared = HvSHAREKEYS(hv);
  1244			
  1245	           2        xhv->xhv_fill = 0;
  1246	           2        HvSHAREKEYS_off(hv);
  1247	           2        HvREHASH_on(hv);
  1248			
  1249	           2        aep = HvARRAY(hv);
  1250			
  1251	         290        for (i=0; i<newsize; i++,aep++) {
  1252	         288    	register HE *entry = *aep;
  1253	         399    	while (entry) {
  1254				    /* We're going to trash this HE's next pointer when we chain it
  1255				       into the new hash below, so store where we go next.  */
  1256	         111    	    HE * const next = HeNEXT(entry);
  1257	         111    	    UV hash;
  1258	         111    	    HE **bep;
  1259			
  1260				    /* Rehash it */
  1261	         111    	    PERL_HASH_INTERNAL(hash, HeKEY(entry), HeKLEN(entry));
  1262			
  1263	         111    	    if (was_shared) {
  1264					/* Unshare it.  */
  1265					HEK *new_hek
  1266	         111    		    = save_hek_flags(HeKEY(entry), HeKLEN(entry),
  1267	         111    				     hash, HeKFLAGS(entry));
  1268	         111    		unshare_hek (HeKEY_hek(entry));
  1269	         111    		HeKEY_hek(entry) = new_hek;
  1270				    } else {
  1271					/* Not shared, so simply write the new hash in. */
  1272	      ######    		HeHASH(entry) = hash;
  1273				    }
  1274				    /*PerlIO_printf(PerlIO_stderr(), "%d ", HeKFLAGS(entry));*/
  1275	         111    	    HEK_REHASH_on(HeKEY_hek(entry));
  1276				    /*PerlIO_printf(PerlIO_stderr(), "%d\n", HeKFLAGS(entry));*/
  1277			
  1278				    /* Copy oentry to the correct new chain.  */
  1279	         111    	    bep = ((HE**)a) + (hash & (I32) xhv->xhv_max);
  1280	         111    	    if (!*bep)
  1281	          99    		    xhv->xhv_fill++; /* HvFILL(hv)++ */
  1282	         111    	    HeNEXT(entry) = *bep;
  1283	         111    	    *bep = entry;
  1284			
  1285	         111    	    entry = next;
  1286				}
  1287			    }
  1288	           2        Safefree (HvARRAY(hv));
  1289	           2        HvARRAY(hv) = (HE **)a;
  1290			}
  1291			
  1292			void
  1293			Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
  1294	        4820    {
  1295	        4820        register XPVHV* xhv = (XPVHV*)SvANY(hv);
  1296	        4820        const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
  1297	        4820        register I32 newsize;
  1298	        4820        register I32 i;
  1299	        4820        register char *a;
  1300	        4820        register HE **aep;
  1301	        4820        register HE *entry;
  1302	        4820        register HE **oentry;
  1303			
  1304	        4820        newsize = (I32) newmax;			/* possible truncation here */
  1305	        4820        if (newsize != newmax || newmax <= oldsize)
  1306	        4540    	return;
  1307	        4623        while ((newsize & (1 + ~newsize)) != newsize) {
  1308	          83    	newsize &= ~(newsize & (1 + ~newsize));	/* get proper power of 2 */
  1309			    }
  1310	        4540        if (newsize < newmax)
  1311	          36    	newsize *= 2;
  1312	        4540        if (newsize < newmax)
  1313	      ######    	return;					/* overflow detection */
  1314			
  1315	        4540        a = (char *) HvARRAY(hv);
  1316	        4540        if (a) {
  1317	           2    	PL_nomemok = TRUE;
  1318			#if defined(STRANGE_MALLOC) || defined(MYMALLOC)
  1319				Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
  1320				      + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
  1321				if (!a) {
  1322				  PL_nomemok = FALSE;
  1323				  return;
  1324				}
  1325				if (SvOOK(hv)) {
  1326				    Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
  1327				}
  1328			#else
  1329				New(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
  1330	           2    	    + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
  1331	           2    	if (!a) {
  1332	      ######    	  PL_nomemok = FALSE;
  1333	      ######    	  return;
  1334				}
  1335	           2    	Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
  1336	           2    	if (SvOOK(hv)) {
  1337	           2    	    Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
  1338				}
  1339	           2    	if (oldsize >= 64) {
  1340	      ######    	    offer_nice_chunk(HvARRAY(hv),
  1341						     PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
  1342						     + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
  1343				}
  1344				else
  1345	           2    	    Safefree(HvARRAY(hv));
  1346			#endif
  1347	           2    	PL_nomemok = FALSE;
  1348	           2    	Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
  1349			    }
  1350			    else {
  1351	        4538    	Newz(0, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
  1352			    }
  1353	        4540        xhv->xhv_max = --newsize; 	/* HvMAX(hv) = --newsize */
  1354	        4540        HvARRAY(hv) = (HE **) a;
  1355	        4540        if (!xhv->xhv_fill /* !HvFILL(hv) */)	/* skip rest if no entries */
  1356	        4538    	return;
  1357			
  1358	           2        aep = (HE**)a;
  1359	          50        for (i=0; i<oldsize; i++,aep++) {
  1360	          48    	if (!*aep)				/* non-existent */
  1361	          20    	    continue;
  1362	          68    	for (oentry = aep, entry = *aep; entry; entry = *oentry) {
  1363	          40    	    register I32 j;
  1364	          40    	    if ((j = (HeHASH(entry) & newsize)) != i) {
  1365	          36    		j -= i;
  1366	          36    		*oentry = HeNEXT(entry);
  1367	          36    		if (!(HeNEXT(entry) = aep[j]))
  1368	          35    		    xhv->xhv_fill++; /* HvFILL(hv)++ */
  1369	          36    		aep[j] = entry;
  1370	          36    		continue;
  1371				    }
  1372				    else
  1373	           4    		oentry = &HeNEXT(entry);
  1374				}
  1375	          28    	if (!*aep)				/* everything moved */
  1376	          24    	    xhv->xhv_fill--; /* HvFILL(hv)-- */
  1377			    }
  1378			}
  1379			
  1380			/*
  1381			=for apidoc newHV
  1382			
  1383			Creates a new HV.  The reference count is set to 1.
  1384			
  1385			=cut
  1386			*/
  1387			
  1388			HV *
  1389			Perl_newHV(pTHX)
  1390	     1284945    {
  1391	     1284945        register XPVHV* xhv;
  1392	     1284945        HV * const hv = (HV*)NEWSV(502,0);
  1393			
  1394	     1284945        sv_upgrade((SV *)hv, SVt_PVHV);
  1395	     1284945        xhv = (XPVHV*)SvANY(hv);
  1396	     1284945        SvPOK_off(hv);
  1397	     1284945        SvNOK_off(hv);
  1398			#ifndef NODEFAULT_SHAREKEYS
  1399	     1284945        HvSHAREKEYS_on(hv);         /* key-sharing on by default */
  1400			#endif
  1401			
  1402	     1284945        xhv->xhv_max    = 7;	/* HvMAX(hv) = 7 (start with 8 buckets) */
  1403	     1284945        xhv->xhv_fill   = 0;	/* HvFILL(hv) = 0 */
  1404	     1284945        return hv;
  1405			}
  1406			
  1407			HV *
  1408			Perl_newHVhv(pTHX_ HV *ohv)
  1409	         331    {
  1410	         331        HV * const hv = newHV();
  1411	         331        STRLEN hv_max, hv_fill;
  1412			
  1413	         331        if (!ohv || (hv_fill = HvFILL(ohv)) == 0)
  1414	          25    	return hv;
  1415	         306        hv_max = HvMAX(ohv);
  1416			
  1417	         306        if (!SvMAGICAL((SV *)ohv)) {
  1418				/* It's an ordinary hash, so copy it fast. AMS 20010804 */
  1419	         306    	STRLEN i;
  1420	         306    	const bool shared = !!HvSHAREKEYS(ohv);
  1421	         306    	HE **ents, **oents = (HE **)HvARRAY(ohv);
  1422	         306    	char *a;
  1423	         306    	New(0, a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
  1424	         306    	ents = (HE**)a;
  1425			
  1426				/* In each bucket... */
  1427	        2754    	for (i = 0; i <= hv_max; i++) {
  1428	        2448    	    HE *prev = NULL, *ent = NULL, *oent = oents[i];
  1429			
  1430	        2448    	    if (!oent) {
  1431	        1823    		ents[i] = NULL;
  1432	        1823    		continue;
  1433				    }
  1434			
  1435				    /* Copy the linked list of entries. */
  1436	        1626    	    for (oent = oents[i]; oent; oent = HeNEXT(oent)) {
  1437	        1001    		const U32 hash   = HeHASH(oent);
  1438	        1001    		const char * const key = HeKEY(oent);
  1439	        1001    		const STRLEN len = HeKLEN(oent);
  1440	        1001    		const int flags  = HeKFLAGS(oent);
  1441			
  1442	        1001    		ent = new_HE();
  1443	        1001    		HeVAL(ent)     = newSVsv(HeVAL(oent));
  1444	        1001    		HeKEY_hek(ent)
  1445			                    = shared ? share_hek_flags(key, len, hash, flags)
  1446			                             :  save_hek_flags(key, len, hash, flags);
  1447	        1001    		if (prev)
  1448	         376    		    HeNEXT(prev) = ent;
  1449					else
  1450	         625    		    ents[i] = ent;
  1451	        1001    		prev = ent;
  1452	        1001    		HeNEXT(ent) = NULL;
  1453				    }
  1454				}
  1455			
  1456	         306    	HvMAX(hv)   = hv_max;
  1457	         306    	HvFILL(hv)  = hv_fill;
  1458	         306    	HvTOTALKEYS(hv)  = HvTOTALKEYS(ohv);
  1459	         306    	HvARRAY(hv) = ents;
  1460			    }
  1461			    else {
  1462				/* Iterate over ohv, copying keys and values one at a time. */
  1463	      ######    	HE *entry;
  1464	      ######    	const I32 riter = HvRITER_get(ohv);
  1465	      ######    	HE * const eiter = HvEITER_get(ohv);
  1466			
  1467				/* Can we use fewer buckets? (hv_max is always 2^n-1) */
  1468	      ######    	while (hv_max && hv_max + 1 >= hv_fill * 2)
  1469	      ######    	    hv_max = hv_max / 2;
  1470	      ######    	HvMAX(hv) = hv_max;
  1471			
  1472	      ######    	hv_iterinit(ohv);
  1473	      ######    	while ((entry = hv_iternext_flags(ohv, 0))) {
  1474	      ######    	    hv_store_flags(hv, HeKEY(entry), HeKLEN(entry),
  1475			                           newSVsv(HeVAL(entry)), HeHASH(entry),
  1476			                           HeKFLAGS(entry));
  1477				}
  1478	      ######    	HvRITER_set(ohv, riter);
  1479	      ######    	HvEITER_set(ohv, eiter);
  1480			    }
  1481			
  1482	         306        return hv;
  1483			}
  1484			
  1485			void
  1486			Perl_hv_free_ent(pTHX_ HV *hv, register HE *entry)
  1487	     6656565    {
  1488	     6656565        SV *val;
  1489			
  1490	     6656565        if (!entry)
  1491	      ######    	return;
  1492	     6656565        val = HeVAL(entry);
  1493	     6656565        if (val && isGV(val) && GvCVu(val) && HvNAME_get(hv))
  1494	           5    	PL_sub_generation++;	/* may be deletion of method from stash */
  1495	     6656565        SvREFCNT_dec(val);
  1496	     6656565        if (HeKLEN(entry) == HEf_SVKEY) {
  1497	      ######    	SvREFCNT_dec(HeKEY_sv(entry));
  1498	      ######    	Safefree(HeKEY_hek(entry));
  1499			    }
  1500	     6656565        else if (HvSHAREKEYS(hv))
  1501	     6624098    	unshare_hek(HeKEY_hek(entry));
  1502			    else
  1503	       32467    	Safefree(HeKEY_hek(entry));
  1504	     6656565        del_HE(entry);
  1505			}
  1506			
  1507			void
  1508			Perl_hv_delayfree_ent(pTHX_ HV *hv, register HE *entry)
  1509	      ######    {
  1510	      ######        if (!entry)
  1511	      ######    	return;
  1512	      ######        if (isGV(HeVAL(entry)) && GvCVu(HeVAL(entry)) && HvNAME_get(hv))
  1513	      ######    	PL_sub_generation++;	/* may be deletion of method from stash */
  1514	      ######        sv_2mortal(HeVAL(entry));	/* free between statements */
  1515	      ######        if (HeKLEN(entry) == HEf_SVKEY) {
  1516	      ######    	sv_2mortal(HeKEY_sv(entry));
  1517	      ######    	Safefree(HeKEY_hek(entry));
  1518			    }
  1519	      ######        else if (HvSHAREKEYS(hv))
  1520	      ######    	unshare_hek(HeKEY_hek(entry));
  1521			    else
  1522	      ######    	Safefree(HeKEY_hek(entry));
  1523	      ######        del_HE(entry);
  1524			}
  1525			
  1526			/*
  1527			=for apidoc hv_clear
  1528			
  1529			Clears a hash, making it empty.
  1530			
  1531			=cut
  1532			*/
  1533			
  1534			void
  1535			Perl_hv_clear(pTHX_ HV *hv)
  1536	      244430    {
  1537			    dVAR;
  1538	      244430        register XPVHV* xhv;
  1539	      244430        if (!hv)
  1540	      ######    	return;
  1541			
  1542	      244430        DEBUG_A(Perl_hv_assert(aTHX_ hv));
  1543			
  1544	      244430        xhv = (XPVHV*)SvANY(hv);
  1545			
  1546	      244430        if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
  1547				/* restricted hash: convert all keys to placeholders */
  1548	           6    	STRLEN i;
  1549	          52    	for (i = 0; i <= xhv->xhv_max; i++) {
  1550	          47    	    HE *entry = (HvARRAY(hv))[i];
  1551	          65    	    for (; entry; entry = HeNEXT(entry)) {
  1552					/* not already placeholder */
  1553	          10    		if (HeVAL(entry) != &PL_sv_placeholder) {
  1554	           7    		    if (HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
  1555	           1    			SV* keysv = hv_iterkeysv(entry);
  1556	           1    			Perl_croak(aTHX_
  1557				"Attempt to delete readonly key '%"SVf"' from a restricted hash",
  1558							   keysv);
  1559					    }
  1560	           6    		    SvREFCNT_dec(HeVAL(entry));
  1561	           6    		    HeVAL(entry) = &PL_sv_placeholder;
  1562	           6    		    HvPLACEHOLDERS(hv)++;
  1563					}
  1564				    }
  1565				}
  1566	      244424    	goto reset;
  1567			    }
  1568			
  1569	      244424        hfreeentries(hv);
  1570	      244424        HvPLACEHOLDERS_set(hv, 0);
  1571	      244424        if (HvARRAY(hv))
  1572	      185902    	(void)memzero(HvARRAY(hv),
  1573					      (xhv->xhv_max+1 /* HvMAX(hv)+1 */) * sizeof(HE*));
  1574			
  1575	      244424        if (SvRMAGICAL(hv))
  1576	         386    	mg_clear((SV*)hv);
  1577			
  1578	      244423        HvHASKFLAGS_off(hv);
  1579	      244423        HvREHASH_off(hv);
  1580			    reset:
  1581	      244428        if (SvOOK(hv)) {
  1582	       93381    	HvEITER_set(hv, NULL);
  1583			    }
  1584			}
  1585			
  1586			/*
  1587			=for apidoc hv_clear_placeholders
  1588			
  1589			Clears any placeholders from a hash.  If a restricted hash has any of its keys
  1590			marked as readonly and the key is subsequently deleted, the key is not actually
  1591			deleted but is marked by assigning it a value of &PL_sv_placeholder.  This tags
  1592			it so it will be ignored by future operations such as iterating over the hash,
  1593			but will still allow the hash to have a value reassigned to the key at some
  1594			future point.  This function clears any such placeholder keys from the hash.
  1595			See Hash::Util::lock_keys() for an example of its use.
  1596			
  1597			=cut
  1598			*/
  1599			
  1600			void
  1601			Perl_hv_clear_placeholders(pTHX_ HV *hv)
  1602	          34    {
  1603			    dVAR;
  1604	          34        I32 items = (I32)HvPLACEHOLDERS_get(hv);
  1605	          34        I32 i;
  1606			
  1607	          34        if (items == 0)
  1608	          32    	return;
  1609			
  1610	           2        i = HvMAX(hv);
  1611	          12        do {
  1612				/* Loop down the linked list heads  */
  1613	          12    	bool first = 1;
  1614	          12    	HE **oentry = &(HvARRAY(hv))[i];
  1615	          12    	HE *entry = *oentry;
  1616			
  1617	          12    	if (!entry)
  1618	           8    	    continue;
  1619			
  1620	           8    	for (; entry; entry = *oentry) {
  1621	           4    	    if (HeVAL(entry) == &PL_sv_placeholder) {
  1622	           2    		*oentry = HeNEXT(entry);
  1623	           2    		if (first && !*oentry)
  1624	           2    		    HvFILL(hv)--; /* This linked list is now empty.  */
  1625	           2    		if (HvEITER_get(hv))
  1626	      ######    		    HvLAZYDEL_on(hv);
  1627					else
  1628	           2    		    hv_free_ent(hv, entry);
  1629			
  1630	           2    		if (--items == 0) {
  1631					    /* Finished.  */
  1632	           2    		    HvTOTALKEYS(hv) -= (IV)HvPLACEHOLDERS_get(hv);
  1633	           2    		    if (HvKEYS(hv) == 0)
  1634	      ######    			HvHASKFLAGS_off(hv);
  1635	           2    		    HvPLACEHOLDERS_set(hv, 0);
  1636	           2    		    return;
  1637					}
  1638				    } else {
  1639	           2    		oentry = &HeNEXT(entry);
  1640	           2    		first = 0;
  1641				    }
  1642				}
  1643	          10        } while (--i >= 0);
  1644			    /* You can't get here, hence assertion should always fail.  */
  1645	      ######        assert (items == 0);
  1646	      ######        assert (0);
  1647			}
  1648			
  1649			STATIC void
  1650			S_hfreeentries(pTHX_ HV *hv)
  1651	     1560856    {
  1652	     1560856        register HE **array;
  1653	     1560856        register HE *entry;
  1654	     1560856        I32 riter;
  1655	     1560856        I32 max;
  1656	     1560856        struct xpvhv_aux *iter;
  1657	     1560856        if (!hv)
  1658	      ######    	return;
  1659	     1560856        if (!HvARRAY(hv))
  1660	      685934    	return;
  1661			
  1662	      874922        iter =  SvOOK(hv) ? HvAUX(hv) : 0;
  1663			
  1664	      874922        riter = 0;
  1665	      874922        max = HvMAX(hv);
  1666	      874922        array = HvARRAY(hv);
  1667			    /* make everyone else think the array is empty, so that the destructors
  1668			     * called for freed entries can't recusively mess with us */
  1669	      874922        HvARRAY(hv) = Null(HE**); 
  1670	      874922        SvFLAGS(hv) &= ~SVf_OOK;
  1671			
  1672	      874922        HvFILL(hv) = 0;
  1673	      874922        ((XPVHV*) SvANY(hv))->xhv_keys = 0;
  1674			
  1675	      874922        entry = array[0];
  1676	    51082946        for (;;) {
  1677	    26748148    	if (entry) {
  1678	     6544998    	    register HE *oentry = entry;
  1679	     6544998    	    entry = HeNEXT(entry);
  1680	     6544998    	    hv_free_ent(hv, oentry);
  1681				}
  1682	    26748148    	if (!entry) {
  1683	    25209720    	    if (++riter > max)
  1684	      874922    		break;
  1685	    24334798    	    entry = array[riter];
  1686				}
  1687			    }
  1688			
  1689	      874922        if (SvOOK(hv)) {
  1690				/* Someone attempted to iterate or set the hash name while we had
  1691				   the array set to 0.  */
  1692	           1    	assert(HvARRAY(hv));
  1693			
  1694	           1    	if (HvAUX(hv)->xhv_name)
  1695	      ######    	    unshare_hek_or_pvn(HvAUX(hv)->xhv_name, 0, 0, 0);
  1696				/* SvOOK_off calls sv_backoff, which isn't correct.  */
  1697			
  1698	           1    	Safefree(HvARRAY(hv));
  1699	           1    	HvARRAY(hv) = 0;
  1700	           1    	SvFLAGS(hv) &= ~SVf_OOK;
  1701			    }
  1702			
  1703			    /* FIXME - things will still go horribly wrong (or at least leak) if
  1704			       people attempt to add elements to the hash while we're undef()ing it  */
  1705	      874922        if (iter) {
  1706	      282633    	entry = iter->xhv_eiter; /* HvEITER(hv) */
  1707	      282633    	if (entry && HvLAZYDEL(hv)) {	/* was deleted earlier? */
  1708	      ######    	    HvLAZYDEL_off(hv);
  1709	      ######    	    hv_free_ent(hv, entry);
  1710				}
  1711	      282633    	iter->xhv_riter = -1; 	/* HvRITER(hv) = -1 */
  1712	      282633    	iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
  1713	      282633    	SvFLAGS(hv) |= SVf_OOK;
  1714			    }
  1715			
  1716	      874922        HvARRAY(hv) = array;
  1717			}
  1718			
  1719			/*
  1720			=for apidoc hv_undef
  1721			
  1722			Undefines the hash.
  1723			
  1724			=cut
  1725			*/
  1726			
  1727			void
  1728			Perl_hv_undef(pTHX_ HV *hv)
  1729	     1316432    {
  1730	     1316432        register XPVHV* xhv;
  1731	     1316432        const char *name;
  1732	     1316432        if (!hv)
  1733	      ######    	return;
  1734	     1316432        DEBUG_A(Perl_hv_assert(aTHX_ hv));
  1735	     1316432        xhv = (XPVHV*)SvANY(hv);
  1736	     1316432        hfreeentries(hv);
  1737	     1316432        if ((name = HvNAME_get(hv))) {
  1738	      142179            if(PL_stashcache)
  1739	        5148    	    hv_delete(PL_stashcache, name, HvNAMELEN_get(hv), G_DISCARD);
  1740	      142179    	Perl_hv_name_set(aTHX_ hv, 0, 0, 0);
  1741			    }
  1742	     1316432        SvFLAGS(hv) &= ~SVf_OOK;
  1743	     1316432        Safefree(HvARRAY(hv));
  1744	     1316432        xhv->xhv_max   = 7;	/* HvMAX(hv) = 7 (it's a normal hash) */
  1745	     1316432        HvARRAY(hv) = 0;
  1746	     1316432        HvPLACEHOLDERS_set(hv, 0);
  1747			
  1748	     1316432        if (SvRMAGICAL(hv))
  1749	      131957    	mg_clear((SV*)hv);
  1750			}
  1751			
  1752			static struct xpvhv_aux*
  1753	      188251    S_hv_auxinit(pTHX_ HV *hv) {
  1754	      188251        struct xpvhv_aux *iter;
  1755	      188251        char *array;
  1756			
  1757	      188251        if (!HvARRAY(hv)) {
  1758				Newz(0, array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
  1759	      148592    	    + sizeof(struct xpvhv_aux), char);
  1760			    } else {
  1761	       39659    	array = (char *) HvARRAY(hv);
  1762				Renew(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
  1763	       39659    	      + sizeof(struct xpvhv_aux), char);
  1764			    }
  1765	      188251        HvARRAY(hv) = (HE**) array;
  1766			    /* SvOOK_on(hv) attacks the IV flags.  */
  1767	      188251        SvFLAGS(hv) |= SVf_OOK;
  1768	      188251        iter = HvAUX(hv);
  1769			
  1770	      188251        iter->xhv_riter = -1; 	/* HvRITER(hv) = -1 */
  1771	      188251        iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
  1772	      188251        iter->xhv_name = 0;
  1773			
  1774	      188251        return iter;
  1775			}
  1776			
  1777			/*
  1778			=for apidoc hv_iterinit
  1779			
  1780			Prepares a starting point to traverse a hash table.  Returns the number of
  1781			keys in the hash (i.e. the same as C<HvKEYS(tb)>).  The return value is
  1782			currently only meaningful for hashes without tie magic.
  1783			
  1784			NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
  1785			hash buckets that happen to be in use.  If you still need that esoteric
  1786			value, you can get it through the macro C<HvFILL(tb)>.
  1787			
  1788			
  1789			=cut
  1790			*/
  1791			
  1792			I32
  1793			Perl_hv_iterinit(pTHX_ HV *hv)
  1794	      166441    {
  1795	      166441        HE *entry;
  1796			
  1797	      166441        if (!hv)
  1798	      ######    	Perl_croak(aTHX_ "Bad hash");
  1799			
  1800	      166441        if (SvOOK(hv)) {
  1801	      119382    	struct xpvhv_aux *iter = HvAUX(hv);
  1802	      119382    	entry = iter->xhv_eiter; /* HvEITER(hv) */
  1803	      119382    	if (entry && HvLAZYDEL(hv)) {	/* was deleted earlier? */
  1804	      ######    	    HvLAZYDEL_off(hv);
  1805	      ######    	    hv_free_ent(hv, entry);
  1806				}
  1807	      119382    	iter->xhv_riter = -1; 	/* HvRITER(hv) = -1 */
  1808	      119382    	iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
  1809			    } else {
  1810	       47059    	S_hv_auxinit(aTHX_ hv);
  1811			    }
  1812			
  1813			    /* used to be xhv->xhv_fill before 5.004_65 */
  1814	      166441        return HvTOTALKEYS(hv);
  1815			}
  1816			
  1817			I32 *
  1818	           8    Perl_hv_riter_p(pTHX_ HV *hv) {
  1819	           8        struct xpvhv_aux *iter;
  1820			
  1821	           8        if (!hv)
  1822	      ######    	Perl_croak(aTHX_ "Bad hash");
  1823			
  1824	           8        iter = SvOOK(hv) ? HvAUX(hv) : S_hv_auxinit(aTHX_ hv);
  1825	           8        return &(iter->xhv_riter);
  1826			}
  1827			
  1828			HE **
  1829	      ######    Perl_hv_eiter_p(pTHX_ HV *hv) {
  1830	      ######        struct xpvhv_aux *iter;
  1831			
  1832	      ######        if (!hv)
  1833	      ######    	Perl_croak(aTHX_ "Bad hash");
  1834			
  1835	      ######        iter = SvOOK(hv) ? HvAUX(hv) : S_hv_auxinit(aTHX_ hv);
  1836	      ######        return &(iter->xhv_eiter);
  1837			}
  1838			
  1839			void
  1840	        1023    Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
  1841	        1023        struct xpvhv_aux *iter;
  1842			
  1843	        1023        if (!hv)
  1844	      ######    	Perl_croak(aTHX_ "Bad hash");
  1845			
  1846	        1023        if (SvOOK(hv)) {
  1847	        1023    	iter = HvAUX(hv);
  1848			    } else {
  1849	      ######    	if (riter == -1)
  1850	      ######    	    return;
  1851			
  1852	      ######    	iter = S_hv_auxinit(aTHX_ hv);
  1853			    }
  1854	        1023        iter->xhv_riter = riter;
  1855			}
  1856			
  1857			void
  1858	       96244    Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
  1859	       96244        struct xpvhv_aux *iter;
  1860			
  1861	       96244        if (!hv)
  1862	      ######    	Perl_croak(aTHX_ "Bad hash");
  1863			
  1864	       96244        if (SvOOK(hv)) {
  1865	       94448    	iter = HvAUX(hv);
  1866			    } else {
  1867				/* 0 is the default so don't go malloc()ing a new structure just to
  1868				   hold 0.  */
  1869	        1796    	if (!eiter)
  1870	        1796    	    return;
  1871			
  1872	      ######    	iter = S_hv_auxinit(aTHX_ hv);
  1873			    }
  1874	       94448        iter->xhv_eiter = eiter;
  1875			}
  1876			
  1877			void
  1878			Perl_hv_name_set(pTHX_ HV *hv, const char *name, I32 len, int flags)
  1879	      283693    {
  1880	      283693        struct xpvhv_aux *iter;
  1881	      283693        U32 hash;
  1882	      283693        (void)flags;
  1883			
  1884	      283693        if (SvOOK(hv)) {
  1885	      142508    	iter = HvAUX(hv);
  1886	      142508    	if (iter->xhv_name) {
  1887	      142508    	    unshare_hek_or_pvn(iter->xhv_name, 0, 0, 0);
  1888				}
  1889			    } else {
  1890	      141185    	if (name == 0)
  1891	      ######    	    return;
  1892			
  1893	      141185    	iter = S_hv_auxinit(aTHX_ hv);
  1894			    }
  1895	      283693        PERL_HASH(hash, name, len);
  1896	      283693        iter->xhv_name = name ? share_hek(name, len, hash) : 0;
  1897			}
  1898			
  1899			/*
  1900			=for apidoc hv_iternext
  1901			
  1902			Returns entries from a hash iterator.  See C<hv_iterinit>.
  1903			
  1904			You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
  1905			iterator currently points to, without losing your place or invalidating your
  1906			iterator.  Note that in this case the current entry is deleted from the hash
  1907			with your iterator holding the last reference to it.  Your iterator is flagged
  1908			to free the entry on the next call to C<hv_iternext>, so you must not discard
  1909			your iterator immediately else the entry will leak - call C<hv_iternext> to
  1910			trigger the resource deallocation.
  1911			
  1912			=cut
  1913			*/
  1914			
  1915			HE *
  1916			Perl_hv_iternext(pTHX_ HV *hv)
  1917	     2528177    {
  1918	     2528177        return hv_iternext_flags(hv, 0);
  1919			}
  1920			
  1921			/*
  1922			=for apidoc hv_iternext_flags
  1923			
  1924			Returns entries from a hash iterator.  See C<hv_iterinit> and C<hv_iternext>.
  1925			The C<flags> value will normally be zero; if HV_ITERNEXT_WANTPLACEHOLDERS is
  1926			set the placeholders keys (for restricted hashes) will be returned in addition
  1927			to normal keys. By default placeholders are automatically skipped over.
  1928			Currently a placeholder is implemented with a value that is
  1929			C<&Perl_sv_placeholder>. Note that the implementation of placeholders and
  1930			restricted hashes may change, and the implementation currently is
  1931			insufficiently abstracted for any change to be tidy.
  1932			
  1933			=cut
  1934			*/
  1935			
  1936			HE *
  1937			Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
  1938	     2558185    {
  1939			    dVAR;
  1940	     2558185        register XPVHV* xhv;
  1941	     2558185        register HE *entry;
  1942	     2558185        HE *oldentry;
  1943	     2558185        MAGIC* mg;
  1944	     2558185        struct xpvhv_aux *iter;
  1945			
  1946	     2558185        if (!hv)
  1947	      ######    	Perl_croak(aTHX_ "Bad hash");
  1948	     2558185        xhv = (XPVHV*)SvANY(hv);
  1949			
  1950	     2558185        if (!SvOOK(hv)) {
  1951				/* Too many things (well, pp_each at least) merrily assume that you can
  1952				   call iv_iternext without calling hv_iterinit, so we'll have to deal
  1953				   with it.  */
  1954	         716    	hv_iterinit(hv);
  1955			    }
  1956	     2558185        iter = HvAUX(hv);
  1957			
  1958	     2558185        oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
  1959			
  1960	     2558185        if ((mg = SvTIED_mg((SV*)hv, PERL_MAGIC_tied))) {
  1961	      107958    	SV *key = sv_newmortal();
  1962	      107958    	if (entry) {
  1963	      107098    	    sv_setsv(key, HeSVKEY_force(entry));
  1964	      107098    	    SvREFCNT_dec(HeSVKEY(entry));	/* get rid of previous key */
  1965				}
  1966				else {
  1967	         860    	    char *k;
  1968	         860    	    HEK *hek;
  1969			
  1970				    /* one HE per MAGICAL hash */
  1971	         860    	    iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
  1972	         860    	    Zero(entry, 1, HE);
  1973	         860    	    Newz(54, k, HEK_BASESIZE + sizeof(SV*), char);
  1974	         860    	    hek = (HEK*)k;
  1975	         860    	    HeKEY_hek(entry) = hek;
  1976	         860    	    HeKLEN(entry) = HEf_SVKEY;
  1977				}
  1978	      107958    	magic_nextpack((SV*) hv,mg,key);
  1979	      107958    	if (SvOK(key)) {
  1980				    /* force key to stay around until next time */
  1981	      107100    	    HeSVKEY_set(entry, SvREFCNT_inc(key));
  1982	      107100    	    return entry;		/* beware, hent_val is not set */
  1983				}
  1984	         858    	if (HeVAL(entry))
  1985	      ######    	    SvREFCNT_dec(HeVAL(entry));
  1986	         858    	Safefree(HeKEY_hek(entry));
  1987	         858    	del_HE(entry);
  1988	         858    	iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
  1989	         858    	return Null(HE*);
  1990			    }
  1991			#ifdef DYNAMIC_ENV_FETCH  /* set up %ENV for iteration */
  1992			    if (!entry && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
  1993				prime_env_iter();
  1994			#endif
  1995			
  1996			    /* hv_iterint now ensures this.  */
  1997	     2450227        assert (HvARRAY(hv));
  1998			
  1999			    /* At start of hash, entry is NULL.  */
  2000	     2450227        if (entry)
  2001			    {
  2002	     2283865    	entry = HeNEXT(entry);
  2003	     2283865            if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
  2004			            /*
  2005			             * Skip past any placeholders -- don't want to include them in
  2006			             * any iteration.
  2007			             */
  2008	     2274255                while (entry && HeVAL(entry) == &PL_sv_placeholder) {
  2009	           8                    entry = HeNEXT(entry);
  2010			            }
  2011				}
  2012			    }
  2013	    11431341        while (!entry) {
  2014				/* OK. Come to the end of the current list.  Grab the next one.  */
  2015			
  2016	     9146369    	iter->xhv_riter++; /* HvRITER(hv)++ */
  2017	     9146369    	if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
  2018				    /* There is no next one.  End of the hash.  */
  2019	      165255    	    iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
  2020	      165255    	    break;
  2021				}
  2022	     8981114    	entry = (HvARRAY(hv))[iter->xhv_riter];
  2023			
  2024	     8981114            if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
  2025			            /* If we have an entry, but it's a placeholder, don't count it.
  2026				       Try the next.  */
  2027	     8962830    	    while (entry && HeVAL(entry) == &PL_sv_placeholder)
  2028	          64    		entry = HeNEXT(entry);
  2029				}
  2030				/* Will loop again if this linked list starts NULL
  2031				   (for HV_ITERNEXT_WANTPLACEHOLDERS)
  2032				   or if we run through it and find only placeholders.  */
  2033			    }
  2034			
  2035	     2450227        if (oldentry && HvLAZYDEL(hv)) {		/* was deleted earlier? */
  2036	          10    	HvLAZYDEL_off(hv);
  2037	          10    	hv_free_ent(hv, oldentry);
  2038			    }
  2039			
  2040			    /*if (HvREHASH(hv) && entry && !HeKREHASH(entry))
  2041			      PerlIO_printf(PerlIO_stderr(), "Awooga %p %p\n", hv, entry);*/
  2042			
  2043	     2450227        iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
  2044	     2450227        return entry;
  2045			}
  2046			
  2047			/*
  2048			=for apidoc hv_iterkey
  2049			
  2050			Returns the key from the current position of the hash iterator.  See
  2051			C<hv_iterinit>.
  2052			
  2053			=cut
  2054			*/
  2055			
  2056			char *
  2057			Perl_hv_iterkey(pTHX_ register HE *entry, I32 *retlen)
  2058	       19053    {
  2059	       19053        if (HeKLEN(entry) == HEf_SVKEY) {
  2060	      ######    	STRLEN len;
  2061	      ######    	char *p = SvPV(HeKEY_sv(entry), len);
  2062	      ######    	*retlen = len;
  2063	      ######    	return p;
  2064			    }
  2065			    else {
  2066	       19053    	*retlen = HeKLEN(entry);
  2067	       19053    	return HeKEY(entry);
  2068			    }
  2069			}
  2070			
  2071			/* unlike hv_iterval(), this always returns a mortal copy of the key */
  2072			/*
  2073			=for apidoc hv_iterkeysv
  2074			
  2075			Returns the key as an C<SV*> from the current position of the hash
  2076			iterator.  The return value will always be a mortal copy of the key.  Also
  2077			see C<hv_iterinit>.
  2078			
  2079			=cut
  2080			*/
  2081			
  2082			SV *
  2083			Perl_hv_iterkeysv(pTHX_ register HE *entry)
  2084	     2300755    {
  2085	     2300755        return sv_2mortal(newSVhek(HeKEY_hek(entry)));
  2086			}
  2087			
  2088			/*
  2089			=for apidoc hv_iterval
  2090			
  2091			Returns the value from the current position of the hash iterator.  See
  2092			C<hv_iterkey>.
  2093			
  2094			=cut
  2095			*/
  2096			
  2097			SV *
  2098			Perl_hv_iterval(pTHX_ HV *hv, register HE *entry)
  2099	      343754    {
  2100	      343754        if (SvRMAGICAL(hv)) {
  2101	      129967    	if (mg_find((SV*)hv, PERL_MAGIC_tied)) {
  2102	      105439    	    SV* sv = sv_newmortal();
  2103	      105439    	    if (HeKLEN(entry) == HEf_SVKEY)
  2104	      105439    		mg_copy((SV*)hv, sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
  2105				    else
  2106	      ######    		mg_copy((SV*)hv, sv, HeKEY(entry), HeKLEN(entry));
  2107	      105439    	    return sv;
  2108				}
  2109			    }
  2110	      238315        return HeVAL(entry);
  2111			}
  2112			
  2113			/*
  2114			=for apidoc hv_iternextsv
  2115			
  2116			Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
  2117			operation.
  2118			
  2119			=cut
  2120			*/
  2121			
  2122			SV *
  2123			Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
  2124	       19380    {
  2125	       19380        HE *he;
  2126	       19380        if ( (he = hv_iternext_flags(hv, 0)) == NULL)
  2127	        1163    	return NULL;
  2128	       18217        *key = hv_iterkey(he, retlen);
  2129	       18217        return hv_iterval(hv, he);
  2130			}
  2131			
  2132			/*
  2133			=for apidoc hv_magic
  2134			
  2135			Adds magic to a hash.  See C<sv_magic>.
  2136			
  2137			=cut
  2138			*/
  2139			
  2140			void
  2141			Perl_hv_magic(pTHX_ HV *hv, GV *gv, int how)
  2142	        7173    {
  2143	        7173        sv_magic((SV*)hv, (SV*)gv, how, Nullch, 0);
  2144			}
  2145			
  2146			#if 0 /* use the macro from hv.h instead */
  2147			
  2148			char*	
  2149			Perl_sharepvn(pTHX_ const char *sv, I32 len, U32 hash)
  2150			{
  2151			    return HEK_KEY(share_hek(sv, len, hash));
  2152			}
  2153			
  2154			#endif
  2155			
  2156			/* possibly free a shared string if no one has access to it
  2157			 * len and hash must both be valid for str.
  2158			 */
  2159			void
  2160			Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
  2161	      ######    {
  2162	      ######        unshare_hek_or_pvn (NULL, str, len, hash);
  2163			}
  2164			
  2165			
  2166			void
  2167			Perl_unshare_hek(pTHX_ HEK *hek)
  2168	    10101144    {
  2169	    10101144        unshare_hek_or_pvn(hek, NULL, 0, 0);
  2170			}
  2171			
  2172			/* possibly free a shared string if no one has access to it
  2173			   hek if non-NULL takes priority over the other 3, else str, len and hash
  2174			   are used.  If so, len and hash must both be valid for str.
  2175			 */
  2176			STATIC void
  2177			S_unshare_hek_or_pvn(pTHX_ const HEK *hek, const char *str, I32 len, U32 hash)
  2178	    10243652    {
  2179	    10243652        register XPVHV* xhv;
  2180	    10243652        register HE *entry;
  2181	    10243652        register HE **oentry;
  2182	    10243652        HE **first;
  2183	    10243652        bool found = 0;
  2184	    10243652        bool is_utf8 = FALSE;
  2185	    10243652        int k_flags = 0;
  2186	    10243652        const char *save = str;
  2187	    10243652        struct shared_he *he = 0;
  2188			
  2189	    10243652        if (hek) {
  2190				/* Find the shared he which is just before us in memory.  */
  2191	    10243652    	he = (struct shared_he *)(((char *)hek)
  2192							  - STRUCT_OFFSET(struct shared_he,
  2193									  shared_he_hek));
  2194			
  2195				/* Assert that the caller passed us a genuine (or at least consistent)
  2196				   shared hek  */
  2197	    10243652    	assert (he->shared_he_he.hent_hek == hek);
  2198			
  2199				LOCK_STRTAB_MUTEX;
  2200	    10243652    	if (he->shared_he_he.hent_val - 1) {
  2201	     7693329    	    --he->shared_he_he.hent_val;
  2202				    UNLOCK_STRTAB_MUTEX;
  2203	     7693329    	    return;
  2204				}
  2205				UNLOCK_STRTAB_MUTEX;
  2206			
  2207	     2550323            hash = HEK_HASH(hek);
  2208	      ######        } else if (len < 0) {
  2209	      ######            STRLEN tmplen = -len;
  2210	      ######            is_utf8 = TRUE;
  2211			        /* See the note in hv_fetch(). --jhi */
  2212	      ######            str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
  2213	      ######            len = tmplen;
  2214	      ######            if (is_utf8)
  2215	      ######                k_flags = HVhek_UTF8;
  2216	      ######            if (str != save)
  2217	      ######                k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
  2218			    }
  2219			
  2220			    /* what follows is the moral equivalent of:
  2221			    if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
  2222				if (--*Svp == Nullsv)
  2223				    hv_delete(PL_strtab, str, len, G_DISCARD, hash);
  2224			    } */
  2225	     2550323        xhv = (XPVHV*)SvANY(PL_strtab);
  2226			    /* assert(xhv_array != 0) */
  2227			    LOCK_STRTAB_MUTEX;
  2228	     2550323        first = oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
  2229	     2550323        if (he) {
  2230	     2550323    	const HE *const he_he = &(he->shared_he_he);
  2231	     2803210            for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
  2232	     2803210                if (entry != he_he)
  2233	      252887                    continue;
  2234	     2550323                found = 1;
  2235	     2550323                break;
  2236			        }
  2237			    } else {
  2238	      ######            const int flags_masked = k_flags & HVhek_MASK;
  2239	      ######            for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
  2240	      ######                if (HeHASH(entry) != hash)		/* strings can't be equal */
  2241	      ######                    continue;
  2242	      ######                if (HeKLEN(entry) != len)
  2243	      ######                    continue;
  2244	      ######                if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len))	/* is this it? */
  2245	      ######                    continue;
  2246	      ######                if (HeKFLAGS(entry) != flags_masked)
  2247	      ######                    continue;
  2248	      ######                found = 1;
  2249	      ######                break;
  2250			        }
  2251			    }
  2252			
  2253	     2550323        if (found) {
  2254	     2550323            if (--HeVAL(entry) == Nullsv) {
  2255	     2550323                *oentry = HeNEXT(entry);
  2256	     2550323                if (!*first) {
  2257					/* There are now no entries in our slot.  */
  2258	     1855513                    xhv->xhv_fill--; /* HvFILL(hv)-- */
  2259				    }
  2260	     2550323                Safefree(entry);
  2261	     2550323                xhv->xhv_keys--; /* HvKEYS(hv)-- */
  2262			        }
  2263			    }
  2264			
  2265			    UNLOCK_STRTAB_MUTEX;
  2266	     2550323        if (!found && ckWARN_d(WARN_INTERNAL))
  2267	      ######    	Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
  2268			                    "Attempt to free non-existent shared string '%s'%s"
  2269			                    pTHX__FORMAT,
  2270			                    hek ? HEK_KEY(hek) : str,
  2271			                    ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
  2272	     2550323        if (k_flags & HVhek_FREEKEY)
  2273	      ######    	Safefree(str);
  2274			}
  2275			
  2276			/* get a (constant) string ptr from the global string table
  2277			 * string will get added if it is not already there.
  2278			 * len and hash must both be valid for str.
  2279			 */
  2280			HEK *
  2281			Perl_share_hek(pTHX_ const char *str, I32 len, register U32 hash)
  2282	     3240840    {
  2283	     3240840        bool is_utf8 = FALSE;
  2284	     3240840        int flags = 0;
  2285	     3240840        const char *save = str;
  2286			
  2287	     3240840        if (len < 0) {
  2288	         392          STRLEN tmplen = -len;
  2289	         392          is_utf8 = TRUE;
  2290			      /* See the note in hv_fetch(). --jhi */
  2291	         392          str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
  2292	         392          len = tmplen;
  2293			      /* If we were able to downgrade here, then than means that we were passed
  2294			         in a key which only had chars 0-255, but was utf8 encoded.  */
  2295	         392          if (is_utf8)
  2296	         392              flags = HVhek_UTF8;
  2297			      /* If we found we were able to downgrade the string to bytes, then
  2298			         we should flag that it needs upgrading on keys or each.  Also flag
  2299			         that we need share_hek_flags to free the string.  */
  2300	         392          if (str != save)
  2301	      ######              flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
  2302			    }
  2303			
  2304	     3240840        return share_hek_flags (str, len, hash, flags);
  2305			}
  2306			
  2307			STATIC HEK *
  2308			S_share_hek_flags(pTHX_ const char *str, I32 len, register U32 hash, int flags)
  2309	     9842852    {
  2310	     9842852        register HE *entry;
  2311	     9842852        register HE **oentry;
  2312	     9842852        I32 found = 0;
  2313	     9842852        const int flags_masked = flags & HVhek_MASK;
  2314			
  2315			    /* what follows is the moral equivalent of:
  2316			
  2317			    if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
  2318				hv_store(PL_strtab, str, len, Nullsv, hash);
  2319			
  2320				Can't rehash the shared string table, so not sure if it's worth
  2321				counting the number of entries in the linked list
  2322			    */
  2323	     9842852        register XPVHV * const xhv = (XPVHV*)SvANY(PL_strtab);
  2324			    /* assert(xhv_array != 0) */
  2325			    LOCK_STRTAB_MUTEX;
  2326	     9842852        oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
  2327	    12747463        for (entry = *oentry; entry; entry = HeNEXT(entry)) {
  2328	    10212523    	if (HeHASH(entry) != hash)		/* strings can't be equal */
  2329	     2903402    	    continue;
  2330	     7309121    	if (HeKLEN(entry) != len)
  2331	        1030    	    continue;
  2332	     7308091    	if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len))	/* is this it? */
  2333	      ######    	    continue;
  2334	     7308091    	if (HeKFLAGS(entry) != flags_masked)
  2335	         179    	    continue;
  2336	     7307912    	found = 1;
  2337	     7307912    	break;
  2338			    }
  2339	     9842852        if (!found) {
  2340				/* What used to be head of the list.
  2341				   If this is NULL, then we're the first entry for this slot, which
  2342				   means we need to increate fill.  */
  2343	     2534940    	const HE *old_first = *oentry;
  2344	     2534940    	struct shared_he *new_entry;
  2345	     2534940    	HEK *hek;
  2346	     2534940    	char *k;
  2347			
  2348				/* We don't actually store a HE from the arena and a regular HEK.
  2349				   Instead we allocate one chunk of memory big enough for both,
  2350				   and put the HEK straight after the HE. This way we can find the
  2351				   HEK directly from the HE.
  2352				*/
  2353			
  2354				New(0, k, STRUCT_OFFSET(struct shared_he,
  2355	     2534940    				shared_he_hek.hek_key[0]) + len + 2, char);
  2356	     2534940    	new_entry = (struct shared_he *)k;
  2357	     2534940    	entry = &(new_entry->shared_he_he);
  2358	     2534940    	hek = &(new_entry->shared_he_hek);
  2359			
  2360	     2534940    	Copy(str, HEK_KEY(hek), len, char);
  2361	     2534940    	HEK_KEY(hek)[len] = 0;
  2362	     2534940    	HEK_LEN(hek) = len;
  2363	     2534940    	HEK_HASH(hek) = hash;
  2364	     2534940    	HEK_FLAGS(hek) = (unsigned char)flags_masked;
  2365			
  2366				/* Still "point" to the HEK, so that other code need not know what
  2367				   we're up to.  */
  2368	     2534940    	HeKEY_hek(entry) = hek;
  2369	     2534940    	HeVAL(entry) = Nullsv;
  2370	     2534940    	HeNEXT(entry) = *oentry;
  2371	     2534940    	*oentry = entry;
  2372			
  2373	     2534940    	xhv->xhv_keys++; /* HvKEYS(hv)++ */
  2374	     2534940    	if (!old_first) {			/* initial entry? */
  2375	     1580364    	    xhv->xhv_fill++; /* HvFILL(hv)++ */
  2376	      954576    	} else if (xhv->xhv_keys > (IV)xhv->xhv_max /* HvKEYS(hv) > HvMAX(hv) */) {
  2377	        2071    		hsplit(PL_strtab);
  2378				}
  2379			    }
  2380			
  2381	     9842852        ++HeVAL(entry);				/* use value slot as REFCNT */
  2382			    UNLOCK_STRTAB_MUTEX;
  2383			
  2384	     9842852        if (flags & HVhek_FREEKEY)
  2385	         703    	Safefree(str);
  2386			
  2387	     9842852        return HeKEY_hek(entry);
  2388			}
  2389			
  2390			I32 *
  2391			Perl_hv_placeholders_p(pTHX_ HV *hv)
  2392	         317    {
  2393			    dVAR;
  2394	         317        MAGIC *mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
  2395			
  2396	         317        if (!mg) {
  2397	          33    	mg = sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, 0);
  2398			
  2399	          33    	if (!mg) {
  2400	      ######    	    Perl_die(aTHX_ "panic: hv_placeholders_p");
  2401				}
  2402			    }
  2403	         317        return &(mg->mg_len);
  2404			}
  2405			
  2406			
  2407			I32
  2408			Perl_hv_placeholders_get(pTHX_ HV *hv)
  2409	       98393    {
  2410			    dVAR;
  2411	       98393        MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
  2412			
  2413	       98393        return mg ? mg->mg_len : 0;
  2414			}
  2415			
  2416			void
  2417			Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
  2418	     1560858    {
  2419			    dVAR;
  2420	     1560858        MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
  2421			
  2422	     1560858        if (mg) {
  2423	          20    	mg->mg_len = ph;
  2424	     1560838        } else if (ph) {
  2425	      ######    	if (!sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, ph))
  2426	      ######    	    Perl_die(aTHX_ "panic: hv_placeholders_set");
  2427			    }
  2428			    /* else we don't need to add magic to record 0 placeholders.  */
  2429			}
  2430			
  2431			/*
  2432			=for apidoc hv_assert
  2433			
  2434			Check that a hash is in an internally consistent state.
  2435			
  2436			=cut
  2437			*/
  2438			
  2439			void
  2440			Perl_hv_assert(pTHX_ HV *hv)
  2441	      ######    {
  2442			  dVAR;
  2443	      ######      HE* entry;
  2444	      ######      int withflags = 0;
  2445	      ######      int placeholders = 0;
  2446	      ######      int real = 0;
  2447	      ######      int bad = 0;
  2448	      ######      const I32 riter = HvRITER_get(hv);
  2449	      ######      HE *eiter = HvEITER_get(hv);
  2450			
  2451	      ######      (void)hv_iterinit(hv);
  2452			
  2453	      ######      while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
  2454			    /* sanity check the values */
  2455	      ######        if (HeVAL(entry) == &PL_sv_placeholder) {
  2456	      ######          placeholders++;
  2457			    } else {
  2458	      ######          real++;
  2459			    }
  2460			    /* sanity check the keys */
  2461	      ######        if (HeSVKEY(entry)) {
  2462			      /* Don't know what to check on SV keys.  */
  2463	      ######        } else if (HeKUTF8(entry)) {
  2464	      ######          withflags++;
  2465	      ######           if (HeKWASUTF8(entry)) {
  2466	      ######    	 PerlIO_printf(Perl_debug_log,
  2467					       "hash key has both WASUFT8 and UTF8: '%.*s'\n",
  2468					       (int) HeKLEN(entry),  HeKEY(entry));
  2469	      ######    	 bad = 1;
  2470			       }
  2471	      ######        } else if (HeKWASUTF8(entry)) {
  2472	      ######          withflags++;
  2473			    }
  2474			  }
  2475	      ######      if (!SvTIED_mg((SV*)hv, PERL_MAGIC_tied)) {
  2476	      ######        if (HvUSEDKEYS(hv) != real) {
  2477	      ######          PerlIO_printf(Perl_debug_log, "Count %d key(s), but hash reports %d\n",
  2478					    (int) real, (int) HvUSEDKEYS(hv));
  2479	      ######          bad = 1;
  2480			    }
  2481	      ######        if (HvPLACEHOLDERS_get(hv) != placeholders) {
  2482	      ######          PerlIO_printf(Perl_debug_log,
  2483					    "Count %d placeholder(s), but hash reports %d\n",
  2484					    (int) placeholders, (int) HvPLACEHOLDERS_get(hv));
  2485	      ######          bad = 1;
  2486			    }
  2487			  }
  2488	      ######      if (withflags && ! HvHASKFLAGS(hv)) {
  2489	      ######        PerlIO_printf(Perl_debug_log,
  2490					  "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
  2491					  withflags);
  2492	      ######        bad = 1;
  2493			  }
  2494	      ######      if (bad) {
  2495	      ######        sv_dump((SV *)hv);
  2496			  }
  2497	      ######      HvRITER_set(hv, riter);		/* Restore hash iterator state */
  2498	      ######      HvEITER_set(hv, eiter);
  2499			}
  2500			
  2501			/*
  2502			 * Local variables:
  2503			 * c-indentation-style: bsd
  2504			 * c-basic-offset: 4
  2505			 * indent-tabs-mode: t
  2506			 * End:
  2507			 *
  2508			 * ex: set ts=8 sts=4 sw=4 noet:
  2509			 */
