home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 1996 February / PCWK0296.iso / sharewar / dos / program / gs300sr1 / gs300sr1.exe / IDICT.C < prev    next >
C/C++ Source or Header  |  1994-07-27  |  28KB  |  867 lines

  1. /* Copyright (C) 1989, 1992, 1993, 1994 Aladdin Enterprises.  All rights reserved.
  2.   
  3.   This file is part of Aladdin Ghostscript.
  4.   
  5.   Aladdin Ghostscript is distributed with NO WARRANTY OF ANY KIND.  No author
  6.   or distributor accepts any responsibility for the consequences of using it,
  7.   or for whether it serves any particular purpose or works at all, unless he
  8.   or she says so in writing.  Refer to the Aladdin Ghostscript Free Public
  9.   License (the "License") for full details.
  10.   
  11.   Every copy of Aladdin Ghostscript must include a copy of the License,
  12.   normally in a plain ASCII text file named PUBLIC.  The License grants you
  13.   the right to copy, modify and redistribute Aladdin Ghostscript, but only
  14.   under certain conditions described in the License.  Among other things, the
  15.   License requires that the copyright notice and this notice be preserved on
  16.   all copies.
  17. */
  18.  
  19. /* idict.c */
  20. /* Dictionaries for Ghostscript */
  21. #include "string_.h"            /* for strlen */
  22. #include "ghost.h"
  23. #include "errors.h"
  24. #include "ialloc.h"
  25. #include "iname.h"
  26. #include "ipacked.h"
  27. #include "isave.h"            /* for value cache in names */
  28. #include "store.h"
  29. #include "idict.h"            /* interface definition */
  30. #include "dstack.h"            /* interface & some implementation */
  31. #include "iutil.h"            /* for array_get and obj_eq */
  32. #include "ivmspace.h"            /* for store check */
  33.  
  34. /*
  35.  * A dictionary of capacity M is a structure of four elements (refs):
  36.  *
  37.  *    keys - a t_shortarray or t_array of M+1 elements, containing
  38.  *    the keys.
  39.  *
  40.  *    values - a t_array of M+1 elements, containing the values.
  41.  *
  42.  *    count - a t_integer whose value tells how many entries are
  43.  *    occupied (N).
  44.  *
  45.  *    maxlength - a t_integer whose value gives the client's view of
  46.  *    the capacity (C).  C may be less than M (see below).
  47.  *
  48.  * C < M is possible because on large-memory systems, we round up M so that
  49.  * M is a power of 2; this allows us to use masking rather than division
  50.  * for computing the initial hash probe.  However, C is always the
  51.  * maxlength specified by the client, so clients get a consistent story.
  52.  *
  53.  * As noted above, the keys may be either in packed or unpacked form.
  54.  * The markers for unused and deleted entries are different in the two forms.
  55.  * In the packed form:
  56.  *    unused entries contain packed_key_empty;
  57.  *    deleted entries contain packed_key_deleted.
  58.  * In the unpacked form:
  59.  *    unused entries contain a literal null;
  60.  *    deleted entries contain an executable null.
  61.  *
  62.  * The first entry is always marked deleted, to reduce the cost of the
  63.  * wrap-around check.
  64.  *
  65.  * Note that if the keys slot in the dictionary is new,
  66.  * all the key slots are new (more recent than the last save).
  67.  * We use this fact to avoid saving stores into packed keys
  68.  * for newly created dictionaries.
  69.  *
  70.  * Note that name keys with indices above packed_max_value require using
  71.  * the unpacked form.
  72.  */
  73. #define dict_is_packed(dct) r_has_type(&(dct)->keys, t_shortarray)
  74. #define packed_key_empty (pt_tag(pt_integer) + 0)
  75. #define packed_key_deleted (pt_tag(pt_integer) + 1)
  76. #define packed_key_impossible pt_tag(pt_full_ref)    /* never matches */
  77. #define packed_name_key(nidx)\
  78.   ((nidx) <= packed_max_value ? pt_tag(pt_literal_name) + (nidx) :\
  79.    packed_key_impossible)
  80. /*
  81.  * Using a special mark for deleted entries causes lookup time to degrade
  82.  * as entries are inserted and deleted.  This is not a problem, because
  83.  * entries are almost never deleted.
  84.  */
  85. #define d_maxlength(dct) ((uint)((dct)->maxlength.value.intval))
  86. #define d_set_maxlength(dct,siz) ((dct)->maxlength.value.intval = (siz))
  87. #define nslots(dct) r_size(&(dct)->values)
  88. #define npairs(dct) (nslots(dct) - 1)
  89. #define d_length(dct) ((uint)((dct)->count.value.intval))
  90.  
  91. /*
  92.  * Define the size of the largest valid dictionary.
  93.  * This is limited by the size field of the keys and values refs,
  94.  * and by the enumeration interface, which requires the size to
  95.  * fit in an int.
  96.  */
  97. const uint dict_max_size = max_ushort / 2 - 2;
  98.  
  99. /* Define whether dictionaries expand automatically when full. */
  100. bool dict_auto_expand = false;
  101.  
  102. /* Define whether dictionaries are packed by default. */
  103. bool dict_default_pack = true;
  104.  
  105. /* Cached values from the top element of the dictionary stack. */
  106. /* See dstack.h for details. */
  107. uint dsmask;                /* see dstack.h */
  108. const ref_packed *dtop_keys;
  109. uint dtop_npairs;
  110. ref *dtop_values;
  111.  
  112. /* Forward references */
  113. private int dict_create_contents(P3(uint size, const ref *pdref, bool pack));
  114. private bool dict_is_permanent_on_dstack(P1(const dict *));
  115.  
  116. /* Debugging statistics */
  117. #ifdef DEBUG
  118. long dn_lookups;        /* total lookups */
  119. long dn_1probe;            /* successful lookups on only 1 probe */
  120. long dn_2probe;            /* successful lookups on 2 probes */
  121. /* Wrappers for dict_find and dict_find_name_by_index */
  122. int real_dict_find(P3(const ref *pdref, const ref *key, ref **ppvalue));
  123. int
  124. dict_find(const ref *pdref, const ref *pkey, ref **ppvalue)
  125. {    dict *pdict = pdref->value.pdict;
  126.     int code = real_dict_find(pdref, pkey, ppvalue);
  127.     dn_lookups++;
  128.     if ( r_has_type(pkey, t_name) && dict_is_packed(pdict) )
  129.     {    uint nidx = name_index(pkey);
  130.         uint hash =
  131.           hash_mod(dict_name_index_hash(nidx), npairs(pdict)) + 1;
  132.         if (  pdict->keys.value.packed[hash] ==
  133.                 pt_tag(pt_literal_name) + nidx
  134.            )
  135.           dn_1probe++;
  136.         else if (  pdict->keys.value.packed[hash - 1] ==
  137.                  pt_tag(pt_literal_name) + nidx
  138.             )
  139.           dn_2probe++;
  140.     }
  141.     if ( !(dn_lookups % 1000) )
  142.         if_debug3('d', "[d]lookups=%ld 1probe=%ld 2probe=%ld\n",
  143.               dn_lookups, dn_1probe, dn_2probe);
  144.     return code;
  145. }
  146. #define dict_find real_dict_find
  147. ref *real_dict_find_name_by_index(P1(uint nidx));
  148. ref *
  149. dict_find_name_by_index(uint nidx)
  150. {    ref *pvalue = real_dict_find_name_by_index(nidx);
  151.     dict *pdict = dsp->value.pdict;
  152.     dn_lookups++;
  153.     if ( dict_is_packed(pdict) )
  154.     {    uint hash =
  155.           hash_mod(dict_name_index_hash(nidx), npairs(pdict)) + 1;
  156.         if (  pdict->keys.value.packed[hash] ==
  157.                 pt_tag(pt_literal_name) + nidx
  158.            )
  159.           dn_1probe++;
  160.         else if (  pdict->keys.value.packed[hash - 1] ==
  161.                  pt_tag(pt_literal_name) + nidx
  162.             )
  163.           dn_2probe++;
  164.     }
  165.     if ( !(dn_lookups % 1000) )
  166.         if_debug3('d', "[d]lookups=%ld 1probe=%ld 2probe=%ld\n",
  167.               dn_lookups, dn_1probe, dn_2probe);
  168.     return pvalue;
  169. }
  170. #define dict_find_name_by_index real_dict_find_name_by_index
  171. #endif
  172.  
  173. /* Create a dictionary in the current VM space. */
  174. int
  175. dict_create(uint size, ref *pdref)
  176. {    ref arr;
  177.     int code = ialloc_ref_array(&arr, a_all, sizeof(dict) / sizeof(ref),
  178.                     "dict_create");
  179.     ref dref;
  180.     if ( code < 0 )
  181.       return code;
  182.     make_tav_new(&dref, t_dictionary,
  183.              (r_is_local(&arr) ? a_all | a_local : a_all),
  184.              pdict, (dict *)arr.value.refs);
  185.     code = dict_create_contents(size, &dref, dict_default_pack);
  186.     if ( code < 0 )
  187.       return code;
  188.     *pdref = dref;
  189.     return 0;
  190. }
  191. /* Create unpacked keys for a dictionary. */
  192. /* The keys are allocated in the same VM space as the dictionary. */
  193. private int
  194. dict_create_unpacked_keys(uint asize, const ref *pdref)
  195. {    dict *pdict = pdref->value.pdict;
  196.     bool local = ialloc_is_local(idmemory);
  197.     int code;
  198.     ref *kp;
  199.     ref *zp;
  200.     register uint i;
  201.     ialloc_set_local(idmemory, r_is_local(pdref));
  202.     code = ialloc_ref_array(&pdict->keys, a_all, asize, "dict_create(keys)");
  203.     if ( code >= 0 )
  204.       { ref_mark_new(&pdict->keys);
  205.         for ( zp = kp = pdict->keys.value.refs, i = asize; i; zp++, i-- )
  206.           make_null_new(zp);
  207.         r_set_attrs(kp, a_executable);    /* wraparound entry */
  208.       }
  209.     ialloc_set_local(idmemory, local);
  210.     return code;
  211. }
  212. /* Create the contents (keys and values) of a dictionary. */
  213. /* Allocate in the current VM space, which is assumed to be the same as */
  214. /* the VM space where the dictionary is allocated. */
  215. private int
  216. dict_create_contents(uint size, const ref *pdref, bool pack)
  217. {    dict *pdict = pdref->value.pdict;
  218.     uint csize = (size == 0 ? 1 : size);    /* client-specified size */
  219.     uint asize = csize;
  220.     int code;
  221.     register uint i;
  222.     ref *zp;
  223. #if dict_round_size
  224.     /* Round up the actual allocated size to the next higher */
  225.     /* power of 2, so we can use & instead of %. */
  226.     while ( asize & (asize - 1) ) asize = (asize | (asize >> 1)) + 1;
  227. #endif
  228.     asize++;        /* allow room for wraparound entry */
  229.     code = ialloc_ref_array(&pdict->values, a_all, asize, "dict_create(values)");
  230.     if ( code < 0 ) return code;
  231.     ref_mark_new(&pdict->values);
  232.     for ( zp = pdict->values.value.refs, i = asize; i; zp++, i-- )
  233.         make_null_new(zp);
  234.     if ( pack )
  235.        {    uint ksize = (asize + packed_per_ref - 1) / packed_per_ref;
  236.         ref arr;
  237.         ref_packed *pkp;
  238.         ref_packed *pzp;
  239.         code = ialloc_ref_array(&arr, a_all, ksize, "dict_create(packed keys)");
  240.         if ( code < 0 ) return code;
  241.         pkp = (ref_packed *)arr.value.refs;
  242.         make_tasv_new(&pdict->keys, t_shortarray,
  243.                   (r_is_local(&arr) ? a_all | a_local : a_all),
  244.                   asize, packed, pkp);
  245.         for ( pzp = pkp, i = 0; i < asize || i % packed_per_ref; pzp++, i++ )
  246.             *pzp = packed_key_empty;
  247.         *pkp = packed_key_deleted;    /* wraparound entry */
  248.        }
  249.     else                /* not packed */
  250.        {    int code = dict_create_unpacked_keys(asize, pdref);
  251.         if ( code < 0 ) return code;
  252.        }
  253.     make_int_new(&pdict->count, 0);
  254.     make_int_new(&pdict->maxlength, csize);
  255.     return 0;
  256. }
  257.  
  258. /*
  259.  * Ensure that a dictionary uses the unpacked representation for keys.
  260.  * We can't just use dict_resize, because the values slots mustn't move.
  261.  */
  262. int
  263. dict_unpack(ref *pdref)
  264. {    dict *pdict = pdref->value.pdict;
  265.     if ( !dict_is_packed(pdict) )
  266.       return 0;            /* nothing to do */
  267.     {    uint count = nslots(pdict);
  268.         const ref_packed *okp = pdict->keys.value.packed;
  269.         ref old_keys;
  270.         int code;
  271.         ref *nkp;
  272.         old_keys = pdict->keys;
  273.         ialloc_save_change(pdref, (ref_packed *)&pdict->keys,
  274.                    "dict_unpack(keys)");
  275.         code = dict_create_unpacked_keys(count, pdref);
  276.         if ( code < 0 )
  277.           return code;
  278.         for ( nkp = pdict->keys.value.refs; count--; okp++, nkp++ )
  279.           if ( r_packed_is_name(okp) )
  280.             packed_get(okp, nkp);
  281.         ifree_ref_array(&old_keys, "dict_unpack(old keys)");
  282.         dict_set_top();    /* just in case */
  283.     }
  284.     return 0;
  285. }
  286.  
  287. /*
  288.  * Define a macro for searching a packed dictionary.  Free variables:
  289.  *    ref_packed kpack - holds the packed key.
  290.  *    uint hash - holds the hash of the name.
  291.  *    dict *pdict - points to the dictionary.
  292.  *    uint size - holds npairs(pdict).
  293.  * Note that the macro is *not* enclosed in {}, so that we can access
  294.  * the values of kbot and kp after leaving the loop.
  295.  *
  296.  * We break the macro into two to avoid overflowing some preprocessors.
  297.  */
  298. /* packed_search_body also uses kp and kbot as free variables. */
  299. #define packed_search_body(del,pre,post,miss)\
  300.     { if_debug2('D', "[D]probe 0x%lx: 0x%x\n", (ulong)kp, *kp);\
  301.       if ( *kp == kpack )\
  302.        { pre (pdict->values.value.refs + (kp - kbot));\
  303.      post;\
  304.        }\
  305.       else if ( !r_packed_is_name(kp) )\
  306.        { /* Empty, deleted, or wraparound. Figure out which. */\
  307.      if ( *kp == packed_key_empty ) miss;\
  308.      if ( kp == kbot ) break;    /* wrap */\
  309.      else { del; }\
  310.        }\
  311.     }
  312. #define packed_search_1(del,pre,post,miss)\
  313.    const ref_packed *kbot = pdict->keys.value.packed;\
  314.    register const ref_packed *kp;\
  315.    for ( kp = kbot + hash_mod(hash, size) + 1; ; kp-- )\
  316.      packed_search_body(del,pre,post,miss)
  317. #define packed_search_2(del,pre,post,miss)\
  318.    for ( kp += size; ; kp-- )\
  319.      packed_search_body(del,pre,post,miss)
  320.  
  321. /*
  322.  * Look up a key in a dictionary.  Store a pointer to the value slot
  323.  * where found, or to the (value) slot for inserting.
  324.  * Return 1 if found, 0 if not and there is room for a new entry,
  325.  * or e_dictfull if the dictionary is full and the key is missing.
  326.  * The caller is responsible for ensuring key is not a null.
  327.  */
  328. int
  329. dict_find(const ref *pdref, const ref *pkey,
  330.   ref **ppvalue    /* result is stored here */)
  331. {    dict *pdict = pdref->value.pdict;
  332.     uint size = npairs(pdict);
  333.     register int etype;
  334.     uint nidx;
  335.     ref_packed kpack;
  336.     uint hash;
  337.     int ktype;
  338.     /* Compute hash.  The only types we bother with are strings, */
  339.     /* names, and (unlikely, but worth checking for) integers. */
  340.     switch ( r_type(pkey) )
  341.     {
  342.     case t_name:
  343.         nidx = name_index(pkey);
  344. nh:        hash = dict_name_index_hash(nidx);
  345.         kpack = packed_name_key(nidx);
  346.         ktype = t_name;
  347.         break;
  348.     case t_string:            /* convert to a name first */
  349.     {    ref nref;
  350.         int code = name_ref(pkey->value.bytes,
  351.                     r_size(pkey), &nref, 1);
  352.         if ( code < 0 ) return code;
  353.         nidx = name_index(&nref);
  354.     }    goto nh;
  355.     case t_integer:
  356.         hash = (uint)pkey->value.intval * 30503;
  357.         kpack = packed_key_impossible;
  358.         ktype = -1;
  359.         break;
  360.     default:
  361.         hash = r_btype(pkey) * 99;    /* yech */
  362.         kpack = packed_key_impossible;
  363.         ktype = -1;
  364.     }
  365.     /* Search the dictionary */
  366.     if ( dict_is_packed(pdict) )
  367.     {    const ref_packed *pslot = 0;
  368.         packed_search_1(if ( pslot == 0 ) pslot = kp,
  369.                 *ppvalue =, return 1, goto miss);
  370.         packed_search_2(if ( pslot == 0 ) pslot = kp,
  371.                 *ppvalue =, return 1, goto miss);
  372.         /* Double wraparound, dict is full. */
  373.         if ( pslot == 0 )        /* no empty slots */
  374.             return e_dictfull;
  375.         *ppvalue = pdict->values.value.refs + (pslot - kbot);
  376.         return 0;
  377. miss:        /* Key is missing, not double wrap. */
  378.         if ( pslot == 0 )
  379.             pslot = kp;
  380.         *ppvalue = pdict->values.value.refs + (pslot - kbot);
  381.         return 0;
  382.     }
  383.     else
  384.     {    ref *kbot = pdict->keys.value.refs;
  385.         register ref *kp;
  386.         ref *pslot = 0;
  387.         int wrap = 0;
  388.         for ( kp = kbot + hash_mod(hash, size) + 2; ; )
  389.         {    --kp;
  390.             if ( (etype = r_type(kp)) == ktype )
  391.             {    /* Fast comparison if both keys are names */
  392.                 if ( name_index(kp) == nidx )
  393.                 {    *ppvalue = pdict->values.value.refs + (kp - kbot);
  394.                     return 1;
  395.                 }
  396.             }
  397.             else if ( etype == t_null )
  398.             {    /* Empty, deleted, or wraparound. */
  399.                 /* Figure out which. */
  400.                 if ( kp == kbot )    /* wrap */
  401.                 {    if ( wrap++ )    /* wrapped twice */
  402.                     {    if ( pslot == 0 )
  403.                             return e_dictfull;
  404.                         break;
  405.                     }
  406.                     kp += size + 1;
  407.                    }
  408.                 else if ( r_has_attr(kp, a_executable) )
  409.                 {    /* Deleted entry, save the slot. */
  410.                     if ( pslot == 0 )
  411.                         pslot = kp;
  412.                 }
  413.                 else    /* key not found */
  414.                     break;
  415.             }
  416.             else
  417.             {    if ( obj_eq(kp, pkey) )
  418.                 {    *ppvalue = pdict->values.value.refs + (kp - kbot);
  419.                     return 1;
  420.                 }
  421.             }
  422.         }
  423.         *ppvalue = pdict->values.value.refs +
  424.               ((pslot != 0 ? pslot : kp) - kbot);
  425.         return 0;
  426.     }
  427. }
  428.  
  429. /*
  430.  * Look up a (constant) C string in a dictionary.
  431.  * Return 1 if found, <= 0 if not.
  432.  */
  433. int
  434. dict_find_string(const ref *pdref, const char _ds *kstr, ref **ppvalue)
  435. {    int code;
  436.     ref kname;
  437.     if ( (code = name_ref((const byte *)kstr, strlen(kstr), &kname, -1)) < 0 )
  438.         return code;
  439.     return dict_find(pdref, &kname, ppvalue);
  440. }
  441.  
  442. /*
  443.  * Check whether a dictionary is one of the permanent ones on the d-stack.
  444.  * (This is a private routine right now, but it might not be in the future.)
  445.  */
  446. private bool
  447. dict_is_permanent_on_dstack(const dict *pdict)
  448. {    int i;
  449.     /* This assumes min_dstack fits inside the first chunk of dstack. */
  450.     for ( i = 0; i < min_dstack_size; i++ )
  451.       {    if ( dsbot[i].value.pdict == (dict *)pdict )
  452.           return true;
  453.       }
  454.     return false;
  455. }
  456.  
  457. /*
  458.  * Look up a name on the dictionary stack.
  459.  * Return the pointer to the value if found, 0 if not.
  460.  */
  461. ref *
  462. dict_find_name_by_index(uint nidx)
  463. {    ds_ptr pdref = dsp;
  464. /* Since we know the hash function is the identity function, */
  465. /* there's no point in allocating a separate variable for it. */
  466. #define hash dict_name_index_hash(nidx)
  467.     ref_packed kpack = packed_name_key(nidx);
  468.     do
  469.        {    dict *pdict = pdref->value.pdict;
  470.         uint size = npairs(pdict);
  471.         if_debug4('D', "[D]lookup 0x%x in 0x%lx(%u/%u)\n",
  472.               nidx, (ulong)pdict, dict_length(pdref),
  473.               dict_maxlength(pdref));
  474.         if ( dict_is_packed(pdict) )
  475.            {    packed_search_1(DO_NOTHING, return,
  476.                     DO_NOTHING, goto miss);
  477.             packed_search_2(DO_NOTHING, return,
  478.                     DO_NOTHING, break);
  479.  miss:            ;
  480.            }
  481.         else
  482.            {    ref *kbot = pdict->keys.value.refs;
  483.             register ref *kp;
  484.             int wrap = 0;
  485.             /* Search the dictionary */
  486.             for ( kp = kbot + hash_mod(hash, size) + 2; ; )
  487.                {    --kp;
  488.                 if ( r_has_type(kp, t_name) )
  489.                    {    if ( name_index(kp) == nidx )
  490.                       return pdict->values.value.refs +
  491.                         (kp - kbot);
  492.                    }
  493.                 else if ( r_has_type(kp, t_null) )
  494.                    {    /* Empty, deleted, or wraparound. */
  495.                     /* Figure out which. */
  496.                     if ( !r_has_attr(kp, a_executable) )
  497.                         break;
  498.                     if ( kp == kbot )    /* wrap */
  499.                        {    if ( wrap++ )
  500.                             break;    /* 2 wraps */
  501.                         kp += size + 1;
  502.                        }
  503.                    }
  504.                }
  505.            }
  506.        }
  507.     while ( pdref-- > dsbot );
  508.     /* The name isn't in the top dictionary block. */
  509.     /* If there are other blocks, search them now (more slowly). */
  510.     if ( !d_stack.extension_size )        /* no more blocks */
  511.       return (ref *)0;
  512.     {    /* We could use the STACK_LOOP macros, but for now, */
  513.         /* we'll do things the simplest way. */
  514.         ref key;
  515.         uint i = dsp + 1 - dsbot;
  516.         uint size = ref_stack_count(&d_stack);
  517.         ref *pvalue;
  518.         name_index_ref(nidx, &key);
  519.         for ( ; i < size; i++ )
  520.           {    if ( dict_find(ref_stack_index(&d_stack, i),
  521.                        &key, &pvalue) > 0
  522.                )
  523.               return pvalue;
  524.           }
  525.     }
  526.     return (ref *)0;
  527. #undef hash
  528. }
  529.  
  530. /*
  531.  * Enter a key-value pair in a dictionary.
  532.  * The caller is responsible for ensuring key is not a null.
  533.  * Return 0, e_dictfull, e_invalidaccess, or e_VMerror if the key
  534.  * was a string and a VMerror occurred when converting it to a name.
  535.  */
  536. int
  537. dict_put(ref *pdref /* t_dictionary */, const ref *pkey, const ref *pvalue)
  538. {    int rcode = 0;
  539.     ref *pvslot;
  540.     /* Check the value. */
  541.     check_store_space(*pdref, *pvalue);
  542. top:    if ( dict_find(pdref, pkey, &pvslot) <= 0 )    /* not found */
  543.        {    /* Check for overflow */
  544.         dict *pdict = pdref->value.pdict;
  545.         ref kname;
  546.         uint index = pvslot - pdict->values.value.refs;
  547.         if ( d_length(pdict) == d_maxlength(pdict) )
  548.            {    int code;
  549.             if ( !dict_auto_expand )
  550.                 return_error(e_dictfull);
  551.             code = dict_grow(pdref);
  552.             if ( code < 0 )
  553.                 return code;
  554.             goto top;    /* keep things simple */
  555.            }
  556.         /* If the key is a string, convert it to a name. */
  557.         if ( r_has_type(pkey, t_string) )
  558.            {    int code = name_from_string(pkey, &kname);
  559.             if ( code < 0 ) return code;
  560.             pkey = &kname;
  561.            }
  562.         if ( dict_is_packed(pdict) )
  563.            {    ref_packed *kp;
  564.             if ( !r_has_type(pkey, t_name) ||
  565.                  name_index(pkey) > packed_max_value
  566.                )
  567.                {    /* Change to unpacked representation. */
  568.                 int code = dict_unpack(pdref);
  569.                 if ( code < 0 )
  570.                     return code;
  571.                 goto top;
  572.                }
  573.             kp = (ref_packed *)(pdict->keys.value.packed + index);
  574.             if ( ialloc_new_mask != 0 &&
  575.                  !r_has_attr(&pdict->keys, l_new)
  576.                )
  577.                {    /* See initial comment for why it is safe */
  578.                 /* not to save the change if the keys */
  579.                 /* array itself is new. */
  580.                 ialloc_save_change(&pdict->keys, kp,
  581.                            "dict_put(key)");
  582.                }
  583.             *kp = pt_tag(pt_literal_name) + name_index(pkey);
  584.            }
  585.         else
  586.            {    ref *kp = pdict->keys.value.refs + index;
  587.             if_debug2('d', "[d]0x%lx fill key 0x%lx\n",
  588.                   (ulong)pdict, (ulong)kp);
  589.             check_store_space(*pdref, *pkey);
  590.             ref_assign_old(&pdict->keys, kp, pkey,
  591.                        "dict_put(key)");    /* set key of pair */
  592.            }
  593.         ref_save(pdref, &pdict->count, "dict_put(count)");
  594.         pdict->count.value.intval++;
  595.         /* If the key is a name, update its 1-element cache. */
  596.         if ( r_has_type(pkey, t_name) )
  597.            {    name *pname = pkey->value.pname;
  598.             if ( pname->pvalue == pv_no_defn &&
  599.                 (pdict == systemdict->value.pdict ||
  600.                  dict_is_permanent_on_dstack(pdict)) &&
  601.                 /* Only set the cache if we aren't inside */
  602.                 /* a save.  This way, we never have to */
  603.                 /* undo setting the cache. */
  604.                 alloc_save_level(idmemory) == 0
  605.                )
  606.                {    /* Set the cache */
  607.                 pname->pvalue = pvslot;
  608.                }
  609.             else    /* The cache is worthless */
  610.                 pname->pvalue = pv_other;
  611.            }
  612.         rcode = 1;
  613.        }
  614.     if_debug8('d', "[d]in 0x%lx put 0x%lx: key %lx %lx\n\t%lx %lx -> %lx %lx\n",
  615.           (ulong)pdref->value.pdict, (ulong)pvslot,
  616.           ((ulong *)pkey)[0], ((ulong *)pkey)[1],
  617.           ((ulong *)pvslot)[0], ((ulong *)pvslot)[1],
  618.           ((ulong *)pvalue)[0], ((ulong *)pvalue)[1]);
  619.     ref_assign_old(&pdref->value.pdict->values, pvslot, pvalue,
  620.                "dict_put(value)");
  621.     return rcode;
  622. }
  623.  
  624. /*
  625.  * Enter a key-value pair where the key is a (constant) C string.
  626.  */
  627. int
  628. dict_put_string(ref *pdref, const char *kstr, const ref *pvalue)
  629. {    int code;
  630.     ref kname;
  631.     if ( (code = name_ref((const byte *)kstr, strlen(kstr), &kname, 0)) < 0 )
  632.         return code;
  633.     return dict_put(pdref, &kname, pvalue);
  634. }
  635.  
  636. /* Remove an element from a dictionary. */
  637. int
  638. dict_undef(ref *pdref, const ref *pkey)
  639. {    ref *pvslot;
  640.     dict *pdict;
  641.     uint index;
  642.     if ( dict_find(pdref, pkey, &pvslot) <= 0 )
  643.         return_error(e_undefined);
  644.     /* Remove the entry from the dictionary. */
  645.     pdict = pdref->value.pdict;
  646.     index = pvslot - pdict->values.value.refs;
  647.     if ( dict_is_packed(pdict) )
  648.        {    ref_packed *pkp =
  649.            (ref_packed *)(pdict->keys.value.packed + index);
  650.         /* Since packed arrays don't have room for a saved bit, */
  651.         /* always save the entire ref containing this key. */
  652.         /* This wastes a little space, but undef is rare. */
  653.         /* See the initial comment for why it is safe not to save */
  654.         /* the change if the keys array itself is new. */
  655.         if ( ialloc_new_mask != 0 && !r_has_attr(&pdict->keys, l_new) )
  656.           ialloc_save_change(&pdict->keys, pkp, "dict_undef(key)");
  657.         /* Accumulating deleted entries slows down lookup. */
  658.         /* Detect the easy case where we can use an empty entry */
  659.         /* rather than a deleted one, namely, when the next entry */
  660.         /* in the probe order is empty. */
  661.         if ( pkp[-1] == packed_key_empty )
  662.             *pkp = packed_key_empty;
  663.         else
  664.             *pkp = packed_key_deleted;
  665.        }
  666.     else                /* not packed */
  667.        {    ref *kp = pdict->keys.value.refs + index;
  668.         make_null_old(&pdict->keys, kp, "dict_undef(key)");
  669.         /* Accumulating deleted entries slows down lookup. */
  670.         /* Detect the easy case where we can use an empty entry */
  671.         /* rather than a deleted one, namely, when the next entry */
  672.         /* in the probe order is empty. */
  673.         if ( !r_has_type(kp - 1, t_null) ||    /* full entry */
  674.              r_has_attr(kp - 1, a_executable)    /* deleted or wraparound */
  675.             )
  676.             r_set_attrs(kp, a_executable);    /* mark as deleted */
  677.        }
  678.     ref_save(pdref, &pdict->count, "dict_undef(count)");
  679.     pdict->count.value.intval--;
  680.     /* If the key is a name, update its 1-element cache. */
  681.     if ( r_has_type(pkey, t_name) )
  682.       {    name *pname = pkey->value.pname;
  683.         if ( pv_valid(pname->pvalue) )
  684.           {
  685. #ifdef DEBUG
  686.             /* Check the the cache is correct. */
  687.             if ( !dict_is_permanent_on_dstack(pdict) )
  688.               lprintf1("dict_undef: cached name value pointer 0x%lx is incorrect!\n",
  689.                    (ulong)pname->pvalue);
  690. #endif
  691.             /* Clear the cache */
  692.             pname->pvalue = pv_no_defn;
  693.           }
  694.       }
  695.     make_null_old(&pdict->values, pvslot, "dict_undef(value)");
  696.     return 0;
  697. }
  698.  
  699. /* Return the number of elements in a dictionary. */
  700. uint
  701. dict_length(const ref *pdref /* t_dictionary */)
  702. {    return d_length(pdref->value.pdict);
  703. }
  704.  
  705. /* Return the capacity of a dictionary. */
  706. uint
  707. dict_maxlength(const ref *pdref    /* t_dictionary */)
  708. {    return d_maxlength(pdref->value.pdict);
  709. }
  710.  
  711. /* Copy one dictionary into another. */
  712. int
  713. dict_copy(const ref *pdrfrom /* t_dictionary */, ref *pdrto /* t_dictionary */)
  714. {    int index;
  715.     ref elt[2];
  716.     int code;
  717.     /* Do the store check before starting the copy. */
  718.     index = dict_first(pdrfrom);
  719.     while ( (index = dict_next(pdrfrom, index, elt)) >= 0 )
  720.     {    check_store_space(*pdrto, elt[0]);
  721.         check_store_space(*pdrto, elt[1]);
  722.     }
  723.     /* Now copy the contents. */
  724.     index = dict_first(pdrfrom);
  725.     while ( (index = dict_next(pdrfrom, index, elt)) >= 0 )
  726.       if ( (code = dict_put(pdrto, &elt[0], &elt[1])) < 0 )
  727.         return code;
  728.     return 0;
  729. }
  730.  
  731. /* Set the cached values computed from the top entry on the dstack. */
  732. /* See dstack.h for details. */
  733. private const ref_packed no_packed_keys[2] =
  734.     { packed_key_deleted, packed_key_empty };
  735. void
  736. dict_set_top(void)
  737. {    dict *pdict = dsp->value.pdict;
  738.     if ( dict_is_packed(pdict) &&
  739.          r_has_attr(dict_access_ref(dsp), a_read)
  740.        )
  741.     {    dtop_keys = pdict->keys.value.packed;
  742.         dtop_npairs = npairs(pdict);
  743.         dtop_values = pdict->values.value.refs;
  744.     }
  745.     else
  746.     {    dtop_keys = no_packed_keys;
  747.         dtop_npairs = 1;
  748.     }
  749.     if ( !r_has_attr(dict_access_ref(dsp), a_write) )
  750.         dsmask = ~0;
  751.     else
  752.         dsmask = ~r_type_attrs(dsp) & a_local;
  753. }
  754.  
  755. /* Resize a dictionary. */
  756. int
  757. dict_resize(ref *pdref, uint new_size)
  758. {    dict *pdict = pdref->value.pdict;
  759.     dict dnew;
  760.     ref drto;
  761.     int code;
  762.     bool local;
  763.     if ( new_size < d_length(pdict) )
  764.     {    if ( !dict_auto_expand )
  765.             return_error(e_dictfull);
  766.         new_size = d_length(pdict);
  767.     }
  768.     local = ialloc_is_local(idmemory);
  769.     ialloc_set_local(idmemory, r_is_local(pdref));
  770.     make_tav_new(&drto, t_dictionary,
  771.              (r_is_local(pdref) ? a_all | a_local : a_all),
  772.              pdict, &dnew);
  773.     if ( (code = dict_create_contents(new_size, &drto, dict_is_packed(pdict))) < 0 )
  774.     {    ialloc_set_local(idmemory, local);
  775.         return code;
  776.     }
  777.     /* We must suppress the store check, in case we are expanding */
  778.     /* systemdict or another global dictionary that is allowed */
  779.     /* to reference local objects. */
  780.     r_set_attrs(&drto, a_local);
  781.     dict_copy(pdref, &drto);    /* can't fail */
  782.     /* Free the old dictionary */
  783.     ifree_ref_array(&pdict->values, "dict_resize(old values)");
  784.     ifree_ref_array(&pdict->keys, "dict_resize(old keys)");
  785.     ref_assign_old(pdref, &pdict->keys, &dnew.keys, "dict_resize(keys)");
  786.     ref_assign_old(pdref, &pdict->values, &dnew.values, "dict_resize(values)");
  787.     ref_save(pdref, &pdict->maxlength, "dict_resize(maxlength)");
  788.     d_set_maxlength(pdict, new_size);
  789.     ialloc_set_local(idmemory, local);
  790.     dict_set_top();        /* just in case this is the top dict */
  791.     return 0;
  792. }
  793.  
  794. /* Grow a dictionary for dict_put. */
  795. int
  796. dict_grow(ref *pdref)
  797. {    dict *pdict = pdref->value.pdict;
  798.     /* We might have maxlength < npairs, if */
  799.     /* dict_round_size is true. */
  800.     ulong new_size = d_maxlength(pdict) * 3 / 2 + 2;
  801.     if ( new_size > dict_max_size )
  802.     {    if ( d_maxlength(pdict) == dict_max_size )
  803.             return_error(e_dictfull);
  804.         new_size = dict_max_size;
  805.     }
  806.     if ( new_size > npairs(pdict) )
  807.     {    int code = dict_resize(pdref, (uint)new_size);
  808.         if ( code < 0 )
  809.             return code;
  810.     }
  811.     else
  812.     {    /* maxlength < npairs, we can grow in place */
  813.         ref_save(pdref, &pdict->maxlength, "dict_put(maxlength)");
  814.         d_set_maxlength(pdict, new_size);
  815.     }
  816.     return 0;
  817. }
  818.  
  819. /* Prepare to enumerate a dictionary. */
  820. int
  821. dict_first(const ref *pdref)
  822. {    return (int)nslots(pdref->value.pdict);
  823. }
  824.  
  825. /* Enumerate the next element of a dictionary. */
  826. int
  827. dict_next(const ref *pdref, int index, ref *eltp /* ref eltp[2] */)
  828. {    dict *pdict = pdref->value.pdict;
  829.     ref *vp = pdict->values.value.refs + index;
  830.     while ( vp--, --index >= 0 )
  831.        {    array_get(&pdict->keys, (long)index, eltp);
  832.         /* Make sure this is a valid entry. */
  833.         if ( r_has_type(eltp, t_name) ||
  834.              (!dict_is_packed(pdict) && !r_has_type(eltp, t_null))
  835.            )
  836.            {    eltp[1] = *vp;
  837.             if_debug6('d', "[d]0x%lx index %d: %lx %lx, %lx %lx\n",
  838.                 (ulong)pdict, index,
  839.                 ((ulong *)eltp)[0], ((ulong *)eltp)[1],
  840.                 ((ulong *)vp)[0], ((ulong *)vp)[1]);
  841.             return index;
  842.            }
  843.        }
  844.     return -1;            /* no more elements */
  845. }
  846.  
  847. /* Return the index of a value within a dictionary. */
  848. int
  849. dict_value_index(const ref *pdref, const ref *pvalue)
  850. {    return (int)(pvalue - pdref->value.pdict->values.value.refs - 1);
  851. }
  852.  
  853. /* Return the entry at a given index within a dictionary. */
  854. /* If the index designates an unoccupied entry, return e_undefined. */
  855. int
  856. dict_index_entry(const ref *pdref, int index, ref *eltp /* ref eltp[2] */)
  857. {    const dict *pdict = pdref->value.pdict;
  858.     array_get(&pdict->keys, (long)(index + 1), eltp);
  859.     if ( r_has_type(eltp, t_name) ||
  860.          (!dict_is_packed(pdict) && !r_has_type(eltp, t_null))
  861.        )
  862.       {    eltp[1] = pdict->values.value.refs[index + 1];
  863.         return 0;
  864.       }
  865.     return e_undefined;
  866. }
  867.