1 /**********************************************************************
6 created at: Mon Nov 22 18:51:18 JST 1993
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9 Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10 Copyright (C) 2000 Information-technology Promotion Agency, Japan
12 **********************************************************************/
14 #include "ruby/ruby.h"
16 #include "ruby/util.h"
17 #include "ruby/signal.h"
20 #include <crt_externs.h>
23 static VALUE
rb_hash_s_try_convert(VALUE
, VALUE
);
25 #define HASH_DELETED FL_USER1
26 #define HASH_PROC_DEFAULT FL_USER2
29 rb_hash_freeze(VALUE hash
)
31 return rb_obj_freeze(hash
);
37 static ID id_hash
, id_yield
, id_default
;
42 return (VALUE
)rb_eql(args
[0], args
[1]);
46 rb_any_cmp(VALUE a
, VALUE b
)
51 if (FIXNUM_P(a
) && FIXNUM_P(b
)) {
54 if (TYPE(a
) == T_STRING
&& RBASIC(a
)->klass
== rb_cString
&&
55 TYPE(b
) == T_STRING
&& RBASIC(b
)->klass
== rb_cString
) {
56 return rb_str_hash_cmp(a
, b
);
58 if (a
== Qundef
|| b
== Qundef
) return -1;
59 if (SYMBOL_P(a
) && SYMBOL_P(b
)) {
65 return !rb_with_disable_interrupt(eql
, (VALUE
)args
);
71 return rb_funcall(obj
, id_hash
, 0);
87 hnum
= rb_str_hash(a
);
91 hval
= rb_funcall(a
, id_hash
, 0);
92 if (!FIXNUM_P(hval
)) {
93 hval
= rb_funcall(hval
, '%', 1, INT2FIX(536870923));
95 hnum
= (int)FIX2LONG(hval
);
98 return RSHIFT(hnum
, 1);
101 static const struct st_hash_type objhash
= {
106 static const struct st_hash_type identhash
= {
111 typedef int st_foreach_func(st_data_t
, st_data_t
, st_data_t
);
113 struct foreach_safe_arg
{
115 st_foreach_func
*func
;
120 foreach_safe_i(st_data_t key
, st_data_t value
, struct foreach_safe_arg
*arg
)
124 if (key
== Qundef
) return ST_CONTINUE
;
125 status
= (*arg
->func
)(key
, value
, arg
->arg
);
126 if (status
== ST_CONTINUE
) {
133 st_foreach_safe(st_table
*table
, int (*func
)(ANYARGS
), st_data_t a
)
135 struct foreach_safe_arg arg
;
138 arg
.func
= (st_foreach_func
*)func
;
140 if (st_foreach(table
, foreach_safe_i
, (st_data_t
)&arg
)) {
141 rb_raise(rb_eRuntimeError
, "hash modified during iteration");
145 typedef int rb_foreach_func(VALUE
, VALUE
, VALUE
);
147 struct hash_foreach_arg
{
149 rb_foreach_func
*func
;
154 hash_foreach_iter(VALUE key
, VALUE value
, struct hash_foreach_arg
*arg
)
159 tbl
= RHASH(arg
->hash
)->ntbl
;
160 if (key
== Qundef
) return ST_CONTINUE
;
161 status
= (*arg
->func
)(key
, value
, arg
->arg
);
162 if (RHASH(arg
->hash
)->ntbl
!= tbl
) {
163 rb_raise(rb_eRuntimeError
, "rehash occurred during iteration");
167 st_delete_safe(tbl
, (st_data_t
*)&key
, 0, Qundef
);
168 FL_SET(arg
->hash
, HASH_DELETED
);
178 hash_foreach_ensure(VALUE hash
)
180 RHASH(hash
)->iter_lev
--;
182 if (RHASH(hash
)->iter_lev
== 0) {
183 if (FL_TEST(hash
, HASH_DELETED
)) {
184 st_cleanup_safe(RHASH(hash
)->ntbl
, Qundef
);
185 FL_UNSET(hash
, HASH_DELETED
);
192 hash_foreach_call(struct hash_foreach_arg
*arg
)
194 if (st_foreach(RHASH(arg
->hash
)->ntbl
, hash_foreach_iter
, (st_data_t
)arg
)) {
195 rb_raise(rb_eRuntimeError
, "hash modified during iteration");
201 rb_hash_foreach(VALUE hash
, int (*func
)(ANYARGS
), VALUE farg
)
203 struct hash_foreach_arg arg
;
205 if (!RHASH(hash
)->ntbl
)
207 RHASH(hash
)->iter_lev
++;
209 arg
.func
= (rb_foreach_func
*)func
;
211 rb_ensure(hash_foreach_call
, (VALUE
)&arg
, hash_foreach_ensure
, hash
);
215 hash_alloc(VALUE klass
)
217 NEWOBJ(hash
, struct RHash
);
218 OBJSETUP(hash
, klass
, T_HASH
);
228 return hash_alloc(rb_cHash
);
232 rb_hash_dup(VALUE hash
)
234 NEWOBJ(ret
, struct RHash
);
237 if (!RHASH_EMPTY_P(hash
))
238 ret
->ntbl
= st_copy(RHASH(hash
)->ntbl
);
239 if (FL_TEST(hash
, HASH_PROC_DEFAULT
)) {
240 FL_SET(ret
, HASH_PROC_DEFAULT
);
242 ret
->ifnone
= RHASH(hash
)->ifnone
;
247 rb_hash_modify_check(VALUE hash
)
249 if (OBJ_FROZEN(hash
)) rb_error_frozen("hash");
250 if (!OBJ_TAINTED(hash
) && rb_safe_level() >= 4)
251 rb_raise(rb_eSecurityError
, "Insecure: can't modify hash");
255 rb_hash_tbl(VALUE hash
)
257 if (!RHASH(hash
)->ntbl
) {
258 RHASH(hash
)->ntbl
= st_init_table(&objhash
);
260 return RHASH(hash
)->ntbl
;
264 rb_hash_modify(VALUE hash
)
266 rb_hash_modify_check(hash
);
273 * Hash.new(obj) => aHash
274 * Hash.new {|hash, key| block } => aHash
276 * Returns a new, empty hash. If this hash is subsequently accessed by
277 * a key that doesn't correspond to a hash entry, the value returned
278 * depends on the style of <code>new</code> used to create the hash. In
279 * the first form, the access returns <code>nil</code>. If
280 * <i>obj</i> is specified, this single object will be used for
281 * all <em>default values</em>. If a block is specified, it will be
282 * called with the hash object and the key, and should return the
283 * default value. It is the block's responsibility to store the value
284 * in the hash if required.
286 * h = Hash.new("Go Fish")
290 * h["c"] #=> "Go Fish"
291 * # The following alters the single default object
292 * h["c"].upcase! #=> "GO FISH"
293 * h["d"] #=> "GO FISH"
294 * h.keys #=> ["a", "b"]
296 * # While this creates a new default object each time
297 * h = Hash.new { |hash, key| hash[key] = "Go Fish: #{key}" }
298 * h["c"] #=> "Go Fish: c"
299 * h["c"].upcase! #=> "GO FISH: C"
300 * h["d"] #=> "Go Fish: d"
301 * h.keys #=> ["c", "d"]
306 rb_hash_initialize(int argc
, VALUE
*argv
, VALUE hash
)
310 rb_hash_modify(hash
);
311 if (rb_block_given_p()) {
313 rb_raise(rb_eArgError
, "wrong number of arguments");
315 RHASH(hash
)->ifnone
= rb_block_proc();
316 FL_SET(hash
, HASH_PROC_DEFAULT
);
319 rb_scan_args(argc
, argv
, "01", &ifnone
);
320 RHASH(hash
)->ifnone
= ifnone
;
328 * Hash[ [key =>|, value]* ] => hash
330 * Creates a new hash populated with the given objects. Equivalent to
331 * the literal <code>{ <i>key</i>, <i>value</i>, ... }</code>. Keys and
332 * values occur in pairs, so there must be an even number of arguments.
334 * Hash["a", 100, "b", 200] #=> {"a"=>100, "b"=>200}
335 * Hash["a" => 100, "b" => 200] #=> {"a"=>100, "b"=>200}
336 * { "a" => 100, "b" => 200 } #=> {"a"=>100, "b"=>200}
340 rb_hash_s_create(int argc
, VALUE
*argv
, VALUE klass
)
346 tmp
= rb_hash_s_try_convert(Qnil
, argv
[0]);
348 hash
= hash_alloc(klass
);
349 if (RHASH(tmp
)->ntbl
) {
350 RHASH(hash
)->ntbl
= st_copy(RHASH(tmp
)->ntbl
);
355 tmp
= rb_check_array_type(argv
[0]);
359 hash
= hash_alloc(klass
);
360 for (i
= 0; i
< RARRAY_LEN(tmp
); ++i
) {
361 VALUE v
= rb_check_array_type(RARRAY_PTR(tmp
)[i
]);
363 if (NIL_P(v
)) continue;
364 if (RARRAY_LEN(v
) < 1 || 2 < RARRAY_LEN(v
)) continue;
365 rb_hash_aset(hash
, RARRAY_PTR(v
)[0], RARRAY_PTR(v
)[1]);
371 rb_raise(rb_eArgError
, "odd number of arguments for Hash");
374 hash
= hash_alloc(klass
);
375 for (i
=0; i
<argc
; i
+=2) {
376 rb_hash_aset(hash
, argv
[i
], argv
[i
+ 1]);
385 return rb_convert_type(hash
, T_HASH
, "Hash", "to_hash");
390 * Hash.try_convert(obj) -> hash or nil
392 * Try to convert <i>obj</i> into a hash, using to_hash method.
393 * Returns converted hash or nil if <i>obj</i> cannot be converted
396 * Hash.try_convert({1=>2}) # => {1=>2}
397 * Hash.try_convert("1=>2") # => nil
400 rb_hash_s_try_convert(VALUE dummy
, VALUE hash
)
402 return rb_check_convert_type(hash
, T_HASH
, "Hash", "to_hash");
406 rb_hash_rehash_i(VALUE key
, VALUE value
, st_table
*tbl
)
408 if (key
!= Qundef
) st_insert(tbl
, key
, value
);
416 * Rebuilds the hash based on the current hash values for each key. If
417 * values of key objects have changed since they were inserted, this
418 * method will reindex <i>hsh</i>. If <code>Hash#rehash</code> is
419 * called while an iterator is traversing the hash, an
420 * <code>RuntimeError</code> will be raised in the iterator.
424 * h = { a => 100, c => 300 }
428 * h.rehash #=> {["z", "b"]=>100, ["c", "d"]=>300}
433 rb_hash_rehash(VALUE hash
)
437 if (RHASH(hash
)->iter_lev
> 0) {
438 rb_raise(rb_eRuntimeError
, "rehash during iteration");
440 rb_hash_modify_check(hash
);
441 if (!RHASH(hash
)->ntbl
)
443 tbl
= st_init_table_with_size(RHASH(hash
)->ntbl
->type
, RHASH(hash
)->ntbl
->num_entries
);
444 rb_hash_foreach(hash
, rb_hash_rehash_i
, (st_data_t
)tbl
);
445 st_free_table(RHASH(hash
)->ntbl
);
446 RHASH(hash
)->ntbl
= tbl
;
455 * Element Reference---Retrieves the <i>value</i> object corresponding
456 * to the <i>key</i> object. If not found, returns the a default value (see
457 * <code>Hash::new</code> for details).
459 * h = { "a" => 100, "b" => 200 }
466 rb_hash_aref(VALUE hash
, VALUE key
)
470 if (!RHASH(hash
)->ntbl
|| !st_lookup(RHASH(hash
)->ntbl
, key
, &val
)) {
471 return rb_funcall(hash
, id_default
, 1, key
);
477 rb_hash_lookup(VALUE hash
, VALUE key
)
481 if (!RHASH(hash
)->ntbl
|| !st_lookup(RHASH(hash
)->ntbl
, key
, &val
)) {
482 return Qnil
; /* without Hash#default */
489 * hsh.fetch(key [, default] ) => obj
490 * hsh.fetch(key) {| key | block } => obj
492 * Returns a value from the hash for the given key. If the key can't be
493 * found, there are several options: With no other arguments, it will
494 * raise an <code>KeyError</code> exception; if <i>default</i> is
495 * given, then that will be returned; if the optional code block is
496 * specified, then that will be run and its result returned.
498 * h = { "a" => 100, "b" => 200 }
499 * h.fetch("a") #=> 100
500 * h.fetch("z", "go fish") #=> "go fish"
501 * h.fetch("z") { |el| "go fish, #{el}"} #=> "go fish, z"
503 * The following example shows that an exception is raised if the key
504 * is not found and a default value is not supplied.
506 * h = { "a" => 100, "b" => 200 }
511 * prog.rb:2:in `fetch': key not found (KeyError)
517 rb_hash_fetch(int argc
, VALUE
*argv
, VALUE hash
)
523 rb_scan_args(argc
, argv
, "11", &key
, &if_none
);
525 block_given
= rb_block_given_p();
526 if (block_given
&& argc
== 2) {
527 rb_warn("block supersedes default value argument");
529 if (!RHASH(hash
)->ntbl
|| !st_lookup(RHASH(hash
)->ntbl
, key
, &val
)) {
530 if (block_given
) return rb_yield(key
);
532 rb_raise(rb_eKeyError
, "key not found");
541 * hsh.default(key=nil) => obj
543 * Returns the default value, the value that would be returned by
544 * <i>hsh</i>[<i>key</i>] if <i>key</i> did not exist in <i>hsh</i>.
545 * See also <code>Hash::new</code> and <code>Hash#default=</code>.
547 * h = Hash.new #=> {}
549 * h.default(2) #=> nil
551 * h = Hash.new("cat") #=> {}
552 * h.default #=> "cat"
553 * h.default(2) #=> "cat"
555 * h = Hash.new {|h,k| h[k] = k.to_i*10} #=> {}
557 * h.default(2) #=> 20
561 rb_hash_default(int argc
, VALUE
*argv
, VALUE hash
)
565 rb_scan_args(argc
, argv
, "01", &key
);
566 if (FL_TEST(hash
, HASH_PROC_DEFAULT
)) {
567 if (argc
== 0) return Qnil
;
568 return rb_funcall(RHASH(hash
)->ifnone
, id_yield
, 2, hash
, key
);
570 return RHASH(hash
)->ifnone
;
575 * hsh.default = obj => hsh
577 * Sets the default value, the value returned for a key that does not
578 * exist in the hash. It is not possible to set the a default to a
579 * <code>Proc</code> that will be executed on each key lookup.
581 * h = { "a" => 100, "b" => 200 }
582 * h.default = "Go fish"
584 * h["z"] #=> "Go fish"
585 * # This doesn't do what you might hope...
586 * h.default = proc do |hash, key|
587 * hash[key] = key + key
589 * h[2] #=> #<Proc:0x401b3948@-:6>
590 * h["cat"] #=> #<Proc:0x401b3948@-:6>
594 rb_hash_set_default(VALUE hash
, VALUE ifnone
)
596 rb_hash_modify(hash
);
597 RHASH(hash
)->ifnone
= ifnone
;
598 FL_UNSET(hash
, HASH_PROC_DEFAULT
);
604 * hsh.default_proc -> anObject
606 * If <code>Hash::new</code> was invoked with a block, return that
607 * block, otherwise return <code>nil</code>.
609 * h = Hash.new {|h,k| h[k] = k*k } #=> {}
610 * p = h.default_proc #=> #<Proc:0x401b3d08@-:1>
613 * a #=> [nil, nil, 4]
618 rb_hash_default_proc(VALUE hash
)
620 if (FL_TEST(hash
, HASH_PROC_DEFAULT
)) {
621 return RHASH(hash
)->ifnone
;
627 key_i(VALUE key
, VALUE value
, VALUE
*args
)
629 if (rb_equal(value
, args
[0])) {
638 * hsh.key(value) => key
640 * Returns the key for a given value. If not found, returns <code>nil</code>.
642 * h = { "a" => 100, "b" => 200 }
649 rb_hash_key(VALUE hash
, VALUE value
)
656 rb_hash_foreach(hash
, key_i
, (st_data_t
)args
);
663 rb_hash_index(VALUE hash
, VALUE value
)
665 rb_warn("Hash#index is deprecated; use Hash#key");
666 return rb_hash_key(hash
, value
);
670 rb_hash_delete_key(VALUE hash
, VALUE key
)
672 st_data_t ktmp
= (st_data_t
)key
, val
;
674 if (!RHASH(hash
)->ntbl
)
676 if (RHASH(hash
)->iter_lev
> 0) {
677 if (st_delete_safe(RHASH(hash
)->ntbl
, &ktmp
, &val
, Qundef
)) {
678 FL_SET(hash
, HASH_DELETED
);
682 else if (st_delete(RHASH(hash
)->ntbl
, &ktmp
, &val
))
689 * hsh.delete(key) => value
690 * hsh.delete(key) {| key | block } => value
692 * Deletes and returns a key-value pair from <i>hsh</i> whose key is
693 * equal to <i>key</i>. If the key is not found, returns the
694 * <em>default value</em>. If the optional code block is given and the
695 * key is not found, pass in the key and return the result of
698 * h = { "a" => 100, "b" => 200 }
699 * h.delete("a") #=> 100
700 * h.delete("z") #=> nil
701 * h.delete("z") { |el| "#{el} not found" } #=> "z not found"
706 rb_hash_delete(VALUE hash
, VALUE key
)
710 rb_hash_modify(hash
);
711 val
= rb_hash_delete_key(hash
, key
);
712 if (val
!= Qundef
) return val
;
713 if (rb_block_given_p()) {
714 return rb_yield(key
);
725 shift_i(VALUE key
, VALUE value
, struct shift_var
*var
)
727 if (key
== Qundef
) return ST_CONTINUE
;
728 if (var
->key
!= Qundef
) return ST_STOP
;
735 shift_i_safe(VALUE key
, VALUE value
, struct shift_var
*var
)
737 if (key
== Qundef
) return ST_CONTINUE
;
745 * hsh.shift -> anArray or obj
747 * Removes a key-value pair from <i>hsh</i> and returns it as the
748 * two-item array <code>[</code> <i>key, value</i> <code>]</code>, or
749 * the hash's default value if the hash is empty.
751 * h = { 1 => "a", 2 => "b", 3 => "c" }
752 * h.shift #=> [1, "a"]
753 * h #=> {2=>"b", 3=>"c"}
757 rb_hash_shift(VALUE hash
)
759 struct shift_var var
;
761 rb_hash_modify(hash
);
763 rb_hash_foreach(hash
, RHASH(hash
)->iter_lev
> 0 ? shift_i_safe
: shift_i
,
766 if (var
.key
!= Qundef
) {
767 if (RHASH(hash
)->iter_lev
> 0) {
768 rb_hash_delete_key(hash
, var
.key
);
770 return rb_assoc_new(var
.key
, var
.val
);
772 else if (FL_TEST(hash
, HASH_PROC_DEFAULT
)) {
773 return rb_funcall(RHASH(hash
)->ifnone
, id_yield
, 2, hash
, Qnil
);
776 return RHASH(hash
)->ifnone
;
781 delete_if_i(VALUE key
, VALUE value
, VALUE hash
)
783 if (key
== Qundef
) return ST_CONTINUE
;
784 if (RTEST(rb_yield_values(2, key
, value
))) {
785 rb_hash_delete_key(hash
, key
);
792 * hsh.delete_if {| key, value | block } -> hsh
794 * Deletes every key-value pair from <i>hsh</i> for which <i>block</i>
795 * evaluates to <code>true</code>.
797 * h = { "a" => 100, "b" => 200, "c" => 300 }
798 * h.delete_if {|key, value| key >= "b" } #=> {"a"=>100}
803 rb_hash_delete_if(VALUE hash
)
805 RETURN_ENUMERATOR(hash
, 0, 0);
806 rb_hash_modify(hash
);
807 rb_hash_foreach(hash
, delete_if_i
, hash
);
813 * hsh.reject! {| key, value | block } -> hsh or nil
815 * Equivalent to <code>Hash#delete_if</code>, but returns
816 * <code>nil</code> if no changes were made.
820 rb_hash_reject_bang(VALUE hash
)
824 RETURN_ENUMERATOR(hash
, 0, 0);
825 if (!RHASH(hash
)->ntbl
)
827 n
= RHASH(hash
)->ntbl
->num_entries
;
828 rb_hash_delete_if(hash
);
829 if (n
== RHASH(hash
)->ntbl
->num_entries
) return Qnil
;
835 * hsh.reject {| key, value | block } -> a_hash
837 * Same as <code>Hash#delete_if</code>, but works on (and returns) a
838 * copy of the <i>hsh</i>. Equivalent to
839 * <code><i>hsh</i>.dup.delete_if</code>.
844 rb_hash_reject(VALUE hash
)
846 return rb_hash_delete_if(rb_obj_dup(hash
));
851 * hsh.values_at(key, ...) => array
853 * Return an array containing the values associated with the given keys.
854 * Also see <code>Hash.select</code>.
856 * h = { "cat" => "feline", "dog" => "canine", "cow" => "bovine" }
857 * h.values_at("cow", "cat") #=> ["bovine", "feline"]
861 rb_hash_values_at(int argc
, VALUE
*argv
, VALUE hash
)
863 VALUE result
= rb_ary_new2(argc
);
866 for (i
=0; i
<argc
; i
++) {
867 rb_ary_push(result
, rb_hash_aref(hash
, argv
[i
]));
873 select_i(VALUE key
, VALUE value
, VALUE result
)
875 if (key
== Qundef
) return ST_CONTINUE
;
876 if (RTEST(rb_yield_values(2, key
, value
)))
877 rb_hash_aset(result
, key
, value
);
883 * hsh.select {|key, value| block} => a_hash
885 * Returns a new hash consisting of entries which the block returns true.
887 * h = { "a" => 100, "b" => 200, "c" => 300 }
888 * h.select {|k,v| k > "a"} #=> {"b" => 200, "c" => 300}
889 * h.select {|k,v| v < 200} #=> {"a" => 100}
893 rb_hash_select(VALUE hash
)
897 RETURN_ENUMERATOR(hash
, 0, 0);
898 result
= rb_hash_new();
899 rb_hash_foreach(hash
, select_i
, result
);
904 clear_i(VALUE key
, VALUE value
, VALUE dummy
)
913 * Removes all key-value pairs from <i>hsh</i>.
915 * h = { "a" => 100, "b" => 200 } #=> {"a"=>100, "b"=>200}
921 rb_hash_clear(VALUE hash
)
923 rb_hash_modify_check(hash
);
924 if (!RHASH(hash
)->ntbl
)
926 if (RHASH(hash
)->ntbl
->num_entries
> 0) {
927 if (RHASH(hash
)->iter_lev
> 0)
928 rb_hash_foreach(hash
, clear_i
, 0);
930 st_clear(RHASH(hash
)->ntbl
);
938 * hsh[key] = value => value
939 * hsh.store(key, value) => value
941 * Element Assignment---Associates the value given by
942 * <i>value</i> with the key given by <i>key</i>.
943 * <i>key</i> should not have its value changed while it is in
944 * use as a key (a <code>String</code> passed as a key will be
945 * duplicated and frozen).
947 * h = { "a" => 100, "b" => 200 }
950 * h #=> {"a"=>9, "b"=>200, "c"=>4}
955 rb_hash_aset(VALUE hash
, VALUE key
, VALUE val
)
957 rb_hash_modify(hash
);
958 if (RHASH(hash
)->ntbl
->type
== &identhash
||
959 TYPE(key
) != T_STRING
|| st_lookup(RHASH(hash
)->ntbl
, key
, 0)) {
960 st_insert(RHASH(hash
)->ntbl
, key
, val
);
963 st_add_direct(RHASH(hash
)->ntbl
, rb_str_new4(key
), val
);
969 replace_i(VALUE key
, VALUE val
, VALUE hash
)
972 rb_hash_aset(hash
, key
, val
);
980 * hsh.replace(other_hash) -> hsh
982 * Replaces the contents of <i>hsh</i> with the contents of
985 * h = { "a" => 100, "b" => 200 }
986 * h.replace({ "c" => 300, "d" => 400 }) #=> {"c"=>300, "d"=>400}
991 rb_hash_replace(VALUE hash
, VALUE hash2
)
993 hash2
= to_hash(hash2
);
994 if (hash
== hash2
) return hash
;
996 rb_hash_foreach(hash2
, replace_i
, hash
);
997 RHASH(hash
)->ifnone
= RHASH(hash2
)->ifnone
;
998 if (FL_TEST(hash2
, HASH_PROC_DEFAULT
)) {
999 FL_SET(hash
, HASH_PROC_DEFAULT
);
1002 FL_UNSET(hash
, HASH_PROC_DEFAULT
);
1010 * hsh.length => fixnum
1011 * hsh.size => fixnum
1013 * Returns the number of key-value pairs in the hash.
1015 * h = { "d" => 100, "a" => 200, "v" => 300, "e" => 400 }
1017 * h.delete("a") #=> 200
1022 rb_hash_size(VALUE hash
)
1024 if (!RHASH(hash
)->ntbl
)
1026 return INT2FIX(RHASH(hash
)->ntbl
->num_entries
);
1032 * hsh.empty? => true or false
1034 * Returns <code>true</code> if <i>hsh</i> contains no key-value pairs.
1036 * {}.empty? #=> true
1041 rb_hash_empty_p(VALUE hash
)
1043 return RHASH_EMPTY_P(hash
) ? Qtrue
: Qfalse
;
1047 each_value_i(VALUE key
, VALUE value
)
1049 if (key
== Qundef
) return ST_CONTINUE
;
1056 * hsh.each_value {| value | block } -> hsh
1058 * Calls <i>block</i> once for each key in <i>hsh</i>, passing the
1059 * value as a parameter.
1061 * h = { "a" => 100, "b" => 200 }
1062 * h.each_value {|value| puts value }
1064 * <em>produces:</em>
1071 rb_hash_each_value(VALUE hash
)
1073 RETURN_ENUMERATOR(hash
, 0, 0);
1074 rb_hash_foreach(hash
, each_value_i
, 0);
1079 each_key_i(VALUE key
, VALUE value
)
1081 if (key
== Qundef
) return ST_CONTINUE
;
1088 * hsh.each_key {| key | block } -> hsh
1090 * Calls <i>block</i> once for each key in <i>hsh</i>, passing the key
1093 * h = { "a" => 100, "b" => 200 }
1094 * h.each_key {|key| puts key }
1096 * <em>produces:</em>
1102 rb_hash_each_key(VALUE hash
)
1104 RETURN_ENUMERATOR(hash
, 0, 0);
1105 rb_hash_foreach(hash
, each_key_i
, 0);
1110 each_pair_i(VALUE key
, VALUE value
)
1112 if (key
== Qundef
) return ST_CONTINUE
;
1113 rb_yield(rb_assoc_new(key
, value
));
1119 * hsh.each {| key, value | block } -> hsh
1120 * hsh.each_pair {| key, value | block } -> hsh
1122 * Calls <i>block</i> once for each key in <i>hsh</i>, passing the key-value
1123 * pair as parameters.
1125 * h = { "a" => 100, "b" => 200 }
1126 * h.each {|key, value| puts "#{key} is #{value}" }
1128 * <em>produces:</em>
1136 rb_hash_each_pair(VALUE hash
)
1138 RETURN_ENUMERATOR(hash
, 0, 0);
1139 rb_hash_foreach(hash
, each_pair_i
, 0);
1144 to_a_i(VALUE key
, VALUE value
, VALUE ary
)
1146 if (key
== Qundef
) return ST_CONTINUE
;
1147 rb_ary_push(ary
, rb_assoc_new(key
, value
));
1155 * Converts <i>hsh</i> to a nested array of <code>[</code> <i>key,
1156 * value</i> <code>]</code> arrays.
1158 * h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300 }
1159 * h.to_a #=> [["c", 300], ["a", 100], ["d", 400]]
1163 rb_hash_to_a(VALUE hash
)
1168 rb_hash_foreach(hash
, to_a_i
, ary
);
1169 if (OBJ_TAINTED(hash
)) OBJ_TAINT(ary
);
1175 inspect_i(VALUE key
, VALUE value
, VALUE str
)
1179 if (key
== Qundef
) return ST_CONTINUE
;
1180 if (RSTRING_LEN(str
) > 1) {
1181 rb_str_cat2(str
, ", ");
1183 str2
= rb_inspect(key
);
1184 rb_str_buf_append(str
, str2
);
1185 OBJ_INFECT(str
, str2
);
1186 rb_str_buf_cat2(str
, "=>");
1187 str2
= rb_inspect(value
);
1188 rb_str_buf_append(str
, str2
);
1189 OBJ_INFECT(str
, str2
);
1195 inspect_hash(VALUE hash
, VALUE dummy
, int recur
)
1199 if (recur
) return rb_usascii_str_new2("{...}");
1200 str
= rb_str_buf_new2("{");
1201 rb_hash_foreach(hash
, inspect_i
, str
);
1202 rb_str_buf_cat2(str
, "}");
1203 OBJ_INFECT(str
, hash
);
1210 * hsh.to_s => string
1211 * hsh.inspect => string
1213 * Return the contents of this hash as a string.
1215 * h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300 }
1216 * h.to_s #=> "{\"c\"=>300, \"a\"=>100, \"d\"=>400}"
1220 rb_hash_inspect(VALUE hash
)
1222 if (RHASH_EMPTY_P(hash
))
1223 return rb_usascii_str_new2("{}");
1224 return rb_exec_recursive(inspect_hash
, hash
, 0);
1229 * hsh.to_hash => hsh
1231 * Returns <i>self</i>.
1235 rb_hash_to_hash(VALUE hash
)
1241 keys_i(VALUE key
, VALUE value
, VALUE ary
)
1243 if (key
== Qundef
) return ST_CONTINUE
;
1244 rb_ary_push(ary
, key
);
1252 * Returns a new array populated with the keys from this hash. See also
1253 * <code>Hash#values</code>.
1255 * h = { "a" => 100, "b" => 200, "c" => 300, "d" => 400 }
1256 * h.keys #=> ["a", "b", "c", "d"]
1261 rb_hash_keys(VALUE hash
)
1266 rb_hash_foreach(hash
, keys_i
, ary
);
1272 values_i(VALUE key
, VALUE value
, VALUE ary
)
1274 if (key
== Qundef
) return ST_CONTINUE
;
1275 rb_ary_push(ary
, value
);
1281 * hsh.values => array
1283 * Returns a new array populated with the values from <i>hsh</i>. See
1284 * also <code>Hash#keys</code>.
1286 * h = { "a" => 100, "b" => 200, "c" => 300 }
1287 * h.values #=> [100, 200, 300]
1292 rb_hash_values(VALUE hash
)
1297 rb_hash_foreach(hash
, values_i
, ary
);
1304 * hsh.has_key?(key) => true or false
1305 * hsh.include?(key) => true or false
1306 * hsh.key?(key) => true or false
1307 * hsh.member?(key) => true or false
1309 * Returns <code>true</code> if the given key is present in <i>hsh</i>.
1311 * h = { "a" => 100, "b" => 200 }
1312 * h.has_key?("a") #=> true
1313 * h.has_key?("z") #=> false
1318 rb_hash_has_key(VALUE hash
, VALUE key
)
1320 if (!RHASH(hash
)->ntbl
)
1322 if (st_lookup(RHASH(hash
)->ntbl
, key
, 0)) {
1329 rb_hash_search_value(VALUE key
, VALUE value
, VALUE
*data
)
1331 if (key
== Qundef
) return ST_CONTINUE
;
1332 if (rb_equal(value
, data
[1])) {
1341 * hsh.has_value?(value) => true or false
1342 * hsh.value?(value) => true or false
1344 * Returns <code>true</code> if the given value is present for some key
1347 * h = { "a" => 100, "b" => 200 }
1348 * h.has_value?(100) #=> true
1349 * h.has_value?(999) #=> false
1353 rb_hash_has_value(VALUE hash
, VALUE val
)
1359 rb_hash_foreach(hash
, rb_hash_search_value
, (st_data_t
)data
);
1370 eql_i(VALUE key
, VALUE val1
, struct equal_data
*data
)
1374 if (key
== Qundef
) return ST_CONTINUE
;
1375 if (!st_lookup(data
->tbl
, key
, &val2
)) {
1376 data
->result
= Qfalse
;
1379 if (!(data
->eql
? rb_eql(val1
, val2
) : rb_equal(val1
, val2
))) {
1380 data
->result
= Qfalse
;
1387 recursive_eql(VALUE hash
, VALUE dt
, int recur
)
1389 struct equal_data
*data
;
1391 if (recur
) return Qfalse
;
1392 data
= (struct equal_data
*)dt
;
1393 data
->result
= Qtrue
;
1394 rb_hash_foreach(hash
, eql_i
, (st_data_t
)data
);
1396 return data
->result
;
1400 hash_equal(VALUE hash1
, VALUE hash2
, int eql
)
1402 struct equal_data data
;
1404 if (hash1
== hash2
) return Qtrue
;
1405 if (TYPE(hash2
) != T_HASH
) {
1406 if (!rb_respond_to(hash2
, rb_intern("to_hash"))) {
1410 return rb_eql(hash2
, hash1
);
1412 return rb_equal(hash2
, hash1
);
1414 if (RHASH_SIZE(hash1
) != RHASH_SIZE(hash2
))
1416 if (!RHASH(hash1
)->ntbl
|| !RHASH(hash2
)->ntbl
)
1418 if (RHASH(hash1
)->ntbl
->type
!= RHASH(hash2
)->ntbl
->type
)
1421 if (!(rb_equal(RHASH(hash1
)->ifnone
, RHASH(hash2
)->ifnone
) &&
1422 FL_TEST(hash1
, HASH_PROC_DEFAULT
) == FL_TEST(hash2
, HASH_PROC_DEFAULT
)))
1426 data
.tbl
= RHASH(hash2
)->ntbl
;
1428 return rb_exec_recursive(recursive_eql
, hash1
, (VALUE
)&data
);
1433 * hsh == other_hash => true or false
1435 * Equality---Two hashes are equal if they each contain the same number
1436 * of keys and if each key-value pair is equal to (according to
1437 * <code>Object#==</code>) the corresponding elements in the other
1440 * h1 = { "a" => 1, "c" => 2 }
1441 * h2 = { 7 => 35, "c" => 2, "a" => 1 }
1442 * h3 = { "a" => 1, "c" => 2, 7 => 35 }
1443 * h4 = { "a" => 1, "d" => 2, "f" => 35 }
1444 * h1 == h2 #=> false
1446 * h3 == h4 #=> false
1451 rb_hash_equal(VALUE hash1
, VALUE hash2
)
1453 return hash_equal(hash1
, hash2
, Qfalse
);
1458 * hash.eql?(other) -> true or false
1460 * Returns <code>true</code> if <i>hash</i> and <i>other</i> are
1461 * both hashes with the same content.
1465 rb_hash_eql(VALUE hash1
, VALUE hash2
)
1467 return hash_equal(hash1
, hash2
, Qtrue
);
1471 hash_i(VALUE key
, VALUE val
, int *hval
)
1473 if (key
== Qundef
) return ST_CONTINUE
;
1474 *hval
^= rb_hash(key
);
1475 *hval
^= rb_hash(val
);
1480 recursive_hash(VALUE hash
, VALUE dummy
, int recur
)
1487 if (!RHASH(hash
)->ntbl
)
1489 hval
= RHASH(hash
)->ntbl
->num_entries
;
1490 rb_hash_foreach(hash
, hash_i
, (st_data_t
)&hval
);
1491 return INT2FIX(hval
);
1496 * array.hash -> fixnum
1498 * Compute a hash-code for this array. Two arrays with the same content
1499 * will have the same hash code (and will compare using <code>eql?</code>).
1503 rb_hash_hash(VALUE hash
)
1505 return rb_exec_recursive(recursive_hash
, hash
, 0);
1509 rb_hash_invert_i(VALUE key
, VALUE value
, VALUE hash
)
1511 if (key
== Qundef
) return ST_CONTINUE
;
1512 rb_hash_aset(hash
, value
, key
);
1518 * hsh.invert -> aHash
1520 * Returns a new hash created by using <i>hsh</i>'s values as keys, and
1521 * the keys as values.
1523 * h = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 }
1524 * h.invert #=> {0=>"a", 100=>"m", 200=>"d", 300=>"y"}
1529 rb_hash_invert(VALUE hash
)
1531 VALUE h
= rb_hash_new();
1533 rb_hash_foreach(hash
, rb_hash_invert_i
, h
);
1538 rb_hash_update_i(VALUE key
, VALUE value
, VALUE hash
)
1540 if (key
== Qundef
) return ST_CONTINUE
;
1541 rb_hash_aset(hash
, key
, value
);
1546 rb_hash_update_block_i(VALUE key
, VALUE value
, VALUE hash
)
1548 if (key
== Qundef
) return ST_CONTINUE
;
1549 if (rb_hash_has_key(hash
, key
)) {
1550 value
= rb_yield_values(3, key
, rb_hash_aref(hash
, key
), value
);
1552 rb_hash_aset(hash
, key
, value
);
1558 * hsh.merge!(other_hash) => hsh
1559 * hsh.update(other_hash) => hsh
1560 * hsh.merge!(other_hash){|key, oldval, newval| block} => hsh
1561 * hsh.update(other_hash){|key, oldval, newval| block} => hsh
1563 * Adds the contents of <i>other_hash</i> to <i>hsh</i>. If no
1564 * block is specified entries with duplicate keys are overwritten
1565 * with the values from <i>other_hash</i>, otherwise the value
1566 * of each duplicate key is determined by calling the block with
1567 * the key, its value in <i>hsh</i> and its value in <i>other_hash</i>.
1569 * h1 = { "a" => 100, "b" => 200 }
1570 * h2 = { "b" => 254, "c" => 300 }
1571 * h1.merge!(h2) #=> {"a"=>100, "b"=>254, "c"=>300}
1573 * h1 = { "a" => 100, "b" => 200 }
1574 * h2 = { "b" => 254, "c" => 300 }
1575 * h1.merge!(h2) { |key, v1, v2| v1 }
1576 * #=> {"a"=>100, "b"=>200, "c"=>300}
1580 rb_hash_update(VALUE hash1
, VALUE hash2
)
1582 hash2
= to_hash(hash2
);
1583 if (rb_block_given_p()) {
1584 rb_hash_foreach(hash2
, rb_hash_update_block_i
, hash1
);
1587 rb_hash_foreach(hash2
, rb_hash_update_i
, hash1
);
1594 * hsh.merge(other_hash) -> a_hash
1595 * hsh.merge(other_hash){|key, oldval, newval| block} -> a_hash
1597 * Returns a new hash containing the contents of <i>other_hash</i> and
1598 * the contents of <i>hsh</i>, overwriting entries in <i>hsh</i> with
1599 * duplicate keys with those from <i>other_hash</i>.
1601 * h1 = { "a" => 100, "b" => 200 }
1602 * h2 = { "b" => 254, "c" => 300 }
1603 * h1.merge(h2) #=> {"a"=>100, "b"=>254, "c"=>300}
1604 * h1 #=> {"a"=>100, "b"=>200}
1609 rb_hash_merge(VALUE hash1
, VALUE hash2
)
1611 return rb_hash_update(rb_obj_dup(hash1
), hash2
);
1615 assoc_i(VALUE key
, VALUE val
, VALUE
*args
)
1617 if (key
== Qundef
) return ST_CONTINUE
;
1618 if (RTEST(rb_equal(args
[0], key
))) {
1619 args
[1] = rb_assoc_new(key
, val
);
1627 * hash.assoc(obj) -> an_array or nil
1629 * Searches through the hash comparing _obj_ with the key using <code>==</code>.
1630 * Returns the key-value pair (two elements array) or +nil+
1631 * if no match is found. See <code>Array#assoc</code>.
1633 * h = {"colors" => ["red", "blue", "green"],
1634 * "letters" => ["a", "b", "c" ]}
1635 * h.assoc("letters") #=> ["letters", ["a", "b", "c"]]
1636 * h.assoc("foo") #=> nil
1640 rb_hash_assoc(VALUE hash
, VALUE obj
)
1646 rb_hash_foreach(hash
, assoc_i
, (st_data_t
)args
);
1651 rassoc_i(VALUE key
, VALUE val
, VALUE
*args
)
1653 if (key
== Qundef
) return ST_CONTINUE
;
1654 if (RTEST(rb_equal(args
[0], val
))) {
1655 args
[1] = rb_assoc_new(key
, val
);
1663 * hash.rassoc(key) -> an_array or nil
1665 * Searches through the hash comparing _obj_ with the value using <code>==</code>.
1666 * Returns the first key-value pair (two elements array) that matches. See
1667 * also <code>Array#rassoc</code>.
1669 * a = {1=> "one", 2 => "two", 3 => "three", "ii" => "two"}
1670 * a.rassoc("two") #=> [2, "two"]
1671 * a.rassoc("four") #=> nil
1675 rb_hash_rassoc(VALUE hash
, VALUE obj
)
1681 rb_hash_foreach(hash
, rassoc_i
, (st_data_t
)args
);
1687 * hash.flatten -> an_array
1688 * hash.flatten(level) -> an_array
1690 * Returns a new array that is a one-dimensional flattening of this
1691 * hash. That is, for every key or value that is an array, extract
1692 * its elements into the new array. Unlike Array#flatten, this
1693 * method does not flatten recursively by default. If the optional
1694 * <i>level</i> argument determines the level of recursion to flatten.
1696 * a = {1=> "one", 2 => [2,"two"], 3 => "three"}
1697 * a.flatten # => [1, "one", 2, [2, "two"], 3, "three"]
1698 * a.flatten(2) # => [1, "one", 2, 2, "two", 3, "three"]
1702 rb_hash_flatten(int argc
, VALUE
*argv
, VALUE hash
)
1706 ary
= rb_hash_to_a(hash
);
1712 rb_funcall2(ary
, rb_intern("flatten!"), argc
, argv
);
1718 * hsh.compare_by_identity => hsh
1720 * Makes <i>hsh</i> to compare its keys by their identity, i.e. it
1721 * will consider exact same objects as same keys.
1723 * h1 = { "a" => 100, "b" => 200, :c => "c" }
1725 * h1.compare_by_identity
1726 * h1.compare_by_identity? #=> true
1727 * h1["a"] #=> nil # different objects.
1728 * h1[:c] #=> "c" # same symbols are all same.
1733 rb_hash_compare_by_id(VALUE hash
)
1735 rb_hash_modify(hash
);
1736 RHASH(hash
)->ntbl
->type
= &identhash
;
1737 rb_hash_rehash(hash
);
1743 * hsh.compare_by_identity? => true or false
1745 * Returns <code>true</code> if <i>hsh</i> will compare its keys by
1746 * their identity. Also see <code>Hash#compare_by_identity</code>.
1751 rb_hash_compare_by_id_p(VALUE hash
)
1753 if (!RHASH(hash
)->ntbl
)
1755 if (RHASH(hash
)->ntbl
->type
== &identhash
) {
1761 static int path_tainted
= -1;
1763 static char **origenviron
;
1765 #define GET_ENVIRON(e) (e = rb_w32_get_environ())
1766 #define FREE_ENVIRON(e) rb_w32_free_environ(e)
1767 static char **my_environ
;
1769 #define environ my_environ
1770 #elif defined(__APPLE__)
1772 #define environ (*_NSGetEnviron())
1773 #define GET_ENVIRON(e) (e)
1774 #define FREE_ENVIRON(e)
1776 extern char **environ
;
1777 #define GET_ENVIRON(e) (e)
1778 #define FREE_ENVIRON(e)
1782 env_str_new(const char *ptr
, long len
)
1784 VALUE str
= rb_tainted_str_new(ptr
, len
);
1791 env_str_new2(const char *ptr
)
1793 if (!ptr
) return Qnil
;
1794 return env_str_new(ptr
, strlen(ptr
));
1798 env_delete(VALUE obj
, VALUE name
)
1803 SafeStringValue(name
);
1804 nam
= RSTRING_PTR(name
);
1805 if (strlen(nam
) != RSTRING_LEN(name
)) {
1806 rb_raise(rb_eArgError
, "bad environment variable name");
1810 VALUE value
= env_str_new2(val
);
1812 ruby_setenv(nam
, 0);
1813 #ifdef ENV_IGNORECASE
1814 if (STRCASECMP(nam
, PATH_ENV
) == 0)
1816 if (strcmp(nam
, PATH_ENV
) == 0)
1827 env_delete_m(VALUE obj
, VALUE name
)
1831 val
= env_delete(obj
, name
);
1832 if (NIL_P(val
) && rb_block_given_p()) rb_yield(name
);
1837 rb_f_getenv(VALUE obj
, VALUE name
)
1842 SafeStringValue(name
);
1843 nam
= RSTRING_PTR(name
);
1844 if (strlen(nam
) != RSTRING_LEN(name
)) {
1845 rb_raise(rb_eArgError
, "bad environment variable name");
1849 #ifdef ENV_IGNORECASE
1850 if (STRCASECMP(nam
, PATH_ENV
) == 0 && !rb_env_path_tainted())
1852 if (strcmp(nam
, PATH_ENV
) == 0 && !rb_env_path_tainted())
1855 VALUE str
= rb_str_new2(env
);
1860 return env_str_new2(env
);
1866 env_fetch(int argc
, VALUE
*argv
)
1873 rb_scan_args(argc
, argv
, "11", &key
, &if_none
);
1874 block_given
= rb_block_given_p();
1875 if (block_given
&& argc
== 2) {
1876 rb_warn("block supersedes default value argument");
1878 SafeStringValue(key
);
1879 nam
= RSTRING_PTR(key
);
1880 if (strlen(nam
) != RSTRING_LEN(key
)) {
1881 rb_raise(rb_eArgError
, "bad environment variable name");
1885 if (block_given
) return rb_yield(key
);
1887 rb_raise(rb_eKeyError
, "key not found");
1891 #ifdef ENV_IGNORECASE
1892 if (STRCASECMP(nam
, PATH_ENV
) == 0 && !rb_env_path_tainted())
1894 if (strcmp(nam
, PATH_ENV
) == 0 && !rb_env_path_tainted())
1896 return rb_str_new2(env
);
1897 return env_str_new2(env
);
1901 path_tainted_p(char *path
)
1903 path_tainted
= rb_path_check(path
)?0:1;
1907 rb_env_path_tainted(void)
1909 if (path_tainted
< 0) {
1910 path_tainted_p(getenv(PATH_ENV
));
1912 return path_tainted
;
1915 #if !defined(_WIN32) && !(defined(HAVE_SETENV) && defined(HAVE_UNSETENV))
1917 envix(const char *nam
)
1919 register int i
, len
= strlen(nam
);
1922 env
= GET_ENVIRON(environ
);
1923 for (i
= 0; env
[i
]; i
++) {
1925 #ifdef ENV_IGNORECASE
1926 STRNCASECMP(env
[i
],nam
,len
) == 0
1928 memcmp(env
[i
],nam
,len
) == 0
1930 && env
[i
][len
] == '=')
1931 break; /* memcmp must come first to avoid */
1932 } /* potential SEGV's */
1933 FREE_ENVIRON(environ
);
1939 ruby_setenv(const char *name
, const char *value
)
1942 /* The sane way to deal with the environment.
1943 * Has these advantages over putenv() & co.:
1944 * * enables us to store a truly empty value in the
1945 * environment (like in UNIX).
1946 * * we don't have to deal with RTL globals, bugs and leaks.
1948 * Why you may want to enable USE_WIN32_RTL_ENV:
1949 * * environ[] and RTL functions will not reflect changes,
1950 * which might be an issue if extensions want to access
1951 * the env. via RTL. This cuts both ways, since RTL will
1952 * not see changes made by extensions that call the Win32
1953 * functions directly, either.
1956 * REMARK: USE_WIN32_RTL_ENV is already obsoleted since we don't use
1957 * RTL's environ global variable directly yet.
1959 SetEnvironmentVariable(name
,value
);
1960 #elif defined(HAVE_SETENV) && defined(HAVE_UNSETENV)
1964 setenv(name
,value
,1);
1969 int i
=envix(name
); /* where does it go? */
1971 if (environ
== origenviron
) { /* need we copy environment? */
1976 for (max
= i
; environ
[max
]; max
++) ;
1977 tmpenv
= ALLOC_N(char*, max
+2);
1978 for (j
=0; j
<max
; j
++) /* copy environment */
1979 tmpenv
[j
] = strdup(environ
[j
]);
1981 environ
= tmpenv
; /* tell exec where it is now */
1984 char **envp
= origenviron
;
1985 while (*envp
&& *envp
!= environ
[i
]) envp
++;
1989 while (environ
[i
]) {
1990 environ
[i
] = environ
[i
+1];
1996 else { /* does not exist yet */
1998 REALLOC_N(environ
, char*, i
+2); /* just expand it a bit */
1999 environ
[i
+1] = 0; /* make sure it's null terminated */
2001 len
= strlen(name
) + strlen(value
) + 2;
2002 environ
[i
] = ALLOC_N(char, len
);
2004 snprintf(environ
[i
],len
,"%s=%s",name
,value
); /* all that work just for this */
2006 /* MS-DOS requires environment variable names to be in uppercase */
2007 /* [Tom Dinger, 27 August 1990: Well, it doesn't _require_ it, but
2008 * some utilities and applications may break because they only look
2009 * for upper case strings. (Fixed strupr() bug here.)]
2011 strcpy(environ
[i
],name
); strupr(environ
[i
]);
2012 sprintf(environ
[i
] + strlen(name
),"=%s", value
);
2019 ruby_unsetenv(const char *name
)
2021 ruby_setenv(name
, 0);
2025 env_aset(VALUE obj
, VALUE nm
, VALUE val
)
2029 if (rb_safe_level() >= 4) {
2030 rb_raise(rb_eSecurityError
, "can't change environment variable");
2034 rb_raise(rb_eTypeError
, "cannot assign nil; use Hash#delete instead");
2038 name
= RSTRING_PTR(nm
);
2039 value
= RSTRING_PTR(val
);
2040 if (strlen(name
) != RSTRING_LEN(nm
))
2041 rb_raise(rb_eArgError
, "bad environment variable name");
2042 if (strlen(value
) != RSTRING_LEN(val
))
2043 rb_raise(rb_eArgError
, "bad environment variable value");
2045 ruby_setenv(name
, value
);
2046 #ifdef ENV_IGNORECASE
2047 if (STRCASECMP(name
, PATH_ENV
) == 0) {
2049 if (strcmp(name
, PATH_ENV
) == 0) {
2051 if (OBJ_TAINTED(val
)) {
2052 /* already tainted, no check */
2057 path_tainted_p(value
);
2071 env
= GET_ENVIRON(environ
);
2073 char *s
= strchr(*env
, '=');
2075 rb_ary_push(ary
, env_str_new(*env
, s
-*env
));
2079 FREE_ENVIRON(environ
);
2084 env_each_key(VALUE ehash
)
2089 RETURN_ENUMERATOR(ehash
, 0, 0);
2090 keys
= env_keys(); /* rb_secure(4); */
2091 for (i
=0; i
<RARRAY_LEN(keys
); i
++) {
2092 rb_yield(RARRAY_PTR(keys
)[i
]);
2105 env
= GET_ENVIRON(environ
);
2107 char *s
= strchr(*env
, '=');
2109 rb_ary_push(ary
, env_str_new2(s
+1));
2113 FREE_ENVIRON(environ
);
2118 env_each_value(VALUE ehash
)
2123 RETURN_ENUMERATOR(ehash
, 0, 0);
2124 values
= env_values(); /* rb_secure(4); */
2125 for (i
=0; i
<RARRAY_LEN(values
); i
++) {
2126 rb_yield(RARRAY_PTR(values
)[i
]);
2132 env_each_pair(VALUE ehash
)
2138 RETURN_ENUMERATOR(ehash
, 0, 0);
2142 env
= GET_ENVIRON(environ
);
2144 char *s
= strchr(*env
, '=');
2146 rb_ary_push(ary
, env_str_new(*env
, s
-*env
));
2147 rb_ary_push(ary
, env_str_new2(s
+1));
2151 FREE_ENVIRON(environ
);
2153 for (i
=0; i
<RARRAY_LEN(ary
); i
+=2) {
2154 rb_yield(rb_assoc_new(RARRAY_PTR(ary
)[i
], RARRAY_PTR(ary
)[i
+1]));
2160 env_reject_bang(VALUE ehash
)
2162 volatile VALUE keys
;
2166 RETURN_ENUMERATOR(ehash
, 0, 0);
2167 keys
= env_keys(); /* rb_secure(4); */
2168 for (i
=0; i
<RARRAY_LEN(keys
); i
++) {
2169 VALUE val
= rb_f_getenv(Qnil
, RARRAY_PTR(keys
)[i
]);
2171 if (RTEST(rb_yield_values(2, RARRAY_PTR(keys
)[i
], val
))) {
2172 FL_UNSET(RARRAY_PTR(keys
)[i
], FL_TAINT
);
2173 env_delete(Qnil
, RARRAY_PTR(keys
)[i
]);
2178 if (del
== 0) return Qnil
;
2183 env_delete_if(VALUE ehash
)
2185 RETURN_ENUMERATOR(ehash
, 0, 0);
2186 env_reject_bang(ehash
);
2191 env_values_at(int argc
, VALUE
*argv
)
2197 result
= rb_ary_new();
2198 for (i
=0; i
<argc
; i
++) {
2199 rb_ary_push(result
, rb_f_getenv(Qnil
, argv
[i
]));
2205 env_select(VALUE ehash
)
2210 RETURN_ENUMERATOR(ehash
, 0, 0);
2212 result
= rb_hash_new();
2213 env
= GET_ENVIRON(environ
);
2215 char *s
= strchr(*env
, '=');
2217 VALUE k
= env_str_new(*env
, s
-*env
);
2218 VALUE v
= env_str_new2(s
+1);
2219 if (RTEST(rb_yield_values(2, k
, v
))) {
2220 rb_hash_aset(result
, k
, v
);
2225 FREE_ENVIRON(environ
);
2233 volatile VALUE keys
;
2236 keys
= env_keys(); /* rb_secure(4); */
2237 for (i
=0; i
<RARRAY_LEN(keys
); i
++) {
2238 VALUE val
= rb_f_getenv(Qnil
, RARRAY_PTR(keys
)[i
]);
2240 env_delete(Qnil
, RARRAY_PTR(keys
)[i
]);
2249 return rb_usascii_str_new2("ENV");
2259 str
= rb_str_buf_new2("{");
2260 env
= GET_ENVIRON(environ
);
2262 char *s
= strchr(*env
, '=');
2264 if (env
!= environ
) {
2265 rb_str_buf_cat2(str
, ", ");
2268 rb_str_buf_cat2(str
, "\"");
2269 rb_str_buf_cat(str
, *env
, s
-*env
);
2270 rb_str_buf_cat2(str
, "\"=>");
2271 i
= rb_inspect(rb_str_new2(s
+1));
2272 rb_str_buf_append(str
, i
);
2276 FREE_ENVIRON(environ
);
2277 rb_str_buf_cat2(str
, "}");
2291 env
= GET_ENVIRON(environ
);
2293 char *s
= strchr(*env
, '=');
2295 rb_ary_push(ary
, rb_assoc_new(env_str_new(*env
, s
-*env
),
2296 env_str_new2(s
+1)));
2300 FREE_ENVIRON(environ
);
2317 env
= GET_ENVIRON(environ
);
2318 for(i
=0; env
[i
]; i
++)
2320 FREE_ENVIRON(environ
);
2330 env
= GET_ENVIRON(environ
);
2332 FREE_ENVIRON(environ
);
2335 FREE_ENVIRON(environ
);
2340 env_has_key(VALUE env
, VALUE key
)
2345 s
= StringValuePtr(key
);
2346 if (strlen(s
) != RSTRING_LEN(key
))
2347 rb_raise(rb_eArgError
, "bad environment variable name");
2348 if (getenv(s
)) return Qtrue
;
2353 env_assoc(VALUE env
, VALUE key
)
2358 s
= StringValuePtr(key
);
2359 if (strlen(s
) != RSTRING_LEN(key
))
2360 rb_raise(rb_eArgError
, "bad environment variable name");
2362 if (e
) return rb_assoc_new(key
, rb_tainted_str_new2(e
));
2367 env_has_value(VALUE dmy
, VALUE obj
)
2372 obj
= rb_check_string_type(obj
);
2373 if (NIL_P(obj
)) return Qnil
;
2374 env
= GET_ENVIRON(environ
);
2376 char *s
= strchr(*env
, '=');
2378 long len
= strlen(s
);
2379 if (RSTRING_LEN(obj
) == len
&& strncmp(s
, RSTRING_PTR(obj
), len
) == 0) {
2380 FREE_ENVIRON(environ
);
2386 FREE_ENVIRON(environ
);
2391 env_rassoc(VALUE dmy
, VALUE obj
)
2396 obj
= rb_check_string_type(obj
);
2397 if (NIL_P(obj
)) return Qnil
;
2398 env
= GET_ENVIRON(environ
);
2400 char *s
= strchr(*env
, '=');
2402 long len
= strlen(s
);
2403 if (RSTRING_LEN(obj
) == len
&& strncmp(s
, RSTRING_PTR(obj
), len
) == 0) {
2404 VALUE result
= rb_assoc_new(rb_tainted_str_new(*env
, s
-*env
-1), obj
);
2405 FREE_ENVIRON(environ
);
2411 FREE_ENVIRON(environ
);
2416 env_key(VALUE dmy
, VALUE value
)
2423 env
= GET_ENVIRON(environ
);
2425 char *s
= strchr(*env
, '=');
2427 long len
= strlen(s
);
2428 if (RSTRING_LEN(value
) == len
&& strncmp(s
, RSTRING_PTR(value
), len
) == 0) {
2429 str
= env_str_new(*env
, s
-*env
-1);
2430 FREE_ENVIRON(environ
);
2436 FREE_ENVIRON(environ
);
2441 env_index(VALUE dmy
, VALUE value
)
2443 rb_warn("ENV.index is deprecated; use ENV.key");
2444 return env_key(dmy
, value
);
2454 hash
= rb_hash_new();
2455 env
= GET_ENVIRON(environ
);
2457 char *s
= strchr(*env
, '=');
2459 rb_hash_aset(hash
, env_str_new(*env
, s
-*env
),
2464 FREE_ENVIRON(environ
);
2471 return rb_hash_delete_if(env_to_hash());
2480 env
= GET_ENVIRON(environ
);
2482 char *s
= strchr(*env
, '=');
2484 VALUE key
= env_str_new(*env
, s
-*env
);
2485 VALUE val
= env_str_new2(getenv(RSTRING_PTR(key
)));
2486 env_delete(Qnil
, key
);
2487 return rb_assoc_new(key
, val
);
2490 FREE_ENVIRON(environ
);
2497 return rb_hash_invert(env_to_hash());
2501 env_replace_i(VALUE key
, VALUE val
, VALUE keys
)
2503 if (key
!= Qundef
) {
2504 env_aset(Qnil
, key
, val
);
2505 if (rb_ary_includes(keys
, key
)) {
2506 rb_ary_delete(keys
, key
);
2513 env_replace(VALUE env
, VALUE hash
)
2515 volatile VALUE keys
;
2518 keys
= env_keys(); /* rb_secure(4); */
2519 if (env
== hash
) return env
;
2520 hash
= to_hash(hash
);
2521 rb_hash_foreach(hash
, env_replace_i
, keys
);
2523 for (i
=0; i
<RARRAY_LEN(keys
); i
++) {
2524 env_delete(env
, RARRAY_PTR(keys
)[i
]);
2530 env_update_i(VALUE key
, VALUE val
)
2532 if (key
!= Qundef
) {
2533 if (rb_block_given_p()) {
2534 val
= rb_yield_values(3, key
, rb_f_getenv(Qnil
, key
), val
);
2536 env_aset(Qnil
, key
, val
);
2542 env_update(VALUE env
, VALUE hash
)
2545 if (env
== hash
) return env
;
2546 hash
= to_hash(hash
);
2547 rb_hash_foreach(hash
, env_update_i
, 0);
2552 * A <code>Hash</code> is a collection of key-value pairs. It is
2553 * similar to an <code>Array</code>, except that indexing is done via
2554 * arbitrary keys of any object type, not an integer index. The order
2555 * in which you traverse a hash by either key or value may seem
2556 * arbitrary, and will generally not be in the insertion order.
2558 * Hashes have a <em>default value</em> that is returned when accessing
2559 * keys that do not exist in the hash. By default, that value is
2569 id_hash
= rb_intern("hash");
2570 id_yield
= rb_intern("yield");
2571 id_default
= rb_intern("default");
2573 rb_cHash
= rb_define_class("Hash", rb_cObject
);
2575 rb_include_module(rb_cHash
, rb_mEnumerable
);
2577 rb_define_alloc_func(rb_cHash
, hash_alloc
);
2578 rb_define_singleton_method(rb_cHash
, "[]", rb_hash_s_create
, -1);
2579 rb_define_singleton_method(rb_cHash
, "try_convert", rb_hash_s_try_convert
, 1);
2580 rb_define_method(rb_cHash
,"initialize", rb_hash_initialize
, -1);
2581 rb_define_method(rb_cHash
,"initialize_copy", rb_hash_replace
, 1);
2582 rb_define_method(rb_cHash
,"rehash", rb_hash_rehash
, 0);
2584 rb_define_method(rb_cHash
,"to_hash", rb_hash_to_hash
, 0);
2585 rb_define_method(rb_cHash
,"to_a", rb_hash_to_a
, 0);
2586 rb_define_method(rb_cHash
,"to_s", rb_hash_inspect
, 0);
2587 rb_define_method(rb_cHash
,"inspect", rb_hash_inspect
, 0);
2589 rb_define_method(rb_cHash
,"==", rb_hash_equal
, 1);
2590 rb_define_method(rb_cHash
,"[]", rb_hash_aref
, 1);
2591 rb_define_method(rb_cHash
,"hash", rb_hash_hash
, 0);
2592 rb_define_method(rb_cHash
,"eql?", rb_hash_eql
, 1);
2593 rb_define_method(rb_cHash
,"fetch", rb_hash_fetch
, -1);
2594 rb_define_method(rb_cHash
,"[]=", rb_hash_aset
, 2);
2595 rb_define_method(rb_cHash
,"store", rb_hash_aset
, 2);
2596 rb_define_method(rb_cHash
,"default", rb_hash_default
, -1);
2597 rb_define_method(rb_cHash
,"default=", rb_hash_set_default
, 1);
2598 rb_define_method(rb_cHash
,"default_proc", rb_hash_default_proc
, 0);
2599 rb_define_method(rb_cHash
,"key", rb_hash_key
, 1);
2600 rb_define_method(rb_cHash
,"index", rb_hash_index
, 1);
2601 rb_define_method(rb_cHash
,"size", rb_hash_size
, 0);
2602 rb_define_method(rb_cHash
,"length", rb_hash_size
, 0);
2603 rb_define_method(rb_cHash
,"empty?", rb_hash_empty_p
, 0);
2605 rb_define_method(rb_cHash
,"each_value", rb_hash_each_value
, 0);
2606 rb_define_method(rb_cHash
,"each_key", rb_hash_each_key
, 0);
2607 rb_define_method(rb_cHash
,"each_pair", rb_hash_each_pair
, 0);
2608 rb_define_method(rb_cHash
,"each", rb_hash_each_pair
, 0);
2610 rb_define_method(rb_cHash
,"keys", rb_hash_keys
, 0);
2611 rb_define_method(rb_cHash
,"values", rb_hash_values
, 0);
2612 rb_define_method(rb_cHash
,"values_at", rb_hash_values_at
, -1);
2614 rb_define_method(rb_cHash
,"shift", rb_hash_shift
, 0);
2615 rb_define_method(rb_cHash
,"delete", rb_hash_delete
, 1);
2616 rb_define_method(rb_cHash
,"delete_if", rb_hash_delete_if
, 0);
2617 rb_define_method(rb_cHash
,"select", rb_hash_select
, 0);
2618 rb_define_method(rb_cHash
,"reject", rb_hash_reject
, 0);
2619 rb_define_method(rb_cHash
,"reject!", rb_hash_reject_bang
, 0);
2620 rb_define_method(rb_cHash
,"clear", rb_hash_clear
, 0);
2621 rb_define_method(rb_cHash
,"invert", rb_hash_invert
, 0);
2622 rb_define_method(rb_cHash
,"update", rb_hash_update
, 1);
2623 rb_define_method(rb_cHash
,"replace", rb_hash_replace
, 1);
2624 rb_define_method(rb_cHash
,"merge!", rb_hash_update
, 1);
2625 rb_define_method(rb_cHash
,"merge", rb_hash_merge
, 1);
2626 rb_define_method(rb_cHash
, "assoc", rb_hash_assoc
, 1);
2627 rb_define_method(rb_cHash
, "rassoc", rb_hash_rassoc
, 1);
2628 rb_define_method(rb_cHash
, "flatten", rb_hash_flatten
, -1);
2630 rb_define_method(rb_cHash
,"include?", rb_hash_has_key
, 1);
2631 rb_define_method(rb_cHash
,"member?", rb_hash_has_key
, 1);
2632 rb_define_method(rb_cHash
,"has_key?", rb_hash_has_key
, 1);
2633 rb_define_method(rb_cHash
,"has_value?", rb_hash_has_value
, 1);
2634 rb_define_method(rb_cHash
,"key?", rb_hash_has_key
, 1);
2635 rb_define_method(rb_cHash
,"value?", rb_hash_has_value
, 1);
2637 rb_define_method(rb_cHash
,"compare_by_identity", rb_hash_compare_by_id
, 0);
2638 rb_define_method(rb_cHash
,"compare_by_identity?", rb_hash_compare_by_id_p
, 0);
2640 #ifndef __MACOS__ /* environment variables nothing on MacOS. */
2641 origenviron
= environ
;
2642 envtbl
= rb_obj_alloc(rb_cObject
);
2643 rb_extend_object(envtbl
, rb_mEnumerable
);
2645 rb_define_singleton_method(envtbl
,"[]", rb_f_getenv
, 1);
2646 rb_define_singleton_method(envtbl
,"fetch", env_fetch
, -1);
2647 rb_define_singleton_method(envtbl
,"[]=", env_aset
, 2);
2648 rb_define_singleton_method(envtbl
,"store", env_aset
, 2);
2649 rb_define_singleton_method(envtbl
,"each", env_each_pair
, 0);
2650 rb_define_singleton_method(envtbl
,"each_pair", env_each_pair
, 0);
2651 rb_define_singleton_method(envtbl
,"each_key", env_each_key
, 0);
2652 rb_define_singleton_method(envtbl
,"each_value", env_each_value
, 0);
2653 rb_define_singleton_method(envtbl
,"delete", env_delete_m
, 1);
2654 rb_define_singleton_method(envtbl
,"delete_if", env_delete_if
, 0);
2655 rb_define_singleton_method(envtbl
,"clear", rb_env_clear
, 0);
2656 rb_define_singleton_method(envtbl
,"reject", env_reject
, 0);
2657 rb_define_singleton_method(envtbl
,"reject!", env_reject_bang
, 0);
2658 rb_define_singleton_method(envtbl
,"select", env_select
, 0);
2659 rb_define_singleton_method(envtbl
,"shift", env_shift
, 0);
2660 rb_define_singleton_method(envtbl
,"invert", env_invert
, 0);
2661 rb_define_singleton_method(envtbl
,"replace", env_replace
, 1);
2662 rb_define_singleton_method(envtbl
,"update", env_update
, 1);
2663 rb_define_singleton_method(envtbl
,"inspect", env_inspect
, 0);
2664 rb_define_singleton_method(envtbl
,"rehash", env_none
, 0);
2665 rb_define_singleton_method(envtbl
,"to_a", env_to_a
, 0);
2666 rb_define_singleton_method(envtbl
,"to_s", env_to_s
, 0);
2667 rb_define_singleton_method(envtbl
,"key", env_key
, 1);
2668 rb_define_singleton_method(envtbl
,"index", env_index
, 1);
2669 rb_define_singleton_method(envtbl
,"size", env_size
, 0);
2670 rb_define_singleton_method(envtbl
,"length", env_size
, 0);
2671 rb_define_singleton_method(envtbl
,"empty?", env_empty_p
, 0);
2672 rb_define_singleton_method(envtbl
,"keys", env_keys
, 0);
2673 rb_define_singleton_method(envtbl
,"values", env_values
, 0);
2674 rb_define_singleton_method(envtbl
,"values_at", env_values_at
, -1);
2675 rb_define_singleton_method(envtbl
,"include?", env_has_key
, 1);
2676 rb_define_singleton_method(envtbl
,"member?", env_has_key
, 1);
2677 rb_define_singleton_method(envtbl
,"has_key?", env_has_key
, 1);
2678 rb_define_singleton_method(envtbl
,"has_value?", env_has_value
, 1);
2679 rb_define_singleton_method(envtbl
,"key?", env_has_key
, 1);
2680 rb_define_singleton_method(envtbl
,"value?", env_has_value
, 1);
2681 rb_define_singleton_method(envtbl
,"to_hash", env_to_hash
, 0);
2682 rb_define_singleton_method(envtbl
,"assoc", env_assoc
, 1);
2683 rb_define_singleton_method(envtbl
,"rassoc", env_rassoc
, 1);
2685 rb_define_global_const("ENV", envtbl
);
2686 #else /* __MACOS__ */
2687 envtbl
= rb_hash_s_new(0, NULL
, rb_cHash
);
2688 rb_define_global_const("ENV", envtbl
);
2689 #endif /* ifndef __MACOS__ environment variables nothing on MacOS. */