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