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