Main Page | Modules | Alphabetical List | Data Structures | File List | Data Fields | Globals

hash.c

Go to the documentation of this file.
00001 /**********************************************************************
00002 
00003   hash.c -
00004 
00005   $Author: matz $
00006   $Date: 2005/07/19 08:25:37 $
00007   created at: Mon Nov 22 18:51:18 JST 1993
00008 
00009   Copyright (C) 1993-2003 Yukihiro Matsumoto
00010   Copyright (C) 2000  Network Applied Communication Laboratory, Inc.
00011   Copyright (C) 2000  Information-technology Promotion Agency, Japan
00012 
00013 **********************************************************************/
00014 
00015 #include "ruby.h"
00016 #include "st.h"
00017 #include "util.h"
00018 #include "rubysig.h"
00019 
00020 #ifdef __APPLE__
00021 #include <crt_externs.h>
00022 #endif
00023 
00024 #define HASH_DELETED  FL_USER1
00025 #define HASH_PROC_DEFAULT FL_USER2
00026 
00027 static void
00028 rb_hash_modify(hash)
00029     VALUE hash;
00030 {
00031     if (!RHASH(hash)->tbl) rb_raise(rb_eTypeError, "uninitialized Hash");
00032     if (OBJ_FROZEN(hash)) rb_error_frozen("hash");
00033     if (!OBJ_TAINTED(hash) && rb_safe_level() >= 4)
00034         rb_raise(rb_eSecurityError, "Insecure: can't modify hash");
00035 }
00036 
00037 VALUE
00038 rb_hash_freeze(hash)
00039     VALUE hash;
00040 {
00041     return rb_obj_freeze(hash);
00042 }
00043 
00044 VALUE rb_cHash;
00045 
00046 static VALUE envtbl;
00047 static ID id_hash, id_call, id_default;
00048 
00049 static VALUE
00050 eql(args)
00051     VALUE *args;
00052 {
00053     return (VALUE)rb_eql(args[0], args[1]);
00054 }
00055 
00056 static int
00057 rb_any_cmp(a, b)
00058     VALUE a, b;
00059 {
00060     VALUE args[2];
00061 
00062     if (a == b) return 0;
00063     if (FIXNUM_P(a) && FIXNUM_P(b)) {
00064         return a != b;
00065     }
00066     if (TYPE(a) == T_STRING && RBASIC(a)->klass == rb_cString &&
00067         TYPE(b) == T_STRING && RBASIC(b)->klass == rb_cString) {
00068         return rb_str_cmp(a, b);
00069     }
00070     if (a == Qundef || b == Qundef) return -1;
00071     if (SYMBOL_P(a) && SYMBOL_P(b)) {
00072         return a != b;
00073     }
00074 
00075     args[0] = a;
00076     args[1] = b;
00077     return !rb_with_disable_interrupt(eql, (VALUE)args);
00078 }
00079 
00080 VALUE
00081 rb_hash(obj)
00082     VALUE obj;
00083 {
00084     return rb_funcall(obj, id_hash, 0);
00085 }
00086 
00087 static int
00088 rb_any_hash(a)
00089     VALUE a;
00090 {
00091     VALUE hval;
00092 
00093     switch (TYPE(a)) {
00094       case T_FIXNUM:
00095       case T_SYMBOL:
00096         return (int)a;
00097         break;
00098 
00099       case T_STRING:
00100         return rb_str_hash(a);
00101         break;
00102 
00103       default:
00104         hval = rb_funcall(a, id_hash, 0);
00105         if (!FIXNUM_P(hval)) {
00106             hval = rb_funcall(hval, '%', 1, INT2FIX(536870923));
00107         }
00108         return (int)FIX2LONG(hval);
00109     }
00110 }
00111 
00112 static struct st_hash_type objhash = {
00113     rb_any_cmp,
00114     rb_any_hash,
00115 };
00116 
00117 struct foreach_safe_arg {
00118     st_table *tbl;
00119     int (*func)();
00120     st_data_t arg;
00121 };
00122 
00123 static int
00124 foreach_safe_i(key, value, arg)
00125     st_data_t key, value;
00126     struct foreach_safe_arg *arg;
00127 {
00128     int status;
00129 
00130     if (key == Qundef) return ST_CONTINUE;
00131     status = (*arg->func)(key, value, arg->arg);
00132     if (status == ST_CONTINUE) {
00133         return ST_CHECK;
00134     }
00135     return status;
00136 }
00137 
00138 void
00139 st_foreach_safe(table, func, a)
00140     st_table *table;
00141     int (*func)();
00142     st_data_t a;
00143 {
00144     struct foreach_safe_arg arg;
00145 
00146     arg.tbl = table;
00147     arg.func = func;
00148     arg.arg = a;
00149     if (st_foreach(table, foreach_safe_i, (st_data_t)&arg)) {
00150         rb_raise(rb_eRuntimeError, "hash modified during iteration");
00151     }
00152 }
00153 
00154 struct hash_foreach_arg {
00155     VALUE hash;
00156     int (*func)();
00157     VALUE arg;
00158 };
00159 
00160 static int
00161 hash_foreach_iter(key, value, arg)
00162     VALUE key, value;
00163     struct hash_foreach_arg *arg;
00164 {
00165     int status;
00166     st_table *tbl;
00167 
00168     tbl = RHASH(arg->hash)->tbl;    
00169     if (key == Qundef) return ST_CONTINUE;
00170     status = (*arg->func)(key, value, arg->arg);
00171     if (RHASH(arg->hash)->tbl != tbl) {
00172         rb_raise(rb_eRuntimeError, "rehash occurred during iteration");
00173     }
00174     switch (status) {
00175       case ST_DELETE:
00176         st_delete_safe(tbl, (st_data_t*)&key, 0, Qundef);
00177         FL_SET(arg->hash, HASH_DELETED);
00178       case ST_CONTINUE:
00179         break;
00180       case ST_STOP:
00181         return ST_STOP;
00182     }
00183     return ST_CHECK;
00184 }
00185 
00186 static VALUE
00187 hash_foreach_ensure(hash)
00188     VALUE hash;
00189 {
00190     RHASH(hash)->iter_lev--;
00191 
00192     if (RHASH(hash)->iter_lev == 0) {
00193         if (FL_TEST(hash, HASH_DELETED)) {
00194             st_cleanup_safe(RHASH(hash)->tbl, Qundef);
00195             FL_UNSET(hash, HASH_DELETED);
00196         }
00197     }
00198     return 0;
00199 }
00200 
00201 static VALUE
00202 hash_foreach_call(arg)
00203     struct hash_foreach_arg *arg;
00204 {
00205     if (st_foreach(RHASH(arg->hash)->tbl, hash_foreach_iter, (st_data_t)arg)) {
00206         rb_raise(rb_eRuntimeError, "hash modified during iteration");
00207     }
00208     return Qnil;
00209 }
00210 
00211 void
00212 rb_hash_foreach(hash, func, farg)
00213     VALUE hash;
00214     int (*func)();
00215     VALUE farg;
00216 {
00217     struct hash_foreach_arg arg;
00218 
00219     RHASH(hash)->iter_lev++;
00220     arg.hash = hash;
00221     arg.func = func;
00222     arg.arg  = farg;
00223     rb_ensure(hash_foreach_call, (VALUE)&arg, hash_foreach_ensure, hash);
00224 }
00225 
00226 static VALUE hash_alloc (VALUE);
00227 static VALUE
00228 hash_alloc(klass)
00229     VALUE klass;
00230 {
00231     NEWOBJ(hash, struct RHash);
00232     OBJSETUP(hash, klass, T_HASH);
00233 
00234     hash->ifnone = Qnil;
00235     hash->tbl = st_init_table(&objhash);
00236 
00237     return (VALUE)hash;
00238 }
00239 
00240 VALUE
00241 rb_hash_new()
00242 {
00243     return hash_alloc(rb_cHash);
00244 }
00245 
00246 /*
00247  *  call-seq:
00248  *     Hash.new                          => hash
00249  *     Hash.new(obj)                     => aHash
00250  *     Hash.new {|hash, key| block }     => aHash
00251  *  
00252  *  Returns a new, empty hash. If this hash is subsequently accessed by
00253  *  a key that doesn't correspond to a hash entry, the value returned
00254  *  depends on the style of <code>new</code> used to create the hash. In
00255  *  the first form, the access returns <code>nil</code>. If
00256  *  <i>obj</i> is specified, this single object will be used for
00257  *  all <em>default values</em>. If a block is specified, it will be
00258  *  called with the hash object and the key, and should return the
00259  *  default value. It is the block's responsibility to store the value
00260  *  in the hash if required.
00261  *     
00262  *     h = Hash.new("Go Fish")
00263  *     h["a"] = 100
00264  *     h["b"] = 200
00265  *     h["a"]           #=> 100
00266  *     h["c"]           #=> "Go Fish"
00267  *     # The following alters the single default object
00268  *     h["c"].upcase!   #=> "GO FISH"
00269  *     h["d"]           #=> "GO FISH"
00270  *     h.keys           #=> ["a", "b"]
00271  *     
00272  *     # While this creates a new default object each time
00273  *     h = Hash.new { |hash, key| hash[key] = "Go Fish: #{key}" }
00274  *     h["c"]           #=> "Go Fish: c"
00275  *     h["c"].upcase!   #=> "GO FISH: C"
00276  *     h["d"]           #=> "Go Fish: d"
00277  *     h.keys           #=> ["c", "d"]
00278  *     
00279  */
00280 
00281 static VALUE
00282 rb_hash_initialize(argc, argv, hash)
00283     int argc;
00284     VALUE *argv;
00285     VALUE hash;
00286 {
00287     VALUE ifnone;
00288 
00289     rb_hash_modify(hash);
00290     if (rb_block_given_p()) {
00291         if (argc > 0) {
00292             rb_raise(rb_eArgError, "wrong number of arguments");
00293         }
00294         RHASH(hash)->ifnone = rb_block_proc();
00295         FL_SET(hash, HASH_PROC_DEFAULT);
00296     }
00297     else {
00298         rb_scan_args(argc, argv, "01", &ifnone);
00299         RHASH(hash)->ifnone = ifnone;
00300     }
00301 
00302     return hash;
00303 }
00304 
00305 /*
00306  *  call-seq:
00307  *     Hash[ [key =>|, value]* ]   => hash
00308  *  
00309  *  Creates a new hash populated with the given objects. Equivalent to
00310  *  the literal <code>{ <i>key</i>, <i>value</i>, ... }</code>. Keys and
00311  *  values occur in pairs, so there must be an even number of arguments.
00312  *     
00313  *     Hash["a", 100, "b", 200]       #=> {"a"=>100, "b"=>200}
00314  *     Hash["a" => 100, "b" => 200]   #=> {"a"=>100, "b"=>200}
00315  *     { "a" => 100, "b" => 200 }     #=> {"a"=>100, "b"=>200}
00316  */
00317 
00318 static VALUE
00319 rb_hash_s_create(argc, argv, klass)
00320     int argc;
00321     VALUE *argv;
00322     VALUE klass;
00323 {
00324     VALUE hash;
00325     int i;
00326 
00327     if (argc == 1 && TYPE(argv[0]) == T_HASH) {
00328         hash = hash_alloc(klass);
00329             
00330         RHASH(hash)->ifnone = Qnil;
00331         RHASH(hash)->tbl = st_copy(RHASH(argv[0])->tbl);
00332 
00333         return hash;
00334     }
00335 
00336     if (argc % 2 != 0) {
00337         rb_raise(rb_eArgError, "odd number of arguments for Hash");
00338     }
00339 
00340     hash = hash_alloc(klass);
00341     for (i=0; i<argc; i+=2) {
00342         rb_hash_aset(hash, argv[i], argv[i + 1]);
00343     }
00344 
00345     return hash;
00346 }
00347 
00348 static VALUE
00349 to_hash(hash)
00350     VALUE hash;
00351 {
00352     return rb_convert_type(hash, T_HASH, "Hash", "to_hash");
00353 }
00354 
00355 static int
00356 rb_hash_rehash_i(key, value, tbl)
00357     VALUE key, value;
00358     st_table *tbl;
00359 {
00360     if (key != Qundef) st_insert(tbl, key, value);
00361     return ST_CONTINUE;
00362 }
00363 
00364 /*
00365  *  call-seq:
00366  *     hsh.rehash -> hsh
00367  *  
00368  *  Rebuilds the hash based on the current hash values for each key. If
00369  *  values of key objects have changed since they were inserted, this
00370  *  method will reindex <i>hsh</i>. If <code>Hash#rehash</code> is
00371  *  called while an iterator is traversing the hash, an
00372  *  <code>IndexError</code> will be raised in the iterator.
00373  *     
00374  *     a = [ "a", "b" ]
00375  *     c = [ "c", "d" ]
00376  *     h = { a => 100, c => 300 }
00377  *     h[a]       #=> 100
00378  *     a[0] = "z"
00379  *     h[a]       #=> nil
00380  *     h.rehash   #=> {["z", "b"]=>100, ["c", "d"]=>300}
00381  *     h[a]       #=> 100
00382  */
00383 
00384 static VALUE
00385 rb_hash_rehash(hash)
00386     VALUE hash;
00387 {
00388     st_table *tbl;
00389 
00390     rb_hash_modify(hash);
00391     tbl = st_init_table_with_size(&objhash, RHASH(hash)->tbl->num_entries);
00392     rb_hash_foreach(hash, rb_hash_rehash_i, (st_data_t)tbl);
00393     st_free_table(RHASH(hash)->tbl);
00394     RHASH(hash)->tbl = tbl;
00395 
00396     return hash;
00397 }
00398 
00399 /*
00400  *  call-seq:
00401  *     hsh[key]    =>  value
00402  *  
00403  *  Element Reference---Retrieves the <i>value</i> object corresponding
00404  *  to the <i>key</i> object. If not found, returns the a default value (see
00405  *  <code>Hash::new</code> for details).
00406  *     
00407  *     h = { "a" => 100, "b" => 200 }
00408  *     h["a"]   #=> 100
00409  *     h["c"]   #=> nil
00410  *     
00411  */
00412 
00413 VALUE
00414 rb_hash_aref(hash, key)
00415     VALUE hash, key;
00416 {
00417     VALUE val;
00418 
00419     if (!st_lookup(RHASH(hash)->tbl, key, &val)) {
00420         return rb_funcall(hash, id_default, 1, key);
00421     }
00422     return val;
00423 }
00424 
00425 /*
00426  *  call-seq:
00427  *     hsh.fetch(key [, default] )       => obj
00428  *     hsh.fetch(key) {| key | block }   => obj
00429  *  
00430  *  Returns a value from the hash for the given key. If the key can't be
00431  *  found, there are several options: With no other arguments, it will
00432  *  raise an <code>IndexError</code> exception; if <i>default</i> is
00433  *  given, then that will be returned; if the optional code block is
00434  *  specified, then that will be run and its result returned.
00435  *     
00436  *     h = { "a" => 100, "b" => 200 }
00437  *     h.fetch("a")                            #=> 100
00438  *     h.fetch("z", "go fish")                 #=> "go fish"
00439  *     h.fetch("z") { |el| "go fish, #{el}"}   #=> "go fish, z"
00440  *     
00441  *  The following example shows that an exception is raised if the key
00442  *  is not found and a default value is not supplied.
00443  *     
00444  *     h = { "a" => 100, "b" => 200 }
00445  *     h.fetch("z")
00446  *     
00447  *  <em>produces:</em>
00448  *     
00449  *     prog.rb:2:in `fetch': key not found (IndexError)
00450  *      from prog.rb:2
00451  *     
00452  */
00453 
00454 static VALUE
00455 rb_hash_fetch(argc, argv, hash)
00456     int argc;
00457     VALUE *argv;
00458     VALUE hash;
00459 {
00460     VALUE key, if_none;
00461     VALUE val;
00462     long block_given;
00463 
00464     rb_scan_args(argc, argv, "11", &key, &if_none);
00465 
00466     block_given = rb_block_given_p();
00467     if (block_given && argc == 2) {
00468         rb_warn("block supersedes default value argument");
00469     }
00470     if (!st_lookup(RHASH(hash)->tbl, key, &val)) {
00471         if (block_given) return rb_yield(key);
00472         if (argc == 1) {
00473             rb_raise(rb_eIndexError, "key not found");
00474         }
00475         return if_none;
00476     }
00477     return val;
00478 }
00479 
00480 /*
00481  *  call-seq:
00482  *     hsh.default(key=nil)   => obj
00483  *  
00484  *  Returns the default value, the value that would be returned by
00485  *  <i>hsh</i>[<i>key</i>] if <i>key</i> did not exist in <i>hsh</i>.
00486  *  See also <code>Hash::new</code> and <code>Hash#default=</code>.
00487  *     
00488  *     h = Hash.new                            #=> {}
00489  *     h.default                               #=> nil
00490  *     h.default(2)                            #=> nil
00491  *     
00492  *     h = Hash.new("cat")                     #=> {}
00493  *     h.default                               #=> "cat"
00494  *     h.default(2)                            #=> "cat"
00495  *     
00496  *     h = Hash.new {|h,k| h[k] = k.to_i*10}   #=> {}
00497  *     h.default                               #=> 0
00498  *     h.default(2)                            #=> 20
00499  */
00500 
00501 static VALUE
00502 rb_hash_default(argc, argv, hash)
00503     int argc;
00504     VALUE *argv;
00505     VALUE hash;
00506 {
00507     VALUE key;
00508 
00509     rb_scan_args(argc, argv, "01", &key);
00510     if (FL_TEST(hash, HASH_PROC_DEFAULT)) {
00511         return rb_funcall(RHASH(hash)->ifnone, id_call, 2, hash, key);
00512     }
00513     return RHASH(hash)->ifnone;
00514 }
00515 
00516 /*
00517  *  call-seq:
00518  *     hsh.default = obj     => hsh
00519  *  
00520  *  Sets the default value, the value returned for a key that does not
00521  *  exist in the hash. It is not possible to set the a default to a
00522  *  <code>Proc</code> that will be executed on each key lookup.
00523  *     
00524  *     h = { "a" => 100, "b" => 200 }
00525  *     h.default = "Go fish"
00526  *     h["a"]     #=> 100
00527  *     h["z"]     #=> "Go fish"
00528  *     # This doesn't do what you might hope...
00529  *     h.default = proc do |hash, key|
00530  *       hash[key] = key + key
00531  *     end
00532  *     h[2]       #=> #<Proc:0x401b3948@-:6>
00533  *     h["cat"]   #=> #<Proc:0x401b3948@-:6>
00534  */
00535 
00536 static VALUE
00537 rb_hash_set_default(hash, ifnone)
00538     VALUE hash, ifnone;
00539 {
00540     rb_hash_modify(hash);
00541     RHASH(hash)->ifnone = ifnone;
00542     FL_UNSET(hash, HASH_PROC_DEFAULT);
00543     return ifnone;
00544 }
00545 
00546 /*
00547  *  call-seq:
00548  *     hsh.default_proc -> anObject
00549  *  
00550  *  If <code>Hash::new</code> was invoked with a block, return that
00551  *  block, otherwise return <code>nil</code>.
00552  *     
00553  *     h = Hash.new {|h,k| h[k] = k*k }   #=> {}
00554  *     p = h.default_proc                 #=> #<Proc:0x401b3d08@-:1>
00555  *     a = []                             #=> []
00556  *     p.call(a, 2)
00557  *     a                                  #=> [nil, nil, 4]
00558  */
00559 
00560 
00561 static VALUE
00562 rb_hash_default_proc(hash)
00563     VALUE hash;
00564 {
00565     if (FL_TEST(hash, HASH_PROC_DEFAULT)) {
00566         return RHASH(hash)->ifnone;
00567     }
00568     return Qnil;
00569 }
00570 
00571 static int
00572 index_i(key, value, args)
00573     VALUE key, value;
00574     VALUE *args;
00575 {
00576     if (rb_equal(value, args[0])) {
00577         args[1] = key;
00578         return ST_STOP;
00579     }
00580     return ST_CONTINUE;
00581 }
00582 
00583 /*
00584  *  call-seq:
00585  *     hsh.index(value)    => key
00586  *  
00587  *  Returns the key for a given value. If not found, returns <code>nil</code>.
00588  *     
00589  *     h = { "a" => 100, "b" => 200 }
00590  *     h.index(200)   #=> "b"
00591  *     h.index(999)   #=> nil
00592  *     
00593  */
00594 
00595 static VALUE
00596 rb_hash_index(hash, value)
00597     VALUE hash, value;
00598 {
00599     VALUE args[2];
00600 
00601     args[0] = value;
00602     args[1] = Qnil;
00603 
00604     rb_hash_foreach(hash, index_i, (st_data_t)args);
00605 
00606     return args[1];
00607 }
00608 
00609 /*
00610  *  call-seq:
00611  *     hsh.indexes(key, ...)    => array
00612  *     hsh.indices(key, ...)    => array
00613  *  
00614  *  Deprecated in favor of <code>Hash#select</code>.
00615  *     
00616  */
00617 
00618 static VALUE
00619 rb_hash_indexes(argc, argv, hash)
00620     int argc;
00621     VALUE *argv;
00622     VALUE hash;
00623 {
00624     VALUE indexes;
00625     int i;
00626 
00627     rb_warn("Hash#%s is deprecated; use Hash#values_at",
00628             rb_id2name(rb_frame_last_func()));
00629     indexes = rb_ary_new2(argc);
00630     for (i=0; i<argc; i++) {
00631         RARRAY(indexes)->ptr[i] = rb_hash_aref(hash, argv[i]);
00632         RARRAY(indexes)->len++;
00633     }
00634     return indexes;
00635 }
00636 
00637 /*
00638  *  call-seq:
00639  *     hsh.delete(key)                   => value
00640  *     hsh.delete(key) {| key | block }  => value
00641  *  
00642  *  Deletes and returns a key-value pair from <i>hsh</i> whose key is
00643  *  equal to <i>key</i>. If the key is not found, returns the
00644  *  <em>default value</em>. If the optional code block is given and the
00645  *  key is not found, pass in the key and return the result of
00646  *  <i>block</i>.
00647  *     
00648  *     h = { "a" => 100, "b" => 200 }
00649  *     h.delete("a")                              #=> 100
00650  *     h.delete("z")                              #=> nil
00651  *     h.delete("z") { |el| "#{el} not found" }   #=> "z not found"
00652  *     
00653  */
00654 
00655 VALUE
00656 rb_hash_delete(hash, key)
00657     VALUE hash, key;
00658 {
00659     VALUE val;
00660 
00661     rb_hash_modify(hash);
00662     if (RHASH(hash)->iter_lev > 0) {
00663         if (st_delete_safe(RHASH(hash)->tbl, (st_data_t*)&key, &val, Qundef)) {
00664             FL_SET(hash, HASH_DELETED);
00665             return val;
00666         }
00667     }
00668     else if (st_delete(RHASH(hash)->tbl, (st_data_t*)&key, &val))
00669         return val;
00670     if (rb_block_given_p()) {
00671         return rb_yield(key);
00672     }
00673     return Qnil;
00674 }
00675 
00676 struct shift_var {
00677     int stop;
00678     VALUE key;
00679     VALUE val;
00680 };
00681 
00682 static int
00683 shift_i(key, value, var)
00684     VALUE key, value;
00685     struct shift_var *var;
00686 {
00687     if (key == Qundef) return ST_CONTINUE;
00688     if (var->stop) return ST_STOP;
00689     var->stop = 1;
00690     var->key = key;
00691     var->val = value;
00692     return ST_DELETE;
00693 }
00694 
00695 /*
00696  *  call-seq:
00697  *     hsh.shift -> anArray or obj
00698  *  
00699  *  Removes a key-value pair from <i>hsh</i> and returns it as the
00700  *  two-item array <code>[</code> <i>key, value</i> <code>]</code>, or
00701  *  the hash's default value if the hash is empty.
00702  *     
00703  *     h = { 1 => "a", 2 => "b", 3 => "c" }
00704  *     h.shift   #=> [1, "a"]
00705  *     h         #=> {2=>"b", 3=>"c"}
00706  */
00707 
00708 static VALUE
00709 rb_hash_shift(hash)
00710     VALUE hash;
00711 {
00712     struct shift_var var;
00713 
00714     rb_hash_modify(hash);
00715     var.stop = 0;
00716     rb_hash_foreach(hash, shift_i, (st_data_t)&var);
00717 
00718     if (var.stop) {
00719         return rb_assoc_new(var.key, var.val);
00720     }
00721     else if (FL_TEST(hash, HASH_PROC_DEFAULT)) {
00722         return rb_funcall(RHASH(hash)->ifnone, id_call, 2, hash, Qnil);
00723     }
00724     else {
00725         return RHASH(hash)->ifnone;
00726     }
00727 }
00728 
00729 static int
00730 delete_if_i(key, value, hash)
00731     VALUE key, value, hash;
00732 {
00733     if (key == Qundef) return ST_CONTINUE;
00734     if (RTEST(rb_yield_values(2, key, value))) {
00735         rb_hash_delete(hash, key);
00736     }
00737     return ST_CONTINUE;
00738 }
00739 
00740 /*
00741  *  call-seq:
00742  *     hsh.delete_if {| key, value | block }  -> hsh
00743  *  
00744  *  Deletes every key-value pair from <i>hsh</i> for which <i>block</i>
00745  *  evaluates to <code>true</code>.
00746  *     
00747  *     h = { "a" => 100, "b" => 200, "c" => 300 }
00748  *     h.delete_if {|key, value| key >= "b" }   #=> {"a"=>100}
00749  *     
00750  */
00751 
00752 VALUE
00753 rb_hash_delete_if(hash)
00754     VALUE hash;
00755 {
00756     rb_hash_modify(hash);
00757     rb_hash_foreach(hash, delete_if_i, hash);
00758     return hash;
00759 }
00760 
00761 /*
00762  *  call-seq:
00763  *     hsh.reject! {| key, value | block }  -> hsh or nil
00764  *  
00765  *  Equivalent to <code>Hash#delete_if</code>, but returns
00766  *  <code>nil</code> if no changes were made.
00767  */
00768 
00769 VALUE
00770 rb_hash_reject_bang(hash)
00771     VALUE hash;
00772 {
00773     int n = RHASH(hash)->tbl->num_entries;
00774     rb_hash_delete_if(hash);
00775     if (n == RHASH(hash)->tbl->num_entries) return Qnil;
00776     return hash;
00777 }
00778 
00779 /*
00780  *  call-seq:
00781  *     hsh.reject {| key, value | block }  -> a_hash
00782  *  
00783  *  Same as <code>Hash#delete_if</code>, but works on (and returns) a
00784  *  copy of the <i>hsh</i>. Equivalent to
00785  *  <code><i>hsh</i>.dup.delete_if</code>.
00786  *     
00787  */
00788 
00789 static VALUE
00790 rb_hash_reject(hash)
00791     VALUE hash;
00792 {
00793     return rb_hash_delete_if(rb_obj_dup(hash));
00794 }
00795 
00796 static int
00797 select_i(key, value, result)
00798     VALUE key, value, result;
00799 {
00800     if (key == Qundef) return ST_CONTINUE;
00801     if (RTEST(rb_yield_values(2, key, value)))
00802         rb_ary_push(result, rb_assoc_new(key, value));
00803     return ST_CONTINUE;
00804 }
00805 
00806 /*
00807  * call-seq:
00808  *   hsh.values_at(key, ...)   => array
00809  *
00810  * Return an array containing the values associated with the given keys.
00811  * Also see <code>Hash.select</code>.
00812  *
00813  *   h = { "cat" => "feline", "dog" => "canine", "cow" => "bovine" }
00814  *   h.values_at("cow", "cat")  #=> ["bovine", "feline"]
00815 */
00816 
00817 VALUE
00818 rb_hash_values_at(argc, argv, hash)
00819     int argc;
00820     VALUE *argv;
00821     VALUE hash;
00822 {
00823     VALUE result = rb_ary_new();
00824     long i;
00825 
00826     for (i=0; i<argc; i++) {
00827         rb_ary_push(result, rb_hash_aref(hash, argv[i]));
00828     }
00829     return result;
00830 }
00831 
00832 /*
00833  *  call-seq:
00834  *     hsh.select {|key, value| block}   => array
00835  *  
00836  *  Returns a new array consisting of <code>[key,value]</code>
00837  *  pairs for which the block returns true.
00838  *  Also see <code>Hash.values_at</code>.
00839  *     
00840  *     h = { "a" => 100, "b" => 200, "c" => 300 }
00841  *     h.select {|k,v| k > "a"}  #=> [["b", 200], ["c", 300]]
00842  *     h.select {|k,v| v < 200}  #=> [["a", 100]]
00843  */
00844 
00845 VALUE
00846 rb_hash_select(argc, argv, hash)
00847     int argc;
00848     VALUE *argv;
00849     VALUE hash;
00850 {
00851     VALUE result;
00852 
00853     if (argc > 0) {
00854         rb_raise(rb_eArgError, "wrong number of arguments (%d for 0)", argc);
00855     }
00856     result = rb_ary_new();
00857     rb_hash_foreach(hash, select_i, result);
00858     return result;
00859 }
00860 
00861 static int
00862 clear_i(key, value, dummy)
00863     VALUE key, value, dummy;
00864 {
00865     return ST_DELETE;
00866 }
00867 
00868 /*
00869  *  call-seq:
00870  *     hsh.clear -> hsh
00871  *  
00872  *  Removes all key-value pairs from <i>hsh</i>.
00873  *     
00874  *     h = { "a" => 100, "b" => 200 }   #=> {"a"=>100, "b"=>200}
00875  *     h.clear                          #=> {}
00876  *     
00877  */
00878 
00879 static VALUE
00880 rb_hash_clear(hash)
00881     VALUE hash;
00882 {
00883     rb_hash_modify(hash);
00884     if (RHASH(hash)->tbl->num_entries > 0) {
00885         rb_hash_foreach(hash, clear_i, 0);
00886     }
00887 
00888     return hash;
00889 }
00890 
00891 /*
00892  *  call-seq:
00893  *     hsh[key] = value        => value
00894  *     hsh.store(key, value)   => value
00895  *  
00896  *  Element Assignment---Associates the value given by
00897  *  <i>value</i> with the key given by <i>key</i>.
00898  *  <i>key</i> should not have its value changed while it is in
00899  *  use as a key (a <code>String</code> passed as a key will be
00900  *  duplicated and frozen).
00901  *     
00902  *     h = { "a" => 100, "b" => 200 }
00903  *     h["a"] = 9
00904  *     h["c"] = 4
00905  *     h   #=> {"a"=>9, "b"=>200, "c"=>4}
00906  *     
00907  */
00908 
00909 VALUE
00910 rb_hash_aset(hash, key, val)
00911     VALUE hash, key, val;
00912 {
00913     rb_hash_modify(hash);
00914     if (TYPE(key) != T_STRING || st_lookup(RHASH(hash)->tbl, key, 0)) {
00915         st_insert(RHASH(hash)->tbl, key, val);
00916     }
00917     else {
00918         st_add_direct(RHASH(hash)->tbl, rb_str_new4(key), val);
00919     }
00920     return val;
00921 }
00922 
00923 static int
00924 replace_i(key, val, hash)
00925     VALUE key, val, hash;
00926 {
00927     if (key != Qundef) {
00928         rb_hash_aset(hash, key, val);
00929     }
00930 
00931     return ST_CONTINUE;
00932 }
00933 
00934 /*
00935  *  call-seq:
00936  *     hsh.replace(other_hash) -> hsh
00937  *  
00938  *  Replaces the contents of <i>hsh</i> with the contents of
00939  *  <i>other_hash</i>.
00940  *     
00941  *     h = { "a" => 100, "b" => 200 }
00942  *     h.replace({ "c" => 300, "d" => 400 })   #=> {"c"=>300, "d"=>400}
00943  *     
00944  */
00945 
00946 static VALUE
00947 rb_hash_replace(hash, hash2)
00948     VALUE hash, hash2;
00949 {
00950     hash2 = to_hash(hash2);
00951     if (hash == hash2) return hash;
00952     rb_hash_clear(hash);
00953     rb_hash_foreach(hash2, replace_i, hash);
00954     RHASH(hash)->ifnone = RHASH(hash2)->ifnone;
00955     if (FL_TEST(hash2, HASH_PROC_DEFAULT)) {
00956         FL_SET(hash, HASH_PROC_DEFAULT);
00957     }
00958     else {
00959         FL_UNSET(hash, HASH_PROC_DEFAULT);
00960     }
00961 
00962     return hash;
00963 }
00964 
00965 /*
00966  *  call-seq:
00967  *     hsh.length    =>  fixnum
00968  *     hsh.size      =>  fixnum
00969  *  
00970  *  Returns the number of key-value pairs in the hash.
00971  *     
00972  *     h = { "d" => 100, "a" => 200, "v" => 300, "e" => 400 }
00973  *     h.length        #=> 4
00974  *     h.delete("a")   #=> 200
00975  *     h.length        #=> 3
00976  */
00977 
00978 static VALUE
00979 rb_hash_size(hash)
00980     VALUE hash;
00981 {
00982     return INT2FIX(RHASH(hash)->tbl->num_entries);
00983 }
00984 
00985 
00986 /*
00987  *  call-seq:
00988  *     hsh.empty?    => true or false
00989  *  
00990  *  Returns <code>true</code> if <i>hsh</i> contains no key-value pairs.
00991  *     
00992  *     {}.empty?   #=> true
00993  *     
00994  */
00995 
00996 static VALUE
00997 rb_hash_empty_p(hash)
00998     VALUE hash;
00999 {
01000     if (RHASH(hash)->tbl->num_entries == 0)
01001         return Qtrue;
01002     return Qfalse;
01003 }
01004 
01005 static int
01006 each_value_i(key, value)
01007     VALUE key, value;
01008 {
01009     if (key == Qundef) return ST_CONTINUE;
01010     rb_yield(value);
01011     return ST_CONTINUE;
01012 }
01013 
01014 /*
01015  *  call-seq:
01016  *     hsh.each_value {| value | block } -> hsh
01017  *  
01018  *  Calls <i>block</i> once for each key in <i>hsh</i>, passing the
01019  *  value as a parameter.
01020  *     
01021  *     h = { "a" => 100, "b" => 200 }
01022  *     h.each_value {|value| puts value }
01023  *     
01024  *  <em>produces:</em>
01025  *     
01026  *     100
01027  *     200
01028  */
01029 
01030 static VALUE
01031 rb_hash_each_value(hash)
01032     VALUE hash;
01033 {
01034     rb_hash_foreach(hash, each_value_i, 0);
01035     return hash;
01036 }
01037 
01038 static int
01039 each_key_i(key, value)
01040     VALUE key, value;
01041 {
01042     if (key == Qundef) return ST_CONTINUE;
01043     rb_yield(key);
01044     return ST_CONTINUE;
01045 }
01046 
01047 /*
01048  *  call-seq:
01049  *     hsh.each_key {| key | block } -> hsh
01050  *  
01051  *  Calls <i>block</i> once for each key in <i>hsh</i>, passing the key
01052  *  as a parameter.
01053  *     
01054  *     h = { "a" => 100, "b" => 200 }
01055  *     h.each_key {|key| puts key }
01056  *     
01057  *  <em>produces:</em>
01058  *     
01059  *     a
01060  *     b
01061  */
01062 static VALUE
01063 rb_hash_each_key(hash)
01064     VALUE hash;
01065 {
01066     rb_hash_foreach(hash, each_key_i, 0);
01067     return hash;
01068 }
01069 
01070 static int
01071 each_pair_i(key, value)
01072     VALUE key, value;
01073 {
01074     if (key == Qundef) return ST_CONTINUE;
01075     rb_yield_values(2, key, value);
01076     return ST_CONTINUE;
01077 }
01078 
01079 /*
01080  *  call-seq:
01081  *     hsh.each_pair {| key_value_array | block } -> hsh
01082  *  
01083  *  Calls <i>block</i> once for each key in <i>hsh</i>, passing the key
01084  *  and value as parameters.
01085  *     
01086  *     h = { "a" => 100, "b" => 200 }
01087  *     h.each_pair {|key, value| puts "#{key} is #{value}" }
01088  *     
01089  *  <em>produces:</em>
01090  *     
01091  *     a is 100
01092  *     b is 200
01093  *     
01094  */
01095 
01096 static VALUE
01097 rb_hash_each_pair(hash)
01098     VALUE hash;
01099 {
01100     rb_hash_foreach(hash, each_pair_i, 0);
01101     return hash;
01102 }
01103 
01104 static int
01105 each_i(key, value)
01106     VALUE key, value;
01107 {
01108     if (key == Qundef) return ST_CONTINUE;
01109     rb_yield(rb_assoc_new(key, value));
01110     return ST_CONTINUE;
01111 }
01112 
01113 /*
01114  *  call-seq:
01115  *     hsh.each {| key, value | block } -> hsh
01116  *  
01117  *  Calls <i>block</i> once for each key in <i>hsh</i>, passing the key
01118  *  and value to the block as a two-element array. Because of the assignment
01119  *  semantics of block parameters, these elements will be split out if the
01120  *  block has two formal parameters. Also see <code>Hash.each_pair</code>, which
01121  *  will be marginally more efficient for blocks with two parameters.
01122  *     
01123  *     h = { "a" => 100, "b" => 200 }
01124  *     h.each {|key, value| puts "#{key} is #{value}" }
01125  *     
01126  *  <em>produces:</em>
01127  *     
01128  *     a is 100
01129  *     b is 200
01130  *     
01131  */
01132 
01133 static VALUE
01134 rb_hash_each(hash)
01135     VALUE hash;
01136 {
01137     rb_hash_foreach(hash, each_i, 0);
01138     return hash;
01139 }
01140 
01141 static int
01142 to_a_i(key, value, ary)
01143     VALUE key, value, ary;
01144 {
01145     if (key == Qundef) return ST_CONTINUE;
01146     rb_ary_push(ary, rb_assoc_new(key, value));
01147     return ST_CONTINUE;
01148 }
01149 
01150 /*
01151  *  call-seq:
01152  *     hsh.to_a -> array
01153  *  
01154  *  Converts <i>hsh</i> to a nested array of <code>[</code> <i>key,
01155  *  value</i> <code>]</code> arrays.
01156  *     
01157  *     h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300  }
01158  *     h.to_a   #=> [["a", 100], ["c", 300], ["d", 400]]
01159  */
01160 
01161 static VALUE
01162 rb_hash_to_a(hash)
01163     VALUE hash;
01164 {
01165     VALUE ary;
01166 
01167     ary = rb_ary_new();
01168     rb_hash_foreach(hash, to_a_i, ary);
01169     if (OBJ_TAINTED(hash)) OBJ_TAINT(ary);
01170 
01171     return ary;
01172 }
01173 
01174 /*
01175  *  call-seq:
01176  *     hsh.sort                    => array 
01177  *     hsh.sort {| a, b | block }  => array 
01178  * 
01179  *  Converts <i>hsh</i> to a nested array of <code>[</code> <i>key,
01180  *  value</i> <code>]</code> arrays and sorts it, using
01181  *  <code>Array#sort</code>.
01182  *     
01183  *     h = { "a" => 20, "b" => 30, "c" => 10  }
01184  *     h.sort                       #=> [["a", 20], ["b", 30], ["c", 10]]
01185  *     h.sort {|a,b| a[1]<=>b[1]}   #=> [["c", 10], ["a", 20], ["b", 30]]
01186  *     
01187  */
01188 
01189 static VALUE
01190 rb_hash_sort(hash)
01191     VALUE hash;
01192 {
01193     VALUE entries = rb_hash_to_a(hash);
01194     rb_ary_sort_bang(entries);
01195     return entries;
01196 }
01197 
01198 static int
01199 inspect_i(key, value, str)
01200     VALUE key, value, str;
01201 {
01202     VALUE str2;
01203 
01204     if (key == Qundef) return ST_CONTINUE;
01205     if (RSTRING(str)->len > 1) {
01206         rb_str_cat2(str, ", ");
01207     }
01208     str2 = rb_inspect(key);
01209     rb_str_buf_append(str, str2);
01210     OBJ_INFECT(str, str2);
01211     rb_str_buf_cat2(str, "=>");
01212     str2 = rb_inspect(value);
01213     rb_str_buf_append(str, str2);
01214     OBJ_INFECT(str, str2);
01215 
01216     return ST_CONTINUE;
01217 }
01218 
01219 static VALUE
01220 inspect_hash(hash)
01221     VALUE hash;
01222 {
01223     VALUE str;
01224 
01225     str = rb_str_buf_new2("{");
01226     rb_hash_foreach(hash, inspect_i, str);
01227     rb_str_buf_cat2(str, "}");
01228     OBJ_INFECT(str, hash);
01229 
01230     return str;
01231 }
01232 
01233 /*
01234  * call-seq:
01235  *   hsh.inspect  => string
01236  *
01237  * Return the contents of this hash as a string.
01238  */
01239 
01240 static VALUE
01241 rb_hash_inspect(hash)
01242     VALUE hash;
01243 {
01244     if (RHASH(hash)->tbl == 0 || RHASH(hash)->tbl->num_entries == 0)
01245         return rb_str_new2("{}");
01246     if (rb_inspecting_p(hash)) return rb_str_new2("{...}");
01247     return rb_protect_inspect(inspect_hash, hash, 0);
01248 }
01249 
01250 static VALUE
01251 to_s_hash(hash)
01252     VALUE hash;
01253 {
01254     return rb_ary_to_s(rb_hash_to_a(hash));
01255 }
01256 
01257 /*
01258  *  call-seq:
01259  *     hsh.to_s   => string
01260  *  
01261  *  Converts <i>hsh</i> to a string by converting the hash to an array
01262  *  of <code>[</code> <i>key, value</i> <code>]</code> pairs and then
01263  *  converting that array to a string using <code>Array#join</code> with
01264  *  the default separator.
01265  *     
01266  *     h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300  }
01267  *     h.to_s   #=> "a100c300d400"
01268  */
01269 
01270 static VALUE
01271 rb_hash_to_s(hash)
01272     VALUE hash;
01273 {
01274     if (rb_inspecting_p(hash)) return rb_str_new2("{...}");
01275     return rb_protect_inspect(to_s_hash, hash, 0);
01276 }
01277 
01278 /*
01279  * call-seq:
01280  *    hsh.to_hash   => hsh
01281  *
01282  * Returns <i>self</i>.
01283  */
01284 
01285 static VALUE
01286 rb_hash_to_hash(hash)
01287     VALUE hash;
01288 {
01289     return hash;
01290 }
01291 
01292 static int
01293 keys_i(key, value, ary)
01294     VALUE key, value, ary;
01295 {
01296     if (key == Qundef) return ST_CONTINUE;
01297     rb_ary_push(ary, key);
01298     return ST_CONTINUE;
01299 }
01300 
01301 /*
01302  *  call-seq:
01303  *     hsh.keys    => array
01304  *  
01305  *  Returns a new array populated with the keys from this hash. See also
01306  *  <code>Hash#values</code>.
01307  *     
01308  *     h = { "a" => 100, "b" => 200, "c" => 300, "d" => 400 }
01309  *     h.keys   #=> ["a", "b", "c", "d"]
01310  *     
01311  */
01312 
01313 static VALUE
01314 rb_hash_keys(hash)
01315     VALUE hash;
01316 {
01317     VALUE ary;
01318 
01319     ary = rb_ary_new();
01320     rb_hash_foreach(hash, keys_i, ary);
01321 
01322     return ary;
01323 }
01324 
01325 static int
01326 values_i(key, value, ary)
01327     VALUE key, value, ary;
01328 {
01329     if (key == Qundef) return ST_CONTINUE;
01330     rb_ary_push(ary, value);
01331     return ST_CONTINUE;
01332 }
01333 
01334 /*
01335  *  call-seq:
01336  *     hsh.values    => array
01337  *  
01338  *  Returns a new array populated with the values from <i>hsh</i>. See
01339  *  also <code>Hash#keys</code>.
01340  *     
01341  *     h = { "a" => 100, "b" => 200, "c" => 300 }
01342  *     h.values   #=> [100, 200, 300]
01343  *     
01344  */
01345 
01346 static VALUE
01347 rb_hash_values(hash)
01348     VALUE hash;
01349 {
01350     VALUE ary;
01351 
01352     ary = rb_ary_new();
01353     rb_hash_foreach(hash, values_i, ary);
01354 
01355     return ary;
01356 }
01357 
01358 /*
01359  *  call-seq:
01360  *     hsh.has_key?(key)    => true or false
01361  *     hsh.include?(key)    => true or false
01362  *     hsh.key?(key)        => true or false
01363  *     hsh.member?(key)     => true or false
01364  *  
01365  *  Returns <code>true</code> if the given key is present in <i>hsh</i>.
01366  *     
01367  *     h = { "a" => 100, "b" => 200 }
01368  *     h.has_key?("a")   #=> true
01369  *     h.has_key?("z")   #=> false
01370  *     
01371  */
01372 
01373 static VALUE
01374 rb_hash_has_key(hash, key)
01375     VALUE hash;
01376     VALUE key;
01377 {
01378     if (st_lookup(RHASH(hash)->tbl, key, 0)) {
01379         return Qtrue;
01380     }
01381     return Qfalse;
01382 }
01383 
01384 static int
01385 rb_hash_search_value(key, value, data)
01386     VALUE key, value, *data;
01387 {
01388     if (key == Qundef) return ST_CONTINUE;
01389     if (rb_equal(value, data[1])) {
01390         data[0] = Qtrue;
01391         return ST_STOP;
01392     }
01393     return ST_CONTINUE;
01394 }
01395 
01396 /*
01397  *  call-seq:
01398  *     hsh.has_value?(value)    => true or false
01399  *     hsh.value?(value)        => true or false
01400  *  
01401  *  Returns <code>true</code> if the given value is present for some key
01402  *  in <i>hsh</i>.
01403  *     
01404  *     h = { "a" => 100, "b" => 200 }
01405  *     h.has_value?(100)   #=> true
01406  *     h.has_value?(999)   #=> false
01407  */
01408 
01409 static VALUE
01410 rb_hash_has_value(hash, val)
01411     VALUE hash;
01412     VALUE val;
01413 {
01414     VALUE data[2];
01415 
01416     data[0] = Qfalse;
01417     data[1] = val;
01418     rb_hash_foreach(hash, rb_hash_search_value, (st_data_t)data);
01419     return data[0];
01420 }
01421 
01422 struct equal_data {
01423     int result;
01424     st_table *tbl;
01425 };
01426 
01427 static int
01428 equal_i(key, val1, data)
01429     VALUE key, val1;
01430     struct equal_data *data;
01431 {
01432     VALUE val2;
01433 
01434     if (key == Qundef) return ST_CONTINUE;
01435     if (!st_lookup(data->tbl, key, &val2)) {
01436         data->result = Qfalse;
01437         return ST_STOP;
01438     }
01439     if (!rb_equal(val1, val2)) {
01440         data->result = Qfalse;
01441         return ST_STOP;
01442     }
01443     return ST_CONTINUE;
01444 }
01445 
01446 static VALUE
01447 hash_equal(hash1, hash2, eql)
01448     VALUE hash1, hash2;
01449     int eql;                    /* compare default value if true */
01450 {
01451     struct equal_data data;
01452 
01453     if (hash1 == hash2) return Qtrue;
01454     if (TYPE(hash2) != T_HASH) {
01455         if (!rb_respond_to(hash2, rb_intern("to_hash"))) {
01456             return Qfalse;
01457         }
01458         return rb_equal(hash2, hash1);
01459     }
01460     if (RHASH(hash1)->tbl->num_entries != RHASH(hash2)->tbl->num_entries)
01461         return Qfalse;
01462     if (eql) {
01463         if (!(rb_equal(RHASH(hash1)->ifnone, RHASH(hash2)->ifnone) &&
01464               FL_TEST(hash1, HASH_PROC_DEFAULT) == FL_TEST(hash2, HASH_PROC_DEFAULT)))
01465             return Qfalse;
01466     }
01467 
01468     data.tbl = RHASH(hash2)->tbl;
01469     data.result = Qtrue;
01470     rb_hash_foreach(hash1, equal_i, (st_data_t)&data);
01471 
01472     return data.result;
01473 }
01474 
01475 /*
01476  *  call-seq:
01477  *     hsh == other_hash    => true or false
01478  *  
01479  *  Equality---Two hashes are equal if they each contain the same number
01480  *  of keys and if each key-value pair is equal to (according to
01481  *  <code>Object#==</code>) the corresponding elements in the other
01482  *  hash.
01483  *     
01484  *     h1 = { "a" => 1, "c" => 2 }
01485  *     h2 = { 7 => 35, "c" => 2, "a" => 1 }
01486  *     h3 = { "a" => 1, "c" => 2, 7 => 35 }
01487  *     h4 = { "a" => 1, "d" => 2, "f" => 35 }
01488  *     h1 == h2   #=> false
01489  *     h2 == h3   #=> true
01490  *     h3 == h4   #=> false
01491  *     
01492  */
01493 
01494 static VALUE
01495 rb_hash_equal(hash1, hash2)
01496     VALUE hash1, hash2;
01497 {
01498     return hash_equal(hash1, hash2, Qfalse);
01499 }
01500 
01501 static int
01502 rb_hash_invert_i(key, value, hash)
01503     VALUE key, value;
01504     VALUE hash;
01505 {
01506     if (key == Qundef) return ST_CONTINUE;
01507     rb_hash_aset(hash, value, key);
01508     return ST_CONTINUE;
01509 }
01510 
01511 /*
01512  *  call-seq:
01513  *     hsh.invert -> aHash
01514  *  
01515  *  Returns a new hash created by using <i>hsh</i>'s values as keys, and
01516  *  the keys as values.
01517  *     
01518  *     h = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 }
01519  *     h.invert   #=> {0=>"a", 100=>"n", 200=>"d", 300=>"y"}
01520  *     
01521  */
01522 
01523 static VALUE
01524 rb_hash_invert(hash)
01525     VALUE hash;
01526 {
01527     VALUE h = rb_hash_new();
01528 
01529     rb_hash_foreach(hash, rb_hash_invert_i, h);
01530     return h;
01531 }
01532 
01533 static int
01534 rb_hash_update_i(key, value, hash)
01535     VALUE key, value;
01536     VALUE hash;
01537 {
01538     if (key == Qundef) return ST_CONTINUE;
01539     rb_hash_aset(hash, key, value);
01540     return ST_CONTINUE;
01541 }
01542 
01543 static int
01544 rb_hash_update_block_i(key, value, hash)
01545     VALUE key, value;
01546     VALUE hash;
01547 {
01548     if (key == Qundef) return ST_CONTINUE;
01549     if (rb_hash_has_key(hash, key)) {
01550         value = rb_yield_values(3, key, rb_hash_aref(hash, key), value);
01551     }
01552     rb_hash_aset(hash, key, value);
01553     return ST_CONTINUE;
01554 }
01555 
01556 /*
01557  *  call-seq:
01558  *     hsh.merge!(other_hash)                                 => hsh
01559  *     hsh.update(other_hash)                                 => hsh
01560  *     hsh.merge!(other_hash){|key, oldval, newval| block}    => hsh
01561  *     hsh.update(other_hash){|key, oldval, newval| block}    => hsh
01562  *  
01563  *  Adds the contents of <i>other_hash</i> to <i>hsh</i>, overwriting
01564  *  entries with duplicate keys with those from <i>other_hash</i>.
01565  *     
01566  *     h1 = { "a" => 100, "b" => 200 }
01567  *     h2 = { "b" => 254, "c" => 300 }
01568  *     h1.merge!(h2)   #=> {"a"=>100, "b"=>254, "c"=>300}
01569  */
01570 
01571 static VALUE
01572 rb_hash_update(hash1, hash2)
01573     VALUE hash1, hash2;
01574 {
01575     hash2 = to_hash(hash2);
01576     if (rb_block_given_p()) {
01577         rb_hash_foreach(hash2, rb_hash_update_block_i, hash1);
01578     }
01579     else {
01580         rb_hash_foreach(hash2, rb_hash_update_i, hash1);
01581     }
01582     return hash1;
01583 }
01584 
01585 /*
01586  *  call-seq:
01587  *     hsh.merge(other_hash)                              -> a_hash
01588  *     hsh.merge(other_hash){|key, oldval, newval| block} -> a_hash
01589  *  
01590  *  Returns a new hash containing the contents of <i>other_hash</i> and
01591  *  the contents of <i>hsh</i>, overwriting entries in <i>hsh</i> with
01592  *  duplicate keys with those from <i>other_hash</i>.
01593  *     
01594  *     h1 = { "a" => 100, "b" => 200 }
01595  *     h2 = { "b" => 254, "c" => 300 }
01596  *     h1.merge(h2)   #=> {"a"=>100, "b"=>254, "c"=>300}
01597  *     h1             #=> {"a"=>100, "b"=>200}
01598  *     
01599  */
01600 
01601 static VALUE
01602 rb_hash_merge(hash1, hash2)
01603     VALUE hash1, hash2;
01604 {
01605     return rb_hash_update(rb_obj_dup(hash1), hash2);
01606 }
01607 
01608 static int path_tainted = -1;
01609 
01610 static char **origenviron;
01611 #ifdef _WIN32
01612 #define GET_ENVIRON(e) (e = rb_w32_get_environ())
01613 #define FREE_ENVIRON(e) rb_w32_free_environ(e)
01614 static char **my_environ;
01615 #undef environ
01616 #define environ my_environ
01617 #elif defined(__APPLE__)
01618 #undef environ
01619 #define environ (*_NSGetEnviron())
01620 #define GET_ENVIRON(e) (e)
01621 #define FREE_ENVIRON(e)
01622 #else
01623 extern char **environ;
01624 #define GET_ENVIRON(e) (e)
01625 #define FREE_ENVIRON(e)
01626 #endif
01627 
01628 static VALUE
01629 env_str_new(ptr, len)
01630     const char *ptr;
01631     long len;
01632 {
01633     VALUE str = rb_tainted_str_new(ptr, len);
01634 
01635     rb_obj_freeze(str);
01636     return str;
01637 }
01638 
01639 static VALUE
01640 env_str_new2(ptr)
01641     const char *ptr;
01642 {
01643     if (!ptr) return Qnil;
01644     return env_str_new(ptr, strlen(ptr));
01645 }
01646 
01647 static VALUE
01648 env_delete(obj, name)
01649     VALUE obj, name;
01650 {
01651     char *nam, *val;
01652 
01653     rb_secure(4);
01654     SafeStringValue(name);
01655     nam = RSTRING(name)->ptr;
01656     if (strlen(nam) != RSTRING(name)->len) {
01657         rb_raise(rb_eArgError, "bad environment variable name");
01658     }
01659     val = getenv(nam);
01660     if (val) {
01661         VALUE value = env_str_new2(val);
01662 
01663         ruby_setenv(nam, 0);
01664 #ifdef ENV_IGNORECASE
01665         if (strcasecmp(nam, PATH_ENV) == 0)
01666 #else
01667         if (strcmp(nam, PATH_ENV) == 0)
01668 #endif
01669         {
01670             path_tainted = 0;
01671         }
01672         return value;
01673     }
01674     return Qnil;
01675 }
01676 
01677 static VALUE
01678 env_delete_m(obj, name)
01679     VALUE obj, name;
01680 {
01681     VALUE val;
01682 
01683     val = env_delete(obj, name);
01684     if (NIL_P(val) && rb_block_given_p()) rb_yield(name);
01685     return val;
01686 }
01687 
01688 static VALUE
01689 rb_f_getenv(obj, name)
01690     VALUE obj, name;
01691 {
01692     char *nam, *env;
01693 
01694     StringValue(name);
01695     nam = RSTRING(name)->ptr;
01696     if (strlen(nam) != RSTRING(name)->len) {
01697         rb_raise(rb_eArgError, "bad environment variable name");
01698     }
01699     env = getenv(nam);
01700     if (env) {
01701 #ifdef ENV_IGNORECASE
01702         if (strcasecmp(nam, PATH_ENV) == 0 && !rb_env_path_tainted())
01703 #else
01704         if (strcmp(nam, PATH_ENV) == 0 && !rb_env_path_tainted())
01705 #endif
01706         {
01707             VALUE str = rb_str_new2(env);
01708 
01709             rb_obj_freeze(str);
01710             return str;
01711         }
01712         return env_str_new2(env);
01713     }
01714     return Qnil;
01715 }
01716 
01717 static VALUE
01718 env_fetch(argc, argv)
01719     int argc;
01720     VALUE *argv;
01721 {
01722     VALUE key, if_none;
01723     long block_given;
01724     char *nam, *env;
01725 
01726     rb_scan_args(argc, argv, "11", &key, &if_none);
01727     block_given = rb_block_given_p();
01728     if (block_given && argc == 2) {
01729         rb_warn("block supersedes default value argument");
01730     }
01731     StringValue(key);
01732     nam = RSTRING(key)->ptr;
01733     if (str