Ruby 2.0.0p247(2013-06-27revision41674)

- Main Page
- Modules
- Data Structures
- Files

- File List
- Globals

hash.c
Go to the documentation of this file.
1 /**********************************************************************
2
3 hash.c -
4
5 $Author: nagachika $
6 created at: Mon Nov 22 18:51:18 JST 1993
7
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
11
12 **********************************************************************/
13
14 #include "ruby/ruby.h"
15 #include "ruby/st.h"
16 #include "ruby/util.h"
17 #include "ruby/encoding.h"
18 #include "internal.h"
19 #include <errno.h>
20 #include "probes.h"
21
22 #ifdef __APPLE__
23 # ifdef HAVE_CRT_EXTERNS_H
24 # include <crt_externs.h>
25 # else
26 # include "missing/crt_externs.h"
27 # endif
28 #endif
29
30 static VALUE rb_hash_s_try_convert(VALUE, VALUE);
31
32 #define HASH_DELETED FL_USER1
33 #define HASH_PROC_DEFAULT FL_USER2
34
35 VALUE
36 rb_hash_freeze(VALUE hash)
37 {
38 return rb_obj_freeze(hash);
39 }
40
41 VALUE rb_cHash;
42
43 static VALUE envtbl;
44 static ID id_hash, id_yield, id_default;
45
46 static int
47 rb_any_cmp(VALUE a, VALUE b)
48 {
49 if (a == b) return 0;
50 if (FIXNUM_P(a) && FIXNUM_P(b)) {
51 return a != b;
52 }
53 if (RB_TYPE_P(a, T_STRING) && RBASIC(a)->klass == rb_cString &&
54 RB_TYPE_P(b, T_STRING) && RBASIC(b)->klass == rb_cString) {
55 return rb_str_hash_cmp(a, b);
56 }
57 if (a == Qundef || b == Qundef) return -1;
58 if (SYMBOL_P(a) && SYMBOL_P(b)) {
59 return a != b;
60 }
61
62 return !rb_eql(a, b);
63 }
64
65 VALUE
66 rb_hash(VALUE obj)
67 {
68 VALUE hval = rb_funcall(obj, id_hash, 0);
69 retry:
70 switch (TYPE(hval)) {
71 case T_FIXNUM:
72 return hval;
73
74 case T_BIGNUM:
75 return LONG2FIX(((long*)(RBIGNUM_DIGITS(hval)))[0]);
76
77 default:
78 hval = rb_to_int(hval);
79 goto retry;
80 }
81 }
82
83 static st_index_t
84 rb_any_hash(VALUE a)
85 {
86 VALUE hval;
87 st_index_t hnum;
88
89 if (SPECIAL_CONST_P(a)) {
90 if (a == Qundef) return 0;
91 hnum = rb_hash_end(rb_hash_start((st_index_t)a));
92 }
93 else if (BUILTIN_TYPE(a) == T_STRING) {
94 hnum = rb_str_hash(a);
95 }
96 else {
97 hval = rb_hash(a);
98 hnum = FIX2LONG(hval);
99 }
100 hnum <<= 1;
101 return (st_index_t)RSHIFT(hnum, 1);
102 }
103
104 static const struct st_hash_type objhash = {
105 rb_any_cmp,
106 rb_any_hash,
107 };
108
109 extern const struct st_hash_type st_hashtype_num;
110 #define identhash st_hashtype_num
111
112 typedef int st_foreach_func(st_data_t, st_data_t, st_data_t);
113
114 struct foreach_safe_arg {
115 st_table *tbl;
116 st_foreach_func *func;
117 st_data_t arg;
118 };
119
120 static int
121 foreach_safe_i(st_data_t key, st_data_t value, struct foreach_safe_arg *arg)
122 {
123 int status;
124
125 status = (*arg->func)(key, value, arg->arg);
126 if (status == ST_CONTINUE) {
127 return ST_CHECK;
128 }
129 return status;
130 }
131
132 void
133 st_foreach_safe(st_table *table, int (*func)(ANYARGS), st_data_t a)
134 {
135 struct foreach_safe_arg arg;
136
137 arg.tbl = table;
138 arg.func = (st_foreach_func *)func;
139 arg.arg = a;
140 if (st_foreach_check(table, foreach_safe_i, (st_data_t)&arg, 0)) {
141 rb_raise(rb_eRuntimeError, "hash modified during iteration");
142 }
143 }
144
145 typedef int rb_foreach_func(VALUE, VALUE, VALUE);
146
147 struct hash_foreach_arg {
148 VALUE hash;
149 rb_foreach_func *func;
150 VALUE arg;
151 };
152
153 static int
154 hash_foreach_iter(st_data_t key, st_data_t value, st_data_t argp)
155 {
156 struct hash_foreach_arg *arg = (struct hash_foreach_arg *)argp;
157 int status;
158 st_table *tbl;
159
160 tbl = RHASH(arg->hash)->ntbl;
161 status = (*arg->func)((VALUE)key, (VALUE)value, arg->arg);
162 if (RHASH(arg->hash)->ntbl != tbl) {
163 rb_raise(rb_eRuntimeError, "rehash occurred during iteration");
164 }
165 switch (status) {
166 case ST_DELETE:
167 FL_SET(arg->hash, HASH_DELETED);
168 return ST_DELETE;
169 case ST_CONTINUE:
170 break;
171 case ST_STOP:
172 return ST_STOP;
173 }
174 return ST_CHECK;
175 }
176
177 static VALUE
178 hash_foreach_ensure(VALUE hash)
179 {
180 if (--RHASH_ITER_LEV(hash) == 0) {
181 if (FL_TEST(hash, HASH_DELETED)) {
182 st_cleanup_safe(RHASH(hash)->ntbl, (st_data_t)Qundef);
183 FL_UNSET(hash, HASH_DELETED);
184 }
185 }
186 return 0;
187 }
188
189 static VALUE
190 hash_foreach_call(VALUE arg)
191 {
192 VALUE hash = ((struct hash_foreach_arg *)arg)->hash;
193 if (st_foreach_check(RHASH(hash)->ntbl, hash_foreach_iter, (st_data_t)arg, (st_data_t)Qundef)) {
194 rb_raise(rb_eRuntimeError, "hash modified during iteration");
195 }
196 return Qnil;
197 }
198
199 void
200 rb_hash_foreach(VALUE hash, int (*func)(ANYARGS), VALUE farg)
201 {
202 struct hash_foreach_arg arg;
203
204 if (!RHASH(hash)->ntbl)
205 return;
206 RHASH_ITER_LEV(hash)++;
207 arg.hash = hash;
208 arg.func = (rb_foreach_func *)func;
209 arg.arg = farg;
210 rb_ensure(hash_foreach_call, (VALUE)&arg, hash_foreach_ensure, hash);
211 }
212
213 static VALUE
214 hash_alloc(VALUE klass)
215 {
216 NEWOBJ_OF(hash, struct RHash, klass, T_HASH);
217
218 RHASH_IFNONE(hash) = Qnil;
219
220 return (VALUE)hash;
221 }
222
223 static VALUE
224 empty_hash_alloc(VALUE klass)
225 {
226 if (RUBY_DTRACE_HASH_CREATE_ENABLED()) {
227 RUBY_DTRACE_HASH_CREATE(0, rb_sourcefile(), rb_sourceline());
228 }
229
230 return hash_alloc(klass);
231 }
232
233 VALUE
234 rb_hash_new(void)
235 {
236 return hash_alloc(rb_cHash);
237 }
238
239 VALUE
240 rb_hash_dup(VALUE hash)
241 {
242 NEWOBJ_OF(ret, struct RHash,
243 rb_obj_class(hash),
244 (RBASIC(hash)->flags)&(T_MASK|FL_EXIVAR|FL_TAINT|FL_UNTRUSTED));
245 if (FL_TEST((hash), FL_EXIVAR))
246 rb_copy_generic_ivar((VALUE)(ret),(VALUE)(hash));
247
248 if (!RHASH_EMPTY_P(hash))
249 ret->ntbl = st_copy(RHASH(hash)->ntbl);
250 if (FL_TEST(hash, HASH_PROC_DEFAULT)) {
251 FL_SET(ret, HASH_PROC_DEFAULT);
252 }
253 RHASH_IFNONE(ret) = RHASH_IFNONE(hash);
254 return (VALUE)ret;
255 }
256
257 static void
258 rb_hash_modify_check(VALUE hash)
259 {
260 rb_check_frozen(hash);
261 if (!OBJ_UNTRUSTED(hash) && rb_safe_level() >= 4)
262 rb_raise(rb_eSecurityError, "Insecure: can't modify hash");
263 }
264
265 struct st_table *
266 rb_hash_tbl(VALUE hash)
267 {
268 if (!RHASH(hash)->ntbl) {
269 RHASH(hash)->ntbl = st_init_table(&objhash);
270 }
271 return RHASH(hash)->ntbl;
272 }
273
274 static void
275 rb_hash_modify(VALUE hash)
276 {
277 rb_hash_modify_check(hash);
278 rb_hash_tbl(hash);
279 }
280
281 NORETURN(static void no_new_key(void));
282 static void
283 no_new_key(void)
284 {
285 rb_raise(rb_eRuntimeError, "can't add a new key into hash during iteration");
286 }
287
288 #define NOINSERT_UPDATE_CALLBACK(func) \
289 int \
290 func##_noinsert(st_data_t *key, st_data_t *val, st_data_t arg, int existing) \
291 { \
292 if (!existing) no_new_key(); \
293 return func(key, val, arg, existing); \
294 }
295
296 #define UPDATE_CALLBACK(iter_lev, func) ((iter_lev) > 0 ? func##_noinsert : func)
297
298 #define RHASH_UPDATE_ITER(hash, iter_lev, key, func, arg) \
299 st_update(RHASH(hash)->ntbl, (st_data_t)(key), \
300 UPDATE_CALLBACK((iter_lev), func), \
301 (st_data_t)(arg))
302 #define RHASH_UPDATE(hash, key, func, arg) \
303 RHASH_UPDATE_ITER(hash, RHASH_ITER_LEV(hash), key, func, arg)
304
305 static void
306 default_proc_arity_check(VALUE proc)
307 {
308 int n = rb_proc_arity(proc);
309
310 if (rb_proc_lambda_p(proc) && n != 2 && (n >= 0 || n < -3)) {
311 if (n < 0) n = -n-1;
312 rb_raise(rb_eTypeError, "default_proc takes two arguments (2 for %d)", n);
313 }
314 }
315
316 /*
317 * call-seq:
318 * Hash.new -> new_hash
319 * Hash.new(obj) -> new_hash
320 * Hash.new {|hash, key| block } -> new_hash
321 *
322 * Returns a new, empty hash. If this hash is subsequently accessed by
323 * a key that doesn't correspond to a hash entry, the value returned
324 * depends on the style of <code>new</code> used to create the hash. In
325 * the first form, the access returns <code>nil</code>. If
326 * <i>obj</i> is specified, this single object will be used for
327 * all <em>default values</em>. If a block is specified, it will be
328 * called with the hash object and the key, and should return the
329 * default value. It is the block's responsibility to store the value
330 * in the hash if required.
331 *
332 * h = Hash.new("Go Fish")
333 * h["a"] = 100
334 * h["b"] = 200
335 * h["a"] #=> 100
336 * h["c"] #=> "Go Fish"
337 * # The following alters the single default object
338 * h["c"].upcase! #=> "GO FISH"
339 * h["d"] #=> "GO FISH"
340 * h.keys #=> ["a", "b"]
341 *
342 * # While this creates a new default object each time
343 * h = Hash.new { |hash, key| hash[key] = "Go Fish: #{key}" }
344 * h["c"] #=> "Go Fish: c"
345 * h["c"].upcase! #=> "GO FISH: C"
346 * h["d"] #=> "Go Fish: d"
347 * h.keys #=> ["c", "d"]
348 *
349 */
350
351 static VALUE
352 rb_hash_initialize(int argc, VALUE *argv, VALUE hash)
353 {
354 VALUE ifnone;
355
356 rb_hash_modify(hash);
357 if (rb_block_given_p()) {
358 rb_check_arity(argc, 0, 0);
359 ifnone = rb_block_proc();
360 default_proc_arity_check(ifnone);
361 RHASH_IFNONE(hash) = ifnone;
362 FL_SET(hash, HASH_PROC_DEFAULT);
363 }
364 else {
365 rb_scan_args(argc, argv, "01", &ifnone);
366 RHASH_IFNONE(hash) = ifnone;
367 }
368
369 return hash;
370 }
371
372 /*
373 * call-seq:
374 * Hash[ key, value, ... ] -> new_hash
375 * Hash[ [ [key, value], ... ] ] -> new_hash
376 * Hash[ object ] -> new_hash
377 *
378 * Creates a new hash populated with the given objects. Equivalent to
379 * the literal <code>{ <i>key</i> => <i>value</i>, ... }</code>. In the first
380 * form, keys and values occur in pairs, so there must be an even number of arguments.
381 * The second and third form take a single argument which is either
382 * an array of key-value pairs or an object convertible to a hash.
383 *
384 * Hash["a", 100, "b", 200] #=> {"a"=>100, "b"=>200}
385 * Hash[ [ ["a", 100], ["b", 200] ] ] #=> {"a"=>100, "b"=>200}
386 * Hash["a" => 100, "b" => 200] #=> {"a"=>100, "b"=>200}
387 */
388
389 static VALUE
390 rb_hash_s_create(int argc, VALUE *argv, VALUE klass)
391 {
392 VALUE hash, tmp;
393 int i;
394
395 if (argc == 1) {
396 tmp = rb_hash_s_try_convert(Qnil, argv[0]);
397 if (!NIL_P(tmp)) {
398 hash = hash_alloc(klass);
399 if (RHASH(tmp)->ntbl) {
400 RHASH(hash)->ntbl = st_copy(RHASH(tmp)->ntbl);
401 }
402 return hash;
403 }
404
405 tmp = rb_check_array_type(argv[0]);
406 if (!NIL_P(tmp)) {
407 long i;
408
409 hash = hash_alloc(klass);
410 for (i = 0; i < RARRAY_LEN(tmp); ++i) {
411 VALUE e = RARRAY_PTR(tmp)[i];
412 VALUE v = rb_check_array_type(e);
413 VALUE key, val = Qnil;
414
415 if (NIL_P(v)) {
416 #if 0 /* refix in the next release */
417 rb_raise(rb_eArgError, "wrong element type %s at %ld (expected array)",
418 rb_builtin_class_name(e), i);
419
420 #else
421 rb_warn("wrong element type %s at %ld (expected array)",
422 rb_builtin_class_name(e), i);
423 rb_warn("ignoring wrong elements is deprecated, remove them explicitly");
424 rb_warn("this causes ArgumentError in the next release");
425 continue;
426 #endif
427 }
428 switch (RARRAY_LEN(v)) {
429 default:
430 rb_raise(rb_eArgError, "invalid number of elements (%ld for 1..2)",
431 RARRAY_LEN(v));
432 case 2:
433 val = RARRAY_PTR(v)[1];
434 case 1:
435 key = RARRAY_PTR(v)[0];
436 rb_hash_aset(hash, key, val);
437 }
438 }
439 return hash;
440 }
441 }
442 if (argc % 2 != 0) {
443 rb_raise(rb_eArgError, "odd number of arguments for Hash");
444 }
445
446 hash = hash_alloc(klass);
447 for (i=0; i<argc; i+=2) {
448 rb_hash_aset(hash, argv[i], argv[i + 1]);
449 }
450
451 return hash;
452 }
453
454 static VALUE
455 to_hash(VALUE hash)
456 {
457 return rb_convert_type(hash, T_HASH, "Hash", "to_hash");
458 }
459
460 VALUE
461 rb_check_hash_type(VALUE hash)
462 {
463 return rb_check_convert_type(hash, T_HASH, "Hash", "to_hash");
464 }
465
466 /*
467 * call-seq:
468 * Hash.try_convert(obj) -> hash or nil
469 *
470 * Try to convert <i>obj</i> into a hash, using to_hash method.
471 * Returns converted hash or nil if <i>obj</i> cannot be converted
472 * for any reason.
473 *
474 * Hash.try_convert({1=>2}) # => {1=>2}
475 * Hash.try_convert("1=>2") # => nil
476 */
477 static VALUE
478 rb_hash_s_try_convert(VALUE dummy, VALUE hash)
479 {
480 return rb_check_hash_type(hash);
481 }
482
483 static int
484 rb_hash_rehash_i(VALUE key, VALUE value, VALUE arg)
485 {
486 st_table *tbl = (st_table *)arg;
487
488 st_insert(tbl, (st_data_t)key, (st_data_t)value);
489 return ST_CONTINUE;
490 }
491
492 /*
493 * call-seq:
494 * hsh.rehash -> hsh
495 *
496 * Rebuilds the hash based on the current hash values for each key. If
497 * values of key objects have changed since they were inserted, this
498 * method will reindex <i>hsh</i>. If <code>Hash#rehash</code> is
499 * called while an iterator is traversing the hash, an
500 * <code>RuntimeError</code> will be raised in the iterator.
501 *
502 * a = [ "a", "b" ]
503 * c = [ "c", "d" ]
504 * h = { a => 100, c => 300 }
505 * h[a] #=> 100
506 * a[0] = "z"
507 * h[a] #=> nil
508 * h.rehash #=> {["z", "b"]=>100, ["c", "d"]=>300}
509 * h[a] #=> 100
510 */
511
512 static VALUE
513 rb_hash_rehash(VALUE hash)
514 {
515 st_table *tbl;
516
517 if (RHASH_ITER_LEV(hash) > 0) {
518 rb_raise(rb_eRuntimeError, "rehash during iteration");
519 }
520 rb_hash_modify_check(hash);
521 if (!RHASH(hash)->ntbl)
522 return hash;
523 tbl = st_init_table_with_size(RHASH(hash)->ntbl->type, RHASH(hash)->ntbl->num_entries);
524 rb_hash_foreach(hash, rb_hash_rehash_i, (VALUE)tbl);
525 st_free_table(RHASH(hash)->ntbl);
526 RHASH(hash)->ntbl = tbl;
527
528 return hash;
529 }
530
531 static VALUE
532 hash_default_value(VALUE hash, VALUE key)
533 {
534 if (rb_method_basic_definition_p(CLASS_OF(hash), id_default)) {
535 VALUE ifnone = RHASH_IFNONE(hash);
536 if (!FL_TEST(hash, HASH_PROC_DEFAULT)) return ifnone;
537 if (key == Qundef) return Qnil;
538 return rb_funcall(ifnone, id_yield, 2, hash, key);
539 }
540 else {
541 return rb_funcall(hash, id_default, 1, key);
542 }
543 }
544
545 /*
546 * call-seq:
547 * hsh[key] -> value
548 *
549 * Element Reference---Retrieves the <i>value</i> object corresponding
550 * to the <i>key</i> object. If not found, returns the default value (see
551 * <code>Hash::new</code> for details).
552 *
553 * h = { "a" => 100, "b" => 200 }
554 * h["a"] #=> 100
555 * h["c"] #=> nil
556 *
557 */
558
559 VALUE
560 rb_hash_aref(VALUE hash, VALUE key)
561 {
562 st_data_t val;
563
564 if (!RHASH(hash)->ntbl || !st_lookup(RHASH(hash)->ntbl, key, &val)) {
565 return hash_default_value(hash, key);
566 }
567 return (VALUE)val;
568 }
569
570 VALUE
571 rb_hash_lookup2(VALUE hash, VALUE key, VALUE def)
572 {
573 st_data_t val;
574
575 if (!RHASH(hash)->ntbl || !st_lookup(RHASH(hash)->ntbl, key, &val)) {
576 return def; /* without Hash#default */
577 }
578 return (VALUE)val;
579 }
580
581 VALUE
582 rb_hash_lookup(VALUE hash, VALUE key)
583 {
584 return rb_hash_lookup2(hash, key, Qnil);
585 }
586
587 /*
588 * call-seq:
589 * hsh.fetch(key [, default] ) -> obj
590 * hsh.fetch(key) {| key | block } -> obj
591 *
592 * Returns a value from the hash for the given key. If the key can't be
593 * found, there are several options: With no other arguments, it will
594 * raise an <code>KeyError</code> exception; if <i>default</i> is
595 * given, then that will be returned; if the optional code block is
596 * specified, then that will be run and its result returned.
597 *
598 * h = { "a" => 100, "b" => 200 }
599 * h.fetch("a") #=> 100
600 * h.fetch("z", "go fish") #=> "go fish"
601 * h.fetch("z") { |el| "go fish, #{el}"} #=> "go fish, z"
602 *
603 * The following example shows that an exception is raised if the key
604 * is not found and a default value is not supplied.
605 *
606 * h = { "a" => 100, "b" => 200 }
607 * h.fetch("z")
608 *
609 * <em>produces:</em>
610 *
611 * prog.rb:2:in `fetch': key not found (KeyError)
612 * from prog.rb:2
613 *
614 */
615
616 static VALUE
617 rb_hash_fetch_m(int argc, VALUE *argv, VALUE hash)
618 {
619 VALUE key, if_none;
620 st_data_t val;
621 long block_given;
622
623 rb_scan_args(argc, argv, "11", &key, &if_none);
624
625 block_given = rb_block_given_p();
626 if (block_given && argc == 2) {
627 rb_warn("block supersedes default value argument");
628 }
629 if (!RHASH(hash)->ntbl || !st_lookup(RHASH(hash)->ntbl, key, &val)) {
630 if (block_given) return rb_yield(key);
631 if (argc == 1) {
632 volatile VALUE desc = rb_protect(rb_inspect, key, 0);
633 if (NIL_P(desc)) {
634 desc = rb_any_to_s(key);
635 }
636 desc = rb_str_ellipsize(desc, 65);
637 rb_raise(rb_eKeyError, "key not found: %s", RSTRING_PTR(desc));
638 }
639 return if_none;
640 }
641 return (VALUE)val;
642 }
643
644 VALUE
645 rb_hash_fetch(VALUE hash, VALUE key)
646 {
647 return rb_hash_fetch_m(1, &key, hash);
648 }
649
650 /*
651 * call-seq:
652 * hsh.default(key=nil) -> obj
653 *
654 * Returns the default value, the value that would be returned by
655 * <i>hsh</i>[<i>key</i>] if <i>key</i> did not exist in <i>hsh</i>.
656 * See also <code>Hash::new</code> and <code>Hash#default=</code>.
657 *
658 * h = Hash.new #=> {}
659 * h.default #=> nil
660 * h.default(2) #=> nil
661 *
662 * h = Hash.new("cat") #=> {}
663 * h.default #=> "cat"
664 * h.default(2) #=> "cat"
665 *
666 * h = Hash.new {|h,k| h[k] = k.to_i*10} #=> {}
667 * h.default #=> nil
668 * h.default(2) #=> 20
669 */
670
671 static VALUE
672 rb_hash_default(int argc, VALUE *argv, VALUE hash)
673 {
674 VALUE key, ifnone;
675
676 rb_scan_args(argc, argv, "01", &key);
677 ifnone = RHASH_IFNONE(hash);
678 if (FL_TEST(hash, HASH_PROC_DEFAULT)) {
679 if (argc == 0) return Qnil;
680 return rb_funcall(ifnone, id_yield, 2, hash, key);
681 }
682 return ifnone;
683 }
684
685 /*
686 * call-seq:
687 * hsh.default = obj -> obj
688 *
689 * Sets the default value, the value returned for a key that does not
690 * exist in the hash. It is not possible to set the default to a
691 * <code>Proc</code> that will be executed on each key lookup.
692 *
693 * h = { "a" => 100, "b" => 200 }
694 * h.default = "Go fish"
695 * h["a"] #=> 100
696 * h["z"] #=> "Go fish"
697 * # This doesn't do what you might hope...
698 * h.default = proc do |hash, key|
699 * hash[key] = key + key
700 * end
701 * h[2] #=> #<Proc:0x401b3948@-:6>
702 * h["cat"] #=> #<Proc:0x401b3948@-:6>
703 */
704
705 static VALUE
706 rb_hash_set_default(VALUE hash, VALUE ifnone)
707 {
708 rb_hash_modify_check(hash);
709 RHASH_IFNONE(hash) = ifnone;
710 FL_UNSET(hash, HASH_PROC_DEFAULT);
711 return ifnone;
712 }
713
714 /*
715 * call-seq:
716 * hsh.default_proc -> anObject
717 *
718 * If <code>Hash::new</code> was invoked with a block, return that
719 * block, otherwise return <code>nil</code>.
720 *
721 * h = Hash.new {|h,k| h[k] = k*k } #=> {}
722 * p = h.default_proc #=> #<Proc:0x401b3d08@-:1>
723 * a = [] #=> []
724 * p.call(a, 2)
725 * a #=> [nil, nil, 4]
726 */
727
728
729 static VALUE
730 rb_hash_default_proc(VALUE hash)
731 {
732 if (FL_TEST(hash, HASH_PROC_DEFAULT)) {
733 return RHASH_IFNONE(hash);
734 }
735 return Qnil;
736 }
737
738 /*
739 * call-seq:
740 * hsh.default_proc = proc_obj or nil
741 *
742 * Sets the default proc to be executed on each failed key lookup.
743 *
744 * h.default_proc = proc do |hash, key|
745 * hash[key] = key + key
746 * end
747 * h[2] #=> 4
748 * h["cat"] #=> "catcat"
749 */
750
751 static VALUE
752 rb_hash_set_default_proc(VALUE hash, VALUE proc)
753 {
754 VALUE b;
755
756 rb_hash_modify_check(hash);
757 if (NIL_P(proc)) {
758 FL_UNSET(hash, HASH_PROC_DEFAULT);
759 RHASH_IFNONE(hash) = proc;
760 return proc;
761 }
762 b = rb_check_convert_type(proc, T_DATA, "Proc", "to_proc");
763 if (NIL_P(b) || !rb_obj_is_proc(b)) {
764 rb_raise(rb_eTypeError,
765 "wrong default_proc type %s (expected Proc)",
766 rb_obj_classname(proc));
767 }
768 proc = b;
769 default_proc_arity_check(proc);
770 RHASH_IFNONE(hash) = proc;
771 FL_SET(hash, HASH_PROC_DEFAULT);
772 return proc;
773 }
774
775 static int
776 key_i(VALUE key, VALUE value, VALUE arg)
777 {
778 VALUE *args = (VALUE *)arg;
779
780 if (rb_equal(value, args[0])) {
781 args[1] = key;
782 return ST_STOP;
783 }
784 return ST_CONTINUE;
785 }
786
787 /*
788 * call-seq:
789 * hsh.key(value) -> key
790 *
791 * Returns the key of an occurrence of a given value. If the value is
792 * not found, returns <code>nil</code>.
793 *
794 * h = { "a" => 100, "b" => 200, "c" => 300, "d" => 300 }
795 * h.key(200) #=> "b"
796 * h.key(300) #=> "c"
797 * h.key(999) #=> nil
798 *
799 */
800
801 static VALUE
802 rb_hash_key(VALUE hash, VALUE value)
803 {
804 VALUE args[2];
805
806 args[0] = value;
807 args[1] = Qnil;
808
809 rb_hash_foreach(hash, key_i, (VALUE)args);
810
811 return args[1];
812 }
813
814 /* :nodoc: */
815 static VALUE
816 rb_hash_index(VALUE hash, VALUE value)
817 {
818 rb_warn("Hash#index is deprecated; use Hash#key");
819 return rb_hash_key(hash, value);
820 }
821
822 static VALUE
823 rb_hash_delete_key(VALUE hash, VALUE key)
824 {
825 st_data_t ktmp = (st_data_t)key, val;
826
827 if (!RHASH(hash)->ntbl)
828 return Qundef;
829 if (RHASH_ITER_LEV(hash) > 0) {
830 if (st_delete_safe(RHASH(hash)->ntbl, &ktmp, &val, (st_data_t)Qundef)) {
831 FL_SET(hash, HASH_DELETED);
832 return (VALUE)val;
833 }
834 }
835 else if (st_delete(RHASH(hash)->ntbl, &ktmp, &val))
836 return (VALUE)val;
837 return Qundef;
838 }
839
840 /*
841 * call-seq:
842 * hsh.delete(key) -> value
843 * hsh.delete(key) {| key | block } -> value
844 *
845 * Deletes the key-value pair and returns the value from <i>hsh</i> whose
846 * key is equal to <i>key</i>. If the key is not found, returns the
847 * <em>default value</em>. If the optional code block is given and the
848 * key is not found, pass in the key and return the result of
849 * <i>block</i>.
850 *
851 * h = { "a" => 100, "b" => 200 }
852 * h.delete("a") #=> 100
853 * h.delete("z") #=> nil
854 * h.delete("z") { |el| "#{el} not found" } #=> "z not found"
855 *
856 */
857
858 VALUE
859 rb_hash_delete(VALUE hash, VALUE key)
860 {
861 VALUE val;
862
863 rb_hash_modify_check(hash);
864 val = rb_hash_delete_key(hash, key);
865 if (val != Qundef) return val;
866 if (rb_block_given_p()) {
867 return rb_yield(key);
868 }
869 return Qnil;
870 }
871
872 struct shift_var {
873 VALUE key;
874 VALUE val;
875 };
876
877 static int
878 shift_i(VALUE key, VALUE value, VALUE arg)
879 {
880 struct shift_var *var = (struct shift_var *)arg;
881
882 if (var->key != Qundef) return ST_STOP;
883 var->key = key;
884 var->val = value;
885 return ST_DELETE;
886 }
887
888 static int
889 shift_i_safe(VALUE key, VALUE value, VALUE arg)
890 {
891 struct shift_var *var = (struct shift_var *)arg;
892
893 var->key = key;
894 var->val = value;
895 return ST_STOP;
896 }
897
898 /*
899 * call-seq:
900 * hsh.shift -> anArray or obj
901 *
902 * Removes a key-value pair from <i>hsh</i> and returns it as the
903 * two-item array <code>[</code> <i>key, value</i> <code>]</code>, or
904 * the hash's default value if the hash is empty.
905 *
906 * h = { 1 => "a", 2 => "b", 3 => "c" }
907 * h.shift #=> [1, "a"]
908 * h #=> {2=>"b", 3=>"c"}
909 */
910
911 static VALUE
912 rb_hash_shift(VALUE hash)
913 {
914 struct shift_var var;
915
916 rb_hash_modify_check(hash);
917 if (RHASH(hash)->ntbl) {
918 var.key = Qundef;
919 rb_hash_foreach(hash, RHASH_ITER_LEV(hash) > 0 ? shift_i_safe : shift_i,
920 (VALUE)&var);
921
922 if (var.key != Qundef) {
923 if (RHASH_ITER_LEV(hash) > 0) {
924 rb_hash_delete_key(hash, var.key);
925 }
926 return rb_assoc_new(var.key, var.val);
927 }
928 }
929 return hash_default_value(hash, Qnil);
930 }
931
932 static int
933 delete_if_i(VALUE key, VALUE value, VALUE hash)
934 {
935 if (RTEST(rb_yield_values(2, key, value))) {
936 rb_hash_delete_key(hash, key);
937 }
938 return ST_CONTINUE;
939 }
940
941 static VALUE rb_hash_size(VALUE hash);
942
943 /*
944 * call-seq:
945 * hsh.delete_if {| key, value | block } -> hsh
946 * hsh.delete_if -> an_enumerator
947 *
948 * Deletes every key-value pair from <i>hsh</i> for which <i>block</i>
949 * evaluates to <code>true</code>.
950 *
951 * If no block is given, an enumerator is returned instead.
952 *
953 * h = { "a" => 100, "b" => 200, "c" => 300 }
954 * h.delete_if {|key, value| key >= "b" } #=> {"a"=>100}
955 *
956 */
957
958 VALUE
959 rb_hash_delete_if(VALUE hash)
960 {
961 RETURN_SIZED_ENUMERATOR(hash, 0, 0, rb_hash_size);
962 rb_hash_modify_check(hash);
963 if (RHASH(hash)->ntbl)
964 rb_hash_foreach(hash, delete_if_i, hash);
965 return hash;
966 }
967
968 /*
969 * call-seq:
970 * hsh.reject! {| key, value | block } -> hsh or nil
971 * hsh.reject! -> an_enumerator
972 *
973 * Equivalent to <code>Hash#delete_if</code>, but returns
974 * <code>nil</code> if no changes were made.
975 */
976
977 VALUE
978 rb_hash_reject_bang(VALUE hash)
979 {
980 st_index_t n;
981
982 RETURN_SIZED_ENUMERATOR(hash, 0, 0, rb_hash_size);
983 rb_hash_modify(hash);
984 if (!RHASH(hash)->ntbl)
985 return Qnil;
986 n = RHASH(hash)->ntbl->num_entries;
987 rb_hash_foreach(hash, delete_if_i, hash);
988 if (n == RHASH(hash)->ntbl->num_entries) return Qnil;
989 return hash;
990 }
991
992 /*
993 * call-seq:
994 * hsh.reject {| key, value | block } -> a_hash
995 * hsh.reject -> an_enumerator
996 *
997 * Same as <code>Hash#delete_if</code>, but works on (and returns) a
998 * copy of the <i>hsh</i>. Equivalent to
999 * <code><i>hsh</i>.dup.delete_if</code>.
1000 *
1001 */
1002
1003 static VALUE
1004 rb_hash_reject(VALUE hash)
1005 {
1006 return rb_hash_delete_if(rb_obj_dup(hash));
1007 }
1008
1009 /*
1010 * call-seq:
1011 * hsh.values_at(key, ...) -> array
1012 *
1013 * Return an array containing the values associated with the given keys.
1014 * Also see <code>Hash.select</code>.
1015 *
1016 * h = { "cat" => "feline", "dog" => "canine", "cow" => "bovine" }
1017 * h.values_at("cow", "cat") #=> ["bovine", "feline"]
1018 */
1019
1020 VALUE
1021 rb_hash_values_at(int argc, VALUE *argv, VALUE hash)
1022 {
1023 VALUE result = rb_ary_new2(argc);
1024 long i;
1025
1026 for (i=0; i<argc; i++) {
1027 rb_ary_push(result, rb_hash_aref(hash, argv[i]));
1028 }
1029 return result;
1030 }
1031
1032 static int
1033 select_i(VALUE key, VALUE value, VALUE result)
1034 {
1035 if (RTEST(rb_yield_values(2, key, value)))
1036 rb_hash_aset(result, key, value);
1037 return ST_CONTINUE;
1038 }
1039
1040 /*
1041 * call-seq:
1042 * hsh.select {|key, value| block} -> a_hash
1043 * hsh.select -> an_enumerator
1044 *
1045 * Returns a new hash consisting of entries for which the block returns true.
1046 *
1047 * If no block is given, an enumerator is returned instead.
1048 *
1049 * h = { "a" => 100, "b" => 200, "c" => 300 }
1050 * h.select {|k,v| k > "a"} #=> {"b" => 200, "c" => 300}
1051 * h.select {|k,v| v < 200} #=> {"a" => 100}
1052 */
1053
1054 VALUE
1055 rb_hash_select(VALUE hash)
1056 {
1057 VALUE result;
1058
1059 RETURN_SIZED_ENUMERATOR(hash, 0, 0, rb_hash_size);
1060 result = rb_hash_new();
1061 rb_hash_foreach(hash, select_i, result);
1062 return result;
1063 }
1064
1065 static int
1066 keep_if_i(VALUE key, VALUE value, VALUE hash)
1067 {
1068 if (!RTEST(rb_yield_values(2, key, value))) {
1069 return ST_DELETE;
1070 }
1071 return ST_CONTINUE;
1072 }
1073
1074 /*
1075 * call-seq:
1076 * hsh.select! {| key, value | block } -> hsh or nil
1077 * hsh.select! -> an_enumerator
1078 *
1079 * Equivalent to <code>Hash#keep_if</code>, but returns
1080 * <code>nil</code> if no changes were made.
1081 */
1082
1083 VALUE
1084 rb_hash_select_bang(VALUE hash)
1085 {
1086 st_index_t n;
1087
1088 RETURN_SIZED_ENUMERATOR(hash, 0, 0, rb_hash_size);
1089 rb_hash_modify_check(hash);
1090 if (!RHASH(hash)->ntbl)
1091 return Qnil;
1092 n = RHASH(hash)->ntbl->num_entries;
1093 rb_hash_foreach(hash, keep_if_i, hash);
1094 if (n == RHASH(hash)->ntbl->num_entries) return Qnil;
1095 return hash;
1096 }
1097
1098 /*
1099 * call-seq:
1100 * hsh.keep_if {| key, value | block } -> hsh
1101 * hsh.keep_if -> an_enumerator
1102 *
1103 * Deletes every key-value pair from <i>hsh</i> for which <i>block</i>
1104 * evaluates to false.
1105 *
1106 * If no block is given, an enumerator is returned instead.
1107 *
1108 */
1109
1110 VALUE
1111 rb_hash_keep_if(VALUE hash)
1112 {
1113 RETURN_SIZED_ENUMERATOR(hash, 0, 0, rb_hash_size);
1114 rb_hash_modify_check(hash);
1115 if (RHASH(hash)->ntbl)
1116 rb_hash_foreach(hash, keep_if_i, hash);
1117 return hash;
1118 }
1119
1120 static int
1121 clear_i(VALUE key, VALUE value, VALUE dummy)
1122 {
1123 return ST_DELETE;
1124 }
1125
1126 /*
1127 * call-seq:
1128 * hsh.clear -> hsh
1129 *
1130 * Removes all key-value pairs from <i>hsh</i>.
1131 *
1132 * h = { "a" => 100, "b" => 200 } #=> {"a"=>100, "b"=>200}
1133 * h.clear #=> {}
1134 *
1135 */
1136
1137 VALUE
1138 rb_hash_clear(VALUE hash)
1139 {
1140 rb_hash_modify_check(hash);
1141 if (!RHASH(hash)->ntbl)
1142 return hash;
1143 if (RHASH(hash)->ntbl->num_entries > 0) {
1144 if (RHASH_ITER_LEV(hash) > 0)
1145 rb_hash_foreach(hash, clear_i, 0);
1146 else
1147 st_clear(RHASH(hash)->ntbl);
1148 }
1149
1150 return hash;
1151 }
1152
1153 static int
1154 hash_aset(st_data_t *key, st_data_t *val, st_data_t arg, int existing)
1155 {
1156 *val = arg;
1157 return ST_CONTINUE;
1158 }
1159
1160 static int
1161 hash_aset_str(st_data_t *key, st_data_t *val, st_data_t arg, int existing)
1162 {
1163 *key = (st_data_t)rb_str_new_frozen((VALUE)*key);
1164 return hash_aset(key, val, arg, existing);
1165 }
1166
1167 static NOINSERT_UPDATE_CALLBACK(hash_aset)
1168 static NOINSERT_UPDATE_CALLBACK(hash_aset_str)
1169
1170 /*
1171 * call-seq:
1172 * hsh[key] = value -> value
1173 * hsh.store(key, value) -> value
1174 *
1175 * Element Assignment---Associates the value given by
1176 * <i>value</i> with the key given by <i>key</i>.
1177 * <i>key</i> should not have its value changed while it is in
1178 * use as a key (a <code>String</code> passed as a key will be
1179 * duplicated and frozen).
1180 *
1181 * h = { "a" => 100, "b" => 200 }
1182 * h["a"] = 9
1183 * h["c"] = 4
1184 * h #=> {"a"=>9, "b"=>200, "c"=>4}
1185 *
1186 */
1187
1188 VALUE
1189 rb_hash_aset(VALUE hash, VALUE key, VALUE val)
1190 {
1191 int iter_lev = RHASH_ITER_LEV(hash);
1192 st_table *tbl = RHASH(hash)->ntbl;
1193
1194 rb_hash_modify(hash);
1195 if (!tbl) {
1196 if (iter_lev > 0) no_new_key();
1197 tbl = RHASH_TBL(hash);
1198 }
1199 if (tbl->type == &identhash || rb_obj_class(key) != rb_cString) {
1200 RHASH_UPDATE_ITER(hash, iter_lev, key, hash_aset, val);
1201 }
1202 else {
1203 RHASH_UPDATE_ITER(hash, iter_lev, key, hash_aset_str, val);
1204 }
1205 return val;
1206 }
1207
1208 static int
1209 replace_i(VALUE key, VALUE val, VALUE hash)
1210 {
1211 rb_hash_aset(hash, key, val);
1212
1213 return ST_CONTINUE;
1214 }
1215
1216 static VALUE
1217 rb_hash_initialize_copy(VALUE hash, VALUE hash2)
1218 {
1219 rb_hash_modify_check(hash);
1220 hash2 = to_hash(hash2);
1221
1222 Check_Type(hash2, T_HASH);
1223
1224 if (!RHASH_EMPTY_P(hash2)) {
1225 RHASH(hash)->ntbl = st_copy(RHASH(hash2)->ntbl);
1226 rb_hash_rehash(hash);
1227 }
1228
1229 if (FL_TEST(hash2, HASH_PROC_DEFAULT)) {
1230 FL_SET(hash, HASH_PROC_DEFAULT);
1231 }
1232 else {
1233 FL_UNSET(hash, HASH_PROC_DEFAULT);
1234 }
1235 RHASH_IFNONE(hash) = RHASH_IFNONE(hash2);
1236
1237 return hash;
1238 }
1239
1240 /*
1241 * call-seq:
1242 * hsh.replace(other_hash) -> hsh
1243 *
1244 * Replaces the contents of <i>hsh</i> with the contents of
1245 * <i>other_hash</i>.
1246 *
1247 * h = { "a" => 100, "b" => 200 }
1248 * h.replace({ "c" => 300, "d" => 400 }) #=> {"c"=>300, "d"=>400}
1249 *
1250 */
1251
1252 static VALUE
1253 rb_hash_replace(VALUE hash, VALUE hash2)
1254 {
1255 rb_hash_modify_check(hash);
1256 hash2 = to_hash(hash2);
1257 if (hash == hash2) return hash;
1258 rb_hash_clear(hash);
1259 if (RHASH(hash2)->ntbl) {
1260 rb_hash_tbl(hash);
1261 RHASH(hash)->ntbl->type = RHASH(hash2)->ntbl->type;
1262 }
1263 rb_hash_foreach(hash2, replace_i, hash);
1264 RHASH_IFNONE(hash) = RHASH_IFNONE(hash2);
1265 if (FL_TEST(hash2, HASH_PROC_DEFAULT)) {
1266 FL_SET(hash, HASH_PROC_DEFAULT);
1267 }
1268 else {
1269 FL_UNSET(hash, HASH_PROC_DEFAULT);
1270 }
1271
1272 return hash;
1273 }
1274
1275 /*
1276 * call-seq:
1277 * hsh.length -> fixnum
1278 * hsh.size -> fixnum
1279 *
1280 * Returns the number of key-value pairs in the hash.
1281 *
1282 * h = { "d" => 100, "a" => 200, "v" => 300, "e" => 400 }
1283 * h.length #=> 4
1284 * h.delete("a") #=> 200
1285 * h.length #=> 3
1286 */
1287
1288 static VALUE
1289 rb_hash_size(VALUE hash)
1290 {
1291 if (!RHASH(hash)->ntbl)
1292 return INT2FIX(0);
1293 return INT2FIX(RHASH(hash)->ntbl->num_entries);
1294 }
1295
1296
1297 /*
1298 * call-seq:
1299 * hsh.empty? -> true or false
1300 *
1301 * Returns <code>true</code> if <i>hsh</i> contains no key-value pairs.
1302 *
1303 * {}.empty? #=> true
1304 *
1305 */
1306
1307 static VALUE
1308 rb_hash_empty_p(VALUE hash)
1309 {
1310 return RHASH_EMPTY_P(hash) ? Qtrue : Qfalse;
1311 }
1312
1313 static int
1314 each_value_i(VALUE key, VALUE value)
1315 {
1316 rb_yield(value);
1317 return ST_CONTINUE;
1318 }
1319
1320 /*
1321 * call-seq:
1322 * hsh.each_value {| value | block } -> hsh
1323 * hsh.each_value -> an_enumerator
1324 *
1325 * Calls <i>block</i> once for each key in <i>hsh</i>, passing the
1326 * value as a parameter.
1327 *
1328 * If no block is given, an enumerator is returned instead.
1329 *
1330 * h = { "a" => 100, "b" => 200 }
1331 * h.each_value {|value| puts value }
1332 *
1333 * <em>produces:</em>
1334 *
1335 * 100
1336 * 200
1337 */
1338
1339 static VALUE
1340 rb_hash_each_value(VALUE hash)
1341 {
1342 RETURN_SIZED_ENUMERATOR(hash, 0, 0, rb_hash_size);
1343 rb_hash_foreach(hash, each_value_i, 0);
1344 return hash;
1345 }
1346
1347 static int
1348 each_key_i(VALUE key, VALUE value)
1349 {
1350 rb_yield(key);
1351 return ST_CONTINUE;
1352 }
1353
1354 /*
1355 * call-seq:
1356 * hsh.each_key {| key | block } -> hsh
1357 * hsh.each_key -> an_enumerator
1358 *
1359 * Calls <i>block</i> once for each key in <i>hsh</i>, passing the key
1360 * as a parameter.
1361 *
1362 * If no block is given, an enumerator is returned instead.
1363 *
1364 * h = { "a" => 100, "b" => 200 }
1365 * h.each_key {|key| puts key }
1366 *
1367 * <em>produces:</em>
1368 *
1369 * a
1370 * b
1371 */
1372 static VALUE
1373 rb_hash_each_key(VALUE hash)
1374 {
1375 RETURN_SIZED_ENUMERATOR(hash, 0, 0, rb_hash_size);
1376 rb_hash_foreach(hash, each_key_i, 0);
1377 return hash;
1378 }
1379
1380 static int
1381 each_pair_i(VALUE key, VALUE value)
1382 {
1383 rb_yield(rb_assoc_new(key, value));
1384 return ST_CONTINUE;
1385 }
1386
1387 /*
1388 * call-seq:
1389 * hsh.each {| key, value | block } -> hsh
1390 * hsh.each_pair {| key, value | block } -> hsh
1391 * hsh.each -> an_enumerator
1392 * hsh.each_pair -> an_enumerator
1393 *
1394 * Calls <i>block</i> once for each key in <i>hsh</i>, passing the key-value
1395 * pair as parameters.
1396 *
1397 * If no block is given, an enumerator is returned instead.
1398 *
1399 * h = { "a" => 100, "b" => 200 }
1400 * h.each {|key, value| puts "#{key} is #{value}" }
1401 *
1402 * <em>produces:</em>
1403 *
1404 * a is 100
1405 * b is 200
1406 *
1407 */
1408
1409 static VALUE
1410 rb_hash_each_pair(VALUE hash)
1411 {
1412 RETURN_SIZED_ENUMERATOR(hash, 0, 0, rb_hash_size);
1413 rb_hash_foreach(hash, each_pair_i, 0);
1414 return hash;
1415 }
1416
1417 static int
1418 to_a_i(VALUE key, VALUE value, VALUE ary)
1419 {
1420 rb_ary_push(ary, rb_assoc_new(key, value));
1421 return ST_CONTINUE;
1422 }
1423
1424 /*
1425 * call-seq:
1426 * hsh.to_a -> array
1427 *
1428 * Converts <i>hsh</i> to a nested array of <code>[</code> <i>key,
1429 * value</i> <code>]</code> arrays.
1430 *
1431 * h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300 }
1432 * h.to_a #=> [["c", 300], ["a", 100], ["d", 400]]
1433 */
1434
1435 static VALUE
1436 rb_hash_to_a(VALUE hash)
1437 {
1438 VALUE ary;
1439
1440 ary = rb_ary_new();
1441 rb_hash_foreach(hash, to_a_i, ary);
1442 OBJ_INFECT(ary, hash);
1443
1444 return ary;
1445 }
1446
1447 static int
1448 inspect_i(VALUE key, VALUE value, VALUE str)
1449 {
1450 VALUE str2;
1451
1452 str2 = rb_inspect(key);
1453 if (RSTRING_LEN(str) > 1) {
1454 rb_str_buf_cat_ascii(str, ", ");
1455 }
1456 else {
1457 rb_enc_copy(str, str2);
1458 }
1459 rb_str_buf_append(str, str2);
1460 OBJ_INFECT(str, str2);
1461 rb_str_buf_cat_ascii(str, "=>");
1462 str2 = rb_inspect(value);
1463 rb_str_buf_append(str, str2);
1464 OBJ_INFECT(str, str2);
1465
1466 return ST_CONTINUE;
1467 }
1468
1469 static VALUE
1470 inspect_hash(VALUE hash, VALUE dummy, int recur)
1471 {
1472 VALUE str;
1473
1474 if (recur) return rb_usascii_str_new2("{...}");
1475 str = rb_str_buf_new2("{");
1476 rb_hash_foreach(hash, inspect_i, str);
1477 rb_str_buf_cat2(str, "}");
1478 OBJ_INFECT(str, hash);
1479
1480 return str;
1481 }
1482
1483 /*
1484 * call-seq:
1485 * hsh.to_s -> string
1486 * hsh.inspect -> string
1487 *
1488 * Return the contents of this hash as a string.
1489 *
1490 * h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300 }
1491 * h.to_s #=> "{\"c\"=>300, \"a\"=>100, \"d\"=>400}"
1492 */
1493
1494 static VALUE
1495 rb_hash_inspect(VALUE hash)
1496 {
1497 if (RHASH_EMPTY_P(hash))
1498 return rb_usascii_str_new2("{}");
1499 return rb_exec_recursive(inspect_hash, hash, 0);
1500 }
1501
1502 /*
1503 * call-seq:
1504 * hsh.to_hash => hsh
1505 *
1506 * Returns +self+.
1507 */
1508
1509 static VALUE
1510 rb_hash_to_hash(VALUE hash)
1511 {
1512 return hash;
1513 }
1514
1515 /*
1516 * call-seq:
1517 * hsh.to_h -> hsh or new_hash
1518 *
1519 * Returns +self+. If called on a subclass of Hash, converts
1520 * the receiver to a Hash object.
1521 */
1522
1523 static VALUE
1524 rb_hash_to_h(VALUE hash)
1525 {
1526 if (rb_obj_class(hash) != rb_cHash) {
1527 VALUE ret = rb_hash_new();
1528 if (!RHASH_EMPTY_P(hash))
1529 RHASH(ret)->ntbl = st_copy(RHASH(hash)->ntbl);
1530 if (FL_TEST(hash, HASH_PROC_DEFAULT)) {
1531 FL_SET(ret, HASH_PROC_DEFAULT);
1532 }
1533 RHASH_IFNONE(ret) = RHASH_IFNONE(hash);
1534 return ret;
1535 }
1536 return hash;
1537 }
1538
1539 static int
1540 keys_i(VALUE key, VALUE value, VALUE ary)
1541 {
1542 rb_ary_push(ary, key);
1543 return ST_CONTINUE;
1544 }
1545
1546 /*
1547 * call-seq:
1548 * hsh.keys -> array
1549 *
1550 * Returns a new array populated with the keys from this hash. See also
1551 * <code>Hash#values</code>.
1552 *
1553 * h = { "a" => 100, "b" => 200, "c" => 300, "d" => 400 }
1554 * h.keys #=> ["a", "b", "c", "d"]
1555 *
1556 */
1557
1558 static VALUE
1559 rb_hash_keys(VALUE hash)
1560 {
1561 VALUE ary;
1562
1563 ary = rb_ary_new();
1564 rb_hash_foreach(hash, keys_i, ary);
1565
1566 return ary;
1567 }
1568
1569 static int
1570 values_i(VALUE key, VALUE value, VALUE ary)
1571 {
1572 rb_ary_push(ary, value);
1573 return ST_CONTINUE;
1574 }
1575
1576 /*
1577 * call-seq:
1578 * hsh.values -> array
1579 *
1580 * Returns a new array populated with the values from <i>hsh</i>. See
1581 * also <code>Hash#keys</code>.
1582 *
1583 * h = { "a" => 100, "b" => 200, "c" => 300 }
1584 * h.values #=> [100, 200, 300]
1585 *
1586 */
1587
1588 static VALUE
1589 rb_hash_values(VALUE hash)
1590 {
1591 VALUE ary;
1592
1593 ary = rb_ary_new();
1594 rb_hash_foreach(hash, values_i, ary);
1595
1596 return ary;
1597 }
1598
1599 /*
1600 * call-seq:
1601 * hsh.has_key?(key) -> true or false
1602 * hsh.include?(key) -> true or false
1603 * hsh.key?(key) -> true or false
1604 * hsh.member?(key) -> true or false
1605 *
1606 * Returns <code>true</code> if the given key is present in <i>hsh</i>.
1607 *
1608 * h = { "a" => 100, "b" => 200 }
1609 * h.has_key?("a") #=> true
1610 * h.has_key?("z") #=> false
1611 *
1612 */
1613
1614 static VALUE
1615 rb_hash_has_key(VALUE hash, VALUE key)
1616 {
1617 if (!RHASH(hash)->ntbl)
1618 return Qfalse;
1619 if (st_lookup(RHASH(hash)->ntbl, key, 0)) {
1620 return Qtrue;
1621 }
1622 return Qfalse;
1623 }
1624
1625 static int
1626 rb_hash_search_value(VALUE key, VALUE value, VALUE arg)
1627 {
1628 VALUE *data = (VALUE *)arg;
1629
1630 if (rb_equal(value, data[1])) {
1631 data[0] = Qtrue;
1632 return ST_STOP;
1633 }
1634 return ST_CONTINUE;
1635 }
1636
1637 /*
1638 * call-seq:
1639 * hsh.has_value?(value) -> true or false
1640 * hsh.value?(value) -> true or false
1641 *
1642 * Returns <code>true</code> if the given value is present for some key
1643 * in <i>hsh</i>.
1644 *
1645 * h = { "a" => 100, "b" => 200 }
1646 * h.has_value?(100) #=> true
1647 * h.has_value?(999) #=> false
1648 */
1649
1650 static VALUE
1651 rb_hash_has_value(VALUE hash, VALUE val)
1652 {
1653 VALUE data[2];
1654
1655 data[0] = Qfalse;
1656 data[1] = val;
1657 rb_hash_foreach(hash, rb_hash_search_value, (VALUE)data);
1658 return data[0];
1659 }
1660
1661 struct equal_data {
1662 VALUE result;
1663 st_table *tbl;
1664 int eql;
1665 };
1666
1667 static int
1668 eql_i(VALUE key, VALUE val1, VALUE arg)
1669 {
1670 struct equal_data *data = (struct equal_data *)arg;
1671 st_data_t val2;
1672
1673 if (!st_lookup(data->tbl, key, &val2)) {
1674 data->result = Qfalse;
1675 return ST_STOP;
1676 }
1677 if (!(data->eql ? rb_eql(val1, (VALUE)val2) : (int)rb_equal(val1, (VALUE)val2))) {
1678 data->result = Qfalse;
1679 return ST_STOP;
1680 }
1681 return ST_CONTINUE;
1682 }
1683
1684 static VALUE
1685 recursive_eql(VALUE hash, VALUE dt, int recur)
1686 {
1687 struct equal_data *data;
1688
1689 if (recur) return Qtrue; /* Subtle! */
1690 data = (struct equal_data*)dt;
1691 data->result = Qtrue;
1692 rb_hash_foreach(hash, eql_i, dt);
1693
1694 return data->result;
1695 }
1696
1697 static VALUE
1698 hash_equal(VALUE hash1, VALUE hash2, int eql)
1699 {
1700 struct equal_data data;
1701
1702 if (hash1 == hash2) return Qtrue;
1703 if (!RB_TYPE_P(hash2, T_HASH)) {
1704 if (!rb_respond_to(hash2, rb_intern("to_hash"))) {
1705 return Qfalse;
1706 }
1707 if (eql)
1708 return rb_eql(hash2, hash1);
1709 else
1710 return rb_equal(hash2, hash1);
1711 }
1712 if (RHASH_SIZE(hash1) != RHASH_SIZE(hash2))
1713 return Qfalse;
1714 if (!RHASH(hash1)->ntbl || !RHASH(hash2)->ntbl)
1715 return Qtrue;
1716 if (RHASH(hash1)->ntbl->type != RHASH(hash2)->ntbl->type)
1717 return Qfalse;
1718 #if 0
1719 if (!(rb_equal(RHASH_IFNONE(hash1), RHASH_IFNONE(hash2)) &&
1720 FL_TEST(hash1, HASH_PROC_DEFAULT) == FL_TEST(hash2, HASH_PROC_DEFAULT)))
1721 return Qfalse;
1722 #endif
1723
1724 data.tbl = RHASH(hash2)->ntbl;
1725 data.eql = eql;
1726 return rb_exec_recursive_paired(recursive_eql, hash1, hash2, (VALUE)&data);
1727 }
1728
1729 /*
1730 * call-seq:
1731 * hsh == other_hash -> true or false
1732 *
1733 * Equality---Two hashes are equal if they each contain the same number
1734 * of keys and if each key-value pair is equal to (according to
1735 * <code>Object#==</code>) the corresponding elements in the other
1736 * hash.
1737 *
1738 * h1 = { "a" => 1, "c" => 2 }
1739 * h2 = { 7 => 35, "c" => 2, "a" => 1 }
1740 * h3 = { "a" => 1, "c" => 2, 7 => 35 }
1741 * h4 = { "a" => 1, "d" => 2, "f" => 35 }
1742 * h1 == h2 #=> false
1743 * h2 == h3 #=> true
1744 * h3 == h4 #=> false
1745 *
1746 */
1747
1748 static VALUE
1749 rb_hash_equal(VALUE hash1, VALUE hash2)
1750 {
1751 return hash_equal(hash1, hash2, FALSE);
1752 }
1753
1754 /*
1755 * call-seq:
1756 * hash.eql?(other) -> true or false
1757 *
1758 * Returns <code>true</code> if <i>hash</i> and <i>other</i> are
1759 * both hashes with the same content.
1760 */
1761
1762 static VALUE
1763 rb_hash_eql(VALUE hash1, VALUE hash2)
1764 {
1765 return hash_equal(hash1, hash2, TRUE);
1766 }
1767
1768 static int
1769 hash_i(VALUE key, VALUE val, VALUE arg)
1770 {
1771 st_index_t *hval = (st_index_t *)arg;
1772 st_index_t hdata[2];
1773
1774 hdata[0] = rb_hash(key);
1775 hdata[1] = rb_hash(val);
1776 *hval ^= st_hash(hdata, sizeof(hdata), 0);
1777 return ST_CONTINUE;
1778 }
1779
1780 static VALUE
1781 recursive_hash(VALUE hash, VALUE dummy, int recur)
1782 {
1783 st_index_t hval;
1784
1785 if (!RHASH(hash)->ntbl)
1786 return LONG2FIX(0);
1787 hval = RHASH(hash)->ntbl->num_entries;
1788 if (!hval) return LONG2FIX(0);
1789 if (recur)
1790 hval = rb_hash_uint(rb_hash_start(rb_hash(rb_cHash)), hval);
1791 else
1792 rb_hash_foreach(hash, hash_i, (VALUE)&hval);
1793 hval = rb_hash_end(hval);
1794 return INT2FIX(hval);
1795 }
1796
1797 /*
1798 * call-seq:
1799 * hsh.hash -> fixnum
1800 *
1801 * Compute a hash-code for this hash. Two hashes with the same content
1802 * will have the same hash code (and will compare using <code>eql?</code>).
1803 */
1804
1805 static VALUE
1806 rb_hash_hash(VALUE hash)
1807 {
1808 return rb_exec_recursive_outer(recursive_hash, hash, 0);
1809 }
1810
1811 static int
1812 rb_hash_invert_i(VALUE key, VALUE value, VALUE hash)
1813 {
1814 rb_hash_aset(hash, value, key);
1815 return ST_CONTINUE;
1816 }
1817
1818 /*
1819 * call-seq:
1820 * hsh.invert -> new_hash
1821 *
1822 * Returns a new hash created by using <i>hsh</i>'s values as keys, and
1823 * the keys as values.
1824 *
1825 * h = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 }
1826 * h.invert #=> {0=>"a", 100=>"m", 200=>"d", 300=>"y"}
1827 *
1828 */
1829
1830 static VALUE
1831 rb_hash_invert(VALUE hash)
1832 {
1833 VALUE h = rb_hash_new();
1834
1835 rb_hash_foreach(hash, rb_hash_invert_i, h);
1836 return h;
1837 }
1838
1839 static int
1840 rb_hash_update_callback(st_data_t *key, st_data_t *value, st_data_t arg, int existing)
1841 {
1842 *value = arg;
1843 return ST_CONTINUE;
1844 }
1845
1846 static NOINSERT_UPDATE_CALLBACK(rb_hash_update_callback)
1847
1848 static int
1849 rb_hash_update_i(VALUE key, VALUE value, VALUE hash)
1850 {
1851 RHASH_UPDATE(hash, key, rb_hash_update_callback, value);
1852 return ST_CONTINUE;
1853 }
1854
1855 static int
1856 rb_hash_update_block_callback(st_data_t *key, st_data_t *value, st_data_t arg, int existing)
1857 {
1858 VALUE newvalue = (VALUE)arg;
1859 if (existing) {
1860 newvalue = rb_yield_values(3, (VALUE)*key, (VALUE)*value, newvalue);
1861 }
1862 *value = (st_data_t)newvalue;
1863 return ST_CONTINUE;
1864 }
1865
1866 static NOINSERT_UPDATE_CALLBACK(rb_hash_update_block_callback)
1867
1868 static int
1869 rb_hash_update_block_i(VALUE key, VALUE value, VALUE hash)
1870 {
1871 RHASH_UPDATE(hash, key, rb_hash_update_block_callback, value);
1872 return ST_CONTINUE;
1873 }
1874
1875 /*
1876 * call-seq:
1877 * hsh.merge!(other_hash) -> hsh
1878 * hsh.update(other_hash) -> hsh
1879 * hsh.merge!(other_hash){|key, oldval, newval| block} -> hsh
1880 * hsh.update(other_hash){|key, oldval, newval| block} -> hsh
1881 *
1882 * Adds the contents of _other_hash_ to _hsh_. If no block is specified,
1883 * entries with duplicate keys are overwritten with the values from
1884 * _other_hash_, otherwise the value of each duplicate key is determined by
1885 * calling the block with the key, its value in _hsh_ and its value in
1886 * _other_hash_.
1887 *
1888 * h1 = { "a" => 100, "b" => 200 }
1889 * h2 = { "b" => 254, "c" => 300 }
1890 * h1.merge!(h2) #=> {"a"=>100, "b"=>254, "c"=>300}
1891 *
1892 * h1 = { "a" => 100, "b" => 200 }
1893 * h2 = { "b" => 254, "c" => 300 }
1894 * h1.merge!(h2) { |key, v1, v2| v1 }
1895 * #=> {"a"=>100, "b"=>200, "c"=>300}
1896 */
1897
1898 static VALUE
1899 rb_hash_update(VALUE hash1, VALUE hash2)
1900 {
1901 rb_hash_modify(hash1);
1902 hash2 = to_hash(hash2);
1903 if (rb_block_given_p()) {
1904 rb_hash_foreach(hash2, rb_hash_update_block_i, hash1);
1905 }
1906 else {
1907 rb_hash_foreach(hash2, rb_hash_update_i, hash1);
1908 }
1909 return hash1;
1910 }
1911
1912 struct update_arg {
1913 VALUE hash;
1914 VALUE value;
1915 rb_hash_update_func *func;
1916 };
1917
1918 static int
1919 rb_hash_update_func_callback(st_data_t *key, st_data_t *value, st_data_t arg0, int existing)
1920 {
1921 struct update_arg *arg = (struct update_arg *)arg0;
1922 VALUE newvalue = arg->value;
1923 if (existing) {
1924 newvalue = (*arg->func)((VALUE)*key, (VALUE)*value, newvalue);
1925 }
1926 *value = (st_data_t)newvalue;
1927 return ST_CONTINUE;
1928 }
1929
1930 static NOINSERT_UPDATE_CALLBACK(rb_hash_update_func_callback)
1931
1932 static int
1933 rb_hash_update_func_i(VALUE key, VALUE value, VALUE arg0)
1934 {
1935 struct update_arg *arg = (struct update_arg *)arg0;
1936 VALUE hash = arg->hash;
1937
1938 arg->value = value;
1939 RHASH_UPDATE(hash, key, rb_hash_update_func_callback, arg);
1940 return ST_CONTINUE;
1941 }
1942
1943 VALUE
1944 rb_hash_update_by(VALUE hash1, VALUE hash2, rb_hash_update_func *func)
1945 {
1946 rb_hash_modify(hash1);
1947 hash2 = to_hash(hash2);
1948 if (func) {
1949 struct update_arg arg;
1950 arg.hash = hash1;
1951 arg.func = func;
1952 rb_hash_foreach(hash2, rb_hash_update_func_i, (VALUE)&arg);
1953 }
1954 else {
1955 rb_hash_foreach(hash2, rb_hash_update_i, hash1);
1956 }
1957 return hash1;
1958 }
1959
1960 /*
1961 * call-seq:
1962 * hsh.merge(other_hash) -> new_hash
1963 * hsh.merge(other_hash){|key, oldval, newval| block} -> new_hash
1964 *
1965 * Returns a new hash containing the contents of <i>other_hash</i> and
1966 * the contents of <i>hsh</i>. If no block is specified, the value for
1967 * entries with duplicate keys will be that of <i>other_hash</i>. Otherwise
1968 * the value for each duplicate key is determined by calling the block
1969 * with the key, its value in <i>hsh</i> and its value in <i>other_hash</i>.
1970 *
1971 * h1 = { "a" => 100, "b" => 200 }
1972 * h2 = { "b" => 254, "c" => 300 }
1973 * h1.merge(h2) #=> {"a"=>100, "b"=>254, "c"=>300}
1974 * h1.merge(h2){|key, oldval, newval| newval - oldval}
1975 * #=> {"a"=>100, "b"=>54, "c"=>300}
1976 * h1 #=> {"a"=>100, "b"=>200}
1977 *
1978 */
1979
1980 static VALUE
1981 rb_hash_merge(VALUE hash1, VALUE hash2)
1982 {
1983 return rb_hash_update(rb_obj_dup(hash1), hash2);
1984 }
1985
1986 static int
1987 assoc_i(VALUE key, VALUE val, VALUE arg)
1988 {
1989 VALUE *args = (VALUE *)arg;
1990
1991 if (RTEST(rb_equal(args[0], key))) {
1992 args[1] = rb_assoc_new(key, val);
1993 return ST_STOP;
1994 }
1995 return ST_CONTINUE;
1996 }
1997
1998 /*
1999 * call-seq:
2000 * hash.assoc(obj) -> an_array or nil
2001 *
2002 * Searches through the hash comparing _obj_ with the key using <code>==</code>.
2003 * Returns the key-value pair (two elements array) or +nil+
2004 * if no match is found. See <code>Array#assoc</code>.
2005 *
2006 * h = {"colors" => ["red", "blue", "green"],
2007 * "letters" => ["a", "b", "c" ]}
2008 * h.assoc("letters") #=> ["letters", ["a", "b", "c"]]
2009 * h.assoc("foo") #=> nil
2010 */
2011
2012 VALUE
2013 rb_hash_assoc(VALUE hash, VALUE obj)
2014 {
2015 VALUE args[2];
2016
2017 args[0] = obj;
2018 args[1] = Qnil;
2019 rb_hash_foreach(hash, assoc_i, (VALUE)args);
2020 return args[1];
2021 }
2022
2023 static int
2024 rassoc_i(VALUE key, VALUE val, VALUE arg)
2025 {
2026 VALUE *args = (VALUE *)arg;
2027
2028 if (RTEST(rb_equal(args[0], val))) {
2029 args[1] = rb_assoc_new(key, val);
2030 return ST_STOP;
2031 }
2032 return ST_CONTINUE;
2033 }
2034
2035 /*
2036 * call-seq:
2037 * hash.rassoc(obj) -> an_array or nil
2038 *
2039 * Searches through the hash comparing _obj_ with the value using <code>==</code>.
2040 * Returns the first key-value pair (two-element array) that matches. See
2041 * also <code>Array#rassoc</code>.
2042 *
2043 * a = {1=> "one", 2 => "two", 3 => "three", "ii" => "two"}
2044 * a.rassoc("two") #=> [2, "two"]
2045 * a.rassoc("four") #=> nil
2046 */
2047
2048 VALUE
2049 rb_hash_rassoc(VALUE hash, VALUE obj)
2050 {
2051 VALUE args[2];
2052
2053 args[0] = obj;
2054 args[1] = Qnil;
2055 rb_hash_foreach(hash, rassoc_i, (VALUE)args);
2056 return args[1];
2057 }
2058
2059 /*
2060 * call-seq:
2061 * hash.flatten -> an_array
2062 * hash.flatten(level) -> an_array
2063 *
2064 * Returns a new array that is a one-dimensional flattening of this
2065 * hash. That is, for every key or value that is an array, extract
2066 * its elements into the new array. Unlike Array#flatten, this
2067 * method does not flatten recursively by default. The optional
2068 * <i>level</i> argument determines the level of recursion to flatten.
2069 *
2070 * a = {1=> "one", 2 => [2,"two"], 3 => "three"}
2071 * a.flatten # => [1, "one", 2, [2, "two"], 3, "three"]
2072 * a.flatten(2) # => [1, "one", 2, 2, "two", 3, "three"]
2073 */
2074
2075 static VALUE
2076 rb_hash_flatten(int argc, VALUE *argv, VALUE hash)
2077 {
2078 VALUE ary, tmp;
2079
2080 ary = rb_hash_to_a(hash);
2081 if (argc == 0) {
2082 argc = 1;
2083 tmp = INT2FIX(1);
2084 argv = &tmp;
2085 }
2086 rb_funcall2(ary, rb_intern("flatten!"), argc, argv);
2087 return ary;
2088 }
2089
2090 /*
2091 * call-seq:
2092 * hsh.compare_by_identity -> hsh
2093 *
2094 * Makes <i>hsh</i> compare its keys by their identity, i.e. it
2095 * will consider exact same objects as same keys.
2096 *
2097 * h1 = { "a" => 100, "b" => 200, :c => "c" }
2098 * h1["a"] #=> 100
2099 * h1.compare_by_identity
2100 * h1.compare_by_identity? #=> true
2101 * h1["a"] #=> nil # different objects.
2102 * h1[:c] #=> "c" # same symbols are all same.
2103 *
2104 */
2105
2106 static VALUE
2107 rb_hash_compare_by_id(VALUE hash)
2108 {
2109 rb_hash_modify(hash);
2110 RHASH(hash)->ntbl->type = &identhash;
2111 rb_hash_rehash(hash);
2112 return hash;
2113 }
2114
2115 /*
2116 * call-seq:
2117 * hsh.compare_by_identity? -> true or false
2118 *
2119 * Returns <code>true</code> if <i>hsh</i> will compare its keys by
2120 * their identity. Also see <code>Hash#compare_by_identity</code>.
2121 *
2122 */
2123
2124 static VALUE
2125 rb_hash_compare_by_id_p(VALUE hash)
2126 {
2127 if (!RHASH(hash)->ntbl)
2128 return Qfalse;
2129 if (RHASH(hash)->ntbl->type == &identhash) {
2130 return Qtrue;
2131 }
2132 return Qfalse;
2133 }
2134
2135 static int path_tainted = -1;
2136
2137 static char **origenviron;
2138 #ifdef _WIN32
2139 #define GET_ENVIRON(e) ((e) = rb_w32_get_environ())
2140 #define FREE_ENVIRON(e) rb_w32_free_environ(e)
2141 static char **my_environ;
2142 #undef environ
2143 #define environ my_environ
2144 #undef getenv
2145 #define getenv(n) rb_w32_ugetenv(n)
2146 #elif defined(__APPLE__)
2147 #undef environ
2148 #define environ (*_NSGetEnviron())
2149 #define GET_ENVIRON(e) (e)
2150 #define FREE_ENVIRON(e)
2151 #else
2152 extern char **environ;
2153 #define GET_ENVIRON(e) (e)
2154 #define FREE_ENVIRON(e)
2155 #endif
2156 #ifdef ENV_IGNORECASE
2157 #define ENVMATCH(s1, s2) (STRCASECMP((s1), (s2)) == 0)
2158 #define ENVNMATCH(s1, s2, n) (STRNCASECMP((s1), (s2), (n)) == 0)
2159 #else
2160 #define ENVMATCH(n1, n2) (strcmp((n1), (n2)) == 0)
2161 #define ENVNMATCH(s1, s2, n) (memcmp((s1), (s2), (n)) == 0)
2162 #endif
2163
2164 static VALUE
2165 env_str_new(const char *ptr, long len)
2166 {
2167 #ifdef _WIN32
2168 VALUE str = rb_str_conv_enc(rb_str_new(ptr, len), rb_utf8_encoding(), rb_locale_encoding());
2169 #else
2170 VALUE str = rb_locale_str_new(ptr, len);
2171 #endif
2172
2173 rb_obj_freeze(str);
2174 return str;
2175 }
2176
2177 static VALUE
2178 env_str_new2(const char *ptr)
2179 {
2180 if (!ptr) return Qnil;
2181 return env_str_new(ptr, strlen(ptr));
2182 }
2183
2184 static VALUE
2185 env_delete(VALUE obj, VALUE name)
2186 {
2187 char *nam, *val;
2188
2189 rb_secure(4);
2190 SafeStringValue(name);
2191 nam = RSTRING_PTR(name);
2192 if (memchr(nam, '\0', RSTRING_LEN(name))) {
2193 rb_raise(rb_eArgError, "bad environment variable name");
2194 }
2195 val = getenv(nam);
2196 if (val) {
2197 VALUE value = env_str_new2(val);
2198
2199 ruby_setenv(nam, 0);
2200 if (ENVMATCH(nam, PATH_ENV)) {
2201 path_tainted = 0;
2202 }
2203 return value;
2204 }
2205 return Qnil;
2206 }
2207
2208 /*
2209 * call-seq:
2210 * ENV.delete(name) -> value
2211 * ENV.delete(name) { |name| } -> value
2212 *
2213 * Deletes the environment variable with +name+ and returns the value of the
2214 * variable. If a block is given it will be called when the named environment
2215 * does not exist.
2216 */
2217 static VALUE
2218 env_delete_m(VALUE obj, VALUE name)
2219 {
2220 VALUE val;
2221
2222 val = env_delete(obj, name);
2223 if (NIL_P(val) && rb_block_given_p()) rb_yield(name);
2224 return val;
2225 }
2226
2227 static int env_path_tainted(const char *);
2228
2229 /*
2230 * call-seq:
2231 * ENV[name] -> value
2232 *
2233 * Retrieves the +value+ for environment variable +name+ as a String. Returns
2234 * +nil+ if the named variable does not exist.
2235 */
2236 static VALUE
2237 rb_f_getenv(VALUE obj, VALUE name)
2238 {
2239 char *nam, *env;
2240
2241 rb_secure(4);
2242 SafeStringValue(name);
2243 nam = RSTRING_PTR(name);
2244 if (memchr(nam, '\0', RSTRING_LEN(name))) {
2245 rb_raise(rb_eArgError, "bad environment variable name");
2246 }
2247 env = getenv(nam);
2248 if (env) {
2249 if (ENVMATCH(nam, PATH_ENV) && !env_path_tainted(env)) {
2250 #ifdef _WIN32
2251 VALUE str = rb_str_conv_enc(rb_str_new(env, strlen(env)), rb_utf8_encoding(), rb_filesystem_encoding());
2252 #else
2253 VALUE str = rb_filesystem_str_new_cstr(env);
2254 #endif
2255
2256 rb_obj_freeze(str);
2257 return str;
2258 }
2259 return env_str_new2(env);
2260 }
2261 return Qnil;
2262 }
2263
2264 /*
2265 * :yield: missing_name
2266 * call-seq:
2267 * ENV.fetch(name) -> value
2268 * ENV.fetch(name, default) -> value
2269 * ENV.fetch(name) { |missing_name| ... } -> value
2270 *
2271 * Retrieves the environment variable +name+.
2272 *
2273 * If the given name does not exist and neither +default+ nor a block a
2274 * provided an IndexError is raised. If a block is given it is called with
2275 * the missing name to provide a value. If a default value is given it will
2276 * be returned when no block is given.
2277 */
2278 static VALUE
2279 env_fetch(int argc, VALUE *argv)
2280 {
2281 VALUE key, if_none;
2282 long block_given;
2283 char *nam, *env;
2284
2285 rb_secure(4);
2286 rb_scan_args(argc, argv, "11", &key, &if_none);
2287 block_given = rb_block_given_p();
2288 if (block_given && argc == 2) {
2289 rb_warn("block supersedes default value argument");
2290 }
2291 SafeStringValue(key);
2292 nam = RSTRING_PTR(key);
2293 if (memchr(nam, '\0', RSTRING_LEN(key))) {
2294 rb_raise(rb_eArgError, "bad environment variable name");
2295 }
2296 env = getenv(nam);
2297 if (!env) {
2298 if (block_given) return rb_yield(key);
2299 if (argc == 1) {
2300 rb_raise(rb_eKeyError, "key not found");
2301 }
2302 return if_none;
2303 }
2304 if (ENVMATCH(nam, PATH_ENV) && !env_path_tainted(env))
2305 #ifdef _WIN32
2306 return rb_str_conv_enc(rb_str_new(env, strlen(env)), rb_utf8_encoding(), rb_filesystem_encoding());
2307 #else
2308 return rb_filesystem_str_new_cstr(env);
2309 #endif
2310 return env_str_new2(env);
2311 }
2312
2313 static void
2314 path_tainted_p(const char *path)
2315 {
2316 path_tainted = rb_path_check(path)?0:1;
2317 }
2318
2319 static int
2320 env_path_tainted(const char *path)
2321 {
2322 if (path_tainted < 0) {
2323 path_tainted_p(path);
2324 }
2325 return path_tainted;
2326 }
2327
2328 int
2329 rb_env_path_tainted(void)
2330 {
2331 if (path_tainted < 0) {
2332 path_tainted_p(getenv(PATH_ENV));
2333 }
2334 return path_tainted;
2335 }
2336
2337 #if defined(_WIN32) || (defined(HAVE_SETENV) && defined(HAVE_UNSETENV))
2338 #elif defined __sun
2339 static int
2340 in_origenv(const char *str)
2341 {
2342 char **env;
2343 for (env = origenviron; *env; ++env) {
2344 if (*env == str) return 1;
2345 }
2346 return 0;
2347 }
2348 #else
2349 static int
2350 envix(const char *nam)
2351 {
2352 register int i, len = strlen(nam);
2353 char **env;
2354
2355 env = GET_ENVIRON(environ);
2356 for (i = 0; env[i]; i++) {
2357 if (ENVNMATCH(env[i],nam,len) && env[i][len] == '=')
2358 break; /* memcmp must come first to avoid */
2359 } /* potential SEGV's */
2360 FREE_ENVIRON(environ);
2361 return i;
2362 }
2363 #endif
2364
2365 #if defined(_WIN32)
2366 static size_t
2367 getenvsize(const char* p)
2368 {
2369 const char* porg = p;
2370 while (*p++) p += strlen(p) + 1;
2371 return p - porg + 1;
2372 }
2373 static size_t
2374 getenvblocksize()
2375 {
2376 return (rb_w32_osver() >= 5) ? 32767 : 5120;
2377 }
2378 #endif
2379
2380 void
2381 ruby_setenv(const char *name, const char *value)
2382 {
2383 #if defined(_WIN32)
2384 VALUE buf;
2385 int failed = 0;
2386 if (strchr(name, '=')) {
2387 fail:
2388 errno = EINVAL;
2389 rb_sys_fail("ruby_setenv");
2390 }
2391 if (value) {
2392 const char* p = GetEnvironmentStringsA();
2393 if (!p) goto fail; /* never happen */
2394 if (strlen(name) + 2 + strlen(value) + getenvsize(p) >= getenvblocksize()) {
2395 goto fail; /* 2 for '=' & '\0' */
2396 }
2397 buf = rb_sprintf("%s=%s", name, value);
2398 }
2399 else {
2400 buf = rb_sprintf("%s=", name);
2401 }
2402 failed = putenv(RSTRING_PTR(buf));
2403 /* even if putenv() failed, clean up and try to delete the
2404 * variable from the system area. */
2405 rb_str_resize(buf, 0);
2406 if (!value || !*value) {
2407 /* putenv() doesn't handle empty value */
2408 if (!SetEnvironmentVariable(name, value) &&
2409 GetLastError() != ERROR_ENVVAR_NOT_FOUND) goto fail;
2410 }
2411 if (failed) goto fail;
2412 #elif defined(HAVE_SETENV) && defined(HAVE_UNSETENV)
2413 #undef setenv
2414 #undef unsetenv
2415 if (value) {
2416 if (setenv(name, value, 1))
2417 rb_sys_fail("setenv");
2418 } else {
2419 #ifdef VOID_UNSETENV
2420 unsetenv(name);
2421 #else
2422 if (unsetenv(name))
2423 rb_sys_fail("unsetenv");
2424 #endif
2425 }
2426 #elif defined __sun
2427 size_t len;
2428 char **env_ptr, *str;
2429 if (strchr(name, '=')) {
2430 errno = EINVAL;
2431 rb_sys_fail("ruby_setenv");
2432 }
2433 len = strlen(name);
2434 for (env_ptr = GET_ENVIRON(environ); (str = *env_ptr) != 0; ++env_ptr) {
2435 if (!strncmp(str, name, len) && str[len] == '=') {
2436 if (!in_origenv(str)) free(str);
2437 while ((env_ptr[0] = env_ptr[1]) != 0) env_ptr++;
2438 break;
2439 }
2440 }
2441 if (value) {
2442 str = malloc(len += strlen(value) + 2);
2443 snprintf(str, len, "%s=%s", name, value);
2444 if (putenv(str))
2445 rb_sys_fail("putenv");
2446 }
2447 #else /* WIN32 */
2448 size_t len;
2449 int i;
2450 if (strchr(name, '=')) {
2451 errno = EINVAL;
2452 rb_sys_fail("ruby_setenv");
2453 }
2454 i=envix(name); /* where does it go? */
2455
2456 if (environ == origenviron) { /* need we copy environment? */
2457 int j;
2458 int max;
2459 char **tmpenv;
2460
2461 for (max = i; environ[max]; max++) ;
2462 tmpenv = ALLOC_N(char*, max+2);
2463 for (j=0; j<max; j++) /* copy environment */
2464 tmpenv[j] = ruby_strdup(environ[j]);
2465 tmpenv[max] = 0;
2466 environ = tmpenv; /* tell exec where it is now */
2467 }
2468 if (environ[i]) {
2469 char **envp = origenviron;
2470 while (*envp && *envp != environ[i]) envp++;
2471 if (!*envp)
2472 xfree(environ[i]);
2473 if (!value) {
2474 while (environ[i]) {
2475 environ[i] = environ[i+1];
2476 i++;
2477 }
2478 return;
2479 }
2480 }
2481 else { /* does not exist yet */
2482 if (!value) return;
2483 REALLOC_N(environ, char*, i+2); /* just expand it a bit */
2484 environ[i+1] = 0; /* make sure it's null terminated */
2485 }
2486 len = strlen(name) + strlen(value) + 2;
2487 environ[i] = ALLOC_N(char, len);
2488 snprintf(environ[i],len,"%s=%s",name,value); /* all that work just for this */
2489 #endif /* WIN32 */
2490 }
2491
2492 void
2493 ruby_unsetenv(const char *name)
2494 {
2495 ruby_setenv(name, 0);
2496 }
2497
2498 /*
2499 * call-seq:
2500 * ENV[name] = value
2501 * ENV.store(name, value) -> value
2502 *
2503 * Sets the environment variable +name+ to +value+. If the value given is
2504 * +nil+ the environment variable is deleted.
2505 *
2506 */
2507 static VALUE
2508 env_aset(VALUE obj, VALUE nm, VALUE val)
2509 {
2510 char *name, *value;
2511
2512 if (rb_safe_level() >= 4) {
2513 rb_raise(rb_eSecurityError, "can't change environment variable");
2514 }
2515
2516 if (NIL_P(val)) {
2517 env_delete(obj, nm);
2518 return Qnil;
2519 }
2520 StringValue(nm);
2521 StringValue(val);
2522 name = RSTRING_PTR(nm);
2523 value = RSTRING_PTR(val);
2524 if (memchr(name, '\0', RSTRING_LEN(nm)))
2525 rb_raise(rb_eArgError, "bad environment variable name");
2526 if (memchr(value, '\0', RSTRING_LEN(val)))
2527 rb_raise(rb_eArgError, "bad environment variable value");
2528
2529 ruby_setenv(name, value);
2530 if (ENVMATCH(name, PATH_ENV)) {
2531 if (OBJ_TAINTED(val)) {
2532 /* already tainted, no check */
2533 path_tainted = 1;
2534 return val;
2535 }
2536 else {
2537 path_tainted_p(value);
2538 }
2539 }
2540 return val;
2541 }
2542
2543 /*
2544 * call-seq:
2545 * ENV.keys -> Array
2546 *
2547 * Returns every environment variable name in an Array
2548 */
2549 static VALUE
2550 env_keys(void)
2551 {
2552 char **env;
2553 VALUE ary;
2554
2555 rb_secure(4);
2556 ary = rb_ary_new();
2557 env = GET_ENVIRON(environ);
2558 while (*env) {
2559 char *s = strchr(*env, '=');
2560 if (s) {
2561 rb_ary_push(ary, env_str_new(*env, s-*env));
2562 }
2563 env++;
2564 }
2565 FREE_ENVIRON(environ);
2566 return ary;
2567 }
2568
2569 static VALUE
2570 rb_env_size(VALUE ehash)
2571 {
2572 char **env;
2573 long cnt = 0;
2574
2575 rb_secure(4);
2576
2577 env = GET_ENVIRON(environ);
2578 for (; *env ; ++env) {
2579 if (strchr(*env, '=')) {
2580 cnt++;
2581 }
2582 }
2583 FREE_ENVIRON(environ);
2584 return LONG2FIX(cnt);
2585 }
2586
2587 /*
2588 * call-seq:
2589 * ENV.each_key { |name| } -> Hash
2590 * ENV.each_key -> Enumerator
2591 *
2592 * Yields each environment variable name.
2593 *
2594 * An Enumerator is returned if no block is given.
2595 */
2596 static VALUE
2597 env_each_key(VALUE ehash)
2598 {
2599 VALUE keys;
2600 long i;
2601
2602 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
2603 keys = env_keys(); /* rb_secure(4); */
2604 for (i=0; i<RARRAY_LEN(keys); i++) {
2605 rb_yield(RARRAY_PTR(keys)[i]);
2606 }
2607 return ehash;
2608 }
2609
2610 /*
2611 * call-seq:
2612 * ENV.values -> Array
2613 *
2614 * Returns every environment variable value as an Array
2615 */
2616 static VALUE
2617 env_values(void)
2618 {
2619 VALUE ary;
2620 char **env;
2621
2622 rb_secure(4);
2623 ary = rb_ary_new();
2624 env = GET_ENVIRON(environ);
2625 while (*env) {
2626 char *s = strchr(*env, '=');
2627 if (s) {
2628 rb_ary_push(ary, env_str_new2(s+1));
2629 }
2630 env++;
2631 }
2632 FREE_ENVIRON(environ);
2633 return ary;
2634 }
2635
2636 /*
2637 * call-seq:
2638 * ENV.each_value { |value| } -> Hash
2639 * ENV.each_value -> Enumerator
2640 *
2641 * Yields each environment variable +value+.
2642 *
2643 * An Enumerator is returned if no block was given.
2644 */
2645 static VALUE
2646 env_each_value(VALUE ehash)
2647 {
2648 VALUE values;
2649 long i;
2650
2651 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
2652 values = env_values(); /* rb_secure(4); */
2653 for (i=0; i<RARRAY_LEN(values); i++) {
2654 rb_yield(RARRAY_PTR(values)[i]);
2655 }
2656 return ehash;
2657 }
2658
2659 /*
2660 * call-seq:
2661 * ENV.each { |name, value| } -> Hash
2662 * ENV.each -> Enumerator
2663 * ENV.each_pair { |name, value| } -> Hash
2664 * ENV.each_pair -> Enumerator
2665 *
2666 * Yields each environment variable +name+ and +value+.
2667 *
2668 * If no block is given an Enumerator is returned.
2669 */
2670 static VALUE
2671 env_each_pair(VALUE ehash)
2672 {
2673 char **env;
2674 VALUE ary;
2675 long i;
2676
2677 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
2678
2679 rb_secure(4);
2680 ary = rb_ary_new();
2681 env = GET_ENVIRON(environ);
2682 while (*env) {
2683 char *s = strchr(*env, '=');
2684 if (s) {
2685 rb_ary_push(ary, env_str_new(*env, s-*env));
2686 rb_ary_push(ary, env_str_new2(s+1));
2687 }
2688 env++;
2689 }
2690 FREE_ENVIRON(environ);
2691
2692 for (i=0; i<RARRAY_LEN(ary); i+=2) {
2693 rb_yield(rb_assoc_new(RARRAY_PTR(ary)[i], RARRAY_PTR(ary)[i+1]));
2694 }
2695 return ehash;
2696 }
2697
2698 /*
2699 * call-seq:
2700 * ENV.reject! { |name, value| } -> ENV or nil
2701 * ENV.reject! -> Enumerator
2702 *
2703 * Equivalent to ENV#delete_if but returns +nil+ if no changes were made.
2704 *
2705 * Returns an Enumerator if no block was given.
2706 */
2707 static VALUE
2708 env_reject_bang(VALUE ehash)
2709 {
2710 volatile VALUE keys;
2711 long i;
2712 int del = 0;
2713
2714 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
2715 keys = env_keys(); /* rb_secure(4); */
2716 RBASIC(keys)->klass = 0;
2717 for (i=0; i<RARRAY_LEN(keys); i++) {
2718 VALUE val = rb_f_getenv(Qnil, RARRAY_PTR(keys)[i]);
2719 if (!NIL_P(val)) {
2720 if (RTEST(rb_yield_values(2, RARRAY_PTR(keys)[i], val))) {
2721 FL_UNSET(RARRAY_PTR(keys)[i], FL_TAINT);
2722 env_delete(Qnil, RARRAY_PTR(keys)[i]);
2723 del++;
2724 }
2725 }
2726 }
2727 if (del == 0) return Qnil;
2728 return envtbl;
2729 }
2730
2731 /*
2732 * call-seq:
2733 * ENV.delete_if { |name, value| } -> Hash
2734 * ENV.delete_if -> Enumerator
2735 *
2736 * Deletes every environment variable for which the block evaluates to +true+.
2737 *
2738 * If no block is given an enumerator is returned instead.
2739 */
2740 static VALUE
2741 env_delete_if(VALUE ehash)
2742 {
2743 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
2744 env_reject_bang(ehash);
2745 return envtbl;
2746 }
2747
2748 /*
2749 * call-seq:
2750 * ENV.values_at(name, ...) -> Array
2751 *
2752 * Returns an array containing the environment variable values associated with
2753 * the given names. See also ENV.select.
2754 */
2755 static VALUE
2756 env_values_at(int argc, VALUE *argv)
2757 {
2758 VALUE result;
2759 long i;
2760
2761 rb_secure(4);
2762 result = rb_ary_new();
2763 for (i=0; i<argc; i++) {
2764 rb_ary_push(result, rb_f_getenv(Qnil, argv[i]));
2765 }
2766 return result;
2767 }
2768
2769 /*
2770 * call-seq:
2771 * ENV.select { |name, value| } -> Hash
2772 * ENV.select -> Enumerator
2773 *
2774 * Returns a copy of the environment for entries where the block returns true.
2775 *
2776 * Returns an Enumerator if no block was given.
2777 */
2778 static VALUE
2779 env_select(VALUE ehash)
2780 {
2781 VALUE result;
2782 char **env;
2783
2784 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
2785 rb_secure(4);
2786 result = rb_hash_new();
2787 env = GET_ENVIRON(environ);
2788 while (*env) {
2789 char *s = strchr(*env, '=');
2790 if (s) {
2791 VALUE k = env_str_new(*env, s-*env);
2792 VALUE v = env_str_new2(s+1);
2793 if (RTEST(rb_yield_values(2, k, v))) {
2794 rb_hash_aset(result, k, v);
2795 }
2796 }
2797 env++;
2798 }
2799 FREE_ENVIRON(environ);
2800
2801 return result;
2802 }
2803
2804 /*
2805 * call-seq:
2806 * ENV.select! { |name, value| } -> ENV or nil
2807 * ENV.select! -> Enumerator
2808 *
2809 * Equivalent to ENV#keep_if but returns +nil+ if no changes were made.
2810 */
2811 static VALUE
2812 env_select_bang(VALUE ehash)
2813 {
2814 volatile VALUE keys;
2815 long i;
2816 int del = 0;
2817
2818 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
2819 keys = env_keys(); /* rb_secure(4); */
2820 RBASIC(keys)->klass = 0;
2821 for (i=0; i<RARRAY_LEN(keys); i++) {
2822 VALUE val = rb_f_getenv(Qnil, RARRAY_PTR(keys)[i]);
2823 if (!NIL_P(val)) {
2824 if (!RTEST(rb_yield_values(2, RARRAY_PTR(keys)[i], val))) {
2825 FL_UNSET(RARRAY_PTR(keys)[i], FL_TAINT);
2826 env_delete(Qnil, RARRAY_PTR(keys)[i]);
2827 del++;
2828 }
2829 }
2830 }
2831 if (del == 0) return Qnil;
2832 return envtbl;
2833 }
2834
2835 /*
2836 * call-seq:
2837 * ENV.keep_if { |name, value| } -> Hash
2838 * ENV.keep_if -> Enumerator
2839 *
2840 * Deletes every environment variable where the block evaluates to +false+.
2841 *
2842 * Returns an enumerator if no block was given.
2843 */
2844 static VALUE
2845 env_keep_if(VALUE ehash)
2846 {
2847 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
2848 env_select_bang(ehash);
2849 return envtbl;
2850 }
2851
2852 /*
2853 * call-seq:
2854 * ENV.clear
2855 *
2856 * Removes every environment variable.
2857 */
2858 VALUE
2859 rb_env_clear(void)
2860 {
2861 volatile VALUE keys;
2862 long i;
2863
2864 keys = env_keys(); /* rb_secure(4); */
2865 for (i=0; i<RARRAY_LEN(keys); i++) {
2866 VALUE val = rb_f_getenv(Qnil, RARRAY_PTR(keys)[i]);
2867 if (!NIL_P(val)) {
2868 env_delete(Qnil, RARRAY_PTR(keys)[i]);
2869 }
2870 }
2871 return envtbl;
2872 }
2873
2874 /*
2875 * call-seq:
2876 * ENV.to_s -> "ENV"
2877 *
2878 * Returns "ENV"
2879 */
2880 static VALUE
2881 env_to_s(void)
2882 {
2883 return rb_usascii_str_new2("ENV");
2884 }
2885
2886 /*
2887 * call-seq:
2888 * ENV.inspect -> string
2889 *
2890 * Returns the contents of the environment as a String.
2891 */
2892 static VALUE
2893 env_inspect(void)
2894 {
2895 char **env;
2896 VALUE str, i;
2897
2898 rb_secure(4);
2899 str = rb_str_buf_new2("{");
2900 env = GET_ENVIRON(environ);
2901 while (*env) {
2902 char *s = strchr(*env, '=');
2903
2904 if (env != environ) {
2905 rb_str_buf_cat2(str, ", ");
2906 }
2907 if (s) {
2908 rb_str_buf_cat2(str, "\"");
2909 rb_str_buf_cat(str, *env, s-*env);
2910 rb_str_buf_cat2(str, "\"=>");
2911 i = rb_inspect(rb_str_new2(s+1));
2912 rb_str_buf_append(str, i);
2913 }
2914 env++;
2915 }
2916 FREE_ENVIRON(environ);
2917 rb_str_buf_cat2(str, "}");
2918 OBJ_TAINT(str);
2919
2920 return str;
2921 }
2922
2923 /*
2924 * call-seq:
2925 * ENV.to_a -> Array
2926 *
2927 * Converts the environment variables into an array of names and value arrays.
2928 *
2929 * ENV.to_a # => [["TERM", "xterm-color"], ["SHELL", "/bin/bash"], ...]
2930 *
2931 */
2932 static VALUE
2933 env_to_a(void)
2934 {
2935 char **env;
2936 VALUE ary;
2937
2938 rb_secure(4);
2939 ary = rb_ary_new();
2940 env = GET_ENVIRON(environ);
2941 while (*env) {
2942 char *s = strchr(*env, '=');
2943 if (s) {
2944 rb_ary_push(ary, rb_assoc_new(env_str_new(*env, s-*env),
2945 env_str_new2(s+1)));
2946 }
2947 env++;
2948 }
2949 FREE_ENVIRON(environ);
2950 return ary;
2951 }
2952
2953 /*
2954 * call-seq:
2955 * ENV.rehash
2956 *
2957 * Re-hashing the environment variables does nothing. It is provided for
2958 * compatibility with Hash.
2959 */
2960 static VALUE
2961 env_none(void)
2962 {
2963 return Qnil;
2964 }
2965
2966 /*
2967 * call-seq:
2968 * ENV.length
2969 * ENV.size
2970 *
2971 * Returns the number of environment variables.
2972 */
2973 static VALUE
2974 env_size(void)
2975 {
2976 int i;
2977 char **env;
2978
2979 rb_secure(4);
2980 env = GET_ENVIRON(environ);
2981 for (i=0; env[i]; i++)
2982 ;
2983 FREE_ENVIRON(environ);
2984 return INT2FIX(i);
2985 }
2986
2987 /*
2988 * call-seq:
2989 * ENV.empty? -> true or false
2990 *
2991 * Returns true when there are no environment variables
2992 */
2993 static VALUE
2994 env_empty_p(void)
2995 {
2996 char **env;
2997
2998 rb_secure(4);
2999 env = GET_ENVIRON(environ);
3000 if (env[0] == 0) {
3001 FREE_ENVIRON(environ);
3002 return Qtrue;
3003 }
3004 FREE_ENVIRON(environ);
3005 return Qfalse;
3006 }
3007
3008 /*
3009 * call-seq:
3010 * ENV.key?(name) -> true or false
3011 * ENV.include?(name) -> true or false
3012 * ENV.has_key?(name) -> true or false
3013 * ENV.member?(name) -> true or false
3014 *
3015 * Returns +true+ if there is an environment variable with the given +name+.
3016 */
3017 static VALUE
3018 env_has_key(VALUE env, VALUE key)
3019 {
3020 char *s;
3021
3022 rb_secure(4);
3023 s = StringValuePtr(key);
3024 if (memchr(s, '\0', RSTRING_LEN(key)))
3025 rb_raise(rb_eArgError, "bad environment variable name");
3026 if (getenv(s)) return Qtrue;
3027 return Qfalse;
3028 }
3029
3030 /*
3031 * call-seq:
3032 * ENV.assoc(name) -> Array or nil
3033 *
3034 * Returns an Array of the name and value of the environment variable with
3035 * +name+ or +nil+ if the name cannot be found.
3036 */
3037 static VALUE
3038 env_assoc(VALUE env, VALUE key)
3039 {
3040 char *s, *e;
3041
3042 rb_secure(4);
3043 s = StringValuePtr(key);
3044 if (memchr(s, '\0', RSTRING_LEN(key)))
3045 rb_raise(rb_eArgError, "bad environment variable name");
3046 e = getenv(s);
3047 if (e) return rb_assoc_new(key, rb_tainted_str_new2(e));
3048 return Qnil;
3049 }
3050
3051 /*
3052 * call-seq:
3053 * ENV.value?(value) -> true or false
3054 * ENV.has_value?(value) -> true or false
3055 *
3056 * Returns +true+ if there is an environment variable with the given +value+.
3057 */
3058 static VALUE
3059 env_has_value(VALUE dmy, VALUE obj)
3060 {
3061 char **env;
3062
3063 rb_secure(4);
3064 obj = rb_check_string_type(obj);
3065 if (NIL_P(obj)) return Qnil;
3066 env = GET_ENVIRON(environ);
3067 while (*env) {
3068 char *s = strchr(*env, '=');
3069 if (s++) {
3070 long len = strlen(s);
3071 if (RSTRING_LEN(obj) == len && strncmp(s, RSTRING_PTR(obj), len) == 0) {
3072 FREE_ENVIRON(environ);
3073 return Qtrue;
3074 }
3075 }
3076 env++;
3077 }
3078 FREE_ENVIRON(environ);
3079 return Qfalse;
3080 }
3081
3082 /*
3083 * call-seq:
3084 * ENV.rassoc(value)
3085 *
3086 * Returns an Array of the name and value of the environment variable with
3087 * +value+ or +nil+ if the value cannot be found.
3088 */
3089 static VALUE
3090 env_rassoc(VALUE dmy, VALUE obj)
3091 {
3092 char **env;
3093
3094 rb_secure(4);
3095 obj = rb_check_string_type(obj);
3096 if (NIL_P(obj)) return Qnil;
3097 env = GET_ENVIRON(environ);
3098 while (*env) {
3099 char *s = strchr(*env, '=');
3100 if (s++) {
3101 long len = strlen(s);
3102 if (RSTRING_LEN(obj) == len && strncmp(s, RSTRING_PTR(obj), len) == 0) {
3103 VALUE result = rb_assoc_new(rb_tainted_str_new(*env, s-*env-1), obj);
3104 FREE_ENVIRON(environ);
3105 return result;
3106 }
3107 }
3108 env++;
3109 }
3110 FREE_ENVIRON(environ);
3111 return Qnil;
3112 }
3113
3114 /*
3115 * call-seq:
3116 * ENV.key(value) -> name
3117 *
3118 * Returns the name of the environment variable with +value+. If the value is
3119 * not found +nil+ is returned.
3120 */
3121 static VALUE
3122 env_key(VALUE dmy, VALUE value)
3123 {
3124 char **env;
3125 VALUE str;
3126
3127 rb_secure(4);
3128 StringValue(value);
3129 env = GET_ENVIRON(environ);
3130 while (*env) {
3131 char *s = strchr(*env, '=');
3132 if (s++) {
3133 long len = strlen(s);
3134 if (RSTRING_LEN(value) == len && strncmp(s, RSTRING_PTR(value), len) == 0) {
3135 str = env_str_new(*env, s-*env-1);
3136 FREE_ENVIRON(environ);
3137 return str;
3138 }
3139 }
3140 env++;
3141 }
3142 FREE_ENVIRON(environ);
3143 return Qnil;
3144 }
3145
3146 /*
3147 * call-seq:
3148 * ENV.index(value) -> key
3149 *
3150 * Deprecated method that is equivalent to ENV.key
3151 */
3152 static VALUE
3153 env_index(VALUE dmy, VALUE value)
3154 {
3155 rb_warn("ENV.index is deprecated; use ENV.key");
3156 return env_key(dmy, value);
3157 }
3158
3159 /*
3160 * call-seq:
3161 * ENV.to_hash -> hash
3162 * ENV.to_h -> hash
3163 *
3164 * Creates a hash with a copy of the environment variables.
3165 *
3166 */
3167 static VALUE
3168 env_to_hash(void)
3169 {
3170 char **env;
3171 VALUE hash;
3172
3173 rb_secure(4);
3174 hash = rb_hash_new();
3175 env = GET_ENVIRON(environ);
3176 while (*env) {
3177 char *s = strchr(*env, '=');
3178 if (s) {
3179 rb_hash_aset(hash, env_str_new(*env, s-*env),
3180 env_str_new2(s+1));
3181 }
3182 env++;
3183 }
3184 FREE_ENVIRON(environ);
3185 return hash;
3186 }
3187
3188 /*
3189 * call-seq:
3190 * ENV.reject { |name, value| } -> Hash
3191 * ENV.reject -> Enumerator
3192 *
3193 * Same as ENV#delete_if, but works on (and returns) a copy of the
3194 * environment.
3195 */
3196 static VALUE
3197 env_reject(void)
3198 {
3199 return rb_hash_delete_if(env_to_hash());
3200 }
3201
3202 /*
3203 * call-seq:
3204 * ENV.shift -> Array or nil
3205 *
3206 * Removes an environment variable name-value pair from ENV and returns it as
3207 * an Array. Returns +nil+ if when the environment is empty.
3208 */
3209 static VALUE
3210 env_shift(void)
3211 {
3212 char **env;
3213
3214 rb_secure(4);
3215 env = GET_ENVIRON(environ);
3216 if (*env) {
3217 char *s = strchr(*env, '=');
3218 if (s) {
3219 VALUE key = env_str_new(*env, s-*env);
3220 VALUE val = env_str_new2(getenv(RSTRING_PTR(key)));
3221 env_delete(Qnil, key);
3222 return rb_assoc_new(key, val);
3223 }
3224 }
3225 FREE_ENVIRON(environ);
3226 return Qnil;
3227 }
3228
3229 /*
3230 * call-seq:
3231 * ENV.invert -> Hash
3232 *
3233 * Returns a new hash created by using environment variable names as values
3234 * and values as names.
3235 */
3236 static VALUE
3237 env_invert(void)
3238 {
3239 return rb_hash_invert(env_to_hash());
3240 }
3241
3242 static int
3243 env_replace_i(VALUE key, VALUE val, VALUE keys)
3244 {
3245 env_aset(Qnil, key, val);
3246 if (rb_ary_includes(keys, key)) {
3247 rb_ary_delete(keys, key);
3248 }
3249 return ST_CONTINUE;
3250 }
3251
3252 /*
3253 * call-seq:
3254 * ENV.replace(hash) -> env
3255 *
3256 * Replaces the contents of the environment variables with the contents of
3257 * +hash+.
3258 */
3259 static VALUE
3260 env_replace(VALUE env, VALUE hash)
3261 {
3262 volatile VALUE keys;
3263 long i;
3264
3265 keys = env_keys(); /* rb_secure(4); */
3266 if (env == hash) return env;
3267 hash = to_hash(hash);
3268 rb_hash_foreach(hash, env_replace_i, keys);
3269
3270 for (i=0; i<RARRAY_LEN(keys); i++) {
3271 env_delete(env, RARRAY_PTR(keys)[i]);
3272 }
3273 return env;
3274 }
3275
3276 static int
3277 env_update_i(VALUE key, VALUE val)
3278 {
3279 if (rb_block_given_p()) {
3280 val = rb_yield_values(3, key, rb_f_getenv(Qnil, key), val);
3281 }
3282 env_aset(Qnil, key, val);
3283 return ST_CONTINUE;
3284 }
3285
3286 /*
3287 * call-seq:
3288 * ENV.update(hash) -> Hash
3289 * ENV.update(hash) { |name, old_value, new_value| } -> Hash
3290 *
3291 * Adds the contents of +hash+ to the environment variables. If no block is
3292 * specified entries with duplicate keys are overwritten, otherwise the value
3293 * of each duplicate name is determined by calling the block with the key, its
3294 * value from the environment and its value from the hash.
3295 */
3296 static VALUE
3297 env_update(VALUE env, VALUE hash)
3298 {
3299 rb_secure(4);
3300 if (env == hash) return env;
3301 hash = to_hash(hash);
3302 rb_hash_foreach(hash, env_update_i, 0);
3303 return env;
3304 }
3305
3306 /*
3307 * A Hash is a dictionary-like collection of unique keys and their values.
3308 * Also called associative arrays, they are similar to Arrays, but where an
3309 * Array uses integers as its index, a Hash allows you to use any object
3310 * type.
3311 *
3312 * Hashes enumerate their values in the order that the corresponding keys
3313 * were inserted.
3314 *
3315 * A Hash can be easily created by using its implicit form:
3316 *
3317 * grades = { "Jane Doe" => 10, "Jim Doe" => 6 }
3318 *
3319 * Hashes allow an alternate syntax form when your keys are always symbols.
3320 * Instead of
3321 *
3322 * options = { :font_size => 10, :font_family => "Arial" }
3323 *
3324 * You could write it as:
3325 *
3326 * options = { font_size: 10, font_family: "Arial" }
3327 *
3328 * Each named key is a symbol you can access in hash:
3329 *
3330 * options[:font_size] # => 10
3331 *
3332 * A Hash can also be created through its ::new method:
3333 *
3334 * grades = Hash.new
3335 * grades["Dorothy Doe"] = 9
3336 *
3337 * Hashes have a <em>default value</em> that is returned when accessing
3338 * keys that do not exist in the hash. If no default is set +nil+ is used.
3339 * You can set the default value by sending it as an argument to Hash.new:
3340 *
3341 * grades = Hash.new(0)
3342 *
3343 * Or by using the #default= method:
3344 *
3345 * grades = {"Timmy Doe" => 8}
3346 * grades.default = 0
3347 *
3348 * Accessing a value in a Hash requires using its key:
3349 *
3350 * puts grades["Jane Doe"] # => 10
3351 *
3352 * === Common Uses
3353 *
3354 * Hashes are an easy way to represent data structures, such as
3355 *
3356 * books = {}
3357 * books[:matz] = "The Ruby Language"
3358 * books[:black] = "The Well-Grounded Rubyist"
3359 *
3360 * Hashes are also commonly used as a way to have named parameters in
3361 * functions. Note that no brackets are used below. If a hash is the last
3362 * argument on a method call, no braces are needed, thus creating a really
3363 * clean interface:
3364 *
3365 * Person.create(name: "John Doe", age: 27)
3366 *
3367 * def self.create(params)
3368 * @name = params[:name]
3369 * @age = params[:age]
3370 * end
3371 *
3372 * === Hash Keys
3373 *
3374 * Two objects refer to the same hash key when their <code>hash</code> value
3375 * is identical and the two objects are <code>eql?</code> to each other.
3376 *
3377 * A user-defined class may be used as a hash key if the <code>hash</code>
3378 * and <code>eql?</code> methods are overridden to provide meaningful
3379 * behavior. By default, separate instances refer to separate hash keys.
3380 *
3381 * A typical implementation of <code>hash</code> is based on the
3382 * object's data while <code>eql?</code> is usually aliased to the overridden
3383 * <code>==</code> method:
3384 *
3385 * class Book
3386 * attr_reader :author, :title
3387 *
3388 * def initialize(author, title)
3389 * @author = author
3390 * @title = title
3391 * end
3392 *
3393 * def ==(other)
3394 * self.class === other and
3395 * other.author == @author and
3396 * other.title == @title
3397 * end
3398 *
3399 * alias eql? ==
3400 *
3401 * def hash
3402 * @author.hash ^ @title.hash # XOR
3403 * end
3404 * end
3405 *
3406 * book1 = Book.new 'matz', 'Ruby in a Nutshell'
3407 * book2 = Book.new 'matz', 'Ruby in a Nutshell'
3408 *
3409 * reviews = {}
3410 *
3411 * reviews[book1] = 'Great reference!'
3412 * reviews[book2] = 'Nice and compact!'
3413 *
3414 * reviews.length #=> 1
3415 *
3416 * See also Object#hash and Object#eql?
3417 */
3418
3419 void
3420 Init_Hash(void)
3421 {
3422 #undef rb_intern
3423 #define rb_intern(str) rb_intern_const(str)
3424
3425 id_hash = rb_intern("hash");
3426 id_yield = rb_intern("yield");
3427 id_default = rb_intern("default");
3428
3429 rb_cHash = rb_define_class("Hash", rb_cObject);
3430
3431 rb_include_module(rb_cHash, rb_mEnumerable);
3432
3433 rb_define_alloc_func(rb_cHash, empty_hash_alloc);
3434 rb_define_singleton_method(rb_cHash, "[]", rb_hash_s_create, -1);
3435 rb_define_singleton_method(rb_cHash, "try_convert", rb_hash_s_try_convert, 1);
3436 rb_define_method(rb_cHash,"initialize", rb_hash_initialize, -1);
3437 rb_define_method(rb_cHash,"initialize_copy", rb_hash_initialize_copy, 1);
3438 rb_define_method(rb_cHash,"rehash", rb_hash_rehash, 0);
3439
3440 rb_define_method(rb_cHash,"to_hash", rb_hash_to_hash, 0);
3441 rb_define_method(rb_cHash,"to_h", rb_hash_to_h, 0);
3442 rb_define_method(rb_cHash,"to_a", rb_hash_to_a, 0);
3443 rb_define_method(rb_cHash,"inspect", rb_hash_inspect, 0);
3444 rb_define_alias(rb_cHash, "to_s", "inspect");
3445
3446 rb_define_method(rb_cHash,"==", rb_hash_equal, 1);
3447 rb_define_method(rb_cHash,"[]", rb_hash_aref, 1);
3448 rb_define_method(rb_cHash,"hash", rb_hash_hash, 0);
3449 rb_define_method(rb_cHash,"eql?", rb_hash_eql, 1);
3450 rb_define_method(rb_cHash,"fetch", rb_hash_fetch_m, -1);
3451 rb_define_method(rb_cHash,"[]=", rb_hash_aset, 2);
3452 rb_define_method(rb_cHash,"store", rb_hash_aset, 2);
3453 rb_define_method(rb_cHash,"default", rb_hash_default, -1);
3454 rb_define_method(rb_cHash,"default=", rb_hash_set_default, 1);
3455 rb_define_method(rb_cHash,"default_proc", rb_hash_default_proc, 0);
3456 rb_define_method(rb_cHash,"default_proc=", rb_hash_set_default_proc, 1);
3457 rb_define_method(rb_cHash,"key", rb_hash_key, 1);
3458 rb_define_method(rb_cHash,"index", rb_hash_index, 1);
3459 rb_define_method(rb_cHash,"size", rb_hash_size, 0);
3460 rb_define_method(rb_cHash,"length", rb_hash_size, 0);
3461 rb_define_method(rb_cHash,"empty?", rb_hash_empty_p, 0);
3462
3463 rb_define_method(rb_cHash,"each_value", rb_hash_each_value, 0);
3464 rb_define_method(rb_cHash,"each_key", rb_hash_each_key, 0);
3465 rb_define_method(rb_cHash,"each_pair", rb_hash_each_pair, 0);
3466 rb_define_method(rb_cHash,"each", rb_hash_each_pair, 0);
3467
3468 rb_define_method(rb_cHash,"keys", rb_hash_keys, 0);
3469 rb_define_method(rb_cHash,"values", rb_hash_values, 0);
3470 rb_define_method(rb_cHash,"values_at", rb_hash_values_at, -1);
3471
3472 rb_define_method(rb_cHash,"shift", rb_hash_shift, 0);
3473 rb_define_method(rb_cHash,"delete", rb_hash_delete, 1);
3474 rb_define_method(rb_cHash,"delete_if", rb_hash_delete_if, 0);
3475 rb_define_method(rb_cHash,"keep_if", rb_hash_keep_if, 0);
3476 rb_define_method(rb_cHash,"select", rb_hash_select, 0);
3477 rb_define_method(rb_cHash,"select!", rb_hash_select_bang, 0);
3478 rb_define_method(rb_cHash,"reject", rb_hash_reject, 0);
3479 rb_define_method(rb_cHash,"reject!", rb_hash_reject_bang, 0);
3480 rb_define_method(rb_cHash,"clear", rb_hash_clear, 0);
3481 rb_define_method(rb_cHash,"invert", rb_hash_invert, 0);
3482 rb_define_method(rb_cHash,"update", rb_hash_update, 1);
3483 rb_define_method(rb_cHash,"replace", rb_hash_replace, 1);
3484 rb_define_method(rb_cHash,"merge!", rb_hash_update, 1);
3485 rb_define_method(rb_cHash,"merge", rb_hash_merge, 1);
3486 rb_define_method(rb_cHash, "assoc", rb_hash_assoc, 1);
3487 rb_define_method(rb_cHash, "rassoc", rb_hash_rassoc, 1);
3488 rb_define_method(rb_cHash, "flatten", rb_hash_flatten, -1);
3489
3490 rb_define_method(rb_cHash,"include?", rb_hash_has_key, 1);
3491 rb_define_method(rb_cHash,"member?", rb_hash_has_key, 1);
3492 rb_define_method(rb_cHash,"has_key?", rb_hash_has_key, 1);
3493 rb_define_method(rb_cHash,"has_value?", rb_hash_has_value, 1);
3494 rb_define_method(rb_cHash,"key?", rb_hash_has_key, 1);
3495 rb_define_method(rb_cHash,"value?", rb_hash_has_value, 1);
3496
3497 rb_define_method(rb_cHash,"compare_by_identity", rb_hash_compare_by_id, 0);
3498 rb_define_method(rb_cHash,"compare_by_identity?", rb_hash_compare_by_id_p, 0);
3499
3500 /* Document-class: ENV
3501 *
3502 * ENV is a hash-like accessor for environment variables.
3503 */
3504
3505 /*
3506 * Hack to get RDoc to regard ENV as a class:
3507 * envtbl = rb_define_class("ENV", rb_cObject);
3508 */
3509 origenviron = environ;
3510 envtbl = rb_obj_alloc(rb_cObject);
3511 rb_extend_object(envtbl, rb_mEnumerable);
3512
3513 rb_define_singleton_method(envtbl,"[]", rb_f_getenv, 1);
3514 rb_define_singleton_method(envtbl,"fetch", env_fetch, -1);
3515 rb_define_singleton_method(envtbl,"[]=", env_aset, 2);
3516 rb_define_singleton_method(envtbl,"store", env_aset, 2);
3517 rb_define_singleton_method(envtbl,"each", env_each_pair, 0);
3518 rb_define_singleton_method(envtbl,"each_pair", env_each_pair, 0);
3519 rb_define_singleton_method(envtbl,"each_key", env_each_key, 0);
3520 rb_define_singleton_method(envtbl,"each_value", env_each_value, 0);
3521 rb_define_singleton_method(envtbl,"delete", env_delete_m, 1);
3522 rb_define_singleton_method(envtbl,"delete_if", env_delete_if, 0);
3523 rb_define_singleton_method(envtbl,"keep_if", env_keep_if, 0);
3524 rb_define_singleton_method(envtbl,"clear", rb_env_clear, 0);
3525 rb_define_singleton_method(envtbl,"reject", env_reject, 0);
3526 rb_define_singleton_method(envtbl,"reject!", env_reject_bang, 0);
3527 rb_define_singleton_method(envtbl,"select", env_select, 0);
3528 rb_define_singleton_method(envtbl,"select!", env_select_bang, 0);
3529 rb_define_singleton_method(envtbl,"shift", env_shift, 0);
3530 rb_define_singleton_method(envtbl,"invert", env_invert, 0);
3531 rb_define_singleton_method(envtbl,"replace", env_replace, 1);
3532 rb_define_singleton_method(envtbl,"update", env_update, 1);
3533 rb_define_singleton_method(envtbl,"inspect", env_inspect, 0);
3534 rb_define_singleton_method(envtbl,"rehash", env_none, 0);
3535 rb_define_singleton_method(envtbl,"to_a", env_to_a, 0);
3536 rb_define_singleton_method(envtbl,"to_s", env_to_s, 0);
3537 rb_define_singleton_method(envtbl,"key", env_key, 1);
3538 rb_define_singleton_method(envtbl,"index", env_index, 1);
3539 rb_define_singleton_method(envtbl,"size", env_size, 0);
3540 rb_define_singleton_method(envtbl,"length", env_size, 0);
3541 rb_define_singleton_method(envtbl,"empty?", env_empty_p, 0);
3542 rb_define_singleton_method(envtbl,"keys", env_keys, 0);
3543 rb_define_singleton_method(envtbl,"values", env_values, 0);
3544 rb_define_singleton_method(envtbl,"values_at", env_values_at, -1);
3545 rb_define_singleton_method(envtbl,"include?", env_has_key, 1);
3546 rb_define_singleton_method(envtbl,"member?", env_has_key, 1);
3547 rb_define_singleton_method(envtbl,"has_key?", env_has_key, 1);
3548 rb_define_singleton_method(envtbl,"has_value?", env_has_value, 1);
3549 rb_define_singleton_method(envtbl,"key?", env_has_key, 1);
3550 rb_define_singleton_method(envtbl,"value?", env_has_value, 1);
3551 rb_define_singleton_method(envtbl,"to_hash", env_to_hash, 0);
3552 rb_define_singleton_method(envtbl,"to_h", env_to_hash, 0);
3553 rb_define_singleton_method(envtbl,"assoc", env_assoc, 1);
3554 rb_define_singleton_method(envtbl,"rassoc", env_rassoc, 1);
3555
3556 /*
3557 * ENV is a Hash-like accessor for environment variables.
3558 *
3559 * See ENV (the class) for more details.
3560 */
3561 rb_define_global_const("ENV", envtbl);
3562 }
3563