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