Ruby 4.1.0dev (2026-03-06 revision d5d144c149d3beabbfb262e3994f60552469181b)
hash.c (d5d144c149d3beabbfb262e3994f60552469181b)
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
495static VALUE
496hash_verify_(VALUE hash, const char *file, int line)
497{
498 HASH_ASSERT(RB_TYPE_P(hash, T_HASH));
499
500 if (RHASH_AR_TABLE_P(hash)) {
501 unsigned i, n = 0, bound = RHASH_AR_TABLE_BOUND(hash);
502
503 for (i=0; i<bound; i++) {
504 st_data_t k, v;
505 if (!ar_cleared_entry(hash, i)) {
506 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
507 k = pair->key;
508 v = pair->val;
509 HASH_ASSERT(!UNDEF_P(k));
510 HASH_ASSERT(!UNDEF_P(v));
511 n++;
512 }
513 }
514 if (n != RHASH_AR_TABLE_SIZE(hash)) {
515 rb_bug("n:%u, RHASH_AR_TABLE_SIZE:%u", n, RHASH_AR_TABLE_SIZE(hash));
516 }
517 }
518 else {
519 HASH_ASSERT(RHASH_ST_TABLE(hash) != NULL);
520 HASH_ASSERT(RHASH_AR_TABLE_SIZE_RAW(hash) == 0);
521 HASH_ASSERT(RHASH_AR_TABLE_BOUND_RAW(hash) == 0);
522 }
523
524 return hash;
525}
526
527#else
528#define hash_verify(h) ((void)0)
529#endif
530
531static inline int
532RHASH_TABLE_EMPTY_P(VALUE hash)
533{
534 return RHASH_SIZE(hash) == 0;
535}
536
537#define RHASH_SET_ST_FLAG(h) FL_SET_RAW(h, RHASH_ST_TABLE_FLAG)
538#define RHASH_UNSET_ST_FLAG(h) FL_UNSET_RAW(h, RHASH_ST_TABLE_FLAG)
539
540static void
541hash_st_table_init(VALUE hash, const struct st_hash_type *type, st_index_t size)
542{
543 st_init_existing_table_with_size(RHASH_ST_TABLE(hash), type, size);
544 RHASH_SET_ST_FLAG(hash);
545}
546
547void
548rb_hash_st_table_set(VALUE hash, st_table *st)
549{
550 HASH_ASSERT(st != NULL);
551 RHASH_SET_ST_FLAG(hash);
552
553 *RHASH_ST_TABLE(hash) = *st;
554}
555
556static inline void
557RHASH_AR_TABLE_BOUND_SET(VALUE h, st_index_t n)
558{
559 HASH_ASSERT(RHASH_AR_TABLE_P(h));
560 HASH_ASSERT(n <= RHASH_AR_TABLE_MAX_BOUND);
561
562 RBASIC(h)->flags &= ~RHASH_AR_TABLE_BOUND_MASK;
563 RBASIC(h)->flags |= n << RHASH_AR_TABLE_BOUND_SHIFT;
564}
565
566static inline void
567RHASH_AR_TABLE_SIZE_SET(VALUE h, st_index_t n)
568{
569 HASH_ASSERT(RHASH_AR_TABLE_P(h));
570 HASH_ASSERT(n <= RHASH_AR_TABLE_MAX_SIZE);
571
572 RBASIC(h)->flags &= ~RHASH_AR_TABLE_SIZE_MASK;
573 RBASIC(h)->flags |= n << RHASH_AR_TABLE_SIZE_SHIFT;
574}
575
576static inline void
577HASH_AR_TABLE_SIZE_ADD(VALUE h, st_index_t n)
578{
579 HASH_ASSERT(RHASH_AR_TABLE_P(h));
580
581 RHASH_AR_TABLE_SIZE_SET(h, RHASH_AR_TABLE_SIZE(h) + n);
582
583 hash_verify(h);
584}
585
586#define RHASH_AR_TABLE_SIZE_INC(h) HASH_AR_TABLE_SIZE_ADD(h, 1)
587
588static inline void
589RHASH_AR_TABLE_SIZE_DEC(VALUE h)
590{
591 HASH_ASSERT(RHASH_AR_TABLE_P(h));
592 int new_size = RHASH_AR_TABLE_SIZE(h) - 1;
593
594 if (new_size != 0) {
595 RHASH_AR_TABLE_SIZE_SET(h, new_size);
596 }
597 else {
598 RHASH_AR_TABLE_SIZE_SET(h, 0);
599 RHASH_AR_TABLE_BOUND_SET(h, 0);
600 }
601 hash_verify(h);
602}
603
604static inline void
605RHASH_AR_TABLE_CLEAR(VALUE h)
606{
607 RBASIC(h)->flags &= ~RHASH_AR_TABLE_SIZE_MASK;
608 RBASIC(h)->flags &= ~RHASH_AR_TABLE_BOUND_MASK;
609
610 memset(RHASH_AR_TABLE(h), 0, sizeof(ar_table));
611}
612
613NOINLINE(static int ar_equal(VALUE x, VALUE y));
614
615static int
616ar_equal(VALUE x, VALUE y)
617{
618 return rb_any_cmp(x, y) == 0;
619}
620
621static unsigned
622ar_find_entry_hint(VALUE hash, ar_hint_t hint, st_data_t key)
623{
624 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
625 const ar_hint_t *hints = RHASH_AR_TABLE(hash)->ar_hint.ary;
626
627 /* if table is NULL, then bound also should be 0 */
628
629 for (i = 0; i < bound; i++) {
630 if (hints[i] == hint) {
631 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
632 if (ar_equal(key, pair->key)) {
633 RB_DEBUG_COUNTER_INC(artable_hint_hit);
634 return i;
635 }
636 else {
637#if 0
638 static int pid;
639 static char fname[256];
640 static FILE *fp;
641
642 if (pid != getpid()) {
643 snprintf(fname, sizeof(fname), "/tmp/ruby-armiss.%d", pid = getpid());
644 if ((fp = fopen(fname, "w")) == NULL) rb_bug("fopen");
645 }
646
647 st_hash_t h1 = ar_do_hash(key);
648 st_hash_t h2 = ar_do_hash(pair->key);
649
650 fprintf(fp, "miss: hash_eq:%d hints[%d]:%02x hint:%02x\n"
651 " key :%016lx %s\n"
652 " pair->key:%016lx %s\n",
653 h1 == h2, i, hints[i], hint,
654 h1, rb_obj_info(key), h2, rb_obj_info(pair->key));
655#endif
656 RB_DEBUG_COUNTER_INC(artable_hint_miss);
657 }
658 }
659 }
660 RB_DEBUG_COUNTER_INC(artable_hint_notfound);
661 return RHASH_AR_TABLE_MAX_BOUND;
662}
663
664static unsigned
665ar_find_entry(VALUE hash, st_hash_t hash_value, st_data_t key)
666{
667 ar_hint_t hint = ar_do_hash_hint(hash_value);
668 return ar_find_entry_hint(hash, hint, key);
669}
670
671static inline void
672hash_ar_free_and_clear_table(VALUE hash)
673{
674 RHASH_AR_TABLE_CLEAR(hash);
675
676 HASH_ASSERT(RHASH_AR_TABLE_SIZE(hash) == 0);
677 HASH_ASSERT(RHASH_AR_TABLE_BOUND(hash) == 0);
678}
679
680void rb_st_add_direct_with_hash(st_table *tab, st_data_t key, st_data_t value, st_hash_t hash); // st.c
681
682enum ar_each_key_type {
683 ar_each_key_copy,
684 ar_each_key_cmp,
685 ar_each_key_insert,
686};
687
688static inline int
689ar_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)
690{
691 for (int i = 0; i < max; i++) {
692 ar_table_pair *pair = &ar->pairs[i];
693
694 switch (type) {
695 case ar_each_key_copy:
696 dst_keys[i] = pair->key;
697 break;
698 case ar_each_key_cmp:
699 if (dst_keys[i] != pair->key) return 1;
700 break;
701 case ar_each_key_insert:
702 if (UNDEF_P(pair->key)) continue; // deleted entry
703 rb_st_add_direct_with_hash(new_tab, pair->key, pair->val, hashes[i]);
704 break;
705 }
706 }
707
708 return 0;
709}
710
711static st_table *
712ar_force_convert_table(VALUE hash, const char *file, int line)
713{
714 if (RHASH_ST_TABLE_P(hash)) {
715 return RHASH_ST_TABLE(hash);
716 }
717 else {
718 ar_table *ar = RHASH_AR_TABLE(hash);
719 st_hash_t hashes[RHASH_AR_TABLE_MAX_SIZE];
720 unsigned int bound, size;
721
722 // prepare hash values
723 do {
724 st_data_t keys[RHASH_AR_TABLE_MAX_SIZE];
725 bound = RHASH_AR_TABLE_BOUND(hash);
726 size = RHASH_AR_TABLE_SIZE(hash);
727 ar_each_key(ar, bound, ar_each_key_copy, keys, NULL, NULL);
728
729 for (unsigned int i = 0; i < bound; i++) {
730 // do_hash calls #hash method and it can modify hash object
731 hashes[i] = UNDEF_P(keys[i]) ? 0 : ar_do_hash(keys[i]);
732 }
733
734 // check if modified
735 if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) return RHASH_ST_TABLE(hash);
736 if (UNLIKELY(RHASH_AR_TABLE_BOUND(hash) != bound)) continue;
737 if (UNLIKELY(ar_each_key(ar, bound, ar_each_key_cmp, keys, NULL, NULL))) continue;
738 } while (0);
739
740 // make st
741 st_table tab;
742 st_table *new_tab = &tab;
743 st_init_existing_table_with_size(new_tab, &objhash, size);
744 ar_each_key(ar, bound, ar_each_key_insert, NULL, new_tab, hashes);
745 hash_ar_free_and_clear_table(hash);
746 RHASH_ST_TABLE_SET(hash, new_tab);
747 return RHASH_ST_TABLE(hash);
748 }
749}
750
751static int
752ar_compact_table(VALUE hash)
753{
754 const unsigned bound = RHASH_AR_TABLE_BOUND(hash);
755 const unsigned size = RHASH_AR_TABLE_SIZE(hash);
756
757 if (size == bound) {
758 return size;
759 }
760 else {
761 unsigned i, j=0;
762 ar_table_pair *pairs = RHASH_AR_TABLE(hash)->pairs;
763
764 for (i=0; i<bound; i++) {
765 if (ar_cleared_entry(hash, i)) {
766 if (j <= i) j = i+1;
767 for (; j<bound; j++) {
768 if (!ar_cleared_entry(hash, j)) {
769 pairs[i] = pairs[j];
770 ar_hint_set_hint(hash, i, (st_hash_t)ar_hint(hash, j));
771 ar_clear_entry(hash, j);
772 j++;
773 goto found;
774 }
775 }
776 /* non-empty is not found */
777 goto done;
778 found:;
779 }
780 }
781 done:
782 HASH_ASSERT(i<=bound);
783
784 RHASH_AR_TABLE_BOUND_SET(hash, size);
785 hash_verify(hash);
786 return size;
787 }
788}
789
790static int
791ar_add_direct_with_hash(VALUE hash, st_data_t key, st_data_t val, st_hash_t hash_value)
792{
793 unsigned bin = RHASH_AR_TABLE_BOUND(hash);
794
795 if (RHASH_AR_TABLE_SIZE(hash) >= RHASH_AR_TABLE_MAX_SIZE) {
796 return 1;
797 }
798 else {
799 if (UNLIKELY(bin >= RHASH_AR_TABLE_MAX_BOUND)) {
800 bin = ar_compact_table(hash);
801 }
802 HASH_ASSERT(bin < RHASH_AR_TABLE_MAX_BOUND);
803
804 ar_set_entry(hash, bin, key, val, hash_value);
805 RHASH_AR_TABLE_BOUND_SET(hash, bin+1);
806 RHASH_AR_TABLE_SIZE_INC(hash);
807 return 0;
808 }
809}
810
811static void
812ensure_ar_table(VALUE hash)
813{
814 if (!RHASH_AR_TABLE_P(hash)) {
815 rb_raise(rb_eRuntimeError, "hash representation was changed during iteration");
816 }
817}
818
819static int
820ar_general_foreach(VALUE hash, st_foreach_check_callback_func *func, st_update_callback_func *replace, st_data_t arg)
821{
822 if (RHASH_AR_TABLE_SIZE(hash) > 0) {
823 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
824
825 for (i = 0; i < bound; i++) {
826 if (ar_cleared_entry(hash, i)) continue;
827
828 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
829 st_data_t key = (st_data_t)pair->key;
830 st_data_t val = (st_data_t)pair->val;
831 enum st_retval retval = (*func)(key, val, arg, 0);
832 ensure_ar_table(hash);
833 /* pair may be not valid here because of theap */
834
835 switch (retval) {
836 case ST_CONTINUE:
837 break;
838 case ST_CHECK:
839 case ST_STOP:
840 return 0;
841 case ST_REPLACE:
842 if (replace) {
843 (*replace)(&key, &val, arg, TRUE);
844
845 // Pair should not have moved
846 HASH_ASSERT(pair == RHASH_AR_TABLE_REF(hash, i));
847
848 pair->key = (VALUE)key;
849 pair->val = (VALUE)val;
850 }
851 break;
852 case ST_DELETE:
853 ar_clear_entry(hash, i);
854 RHASH_AR_TABLE_SIZE_DEC(hash);
855 break;
856 }
857 }
858 }
859 return 0;
860}
861
862static int
863ar_foreach_with_replace(VALUE hash, st_foreach_check_callback_func *func, st_update_callback_func *replace, st_data_t arg)
864{
865 return ar_general_foreach(hash, func, replace, arg);
866}
867
868struct functor {
869 st_foreach_callback_func *func;
870 st_data_t arg;
871};
872
873static int
874apply_functor(st_data_t k, st_data_t v, st_data_t d, int _)
875{
876 const struct functor *f = (void *)d;
877 return f->func(k, v, f->arg);
878}
879
880static int
881ar_foreach(VALUE hash, st_foreach_callback_func *func, st_data_t arg)
882{
883 const struct functor f = { func, arg };
884 return ar_general_foreach(hash, apply_functor, NULL, (st_data_t)&f);
885}
886
887static int
888ar_foreach_check(VALUE hash, st_foreach_check_callback_func *func, st_data_t arg,
889 st_data_t never)
890{
891 if (RHASH_AR_TABLE_SIZE(hash) > 0) {
892 unsigned i, ret = 0, bound = RHASH_AR_TABLE_BOUND(hash);
893 enum st_retval retval;
894 st_data_t key;
895 ar_table_pair *pair;
896 ar_hint_t hint;
897
898 for (i = 0; i < bound; i++) {
899 if (ar_cleared_entry(hash, i)) continue;
900
901 pair = RHASH_AR_TABLE_REF(hash, i);
902 key = pair->key;
903 hint = ar_hint(hash, i);
904
905 retval = (*func)(key, pair->val, arg, 0);
906 ensure_ar_table(hash);
907 hash_verify(hash);
908
909 switch (retval) {
910 case ST_CHECK: {
911 pair = RHASH_AR_TABLE_REF(hash, i);
912 if (pair->key == never) break;
913 ret = ar_find_entry_hint(hash, hint, key);
914 if (ret == RHASH_AR_TABLE_MAX_BOUND) {
915 (*func)(0, 0, arg, 1);
916 return 2;
917 }
918 }
919 case ST_CONTINUE:
920 break;
921 case ST_STOP:
922 case ST_REPLACE:
923 return 0;
924 case ST_DELETE: {
925 if (!ar_cleared_entry(hash, i)) {
926 ar_clear_entry(hash, i);
927 RHASH_AR_TABLE_SIZE_DEC(hash);
928 }
929 break;
930 }
931 }
932 }
933 }
934 return 0;
935}
936
937static int
938ar_update(VALUE hash, st_data_t key,
939 st_update_callback_func *func, st_data_t arg)
940{
941 int retval, existing;
942 unsigned bin = RHASH_AR_TABLE_MAX_BOUND;
943 st_data_t value = 0, old_key;
944 st_hash_t hash_value = ar_do_hash(key);
945
946 if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) {
947 // `#hash` changes ar_table -> st_table
948 return -1;
949 }
950
951 if (RHASH_AR_TABLE_SIZE(hash) > 0) {
952 bin = ar_find_entry(hash, hash_value, key);
953 existing = (bin != RHASH_AR_TABLE_MAX_BOUND) ? TRUE : FALSE;
954 }
955 else {
956 existing = FALSE;
957 }
958
959 if (existing) {
960 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, bin);
961 key = pair->key;
962 value = pair->val;
963 }
964 old_key = key;
965 retval = (*func)(&key, &value, arg, existing);
966 /* pair can be invalid here because of theap */
967 ensure_ar_table(hash);
968
969 switch (retval) {
970 case ST_CONTINUE:
971 if (!existing) {
972 if (ar_add_direct_with_hash(hash, key, value, hash_value)) {
973 return -1;
974 }
975 }
976 else {
977 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, bin);
978 if (old_key != key) {
979 pair->key = key;
980 }
981 pair->val = value;
982 }
983 break;
984 case ST_DELETE:
985 if (existing) {
986 ar_clear_entry(hash, bin);
987 RHASH_AR_TABLE_SIZE_DEC(hash);
988 }
989 break;
990 }
991 return existing;
992}
993
994static int
995ar_insert(VALUE hash, st_data_t key, st_data_t value)
996{
997 unsigned bin = RHASH_AR_TABLE_BOUND(hash);
998 st_hash_t hash_value = ar_do_hash(key);
999
1000 if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) {
1001 // `#hash` changes ar_table -> st_table
1002 return -1;
1003 }
1004
1005 bin = ar_find_entry(hash, hash_value, key);
1006 if (bin == RHASH_AR_TABLE_MAX_BOUND) {
1007 if (RHASH_AR_TABLE_SIZE(hash) >= RHASH_AR_TABLE_MAX_SIZE) {
1008 return -1;
1009 }
1010 else if (bin >= RHASH_AR_TABLE_MAX_BOUND) {
1011 bin = ar_compact_table(hash);
1012 }
1013 HASH_ASSERT(bin < RHASH_AR_TABLE_MAX_BOUND);
1014
1015 ar_set_entry(hash, bin, key, value, hash_value);
1016 RHASH_AR_TABLE_BOUND_SET(hash, bin+1);
1017 RHASH_AR_TABLE_SIZE_INC(hash);
1018 return 0;
1019 }
1020 else {
1021 RHASH_AR_TABLE_REF(hash, bin)->val = value;
1022 return 1;
1023 }
1024}
1025
1026static int
1027ar_lookup(VALUE hash, st_data_t key, st_data_t *value)
1028{
1029 if (RHASH_AR_TABLE_SIZE(hash) == 0) {
1030 return 0;
1031 }
1032 else {
1033 st_hash_t hash_value = ar_do_hash(key);
1034 if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) {
1035 // `#hash` changes ar_table -> st_table
1036 return st_lookup(RHASH_ST_TABLE(hash), key, value);
1037 }
1038 unsigned bin = ar_find_entry(hash, hash_value, key);
1039
1040 if (bin == RHASH_AR_TABLE_MAX_BOUND) {
1041 return 0;
1042 }
1043 else {
1044 HASH_ASSERT(bin < RHASH_AR_TABLE_MAX_BOUND);
1045 if (value != NULL) {
1046 *value = RHASH_AR_TABLE_REF(hash, bin)->val;
1047 }
1048 return 1;
1049 }
1050 }
1051}
1052
1053static int
1054ar_delete(VALUE hash, st_data_t *key, st_data_t *value)
1055{
1056 unsigned bin;
1057 st_hash_t hash_value = ar_do_hash(*key);
1058
1059 if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) {
1060 // `#hash` changes ar_table -> st_table
1061 return st_delete(RHASH_ST_TABLE(hash), key, value);
1062 }
1063
1064 bin = ar_find_entry(hash, hash_value, *key);
1065
1066 if (bin == RHASH_AR_TABLE_MAX_BOUND) {
1067 if (value != 0) *value = 0;
1068 return 0;
1069 }
1070 else {
1071 if (value != 0) {
1072 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, bin);
1073 *value = pair->val;
1074 }
1075 ar_clear_entry(hash, bin);
1076 RHASH_AR_TABLE_SIZE_DEC(hash);
1077 return 1;
1078 }
1079}
1080
1081static int
1082ar_shift(VALUE hash, st_data_t *key, st_data_t *value)
1083{
1084 if (RHASH_AR_TABLE_SIZE(hash) > 0) {
1085 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
1086
1087 for (i = 0; i < bound; i++) {
1088 if (!ar_cleared_entry(hash, i)) {
1089 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
1090 if (value != 0) *value = pair->val;
1091 *key = pair->key;
1092 ar_clear_entry(hash, i);
1093 RHASH_AR_TABLE_SIZE_DEC(hash);
1094 return 1;
1095 }
1096 }
1097 }
1098 if (value != NULL) *value = 0;
1099 return 0;
1100}
1101
1102static long
1103ar_keys(VALUE hash, st_data_t *keys, st_index_t size)
1104{
1105 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
1106 st_data_t *keys_start = keys, *keys_end = keys + size;
1107
1108 for (i = 0; i < bound; i++) {
1109 if (keys == keys_end) {
1110 break;
1111 }
1112 else {
1113 if (!ar_cleared_entry(hash, i)) {
1114 *keys++ = RHASH_AR_TABLE_REF(hash, i)->key;
1115 }
1116 }
1117 }
1118
1119 return keys - keys_start;
1120}
1121
1122static long
1123ar_values(VALUE hash, st_data_t *values, st_index_t size)
1124{
1125 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
1126 st_data_t *values_start = values, *values_end = values + size;
1127
1128 for (i = 0; i < bound; i++) {
1129 if (values == values_end) {
1130 break;
1131 }
1132 else {
1133 if (!ar_cleared_entry(hash, i)) {
1134 *values++ = RHASH_AR_TABLE_REF(hash, i)->val;
1135 }
1136 }
1137 }
1138
1139 return values - values_start;
1140}
1141
1142static ar_table*
1143ar_copy(VALUE hash1, VALUE hash2)
1144{
1145 ar_table *old_tab = RHASH_AR_TABLE(hash2);
1146 ar_table *new_tab = RHASH_AR_TABLE(hash1);
1147
1148 *new_tab = *old_tab;
1149 RHASH_AR_TABLE(hash1)->ar_hint.word = RHASH_AR_TABLE(hash2)->ar_hint.word;
1150 RHASH_AR_TABLE_BOUND_SET(hash1, RHASH_AR_TABLE_BOUND(hash2));
1151 RHASH_AR_TABLE_SIZE_SET(hash1, RHASH_AR_TABLE_SIZE(hash2));
1152
1153 rb_gc_writebarrier_remember(hash1);
1154
1155 return new_tab;
1156}
1157
1158static void
1159ar_clear(VALUE hash)
1160{
1161 if (RHASH_AR_TABLE(hash) != NULL) {
1162 RHASH_AR_TABLE_SIZE_SET(hash, 0);
1163 RHASH_AR_TABLE_BOUND_SET(hash, 0);
1164 }
1165 else {
1166 HASH_ASSERT(RHASH_AR_TABLE_SIZE(hash) == 0);
1167 HASH_ASSERT(RHASH_AR_TABLE_BOUND(hash) == 0);
1168 }
1169}
1170
1171static void
1172hash_st_free(VALUE hash)
1173{
1174 HASH_ASSERT(RHASH_ST_TABLE_P(hash));
1175
1176 rb_st_free_embedded_table(RHASH_ST_TABLE(hash));
1177}
1178
1179static void
1180hash_st_free_and_clear_table(VALUE hash)
1181{
1182 hash_st_free(hash);
1183 RHASH_ST_CLEAR(hash);
1184}
1185
1186void
1187rb_hash_free(VALUE hash)
1188{
1189 if (RHASH_ST_TABLE_P(hash)) {
1190 hash_st_free(hash);
1191 }
1192}
1193
1194typedef int st_foreach_func(st_data_t, st_data_t, st_data_t);
1195
1197 st_table *tbl;
1198 st_foreach_func *func;
1199 st_data_t arg;
1200};
1201
1202static int
1203foreach_safe_i(st_data_t key, st_data_t value, st_data_t args, int error)
1204{
1205 int status;
1206 struct foreach_safe_arg *arg = (void *)args;
1207
1208 if (error) return ST_STOP;
1209 status = (*arg->func)(key, value, arg->arg);
1210 if (status == ST_CONTINUE) {
1211 return ST_CHECK;
1212 }
1213 return status;
1214}
1215
1216void
1217st_foreach_safe(st_table *table, st_foreach_func *func, st_data_t a)
1218{
1219 struct foreach_safe_arg arg;
1220
1221 arg.tbl = table;
1222 arg.func = (st_foreach_func *)func;
1223 arg.arg = a;
1224 if (st_foreach_check(table, foreach_safe_i, (st_data_t)&arg, 0)) {
1225 rb_raise(rb_eRuntimeError, "hash modified during iteration");
1226 }
1227}
1228
1229typedef int rb_foreach_func(VALUE, VALUE, VALUE);
1230
1232 VALUE hash;
1233 rb_foreach_func *func;
1234 VALUE arg;
1235};
1236
1237static int
1238hash_iter_status_check(int status)
1239{
1240 switch (status) {
1241 case ST_DELETE:
1242 return ST_DELETE;
1243 case ST_CONTINUE:
1244 break;
1245 case ST_STOP:
1246 return ST_STOP;
1247 }
1248
1249 return ST_CHECK;
1250}
1251
1252static int
1253hash_ar_foreach_iter(st_data_t key, st_data_t value, st_data_t argp, int error)
1254{
1255 struct hash_foreach_arg *arg = (struct hash_foreach_arg *)argp;
1256
1257 if (error) return ST_STOP;
1258
1259 int status = (*arg->func)((VALUE)key, (VALUE)value, arg->arg);
1260
1261 return hash_iter_status_check(status);
1262}
1263
1264static int
1265hash_foreach_iter(st_data_t key, st_data_t value, st_data_t argp, int error)
1266{
1267 struct hash_foreach_arg *arg = (struct hash_foreach_arg *)argp;
1268
1269 if (error) return ST_STOP;
1270
1271 int status = (*arg->func)((VALUE)key, (VALUE)value, arg->arg);
1272
1273 return hash_iter_status_check(status);
1274}
1275
1276static unsigned long
1277iter_lev_in_ivar(VALUE hash)
1278{
1279 VALUE levval = rb_ivar_get(hash, id_hash_iter_lev);
1280 HASH_ASSERT(FIXNUM_P(levval));
1281 long lev = FIX2LONG(levval);
1282 HASH_ASSERT(lev >= 0);
1283 return (unsigned long)lev;
1284}
1285
1286void rb_ivar_set_internal(VALUE obj, ID id, VALUE val);
1287
1288static void
1289iter_lev_in_ivar_set(VALUE hash, unsigned long lev)
1290{
1291 HASH_ASSERT(lev >= RHASH_LEV_MAX);
1292 HASH_ASSERT(POSFIXABLE(lev)); /* POSFIXABLE means fitting to long */
1293 rb_ivar_set_internal(hash, id_hash_iter_lev, LONG2FIX((long)lev));
1294}
1295
1296static inline unsigned long
1297iter_lev_in_flags(VALUE hash)
1298{
1299 return (unsigned long)((RBASIC(hash)->flags >> RHASH_LEV_SHIFT) & RHASH_LEV_MAX);
1300}
1301
1302static inline void
1303iter_lev_in_flags_set(VALUE hash, unsigned long lev)
1304{
1305 HASH_ASSERT(lev <= RHASH_LEV_MAX);
1306 RBASIC(hash)->flags = ((RBASIC(hash)->flags & ~RHASH_LEV_MASK) | ((VALUE)lev << RHASH_LEV_SHIFT));
1307}
1308
1309static inline bool
1310hash_iterating_p(VALUE hash)
1311{
1312 return iter_lev_in_flags(hash) > 0;
1313}
1314
1315static void
1316hash_iter_lev_inc(VALUE hash)
1317{
1318 unsigned long lev = iter_lev_in_flags(hash);
1319 if (lev == RHASH_LEV_MAX) {
1320 lev = iter_lev_in_ivar(hash) + 1;
1321 if (!POSFIXABLE(lev)) { /* paranoiac check */
1322 rb_raise(rb_eRuntimeError, "too much nested iterations");
1323 }
1324 }
1325 else {
1326 lev += 1;
1327 iter_lev_in_flags_set(hash, lev);
1328 if (lev < RHASH_LEV_MAX) return;
1329 }
1330 iter_lev_in_ivar_set(hash, lev);
1331}
1332
1333static void
1334hash_iter_lev_dec(VALUE hash)
1335{
1336 unsigned long lev = iter_lev_in_flags(hash);
1337 if (lev == RHASH_LEV_MAX) {
1338 lev = iter_lev_in_ivar(hash);
1339 if (lev > RHASH_LEV_MAX) {
1340 iter_lev_in_ivar_set(hash, lev-1);
1341 return;
1342 }
1343 rb_attr_delete(hash, id_hash_iter_lev);
1344 }
1345 else if (lev == 0) {
1346 rb_raise(rb_eRuntimeError, "iteration level underflow");
1347 }
1348 iter_lev_in_flags_set(hash, lev - 1);
1349}
1350
1351static VALUE
1352hash_foreach_ensure(VALUE hash)
1353{
1354 hash_iter_lev_dec(hash);
1355 return 0;
1356}
1357
1358/* This does not manage iteration level */
1359int
1360rb_hash_stlike_foreach(VALUE hash, st_foreach_callback_func *func, st_data_t arg)
1361{
1362 if (RHASH_AR_TABLE_P(hash)) {
1363 return ar_foreach(hash, func, arg);
1364 }
1365 else {
1366 return st_foreach(RHASH_ST_TABLE(hash), func, arg);
1367 }
1368}
1369
1370/* This does not manage iteration level */
1371int
1372rb_hash_stlike_foreach_with_replace(VALUE hash, st_foreach_check_callback_func *func, st_update_callback_func *replace, st_data_t arg)
1373{
1374 if (RHASH_AR_TABLE_P(hash)) {
1375 return ar_foreach_with_replace(hash, func, replace, arg);
1376 }
1377 else {
1378 return st_foreach_with_replace(RHASH_ST_TABLE(hash), func, replace, arg);
1379 }
1380}
1381
1382static VALUE
1383hash_foreach_call(VALUE arg)
1384{
1385 VALUE hash = ((struct hash_foreach_arg *)arg)->hash;
1386 int ret = 0;
1387 if (RHASH_AR_TABLE_P(hash)) {
1388 ret = ar_foreach_check(hash, hash_ar_foreach_iter,
1389 (st_data_t)arg, (st_data_t)Qundef);
1390 }
1391 else if (RHASH_ST_TABLE_P(hash)) {
1392 ret = st_foreach_check(RHASH_ST_TABLE(hash), hash_foreach_iter,
1393 (st_data_t)arg, (st_data_t)Qundef);
1394 }
1395 if (ret) {
1396 rb_raise(rb_eRuntimeError, "ret: %d, hash modified during iteration", ret);
1397 }
1398 return Qnil;
1399}
1400
1401void
1402rb_hash_foreach(VALUE hash, rb_foreach_func *func, VALUE farg)
1403{
1404 struct hash_foreach_arg arg;
1405
1406 if (RHASH_TABLE_EMPTY_P(hash))
1407 return;
1408 arg.hash = hash;
1409 arg.func = (rb_foreach_func *)func;
1410 arg.arg = farg;
1411 if (RB_OBJ_FROZEN(hash)) {
1412 hash_foreach_call((VALUE)&arg);
1413 }
1414 else {
1415 hash_iter_lev_inc(hash);
1416 rb_ensure(hash_foreach_call, (VALUE)&arg, hash_foreach_ensure, hash);
1417 }
1418 hash_verify(hash);
1419}
1420
1421void rb_st_compact_table(st_table *tab);
1422
1423static void
1424compact_after_delete(VALUE hash)
1425{
1426 if (!hash_iterating_p(hash) && RHASH_ST_TABLE_P(hash)) {
1427 rb_st_compact_table(RHASH_ST_TABLE(hash));
1428 }
1429}
1430
1431static VALUE
1432hash_alloc_flags(VALUE klass, VALUE flags, VALUE ifnone, bool st)
1433{
1435 const size_t size = sizeof(struct RHash) + (st ? sizeof(st_table) : sizeof(ar_table));
1436
1437 NEWOBJ_OF(hash, struct RHash, klass, T_HASH | wb | flags, size, 0);
1438
1439 RHASH_SET_IFNONE((VALUE)hash, ifnone);
1440
1441 return (VALUE)hash;
1442}
1443
1444static VALUE
1445hash_alloc(VALUE klass)
1446{
1447 /* Allocate to be able to fit both st_table and ar_table. */
1448 return hash_alloc_flags(klass, 0, Qnil, sizeof(st_table) > sizeof(ar_table));
1449}
1450
1451static VALUE
1452empty_hash_alloc(VALUE klass)
1453{
1454 RUBY_DTRACE_CREATE_HOOK(HASH, 0);
1455
1456 return hash_alloc(klass);
1457}
1458
1459VALUE
1460rb_hash_new(void)
1461{
1462 return hash_alloc(rb_cHash);
1463}
1464
1465static VALUE
1466copy_compare_by_id(VALUE hash, VALUE basis)
1467{
1468 if (rb_hash_compare_by_id_p(basis)) {
1469 return rb_hash_compare_by_id(hash);
1470 }
1471 return hash;
1472}
1473
1474VALUE
1475rb_hash_new_with_size(st_index_t size)
1476{
1477 bool st = size > RHASH_AR_TABLE_MAX_SIZE;
1478 VALUE ret = hash_alloc_flags(rb_cHash, 0, Qnil, st);
1479
1480 if (st) {
1481 hash_st_table_init(ret, &objhash, size);
1482 }
1483
1484 return ret;
1485}
1486
1487VALUE
1488rb_hash_new_capa(long capa)
1489{
1490 return rb_hash_new_with_size((st_index_t)capa);
1491}
1492
1493static VALUE
1494hash_copy(VALUE ret, VALUE hash)
1495{
1496 if (rb_hash_compare_by_id_p(hash)) {
1497 rb_gc_register_pinning_obj(ret);
1498 }
1499
1500 if (RHASH_AR_TABLE_P(hash)) {
1501 if (RHASH_AR_TABLE_P(ret)) {
1502 ar_copy(ret, hash);
1503 }
1504 else {
1505 st_table *tab = RHASH_ST_TABLE(ret);
1506 st_init_existing_table_with_size(tab, &objhash, RHASH_AR_TABLE_SIZE(hash));
1507
1508 int bound = RHASH_AR_TABLE_BOUND(hash);
1509 for (int i = 0; i < bound; i++) {
1510 if (ar_cleared_entry(hash, i)) continue;
1511
1512 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
1513 st_add_direct(tab, pair->key, pair->val);
1514 RB_OBJ_WRITTEN(ret, Qundef, pair->key);
1515 RB_OBJ_WRITTEN(ret, Qundef, pair->val);
1516 }
1517 }
1518 }
1519 else {
1520 HASH_ASSERT(sizeof(st_table) <= sizeof(ar_table));
1521
1522 RHASH_SET_ST_FLAG(ret);
1523 st_replace(RHASH_ST_TABLE(ret), RHASH_ST_TABLE(hash));
1524
1525 rb_gc_writebarrier_remember(ret);
1526 }
1527 return ret;
1528}
1529
1530static VALUE
1531hash_dup_with_compare_by_id(VALUE hash)
1532{
1533 VALUE dup = hash_alloc_flags(rb_cHash, 0, Qnil, RHASH_ST_TABLE_P(hash));
1534 if (RHASH_ST_TABLE_P(hash)) {
1535 RHASH_SET_ST_FLAG(dup);
1536 }
1537 else {
1538 RHASH_UNSET_ST_FLAG(dup);
1539 }
1540
1541 return hash_copy(dup, hash);
1542}
1543
1544static VALUE
1545hash_dup(VALUE hash, VALUE klass, VALUE flags)
1546{
1547 return hash_copy(hash_alloc_flags(klass, flags, RHASH_IFNONE(hash), !RHASH_EMPTY_P(hash) && RHASH_ST_TABLE_P(hash)),
1548 hash);
1549}
1550
1551VALUE
1552rb_hash_dup(VALUE hash)
1553{
1554 const VALUE flags = RBASIC(hash)->flags;
1555 VALUE ret = hash_dup(hash, rb_obj_class(hash), flags & RHASH_PROC_DEFAULT);
1556
1557 rb_copy_generic_ivar(ret, hash);
1558
1559 return ret;
1560}
1561
1562VALUE
1563rb_hash_resurrect(VALUE hash)
1564{
1565 VALUE ret = hash_dup(hash, rb_cHash, 0);
1566 return ret;
1567}
1568
1569static void
1570rb_hash_modify_check(VALUE hash)
1571{
1572 rb_check_frozen(hash);
1573}
1574
1575struct st_table *
1576rb_hash_tbl_raw(VALUE hash, const char *file, int line)
1577{
1578 return ar_force_convert_table(hash, file, line);
1579}
1580
1581struct st_table *
1582rb_hash_tbl(VALUE hash, const char *file, int line)
1583{
1584 OBJ_WB_UNPROTECT(hash);
1585 return rb_hash_tbl_raw(hash, file, line);
1586}
1587
1588static void
1589rb_hash_modify(VALUE hash)
1590{
1591 rb_hash_modify_check(hash);
1592}
1593
1594NORETURN(static void no_new_key(void));
1595static void
1596no_new_key(void)
1597{
1598 rb_raise(rb_eRuntimeError, "can't add a new key into hash during iteration");
1599}
1600
1602 VALUE hash;
1603 st_data_t arg;
1604};
1605
1606#define NOINSERT_UPDATE_CALLBACK(func) \
1607static int \
1608func##_noinsert(st_data_t *key, st_data_t *val, st_data_t arg, int existing) \
1609{ \
1610 if (!existing) no_new_key(); \
1611 return func(key, val, (struct update_arg *)arg, existing); \
1612} \
1613 \
1614static int \
1615func##_insert(st_data_t *key, st_data_t *val, st_data_t arg, int existing) \
1616{ \
1617 return func(key, val, (struct update_arg *)arg, existing); \
1618}
1619
1621 st_data_t arg;
1622 st_update_callback_func *func;
1623 VALUE hash;
1624 VALUE key;
1625 VALUE value;
1626};
1627
1628typedef int (*tbl_update_func)(st_data_t *, st_data_t *, st_data_t, int);
1629
1630int
1631rb_hash_stlike_update(VALUE hash, st_data_t key, st_update_callback_func *func, st_data_t arg)
1632{
1633 if (RHASH_AR_TABLE_P(hash)) {
1634 int result = ar_update(hash, key, func, arg);
1635 if (result == -1) {
1636 ar_force_convert_table(hash, __FILE__, __LINE__);
1637 }
1638 else {
1639 return result;
1640 }
1641 }
1642
1643 return st_update(RHASH_ST_TABLE(hash), key, func, arg);
1644}
1645
1646static int
1647tbl_update_modify(st_data_t *key, st_data_t *val, st_data_t arg, int existing)
1648{
1649 struct update_arg *p = (struct update_arg *)arg;
1650 st_data_t old_key = *key;
1651 st_data_t old_value = *val;
1652 VALUE hash = p->hash;
1653 int ret = (p->func)(key, val, arg, existing);
1654 switch (ret) {
1655 default:
1656 break;
1657 case ST_CONTINUE:
1658 if (!existing || *key != old_key || *val != old_value) {
1659 rb_hash_modify(hash);
1660 p->key = *key;
1661 p->value = *val;
1662 }
1663 break;
1664 case ST_DELETE:
1665 if (existing)
1666 rb_hash_modify(hash);
1667 break;
1668 }
1669
1670 return ret;
1671}
1672
1673static int
1674tbl_update(VALUE hash, VALUE key, tbl_update_func func, st_data_t optional_arg)
1675{
1676 struct update_arg arg = {
1677 .arg = optional_arg,
1678 .func = func,
1679 .hash = hash,
1680 .key = key,
1681 .value = 0
1682 };
1683
1684 int ret = rb_hash_stlike_update(hash, key, tbl_update_modify, (st_data_t)&arg);
1685
1686 /* write barrier */
1687 RB_OBJ_WRITTEN(hash, Qundef, arg.key);
1688 if (arg.value) RB_OBJ_WRITTEN(hash, Qundef, arg.value);
1689
1690 return ret;
1691}
1692
1693#define UPDATE_CALLBACK(iter_p, func) ((iter_p) ? func##_noinsert : func##_insert)
1694
1695#define RHASH_UPDATE_ITER(h, iter_p, key, func, a) do { \
1696 tbl_update((h), (key), UPDATE_CALLBACK(iter_p, func), (st_data_t)(a)); \
1697} while (0)
1698
1699#define RHASH_UPDATE(hash, key, func, arg) \
1700 RHASH_UPDATE_ITER(hash, hash_iterating_p(hash), key, func, arg)
1701
1702static void
1703set_proc_default(VALUE hash, VALUE proc)
1704{
1705 if (rb_proc_lambda_p(proc)) {
1706 int n = rb_proc_arity(proc);
1707
1708 if (n != 2 && (n >= 0 || n < -3)) {
1709 if (n < 0) n = -n-1;
1710 rb_raise(rb_eTypeError, "default_proc takes two arguments (2 for %d)", n);
1711 }
1712 }
1713
1714 FL_SET_RAW(hash, RHASH_PROC_DEFAULT);
1715 RHASH_SET_IFNONE(hash, proc);
1716}
1717
1718static VALUE
1719rb_hash_init(rb_execution_context_t *ec, VALUE hash, VALUE capa_value, VALUE ifnone_unset, VALUE ifnone, VALUE block)
1720{
1721 rb_hash_modify(hash);
1722
1723 if (capa_value != INT2FIX(0)) {
1724 long capa = NUM2LONG(capa_value);
1725 if (capa > 0 && RHASH_SIZE(hash) == 0 && RHASH_AR_TABLE_P(hash)) {
1726 hash_st_table_init(hash, &objhash, capa);
1727 }
1728 }
1729
1730 if (!NIL_P(block)) {
1731 if (ifnone_unset != Qtrue) {
1732 rb_check_arity(1, 0, 0);
1733 }
1734 else {
1735 SET_PROC_DEFAULT(hash, block);
1736 }
1737 }
1738 else {
1739 RHASH_SET_IFNONE(hash, ifnone_unset == Qtrue ? Qnil : ifnone);
1740 }
1741
1742 hash_verify(hash);
1743 return hash;
1744}
1745
1746static VALUE rb_hash_to_a(VALUE hash);
1747
1748/*
1749 * call-seq:
1750 * Hash[] -> new_empty_hash
1751 * Hash[other_hash] -> new_hash
1752 * Hash[ [*2_element_arrays] ] -> new_hash
1753 * Hash[*objects] -> new_hash
1754 *
1755 * Returns a new \Hash object populated with the given objects, if any.
1756 * See Hash::new.
1757 *
1758 * With no argument given, returns a new empty hash.
1759 *
1760 * With a single argument +other_hash+ given that is a hash,
1761 * returns a new hash initialized with the entries from that hash
1762 * (but not with its +default+ or +default_proc+):
1763 *
1764 * h = {foo: 0, bar: 1, baz: 2}
1765 * Hash[h] # => {foo: 0, bar: 1, baz: 2}
1766 *
1767 * With a single argument +2_element_arrays+ given that is an array of 2-element arrays,
1768 * returns a new hash wherein each given 2-element array forms a
1769 * key-value entry:
1770 *
1771 * Hash[ [ [:foo, 0], [:bar, 1] ] ] # => {foo: 0, bar: 1}
1772 *
1773 * With an even number of arguments +objects+ given,
1774 * returns a new hash wherein each successive pair of arguments
1775 * is a key-value entry:
1776 *
1777 * Hash[:foo, 0, :bar, 1] # => {foo: 0, bar: 1}
1778 *
1779 * Raises ArgumentError if the argument list does not conform to any
1780 * of the above.
1781 *
1782 * See also {Methods for Creating a Hash}[rdoc-ref:Hash@Methods+for+Creating+a+Hash].
1783 */
1784
1785static VALUE
1786rb_hash_s_create(int argc, VALUE *argv, VALUE klass)
1787{
1788 VALUE hash, tmp;
1789
1790 if (argc == 1) {
1791 tmp = rb_hash_s_try_convert(Qnil, argv[0]);
1792 if (!NIL_P(tmp)) {
1793 if (!RHASH_EMPTY_P(tmp) && rb_hash_compare_by_id_p(tmp)) {
1794 /* hash_copy for non-empty hash will copy compare_by_identity
1795 flag, but we don't want it copied. Work around by
1796 converting hash to flattened array and using that. */
1797 tmp = rb_hash_to_a(tmp);
1798 }
1799 else {
1800 hash = hash_alloc(klass);
1801 if (!RHASH_EMPTY_P(tmp))
1802 hash_copy(hash, tmp);
1803 return hash;
1804 }
1805 }
1806 else {
1807 tmp = rb_check_array_type(argv[0]);
1808 }
1809
1810 if (!NIL_P(tmp)) {
1811 long i;
1812
1813 hash = hash_alloc(klass);
1814 for (i = 0; i < RARRAY_LEN(tmp); ++i) {
1815 VALUE e = RARRAY_AREF(tmp, i);
1817 VALUE key, val = Qnil;
1818
1819 if (NIL_P(v)) {
1820 rb_raise(rb_eArgError, "wrong element type %s at %ld (expected array)",
1821 rb_builtin_class_name(e), i);
1822 }
1823 switch (RARRAY_LEN(v)) {
1824 default:
1825 rb_raise(rb_eArgError, "invalid number of elements (%ld for 1..2)",
1826 RARRAY_LEN(v));
1827 case 2:
1828 val = RARRAY_AREF(v, 1);
1829 case 1:
1830 key = RARRAY_AREF(v, 0);
1831 rb_hash_aset(hash, key, val);
1832 }
1833 }
1834 return hash;
1835 }
1836 }
1837 if (argc % 2 != 0) {
1838 rb_raise(rb_eArgError, "odd number of arguments for Hash");
1839 }
1840
1841 hash = hash_alloc(klass);
1842 rb_hash_bulk_insert(argc, argv, hash);
1843 hash_verify(hash);
1844 return hash;
1845}
1846
1847VALUE
1848rb_to_hash_type(VALUE hash)
1849{
1850 return rb_convert_type_with_id(hash, T_HASH, "Hash", idTo_hash);
1851}
1852#define to_hash rb_to_hash_type
1853
1854VALUE
1855rb_check_hash_type(VALUE hash)
1856{
1857 return rb_check_convert_type_with_id(hash, T_HASH, "Hash", idTo_hash);
1858}
1859
1860/*
1861 * call-seq:
1862 * Hash.try_convert(object) -> object, new_hash, or nil
1863 *
1864 * If +object+ is a hash, returns +object+.
1865 *
1866 * Otherwise if +object+ responds to +:to_hash+,
1867 * calls <tt>object.to_hash</tt>;
1868 * returns the result if it is a hash, or raises TypeError if not.
1869 *
1870 * Otherwise if +object+ does not respond to +:to_hash+, returns +nil+.
1871 */
1872static VALUE
1873rb_hash_s_try_convert(VALUE dummy, VALUE hash)
1874{
1875 return rb_check_hash_type(hash);
1876}
1877
1878/*
1879 * call-seq:
1880 * Hash.ruby2_keywords_hash?(hash) -> true or false
1881 *
1882 * Checks if a given hash is flagged by Module#ruby2_keywords (or
1883 * Proc#ruby2_keywords).
1884 * This method is not for casual use; debugging, researching, and
1885 * some truly necessary cases like serialization of arguments.
1886 *
1887 * ruby2_keywords def foo(*args)
1888 * Hash.ruby2_keywords_hash?(args.last)
1889 * end
1890 * foo(k: 1) #=> true
1891 * foo({k: 1}) #=> false
1892 */
1893static VALUE
1894rb_hash_s_ruby2_keywords_hash_p(VALUE dummy, VALUE hash)
1895{
1896 Check_Type(hash, T_HASH);
1897 return RBOOL(RHASH(hash)->basic.flags & RHASH_PASS_AS_KEYWORDS);
1898}
1899
1900/*
1901 * call-seq:
1902 * Hash.ruby2_keywords_hash(hash) -> hash
1903 *
1904 * Duplicates a given hash and adds a ruby2_keywords flag.
1905 * This method is not for casual use; debugging, researching, and
1906 * some truly necessary cases like deserialization of arguments.
1907 *
1908 * h = {k: 1}
1909 * h = Hash.ruby2_keywords_hash(h)
1910 * def foo(k: 42)
1911 * k
1912 * end
1913 * foo(*[h]) #=> 1 with neither a warning or an error
1914 */
1915static VALUE
1916rb_hash_s_ruby2_keywords_hash(VALUE dummy, VALUE hash)
1917{
1918 Check_Type(hash, T_HASH);
1919 VALUE tmp = rb_hash_dup(hash);
1920 if (RHASH_EMPTY_P(hash) && rb_hash_compare_by_id_p(hash)) {
1921 rb_hash_compare_by_id(tmp);
1922 }
1923 RHASH(tmp)->basic.flags |= RHASH_PASS_AS_KEYWORDS;
1924 return tmp;
1925}
1926
1928 VALUE hash;
1929 st_table *tbl;
1930};
1931
1932static int
1933rb_hash_rehash_i(VALUE key, VALUE value, VALUE arg)
1934{
1935 if (RHASH_AR_TABLE_P(arg)) {
1936 ar_insert(arg, (st_data_t)key, (st_data_t)value);
1937 }
1938 else {
1939 st_insert(RHASH_ST_TABLE(arg), (st_data_t)key, (st_data_t)value);
1940 }
1941 return ST_CONTINUE;
1942}
1943
1944/*
1945 * call-seq:
1946 * rehash -> self
1947 *
1948 * Rebuilds the hash table for +self+ by recomputing the hash index for each key;
1949 * returns <tt>self</tt>.
1950 * Calling this method ensures that the hash table is valid.
1951 *
1952 * The hash table becomes invalid if the hash value of a key
1953 * has changed after the entry was created.
1954 * See {Modifying an Active Hash Key}[rdoc-ref:Hash@Modifying+an+Active+Hash+Key].
1955 */
1956
1957VALUE
1958rb_hash_rehash(VALUE hash)
1959{
1960 VALUE tmp;
1961 st_table *tbl;
1962
1963 if (hash_iterating_p(hash)) {
1964 rb_raise(rb_eRuntimeError, "rehash during iteration");
1965 }
1966 rb_hash_modify_check(hash);
1967 if (RHASH_AR_TABLE_P(hash)) {
1968 tmp = hash_alloc(0);
1969 rb_hash_foreach(hash, rb_hash_rehash_i, (VALUE)tmp);
1970
1971 hash_ar_free_and_clear_table(hash);
1972 ar_copy(hash, tmp);
1973 }
1974 else if (RHASH_ST_TABLE_P(hash)) {
1975 st_table *old_tab = RHASH_ST_TABLE(hash);
1976 tmp = hash_alloc(0);
1977
1978 hash_st_table_init(tmp, old_tab->type, old_tab->num_entries);
1979 tbl = RHASH_ST_TABLE(tmp);
1980
1981 rb_hash_foreach(hash, rb_hash_rehash_i, (VALUE)tmp);
1982
1983 hash_st_free(hash);
1984 RHASH_ST_TABLE_SET(hash, tbl);
1985 RHASH_ST_CLEAR(tmp);
1986 }
1987 hash_verify(hash);
1988 return hash;
1989}
1990
1991static VALUE
1992call_default_proc(VALUE proc, VALUE hash, VALUE key)
1993{
1994 VALUE args[2] = {hash, key};
1995 return rb_proc_call_with_block(proc, 2, args, Qnil);
1996}
1997
1998bool
1999rb_hash_default_unredefined(VALUE hash)
2000{
2001 VALUE klass = RBASIC_CLASS(hash);
2002 if (LIKELY(klass == rb_cHash)) {
2003 return !!BASIC_OP_UNREDEFINED_P(BOP_DEFAULT, HASH_REDEFINED_OP_FLAG);
2004 }
2005 else {
2006 return LIKELY(rb_method_basic_definition_p(klass, id_default));
2007 }
2008}
2009
2010VALUE
2011rb_hash_default_value(VALUE hash, VALUE key)
2012{
2014
2015 if (LIKELY(rb_hash_default_unredefined(hash))) {
2016 VALUE ifnone = RHASH_IFNONE(hash);
2017 if (LIKELY(!FL_TEST_RAW(hash, RHASH_PROC_DEFAULT))) return ifnone;
2018 if (UNDEF_P(key)) return Qnil;
2019 return call_default_proc(ifnone, hash, key);
2020 }
2021 else {
2022 return rb_funcall(hash, id_default, 1, key);
2023 }
2024}
2025
2026static inline int
2027hash_stlike_lookup(VALUE hash, st_data_t key, st_data_t *pval)
2028{
2029 hash_verify(hash);
2030
2031 if (RHASH_AR_TABLE_P(hash)) {
2032 return ar_lookup(hash, key, pval);
2033 }
2034 else {
2035 extern st_index_t rb_iseq_cdhash_hash(VALUE);
2036 RUBY_ASSERT(RHASH_ST_TABLE(hash)->type->hash == rb_any_hash ||
2037 RHASH_ST_TABLE(hash)->type->hash == rb_ident_hash ||
2038 RHASH_ST_TABLE(hash)->type->hash == rb_iseq_cdhash_hash);
2039 return st_lookup(RHASH_ST_TABLE(hash), key, pval);
2040 }
2041}
2042
2043int
2044rb_hash_stlike_lookup(VALUE hash, st_data_t key, st_data_t *pval)
2045{
2046 return hash_stlike_lookup(hash, key, pval);
2047}
2048
2049/*
2050 * call-seq:
2051 * self[key] -> object
2052 *
2053 * Searches for a hash key equivalent to the given +key+;
2054 * see {Hash Key Equivalence}[rdoc-ref:Hash@Hash+Key+Equivalence].
2055 *
2056 * If the key is found, returns its value:
2057 *
2058 * {foo: 0, bar: 1, baz: 2}
2059 * h[:bar] # => 1
2060 *
2061 * Otherwise, returns a default value (see {Hash Default}[rdoc-ref:Hash@Hash+Default]).
2062 *
2063 * Related: #[]=; see also {Methods for Fetching}[rdoc-ref:Hash@Methods+for+Fetching].
2064 */
2065
2066VALUE
2067rb_hash_aref(VALUE hash, VALUE key)
2068{
2069 st_data_t val;
2070
2071 if (hash_stlike_lookup(hash, key, &val)) {
2072 return (VALUE)val;
2073 }
2074 else {
2075 return rb_hash_default_value(hash, key);
2076 }
2077}
2078
2079VALUE
2080rb_hash_lookup2(VALUE hash, VALUE key, VALUE def)
2081{
2082 st_data_t val;
2083
2084 if (hash_stlike_lookup(hash, key, &val)) {
2085 return (VALUE)val;
2086 }
2087 else {
2088 return def; /* without Hash#default */
2089 }
2090}
2091
2092VALUE
2093rb_hash_lookup(VALUE hash, VALUE key)
2094{
2095 return rb_hash_lookup2(hash, key, Qnil);
2096}
2097
2098/*
2099 * call-seq:
2100 * fetch(key) -> object
2101 * fetch(key, default_value) -> object
2102 * fetch(key) {|key| ... } -> object
2103 *
2104 * With no block given, returns the value for the given +key+, if found;
2105 *
2106 * h = {foo: 0, bar: 1, baz: 2}
2107 * h.fetch(:bar) # => 1
2108 *
2109 * If the key is not found, returns +default_value+, if given,
2110 * or raises KeyError otherwise:
2111 *
2112 * h.fetch(:nosuch, :default) # => :default
2113 * h.fetch(:nosuch) # Raises KeyError.
2114 *
2115 * With a block given, calls the block with +key+ and returns the block's return value:
2116 *
2117 * {}.fetch(:nosuch) {|key| "No key #{key}"} # => "No key nosuch"
2118 *
2119 * Note that this method does not use the values of either #default or #default_proc.
2120 *
2121 * Related: see {Methods for Fetching}[rdoc-ref:Hash@Methods+for+Fetching].
2122 */
2123
2124static VALUE
2125rb_hash_fetch_m(int argc, VALUE *argv, VALUE hash)
2126{
2127 VALUE key;
2128 st_data_t val;
2129 long block_given;
2130
2131 rb_check_arity(argc, 1, 2);
2132 key = argv[0];
2133
2134 block_given = rb_block_given_p();
2135 if (block_given && argc == 2) {
2136 rb_warn("block supersedes default value argument");
2137 }
2138
2139 if (hash_stlike_lookup(hash, key, &val)) {
2140 return (VALUE)val;
2141 }
2142 else {
2143 if (block_given) {
2144 return rb_yield(key);
2145 }
2146 else if (argc == 1) {
2147 VALUE desc = rb_protect(rb_inspect, key, 0);
2148 if (NIL_P(desc)) {
2149 desc = rb_any_to_s(key);
2150 }
2151 desc = rb_str_ellipsize(desc, 65);
2152 rb_key_err_raise(rb_sprintf("key not found: %"PRIsVALUE, desc), hash, key);
2153 }
2154 else {
2155 return argv[1];
2156 }
2157 }
2158}
2159
2160VALUE
2161rb_hash_fetch(VALUE hash, VALUE key)
2162{
2163 return rb_hash_fetch_m(1, &key, hash);
2164}
2165
2166/*
2167 * call-seq:
2168 * default -> object
2169 * default(key) -> object
2170 *
2171 * Returns the default value for the given +key+.
2172 * The returned value will be determined either by the default proc or by the default value.
2173 * See {Hash Default}[rdoc-ref:Hash@Hash+Default].
2174 *
2175 * With no argument, returns the current default value:
2176 * h = {}
2177 * h.default # => nil
2178 *
2179 * If +key+ is given, returns the default value for +key+,
2180 * regardless of whether that key exists:
2181 * h = Hash.new { |hash, key| hash[key] = "No key #{key}"}
2182 * h[:foo] = "Hello"
2183 * h.default(:foo) # => "No key foo"
2184 */
2185
2186static VALUE
2187rb_hash_default(int argc, VALUE *argv, VALUE hash)
2188{
2189 VALUE ifnone;
2190
2191 rb_check_arity(argc, 0, 1);
2192 ifnone = RHASH_IFNONE(hash);
2193 if (FL_TEST(hash, RHASH_PROC_DEFAULT)) {
2194 if (argc == 0) return Qnil;
2195 return call_default_proc(ifnone, hash, argv[0]);
2196 }
2197 return ifnone;
2198}
2199
2200/*
2201 * call-seq:
2202 * default = value -> object
2203 *
2204 * Sets the default value to +value+; returns +value+:
2205 * h = {}
2206 * h.default # => nil
2207 * h.default = false # => false
2208 * h.default # => false
2209 *
2210 * See {Hash Default}[rdoc-ref:Hash@Hash+Default].
2211 */
2212
2213VALUE
2214rb_hash_set_default(VALUE hash, VALUE ifnone)
2215{
2216 rb_hash_modify_check(hash);
2217 SET_DEFAULT(hash, ifnone);
2218 return ifnone;
2219}
2220
2221/*
2222 * call-seq:
2223 * default_proc -> proc or nil
2224 *
2225 * Returns the default proc for +self+
2226 * (see {Hash Default}[rdoc-ref:Hash@Hash+Default]):
2227 * h = {}
2228 * h.default_proc # => nil
2229 * h.default_proc = proc {|hash, key| "Default value for #{key}" }
2230 * h.default_proc.class # => Proc
2231 */
2232
2233static VALUE
2234rb_hash_default_proc(VALUE hash)
2235{
2236 if (FL_TEST(hash, RHASH_PROC_DEFAULT)) {
2237 return RHASH_IFNONE(hash);
2238 }
2239 return Qnil;
2240}
2241
2242/*
2243 * call-seq:
2244 * default_proc = proc -> proc
2245 *
2246 * Sets the default proc for +self+ to +proc+
2247 * (see {Hash Default}[rdoc-ref:Hash@Hash+Default]):
2248 * h = {}
2249 * h.default_proc # => nil
2250 * h.default_proc = proc { |hash, key| "Default value for #{key}" }
2251 * h.default_proc.class # => Proc
2252 * h.default_proc = nil
2253 * h.default_proc # => nil
2254 */
2255
2256VALUE
2257rb_hash_set_default_proc(VALUE hash, VALUE proc)
2258{
2259 VALUE b;
2260
2261 rb_hash_modify_check(hash);
2262 if (NIL_P(proc)) {
2263 SET_DEFAULT(hash, proc);
2264 return proc;
2265 }
2266 b = rb_check_convert_type_with_id(proc, T_DATA, "Proc", idTo_proc);
2267 if (NIL_P(b) || !rb_obj_is_proc(b)) {
2268 rb_raise(rb_eTypeError,
2269 "wrong default_proc type %s (expected Proc)",
2270 rb_obj_classname(proc));
2271 }
2272 proc = b;
2273 SET_PROC_DEFAULT(hash, proc);
2274 return proc;
2275}
2276
2277static int
2278key_i(VALUE key, VALUE value, VALUE arg)
2279{
2280 VALUE *args = (VALUE *)arg;
2281
2282 if (rb_equal(value, args[0])) {
2283 args[1] = key;
2284 return ST_STOP;
2285 }
2286 return ST_CONTINUE;
2287}
2288
2289/*
2290 * call-seq:
2291 * key(value) -> key or nil
2292 *
2293 * Returns the key for the first-found entry with the given +value+
2294 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
2295 *
2296 * h = {foo: 0, bar: 2, baz: 2}
2297 * h.key(0) # => :foo
2298 * h.key(2) # => :bar
2299 *
2300 * Returns +nil+ if no such value is found.
2301 *
2302 * Related: see {Methods for Fetching}[rdoc-ref:Hash@Methods+for+Fetching].
2303 */
2304
2305static VALUE
2306rb_hash_key(VALUE hash, VALUE value)
2307{
2308 VALUE args[2];
2309
2310 args[0] = value;
2311 args[1] = Qnil;
2312
2313 rb_hash_foreach(hash, key_i, (VALUE)args);
2314
2315 return args[1];
2316}
2317
2318int
2319rb_hash_stlike_delete(VALUE hash, st_data_t *pkey, st_data_t *pval)
2320{
2321 if (RHASH_AR_TABLE_P(hash)) {
2322 return ar_delete(hash, pkey, pval);
2323 }
2324 else {
2325 return st_delete(RHASH_ST_TABLE(hash), pkey, pval);
2326 }
2327}
2328
2329/*
2330 * delete a specified entry by a given key.
2331 * if there is the corresponding entry, return a value of the entry.
2332 * if there is no corresponding entry, return Qundef.
2333 */
2334VALUE
2335rb_hash_delete_entry(VALUE hash, VALUE key)
2336{
2337 st_data_t ktmp = (st_data_t)key, val;
2338
2339 if (rb_hash_stlike_delete(hash, &ktmp, &val)) {
2340 return (VALUE)val;
2341 }
2342 else {
2343 return Qundef;
2344 }
2345}
2346
2347/*
2348 * delete a specified entry by a given key.
2349 * if there is the corresponding entry, return a value of the entry.
2350 * if there is no corresponding entry, return Qnil.
2351 */
2352VALUE
2353rb_hash_delete(VALUE hash, VALUE key)
2354{
2355 VALUE deleted_value = rb_hash_delete_entry(hash, key);
2356
2357 if (!UNDEF_P(deleted_value)) { /* likely pass */
2358 return deleted_value;
2359 }
2360 else {
2361 return Qnil;
2362 }
2363}
2364
2365/*
2366 * call-seq:
2367 * delete(key) -> value or nil
2368 * delete(key) {|key| ... } -> object
2369 *
2370 * If an entry for the given +key+ is found,
2371 * deletes the entry and returns its associated value;
2372 * otherwise returns +nil+ or calls the given block.
2373 *
2374 * With no block given and +key+ found, deletes the entry and returns its value:
2375 *
2376 * h = {foo: 0, bar: 1, baz: 2}
2377 * h.delete(:bar) # => 1
2378 * h # => {foo: 0, baz: 2}
2379 *
2380 * With no block given and +key+ not found, returns +nil+.
2381 *
2382 * With a block given and +key+ found, ignores the block,
2383 * deletes the entry, and returns its value:
2384 *
2385 * h = {foo: 0, bar: 1, baz: 2}
2386 * h.delete(:baz) { |key| raise 'Will never happen'} # => 2
2387 * h # => {foo: 0, bar: 1}
2388 *
2389 * With a block given and +key+ not found,
2390 * calls the block and returns the block's return value:
2391 *
2392 * h = {foo: 0, bar: 1, baz: 2}
2393 * h.delete(:nosuch) { |key| "Key #{key} not found" } # => "Key nosuch not found"
2394 * h # => {foo: 0, bar: 1, baz: 2}
2395 *
2396 * Related: see {Methods for Deleting}[rdoc-ref:Hash@Methods+for+Deleting].
2397 */
2398
2399static VALUE
2400rb_hash_delete_m(VALUE hash, VALUE key)
2401{
2402 VALUE val;
2403
2404 rb_hash_modify_check(hash);
2405 val = rb_hash_delete_entry(hash, key);
2406
2407 if (!UNDEF_P(val)) {
2408 compact_after_delete(hash);
2409 return val;
2410 }
2411 else {
2412 if (rb_block_given_p()) {
2413 return rb_yield(key);
2414 }
2415 else {
2416 return Qnil;
2417 }
2418 }
2419}
2420
2422 VALUE key;
2423 VALUE val;
2424};
2425
2426static int
2427shift_i_safe(VALUE key, VALUE value, VALUE arg)
2428{
2429 struct shift_var *var = (struct shift_var *)arg;
2430
2431 var->key = key;
2432 var->val = value;
2433 return ST_STOP;
2434}
2435
2436/*
2437 * call-seq:
2438 * shift -> [key, value] or nil
2439 *
2440 * Removes and returns the first entry of +self+ as a 2-element array;
2441 * see {Entry Order}[rdoc-ref:Hash@Entry+Order]:
2442 *
2443 * h = {foo: 0, bar: 1, baz: 2}
2444 * h.shift # => [:foo, 0]
2445 * h # => {bar: 1, baz: 2}
2446 *
2447 * Returns +nil+ if +self+ is empty.
2448 *
2449 * Related: see {Methods for Deleting}[rdoc-ref:Hash@Methods+for+Deleting].
2450 */
2451
2452static VALUE
2453rb_hash_shift(VALUE hash)
2454{
2455 struct shift_var var;
2456
2457 rb_hash_modify_check(hash);
2458 if (RHASH_AR_TABLE_P(hash)) {
2459 var.key = Qundef;
2460 if (!hash_iterating_p(hash)) {
2461 if (ar_shift(hash, &var.key, &var.val)) {
2462 return rb_assoc_new(var.key, var.val);
2463 }
2464 }
2465 else {
2466 rb_hash_foreach(hash, shift_i_safe, (VALUE)&var);
2467 if (!UNDEF_P(var.key)) {
2468 rb_hash_delete_entry(hash, var.key);
2469 return rb_assoc_new(var.key, var.val);
2470 }
2471 }
2472 }
2473 if (RHASH_ST_TABLE_P(hash)) {
2474 var.key = Qundef;
2475 if (!hash_iterating_p(hash)) {
2476 if (st_shift(RHASH_ST_TABLE(hash), &var.key, &var.val)) {
2477 return rb_assoc_new(var.key, var.val);
2478 }
2479 }
2480 else {
2481 rb_hash_foreach(hash, shift_i_safe, (VALUE)&var);
2482 if (!UNDEF_P(var.key)) {
2483 rb_hash_delete_entry(hash, var.key);
2484 return rb_assoc_new(var.key, var.val);
2485 }
2486 }
2487 }
2488 return Qnil;
2489}
2490
2491static int
2492delete_if_i(VALUE key, VALUE value, VALUE hash)
2493{
2494 if (RTEST(rb_yield_values(2, key, value))) {
2495 rb_hash_modify(hash);
2496 return ST_DELETE;
2497 }
2498 return ST_CONTINUE;
2499}
2500
2501static VALUE
2502hash_enum_size(VALUE hash, VALUE args, VALUE eobj)
2503{
2504 return rb_hash_size(hash);
2505}
2506
2507/*
2508 * call-seq:
2509 * delete_if {|key, value| ... } -> self
2510 * delete_if -> new_enumerator
2511 *
2512 * With a block given, calls the block with each key-value pair,
2513 * deletes each entry for which the block returns a truthy value,
2514 * and returns +self+:
2515 *
2516 * h = {foo: 0, bar: 1, baz: 2}
2517 * h.delete_if {|key, value| value > 0 } # => {foo: 0}
2518 *
2519 * With no block given, returns a new Enumerator.
2520 *
2521 * Related: see {Methods for Deleting}[rdoc-ref:Hash@Methods+for+Deleting].
2522 */
2523
2524VALUE
2525rb_hash_delete_if(VALUE hash)
2526{
2527 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2528 rb_hash_modify_check(hash);
2529 if (!RHASH_TABLE_EMPTY_P(hash)) {
2530 rb_hash_foreach(hash, delete_if_i, hash);
2531 compact_after_delete(hash);
2532 }
2533 return hash;
2534}
2535
2536/*
2537 * call-seq:
2538 * reject! {|key, value| ... } -> self or nil
2539 * reject! -> new_enumerator
2540 *
2541 * With a block given, calls the block with each entry's key and value;
2542 * removes the entry from +self+ if the block returns a truthy value.
2543 *
2544 * Return +self+ if any entries were removed, +nil+ otherwise:
2545 *
2546 * h = {foo: 0, bar: 1, baz: 2}
2547 * h.reject! {|key, value| value < 2 } # => {baz: 2}
2548 * h.reject! {|key, value| value < 2 } # => nil
2549 *
2550 * With no block given, returns a new Enumerator.
2551 *
2552 * Related: see {Methods for Deleting}[rdoc-ref:Hash@Methods+for+Deleting].
2553 */
2554
2555static VALUE
2556rb_hash_reject_bang(VALUE hash)
2557{
2558 st_index_t n;
2559
2560 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2561 rb_hash_modify(hash);
2562 n = RHASH_SIZE(hash);
2563 if (!n) return Qnil;
2564 rb_hash_foreach(hash, delete_if_i, hash);
2565 if (n == RHASH_SIZE(hash)) return Qnil;
2566 return hash;
2567}
2568
2569/*
2570 * call-seq:
2571 * reject {|key, value| ... } -> new_hash
2572 * reject -> new_enumerator
2573 *
2574 * With a block given, returns a copy of +self+ with zero or more entries removed;
2575 * calls the block with each key-value pair;
2576 * excludes the entry in the copy if the block returns a truthy value,
2577 * includes it otherwise:
2578 *
2579 * h = {foo: 0, bar: 1, baz: 2}
2580 * h.reject {|key, value| key.start_with?('b') }
2581 * # => {foo: 0}
2582 *
2583 * With no block given, returns a new Enumerator.
2584 *
2585 * Related: see {Methods for Deleting}[rdoc-ref:Hash@Methods+for+Deleting].
2586 */
2587
2588static VALUE
2589rb_hash_reject(VALUE hash)
2590{
2591 VALUE result;
2592
2593 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2594 result = hash_dup_with_compare_by_id(hash);
2595 if (!RHASH_EMPTY_P(hash)) {
2596 rb_hash_foreach(result, delete_if_i, result);
2597 compact_after_delete(result);
2598 }
2599 return result;
2600}
2601
2602/*
2603 * call-seq:
2604 * slice(*keys) -> new_hash
2605 *
2606 * Returns a new hash containing the entries from +self+ for the given +keys+;
2607 * ignores any keys that are not found:
2608 *
2609 * h = {foo: 0, bar: 1, baz: 2}
2610 * h.slice(:baz, :foo, :nosuch) # => {baz: 2, foo: 0}
2611 *
2612 * Related: see {Methods for Deleting}[rdoc-ref:Hash@Methods+for+Deleting].
2613 */
2614
2615static VALUE
2616rb_hash_slice(int argc, VALUE *argv, VALUE hash)
2617{
2618 int i;
2619 VALUE key, value, result;
2620
2621 if (argc == 0 || RHASH_EMPTY_P(hash)) {
2622 return copy_compare_by_id(rb_hash_new(), hash);
2623 }
2624 result = copy_compare_by_id(rb_hash_new_with_size(argc), hash);
2625
2626 for (i = 0; i < argc; i++) {
2627 key = argv[i];
2628 value = rb_hash_lookup2(hash, key, Qundef);
2629 if (!UNDEF_P(value))
2630 rb_hash_aset(result, key, value);
2631 }
2632
2633 return result;
2634}
2635
2636/*
2637 * call-seq:
2638 * except(*keys) -> new_hash
2639 *
2640 * Returns a copy of +self+ that excludes entries for the given +keys+;
2641 * any +keys+ that are not found are ignored:
2642 *
2643 * h = {foo:0, bar: 1, baz: 2} # => {foo: 0, bar: 1, baz: 2}
2644 * h.except(:baz, :foo) # => {bar: 1}
2645 * h.except(:bar, :nosuch) # => {foo: 0, baz: 2}
2646 *
2647 * Related: see {Methods for Deleting}[rdoc-ref:Hash@Methods+for+Deleting].
2648 */
2649
2650static VALUE
2651rb_hash_except(int argc, VALUE *argv, VALUE hash)
2652{
2653 int i;
2654 VALUE key, result;
2655
2656 result = hash_dup_with_compare_by_id(hash);
2657
2658 for (i = 0; i < argc; i++) {
2659 key = argv[i];
2660 rb_hash_delete(result, key);
2661 }
2662 compact_after_delete(result);
2663
2664 return result;
2665}
2666
2667/*
2668 * call-seq:
2669 * values_at(*keys) -> new_array
2670 *
2671 * Returns a new array containing values for the given +keys+:
2672 *
2673 * h = {foo: 0, bar: 1, baz: 2}
2674 * h.values_at(:baz, :foo) # => [2, 0]
2675 *
2676 * The {hash default}[rdoc-ref:Hash@Hash+Default] is returned
2677 * for each key that is not found:
2678 *
2679 * h.values_at(:hello, :foo) # => [nil, 0]
2680 *
2681 * Related: see {Methods for Fetching}[rdoc-ref:Hash@Methods+for+Fetching].
2682 */
2683
2684static VALUE
2685rb_hash_values_at(int argc, VALUE *argv, VALUE hash)
2686{
2687 VALUE result = rb_ary_new2(argc);
2688 long i;
2689
2690 for (i=0; i<argc; i++) {
2691 rb_ary_push(result, rb_hash_aref(hash, argv[i]));
2692 }
2693 return result;
2694}
2695
2696/*
2697 * call-seq:
2698 * fetch_values(*keys) -> new_array
2699 * fetch_values(*keys) {|key| ... } -> new_array
2700 *
2701 * When all given +keys+ are found,
2702 * returns a new array containing the values associated with the given +keys+:
2703 *
2704 * h = {foo: 0, bar: 1, baz: 2}
2705 * h.fetch_values(:baz, :foo) # => [2, 0]
2706 *
2707 * When any given +keys+ are not found and a block is given,
2708 * calls the block with each unfound key and uses the block's return value
2709 * as the value for that key:
2710 *
2711 * h.fetch_values(:bar, :foo, :bad, :bam) {|key| key.to_s}
2712 * # => [1, 0, "bad", "bam"]
2713 *
2714 * When any given +keys+ are not found and no block is given,
2715 * raises KeyError.
2716 *
2717 * Related: see {Methods for Fetching}[rdoc-ref:Hash@Methods+for+Fetching].
2718 */
2719
2720static VALUE
2721rb_hash_fetch_values(int argc, VALUE *argv, VALUE hash)
2722{
2723 VALUE result = rb_ary_new2(argc);
2724 long i;
2725
2726 for (i=0; i<argc; i++) {
2727 rb_ary_push(result, rb_hash_fetch(hash, argv[i]));
2728 }
2729 return result;
2730}
2731
2732static int
2733keep_if_i(VALUE key, VALUE value, VALUE hash)
2734{
2735 if (!RTEST(rb_yield_values(2, key, value))) {
2736 rb_hash_modify(hash);
2737 return ST_DELETE;
2738 }
2739 return ST_CONTINUE;
2740}
2741
2742/*
2743 * call-seq:
2744 * select {|key, value| ... } -> new_hash
2745 * select -> new_enumerator
2746 *
2747 * With a block given, calls the block with each entry's key and value;
2748 * returns a new hash whose entries are those for which the block returns a truthy value:
2749 *
2750 * h = {foo: 0, bar: 1, baz: 2}
2751 * h.select {|key, value| value < 2 } # => {foo: 0, bar: 1}
2752 *
2753 * With no block given, returns a new Enumerator.
2754 *
2755 * Related: see {Methods for Deleting}[rdoc-ref:Hash@Methods+for+Deleting].
2756 */
2757
2758static VALUE
2759rb_hash_select(VALUE hash)
2760{
2761 VALUE result;
2762
2763 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2764 result = hash_dup_with_compare_by_id(hash);
2765 if (!RHASH_EMPTY_P(hash)) {
2766 rb_hash_foreach(result, keep_if_i, result);
2767 compact_after_delete(result);
2768 }
2769 return result;
2770}
2771
2772/*
2773 * call-seq:
2774 * select! {|key, value| ... } -> self or nil
2775 * select! -> new_enumerator
2776 *
2777 * With a block given, calls the block with each entry's key and value;
2778 * removes from +self+ each entry for which the block returns +false+ or +nil+.
2779 *
2780 * Returns +self+ if any entries were removed, +nil+ otherwise:
2781 *
2782 * h = {foo: 0, bar: 1, baz: 2}
2783 * h.select! {|key, value| value < 2 } # => {foo: 0, bar: 1}
2784 * h.select! {|key, value| value < 2 } # => nil
2785 *
2786 *
2787 * With no block given, returns a new Enumerator.
2788 *
2789 * Related: see {Methods for Deleting}[rdoc-ref:Hash@Methods+for+Deleting].
2790 */
2791
2792static VALUE
2793rb_hash_select_bang(VALUE hash)
2794{
2795 st_index_t n;
2796
2797 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2798 rb_hash_modify_check(hash);
2799 n = RHASH_SIZE(hash);
2800 if (!n) return Qnil;
2801 rb_hash_foreach(hash, keep_if_i, hash);
2802 if (n == RHASH_SIZE(hash)) return Qnil;
2803 return hash;
2804}
2805
2806/*
2807 * call-seq:
2808 * keep_if {|key, value| ... } -> self
2809 * keep_if -> new_enumerator
2810 *
2811 * With a block given, calls the block for each key-value pair;
2812 * retains the entry if the block returns a truthy value;
2813 * otherwise deletes the entry; returns +self+:
2814 *
2815 * h = {foo: 0, bar: 1, baz: 2}
2816 * h.keep_if { |key, value| key.start_with?('b') } # => {bar: 1, baz: 2}
2817 *
2818 * With no block given, returns a new Enumerator.
2819 *
2820 * Related: see {Methods for Deleting}[rdoc-ref:Hash@Methods+for+Deleting].
2821 */
2822
2823static VALUE
2824rb_hash_keep_if(VALUE hash)
2825{
2826 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2827 rb_hash_modify_check(hash);
2828 if (!RHASH_TABLE_EMPTY_P(hash)) {
2829 rb_hash_foreach(hash, keep_if_i, hash);
2830 }
2831 return hash;
2832}
2833
2834static int
2835clear_i(VALUE key, VALUE value, VALUE dummy)
2836{
2837 return ST_DELETE;
2838}
2839
2840/*
2841 * call-seq:
2842 * clear -> self
2843 *
2844 * Removes all entries from +self+; returns emptied +self+.
2845 *
2846 * Related: see {Methods for Deleting}[rdoc-ref:Hash@Methods+for+Deleting].
2847 */
2848
2849VALUE
2850rb_hash_clear(VALUE hash)
2851{
2852 rb_hash_modify_check(hash);
2853
2854 if (hash_iterating_p(hash)) {
2855 rb_hash_foreach(hash, clear_i, 0);
2856 }
2857 else if (RHASH_AR_TABLE_P(hash)) {
2858 ar_clear(hash);
2859 }
2860 else {
2861 st_clear(RHASH_ST_TABLE(hash));
2862 compact_after_delete(hash);
2863 }
2864
2865 return hash;
2866}
2867
2868static int
2869hash_aset(st_data_t *key, st_data_t *val, struct update_arg *arg, int existing)
2870{
2871 *val = arg->arg;
2872 return ST_CONTINUE;
2873}
2874
2875VALUE
2876rb_hash_key_str(VALUE key)
2877{
2878 if (!rb_obj_gen_fields_p(key) && RBASIC_CLASS(key) == rb_cString) {
2879 return rb_fstring(key);
2880 }
2881 else {
2882 return rb_str_new_frozen(key);
2883 }
2884}
2885
2886static int
2887hash_aset_str(st_data_t *key, st_data_t *val, struct update_arg *arg, int existing)
2888{
2889 if (!existing && !RB_OBJ_FROZEN(*key)) {
2890 *key = rb_hash_key_str(*key);
2891 }
2892 return hash_aset(key, val, arg, existing);
2893}
2894
2895NOINSERT_UPDATE_CALLBACK(hash_aset)
2896NOINSERT_UPDATE_CALLBACK(hash_aset_str)
2897
2898/*
2899 * call-seq:
2900 * self[key] = object -> object
2901 *
2902 * Associates the given +object+ with the given +key+; returns +object+.
2903 *
2904 * Searches for a hash key equivalent to the given +key+;
2905 * see {Hash Key Equivalence}[rdoc-ref:Hash@Hash+Key+Equivalence].
2906 *
2907 * If the key is found, replaces its value with the given +object+;
2908 * the ordering is not affected
2909 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
2910 *
2911 * h = {foo: 0, bar: 1}
2912 * h[:foo] = 2 # => 2
2913 * h[:foo] # => 2
2914 *
2915 * If +key+ is not found, creates a new entry for the given +key+ and +object+;
2916 * the new entry is last in the order
2917 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
2918 *
2919 * h = {foo: 0, bar: 1}
2920 * h[:baz] = 2 # => 2
2921 * h[:baz] # => 2
2922 * h # => {foo: 0, bar: 1, baz: 2}
2923 *
2924 * Related: #[]; see also {Methods for Assigning}[rdoc-ref:Hash@Methods+for+Assigning].
2925 */
2926
2927VALUE
2928rb_hash_aset(VALUE hash, VALUE key, VALUE val)
2929{
2930 bool iter_p = hash_iterating_p(hash);
2931
2932 rb_hash_modify(hash);
2933
2934 if (!RHASH_STRING_KEY_P(hash, key)) {
2935 RHASH_UPDATE_ITER(hash, iter_p, key, hash_aset, val);
2936 }
2937 else {
2938 RHASH_UPDATE_ITER(hash, iter_p, key, hash_aset_str, val);
2939 }
2940 return val;
2941}
2942
2943/*
2944 * call-seq:
2945 * replace(other_hash) -> self
2946 *
2947 * Replaces the entire contents of +self+ with the contents of +other_hash+;
2948 * returns +self+:
2949 *
2950 * h = {foo: 0, bar: 1, baz: 2}
2951 * h.replace({bat: 3, bam: 4}) # => {bat: 3, bam: 4}
2952 *
2953 * Also replaces the default value or proc of +self+ with the default value
2954 * or proc of +other_hash+.
2955 *
2956 * h = {}
2957 * other = Hash.new(:ok)
2958 * h.replace(other)
2959 * h.default # => :ok
2960 *
2961 * Related: see {Methods for Assigning}[rdoc-ref:Hash@Methods+for+Assigning].
2962 */
2963
2964static VALUE
2965rb_hash_replace(VALUE hash, VALUE hash2)
2966{
2967 rb_hash_modify_check(hash);
2968 if (hash == hash2) return hash;
2969 if (hash_iterating_p(hash)) {
2970 rb_raise(rb_eRuntimeError, "can't replace hash during iteration");
2971 }
2972 hash2 = to_hash(hash2);
2973
2974 COPY_DEFAULT(hash, hash2);
2975
2976 if (RHASH_AR_TABLE_P(hash)) {
2977 hash_ar_free_and_clear_table(hash);
2978 }
2979 else {
2980 hash_st_free_and_clear_table(hash);
2981 }
2982
2983 hash_copy(hash, hash2);
2984
2985 return hash;
2986}
2987
2988/*
2989 * call-seq:
2990 * size -> integer
2991 *
2992 * Returns the count of entries in +self+:
2993 *
2994 * {foo: 0, bar: 1, baz: 2}.size # => 3
2995 *
2996 * Related: see {Methods for Querying}[rdoc-ref:Hash@Methods+for+Querying].
2997 */
2998
2999VALUE
3000rb_hash_size(VALUE hash)
3001{
3002 return INT2FIX(RHASH_SIZE(hash));
3003}
3004
3005size_t
3006rb_hash_size_num(VALUE hash)
3007{
3008 return (long)RHASH_SIZE(hash);
3009}
3010
3011/*
3012 * call-seq:
3013 * empty? -> true or false
3014 *
3015 * Returns +true+ if there are no hash entries, +false+ otherwise:
3016 *
3017 * {}.empty? # => true
3018 * {foo: 0}.empty? # => false
3019 *
3020 * Related: see {Methods for Querying}[rdoc-ref:Hash@Methods+for+Querying].
3021 */
3022
3023VALUE
3024rb_hash_empty_p(VALUE hash)
3025{
3026 return RBOOL(RHASH_EMPTY_P(hash));
3027}
3028
3029static int
3030each_value_i(VALUE key, VALUE value, VALUE _)
3031{
3032 rb_yield(value);
3033 return ST_CONTINUE;
3034}
3035
3036/*
3037 * call-seq:
3038 * each_value {|value| ... } -> self
3039 * each_value -> new_enumerator
3040 *
3041 * With a block given, calls the block with each value; returns +self+:
3042 *
3043 * h = {foo: 0, bar: 1, baz: 2}
3044 * h.each_value {|value| puts value } # => {foo: 0, bar: 1, baz: 2}
3045 *
3046 * Output:
3047 * 0
3048 * 1
3049 * 2
3050 *
3051 * With no block given, returns a new Enumerator.
3052 *
3053 * Related: see {Methods for Iterating}[rdoc-ref:Hash@Methods+for+Iterating].
3054 */
3055
3056static VALUE
3057rb_hash_each_value(VALUE hash)
3058{
3059 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3060 rb_hash_foreach(hash, each_value_i, 0);
3061 return hash;
3062}
3063
3064static int
3065each_key_i(VALUE key, VALUE value, VALUE _)
3066{
3067 rb_yield(key);
3068 return ST_CONTINUE;
3069}
3070
3071/*
3072 * call-seq:
3073 * each_key {|key| ... } -> self
3074 * each_key -> new_enumerator
3075 *
3076 * With a block given, calls the block with each key; returns +self+:
3077 *
3078 * h = {foo: 0, bar: 1, baz: 2}
3079 * h.each_key {|key| puts key } # => {foo: 0, bar: 1, baz: 2}
3080 *
3081 * Output:
3082 * foo
3083 * bar
3084 * baz
3085 *
3086 * With no block given, returns a new Enumerator.
3087 *
3088 * Related: see {Methods for Iterating}[rdoc-ref:Hash@Methods+for+Iterating].
3089 */
3090static VALUE
3091rb_hash_each_key(VALUE hash)
3092{
3093 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3094 rb_hash_foreach(hash, each_key_i, 0);
3095 return hash;
3096}
3097
3098static int
3099each_pair_i(VALUE key, VALUE value, VALUE _)
3100{
3101 rb_yield(rb_assoc_new(key, value));
3102 return ST_CONTINUE;
3103}
3104
3105static int
3106each_pair_i_fast(VALUE key, VALUE value, VALUE _)
3107{
3108 VALUE argv[2];
3109 argv[0] = key;
3110 argv[1] = value;
3111 rb_yield_values2(2, argv);
3112 return ST_CONTINUE;
3113}
3114
3115/*
3116 * call-seq:
3117 * each_pair {|key, value| ... } -> self
3118 * each_pair -> new_enumerator
3119 *
3120 * With a block given, calls the block with each key-value pair; returns +self+:
3121 *
3122 * h = {foo: 0, bar: 1, baz: 2}
3123 * h.each_pair {|key, value| puts "#{key}: #{value}"} # => {foo: 0, bar: 1, baz: 2}
3124 *
3125 * Output:
3126 *
3127 * foo: 0
3128 * bar: 1
3129 * baz: 2
3130 *
3131 * With no block given, returns a new Enumerator.
3132 *
3133 * Related: see {Methods for Iterating}[rdoc-ref:Hash@Methods+for+Iterating].
3134 */
3135
3136static VALUE
3137rb_hash_each_pair(VALUE hash)
3138{
3139 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3140 if (rb_block_pair_yield_optimizable())
3141 rb_hash_foreach(hash, each_pair_i_fast, 0);
3142 else
3143 rb_hash_foreach(hash, each_pair_i, 0);
3144 return hash;
3145}
3146
3148 VALUE trans;
3149 VALUE result;
3150 int block_given;
3151};
3152
3153static int
3154transform_keys_hash_i(VALUE key, VALUE value, VALUE transarg)
3155{
3156 struct transform_keys_args *p = (void *)transarg;
3157 VALUE trans = p->trans, result = p->result;
3158 VALUE new_key = rb_hash_lookup2(trans, key, Qundef);
3159 if (UNDEF_P(new_key)) {
3160 if (p->block_given)
3161 new_key = rb_yield(key);
3162 else
3163 new_key = key;
3164 }
3165 rb_hash_aset(result, new_key, value);
3166 return ST_CONTINUE;
3167}
3168
3169static int
3170transform_keys_i(VALUE key, VALUE value, VALUE result)
3171{
3172 VALUE new_key = rb_yield(key);
3173 rb_hash_aset(result, new_key, value);
3174 return ST_CONTINUE;
3175}
3176
3177/*
3178 * call-seq:
3179 * transform_keys {|old_key| ... } -> new_hash
3180 * transform_keys(other_hash) -> new_hash
3181 * transform_keys(other_hash) {|old_key| ...} -> new_hash
3182 * transform_keys -> new_enumerator
3183 *
3184 * With an argument, a block, or both given,
3185 * derives a new hash +new_hash+ from +self+, the argument, and/or the block;
3186 * all, some, or none of its keys may be different from those in +self+.
3187 *
3188 * With a block given and no argument,
3189 * +new_hash+ has keys determined only by the block.
3190 *
3191 * For each key/value pair <tt>old_key/value</tt> in +self+, calls the block with +old_key+;
3192 * the block's return value becomes +new_key+;
3193 * sets <tt>new_hash[new_key] = value</tt>;
3194 * a duplicate key overwrites:
3195 *
3196 * h = {foo: 0, bar: 1, baz: 2}
3197 * h.transform_keys {|old_key| old_key.to_s }
3198 * # => {"foo" => 0, "bar" => 1, "baz" => 2}
3199 * h.transform_keys {|old_key| 'xxx' }
3200 * # => {"xxx" => 2}
3201 *
3202 * With argument +other_hash+ given and no block,
3203 * +new_hash+ may have new keys provided by +other_hash+
3204 * and unchanged keys provided by +self+.
3205 *
3206 * For each key/value pair <tt>old_key/old_value</tt> in +self+,
3207 * looks for key +old_key+ in +other_hash+:
3208 *
3209 * - If +old_key+ is found, its value <tt>other_hash[old_key]</tt> is taken as +new_key+;
3210 * sets <tt>new_hash[new_key] = value</tt>;
3211 * a duplicate key overwrites:
3212 *
3213 * h = {foo: 0, bar: 1, baz: 2}
3214 * h.transform_keys(baz: :BAZ, bar: :BAR, foo: :FOO)
3215 * # => {FOO: 0, BAR: 1, BAZ: 2}
3216 * h.transform_keys(baz: :FOO, bar: :FOO, foo: :FOO)
3217 * # => {FOO: 2}
3218 *
3219 * - If +old_key+ is not found,
3220 * sets <tt>new_hash[old_key] = value</tt>;
3221 * a duplicate key overwrites:
3222 *
3223 * h = {foo: 0, bar: 1, baz: 2}
3224 * h.transform_keys({})
3225 * # => {foo: 0, bar: 1, baz: 2}
3226 * h.transform_keys(baz: :foo)
3227 * # => {foo: 2, bar: 1}
3228 *
3229 * Unused keys in +other_hash+ are ignored:
3230 *
3231 * h = {foo: 0, bar: 1, baz: 2}
3232 * h.transform_keys(bat: 3)
3233 * # => {foo: 0, bar: 1, baz: 2}
3234 *
3235 * With both argument +other_hash+ and a block given,
3236 * +new_hash+ has new keys specified by +other_hash+ or by the block,
3237 * and unchanged keys provided by +self+.
3238 *
3239 * For each pair +old_key+ and +value+ in +self+:
3240 *
3241 * - If +other_hash+ has key +old_key+ (with value +new_key+),
3242 * does not call the block for that key;
3243 * sets <tt>new_hash[new_key] = value</tt>;
3244 * a duplicate key overwrites:
3245 *
3246 * h = {foo: 0, bar: 1, baz: 2}
3247 * h.transform_keys(baz: :BAZ, bar: :BAR, foo: :FOO) {|key| fail 'Not called' }
3248 * # => {FOO: 0, BAR: 1, BAZ: 2}
3249 *
3250 * - If +other_hash+ does not have key +old_key+,
3251 * calls the block with +old_key+ and takes its return value as +new_key+;
3252 * sets <tt>new_hash[new_key] = value</tt>;
3253 * a duplicate key overwrites:
3254 *
3255 * h = {foo: 0, bar: 1, baz: 2}
3256 * h.transform_keys(baz: :BAZ) {|key| key.to_s.reverse }
3257 * # => {"oof" => 0, "rab" => 1, BAZ: 2}
3258 * h.transform_keys(baz: :BAZ) {|key| 'ook' }
3259 * # => {"ook" => 1, BAZ: 2}
3260 *
3261 * With no argument and no block given, returns a new Enumerator.
3262 *
3263 * Related: see {Methods for Transforming Keys and Values}[rdoc-ref:Hash@Methods+for+Transforming+Keys+and+Values].
3264 */
3265static VALUE
3266rb_hash_transform_keys(int argc, VALUE *argv, VALUE hash)
3267{
3268 VALUE result;
3269 struct transform_keys_args transarg = {0};
3270
3271 argc = rb_check_arity(argc, 0, 1);
3272 if (argc > 0) {
3273 transarg.trans = to_hash(argv[0]);
3274 transarg.block_given = rb_block_given_p();
3275 }
3276 else {
3277 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3278 }
3279 result = rb_hash_new();
3280 if (!RHASH_EMPTY_P(hash)) {
3281 if (transarg.trans) {
3282 transarg.result = result;
3283 rb_hash_foreach(hash, transform_keys_hash_i, (VALUE)&transarg);
3284 }
3285 else {
3286 rb_hash_foreach(hash, transform_keys_i, result);
3287 }
3288 }
3289
3290 return result;
3291}
3292
3293static int flatten_i(VALUE key, VALUE val, VALUE ary);
3294
3295/*
3296 * call-seq:
3297 * transform_keys! {|old_key| ... } -> self
3298 * transform_keys!(other_hash) -> self
3299 * transform_keys!(other_hash) {|old_key| ...} -> self
3300 * transform_keys! -> new_enumerator
3301 *
3302 * With an argument, a block, or both given,
3303 * derives keys from the argument, the block, and +self+;
3304 * all, some, or none of the keys in +self+ may be changed.
3305 *
3306 * With a block given and no argument,
3307 * derives keys only from the block;
3308 * all, some, or none of the keys in +self+ may be changed.
3309 *
3310 * For each key/value pair <tt>old_key/value</tt> in +self+, calls the block with +old_key+;
3311 * the block's return value becomes +new_key+;
3312 * removes the entry for +old_key+: <tt>self.delete(old_key)</tt>;
3313 * sets <tt>self[new_key] = value</tt>;
3314 * a duplicate key overwrites:
3315 *
3316 * h = {foo: 0, bar: 1, baz: 2}
3317 * h.transform_keys! {|old_key| old_key.to_s }
3318 * # => {"foo" => 0, "bar" => 1, "baz" => 2}
3319 * h = {foo: 0, bar: 1, baz: 2}
3320 * h.transform_keys! {|old_key| 'xxx' }
3321 * # => {"xxx" => 2}
3322 *
3323 * With argument +other_hash+ given and no block,
3324 * derives keys for +self+ from +other_hash+ and +self+;
3325 * all, some, or none of the keys in +self+ may be changed.
3326 *
3327 * For each key/value pair <tt>old_key/old_value</tt> in +self+,
3328 * looks for key +old_key+ in +other_hash+:
3329 *
3330 * - If +old_key+ is found, takes value <tt>other_hash[old_key]</tt> as +new_key+;
3331 * removes the entry for +old_key+: <tt>self.delete(old_key)</tt>;
3332 * sets <tt>self[new_key] = value</tt>;
3333 * a duplicate key overwrites:
3334 *
3335 * h = {foo: 0, bar: 1, baz: 2}
3336 * h.transform_keys!(baz: :BAZ, bar: :BAR, foo: :FOO)
3337 * # => {FOO: 0, BAR: 1, BAZ: 2}
3338 * h = {foo: 0, bar: 1, baz: 2}
3339 * h.transform_keys!(baz: :FOO, bar: :FOO, foo: :FOO)
3340 * # => {FOO: 2}
3341 *
3342 * - If +old_key+ is not found, does nothing:
3343 *
3344 * h = {foo: 0, bar: 1, baz: 2}
3345 * h.transform_keys!({})
3346 * # => {foo: 0, bar: 1, baz: 2}
3347 * h.transform_keys!(baz: :foo)
3348 * # => {foo: 2, bar: 1}
3349 *
3350 * Unused keys in +other_hash+ are ignored:
3351 *
3352 * h = {foo: 0, bar: 1, baz: 2}
3353 * h.transform_keys!(bat: 3)
3354 * # => {foo: 0, bar: 1, baz: 2}
3355 *
3356 * With both argument +other_hash+ and a block given,
3357 * derives keys from +other_hash+, the block, and +self+;
3358 * all, some, or none of the keys in +self+ may be changed.
3359 *
3360 * For each pair +old_key+ and +value+ in +self+:
3361 *
3362 * - If +other_hash+ has key +old_key+ (with value +new_key+),
3363 * does not call the block for that key;
3364 * removes the entry for +old_key+: <tt>self.delete(old_key)</tt>;
3365 * sets <tt>self[new_key] = value</tt>;
3366 * a duplicate key overwrites:
3367 *
3368 * h = {foo: 0, bar: 1, baz: 2}
3369 * h.transform_keys!(baz: :BAZ, bar: :BAR, foo: :FOO) {|key| fail 'Not called' }
3370 * # => {FOO: 0, BAR: 1, BAZ: 2}
3371 *
3372 * - If +other_hash+ does not have key +old_key+,
3373 * calls the block with +old_key+ and takes its return value as +new_key+;
3374 * removes the entry for +old_key+: <tt>self.delete(old_key)</tt>;
3375 * sets <tt>self[new_key] = value</tt>;
3376 * a duplicate key overwrites:
3377 *
3378 * h = {foo: 0, bar: 1, baz: 2}
3379 * h.transform_keys!(baz: :BAZ) {|key| key.to_s.reverse }
3380 * # => {"oof" => 0, "rab" => 1, BAZ: 2}
3381 * h = {foo: 0, bar: 1, baz: 2}
3382 * h.transform_keys!(baz: :BAZ) {|key| 'ook' }
3383 * # => {"ook" => 1, BAZ: 2}
3384 *
3385 * With no argument and no block given, returns a new Enumerator.
3386 *
3387 * Related: see {Methods for Transforming Keys and Values}[rdoc-ref:Hash@Methods+for+Transforming+Keys+and+Values].
3388 */
3389static VALUE
3390rb_hash_transform_keys_bang(int argc, VALUE *argv, VALUE hash)
3391{
3392 VALUE trans = 0;
3393 int block_given = 0;
3394
3395 argc = rb_check_arity(argc, 0, 1);
3396 if (argc > 0) {
3397 trans = to_hash(argv[0]);
3398 block_given = rb_block_given_p();
3399 }
3400 else {
3401 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3402 }
3403 rb_hash_modify_check(hash);
3404 if (!RHASH_TABLE_EMPTY_P(hash)) {
3405 long i;
3406 VALUE new_keys = hash_alloc(0);
3407 VALUE pairs = rb_ary_hidden_new(RHASH_SIZE(hash) * 2);
3408 rb_hash_foreach(hash, flatten_i, pairs);
3409 for (i = 0; i < RARRAY_LEN(pairs); i += 2) {
3410 VALUE key = RARRAY_AREF(pairs, i), new_key, val;
3411
3412 if (!trans) {
3413 new_key = rb_yield(key);
3414 }
3415 else if (!UNDEF_P(new_key = rb_hash_lookup2(trans, key, Qundef))) {
3416 /* use the transformed key */
3417 }
3418 else if (block_given) {
3419 new_key = rb_yield(key);
3420 }
3421 else {
3422 new_key = key;
3423 }
3424 val = RARRAY_AREF(pairs, i+1);
3425 if (!hash_stlike_lookup(new_keys, key, NULL)) {
3426 rb_hash_stlike_delete(hash, &key, NULL);
3427 }
3428 rb_hash_aset(hash, new_key, val);
3429 rb_hash_aset(new_keys, new_key, Qnil);
3430 }
3431 rb_ary_clear(pairs);
3432 rb_hash_clear(new_keys);
3433 }
3434 compact_after_delete(hash);
3435 return hash;
3436}
3437
3438static int
3439transform_values_foreach_func(st_data_t key, st_data_t value, st_data_t argp, int error)
3440{
3441 return ST_REPLACE;
3442}
3443
3444static int
3445transform_values_foreach_replace(st_data_t *key, st_data_t *value, st_data_t argp, int existing)
3446{
3447 VALUE new_value = rb_yield((VALUE)*value);
3448 VALUE hash = (VALUE)argp;
3449 rb_hash_modify(hash);
3450 RB_OBJ_WRITE(hash, value, new_value);
3451 return ST_CONTINUE;
3452}
3453
3454static VALUE
3455transform_values_call(VALUE hash)
3456{
3457 rb_hash_stlike_foreach_with_replace(hash, transform_values_foreach_func, transform_values_foreach_replace, hash);
3458 return hash;
3459}
3460
3461static void
3462transform_values(VALUE hash)
3463{
3464 hash_iter_lev_inc(hash);
3465 rb_ensure(transform_values_call, hash, hash_foreach_ensure, hash);
3466}
3467
3468/*
3469 * call-seq:
3470 * transform_values {|value| ... } -> new_hash
3471 * transform_values -> new_enumerator
3472 *
3473 * With a block given, returns a new hash +new_hash+;
3474 * for each pair +key+/+value+ in +self+,
3475 * calls the block with +value+ and captures its return as +new_value+;
3476 * adds to +new_hash+ the entry +key+/+new_value+:
3477 *
3478 * h = {foo: 0, bar: 1, baz: 2}
3479 * h1 = h.transform_values {|value| value * 100}
3480 * h1 # => {foo: 0, bar: 100, baz: 200}
3481 *
3482 * With no block given, returns a new Enumerator.
3483 *
3484 * Related: see {Methods for Transforming Keys and Values}[rdoc-ref:Hash@Methods+for+Transforming+Keys+and+Values].
3485 */
3486static VALUE
3487rb_hash_transform_values(VALUE hash)
3488{
3489 VALUE result;
3490
3491 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3492 result = hash_dup_with_compare_by_id(hash);
3493 SET_DEFAULT(result, Qnil);
3494
3495 if (!RHASH_EMPTY_P(hash)) {
3496 transform_values(result);
3497 compact_after_delete(result);
3498 }
3499
3500 return result;
3501}
3502
3503/*
3504 * call-seq:
3505 * transform_values! {|old_value| ... } -> self
3506 * transform_values! -> new_enumerator
3507 *
3508 *
3509 * With a block given, changes the values of +self+ as determined by the block;
3510 * returns +self+.
3511 *
3512 * For each entry +key+/+old_value+ in +self+,
3513 * calls the block with +old_value+,
3514 * captures its return value as +new_value+,
3515 * and sets <tt>self[key] = new_value</tt>:
3516 *
3517 * h = {foo: 0, bar: 1, baz: 2}
3518 * h.transform_values! {|value| value * 100} # => {foo: 0, bar: 100, baz: 200}
3519 *
3520 * With no block given, returns a new Enumerator.
3521 *
3522 * Related: see {Methods for Transforming Keys and Values}[rdoc-ref:Hash@Methods+for+Transforming+Keys+and+Values].
3523 */
3524static VALUE
3525rb_hash_transform_values_bang(VALUE hash)
3526{
3527 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3528 rb_hash_modify_check(hash);
3529
3530 if (!RHASH_TABLE_EMPTY_P(hash)) {
3531 transform_values(hash);
3532 }
3533
3534 return hash;
3535}
3536
3537static int
3538to_a_i(VALUE key, VALUE value, VALUE ary)
3539{
3540 rb_ary_push(ary, rb_assoc_new(key, value));
3541 return ST_CONTINUE;
3542}
3543
3544/*
3545 * call-seq:
3546 * to_a -> new_array
3547 *
3548 * Returns all elements of +self+ as an array of 2-element arrays;
3549 * each nested array contains a key-value pair from +self+:
3550 *
3551 * h = {foo: 0, bar: 1, baz: 2}
3552 * h.to_a # => [[:foo, 0], [:bar, 1], [:baz, 2]]
3553 *
3554 * Related: see {Methods for Converting}[rdoc-ref:Hash@Methods+for+Converting].
3555 */
3556
3557static VALUE
3558rb_hash_to_a(VALUE hash)
3559{
3560 VALUE ary;
3561
3562 ary = rb_ary_new_capa(RHASH_SIZE(hash));
3563 rb_hash_foreach(hash, to_a_i, ary);
3564
3565 return ary;
3566}
3567
3568static bool
3569symbol_key_needs_quote(VALUE str)
3570{
3571 long len = RSTRING_LEN(str);
3572 if (len == 0 || !rb_str_symname_p(str)) return true;
3573 const char *s = RSTRING_PTR(str);
3574 char first = s[0];
3575 if (first == '@' || first == '$' || first == '!') return true;
3576 if (!at_char_boundary(s, s + len - 1, RSTRING_END(str), rb_enc_get(str))) return false;
3577 switch (s[len - 1]) {
3578 case '+':
3579 case '-':
3580 case '*':
3581 case '/':
3582 case '`':
3583 case '%':
3584 case '^':
3585 case '&':
3586 case '|':
3587 case ']':
3588 case '<':
3589 case '=':
3590 case '>':
3591 case '~':
3592 case '@':
3593 return true;
3594 default:
3595 return false;
3596 }
3597}
3598
3599static int
3600inspect_i(VALUE key, VALUE value, VALUE str)
3601{
3602 VALUE str2;
3603
3604 bool is_symbol = SYMBOL_P(key);
3605 bool quote = false;
3606 if (is_symbol) {
3607 str2 = rb_sym2str(key);
3608 quote = symbol_key_needs_quote(str2);
3609 }
3610 else {
3611 str2 = rb_inspect(key);
3612 }
3613 if (RSTRING_LEN(str) > 1) {
3614 rb_str_buf_cat_ascii(str, ", ");
3615 }
3616 else {
3617 rb_enc_copy(str, str2);
3618 }
3619 if (quote) {
3621 }
3622 else {
3623 rb_str_buf_append(str, str2);
3624 }
3625
3626 rb_str_buf_cat_ascii(str, is_symbol ? ": " : " => ");
3627 str2 = rb_inspect(value);
3628 rb_str_buf_append(str, str2);
3629
3630 return ST_CONTINUE;
3631}
3632
3633static VALUE
3634inspect_hash(VALUE hash, VALUE dummy, int recur)
3635{
3636 VALUE str;
3637
3638 if (recur) return rb_usascii_str_new2("{...}");
3639 str = rb_str_buf_new2("{");
3640 rb_hash_foreach(hash, inspect_i, str);
3641 rb_str_buf_cat2(str, "}");
3642
3643 return str;
3644}
3645
3646/*
3647 * call-seq:
3648 * inspect -> new_string
3649 *
3650 * Returns a new string containing the hash entries:
3651 *
3652 * h = {foo: 0, bar: 1, baz: 2}
3653 * h.inspect # => "{foo: 0, bar: 1, baz: 2}"
3654 *
3655 * Related: see {Methods for Converting}[rdoc-ref:Hash@Methods+for+Converting].
3656 */
3657
3658static VALUE
3659rb_hash_inspect(VALUE hash)
3660{
3661 if (RHASH_EMPTY_P(hash))
3662 return rb_usascii_str_new2("{}");
3663 return rb_exec_recursive(inspect_hash, hash, 0);
3664}
3665
3666/*
3667 * call-seq:
3668 * to_hash -> self
3669 *
3670 * Returns +self+.
3671 *
3672 * Related: see {Methods for Converting}[rdoc-ref:Hash@Methods+for+Converting].
3673 */
3674static VALUE
3675rb_hash_to_hash(VALUE hash)
3676{
3677 return hash;
3678}
3679
3680VALUE
3681rb_hash_set_pair(VALUE hash, VALUE arg)
3682{
3683 VALUE pair;
3684
3685 pair = rb_check_array_type(arg);
3686 if (NIL_P(pair)) {
3687 rb_raise(rb_eTypeError, "wrong element type %s (expected array)",
3688 rb_builtin_class_name(arg));
3689 }
3690 if (RARRAY_LEN(pair) != 2) {
3691 rb_raise(rb_eArgError, "element has wrong array length (expected 2, was %ld)",
3692 RARRAY_LEN(pair));
3693 }
3694 rb_hash_aset(hash, RARRAY_AREF(pair, 0), RARRAY_AREF(pair, 1));
3695 return hash;
3696}
3697
3698static int
3699to_h_i(VALUE key, VALUE value, VALUE hash)
3700{
3701 rb_hash_set_pair(hash, rb_yield_values(2, key, value));
3702 return ST_CONTINUE;
3703}
3704
3705static VALUE
3706rb_hash_to_h_block(VALUE hash)
3707{
3708 VALUE h = rb_hash_new_with_size(RHASH_SIZE(hash));
3709 rb_hash_foreach(hash, to_h_i, h);
3710 return h;
3711}
3712
3713/*
3714 * call-seq:
3715 * to_h {|key, value| ... } -> new_hash
3716 * to_h -> self or new_hash
3717 *
3718 * With a block given, returns a new hash whose content is based on the block;
3719 * the block is called with each entry's key and value;
3720 * the block should return a 2-element array
3721 * containing the key and value to be included in the returned array:
3722 *
3723 * h = {foo: 0, bar: 1, baz: 2}
3724 * h.to_h {|key, value| [value, key] }
3725 * # => {0 => :foo, 1 => :bar, 2 => :baz}
3726 *
3727 * With no block given, returns +self+ if +self+ is an instance of +Hash+;
3728 * if +self+ is a subclass of +Hash+, returns a new hash containing the content of +self+.
3729 *
3730 * Related: see {Methods for Converting}[rdoc-ref:Hash@Methods+for+Converting].
3731 */
3732
3733static VALUE
3734rb_hash_to_h(VALUE hash)
3735{
3736 if (rb_block_given_p()) {
3737 return rb_hash_to_h_block(hash);
3738 }
3739 if (rb_obj_class(hash) != rb_cHash) {
3740 const VALUE flags = RBASIC(hash)->flags;
3741 hash = hash_dup(hash, rb_cHash, flags & RHASH_PROC_DEFAULT);
3742 }
3743 return hash;
3744}
3745
3746static int
3747keys_i(VALUE key, VALUE value, VALUE ary)
3748{
3749 rb_ary_push(ary, key);
3750 return ST_CONTINUE;
3751}
3752
3753/*
3754 * call-seq:
3755 * keys -> new_array
3756 *
3757 * Returns a new array containing all keys in +self+:
3758 *
3759 * h = {foo: 0, bar: 1, baz: 2}
3760 * h.keys # => [:foo, :bar, :baz]
3761 *
3762 * Related: see {Methods for Fetching}[rdoc-ref:Hash@Methods+for+Fetching].
3763 */
3764
3765VALUE
3766rb_hash_keys(VALUE hash)
3767{
3768 st_index_t size = RHASH_SIZE(hash);
3769 VALUE keys = rb_ary_new_capa(size);
3770
3771 if (size == 0) return keys;
3772
3773 if (ST_DATA_COMPATIBLE_P(VALUE)) {
3774 RARRAY_PTR_USE(keys, ptr, {
3775 if (RHASH_AR_TABLE_P(hash)) {
3776 size = ar_keys(hash, ptr, size);
3777 }
3778 else {
3779 st_table *table = RHASH_ST_TABLE(hash);
3780 size = st_keys(table, ptr, size);
3781 }
3782 });
3783 rb_gc_writebarrier_remember(keys);
3784 rb_ary_set_len(keys, size);
3785 }
3786 else {
3787 rb_hash_foreach(hash, keys_i, keys);
3788 }
3789
3790 return keys;
3791}
3792
3793static int
3794values_i(VALUE key, VALUE value, VALUE ary)
3795{
3796 rb_ary_push(ary, value);
3797 return ST_CONTINUE;
3798}
3799
3800/*
3801 * call-seq:
3802 * values -> new_array
3803 *
3804 * Returns a new array containing all values in +self+:
3805 *
3806 * h = {foo: 0, bar: 1, baz: 2}
3807 * h.values # => [0, 1, 2]
3808 *
3809 * Related: see {Methods for Fetching}[rdoc-ref:Hash@Methods+for+Fetching].
3810 */
3811
3812VALUE
3813rb_hash_values(VALUE hash)
3814{
3815 VALUE values;
3816 st_index_t size = RHASH_SIZE(hash);
3817
3818 values = rb_ary_new_capa(size);
3819 if (size == 0) return values;
3820
3821 if (ST_DATA_COMPATIBLE_P(VALUE)) {
3822 if (RHASH_AR_TABLE_P(hash)) {
3823 rb_gc_writebarrier_remember(values);
3824 RARRAY_PTR_USE(values, ptr, {
3825 size = ar_values(hash, ptr, size);
3826 });
3827 }
3828 else if (RHASH_ST_TABLE_P(hash)) {
3829 st_table *table = RHASH_ST_TABLE(hash);
3830 rb_gc_writebarrier_remember(values);
3831 RARRAY_PTR_USE(values, ptr, {
3832 size = st_values(table, ptr, size);
3833 });
3834 }
3835 rb_ary_set_len(values, size);
3836 }
3837 else {
3838 rb_hash_foreach(hash, values_i, values);
3839 }
3840
3841 return values;
3842}
3843
3844/*
3845 * call-seq:
3846 * include?(key) -> true or false
3847 *
3848 * Returns whether +key+ is a key in +self+:
3849 *
3850 * h = {foo: 0, bar: 1, baz: 2}
3851 * h.include?(:bar) # => true
3852 * h.include?(:BAR) # => false
3853 *
3854 * Related: {Methods for Querying}[rdoc-ref:Hash@Methods+for+Querying].
3855 */
3856
3857VALUE
3858rb_hash_has_key(VALUE hash, VALUE key)
3859{
3860 return RBOOL(hash_stlike_lookup(hash, key, NULL));
3861}
3862
3863static int
3864rb_hash_search_value(VALUE key, VALUE value, VALUE arg)
3865{
3866 VALUE *data = (VALUE *)arg;
3867
3868 if (rb_equal(value, data[1])) {
3869 data[0] = Qtrue;
3870 return ST_STOP;
3871 }
3872 return ST_CONTINUE;
3873}
3874
3875/*
3876 * call-seq:
3877 * has_value?(value) -> true or false
3878 *
3879 * Returns whether +value+ is a value in +self+.
3880 *
3881 * Related: {Methods for Querying}[rdoc-ref:Hash@Methods+for+Querying].
3882 */
3883
3884static VALUE
3885rb_hash_has_value(VALUE hash, VALUE val)
3886{
3887 VALUE data[2];
3888
3889 data[0] = Qfalse;
3890 data[1] = val;
3891 rb_hash_foreach(hash, rb_hash_search_value, (VALUE)data);
3892 return data[0];
3893}
3894
3896 VALUE result;
3897 VALUE hash;
3898 int eql;
3899};
3900
3901static int
3902eql_i(VALUE key, VALUE val1, VALUE arg)
3903{
3904 struct equal_data *data = (struct equal_data *)arg;
3905 st_data_t val2;
3906
3907 if (!hash_stlike_lookup(data->hash, key, &val2)) {
3908 data->result = Qfalse;
3909 return ST_STOP;
3910 }
3911 else {
3912 if (!(data->eql ? rb_eql(val1, (VALUE)val2) : (int)rb_equal(val1, (VALUE)val2))) {
3913 data->result = Qfalse;
3914 return ST_STOP;
3915 }
3916 return ST_CONTINUE;
3917 }
3918}
3919
3920static VALUE
3921recursive_eql(VALUE hash, VALUE dt, int recur)
3922{
3923 struct equal_data *data;
3924
3925 if (recur) return Qtrue; /* Subtle! */
3926 data = (struct equal_data*)dt;
3927 data->result = Qtrue;
3928 rb_hash_foreach(hash, eql_i, dt);
3929
3930 return data->result;
3931}
3932
3933static VALUE
3934hash_equal(VALUE hash1, VALUE hash2, int eql)
3935{
3936 struct equal_data data;
3937
3938 if (hash1 == hash2) return Qtrue;
3939 if (!RB_TYPE_P(hash2, T_HASH)) {
3940 if (!rb_respond_to(hash2, idTo_hash)) {
3941 return Qfalse;
3942 }
3943 if (eql) {
3944 if (rb_eql(hash2, hash1)) {
3945 return Qtrue;
3946 }
3947 else {
3948 return Qfalse;
3949 }
3950 }
3951 else {
3952 return rb_equal(hash2, hash1);
3953 }
3954 }
3955 if (RHASH_SIZE(hash1) != RHASH_SIZE(hash2))
3956 return Qfalse;
3957 if (!RHASH_TABLE_EMPTY_P(hash1) && !RHASH_TABLE_EMPTY_P(hash2)) {
3958 if (RHASH_TYPE(hash1) != RHASH_TYPE(hash2)) {
3959 return Qfalse;
3960 }
3961 else {
3962 data.hash = hash2;
3963 data.eql = eql;
3964 return rb_exec_recursive_paired(recursive_eql, hash1, hash2, (VALUE)&data);
3965 }
3966 }
3967
3968#if 0
3969 if (!(rb_equal(RHASH_IFNONE(hash1), RHASH_IFNONE(hash2)) &&
3970 FL_TEST(hash1, RHASH_PROC_DEFAULT) == FL_TEST(hash2, RHASH_PROC_DEFAULT)))
3971 return Qfalse;
3972#endif
3973 return Qtrue;
3974}
3975
3976/*
3977 * call-seq:
3978 * self == other -> true or false
3979 *
3980 * Returns whether all of the following are true:
3981 *
3982 * - +other+ is a +Hash+ object (or can be converted to one).
3983 * - +self+ and +other+ have the same keys (regardless of order).
3984 * - For each key +key+, <tt>self[key] == other[key]</tt>.
3985 *
3986 * Examples:
3987 *
3988 * h = {foo: 0, bar: 1}
3989 * h == {foo: 0, bar: 1} # => true # Equal entries (same order)
3990 * h == {bar: 1, foo: 0} # => true # Equal entries (different order).
3991 * h == 1 # => false # Object not a hash.
3992 * h == {} # => false # Different number of entries.
3993 * h == {foo: 0, bar: 1} # => false # Different key.
3994 * h == {foo: 0, bar: 1} # => false # Different value.
3995 *
3996 * Related: see {Methods for Comparing}[rdoc-ref:Hash@Methods+for+Comparing].
3997 */
3998
3999static VALUE
4000rb_hash_equal(VALUE hash1, VALUE hash2)
4001{
4002 return hash_equal(hash1, hash2, FALSE);
4003}
4004
4005/*
4006 * call-seq:
4007 * eql?(object) -> true or false
4008 *
4009 * Returns +true+ if all of the following are true:
4010 *
4011 * - The given +object+ is a +Hash+ object.
4012 * - +self+ and +object+ have the same keys (regardless of order).
4013 * - For each key +key+, <tt>self[key].eql?(object[key])</tt>.
4014 *
4015 * Otherwise, returns +false+.
4016 *
4017 * h1 = {foo: 0, bar: 1, baz: 2}
4018 * h2 = {foo: 0, bar: 1, baz: 2}
4019 * h1.eql? h2 # => true
4020 * h3 = {baz: 2, bar: 1, foo: 0}
4021 * h1.eql? h3 # => true
4022 *
4023 * Related: see {Methods for Querying}[rdoc-ref:Hash@Methods+for+Querying].
4024 */
4025
4026static VALUE
4027rb_hash_eql(VALUE hash1, VALUE hash2)
4028{
4029 return hash_equal(hash1, hash2, TRUE);
4030}
4031
4032static int
4033hash_i(VALUE key, VALUE val, VALUE arg)
4034{
4035 st_index_t *hval = (st_index_t *)arg;
4036 st_index_t hdata[2];
4037
4038 hdata[0] = rb_hash(key);
4039 hdata[1] = rb_hash(val);
4040 *hval ^= st_hash(hdata, sizeof(hdata), 0);
4041 return ST_CONTINUE;
4042}
4043
4044/*
4045 * call-seq:
4046 * hash -> an_integer
4047 *
4048 * Returns the integer hash-code for the hash.
4049 *
4050 * Two hashes have the same hash-code if their content is the same
4051 * (regardless of order):
4052 *
4053 * h1 = {foo: 0, bar: 1, baz: 2}
4054 * h2 = {baz: 2, bar: 1, foo: 0}
4055 * h2.hash == h1.hash # => true
4056 * h2.eql? h1 # => true
4057 *
4058 * Related: see {Methods for Querying}[rdoc-ref:Hash@Methods+for+Querying].
4059 */
4060
4061static VALUE
4062rb_hash_hash(VALUE hash)
4063{
4064 st_index_t size = RHASH_SIZE(hash);
4065 st_index_t hval = rb_hash_start(size);
4066 hval = rb_hash_uint(hval, (st_index_t)rb_hash_hash);
4067 if (size) {
4068 rb_hash_foreach(hash, hash_i, (VALUE)&hval);
4069 }
4070 hval = rb_hash_end(hval);
4071 return ST2FIX(hval);
4072}
4073
4074static int
4075rb_hash_invert_i(VALUE key, VALUE value, VALUE hash)
4076{
4077 rb_hash_aset(hash, value, key);
4078 return ST_CONTINUE;
4079}
4080
4081/*
4082 * call-seq:
4083 * invert -> new_hash
4084 *
4085 * Returns a new hash with each key-value pair inverted:
4086 *
4087 * h = {foo: 0, bar: 1, baz: 2}
4088 * h1 = h.invert
4089 * h1 # => {0=>:foo, 1=>:bar, 2=>:baz}
4090 *
4091 * Overwrites any repeated new keys
4092 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
4093 *
4094 * h = {foo: 0, bar: 0, baz: 0}
4095 * h.invert # => {0=>:baz}
4096 *
4097 * Related: see {Methods for Transforming Keys and Values}[rdoc-ref:Hash@Methods+for+Transforming+Keys+and+Values].
4098 */
4099
4100static VALUE
4101rb_hash_invert(VALUE hash)
4102{
4103 VALUE h = rb_hash_new_with_size(RHASH_SIZE(hash));
4104
4105 rb_hash_foreach(hash, rb_hash_invert_i, h);
4106 return h;
4107}
4108
4109static int
4110rb_hash_update_i(VALUE key, VALUE value, VALUE hash)
4111{
4112 rb_hash_aset(hash, key, value);
4113 return ST_CONTINUE;
4114}
4115
4117 VALUE hash, newvalue, *argv;
4118 int argc;
4119 bool block_given;
4120 bool iterating;
4121};
4122
4123static int
4124rb_hash_update_block_callback(st_data_t *key, st_data_t *value, struct update_arg *arg, int existing)
4125{
4126 VALUE k = (VALUE)*key, v = (VALUE)*value;
4127 struct update_call_args *ua = (void *)arg->arg;
4128 VALUE newvalue = ua->newvalue, hash = arg->hash;
4129
4130 if (existing) {
4131 hash_iter_lev_inc(hash);
4132 ua->iterating = true;
4133 newvalue = rb_yield_values(3, k, v, newvalue);
4134 hash_iter_lev_dec(hash);
4135 ua->iterating = false;
4136 }
4137 else if (RHASH_STRING_KEY_P(hash, k) && !RB_OBJ_FROZEN(k)) {
4138 *key = (st_data_t)rb_hash_key_str(k);
4139 }
4140 *value = (st_data_t)newvalue;
4141 return ST_CONTINUE;
4142}
4143
4144NOINSERT_UPDATE_CALLBACK(rb_hash_update_block_callback)
4145
4146static int
4147rb_hash_update_block_i(VALUE key, VALUE value, VALUE args)
4148{
4149 struct update_call_args *ua = (void *)args;
4150 ua->newvalue = value;
4151 RHASH_UPDATE(ua->hash, key, rb_hash_update_block_callback, args);
4152 return ST_CONTINUE;
4153}
4154
4155static VALUE
4156rb_hash_update_call(VALUE args)
4157{
4158 struct update_call_args *arg = (void *)args;
4159
4160 for (int i = 0; i < arg->argc; i++){
4161 VALUE hash = to_hash(arg->argv[i]);
4162 if (arg->block_given) {
4163 rb_hash_foreach(hash, rb_hash_update_block_i, args);
4164 }
4165 else {
4166 rb_hash_foreach(hash, rb_hash_update_i, arg->hash);
4167 }
4168 }
4169 return arg->hash;
4170}
4171
4172static VALUE
4173rb_hash_update_ensure(VALUE args)
4174{
4175 struct update_call_args *ua = (void *)args;
4176 if (ua->iterating) hash_iter_lev_dec(ua->hash);
4177 return Qnil;
4178}
4179
4180/*
4181 * call-seq:
4182 * update(*other_hashes) -> self
4183 * update(*other_hashes) { |key, old_value, new_value| ... } -> self
4184 *
4185 * Updates values and/or adds entries to +self+; returns +self+.
4186 *
4187 * Each argument +other_hash+ in +other_hashes+ must be a hash.
4188 *
4189 * With no block given, for each successive entry +key+/+new_value+ in each successive +other_hash+:
4190 *
4191 * - If +key+ is in +self+, sets <tt>self[key] = new_value</tt>, whose position is unchanged:
4192 *
4193 * h0 = {foo: 0, bar: 1, baz: 2}
4194 * h1 = {bar: 3, foo: -1}
4195 * h0.update(h1) # => {foo: -1, bar: 3, baz: 2}
4196 *
4197 * - If +key+ is not in +self+, adds the entry at the end of +self+:
4198 *
4199 * h = {foo: 0, bar: 1, baz: 2}
4200 * h.update({bam: 3, bah: 4}) # => {foo: 0, bar: 1, baz: 2, bam: 3, bah: 4}
4201 *
4202 * With a block given, for each successive entry +key+/+new_value+ in each successive +other_hash+:
4203 *
4204 * - If +key+ is in +self+, fetches +old_value+ from <tt>self[key]</tt>,
4205 * calls the block with +key+, +old_value+, and +new_value+,
4206 * and sets <tt>self[key] = new_value</tt>, whose position is unchanged :
4207 *
4208 * season = {AB: 75, H: 20, HR: 3, SO: 17, W: 11, HBP: 3}
4209 * today = {AB: 3, H: 1, W: 1}
4210 * yesterday = {AB: 4, H: 2, HR: 1}
4211 * season.update(yesterday, today) {|key, old_value, new_value| old_value + new_value }
4212 * # => {AB: 82, H: 23, HR: 4, SO: 17, W: 12, HBP: 3}
4213 *
4214 * - If +key+ is not in +self+, adds the entry at the end of +self+:
4215 *
4216 * h = {foo: 0, bar: 1, baz: 2}
4217 * h.update({bat: 3}) { fail 'Cannot happen' }
4218 * # => {foo: 0, bar: 1, baz: 2, bat: 3}
4219 *
4220 * Related: see {Methods for Assigning}[rdoc-ref:Hash@Methods+for+Assigning].
4221 */
4222
4223static VALUE
4224rb_hash_update(int argc, VALUE *argv, VALUE self)
4225{
4226 struct update_call_args args = {
4227 .hash = self,
4228 .argv = argv,
4229 .argc = argc,
4230 .block_given = rb_block_given_p(),
4231 .iterating = false,
4232 };
4233 VALUE arg = (VALUE)&args;
4234
4235 rb_hash_modify(self);
4236 return rb_ensure(rb_hash_update_call, arg, rb_hash_update_ensure, arg);
4237}
4238
4240 VALUE hash;
4241 VALUE value;
4242 rb_hash_update_func *func;
4243};
4244
4245static int
4246rb_hash_update_func_callback(st_data_t *key, st_data_t *value, struct update_arg *arg, int existing)
4247{
4248 struct update_func_arg *uf_arg = (struct update_func_arg *)arg->arg;
4249 VALUE newvalue = uf_arg->value;
4250
4251 if (existing) {
4252 newvalue = (*uf_arg->func)((VALUE)*key, (VALUE)*value, newvalue);
4253 }
4254 *value = newvalue;
4255 return ST_CONTINUE;
4256}
4257
4258NOINSERT_UPDATE_CALLBACK(rb_hash_update_func_callback)
4259
4260static int
4261rb_hash_update_func_i(VALUE key, VALUE value, VALUE arg0)
4262{
4263 struct update_func_arg *arg = (struct update_func_arg *)arg0;
4264 VALUE hash = arg->hash;
4265
4266 arg->value = value;
4267 RHASH_UPDATE(hash, key, rb_hash_update_func_callback, (VALUE)arg);
4268 return ST_CONTINUE;
4269}
4270
4271VALUE
4272rb_hash_update_by(VALUE hash1, VALUE hash2, rb_hash_update_func *func)
4273{
4274 rb_hash_modify(hash1);
4275 hash2 = to_hash(hash2);
4276 if (func) {
4277 struct update_func_arg arg;
4278 arg.hash = hash1;
4279 arg.func = func;
4280 rb_hash_foreach(hash2, rb_hash_update_func_i, (VALUE)&arg);
4281 }
4282 else {
4283 rb_hash_foreach(hash2, rb_hash_update_i, hash1);
4284 }
4285 return hash1;
4286}
4287
4288/*
4289 * call-seq:
4290 * merge(*other_hashes) -> new_hash
4291 * merge(*other_hashes) { |key, old_value, new_value| ... } -> new_hash
4292 *
4293 * Each argument +other_hash+ in +other_hashes+ must be a hash.
4294 *
4295 * With arguments +other_hashes+ given and no block,
4296 * returns the new hash formed by merging each successive +other_hash+
4297 * into a copy of +self+;
4298 * returns that copy;
4299 * for each successive entry in +other_hash+:
4300 *
4301 * - For a new key, the entry is added at the end of +self+.
4302 * - For duplicate key, the entry overwrites the entry in +self+,
4303 * whose position is unchanged.
4304 *
4305 * Example:
4306 *
4307 * h = {foo: 0, bar: 1, baz: 2}
4308 * h1 = {bat: 3, bar: 4}
4309 * h2 = {bam: 5, bat:6}
4310 * h.merge(h1, h2) # => {foo: 0, bar: 4, baz: 2, bat: 6, bam: 5}
4311 *
4312 * With arguments +other_hashes+ and a block given, behaves as above
4313 * except that for a duplicate key
4314 * the overwriting entry takes it value not from the entry in +other_hash+,
4315 * but instead from the block:
4316 *
4317 * - The block is called with the duplicate key and the values
4318 * from both +self+ and +other_hash+.
4319 * - The block's return value becomes the new value for the entry in +self+.
4320 *
4321 * Example:
4322 *
4323 * h = {foo: 0, bar: 1, baz: 2}
4324 * h1 = {bat: 3, bar: 4}
4325 * h2 = {bam: 5, bat:6}
4326 * h.merge(h1, h2) { |key, old_value, new_value| old_value + new_value }
4327 * # => {foo: 0, bar: 5, baz: 2, bat: 9, bam: 5}
4328 *
4329 * With no arguments, returns a copy of +self+; the block, if given, is ignored.
4330 *
4331 * Related: see {Methods for Assigning}[rdoc-ref:Hash@Methods+for+Assigning].
4332 */
4333
4334static VALUE
4335rb_hash_merge(int argc, VALUE *argv, VALUE self)
4336{
4337 return rb_hash_update(argc, argv, copy_compare_by_id(rb_hash_dup(self), self));
4338}
4339
4340static int
4341assoc_cmp(VALUE a, VALUE b)
4342{
4343 return !RTEST(rb_equal(a, b));
4344}
4345
4347 st_table *tbl;
4348 st_data_t key;
4349};
4350
4351static VALUE
4352assoc_lookup(VALUE arg)
4353{
4354 struct assoc_arg *p = (struct assoc_arg*)arg;
4355 st_data_t data;
4356 if (st_lookup(p->tbl, p->key, &data)) return (VALUE)data;
4357 return Qundef;
4358}
4359
4360static int
4361assoc_i(VALUE key, VALUE val, VALUE arg)
4362{
4363 VALUE *args = (VALUE *)arg;
4364
4365 if (RTEST(rb_equal(args[0], key))) {
4366 args[1] = rb_assoc_new(key, val);
4367 return ST_STOP;
4368 }
4369 return ST_CONTINUE;
4370}
4371
4372/*
4373 * call-seq:
4374 * assoc(key) -> entry or nil
4375 *
4376 * If the given +key+ is found, returns its entry as a 2-element array
4377 * containing that key and its value:
4378 *
4379 * h = {foo: 0, bar: 1, baz: 2}
4380 * h.assoc(:bar) # => [:bar, 1]
4381 *
4382 * Returns +nil+ if the key is not found.
4383 *
4384 * Related: see {Methods for Fetching}[rdoc-ref:Hash@Methods+for+Fetching].
4385 */
4386
4387static VALUE
4388rb_hash_assoc(VALUE hash, VALUE key)
4389{
4390 VALUE args[2];
4391
4392 if (RHASH_EMPTY_P(hash)) return Qnil;
4393
4394 if (RHASH_ST_TABLE_P(hash) && !RHASH_IDENTHASH_P(hash)) {
4395 VALUE value = Qundef;
4396 st_table assoctable = *RHASH_ST_TABLE(hash);
4397 assoctable.type = &(struct st_hash_type){
4398 .compare = assoc_cmp,
4399 .hash = assoctable.type->hash,
4400 };
4401 VALUE arg = (VALUE)&(struct assoc_arg){
4402 .tbl = &assoctable,
4403 .key = (st_data_t)key,
4404 };
4405
4406 if (RB_OBJ_FROZEN(hash)) {
4407 value = assoc_lookup(arg);
4408 }
4409 else {
4410 hash_iter_lev_inc(hash);
4411 value = rb_ensure(assoc_lookup, arg, hash_foreach_ensure, hash);
4412 }
4413 hash_verify(hash);
4414 if (!UNDEF_P(value)) return rb_assoc_new(key, value);
4415 }
4416
4417 args[0] = key;
4418 args[1] = Qnil;
4419 rb_hash_foreach(hash, assoc_i, (VALUE)args);
4420 return args[1];
4421}
4422
4423static int
4424rassoc_i(VALUE key, VALUE val, VALUE arg)
4425{
4426 VALUE *args = (VALUE *)arg;
4427
4428 if (RTEST(rb_equal(args[0], val))) {
4429 args[1] = rb_assoc_new(key, val);
4430 return ST_STOP;
4431 }
4432 return ST_CONTINUE;
4433}
4434
4435/*
4436 * call-seq:
4437 * rassoc(value) -> new_array or nil
4438 *
4439 * Searches +self+ for the first entry whose value is <tt>==</tt> to the given +value+;
4440 * see {Entry Order}[rdoc-ref:Hash@Entry+Order].
4441 *
4442 * If the entry is found, returns its key and value as a 2-element array;
4443 * returns +nil+ if not found:
4444 *
4445 * h = {foo: 0, bar: 1, baz: 1}
4446 * h.rassoc(1) # => [:bar, 1]
4447 *
4448 * Related: see {Methods for Fetching}[rdoc-ref:Hash@Methods+for+Fetching].
4449 */
4450
4451static VALUE
4452rb_hash_rassoc(VALUE hash, VALUE obj)
4453{
4454 VALUE args[2];
4455
4456 args[0] = obj;
4457 args[1] = Qnil;
4458 rb_hash_foreach(hash, rassoc_i, (VALUE)args);
4459 return args[1];
4460}
4461
4462static int
4463flatten_i(VALUE key, VALUE val, VALUE ary)
4464{
4465 VALUE pair[2];
4466
4467 pair[0] = key;
4468 pair[1] = val;
4469 rb_ary_cat(ary, pair, 2);
4470
4471 return ST_CONTINUE;
4472}
4473
4474/*
4475 * call-seq:
4476 * flatten(depth = 1) -> new_array
4477 *
4478 * With positive integer +depth+,
4479 * returns a new array that is a recursive flattening of +self+ to the given +depth+.
4480 *
4481 * At each level of recursion:
4482 *
4483 * - Each element whose value is an array is "flattened" (that is, replaced by its individual array elements);
4484 * see Array#flatten.
4485 * - Each element whose value is not an array is unchanged.
4486 * even if the value is an object that has instance method flatten (such as a hash).
4487 *
4488 * Examples; note that entry <tt>foo: {bar: 1, baz: 2}</tt> is never flattened.
4489 *
4490 * h = {foo: {bar: 1, baz: 2}, bat: [:bam, [:bap, [:bah]]]}
4491 * h.flatten(1) # => [:foo, {bar: 1, baz: 2}, :bat, [:bam, [:bap, [:bah]]]]
4492 * h.flatten(2) # => [:foo, {bar: 1, baz: 2}, :bat, :bam, [:bap, [:bah]]]
4493 * h.flatten(3) # => [:foo, {bar: 1, baz: 2}, :bat, :bam, :bap, [:bah]]
4494 * h.flatten(4) # => [:foo, {bar: 1, baz: 2}, :bat, :bam, :bap, :bah]
4495 * h.flatten(5) # => [:foo, {bar: 1, baz: 2}, :bat, :bam, :bap, :bah]
4496 *
4497 * With negative integer +depth+,
4498 * flattens all levels:
4499 *
4500 * h.flatten(-1) # => [:foo, {bar: 1, baz: 2}, :bat, :bam, :bap, :bah]
4501 *
4502 * With +depth+ zero,
4503 * returns the equivalent of #to_a:
4504 *
4505 * h.flatten(0) # => [[:foo, {bar: 1, baz: 2}], [:bat, [:bam, [:bap, [:bah]]]]]
4506 *
4507 * Related: see {Methods for Converting}[rdoc-ref:Hash@Methods+for+Converting].
4508 */
4509
4510static VALUE
4511rb_hash_flatten(int argc, VALUE *argv, VALUE hash)
4512{
4513 VALUE ary;
4514
4515 rb_check_arity(argc, 0, 1);
4516
4517 if (argc) {
4518 int level = NUM2INT(argv[0]);
4519
4520 if (level == 0) return rb_hash_to_a(hash);
4521
4522 ary = rb_ary_new_capa(RHASH_SIZE(hash) * 2);
4523 rb_hash_foreach(hash, flatten_i, ary);
4524 level--;
4525
4526 if (level > 0) {
4527 VALUE ary_flatten_level = INT2FIX(level);
4528 rb_funcallv(ary, id_flatten_bang, 1, &ary_flatten_level);
4529 }
4530 else if (level < 0) {
4531 /* flatten recursively */
4532 rb_funcallv(ary, id_flatten_bang, 0, 0);
4533 }
4534 }
4535 else {
4536 ary = rb_ary_new_capa(RHASH_SIZE(hash) * 2);
4537 rb_hash_foreach(hash, flatten_i, ary);
4538 }
4539
4540 return ary;
4541}
4542
4543static int
4544delete_if_nil(VALUE key, VALUE value, VALUE hash)
4545{
4546 if (NIL_P(value)) {
4547 return ST_DELETE;
4548 }
4549 return ST_CONTINUE;
4550}
4551
4552/*
4553 * call-seq:
4554 * compact -> new_hash
4555 *
4556 * Returns a copy of +self+ with all +nil+-valued entries removed:
4557 *
4558 * h = {foo: 0, bar: nil, baz: 2, bat: nil}
4559 * h.compact # => {foo: 0, baz: 2}
4560 *
4561 * Related: see {Methods for Deleting}[rdoc-ref:Hash@Methods+for+Deleting].
4562 */
4563
4564static VALUE
4565rb_hash_compact(VALUE hash)
4566{
4567 VALUE result = rb_hash_dup(hash);
4568 if (!RHASH_EMPTY_P(hash)) {
4569 rb_hash_foreach(result, delete_if_nil, result);
4570 compact_after_delete(result);
4571 }
4572 else if (rb_hash_compare_by_id_p(hash)) {
4573 result = rb_hash_compare_by_id(result);
4574 }
4575 return result;
4576}
4577
4578/*
4579 * call-seq:
4580 * compact! -> self or nil
4581 *
4582 * If +self+ contains any +nil+-valued entries,
4583 * returns +self+ with all +nil+-valued entries removed;
4584 * returns +nil+ otherwise:
4585 *
4586 * h = {foo: 0, bar: nil, baz: 2, bat: nil}
4587 * h.compact!
4588 * h # => {foo: 0, baz: 2}
4589 * h.compact! # => nil
4590 *
4591 * Related: see {Methods for Deleting}[rdoc-ref:Hash@Methods+for+Deleting].
4592 */
4593
4594static VALUE
4595rb_hash_compact_bang(VALUE hash)
4596{
4597 st_index_t n;
4598 rb_hash_modify_check(hash);
4599 n = RHASH_SIZE(hash);
4600 if (n) {
4601 rb_hash_foreach(hash, delete_if_nil, hash);
4602 if (n != RHASH_SIZE(hash))
4603 return hash;
4604 }
4605 return Qnil;
4606}
4607
4608/*
4609 * call-seq:
4610 * compare_by_identity -> self
4611 *
4612 * Sets +self+ to compare keys using _identity_ (rather than mere _equality_);
4613 * returns +self+:
4614 *
4615 * By default, two keys are considered to be the same key
4616 * if and only if they are _equal_ objects (per method #eql?):
4617 *
4618 * h = {}
4619 * h['x'] = 0
4620 * h['x'] = 1 # Overwrites.
4621 * h # => {"x"=>1}
4622 *
4623 * When this method has been called, two keys are considered to be the same key
4624 * if and only if they are the _same_ object:
4625 *
4626 * h.compare_by_identity
4627 * h['x'] = 2 # Does not overwrite.
4628 * h # => {"x"=>1, "x"=>2}
4629 *
4630 * Related: #compare_by_identity?;
4631 * see also {Methods for Comparing}[rdoc-ref:Hash@Methods+for+Comparing].
4632 */
4633
4634VALUE
4635rb_hash_compare_by_id(VALUE hash)
4636{
4637 VALUE tmp;
4638 st_table *identtable;
4639
4640 if (rb_hash_compare_by_id_p(hash)) return hash;
4641
4642 rb_hash_modify_check(hash);
4643 if (hash_iterating_p(hash)) {
4644 rb_raise(rb_eRuntimeError, "compare_by_identity during iteration");
4645 }
4646
4647 if (RHASH_TABLE_EMPTY_P(hash)) {
4648 // Fast path: There's nothing to rehash, so we don't need a `tmp` table.
4649 // We're most likely an AR table, so this will need an allocation.
4650 ar_force_convert_table(hash, __FILE__, __LINE__);
4651 HASH_ASSERT(RHASH_ST_TABLE_P(hash));
4652
4653 RHASH_ST_TABLE(hash)->type = &identhash;
4654 }
4655 else {
4656 // Slow path: Need to rehash the members of `self` into a new
4657 // `tmp` table using the new `identhash` compare/hash functions.
4658 tmp = hash_alloc(0);
4659 hash_st_table_init(tmp, &identhash, RHASH_SIZE(hash));
4660 identtable = RHASH_ST_TABLE(tmp);
4661
4662 rb_hash_foreach(hash, rb_hash_rehash_i, (VALUE)tmp);
4663 rb_hash_free(hash);
4664
4665 // We know for sure `identtable` is an st table,
4666 // so we can skip `ar_force_convert_table` here.
4667 RHASH_ST_TABLE_SET(hash, identtable);
4668 RHASH_ST_CLEAR(tmp);
4669 }
4670
4671 rb_gc_register_pinning_obj(hash);
4672
4673 return hash;
4674}
4675
4676/*
4677 * call-seq:
4678 * compare_by_identity? -> true or false
4679 *
4680 * Returns whether #compare_by_identity has been called:
4681 *
4682 * h = {}
4683 * h.compare_by_identity? # => false
4684 * h.compare_by_identity
4685 * h.compare_by_identity? # => true
4686 *
4687 * Related: #compare_by_identity;
4688 * see also {Methods for Comparing}[rdoc-ref:Hash@Methods+for+Comparing].
4689 */
4690
4691VALUE
4692rb_hash_compare_by_id_p(VALUE hash)
4693{
4694 return RBOOL(RHASH_IDENTHASH_P(hash));
4695}
4696
4697VALUE
4698rb_ident_hash_new(void)
4699{
4700 VALUE hash = rb_hash_new();
4701 hash_st_table_init(hash, &identhash, 0);
4702 rb_gc_register_pinning_obj(hash);
4703 return hash;
4704}
4705
4706VALUE
4707rb_ident_hash_new_with_size(st_index_t size)
4708{
4709 VALUE hash = rb_hash_new();
4710 hash_st_table_init(hash, &identhash, size);
4711 rb_gc_register_pinning_obj(hash);
4712 return hash;
4713}
4714
4715st_table *
4716rb_init_identtable(void)
4717{
4718 return st_init_table(&identhash);
4719}
4720
4721static int
4722any_p_i(VALUE key, VALUE value, VALUE arg)
4723{
4724 VALUE ret = rb_yield(rb_assoc_new(key, value));
4725 if (RTEST(ret)) {
4726 *(VALUE *)arg = Qtrue;
4727 return ST_STOP;
4728 }
4729 return ST_CONTINUE;
4730}
4731
4732static int
4733any_p_i_fast(VALUE key, VALUE value, VALUE arg)
4734{
4735 VALUE ret = rb_yield_values(2, key, value);
4736 if (RTEST(ret)) {
4737 *(VALUE *)arg = Qtrue;
4738 return ST_STOP;
4739 }
4740 return ST_CONTINUE;
4741}
4742
4743static int
4744any_p_i_pattern(VALUE key, VALUE value, VALUE arg)
4745{
4746 VALUE ret = rb_funcall(((VALUE *)arg)[1], idEqq, 1, rb_assoc_new(key, value));
4747 if (RTEST(ret)) {
4748 *(VALUE *)arg = Qtrue;
4749 return ST_STOP;
4750 }
4751 return ST_CONTINUE;
4752}
4753
4754/*
4755 * call-seq:
4756 * any? -> true or false
4757 * any?(entry) -> true or false
4758 * any? {|key, value| ... } -> true or false
4759 *
4760 * Returns +true+ if any element satisfies a given criterion;
4761 * +false+ otherwise.
4762 *
4763 * If +self+ has no element, returns +false+ and argument or block are not used;
4764 * otherwise behaves as below.
4765 *
4766 * With no argument and no block,
4767 * returns +true+ if +self+ is non-empty, +false+ otherwise.
4768 *
4769 * With argument +entry+ and no block,
4770 * returns +true+ if for any key +key+
4771 * <tt>self.assoc(key) == entry</tt>, +false+ otherwise:
4772 *
4773 * h = {foo: 0, bar: 1, baz: 2}
4774 * h.assoc(:bar) # => [:bar, 1]
4775 * h.any?([:bar, 1]) # => true
4776 * h.any?([:bar, 0]) # => false
4777 *
4778 * With no argument and a block given,
4779 * calls the block with each key-value pair;
4780 * returns +true+ if the block returns a truthy value,
4781 * +false+ otherwise:
4782 *
4783 * h = {foo: 0, bar: 1, baz: 2}
4784 * h.any? {|key, value| value < 3 } # => true
4785 * h.any? {|key, value| value > 3 } # => false
4786 *
4787 * With both argument +entry+ and a block given,
4788 * issues a warning and ignores the block.
4789 *
4790 * Related: Enumerable#any? (which this method overrides);
4791 * see also {Methods for Fetching}[rdoc-ref:Hash@Methods+for+Fetching].
4792 */
4793
4794static VALUE
4795rb_hash_any_p(int argc, VALUE *argv, VALUE hash)
4796{
4797 VALUE args[2];
4798 args[0] = Qfalse;
4799
4800 rb_check_arity(argc, 0, 1);
4801 if (RHASH_EMPTY_P(hash)) return Qfalse;
4802 if (argc) {
4803 if (rb_block_given_p()) {
4804 rb_warn("given block not used");
4805 }
4806 args[1] = argv[0];
4807
4808 rb_hash_foreach(hash, any_p_i_pattern, (VALUE)args);
4809 }
4810 else {
4811 if (!rb_block_given_p()) {
4812 /* yields pairs, never false */
4813 return Qtrue;
4814 }
4815 if (rb_block_pair_yield_optimizable())
4816 rb_hash_foreach(hash, any_p_i_fast, (VALUE)args);
4817 else
4818 rb_hash_foreach(hash, any_p_i, (VALUE)args);
4819 }
4820 return args[0];
4821}
4822
4823/*
4824 * call-seq:
4825 * dig(key, *identifiers) -> object
4826 *
4827 * Finds and returns an object found in nested objects,
4828 * as specified by +key+ and +identifiers+.
4829 *
4830 * The nested objects may be instances of various classes.
4831 * See {Dig Methods}[rdoc-ref:dig_methods.rdoc].
4832 *
4833 * Nested hashes:
4834 *
4835 * h = {foo: {bar: {baz: 2}}}
4836 * h.dig(:foo) # => {bar: {baz: 2}}
4837 * h.dig(:foo, :bar) # => {baz: 2}
4838 * h.dig(:foo, :bar, :baz) # => 2
4839 * h.dig(:foo, :bar, :BAZ) # => nil
4840 *
4841 * Nested hashes and arrays:
4842 *
4843 * h = {foo: {bar: [:a, :b, :c]}}
4844 * h.dig(:foo, :bar, 2) # => :c
4845 *
4846 * If no such object is found,
4847 * returns the {hash default}[rdoc-ref:Hash@Hash+Default]:
4848 *
4849 * h = {foo: {bar: [:a, :b, :c]}}
4850 * h.dig(:hello) # => nil
4851 * h.default_proc = -> (hash, _key) { hash }
4852 * h.dig(:hello, :world)
4853 * # => {foo: {bar: [:a, :b, :c]}}
4854 *
4855 * Related: {Methods for Fetching}[rdoc-ref:Hash@Methods+for+Fetching].
4856 */
4857
4858static VALUE
4859rb_hash_dig(int argc, VALUE *argv, VALUE self)
4860{
4862 self = rb_hash_aref(self, *argv);
4863 if (!--argc) return self;
4864 ++argv;
4865 return rb_obj_dig(argc, argv, self, Qnil);
4866}
4867
4868static int
4869hash_le_i(VALUE key, VALUE value, VALUE arg)
4870{
4871 VALUE *args = (VALUE *)arg;
4872 VALUE v = rb_hash_lookup2(args[0], key, Qundef);
4873 if (!UNDEF_P(v) && rb_equal(value, v)) return ST_CONTINUE;
4874 args[1] = Qfalse;
4875 return ST_STOP;
4876}
4877
4878static VALUE
4879hash_le(VALUE hash1, VALUE hash2)
4880{
4881 VALUE args[2];
4882 args[0] = hash2;
4883 args[1] = Qtrue;
4884 rb_hash_foreach(hash1, hash_le_i, (VALUE)args);
4885 return args[1];
4886}
4887
4888/*
4889 * call-seq:
4890 * self <= other -> true or false
4891 *
4892 * Returns whether the entries of +self+ are a subset of the entries of +other+:
4893 *
4894 * h0 = {foo: 0, bar: 1}
4895 * h1 = {foo: 0, bar: 1, baz: 2}
4896 * h0 <= h0 # => true
4897 * h0 <= h1 # => true
4898 * h1 <= h0 # => false
4899 *
4900 * See {Hash Inclusion}[rdoc-ref:language/hash_inclusion.rdoc].
4901 *
4902 * Raises TypeError if +other_hash+ is not a hash and cannot be converted to a hash.
4903 *
4904 * Related: see {Methods for Comparing}[rdoc-ref:Hash@Methods+for+Comparing].
4905 */
4906static VALUE
4907rb_hash_le(VALUE hash, VALUE other)
4908{
4909 other = to_hash(other);
4910 if (RHASH_SIZE(hash) > RHASH_SIZE(other)) return Qfalse;
4911 return hash_le(hash, other);
4912}
4913
4914/*
4915 * call-seq:
4916 * self < other -> true or false
4917 *
4918 * Returns whether the entries of +self+ are a proper subset of the entries of +other+:
4919 *
4920 * h = {foo: 0, bar: 1}
4921 * h < {foo: 0, bar: 1, baz: 2} # => true # Proper subset.
4922 * h < {baz: 2, bar: 1, foo: 0} # => true # Order may differ.
4923 * h < h # => false # Not a proper subset.
4924 * h < {bar: 1, foo: 0} # => false # Not a proper subset.
4925 * h < {foo: 0, bar: 1, baz: 2} # => false # Different key.
4926 * h < {foo: 0, bar: 1, baz: 2} # => false # Different value.
4927 *
4928 * See {Hash Inclusion}[rdoc-ref:language/hash_inclusion.rdoc].
4929 *
4930 * Raises TypeError if +other_hash+ is not a hash and cannot be converted to a hash.
4931 *
4932 * Related: see {Methods for Comparing}[rdoc-ref:Hash@Methods+for+Comparing].
4933 */
4934static VALUE
4935rb_hash_lt(VALUE hash, VALUE other)
4936{
4937 other = to_hash(other);
4938 if (RHASH_SIZE(hash) >= RHASH_SIZE(other)) return Qfalse;
4939 return hash_le(hash, other);
4940}
4941
4942/*
4943 * call-seq:
4944 * self >= other -> true or false
4945 *
4946 * Returns whether the entries of +self+ are a superset of the entries of +other+:
4947 *
4948 * h0 = {foo: 0, bar: 1, baz: 2}
4949 * h1 = {foo: 0, bar: 1}
4950 * h0 >= h1 # => true
4951 * h0 >= h0 # => true
4952 * h1 >= h0 # => false
4953 *
4954 * See {Hash Inclusion}[rdoc-ref:language/hash_inclusion.rdoc].
4955 *
4956 * Raises TypeError if +other_hash+ is not a hash and cannot be converted to a hash.
4957 *
4958 * Related: see {Methods for Comparing}[rdoc-ref:Hash@Methods+for+Comparing].
4959 */
4960static VALUE
4961rb_hash_ge(VALUE hash, VALUE other)
4962{
4963 other = to_hash(other);
4964 if (RHASH_SIZE(hash) < RHASH_SIZE(other)) return Qfalse;
4965 return hash_le(other, hash);
4966}
4967
4968/*
4969 * call-seq:
4970 * self > other -> true or false
4971 *
4972 * Returns whether the entries of +self+ are a proper superset of the entries of +other+:
4973 *
4974 * h = {foo: 0, bar: 1, baz: 2}
4975 * h > {foo: 0, bar: 1} # => true # Proper superset.
4976 * h > {bar: 1, foo: 0} # => true # Order may differ.
4977 * h > h # => false # Not a proper superset.
4978 * h > {baz: 2, bar: 1, foo: 0} # => false # Not a proper superset.
4979 * h > {foo: 0, bar: 1} # => false # Different key.
4980 * h > {foo: 0, bar: 1} # => false # Different value.
4981 *
4982 * See {Hash Inclusion}[rdoc-ref:language/hash_inclusion.rdoc].
4983 *
4984 * Raises TypeError if +other_hash+ is not a hash and cannot be converted to a hash.
4985 *
4986 * Related: see {Methods for Comparing}[rdoc-ref:Hash@Methods+for+Comparing].
4987 */
4988static VALUE
4989rb_hash_gt(VALUE hash, VALUE other)
4990{
4991 other = to_hash(other);
4992 if (RHASH_SIZE(hash) <= RHASH_SIZE(other)) return Qfalse;
4993 return hash_le(other, hash);
4994}
4995
4996static VALUE
4997hash_proc_call(RB_BLOCK_CALL_FUNC_ARGLIST(key, hash))
4998{
4999 rb_check_arity(argc, 1, 1);
5000 return rb_hash_aref(hash, *argv);
5001}
5002
5003/*
5004 * call-seq:
5005 * to_proc -> proc
5006 *
5007 * Returns a Proc object that maps a key to its value:
5008 *
5009 * h = {foo: 0, bar: 1, baz: 2}
5010 * proc = h.to_proc
5011 * proc.class # => Proc
5012 * proc.call(:foo) # => 0
5013 * proc.call(:bar) # => 1
5014 * proc.call(:nosuch) # => nil
5015 *
5016 * Related: see {Methods for Converting}[rdoc-ref:Hash@Methods+for+Converting].
5017 */
5018static VALUE
5019rb_hash_to_proc(VALUE hash)
5020{
5021 return rb_func_lambda_new(hash_proc_call, hash, 1, 1);
5022}
5023
5024/* :nodoc: */
5025static VALUE
5026rb_hash_deconstruct_keys(VALUE hash, VALUE keys)
5027{
5028 return hash;
5029}
5030
5031static int
5032add_new_i(st_data_t *key, st_data_t *val, st_data_t arg, int existing)
5033{
5034 if (existing) return ST_STOP;
5035 *val = arg;
5036 return ST_CONTINUE;
5037}
5038
5039/*
5040 * add +key+ to +val+ pair if +hash+ does not contain +key+.
5041 * returns non-zero if +key+ was contained.
5042 */
5043int
5044rb_hash_add_new_element(VALUE hash, VALUE key, VALUE val)
5045{
5046 st_table *tbl;
5047 int ret = -1;
5048
5049 if (RHASH_AR_TABLE_P(hash)) {
5050 ret = ar_update(hash, (st_data_t)key, add_new_i, (st_data_t)val);
5051 if (ret == -1) {
5052 ar_force_convert_table(hash, __FILE__, __LINE__);
5053 }
5054 }
5055
5056 if (ret == -1) {
5057 tbl = RHASH_TBL_RAW(hash);
5058 ret = st_update(tbl, (st_data_t)key, add_new_i, (st_data_t)val);
5059 }
5060 if (!ret) {
5061 // Newly inserted
5062 RB_OBJ_WRITTEN(hash, Qundef, key);
5063 RB_OBJ_WRITTEN(hash, Qundef, val);
5064 }
5065 return ret;
5066}
5067
5068static st_data_t
5069key_stringify(VALUE key)
5070{
5071 return (rb_obj_class(key) == rb_cString && !RB_OBJ_FROZEN(key)) ?
5072 rb_hash_key_str(key) : key;
5073}
5074
5075static void
5076ar_bulk_insert(VALUE hash, long argc, const VALUE *argv)
5077{
5078 long i;
5079 for (i = 0; i < argc; ) {
5080 st_data_t k = key_stringify(argv[i++]);
5081 st_data_t v = argv[i++];
5082 ar_insert(hash, k, v);
5083 RB_OBJ_WRITTEN(hash, Qundef, k);
5084 RB_OBJ_WRITTEN(hash, Qundef, v);
5085 }
5086}
5087
5088void
5089rb_hash_bulk_insert(long argc, const VALUE *argv, VALUE hash)
5090{
5091 HASH_ASSERT(argc % 2 == 0);
5092 if (argc > 0) {
5093 st_index_t size = argc / 2;
5094
5095 if (RHASH_AR_TABLE_P(hash) &&
5096 (RHASH_AR_TABLE_SIZE(hash) + size <= RHASH_AR_TABLE_MAX_SIZE)) {
5097 ar_bulk_insert(hash, argc, argv);
5098 }
5099 else {
5100 rb_hash_bulk_insert_into_st_table(argc, argv, hash);
5101 }
5102 }
5103}
5104
5105static char **origenviron;
5106#ifdef _WIN32
5107#define GET_ENVIRON(e) ((e) = rb_w32_get_environ())
5108#define FREE_ENVIRON(e) rb_w32_free_environ(e)
5109static char **my_environ;
5110#undef environ
5111#define environ my_environ
5112#undef getenv
5113#define getenv(n) rb_w32_ugetenv(n)
5114#elif defined(__APPLE__)
5115#undef environ
5116#define environ (*_NSGetEnviron())
5117#define GET_ENVIRON(e) (e)
5118#define FREE_ENVIRON(e)
5119#else
5120extern char **environ;
5121#define GET_ENVIRON(e) (e)
5122#define FREE_ENVIRON(e)
5123#endif
5124#ifdef ENV_IGNORECASE
5125#define ENVMATCH(s1, s2) (STRCASECMP((s1), (s2)) == 0)
5126#define ENVNMATCH(s1, s2, n) (STRNCASECMP((s1), (s2), (n)) == 0)
5127#else
5128#define ENVMATCH(n1, n2) (strcmp((n1), (n2)) == 0)
5129#define ENVNMATCH(s1, s2, n) (memcmp((s1), (s2), (n)) == 0)
5130#endif
5131
5132#define ENV_LOCKING() RB_VM_LOCKING()
5133
5134static inline rb_encoding *
5135env_encoding(void)
5136{
5137#ifdef _WIN32
5138 return rb_utf8_encoding();
5139#else
5140 return rb_locale_encoding();
5141#endif
5142}
5143
5144static VALUE
5145env_enc_str_new(const char *ptr, long len, rb_encoding *enc)
5146{
5147 VALUE str = rb_external_str_new_with_enc(ptr, len, enc);
5148
5149 rb_obj_freeze(str);
5150 return str;
5151}
5152
5153static VALUE
5154env_str_new(const char *ptr, long len, rb_encoding *enc)
5155{
5156 return env_enc_str_new(ptr, len, enc);
5157}
5158
5159static VALUE
5160env_str_new2(const char *ptr, rb_encoding *enc)
5161{
5162 if (!ptr) return Qnil;
5163 return env_str_new(ptr, strlen(ptr), enc);
5164}
5165
5166static VALUE
5167getenv_with_lock(const char *name)
5168{
5169 VALUE ret;
5170 rb_encoding *enc = env_encoding();
5171 ENV_LOCKING() {
5172 const char *val = getenv(name);
5173 ret = env_str_new2(val, enc);
5174 }
5175 return ret;
5176}
5177
5178static bool
5179has_env_with_lock(const char *name)
5180{
5181 const char *val;
5182
5183 ENV_LOCKING() {
5184 val = getenv(name);
5185 }
5186
5187 return val ? true : false;
5188}
5189
5190static const char TZ_ENV[] = "TZ";
5191
5192static void *
5193get_env_cstr(VALUE str, const char *name)
5194{
5195 char *var;
5196 rb_encoding *enc = rb_enc_get(str);
5197 if (!rb_enc_asciicompat(enc)) {
5198 rb_raise(rb_eArgError, "bad environment variable %s: ASCII incompatible encoding: %s",
5199 name, rb_enc_name(enc));
5200 }
5201 var = RSTRING_PTR(str);
5202 if (memchr(var, '\0', RSTRING_LEN(str))) {
5203 rb_raise(rb_eArgError, "bad environment variable %s: contains null byte", name);
5204 }
5205 return rb_str_fill_terminator(str, 1); /* ASCII compatible */
5206}
5207
5208#define get_env_ptr(var, val) \
5209 (var = get_env_cstr(val, #var))
5210
5211static inline const char *
5212env_name(volatile VALUE *s)
5213{
5214 const char *name;
5215 StringValue(*s);
5216 get_env_ptr(name, *s);
5217 return name;
5218}
5219
5220#define env_name(s) env_name(&(s))
5221
5222static VALUE env_aset(VALUE nm, VALUE val);
5223
5224static void
5225reset_by_modified_env(const char *nam, const char *val)
5226{
5227 /*
5228 * ENV['TZ'] = nil has a special meaning.
5229 * TZ is no longer considered up-to-date and ruby call tzset() as needed.
5230 * It could be useful if sysadmin change /etc/localtime.
5231 * This hack might works only on Linux glibc.
5232 */
5233 if (ENVMATCH(nam, TZ_ENV)) {
5234 ruby_reset_timezone(val);
5235 }
5236}
5237
5238static VALUE
5239env_delete(VALUE name)
5240{
5241 const char *nam = env_name(name);
5242 reset_by_modified_env(nam, NULL);
5243 VALUE val = getenv_with_lock(nam);
5244
5245 if (!NIL_P(val)) {
5246 ruby_setenv(nam, 0);
5247 }
5248 return val;
5249}
5250
5251/*
5252 * call-seq:
5253 * ENV.delete(name) -> value
5254 * ENV.delete(name) { |name| block } -> value
5255 * ENV.delete(missing_name) -> nil
5256 * ENV.delete(missing_name) { |name| block } -> block_value
5257 *
5258 * Deletes the environment variable with +name+ if it exists and returns its value:
5259 * ENV['foo'] = '0'
5260 * ENV.delete('foo') # => '0'
5261 *
5262 * If a block is not given and the named environment variable does not exist, returns +nil+.
5263 *
5264 * If a block given and the environment variable does not exist,
5265 * yields +name+ to the block and returns the value of the block:
5266 * ENV.delete('foo') { |name| name * 2 } # => "foofoo"
5267 *
5268 * If a block given and the environment variable exists,
5269 * deletes the environment variable and returns its value (ignoring the block):
5270 * ENV['foo'] = '0'
5271 * ENV.delete('foo') { |name| raise 'ignored' } # => "0"
5272 *
5273 * Raises an exception if +name+ is invalid.
5274 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
5275 */
5276static VALUE
5277env_delete_m(VALUE obj, VALUE name)
5278{
5279 VALUE val;
5280
5281 val = env_delete(name);
5282 if (NIL_P(val) && rb_block_given_p()) val = rb_yield(name);
5283 return val;
5284}
5285
5286/*
5287 * call-seq:
5288 * ENV[name] -> value
5289 *
5290 * Returns the value for the environment variable +name+ if it exists:
5291 * ENV['foo'] = '0'
5292 * ENV['foo'] # => "0"
5293 * Returns +nil+ if the named variable does not exist.
5294 *
5295 * Raises an exception if +name+ is invalid.
5296 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
5297 */
5298static VALUE
5299rb_f_getenv(VALUE obj, VALUE name)
5300{
5301 const char *nam = env_name(name);
5302 VALUE env = getenv_with_lock(nam);
5303 return env;
5304}
5305
5306/*
5307 * call-seq:
5308 * ENV.fetch(name) -> value
5309 * ENV.fetch(name, default) -> value
5310 * ENV.fetch(name) { |name| block } -> value
5311 *
5312 * If +name+ is the name of an environment variable, returns its value:
5313 * ENV['foo'] = '0'
5314 * ENV.fetch('foo') # => '0'
5315 * Otherwise if a block is given (but not a default value),
5316 * yields +name+ to the block and returns the block's return value:
5317 * ENV.fetch('foo') { |name| :need_not_return_a_string } # => :need_not_return_a_string
5318 * Otherwise if a default value is given (but not a block), returns the default value:
5319 * ENV.delete('foo')
5320 * ENV.fetch('foo', :default_need_not_be_a_string) # => :default_need_not_be_a_string
5321 * If the environment variable does not exist and both default and block are given,
5322 * issues a warning ("warning: block supersedes default value argument"),
5323 * yields +name+ to the block, and returns the block's return value:
5324 * ENV.fetch('foo', :default) { |name| :block_return } # => :block_return
5325 * Raises KeyError if +name+ is valid, but not found,
5326 * and neither default value nor block is given:
5327 * ENV.fetch('foo') # Raises KeyError (key not found: "foo")
5328 * Raises an exception if +name+ is invalid.
5329 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
5330 */
5331static VALUE
5332env_fetch(int argc, VALUE *argv, VALUE _)
5333{
5334 VALUE key;
5335 int block_given;
5336 const char *nam;
5337 VALUE env;
5338
5339 rb_check_arity(argc, 1, 2);
5340 key = argv[0];
5341 block_given = rb_block_given_p();
5342 if (block_given && argc == 2) {
5343 rb_warn("block supersedes default value argument");
5344 }
5345 nam = env_name(key);
5346 env = getenv_with_lock(nam);
5347
5348 if (NIL_P(env)) {
5349 if (block_given) return rb_yield(key);
5350 if (argc == 1) {
5351 rb_key_err_raise(rb_sprintf("key not found: \"%"PRIsVALUE"\"", key), envtbl, key);
5352 }
5353 return argv[1];
5354 }
5355 return env;
5356}
5357
5358/*
5359 * call-seq:
5360 * ENV.fetch_values(*names) -> array of values
5361 * ENV.fetch_values(*names) {|name| ... } -> array of values
5362 *
5363 * Returns an Array containing the environment variable values associated with
5364 * the given names:
5365 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5366 * ENV.fetch_values('foo', 'baz') # => ["0", "2"]
5367 *
5368 * Otherwise if a block is given yields +name+ to
5369 * the block and returns the block's return value:
5370 * ENV.fetch_values('foo', 'bam') {|key| key.to_s} # => ["0", "bam"]
5371 *
5372 * Raises KeyError if +name+ is valid, but not found and block is not given:
5373 * ENV.fetch_values('foo', 'bam') # Raises KeyError (key not found: "bam")
5374 *
5375 * Returns an empty Array if no names given.
5376 *
5377 * Raises an exception if any name is invalid.
5378 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
5379 */
5380
5381static VALUE
5382env_fetch_values(int argc, VALUE *argv, VALUE ehash)
5383{
5384 VALUE result = rb_ary_new2(argc);
5385 long i;
5386
5387 for (i=0; i<argc; i++) {
5388 rb_ary_push(result, env_fetch(1, &argv[i], ehash));
5389 }
5390
5391 return result;
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@Whats+Here].
7252 * - Includes {module Enumerable}[rdoc-ref:Enumerable@Whats+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 * - #invert: Returns a hash with the each key-value pair inverted.
7366 * - #transform_keys: Returns a copy of +self+ with modified keys.
7367 * - #transform_keys!: Modifies keys in +self+
7368 * - #transform_values: Returns a copy of +self+ with modified values.
7369 * - #transform_values!: Modifies values in +self+.
7370 *
7371 */
7372
7373void
7374Init_Hash(void)
7375{
7376 id_hash = rb_intern_const("hash");
7377 id_flatten_bang = rb_intern_const("flatten!");
7378 id_hash_iter_lev = rb_make_internal_id();
7379
7381
7383
7384 rb_define_alloc_func(rb_cHash, empty_hash_alloc);
7385 rb_define_singleton_method(rb_cHash, "[]", rb_hash_s_create, -1);
7386 rb_define_singleton_method(rb_cHash, "try_convert", rb_hash_s_try_convert, 1);
7387 rb_define_method(rb_cHash, "initialize_copy", rb_hash_replace, 1);
7388 rb_define_method(rb_cHash, "rehash", rb_hash_rehash, 0);
7389 rb_define_method(rb_cHash, "freeze", rb_hash_freeze, 0);
7390
7391 rb_define_method(rb_cHash, "to_hash", rb_hash_to_hash, 0);
7392 rb_define_method(rb_cHash, "to_h", rb_hash_to_h, 0);
7393 rb_define_method(rb_cHash, "to_a", rb_hash_to_a, 0);
7394 rb_define_method(rb_cHash, "inspect", rb_hash_inspect, 0);
7395 rb_define_alias(rb_cHash, "to_s", "inspect");
7396 rb_define_method(rb_cHash, "to_proc", rb_hash_to_proc, 0);
7397
7398 rb_define_method(rb_cHash, "==", rb_hash_equal, 1);
7399 rb_define_method(rb_cHash, "[]", rb_hash_aref, 1);
7400 rb_define_method(rb_cHash, "hash", rb_hash_hash, 0);
7401 rb_define_method(rb_cHash, "eql?", rb_hash_eql, 1);
7402 rb_define_method(rb_cHash, "fetch", rb_hash_fetch_m, -1);
7403 rb_define_method(rb_cHash, "[]=", rb_hash_aset, 2);
7404 rb_define_method(rb_cHash, "store", rb_hash_aset, 2);
7405 rb_define_method(rb_cHash, "default", rb_hash_default, -1);
7406 rb_define_method(rb_cHash, "default=", rb_hash_set_default, 1);
7407 rb_define_method(rb_cHash, "default_proc", rb_hash_default_proc, 0);
7408 rb_define_method(rb_cHash, "default_proc=", rb_hash_set_default_proc, 1);
7409 rb_define_method(rb_cHash, "key", rb_hash_key, 1);
7410 rb_define_method(rb_cHash, "size", rb_hash_size, 0);
7411 rb_define_method(rb_cHash, "length", rb_hash_size, 0);
7412 rb_define_method(rb_cHash, "empty?", rb_hash_empty_p, 0);
7413
7414 rb_define_method(rb_cHash, "each_value", rb_hash_each_value, 0);
7415 rb_define_method(rb_cHash, "each_key", rb_hash_each_key, 0);
7416 rb_define_method(rb_cHash, "each_pair", rb_hash_each_pair, 0);
7417 rb_define_method(rb_cHash, "each", rb_hash_each_pair, 0);
7418
7419 rb_define_method(rb_cHash, "transform_keys", rb_hash_transform_keys, -1);
7420 rb_define_method(rb_cHash, "transform_keys!", rb_hash_transform_keys_bang, -1);
7421 rb_define_method(rb_cHash, "transform_values", rb_hash_transform_values, 0);
7422 rb_define_method(rb_cHash, "transform_values!", rb_hash_transform_values_bang, 0);
7423
7424 rb_define_method(rb_cHash, "keys", rb_hash_keys, 0);
7425 rb_define_method(rb_cHash, "values", rb_hash_values, 0);
7426 rb_define_method(rb_cHash, "values_at", rb_hash_values_at, -1);
7427 rb_define_method(rb_cHash, "fetch_values", rb_hash_fetch_values, -1);
7428
7429 rb_define_method(rb_cHash, "shift", rb_hash_shift, 0);
7430 rb_define_method(rb_cHash, "delete", rb_hash_delete_m, 1);
7431 rb_define_method(rb_cHash, "delete_if", rb_hash_delete_if, 0);
7432 rb_define_method(rb_cHash, "keep_if", rb_hash_keep_if, 0);
7433 rb_define_method(rb_cHash, "select", rb_hash_select, 0);
7434 rb_define_method(rb_cHash, "select!", rb_hash_select_bang, 0);
7435 rb_define_method(rb_cHash, "filter", rb_hash_select, 0);
7436 rb_define_method(rb_cHash, "filter!", rb_hash_select_bang, 0);
7437 rb_define_method(rb_cHash, "reject", rb_hash_reject, 0);
7438 rb_define_method(rb_cHash, "reject!", rb_hash_reject_bang, 0);
7439 rb_define_method(rb_cHash, "slice", rb_hash_slice, -1);
7440 rb_define_method(rb_cHash, "except", rb_hash_except, -1);
7441 rb_define_method(rb_cHash, "clear", rb_hash_clear, 0);
7442 rb_define_method(rb_cHash, "invert", rb_hash_invert, 0);
7443 rb_define_method(rb_cHash, "update", rb_hash_update, -1);
7444 rb_define_method(rb_cHash, "replace", rb_hash_replace, 1);
7445 rb_define_method(rb_cHash, "merge!", rb_hash_update, -1);
7446 rb_define_method(rb_cHash, "merge", rb_hash_merge, -1);
7447 rb_define_method(rb_cHash, "assoc", rb_hash_assoc, 1);
7448 rb_define_method(rb_cHash, "rassoc", rb_hash_rassoc, 1);
7449 rb_define_method(rb_cHash, "flatten", rb_hash_flatten, -1);
7450 rb_define_method(rb_cHash, "compact", rb_hash_compact, 0);
7451 rb_define_method(rb_cHash, "compact!", rb_hash_compact_bang, 0);
7452
7453 rb_define_method(rb_cHash, "include?", rb_hash_has_key, 1);
7454 rb_define_method(rb_cHash, "member?", rb_hash_has_key, 1);
7455 rb_define_method(rb_cHash, "has_key?", rb_hash_has_key, 1);
7456 rb_define_method(rb_cHash, "has_value?", rb_hash_has_value, 1);
7457 rb_define_method(rb_cHash, "key?", rb_hash_has_key, 1);
7458 rb_define_method(rb_cHash, "value?", rb_hash_has_value, 1);
7459
7460 rb_define_method(rb_cHash, "compare_by_identity", rb_hash_compare_by_id, 0);
7461 rb_define_method(rb_cHash, "compare_by_identity?", rb_hash_compare_by_id_p, 0);
7462
7463 rb_define_method(rb_cHash, "any?", rb_hash_any_p, -1);
7464 rb_define_method(rb_cHash, "dig", rb_hash_dig, -1);
7465
7466 rb_define_method(rb_cHash, "<=", rb_hash_le, 1);
7467 rb_define_method(rb_cHash, "<", rb_hash_lt, 1);
7468 rb_define_method(rb_cHash, ">=", rb_hash_ge, 1);
7469 rb_define_method(rb_cHash, ">", rb_hash_gt, 1);
7470
7471 rb_define_method(rb_cHash, "deconstruct_keys", rb_hash_deconstruct_keys, 1);
7472
7473 rb_define_singleton_method(rb_cHash, "ruby2_keywords_hash?", rb_hash_s_ruby2_keywords_hash_p, 1);
7474 rb_define_singleton_method(rb_cHash, "ruby2_keywords_hash", rb_hash_s_ruby2_keywords_hash, 1);
7475
7476 rb_cHash_empty_frozen = rb_hash_freeze(rb_hash_new());
7477 RB_OBJ_SET_SHAREABLE(rb_cHash_empty_frozen);
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@Whats+Here].
7564 * - Extends {module Enumerable}[rdoc-ref:Enumerable@Whats+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 * - ::fetch_values: Returns array containing the values associated with given names.
7617 * - ::inspect: Returns the contents of +ENV+ as a string.
7618 * - ::invert: Returns a hash whose keys are the +ENV+ values,
7619 and whose values are the corresponding +ENV+ names.
7620 * - ::keys: Returns an array of all names.
7621 * - ::rassoc: Returns the name and value of the first found entry
7622 * that has the given value.
7623 * - ::reject: Returns a hash of those entries not rejected by the block.
7624 * - ::select, ::filter: Returns a hash of name/value pairs selected by the block.
7625 * - ::slice: Returns a hash of the given names and their corresponding values.
7626 * - ::to_a: Returns the entries as an array of 2-element Arrays.
7627 * - ::to_h: Returns a hash of entries selected by the block.
7628 * - ::to_hash: Returns a hash of all entries.
7629 * - ::to_s: Returns the string <tt>'ENV'</tt>.
7630 * - ::values: Returns all values as an array.
7631 * - ::values_at: Returns an array of the values for the given name.
7632 *
7633 * ==== More Methods
7634 *
7635 * - ::dup: Raises an exception.
7636 * - ::freeze: Raises an exception.
7637 * - ::rehash: Returns +nil+, without modifying +ENV+.
7638 *
7639 */
7640
7641 /*
7642 * Hack to get RDoc to regard ENV as a class:
7643 * envtbl = rb_define_class("ENV", rb_cObject);
7644 */
7645 origenviron = environ;
7646 envtbl = TypedData_Wrap_Struct(rb_cObject, &env_data_type, NULL);
7648 RB_OBJ_SET_SHAREABLE(envtbl);
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, "fetch_values", env_fetch_values, -1);
7653 rb_define_singleton_method(envtbl, "[]=", env_aset_m, 2);
7654 rb_define_singleton_method(envtbl, "store", env_aset_m, 2);
7655 rb_define_singleton_method(envtbl, "each", env_each_pair, 0);
7656 rb_define_singleton_method(envtbl, "each_pair", env_each_pair, 0);
7657 rb_define_singleton_method(envtbl, "each_key", env_each_key, 0);
7658 rb_define_singleton_method(envtbl, "each_value", env_each_value, 0);
7659 rb_define_singleton_method(envtbl, "delete", env_delete_m, 1);
7660 rb_define_singleton_method(envtbl, "delete_if", env_delete_if, 0);
7661 rb_define_singleton_method(envtbl, "keep_if", env_keep_if, 0);
7662 rb_define_singleton_method(envtbl, "slice", env_slice, -1);
7663 rb_define_singleton_method(envtbl, "except", env_except, -1);
7664 rb_define_singleton_method(envtbl, "clear", env_clear, 0);
7665 rb_define_singleton_method(envtbl, "reject", env_reject, 0);
7666 rb_define_singleton_method(envtbl, "reject!", env_reject_bang, 0);
7667 rb_define_singleton_method(envtbl, "select", env_select, 0);
7668 rb_define_singleton_method(envtbl, "select!", env_select_bang, 0);
7669 rb_define_singleton_method(envtbl, "filter", env_select, 0);
7670 rb_define_singleton_method(envtbl, "filter!", env_select_bang, 0);
7671 rb_define_singleton_method(envtbl, "shift", env_shift, 0);
7672 rb_define_singleton_method(envtbl, "freeze", env_freeze, 0);
7673 rb_define_singleton_method(envtbl, "invert", env_invert, 0);
7674 rb_define_singleton_method(envtbl, "replace", env_replace, 1);
7675 rb_define_singleton_method(envtbl, "update", env_update, -1);
7676 rb_define_singleton_method(envtbl, "merge!", env_update, -1);
7677 rb_define_singleton_method(envtbl, "inspect", env_inspect, 0);
7678 rb_define_singleton_method(envtbl, "rehash", env_none, 0);
7679 rb_define_singleton_method(envtbl, "to_a", env_to_a, 0);
7680 rb_define_singleton_method(envtbl, "to_s", env_to_s, 0);
7681 rb_define_singleton_method(envtbl, "key", env_key, 1);
7682 rb_define_singleton_method(envtbl, "size", env_size, 0);
7683 rb_define_singleton_method(envtbl, "length", env_size, 0);
7684 rb_define_singleton_method(envtbl, "empty?", env_empty_p, 0);
7685 rb_define_singleton_method(envtbl, "keys", env_f_keys, 0);
7686 rb_define_singleton_method(envtbl, "values", env_f_values, 0);
7687 rb_define_singleton_method(envtbl, "values_at", env_values_at, -1);
7688 rb_define_singleton_method(envtbl, "include?", env_has_key, 1);
7689 rb_define_singleton_method(envtbl, "member?", env_has_key, 1);
7690 rb_define_singleton_method(envtbl, "has_key?", env_has_key, 1);
7691 rb_define_singleton_method(envtbl, "has_value?", env_has_value, 1);
7692 rb_define_singleton_method(envtbl, "key?", env_has_key, 1);
7693 rb_define_singleton_method(envtbl, "value?", env_has_value, 1);
7694 rb_define_singleton_method(envtbl, "to_hash", env_f_to_hash, 0);
7695 rb_define_singleton_method(envtbl, "to_h", env_to_h, 0);
7696 rb_define_singleton_method(envtbl, "assoc", env_assoc, 1);
7697 rb_define_singleton_method(envtbl, "rassoc", env_rassoc, 1);
7698 rb_define_singleton_method(envtbl, "clone", env_clone, -1);
7699 rb_define_singleton_method(envtbl, "dup", env_dup, 0);
7700
7701 VALUE envtbl_class = rb_singleton_class(envtbl);
7702 rb_undef_method(envtbl_class, "initialize");
7703 rb_undef_method(envtbl_class, "initialize_clone");
7704 rb_undef_method(envtbl_class, "initialize_copy");
7705 rb_undef_method(envtbl_class, "initialize_dup");
7706
7707 /*
7708 * +ENV+ is a Hash-like accessor for environment variables.
7709 *
7710 * See ENV (the class) for more details.
7711 */
7712 rb_define_global_const("ENV", envtbl);
7713
7714 HASH_ASSERT(sizeof(ar_hint_t) * RHASH_AR_TABLE_MAX_SIZE == sizeof(VALUE));
7715}
7716
7717#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:711
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1803
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:1596
void rb_extend_object(VALUE obj, VALUE module)
Extend the object with the module.
Definition eval.c:1863
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:2922
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2965
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2775
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:3255
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1017
#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:1683
#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:1680
#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:205
#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:128
#define rb_usascii_str_new2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1681
#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:127
#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:126
#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:3964
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1418
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1416
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:60
VALUE rb_cObject
Object class.
Definition object.c:61
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
Definition object.c:675
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:189
VALUE rb_cHash
Hash class.
Definition hash.c:109
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:264
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:686
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:176
VALUE rb_obj_freeze(VALUE obj)
Just calls rb_obj_freeze_inline() inside.
Definition object.c:1342
VALUE rb_cString
String class.
Definition string.c:84
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3365
#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:1331
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:208
#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:247
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:1169
int rb_proc_arity(VALUE recv)
Queries the number of mandatory arguments of the given Proc.
Definition proc.c:1276
VALUE rb_obj_is_proc(VALUE recv)
Queries if the given object is a proc.
Definition proc.c:122
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
Definition string.h:943
#define rb_hash_end(h)
Just another name of st_hash_end.
Definition string.h:946
int rb_str_hash_cmp(VALUE str1, VALUE str2)
Compares two strings.
Definition string.c:4181
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:11694
st_index_t rb_memhash(const void *ptr, long len)
This is a universal hash function.
Definition random.c:1783
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1499
VALUE rb_str_new_frozen(VALUE str)
Creates a frozen copy of the string, if necessary.
Definition string.c:1501
st_index_t rb_str_hash(VALUE str)
Calculates a hash value of a string.
Definition string.c:4167
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:3784
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition random.c:1777
VALUE rb_str_inspect(VALUE str)
Generates a "readable" version of the receiver.
Definition string.c:7256
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:3760
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:2968
#define rb_utf8_str_new(str, len)
Identical to rb_str_new, except it generates a string of "UTF-8" encoding.
Definition string.h:1550
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:1492
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition vm_method.c:3457
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:285
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:1031
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:4042
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:1395
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:1417
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:2226
#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:166
#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:409
#define RSTRING_GETMEM(str, ptrvar, lenvar)
Convenient macro to obtain the contents and length at once.
Definition rstring.h:450
#define RUBY_TYPED_FREE_IMMEDIATELY
Macros to see if each corresponding flag is defined.
Definition rtypeddata.h:119
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
Definition rtypeddata.h:514
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition variable.c:515
@ 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:211
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