		/*    hv.c
		 *
		 *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
		 *    2000, 2001, 2002, 2003, 2004, 2005, by Larry Wall and others
		 *
		 *    You may distribute under the terms of either the GNU General Public
		 *    License or the Artistic License, as specified in the README file.
		 *
		 */
		
		/*
		 * "I sit beside the fire and think of all that I have seen."  --Bilbo
		 */
		
		/* 
		=head1 Hash Manipulation Functions
		
		A HV structure represents a Perl hash. It consists mainly of an array
		of pointers, each of which points to a linked list of HE structures. The
		array is indexed by the hash function of the key, so each linked list
		represents all the hash entries with the same hash value. Each HE contains
		a pointer to the actual value, plus a pointer to a HEK structure which
		holds the key and hash value.
		
		=cut
		
		*/
		
		#include "EXTERN.h"
		#define PERL_IN_HV_C
		#define PERL_HASH_INTERNAL_ACCESS
		#include "perl.h"
		
		#define HV_MAX_LENGTH_BEFORE_SPLIT 14
		
		static const char *const S_strtab_error
		    = "Cannot modify shared string table in hv_%s";
		
		STATIC void
		S_more_he(pTHX)
       14983    {
       14983        HE* he;
       14983        HE* heend;
       14983        New(54, he, PERL_ARENA_SIZE/sizeof(HE), HE);
       14983        HeNEXT(he) = PL_he_arenaroot;
       14983        PL_he_arenaroot = he;
		
       14983        heend = &he[PERL_ARENA_SIZE / sizeof(HE) - 1];
       14983        PL_he_root = ++he;
     5079237        while (he < heend) {
     5064254    	HeNEXT(he) = (HE*)(he + 1);
     5064254    	he++;
		    }
       14983        HeNEXT(he) = 0;
		}
		
		STATIC HE*
		S_new_he(pTHX)
     6636892    {
     6636892        HE* he;
		    LOCK_SV_MUTEX;
     6636892        if (!PL_he_root)
       14983    	S_more_he(aTHX);
     6636892        he = PL_he_root;
     6636892        PL_he_root = HeNEXT(he);
		    UNLOCK_SV_MUTEX;
     6636892        return he;
		}
		
		STATIC void
		S_del_he(pTHX_ HE *p)
     6659114    {
		    LOCK_SV_MUTEX;
     6659114        HeNEXT(p) = (HE*)PL_he_root;
     6659114        PL_he_root = p;
		    UNLOCK_SV_MUTEX;
		}
		
		#ifdef PURIFY
		
		#define new_HE() (HE*)safemalloc(sizeof(HE))
		#define del_HE(p) safefree((char*)p)
		
		#else
		
		#define new_HE() new_he()
		#define del_HE(p) del_he(p)
		
		#endif
		
		STATIC HEK *
		S_save_hek_flags(pTHX_ const char *str, I32 len, U32 hash, int flags)
       32467    {
       32467        const int flags_masked = flags & HVhek_MASK;
       32467        char *k;
       32467        register HEK *hek;
		
       32467        New(54, k, HEK_BASESIZE + len + 2, char);
       32467        hek = (HEK*)k;
       32467        Copy(str, HEK_KEY(hek), len, char);
       32467        HEK_KEY(hek)[len] = 0;
       32467        HEK_LEN(hek) = len;
       32467        HEK_HASH(hek) = hash;
       32467        HEK_FLAGS(hek) = (unsigned char)flags_masked;
		
       32467        if (flags & HVhek_FREEKEY)
      ######    	Safefree(str);
       32467        return hek;
		}
		
		/* free the pool of temporary HE/HEK pairs retunrned by hv_fetch_ent
		 * for tied hashes */
		
		void
		Perl_free_tied_hv_pool(pTHX)
        4549    {
        4549        HE *he = PL_hv_fetch_ent_mh;
        6240        while (he) {
        1691    	HE * const ohe = he;
        1691    	Safefree(HeKEY_hek(he));
        1691    	he = HeNEXT(he);
        1691    	del_HE(ohe);
		    }
        4549        PL_hv_fetch_ent_mh = Nullhe;
		}
		
		#if defined(USE_ITHREADS)
		HEK *
		Perl_hek_dup(pTHX_ HEK *source, CLONE_PARAMS* param)
		{
		    HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
		
		    PERL_UNUSED_ARG(param);
		
		    if (shared) {
			/* We already shared this hash key.  */
			(void)share_hek_hek(shared);
		    }
		    else {
			shared
			    = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
					      HEK_HASH(source), HEK_FLAGS(source));
			ptr_table_store(PL_ptr_table, source, shared);
		    }
		    return shared;
		}
		
		HE *
		Perl_he_dup(pTHX_ HE *e, bool shared, CLONE_PARAMS* param)
		{
		    HE *ret;
		
		    if (!e)
			return Nullhe;
		    /* look for it in the table first */
		    ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
		    if (ret)
			return ret;
		
		    /* create anew and remember what it is */
		    ret = new_HE();
		    ptr_table_store(PL_ptr_table, e, ret);
		
		    HeNEXT(ret) = he_dup(HeNEXT(e),shared, param);
		    if (HeKLEN(e) == HEf_SVKEY) {
			char *k;
			New(54, k, HEK_BASESIZE + sizeof(SV*), char);
			HeKEY_hek(ret) = (HEK*)k;
			HeKEY_sv(ret) = SvREFCNT_inc(sv_dup(HeKEY_sv(e), param));
		    }
		    else if (shared) {
			/* This is hek_dup inlined, which seems to be important for speed
			   reasons.  */
			HEK * const source = HeKEY_hek(e);
			HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
		
			if (shared) {
			    /* We already shared this hash key.  */
			    (void)share_hek_hek(shared);
			}
			else {
			    shared
				= share_hek_flags(HEK_KEY(source), HEK_LEN(source),
						  HEK_HASH(source), HEK_FLAGS(source));
			    ptr_table_store(PL_ptr_table, source, shared);
			}
			HeKEY_hek(ret) = shared;
		    }
		    else
			HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
		                                        HeKFLAGS(e));
		    HeVAL(ret) = SvREFCNT_inc(sv_dup(HeVAL(e), param));
		    return ret;
		}
		#endif	/* USE_ITHREADS */
		
		static void
		S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
				const char *msg)
          34    {
          34        SV * const sv = sv_newmortal();
          34        if (!(flags & HVhek_FREEKEY)) {
          34    	sv_setpvn(sv, key, klen);
		    }
		    else {
			/* Need to free saved eventually assign to mortal SV */
			/* XXX is this line an error ???:  SV *sv = sv_newmortal(); */
      ######    	sv_usepvn(sv, (char *) key, klen);
		    }
          34        if (flags & HVhek_UTF8) {
           1    	SvUTF8_on(sv);
		    }
          34        Perl_croak(aTHX_ msg, sv);
		}
		
		/* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
		 * contains an SV* */
		
		#define HV_FETCH_ISSTORE   0x01
		#define HV_FETCH_ISEXISTS  0x02
		#define HV_FETCH_LVALUE    0x04
		#define HV_FETCH_JUST_SV   0x08
		
		/*
		=for apidoc hv_store
		
		Stores an SV in a hash.  The hash key is specified as C<key> and C<klen> is
		the length of the key.  The C<hash> parameter is the precomputed hash
		value; if it is zero then Perl will compute it.  The return value will be
		NULL if the operation failed or if the value did not need to be actually
		stored within the hash (as in the case of tied hashes).  Otherwise it can
		be dereferenced to get the original C<SV*>.  Note that the caller is
		responsible for suitably incrementing the reference count of C<val> before
		the call, and decrementing it if the function returned NULL.  Effectively
		a successful hv_store takes ownership of one reference to C<val>.  This is
		usually what you want; a newly created SV has a reference count of one, so
		if all your code does is create SVs then store them in a hash, hv_store
		will own the only reference to the new SV, and your code doesn't need to do
		anything further to tidy up.  hv_store is not implemented as a call to
		hv_store_ent, and does not create a temporary SV for the key, so if your
		key data is not already in SV form then use hv_store in preference to
		hv_store_ent.
		
		See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
		information on how to use this function on tied hashes.
		
		=cut
		*/
		
		SV**
		Perl_hv_store(pTHX_ HV *hv, const char *key, I32 klen_i32, SV *val, U32 hash)
      393427    {
      393427        HE *hek;
      393427        STRLEN klen;
      393427        int flags;
		
      393427        if (klen_i32 < 0) {
          33    	klen = -klen_i32;
          33    	flags = HVhek_UTF8;
		    } else {
      393394    	klen = klen_i32;
      393394    	flags = 0;
		    }
      393427        hek = hv_fetch_common (hv, NULL, key, klen, flags,
					   (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
      393426        return hek ? &HeVAL(hek) : NULL;
		}
		
		SV**
		Perl_hv_store_flags(pTHX_ HV *hv, const char *key, I32 klen, SV *val,
		                 register U32 hash, int flags)
         179    {
         179        HE * const hek = hv_fetch_common (hv, NULL, key, klen, flags,
         179    			       (HV_FETCH_ISSTORE|HV_FETCH_JUST_SV), val, hash);
         179        return hek ? &HeVAL(hek) : NULL;
		}
		
		/*
		=for apidoc hv_store_ent
		
		Stores C<val> in a hash.  The hash key is specified as C<key>.  The C<hash>
		parameter is the precomputed hash value; if it is zero then Perl will
		compute it.  The return value is the new hash entry so created.  It will be
		NULL if the operation failed or if the value did not need to be actually
		stored within the hash (as in the case of tied hashes).  Otherwise the
		contents of the return value can be accessed using the C<He?> macros
		described here.  Note that the caller is responsible for suitably
		incrementing the reference count of C<val> before the call, and
		decrementing it if the function returned NULL.  Effectively a successful
		hv_store_ent takes ownership of one reference to C<val>.  This is
		usually what you want; a newly created SV has a reference count of one, so
		if all your code does is create SVs then store them in a hash, hv_store
		will own the only reference to the new SV, and your code doesn't need to do
		anything further to tidy up.  Note that hv_store_ent only reads the C<key>;
		unlike C<val> it does not take ownership of it, so maintaining the correct
		reference count on C<key> is entirely the caller's responsibility.  hv_store
		is not implemented as a call to hv_store_ent, and does not create a temporary
		SV for the key, so if your key data is not already in SV form then use
		hv_store in preference to hv_store_ent.
		
		See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
		information on how to use this function on tied hashes.
		
		=cut
		*/
		
		HE *
		Perl_hv_store_ent(pTHX_ HV *hv, SV *keysv, SV *val, U32 hash)
     1632874    {
     1632874      return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISSTORE, val, hash);
		}
		
		/*
		=for apidoc hv_exists
		
		Returns a boolean indicating whether the specified hash key exists.  The
		C<klen> is the length of the key.
		
		=cut
		*/
		
		bool
		Perl_hv_exists(pTHX_ HV *hv, const char *key, I32 klen_i32)
       93038    {
       93038        STRLEN klen;
       93038        int flags;
		
       93038        if (klen_i32 < 0) {
          44    	klen = -klen_i32;
          44    	flags = HVhek_UTF8;
		    } else {
       92994    	klen = klen_i32;
       92994    	flags = 0;
		    }
       93038        return hv_fetch_common(hv, NULL, key, klen, flags, HV_FETCH_ISEXISTS, 0, 0)
			? TRUE : FALSE;
		}
		
		/*
		=for apidoc hv_fetch
		
		Returns the SV which corresponds to the specified key in the hash.  The
		C<klen> is the length of the key.  If C<lval> is set then the fetch will be
		part of a store.  Check that the return value is non-null before
		dereferencing it to an C<SV*>.
		
		See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
		information on how to use this function on tied hashes.
		
		=cut
		*/
		
		SV**
		Perl_hv_fetch(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 lval)
    24823873    {
    24823873        HE *hek;
    24823873        STRLEN klen;
    24823873        int flags;
		
    24823873        if (klen_i32 < 0) {
          48    	klen = -klen_i32;
          48    	flags = HVhek_UTF8;
		    } else {
    24823825    	klen = klen_i32;
    24823825    	flags = 0;
		    }
    24823873        hek = hv_fetch_common (hv, NULL, key, klen, flags,
					   HV_FETCH_JUST_SV | (lval ? HV_FETCH_LVALUE : 0),
					   Nullsv, 0);
    24823873        return hek ? &HeVAL(hek) : NULL;
		}
		
		/*
		=for apidoc hv_exists_ent
		
		Returns a boolean indicating whether the specified hash key exists. C<hash>
		can be a valid precomputed hash value, or 0 to ask for it to be
		computed.
		
		=cut
		*/
		
		bool
		Perl_hv_exists_ent(pTHX_ HV *hv, SV *keysv, U32 hash)
      981051    {
      981051        return hv_fetch_common(hv, keysv, NULL, 0, 0, HV_FETCH_ISEXISTS, 0, hash)
			? TRUE : FALSE;
		}
		
		/* returns an HE * structure with the all fields set */
		/* note that hent_val will be a mortal sv for MAGICAL hashes */
		/*
		=for apidoc hv_fetch_ent
		
		Returns the hash entry which corresponds to the specified key in the hash.
		C<hash> must be a valid precomputed hash number for the given C<key>, or 0
		if you want the function to compute it.  IF C<lval> is set then the fetch
		will be part of a store.  Make sure the return value is non-null before
		accessing it.  The return value when C<tb> is a tied hash is a pointer to a
		static location, so be sure to make a copy of the structure if you need to
		store it somewhere.
		
		See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
		information on how to use this function on tied hashes.
		
		=cut
		*/
		
		HE *
		Perl_hv_fetch_ent(pTHX_ HV *hv, SV *keysv, I32 lval, register U32 hash)
    23191424    {
    23191424        return hv_fetch_common(hv, keysv, NULL, 0, 0, 
					   (lval ? HV_FETCH_LVALUE : 0), Nullsv, hash);
		}
		
		STATIC HE *
		S_hv_fetch_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
				  int flags, int action, SV *val, register U32 hash)
    52451536    {
		    dVAR;
    52451536        XPVHV* xhv;
    52451536        HE *entry;
    52451536        HE **oentry;
    52451536        SV *sv;
    52451536        bool is_utf8;
    52451536        int masked_flags;
		
    52451536        if (!hv)
          23    	return 0;
		
    52451513        if (keysv) {
    25809190    	if (flags & HVhek_FREEKEY)
      ######    	    Safefree(key);
    25809190    	key = SvPV_const(keysv, klen);
    25809190    	flags = 0;
    25809190    	is_utf8 = (SvUTF8(keysv) != 0);
		    } else {
    26642323    	is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
		    }
		
    52451513        xhv = (XPVHV*)SvANY(hv);
    52451513        if (SvMAGICAL(hv)) {
    30717605    	if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS)))
			  {
    29159015    	    if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
       11530    		sv = sv_newmortal();
		
				/* XXX should be able to skimp on the HE/HEK here when
				   HV_FETCH_JUST_SV is true.  */
		
       11530    		if (!keysv) {
          37    		    keysv = newSVpvn(key, klen);
          37    		    if (is_utf8) {
          22    			SvUTF8_on(keysv);
				    }
				} else {
       11493    		    keysv = newSVsv(keysv);
				}
       11530    		mg_copy((SV*)hv, sv, (char *)keysv, HEf_SVKEY);
		
				/* grab a fake HE/HEK pair from the pool or make a new one */
       11530    		entry = PL_hv_fetch_ent_mh;
       11530    		if (entry)
        9865    		    PL_hv_fetch_ent_mh = HeNEXT(entry);
				else {
        1665    		    char *k;
        1665    		    entry = new_HE();
        1665    		    New(54, k, HEK_BASESIZE + sizeof(SV*), char);
        1665    		    HeKEY_hek(entry) = (HEK*)k;
				}
       11530    		HeNEXT(entry) = Nullhe;
       11530    		HeSVKEY_set(entry, keysv);
       11530    		HeVAL(entry) = sv;
       11530    		sv_upgrade(sv, SVt_PVLV);
       11530    		LvTYPE(sv) = 'T';
				 /* so we can free entry when freeing sv */
       11530    		LvTARG(sv) = (SV*)entry;
		
				/* XXX remove at some point? */
       11530    		if (flags & HVhek_FREEKEY)
      ######    		    Safefree(key);
		
       11530    		return entry;
			    }
		#ifdef ENV_IS_CASELESS
			    else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
				U32 i;
				for (i = 0; i < klen; ++i)
				    if (isLOWER(key[i])) {
					/* Would be nice if we had a routine to do the
					   copy and upercase in a single pass through.  */
					const char *nkey = strupr(savepvn(key,klen));
					/* Note that this fetch is for nkey (the uppercased
					   key) whereas the store is for key (the original)  */
					entry = hv_fetch_common(hv, Nullsv, nkey, klen,
								HVhek_FREEKEY, /* free nkey */
								0 /* non-LVAL fetch */,
								Nullsv /* no value */,
								0 /* compute hash */);
					if (!entry && (action & HV_FETCH_LVALUE)) {
					    /* This call will free key if necessary.
					       Do it this way to encourage compiler to tail
					       call optimise.  */
					    entry = hv_fetch_common(hv, keysv, key, klen,
								    flags, HV_FETCH_ISSTORE,
								    NEWSV(61,0), hash);
					} else {
					    if (flags & HVhek_FREEKEY)
						Safefree(key);
					}
					return entry;
				    }
			    }
		#endif
			} /* ISFETCH */
     1558590    	else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
        7067    	    if (mg_find((SV*)hv, PERL_MAGIC_tied) || SvGMAGICAL((SV*)hv)) {
				/* I don't understand why hv_exists_ent has svret and sv,
				   whereas hv_exists only had one.  */
         320    		SV * const svret = sv_newmortal();
         320    		sv = sv_newmortal();
		
         320    		if (keysv || is_utf8) {
         308    		    if (!keysv) {
          22    			keysv = newSVpvn(key, klen);
          22    			SvUTF8_on(keysv);
				    } else {
         286    			keysv = newSVsv(keysv);
				    }
         308    		    mg_copy((SV*)hv, sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
				} else {
          12    		    mg_copy((SV*)hv, sv, key, klen);
				}
         320    		if (flags & HVhek_FREEKEY)
      ######    		    Safefree(key);
         320    		magic_existspack(svret, mg_find(sv, PERL_MAGIC_tiedelem));
				/* This cast somewhat evil, but I'm merely using NULL/
				   not NULL to return the boolean exists.
				   And I know hv is not NULL.  */
         320    		return SvTRUE(svret) ? (HE *)hv : NULL;
				}
		#ifdef ENV_IS_CASELESS
			    else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
				/* XXX This code isn't UTF8 clean.  */
				char * const keysave = (char * const)key;
				/* Will need to free this, so set FREEKEY flag.  */
				key = savepvn(key,klen);
				key = (const char*)strupr((char*)key);
				is_utf8 = 0;
				hash = 0;
				keysv = 0;
		
				if (flags & HVhek_FREEKEY) {
				    Safefree(keysave);
				}
				flags |= HVhek_FREEKEY;
			    }
		#endif
			} /* ISEXISTS */
     1551523    	else if (action & HV_FETCH_ISSTORE) {
     1551286    	    bool needs_copy;
     1551286    	    bool needs_store;
     1551286    	    hv_magic_check (hv, &needs_copy, &needs_store);
     1551286    	    if (needs_copy) {
      353732    		const bool save_taint = PL_tainted;
      353732    		if (keysv || is_utf8) {
        4536    		    if (!keysv) {
          17    			keysv = newSVpvn(key, klen);
          17    			SvUTF8_on(keysv);
				    }
        4536    		    if (PL_tainting)
          88    			PL_tainted = SvTAINTED(keysv);
        4536    		    keysv = sv_2mortal(newSVsv(keysv));
        4536    		    mg_copy((SV*)hv, val, (char*)keysv, HEf_SVKEY);
				} else {
      349196    		    mg_copy((SV*)hv, val, key, klen);
				}
		
      353732    		TAINT_IF(save_taint);
      353732    		if (!HvARRAY(hv) && !needs_store) {
          16    		    if (flags & HVhek_FREEKEY)
      ######    			Safefree(key);
          16    		    return Nullhe;
				}
		#ifdef ENV_IS_CASELESS
				else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
				    /* XXX This code isn't UTF8 clean.  */
				    const char *keysave = key;
				    /* Will need to free this, so set FREEKEY flag.  */
				    key = savepvn(key,klen);
				    key = (const char*)strupr((char*)key);
				    is_utf8 = 0;
				    hash = 0;
				    keysv = 0;
		
				    if (flags & HVhek_FREEKEY) {
					Safefree(keysave);
				    }
				    flags |= HVhek_FREEKEY;
				}
		#endif
			    }
			} /* ISSTORE */
		    } /* SvMAGICAL */
		
    52439647        if (!HvARRAY(hv)) {
      841933    	if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
		#ifdef DYNAMIC_ENV_FETCH  /* if it's an %ENV lookup, we may get it on the fly */
				 || (SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
		#endif
										  ) {
      538643    	    char *array;
			    Newz(503, array,
				 PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
      538643    		 char);
      538643    	    HvARRAY(hv) = (HE**)array;
			}
		#ifdef DYNAMIC_ENV_FETCH
			else if (action & HV_FETCH_ISEXISTS) {
			    /* for an %ENV exists, if we do an insert it's by a recursive
			       store call, so avoid creating HvARRAY(hv) right now.  */
			}
		#endif
			else {
			    /* XXX remove at some point? */
      303290                if (flags & HVhek_FREEKEY)
      ######                    Safefree(key);
		
      303290    	    return 0;
			}
		    }
		
    52136357        if (is_utf8) {
        3322    	char * const keysave = (char * const)key;
        3322    	key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
        3322            if (is_utf8)
        2174    	    flags |= HVhek_UTF8;
			else
        1148    	    flags &= ~HVhek_UTF8;
        3322            if (key != keysave) {
        1148    	    if (flags & HVhek_FREEKEY)
      ######    		Safefree(keysave);
        1148                flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
			}
		    }
		
    52136357        if (HvREHASH(hv)) {
           6    	PERL_HASH_INTERNAL(hash, key, klen);
			/* We don't have a pointer to the hv, so we have to replicate the
			   flag into every HEK, so that hv_iterkeysv can see it.  */
			/* And yes, you do need this even though you are not "storing" because
			   you can flip the flags below if doing an lval lookup.  (And that
			   was put in to give the semantics Andreas was expecting.)  */
           6    	flags |= HVhek_REHASH;
    52136351        } else if (!hash) {
    33209329            if (keysv && (SvIsCOW_shared_hash(keysv))) {
      357991                hash = SvSHARED_HASH(keysv);
		        } else {
    32851338                PERL_HASH(hash, key, klen);
		        }
		    }
		
    52136357        masked_flags = (flags & HVhek_MASK);
		
		#ifdef DYNAMIC_ENV_FETCH
		    if (!HvARRAY(hv)) entry = Null(HE*);
		    else
		#endif
		    {
    52136357    	entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
		    }
    86035607        for (; entry; entry = HeNEXT(entry)) {
    49397003    	if (HeHASH(entry) != hash)		/* strings can't be equal */
    16949330    	    continue;
    32447673    	if (HeKLEN(entry) != (I32)klen)
         185    	    continue;
    32447488    	if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen))	/* is this it? */
      ######    	    continue;
    32447488    	if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
         110    	    continue;
		
    32447378            if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
    12693912    	    if (HeKFLAGS(entry) != masked_flags) {
				/* We match if HVhek_UTF8 bit in our flags and hash key's
				   match.  But if entry was set previously with HVhek_WASUTF8
				   and key now doesn't (or vice versa) then we should change
				   the key's flag, as this is assignment.  */
           3    		if (HvSHAREKEYS(hv)) {
				    /* Need to swap the key we have for a key with the flags we
				       need. As keys are shared we can't just write to the
				       flag, so we share the new one, unshare the old one.  */
           3    		    HEK *new_hek = share_hek_flags(key, klen, hash,
           3    						   masked_flags);
           3    		    unshare_hek (HeKEY_hek(entry));
           3    		    HeKEY_hek(entry) = new_hek;
				}
      ######    		else if (hv == PL_strtab) {
				    /* PL_strtab is usually the only hash without HvSHAREKEYS,
				       so putting this test here is cheap  */
      ######    		    if (flags & HVhek_FREEKEY)
      ######    			Safefree(key);
      ######    		    Perl_croak(aTHX_ S_strtab_error,
					       action & HV_FETCH_LVALUE ? "fetch" : "store");
				}
				else
      ######    		    HeKFLAGS(entry) = masked_flags;
           3    		if (masked_flags & HVhek_ENABLEHVKFLAGS)
           2    		    HvHASKFLAGS_on(hv);
			    }
    12693912    	    if (HeVAL(entry) == &PL_sv_placeholder) {
				/* yes, can store into placeholder slot */
         111    		if (action & HV_FETCH_LVALUE) {
         107    		    if (SvMAGICAL(hv)) {
					/* This preserves behaviour with the old hv_fetch
					   implementation which at this point would bail out
					   with a break; (at "if we find a placeholder, we
					   pretend we haven't found anything")
		
					   That break mean that if a placeholder were found, it
					   caused a call into hv_store, which in turn would
					   check magic, and if there is no magic end up pretty
					   much back at this point (in hv_store's code).  */
      ######    			break;
				    }
				    /* LVAL fetch which actaully needs a store.  */
         107    		    val = NEWSV(61,0);
         107    		    HvPLACEHOLDERS(hv)--;
				} else {
				    /* store */
           4    		    if (val != &PL_sv_placeholder)
           4    			HvPLACEHOLDERS(hv)--;
				}
         111    		HeVAL(entry) = val;
    12693801    	    } else if (action & HV_FETCH_ISSTORE) {
       22595    		SvREFCNT_dec(HeVAL(entry));
       22595    		HeVAL(entry) = val;
			    }
    19753466    	} else if (HeVAL(entry) == &PL_sv_placeholder) {
			    /* if we find a placeholder, we pretend we haven't found
			       anything */
          21    	    break;
			}
    32447357    	if (flags & HVhek_FREEKEY)
         319    	    Safefree(key);
    32447357    	return entry;
		    }
		#ifdef DYNAMIC_ENV_FETCH  /* %ENV lookup?  If so, try to fetch the value now */
		    if (!(action & HV_FETCH_ISSTORE) 
			&& SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env)) {
			unsigned long len;
			const char * const env = PerlEnv_ENVgetenv_len(key,&len);
			if (env) {
			    sv = newSVpvn(env,len);
			    SvTAINTED_on(sv);
			    return hv_fetch_common(hv,keysv,key,klen,flags,HV_FETCH_ISSTORE,sv,
						   hash);
			}
		    }
		#endif
		
    19689000        if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
          32    	S_hv_notallowed(aTHX_ flags, key, klen,
					"Attempt to access disallowed key '%"SVf"' in"
					" a restricted hash");
		    }
    19688968        if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
			/* Not doing some form of store, so return failure.  */
    11720200    	if (flags & HVhek_FREEKEY)
         126    	    Safefree(key);
    11720200    	return 0;
		    }
     7968768        if (action & HV_FETCH_LVALUE) {
     4629502    	val = NEWSV(61,0);
     4629502    	if (SvMAGICAL(hv)) {
			    /* At this point the old hv_fetch code would call to hv_store,
			       which in turn might do some tied magic. So we need to make that
			       magic check happen.  */
			    /* gonna assign to this, so it better be there */
     1335402    	    return hv_fetch_common(hv, keysv, key, klen, flags,
						   HV_FETCH_ISSTORE, val, hash);
			    /* XXX Surely that could leak if the fetch-was-store fails?
			       Just like the hv_fetch.  */
			}
		    }
		
		    /* Welcome to hv_store...  */
		
     6633366        if (!HvARRAY(hv)) {
			/* Not sure if we can get here.  I think the only case of oentry being
			   NULL is for %ENV with dynamic env fetch.  But that should disappear
			   with magic in the previous code.  */
      ######    	char *array;
			Newz(503, array,
			     PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
      ######    	     char);
      ######    	HvARRAY(hv) = (HE**)array;
		    }
		
     6633366        oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
		
     6633366        entry = new_HE();
		    /* share_hek_flags will do the free for us.  This might be considered
		       bad API design.  */
     6633366        if (HvSHAREKEYS(hv))
     6601008    	HeKEY_hek(entry) = share_hek_flags(key, klen, hash, flags);
       32358        else if (hv == PL_strtab) {
			/* PL_strtab is usually the only hash without HvSHAREKEYS, so putting
			   this test here is cheap  */
           2    	if (flags & HVhek_FREEKEY)
      ######    	    Safefree(key);
           2    	Perl_croak(aTHX_ S_strtab_error,
				   action & HV_FETCH_LVALUE ? "fetch" : "store");
		    }
		    else                                       /* gotta do the real thing */
       32356    	HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
     6633364        HeVAL(entry) = val;
     6633364        HeNEXT(entry) = *oentry;
     6633364        *oentry = entry;
		
     6633364        if (val == &PL_sv_placeholder)
          80    	HvPLACEHOLDERS(hv)++;
     6633364        if (masked_flags & HVhek_ENABLEHVKFLAGS)
        1900    	HvHASKFLAGS_on(hv);
		
		    {
     6633364    	const HE *counter = HeNEXT(entry);
		
     6633364    	xhv->xhv_keys++; /* HvKEYS(hv)++ */
     6633364    	if (!counter) {				/* initial entry? */
     4197308    	    xhv->xhv_fill++; /* HvFILL(hv)++ */
     2436056    	} else if (xhv->xhv_keys > (IV)xhv->xhv_max) {
      256069    	    hsplit(hv);
     2179987    	} else if(!HvREHASH(hv)) {
     2179986    	    U32 n_links = 1;
		
     2830443    	    while ((counter = HeNEXT(counter)))
      650457    		n_links++;
		
     2179986    	    if (n_links > HV_MAX_LENGTH_BEFORE_SPLIT) {
				/* Use only the old HvKEYS(hv) > HvMAX(hv) condition to limit
				   bucket splits on a rehashed hash, as we're not going to
				   split it again, and if someone is lucky (evil) enough to
				   get all the keys in one list they could exhaust our memory
				   as we repeatedly double the number of buckets on every
				   entry. Linear search feels a less worse thing to do.  */
           1    		hsplit(hv);
			    }
			}
		    }
		
     6633364        return entry;
		}
		
		STATIC void
		S_hv_magic_check(pTHX_ HV *hv, bool *needs_copy, bool *needs_store)
     1618879    {
     1618879        const MAGIC *mg = SvMAGIC(hv);
     1618879        *needs_copy = FALSE;
     1618879        *needs_store = TRUE;
     3607018        while (mg) {
     2125759    	if (isUPPER(mg->mg_type)) {
      354000    	    *needs_copy = TRUE;
      354000    	    switch (mg->mg_type) {
			    case PERL_MAGIC_tied:
			    case PERL_MAGIC_sig:
      137620    		*needs_store = FALSE;
      137620    		return; /* We've set all there is to set. */
			    }
			}
     1988139    	mg = mg->mg_moremagic;
		    }
		}
		
		/*
		=for apidoc hv_scalar
		
		Evaluates the hash in scalar context and returns the result. Handles magic when the hash is tied.
		
		=cut
		*/
		
		SV *
		Perl_hv_scalar(pTHX_ HV *hv)
       23571    {
       23571        MAGIC *mg;
       23571        SV *sv;
		    
       23571        if ((SvRMAGICAL(hv) && (mg = mg_find((SV*)hv, PERL_MAGIC_tied)))) {
           7            sv = magic_scalarpack(hv, mg);
           7            return sv;
		    } 
		
       23564        sv = sv_newmortal();
       23564        if (HvFILL((HV*)hv)) 
        2491            Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
		                (long)HvFILL(hv), (long)HvMAX(hv) + 1);
		    else
       21073            sv_setiv(sv, 0);
		    
       23564        return sv;
		}
		
		/*
		=for apidoc hv_delete
		
		Deletes a key/value pair in the hash.  The value SV is removed from the
		hash and returned to the caller.  The C<klen> is the length of the key.
		The C<flags> value will normally be zero; if set to G_DISCARD then NULL
		will be returned.
		
		=cut
		*/
		
		SV *
		Perl_hv_delete(pTHX_ HV *hv, const char *key, I32 klen_i32, I32 flags)
       72390    {
       72390        STRLEN klen;
       72390        int k_flags = 0;
		
       72390        if (klen_i32 < 0) {
          44    	klen = -klen_i32;
          44    	k_flags |= HVhek_UTF8;
		    } else {
       72346    	klen = klen_i32;
		    }
       72390        return hv_delete_common(hv, NULL, key, klen, k_flags, flags, 0);
		}
		
		/*
		=for apidoc hv_delete_ent
		
		Deletes a key/value pair in the hash.  The value SV is removed from the
		hash and returned to the caller.  The C<flags> value will normally be zero;
		if set to G_DISCARD then NULL will be returned.  C<hash> can be a valid
		precomputed hash value, or 0 to ask for it to be computed.
		
		=cut
		*/
		
		SV *
		Perl_hv_delete_ent(pTHX_ HV *hv, SV *keysv, I32 flags, U32 hash)
      125745    {
      125745        return hv_delete_common(hv, keysv, NULL, 0, 0, flags, hash);
		}
		
		STATIC SV *
		S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
				   int k_flags, I32 d_flags, U32 hash)
      198135    {
		    dVAR;
      198135        register XPVHV* xhv;
      198135        register HE *entry;
      198135        register HE **oentry;
      198135        HE *const *first_entry;
      198135        SV *sv;
      198135        bool is_utf8;
      198135        int masked_flags;
		
      198135        if (!hv)
      ######    	return Nullsv;
		
      198135        if (keysv) {
      125745    	if (k_flags & HVhek_FREEKEY)
      ######    	    Safefree(key);
      125745    	key = SvPV_const(keysv, klen);
      125745    	k_flags = 0;
      125745    	is_utf8 = (SvUTF8(keysv) != 0);
		    } else {
       72390    	is_utf8 = ((k_flags & HVhek_UTF8) ? TRUE : FALSE);
		    }
		
      198135        if (SvRMAGICAL(hv)) {
       67593    	bool needs_copy;
       67593    	bool needs_store;
       67593    	hv_magic_check (hv, &needs_copy, &needs_store);
		
       67593    	if (needs_copy) {
         268    	    entry = hv_fetch_common(hv, keysv, key, klen,
						    k_flags & ~HVhek_FREEKEY, HV_FETCH_LVALUE,
						    Nullsv, hash);
         268    	    sv = entry ? HeVAL(entry) : NULL;
         268    	    if (sv) {
         268    		if (SvMAGICAL(sv)) {
         268    		    mg_clear(sv);
				}
         265    		if (!needs_store) {
          78    		    if (mg_find(sv, PERL_MAGIC_tiedelem)) {
					/* No longer an element */
          77    			sv_unmagic(sv, PERL_MAGIC_tiedelem);
          77    			return sv;
				    }		
           1    		    return Nullsv;		/* element cannot be deleted */
				}
		#ifdef ENV_IS_CASELESS
				else if (mg_find((SV*)hv, PERL_MAGIC_env)) {
				    /* XXX This code isn't UTF8 clean.  */
				    keysv = sv_2mortal(newSVpvn(key,klen));
				    if (k_flags & HVhek_FREEKEY) {
					Safefree(key);
				    }
				    key = strupr(SvPVX(keysv));
				    is_utf8 = 0;
				    k_flags = 0;
				    hash = 0;
				}
		#endif
			    }
			}
		    }
      198054        xhv = (XPVHV*)SvANY(hv);
      198054        if (!HvARRAY(hv))
        4667    	return Nullsv;
		
      193387        if (is_utf8) {
          99    	const char *keysave = key;
          99    	key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
		
          99            if (is_utf8)
          44                k_flags |= HVhek_UTF8;
			else
          55                k_flags &= ~HVhek_UTF8;
          99            if (key != keysave) {
          55    	    if (k_flags & HVhek_FREEKEY) {
				/* This shouldn't happen if our caller does what we expect,
				   but strictly the API allows it.  */
      ######    		Safefree(keysave);
			    }
          55    	    k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
			}
          99            HvHASKFLAGS_on((SV*)hv);
		    }
		
      193387        if (HvREHASH(hv)) {
      ######    	PERL_HASH_INTERNAL(hash, key, klen);
      193387        } else if (!hash) {
      193387            if (keysv && (SvIsCOW_shared_hash(keysv))) {
       23101                hash = SvSHARED_HASH(keysv);
		        } else {
      170286                PERL_HASH(hash, key, klen);
		        }
		    }
		
      193387        masked_flags = (k_flags & HVhek_MASK);
		
      193387        first_entry = oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
      193387        entry = *oentry;
      224171        for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
      127079    	if (HeHASH(entry) != hash)		/* strings can't be equal */
       15368    	    continue;
      111711    	if (HeKLEN(entry) != (I32)klen)
      ######    	    continue;
      111711    	if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen))	/* is this it? */
      ######    	    continue;
      111711    	if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
          24    	    continue;
		
      111687    	if (hv == PL_strtab) {
           1    	    if (k_flags & HVhek_FREEKEY)
           1    		Safefree(key);
           1    	    Perl_croak(aTHX_ S_strtab_error, "delete");
			}
		
			/* if placeholder is here, it's already been deleted.... */
      111686    	if (HeVAL(entry) == &PL_sv_placeholder)
			{
      ######    	  if (k_flags & HVhek_FREEKEY)
      ######                Safefree(key);
      ######    	  return Nullsv;
			}
      111686    	else if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
           1    	    S_hv_notallowed(aTHX_ k_flags, key, klen,
					    "Attempt to delete readonly key '%"SVf"' from"
					    " a restricted hash");
			}
      111685            if (k_flags & HVhek_FREEKEY)
          22                Safefree(key);
		
      111685    	if (d_flags & G_DISCARD)
      105086    	    sv = Nullsv;
			else {
        6599    	    sv = sv_2mortal(HeVAL(entry));
        6599    	    HeVAL(entry) = &PL_sv_placeholder;
			}
		
			/*
			 * If a restricted hash, rather than really deleting the entry, put
			 * a placeholder there. This marks the key as being "approved", so
			 * we can still access via not-really-existing key without raising
			 * an error.
			 */
      111685    	if (SvREADONLY(hv)) {
         120    	    SvREFCNT_dec(HeVAL(entry));
         120    	    HeVAL(entry) = &PL_sv_placeholder;
			    /* We'll be saving this slot, so the number of allocated keys
			     * doesn't go down, but the number placeholders goes up */
         120    	    HvPLACEHOLDERS(hv)++;
			} else {
      111565    	    *oentry = HeNEXT(entry);
      111565    	    if(!*first_entry) {
       55458    		xhv->xhv_fill--; /* HvFILL(hv)-- */
			    }
      111565    	    if (SvOOK(hv) && entry == HvAUX(hv)->xhv_eiter /* HvEITER(hv) */)
          10    		HvLAZYDEL_on(hv);
			    else
      111555    		hv_free_ent(hv, entry);
      111565    	    xhv->xhv_keys--; /* HvKEYS(hv)-- */
      111565    	    if (xhv->xhv_keys == 0)
        1454    	        HvHASKFLAGS_off(hv);
			}
      111685    	return sv;
		    }
       81700        if (SvREADONLY(hv)) {
           1            S_hv_notallowed(aTHX_ k_flags, key, klen,
					"Attempt to delete disallowed key '%"SVf"' from"
					" a restricted hash");
		    }
		
       81699        if (k_flags & HVhek_FREEKEY)
          32    	Safefree(key);
       81699        return Nullsv;
		}
		
		STATIC void
		S_hsplit(pTHX_ HV *hv)
      258141    {
      258141        register XPVHV* xhv = (XPVHV*)SvANY(hv);
      258141        const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
      258141        register I32 newsize = oldsize * 2;
      258141        register I32 i;
      258141        char *a = (char*) HvARRAY(hv);
      258141        register HE **aep;
      258141        register HE **oentry;
      258141        int longest_chain = 0;
      258141        int was_shared;
		
		    /*PerlIO_printf(PerlIO_stderr(), "hsplit called for %p which had %d\n",
		      hv, (int) oldsize);*/
		
      258141        if (HvPLACEHOLDERS_get(hv) && !SvREADONLY(hv)) {
		      /* Can make this clear any placeholders first for non-restricted hashes,
			 even though Storable rebuilds restricted hashes by putting in all the
			 placeholders (first) before turning on the readonly flag, because
			 Storable always pre-splits the hash.  */
      ######          hv_clear_placeholders(hv);
		    }
			       
      258141        PL_nomemok = TRUE;
		#if defined(STRANGE_MALLOC) || defined(MYMALLOC)
		    Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
			  + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
		    if (!a) {
		      PL_nomemok = FALSE;
		      return;
		    }
		    if (SvOOK(hv)) {
			Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
		    }
		#else
		    New(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
      258141    	+ (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
      258141        if (!a) {
      ######          PL_nomemok = FALSE;
      ######          return;
		    }
      258141        Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
      258141        if (SvOOK(hv)) {
       80122    	Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
		    }
      258141        if (oldsize >= 64) {
       16631    	offer_nice_chunk(HvARRAY(hv),
					 PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
					 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
		    }
		    else
      241510    	Safefree(HvARRAY(hv));
		#endif
		
      258141        PL_nomemok = FALSE;
      258141        Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char);	/* zero 2nd half*/
      258141        xhv->xhv_max = --newsize;	/* HvMAX(hv) = --newsize */
      258141        HvARRAY(hv) = (HE**) a;
      258141        aep = (HE**)a;
		
     7265883        for (i=0; i<oldsize; i++,aep++) {
     7007742    	int left_length = 0;
     7007742    	int right_length = 0;
     7007742    	register HE *entry;
     7007742    	register HE **bep;
		
     7007742    	if (!*aep)				/* non-existent */
     2518419    	    continue;
     4489323    	bep = aep+oldsize;
    11646343    	for (oentry = aep, entry = *aep; entry; entry = *oentry) {
     7157020    	    if ((HeHASH(entry) & newsize) != (U32)i) {
     3470130    		*oentry = HeNEXT(entry);
     3470130    		HeNEXT(entry) = *bep;
     3470130    		if (!*bep)
     2688429    		    xhv->xhv_fill++; /* HvFILL(hv)++ */
     3470130    		*bep = entry;
     3470130    		right_length++;
     3470130    		continue;
			    }
			    else {
     3686890    		oentry = &HeNEXT(entry);
     3686890    		left_length++;
			    }
			}
     4489323    	if (!*aep)				/* everything moved */
     1577442    	    xhv->xhv_fill--; /* HvFILL(hv)-- */
			/* I think we don't actually need to keep track of the longest length,
			   merely flag if anything is too long. But for the moment while
			   developing this code I'll track it.  */
     4489323    	if (left_length > longest_chain)
      328225    	    longest_chain = left_length;
     4489323    	if (right_length > longest_chain)
      180965    	    longest_chain = right_length;
		    }
		
		
		    /* Pick your policy for "hashing isn't working" here:  */
      258141        if (longest_chain <= HV_MAX_LENGTH_BEFORE_SPLIT /* split worked?  */
			|| HvREHASH(hv)) {
           2    	return;
		    }
		
           2        if (hv == PL_strtab) {
			/* Urg. Someone is doing something nasty to the string table.
			   Can't win.  */
      ######    	return;
		    }
		
		    /* Awooga. Awooga. Pathological data.  */
		    /*PerlIO_printf(PerlIO_stderr(), "%p %d of %d with %d/%d buckets\n", hv,
		      longest_chain, HvTOTALKEYS(hv), HvFILL(hv),  1+HvMAX(hv));*/
		
           2        ++newsize;
		    Newz(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
           2    	 + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
           2        if (SvOOK(hv)) {
           1    	Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
		    }
		
           2        was_shared = HvSHAREKEYS(hv);
		
           2        xhv->xhv_fill = 0;
           2        HvSHAREKEYS_off(hv);
           2        HvREHASH_on(hv);
		
           2        aep = HvARRAY(hv);
		
         290        for (i=0; i<newsize; i++,aep++) {
         288    	register HE *entry = *aep;
         399    	while (entry) {
			    /* We're going to trash this HE's next pointer when we chain it
			       into the new hash below, so store where we go next.  */
         111    	    HE * const next = HeNEXT(entry);
         111    	    UV hash;
         111    	    HE **bep;
		
			    /* Rehash it */
         111    	    PERL_HASH_INTERNAL(hash, HeKEY(entry), HeKLEN(entry));
		
         111    	    if (was_shared) {
				/* Unshare it.  */
				HEK *new_hek
         111    		    = save_hek_flags(HeKEY(entry), HeKLEN(entry),
         111    				     hash, HeKFLAGS(entry));
         111    		unshare_hek (HeKEY_hek(entry));
         111    		HeKEY_hek(entry) = new_hek;
			    } else {
				/* Not shared, so simply write the new hash in. */
      ######    		HeHASH(entry) = hash;
			    }
			    /*PerlIO_printf(PerlIO_stderr(), "%d ", HeKFLAGS(entry));*/
         111    	    HEK_REHASH_on(HeKEY_hek(entry));
			    /*PerlIO_printf(PerlIO_stderr(), "%d\n", HeKFLAGS(entry));*/
		
			    /* Copy oentry to the correct new chain.  */
         111    	    bep = ((HE**)a) + (hash & (I32) xhv->xhv_max);
         111    	    if (!*bep)
          99    		    xhv->xhv_fill++; /* HvFILL(hv)++ */
         111    	    HeNEXT(entry) = *bep;
         111    	    *bep = entry;
		
         111    	    entry = next;
			}
		    }
           2        Safefree (HvARRAY(hv));
           2        HvARRAY(hv) = (HE **)a;
		}
		
		void
		Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
        4820    {
        4820        register XPVHV* xhv = (XPVHV*)SvANY(hv);
        4820        const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
        4820        register I32 newsize;
        4820        register I32 i;
        4820        register char *a;
        4820        register HE **aep;
        4820        register HE *entry;
        4820        register HE **oentry;
		
        4820        newsize = (I32) newmax;			/* possible truncation here */
        4820        if (newsize != newmax || newmax <= oldsize)
        4540    	return;
        4623        while ((newsize & (1 + ~newsize)) != newsize) {
          83    	newsize &= ~(newsize & (1 + ~newsize));	/* get proper power of 2 */
		    }
        4540        if (newsize < newmax)
          36    	newsize *= 2;
        4540        if (newsize < newmax)
      ######    	return;					/* overflow detection */
		
        4540        a = (char *) HvARRAY(hv);
        4540        if (a) {
           2    	PL_nomemok = TRUE;
		#if defined(STRANGE_MALLOC) || defined(MYMALLOC)
			Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
			      + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
			if (!a) {
			  PL_nomemok = FALSE;
			  return;
			}
			if (SvOOK(hv)) {
			    Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
			}
		#else
			New(2, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
           2    	    + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
           2    	if (!a) {
      ######    	  PL_nomemok = FALSE;
      ######    	  return;
			}
           2    	Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
           2    	if (SvOOK(hv)) {
           2    	    Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
			}
           2    	if (oldsize >= 64) {
      ######    	    offer_nice_chunk(HvARRAY(hv),
					     PERL_HV_ARRAY_ALLOC_BYTES(oldsize)
					     + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0));
			}
			else
           2    	    Safefree(HvARRAY(hv));
		#endif
           2    	PL_nomemok = FALSE;
           2    	Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
		    }
		    else {
        4538    	Newz(0, a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
		    }
        4540        xhv->xhv_max = --newsize; 	/* HvMAX(hv) = --newsize */
        4540        HvARRAY(hv) = (HE **) a;
        4540        if (!xhv->xhv_fill /* !HvFILL(hv) */)	/* skip rest if no entries */
        4538    	return;
		
           2        aep = (HE**)a;
          50        for (i=0; i<oldsize; i++,aep++) {
          48    	if (!*aep)				/* non-existent */
          20    	    continue;
          68    	for (oentry = aep, entry = *aep; entry; entry = *oentry) {
          40    	    register I32 j;
          40    	    if ((j = (HeHASH(entry) & newsize)) != i) {
          36    		j -= i;
          36    		*oentry = HeNEXT(entry);
          36    		if (!(HeNEXT(entry) = aep[j]))
          35    		    xhv->xhv_fill++; /* HvFILL(hv)++ */
          36    		aep[j] = entry;
          36    		continue;
			    }
			    else
           4    		oentry = &HeNEXT(entry);
			}
          28    	if (!*aep)				/* everything moved */
          24    	    xhv->xhv_fill--; /* HvFILL(hv)-- */
		    }
		}
		
		/*
		=for apidoc newHV
		
		Creates a new HV.  The reference count is set to 1.
		
		=cut
		*/
		
		HV *
		Perl_newHV(pTHX)
     1284945    {
     1284945        register XPVHV* xhv;
     1284945        HV * const hv = (HV*)NEWSV(502,0);
		
     1284945        sv_upgrade((SV *)hv, SVt_PVHV);
     1284945        xhv = (XPVHV*)SvANY(hv);
     1284945        SvPOK_off(hv);
     1284945        SvNOK_off(hv);
		#ifndef NODEFAULT_SHAREKEYS
     1284945        HvSHAREKEYS_on(hv);         /* key-sharing on by default */
		#endif
		
     1284945        xhv->xhv_max    = 7;	/* HvMAX(hv) = 7 (start with 8 buckets) */
     1284945        xhv->xhv_fill   = 0;	/* HvFILL(hv) = 0 */
     1284945        return hv;
		}
		
		HV *
		Perl_newHVhv(pTHX_ HV *ohv)
         331    {
         331        HV * const hv = newHV();
         331        STRLEN hv_max, hv_fill;
		
         331        if (!ohv || (hv_fill = HvFILL(ohv)) == 0)
          25    	return hv;
         306        hv_max = HvMAX(ohv);
		
         306        if (!SvMAGICAL((SV *)ohv)) {
			/* It's an ordinary hash, so copy it fast. AMS 20010804 */
         306    	STRLEN i;
         306    	const bool shared = !!HvSHAREKEYS(ohv);
         306    	HE **ents, **oents = (HE **)HvARRAY(ohv);
         306    	char *a;
         306    	New(0, a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
         306    	ents = (HE**)a;
		
			/* In each bucket... */
        2754    	for (i = 0; i <= hv_max; i++) {
        2448    	    HE *prev = NULL, *ent = NULL, *oent = oents[i];
		
        2448    	    if (!oent) {
        1823    		ents[i] = NULL;
        1823    		continue;
			    }
		
			    /* Copy the linked list of entries. */
        1626    	    for (oent = oents[i]; oent; oent = HeNEXT(oent)) {
        1001    		const U32 hash   = HeHASH(oent);
        1001    		const char * const key = HeKEY(oent);
        1001    		const STRLEN len = HeKLEN(oent);
        1001    		const int flags  = HeKFLAGS(oent);
		
        1001    		ent = new_HE();
        1001    		HeVAL(ent)     = newSVsv(HeVAL(oent));
        1001    		HeKEY_hek(ent)
		                    = shared ? share_hek_flags(key, len, hash, flags)
		                             :  save_hek_flags(key, len, hash, flags);
        1001    		if (prev)
         376    		    HeNEXT(prev) = ent;
				else
         625    		    ents[i] = ent;
        1001    		prev = ent;
        1001    		HeNEXT(ent) = NULL;
			    }
			}
		
         306    	HvMAX(hv)   = hv_max;
         306    	HvFILL(hv)  = hv_fill;
         306    	HvTOTALKEYS(hv)  = HvTOTALKEYS(ohv);
         306    	HvARRAY(hv) = ents;
		    }
		    else {
			/* Iterate over ohv, copying keys and values one at a time. */
      ######    	HE *entry;
      ######    	const I32 riter = HvRITER_get(ohv);
      ######    	HE * const eiter = HvEITER_get(ohv);
		
			/* Can we use fewer buckets? (hv_max is always 2^n-1) */
      ######    	while (hv_max && hv_max + 1 >= hv_fill * 2)
      ######    	    hv_max = hv_max / 2;
      ######    	HvMAX(hv) = hv_max;
		
      ######    	hv_iterinit(ohv);
      ######    	while ((entry = hv_iternext_flags(ohv, 0))) {
      ######    	    hv_store_flags(hv, HeKEY(entry), HeKLEN(entry),
		                           newSVsv(HeVAL(entry)), HeHASH(entry),
		                           HeKFLAGS(entry));
			}
      ######    	HvRITER_set(ohv, riter);
      ######    	HvEITER_set(ohv, eiter);
		    }
		
         306        return hv;
		}
		
		void
		Perl_hv_free_ent(pTHX_ HV *hv, register HE *entry)
     6656565    {
     6656565        SV *val;
		
     6656565        if (!entry)
      ######    	return;
     6656565        val = HeVAL(entry);
     6656565        if (val && isGV(val) && GvCVu(val) && HvNAME_get(hv))
           5    	PL_sub_generation++;	/* may be deletion of method from stash */
     6656565        SvREFCNT_dec(val);
     6656565        if (HeKLEN(entry) == HEf_SVKEY) {
      ######    	SvREFCNT_dec(HeKEY_sv(entry));
      ######    	Safefree(HeKEY_hek(entry));
		    }
     6656565        else if (HvSHAREKEYS(hv))
     6624098    	unshare_hek(HeKEY_hek(entry));
		    else
       32467    	Safefree(HeKEY_hek(entry));
     6656565        del_HE(entry);
		}
		
		void
		Perl_hv_delayfree_ent(pTHX_ HV *hv, register HE *entry)
      ######    {
      ######        if (!entry)
      ######    	return;
      ######        if (isGV(HeVAL(entry)) && GvCVu(HeVAL(entry)) && HvNAME_get(hv))
      ######    	PL_sub_generation++;	/* may be deletion of method from stash */
      ######        sv_2mortal(HeVAL(entry));	/* free between statements */
      ######        if (HeKLEN(entry) == HEf_SVKEY) {
      ######    	sv_2mortal(HeKEY_sv(entry));
      ######    	Safefree(HeKEY_hek(entry));
		    }
      ######        else if (HvSHAREKEYS(hv))
      ######    	unshare_hek(HeKEY_hek(entry));
		    else
      ######    	Safefree(HeKEY_hek(entry));
      ######        del_HE(entry);
		}
		
		/*
		=for apidoc hv_clear
		
		Clears a hash, making it empty.
		
		=cut
		*/
		
		void
		Perl_hv_clear(pTHX_ HV *hv)
      244430    {
		    dVAR;
      244430        register XPVHV* xhv;
      244430        if (!hv)
      ######    	return;
		
      244430        DEBUG_A(Perl_hv_assert(aTHX_ hv));
		
      244430        xhv = (XPVHV*)SvANY(hv);
		
      244430        if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
			/* restricted hash: convert all keys to placeholders */
           6    	STRLEN i;
          52    	for (i = 0; i <= xhv->xhv_max; i++) {
          47    	    HE *entry = (HvARRAY(hv))[i];
          65    	    for (; entry; entry = HeNEXT(entry)) {
				/* not already placeholder */
          10    		if (HeVAL(entry) != &PL_sv_placeholder) {
           7    		    if (HeVAL(entry) && SvREADONLY(HeVAL(entry))) {
           1    			SV* keysv = hv_iterkeysv(entry);
           1    			Perl_croak(aTHX_
			"Attempt to delete readonly key '%"SVf"' from a restricted hash",
						   keysv);
				    }
           6    		    SvREFCNT_dec(HeVAL(entry));
           6    		    HeVAL(entry) = &PL_sv_placeholder;
           6    		    HvPLACEHOLDERS(hv)++;
				}
			    }
			}
      244424    	goto reset;
		    }
		
      244424        hfreeentries(hv);
      244424        HvPLACEHOLDERS_set(hv, 0);
      244424        if (HvARRAY(hv))
      185902    	(void)memzero(HvARRAY(hv),
				      (xhv->xhv_max+1 /* HvMAX(hv)+1 */) * sizeof(HE*));
		
      244424        if (SvRMAGICAL(hv))
         386    	mg_clear((SV*)hv);
		
      244423        HvHASKFLAGS_off(hv);
      244423        HvREHASH_off(hv);
		    reset:
      244428        if (SvOOK(hv)) {
       93381    	HvEITER_set(hv, NULL);
		    }
		}
		
		/*
		=for apidoc hv_clear_placeholders
		
		Clears any placeholders from a hash.  If a restricted hash has any of its keys
		marked as readonly and the key is subsequently deleted, the key is not actually
		deleted but is marked by assigning it a value of &PL_sv_placeholder.  This tags
		it so it will be ignored by future operations such as iterating over the hash,
		but will still allow the hash to have a value reassigned to the key at some
		future point.  This function clears any such placeholder keys from the hash.
		See Hash::Util::lock_keys() for an example of its use.
		
		=cut
		*/
		
		void
		Perl_hv_clear_placeholders(pTHX_ HV *hv)
          34    {
		    dVAR;
          34        I32 items = (I32)HvPLACEHOLDERS_get(hv);
          34        I32 i;
		
          34        if (items == 0)
          32    	return;
		
           2        i = HvMAX(hv);
          12        do {
			/* Loop down the linked list heads  */
          12    	bool first = 1;
          12    	HE **oentry = &(HvARRAY(hv))[i];
          12    	HE *entry = *oentry;
		
          12    	if (!entry)
           8    	    continue;
		
           8    	for (; entry; entry = *oentry) {
           4    	    if (HeVAL(entry) == &PL_sv_placeholder) {
           2    		*oentry = HeNEXT(entry);
           2    		if (first && !*oentry)
           2    		    HvFILL(hv)--; /* This linked list is now empty.  */
           2    		if (HvEITER_get(hv))
      ######    		    HvLAZYDEL_on(hv);
				else
           2    		    hv_free_ent(hv, entry);
		
           2    		if (--items == 0) {
				    /* Finished.  */
           2    		    HvTOTALKEYS(hv) -= (IV)HvPLACEHOLDERS_get(hv);
           2    		    if (HvKEYS(hv) == 0)
      ######    			HvHASKFLAGS_off(hv);
           2    		    HvPLACEHOLDERS_set(hv, 0);
           2    		    return;
				}
			    } else {
           2    		oentry = &HeNEXT(entry);
           2    		first = 0;
			    }
			}
          10        } while (--i >= 0);
		    /* You can't get here, hence assertion should always fail.  */
      ######        assert (items == 0);
      ######        assert (0);
		}
		
		STATIC void
		S_hfreeentries(pTHX_ HV *hv)
     1560856    {
     1560856        register HE **array;
     1560856        register HE *entry;
     1560856        I32 riter;
     1560856        I32 max;
     1560856        struct xpvhv_aux *iter;
     1560856        if (!hv)
      ######    	return;
     1560856        if (!HvARRAY(hv))
      685934    	return;
		
      874922        iter =  SvOOK(hv) ? HvAUX(hv) : 0;
		
      874922        riter = 0;
      874922        max = HvMAX(hv);
      874922        array = HvARRAY(hv);
		    /* make everyone else think the array is empty, so that the destructors
		     * called for freed entries can't recusively mess with us */
      874922        HvARRAY(hv) = Null(HE**); 
      874922        SvFLAGS(hv) &= ~SVf_OOK;
		
      874922        HvFILL(hv) = 0;
      874922        ((XPVHV*) SvANY(hv))->xhv_keys = 0;
		
      874922        entry = array[0];
    51082946        for (;;) {
    26748148    	if (entry) {
     6544998    	    register HE *oentry = entry;
     6544998    	    entry = HeNEXT(entry);
     6544998    	    hv_free_ent(hv, oentry);
			}
    26748148    	if (!entry) {
    25209720    	    if (++riter > max)
      874922    		break;
    24334798    	    entry = array[riter];
			}
		    }
		
      874922        if (SvOOK(hv)) {
			/* Someone attempted to iterate or set the hash name while we had
			   the array set to 0.  */
           1    	assert(HvARRAY(hv));
		
           1    	if (HvAUX(hv)->xhv_name)
      ######    	    unshare_hek_or_pvn(HvAUX(hv)->xhv_name, 0, 0, 0);
			/* SvOOK_off calls sv_backoff, which isn't correct.  */
		
           1    	Safefree(HvARRAY(hv));
           1    	HvARRAY(hv) = 0;
           1    	SvFLAGS(hv) &= ~SVf_OOK;
		    }
		
		    /* FIXME - things will still go horribly wrong (or at least leak) if
		       people attempt to add elements to the hash while we're undef()ing it  */
      874922        if (iter) {
      282633    	entry = iter->xhv_eiter; /* HvEITER(hv) */
      282633    	if (entry && HvLAZYDEL(hv)) {	/* was deleted earlier? */
      ######    	    HvLAZYDEL_off(hv);
      ######    	    hv_free_ent(hv, entry);
			}
      282633    	iter->xhv_riter = -1; 	/* HvRITER(hv) = -1 */
      282633    	iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
      282633    	SvFLAGS(hv) |= SVf_OOK;
		    }
		
      874922        HvARRAY(hv) = array;
		}
		
		/*
		=for apidoc hv_undef
		
		Undefines the hash.
		
		=cut
		*/
		
		void
		Perl_hv_undef(pTHX_ HV *hv)
     1316432    {
     1316432        register XPVHV* xhv;
     1316432        const char *name;
     1316432        if (!hv)
      ######    	return;
     1316432        DEBUG_A(Perl_hv_assert(aTHX_ hv));
     1316432        xhv = (XPVHV*)SvANY(hv);
     1316432        hfreeentries(hv);
     1316432        if ((name = HvNAME_get(hv))) {
      142179            if(PL_stashcache)
        5148    	    hv_delete(PL_stashcache, name, HvNAMELEN_get(hv), G_DISCARD);
      142179    	Perl_hv_name_set(aTHX_ hv, 0, 0, 0);
		    }
     1316432        SvFLAGS(hv) &= ~SVf_OOK;
     1316432        Safefree(HvARRAY(hv));
     1316432        xhv->xhv_max   = 7;	/* HvMAX(hv) = 7 (it's a normal hash) */
     1316432        HvARRAY(hv) = 0;
     1316432        HvPLACEHOLDERS_set(hv, 0);
		
     1316432        if (SvRMAGICAL(hv))
      131957    	mg_clear((SV*)hv);
		}
		
		static struct xpvhv_aux*
      188251    S_hv_auxinit(pTHX_ HV *hv) {
      188251        struct xpvhv_aux *iter;
      188251        char *array;
		
      188251        if (!HvARRAY(hv)) {
			Newz(0, array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
      148592    	    + sizeof(struct xpvhv_aux), char);
		    } else {
       39659    	array = (char *) HvARRAY(hv);
			Renew(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
       39659    	      + sizeof(struct xpvhv_aux), char);
		    }
      188251        HvARRAY(hv) = (HE**) array;
		    /* SvOOK_on(hv) attacks the IV flags.  */
      188251        SvFLAGS(hv) |= SVf_OOK;
      188251        iter = HvAUX(hv);
		
      188251        iter->xhv_riter = -1; 	/* HvRITER(hv) = -1 */
      188251        iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
      188251        iter->xhv_name = 0;
		
      188251        return iter;
		}
		
		/*
		=for apidoc hv_iterinit
		
		Prepares a starting point to traverse a hash table.  Returns the number of
		keys in the hash (i.e. the same as C<HvKEYS(tb)>).  The return value is
		currently only meaningful for hashes without tie magic.
		
		NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
		hash buckets that happen to be in use.  If you still need that esoteric
		value, you can get it through the macro C<HvFILL(tb)>.
		
		
		=cut
		*/
		
		I32
		Perl_hv_iterinit(pTHX_ HV *hv)
      166441    {
      166441        HE *entry;
		
      166441        if (!hv)
      ######    	Perl_croak(aTHX_ "Bad hash");
		
      166441        if (SvOOK(hv)) {
      119382    	struct xpvhv_aux *iter = HvAUX(hv);
      119382    	entry = iter->xhv_eiter; /* HvEITER(hv) */
      119382    	if (entry && HvLAZYDEL(hv)) {	/* was deleted earlier? */
      ######    	    HvLAZYDEL_off(hv);
      ######    	    hv_free_ent(hv, entry);
			}
      119382    	iter->xhv_riter = -1; 	/* HvRITER(hv) = -1 */
      119382    	iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
		    } else {
       47059    	S_hv_auxinit(aTHX_ hv);
		    }
		
		    /* used to be xhv->xhv_fill before 5.004_65 */
      166441        return HvTOTALKEYS(hv);
		}
		
		I32 *
           8    Perl_hv_riter_p(pTHX_ HV *hv) {
           8        struct xpvhv_aux *iter;
		
           8        if (!hv)
      ######    	Perl_croak(aTHX_ "Bad hash");
		
           8        iter = SvOOK(hv) ? HvAUX(hv) : S_hv_auxinit(aTHX_ hv);
           8        return &(iter->xhv_riter);
		}
		
		HE **
      ######    Perl_hv_eiter_p(pTHX_ HV *hv) {
      ######        struct xpvhv_aux *iter;
		
      ######        if (!hv)
      ######    	Perl_croak(aTHX_ "Bad hash");
		
      ######        iter = SvOOK(hv) ? HvAUX(hv) : S_hv_auxinit(aTHX_ hv);
      ######        return &(iter->xhv_eiter);
		}
		
		void
        1023    Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
        1023        struct xpvhv_aux *iter;
		
        1023        if (!hv)
      ######    	Perl_croak(aTHX_ "Bad hash");
		
        1023        if (SvOOK(hv)) {
        1023    	iter = HvAUX(hv);
		    } else {
      ######    	if (riter == -1)
      ######    	    return;
		
      ######    	iter = S_hv_auxinit(aTHX_ hv);
		    }
        1023        iter->xhv_riter = riter;
		}
		
		void
       96244    Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
       96244        struct xpvhv_aux *iter;
		
       96244        if (!hv)
      ######    	Perl_croak(aTHX_ "Bad hash");
		
       96244        if (SvOOK(hv)) {
       94448    	iter = HvAUX(hv);
		    } else {
			/* 0 is the default so don't go malloc()ing a new structure just to
			   hold 0.  */
        1796    	if (!eiter)
        1796    	    return;
		
      ######    	iter = S_hv_auxinit(aTHX_ hv);
		    }
       94448        iter->xhv_eiter = eiter;
		}
		
		void
		Perl_hv_name_set(pTHX_ HV *hv, const char *name, I32 len, int flags)
      283693    {
      283693        struct xpvhv_aux *iter;
      283693        U32 hash;
      283693        (void)flags;
		
      283693        if (SvOOK(hv)) {
      142508    	iter = HvAUX(hv);
      142508    	if (iter->xhv_name) {
      142508    	    unshare_hek_or_pvn(iter->xhv_name, 0, 0, 0);
			}
		    } else {
      141185    	if (name == 0)
      ######    	    return;
		
      141185    	iter = S_hv_auxinit(aTHX_ hv);
		    }
      283693        PERL_HASH(hash, name, len);
      283693        iter->xhv_name = name ? share_hek(name, len, hash) : 0;
		}
		
		/*
		=for apidoc hv_iternext
		
		Returns entries from a hash iterator.  See C<hv_iterinit>.
		
		You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
		iterator currently points to, without losing your place or invalidating your
		iterator.  Note that in this case the current entry is deleted from the hash
		with your iterator holding the last reference to it.  Your iterator is flagged
		to free the entry on the next call to C<hv_iternext>, so you must not discard
		your iterator immediately else the entry will leak - call C<hv_iternext> to
		trigger the resource deallocation.
		
		=cut
		*/
		
		HE *
		Perl_hv_iternext(pTHX_ HV *hv)
     2528177    {
     2528177        return hv_iternext_flags(hv, 0);
		}
		
		/*
		=for apidoc hv_iternext_flags
		
		Returns entries from a hash iterator.  See C<hv_iterinit> and C<hv_iternext>.
		The C<flags> value will normally be zero; if HV_ITERNEXT_WANTPLACEHOLDERS is
		set the placeholders keys (for restricted hashes) will be returned in addition
		to normal keys. By default placeholders are automatically skipped over.
		Currently a placeholder is implemented with a value that is
		C<&Perl_sv_placeholder>. Note that the implementation of placeholders and
		restricted hashes may change, and the implementation currently is
		insufficiently abstracted for any change to be tidy.
		
		=cut
		*/
		
		HE *
		Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
     2558185    {
		    dVAR;
     2558185        register XPVHV* xhv;
     2558185        register HE *entry;
     2558185        HE *oldentry;
     2558185        MAGIC* mg;
     2558185        struct xpvhv_aux *iter;
		
     2558185        if (!hv)
      ######    	Perl_croak(aTHX_ "Bad hash");
     2558185        xhv = (XPVHV*)SvANY(hv);
		
     2558185        if (!SvOOK(hv)) {
			/* Too many things (well, pp_each at least) merrily assume that you can
			   call iv_iternext without calling hv_iterinit, so we'll have to deal
			   with it.  */
         716    	hv_iterinit(hv);
		    }
     2558185        iter = HvAUX(hv);
		
     2558185        oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
		
     2558185        if ((mg = SvTIED_mg((SV*)hv, PERL_MAGIC_tied))) {
      107958    	SV *key = sv_newmortal();
      107958    	if (entry) {
      107098    	    sv_setsv(key, HeSVKEY_force(entry));
      107098    	    SvREFCNT_dec(HeSVKEY(entry));	/* get rid of previous key */
			}
			else {
         860    	    char *k;
         860    	    HEK *hek;
		
			    /* one HE per MAGICAL hash */
         860    	    iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
         860    	    Zero(entry, 1, HE);
         860    	    Newz(54, k, HEK_BASESIZE + sizeof(SV*), char);
         860    	    hek = (HEK*)k;
         860    	    HeKEY_hek(entry) = hek;
         860    	    HeKLEN(entry) = HEf_SVKEY;
			}
      107958    	magic_nextpack((SV*) hv,mg,key);
      107958    	if (SvOK(key)) {
			    /* force key to stay around until next time */
      107100    	    HeSVKEY_set(entry, SvREFCNT_inc(key));
      107100    	    return entry;		/* beware, hent_val is not set */
			}
         858    	if (HeVAL(entry))
      ######    	    SvREFCNT_dec(HeVAL(entry));
         858    	Safefree(HeKEY_hek(entry));
         858    	del_HE(entry);
         858    	iter->xhv_eiter = Null(HE*); /* HvEITER(hv) = Null(HE*) */
         858    	return Null(HE*);
		    }
		#ifdef DYNAMIC_ENV_FETCH  /* set up %ENV for iteration */
		    if (!entry && SvRMAGICAL((SV*)hv) && mg_find((SV*)hv, PERL_MAGIC_env))
			prime_env_iter();
		#endif
		
		    /* hv_iterint now ensures this.  */
     2450227        assert (HvARRAY(hv));
		
		    /* At start of hash, entry is NULL.  */
     2450227        if (entry)
		    {
     2283865    	entry = HeNEXT(entry);
     2283865            if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
		            /*
		             * Skip past any placeholders -- don't want to include them in
		             * any iteration.
		             */
     2274255                while (entry && HeVAL(entry) == &PL_sv_placeholder) {
           8                    entry = HeNEXT(entry);
		            }
			}
		    }
    11431341        while (!entry) {
			/* OK. Come to the end of the current list.  Grab the next one.  */
		
     9146369    	iter->xhv_riter++; /* HvRITER(hv)++ */
     9146369    	if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
			    /* There is no next one.  End of the hash.  */
      165255    	    iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
      165255    	    break;
			}
     8981114    	entry = (HvARRAY(hv))[iter->xhv_riter];
		
     8981114            if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
		            /* If we have an entry, but it's a placeholder, don't count it.
			       Try the next.  */
     8962830    	    while (entry && HeVAL(entry) == &PL_sv_placeholder)
          64    		entry = HeNEXT(entry);
			}
			/* Will loop again if this linked list starts NULL
			   (for HV_ITERNEXT_WANTPLACEHOLDERS)
			   or if we run through it and find only placeholders.  */
		    }
		
     2450227        if (oldentry && HvLAZYDEL(hv)) {		/* was deleted earlier? */
          10    	HvLAZYDEL_off(hv);
          10    	hv_free_ent(hv, oldentry);
		    }
		
		    /*if (HvREHASH(hv) && entry && !HeKREHASH(entry))
		      PerlIO_printf(PerlIO_stderr(), "Awooga %p %p\n", hv, entry);*/
		
     2450227        iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
     2450227        return entry;
		}
		
		/*
		=for apidoc hv_iterkey
		
		Returns the key from the current position of the hash iterator.  See
		C<hv_iterinit>.
		
		=cut
		*/
		
		char *
		Perl_hv_iterkey(pTHX_ register HE *entry, I32 *retlen)
       19053    {
       19053        if (HeKLEN(entry) == HEf_SVKEY) {
      ######    	STRLEN len;
      ######    	char *p = SvPV(HeKEY_sv(entry), len);
      ######    	*retlen = len;
      ######    	return p;
		    }
		    else {
       19053    	*retlen = HeKLEN(entry);
       19053    	return HeKEY(entry);
		    }
		}
		
		/* unlike hv_iterval(), this always returns a mortal copy of the key */
		/*
		=for apidoc hv_iterkeysv
		
		Returns the key as an C<SV*> from the current position of the hash
		iterator.  The return value will always be a mortal copy of the key.  Also
		see C<hv_iterinit>.
		
		=cut
		*/
		
		SV *
		Perl_hv_iterkeysv(pTHX_ register HE *entry)
     2300755    {
     2300755        return sv_2mortal(newSVhek(HeKEY_hek(entry)));
		}
		
		/*
		=for apidoc hv_iterval
		
		Returns the value from the current position of the hash iterator.  See
		C<hv_iterkey>.
		
		=cut
		*/
		
		SV *
		Perl_hv_iterval(pTHX_ HV *hv, register HE *entry)
      343754    {
      343754        if (SvRMAGICAL(hv)) {
      129967    	if (mg_find((SV*)hv, PERL_MAGIC_tied)) {
      105439    	    SV* sv = sv_newmortal();
      105439    	    if (HeKLEN(entry) == HEf_SVKEY)
      105439    		mg_copy((SV*)hv, sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
			    else
      ######    		mg_copy((SV*)hv, sv, HeKEY(entry), HeKLEN(entry));
      105439    	    return sv;
			}
		    }
      238315        return HeVAL(entry);
		}
		
		/*
		=for apidoc hv_iternextsv
		
		Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
		operation.
		
		=cut
		*/
		
		SV *
		Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
       19380    {
       19380        HE *he;
       19380        if ( (he = hv_iternext_flags(hv, 0)) == NULL)
        1163    	return NULL;
       18217        *key = hv_iterkey(he, retlen);
       18217        return hv_iterval(hv, he);
		}
		
		/*
		=for apidoc hv_magic
		
		Adds magic to a hash.  See C<sv_magic>.
		
		=cut
		*/
		
		void
		Perl_hv_magic(pTHX_ HV *hv, GV *gv, int how)
        7173    {
        7173        sv_magic((SV*)hv, (SV*)gv, how, Nullch, 0);
		}
		
		#if 0 /* use the macro from hv.h instead */
		
		char*	
		Perl_sharepvn(pTHX_ const char *sv, I32 len, U32 hash)
		{
		    return HEK_KEY(share_hek(sv, len, hash));
		}
		
		#endif
		
		/* possibly free a shared string if no one has access to it
		 * len and hash must both be valid for str.
		 */
		void
		Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
      ######    {
      ######        unshare_hek_or_pvn (NULL, str, len, hash);
		}
		
		
		void
		Perl_unshare_hek(pTHX_ HEK *hek)
    10101144    {
    10101144        unshare_hek_or_pvn(hek, NULL, 0, 0);
		}
		
		/* possibly free a shared string if no one has access to it
		   hek if non-NULL takes priority over the other 3, else str, len and hash
		   are used.  If so, len and hash must both be valid for str.
		 */
		STATIC void
		S_unshare_hek_or_pvn(pTHX_ const HEK *hek, const char *str, I32 len, U32 hash)
    10243652    {
    10243652        register XPVHV* xhv;
    10243652        register HE *entry;
    10243652        register HE **oentry;
    10243652        HE **first;
    10243652        bool found = 0;
    10243652        bool is_utf8 = FALSE;
    10243652        int k_flags = 0;
    10243652        const char *save = str;
    10243652        struct shared_he *he = 0;
		
    10243652        if (hek) {
			/* Find the shared he which is just before us in memory.  */
    10243652    	he = (struct shared_he *)(((char *)hek)
						  - STRUCT_OFFSET(struct shared_he,
								  shared_he_hek));
		
			/* Assert that the caller passed us a genuine (or at least consistent)
			   shared hek  */
    10243652    	assert (he->shared_he_he.hent_hek == hek);
		
			LOCK_STRTAB_MUTEX;
    10243652    	if (he->shared_he_he.hent_val - 1) {
     7693329    	    --he->shared_he_he.hent_val;
			    UNLOCK_STRTAB_MUTEX;
     7693329    	    return;
			}
			UNLOCK_STRTAB_MUTEX;
		
     2550323            hash = HEK_HASH(hek);
      ######        } else if (len < 0) {
      ######            STRLEN tmplen = -len;
      ######            is_utf8 = TRUE;
		        /* See the note in hv_fetch(). --jhi */
      ######            str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
      ######            len = tmplen;
      ######            if (is_utf8)
      ######                k_flags = HVhek_UTF8;
      ######            if (str != save)
      ######                k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
		    }
		
		    /* what follows is the moral equivalent of:
		    if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
			if (--*Svp == Nullsv)
			    hv_delete(PL_strtab, str, len, G_DISCARD, hash);
		    } */
     2550323        xhv = (XPVHV*)SvANY(PL_strtab);
		    /* assert(xhv_array != 0) */
		    LOCK_STRTAB_MUTEX;
     2550323        first = oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
     2550323        if (he) {
     2550323    	const HE *const he_he = &(he->shared_he_he);
     2803210            for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
     2803210                if (entry != he_he)
      252887                    continue;
     2550323                found = 1;
     2550323                break;
		        }
		    } else {
      ######            const int flags_masked = k_flags & HVhek_MASK;
      ######            for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
      ######                if (HeHASH(entry) != hash)		/* strings can't be equal */
      ######                    continue;
      ######                if (HeKLEN(entry) != len)
      ######                    continue;
      ######                if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len))	/* is this it? */
      ######                    continue;
      ######                if (HeKFLAGS(entry) != flags_masked)
      ######                    continue;
      ######                found = 1;
      ######                break;
		        }
		    }
		
     2550323        if (found) {
     2550323            if (--HeVAL(entry) == Nullsv) {
     2550323                *oentry = HeNEXT(entry);
     2550323                if (!*first) {
				/* There are now no entries in our slot.  */
     1855513                    xhv->xhv_fill--; /* HvFILL(hv)-- */
			    }
     2550323                Safefree(entry);
     2550323                xhv->xhv_keys--; /* HvKEYS(hv)-- */
		        }
		    }
		
		    UNLOCK_STRTAB_MUTEX;
     2550323        if (!found && ckWARN_d(WARN_INTERNAL))
      ######    	Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
		                    "Attempt to free non-existent shared string '%s'%s"
		                    pTHX__FORMAT,
		                    hek ? HEK_KEY(hek) : str,
		                    ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
     2550323        if (k_flags & HVhek_FREEKEY)
      ######    	Safefree(str);
		}
		
		/* get a (constant) string ptr from the global string table
		 * string will get added if it is not already there.
		 * len and hash must both be valid for str.
		 */
		HEK *
		Perl_share_hek(pTHX_ const char *str, I32 len, register U32 hash)
     3240840    {
     3240840        bool is_utf8 = FALSE;
     3240840        int flags = 0;
     3240840        const char *save = str;
		
     3240840        if (len < 0) {
         392          STRLEN tmplen = -len;
         392          is_utf8 = TRUE;
		      /* See the note in hv_fetch(). --jhi */
         392          str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
         392          len = tmplen;
		      /* If we were able to downgrade here, then than means that we were passed
		         in a key which only had chars 0-255, but was utf8 encoded.  */
         392          if (is_utf8)
         392              flags = HVhek_UTF8;
		      /* If we found we were able to downgrade the string to bytes, then
		         we should flag that it needs upgrading on keys or each.  Also flag
		         that we need share_hek_flags to free the string.  */
         392          if (str != save)
      ######              flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
		    }
		
     3240840        return share_hek_flags (str, len, hash, flags);
		}
		
		STATIC HEK *
		S_share_hek_flags(pTHX_ const char *str, I32 len, register U32 hash, int flags)
     9842852    {
     9842852        register HE *entry;
     9842852        register HE **oentry;
     9842852        I32 found = 0;
     9842852        const int flags_masked = flags & HVhek_MASK;
		
		    /* what follows is the moral equivalent of:
		
		    if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
			hv_store(PL_strtab, str, len, Nullsv, hash);
		
			Can't rehash the shared string table, so not sure if it's worth
			counting the number of entries in the linked list
		    */
     9842852        register XPVHV * const xhv = (XPVHV*)SvANY(PL_strtab);
		    /* assert(xhv_array != 0) */
		    LOCK_STRTAB_MUTEX;
     9842852        oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
    12747463        for (entry = *oentry; entry; entry = HeNEXT(entry)) {
    10212523    	if (HeHASH(entry) != hash)		/* strings can't be equal */
     2903402    	    continue;
     7309121    	if (HeKLEN(entry) != len)
        1030    	    continue;
     7308091    	if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len))	/* is this it? */
      ######    	    continue;
     7308091    	if (HeKFLAGS(entry) != flags_masked)
         179    	    continue;
     7307912    	found = 1;
     7307912    	break;
		    }
     9842852        if (!found) {
			/* What used to be head of the list.
			   If this is NULL, then we're the first entry for this slot, which
			   means we need to increate fill.  */
     2534940    	const HE *old_first = *oentry;
     2534940    	struct shared_he *new_entry;
     2534940    	HEK *hek;
     2534940    	char *k;
		
			/* We don't actually store a HE from the arena and a regular HEK.
			   Instead we allocate one chunk of memory big enough for both,
			   and put the HEK straight after the HE. This way we can find the
			   HEK directly from the HE.
			*/
		
			New(0, k, STRUCT_OFFSET(struct shared_he,
     2534940    				shared_he_hek.hek_key[0]) + len + 2, char);
     2534940    	new_entry = (struct shared_he *)k;
     2534940    	entry = &(new_entry->shared_he_he);
     2534940    	hek = &(new_entry->shared_he_hek);
		
     2534940    	Copy(str, HEK_KEY(hek), len, char);
     2534940    	HEK_KEY(hek)[len] = 0;
     2534940    	HEK_LEN(hek) = len;
     2534940    	HEK_HASH(hek) = hash;
     2534940    	HEK_FLAGS(hek) = (unsigned char)flags_masked;
		
			/* Still "point" to the HEK, so that other code need not know what
			   we're up to.  */
     2534940    	HeKEY_hek(entry) = hek;
     2534940    	HeVAL(entry) = Nullsv;
     2534940    	HeNEXT(entry) = *oentry;
     2534940    	*oentry = entry;
		
     2534940    	xhv->xhv_keys++; /* HvKEYS(hv)++ */
     2534940    	if (!old_first) {			/* initial entry? */
     1580364    	    xhv->xhv_fill++; /* HvFILL(hv)++ */
      954576    	} else if (xhv->xhv_keys > (IV)xhv->xhv_max /* HvKEYS(hv) > HvMAX(hv) */) {
        2071    		hsplit(PL_strtab);
			}
		    }
		
     9842852        ++HeVAL(entry);				/* use value slot as REFCNT */
		    UNLOCK_STRTAB_MUTEX;
		
     9842852        if (flags & HVhek_FREEKEY)
         703    	Safefree(str);
		
     9842852        return HeKEY_hek(entry);
		}
		
		I32 *
		Perl_hv_placeholders_p(pTHX_ HV *hv)
         317    {
		    dVAR;
         317        MAGIC *mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
		
         317        if (!mg) {
          33    	mg = sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, 0);
		
          33    	if (!mg) {
      ######    	    Perl_die(aTHX_ "panic: hv_placeholders_p");
			}
		    }
         317        return &(mg->mg_len);
		}
		
		
		I32
		Perl_hv_placeholders_get(pTHX_ HV *hv)
       98393    {
		    dVAR;
       98393        MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
		
       98393        return mg ? mg->mg_len : 0;
		}
		
		void
		Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
     1560858    {
		    dVAR;
     1560858        MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_rhash);
		
     1560858        if (mg) {
          20    	mg->mg_len = ph;
     1560838        } else if (ph) {
      ######    	if (!sv_magicext((SV*)hv, 0, PERL_MAGIC_rhash, 0, 0, ph))
      ######    	    Perl_die(aTHX_ "panic: hv_placeholders_set");
		    }
		    /* else we don't need to add magic to record 0 placeholders.  */
		}
		
		/*
		=for apidoc hv_assert
		
		Check that a hash is in an internally consistent state.
		
		=cut
		*/
		
		void
		Perl_hv_assert(pTHX_ HV *hv)
      ######    {
		  dVAR;
      ######      HE* entry;
      ######      int withflags = 0;
      ######      int placeholders = 0;
      ######      int real = 0;
      ######      int bad = 0;
      ######      const I32 riter = HvRITER_get(hv);
      ######      HE *eiter = HvEITER_get(hv);
		
      ######      (void)hv_iterinit(hv);
		
      ######      while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
		    /* sanity check the values */
      ######        if (HeVAL(entry) == &PL_sv_placeholder) {
      ######          placeholders++;
		    } else {
      ######          real++;
		    }
		    /* sanity check the keys */
      ######        if (HeSVKEY(entry)) {
		      /* Don't know what to check on SV keys.  */
      ######        } else if (HeKUTF8(entry)) {
      ######          withflags++;
      ######           if (HeKWASUTF8(entry)) {
      ######    	 PerlIO_printf(Perl_debug_log,
				       "hash key has both WASUFT8 and UTF8: '%.*s'\n",
				       (int) HeKLEN(entry),  HeKEY(entry));
      ######    	 bad = 1;
		       }
      ######        } else if (HeKWASUTF8(entry)) {
      ######          withflags++;
		    }
		  }
      ######      if (!SvTIED_mg((SV*)hv, PERL_MAGIC_tied)) {
      ######        if (HvUSEDKEYS(hv) != real) {
      ######          PerlIO_printf(Perl_debug_log, "Count %d key(s), but hash reports %d\n",
				    (int) real, (int) HvUSEDKEYS(hv));
      ######          bad = 1;
		    }
      ######        if (HvPLACEHOLDERS_get(hv) != placeholders) {
      ######          PerlIO_printf(Perl_debug_log,
				    "Count %d placeholder(s), but hash reports %d\n",
				    (int) placeholders, (int) HvPLACEHOLDERS_get(hv));
      ######          bad = 1;
		    }
		  }
      ######      if (withflags && ! HvHASKFLAGS(hv)) {
      ######        PerlIO_printf(Perl_debug_log,
				  "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
				  withflags);
      ######        bad = 1;
		  }
      ######      if (bad) {
      ######        sv_dump((SV *)hv);
		  }
      ######      HvRITER_set(hv, riter);		/* Restore hash iterator state */
      ######      HvEITER_set(hv, eiter);
		}
		
		/*
		 * Local variables:
		 * c-indentation-style: bsd
		 * c-basic-offset: 4
		 * indent-tabs-mode: t
		 * End:
		 *
		 * ex: set ts=8 sts=4 sw=4 noet:
		 */
