Ruby  3.1.4p223 (2023-03-30 revision HEAD)
hash.c
1 /**********************************************************************
2 
3  hash.c -
4 
5  $Author$
6  created at: Mon Nov 22 18:51:18 JST 1993
7 
8  Copyright (C) 1993-2007 Yukihiro Matsumoto
9  Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10  Copyright (C) 2000 Information-technology Promotion Agency, Japan
11 
12 **********************************************************************/
13 
14 #include "ruby/internal/config.h"
15 
16 #include <errno.h>
17 
18 #ifdef __APPLE__
19 # ifdef HAVE_CRT_EXTERNS_H
20 # include <crt_externs.h>
21 # else
22 # include "missing/crt_externs.h"
23 # endif
24 #endif
25 
26 #include "debug_counter.h"
27 #include "id.h"
28 #include "internal.h"
29 #include "internal/array.h"
30 #include "internal/bignum.h"
31 #include "internal/class.h"
32 #include "internal/cont.h"
33 #include "internal/error.h"
34 #include "internal/hash.h"
35 #include "internal/object.h"
36 #include "internal/proc.h"
37 #include "internal/symbol.h"
38 #include "internal/time.h"
39 #include "internal/vm.h"
40 #include "probes.h"
41 #include "ruby/st.h"
42 #include "ruby/util.h"
43 #include "ruby_assert.h"
44 #include "symbol.h"
45 #include "transient_heap.h"
46 #include "ruby/thread_native.h"
47 #include "ruby/ractor.h"
48 #include "vm_sync.h"
49 
50 #ifndef HASH_DEBUG
51 #define HASH_DEBUG 0
52 #endif
53 
54 #if HASH_DEBUG
55 #include "gc.h"
56 #endif
57 
58 #define SET_DEFAULT(hash, ifnone) ( \
59  FL_UNSET_RAW(hash, RHASH_PROC_DEFAULT), \
60  RHASH_SET_IFNONE(hash, ifnone))
61 
62 #define SET_PROC_DEFAULT(hash, proc) set_proc_default(hash, proc)
63 
64 #define COPY_DEFAULT(hash, hash2) copy_default(RHASH(hash), RHASH(hash2))
65 
66 static inline void
67 copy_default(struct RHash *hash, const struct RHash *hash2)
68 {
69  hash->basic.flags &= ~RHASH_PROC_DEFAULT;
70  hash->basic.flags |= hash2->basic.flags & RHASH_PROC_DEFAULT;
71  RHASH_SET_IFNONE(hash, RHASH_IFNONE((VALUE)hash2));
72 }
73 
74 static VALUE rb_hash_s_try_convert(VALUE, VALUE);
75 
76 /*
77  * Hash WB strategy:
78  * 1. Check mutate st_* functions
79  * * st_insert()
80  * * st_insert2()
81  * * st_update()
82  * * st_add_direct()
83  * 2. Insert WBs
84  */
85 
86 VALUE
88 {
89  return rb_obj_freeze(hash);
90 }
91 
93 
94 static VALUE envtbl;
95 static ID id_hash, id_default, id_flatten_bang;
96 static ID id_hash_iter_lev;
97 
98 VALUE
100 {
101  RB_OBJ_WRITE(hash, (&RHASH(hash)->ifnone), ifnone);
102  return hash;
103 }
104 
105 static int
106 rb_any_cmp(VALUE a, VALUE b)
107 {
108  if (a == b) return 0;
109  if (RB_TYPE_P(a, T_STRING) && RBASIC(a)->klass == rb_cString &&
110  RB_TYPE_P(b, T_STRING) && RBASIC(b)->klass == rb_cString) {
111  return rb_str_hash_cmp(a, b);
112  }
113  if (a == Qundef || b == Qundef) return -1;
114  if (SYMBOL_P(a) && SYMBOL_P(b)) {
115  return a != b;
116  }
117 
118  return !rb_eql(a, b);
119 }
120 
121 static VALUE
122 hash_recursive(VALUE obj, VALUE arg, int recurse)
123 {
124  if (recurse) return INT2FIX(0);
125  return rb_funcallv(obj, id_hash, 0, 0);
126 }
127 
128 static long rb_objid_hash(st_index_t index);
129 
130 static st_index_t
131 dbl_to_index(double d)
132 {
133  union {double d; st_index_t i;} u;
134  u.d = d;
135  return u.i;
136 }
137 
138 long
139 rb_dbl_long_hash(double d)
140 {
141  /* normalize -0.0 to 0.0 */
142  if (d == 0.0) d = 0.0;
143 #if SIZEOF_INT == SIZEOF_VOIDP
144  return rb_memhash(&d, sizeof(d));
145 #else
146  return rb_objid_hash(dbl_to_index(d));
147 #endif
148 }
149 
150 static inline long
151 any_hash(VALUE a, st_index_t (*other_func)(VALUE))
152 {
153  VALUE hval;
154  st_index_t hnum;
155 
156  switch (TYPE(a)) {
157  case T_SYMBOL:
158  if (STATIC_SYM_P(a)) {
159  hnum = a >> (RUBY_SPECIAL_SHIFT + ID_SCOPE_SHIFT);
160  hnum = rb_hash_start(hnum);
161  }
162  else {
163  hnum = RSYMBOL(a)->hashval;
164  }
165  break;
166  case T_FIXNUM:
167  case T_TRUE:
168  case T_FALSE:
169  case T_NIL:
170  hnum = rb_objid_hash((st_index_t)a);
171  break;
172  case T_STRING:
173  hnum = rb_str_hash(a);
174  break;
175  case T_BIGNUM:
176  hval = rb_big_hash(a);
177  hnum = FIX2LONG(hval);
178  break;
179  case T_FLOAT: /* prevent pathological behavior: [Bug #10761] */
180  hnum = rb_dbl_long_hash(rb_float_value(a));
181  break;
182  default:
183  hnum = other_func(a);
184  }
185  if ((SIGNED_VALUE)hnum > 0)
186  hnum &= FIXNUM_MAX;
187  else
188  hnum |= FIXNUM_MIN;
189  return (long)hnum;
190 }
191 
192 static st_index_t
193 obj_any_hash(VALUE obj)
194 {
195  VALUE hval = rb_check_funcall_basic_kw(obj, id_hash, rb_mKernel, 0, 0, 0);
196 
197  if (hval == Qundef) {
198  hval = rb_exec_recursive_outer(hash_recursive, obj, 0);
199  }
200 
201  while (!FIXNUM_P(hval)) {
202  if (RB_TYPE_P(hval, T_BIGNUM)) {
203  int sign;
204  unsigned long ul;
205  sign = rb_integer_pack(hval, &ul, 1, sizeof(ul), 0,
207  if (sign < 0) {
208  hval = LONG2FIX(ul | FIXNUM_MIN);
209  }
210  else {
211  hval = LONG2FIX(ul & FIXNUM_MAX);
212  }
213  }
214  hval = rb_to_int(hval);
215  }
216 
217  return FIX2LONG(hval);
218 }
219 
220 static st_index_t
221 rb_any_hash(VALUE a)
222 {
223  return any_hash(a, obj_any_hash);
224 }
225 
226 VALUE
228 {
229  return LONG2FIX(any_hash(obj, obj_any_hash));
230 }
231 
232 
233 /* Here is a hash function for 64-bit key. It is about 5 times faster
234  (2 times faster when uint128 type is absent) on Haswell than
235  tailored Spooky or City hash function can be. */
236 
237 /* Here we two primes with random bit generation. */
238 static const uint64_t prime1 = ((uint64_t)0x2e0bb864 << 32) | 0xe9ea7df5;
239 static const uint32_t prime2 = 0x830fcab9;
240 
241 
242 static inline uint64_t
243 mult_and_mix(uint64_t m1, uint64_t m2)
244 {
245 #if defined HAVE_UINT128_T
246  uint128_t r = (uint128_t) m1 * (uint128_t) m2;
247  return (uint64_t) (r >> 64) ^ (uint64_t) r;
248 #else
249  uint64_t hm1 = m1 >> 32, hm2 = m2 >> 32;
250  uint64_t lm1 = m1, lm2 = m2;
251  uint64_t v64_128 = hm1 * hm2;
252  uint64_t v32_96 = hm1 * lm2 + lm1 * hm2;
253  uint64_t v1_32 = lm1 * lm2;
254 
255  return (v64_128 + (v32_96 >> 32)) ^ ((v32_96 << 32) + v1_32);
256 #endif
257 }
258 
259 static inline uint64_t
260 key64_hash(uint64_t key, uint32_t seed)
261 {
262  return mult_and_mix(key + seed, prime1);
263 }
264 
265 /* Should cast down the result for each purpose */
266 #define st_index_hash(index) key64_hash(rb_hash_start(index), prime2)
267 
268 static long
269 rb_objid_hash(st_index_t index)
270 {
271  return (long)st_index_hash(index);
272 }
273 
274 static st_index_t
275 objid_hash(VALUE obj)
276 {
277  VALUE object_id = rb_obj_id(obj);
278  if (!FIXNUM_P(object_id))
279  object_id = rb_big_hash(object_id);
280 
281 #if SIZEOF_LONG == SIZEOF_VOIDP
282  return (st_index_t)st_index_hash((st_index_t)NUM2LONG(object_id));
283 #elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
284  return (st_index_t)st_index_hash((st_index_t)NUM2LL(object_id));
285 #endif
286 }
287 
291 VALUE
292 rb_obj_hash(VALUE obj)
293 {
294  long hnum = any_hash(obj, objid_hash);
295  return ST2FIX(hnum);
296 }
297 
298 static const struct st_hash_type objhash = {
299  rb_any_cmp,
300  rb_any_hash,
301 };
302 
303 #define rb_ident_cmp st_numcmp
304 
305 static st_index_t
306 rb_ident_hash(st_data_t n)
307 {
308 #ifdef USE_FLONUM /* RUBY */
309  /*
310  * - flonum (on 64-bit) is pathologically bad, mix the actual
311  * float value in, but do not use the float value as-is since
312  * many integers get interpreted as 2.0 or -2.0 [Bug #10761]
313  */
314  if (FLONUM_P(n)) {
315  n ^= dbl_to_index(rb_float_value(n));
316  }
317 #endif
318 
319  return (st_index_t)st_index_hash((st_index_t)n);
320 }
321 
322 #define identhash rb_hashtype_ident
323 const struct st_hash_type rb_hashtype_ident = {
324  rb_ident_cmp,
325  rb_ident_hash,
326 };
327 
328 typedef st_index_t st_hash_t;
329 
330 /*
331  * RHASH_AR_TABLE_P(h):
332  * * as.ar == NULL or
333  * as.ar points ar_table.
334  * * as.ar is allocated by transient heap or xmalloc.
335  *
336  * !RHASH_AR_TABLE_P(h):
337  * * as.st points st_table.
338  */
339 
340 #define RHASH_AR_TABLE_MAX_BOUND RHASH_AR_TABLE_MAX_SIZE
341 
342 #define RHASH_AR_TABLE_REF(hash, n) (&RHASH_AR_TABLE(hash)->pairs[n])
343 #define RHASH_AR_CLEARED_HINT 0xff
344 
345 typedef struct ar_table_pair_struct {
346  VALUE key;
347  VALUE val;
348 } ar_table_pair;
349 
350 typedef struct ar_table_struct {
351  /* 64bit CPU: 8B * 2 * 8 = 128B */
352  ar_table_pair pairs[RHASH_AR_TABLE_MAX_SIZE];
353 } ar_table;
354 
355 size_t
356 rb_hash_ar_table_size(void)
357 {
358  return sizeof(ar_table);
359 }
360 
361 static inline st_hash_t
362 ar_do_hash(st_data_t key)
363 {
364  return (st_hash_t)rb_any_hash(key);
365 }
366 
367 static inline ar_hint_t
368 ar_do_hash_hint(st_hash_t hash_value)
369 {
370  return (ar_hint_t)hash_value;
371 }
372 
373 static inline ar_hint_t
374 ar_hint(VALUE hash, unsigned int index)
375 {
376  return RHASH(hash)->ar_hint.ary[index];
377 }
378 
379 static inline void
380 ar_hint_set_hint(VALUE hash, unsigned int index, ar_hint_t hint)
381 {
382  RHASH(hash)->ar_hint.ary[index] = hint;
383 }
384 
385 static inline void
386 ar_hint_set(VALUE hash, unsigned int index, st_hash_t hash_value)
387 {
388  ar_hint_set_hint(hash, index, ar_do_hash_hint(hash_value));
389 }
390 
391 static inline void
392 ar_clear_entry(VALUE hash, unsigned int index)
393 {
394  ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, index);
395  pair->key = Qundef;
396  ar_hint_set_hint(hash, index, RHASH_AR_CLEARED_HINT);
397 }
398 
399 static inline int
400 ar_cleared_entry(VALUE hash, unsigned int index)
401 {
402  if (ar_hint(hash, index) == RHASH_AR_CLEARED_HINT) {
403  /* RHASH_AR_CLEARED_HINT is only a hint, not mean cleared entry,
404  * so you need to check key == Qundef
405  */
406  ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, index);
407  return pair->key == Qundef;
408  }
409  else {
410  return FALSE;
411  }
412 }
413 
414 static inline void
415 ar_set_entry(VALUE hash, unsigned int index, st_data_t key, st_data_t val, st_hash_t hash_value)
416 {
417  ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, index);
418  pair->key = key;
419  pair->val = val;
420  ar_hint_set(hash, index, hash_value);
421 }
422 
423 #define RHASH_AR_TABLE_SIZE(h) (HASH_ASSERT(RHASH_AR_TABLE_P(h)), \
424  RHASH_AR_TABLE_SIZE_RAW(h))
425 
426 #define RHASH_AR_TABLE_BOUND_RAW(h) \
427  ((unsigned int)((RBASIC(h)->flags >> RHASH_AR_TABLE_BOUND_SHIFT) & \
428  (RHASH_AR_TABLE_BOUND_MASK >> RHASH_AR_TABLE_BOUND_SHIFT)))
429 
430 #define RHASH_AR_TABLE_BOUND(h) (HASH_ASSERT(RHASH_AR_TABLE_P(h)), \
431  RHASH_AR_TABLE_BOUND_RAW(h))
432 
433 #define RHASH_ST_TABLE_SET(h, s) rb_hash_st_table_set(h, s)
434 #define RHASH_TYPE(hash) (RHASH_AR_TABLE_P(hash) ? &objhash : RHASH_ST_TABLE(hash)->type)
435 
436 #define HASH_ASSERT(expr) RUBY_ASSERT_MESG_WHEN(HASH_DEBUG, expr, #expr)
437 
438 #if HASH_DEBUG
439 #define hash_verify(hash) hash_verify_(hash, __FILE__, __LINE__)
440 
441 void
442 rb_hash_dump(VALUE hash)
443 {
444  rb_obj_info_dump(hash);
445 
446  if (RHASH_AR_TABLE_P(hash)) {
447  unsigned i, n = 0, bound = RHASH_AR_TABLE_BOUND(hash);
448 
449  fprintf(stderr, " size:%u bound:%u\n",
450  RHASH_AR_TABLE_SIZE(hash), RHASH_AR_TABLE_BOUND(hash));
451 
452  for (i=0; i<bound; i++) {
453  st_data_t k, v;
454 
455  if (!ar_cleared_entry(hash, i)) {
456  char b1[0x100], b2[0x100];
457  ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
458  k = pair->key;
459  v = pair->val;
460  fprintf(stderr, " %d key:%s val:%s hint:%02x\n", i,
461  rb_raw_obj_info(b1, 0x100, k),
462  rb_raw_obj_info(b2, 0x100, v),
463  ar_hint(hash, i));
464  n++;
465  }
466  else {
467  fprintf(stderr, " %d empty\n", i);
468  }
469  }
470  }
471 }
472 
473 static VALUE
474 hash_verify_(VALUE hash, const char *file, int line)
475 {
476  HASH_ASSERT(RB_TYPE_P(hash, T_HASH));
477 
478  if (RHASH_AR_TABLE_P(hash)) {
479  unsigned i, n = 0, bound = RHASH_AR_TABLE_BOUND(hash);
480 
481  for (i=0; i<bound; i++) {
482  st_data_t k, v;
483  if (!ar_cleared_entry(hash, i)) {
484  ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
485  k = pair->key;
486  v = pair->val;
487  HASH_ASSERT(k != Qundef);
488  HASH_ASSERT(v != Qundef);
489  n++;
490  }
491  }
492  if (n != RHASH_AR_TABLE_SIZE(hash)) {
493  rb_bug("n:%u, RHASH_AR_TABLE_SIZE:%u", n, RHASH_AR_TABLE_SIZE(hash));
494  }
495  }
496  else {
497  HASH_ASSERT(RHASH_ST_TABLE(hash) != NULL);
498  HASH_ASSERT(RHASH_AR_TABLE_SIZE_RAW(hash) == 0);
499  HASH_ASSERT(RHASH_AR_TABLE_BOUND_RAW(hash) == 0);
500  }
501 
502 #if USE_TRANSIENT_HEAP
503  if (RHASH_TRANSIENT_P(hash)) {
504  volatile st_data_t MAYBE_UNUSED(key) = RHASH_AR_TABLE_REF(hash, 0)->key; /* read */
505  HASH_ASSERT(RHASH_AR_TABLE(hash) != NULL);
506  HASH_ASSERT(rb_transient_heap_managed_ptr_p(RHASH_AR_TABLE(hash)));
507  }
508 #endif
509  return hash;
510 }
511 
512 #else
513 #define hash_verify(h) ((void)0)
514 #endif
515 
516 static inline int
517 RHASH_TABLE_NULL_P(VALUE hash)
518 {
519  if (RHASH(hash)->as.ar == NULL) {
520  HASH_ASSERT(RHASH_AR_TABLE_P(hash));
521  return TRUE;
522  }
523  else {
524  return FALSE;
525  }
526 }
527 
528 static inline int
529 RHASH_TABLE_EMPTY_P(VALUE hash)
530 {
531  return RHASH_SIZE(hash) == 0;
532 }
533 
534 int
535 rb_hash_ar_table_p(VALUE hash)
536 {
537  if (FL_TEST_RAW((hash), RHASH_ST_TABLE_FLAG)) {
538  HASH_ASSERT(RHASH(hash)->as.st != NULL);
539  return FALSE;
540  }
541  else {
542  return TRUE;
543  }
544 }
545 
546 ar_table *
547 rb_hash_ar_table(VALUE hash)
548 {
549  HASH_ASSERT(RHASH_AR_TABLE_P(hash));
550  return RHASH(hash)->as.ar;
551 }
552 
553 st_table *
554 rb_hash_st_table(VALUE hash)
555 {
556  HASH_ASSERT(!RHASH_AR_TABLE_P(hash));
557  return RHASH(hash)->as.st;
558 }
559 
560 void
561 rb_hash_st_table_set(VALUE hash, st_table *st)
562 {
563  HASH_ASSERT(st != NULL);
564  FL_SET_RAW((hash), RHASH_ST_TABLE_FLAG);
565  RHASH(hash)->as.st = st;
566 }
567 
568 static void
569 hash_ar_table_set(VALUE hash, ar_table *ar)
570 {
571  HASH_ASSERT(RHASH_AR_TABLE_P(hash));
572  HASH_ASSERT((RHASH_TRANSIENT_P(hash) && ar == NULL) ? FALSE : TRUE);
573  RHASH(hash)->as.ar = ar;
574  hash_verify(hash);
575 }
576 
577 #define RHASH_SET_ST_FLAG(h) FL_SET_RAW(h, RHASH_ST_TABLE_FLAG)
578 #define RHASH_UNSET_ST_FLAG(h) FL_UNSET_RAW(h, RHASH_ST_TABLE_FLAG)
579 
580 static inline void
581 RHASH_AR_TABLE_BOUND_SET(VALUE h, st_index_t n)
582 {
583  HASH_ASSERT(RHASH_AR_TABLE_P(h));
584  HASH_ASSERT(n <= RHASH_AR_TABLE_MAX_BOUND);
585 
586  RBASIC(h)->flags &= ~RHASH_AR_TABLE_BOUND_MASK;
587  RBASIC(h)->flags |= n << RHASH_AR_TABLE_BOUND_SHIFT;
588 }
589 
590 static inline void
591 RHASH_AR_TABLE_SIZE_SET(VALUE h, st_index_t n)
592 {
593  HASH_ASSERT(RHASH_AR_TABLE_P(h));
594  HASH_ASSERT(n <= RHASH_AR_TABLE_MAX_SIZE);
595 
596  RBASIC(h)->flags &= ~RHASH_AR_TABLE_SIZE_MASK;
597  RBASIC(h)->flags |= n << RHASH_AR_TABLE_SIZE_SHIFT;
598 }
599 
600 static inline void
601 HASH_AR_TABLE_SIZE_ADD(VALUE h, st_index_t n)
602 {
603  HASH_ASSERT(RHASH_AR_TABLE_P(h));
604 
605  RHASH_AR_TABLE_SIZE_SET(h, RHASH_AR_TABLE_SIZE(h) + n);
606 
607  hash_verify(h);
608 }
609 
610 #define RHASH_AR_TABLE_SIZE_INC(h) HASH_AR_TABLE_SIZE_ADD(h, 1)
611 
612 static inline void
613 RHASH_AR_TABLE_SIZE_DEC(VALUE h)
614 {
615  HASH_ASSERT(RHASH_AR_TABLE_P(h));
616  int new_size = RHASH_AR_TABLE_SIZE(h) - 1;
617 
618  if (new_size != 0) {
619  RHASH_AR_TABLE_SIZE_SET(h, new_size);
620  }
621  else {
622  RHASH_AR_TABLE_SIZE_SET(h, 0);
623  RHASH_AR_TABLE_BOUND_SET(h, 0);
624  }
625  hash_verify(h);
626 }
627 
628 static inline void
629 RHASH_AR_TABLE_CLEAR(VALUE h)
630 {
631  RBASIC(h)->flags &= ~RHASH_AR_TABLE_SIZE_MASK;
632  RBASIC(h)->flags &= ~RHASH_AR_TABLE_BOUND_MASK;
633 
634  hash_ar_table_set(h, NULL);
635 }
636 
637 static ar_table*
638 ar_alloc_table(VALUE hash)
639 {
640  ar_table *tab = (ar_table*)rb_transient_heap_alloc(hash, sizeof(ar_table));
641 
642  if (tab != NULL) {
643  RHASH_SET_TRANSIENT_FLAG(hash);
644  }
645  else {
646  RHASH_UNSET_TRANSIENT_FLAG(hash);
647  tab = (ar_table*)ruby_xmalloc(sizeof(ar_table));
648  }
649 
650  RHASH_AR_TABLE_SIZE_SET(hash, 0);
651  RHASH_AR_TABLE_BOUND_SET(hash, 0);
652  hash_ar_table_set(hash, tab);
653 
654  return tab;
655 }
656 
657 NOINLINE(static int ar_equal(VALUE x, VALUE y));
658 
659 static int
660 ar_equal(VALUE x, VALUE y)
661 {
662  return rb_any_cmp(x, y) == 0;
663 }
664 
665 static unsigned
666 ar_find_entry_hint(VALUE hash, ar_hint_t hint, st_data_t key)
667 {
668  unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
669  const ar_hint_t *hints = RHASH(hash)->ar_hint.ary;
670 
671  /* if table is NULL, then bound also should be 0 */
672 
673  for (i = 0; i < bound; i++) {
674  if (hints[i] == hint) {
675  ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
676  if (ar_equal(key, pair->key)) {
677  RB_DEBUG_COUNTER_INC(artable_hint_hit);
678  return i;
679  }
680  else {
681 #if 0
682  static int pid;
683  static char fname[256];
684  static FILE *fp;
685 
686  if (pid != getpid()) {
687  snprintf(fname, sizeof(fname), "/tmp/ruby-armiss.%d", pid = getpid());
688  if ((fp = fopen(fname, "w")) == NULL) rb_bug("fopen");
689  }
690 
691  st_hash_t h1 = ar_do_hash(key);
692  st_hash_t h2 = ar_do_hash(pair->key);
693 
694  fprintf(fp, "miss: hash_eq:%d hints[%d]:%02x hint:%02x\n"
695  " key :%016lx %s\n"
696  " pair->key:%016lx %s\n",
697  h1 == h2, i, hints[i], hint,
698  h1, rb_obj_info(key), h2, rb_obj_info(pair->key));
699 #endif
700  RB_DEBUG_COUNTER_INC(artable_hint_miss);
701  }
702  }
703  }
704  RB_DEBUG_COUNTER_INC(artable_hint_notfound);
705  return RHASH_AR_TABLE_MAX_BOUND;
706 }
707 
708 static unsigned
709 ar_find_entry(VALUE hash, st_hash_t hash_value, st_data_t key)
710 {
711  ar_hint_t hint = ar_do_hash_hint(hash_value);
712  return ar_find_entry_hint(hash, hint, key);
713 }
714 
715 static inline void
716 ar_free_and_clear_table(VALUE hash)
717 {
718  ar_table *tab = RHASH_AR_TABLE(hash);
719 
720  if (tab) {
721  if (RHASH_TRANSIENT_P(hash)) {
722  RHASH_UNSET_TRANSIENT_FLAG(hash);
723  }
724  else {
725  ruby_xfree(RHASH_AR_TABLE(hash));
726  }
727  RHASH_AR_TABLE_CLEAR(hash);
728  }
729  HASH_ASSERT(RHASH_AR_TABLE_SIZE(hash) == 0);
730  HASH_ASSERT(RHASH_AR_TABLE_BOUND(hash) == 0);
731  HASH_ASSERT(RHASH_TRANSIENT_P(hash) == 0);
732 }
733 
734 static void
735 ar_try_convert_table(VALUE hash)
736 {
737  if (!RHASH_AR_TABLE_P(hash)) return;
738 
739  const unsigned size = RHASH_AR_TABLE_SIZE(hash);
740 
741  st_table *new_tab;
742  st_index_t i;
743 
744  if (size < RHASH_AR_TABLE_MAX_SIZE) {
745  return;
746  }
747 
748  new_tab = st_init_table_with_size(&objhash, size * 2);
749 
750  for (i = 0; i < RHASH_AR_TABLE_MAX_BOUND; i++) {
751  ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
752  st_add_direct(new_tab, pair->key, pair->val);
753  }
754  ar_free_and_clear_table(hash);
755  RHASH_ST_TABLE_SET(hash, new_tab);
756  return;
757 }
758 
759 static st_table *
760 ar_force_convert_table(VALUE hash, const char *file, int line)
761 {
762  st_table *new_tab;
763 
764  if (RHASH_ST_TABLE_P(hash)) {
765  return RHASH_ST_TABLE(hash);
766  }
767 
768  if (RHASH_AR_TABLE(hash)) {
769  unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
770 
771 #if defined(RHASH_CONVERT_TABLE_DEBUG) && RHASH_CONVERT_TABLE_DEBUG
772  rb_obj_info_dump(hash);
773  fprintf(stderr, "force_convert: %s:%d\n", file, line);
774  RB_DEBUG_COUNTER_INC(obj_hash_force_convert);
775 #endif
776 
777  new_tab = st_init_table_with_size(&objhash, RHASH_AR_TABLE_SIZE(hash));
778 
779  for (i = 0; i < bound; i++) {
780  if (ar_cleared_entry(hash, i)) continue;
781 
782  ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
783  st_add_direct(new_tab, pair->key, pair->val);
784  }
785  ar_free_and_clear_table(hash);
786  }
787  else {
788  new_tab = st_init_table(&objhash);
789  }
790  RHASH_ST_TABLE_SET(hash, new_tab);
791 
792  return new_tab;
793 }
794 
795 static ar_table *
796 hash_ar_table(VALUE hash)
797 {
798  if (RHASH_TABLE_NULL_P(hash)) {
799  ar_alloc_table(hash);
800  }
801  return RHASH_AR_TABLE(hash);
802 }
803 
804 static int
805 ar_compact_table(VALUE hash)
806 {
807  const unsigned bound = RHASH_AR_TABLE_BOUND(hash);
808  const unsigned size = RHASH_AR_TABLE_SIZE(hash);
809 
810  if (size == bound) {
811  return size;
812  }
813  else {
814  unsigned i, j=0;
815  ar_table_pair *pairs = RHASH_AR_TABLE(hash)->pairs;
816 
817  for (i=0; i<bound; i++) {
818  if (ar_cleared_entry(hash, i)) {
819  if (j <= i) j = i+1;
820  for (; j<bound; j++) {
821  if (!ar_cleared_entry(hash, j)) {
822  pairs[i] = pairs[j];
823  ar_hint_set_hint(hash, i, (st_hash_t)ar_hint(hash, j));
824  ar_clear_entry(hash, j);
825  j++;
826  goto found;
827  }
828  }
829  /* non-empty is not found */
830  goto done;
831  found:;
832  }
833  }
834  done:
835  HASH_ASSERT(i<=bound);
836 
837  RHASH_AR_TABLE_BOUND_SET(hash, size);
838  hash_verify(hash);
839  return size;
840  }
841 }
842 
843 static int
844 ar_add_direct_with_hash(VALUE hash, st_data_t key, st_data_t val, st_hash_t hash_value)
845 {
846  unsigned bin = RHASH_AR_TABLE_BOUND(hash);
847 
848  if (RHASH_AR_TABLE_SIZE(hash) >= RHASH_AR_TABLE_MAX_SIZE) {
849  return 1;
850  }
851  else {
852  if (UNLIKELY(bin >= RHASH_AR_TABLE_MAX_BOUND)) {
853  bin = ar_compact_table(hash);
854  hash_ar_table(hash);
855  }
856  HASH_ASSERT(bin < RHASH_AR_TABLE_MAX_BOUND);
857 
858  ar_set_entry(hash, bin, key, val, hash_value);
859  RHASH_AR_TABLE_BOUND_SET(hash, bin+1);
860  RHASH_AR_TABLE_SIZE_INC(hash);
861  return 0;
862  }
863 }
864 
865 static int
866 ar_general_foreach(VALUE hash, st_foreach_check_callback_func *func, st_update_callback_func *replace, st_data_t arg)
867 {
868  if (RHASH_AR_TABLE_SIZE(hash) > 0) {
869  unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
870 
871  for (i = 0; i < bound; i++) {
872  if (ar_cleared_entry(hash, i)) continue;
873 
874  ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
875  enum st_retval retval = (*func)(pair->key, pair->val, arg, 0);
876  /* pair may be not valid here because of theap */
877 
878  switch (retval) {
879  case ST_CONTINUE:
880  break;
881  case ST_CHECK:
882  case ST_STOP:
883  return 0;
884  case ST_REPLACE:
885  if (replace) {
886  VALUE key = pair->key;
887  VALUE val = pair->val;
888  retval = (*replace)(&key, &val, arg, TRUE);
889 
890  // TODO: pair should be same as pair before.
891  ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
892  pair->key = key;
893  pair->val = val;
894  }
895  break;
896  case ST_DELETE:
897  ar_clear_entry(hash, i);
898  RHASH_AR_TABLE_SIZE_DEC(hash);
899  break;
900  }
901  }
902  }
903  return 0;
904 }
905 
906 static int
907 ar_foreach_with_replace(VALUE hash, st_foreach_check_callback_func *func, st_update_callback_func *replace, st_data_t arg)
908 {
909  return ar_general_foreach(hash, func, replace, arg);
910 }
911 
912 struct functor {
913  st_foreach_callback_func *func;
914  st_data_t arg;
915 };
916 
917 static int
918 apply_functor(st_data_t k, st_data_t v, st_data_t d, int _)
919 {
920  const struct functor *f = (void *)d;
921  return f->func(k, v, f->arg);
922 }
923 
924 static int
925 ar_foreach(VALUE hash, st_foreach_callback_func *func, st_data_t arg)
926 {
927  const struct functor f = { func, arg };
928  return ar_general_foreach(hash, apply_functor, NULL, (st_data_t)&f);
929 }
930 
931 static int
932 ar_foreach_check(VALUE hash, st_foreach_check_callback_func *func, st_data_t arg,
933  st_data_t never)
934 {
935  if (RHASH_AR_TABLE_SIZE(hash) > 0) {
936  unsigned i, ret = 0, bound = RHASH_AR_TABLE_BOUND(hash);
937  enum st_retval retval;
938  st_data_t key;
939  ar_table_pair *pair;
940  ar_hint_t hint;
941 
942  for (i = 0; i < bound; i++) {
943  if (ar_cleared_entry(hash, i)) continue;
944 
945  pair = RHASH_AR_TABLE_REF(hash, i);
946  key = pair->key;
947  hint = ar_hint(hash, i);
948 
949  retval = (*func)(key, pair->val, arg, 0);
950  hash_verify(hash);
951 
952  switch (retval) {
953  case ST_CHECK: {
954  pair = RHASH_AR_TABLE_REF(hash, i);
955  if (pair->key == never) break;
956  ret = ar_find_entry_hint(hash, hint, key);
957  if (ret == RHASH_AR_TABLE_MAX_BOUND) {
958  retval = (*func)(0, 0, arg, 1);
959  return 2;
960  }
961  }
962  case ST_CONTINUE:
963  break;
964  case ST_STOP:
965  case ST_REPLACE:
966  return 0;
967  case ST_DELETE: {
968  if (!ar_cleared_entry(hash, i)) {
969  ar_clear_entry(hash, i);
970  RHASH_AR_TABLE_SIZE_DEC(hash);
971  }
972  break;
973  }
974  }
975  }
976  }
977  return 0;
978 }
979 
980 static int
981 ar_update(VALUE hash, st_data_t key,
982  st_update_callback_func *func, st_data_t arg)
983 {
984  int retval, existing;
985  unsigned bin = RHASH_AR_TABLE_MAX_BOUND;
986  st_data_t value = 0, old_key;
987  st_hash_t hash_value = ar_do_hash(key);
988 
989  if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) {
990  // `#hash` changes ar_table -> st_table
991  return -1;
992  }
993 
994  if (RHASH_AR_TABLE_SIZE(hash) > 0) {
995  bin = ar_find_entry(hash, hash_value, key);
996  existing = (bin != RHASH_AR_TABLE_MAX_BOUND) ? TRUE : FALSE;
997  }
998  else {
999  hash_ar_table(hash); /* allocate ltbl if needed */
1000  existing = FALSE;
1001  }
1002 
1003  if (existing) {
1004  ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, bin);
1005  key = pair->key;
1006  value = pair->val;
1007  }
1008  old_key = key;
1009  retval = (*func)(&key, &value, arg, existing);
1010  /* pair can be invalid here because of theap */
1011 
1012  switch (retval) {
1013  case ST_CONTINUE:
1014  if (!existing) {
1015  if (ar_add_direct_with_hash(hash, key, value, hash_value)) {
1016  return -1;
1017  }
1018  }
1019  else {
1020  ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, bin);
1021  if (old_key != key) {
1022  pair->key = key;
1023  }
1024  pair->val = value;
1025  }
1026  break;
1027  case ST_DELETE:
1028  if (existing) {
1029  ar_clear_entry(hash, bin);
1030  RHASH_AR_TABLE_SIZE_DEC(hash);
1031  }
1032  break;
1033  }
1034  return existing;
1035 }
1036 
1037 static int
1038 ar_insert(VALUE hash, st_data_t key, st_data_t value)
1039 {
1040  unsigned bin = RHASH_AR_TABLE_BOUND(hash);
1041  st_hash_t hash_value = ar_do_hash(key);
1042 
1043  if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) {
1044  // `#hash` changes ar_table -> st_table
1045  return -1;
1046  }
1047 
1048  hash_ar_table(hash); /* prepare ltbl */
1049 
1050  bin = ar_find_entry(hash, hash_value, key);
1051  if (bin == RHASH_AR_TABLE_MAX_BOUND) {
1052  if (RHASH_AR_TABLE_SIZE(hash) >= RHASH_AR_TABLE_MAX_SIZE) {
1053  return -1;
1054  }
1055  else if (bin >= RHASH_AR_TABLE_MAX_BOUND) {
1056  bin = ar_compact_table(hash);
1057  hash_ar_table(hash);
1058  }
1059  HASH_ASSERT(bin < RHASH_AR_TABLE_MAX_BOUND);
1060 
1061  ar_set_entry(hash, bin, key, value, hash_value);
1062  RHASH_AR_TABLE_BOUND_SET(hash, bin+1);
1063  RHASH_AR_TABLE_SIZE_INC(hash);
1064  return 0;
1065  }
1066  else {
1067  RHASH_AR_TABLE_REF(hash, bin)->val = value;
1068  return 1;
1069  }
1070 }
1071 
1072 static int
1073 ar_lookup(VALUE hash, st_data_t key, st_data_t *value)
1074 {
1075  if (RHASH_AR_TABLE_SIZE(hash) == 0) {
1076  return 0;
1077  }
1078  else {
1079  st_hash_t hash_value = ar_do_hash(key);
1080  if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) {
1081  // `#hash` changes ar_table -> st_table
1082  return st_lookup(RHASH_ST_TABLE(hash), key, value);
1083  }
1084  unsigned bin = ar_find_entry(hash, hash_value, key);
1085 
1086  if (bin == RHASH_AR_TABLE_MAX_BOUND) {
1087  return 0;
1088  }
1089  else {
1090  HASH_ASSERT(bin < RHASH_AR_TABLE_MAX_BOUND);
1091  if (value != NULL) {
1092  *value = RHASH_AR_TABLE_REF(hash, bin)->val;
1093  }
1094  return 1;
1095  }
1096  }
1097 }
1098 
1099 static int
1100 ar_delete(VALUE hash, st_data_t *key, st_data_t *value)
1101 {
1102  unsigned bin;
1103  st_hash_t hash_value = ar_do_hash(*key);
1104 
1105  if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) {
1106  // `#hash` changes ar_table -> st_table
1107  return st_delete(RHASH_ST_TABLE(hash), key, value);
1108  }
1109 
1110  bin = ar_find_entry(hash, hash_value, *key);
1111 
1112  if (bin == RHASH_AR_TABLE_MAX_BOUND) {
1113  if (value != 0) *value = 0;
1114  return 0;
1115  }
1116  else {
1117  if (value != 0) {
1118  ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, bin);
1119  *value = pair->val;
1120  }
1121  ar_clear_entry(hash, bin);
1122  RHASH_AR_TABLE_SIZE_DEC(hash);
1123  return 1;
1124  }
1125 }
1126 
1127 static int
1128 ar_shift(VALUE hash, st_data_t *key, st_data_t *value)
1129 {
1130  if (RHASH_AR_TABLE_SIZE(hash) > 0) {
1131  unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
1132 
1133  for (i = 0; i < bound; i++) {
1134  if (!ar_cleared_entry(hash, i)) {
1135  ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
1136  if (value != 0) *value = pair->val;
1137  *key = pair->key;
1138  ar_clear_entry(hash, i);
1139  RHASH_AR_TABLE_SIZE_DEC(hash);
1140  return 1;
1141  }
1142  }
1143  }
1144  if (value != NULL) *value = 0;
1145  return 0;
1146 }
1147 
1148 static long
1149 ar_keys(VALUE hash, st_data_t *keys, st_index_t size)
1150 {
1151  unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
1152  st_data_t *keys_start = keys, *keys_end = keys + size;
1153 
1154  for (i = 0; i < bound; i++) {
1155  if (keys == keys_end) {
1156  break;
1157  }
1158  else {
1159  if (!ar_cleared_entry(hash, i)) {
1160  *keys++ = RHASH_AR_TABLE_REF(hash, i)->key;
1161  }
1162  }
1163  }
1164 
1165  return keys - keys_start;
1166 }
1167 
1168 static long
1169 ar_values(VALUE hash, st_data_t *values, st_index_t size)
1170 {
1171  unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
1172  st_data_t *values_start = values, *values_end = values + size;
1173 
1174  for (i = 0; i < bound; i++) {
1175  if (values == values_end) {
1176  break;
1177  }
1178  else {
1179  if (!ar_cleared_entry(hash, i)) {
1180  *values++ = RHASH_AR_TABLE_REF(hash, i)->val;
1181  }
1182  }
1183  }
1184 
1185  return values - values_start;
1186 }
1187 
1188 static ar_table*
1189 ar_copy(VALUE hash1, VALUE hash2)
1190 {
1191  ar_table *old_tab = RHASH_AR_TABLE(hash2);
1192 
1193  if (old_tab != NULL) {
1194  ar_table *new_tab = RHASH_AR_TABLE(hash1);
1195  if (new_tab == NULL) {
1196  new_tab = (ar_table*) rb_transient_heap_alloc(hash1, sizeof(ar_table));
1197  if (new_tab != NULL) {
1198  RHASH_SET_TRANSIENT_FLAG(hash1);
1199  }
1200  else {
1201  RHASH_UNSET_TRANSIENT_FLAG(hash1);
1202  new_tab = (ar_table*)ruby_xmalloc(sizeof(ar_table));
1203  }
1204  }
1205  *new_tab = *old_tab;
1206  RHASH(hash1)->ar_hint.word = RHASH(hash2)->ar_hint.word;
1207  RHASH_AR_TABLE_BOUND_SET(hash1, RHASH_AR_TABLE_BOUND(hash2));
1208  RHASH_AR_TABLE_SIZE_SET(hash1, RHASH_AR_TABLE_SIZE(hash2));
1209  hash_ar_table_set(hash1, new_tab);
1210 
1211  rb_gc_writebarrier_remember(hash1);
1212  return new_tab;
1213  }
1214  else {
1215  RHASH_AR_TABLE_BOUND_SET(hash1, RHASH_AR_TABLE_BOUND(hash2));
1216  RHASH_AR_TABLE_SIZE_SET(hash1, RHASH_AR_TABLE_SIZE(hash2));
1217 
1218  if (RHASH_TRANSIENT_P(hash1)) {
1219  RHASH_UNSET_TRANSIENT_FLAG(hash1);
1220  }
1221  else if (RHASH_AR_TABLE(hash1)) {
1222  ruby_xfree(RHASH_AR_TABLE(hash1));
1223  }
1224 
1225  hash_ar_table_set(hash1, NULL);
1226 
1227  rb_gc_writebarrier_remember(hash1);
1228  return old_tab;
1229  }
1230 }
1231 
1232 static void
1233 ar_clear(VALUE hash)
1234 {
1235  if (RHASH_AR_TABLE(hash) != NULL) {
1236  RHASH_AR_TABLE_SIZE_SET(hash, 0);
1237  RHASH_AR_TABLE_BOUND_SET(hash, 0);
1238  }
1239  else {
1240  HASH_ASSERT(RHASH_AR_TABLE_SIZE(hash) == 0);
1241  HASH_ASSERT(RHASH_AR_TABLE_BOUND(hash) == 0);
1242  }
1243 }
1244 
1245 #if USE_TRANSIENT_HEAP
1246 void
1247 rb_hash_transient_heap_evacuate(VALUE hash, int promote)
1248 {
1249  if (RHASH_TRANSIENT_P(hash)) {
1250  ar_table *new_tab;
1251  ar_table *old_tab = RHASH_AR_TABLE(hash);
1252 
1253  if (UNLIKELY(old_tab == NULL)) {
1254  return;
1255  }
1256  HASH_ASSERT(old_tab != NULL);
1257  if (! promote) {
1258  new_tab = rb_transient_heap_alloc(hash, sizeof(ar_table));
1259  if (new_tab == NULL) promote = true;
1260  }
1261  if (promote) {
1262  new_tab = ruby_xmalloc(sizeof(ar_table));
1263  RHASH_UNSET_TRANSIENT_FLAG(hash);
1264  }
1265  *new_tab = *old_tab;
1266  hash_ar_table_set(hash, new_tab);
1267  }
1268  hash_verify(hash);
1269 }
1270 #endif
1271 
1272 typedef int st_foreach_func(st_data_t, st_data_t, st_data_t);
1273 
1275  st_table *tbl;
1276  st_foreach_func *func;
1277  st_data_t arg;
1278 };
1279 
1280 static int
1281 foreach_safe_i(st_data_t key, st_data_t value, st_data_t args, int error)
1282 {
1283  int status;
1284  struct foreach_safe_arg *arg = (void *)args;
1285 
1286  if (error) return ST_STOP;
1287  status = (*arg->func)(key, value, arg->arg);
1288  if (status == ST_CONTINUE) {
1289  return ST_CHECK;
1290  }
1291  return status;
1292 }
1293 
1294 void
1295 st_foreach_safe(st_table *table, st_foreach_func *func, st_data_t a)
1296 {
1297  struct foreach_safe_arg arg;
1298 
1299  arg.tbl = table;
1300  arg.func = (st_foreach_func *)func;
1301  arg.arg = a;
1302  if (st_foreach_check(table, foreach_safe_i, (st_data_t)&arg, 0)) {
1303  rb_raise(rb_eRuntimeError, "hash modified during iteration");
1304  }
1305 }
1306 
1307 typedef int rb_foreach_func(VALUE, VALUE, VALUE);
1308 
1310  VALUE hash;
1311  rb_foreach_func *func;
1312  VALUE arg;
1313 };
1314 
1315 static int
1316 hash_ar_foreach_iter(st_data_t key, st_data_t value, st_data_t argp, int error)
1317 {
1318  struct hash_foreach_arg *arg = (struct hash_foreach_arg *)argp;
1319  int status;
1320 
1321  if (error) return ST_STOP;
1322  status = (*arg->func)((VALUE)key, (VALUE)value, arg->arg);
1323  /* TODO: rehash check? rb_raise(rb_eRuntimeError, "rehash occurred during iteration"); */
1324 
1325  switch (status) {
1326  case ST_DELETE:
1327  return ST_DELETE;
1328  case ST_CONTINUE:
1329  break;
1330  case ST_STOP:
1331  return ST_STOP;
1332  }
1333  return ST_CHECK;
1334 }
1335 
1336 static int
1337 hash_foreach_iter(st_data_t key, st_data_t value, st_data_t argp, int error)
1338 {
1339  struct hash_foreach_arg *arg = (struct hash_foreach_arg *)argp;
1340  int status;
1341  st_table *tbl;
1342 
1343  if (error) return ST_STOP;
1344  tbl = RHASH_ST_TABLE(arg->hash);
1345  status = (*arg->func)((VALUE)key, (VALUE)value, arg->arg);
1346  if (RHASH_ST_TABLE(arg->hash) != tbl) {
1347  rb_raise(rb_eRuntimeError, "rehash occurred during iteration");
1348  }
1349  switch (status) {
1350  case ST_DELETE:
1351  return ST_DELETE;
1352  case ST_CONTINUE:
1353  break;
1354  case ST_STOP:
1355  return ST_STOP;
1356  }
1357  return ST_CHECK;
1358 }
1359 
1360 static int
1361 iter_lev_in_ivar(VALUE hash)
1362 {
1363  VALUE levval = rb_ivar_get(hash, id_hash_iter_lev);
1364  HASH_ASSERT(FIXNUM_P(levval));
1365  return FIX2INT(levval);
1366 }
1367 
1368 void rb_ivar_set_internal(VALUE obj, ID id, VALUE val);
1369 
1370 static void
1371 iter_lev_in_ivar_set(VALUE hash, int lev)
1372 {
1373  rb_ivar_set_internal(hash, id_hash_iter_lev, INT2FIX(lev));
1374 }
1375 
1376 static int
1377 iter_lev_in_flags(VALUE hash)
1378 {
1379  unsigned int u = (unsigned int)((RBASIC(hash)->flags >> RHASH_LEV_SHIFT) & RHASH_LEV_MAX);
1380  return (int)u;
1381 }
1382 
1383 static int
1384 RHASH_ITER_LEV(VALUE hash)
1385 {
1386  int lev = iter_lev_in_flags(hash);
1387 
1388  if (lev == RHASH_LEV_MAX) {
1389  return iter_lev_in_ivar(hash);
1390  }
1391  else {
1392  return lev;
1393  }
1394 }
1395 
1396 static void
1397 hash_iter_lev_inc(VALUE hash)
1398 {
1399  int lev = iter_lev_in_flags(hash);
1400  if (lev == RHASH_LEV_MAX) {
1401  lev = iter_lev_in_ivar(hash);
1402  iter_lev_in_ivar_set(hash, lev+1);
1403  }
1404  else {
1405  lev += 1;
1406  RBASIC(hash)->flags = ((RBASIC(hash)->flags & ~RHASH_LEV_MASK) | ((VALUE)lev << RHASH_LEV_SHIFT));
1407  if (lev == RHASH_LEV_MAX) {
1408  iter_lev_in_ivar_set(hash, lev);
1409  }
1410  }
1411 }
1412 
1413 static void
1414 hash_iter_lev_dec(VALUE hash)
1415 {
1416  int lev = iter_lev_in_flags(hash);
1417  if (lev == RHASH_LEV_MAX) {
1418  lev = iter_lev_in_ivar(hash);
1419  HASH_ASSERT(lev > 0);
1420  iter_lev_in_ivar_set(hash, lev-1);
1421  }
1422  else {
1423  HASH_ASSERT(lev > 0);
1424  RBASIC(hash)->flags = ((RBASIC(hash)->flags & ~RHASH_LEV_MASK) | ((lev-1) << RHASH_LEV_SHIFT));
1425  }
1426 }
1427 
1428 static VALUE
1429 hash_foreach_ensure_rollback(VALUE hash)
1430 {
1431  hash_iter_lev_inc(hash);
1432  return 0;
1433 }
1434 
1435 static VALUE
1436 hash_foreach_ensure(VALUE hash)
1437 {
1438  hash_iter_lev_dec(hash);
1439  return 0;
1440 }
1441 
1442 int
1443 rb_hash_stlike_foreach(VALUE hash, st_foreach_callback_func *func, st_data_t arg)
1444 {
1445  if (RHASH_AR_TABLE_P(hash)) {
1446  return ar_foreach(hash, func, arg);
1447  }
1448  else {
1449  return st_foreach(RHASH_ST_TABLE(hash), func, arg);
1450  }
1451 }
1452 
1453 int
1454 rb_hash_stlike_foreach_with_replace(VALUE hash, st_foreach_check_callback_func *func, st_update_callback_func *replace, st_data_t arg)
1455 {
1456  if (RHASH_AR_TABLE_P(hash)) {
1457  return ar_foreach_with_replace(hash, func, replace, arg);
1458  }
1459  else {
1460  return st_foreach_with_replace(RHASH_ST_TABLE(hash), func, replace, arg);
1461  }
1462 }
1463 
1464 static VALUE
1465 hash_foreach_call(VALUE arg)
1466 {
1467  VALUE hash = ((struct hash_foreach_arg *)arg)->hash;
1468  int ret = 0;
1469  if (RHASH_AR_TABLE_P(hash)) {
1470  ret = ar_foreach_check(hash, hash_ar_foreach_iter,
1471  (st_data_t)arg, (st_data_t)Qundef);
1472  }
1473  else if (RHASH_ST_TABLE_P(hash)) {
1474  ret = st_foreach_check(RHASH_ST_TABLE(hash), hash_foreach_iter,
1475  (st_data_t)arg, (st_data_t)Qundef);
1476  }
1477  if (ret) {
1478  rb_raise(rb_eRuntimeError, "ret: %d, hash modified during iteration", ret);
1479  }
1480  return Qnil;
1481 }
1482 
1483 void
1484 rb_hash_foreach(VALUE hash, rb_foreach_func *func, VALUE farg)
1485 {
1486  struct hash_foreach_arg arg;
1487 
1488  if (RHASH_TABLE_EMPTY_P(hash))
1489  return;
1490  arg.hash = hash;
1491  arg.func = (rb_foreach_func *)func;
1492  arg.arg = farg;
1493  if (RB_OBJ_FROZEN(hash)) {
1494  hash_foreach_call((VALUE)&arg);
1495  }
1496  else {
1497  hash_iter_lev_inc(hash);
1498  rb_ensure(hash_foreach_call, (VALUE)&arg, hash_foreach_ensure, hash);
1499  }
1500  hash_verify(hash);
1501 }
1502 
1503 static VALUE
1504 hash_alloc_flags(VALUE klass, VALUE flags, VALUE ifnone)
1505 {
1506  const VALUE wb = (RGENGC_WB_PROTECTED_HASH ? FL_WB_PROTECTED : 0);
1507  NEWOBJ_OF(hash, struct RHash, klass, T_HASH | wb | flags);
1508 
1509  RHASH_SET_IFNONE((VALUE)hash, ifnone);
1510 
1511  return (VALUE)hash;
1512 }
1513 
1514 static VALUE
1515 hash_alloc(VALUE klass)
1516 {
1517  return hash_alloc_flags(klass, 0, Qnil);
1518 }
1519 
1520 static VALUE
1521 empty_hash_alloc(VALUE klass)
1522 {
1523  RUBY_DTRACE_CREATE_HOOK(HASH, 0);
1524 
1525  return hash_alloc(klass);
1526 }
1527 
1528 VALUE
1530 {
1531  return hash_alloc(rb_cHash);
1532 }
1533 
1534 static VALUE
1535 copy_compare_by_id(VALUE hash, VALUE basis)
1536 {
1537  if (rb_hash_compare_by_id_p(basis)) {
1538  return rb_hash_compare_by_id(hash);
1539  }
1540  return hash;
1541 }
1542 
1543 MJIT_FUNC_EXPORTED VALUE
1544 rb_hash_new_with_size(st_index_t size)
1545 {
1546  VALUE ret = rb_hash_new();
1547  if (size == 0) {
1548  /* do nothing */
1549  }
1550  else if (size <= RHASH_AR_TABLE_MAX_SIZE) {
1551  ar_alloc_table(ret);
1552  }
1553  else {
1554  RHASH_ST_TABLE_SET(ret, st_init_table_with_size(&objhash, size));
1555  }
1556  return ret;
1557 }
1558 
1559 static VALUE
1560 hash_copy(VALUE ret, VALUE hash)
1561 {
1562  if (!RHASH_EMPTY_P(hash)) {
1563  if (RHASH_AR_TABLE_P(hash))
1564  ar_copy(ret, hash);
1565  else if (RHASH_ST_TABLE_P(hash))
1566  RHASH_ST_TABLE_SET(ret, st_copy(RHASH_ST_TABLE(hash)));
1567  }
1568  return ret;
1569 }
1570 
1571 static VALUE
1572 hash_dup_with_compare_by_id(VALUE hash)
1573 {
1574  return hash_copy(copy_compare_by_id(rb_hash_new(), hash), hash);
1575 }
1576 
1577 static VALUE
1578 hash_dup(VALUE hash, VALUE klass, VALUE flags)
1579 {
1580  return hash_copy(hash_alloc_flags(klass, flags, RHASH_IFNONE(hash)),
1581  hash);
1582 }
1583 
1584 VALUE
1586 {
1587  const VALUE flags = RBASIC(hash)->flags;
1588  VALUE ret = hash_dup(hash, rb_obj_class(hash),
1589  flags & (FL_EXIVAR|RHASH_PROC_DEFAULT));
1590  if (flags & FL_EXIVAR)
1591  rb_copy_generic_ivar(ret, hash);
1592  return ret;
1593 }
1594 
1595 MJIT_FUNC_EXPORTED VALUE
1596 rb_hash_resurrect(VALUE hash)
1597 {
1598  VALUE ret = hash_dup(hash, rb_cHash, 0);
1599  return ret;
1600 }
1601 
1602 static void
1603 rb_hash_modify_check(VALUE hash)
1604 {
1605  rb_check_frozen(hash);
1606 }
1607 
1608 MJIT_FUNC_EXPORTED struct st_table *
1609 rb_hash_tbl_raw(VALUE hash, const char *file, int line)
1610 {
1611  return ar_force_convert_table(hash, file, line);
1612 }
1613 
1614 struct st_table *
1615 rb_hash_tbl(VALUE hash, const char *file, int line)
1616 {
1617  OBJ_WB_UNPROTECT(hash);
1618  return rb_hash_tbl_raw(hash, file, line);
1619 }
1620 
1621 static void
1622 rb_hash_modify(VALUE hash)
1623 {
1624  rb_hash_modify_check(hash);
1625 }
1626 
1627 NORETURN(static void no_new_key(void));
1628 static void
1629 no_new_key(void)
1630 {
1631  rb_raise(rb_eRuntimeError, "can't add a new key into hash during iteration");
1632 }
1633 
1635  VALUE hash;
1636  st_data_t arg;
1637 };
1638 
1639 #define NOINSERT_UPDATE_CALLBACK(func) \
1640 static int \
1641 func##_noinsert(st_data_t *key, st_data_t *val, st_data_t arg, int existing) \
1642 { \
1643  if (!existing) no_new_key(); \
1644  return func(key, val, (struct update_arg *)arg, existing); \
1645 } \
1646  \
1647 static int \
1648 func##_insert(st_data_t *key, st_data_t *val, st_data_t arg, int existing) \
1649 { \
1650  return func(key, val, (struct update_arg *)arg, existing); \
1651 }
1652 
1653 struct update_arg {
1654  st_data_t arg;
1655  st_update_callback_func *func;
1656  VALUE hash;
1657  VALUE key;
1658  VALUE value;
1659 };
1660 
1661 typedef int (*tbl_update_func)(st_data_t *, st_data_t *, st_data_t, int);
1662 
1663 int
1664 rb_hash_stlike_update(VALUE hash, st_data_t key, st_update_callback_func *func, st_data_t arg)
1665 {
1666  if (RHASH_AR_TABLE_P(hash)) {
1667  int result = ar_update(hash, key, func, arg);
1668  if (result == -1) {
1669  ar_try_convert_table(hash);
1670  }
1671  else {
1672  return result;
1673  }
1674  }
1675 
1676  return st_update(RHASH_ST_TABLE(hash), key, func, arg);
1677 }
1678 
1679 static int
1680 tbl_update_modify(st_data_t *key, st_data_t *val, st_data_t arg, int existing)
1681 {
1682  struct update_arg *p = (struct update_arg *)arg;
1683  st_data_t old_key = *key;
1684  st_data_t old_value = *val;
1685  VALUE hash = p->hash;
1686  int ret = (p->func)(key, val, arg, existing);
1687  switch (ret) {
1688  default:
1689  break;
1690  case ST_CONTINUE:
1691  if (!existing || *key != old_key || *val != old_value) {
1692  rb_hash_modify(hash);
1693  p->key = *key;
1694  p->value = *val;
1695  }
1696  break;
1697  case ST_DELETE:
1698  if (existing)
1699  rb_hash_modify(hash);
1700  break;
1701  }
1702 
1703  return ret;
1704 }
1705 
1706 static int
1707 tbl_update(VALUE hash, VALUE key, tbl_update_func func, st_data_t optional_arg)
1708 {
1709  struct update_arg arg = {
1710  .arg = optional_arg,
1711  .func = func,
1712  .hash = hash,
1713  .key = key,
1714  .value = (VALUE)optional_arg,
1715  };
1716 
1717  int ret = rb_hash_stlike_update(hash, key, tbl_update_modify, (st_data_t)&arg);
1718 
1719  /* write barrier */
1720  RB_OBJ_WRITTEN(hash, Qundef, arg.key);
1721  RB_OBJ_WRITTEN(hash, Qundef, arg.value);
1722 
1723  return ret;
1724 }
1725 
1726 #define UPDATE_CALLBACK(iter_lev, func) ((iter_lev) > 0 ? func##_noinsert : func##_insert)
1727 
1728 #define RHASH_UPDATE_ITER(h, iter_lev, key, func, a) do { \
1729  tbl_update((h), (key), UPDATE_CALLBACK((iter_lev), func), (st_data_t)(a)); \
1730 } while (0)
1731 
1732 #define RHASH_UPDATE(hash, key, func, arg) \
1733  RHASH_UPDATE_ITER(hash, RHASH_ITER_LEV(hash), key, func, arg)
1734 
1735 static void
1736 set_proc_default(VALUE hash, VALUE proc)
1737 {
1738  if (rb_proc_lambda_p(proc)) {
1739  int n = rb_proc_arity(proc);
1740 
1741  if (n != 2 && (n >= 0 || n < -3)) {
1742  if (n < 0) n = -n-1;
1743  rb_raise(rb_eTypeError, "default_proc takes two arguments (2 for %d)", n);
1744  }
1745  }
1746 
1747  FL_SET_RAW(hash, RHASH_PROC_DEFAULT);
1748  RHASH_SET_IFNONE(hash, proc);
1749 }
1750 
1751 /*
1752  * call-seq:
1753  * Hash.new(default_value = nil) -> new_hash
1754  * Hash.new {|hash, key| ... } -> new_hash
1755  *
1756  * Returns a new empty \Hash object.
1757  *
1758  * The initial default value and initial default proc for the new hash
1759  * depend on which form above was used. See {Default Values}[#class-Hash-label-Default+Values].
1760  *
1761  * If neither an argument nor a block given,
1762  * initializes both the default value and the default proc to <tt>nil</tt>:
1763  * h = Hash.new
1764  * h.default # => nil
1765  * h.default_proc # => nil
1766  *
1767  * If argument <tt>default_value</tt> given but no block given,
1768  * initializes the default value to the given <tt>default_value</tt>
1769  * and the default proc to <tt>nil</tt>:
1770  * h = Hash.new(false)
1771  * h.default # => false
1772  * h.default_proc # => nil
1773  *
1774  * If a block given but no argument, stores the block as the default proc
1775  * and sets the default value to <tt>nil</tt>:
1776  * h = Hash.new {|hash, key| "Default value for #{key}" }
1777  * h.default # => nil
1778  * h.default_proc.class # => Proc
1779  * h[:nosuch] # => "Default value for nosuch"
1780  */
1781 
1782 static VALUE
1783 rb_hash_initialize(int argc, VALUE *argv, VALUE hash)
1784 {
1785  VALUE ifnone;
1786 
1787  rb_hash_modify(hash);
1788  if (rb_block_given_p()) {
1789  rb_check_arity(argc, 0, 0);
1790  ifnone = rb_block_proc();
1791  SET_PROC_DEFAULT(hash, ifnone);
1792  }
1793  else {
1794  rb_check_arity(argc, 0, 1);
1795  ifnone = argc == 0 ? Qnil : argv[0];
1796  RHASH_SET_IFNONE(hash, ifnone);
1797  }
1798 
1799  return hash;
1800 }
1801 
1802 /*
1803  * call-seq:
1804  * Hash[] -> new_empty_hash
1805  * Hash[hash] -> new_hash
1806  * Hash[ [*2_element_arrays] ] -> new_hash
1807  * Hash[*objects] -> new_hash
1808  *
1809  * Returns a new \Hash object populated with the given objects, if any.
1810  * See Hash::new.
1811  *
1812  * With no argument, returns a new empty \Hash.
1813  *
1814  * When the single given argument is a \Hash, returns a new \Hash
1815  * populated with the entries from the given \Hash, excluding the
1816  * default value or proc.
1817  *
1818  * h = {foo: 0, bar: 1, baz: 2}
1819  * Hash[h] # => {:foo=>0, :bar=>1, :baz=>2}
1820  *
1821  * When the single given argument is an \Array of 2-element Arrays,
1822  * returns a new \Hash object wherein each 2-element array forms a
1823  * key-value entry:
1824  *
1825  * Hash[ [ [:foo, 0], [:bar, 1] ] ] # => {:foo=>0, :bar=>1}
1826  *
1827  * When the argument count is an even number;
1828  * returns a new \Hash object wherein each successive pair of arguments
1829  * has become a key-value entry:
1830  *
1831  * Hash[:foo, 0, :bar, 1] # => {:foo=>0, :bar=>1}
1832  *
1833  * Raises an exception if the argument list does not conform to any
1834  * of the above.
1835  */
1836 
1837 static VALUE
1838 rb_hash_s_create(int argc, VALUE *argv, VALUE klass)
1839 {
1840  VALUE hash, tmp;
1841 
1842  if (argc == 1) {
1843  tmp = rb_hash_s_try_convert(Qnil, argv[0]);
1844  if (!NIL_P(tmp)) {
1845  hash = hash_alloc(klass);
1846  hash_copy(hash, tmp);
1847  return hash;
1848  }
1849 
1850  tmp = rb_check_array_type(argv[0]);
1851  if (!NIL_P(tmp)) {
1852  long i;
1853 
1854  hash = hash_alloc(klass);
1855  for (i = 0; i < RARRAY_LEN(tmp); ++i) {
1856  VALUE e = RARRAY_AREF(tmp, i);
1857  VALUE v = rb_check_array_type(e);
1858  VALUE key, val = Qnil;
1859 
1860  if (NIL_P(v)) {
1861  rb_raise(rb_eArgError, "wrong element type %s at %ld (expected array)",
1862  rb_builtin_class_name(e), i);
1863  }
1864  switch (RARRAY_LEN(v)) {
1865  default:
1866  rb_raise(rb_eArgError, "invalid number of elements (%ld for 1..2)",
1867  RARRAY_LEN(v));
1868  case 2:
1869  val = RARRAY_AREF(v, 1);
1870  case 1:
1871  key = RARRAY_AREF(v, 0);
1872  rb_hash_aset(hash, key, val);
1873  }
1874  }
1875  return hash;
1876  }
1877  }
1878  if (argc % 2 != 0) {
1879  rb_raise(rb_eArgError, "odd number of arguments for Hash");
1880  }
1881 
1882  hash = hash_alloc(klass);
1883  rb_hash_bulk_insert(argc, argv, hash);
1884  hash_verify(hash);
1885  return hash;
1886 }
1887 
1888 MJIT_FUNC_EXPORTED VALUE
1889 rb_to_hash_type(VALUE hash)
1890 {
1891  return rb_convert_type_with_id(hash, T_HASH, "Hash", idTo_hash);
1892 }
1893 #define to_hash rb_to_hash_type
1894 
1895 VALUE
1897 {
1898  return rb_check_convert_type_with_id(hash, T_HASH, "Hash", idTo_hash);
1899 }
1900 
1901 /*
1902  * call-seq:
1903  * Hash.try_convert(obj) -> obj, new_hash, or nil
1904  *
1905  * If +obj+ is a \Hash object, returns +obj+.
1906  *
1907  * Otherwise if +obj+ responds to <tt>:to_hash</tt>,
1908  * calls <tt>obj.to_hash</tt> and returns the result.
1909  *
1910  * Returns +nil+ if +obj+ does not respond to <tt>:to_hash</tt>
1911  *
1912  * Raises an exception unless <tt>obj.to_hash</tt> returns a \Hash object.
1913  */
1914 static VALUE
1915 rb_hash_s_try_convert(VALUE dummy, VALUE hash)
1916 {
1917  return rb_check_hash_type(hash);
1918 }
1919 
1920 /*
1921  * call-seq:
1922  * Hash.ruby2_keywords_hash?(hash) -> true or false
1923  *
1924  * Checks if a given hash is flagged by Module#ruby2_keywords (or
1925  * Proc#ruby2_keywords).
1926  * This method is not for casual use; debugging, researching, and
1927  * some truly necessary cases like serialization of arguments.
1928  *
1929  * ruby2_keywords def foo(*args)
1930  * Hash.ruby2_keywords_hash?(args.last)
1931  * end
1932  * foo(k: 1) #=> true
1933  * foo({k: 1}) #=> false
1934  */
1935 static VALUE
1936 rb_hash_s_ruby2_keywords_hash_p(VALUE dummy, VALUE hash)
1937 {
1938  Check_Type(hash, T_HASH);
1939  return RBOOL(RHASH(hash)->basic.flags & RHASH_PASS_AS_KEYWORDS);
1940 }
1941 
1942 /*
1943  * call-seq:
1944  * Hash.ruby2_keywords_hash(hash) -> hash
1945  *
1946  * Duplicates a given hash and adds a ruby2_keywords flag.
1947  * This method is not for casual use; debugging, researching, and
1948  * some truly necessary cases like deserialization of arguments.
1949  *
1950  * h = {k: 1}
1951  * h = Hash.ruby2_keywords_hash(h)
1952  * def foo(k: 42)
1953  * k
1954  * end
1955  * foo(*[h]) #=> 1 with neither a warning or an error
1956  */
1957 static VALUE
1958 rb_hash_s_ruby2_keywords_hash(VALUE dummy, VALUE hash)
1959 {
1960  Check_Type(hash, T_HASH);
1961  hash = rb_hash_dup(hash);
1962  RHASH(hash)->basic.flags |= RHASH_PASS_AS_KEYWORDS;
1963  return hash;
1964 }
1965 
1966 struct rehash_arg {
1967  VALUE hash;
1968  st_table *tbl;
1969 };
1970 
1971 static int
1972 rb_hash_rehash_i(VALUE key, VALUE value, VALUE arg)
1973 {
1974  if (RHASH_AR_TABLE_P(arg)) {
1975  ar_insert(arg, (st_data_t)key, (st_data_t)value);
1976  }
1977  else {
1978  st_insert(RHASH_ST_TABLE(arg), (st_data_t)key, (st_data_t)value);
1979  }
1980  return ST_CONTINUE;
1981 }
1982 
1983 /*
1984  * call-seq:
1985  * hash.rehash -> self
1986  *
1987  * Rebuilds the hash table by recomputing the hash index for each key;
1988  * returns <tt>self</tt>.
1989  *
1990  * The hash table becomes invalid if the hash value of a key
1991  * has changed after the entry was created.
1992  * See {Modifying an Active Hash Key}[#class-Hash-label-Modifying+an+Active+Hash+Key].
1993  */
1994 
1995 VALUE
1996 rb_hash_rehash(VALUE hash)
1997 {
1998  VALUE tmp;
1999  st_table *tbl;
2000 
2001  if (RHASH_ITER_LEV(hash) > 0) {
2002  rb_raise(rb_eRuntimeError, "rehash during iteration");
2003  }
2004  rb_hash_modify_check(hash);
2005  if (RHASH_AR_TABLE_P(hash)) {
2006  tmp = hash_alloc(0);
2007  ar_alloc_table(tmp);
2008  rb_hash_foreach(hash, rb_hash_rehash_i, (VALUE)tmp);
2009  ar_free_and_clear_table(hash);
2010  ar_copy(hash, tmp);
2011  ar_free_and_clear_table(tmp);
2012  }
2013  else if (RHASH_ST_TABLE_P(hash)) {
2014  st_table *old_tab = RHASH_ST_TABLE(hash);
2015  tmp = hash_alloc(0);
2016  tbl = st_init_table_with_size(old_tab->type, old_tab->num_entries);
2017  RHASH_ST_TABLE_SET(tmp, tbl);
2018  rb_hash_foreach(hash, rb_hash_rehash_i, (VALUE)tmp);
2019  st_free_table(old_tab);
2020  RHASH_ST_TABLE_SET(hash, tbl);
2021  RHASH_ST_CLEAR(tmp);
2022  }
2023  hash_verify(hash);
2024  return hash;
2025 }
2026 
2027 static VALUE
2028 call_default_proc(VALUE proc, VALUE hash, VALUE key)
2029 {
2030  VALUE args[2] = {hash, key};
2031  return rb_proc_call_with_block(proc, 2, args, Qnil);
2032 }
2033 
2034 VALUE
2035 rb_hash_default_value(VALUE hash, VALUE key)
2036 {
2037  if (LIKELY(rb_method_basic_definition_p(CLASS_OF(hash), id_default))) {
2038  VALUE ifnone = RHASH_IFNONE(hash);
2039  if (!FL_TEST(hash, RHASH_PROC_DEFAULT)) return ifnone;
2040  if (key == Qundef) return Qnil;
2041  return call_default_proc(ifnone, hash, key);
2042  }
2043  else {
2044  return rb_funcall(hash, id_default, 1, key);
2045  }
2046 }
2047 
2048 static inline int
2049 hash_stlike_lookup(VALUE hash, st_data_t key, st_data_t *pval)
2050 {
2051  hash_verify(hash);
2052 
2053  if (RHASH_AR_TABLE_P(hash)) {
2054  return ar_lookup(hash, key, pval);
2055  }
2056  else {
2057  return st_lookup(RHASH_ST_TABLE(hash), key, pval);
2058  }
2059 }
2060 
2061 MJIT_FUNC_EXPORTED int
2062 rb_hash_stlike_lookup(VALUE hash, st_data_t key, st_data_t *pval)
2063 {
2064  return hash_stlike_lookup(hash, key, pval);
2065 }
2066 
2067 /*
2068  * call-seq:
2069  * hash[key] -> value
2070  *
2071  * Returns the value associated with the given +key+, if found:
2072  * h = {foo: 0, bar: 1, baz: 2}
2073  * h[:foo] # => 0
2074  *
2075  * If +key+ is not found, returns a default value
2076  * (see {Default Values}[#class-Hash-label-Default+Values]):
2077  * h = {foo: 0, bar: 1, baz: 2}
2078  * h[:nosuch] # => nil
2079  */
2080 
2081 VALUE
2083 {
2084  st_data_t val;
2085 
2086  if (hash_stlike_lookup(hash, key, &val)) {
2087  return (VALUE)val;
2088  }
2089  else {
2090  return rb_hash_default_value(hash, key);
2091  }
2092 }
2093 
2094 VALUE
2096 {
2097  st_data_t val;
2098 
2099  if (hash_stlike_lookup(hash, key, &val)) {
2100  return (VALUE)val;
2101  }
2102  else {
2103  return def; /* without Hash#default */
2104  }
2105 }
2106 
2107 VALUE
2109 {
2110  return rb_hash_lookup2(hash, key, Qnil);
2111 }
2112 
2113 /*
2114  * call-seq:
2115  * hash.fetch(key) -> object
2116  * hash.fetch(key, default_value) -> object
2117  * hash.fetch(key) {|key| ... } -> object
2118  *
2119  * Returns the value for the given +key+, if found.
2120  * h = {foo: 0, bar: 1, baz: 2}
2121  * h.fetch(:bar) # => 1
2122  *
2123  * If +key+ is not found and no block was given,
2124  * returns +default_value+:
2125  * {}.fetch(:nosuch, :default) # => :default
2126  *
2127  * If +key+ is not found and a block was given,
2128  * yields +key+ to the block and returns the block's return value:
2129  * {}.fetch(:nosuch) {|key| "No key #{key}"} # => "No key nosuch"
2130  *
2131  * Raises KeyError if neither +default_value+ nor a block was given.
2132  *
2133  * Note that this method does not use the values of either #default or #default_proc.
2134  */
2135 
2136 static VALUE
2137 rb_hash_fetch_m(int argc, VALUE *argv, VALUE hash)
2138 {
2139  VALUE key;
2140  st_data_t val;
2141  long block_given;
2142 
2143  rb_check_arity(argc, 1, 2);
2144  key = argv[0];
2145 
2146  block_given = rb_block_given_p();
2147  if (block_given && argc == 2) {
2148  rb_warn("block supersedes default value argument");
2149  }
2150 
2151  if (hash_stlike_lookup(hash, key, &val)) {
2152  return (VALUE)val;
2153  }
2154  else {
2155  if (block_given) {
2156  return rb_yield(key);
2157  }
2158  else if (argc == 1) {
2159  VALUE desc = rb_protect(rb_inspect, key, 0);
2160  if (NIL_P(desc)) {
2161  desc = rb_any_to_s(key);
2162  }
2163  desc = rb_str_ellipsize(desc, 65);
2164  rb_key_err_raise(rb_sprintf("key not found: %"PRIsVALUE, desc), hash, key);
2165  }
2166  else {
2167  return argv[1];
2168  }
2169  }
2170 }
2171 
2172 VALUE
2174 {
2175  return rb_hash_fetch_m(1, &key, hash);
2176 }
2177 
2178 /*
2179  * call-seq:
2180  * hash.default -> object
2181  * hash.default(key) -> object
2182  *
2183  * Returns the default value for the given +key+.
2184  * The returned value will be determined either by the default proc or by the default value.
2185  * See {Default Values}[#class-Hash-label-Default+Values].
2186  *
2187  * With no argument, returns the current default value:
2188  * h = {}
2189  * h.default # => nil
2190  *
2191  * If +key+ is given, returns the default value for +key+,
2192  * regardless of whether that key exists:
2193  * h = Hash.new { |hash, key| hash[key] = "No key #{key}"}
2194  * h[:foo] = "Hello"
2195  * h.default(:foo) # => "No key foo"
2196  */
2197 
2198 static VALUE
2199 rb_hash_default(int argc, VALUE *argv, VALUE hash)
2200 {
2201  VALUE ifnone;
2202 
2203  rb_check_arity(argc, 0, 1);
2204  ifnone = RHASH_IFNONE(hash);
2205  if (FL_TEST(hash, RHASH_PROC_DEFAULT)) {
2206  if (argc == 0) return Qnil;
2207  return call_default_proc(ifnone, hash, argv[0]);
2208  }
2209  return ifnone;
2210 }
2211 
2212 /*
2213  * call-seq:
2214  * hash.default = value -> object
2215  *
2216  * Sets the default value to +value+; returns +value+:
2217  * h = {}
2218  * h.default # => nil
2219  * h.default = false # => false
2220  * h.default # => false
2221  *
2222  * See {Default Values}[#class-Hash-label-Default+Values].
2223  */
2224 
2225 static VALUE
2226 rb_hash_set_default(VALUE hash, VALUE ifnone)
2227 {
2228  rb_hash_modify_check(hash);
2229  SET_DEFAULT(hash, ifnone);
2230  return ifnone;
2231 }
2232 
2233 /*
2234  * call-seq:
2235  * hash.default_proc -> proc or nil
2236  *
2237  * Returns the default proc for +self+
2238  * (see {Default Values}[#class-Hash-label-Default+Values]):
2239  * h = {}
2240  * h.default_proc # => nil
2241  * h.default_proc = proc {|hash, key| "Default value for #{key}" }
2242  * h.default_proc.class # => Proc
2243  */
2244 
2245 static VALUE
2246 rb_hash_default_proc(VALUE hash)
2247 {
2248  if (FL_TEST(hash, RHASH_PROC_DEFAULT)) {
2249  return RHASH_IFNONE(hash);
2250  }
2251  return Qnil;
2252 }
2253 
2254 /*
2255  * call-seq:
2256  * hash.default_proc = proc -> proc
2257  *
2258  * Sets the default proc for +self+ to +proc+:
2259  * (see {Default Values}[#class-Hash-label-Default+Values]):
2260  * h = {}
2261  * h.default_proc # => nil
2262  * h.default_proc = proc { |hash, key| "Default value for #{key}" }
2263  * h.default_proc.class # => Proc
2264  * h.default_proc = nil
2265  * h.default_proc # => nil
2266  */
2267 
2268 VALUE
2269 rb_hash_set_default_proc(VALUE hash, VALUE proc)
2270 {
2271  VALUE b;
2272 
2273  rb_hash_modify_check(hash);
2274  if (NIL_P(proc)) {
2275  SET_DEFAULT(hash, proc);
2276  return proc;
2277  }
2278  b = rb_check_convert_type_with_id(proc, T_DATA, "Proc", idTo_proc);
2279  if (NIL_P(b) || !rb_obj_is_proc(b)) {
2281  "wrong default_proc type %s (expected Proc)",
2282  rb_obj_classname(proc));
2283  }
2284  proc = b;
2285  SET_PROC_DEFAULT(hash, proc);
2286  return proc;
2287 }
2288 
2289 static int
2290 key_i(VALUE key, VALUE value, VALUE arg)
2291 {
2292  VALUE *args = (VALUE *)arg;
2293 
2294  if (rb_equal(value, args[0])) {
2295  args[1] = key;
2296  return ST_STOP;
2297  }
2298  return ST_CONTINUE;
2299 }
2300 
2301 /*
2302  * call-seq:
2303  * hash.key(value) -> key or nil
2304  *
2305  * Returns the key for the first-found entry with the given +value+
2306  * (see {Entry Order}[#class-Hash-label-Entry+Order]):
2307  * h = {foo: 0, bar: 2, baz: 2}
2308  * h.key(0) # => :foo
2309  * h.key(2) # => :bar
2310  *
2311  * Returns +nil+ if so such value is found.
2312  */
2313 
2314 static VALUE
2315 rb_hash_key(VALUE hash, VALUE value)
2316 {
2317  VALUE args[2];
2318 
2319  args[0] = value;
2320  args[1] = Qnil;
2321 
2322  rb_hash_foreach(hash, key_i, (VALUE)args);
2323 
2324  return args[1];
2325 }
2326 
2327 int
2328 rb_hash_stlike_delete(VALUE hash, st_data_t *pkey, st_data_t *pval)
2329 {
2330  if (RHASH_AR_TABLE_P(hash)) {
2331  return ar_delete(hash, pkey, pval);
2332  }
2333  else {
2334  return st_delete(RHASH_ST_TABLE(hash), pkey, pval);
2335  }
2336 }
2337 
2338 /*
2339  * delete a specified entry by a given key.
2340  * if there is the corresponding entry, return a value of the entry.
2341  * if there is no corresponding entry, return Qundef.
2342  */
2343 VALUE
2344 rb_hash_delete_entry(VALUE hash, VALUE key)
2345 {
2346  st_data_t ktmp = (st_data_t)key, val;
2347 
2348  if (rb_hash_stlike_delete(hash, &ktmp, &val)) {
2349  return (VALUE)val;
2350  }
2351  else {
2352  return Qundef;
2353  }
2354 }
2355 
2356 /*
2357  * delete a specified entry by a given key.
2358  * if there is the corresponding entry, return a value of the entry.
2359  * if there is no corresponding entry, return Qnil.
2360  */
2361 VALUE
2363 {
2364  VALUE deleted_value = rb_hash_delete_entry(hash, key);
2365 
2366  if (deleted_value != Qundef) { /* likely pass */
2367  return deleted_value;
2368  }
2369  else {
2370  return Qnil;
2371  }
2372 }
2373 
2374 /*
2375  * call-seq:
2376  * hash.delete(key) -> value or nil
2377  * hash.delete(key) {|key| ... } -> object
2378  *
2379  * Deletes the entry for the given +key+ and returns its associated value.
2380  *
2381  * If no block is given and +key+ is found, deletes the entry and returns the associated value:
2382  * h = {foo: 0, bar: 1, baz: 2}
2383  * h.delete(:bar) # => 1
2384  * h # => {:foo=>0, :baz=>2}
2385  *
2386  * If no block given and +key+ is not found, returns +nil+.
2387  *
2388  * If a block is given and +key+ is found, ignores the block,
2389  * deletes the entry, and returns the associated value:
2390  * h = {foo: 0, bar: 1, baz: 2}
2391  * h.delete(:baz) { |key| raise 'Will never happen'} # => 2
2392  * h # => {:foo=>0, :bar=>1}
2393  *
2394  * If a block is given and +key+ is not found,
2395  * calls the block and returns the block's return value:
2396  * h = {foo: 0, bar: 1, baz: 2}
2397  * h.delete(:nosuch) { |key| "Key #{key} not found" } # => "Key nosuch not found"
2398  * h # => {:foo=>0, :bar=>1, :baz=>2}
2399  */
2400 
2401 static VALUE
2402 rb_hash_delete_m(VALUE hash, VALUE key)
2403 {
2404  VALUE val;
2405 
2406  rb_hash_modify_check(hash);
2407  val = rb_hash_delete_entry(hash, key);
2408 
2409  if (val != Qundef) {
2410  return val;
2411  }
2412  else {
2413  if (rb_block_given_p()) {
2414  return rb_yield(key);
2415  }
2416  else {
2417  return Qnil;
2418  }
2419  }
2420 }
2421 
2422 struct shift_var {
2423  VALUE key;
2424  VALUE val;
2425 };
2426 
2427 static int
2428 shift_i_safe(VALUE key, VALUE value, VALUE arg)
2429 {
2430  struct shift_var *var = (struct shift_var *)arg;
2431 
2432  var->key = key;
2433  var->val = value;
2434  return ST_STOP;
2435 }
2436 
2437 /*
2438  * call-seq:
2439  * hash.shift -> [key, value] or default_value
2440  *
2441  * Removes the first hash entry
2442  * (see {Entry Order}[#class-Hash-label-Entry+Order]);
2443  * returns a 2-element \Array containing the removed key and value:
2444  * h = {foo: 0, bar: 1, baz: 2}
2445  * h.shift # => [:foo, 0]
2446  * h # => {:bar=>1, :baz=>2}
2447  *
2448  * Returns the default value if the hash is empty
2449  * (see {Default Values}[#class-Hash-label-Default+Values]).
2450  */
2451 
2452 static VALUE
2453 rb_hash_shift(VALUE hash)
2454 {
2455  struct shift_var var;
2456 
2457  rb_hash_modify_check(hash);
2458  if (RHASH_AR_TABLE_P(hash)) {
2459  var.key = Qundef;
2460  if (RHASH_ITER_LEV(hash) == 0) {
2461  if (ar_shift(hash, &var.key, &var.val)) {
2462  return rb_assoc_new(var.key, var.val);
2463  }
2464  }
2465  else {
2466  rb_hash_foreach(hash, shift_i_safe, (VALUE)&var);
2467  if (var.key != Qundef) {
2468  rb_hash_delete_entry(hash, var.key);
2469  return rb_assoc_new(var.key, var.val);
2470  }
2471  }
2472  }
2473  if (RHASH_ST_TABLE_P(hash)) {
2474  var.key = Qundef;
2475  if (RHASH_ITER_LEV(hash) == 0) {
2476  if (st_shift(RHASH_ST_TABLE(hash), &var.key, &var.val)) {
2477  return rb_assoc_new(var.key, var.val);
2478  }
2479  }
2480  else {
2481  rb_hash_foreach(hash, shift_i_safe, (VALUE)&var);
2482  if (var.key != Qundef) {
2483  rb_hash_delete_entry(hash, var.key);
2484  return rb_assoc_new(var.key, var.val);
2485  }
2486  }
2487  }
2488  return rb_hash_default_value(hash, Qnil);
2489 }
2490 
2491 static int
2492 delete_if_i(VALUE key, VALUE value, VALUE hash)
2493 {
2494  if (RTEST(rb_yield_values(2, key, value))) {
2495  rb_hash_modify(hash);
2496  return ST_DELETE;
2497  }
2498  return ST_CONTINUE;
2499 }
2500 
2501 static VALUE
2502 hash_enum_size(VALUE hash, VALUE args, VALUE eobj)
2503 {
2504  return rb_hash_size(hash);
2505 }
2506 
2507 /*
2508  * call-seq:
2509  * hash.delete_if {|key, value| ... } -> self
2510  * hash.delete_if -> new_enumerator
2511  *
2512  * If a block given, calls the block with each key-value pair;
2513  * deletes each entry for which the block returns a truthy value;
2514  * returns +self+:
2515  * h = {foo: 0, bar: 1, baz: 2}
2516  * h.delete_if {|key, value| value > 0 } # => {:foo=>0}
2517  *
2518  * If no block given, returns a new \Enumerator:
2519  * h = {foo: 0, bar: 1, baz: 2}
2520  * e = h.delete_if # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:delete_if>
2521  * e.each { |key, value| value > 0 } # => {:foo=>0}
2522  */
2523 
2524 VALUE
2526 {
2527  RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2528  rb_hash_modify_check(hash);
2529  if (!RHASH_TABLE_EMPTY_P(hash)) {
2530  rb_hash_foreach(hash, delete_if_i, hash);
2531  }
2532  return hash;
2533 }
2534 
2535 /*
2536  * call-seq:
2537  * hash.reject! {|key, value| ... } -> self or nil
2538  * hash.reject! -> new_enumerator
2539  *
2540  * Returns +self+, whose remaining entries are those
2541  * for which the block returns +false+ or +nil+:
2542  * h = {foo: 0, bar: 1, baz: 2}
2543  * h.reject! {|key, value| value < 2 } # => {:baz=>2}
2544  *
2545  * Returns +nil+ if no entries are removed.
2546  *
2547  * Returns a new \Enumerator if no block given:
2548  * h = {foo: 0, bar: 1, baz: 2}
2549  * e = h.reject! # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:reject!>
2550  * e.each {|key, value| key.start_with?('b') } # => {:foo=>0}
2551  */
2552 
2553 static VALUE
2554 rb_hash_reject_bang(VALUE hash)
2555 {
2556  st_index_t n;
2557 
2558  RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2559  rb_hash_modify(hash);
2560  n = RHASH_SIZE(hash);
2561  if (!n) return Qnil;
2562  rb_hash_foreach(hash, delete_if_i, hash);
2563  if (n == RHASH_SIZE(hash)) return Qnil;
2564  return hash;
2565 }
2566 
2567 /*
2568  * call-seq:
2569  * hash.reject {|key, value| ... } -> new_hash
2570  * hash.reject -> new_enumerator
2571  *
2572  * Returns a new \Hash object whose entries are all those
2573  * from +self+ for which the block returns +false+ or +nil+:
2574  * h = {foo: 0, bar: 1, baz: 2}
2575  * h1 = h.reject {|key, value| key.start_with?('b') }
2576  * h1 # => {:foo=>0}
2577  *
2578  * Returns a new \Enumerator if no block given:
2579  * h = {foo: 0, bar: 1, baz: 2}
2580  * e = h.reject # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:reject>
2581  * h1 = e.each {|key, value| key.start_with?('b') }
2582  * h1 # => {:foo=>0}
2583  */
2584 
2585 static VALUE
2586 rb_hash_reject(VALUE hash)
2587 {
2588  VALUE result;
2589 
2590  RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2591  result = hash_dup_with_compare_by_id(hash);
2592  if (!RHASH_EMPTY_P(hash)) {
2593  rb_hash_foreach(result, delete_if_i, result);
2594  }
2595  return result;
2596 }
2597 
2598 /*
2599  * call-seq:
2600  * hash.slice(*keys) -> new_hash
2601  *
2602  * Returns a new \Hash object containing the entries for the given +keys+:
2603  * h = {foo: 0, bar: 1, baz: 2}
2604  * h.slice(:baz, :foo) # => {:baz=>2, :foo=>0}
2605  *
2606  * Any given +keys+ that are not found are ignored.
2607  */
2608 
2609 static VALUE
2610 rb_hash_slice(int argc, VALUE *argv, VALUE hash)
2611 {
2612  int i;
2613  VALUE key, value, result;
2614 
2615  if (argc == 0 || RHASH_EMPTY_P(hash)) {
2616  return copy_compare_by_id(rb_hash_new(), hash);
2617  }
2618  result = copy_compare_by_id(rb_hash_new_with_size(argc), hash);
2619 
2620  for (i = 0; i < argc; i++) {
2621  key = argv[i];
2622  value = rb_hash_lookup2(hash, key, Qundef);
2623  if (value != Qundef)
2624  rb_hash_aset(result, key, value);
2625  }
2626 
2627  return result;
2628 }
2629 
2630 /*
2631  * call-seq:
2632  * hsh.except(*keys) -> a_hash
2633  *
2634  * Returns a new \Hash excluding entries for the given +keys+:
2635  * h = { a: 100, b: 200, c: 300 }
2636  * h.except(:a) #=> {:b=>200, :c=>300}
2637  *
2638  * Any given +keys+ that are not found are ignored.
2639  */
2640 
2641 static VALUE
2642 rb_hash_except(int argc, VALUE *argv, VALUE hash)
2643 {
2644  int i;
2645  VALUE key, result;
2646 
2647  result = hash_dup_with_compare_by_id(hash);
2648 
2649  for (i = 0; i < argc; i++) {
2650  key = argv[i];
2651  rb_hash_delete(result, key);
2652  }
2653 
2654  return result;
2655 }
2656 
2657 /*
2658  * call-seq:
2659  * hash.values_at(*keys) -> new_array
2660  *
2661  * Returns a new \Array containing values for the given +keys+:
2662  * h = {foo: 0, bar: 1, baz: 2}
2663  * h.values_at(:baz, :foo) # => [2, 0]
2664  *
2665  * The {default values}[#class-Hash-label-Default+Values] are returned
2666  * for any keys that are not found:
2667  * h.values_at(:hello, :foo) # => [nil, 0]
2668  */
2669 
2670 static VALUE
2671 rb_hash_values_at(int argc, VALUE *argv, VALUE hash)
2672 {
2673  VALUE result = rb_ary_new2(argc);
2674  long i;
2675 
2676  for (i=0; i<argc; i++) {
2677  rb_ary_push(result, rb_hash_aref(hash, argv[i]));
2678  }
2679  return result;
2680 }
2681 
2682 /*
2683  * call-seq:
2684  * hash.fetch_values(*keys) -> new_array
2685  * hash.fetch_values(*keys) {|key| ... } -> new_array
2686  *
2687  * Returns a new \Array containing the values associated with the given keys *keys:
2688  * h = {foo: 0, bar: 1, baz: 2}
2689  * h.fetch_values(:baz, :foo) # => [2, 0]
2690  *
2691  * Returns a new empty \Array if no arguments given.
2692  *
2693  * When a block is given, calls the block with each missing key,
2694  * treating the block's return value as the value for that key:
2695  * h = {foo: 0, bar: 1, baz: 2}
2696  * values = h.fetch_values(:bar, :foo, :bad, :bam) {|key| key.to_s}
2697  * values # => [1, 0, "bad", "bam"]
2698  *
2699  * When no block is given, raises an exception if any given key is not found.
2700  */
2701 
2702 static VALUE
2703 rb_hash_fetch_values(int argc, VALUE *argv, VALUE hash)
2704 {
2705  VALUE result = rb_ary_new2(argc);
2706  long i;
2707 
2708  for (i=0; i<argc; i++) {
2709  rb_ary_push(result, rb_hash_fetch(hash, argv[i]));
2710  }
2711  return result;
2712 }
2713 
2714 static int
2715 keep_if_i(VALUE key, VALUE value, VALUE hash)
2716 {
2717  if (!RTEST(rb_yield_values(2, key, value))) {
2718  rb_hash_modify(hash);
2719  return ST_DELETE;
2720  }
2721  return ST_CONTINUE;
2722 }
2723 
2724 /*
2725  * call-seq:
2726  * hash.select {|key, value| ... } -> new_hash
2727  * hash.select -> new_enumerator
2728  *
2729  * Hash#filter is an alias for Hash#select.
2730  *
2731  * Returns a new \Hash object whose entries are those for which the block returns a truthy value:
2732  * h = {foo: 0, bar: 1, baz: 2}
2733  * h.select {|key, value| value < 2 } # => {:foo=>0, :bar=>1}
2734  *
2735  * Returns a new \Enumerator if no block given:
2736  * h = {foo: 0, bar: 1, baz: 2}
2737  * e = h.select # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:select>
2738  * e.each {|key, value| value < 2 } # => {:foo=>0, :bar=>1}
2739  */
2740 
2741 static VALUE
2742 rb_hash_select(VALUE hash)
2743 {
2744  VALUE result;
2745 
2746  RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2747  result = hash_dup_with_compare_by_id(hash);
2748  if (!RHASH_EMPTY_P(hash)) {
2749  rb_hash_foreach(result, keep_if_i, result);
2750  }
2751  return result;
2752 }
2753 
2754 /*
2755  * call-seq:
2756  * hash.select! {|key, value| ... } -> self or nil
2757  * hash.select! -> new_enumerator
2758  *
2759  * Hash#filter! is an alias for Hash#select!.
2760  *
2761  * Returns +self+, whose entries are those for which the block returns a truthy value:
2762  * h = {foo: 0, bar: 1, baz: 2}
2763  * h.select! {|key, value| value < 2 } => {:foo=>0, :bar=>1}
2764  *
2765  * Returns +nil+ if no entries were removed.
2766  *
2767  * Returns a new \Enumerator if no block given:
2768  * h = {foo: 0, bar: 1, baz: 2}
2769  * e = h.select! # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:select!>
2770  * e.each { |key, value| value < 2 } # => {:foo=>0, :bar=>1}
2771  */
2772 
2773 static VALUE
2774 rb_hash_select_bang(VALUE hash)
2775 {
2776  st_index_t n;
2777 
2778  RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2779  rb_hash_modify_check(hash);
2780  n = RHASH_SIZE(hash);
2781  if (!n) return Qnil;
2782  rb_hash_foreach(hash, keep_if_i, hash);
2783  if (n == RHASH_SIZE(hash)) return Qnil;
2784  return hash;
2785 }
2786 
2787 /*
2788  * call-seq:
2789  * hash.keep_if {|key, value| ... } -> self
2790  * hash.keep_if -> new_enumerator
2791  *
2792  * Calls the block for each key-value pair;
2793  * retains the entry if the block returns a truthy value;
2794  * otherwise deletes the entry; returns +self+.
2795  * h = {foo: 0, bar: 1, baz: 2}
2796  * h.keep_if { |key, value| key.start_with?('b') } # => {:bar=>1, :baz=>2}
2797  *
2798  * Returns a new \Enumerator if no block given:
2799  * h = {foo: 0, bar: 1, baz: 2}
2800  * e = h.keep_if # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:keep_if>
2801  * e.each { |key, value| key.start_with?('b') } # => {:bar=>1, :baz=>2}
2802  */
2803 
2804 static VALUE
2805 rb_hash_keep_if(VALUE hash)
2806 {
2807  RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2808  rb_hash_modify_check(hash);
2809  if (!RHASH_TABLE_EMPTY_P(hash)) {
2810  rb_hash_foreach(hash, keep_if_i, hash);
2811  }
2812  return hash;
2813 }
2814 
2815 static int
2816 clear_i(VALUE key, VALUE value, VALUE dummy)
2817 {
2818  return ST_DELETE;
2819 }
2820 
2821 /*
2822  * call-seq:
2823  * hash.clear -> self
2824  *
2825  * Removes all hash entries; returns +self+.
2826  */
2827 
2828 VALUE
2830 {
2831  rb_hash_modify_check(hash);
2832 
2833  if (RHASH_ITER_LEV(hash) > 0) {
2834  rb_hash_foreach(hash, clear_i, 0);
2835  }
2836  else if (RHASH_AR_TABLE_P(hash)) {
2837  ar_clear(hash);
2838  }
2839  else {
2840  st_clear(RHASH_ST_TABLE(hash));
2841  }
2842 
2843  return hash;
2844 }
2845 
2846 static int
2847 hash_aset(st_data_t *key, st_data_t *val, struct update_arg *arg, int existing)
2848 {
2849  *val = arg->arg;
2850  return ST_CONTINUE;
2851 }
2852 
2853 VALUE
2854 rb_hash_key_str(VALUE key)
2855 {
2856  if (!RB_FL_ANY_RAW(key, FL_EXIVAR) && RBASIC_CLASS(key) == rb_cString) {
2857  return rb_fstring(key);
2858  }
2859  else {
2860  return rb_str_new_frozen(key);
2861  }
2862 }
2863 
2864 static int
2865 hash_aset_str(st_data_t *key, st_data_t *val, struct update_arg *arg, int existing)
2866 {
2867  if (!existing && !RB_OBJ_FROZEN(*key)) {
2868  *key = rb_hash_key_str(*key);
2869  }
2870  return hash_aset(key, val, arg, existing);
2871 }
2872 
2873 NOINSERT_UPDATE_CALLBACK(hash_aset)
2874 NOINSERT_UPDATE_CALLBACK(hash_aset_str)
2875 
2876 /*
2877  * call-seq:
2878  * hash[key] = value -> value
2879  * hash.store(key, value)
2880  *
2881  * Hash#store is an alias for Hash#[]=.
2882 
2883  * Associates the given +value+ with the given +key+; returns +value+.
2884  *
2885  * If the given +key+ exists, replaces its value with the given +value+;
2886  * the ordering is not affected
2887  * (see {Entry Order}[#class-Hash-label-Entry+Order]):
2888  * h = {foo: 0, bar: 1}
2889  * h[:foo] = 2 # => 2
2890  * h.store(:bar, 3) # => 3
2891  * h # => {:foo=>2, :bar=>3}
2892  *
2893  * If +key+ does not exist, adds the +key+ and +value+;
2894  * the new entry is last in the order
2895  * (see {Entry Order}[#class-Hash-label-Entry+Order]):
2896  * h = {foo: 0, bar: 1}
2897  * h[:baz] = 2 # => 2
2898  * h.store(:bat, 3) # => 3
2899  * h # => {:foo=>0, :bar=>1, :baz=>2, :bat=>3}
2900  */
2901 
2902 VALUE
2904 {
2905  int iter_lev = RHASH_ITER_LEV(hash);
2906 
2907  rb_hash_modify(hash);
2908 
2909  if (RHASH_TABLE_NULL_P(hash)) {
2910  if (iter_lev > 0) no_new_key();
2911  ar_alloc_table(hash);
2912  }
2913 
2914  if (RHASH_TYPE(hash) == &identhash || rb_obj_class(key) != rb_cString) {
2915  RHASH_UPDATE_ITER(hash, iter_lev, key, hash_aset, val);
2916  }
2917  else {
2918  RHASH_UPDATE_ITER(hash, iter_lev, key, hash_aset_str, val);
2919  }
2920  return val;
2921 }
2922 
2923 /*
2924  * call-seq:
2925  * hash.replace(other_hash) -> self
2926  *
2927  * Replaces the entire contents of +self+ with the contents of +other_hash+;
2928  * returns +self+:
2929  * h = {foo: 0, bar: 1, baz: 2}
2930  * h.replace({bat: 3, bam: 4}) # => {:bat=>3, :bam=>4}
2931  */
2932 
2933 static VALUE
2934 rb_hash_replace(VALUE hash, VALUE hash2)
2935 {
2936  rb_hash_modify_check(hash);
2937  if (hash == hash2) return hash;
2938  if (RHASH_ITER_LEV(hash) > 0) {
2939  rb_raise(rb_eRuntimeError, "can't replace hash during iteration");
2940  }
2941  hash2 = to_hash(hash2);
2942 
2943  COPY_DEFAULT(hash, hash2);
2944 
2945  if (RHASH_AR_TABLE_P(hash)) {
2946  ar_free_and_clear_table(hash);
2947  }
2948  else {
2949  st_free_table(RHASH_ST_TABLE(hash));
2950  RHASH_ST_CLEAR(hash);
2951  }
2952  hash_copy(hash, hash2);
2953  if (RHASH_EMPTY_P(hash2) && RHASH_ST_TABLE_P(hash2)) {
2954  /* ident hash */
2955  RHASH_ST_TABLE_SET(hash, st_init_table_with_size(RHASH_TYPE(hash2), 0));
2956  }
2957 
2958  rb_gc_writebarrier_remember(hash);
2959 
2960  return hash;
2961 }
2962 
2963 /*
2964  * call-seq:
2965  * hash.length -> integer
2966  * hash.size -> integer
2967  *
2968  * Returns the count of entries in +self+:
2969  * {foo: 0, bar: 1, baz: 2}.length # => 3
2970  *
2971  * Hash#length is an alias for Hash#size.
2972  */
2973 
2974 VALUE
2976 {
2977  return INT2FIX(RHASH_SIZE(hash));
2978 }
2979 
2980 size_t
2982 {
2983  return (long)RHASH_SIZE(hash);
2984 }
2985 
2986 /*
2987  * call-seq:
2988  * hash.empty? -> true or false
2989  *
2990  * Returns +true+ if there are no hash entries, +false+ otherwise:
2991  * {}.empty? # => true
2992  * {foo: 0, bar: 1, baz: 2}.empty? # => false
2993  */
2994 
2995 static VALUE
2996 rb_hash_empty_p(VALUE hash)
2997 {
2998  return RBOOL(RHASH_EMPTY_P(hash));
2999 }
3000 
3001 static int
3002 each_value_i(VALUE key, VALUE value, VALUE _)
3003 {
3004  rb_yield(value);
3005  return ST_CONTINUE;
3006 }
3007 
3008 /*
3009  * call-seq:
3010  * hash.each_value {|value| ... } -> self
3011  * hash.each_value -> new_enumerator
3012  *
3013  * Calls the given block with each value; returns +self+:
3014  * h = {foo: 0, bar: 1, baz: 2}
3015  * h.each_value {|value| puts value } # => {:foo=>0, :bar=>1, :baz=>2}
3016  * Output:
3017  * 0
3018  * 1
3019  * 2
3020  *
3021  * Returns a new \Enumerator if no block given:
3022  * h = {foo: 0, bar: 1, baz: 2}
3023  * e = h.each_value # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_value>
3024  * h1 = e.each {|value| puts value }
3025  * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3026  * Output:
3027  * 0
3028  * 1
3029  * 2
3030  */
3031 
3032 static VALUE
3033 rb_hash_each_value(VALUE hash)
3034 {
3035  RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3036  rb_hash_foreach(hash, each_value_i, 0);
3037  return hash;
3038 }
3039 
3040 static int
3041 each_key_i(VALUE key, VALUE value, VALUE _)
3042 {
3043  rb_yield(key);
3044  return ST_CONTINUE;
3045 }
3046 
3047 /*
3048  * call-seq:
3049  * hash.each_key {|key| ... } -> self
3050  * hash.each_key -> new_enumerator
3051  *
3052  * Calls the given block with each key; returns +self+:
3053  * h = {foo: 0, bar: 1, baz: 2}
3054  * h.each_key {|key| puts key } # => {:foo=>0, :bar=>1, :baz=>2}
3055  * Output:
3056  * foo
3057  * bar
3058  * baz
3059  *
3060  * Returns a new \Enumerator if no block given:
3061  * h = {foo: 0, bar: 1, baz: 2}
3062  * e = h.each_key # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_key>
3063  * h1 = e.each {|key| puts key }
3064  * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3065  * Output:
3066  * foo
3067  * bar
3068  * baz
3069  */
3070 static VALUE
3071 rb_hash_each_key(VALUE hash)
3072 {
3073  RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3074  rb_hash_foreach(hash, each_key_i, 0);
3075  return hash;
3076 }
3077 
3078 static int
3079 each_pair_i(VALUE key, VALUE value, VALUE _)
3080 {
3081  rb_yield(rb_assoc_new(key, value));
3082  return ST_CONTINUE;
3083 }
3084 
3085 static int
3086 each_pair_i_fast(VALUE key, VALUE value, VALUE _)
3087 {
3088  VALUE argv[2];
3089  argv[0] = key;
3090  argv[1] = value;
3091  rb_yield_values2(2, argv);
3092  return ST_CONTINUE;
3093 }
3094 
3095 /*
3096  * call-seq:
3097  * hash.each {|key, value| ... } -> self
3098  * hash.each_pair {|key, value| ... } -> self
3099  * hash.each -> new_enumerator
3100  * hash.each_pair -> new_enumerator
3101  *
3102  * Hash#each is an alias for Hash#each_pair.
3103 
3104  * Calls the given block with each key-value pair; returns +self+:
3105  * h = {foo: 0, bar: 1, baz: 2}
3106  * h.each_pair {|key, value| puts "#{key}: #{value}"} # => {:foo=>0, :bar=>1, :baz=>2}
3107  * Output:
3108  * foo: 0
3109  * bar: 1
3110  * baz: 2
3111  *
3112  * Returns a new \Enumerator if no block given:
3113  * h = {foo: 0, bar: 1, baz: 2}
3114  * e = h.each_pair # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_pair>
3115  * h1 = e.each {|key, value| puts "#{key}: #{value}"}
3116  * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3117  * Output:
3118  * foo: 0
3119  * bar: 1
3120  * baz: 2
3121  */
3122 
3123 static VALUE
3124 rb_hash_each_pair(VALUE hash)
3125 {
3126  RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3127  if (rb_block_pair_yield_optimizable())
3128  rb_hash_foreach(hash, each_pair_i_fast, 0);
3129  else
3130  rb_hash_foreach(hash, each_pair_i, 0);
3131  return hash;
3132 }
3133 
3135  VALUE trans;
3136  VALUE result;
3137  int block_given;
3138 };
3139 
3140 static int
3141 transform_keys_hash_i(VALUE key, VALUE value, VALUE transarg)
3142 {
3143  struct transform_keys_args *p = (void *)transarg;
3144  VALUE trans = p->trans, result = p->result;
3145  VALUE new_key = rb_hash_lookup2(trans, key, Qundef);
3146  if (new_key == Qundef) {
3147  if (p->block_given)
3148  new_key = rb_yield(key);
3149  else
3150  new_key = key;
3151  }
3152  rb_hash_aset(result, new_key, value);
3153  return ST_CONTINUE;
3154 }
3155 
3156 static int
3157 transform_keys_i(VALUE key, VALUE value, VALUE result)
3158 {
3159  VALUE new_key = rb_yield(key);
3160  rb_hash_aset(result, new_key, value);
3161  return ST_CONTINUE;
3162 }
3163 
3164 /*
3165  * call-seq:
3166  * hash.transform_keys {|key| ... } -> new_hash
3167  * hash.transform_keys(hash2) -> new_hash
3168  * hash.transform_keys(hash2) {|other_key| ...} -> new_hash
3169  * hash.transform_keys -> new_enumerator
3170  *
3171  * Returns a new \Hash object; each entry has:
3172  * * A key provided by the block.
3173  * * The value from +self+.
3174  *
3175  * An optional hash argument can be provided to map keys to new keys.
3176  * Any key not given will be mapped using the provided block,
3177  * or remain the same if no block is given.
3178  *
3179  * Transform keys:
3180  * h = {foo: 0, bar: 1, baz: 2}
3181  * h1 = h.transform_keys {|key| key.to_s }
3182  * h1 # => {"foo"=>0, "bar"=>1, "baz"=>2}
3183  *
3184  * h.transform_keys(foo: :bar, bar: :foo)
3185  * #=> {bar: 0, foo: 1, baz: 2}
3186  *
3187  * h.transform_keys(foo: :hello, &:to_s)
3188  * #=> {:hello=>0, "bar"=>1, "baz"=>2}
3189  *
3190  * Overwrites values for duplicate keys:
3191  * h = {foo: 0, bar: 1, baz: 2}
3192  * h1 = h.transform_keys {|key| :bat }
3193  * h1 # => {:bat=>2}
3194  *
3195  * Returns a new \Enumerator if no block given:
3196  * h = {foo: 0, bar: 1, baz: 2}
3197  * e = h.transform_keys # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:transform_keys>
3198  * h1 = e.each { |key| key.to_s }
3199  * h1 # => {"foo"=>0, "bar"=>1, "baz"=>2}
3200  */
3201 static VALUE
3202 rb_hash_transform_keys(int argc, VALUE *argv, VALUE hash)
3203 {
3204  VALUE result;
3205  struct transform_keys_args transarg = {0};
3206 
3207  argc = rb_check_arity(argc, 0, 1);
3208  if (argc > 0) {
3209  transarg.trans = to_hash(argv[0]);
3210  transarg.block_given = rb_block_given_p();
3211  }
3212  else {
3213  RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3214  }
3215  result = rb_hash_new();
3216  if (!RHASH_EMPTY_P(hash)) {
3217  if (transarg.trans) {
3218  transarg.result = result;
3219  rb_hash_foreach(hash, transform_keys_hash_i, (VALUE)&transarg);
3220  }
3221  else {
3222  rb_hash_foreach(hash, transform_keys_i, result);
3223  }
3224  }
3225 
3226  return result;
3227 }
3228 
3229 static int flatten_i(VALUE key, VALUE val, VALUE ary);
3230 
3231 /*
3232  * call-seq:
3233  * hash.transform_keys! {|key| ... } -> self
3234  * hash.transform_keys!(hash2) -> self
3235  * hash.transform_keys!(hash2) {|other_key| ...} -> self
3236  * hash.transform_keys! -> new_enumerator
3237  *
3238  * Same as Hash#transform_keys but modifies the receiver in place
3239  * instead of returning a new hash.
3240  */
3241 static VALUE
3242 rb_hash_transform_keys_bang(int argc, VALUE *argv, VALUE hash)
3243 {
3244  VALUE trans = 0;
3245  int block_given = 0;
3246 
3247  argc = rb_check_arity(argc, 0, 1);
3248  if (argc > 0) {
3249  trans = to_hash(argv[0]);
3250  block_given = rb_block_given_p();
3251  }
3252  else {
3253  RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3254  }
3255  rb_hash_modify_check(hash);
3256  if (!RHASH_TABLE_EMPTY_P(hash)) {
3257  long i;
3258  VALUE new_keys = hash_alloc(0);
3259  VALUE pairs = rb_ary_tmp_new(RHASH_SIZE(hash) * 2);
3260  rb_hash_foreach(hash, flatten_i, pairs);
3261  for (i = 0; i < RARRAY_LEN(pairs); i += 2) {
3262  VALUE key = RARRAY_AREF(pairs, i), new_key, val;
3263 
3264  if (!trans) {
3265  new_key = rb_yield(key);
3266  }
3267  else if ((new_key = rb_hash_lookup2(trans, key, Qundef)) != Qundef) {
3268  /* use the transformed key */
3269  }
3270  else if (block_given) {
3271  new_key = rb_yield(key);
3272  }
3273  else {
3274  new_key = key;
3275  }
3276  val = RARRAY_AREF(pairs, i+1);
3277  if (!hash_stlike_lookup(new_keys, key, NULL)) {
3278  rb_hash_stlike_delete(hash, &key, NULL);
3279  }
3280  rb_hash_aset(hash, new_key, val);
3281  rb_hash_aset(new_keys, new_key, Qnil);
3282  }
3283  rb_ary_clear(pairs);
3284  rb_hash_clear(new_keys);
3285  }
3286  return hash;
3287 }
3288 
3289 static int
3290 transform_values_foreach_func(st_data_t key, st_data_t value, st_data_t argp, int error)
3291 {
3292  return ST_REPLACE;
3293 }
3294 
3295 static int
3296 transform_values_foreach_replace(st_data_t *key, st_data_t *value, st_data_t argp, int existing)
3297 {
3298  VALUE new_value = rb_yield((VALUE)*value);
3299  VALUE hash = (VALUE)argp;
3300  rb_hash_modify(hash);
3301  RB_OBJ_WRITE(hash, value, new_value);
3302  return ST_CONTINUE;
3303 }
3304 
3305 /*
3306  * call-seq:
3307  * hash.transform_values {|value| ... } -> new_hash
3308  * hash.transform_values -> new_enumerator
3309  *
3310  * Returns a new \Hash object; each entry has:
3311  * * A key from +self+.
3312  * * A value provided by the block.
3313  *
3314  * Transform values:
3315  * h = {foo: 0, bar: 1, baz: 2}
3316  * h1 = h.transform_values {|value| value * 100}
3317  * h1 # => {:foo=>0, :bar=>100, :baz=>200}
3318  *
3319  * Returns a new \Enumerator if no block given:
3320  * h = {foo: 0, bar: 1, baz: 2}
3321  * e = h.transform_values # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:transform_values>
3322  * h1 = e.each { |value| value * 100}
3323  * h1 # => {:foo=>0, :bar=>100, :baz=>200}
3324  */
3325 static VALUE
3326 rb_hash_transform_values(VALUE hash)
3327 {
3328  VALUE result;
3329 
3330  RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3331  result = hash_dup_with_compare_by_id(hash);
3332  SET_DEFAULT(result, Qnil);
3333 
3334  if (!RHASH_EMPTY_P(hash)) {
3335  rb_hash_stlike_foreach_with_replace(result, transform_values_foreach_func, transform_values_foreach_replace, result);
3336  }
3337 
3338  return result;
3339 }
3340 
3341 /*
3342  * call-seq:
3343  * hash.transform_values! {|value| ... } -> self
3344  * hash.transform_values! -> new_enumerator
3345  *
3346  * Returns +self+, whose keys are unchanged, and whose values are determined by the given block.
3347  * h = {foo: 0, bar: 1, baz: 2}
3348  * h.transform_values! {|value| value * 100} # => {:foo=>0, :bar=>100, :baz=>200}
3349  *
3350  * Returns a new \Enumerator if no block given:
3351  * h = {foo: 0, bar: 1, baz: 2}
3352  * e = h.transform_values! # => #<Enumerator: {:foo=>0, :bar=>100, :baz=>200}:transform_values!>
3353  * h1 = e.each {|value| value * 100}
3354  * h1 # => {:foo=>0, :bar=>100, :baz=>200}
3355  */
3356 static VALUE
3357 rb_hash_transform_values_bang(VALUE hash)
3358 {
3359  RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3360  rb_hash_modify_check(hash);
3361 
3362  if (!RHASH_TABLE_EMPTY_P(hash)) {
3363  rb_hash_stlike_foreach_with_replace(hash, transform_values_foreach_func, transform_values_foreach_replace, hash);
3364  }
3365 
3366  return hash;
3367 }
3368 
3369 static int
3370 to_a_i(VALUE key, VALUE value, VALUE ary)
3371 {
3372  rb_ary_push(ary, rb_assoc_new(key, value));
3373  return ST_CONTINUE;
3374 }
3375 
3376 /*
3377  * call-seq:
3378  * hash.to_a -> new_array
3379  *
3380  * Returns a new \Array of 2-element \Array objects;
3381  * each nested \Array contains a key-value pair from +self+:
3382  * h = {foo: 0, bar: 1, baz: 2}
3383  * h.to_a # => [[:foo, 0], [:bar, 1], [:baz, 2]]
3384  */
3385 
3386 static VALUE
3387 rb_hash_to_a(VALUE hash)
3388 {
3389  VALUE ary;
3390 
3391  ary = rb_ary_new_capa(RHASH_SIZE(hash));
3392  rb_hash_foreach(hash, to_a_i, ary);
3393 
3394  return ary;
3395 }
3396 
3397 static int
3398 inspect_i(VALUE key, VALUE value, VALUE str)
3399 {
3400  VALUE str2;
3401 
3402  str2 = rb_inspect(key);
3403  if (RSTRING_LEN(str) > 1) {
3404  rb_str_buf_cat_ascii(str, ", ");
3405  }
3406  else {
3407  rb_enc_copy(str, str2);
3408  }
3409  rb_str_buf_append(str, str2);
3410  rb_str_buf_cat_ascii(str, "=>");
3411  str2 = rb_inspect(value);
3412  rb_str_buf_append(str, str2);
3413 
3414  return ST_CONTINUE;
3415 }
3416 
3417 static VALUE
3418 inspect_hash(VALUE hash, VALUE dummy, int recur)
3419 {
3420  VALUE str;
3421 
3422  if (recur) return rb_usascii_str_new2("{...}");
3423  str = rb_str_buf_new2("{");
3424  rb_hash_foreach(hash, inspect_i, str);
3425  rb_str_buf_cat2(str, "}");
3426 
3427  return str;
3428 }
3429 
3430 /*
3431  * call-seq:
3432  * hash.inspect -> new_string
3433  *
3434  * Returns a new \String containing the hash entries:
3435  * h = {foo: 0, bar: 1, baz: 2}
3436  * h.inspect # => "{:foo=>0, :bar=>1, :baz=>2}"
3437  *
3438  * Hash#to_s is an alias for Hash#inspect.
3439  */
3440 
3441 static VALUE
3442 rb_hash_inspect(VALUE hash)
3443 {
3444  if (RHASH_EMPTY_P(hash))
3445  return rb_usascii_str_new2("{}");
3446  return rb_exec_recursive(inspect_hash, hash, 0);
3447 }
3448 
3449 /*
3450  * call-seq:
3451  * hash.to_hash -> self
3452  *
3453  * Returns +self+.
3454  */
3455 static VALUE
3456 rb_hash_to_hash(VALUE hash)
3457 {
3458  return hash;
3459 }
3460 
3461 VALUE
3462 rb_hash_set_pair(VALUE hash, VALUE arg)
3463 {
3464  VALUE pair;
3465 
3466  pair = rb_check_array_type(arg);
3467  if (NIL_P(pair)) {
3468  rb_raise(rb_eTypeError, "wrong element type %s (expected array)",
3469  rb_builtin_class_name(arg));
3470  }
3471  if (RARRAY_LEN(pair) != 2) {
3472  rb_raise(rb_eArgError, "element has wrong array length (expected 2, was %ld)",
3473  RARRAY_LEN(pair));
3474  }
3475  rb_hash_aset(hash, RARRAY_AREF(pair, 0), RARRAY_AREF(pair, 1));
3476  return hash;
3477 }
3478 
3479 static int
3480 to_h_i(VALUE key, VALUE value, VALUE hash)
3481 {
3482  rb_hash_set_pair(hash, rb_yield_values(2, key, value));
3483  return ST_CONTINUE;
3484 }
3485 
3486 static VALUE
3487 rb_hash_to_h_block(VALUE hash)
3488 {
3489  VALUE h = rb_hash_new_with_size(RHASH_SIZE(hash));
3490  rb_hash_foreach(hash, to_h_i, h);
3491  return h;
3492 }
3493 
3494 /*
3495  * call-seq:
3496  * hash.to_h -> self or new_hash
3497  * hash.to_h {|key, value| ... } -> new_hash
3498  *
3499  * For an instance of \Hash, returns +self+.
3500  *
3501  * For a subclass of \Hash, returns a new \Hash
3502  * containing the content of +self+.
3503  *
3504  * When a block is given, returns a new \Hash object
3505  * whose content is based on the block;
3506  * the block should return a 2-element \Array object
3507  * specifying the key-value pair to be included in the returned \Array:
3508  * h = {foo: 0, bar: 1, baz: 2}
3509  * h1 = h.to_h {|key, value| [value, key] }
3510  * h1 # => {0=>:foo, 1=>:bar, 2=>:baz}
3511  */
3512 
3513 static VALUE
3514 rb_hash_to_h(VALUE hash)
3515 {
3516  if (rb_block_given_p()) {
3517  return rb_hash_to_h_block(hash);
3518  }
3519  if (rb_obj_class(hash) != rb_cHash) {
3520  const VALUE flags = RBASIC(hash)->flags;
3521  hash = hash_dup(hash, rb_cHash, flags & RHASH_PROC_DEFAULT);
3522  }
3523  return hash;
3524 }
3525 
3526 static int
3527 keys_i(VALUE key, VALUE value, VALUE ary)
3528 {
3529  rb_ary_push(ary, key);
3530  return ST_CONTINUE;
3531 }
3532 
3533 /*
3534  * call-seq:
3535  * hash.keys -> new_array
3536  *
3537  * Returns a new \Array containing all keys in +self+:
3538  * h = {foo: 0, bar: 1, baz: 2}
3539  * h.keys # => [:foo, :bar, :baz]
3540  */
3541 
3542 MJIT_FUNC_EXPORTED VALUE
3543 rb_hash_keys(VALUE hash)
3544 {
3545  st_index_t size = RHASH_SIZE(hash);
3546  VALUE keys = rb_ary_new_capa(size);
3547 
3548  if (size == 0) return keys;
3549 
3550  if (ST_DATA_COMPATIBLE_P(VALUE)) {
3551  RARRAY_PTR_USE_TRANSIENT(keys, ptr, {
3552  if (RHASH_AR_TABLE_P(hash)) {
3553  size = ar_keys(hash, ptr, size);
3554  }
3555  else {
3556  st_table *table = RHASH_ST_TABLE(hash);
3557  size = st_keys(table, ptr, size);
3558  }
3559  });
3560  rb_gc_writebarrier_remember(keys);
3561  rb_ary_set_len(keys, size);
3562  }
3563  else {
3564  rb_hash_foreach(hash, keys_i, keys);
3565  }
3566 
3567  return keys;
3568 }
3569 
3570 static int
3571 values_i(VALUE key, VALUE value, VALUE ary)
3572 {
3573  rb_ary_push(ary, value);
3574  return ST_CONTINUE;
3575 }
3576 
3577 /*
3578  * call-seq:
3579  * hash.values -> new_array
3580  *
3581  * Returns a new \Array containing all values in +self+:
3582  * h = {foo: 0, bar: 1, baz: 2}
3583  * h.values # => [0, 1, 2]
3584  */
3585 
3586 VALUE
3587 rb_hash_values(VALUE hash)
3588 {
3589  VALUE values;
3590  st_index_t size = RHASH_SIZE(hash);
3591 
3592  values = rb_ary_new_capa(size);
3593  if (size == 0) return values;
3594 
3595  if (ST_DATA_COMPATIBLE_P(VALUE)) {
3596  if (RHASH_AR_TABLE_P(hash)) {
3597  rb_gc_writebarrier_remember(values);
3598  RARRAY_PTR_USE_TRANSIENT(values, ptr, {
3599  size = ar_values(hash, ptr, size);
3600  });
3601  }
3602  else if (RHASH_ST_TABLE_P(hash)) {
3603  st_table *table = RHASH_ST_TABLE(hash);
3604  rb_gc_writebarrier_remember(values);
3605  RARRAY_PTR_USE_TRANSIENT(values, ptr, {
3606  size = st_values(table, ptr, size);
3607  });
3608  }
3609  rb_ary_set_len(values, size);
3610  }
3611 
3612  else {
3613  rb_hash_foreach(hash, values_i, values);
3614  }
3615 
3616  return values;
3617 }
3618 
3619 /*
3620  * call-seq:
3621  * hash.include?(key) -> true or false
3622  * hash.has_key?(key) -> true or false
3623  * hash.key?(key) -> true or false
3624  * hash.member?(key) -> true or false
3625 
3626  * Methods #has_key?, #key?, and #member? are aliases for \#include?.
3627  *
3628  * Returns +true+ if +key+ is a key in +self+, otherwise +false+.
3629  */
3630 
3631 MJIT_FUNC_EXPORTED VALUE
3632 rb_hash_has_key(VALUE hash, VALUE key)
3633 {
3634  return RBOOL(hash_stlike_lookup(hash, key, NULL));
3635 }
3636 
3637 static int
3638 rb_hash_search_value(VALUE key, VALUE value, VALUE arg)
3639 {
3640  VALUE *data = (VALUE *)arg;
3641 
3642  if (rb_equal(value, data[1])) {
3643  data[0] = Qtrue;
3644  return ST_STOP;
3645  }
3646  return ST_CONTINUE;
3647 }
3648 
3649 /*
3650  * call-seq:
3651  * hash.has_value?(value) -> true or false
3652  * hash.value?(value) -> true or false
3653  *
3654  * Method #value? is an alias for \#has_value?.
3655  *
3656  * Returns +true+ if +value+ is a value in +self+, otherwise +false+.
3657  */
3658 
3659 static VALUE
3660 rb_hash_has_value(VALUE hash, VALUE val)
3661 {
3662  VALUE data[2];
3663 
3664  data[0] = Qfalse;
3665  data[1] = val;
3666  rb_hash_foreach(hash, rb_hash_search_value, (VALUE)data);
3667  return data[0];
3668 }
3669 
3670 struct equal_data {
3671  VALUE result;
3672  VALUE hash;
3673  int eql;
3674 };
3675 
3676 static int
3677 eql_i(VALUE key, VALUE val1, VALUE arg)
3678 {
3679  struct equal_data *data = (struct equal_data *)arg;
3680  st_data_t val2;
3681 
3682  if (!hash_stlike_lookup(data->hash, key, &val2)) {
3683  data->result = Qfalse;
3684  return ST_STOP;
3685  }
3686  else {
3687  if (!(data->eql ? rb_eql(val1, (VALUE)val2) : (int)rb_equal(val1, (VALUE)val2))) {
3688  data->result = Qfalse;
3689  return ST_STOP;
3690  }
3691  return ST_CONTINUE;
3692  }
3693 }
3694 
3695 static VALUE
3696 recursive_eql(VALUE hash, VALUE dt, int recur)
3697 {
3698  struct equal_data *data;
3699 
3700  if (recur) return Qtrue; /* Subtle! */
3701  data = (struct equal_data*)dt;
3702  data->result = Qtrue;
3703  rb_hash_foreach(hash, eql_i, dt);
3704 
3705  return data->result;
3706 }
3707 
3708 static VALUE
3709 hash_equal(VALUE hash1, VALUE hash2, int eql)
3710 {
3711  struct equal_data data;
3712 
3713  if (hash1 == hash2) return Qtrue;
3714  if (!RB_TYPE_P(hash2, T_HASH)) {
3715  if (!rb_respond_to(hash2, idTo_hash)) {
3716  return Qfalse;
3717  }
3718  if (eql) {
3719  if (rb_eql(hash2, hash1)) {
3720  return Qtrue;
3721  }
3722  else {
3723  return Qfalse;
3724  }
3725  }
3726  else {
3727  return rb_equal(hash2, hash1);
3728  }
3729  }
3730  if (RHASH_SIZE(hash1) != RHASH_SIZE(hash2))
3731  return Qfalse;
3732  if (!RHASH_TABLE_EMPTY_P(hash1) && !RHASH_TABLE_EMPTY_P(hash2)) {
3733  if (RHASH_TYPE(hash1) != RHASH_TYPE(hash2)) {
3734  return Qfalse;
3735  }
3736  else {
3737  data.hash = hash2;
3738  data.eql = eql;
3739  return rb_exec_recursive_paired(recursive_eql, hash1, hash2, (VALUE)&data);
3740  }
3741  }
3742 
3743 #if 0
3744  if (!(rb_equal(RHASH_IFNONE(hash1), RHASH_IFNONE(hash2)) &&
3745  FL_TEST(hash1, RHASH_PROC_DEFAULT) == FL_TEST(hash2, RHASH_PROC_DEFAULT)))
3746  return Qfalse;
3747 #endif
3748  return Qtrue;
3749 }
3750 
3751 /*
3752  * call-seq:
3753  * hash == object -> true or false
3754  *
3755  * Returns +true+ if all of the following are true:
3756  * * +object+ is a \Hash object.
3757  * * +hash+ and +object+ have the same keys (regardless of order).
3758  * * For each key +key+, <tt>hash[key] == object[key]</tt>.
3759  *
3760  * Otherwise, returns +false+.
3761  *
3762  * Equal:
3763  * h1 = {foo: 0, bar: 1, baz: 2}
3764  * h2 = {foo: 0, bar: 1, baz: 2}
3765  * h1 == h2 # => true
3766  * h3 = {baz: 2, bar: 1, foo: 0}
3767  * h1 == h3 # => true
3768  */
3769 
3770 static VALUE
3771 rb_hash_equal(VALUE hash1, VALUE hash2)
3772 {
3773  return hash_equal(hash1, hash2, FALSE);
3774 }
3775 
3776 /*
3777  * call-seq:
3778  * hash.eql? object -> true or false
3779  *
3780  * Returns +true+ if all of the following are true:
3781  * * +object+ is a \Hash object.
3782  * * +hash+ and +object+ have the same keys (regardless of order).
3783  * * For each key +key+, <tt>h[key] eql? object[key]</tt>.
3784  *
3785  * Otherwise, returns +false+.
3786  *
3787  * Equal:
3788  * h1 = {foo: 0, bar: 1, baz: 2}
3789  * h2 = {foo: 0, bar: 1, baz: 2}
3790  * h1.eql? h2 # => true
3791  * h3 = {baz: 2, bar: 1, foo: 0}
3792  * h1.eql? h3 # => true
3793  */
3794 
3795 static VALUE
3796 rb_hash_eql(VALUE hash1, VALUE hash2)
3797 {
3798  return hash_equal(hash1, hash2, TRUE);
3799 }
3800 
3801 static int
3802 hash_i(VALUE key, VALUE val, VALUE arg)
3803 {
3804  st_index_t *hval = (st_index_t *)arg;
3805  st_index_t hdata[2];
3806 
3807  hdata[0] = rb_hash(key);
3808  hdata[1] = rb_hash(val);
3809  *hval ^= st_hash(hdata, sizeof(hdata), 0);
3810  return ST_CONTINUE;
3811 }
3812 
3813 /*
3814  * call-seq:
3815  * hash.hash -> an_integer
3816  *
3817  * Returns the \Integer hash-code for the hash.
3818  *
3819  * Two \Hash objects have the same hash-code if their content is the same
3820  * (regardless or order):
3821  * h1 = {foo: 0, bar: 1, baz: 2}
3822  * h2 = {baz: 2, bar: 1, foo: 0}
3823  * h2.hash == h1.hash # => true
3824  * h2.eql? h1 # => true
3825  */
3826 
3827 static VALUE
3828 rb_hash_hash(VALUE hash)
3829 {
3830  st_index_t size = RHASH_SIZE(hash);
3831  st_index_t hval = rb_hash_start(size);
3832  hval = rb_hash_uint(hval, (st_index_t)rb_hash_hash);
3833  if (size) {
3834  rb_hash_foreach(hash, hash_i, (VALUE)&hval);
3835  }
3836  hval = rb_hash_end(hval);
3837  return ST2FIX(hval);
3838 }
3839 
3840 static int
3841 rb_hash_invert_i(VALUE key, VALUE value, VALUE hash)
3842 {
3843  rb_hash_aset(hash, value, key);
3844  return ST_CONTINUE;
3845 }
3846 
3847 /*
3848  * call-seq:
3849  * hash.invert -> new_hash
3850  *
3851  * Returns a new \Hash object with the each key-value pair inverted:
3852  * h = {foo: 0, bar: 1, baz: 2}
3853  * h1 = h.invert
3854  * h1 # => {0=>:foo, 1=>:bar, 2=>:baz}
3855  *
3856  * Overwrites any repeated new keys:
3857  * (see {Entry Order}[#class-Hash-label-Entry+Order]):
3858  * h = {foo: 0, bar: 0, baz: 0}
3859  * h.invert # => {0=>:baz}
3860  */
3861 
3862 static VALUE
3863 rb_hash_invert(VALUE hash)
3864 {
3865  VALUE h = rb_hash_new_with_size(RHASH_SIZE(hash));
3866 
3867  rb_hash_foreach(hash, rb_hash_invert_i, h);
3868  return h;
3869 }
3870 
3871 static int
3872 rb_hash_update_callback(st_data_t *key, st_data_t *value, struct update_arg *arg, int existing)
3873 {
3874  *value = arg->arg;
3875  return ST_CONTINUE;
3876 }
3877 
3878 NOINSERT_UPDATE_CALLBACK(rb_hash_update_callback)
3879 
3880 static int
3881 rb_hash_update_i(VALUE key, VALUE value, VALUE hash)
3882 {
3883  RHASH_UPDATE(hash, key, rb_hash_update_callback, value);
3884  return ST_CONTINUE;
3885 }
3886 
3887 static int
3888 rb_hash_update_block_callback(st_data_t *key, st_data_t *value, struct update_arg *arg, int existing)
3889 {
3890  st_data_t newvalue = arg->arg;
3891 
3892  if (existing) {
3893  newvalue = (st_data_t)rb_yield_values(3, (VALUE)*key, (VALUE)*value, (VALUE)newvalue);
3894  }
3895  *value = newvalue;
3896  return ST_CONTINUE;
3897 }
3898 
3899 NOINSERT_UPDATE_CALLBACK(rb_hash_update_block_callback)
3900 
3901 static int
3902 rb_hash_update_block_i(VALUE key, VALUE value, VALUE hash)
3903 {
3904  RHASH_UPDATE(hash, key, rb_hash_update_block_callback, value);
3905  return ST_CONTINUE;
3906 }
3907 
3908 /*
3909  * call-seq:
3910  * hash.merge! -> self
3911  * hash.merge!(*other_hashes) -> self
3912  * hash.merge!(*other_hashes) { |key, old_value, new_value| ... } -> self
3913  *
3914  * Merges each of +other_hashes+ into +self+; returns +self+.
3915  *
3916  * Each argument in +other_hashes+ must be a \Hash.
3917  *
3918  * \Method #update is an alias for \#merge!.
3919  *
3920  * With arguments and no block:
3921  * * Returns +self+, after the given hashes are merged into it.
3922  * * The given hashes are merged left to right.
3923  * * Each new entry is added at the end.
3924  * * Each duplicate-key entry's value overwrites the previous value.
3925  *
3926  * Example:
3927  * h = {foo: 0, bar: 1, baz: 2}
3928  * h1 = {bat: 3, bar: 4}
3929  * h2 = {bam: 5, bat:6}
3930  * h.merge!(h1, h2) # => {:foo=>0, :bar=>4, :baz=>2, :bat=>6, :bam=>5}
3931  *
3932  * With arguments and a block:
3933  * * Returns +self+, after the given hashes are merged.
3934  * * The given hashes are merged left to right.
3935  * * Each new-key entry is added at the end.
3936  * * For each duplicate key:
3937  * * Calls the block with the key and the old and new values.
3938  * * The block's return value becomes the new value for the entry.
3939  *
3940  * Example:
3941  * h = {foo: 0, bar: 1, baz: 2}
3942  * h1 = {bat: 3, bar: 4}
3943  * h2 = {bam: 5, bat:6}
3944  * h3 = h.merge!(h1, h2) { |key, old_value, new_value| old_value + new_value }
3945  * h3 # => {:foo=>0, :bar=>5, :baz=>2, :bat=>9, :bam=>5}
3946  *
3947  * With no arguments:
3948  * * Returns +self+, unmodified.
3949  * * The block, if given, is ignored.
3950  *
3951  * Example:
3952  * h = {foo: 0, bar: 1, baz: 2}
3953  * h.merge # => {:foo=>0, :bar=>1, :baz=>2}
3954  * h1 = h.merge! { |key, old_value, new_value| raise 'Cannot happen' }
3955  * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3956  */
3957 
3958 static VALUE
3959 rb_hash_update(int argc, VALUE *argv, VALUE self)
3960 {
3961  int i;
3962  bool block_given = rb_block_given_p();
3963 
3964  rb_hash_modify(self);
3965  for (i = 0; i < argc; i++){
3966  VALUE hash = to_hash(argv[i]);
3967  if (block_given) {
3968  rb_hash_foreach(hash, rb_hash_update_block_i, self);
3969  }
3970  else {
3971  rb_hash_foreach(hash, rb_hash_update_i, self);
3972  }
3973  }
3974  return self;
3975 }
3976 
3978  VALUE hash;
3979  VALUE value;
3980  rb_hash_update_func *func;
3981 };
3982 
3983 static int
3984 rb_hash_update_func_callback(st_data_t *key, st_data_t *value, struct update_arg *arg, int existing)
3985 {
3986  struct update_func_arg *uf_arg = (struct update_func_arg *)arg->arg;
3987  VALUE newvalue = uf_arg->value;
3988 
3989  if (existing) {
3990  newvalue = (*uf_arg->func)((VALUE)*key, (VALUE)*value, newvalue);
3991  }
3992  *value = newvalue;
3993  return ST_CONTINUE;
3994 }
3995 
3996 NOINSERT_UPDATE_CALLBACK(rb_hash_update_func_callback)
3997 
3998 static int
3999 rb_hash_update_func_i(VALUE key, VALUE value, VALUE arg0)
4000 {
4001  struct update_func_arg *arg = (struct update_func_arg *)arg0;
4002  VALUE hash = arg->hash;
4003 
4004  arg->value = value;
4005  RHASH_UPDATE(hash, key, rb_hash_update_func_callback, (VALUE)arg);
4006  return ST_CONTINUE;
4007 }
4008 
4009 VALUE
4011 {
4012  rb_hash_modify(hash1);
4013  hash2 = to_hash(hash2);
4014  if (func) {
4015  struct update_func_arg arg;
4016  arg.hash = hash1;
4017  arg.func = func;
4018  rb_hash_foreach(hash2, rb_hash_update_func_i, (VALUE)&arg);
4019  }
4020  else {
4021  rb_hash_foreach(hash2, rb_hash_update_i, hash1);
4022  }
4023  return hash1;
4024 }
4025 
4026 /*
4027  * call-seq:
4028  * hash.merge -> copy_of_self
4029  * hash.merge(*other_hashes) -> new_hash
4030  * hash.merge(*other_hashes) { |key, old_value, new_value| ... } -> new_hash
4031  *
4032  * Returns the new \Hash formed by merging each of +other_hashes+
4033  * into a copy of +self+.
4034  *
4035  * Each argument in +other_hashes+ must be a \Hash.
4036  *
4037  * ---
4038  *
4039  * With arguments and no block:
4040  * * Returns the new \Hash object formed by merging each successive
4041  * \Hash in +other_hashes+ into +self+.
4042  * * Each new-key entry is added at the end.
4043  * * Each duplicate-key entry's value overwrites the previous value.
4044  *
4045  * Example:
4046  * h = {foo: 0, bar: 1, baz: 2}
4047  * h1 = {bat: 3, bar: 4}
4048  * h2 = {bam: 5, bat:6}
4049  * h.merge(h1, h2) # => {:foo=>0, :bar=>4, :baz=>2, :bat=>6, :bam=>5}
4050  *
4051  * With arguments and a block:
4052  * * Returns a new \Hash object that is the merge of +self+ and each given hash.
4053  * * The given hashes are merged left to right.
4054  * * Each new-key entry is added at the end.
4055  * * For each duplicate key:
4056  * * Calls the block with the key and the old and new values.
4057  * * The block's return value becomes the new value for the entry.
4058  *
4059  * Example:
4060  * h = {foo: 0, bar: 1, baz: 2}
4061  * h1 = {bat: 3, bar: 4}
4062  * h2 = {bam: 5, bat:6}
4063  * h3 = h.merge(h1, h2) { |key, old_value, new_value| old_value + new_value }
4064  * h3 # => {:foo=>0, :bar=>5, :baz=>2, :bat=>9, :bam=>5}
4065  *
4066  * With no arguments:
4067  * * Returns a copy of +self+.
4068  * * The block, if given, is ignored.
4069  *
4070  * Example:
4071  * h = {foo: 0, bar: 1, baz: 2}
4072  * h.merge # => {:foo=>0, :bar=>1, :baz=>2}
4073  * h1 = h.merge { |key, old_value, new_value| raise 'Cannot happen' }
4074  * h1 # => {:foo=>0, :bar=>1, :baz=>2}
4075  */
4076 
4077 static VALUE
4078 rb_hash_merge(int argc, VALUE *argv, VALUE self)
4079 {
4080  return rb_hash_update(argc, argv, copy_compare_by_id(rb_hash_dup(self), self));
4081 }
4082 
4083 static int
4084 assoc_cmp(VALUE a, VALUE b)
4085 {
4086  return !RTEST(rb_equal(a, b));
4087 }
4088 
4089 static VALUE
4090 lookup2_call(VALUE arg)
4091 {
4092  VALUE *args = (VALUE *)arg;
4093  return rb_hash_lookup2(args[0], args[1], Qundef);
4094 }
4095 
4097  VALUE hash;
4098  const struct st_hash_type *orighash;
4099 };
4100 
4101 static VALUE
4102 reset_hash_type(VALUE arg)
4103 {
4104  struct reset_hash_type_arg *p = (struct reset_hash_type_arg *)arg;
4105  HASH_ASSERT(RHASH_ST_TABLE_P(p->hash));
4106  RHASH_ST_TABLE(p->hash)->type = p->orighash;
4107  return Qundef;
4108 }
4109 
4110 static int
4111 assoc_i(VALUE key, VALUE val, VALUE arg)
4112 {
4113  VALUE *args = (VALUE *)arg;
4114 
4115  if (RTEST(rb_equal(args[0], key))) {
4116  args[1] = rb_assoc_new(key, val);
4117  return ST_STOP;
4118  }
4119  return ST_CONTINUE;
4120 }
4121 
4122 /*
4123  * call-seq:
4124  * hash.assoc(key) -> new_array or nil
4125  *
4126  * If the given +key+ is found, returns a 2-element \Array containing that key and its value:
4127  * h = {foo: 0, bar: 1, baz: 2}
4128  * h.assoc(:bar) # => [:bar, 1]
4129  *
4130  * Returns +nil+ if key +key+ is not found.
4131  */
4132 
4133 static VALUE
4134 rb_hash_assoc(VALUE hash, VALUE key)
4135 {
4136  st_table *table;
4137  const struct st_hash_type *orighash;
4138  VALUE args[2];
4139 
4140  if (RHASH_EMPTY_P(hash)) return Qnil;
4141 
4142  ar_force_convert_table(hash, __FILE__, __LINE__);
4143  HASH_ASSERT(RHASH_ST_TABLE_P(hash));
4144  table = RHASH_ST_TABLE(hash);
4145  orighash = table->type;
4146 
4147  if (orighash != &identhash) {
4148  VALUE value;
4149  struct reset_hash_type_arg ensure_arg;
4150  struct st_hash_type assochash;
4151 
4152  assochash.compare = assoc_cmp;
4153  assochash.hash = orighash->hash;
4154  table->type = &assochash;
4155  args[0] = hash;
4156  args[1] = key;
4157  ensure_arg.hash = hash;
4158  ensure_arg.orighash = orighash;
4159  value = rb_ensure(lookup2_call, (VALUE)&args, reset_hash_type, (VALUE)&ensure_arg);
4160  if (value != Qundef) return rb_assoc_new(key, value);
4161  }
4162 
4163  args[0] = key;
4164  args[1] = Qnil;
4165  rb_hash_foreach(hash, assoc_i, (VALUE)args);
4166  return args[1];
4167 }
4168 
4169 static int
4170 rassoc_i(VALUE key, VALUE val, VALUE arg)
4171 {
4172  VALUE *args = (VALUE *)arg;
4173 
4174  if (RTEST(rb_equal(args[0], val))) {
4175  args[1] = rb_assoc_new(key, val);
4176  return ST_STOP;
4177  }
4178  return ST_CONTINUE;
4179 }
4180 
4181 /*
4182  * call-seq:
4183  * hash.rassoc(value) -> new_array or nil
4184  *
4185  * Returns a new 2-element \Array consisting of the key and value
4186  * of the first-found entry whose value is <tt>==</tt> to value
4187  * (see {Entry Order}[#class-Hash-label-Entry+Order]):
4188  * h = {foo: 0, bar: 1, baz: 1}
4189  * h.rassoc(1) # => [:bar, 1]
4190  *
4191  * Returns +nil+ if no such value found.
4192  */
4193 
4194 static VALUE
4195 rb_hash_rassoc(VALUE hash, VALUE obj)
4196 {
4197  VALUE args[2];
4198 
4199  args[0] = obj;
4200  args[1] = Qnil;
4201  rb_hash_foreach(hash, rassoc_i, (VALUE)args);
4202  return args[1];
4203 }
4204 
4205 static int
4206 flatten_i(VALUE key, VALUE val, VALUE ary)
4207 {
4208  VALUE pair[2];
4209 
4210  pair[0] = key;
4211  pair[1] = val;
4212  rb_ary_cat(ary, pair, 2);
4213 
4214  return ST_CONTINUE;
4215 }
4216 
4217 /*
4218  * call-seq:
4219  * hash.flatten -> new_array
4220  * hash.flatten(level) -> new_array
4221  *
4222  * Returns a new \Array object that is a 1-dimensional flattening of +self+.
4223  *
4224  * ---
4225  *
4226  * By default, nested Arrays are not flattened:
4227  * h = {foo: 0, bar: [:bat, 3], baz: 2}
4228  * h.flatten # => [:foo, 0, :bar, [:bat, 3], :baz, 2]
4229  *
4230  * Takes the depth of recursive flattening from \Integer argument +level+:
4231  * h = {foo: 0, bar: [:bat, [:baz, [:bat, ]]]}
4232  * h.flatten(1) # => [:foo, 0, :bar, [:bat, [:baz, [:bat]]]]
4233  * h.flatten(2) # => [:foo, 0, :bar, :bat, [:baz, [:bat]]]
4234  * h.flatten(3) # => [:foo, 0, :bar, :bat, :baz, [:bat]]
4235  * h.flatten(4) # => [:foo, 0, :bar, :bat, :baz, :bat]
4236  *
4237  * When +level+ is negative, flattens all nested Arrays:
4238  * h = {foo: 0, bar: [:bat, [:baz, [:bat, ]]]}
4239  * h.flatten(-1) # => [:foo, 0, :bar, :bat, :baz, :bat]
4240  * h.flatten(-2) # => [:foo, 0, :bar, :bat, :baz, :bat]
4241  *
4242  * When +level+ is zero, returns the equivalent of #to_a :
4243  * h = {foo: 0, bar: [:bat, 3], baz: 2}
4244  * h.flatten(0) # => [[:foo, 0], [:bar, [:bat, 3]], [:baz, 2]]
4245  * h.flatten(0) == h.to_a # => true
4246  */
4247 
4248 static VALUE
4249 rb_hash_flatten(int argc, VALUE *argv, VALUE hash)
4250 {
4251  VALUE ary;
4252 
4253  rb_check_arity(argc, 0, 1);
4254 
4255  if (argc) {
4256  int level = NUM2INT(argv[0]);
4257 
4258  if (level == 0) return rb_hash_to_a(hash);
4259 
4260  ary = rb_ary_new_capa(RHASH_SIZE(hash) * 2);
4261  rb_hash_foreach(hash, flatten_i, ary);
4262  level--;
4263 
4264  if (level > 0) {
4265  VALUE ary_flatten_level = INT2FIX(level);
4266  rb_funcallv(ary, id_flatten_bang, 1, &ary_flatten_level);
4267  }
4268  else if (level < 0) {
4269  /* flatten recursively */
4270  rb_funcallv(ary, id_flatten_bang, 0, 0);
4271  }
4272  }
4273  else {
4274  ary = rb_ary_new_capa(RHASH_SIZE(hash) * 2);
4275  rb_hash_foreach(hash, flatten_i, ary);
4276  }
4277 
4278  return ary;
4279 }
4280 
4281 static int
4282 delete_if_nil(VALUE key, VALUE value, VALUE hash)
4283 {
4284  if (NIL_P(value)) {
4285  return ST_DELETE;
4286  }
4287  return ST_CONTINUE;
4288 }
4289 
4290 static int
4291 set_if_not_nil(VALUE key, VALUE value, VALUE hash)
4292 {
4293  if (!NIL_P(value)) {
4294  rb_hash_aset(hash, key, value);
4295  }
4296  return ST_CONTINUE;
4297 }
4298 
4299 /*
4300  * call-seq:
4301  * hash.compact -> new_hash
4302  *
4303  * Returns a copy of +self+ with all +nil+-valued entries removed:
4304  * h = {foo: 0, bar: nil, baz: 2, bat: nil}
4305  * h1 = h.compact
4306  * h1 # => {:foo=>0, :baz=>2}
4307  */
4308 
4309 static VALUE
4310 rb_hash_compact(VALUE hash)
4311 {
4312  VALUE result = rb_hash_new();
4313  if (!RHASH_EMPTY_P(hash)) {
4314  rb_hash_foreach(hash, set_if_not_nil, result);
4315  }
4316  return result;
4317 }
4318 
4319 /*
4320  * call-seq:
4321  * hash.compact! -> self or nil
4322  *
4323  * Returns +self+ with all its +nil+-valued entries removed (in place):
4324  * h = {foo: 0, bar: nil, baz: 2, bat: nil}
4325  * h.compact! # => {:foo=>0, :baz=>2}
4326  *
4327  * Returns +nil+ if no entries were removed.
4328  */
4329 
4330 static VALUE
4331 rb_hash_compact_bang(VALUE hash)
4332 {
4333  st_index_t n;
4334  rb_hash_modify_check(hash);
4335  n = RHASH_SIZE(hash);
4336  if (n) {
4337  rb_hash_foreach(hash, delete_if_nil, hash);
4338  if (n != RHASH_SIZE(hash))
4339  return hash;
4340  }
4341  return Qnil;
4342 }
4343 
4344 static st_table *rb_init_identtable_with_size(st_index_t size);
4345 
4346 /*
4347  * call-seq:
4348  * hash.compare_by_identity -> self
4349  *
4350  * Sets +self+ to consider only identity in comparing keys;
4351  * two keys are considered the same only if they are the same object;
4352  * returns +self+.
4353  *
4354  * By default, these two object are considered to be the same key,
4355  * so +s1+ will overwrite +s0+:
4356  * s0 = 'x'
4357  * s1 = 'x'
4358  * h = {}
4359  * h.compare_by_identity? # => false
4360  * h[s0] = 0
4361  * h[s1] = 1
4362  * h # => {"x"=>1}
4363  *
4364  * After calling \#compare_by_identity, the keys are considered to be different,
4365  * and therefore do not overwrite each other:
4366  * h = {}
4367  * h.compare_by_identity # => {}
4368  * h.compare_by_identity? # => true
4369  * h[s0] = 0
4370  * h[s1] = 1
4371  * h # => {"x"=>0, "x"=>1}
4372  */
4373 
4374 VALUE
4375 rb_hash_compare_by_id(VALUE hash)
4376 {
4377  VALUE tmp;
4378  st_table *identtable;
4379 
4380  if (rb_hash_compare_by_id_p(hash)) return hash;
4381 
4382  rb_hash_modify_check(hash);
4383  ar_force_convert_table(hash, __FILE__, __LINE__);
4384  HASH_ASSERT(RHASH_ST_TABLE_P(hash));
4385 
4386  tmp = hash_alloc(0);
4387  identtable = rb_init_identtable_with_size(RHASH_SIZE(hash));
4388  RHASH_ST_TABLE_SET(tmp, identtable);
4389  rb_hash_foreach(hash, rb_hash_rehash_i, (VALUE)tmp);
4390  st_free_table(RHASH_ST_TABLE(hash));
4391  RHASH_ST_TABLE_SET(hash, identtable);
4392  RHASH_ST_CLEAR(tmp);
4393 
4394  return hash;
4395 }
4396 
4397 /*
4398  * call-seq:
4399  * hash.compare_by_identity? -> true or false
4400  *
4401  * Returns +true+ if #compare_by_identity has been called, +false+ otherwise.
4402  */
4403 
4404 MJIT_FUNC_EXPORTED VALUE
4405 rb_hash_compare_by_id_p(VALUE hash)
4406 {
4407  return RBOOL(RHASH_ST_TABLE_P(hash) && RHASH_ST_TABLE(hash)->type == &identhash);
4408 }
4409 
4410 VALUE
4411 rb_ident_hash_new(void)
4412 {
4413  VALUE hash = rb_hash_new();
4414  RHASH_ST_TABLE_SET(hash, st_init_table(&identhash));
4415  return hash;
4416 }
4417 
4418 VALUE
4419 rb_ident_hash_new_with_size(st_index_t size)
4420 {
4421  VALUE hash = rb_hash_new();
4422  RHASH_ST_TABLE_SET(hash, st_init_table_with_size(&identhash, size));
4423  return hash;
4424 }
4425 
4426 st_table *
4427 rb_init_identtable(void)
4428 {
4429  return st_init_table(&identhash);
4430 }
4431 
4432 static st_table *
4433 rb_init_identtable_with_size(st_index_t size)
4434 {
4435  return st_init_table_with_size(&identhash, size);
4436 }
4437 
4438 static int
4439 any_p_i(VALUE key, VALUE value, VALUE arg)
4440 {
4441  VALUE ret = rb_yield(rb_assoc_new(key, value));
4442  if (RTEST(ret)) {
4443  *(VALUE *)arg = Qtrue;
4444  return ST_STOP;
4445  }
4446  return ST_CONTINUE;
4447 }
4448 
4449 static int
4450 any_p_i_fast(VALUE key, VALUE value, VALUE arg)
4451 {
4452  VALUE ret = rb_yield_values(2, key, value);
4453  if (RTEST(ret)) {
4454  *(VALUE *)arg = Qtrue;
4455  return ST_STOP;
4456  }
4457  return ST_CONTINUE;
4458 }
4459 
4460 static int
4461 any_p_i_pattern(VALUE key, VALUE value, VALUE arg)
4462 {
4463  VALUE ret = rb_funcall(((VALUE *)arg)[1], idEqq, 1, rb_assoc_new(key, value));
4464  if (RTEST(ret)) {
4465  *(VALUE *)arg = Qtrue;
4466  return ST_STOP;
4467  }
4468  return ST_CONTINUE;
4469 }
4470 
4471 /*
4472  * call-seq:
4473  * hash.any? -> true or false
4474  * hash.any?(object) -> true or false
4475  * hash.any? {|key, value| ... } -> true or false
4476  *
4477  * Returns +true+ if any element satisfies a given criterion;
4478  * +false+ otherwise.
4479  *
4480  * With no argument and no block,
4481  * returns +true+ if +self+ is non-empty; +false+ if empty.
4482  *
4483  * With argument +object+ and no block,
4484  * returns +true+ if for any key +key+
4485  * <tt>h.assoc(key) == object</tt>:
4486  * h = {foo: 0, bar: 1, baz: 2}
4487  * h.any?([:bar, 1]) # => true
4488  * h.any?([:bar, 0]) # => false
4489  * h.any?([:baz, 1]) # => false
4490  *
4491  * With no argument and a block,
4492  * calls the block with each key-value pair;
4493  * returns +true+ if the block returns any truthy value,
4494  * +false+ otherwise:
4495  * h = {foo: 0, bar: 1, baz: 2}
4496  * h.any? {|key, value| value < 3 } # => true
4497  * h.any? {|key, value| value > 3 } # => false
4498  */
4499 
4500 static VALUE
4501 rb_hash_any_p(int argc, VALUE *argv, VALUE hash)
4502 {
4503  VALUE args[2];
4504  args[0] = Qfalse;
4505 
4506  rb_check_arity(argc, 0, 1);
4507  if (RHASH_EMPTY_P(hash)) return Qfalse;
4508  if (argc) {
4509  if (rb_block_given_p()) {
4510  rb_warn("given block not used");
4511  }
4512  args[1] = argv[0];
4513 
4514  rb_hash_foreach(hash, any_p_i_pattern, (VALUE)args);
4515  }
4516  else {
4517  if (!rb_block_given_p()) {
4518  /* yields pairs, never false */
4519  return Qtrue;
4520  }
4521  if (rb_block_pair_yield_optimizable())
4522  rb_hash_foreach(hash, any_p_i_fast, (VALUE)args);
4523  else
4524  rb_hash_foreach(hash, any_p_i, (VALUE)args);
4525  }
4526  return args[0];
4527 }
4528 
4529 /*
4530  * call-seq:
4531  * hash.dig(key, *identifiers) -> object
4532  *
4533  * Finds and returns the object in nested objects
4534  * that is specified by +key+ and +identifiers+.
4535  * The nested objects may be instances of various classes.
4536  * See {Dig Methods}[rdoc-ref:dig_methods.rdoc].
4537  *
4538  * Nested Hashes:
4539  * h = {foo: {bar: {baz: 2}}}
4540  * h.dig(:foo) # => {:bar=>{:baz=>2}}
4541  * h.dig(:foo, :bar) # => {:baz=>2}
4542  * h.dig(:foo, :bar, :baz) # => 2
4543  * h.dig(:foo, :bar, :BAZ) # => nil
4544  *
4545  * Nested Hashes and Arrays:
4546  * h = {foo: {bar: [:a, :b, :c]}}
4547  * h.dig(:foo, :bar, 2) # => :c
4548  *
4549  * This method will use the {default values}[#class-Hash-label-Default+Values]
4550  * for keys that are not present:
4551  * h = {foo: {bar: [:a, :b, :c]}}
4552  * h.dig(:hello) # => nil
4553  * h.default_proc = -> (hash, _key) { hash }
4554  * h.dig(:hello, :world) # => h
4555  * h.dig(:hello, :world, :foo, :bar, 2) # => :c
4556  */
4557 
4558 static VALUE
4559 rb_hash_dig(int argc, VALUE *argv, VALUE self)
4560 {
4562  self = rb_hash_aref(self, *argv);
4563  if (!--argc) return self;
4564  ++argv;
4565  return rb_obj_dig(argc, argv, self, Qnil);
4566 }
4567 
4568 static int
4569 hash_le_i(VALUE key, VALUE value, VALUE arg)
4570 {
4571  VALUE *args = (VALUE *)arg;
4572  VALUE v = rb_hash_lookup2(args[0], key, Qundef);
4573  if (v != Qundef && rb_equal(value, v)) return ST_CONTINUE;
4574  args[1] = Qfalse;
4575  return ST_STOP;
4576 }
4577 
4578 static VALUE
4579 hash_le(VALUE hash1, VALUE hash2)
4580 {
4581  VALUE args[2];
4582  args[0] = hash2;
4583  args[1] = Qtrue;
4584  rb_hash_foreach(hash1, hash_le_i, (VALUE)args);
4585  return args[1];
4586 }
4587 
4588 /*
4589  * call-seq:
4590  * hash <= other_hash -> true or false
4591  *
4592  * Returns +true+ if +hash+ is a subset of +other_hash+, +false+ otherwise:
4593  * h1 = {foo: 0, bar: 1}
4594  * h2 = {foo: 0, bar: 1, baz: 2}
4595  * h1 <= h2 # => true
4596  * h2 <= h1 # => false
4597  * h1 <= h1 # => true
4598  */
4599 static VALUE
4600 rb_hash_le(VALUE hash, VALUE other)
4601 {
4602  other = to_hash(other);
4603  if (RHASH_SIZE(hash) > RHASH_SIZE(other)) return Qfalse;
4604  return hash_le(hash, other);
4605 }
4606 
4607 /*
4608  * call-seq:
4609  * hash < other_hash -> true or false
4610  *
4611  * Returns +true+ if +hash+ is a proper subset of +other_hash+, +false+ otherwise:
4612  * h1 = {foo: 0, bar: 1}
4613  * h2 = {foo: 0, bar: 1, baz: 2}
4614  * h1 < h2 # => true
4615  * h2 < h1 # => false
4616  * h1 < h1 # => false
4617  */
4618 static VALUE
4619 rb_hash_lt(VALUE hash, VALUE other)
4620 {
4621  other = to_hash(other);
4622  if (RHASH_SIZE(hash) >= RHASH_SIZE(other)) return Qfalse;
4623  return hash_le(hash, other);
4624 }
4625 
4626 /*
4627  * call-seq:
4628  * hash >= other_hash -> true or false
4629  *
4630  * Returns +true+ if +hash+ is a superset of +other_hash+, +false+ otherwise:
4631  * h1 = {foo: 0, bar: 1, baz: 2}
4632  * h2 = {foo: 0, bar: 1}
4633  * h1 >= h2 # => true
4634  * h2 >= h1 # => false
4635  * h1 >= h1 # => true
4636  */
4637 static VALUE
4638 rb_hash_ge(VALUE hash, VALUE other)
4639 {
4640  other = to_hash(other);
4641  if (RHASH_SIZE(hash) < RHASH_SIZE(other)) return Qfalse;
4642  return hash_le(other, hash);
4643 }
4644 
4645 /*
4646  * call-seq:
4647  * hash > other_hash -> true or false
4648  *
4649  * Returns +true+ if +hash+ is a proper superset of +other_hash+, +false+ otherwise:
4650  * h1 = {foo: 0, bar: 1, baz: 2}
4651  * h2 = {foo: 0, bar: 1}
4652  * h1 > h2 # => true
4653  * h2 > h1 # => false
4654  * h1 > h1 # => false
4655  */
4656 static VALUE
4657 rb_hash_gt(VALUE hash, VALUE other)
4658 {
4659  other = to_hash(other);
4660  if (RHASH_SIZE(hash) <= RHASH_SIZE(other)) return Qfalse;
4661  return hash_le(other, hash);
4662 }
4663 
4664 static VALUE
4665 hash_proc_call(RB_BLOCK_CALL_FUNC_ARGLIST(key, hash))
4666 {
4667  rb_check_arity(argc, 1, 1);
4668  return rb_hash_aref(hash, *argv);
4669 }
4670 
4671 /*
4672  * call-seq:
4673  * hash.to_proc -> proc
4674  *
4675  * Returns a \Proc object that maps a key to its value:
4676  * h = {foo: 0, bar: 1, baz: 2}
4677  * proc = h.to_proc
4678  * proc.class # => Proc
4679  * proc.call(:foo) # => 0
4680  * proc.call(:bar) # => 1
4681  * proc.call(:nosuch) # => nil
4682  */
4683 static VALUE
4684 rb_hash_to_proc(VALUE hash)
4685 {
4686  return rb_func_lambda_new(hash_proc_call, hash, 1, 1);
4687 }
4688 
4689 static VALUE
4690 rb_hash_deconstruct_keys(VALUE hash, VALUE keys)
4691 {
4692  return hash;
4693 }
4694 
4695 static int
4696 add_new_i(st_data_t *key, st_data_t *val, st_data_t arg, int existing)
4697 {
4698  VALUE *args = (VALUE *)arg;
4699  if (existing) return ST_STOP;
4700  RB_OBJ_WRITTEN(args[0], Qundef, (VALUE)*key);
4701  RB_OBJ_WRITE(args[0], (VALUE *)val, args[1]);
4702  return ST_CONTINUE;
4703 }
4704 
4705 /*
4706  * add +key+ to +val+ pair if +hash+ does not contain +key+.
4707  * returns non-zero if +key+ was contained.
4708  */
4709 int
4710 rb_hash_add_new_element(VALUE hash, VALUE key, VALUE val)
4711 {
4712  st_table *tbl;
4713  int ret = 0;
4714  VALUE args[2];
4715  args[0] = hash;
4716  args[1] = val;
4717 
4718  if (RHASH_AR_TABLE_P(hash)) {
4719  hash_ar_table(hash);
4720 
4721  ret = ar_update(hash, (st_data_t)key, add_new_i, (st_data_t)args);
4722  if (ret != -1) {
4723  return ret;
4724  }
4725  ar_try_convert_table(hash);
4726  }
4727  tbl = RHASH_TBL_RAW(hash);
4728  return st_update(tbl, (st_data_t)key, add_new_i, (st_data_t)args);
4729 
4730 }
4731 
4732 static st_data_t
4733 key_stringify(VALUE key)
4734 {
4735  return (rb_obj_class(key) == rb_cString && !RB_OBJ_FROZEN(key)) ?
4736  rb_hash_key_str(key) : key;
4737 }
4738 
4739 static void
4740 ar_bulk_insert(VALUE hash, long argc, const VALUE *argv)
4741 {
4742  long i;
4743  for (i = 0; i < argc; ) {
4744  st_data_t k = key_stringify(argv[i++]);
4745  st_data_t v = argv[i++];
4746  ar_insert(hash, k, v);
4747  RB_OBJ_WRITTEN(hash, Qundef, k);
4748  RB_OBJ_WRITTEN(hash, Qundef, v);
4749  }
4750 }
4751 
4752 void
4753 rb_hash_bulk_insert(long argc, const VALUE *argv, VALUE hash)
4754 {
4755  HASH_ASSERT(argc % 2 == 0);
4756  if (argc > 0) {
4757  st_index_t size = argc / 2;
4758 
4759  if (RHASH_TABLE_NULL_P(hash)) {
4760  if (size <= RHASH_AR_TABLE_MAX_SIZE) {
4761  hash_ar_table(hash);
4762  }
4763  else {
4764  RHASH_TBL_RAW(hash);
4765  }
4766  }
4767 
4768  if (RHASH_AR_TABLE_P(hash) &&
4769  (RHASH_AR_TABLE_SIZE(hash) + size <= RHASH_AR_TABLE_MAX_SIZE)) {
4770  ar_bulk_insert(hash, argc, argv);
4771  }
4772  else {
4773  rb_hash_bulk_insert_into_st_table(argc, argv, hash);
4774  }
4775  }
4776 }
4777 
4778 static char **origenviron;
4779 #ifdef _WIN32
4780 #define GET_ENVIRON(e) ((e) = rb_w32_get_environ())
4781 #define FREE_ENVIRON(e) rb_w32_free_environ(e)
4782 static char **my_environ;
4783 #undef environ
4784 #define environ my_environ
4785 #undef getenv
4786 #define getenv(n) rb_w32_ugetenv(n)
4787 #elif defined(__APPLE__)
4788 #undef environ
4789 #define environ (*_NSGetEnviron())
4790 #define GET_ENVIRON(e) (e)
4791 #define FREE_ENVIRON(e)
4792 #else
4793 extern char **environ;
4794 #define GET_ENVIRON(e) (e)
4795 #define FREE_ENVIRON(e)
4796 #endif
4797 #ifdef ENV_IGNORECASE
4798 #define ENVMATCH(s1, s2) (STRCASECMP((s1), (s2)) == 0)
4799 #define ENVNMATCH(s1, s2, n) (STRNCASECMP((s1), (s2), (n)) == 0)
4800 #else
4801 #define ENVMATCH(n1, n2) (strcmp((n1), (n2)) == 0)
4802 #define ENVNMATCH(s1, s2, n) (memcmp((s1), (s2), (n)) == 0)
4803 #endif
4804 
4805 #define ENV_LOCK() RB_VM_LOCK_ENTER()
4806 #define ENV_UNLOCK() RB_VM_LOCK_LEAVE()
4807 
4808 static inline rb_encoding *
4809 env_encoding(void)
4810 {
4811 #ifdef _WIN32
4812  return rb_utf8_encoding();
4813 #else
4814  return rb_locale_encoding();
4815 #endif
4816 }
4817 
4818 static VALUE
4819 env_enc_str_new(const char *ptr, long len, rb_encoding *enc)
4820 {
4821  VALUE str = rb_external_str_new_with_enc(ptr, len, enc);
4822 
4823  rb_obj_freeze(str);
4824  return str;
4825 }
4826 
4827 static VALUE
4828 env_str_new(const char *ptr, long len)
4829 {
4830  return env_enc_str_new(ptr, len, env_encoding());
4831 }
4832 
4833 static VALUE
4834 env_str_new2(const char *ptr)
4835 {
4836  if (!ptr) return Qnil;
4837  return env_str_new(ptr, strlen(ptr));
4838 }
4839 
4840 static VALUE
4841 getenv_with_lock(const char *name)
4842 {
4843  VALUE ret;
4844  ENV_LOCK();
4845  {
4846  const char *val = getenv(name);
4847  ret = env_str_new2(val);
4848  }
4849  ENV_UNLOCK();
4850  return ret;
4851 }
4852 
4853 static bool
4854 has_env_with_lock(const char *name)
4855 {
4856  const char *val;
4857 
4858  ENV_LOCK();
4859  {
4860  val = getenv(name);
4861  }
4862  ENV_UNLOCK();
4863 
4864  return val ? true : false;
4865 }
4866 
4867 static const char TZ_ENV[] = "TZ";
4868 
4869 static void *
4870 get_env_cstr(
4871  VALUE str,
4872  const char *name)
4873 {
4874  char *var;
4875  rb_encoding *enc = rb_enc_get(str);
4876  if (!rb_enc_asciicompat(enc)) {
4877  rb_raise(rb_eArgError, "bad environment variable %s: ASCII incompatible encoding: %s",
4878  name, rb_enc_name(enc));
4879  }
4880  var = RSTRING_PTR(str);
4881  if (memchr(var, '\0', RSTRING_LEN(str))) {
4882  rb_raise(rb_eArgError, "bad environment variable %s: contains null byte", name);
4883  }
4884  return rb_str_fill_terminator(str, 1); /* ASCII compatible */
4885 }
4886 
4887 #define get_env_ptr(var, val) \
4888  (var = get_env_cstr(val, #var))
4889 
4890 static inline const char *
4891 env_name(volatile VALUE *s)
4892 {
4893  const char *name;
4894  SafeStringValue(*s);
4895  get_env_ptr(name, *s);
4896  return name;
4897 }
4898 
4899 #define env_name(s) env_name(&(s))
4900 
4901 static VALUE env_aset(VALUE nm, VALUE val);
4902 
4903 static void
4904 reset_by_modified_env(const char *nam)
4905 {
4906  /*
4907  * ENV['TZ'] = nil has a special meaning.
4908  * TZ is no longer considered up-to-date and ruby call tzset() as needed.
4909  * It could be useful if sysadmin change /etc/localtime.
4910  * This hack might works only on Linux glibc.
4911  */
4912  if (ENVMATCH(nam, TZ_ENV)) {
4913  ruby_reset_timezone();
4914  }
4915 }
4916 
4917 static VALUE
4918 env_delete(VALUE name)
4919 {
4920  const char *nam = env_name(name);
4921  reset_by_modified_env(nam);
4922  VALUE val = getenv_with_lock(nam);
4923 
4924  if (!NIL_P(val)) {
4925  ruby_setenv(nam, 0);
4926  }
4927  return val;
4928 }
4929 
4930 /*
4931  * call-seq:
4932  * ENV.delete(name) -> value
4933  * ENV.delete(name) { |name| block } -> value
4934  * ENV.delete(missing_name) -> nil
4935  * ENV.delete(missing_name) { |name| block } -> block_value
4936  *
4937  * Deletes the environment variable with +name+ if it exists and returns its value:
4938  * ENV['foo'] = '0'
4939  * ENV.delete('foo') # => '0'
4940  *
4941  * If a block is not given and the named environment variable does not exist, returns +nil+.
4942  *
4943  * If a block given and the environment variable does not exist,
4944  * yields +name+ to the block and returns the value of the block:
4945  * ENV.delete('foo') { |name| name * 2 } # => "foofoo"
4946  *
4947  * If a block given and the environment variable exists,
4948  * deletes the environment variable and returns its value (ignoring the block):
4949  * ENV['foo'] = '0'
4950  * ENV.delete('foo') { |name| raise 'ignored' } # => "0"
4951  *
4952  * Raises an exception if +name+ is invalid.
4953  * See {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values].
4954  */
4955 static VALUE
4956 env_delete_m(VALUE obj, VALUE name)
4957 {
4958  VALUE val;
4959 
4960  val = env_delete(name);
4961  if (NIL_P(val) && rb_block_given_p()) val = rb_yield(name);
4962  return val;
4963 }
4964 
4965 /*
4966  * call-seq:
4967  * ENV[name] -> value
4968  *
4969  * Returns the value for the environment variable +name+ if it exists:
4970  * ENV['foo'] = '0'
4971  * ENV['foo'] # => "0"
4972  * Returns +nil+ if the named variable does not exist.
4973  *
4974  * Raises an exception if +name+ is invalid.
4975  * See {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values].
4976  */
4977 static VALUE
4978 rb_f_getenv(VALUE obj, VALUE name)
4979 {
4980  const char *nam = env_name(name);
4981  VALUE env = getenv_with_lock(nam);
4982  return env;
4983 }
4984 
4985 /*
4986  * call-seq:
4987  * ENV.fetch(name) -> value
4988  * ENV.fetch(name, default) -> value
4989  * ENV.fetch(name) { |name| block } -> value
4990  *
4991  * If +name+ is the name of an environment variable, returns its value:
4992  * ENV['foo'] = '0'
4993  * ENV.fetch('foo') # => '0'
4994  * Otherwise if a block is given (but not a default value),
4995  * yields +name+ to the block and returns the block's return value:
4996  * ENV.fetch('foo') { |name| :need_not_return_a_string } # => :need_not_return_a_string
4997  * Otherwise if a default value is given (but not a block), returns the default value:
4998  * ENV.delete('foo')
4999  * ENV.fetch('foo', :default_need_not_be_a_string) # => :default_need_not_be_a_string
5000  * If the environment variable does not exist and both default and block are given,
5001  * issues a warning ("warning: block supersedes default value argument"),
5002  * yields +name+ to the block, and returns the block's return value:
5003  * ENV.fetch('foo', :default) { |name| :block_return } # => :block_return
5004  * Raises KeyError if +name+ is valid, but not found,
5005  * and neither default value nor block is given:
5006  * ENV.fetch('foo') # Raises KeyError (key not found: "foo")
5007  * Raises an exception if +name+ is invalid.
5008  * See {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values].
5009  */
5010 static VALUE
5011 env_fetch(int argc, VALUE *argv, VALUE _)
5012 {
5013  VALUE key;
5014  long block_given;
5015  const char *nam;
5016  VALUE env;
5017 
5018  rb_check_arity(argc, 1, 2);
5019  key = argv[0];
5020  block_given = rb_block_given_p();
5021  if (block_given && argc == 2) {
5022  rb_warn("block supersedes default value argument");
5023  }
5024  nam = env_name(key);
5025  env = getenv_with_lock(nam);
5026 
5027  if (NIL_P(env)) {
5028  if (block_given) return rb_yield(key);
5029  if (argc == 1) {
5030  rb_key_err_raise(rb_sprintf("key not found: \"%"PRIsVALUE"\"", key), envtbl, key);
5031  }
5032  return argv[1];
5033  }
5034  return env;
5035 }
5036 
5037 int
5039 {
5040  rb_warn_deprecated_to_remove_at(3.2, "rb_env_path_tainted", NULL);
5041  return 0;
5042 }
5043 
5044 #if defined(_WIN32) || (defined(HAVE_SETENV) && defined(HAVE_UNSETENV))
5045 #elif defined __sun
5046 static int
5047 in_origenv(const char *str)
5048 {
5049  char **env;
5050  for (env = origenviron; *env; ++env) {
5051  if (*env == str) return 1;
5052  }
5053  return 0;
5054 }
5055 #else
5056 static int
5057 envix(const char *nam)
5058 {
5059  // should be locked
5060 
5061  register int i, len = strlen(nam);
5062  char **env;
5063 
5064  env = GET_ENVIRON(environ);
5065  for (i = 0; env[i]; i++) {
5066  if (ENVNMATCH(env[i],nam,len) && env[i][len] == '=')
5067  break; /* memcmp must come first to avoid */
5068  } /* potential SEGV's */
5069  FREE_ENVIRON(environ);
5070  return i;
5071 }
5072 #endif
5073 
5074 #if defined(_WIN32)
5075 static size_t
5076 getenvsize(const WCHAR* p)
5077 {
5078  const WCHAR* porg = p;
5079  while (*p++) p += lstrlenW(p) + 1;
5080  return p - porg + 1;
5081 }
5082 
5083 static size_t
5084 getenvblocksize(void)
5085 {
5086 #ifdef _MAX_ENV
5087  return _MAX_ENV;
5088 #else
5089  return 32767;
5090 #endif
5091 }
5092 
5093 static int
5094 check_envsize(size_t n)
5095 {
5096  if (_WIN32_WINNT < 0x0600 && rb_w32_osver() < 6) {
5097  /* https://msdn.microsoft.com/en-us/library/windows/desktop/ms682653(v=vs.85).aspx */
5098  /* Windows Server 2003 and Windows XP: The maximum size of the
5099  * environment block for the process is 32,767 characters. */
5100  WCHAR* p = GetEnvironmentStringsW();
5101  if (!p) return -1; /* never happen */
5102  n += getenvsize(p);
5103  FreeEnvironmentStringsW(p);
5104  if (n >= getenvblocksize()) {
5105  return -1;
5106  }
5107  }
5108  return 0;
5109 }
5110 #endif
5111 
5112 #if defined(_WIN32) || \
5113  (defined(__sun) && !(defined(HAVE_SETENV) && defined(HAVE_UNSETENV)))
5114 
5115 NORETURN(static void invalid_envname(const char *name));
5116 
5117 static void
5118 invalid_envname(const char *name)
5119 {
5120  rb_syserr_fail_str(EINVAL, rb_sprintf("ruby_setenv(%s)", name));
5121 }
5122 
5123 static const char *
5124 check_envname(const char *name)
5125 {
5126  if (strchr(name, '=')) {
5127  invalid_envname(name);
5128  }
5129  return name;
5130 }
5131 #endif
5132 
5133 void
5134 ruby_setenv(const char *name, const char *value)
5135 {
5136 #if defined(_WIN32)
5137 # if defined(MINGW_HAS_SECURE_API) || RUBY_MSVCRT_VERSION >= 80
5138 # define HAVE__WPUTENV_S 1
5139 # endif
5140  VALUE buf;
5141  WCHAR *wname;
5142  WCHAR *wvalue = 0;
5143  int failed = 0;
5144  int len;
5145  check_envname(name);
5146  len = MultiByteToWideChar(CP_UTF8, 0, name, -1, NULL, 0);
5147  if (value) {
5148  int len2;
5149  len2 = MultiByteToWideChar(CP_UTF8, 0, value, -1, NULL, 0);
5150  if (check_envsize((size_t)len + len2)) { /* len and len2 include '\0' */
5151  goto fail; /* 2 for '=' & '\0' */
5152  }
5153  wname = ALLOCV_N(WCHAR, buf, len + len2);
5154  wvalue = wname + len;
5155  MultiByteToWideChar(CP_UTF8, 0, name, -1, wname, len);
5156  MultiByteToWideChar(CP_UTF8, 0, value, -1, wvalue, len2);
5157 #ifndef HAVE__WPUTENV_S
5158  wname[len-1] = L'=';
5159 #endif
5160  }
5161  else {
5162  wname = ALLOCV_N(WCHAR, buf, len + 1);
5163  MultiByteToWideChar(CP_UTF8, 0, name, -1, wname, len);
5164  wvalue = wname + len;
5165  *wvalue = L'\0';
5166 #ifndef HAVE__WPUTENV_S
5167  wname[len-1] = L'=';
5168 #endif
5169  }
5170 
5171  ENV_LOCK();
5172  {
5173 #ifndef HAVE__WPUTENV_S
5174  failed = _wputenv(wname);
5175 #else
5176  failed = _wputenv_s(wname, wvalue);
5177 #endif
5178  }
5179  ENV_UNLOCK();
5180 
5181  ALLOCV_END(buf);
5182  /* even if putenv() failed, clean up and try to delete the
5183  * variable from the system area. */
5184  if (!value || !*value) {
5185  /* putenv() doesn't handle empty value */
5186  if (!SetEnvironmentVariable(name, value) &&
5187  GetLastError() != ERROR_ENVVAR_NOT_FOUND) goto fail;
5188  }
5189  if (failed) {
5190  fail:
5191  invalid_envname(name);
5192  }
5193 #elif defined(HAVE_SETENV) && defined(HAVE_UNSETENV)
5194  if (value) {
5195  int ret;
5196  ENV_LOCK();
5197  {
5198  ret = setenv(name, value, 1);
5199  }
5200  ENV_UNLOCK();
5201 
5202  if (ret) rb_sys_fail_str(rb_sprintf("setenv(%s)", name));
5203  }
5204  else {
5205 #ifdef VOID_UNSETENV
5206  ENV_LOCK();
5207  {
5208  unsetenv(name);
5209  }
5210  ENV_UNLOCK();
5211 #else
5212  int ret;
5213  ENV_LOCK();
5214  {
5215  ret = unsetenv(name);
5216  }
5217  ENV_UNLOCK();
5218 
5219  if (ret) rb_sys_fail_str(rb_sprintf("unsetenv(%s)", name));
5220 #endif
5221  }
5222 #elif defined __sun
5223  /* Solaris 9 (or earlier) does not have setenv(3C) and unsetenv(3C). */
5224  /* The below code was tested on Solaris 10 by:
5225  % ./configure ac_cv_func_setenv=no ac_cv_func_unsetenv=no
5226  */
5227  size_t len, mem_size;
5228  char **env_ptr, *str, *mem_ptr;
5229 
5230  check_envname(name);
5231  len = strlen(name);
5232  if (value) {
5233  mem_size = len + strlen(value) + 2;
5234  mem_ptr = malloc(mem_size);
5235  if (mem_ptr == NULL)
5236  rb_sys_fail_str(rb_sprintf("malloc(%"PRIuSIZE")", mem_size));
5237  snprintf(mem_ptr, mem_size, "%s=%s", name, value);
5238  }
5239 
5240  ENV_LOCK();
5241  {
5242  for (env_ptr = GET_ENVIRON(environ); (str = *env_ptr) != 0; ++env_ptr) {
5243  if (!strncmp(str, name, len) && str[len] == '=') {
5244  if (!in_origenv(str)) free(str);
5245  while ((env_ptr[0] = env_ptr[1]) != 0) env_ptr++;
5246  break;
5247  }
5248  }
5249  }
5250  ENV_UNLOCK();
5251 
5252  if (value) {
5253  int ret;
5254  ENV_LOCK();
5255  {
5256  ret = putenv(mem_ptr);
5257  }
5258  ENV_UNLOCK();
5259 
5260  if (ret) {
5261  free(mem_ptr);
5262  rb_sys_fail_str(rb_sprintf("putenv(%s)", name));
5263  }
5264  }
5265 #else /* WIN32 */
5266  size_t len;
5267  int i;
5268 
5269  ENV_LOCK();
5270  {
5271  i = envix(name); /* where does it go? */
5272 
5273  if (environ == origenviron) { /* need we copy environment? */
5274  int j;
5275  int max;
5276  char **tmpenv;
5277 
5278  for (max = i; environ[max]; max++) ;
5279  tmpenv = ALLOC_N(char*, max+2);
5280  for (j=0; j<max; j++) /* copy environment */
5281  tmpenv[j] = ruby_strdup(environ[j]);
5282  tmpenv[max] = 0;
5283  environ = tmpenv; /* tell exec where it is now */
5284  }
5285 
5286  if (environ[i]) {
5287  char **envp = origenviron;
5288  while (*envp && *envp != environ[i]) envp++;
5289  if (!*envp)
5290  xfree(environ[i]);
5291  if (!value) {
5292  while (environ[i]) {
5293  environ[i] = environ[i+1];
5294  i++;
5295  }
5296  goto finish;
5297  }
5298  }
5299  else { /* does not exist yet */
5300  if (!value) goto finish;
5301  REALLOC_N(environ, char*, i+2); /* just expand it a bit */
5302  environ[i+1] = 0; /* make sure it's null terminated */
5303  }
5304 
5305  len = strlen(name) + strlen(value) + 2;
5306  environ[i] = ALLOC_N(char, len);
5307  snprintf(environ[i],len,"%s=%s",name,value); /* all that work just for this */
5308 
5309  finish:;
5310  }
5311  ENV_UNLOCK();
5312 #endif /* WIN32 */
5313 }
5314 
5315 void
5316 ruby_unsetenv(const char *name)
5317 {
5318  ruby_setenv(name, 0);
5319 }
5320 
5321 /*
5322  * call-seq:
5323  * ENV[name] = value -> value
5324  * ENV.store(name, value) -> value
5325  *
5326  * ENV.store is an alias for ENV.[]=.
5327  *
5328  * Creates, updates, or deletes the named environment variable, returning the value.
5329  * Both +name+ and +value+ may be instances of String.
5330  * See {Valid Names and Values}[#class-ENV-label-Valid+Names+and+Values].
5331  *
5332  * - If the named environment variable does not exist:
5333  * - If +value+ is +nil+, does nothing.
5334  * ENV.clear
5335  * ENV['foo'] = nil # => nil
5336  * ENV.include?('foo') # => false
5337  * ENV.store('bar', nil) # => nil
5338  * ENV.include?('bar') # => false
5339  * - If +value+ is not +nil+, creates the environment variable with +name+ and +value+:
5340  * # Create 'foo' using ENV.[]=.
5341  * ENV['foo'] = '0' # => '0'
5342  * ENV['foo'] # => '0'
5343  * # Create 'bar' using ENV.store.
5344  * ENV.store('bar', '1') # => '1'
5345  * ENV['bar'] # => '1'
5346  * - If the named environment variable exists:
5347  * - If +value+ is not +nil+, updates the environment variable with value +value+:
5348  * # Update 'foo' using ENV.[]=.
5349  * ENV['foo'] = '2' # => '2'
5350  * ENV['foo'] # => '2'
5351  * # Update 'bar' using ENV.store.
5352  * ENV.store('bar', '3') # => '3'
5353  * ENV['bar'] # => '3'
5354  * - If +value+ is +nil+, deletes the environment variable:
5355  * # Delete 'foo' using ENV.[]=.
5356  * ENV['foo'] = nil # => nil
5357  * ENV.include?('foo') # => false
5358  * # Delete 'bar' using ENV.store.
5359  * ENV.store('bar', nil) # => nil
5360  * ENV.include?('bar') # => false
5361  *
5362  * Raises an exception if +name+ or +value+ is invalid.
5363  * See {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values].
5364  */
5365 static VALUE
5366 env_aset_m(VALUE obj, VALUE nm, VALUE val)
5367 {
5368  return env_aset(nm, val);
5369 }
5370 
5371 static VALUE
5372 env_aset(VALUE nm, VALUE val)
5373 {
5374  char *name, *value;
5375 
5376  if (NIL_P(val)) {
5377  env_delete(nm);
5378  return Qnil;
5379  }
5380  SafeStringValue(nm);
5381  SafeStringValue(val);
5382  /* nm can be modified in `val.to_str`, don't get `name` before
5383  * check for `val` */
5384  get_env_ptr(name, nm);
5385  get_env_ptr(value, val);
5386 
5387  ruby_setenv(name, value);
5388  reset_by_modified_env(name);
5389  return val;
5390 }
5391 
5392 static VALUE
5393 env_keys(int raw)
5394 {
5395  rb_encoding *enc = raw ? 0 : rb_locale_encoding();
5396  VALUE ary = rb_ary_new();
5397 
5398  ENV_LOCK();
5399  {
5400  char **env = GET_ENVIRON(environ);
5401  while (*env) {
5402  char *s = strchr(*env, '=');
5403  if (s) {
5404  const char *p = *env;
5405  size_t l = s - p;
5406  VALUE e = raw ? rb_utf8_str_new(p, l) : env_enc_str_new(p, l, enc);
5407  rb_ary_push(ary, e);
5408  }
5409  env++;
5410  }
5411  FREE_ENVIRON(environ);
5412  }
5413  ENV_UNLOCK();
5414 
5415  return ary;
5416 }
5417 
5418 /*
5419  * call-seq:
5420  * ENV.keys -> array of names
5421  *
5422  * Returns all variable names in an Array:
5423  * ENV.replace('foo' => '0', 'bar' => '1')
5424  * ENV.keys # => ['bar', 'foo']
5425  * The order of the names is OS-dependent.
5426  * See {About Ordering}[#class-ENV-label-About+Ordering].
5427  *
5428  * Returns the empty Array if ENV is empty.
5429  */
5430 
5431 static VALUE
5432 env_f_keys(VALUE _)
5433 {
5434  return env_keys(FALSE);
5435 }
5436 
5437 static VALUE
5438 rb_env_size(VALUE ehash, VALUE args, VALUE eobj)
5439 {
5440  char **env;
5441  long cnt = 0;
5442 
5443  ENV_LOCK();
5444  {
5445  env = GET_ENVIRON(environ);
5446  for (; *env ; ++env) {
5447  if (strchr(*env, '=')) {
5448  cnt++;
5449  }
5450  }
5451  FREE_ENVIRON(environ);
5452  }
5453  ENV_UNLOCK();
5454 
5455  return LONG2FIX(cnt);
5456 }
5457 
5458 /*
5459  * call-seq:
5460  * ENV.each_key { |name| block } -> ENV
5461  * ENV.each_key -> an_enumerator
5462  *
5463  * Yields each environment variable name:
5464  * ENV.replace('foo' => '0', 'bar' => '1') # => ENV
5465  * names = []
5466  * ENV.each_key { |name| names.push(name) } # => ENV
5467  * names # => ["bar", "foo"]
5468  *
5469  * Returns an Enumerator if no block given:
5470  * e = ENV.each_key # => #<Enumerator: {"bar"=>"1", "foo"=>"0"}:each_key>
5471  * names = []
5472  * e.each { |name| names.push(name) } # => ENV
5473  * names # => ["bar", "foo"]
5474  */
5475 static VALUE
5476 env_each_key(VALUE ehash)
5477 {
5478  VALUE keys;
5479  long i;
5480 
5481  RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5482  keys = env_keys(FALSE);
5483  for (i=0; i<RARRAY_LEN(keys); i++) {
5484  rb_yield(RARRAY_AREF(keys, i));
5485  }
5486  return ehash;
5487 }
5488 
5489 static VALUE
5490 env_values(void)
5491 {
5492  VALUE ary = rb_ary_new();
5493 
5494  ENV_LOCK();
5495  {
5496  char **env = GET_ENVIRON(environ);
5497 
5498  while (*env) {
5499  char *s = strchr(*env, '=');
5500  if (s) {
5501  rb_ary_push(ary, env_str_new2(s+1));
5502  }
5503  env++;
5504  }
5505  FREE_ENVIRON(environ);
5506  }
5507  ENV_UNLOCK();
5508 
5509  return ary;
5510 }
5511 
5512 /*
5513  * call-seq:
5514  * ENV.values -> array of values
5515  *
5516  * Returns all environment variable values in an Array:
5517  * ENV.replace('foo' => '0', 'bar' => '1')
5518  * ENV.values # => ['1', '0']
5519  * The order of the values is OS-dependent.
5520  * See {About Ordering}[#class-ENV-label-About+Ordering].
5521  *
5522  * Returns the empty Array if ENV is empty.
5523  */
5524 static VALUE
5525 env_f_values(VALUE _)
5526 {
5527  return env_values();
5528 }
5529 
5530 /*
5531  * call-seq:
5532  * ENV.each_value { |value| block } -> ENV
5533  * ENV.each_value -> an_enumerator
5534  *
5535  * Yields each environment variable value:
5536  * ENV.replace('foo' => '0', 'bar' => '1') # => ENV
5537  * values = []
5538  * ENV.each_value { |value| values.push(value) } # => ENV
5539  * values # => ["1", "0"]
5540  *
5541  * Returns an Enumerator if no block given:
5542  * e = ENV.each_value # => #<Enumerator: {"bar"=>"1", "foo"=>"0"}:each_value>
5543  * values = []
5544  * e.each { |value| values.push(value) } # => ENV
5545  * values # => ["1", "0"]
5546  */
5547 static VALUE
5548 env_each_value(VALUE ehash)
5549 {
5550  VALUE values;
5551  long i;
5552 
5553  RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5554  values = env_values();
5555  for (i=0; i<RARRAY_LEN(values); i++) {
5556  rb_yield(RARRAY_AREF(values, i));
5557  }
5558  return ehash;
5559 }
5560 
5561 /*
5562  * call-seq:
5563  * ENV.each { |name, value| block } -> ENV
5564  * ENV.each -> an_enumerator
5565  * ENV.each_pair { |name, value| block } -> ENV
5566  * ENV.each_pair -> an_enumerator
5567  *
5568  * Yields each environment variable name and its value as a 2-element \Array:
5569  * h = {}
5570  * ENV.each_pair { |name, value| h[name] = value } # => ENV
5571  * h # => {"bar"=>"1", "foo"=>"0"}
5572  *
5573  * Returns an Enumerator if no block given:
5574  * h = {}
5575  * e = ENV.each_pair # => #<Enumerator: {"bar"=>"1", "foo"=>"0"}:each_pair>
5576  * e.each { |name, value| h[name] = value } # => ENV
5577  * h # => {"bar"=>"1", "foo"=>"0"}
5578  */
5579 static VALUE
5580 env_each_pair(VALUE ehash)
5581 {
5582  long i;
5583 
5584  RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5585 
5586  VALUE ary = rb_ary_new();
5587 
5588  ENV_LOCK();
5589  {
5590  char **env = GET_ENVIRON(environ);
5591 
5592  while (*env) {
5593  char *s = strchr(*env, '=');
5594  if (s) {
5595  rb_ary_push(ary, env_str_new(*env, s-*env));
5596  rb_ary_push(ary, env_str_new2(s+1));
5597  }
5598  env++;
5599  }
5600  FREE_ENVIRON(environ);
5601  }
5602  ENV_UNLOCK();
5603 
5604  if (rb_block_pair_yield_optimizable()) {
5605  for (i=0; i<RARRAY_LEN(ary); i+=2) {
5606  rb_yield_values(2, RARRAY_AREF(ary, i), RARRAY_AREF(ary, i+1));
5607  }
5608  }
5609  else {
5610  for (i=0; i<RARRAY_LEN(ary); i+=2) {
5611  rb_yield(rb_assoc_new(RARRAY_AREF(ary, i), RARRAY_AREF(ary, i+1)));
5612  }
5613  }
5614 
5615  return ehash;
5616 }
5617 
5618 /*
5619  * call-seq:
5620  * ENV.reject! { |name, value| block } -> ENV or nil
5621  * ENV.reject! -> an_enumerator
5622  *
5623  * Similar to ENV.delete_if, but returns +nil+ if no changes were made.
5624  *
5625  * Yields each environment variable name and its value as a 2-element Array,
5626  * deleting each environment variable for which the block returns a truthy value,
5627  * and returning ENV (if any deletions) or +nil+ (if not):
5628  * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5629  * ENV.reject! { |name, value| name.start_with?('b') } # => ENV
5630  * ENV # => {"foo"=>"0"}
5631  * ENV.reject! { |name, value| name.start_with?('b') } # => nil
5632  *
5633  * Returns an Enumerator if no block given:
5634  * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5635  * e = ENV.reject! # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:reject!>
5636  * e.each { |name, value| name.start_with?('b') } # => ENV
5637  * ENV # => {"foo"=>"0"}
5638  * e.each { |name, value| name.start_with?('b') } # => nil
5639  */
5640 static VALUE
5641 env_reject_bang(VALUE ehash)
5642 {
5643  VALUE keys;
5644  long i;
5645  int del = 0;
5646 
5647  RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5648  keys = env_keys(FALSE);
5649  RBASIC_CLEAR_CLASS(keys);
5650  for (i=0; i<RARRAY_LEN(keys); i++) {
5651  VALUE val = rb_f_getenv(Qnil, RARRAY_AREF(keys, i));
5652  if (!NIL_P(val)) {
5653  if (RTEST(rb_yield_values(2, RARRAY_AREF(keys, i), val))) {
5654  env_delete(RARRAY_AREF(keys, i));
5655  del++;
5656  }
5657  }
5658  }
5659  RB_GC_GUARD(keys);
5660  if (del == 0) return Qnil;
5661  return envtbl;
5662 }
5663 
5664 /*
5665  * call-seq:
5666  * ENV.delete_if { |name, value| block } -> ENV
5667  * ENV.delete_if -> an_enumerator
5668  *
5669  * Yields each environment variable name and its value as a 2-element Array,
5670  * deleting each environment variable for which the block returns a truthy value,
5671  * and returning ENV (regardless of whether any deletions):
5672  * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5673  * ENV.delete_if { |name, value| name.start_with?('b') } # => ENV
5674  * ENV # => {"foo"=>"0"}
5675  * ENV.delete_if { |name, value| name.start_with?('b') } # => ENV
5676  *
5677  * Returns an Enumerator if no block given:
5678  * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5679  * e = ENV.delete_if # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:delete_if!>
5680  * e.each { |name, value| name.start_with?('b') } # => ENV
5681  * ENV # => {"foo"=>"0"}
5682  * e.each { |name, value| name.start_with?('b') } # => ENV
5683  */
5684 static VALUE
5685 env_delete_if(VALUE ehash)
5686 {
5687  RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5688  env_reject_bang(ehash);
5689  return envtbl;
5690 }
5691 
5692 /*
5693  * call-seq:
5694  * ENV.values_at(*names) -> array of values
5695  *
5696  * Returns an Array containing the environment variable values associated with
5697  * the given names:
5698  * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5699  * ENV.values_at('foo', 'baz') # => ["0", "2"]
5700  *
5701  * Returns +nil+ in the Array for each name that is not an ENV name:
5702  * ENV.values_at('foo', 'bat', 'bar', 'bam') # => ["0", nil, "1", nil]
5703  *
5704  * Returns an empty \Array if no names given.
5705  *
5706  * Raises an exception if any name is invalid.
5707  * See {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values].
5708  */
5709 static VALUE
5710 env_values_at(int argc, VALUE *argv, VALUE _)
5711 {
5712  VALUE result;
5713  long i;
5714 
5715  result = rb_ary_new();
5716  for (i=0; i<argc; i++) {
5717  rb_ary_push(result, rb_f_getenv(Qnil, argv[i]));
5718  }
5719  return result;
5720 }
5721 
5722 /*
5723  * call-seq:
5724  * ENV.select { |name, value| block } -> hash of name/value pairs
5725  * ENV.select -> an_enumerator
5726  * ENV.filter { |name, value| block } -> hash of name/value pairs
5727  * ENV.filter -> an_enumerator
5728  *
5729  * ENV.filter is an alias for ENV.select.
5730  *
5731  * Yields each environment variable name and its value as a 2-element Array,
5732  * returning a Hash of the names and values for which the block returns a truthy value:
5733  * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5734  * ENV.select { |name, value| name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5735  * ENV.filter { |name, value| name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5736  *
5737  * Returns an Enumerator if no block given:
5738  * e = ENV.select # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:select>
5739  * e.each { |name, value | name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5740  * e = ENV.filter # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:filter>
5741  * e.each { |name, value | name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5742  */
5743 static VALUE
5744 env_select(VALUE ehash)
5745 {
5746  VALUE result;
5747  VALUE keys;
5748  long i;
5749 
5750  RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5751  result = rb_hash_new();
5752  keys = env_keys(FALSE);
5753  for (i = 0; i < RARRAY_LEN(keys); ++i) {
5754  VALUE key = RARRAY_AREF(keys, i);
5755  VALUE val = rb_f_getenv(Qnil, key);
5756  if (!NIL_P(val)) {
5757  if (RTEST(rb_yield_values(2, key, val))) {
5758  rb_hash_aset(result, key, val);
5759  }
5760  }
5761  }
5762  RB_GC_GUARD(keys);
5763 
5764  return result;
5765 }
5766 
5767 /*
5768  * call-seq:
5769  * ENV.select! { |name, value| block } -> ENV or nil
5770  * ENV.select! -> an_enumerator
5771  * ENV.filter! { |name, value| block } -> ENV or nil
5772  * ENV.filter! -> an_enumerator
5773  *
5774  * ENV.filter! is an alias for ENV.select!.
5775  *
5776  * Yields each environment variable name and its value as a 2-element Array,
5777  * deleting each entry for which the block returns +false+ or +nil+,
5778  * and returning ENV if any deletions made, or +nil+ otherwise:
5779  *
5780  * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5781  * ENV.select! { |name, value| name.start_with?('b') } # => ENV
5782  * ENV # => {"bar"=>"1", "baz"=>"2"}
5783  * ENV.select! { |name, value| true } # => nil
5784  *
5785  * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5786  * ENV.filter! { |name, value| name.start_with?('b') } # => ENV
5787  * ENV # => {"bar"=>"1", "baz"=>"2"}
5788  * ENV.filter! { |name, value| true } # => nil
5789  *
5790  * Returns an Enumerator if no block given:
5791  *
5792  * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5793  * e = ENV.select! # => #<Enumerator: {"bar"=>"1", "baz"=>"2"}:select!>
5794  * e.each { |name, value| name.start_with?('b') } # => ENV
5795  * ENV # => {"bar"=>"1", "baz"=>"2"}
5796  * e.each { |name, value| true } # => nil
5797  *
5798  * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5799  * e = ENV.filter! # => #<Enumerator: {"bar"=>"1", "baz"=>"2"}:filter!>
5800  * e.each { |name, value| name.start_with?('b') } # => ENV
5801  * ENV # => {"bar"=>"1", "baz"=>"2"}
5802  * e.each { |name, value| true } # => nil
5803  */
5804 static VALUE
5805 env_select_bang(VALUE ehash)
5806 {
5807  VALUE keys;
5808  long i;
5809  int del = 0;
5810 
5811  RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5812  keys = env_keys(FALSE);
5813  RBASIC_CLEAR_CLASS(keys);
5814  for (i=0; i<RARRAY_LEN(keys); i++) {
5815  VALUE val = rb_f_getenv(Qnil, RARRAY_AREF(keys, i));
5816  if (!NIL_P(val)) {
5817  if (!RTEST(rb_yield_values(2, RARRAY_AREF(keys, i), val))) {
5818  env_delete(RARRAY_AREF(keys, i));
5819  del++;
5820  }
5821  }
5822  }
5823  RB_GC_GUARD(keys);
5824  if (del == 0) return Qnil;
5825  return envtbl;
5826 }
5827 
5828 /*
5829  * call-seq:
5830  * ENV.keep_if { |name, value| block } -> ENV
5831  * ENV.keep_if -> an_enumerator
5832  *
5833  * Yields each environment variable name and its value as a 2-element Array,
5834  * deleting each environment variable for which the block returns +false+ or +nil+,
5835  * and returning ENV:
5836  * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5837  * ENV.keep_if { |name, value| name.start_with?('b') } # => ENV
5838  * ENV # => {"bar"=>"1", "baz"=>"2"}
5839  *
5840  * Returns an Enumerator if no block given:
5841  * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5842  * e = ENV.keep_if # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:keep_if>
5843  * e.each { |name, value| name.start_with?('b') } # => ENV
5844  * ENV # => {"bar"=>"1", "baz"=>"2"}
5845  */
5846 static VALUE
5847 env_keep_if(VALUE ehash)
5848 {
5849  RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5850  env_select_bang(ehash);
5851  return envtbl;
5852 }
5853 
5854 /*
5855  * call-seq:
5856  * ENV.slice(*names) -> hash of name/value pairs
5857  *
5858  * Returns a Hash of the given ENV names and their corresponding values:
5859  * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2', 'bat' => '3')
5860  * ENV.slice('foo', 'baz') # => {"foo"=>"0", "baz"=>"2"}
5861  * ENV.slice('baz', 'foo') # => {"baz"=>"2", "foo"=>"0"}
5862  * Raises an exception if any of the +names+ is invalid
5863  * (see {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values]):
5864  * ENV.slice('foo', 'bar', :bat) # Raises TypeError (no implicit conversion of Symbol into String)
5865  */
5866 static VALUE
5867 env_slice(int argc, VALUE *argv, VALUE _)
5868 {
5869  int i;
5870  VALUE key, value, result;
5871 
5872  if (argc == 0) {
5873  return rb_hash_new();
5874  }
5875  result = rb_hash_new_with_size(argc);
5876 
5877  for (i = 0; i < argc; i++) {
5878  key = argv[i];
5879  value = rb_f_getenv(Qnil, key);
5880  if (value != Qnil)
5881  rb_hash_aset(result, key, value);
5882  }
5883 
5884  return result;
5885 }
5886 
5887 VALUE
5889 {
5890  VALUE keys;
5891  long i;
5892 
5893  keys = env_keys(TRUE);
5894  for (i=0; i<RARRAY_LEN(keys); i++) {
5895  VALUE key = RARRAY_AREF(keys, i);
5896  const char *nam = RSTRING_PTR(key);
5897  ruby_setenv(nam, 0);
5898  }
5899  RB_GC_GUARD(keys);
5900  return envtbl;
5901 }
5902 
5903 /*
5904  * call-seq:
5905  * ENV.clear -> ENV
5906  *
5907  * Removes every environment variable; returns ENV:
5908  * ENV.replace('foo' => '0', 'bar' => '1')
5909  * ENV.size # => 2
5910  * ENV.clear # => ENV
5911  * ENV.size # => 0
5912  */
5913 static VALUE
5914 env_clear(VALUE _)
5915 {
5916  return rb_env_clear();
5917 }
5918 
5919 /*
5920  * call-seq:
5921  * ENV.to_s -> "ENV"
5922  *
5923  * Returns String 'ENV':
5924  * ENV.to_s # => "ENV"
5925  */
5926 static VALUE
5927 env_to_s(VALUE _)
5928 {
5929  return rb_usascii_str_new2("ENV");
5930 }
5931 
5932 /*
5933  * call-seq:
5934  * ENV.inspect -> a_string
5935  *
5936  * Returns the contents of the environment as a String:
5937  * ENV.replace('foo' => '0', 'bar' => '1')
5938  * ENV.inspect # => "{\"bar\"=>\"1\", \"foo\"=>\"0\"}"
5939  */
5940 static VALUE
5941 env_inspect(VALUE _)
5942 {
5943  VALUE i;
5944  VALUE str = rb_str_buf_new2("{");
5945 
5946  ENV_LOCK();
5947  {
5948  char **env = GET_ENVIRON(environ);
5949  while (*env) {
5950  char *s = strchr(*env, '=');
5951 
5952  if (env != environ) {
5953  rb_str_buf_cat2(str, ", ");
5954  }
5955  if (s) {
5956  rb_str_buf_cat2(str, "\"");
5957  rb_str_buf_cat(str, *env, s-*env);
5958  rb_str_buf_cat2(str, "\"=>");
5959  i = rb_inspect(rb_str_new2(s+1));
5960  rb_str_buf_append(str, i);
5961  }
5962  env++;
5963  }
5964  FREE_ENVIRON(environ);
5965  }
5966  ENV_UNLOCK();
5967 
5968  rb_str_buf_cat2(str, "}");
5969 
5970  return str;
5971 }
5972 
5973 /*
5974  * call-seq:
5975  * ENV.to_a -> array of 2-element arrays
5976  *
5977  * Returns the contents of ENV as an Array of 2-element Arrays,
5978  * each of which is a name/value pair:
5979  * ENV.replace('foo' => '0', 'bar' => '1')
5980  * ENV.to_a # => [["bar", "1"], ["foo", "0"]]
5981  */
5982 static VALUE
5983 env_to_a(VALUE _)
5984 {
5985  VALUE ary = rb_ary_new();
5986 
5987  ENV_LOCK();
5988  {
5989  char **env = GET_ENVIRON(environ);
5990  while (*env) {
5991  char *s = strchr(*env, '=');
5992  if (s) {
5993  rb_ary_push(ary, rb_assoc_new(env_str_new(*env, s-*env),
5994  env_str_new2(s+1)));
5995  }
5996  env++;
5997  }
5998  FREE_ENVIRON(environ);
5999  }
6000  ENV_UNLOCK();
6001 
6002  return ary;
6003 }
6004 
6005 /*
6006  * call-seq:
6007  * ENV.rehash -> nil
6008  *
6009  * (Provided for compatibility with Hash.)
6010  *
6011  * Does not modify ENV; returns +nil+.
6012  */
6013 static VALUE
6014 env_none(VALUE _)
6015 {
6016  return Qnil;
6017 }
6018 
6019 static int
6020 env_size_with_lock(void)
6021 {
6022  int i = 0;
6023 
6024  ENV_LOCK();
6025  {
6026  char **env = GET_ENVIRON(environ);
6027  while (env[i]) i++;
6028  FREE_ENVIRON(environ);
6029  }
6030  ENV_UNLOCK();
6031 
6032  return i;
6033 }
6034 
6035 /*
6036  * call-seq:
6037  * ENV.length -> an_integer
6038  * ENV.size -> an_integer
6039  *
6040  * Returns the count of environment variables:
6041  * ENV.replace('foo' => '0', 'bar' => '1')
6042  * ENV.length # => 2
6043  * ENV.size # => 2
6044  */
6045 static VALUE
6046 env_size(VALUE _)
6047 {
6048  return INT2FIX(env_size_with_lock());
6049 }
6050 
6051 /*
6052  * call-seq:
6053  * ENV.empty? -> true or false
6054  *
6055  * Returns +true+ when there are no environment variables, +false+ otherwise:
6056  * ENV.clear
6057  * ENV.empty? # => true
6058  * ENV['foo'] = '0'
6059  * ENV.empty? # => false
6060  */
6061 static VALUE
6062 env_empty_p(VALUE _)
6063 {
6064  bool empty = true;
6065 
6066  ENV_LOCK();
6067  {
6068  char **env = GET_ENVIRON(environ);
6069  if (env[0] != 0) {
6070  empty = false;
6071  }
6072  FREE_ENVIRON(environ);
6073  }
6074  ENV_UNLOCK();
6075 
6076  return RBOOL(empty);
6077 }
6078 
6079 /*
6080  * call-seq:
6081  * ENV.include?(name) -> true or false
6082  * ENV.has_key?(name) -> true or false
6083  * ENV.member?(name) -> true or false
6084  * ENV.key?(name) -> true or false
6085  *
6086  * ENV.has_key?, ENV.member?, and ENV.key? are aliases for ENV.include?.
6087  *
6088  * Returns +true+ if there is an environment variable with the given +name+:
6089  * ENV.replace('foo' => '0', 'bar' => '1')
6090  * ENV.include?('foo') # => true
6091  * Returns +false+ if +name+ is a valid String and there is no such environment variable:
6092  * ENV.include?('baz') # => false
6093  * Returns +false+ if +name+ is the empty String or is a String containing character <code>'='</code>:
6094  * ENV.include?('') # => false
6095  * ENV.include?('=') # => false
6096  * Raises an exception if +name+ is a String containing the NUL character <code>"\0"</code>:
6097  * ENV.include?("\0") # Raises ArgumentError (bad environment variable name: contains null byte)
6098  * Raises an exception if +name+ has an encoding that is not ASCII-compatible:
6099  * ENV.include?("\xa1\xa1".force_encoding(Encoding::UTF_16LE))
6100  * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: UTF-16LE)
6101  * Raises an exception if +name+ is not a String:
6102  * ENV.include?(Object.new) # TypeError (no implicit conversion of Object into String)
6103  */
6104 static VALUE
6105 env_has_key(VALUE env, VALUE key)
6106 {
6107  const char *s = env_name(key);
6108  return RBOOL(has_env_with_lock(s));
6109 }
6110 
6111 /*
6112  * call-seq:
6113  * ENV.assoc(name) -> [name, value] or nil
6114  *
6115  * Returns a 2-element Array containing the name and value of the environment variable
6116  * for +name+ if it exists:
6117  * ENV.replace('foo' => '0', 'bar' => '1')
6118  * ENV.assoc('foo') # => ['foo', '0']
6119  * Returns +nil+ if +name+ is a valid String and there is no such environment variable.
6120  *
6121  * Returns +nil+ if +name+ is the empty String or is a String containing character <code>'='</code>.
6122  *
6123  * Raises an exception if +name+ is a String containing the NUL character <code>"\0"</code>:
6124  * ENV.assoc("\0") # Raises ArgumentError (bad environment variable name: contains null byte)
6125  * Raises an exception if +name+ has an encoding that is not ASCII-compatible:
6126  * ENV.assoc("\xa1\xa1".force_encoding(Encoding::UTF_16LE))
6127  * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: UTF-16LE)
6128  * Raises an exception if +name+ is not a String:
6129  * ENV.assoc(Object.new) # TypeError (no implicit conversion of Object into String)
6130  */
6131 static VALUE
6132 env_assoc(VALUE env, VALUE key)
6133 {
6134  const char *s = env_name(key);
6135  VALUE e = getenv_with_lock(s);
6136 
6137  if (!NIL_P(e)) {
6138  return rb_assoc_new(key, e);
6139  }
6140  else {
6141  return Qnil;
6142  }
6143 }
6144 
6145 /*
6146  * call-seq:
6147  * ENV.value?(value) -> true or false
6148  * ENV.has_value?(value) -> true or false
6149  *
6150  * Returns +true+ if +value+ is the value for some environment variable name, +false+ otherwise:
6151  * ENV.replace('foo' => '0', 'bar' => '1')
6152  * ENV.value?('0') # => true
6153  * ENV.has_value?('0') # => true
6154  * ENV.value?('2') # => false
6155  * ENV.has_value?('2') # => false
6156  */
6157 static VALUE
6158 env_has_value(VALUE dmy, VALUE obj)
6159 {
6160  obj = rb_check_string_type(obj);
6161  if (NIL_P(obj)) return Qnil;
6162 
6163  VALUE ret = Qfalse;
6164 
6165  ENV_LOCK();
6166  {
6167  char **env = GET_ENVIRON(environ);
6168  while (*env) {
6169  char *s = strchr(*env, '=');
6170  if (s++) {
6171  long len = strlen(s);
6172  if (RSTRING_LEN(obj) == len && strncmp(s, RSTRING_PTR(obj), len) == 0) {
6173  ret = Qtrue;
6174  break;
6175  }
6176  }
6177  env++;
6178  }
6179  FREE_ENVIRON(environ);
6180  }
6181  ENV_UNLOCK();
6182 
6183  return ret;
6184 }
6185 
6186 /*
6187  * call-seq:
6188  * ENV.rassoc(value) -> [name, value] or nil
6189  *
6190  * Returns a 2-element Array containing the name and value of the
6191  * *first* *found* environment variable that has value +value+, if one
6192  * exists:
6193  * ENV.replace('foo' => '0', 'bar' => '0')
6194  * ENV.rassoc('0') # => ["bar", "0"]
6195  * The order in which environment variables are examined is OS-dependent.
6196  * See {About Ordering}[#class-ENV-label-About+Ordering].
6197  *
6198  * Returns +nil+ if there is no such environment variable.
6199  */
6200 static VALUE
6201 env_rassoc(VALUE dmy, VALUE obj)
6202 {
6203  obj = rb_check_string_type(obj);
6204  if (NIL_P(obj)) return Qnil;
6205 
6206  VALUE result = Qnil;
6207 
6208  ENV_LOCK();
6209  {
6210  char **env = GET_ENVIRON(environ);
6211 
6212  while (*env) {
6213  const char *p = *env;
6214  char *s = strchr(p, '=');
6215  if (s++) {
6216  long len = strlen(s);
6217  if (RSTRING_LEN(obj) == len && strncmp(s, RSTRING_PTR(obj), len) == 0) {
6218  result = rb_assoc_new(rb_str_new(p, s-p-1), obj);
6219  break;
6220  }
6221  }
6222  env++;
6223  }
6224  FREE_ENVIRON(environ);
6225  }
6226  ENV_UNLOCK();
6227 
6228  return result;
6229 }
6230 
6231 /*
6232  * call-seq:
6233  * ENV.key(value) -> name or nil
6234  *
6235  * Returns the name of the first environment variable with +value+, if it exists:
6236  * ENV.replace('foo' => '0', 'bar' => '0')
6237  * ENV.key('0') # => "foo"
6238  * The order in which environment variables are examined is OS-dependent.
6239  * See {About Ordering}[#class-ENV-label-About+Ordering].
6240  *
6241  * Returns +nil+ if there is no such value.
6242  *
6243  * Raises an exception if +value+ is invalid:
6244  * ENV.key(Object.new) # raises TypeError (no implicit conversion of Object into String)
6245  * See {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values].
6246  */
6247 static VALUE
6248 env_key(VALUE dmy, VALUE value)
6249 {
6250  SafeStringValue(value);
6251  VALUE str = Qnil;
6252 
6253  ENV_LOCK();
6254  {
6255  char **env = GET_ENVIRON(environ);
6256  while (*env) {
6257  char *s = strchr(*env, '=');
6258  if (s++) {
6259  long len = strlen(s);
6260  if (RSTRING_LEN(value) == len && strncmp(s, RSTRING_PTR(value), len) == 0) {
6261  str = env_str_new(*env, s-*env-1);
6262  break;
6263  }
6264  }
6265  env++;
6266  }
6267  FREE_ENVIRON(environ);
6268  }
6269  ENV_UNLOCK();
6270 
6271  return str;
6272 }
6273 
6274 static VALUE
6275 env_to_hash(void)
6276 {
6277  VALUE hash = rb_hash_new();
6278 
6279  ENV_LOCK();
6280  {
6281  char **env = GET_ENVIRON(environ);
6282  while (*env) {
6283  char *s = strchr(*env, '=');
6284  if (s) {
6285  rb_hash_aset(hash, env_str_new(*env, s-*env),
6286  env_str_new2(s+1));
6287  }
6288  env++;
6289  }
6290  FREE_ENVIRON(environ);
6291  }
6292  ENV_UNLOCK();
6293 
6294  return hash;
6295 }
6296 
6297 VALUE
6298 rb_envtbl(void)
6299 {
6300  return envtbl;
6301 }
6302 
6303 VALUE
6304 rb_env_to_hash(void)
6305 {
6306  return env_to_hash();
6307 }
6308 
6309 /*
6310  * call-seq:
6311  * ENV.to_hash -> hash of name/value pairs
6312  *
6313  * Returns a Hash containing all name/value pairs from ENV:
6314  * ENV.replace('foo' => '0', 'bar' => '1')
6315  * ENV.to_hash # => {"bar"=>"1", "foo"=>"0"}
6316  */
6317 
6318 static VALUE
6319 env_f_to_hash(VALUE _)
6320 {
6321  return env_to_hash();
6322 }
6323 
6324 /*
6325  * call-seq:
6326  * ENV.to_h -> hash of name/value pairs
6327  * ENV.to_h {|name, value| block } -> hash of name/value pairs
6328  *
6329  * With no block, returns a Hash containing all name/value pairs from ENV:
6330  * ENV.replace('foo' => '0', 'bar' => '1')
6331  * ENV.to_h # => {"bar"=>"1", "foo"=>"0"}
6332  * With a block, returns a Hash whose items are determined by the block.
6333  * Each name/value pair in ENV is yielded to the block.
6334  * The block must return a 2-element Array (name/value pair)
6335  * that is added to the return Hash as a key and value:
6336  * ENV.to_h { |name, value| [name.to_sym, value.to_i] } # => {:bar=>1, :foo=>0}
6337  * Raises an exception if the block does not return an Array:
6338  * ENV.to_h { |name, value| name } # Raises TypeError (wrong element type String (expected array))
6339  * Raises an exception if the block returns an Array of the wrong size:
6340  * ENV.to_h { |name, value| [name] } # Raises ArgumentError (element has wrong array length (expected 2, was 1))
6341  */
6342 static VALUE
6343 env_to_h(VALUE _)
6344 {
6345  VALUE hash = env_to_hash();
6346  if (rb_block_given_p()) {
6347  hash = rb_hash_to_h_block(hash);
6348  }
6349  return hash;
6350 }
6351 
6352 /*
6353  * call-seq:
6354  * ENV.except(*keys) -> a_hash
6355  *
6356  * Returns a hash except the given keys from ENV and their values.
6357  *
6358  * ENV #=> {"LANG"=>"en_US.UTF-8", "TERM"=>"xterm-256color", "HOME"=>"/Users/rhc"}
6359  * ENV.except("TERM","HOME") #=> {"LANG"=>"en_US.UTF-8"}
6360  */
6361 static VALUE
6362 env_except(int argc, VALUE *argv, VALUE _)
6363 {
6364  int i;
6365  VALUE key, hash = env_to_hash();
6366 
6367  for (i = 0; i < argc; i++) {
6368  key = argv[i];
6369  rb_hash_delete(hash, key);
6370  }
6371 
6372  return hash;
6373 }
6374 
6375 /*
6376  * call-seq:
6377  * ENV.reject { |name, value| block } -> hash of name/value pairs
6378  * ENV.reject -> an_enumerator
6379  *
6380  * Yields each environment variable name and its value as a 2-element Array.
6381  * Returns a Hash whose items are determined by the block.
6382  * When the block returns a truthy value, the name/value pair is added to the return Hash;
6383  * otherwise the pair is ignored:
6384  * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
6385  * ENV.reject { |name, value| name.start_with?('b') } # => {"foo"=>"0"}
6386  * Returns an Enumerator if no block given:
6387  * e = ENV.reject
6388  * e.each { |name, value| name.start_with?('b') } # => {"foo"=>"0"}
6389  */
6390 static VALUE
6391 env_reject(VALUE _)
6392 {
6393  return rb_hash_delete_if(env_to_hash());
6394 }
6395 
6396 NORETURN(static VALUE env_freeze(VALUE self));
6397 /*
6398  * call-seq:
6399  * ENV.freeze
6400  *
6401  * Raises an exception:
6402  * ENV.freeze # Raises TypeError (cannot freeze ENV)
6403  */
6404 static VALUE
6405 env_freeze(VALUE self)
6406 {
6407  rb_raise(rb_eTypeError, "cannot freeze ENV");
6408  UNREACHABLE_RETURN(self);
6409 }
6410 
6411 /*
6412  * call-seq:
6413  * ENV.shift -> [name, value] or nil
6414  *
6415  * Removes the first environment variable from ENV and returns
6416  * a 2-element Array containing its name and value:
6417  * ENV.replace('foo' => '0', 'bar' => '1')
6418  * ENV.to_hash # => {'bar' => '1', 'foo' => '0'}
6419  * ENV.shift # => ['bar', '1']
6420  * ENV.to_hash # => {'foo' => '0'}
6421  * Exactly which environment variable is "first" is OS-dependent.
6422  * See {About Ordering}[#class-ENV-label-About+Ordering].
6423  *
6424  * Returns +nil+ if the environment is empty.
6425  */
6426 static VALUE
6427 env_shift(VALUE _)
6428 {
6429  VALUE result = Qnil;
6430  VALUE key = Qnil;
6431 
6432  ENV_LOCK();
6433  {
6434  char **env = GET_ENVIRON(environ);
6435  if (*env) {
6436  const char *p = *env;
6437  char *s = strchr(p, '=');
6438  if (s) {
6439  key = env_str_new(p, s-p);
6440  VALUE val = env_str_new2(getenv(RSTRING_PTR(key)));
6441  result = rb_assoc_new(key, val);
6442  }
6443  }
6444  FREE_ENVIRON(environ);
6445  }
6446  ENV_UNLOCK();
6447 
6448  if (!NIL_P(key)) {
6449  env_delete(key);
6450  }
6451 
6452  return result;
6453 }
6454 
6455 /*
6456  * call-seq:
6457  * ENV.invert -> hash of value/name pairs
6458  *
6459  * Returns a Hash whose keys are the ENV values,
6460  * and whose values are the corresponding ENV names:
6461  * ENV.replace('foo' => '0', 'bar' => '1')
6462  * ENV.invert # => {"1"=>"bar", "0"=>"foo"}
6463  * For a duplicate ENV value, overwrites the hash entry:
6464  * ENV.replace('foo' => '0', 'bar' => '0')
6465  * ENV.invert # => {"0"=>"foo"}
6466  * Note that the order of the ENV processing is OS-dependent,
6467  * which means that the order of overwriting is also OS-dependent.
6468  * See {About Ordering}[#class-ENV-label-About+Ordering].
6469  */
6470 static VALUE
6471 env_invert(VALUE _)
6472 {
6473  return rb_hash_invert(env_to_hash());
6474 }
6475 
6476 static void
6477 keylist_delete(VALUE keys, VALUE key)
6478 {
6479  long keylen, elen;
6480  const char *keyptr, *eptr;
6481  RSTRING_GETMEM(key, keyptr, keylen);
6482  /* Don't stop at first key, as it is possible to have
6483  multiple environment values with the same key.
6484  */
6485  for (long i=0; i<RARRAY_LEN(keys); i++) {
6486  VALUE e = RARRAY_AREF(keys, i);
6487  RSTRING_GETMEM(e, eptr, elen);
6488  if (elen != keylen) continue;
6489  if (!ENVNMATCH(keyptr, eptr, elen)) continue;
6490  rb_ary_delete_at(keys, i);
6491  i--;
6492  }
6493 }
6494 
6495 static int
6496 env_replace_i(VALUE key, VALUE val, VALUE keys)
6497 {
6498  env_name(key);
6499  env_aset(key, val);
6500 
6501  keylist_delete(keys, key);
6502  return ST_CONTINUE;
6503 }
6504 
6505 /*
6506  * call-seq:
6507  * ENV.replace(hash) -> ENV
6508  *
6509  * Replaces the entire content of the environment variables
6510  * with the name/value pairs in the given +hash+;
6511  * returns ENV.
6512  *
6513  * Replaces the content of ENV with the given pairs:
6514  * ENV.replace('foo' => '0', 'bar' => '1') # => ENV
6515  * ENV.to_hash # => {"bar"=>"1", "foo"=>"0"}
6516  *
6517  * Raises an exception if a name or value is invalid
6518  * (see {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values]):
6519  * ENV.replace('foo' => '0', :bar => '1') # Raises TypeError (no implicit conversion of Symbol into String)
6520  * ENV.replace('foo' => '0', 'bar' => 1) # Raises TypeError (no implicit conversion of Integer into String)
6521  * ENV.to_hash # => {"bar"=>"1", "foo"=>"0"}
6522  */
6523 static VALUE
6524 env_replace(VALUE env, VALUE hash)
6525 {
6526  VALUE keys;
6527  long i;
6528 
6529  keys = env_keys(TRUE);
6530  if (env == hash) return env;
6531  hash = to_hash(hash);
6532  rb_hash_foreach(hash, env_replace_i, keys);
6533 
6534  for (i=0; i<RARRAY_LEN(keys); i++) {
6535  env_delete(RARRAY_AREF(keys, i));
6536  }
6537  RB_GC_GUARD(keys);
6538  return env;
6539 }
6540 
6541 static int
6542 env_update_i(VALUE key, VALUE val, VALUE _)
6543 {
6544  env_aset(key, val);
6545  return ST_CONTINUE;
6546 }
6547 
6548 static int
6549 env_update_block_i(VALUE key, VALUE val, VALUE _)
6550 {
6551  VALUE oldval = rb_f_getenv(Qnil, key);
6552  if (!NIL_P(oldval)) {
6553  val = rb_yield_values(3, key, oldval, val);
6554  }
6555  env_aset(key, val);
6556  return ST_CONTINUE;
6557 }
6558 
6559 /*
6560  * call-seq:
6561  * ENV.update(hash) -> ENV
6562  * ENV.update(hash) { |name, env_val, hash_val| block } -> ENV
6563  * ENV.merge!(hash) -> ENV
6564  * ENV.merge!(hash) { |name, env_val, hash_val| block } -> ENV
6565  *
6566  * ENV.update is an alias for ENV.merge!.
6567  *
6568  * Adds to ENV each key/value pair in the given +hash+; returns ENV:
6569  * ENV.replace('foo' => '0', 'bar' => '1')
6570  * ENV.merge!('baz' => '2', 'bat' => '3') # => {"bar"=>"1", "bat"=>"3", "baz"=>"2", "foo"=>"0"}
6571  * Deletes the ENV entry for a hash value that is +nil+:
6572  * ENV.merge!('baz' => nil, 'bat' => nil) # => {"bar"=>"1", "foo"=>"0"}
6573  * For an already-existing name, if no block given, overwrites the ENV value:
6574  * ENV.merge!('foo' => '4') # => {"bar"=>"1", "foo"=>"4"}
6575  * For an already-existing name, if block given,
6576  * yields the name, its ENV value, and its hash value;
6577  * the block's return value becomes the new name:
6578  * ENV.merge!('foo' => '5') { |name, env_val, hash_val | env_val + hash_val } # => {"bar"=>"1", "foo"=>"45"}
6579  * Raises an exception if a name or value is invalid
6580  * (see {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values]);
6581  * ENV.replace('foo' => '0', 'bar' => '1')
6582  * ENV.merge!('foo' => '6', :bar => '7', 'baz' => '9') # Raises TypeError (no implicit conversion of Symbol into String)
6583  * ENV # => {"bar"=>"1", "foo"=>"6"}
6584  * ENV.merge!('foo' => '7', 'bar' => 8, 'baz' => '9') # Raises TypeError (no implicit conversion of Integer into String)
6585  * ENV # => {"bar"=>"1", "foo"=>"7"}
6586  * Raises an exception if the block returns an invalid name:
6587  * (see {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values]):
6588  * ENV.merge!('bat' => '8', 'foo' => '9') { |name, env_val, hash_val | 10 } # Raises TypeError (no implicit conversion of Integer into String)
6589  * ENV # => {"bar"=>"1", "bat"=>"8", "foo"=>"7"}
6590  *
6591  * Note that for the exceptions above,
6592  * hash pairs preceding an invalid name or value are processed normally;
6593  * those following are ignored.
6594  */
6595 static VALUE
6596 env_update(VALUE env, VALUE hash)
6597 {
6598  if (env == hash) return env;
6599  hash = to_hash(hash);
6600  rb_foreach_func *func = rb_block_given_p() ?
6601  env_update_block_i : env_update_i;
6602  rb_hash_foreach(hash, func, 0);
6603  return env;
6604 }
6605 
6606 /*
6607  * call-seq:
6608  * ENV.clone(freeze: nil) -> ENV
6609  *
6610  * Returns ENV itself, and warns because ENV is a wrapper for the
6611  * process-wide environment variables and a clone is useless.
6612  * If +freeze+ keyword is given and not +nil+ or +false+, raises ArgumentError.
6613  * If +freeze+ keyword is given and +true+, raises TypeError, as ENV storage
6614  * cannot be frozen.
6615  */
6616 static VALUE
6617 env_clone(int argc, VALUE *argv, VALUE obj)
6618 {
6619  if (argc) {
6620  VALUE opt, kwfreeze;
6621  if (rb_scan_args(argc, argv, "0:", &opt) < argc) {
6622  kwfreeze = rb_get_freeze_opt(1, &opt);
6623  if (RTEST(kwfreeze)) {
6624  rb_raise(rb_eTypeError, "cannot freeze ENV");
6625  }
6626  }
6627  }
6628 
6629  rb_warn_deprecated("ENV.clone", "ENV.to_h");
6630  return envtbl;
6631 }
6632 
6633 NORETURN(static VALUE env_dup(VALUE));
6634 /*
6635  * call-seq:
6636  * ENV.dup # raises TypeError
6637  *
6638  * Raises TypeError, because ENV is a singleton object.
6639  * Use #to_h to get a copy of ENV data as a hash.
6640  */
6641 static VALUE
6642 env_dup(VALUE obj)
6643 {
6644  rb_raise(rb_eTypeError, "Cannot dup ENV, use ENV.to_h to get a copy of ENV as a hash");
6645 }
6646 
6647 static const rb_data_type_t env_data_type = {
6648  "ENV",
6649  {
6650  NULL,
6651  NULL,
6652  NULL,
6653  NULL,
6654  },
6655  0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED,
6656 };
6657 
6658 /*
6659  * A \Hash maps each of its unique keys to a specific value.
6660  *
6661  * A \Hash has certain similarities to an \Array, but:
6662  * - An \Array index is always an \Integer.
6663  * - A \Hash key can be (almost) any object.
6664  *
6665  * === \Hash \Data Syntax
6666  *
6667  * The older syntax for \Hash data uses the "hash rocket," <tt>=></tt>:
6668  *
6669  * h = {:foo => 0, :bar => 1, :baz => 2}
6670  * h # => {:foo=>0, :bar=>1, :baz=>2}
6671  *
6672  * Alternatively, but only for a \Hash key that's a \Symbol,
6673  * you can use a newer JSON-style syntax,
6674  * where each bareword becomes a \Symbol:
6675  *
6676  * h = {foo: 0, bar: 1, baz: 2}
6677  * h # => {:foo=>0, :bar=>1, :baz=>2}
6678  *
6679  * You can also use a \String in place of a bareword:
6680  *
6681  * h = {'foo': 0, 'bar': 1, 'baz': 2}
6682  * h # => {:foo=>0, :bar=>1, :baz=>2}
6683  *
6684  * And you can mix the styles:
6685  *
6686  * h = {foo: 0, :bar => 1, 'baz': 2}
6687  * h # => {:foo=>0, :bar=>1, :baz=>2}
6688  *
6689  * But it's an error to try the JSON-style syntax
6690  * for a key that's not a bareword or a String:
6691  *
6692  * # Raises SyntaxError (syntax error, unexpected ':', expecting =>):
6693  * h = {0: 'zero'}
6694  *
6695  * Hash value can be omitted, meaning that value will be fetched from the context
6696  * by the name of the key:
6697  *
6698  * x = 0
6699  * y = 100
6700  * h = {x:, y:}
6701  * h # => {:x=>0, :y=>100}
6702  *
6703  * === Common Uses
6704  *
6705  * You can use a \Hash to give names to objects:
6706  *
6707  * person = {name: 'Matz', language: 'Ruby'}
6708  * person # => {:name=>"Matz", :language=>"Ruby"}
6709  *
6710  * You can use a \Hash to give names to method arguments:
6711  *
6712  * def some_method(hash)
6713  * p hash
6714  * end
6715  * some_method({foo: 0, bar: 1, baz: 2}) # => {:foo=>0, :bar=>1, :baz=>2}
6716  *
6717  * Note: when the last argument in a method call is a \Hash,
6718  * the curly braces may be omitted:
6719  *
6720  * some_method(foo: 0, bar: 1, baz: 2) # => {:foo=>0, :bar=>1, :baz=>2}
6721  *
6722  * You can use a \Hash to initialize an object:
6723  *
6724  * class Dev
6725  * attr_accessor :name, :language
6726  * def initialize(hash)
6727  * self.name = hash[:name]
6728  * self.language = hash[:language]
6729  * end
6730  * end
6731  * matz = Dev.new(name: 'Matz', language: 'Ruby')
6732  * matz # => #<Dev: @name="Matz", @language="Ruby">
6733  *
6734  * === Creating a \Hash
6735  *
6736  * You can create a \Hash object explicitly with:
6737  *
6738  * - A {hash literal}[doc/syntax/literals_rdoc.html#label-Hash+Literals].
6739  *
6740  * You can convert certain objects to Hashes with:
6741  *
6742  * - \Method {Hash}[Kernel.html#method-i-Hash].
6743  *
6744  * You can create a \Hash by calling method Hash.new.
6745  *
6746  * Create an empty Hash:
6747  *
6748  * h = Hash.new
6749  * h # => {}
6750  * h.class # => Hash
6751  *
6752  * You can create a \Hash by calling method Hash.[].
6753  *
6754  * Create an empty Hash:
6755  *
6756  * h = Hash[]
6757  * h # => {}
6758  *
6759  * Create a \Hash with initial entries:
6760  *
6761  * h = Hash[foo: 0, bar: 1, baz: 2]
6762  * h # => {:foo=>0, :bar=>1, :baz=>2}
6763  *
6764  * You can create a \Hash by using its literal form (curly braces).
6765  *
6766  * Create an empty \Hash:
6767  *
6768  * h = {}
6769  * h # => {}
6770  *
6771  * Create a \Hash with initial entries:
6772  *
6773  * h = {foo: 0, bar: 1, baz: 2}
6774  * h # => {:foo=>0, :bar=>1, :baz=>2}
6775  *
6776  *
6777  * === \Hash Value Basics
6778  *
6779  * The simplest way to retrieve a \Hash value (instance method #[]):
6780  *
6781  * h = {foo: 0, bar: 1, baz: 2}
6782  * h[:foo] # => 0
6783  *
6784  * The simplest way to create or update a \Hash value (instance method #[]=):
6785  *
6786  * h = {foo: 0, bar: 1, baz: 2}
6787  * h[:bat] = 3 # => 3
6788  * h # => {:foo=>0, :bar=>1, :baz=>2, :bat=>3}
6789  * h[:foo] = 4 # => 4
6790  * h # => {:foo=>4, :bar=>1, :baz=>2, :bat=>3}
6791  *
6792  * The simplest way to delete a \Hash entry (instance method #delete):
6793  *
6794  * h = {foo: 0, bar: 1, baz: 2}
6795  * h.delete(:bar) # => 1
6796  * h # => {:foo=>0, :baz=>2}
6797  *
6798  * === Entry Order
6799  *
6800  * A \Hash object presents its entries in the order of their creation. This is seen in:
6801  *
6802  * - Iterative methods such as <tt>each</tt>, <tt>each_key</tt>, <tt>each_pair</tt>, <tt>each_value</tt>.
6803  * - Other order-sensitive methods such as <tt>shift</tt>, <tt>keys</tt>, <tt>values</tt>.
6804  * - The \String returned by method <tt>inspect</tt>.
6805  *
6806  * A new \Hash has its initial ordering per the given entries:
6807  *
6808  * h = Hash[foo: 0, bar: 1]
6809  * h # => {:foo=>0, :bar=>1}
6810  *
6811  * New entries are added at the end:
6812  *
6813  * h[:baz] = 2
6814  * h # => {:foo=>0, :bar=>1, :baz=>2}
6815  *
6816  * Updating a value does not affect the order:
6817  *
6818  * h[:baz] = 3
6819  * h # => {:foo=>0, :bar=>1, :baz=>3}
6820  *
6821  * But re-creating a deleted entry can affect the order:
6822  *
6823  * h.delete(:foo)
6824  * h[:foo] = 5
6825  * h # => {:bar=>1, :baz=>3, :foo=>5}
6826  *
6827  * === \Hash Keys
6828  *
6829  * ==== \Hash Key Equivalence
6830  *
6831  * Two objects are treated as the same \hash key when their <code>hash</code> value
6832  * is identical and the two objects are <code>eql?</code> to each other.
6833  *
6834  * ==== Modifying an Active \Hash Key
6835  *
6836  * Modifying a \Hash key while it is in use damages the hash's index.
6837  *
6838  * This \Hash has keys that are Arrays:
6839  *
6840  * a0 = [ :foo, :bar ]
6841  * a1 = [ :baz, :bat ]
6842  * h = {a0 => 0, a1 => 1}
6843  * h.include?(a0) # => true
6844  * h[a0] # => 0
6845  * a0.hash # => 110002110
6846  *
6847  * Modifying array element <tt>a0[0]</tt> changes its hash value:
6848  *
6849  * a0[0] = :bam
6850  * a0.hash # => 1069447059
6851  *
6852  * And damages the \Hash index:
6853  *
6854  * h.include?(a0) # => false
6855  * h[a0] # => nil
6856  *
6857  * You can repair the hash index using method +rehash+:
6858  *
6859  * h.rehash # => {[:bam, :bar]=>0, [:baz, :bat]=>1}
6860  * h.include?(a0) # => true
6861  * h[a0] # => 0
6862  *
6863  * A \String key is always safe.
6864  * That's because an unfrozen \String
6865  * passed as a key will be replaced by a duplicated and frozen \String:
6866  *
6867  * s = 'foo'
6868  * s.frozen? # => false
6869  * h = {s => 0}
6870  * first_key = h.keys.first
6871  * first_key.frozen? # => true
6872  *
6873  * ==== User-Defined \Hash Keys
6874  *
6875  * To be useable as a \Hash key, objects must implement the methods <code>hash</code> and <code>eql?</code>.
6876  * Note: this requirement does not apply if the \Hash uses #compare_by_identity since comparison will then
6877  * rely on the keys' object id instead of <code>hash</code> and <code>eql?</code>.
6878  *
6879  * \Object defines basic implementation for <code>hash</code> and <code>eq?</code> that makes each object
6880  * a distinct key. Typically, user-defined classes will want to override these methods to provide meaningful
6881  * behavior, or for example inherit \Struct that has useful definitions for these.
6882  *
6883  * A typical implementation of <code>hash</code> is based on the
6884  * object's data while <code>eql?</code> is usually aliased to the overridden
6885  * <code>==</code> method:
6886  *
6887  * class Book
6888  * attr_reader :author, :title
6889  *
6890  * def initialize(author, title)
6891  * @author = author
6892  * @title = title
6893  * end
6894  *
6895  * def ==(other)
6896  * self.class === other &&
6897  * other.author == @author &&
6898  * other.title == @title
6899  * end
6900  *
6901  * alias eql? ==
6902  *
6903  * def hash
6904  * @author.hash ^ @title.hash # XOR
6905  * end
6906  * end
6907  *
6908  * book1 = Book.new 'matz', 'Ruby in a Nutshell'
6909  * book2 = Book.new 'matz', 'Ruby in a Nutshell'
6910  *
6911  * reviews = {}
6912  *
6913  * reviews[book1] = 'Great reference!'
6914  * reviews[book2] = 'Nice and compact!'
6915  *
6916  * reviews.length #=> 1
6917  *
6918  * === Default Values
6919  *
6920  * The methods #[], #values_at and #dig need to return the value associated to a certain key.
6921  * When that key is not found, that value will be determined by its default proc (if any)
6922  * or else its default (initially `nil`).
6923  *
6924  * You can retrieve the default value with method #default:
6925  *
6926  * h = Hash.new
6927  * h.default # => nil
6928  *
6929  * You can set the default value by passing an argument to method Hash.new or
6930  * with method #default=
6931  *
6932  * h = Hash.new(-1)
6933  * h.default # => -1
6934  * h.default = 0
6935  * h.default # => 0
6936  *
6937  * This default value is returned for #[], #values_at and #dig when a key is
6938  * not found:
6939  *
6940  * counts = {foo: 42}
6941  * counts.default # => nil (default)
6942  * counts[:foo] = 42
6943  * counts[:bar] # => nil
6944  * counts.default = 0
6945  * counts[:bar] # => 0
6946  * counts.values_at(:foo, :bar, :baz) # => [42, 0, 0]
6947  * counts.dig(:bar) # => 0
6948  *
6949  * Note that the default value is used without being duplicated. It is not advised to set
6950  * the default value to a mutable object:
6951  *
6952  * synonyms = Hash.new([])
6953  * synonyms[:hello] # => []
6954  * synonyms[:hello] << :hi # => [:hi], but this mutates the default!
6955  * synonyms.default # => [:hi]
6956  * synonyms[:world] << :universe
6957  * synonyms[:world] # => [:hi, :universe], oops
6958  * synonyms.keys # => [], oops
6959  *
6960  * To use a mutable object as default, it is recommended to use a default proc
6961  *
6962  * ==== Default \Proc
6963  *
6964  * When the default proc for a \Hash is set (i.e., not +nil+),
6965  * the default value returned by method #[] is determined by the default proc alone.
6966  *
6967  * You can retrieve the default proc with method #default_proc:
6968  *
6969  * h = Hash.new
6970  * h.default_proc # => nil
6971  *
6972  * You can set the default proc by calling Hash.new with a block or
6973  * calling the method #default_proc=
6974  *
6975  * h = Hash.new { |hash, key| "Default value for #{key}" }
6976  * h.default_proc.class # => Proc
6977  * h.default_proc = proc { |hash, key| "Default value for #{key.inspect}" }
6978  * h.default_proc.class # => Proc
6979  *
6980  * When the default proc is set (i.e., not +nil+)
6981  * and method #[] is called with with a non-existent key,
6982  * #[] calls the default proc with both the \Hash object itself and the missing key,
6983  * then returns the proc's return value:
6984  *
6985  * h = Hash.new { |hash, key| "Default value for #{key}" }
6986  * h[:nosuch] # => "Default value for nosuch"
6987  *
6988  * Note that in the example above no entry for key +:nosuch+ is created:
6989  *
6990  * h.include?(:nosuch) # => false
6991  *
6992  * However, the proc itself can add a new entry:
6993  *
6994  * synonyms = Hash.new { |hash, key| hash[key] = [] }
6995  * synonyms.include?(:hello) # => false
6996  * synonyms[:hello] << :hi # => [:hi]
6997  * synonyms[:world] << :universe # => [:universe]
6998  * synonyms.keys # => [:hello, :world]
6999  *
7000  * Note that setting the default proc will clear the default value and vice versa.
7001  *
7002  * === What's Here
7003  *
7004  * First, what's elsewhere. \Class \Hash:
7005  *
7006  * - Inherits from {class Object}[Object.html#class-Object-label-What-27s+Here].
7007  * - Includes {module Enumerable}[Enumerable.html#module-Enumerable-label-What-27s+Here],
7008  * which provides dozens of additional methods.
7009  *
7010  * Here, class \Hash provides methods that are useful for:
7011  *
7012  * - {Creating a Hash}[#class-Hash-label-Methods+for+Creating+a+Hash]
7013  * - {Setting Hash State}[#class-Hash-label-Methods+for+Setting+Hash+State]
7014  * - {Querying}[#class-Hash-label-Methods+for+Querying]
7015  * - {Comparing}[#class-Hash-label-Methods+for+Comparing]
7016  * - {Fetching}[#class-Hash-label-Methods+for+Fetching]
7017  * - {Assigning}[#class-Hash-label-Methods+for+Assigning]
7018  * - {Deleting}[#class-Hash-label-Methods+for+Deleting]
7019  * - {Iterating}[#class-Hash-label-Methods+for+Iterating]
7020  * - {Converting}[#class-Hash-label-Methods+for+Converting]
7021  * - {Transforming Keys and Values}[#class-Hash-label-Methods+for+Transforming+Keys+and+Values]
7022  * - {And more....}[#class-Hash-label-Other+Methods]
7023  *
7024  * \Class \Hash also includes methods from module Enumerable.
7025  *
7026  * ==== Methods for Creating a \Hash
7027  *
7028  * ::[]:: Returns a new hash populated with given objects.
7029  * ::new:: Returns a new empty hash.
7030  * ::try_convert:: Returns a new hash created from a given object.
7031  *
7032  * ==== Methods for Setting \Hash State
7033  *
7034  * #compare_by_identity:: Sets +self+ to consider only identity in comparing keys.
7035  * #default=:: Sets the default to a given value.
7036  * #default_proc=:: Sets the default proc to a given proc.
7037  * #rehash:: Rebuilds the hash table by recomputing the hash index for each key.
7038  *
7039  * ==== Methods for Querying
7040  *
7041  * #any?:: Returns whether any element satisfies a given criterion.
7042  * #compare_by_identity?:: Returns whether the hash considers only identity when comparing keys.
7043  * #default:: Returns the default value, or the default value for a given key.
7044  * #default_proc:: Returns the default proc.
7045  * #empty?:: Returns whether there are no entries.
7046  * #eql?:: Returns whether a given object is equal to +self+.
7047  * #hash:: Returns the integer hash code.
7048  * #has_value?:: Returns whether a given object is a value in +self+.
7049  * #include?, #has_key?, #member?, #key?:: Returns whether a given object is a key in +self+.
7050  * #length, #size:: Returns the count of entries.
7051  * #value?:: Returns whether a given object is a value in +self+.
7052  *
7053  * ==== Methods for Comparing
7054  *
7055  * {#<}[#method-i-3C]:: Returns whether +self+ is a proper subset of a given object.
7056  * {#<=}[#method-i-3C-3D]:: Returns whether +self+ is a subset of a given object.
7057  * {#==}[#method-i-3D-3D]:: Returns whether a given object is equal to +self+.
7058  * {#>}[#method-i-3E]:: Returns whether +self+ is a proper superset of a given object
7059  * {#>=}[#method-i-3E-3D]:: Returns whether +self+ is a proper superset of a given object.
7060  *
7061  * ==== Methods for Fetching
7062  *
7063  * #[]:: Returns the value associated with a given key.
7064  * #assoc:: Returns a 2-element array containing a given key and its value.
7065  * #dig:: Returns the object in nested objects that is specified
7066  * by a given key and additional arguments.
7067  * #fetch:: Returns the value for a given key.
7068  * #fetch_values:: Returns array containing the values associated with given keys.
7069  * #key:: Returns the key for the first-found entry with a given value.
7070  * #keys:: Returns an array containing all keys in +self+.
7071  * #rassoc:: Returns a 2-element array consisting of the key and value
7072  of the first-found entry having a given value.
7073  * #values:: Returns an array containing all values in +self+/
7074  * #values_at:: Returns an array containing values for given keys.
7075  *
7076  * ==== Methods for Assigning
7077  *
7078  * #[]=, #store:: Associates a given key with a given value.
7079  * #merge:: Returns the hash formed by merging each given hash into a copy of +self+.
7080  * #merge!, #update:: Merges each given hash into +self+.
7081  * #replace:: Replaces the entire contents of +self+ with the contents of a givan hash.
7082  *
7083  * ==== Methods for Deleting
7084  *
7085  * These methods remove entries from +self+:
7086  *
7087  * #clear:: Removes all entries from +self+.
7088  * #compact!:: Removes all +nil+-valued entries from +self+.
7089  * #delete:: Removes the entry for a given key.
7090  * #delete_if:: Removes entries selected by a given block.
7091  * #filter!, #select!:: Keep only those entries selected by a given block.
7092  * #keep_if:: Keep only those entries selected by a given block.
7093  * #reject!:: Removes entries selected by a given block.
7094  * #shift:: Removes and returns the first entry.
7095  *
7096  * These methods return a copy of +self+ with some entries removed:
7097  *
7098  * #compact:: Returns a copy of +self+ with all +nil+-valued entries removed.
7099  * #except:: Returns a copy of +self+ with entries removed for specified keys.
7100  * #filter, #select:: Returns a copy of +self+ with only those entries selected by a given block.
7101  * #reject:: Returns a copy of +self+ with entries removed as specified by a given block.
7102  * #slice:: Returns a hash containing the entries for given keys.
7103  *
7104  * ==== Methods for Iterating
7105  * #each, #each_pair:: Calls a given block with each key-value pair.
7106  * #each_key:: Calls a given block with each key.
7107  * #each_value:: Calls a given block with each value.
7108  *
7109  * ==== Methods for Converting
7110  *
7111  * #inspect, #to_s:: Returns a new String containing the hash entries.
7112  * #to_a:: Returns a new array of 2-element arrays;
7113  * each nested array contains a key-value pair from +self+.
7114  * #to_h:: Returns +self+ if a \Hash;
7115  * if a subclass of \Hash, returns a \Hash containing the entries from +self+.
7116  * #to_hash:: Returns +self+.
7117  * #to_proc:: Returns a proc that maps a given key to its value.
7118  *
7119  * ==== Methods for Transforming Keys and Values
7120  *
7121  * #transform_keys:: Returns a copy of +self+ with modified keys.
7122  * #transform_keys!:: Modifies keys in +self+
7123  * #transform_values:: Returns a copy of +self+ with modified values.
7124  * #transform_values!:: Modifies values in +self+.
7125  *
7126  * ==== Other Methods
7127  * #flatten:: Returns an array that is a 1-dimensional flattening of +self+.
7128  * #invert:: Returns a hash with the each key-value pair inverted.
7129  *
7130  */
7131 
7132 void
7133 Init_Hash(void)
7134 {
7135  id_hash = rb_intern_const("hash");
7136  id_default = rb_intern_const("default");
7137  id_flatten_bang = rb_intern_const("flatten!");
7138  id_hash_iter_lev = rb_make_internal_id();
7139 
7140  rb_cHash = rb_define_class("Hash", rb_cObject);
7141 
7143 
7144  rb_define_alloc_func(rb_cHash, empty_hash_alloc);
7145  rb_define_singleton_method(rb_cHash, "[]", rb_hash_s_create, -1);
7146  rb_define_singleton_method(rb_cHash, "try_convert", rb_hash_s_try_convert, 1);
7147  rb_define_method(rb_cHash, "initialize", rb_hash_initialize, -1);
7148  rb_define_method(rb_cHash, "initialize_copy", rb_hash_replace, 1);
7149  rb_define_method(rb_cHash, "rehash", rb_hash_rehash, 0);
7150 
7151  rb_define_method(rb_cHash, "to_hash", rb_hash_to_hash, 0);
7152  rb_define_method(rb_cHash, "to_h", rb_hash_to_h, 0);
7153  rb_define_method(rb_cHash, "to_a", rb_hash_to_a, 0);
7154  rb_define_method(rb_cHash, "inspect", rb_hash_inspect, 0);
7155  rb_define_alias(rb_cHash, "to_s", "inspect");
7156  rb_define_method(rb_cHash, "to_proc", rb_hash_to_proc, 0);
7157 
7158  rb_define_method(rb_cHash, "==", rb_hash_equal, 1);
7160  rb_define_method(rb_cHash, "hash", rb_hash_hash, 0);
7161  rb_define_method(rb_cHash, "eql?", rb_hash_eql, 1);
7162  rb_define_method(rb_cHash, "fetch", rb_hash_fetch_m, -1);
7164  rb_define_method(rb_cHash, "store", rb_hash_aset, 2);
7165  rb_define_method(rb_cHash, "default", rb_hash_default, -1);
7166  rb_define_method(rb_cHash, "default=", rb_hash_set_default, 1);
7167  rb_define_method(rb_cHash, "default_proc", rb_hash_default_proc, 0);
7168  rb_define_method(rb_cHash, "default_proc=", rb_hash_set_default_proc, 1);
7169  rb_define_method(rb_cHash, "key", rb_hash_key, 1);
7170  rb_define_method(rb_cHash, "size", rb_hash_size, 0);
7171  rb_define_method(rb_cHash, "length", rb_hash_size, 0);
7172  rb_define_method(rb_cHash, "empty?", rb_hash_empty_p, 0);
7173 
7174  rb_define_method(rb_cHash, "each_value", rb_hash_each_value, 0);
7175  rb_define_method(rb_cHash, "each_key", rb_hash_each_key, 0);
7176  rb_define_method(rb_cHash, "each_pair", rb_hash_each_pair, 0);
7177  rb_define_method(rb_cHash, "each", rb_hash_each_pair, 0);
7178 
7179  rb_define_method(rb_cHash, "transform_keys", rb_hash_transform_keys, -1);
7180  rb_define_method(rb_cHash, "transform_keys!", rb_hash_transform_keys_bang, -1);
7181  rb_define_method(rb_cHash, "transform_values", rb_hash_transform_values, 0);
7182  rb_define_method(rb_cHash, "transform_values!", rb_hash_transform_values_bang, 0);
7183 
7184  rb_define_method(rb_cHash, "keys", rb_hash_keys, 0);
7185  rb_define_method(rb_cHash, "values", rb_hash_values, 0);
7186  rb_define_method(rb_cHash, "values_at", rb_hash_values_at, -1);
7187  rb_define_method(rb_cHash, "fetch_values", rb_hash_fetch_values, -1);
7188 
7189  rb_define_method(rb_cHash, "shift", rb_hash_shift, 0);
7190  rb_define_method(rb_cHash, "delete", rb_hash_delete_m, 1);
7191  rb_define_method(rb_cHash, "delete_if", rb_hash_delete_if, 0);
7192  rb_define_method(rb_cHash, "keep_if", rb_hash_keep_if, 0);
7193  rb_define_method(rb_cHash, "select", rb_hash_select, 0);
7194  rb_define_method(rb_cHash, "select!", rb_hash_select_bang, 0);
7195  rb_define_method(rb_cHash, "filter", rb_hash_select, 0);
7196  rb_define_method(rb_cHash, "filter!", rb_hash_select_bang, 0);
7197  rb_define_method(rb_cHash, "reject", rb_hash_reject, 0);
7198  rb_define_method(rb_cHash, "reject!", rb_hash_reject_bang, 0);
7199  rb_define_method(rb_cHash, "slice", rb_hash_slice, -1);
7200  rb_define_method(rb_cHash, "except", rb_hash_except, -1);
7201  rb_define_method(rb_cHash, "clear", rb_hash_clear, 0);
7202  rb_define_method(rb_cHash, "invert", rb_hash_invert, 0);
7203  rb_define_method(rb_cHash, "update", rb_hash_update, -1);
7204  rb_define_method(rb_cHash, "replace", rb_hash_replace, 1);
7205  rb_define_method(rb_cHash, "merge!", rb_hash_update, -1);
7206  rb_define_method(rb_cHash, "merge", rb_hash_merge, -1);
7207  rb_define_method(rb_cHash, "assoc", rb_hash_assoc, 1);
7208  rb_define_method(rb_cHash, "rassoc", rb_hash_rassoc, 1);
7209  rb_define_method(rb_cHash, "flatten", rb_hash_flatten, -1);
7210  rb_define_method(rb_cHash, "compact", rb_hash_compact, 0);
7211  rb_define_method(rb_cHash, "compact!", rb_hash_compact_bang, 0);
7212 
7213  rb_define_method(rb_cHash, "include?", rb_hash_has_key, 1);
7214  rb_define_method(rb_cHash, "member?", rb_hash_has_key, 1);
7215  rb_define_method(rb_cHash, "has_key?", rb_hash_has_key, 1);
7216  rb_define_method(rb_cHash, "has_value?", rb_hash_has_value, 1);
7217  rb_define_method(rb_cHash, "key?", rb_hash_has_key, 1);
7218  rb_define_method(rb_cHash, "value?", rb_hash_has_value, 1);
7219 
7220  rb_define_method(rb_cHash, "compare_by_identity", rb_hash_compare_by_id, 0);
7221  rb_define_method(rb_cHash, "compare_by_identity?", rb_hash_compare_by_id_p, 0);
7222 
7223  rb_define_method(rb_cHash, "any?", rb_hash_any_p, -1);
7224  rb_define_method(rb_cHash, "dig", rb_hash_dig, -1);
7225 
7226  rb_define_method(rb_cHash, "<=", rb_hash_le, 1);
7227  rb_define_method(rb_cHash, "<", rb_hash_lt, 1);
7228  rb_define_method(rb_cHash, ">=", rb_hash_ge, 1);
7229  rb_define_method(rb_cHash, ">", rb_hash_gt, 1);
7230 
7231  rb_define_method(rb_cHash, "deconstruct_keys", rb_hash_deconstruct_keys, 1);
7232 
7233  rb_define_singleton_method(rb_cHash, "ruby2_keywords_hash?", rb_hash_s_ruby2_keywords_hash_p, 1);
7234  rb_define_singleton_method(rb_cHash, "ruby2_keywords_hash", rb_hash_s_ruby2_keywords_hash, 1);
7235 
7236  /* Document-class: ENV
7237  *
7238  * ENV is a hash-like accessor for environment variables.
7239  *
7240  * === Interaction with the Operating System
7241  *
7242  * The ENV object interacts with the operating system's environment variables:
7243  *
7244  * - When you get the value for a name in ENV, the value is retrieved from among the current environment variables.
7245  * - When you create or set a name-value pair in ENV, the name and value are immediately set in the environment variables.
7246  * - When you delete a name-value pair in ENV, it is immediately deleted from the environment variables.
7247  *
7248  * === Names and Values
7249  *
7250  * Generally, a name or value is a String.
7251  *
7252  * ==== Valid Names and Values
7253  *
7254  * Each name or value must be one of the following:
7255  *
7256  * - A String.
7257  * - An object that responds to \#to_str by returning a String, in which case that String will be used as the name or value.
7258  *
7259  * ==== Invalid Names and Values
7260  *
7261  * A new name:
7262  *
7263  * - May not be the empty string:
7264  * ENV[''] = '0'
7265  * # Raises Errno::EINVAL (Invalid argument - ruby_setenv())
7266  *
7267  * - May not contain character <code>"="</code>:
7268  * ENV['='] = '0'
7269  * # Raises Errno::EINVAL (Invalid argument - ruby_setenv(=))
7270  *
7271  * A new name or value:
7272  *
7273  * - May not be a non-String that does not respond to \#to_str:
7274  *
7275  * ENV['foo'] = Object.new
7276  * # Raises TypeError (no implicit conversion of Object into String)
7277  * ENV[Object.new] = '0'
7278  * # Raises TypeError (no implicit conversion of Object into String)
7279  *
7280  * - May not contain the NUL character <code>"\0"</code>:
7281  *
7282  * ENV['foo'] = "\0"
7283  * # Raises ArgumentError (bad environment variable value: contains null byte)
7284  * ENV["\0"] == '0'
7285  * # Raises ArgumentError (bad environment variable name: contains null byte)
7286  *
7287  * - May not have an ASCII-incompatible encoding such as UTF-16LE or ISO-2022-JP:
7288  *
7289  * ENV['foo'] = '0'.force_encoding(Encoding::ISO_2022_JP)
7290  * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: ISO-2022-JP)
7291  * ENV["foo".force_encoding(Encoding::ISO_2022_JP)] = '0'
7292  * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: ISO-2022-JP)
7293  *
7294  * === About Ordering
7295  *
7296  * ENV enumerates its name/value pairs in the order found
7297  * in the operating system's environment variables.
7298  * Therefore the ordering of ENV content is OS-dependent, and may be indeterminate.
7299  *
7300  * This will be seen in:
7301  * - A Hash returned by an ENV method.
7302  * - An Enumerator returned by an ENV method.
7303  * - An Array returned by ENV.keys, ENV.values, or ENV.to_a.
7304  * - The String returned by ENV.inspect.
7305  * - The Array returned by ENV.shift.
7306  * - The name returned by ENV.key.
7307  *
7308  * === About the Examples
7309  * Some methods in ENV return ENV itself. Typically, there are many environment variables.
7310  * It's not useful to display a large ENV in the examples here,
7311  * so most example snippets begin by resetting the contents of ENV:
7312  * - ENV.replace replaces ENV with a new collection of entries.
7313  * - ENV.clear empties ENV.
7314  *
7315  * == What's Here
7316  *
7317  * First, what's elsewhere. \Class \ENV:
7318  *
7319  * - Inherits from {class Object}[Object.html#class-Object-label-What-27s+Here].
7320  * - Extends {module Enumerable}[Enumerable.html#module-Enumerable-label-What-27s+Here],
7321  *
7322  * Here, class \ENV provides methods that are useful for:
7323  *
7324  * - {Querying}[#class-ENV-label-Methods+for+Querying]
7325  * - {Assigning}[#class-ENV-label-Methods+for+Assigning]
7326  * - {Deleting}[#class-ENV-label-Methods+for+Deleting]
7327  * - {Iterating}[#class-ENV-label-Methods+for+Iterating]
7328  * - {Converting}[#class-ENV-label-Methods+for+Converting]
7329  * - {And more ....}[#class-ENV-label-More+Methods]
7330  *
7331  * === Methods for Querying
7332  *
7333  * - ::[]:: Returns the value for the given environment variable name if it exists:
7334  * - ::empty?:: Returns whether \ENV is empty.
7335  * - ::has_value?, ::value?:: Returns whether the given value is in \ENV.
7336  * - ::include?, ::has_key?, ::key?, ::member?:: Returns whether the given name
7337  is in \ENV.
7338  * - ::key:: Returns the name of the first entry with the given value.
7339  * - ::size, ::length:: Returns the number of entries.
7340  * - ::value?:: Returns whether any entry has the given value.
7341  *
7342  * === Methods for Assigning
7343  *
7344  * - ::[]=, ::store:: Creates, updates, or deletes the named environment variable.
7345  * - ::clear:: Removes every environment variable; returns \ENV:
7346  * - ::update, ::merge!:: Adds to \ENV each key/value pair in the given hash.
7347  * - ::replace:: Replaces the entire content of the \ENV
7348  * with the name/value pairs in the given hash.
7349  *
7350  * === Methods for Deleting
7351  *
7352  * - ::delete:: Deletes the named environment variable name if it exists.
7353  * - ::delete_if:: Deletes entries selected by the block.
7354  * - ::keep_if:: Deletes entries not selected by the block.
7355  * - ::reject!:: Similar to #delete_if, but returns +nil+ if no change was made.
7356  * - ::select!, ::filter!:: Deletes entries selected by the block.
7357  * - ::shift:: Removes and returns the first entry.
7358  *
7359  * === Methods for Iterating
7360  *
7361  * - ::each, ::each_pair:: Calls the block with each name/value pair.
7362  * - ::each_key:: Calls the block with each name.
7363  * - ::each_value:: Calls the block with each value.
7364  *
7365  * === Methods for Converting
7366  *
7367  * - ::assoc:: Returns a 2-element array containing the name and value
7368  * of the named environment variable if it exists:
7369  * - ::clone:: Returns \ENV (and issues a warning).
7370  * - ::except:: Returns a hash of all name/value pairs except those given.
7371  * - ::fetch:: Returns the value for the given name.
7372  * - ::inspect:: Returns the contents of \ENV as a string.
7373  * - ::invert:: Returns a hash whose keys are the ENV values,
7374  and whose values are the corresponding ENV names.
7375  * - ::keys:: Returns an array of all names.
7376  * - ::rassoc:: Returns the name and value of the first found entry
7377  * that has the given value.
7378  * - ::reject:: Returns a hash of those entries not rejected by the block.
7379  * - ::select, ::filter:: Returns a hash of name/value pairs selected by the block.
7380  * - ::slice:: Returns a hash of the given names and their corresponding values.
7381  * - ::to_a:: Returns the entries as an array of 2-element Arrays.
7382  * - ::to_h:: Returns a hash of entries selected by the block.
7383  * - ::to_hash:: Returns a hash of all entries.
7384  * - ::to_s:: Returns the string <tt>'ENV'</tt>.
7385  * - ::values:: Returns all values as an array.
7386  * - ::values_at:: Returns an array of the values for the given name.
7387  *
7388  * === More Methods
7389  *
7390  * - ::dup:: Raises an exception.
7391  * - ::freeze:: Raises an exception.
7392  * - ::rehash:: Returns +nil+, without modifying \ENV.
7393  *
7394  */
7395 
7396  /*
7397  * Hack to get RDoc to regard ENV as a class:
7398  * envtbl = rb_define_class("ENV", rb_cObject);
7399  */
7400  origenviron = environ;
7401  envtbl = TypedData_Wrap_Struct(rb_cObject, &env_data_type, NULL);
7403  FL_SET_RAW(envtbl, RUBY_FL_SHAREABLE);
7404 
7405 
7406  rb_define_singleton_method(envtbl, "[]", rb_f_getenv, 1);
7407  rb_define_singleton_method(envtbl, "fetch", env_fetch, -1);
7408  rb_define_singleton_method(envtbl, "[]=", env_aset_m, 2);
7409  rb_define_singleton_method(envtbl, "store", env_aset_m, 2);
7410  rb_define_singleton_method(envtbl, "each", env_each_pair, 0);
7411  rb_define_singleton_method(envtbl, "each_pair", env_each_pair, 0);
7412  rb_define_singleton_method(envtbl, "each_key", env_each_key, 0);
7413  rb_define_singleton_method(envtbl, "each_value", env_each_value, 0);
7414  rb_define_singleton_method(envtbl, "delete", env_delete_m, 1);
7415  rb_define_singleton_method(envtbl, "delete_if", env_delete_if, 0);
7416  rb_define_singleton_method(envtbl, "keep_if", env_keep_if, 0);
7417  rb_define_singleton_method(envtbl, "slice", env_slice, -1);
7418  rb_define_singleton_method(envtbl, "except", env_except, -1);
7419  rb_define_singleton_method(envtbl, "clear", env_clear, 0);
7420  rb_define_singleton_method(envtbl, "reject", env_reject, 0);
7421  rb_define_singleton_method(envtbl, "reject!", env_reject_bang, 0);
7422  rb_define_singleton_method(envtbl, "select", env_select, 0);
7423  rb_define_singleton_method(envtbl, "select!", env_select_bang, 0);
7424  rb_define_singleton_method(envtbl, "filter", env_select, 0);
7425  rb_define_singleton_method(envtbl, "filter!", env_select_bang, 0);
7426  rb_define_singleton_method(envtbl, "shift", env_shift, 0);
7427  rb_define_singleton_method(envtbl, "freeze", env_freeze, 0);
7428  rb_define_singleton_method(envtbl, "invert", env_invert, 0);
7429  rb_define_singleton_method(envtbl, "replace", env_replace, 1);
7430  rb_define_singleton_method(envtbl, "update", env_update, 1);
7431  rb_define_singleton_method(envtbl, "merge!", env_update, 1);
7432  rb_define_singleton_method(envtbl, "inspect", env_inspect, 0);
7433  rb_define_singleton_method(envtbl, "rehash", env_none, 0);
7434  rb_define_singleton_method(envtbl, "to_a", env_to_a, 0);
7435  rb_define_singleton_method(envtbl, "to_s", env_to_s, 0);
7436  rb_define_singleton_method(envtbl, "key", env_key, 1);
7437  rb_define_singleton_method(envtbl, "size", env_size, 0);
7438  rb_define_singleton_method(envtbl, "length", env_size, 0);
7439  rb_define_singleton_method(envtbl, "empty?", env_empty_p, 0);
7440  rb_define_singleton_method(envtbl, "keys", env_f_keys, 0);
7441  rb_define_singleton_method(envtbl, "values", env_f_values, 0);
7442  rb_define_singleton_method(envtbl, "values_at", env_values_at, -1);
7443  rb_define_singleton_method(envtbl, "include?", env_has_key, 1);
7444  rb_define_singleton_method(envtbl, "member?", env_has_key, 1);
7445  rb_define_singleton_method(envtbl, "has_key?", env_has_key, 1);
7446  rb_define_singleton_method(envtbl, "has_value?", env_has_value, 1);
7447  rb_define_singleton_method(envtbl, "key?", env_has_key, 1);
7448  rb_define_singleton_method(envtbl, "value?", env_has_value, 1);
7449  rb_define_singleton_method(envtbl, "to_hash", env_f_to_hash, 0);
7450  rb_define_singleton_method(envtbl, "to_h", env_to_h, 0);
7451  rb_define_singleton_method(envtbl, "assoc", env_assoc, 1);
7452  rb_define_singleton_method(envtbl, "rassoc", env_rassoc, 1);
7453  rb_define_singleton_method(envtbl, "clone", env_clone, -1);
7454  rb_define_singleton_method(envtbl, "dup", env_dup, 0);
7455 
7456  VALUE envtbl_class = rb_singleton_class(envtbl);
7457  rb_undef_method(envtbl_class, "initialize");
7458  rb_undef_method(envtbl_class, "initialize_clone");
7459  rb_undef_method(envtbl_class, "initialize_copy");
7460  rb_undef_method(envtbl_class, "initialize_dup");
7461 
7462  /*
7463  * ENV is a Hash-like accessor for environment variables.
7464  *
7465  * See ENV (the class) for more details.
7466  */
7467  rb_define_global_const("ENV", envtbl);
7468 
7469  /* for callcc */
7470  ruby_register_rollback_func_for_ensure(hash_foreach_ensure, hash_foreach_ensure_rollback);
7471 
7472  HASH_ASSERT(sizeof(ar_hint_t) * RHASH_AR_TABLE_MAX_SIZE == sizeof(VALUE));
7473 }
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
Definition: cxxanyargs.hpp:685
double rb_float_value(VALUE num)
Extracts its double value from an instance of rb_cFloat.
Definition: numeric.c:6424
static bool RB_FL_ANY_RAW(VALUE obj, VALUE flags)
This is an implenentation detail of RB_FL_ANY().
Definition: fl_type.h:556
static bool RB_OBJ_FROZEN(VALUE obj)
Checks if an object is frozen.
Definition: fl_type.h:927
@ RUBY_FL_SHAREABLE
This flag has something to do with Ractor.
Definition: fl_type.h:298
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition: class.c:1043
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition: class.c:837
void rb_extend_object(VALUE obj, VALUE module)
Extend the object with the module.
Definition: eval.c:1583
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition: class.c:2068
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition: class.c:2116
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition: class.c:1938
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition: class.c:2406
void rb_define_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a method.
Definition: class.c:1914
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition: eval.c:854
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition: string.h:1738
#define TYPE(_)
Old name of rb_type.
Definition: value_type.h:107
#define NEWOBJ_OF
Old name of RB_NEWOBJ_OF.
Definition: newobj.h:61
#define FL_EXIVAR
Old name of RUBY_FL_EXIVAR.
Definition: fl_type.h:67
#define NUM2LL
Old name of RB_NUM2LL.
Definition: long_long.h:34
#define REALLOC_N
Old name of RB_REALLOC_N.
Definition: memory.h:397
#define T_STRING
Old name of RUBY_T_STRING.
Definition: value_type.h:78
#define xfree
Old name of ruby_xfree.
Definition: xmalloc.h:58
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition: long.h:48
#define T_NIL
Old name of RUBY_T_NIL.
Definition: value_type.h:72
#define T_FLOAT
Old name of RUBY_T_FLOAT.
Definition: value_type.h:64
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
Definition: value_type.h:57
#define rb_str_buf_new2
Old name of rb_str_buf_new_cstr.
Definition: string.h:1743
#define T_FIXNUM
Old name of RUBY_T_FIXNUM.
Definition: value_type.h:63
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition: assume.h:31
#define T_DATA
Old name of RUBY_T_DATA.
Definition: value_type.h:60
#define CLASS_OF
Old name of rb_class_of.
Definition: globals.h:203
#define LONG2FIX
Old name of RB_INT2FIX.
Definition: long.h:49
#define FIX2INT
Old name of RB_FIX2INT.
Definition: int.h:41
#define STATIC_SYM_P
Old name of RB_STATIC_SYM_P.
#define T_TRUE
Old name of RUBY_T_TRUE.
Definition: value_type.h:81
#define T_HASH
Old name of RUBY_T_HASH.
Definition: value_type.h:65
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition: memory.h:393
#define FL_TEST_RAW
Old name of RB_FL_TEST_RAW.
Definition: fl_type.h:140
#define rb_usascii_str_new2
Old name of rb_usascii_str_new_cstr.
Definition: string.h:1744
#define T_FALSE
Old name of RUBY_T_FALSE.
Definition: value_type.h:61
#define FIXNUM_MIN
Old name of RUBY_FIXNUM_MIN.
Definition: fixnum.h:27
#define FLONUM_P
Old name of RB_FLONUM_P.
#define Qtrue
Old name of RUBY_Qtrue.
#define ST2FIX
Old name of RB_ST2FIX.
Definition: st_data_t.h:33
#define FIXNUM_MAX
Old name of RUBY_FIXNUM_MAX.
Definition: fixnum.h:26
#define NUM2INT
Old name of RB_NUM2INT.
Definition: int.h:44
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
Definition: long.h:46
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition: memory.h:399
#define FL_WB_PROTECTED
Old name of RUBY_FL_WB_PROTECTED.
Definition: fl_type.h:59
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition: value_type.h:80
#define FL_TEST
Old name of RB_FL_TEST.
Definition: fl_type.h:139
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition: long.h:51
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define OBJ_WB_UNPROTECT
Old name of RB_OBJ_WB_UNPROTECT.
Definition: rgengc.h:238
#define rb_ary_new2
Old name of rb_ary_new_capa.
Definition: array.h:651
#define FL_SET_RAW
Old name of RB_FL_SET_RAW.
Definition: fl_type.h:138
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition: memory.h:400
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition: value_type.h:88
void rb_raise(VALUE exc, const char *fmt,...)
Exception entry point.
Definition: error.c:3025
void rb_bug(const char *fmt,...)
Interpreter panic switch.
Definition: error.c:802
void rb_syserr_fail_str(int e, VALUE mesg)
Identical to rb_syserr_fail(), except it takes the message in Ruby's String instead of C's.
Definition: error.c:3143
VALUE rb_eTypeError
TypeError exception.
Definition: error.c:1099
VALUE rb_eRuntimeError
RuntimeError exception.
Definition: error.c:1097
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports always regardless of runtime -W flag.
Definition: error.c:418
VALUE rb_eArgError
ArgumentError exception.
Definition: error.c:1100
VALUE rb_ensure(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*e_proc)(VALUE), VALUE data2)
An equivalent to ensure clause.
Definition: eval.c:983
void rb_sys_fail_str(VALUE mesg)
Identical to rb_sys_fail(), except it takes the message in Ruby's String instead of C's.
Definition: error.c:3155
VALUE rb_mKernel
Kernel module.
Definition: object.c:49
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
Definition: object.c:553
VALUE rb_mEnumerable
Enumerable module.
Definition: enum.c:27
int rb_eql(VALUE lhs, VALUE rhs)
Checks for equality of the passed objects, in terms of Object#eql?.
Definition: object.c:133
VALUE rb_cHash
Hash class.
Definition: hash.c:92
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition: object.c:188
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition: object.c:564
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition: object.c:120
VALUE rb_obj_freeze(VALUE obj)
Just calls rb_obj_freeze_inline() inside.
Definition: object.c:1161
VALUE rb_cString
String class.
Definition: string.c:80
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition: object.c:2998
#define RB_OBJ_WRITTEN(old, oldv, young)
Identical to RB_OBJ_WRITE(), except it doesn't write any values, but only a WB declaration.
Definition: rgengc.h:232
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition: rgengc.h:220
rb_encoding * rb_locale_encoding(void)
Queries the encoding that represents the current locale.
Definition: encoding.c:1573
void rb_enc_copy(VALUE dst, VALUE src)
Destructively copies the encoding of the latter object to that of former one.
Definition: encoding.c:1192
static bool rb_enc_asciicompat(rb_encoding *enc)
Queries if the passed encoding is in some sense compatible with ASCII.
Definition: encoding.h:782
rb_encoding * rb_utf8_encoding(void)
Queries the encoding that represents UTF-8.
Definition: encoding.c:1527
rb_encoding * rb_enc_get(VALUE obj)
Identical to rb_enc_get_index(), except the return type.
Definition: encoding.c:1072
static const char * rb_enc_name(rb_encoding *enc)
Queries the (canonical) name of the passed encoding.
Definition: encoding.h:433
VALUE rb_external_str_new_with_enc(const char *ptr, long len, rb_encoding *enc)
Identical to rb_external_str_new(), except it additionally takes an encoding.
Definition: string.c:1188
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition: vm_eval.c:1102
VALUE rb_funcallv(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcall(), except it takes the method arguments as a C array.
Definition: vm_eval.c:1061
VALUE rb_ary_delete_at(VALUE ary, long pos)
Destructively removes an element which resides at the specific index of the passed array.
Definition: array.c:3941
VALUE rb_ary_cat(VALUE ary, const VALUE *train, long len)
Destructively appends multiple elements at the end of the array.
Definition: array.c:1321
VALUE rb_check_array_type(VALUE obj)
Try converting an object to its array representation using its to_ary method, if any.
Definition: array.c:989
VALUE rb_ary_new(void)
Allocates a new, empty array.
Definition: array.c:750
VALUE rb_ary_new_capa(long capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
Definition: array.c:744
VALUE rb_ary_tmp_new(long capa)
Allocates a "temporary" array.
Definition: array.c:847
VALUE rb_ary_clear(VALUE ary)
Destructively removes everything form an array.
Definition: array.c:4465
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
Definition: array.c:1308
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
Definition: array.c:976
int rb_integer_pack(VALUE val, void *words, size_t numwords, size_t wordsize, size_t nails, int flags)
Exports an integer into a buffer.
Definition: bignum.c:3559
#define INTEGER_PACK_NATIVE_BYTE_ORDER
Means either INTEGER_PACK_MSBYTE_FIRST or INTEGER_PACK_LSBYTE_FIRST, depending on the host processor'...
Definition: bignum.h:546
#define RETURN_SIZED_ENUMERATOR(obj, argc, argv, size_fn)
This roughly resembles return enum_for(__callee__) unless block_given?.
Definition: enumerator.h:206
#define UNLIMITED_ARGUMENTS
This macro is used in conjunction with rb_check_arity().
Definition: error.h:35
#define rb_check_frozen
Just another name of rb_check_frozen.
Definition: error.h:278
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition: error.h:294
VALUE rb_hash_size(VALUE hash)
Identical to RHASH_SIZE(), except it returns the size in Ruby's integer instead of C's.
Definition: hash.c:2975
void rb_hash_bulk_insert(long argc, const VALUE *argv, VALUE hash)
Inserts a list of key-value pairs into a hash table at once.
Definition: hash.c:4753
void rb_hash_foreach(VALUE hash, int(*func)(VALUE key, VALUE val, VALUE arg), VALUE arg)
Iterates over a hash.
VALUE rb_check_hash_type(VALUE obj)
Try converting an object to its hash representation using its to_hash method, if any.
Definition: hash.c:1896
VALUE rb_hash_lookup2(VALUE hash, VALUE key, VALUE def)
Identical to rb_hash_lookup(), except you can specify what to return on misshits.
Definition: hash.c:2095
VALUE rb_hash_freeze(VALUE obj)
Just another name of rb_obj_freeze.
Definition: hash.c:87
VALUE rb_hash_update_func(VALUE newkey, VALUE oldkey, VALUE value)
Type of callback functions to pass to rb_hash_update_by().
Definition: hash.h:258
#define st_foreach_safe
Just another name of rb_st_foreach_safe.
Definition: hash.h:51
int rb_env_path_tainted(void)
Definition: hash.c:5038
VALUE rb_hash_delete(VALUE hash, VALUE key)
Deletes the passed key from the passed hash table, if any.
Definition: hash.c:2362
VALUE rb_hash_fetch(VALUE hash, VALUE key)
Identical to rb_hash_lookup(), except it yields the (implicitly) passed block instead of returning RU...
Definition: hash.c:2173
VALUE rb_hash_delete_if(VALUE hash)
Deletes each entry for which the block returns a truthy value.
Definition: hash.c:2525
VALUE rb_hash_update_by(VALUE hash1, VALUE hash2, rb_hash_update_func *func)
Destructively merges two hash tables into one.
Definition: hash.c:4010
VALUE rb_hash_aref(VALUE hash, VALUE key)
Queries the given key in the given hash table.
Definition: hash.c:2082
VALUE rb_hash_aset(VALUE hash, VALUE key, VALUE val)
Inserts or replaces ("upsert"s) the objects into the given hash table.
Definition: hash.c:2903
VALUE rb_env_clear(void)
Destructively removes every environment variables of the running process.
Definition: hash.c:5888
VALUE rb_hash_lookup(VALUE hash, VALUE key)
Identical to rb_hash_aref(), except it always returns RUBY_Qnil for misshits.
Definition: hash.c:2108
VALUE rb_hash_dup(VALUE hash)
Duplicates a hash.
Definition: hash.c:1585
VALUE rb_hash(VALUE obj)
Calculates a message authentication code of the passed object.
Definition: hash.c:227
VALUE rb_hash_clear(VALUE hash)
Swipes everything out of the passed hash table.
Definition: hash.c:2829
VALUE rb_hash_new(void)
Creates a new, empty hash object.
Definition: hash.c:1529
VALUE rb_obj_id(VALUE obj)
Finds or creates an integer primary key of the given object.
Definition: gc.c:4447
VALUE rb_proc_lambda_p(VALUE recv)
Queries if the given object is a lambda.
Definition: proc.c:293
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition: proc.c:848
VALUE rb_proc_call_with_block(VALUE recv, int argc, const VALUE *argv, VALUE proc)
Identical to rb_proc_call(), except you can additionally pass another proc object,...
Definition: proc.c:1027
VALUE rb_protect(VALUE(*func)(VALUE args), VALUE args, int *state)
Protects a function call from potential global escapes from the function.
int rb_proc_arity(VALUE recv)
Queries the number of mandatory arguments of the given Proc.
Definition: proc.c:1134
VALUE rb_obj_is_proc(VALUE recv)
Queries if the given object is a proc.
Definition: proc.c:175
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
Definition: string.h:973
#define rb_hash_end(h)
Just another name of st_hash_end.
Definition: string.h:976
VALUE rb_utf8_str_new(const char *ptr, long len)
Identical to rb_str_new(), except it generates a string of "UTF-8" encoding.
Definition: string.c:932
int rb_str_hash_cmp(VALUE str1, VALUE str2)
Compares two strings.
Definition: string.c:3526
VALUE rb_str_ellipsize(VALUE str, long len)
Shortens str and adds three dots, an ellipsis, if it is longer than len characters.
Definition: string.c:10802
st_index_t rb_memhash(const void *ptr, long len)
This is a universal hash function.
Definition: random.c:1720
VALUE rb_str_buf_cat(VALUE, const char *, long)
Just another name of rb_str_cat.
VALUE rb_str_new_frozen(VALUE str)
Creates a frozen copy of the string, if necessary.
Definition: string.c:1356
st_index_t rb_str_hash(VALUE str)
Calculates a hash value of a string.
Definition: string.c:3516
VALUE rb_str_buf_cat2(VALUE, const char *)
Just another name of rb_str_cat_cstr.
VALUE rb_str_buf_append(VALUE dst, VALUE src)
Identical to rb_str_cat_cstr(), except it takes Ruby's string instead of C's.
Definition: string.c:3302
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition: random.c:1714
VALUE rb_str_buf_cat_ascii(VALUE dst, const char *src)
Identical to rb_str_cat_cstr(), except it additionally assumes the source string be a NUL terminated ...
Definition: string.c:3278
VALUE rb_str_new(const char *ptr, long len)
Allocates an instance of rb_cString.
Definition: string.c:918
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition: string.c:2659
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
VALUE rb_exec_recursive_paired(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h)
Identical to rb_exec_recursive(), except it checks for the recursion on the ordered pair of { g,...
VALUE rb_exec_recursive_outer(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
Identical to rb_exec_recursive(), except it calls f for outermost recursion only.
VALUE rb_ivar_get(VALUE obj, ID name)
Identical to rb_iv_get(), except it accepts the name as an ID instead of a C string.
Definition: variable.c:1285
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition: vm_method.c:2765
int rb_method_basic_definition_p(VALUE klass, ID mid)
Well...
Definition: vm_method.c:2643
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition: symbol.h:276
void rb_define_global_const(const char *name, VALUE val)
Identical to rb_define_const(), except it defines that of "global", i.e.
Definition: variable.c:3265
void ruby_setenv(const char *key, const char *val)
Sets an environment variable.
Definition: hash.c:5134
char * ruby_strdup(const char *str)
This is our own version of strdup(3) that uses ruby_xmalloc() instead of system malloc (benefits our ...
Definition: util.c:536
void ruby_unsetenv(const char *key)
Deletes the passed environment variable, if any.
Definition: hash.c:5316
VALUE rb_sprintf(const char *fmt,...)
Ruby's extended sprintf(3).
Definition: sprintf.c:1201
#define RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg)
Shim for block function parameters.
Definition: iterator.h:58
VALUE rb_yield_values(int n,...)
Identical to rb_yield(), except it takes variadic number of parameters and pass them to the block.
Definition: vm_eval.c:1369
VALUE rb_yield_values2(int n, const VALUE *argv)
Identical to rb_yield_values(), except it takes the parameters as a C array instead of variadic argum...
Definition: vm_eval.c:1391
VALUE rb_yield(VALUE val)
Yields the block.
Definition: vm_eval.c:1357
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition: memory.h:161
VALUE type(ANYARGS)
ANYARGS-ed function type.
Definition: cxxanyargs.hpp:56
int st_foreach(st_table *q, int_type *w, st_data_t e)
Iteration over the given table.
Definition: cxxanyargs.hpp:432
int st_foreach_check(st_table *q, int_type *w, st_data_t e, st_data_t)
Iteration over the given table.
Definition: cxxanyargs.hpp:450
void rb_copy_generic_ivar(VALUE clone, VALUE obj)
Copies the list of instance variables.
Definition: variable.c:1719
#define RARRAY_LEN
Just another name of rb_array_len.
Definition: rarray.h:68
#define RARRAY_AREF(a, i)
Definition: rarray.h:588
#define RARRAY_PTR_USE_TRANSIENT(ary, ptr_name, expr)
Identical to RARRAY_PTR_USE, except the pointer can be a transient one.
Definition: rarray.h:533
static VALUE RBASIC_CLASS(VALUE obj)
Queries the class of an object.
Definition: rbasic.h:152
#define RBASIC(obj)
Convenient casting macro.
Definition: rbasic.h:40
#define RGENGC_WB_PROTECTED_HASH
This is a compile-time flag to enable/disable write barrier for struct RHash.
Definition: rgengc.h:85
#define RHASH_SET_IFNONE(h, ifnone)
Destructively updates the default value of the hash.
Definition: rhash.h:105
VALUE rb_hash_set_ifnone(VALUE hash, VALUE ifnone)
This is the implementation detail of RHASH_SET_IFNONE.
Definition: hash.c:99
#define RHASH_IFNONE(h)
Definition: rhash.h:72
#define RHASH_ITER_LEV(h)
Definition: rhash.h:59
#define RHASH_SIZE(h)
Queries the size of the hash.
Definition: rhash.h:82
struct st_table * rb_hash_tbl(VALUE hash, const char *file, int line)
This is the implementation detail of RHASH_TBL.
Definition: hash.c:1615
size_t rb_hash_size_num(VALUE hash)
This is the implementation detail of RHASH_SIZE.
Definition: hash.c:2981
#define RHASH_EMPTY_P(h)
Checks if the hash is empty.
Definition: rhash.h:92
#define SafeStringValue(v)
Definition: rstring.h:104
static char * RSTRING_PTR(VALUE str)
Queries the contents pointer of the string.
Definition: rstring.h:497
#define RSTRING_GETMEM(str, ptrvar, lenvar)
Convenient macro to obtain the contents and length at once.
Definition: rstring.h:573
static long RSTRING_LEN(VALUE str)
Queries the length of the string.
Definition: rstring.h:483
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
Definition: rtypeddata.h:441
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition: variable.c:309
@ RUBY_SPECIAL_SHIFT
Least significant 8 bits are reserved.
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
Definition: stdarg.h:35
VALUE flags
Per-object flags.
Definition: rbasic.h:77
Definition: hash.h:43
Definition: hash.c:912
This is the struct that holds necessary info for a struct.
Definition: rtypeddata.h:190
Definition: st.h:79
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
Definition: value.h:63
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition: value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition: value.h:40
static void Check_Type(VALUE v, enum ruby_value_type t)
Identical to RB_TYPE_P(), except it raises exceptions on predication failure.
Definition: value_type.h:432
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition: value_type.h:375
void * ruby_xmalloc(size_t size)
Allocates a storage instance.
Definition: gc.c:13704
void ruby_xfree(void *ptr)
Deallocates a storage instance.
Definition: gc.c:11775