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