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