PageRenderTime 32ms CodeModel.GetById 13ms RepoModel.GetById 8ms app.codeStats 0ms

/hash.c

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