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