Ruby 4.1.0dev (2026-12-05 revision ac1e8ed8497c5477f581a5df5f5b7dfb723e6ea8)
set.c (ac1e8ed8497c5477f581a5df5f5b7dfb723e6ea8)
1/* This implements sets using the same hash table implementation as in
2 st.c, but without a value for each hash entry. This results in the
3 same basic performance characteristics as when using an st table,
4 but uses 1/3 less memory.
5 */
6
7#include "id.h"
8#include "internal.h"
9#include "internal/bits.h"
10#include "internal/error.h"
11#include "internal/hash.h"
12#include "internal/object.h"
13#include "internal/proc.h"
14#include "internal/sanitizers.h"
15#include "internal/set.h"
16#include "internal/set_table.h"
17#include "internal/symbol.h"
18#include "internal/variable.h"
19#include "ruby_assert.h"
20
21#include <stdio.h>
22#ifdef HAVE_STDLIB_H
23#include <stdlib.h>
24#endif
25#include <string.h>
26
27#ifndef SET_DEBUG
28#define SET_DEBUG 0
29#endif
30
31#if SET_DEBUG
32#include "internal/gc.h"
33#endif
34
35static st_index_t
36dbl_to_index(double d)
37{
38 union {double d; st_index_t i;} u;
39 u.d = d;
40 return u.i;
41}
42
43static const uint64_t prime1 = ((uint64_t)0x2e0bb864 << 32) | 0xe9ea7df5;
44static const uint32_t prime2 = 0x830fcab9;
45
46static inline uint64_t
47mult_and_mix(uint64_t m1, uint64_t m2)
48{
49#if defined HAVE_UINT128_T
50 uint128_t r = (uint128_t) m1 * (uint128_t) m2;
51 return (uint64_t) (r >> 64) ^ (uint64_t) r;
52#else
53 uint64_t hm1 = m1 >> 32, hm2 = m2 >> 32;
54 uint64_t lm1 = m1, lm2 = m2;
55 uint64_t v64_128 = hm1 * hm2;
56 uint64_t v32_96 = hm1 * lm2 + lm1 * hm2;
57 uint64_t v1_32 = lm1 * lm2;
58
59 return (v64_128 + (v32_96 >> 32)) ^ ((v32_96 << 32) + v1_32);
60#endif
61}
62
63static inline uint64_t
64key64_hash(uint64_t key, uint32_t seed)
65{
66 return mult_and_mix(key + seed, prime1);
67}
68
69/* Should cast down the result for each purpose */
70#define set_index_hash(index) key64_hash(rb_hash_start(index), prime2)
71
72static st_index_t
73set_ident_hash(st_data_t n)
74{
75#ifdef USE_FLONUM /* RUBY */
76 /*
77 * - flonum (on 64-bit) is pathologically bad, mix the actual
78 * float value in, but do not use the float value as-is since
79 * many integers get interpreted as 2.0 or -2.0 [Bug #10761]
80 */
81 if (FLONUM_P(n)) {
82 n ^= dbl_to_index(rb_float_value(n));
83 }
84#endif
85
86 return (st_index_t)set_index_hash((st_index_t)n);
87}
88
89static const struct st_hash_type identhash = {
90 rb_st_numcmp,
91 set_ident_hash,
92};
93
94static const struct st_hash_type objhash = {
95 rb_any_cmp,
96 rb_any_hash,
97};
98
100static VALUE set_i_compare_by_identity(VALUE set);
101
102#define id_each idEach
103static ID id_each_entry;
104static ID id_any_p;
105static ID id_new;
106static ID id_i_hash;
107static ID id_set_iter_lev;
108static ID id_subclass_compatible;
109static ID id_class_methods;
110
111#define RSET_INITIALIZED FL_USER1
112#define RSET_LEV_MASK (FL_USER13 | FL_USER14 | FL_USER15 | /* FL 13..19 */ \
113 FL_USER16 | FL_USER17 | FL_USER18 | FL_USER19)
114#define RSET_LEV_SHIFT (FL_USHIFT + 13)
115#define RSET_LEV_MAX 127 /* 7 bits */
116
117#define SET_ASSERT(expr) RUBY_ASSERT_MESG_WHEN(SET_DEBUG, expr, #expr)
118
119#define RSET_SIZE(set) set_table_size(RSET_TABLE(set))
120#define RSET_EMPTY(set) (RSET_SIZE(set) == 0)
121#define RSET_SIZE_NUM(set) SIZET2NUM(RSET_SIZE(set))
122#define RSET_IS_MEMBER(set, item) set_table_lookup(RSET_TABLE(set), (st_data_t)(item))
123#define RSET_COMPARE_BY_IDENTITY(set) (RSET_TABLE(set)->type == &identhash)
124
126 set_table table;
127};
128
129static int
130mark_and_pin_key(st_data_t key, st_data_t data)
131{
132 rb_gc_mark((VALUE)key);
133
134 return ST_CONTINUE;
135}
136
137static int
138mark_key(st_data_t key, st_data_t data)
139{
140 rb_gc_mark_movable((VALUE)key);
141
142 return ST_CONTINUE;
143}
144
145static void
146set_mark(void *ptr)
147{
148 struct set_object *sobj = ptr;
149 if (sobj->table.entries) {
150 if (sobj->table.type == &identhash) {
151 set_table_foreach(&sobj->table, mark_and_pin_key, 0);
152 }
153 else {
154 set_table_foreach(&sobj->table, mark_key, 0);
155 }
156 }
157}
158
159static void
160set_free(void *ptr)
161{
162 struct set_object *sobj = ptr;
163 set_free_embedded_table(&sobj->table);
164}
165
166static size_t
167set_size(const void *ptr)
168{
169 const struct set_object *sobj = ptr;
170 /* Do not count the table size twice, as it is embedded */
171 return (unsigned long)set_memsize(&sobj->table) - sizeof(sobj->table);
172}
173
174static int
175set_foreach_replace(st_data_t key, st_data_t argp, int error)
176{
177 if (rb_gc_location((VALUE)key) != (VALUE)key) {
178 return ST_REPLACE;
179 }
180
181 return ST_CONTINUE;
182}
183
184static int
185set_replace_ref(st_data_t *key, st_data_t argp, int existing)
186{
187 rb_gc_mark_and_move((VALUE *)key);
188
189 return ST_CONTINUE;
190}
191
192static void
193set_update_references(void *ptr)
194{
195 struct set_object *sobj = ptr;
196 set_foreach_with_replace(&sobj->table, set_foreach_replace, set_replace_ref, 0);
197}
198
199static const rb_data_type_t set_data_type = {
200 .wrap_struct_name = "set",
201 .function = {
202 .dmark = set_mark,
203 .dfree = set_free,
204 .dsize = set_size,
205 .dcompact = set_update_references,
206 },
207 .flags = RUBY_TYPED_EMBEDDABLE | RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FROZEN_SHAREABLE
208};
209
210static inline set_table *
211RSET_TABLE(VALUE set)
212{
213 struct set_object *sobj;
214 TypedData_Get_Struct(set, struct set_object, &set_data_type, sobj);
215 return &sobj->table;
216}
217
218static unsigned long
219iter_lev_in_ivar(VALUE set)
220{
221 VALUE levval = rb_ivar_get(set, id_set_iter_lev);
222 SET_ASSERT(FIXNUM_P(levval));
223 long lev = FIX2LONG(levval);
224 SET_ASSERT(lev >= 0);
225 return (unsigned long)lev;
226}
227
228void rb_ivar_set_internal(VALUE obj, ID id, VALUE val);
229
230static void
231iter_lev_in_ivar_set(VALUE set, unsigned long lev)
232{
233 SET_ASSERT(lev >= RSET_LEV_MAX);
234 SET_ASSERT(POSFIXABLE(lev)); /* POSFIXABLE means fitting to long */
235 rb_ivar_set_internal(set, id_set_iter_lev, LONG2FIX((long)lev));
236}
237
238static inline unsigned long
239iter_lev_in_flags(VALUE set)
240{
241 return (unsigned long)((RBASIC(set)->flags >> RSET_LEV_SHIFT) & RSET_LEV_MAX);
242}
243
244static inline void
245iter_lev_in_flags_set(VALUE set, unsigned long lev)
246{
247 SET_ASSERT(lev <= RSET_LEV_MAX);
248 RBASIC(set)->flags = ((RBASIC(set)->flags & ~RSET_LEV_MASK) | ((VALUE)lev << RSET_LEV_SHIFT));
249}
250
251static inline bool
252set_iterating_p(VALUE set)
253{
254 return iter_lev_in_flags(set) > 0;
255}
256
257static void
258set_iter_lev_inc(VALUE set)
259{
260 unsigned long lev = iter_lev_in_flags(set);
261 if (lev == RSET_LEV_MAX) {
262 lev = iter_lev_in_ivar(set) + 1;
263 if (!POSFIXABLE(lev)) { /* paranoiac check */
264 rb_raise(rb_eRuntimeError, "too much nested iterations");
265 }
266 }
267 else {
268 lev += 1;
269 iter_lev_in_flags_set(set, lev);
270 if (lev < RSET_LEV_MAX) return;
271 }
272 iter_lev_in_ivar_set(set, lev);
273}
274
275static void
276set_iter_lev_dec(VALUE set)
277{
278 unsigned long lev = iter_lev_in_flags(set);
279 if (lev == RSET_LEV_MAX) {
280 lev = iter_lev_in_ivar(set);
281 if (lev > RSET_LEV_MAX) {
282 iter_lev_in_ivar_set(set, lev-1);
283 return;
284 }
285 rb_attr_delete(set, id_set_iter_lev);
286 }
287 else if (lev == 0) {
288 rb_raise(rb_eRuntimeError, "iteration level underflow");
289 }
290 iter_lev_in_flags_set(set, lev - 1);
291}
292
293static VALUE
294set_foreach_ensure(VALUE set)
295{
296 set_iter_lev_dec(set);
297 return 0;
298}
299
300typedef int set_foreach_func(VALUE, VALUE);
301
303 VALUE set;
304 set_foreach_func *func;
305 VALUE arg;
306};
307
308static int
309set_iter_status_check(int status)
310{
311 if (status == ST_CONTINUE) {
312 return ST_CHECK;
313 }
314
315 return status;
316}
317
318static int
319set_foreach_iter(st_data_t key, st_data_t argp, int error)
320{
321 struct set_foreach_arg *arg = (struct set_foreach_arg *)argp;
322
323 if (error) return ST_STOP;
324
325 set_table *tbl = RSET_TABLE(arg->set);
326 int status = (*arg->func)((VALUE)key, arg->arg);
327
328 if (RSET_TABLE(arg->set) != tbl) {
329 rb_raise(rb_eRuntimeError, "reset occurred during iteration");
330 }
331
332 return set_iter_status_check(status);
333}
334
335static VALUE
336set_foreach_call(VALUE arg)
337{
338 VALUE set = ((struct set_foreach_arg *)arg)->set;
339 int ret = 0;
340 ret = set_foreach_check(RSET_TABLE(set), set_foreach_iter,
341 (st_data_t)arg, (st_data_t)Qundef);
342 if (ret) {
343 rb_raise(rb_eRuntimeError, "ret: %d, set modified during iteration", ret);
344 }
345 return Qnil;
346}
347
348static void
349set_iter(VALUE set, set_foreach_func *func, VALUE farg)
350{
351 struct set_foreach_arg arg;
352
353 if (RSET_EMPTY(set))
354 return;
355 arg.set = set;
356 arg.func = func;
357 arg.arg = farg;
358 if (RB_OBJ_FROZEN(set)) {
359 set_foreach_call((VALUE)&arg);
360 }
361 else {
362 set_iter_lev_inc(set);
363 rb_ensure(set_foreach_call, (VALUE)&arg, set_foreach_ensure, set);
364 }
365}
366
367NORETURN(static void no_new_item(void));
368static void
369no_new_item(void)
370{
371 rb_raise(rb_eRuntimeError, "can't add a new item into set during iteration");
372}
373
374static void
375set_compact_after_delete(VALUE set)
376{
377 if (!set_iterating_p(set)) {
378 set_compact_table(RSET_TABLE(set));
379 }
380}
381
382static int
383set_table_insert_wb(set_table *tab, VALUE set, VALUE key)
384{
385 if (tab->type != &identhash && rb_obj_class(key) == rb_cString && !RB_OBJ_FROZEN(key)) {
386 key = rb_hash_key_str(key);
387 }
388 int ret = set_insert(tab, (st_data_t)key);
389 if (ret == 0) RB_OBJ_WRITTEN(set, Qundef, key);
390 return ret;
391}
392
393static int
394set_insert_wb(VALUE set, VALUE key)
395{
396 return set_table_insert_wb(RSET_TABLE(set), set, key);
397}
398
399static VALUE
400set_alloc_with_size_and_type(VALUE klass, st_index_t size, const struct st_hash_type *type)
401{
402 VALUE set;
403 struct set_object *sobj;
404
405 set = TypedData_Make_Struct(klass, struct set_object, &set_data_type, sobj);
406 set_init_table_with_size(&sobj->table, type, size);
407
408 return set;
409}
410
411static VALUE
412set_alloc_with_size(VALUE klass, st_index_t size)
413{
414 return set_alloc_with_size_and_type(klass, size, &objhash);
415}
416
417static VALUE
418set_s_alloc(VALUE klass)
419{
420 return set_alloc_with_size(klass, 0);
421}
422
423bool
424rb_set_p(VALUE obj)
425{
426 return rb_typeddata_is_instance_of(obj, &set_data_type);
427}
428
429/*
430 * call-seq:
431 * Set[*objects] -> new_set
432 *
433 * Returns a new set populated with the given +objects+:
434 *
435 * Set[1, 'one', :one, 1.0, %w[a b c], {foo: 0, bar: 1}]
436 * # => Set[1, "one", :one, 1.0, ["a", "b", "c"], {foo: 0, bar: 1}]
437 * Set[Set[0, 1, 2], Set[%w[a b c]]]
438 * # => Set[Set[0, 1, 2], Set[["a", "b", "c"]]]
439 * Set[] # => Set[]
440 *
441 * Related: see {Methods for Creating a Set}[rdoc-ref:Set@Methods+for+Creating+a+Set].
442 *
443 */
444static VALUE
445set_s_create(int argc, VALUE *argv, VALUE klass)
446{
447 VALUE set = set_alloc_with_size(klass, argc);
448 set_table *table = RSET_TABLE(set);
449 int i;
450
451 for (i=0; i < argc; i++) {
452 set_table_insert_wb(table, set, argv[i]);
453 }
454
455 return set;
456}
457
458static VALUE
459set_s_inherited(VALUE klass, VALUE subclass)
460{
461 if (klass == rb_cSet) {
462 // When subclassing directly from Set, include the compatibility layer
463 rb_require("set/subclass_compatible.rb");
464 VALUE subclass_compatible = rb_const_get(klass, id_subclass_compatible);
465 rb_include_module(subclass, subclass_compatible);
466 rb_extend_object(subclass, rb_const_get(subclass_compatible, id_class_methods));
467 }
468 return Qnil;
469}
470
471static void
472check_set(VALUE arg)
473{
474 if (!rb_obj_is_kind_of(arg, rb_cSet)) {
475 rb_raise(rb_eArgError, "value must be a set");
476 }
477}
478
479static ID
480enum_method_id(VALUE other)
481{
482 if (rb_respond_to(other, id_each_entry)) {
483 return id_each_entry;
484 }
485 else if (rb_respond_to(other, id_each)) {
486 return id_each;
487 }
488 else {
489 rb_raise(rb_eArgError, "value must be enumerable");
490 }
491}
492
493static VALUE
494set_enum_size(VALUE set, VALUE args, VALUE eobj)
495{
496 return RSET_SIZE_NUM(set);
497}
498
499static VALUE
500set_initialize_without_block(RB_BLOCK_CALL_FUNC_ARGLIST(i, set))
501{
502 VALUE element = i;
503 set_insert_wb(set, element);
504 return element;
505}
506
507static VALUE
508set_initialize_with_block(RB_BLOCK_CALL_FUNC_ARGLIST(i, set))
509{
510 VALUE element = rb_yield(i);
511 set_insert_wb(set, element);
512 return element;
513}
514
515/*
516 * call-seq:
517 * Set.new(object = nil) -> new_set
518 * Set.new(object = nil) {|element| ... } -> new_set
519 *
520 * Returns a new set based on the given +object+,
521 * which must be an Enumerable or +nil+.
522 *
523 * With argument +object+ given as +nil+,
524 * returns a new empty set:
525 *
526 * Set.new # => Set[]
527 * Set.new { fail 'Cannot happen' } # => Set[] # Block not called.
528 *
529 * With no block given and enumerable argument +object+ given,
530 * populates the new set with the elements of +object+:
531 *
532 * Set.new(%w[ a b c ]) # => Set["a", "b", "c"]
533 * Set.new({foo: 0, bar: 1}) # => Set[[:foo, 0], [:bar, 1]]
534 * Set.new(4..10) # => Set[4, 5, 6, 7, 8, 9, 10]
535 * Set.new(Dir.new('lib')).take(5)
536 * # => [".", "..", "bundled_gems.rb", "bundler", "bundler.rb"]
537 * Set.new(File.new('doc/NEWS/NEWS-4.0.0.md')).take(3)
538 * # => ["# NEWS for Ruby 4.0.0\n", "\n", "This document is a list of user-visible feature changes\n"]
539 *
540 * With a block given and enumerable argument +object+ given,
541 * calls the block with each element of +object+;
542 * adds the block's return value to the new set:
543 *
544 * Set.new(4..10) {|i| i * 2 } # => Set[8, 10, 12, 14, 16, 18, 20]
545 *
546 * Related: see {Methods for Creating a Set}[rdoc-ref:Set@Methods+for+Creating+a+Set].
547 *
548 */
549static VALUE
550set_i_initialize(int argc, VALUE *argv, VALUE set)
551{
552 rb_check_frozen(set);
553
554 if (RBASIC(set)->flags & RSET_INITIALIZED) {
555 rb_raise(rb_eRuntimeError, "cannot reinitialize set");
556 }
557 RBASIC(set)->flags |= RSET_INITIALIZED;
558
559 VALUE other;
560 rb_check_arity(argc, 0, 1);
561
562 if (argc > 0 && (other = argv[0]) != Qnil) {
563 if (RB_TYPE_P(other, T_ARRAY)) {
564 rb_len_t i;
565 int block_given = rb_block_given_p();
566 set_table *into = RSET_TABLE(set);
567 for (i=0; i<RARRAY_LEN(other); i++) {
568 VALUE key = RARRAY_AREF(other, i);
569 if (block_given) key = rb_yield(key);
570 set_table_insert_wb(into, set, key);
571 }
572 }
573 else {
574 rb_block_call(other, enum_method_id(other), 0, 0,
575 rb_block_given_p() ? set_initialize_with_block : set_initialize_without_block,
576 set);
577 }
578 }
579
580 return set;
581}
582
583/* :nodoc: */
584static VALUE
585set_i_initialize_copy(VALUE set, VALUE other)
586{
587 rb_check_frozen(set);
588
589 if (set == other) return set;
590
591 if (set_iterating_p(set)) {
592 rb_raise(rb_eRuntimeError, "cannot replace set during iteration");
593 }
594
595 struct set_object *sobj;
596 TypedData_Get_Struct(set, struct set_object, &set_data_type, sobj);
597
598 set_table *other_table = RSET_TABLE(other);
599 set_table new_table;
600 set_copy(&new_table, other_table);
601 set_free_embedded_table(&sobj->table);
602 sobj->table = new_table;
603 RB_GC_GUARD(other);
604 rb_gc_writebarrier_remember(set);
605
606 return set;
607}
608
609static int
610set_inspect_i(st_data_t key, st_data_t arg)
611{
612 VALUE *args = (VALUE*)arg;
613 VALUE str = args[0];
614 if (args[1] == Qtrue) {
615 rb_str_buf_cat_ascii(str, ", ");
616 }
617 else {
618 args[1] = Qtrue;
619 }
621
622 return ST_CONTINUE;
623}
624
625static VALUE
626set_inspect(VALUE set, VALUE dummy, int recur)
627{
628 VALUE str;
629 VALUE klass_name = rb_class_path(CLASS_OF(set));
630
631 if (recur) {
632 str = rb_sprintf("%"PRIsVALUE"[...]", klass_name);
634 }
635
636 str = rb_sprintf("%"PRIsVALUE"[", klass_name);
637 VALUE args[2] = {str, Qfalse};
638 set_iter(set, set_inspect_i, (st_data_t)args);
639 rb_str_buf_cat2(str, "]");
640
641 return str;
642}
643
644/*
645 * call-seq:
646 * inspect -> string
647 *
648 * Returns a string representation of +self+:
649 *
650 * Set[*%w[foo bar], {foo: 0, bar: 1}].inspect
651 * # => "Set[\"foo\", \"bar\", {foo: 0, bar: 1}]"
652 *
653 * Related: see {Methods for Converting}[rdoc-ref:Set@Methods+for+Converting].
654 */
655static VALUE
656set_i_inspect(VALUE set)
657{
658 return rb_exec_recursive(set_inspect, set, 0);
659}
660
661static int
662set_to_a_i(st_data_t key, st_data_t arg)
663{
664 rb_ary_push((VALUE)arg, (VALUE)key);
665 return ST_CONTINUE;
666}
667
668/*
669 * call-seq:
670 * to_a -> array
671 *
672 * Returns an array containing the elements of +self+:
673 *
674 * Set[1, 2].to_a # => [1, 2]
675 * Set[1, 'c', :s].to_a # => [1, "c", :s]
676 *
677 * Related: {Methods for Converting}[rdoc-ref:Set@Methods+for+Converting].
678 */
679static VALUE
680set_i_to_a(VALUE set)
681{
682 st_index_t size = RSET_SIZE(set);
683 VALUE ary = rb_ary_new_capa(size);
684
685 if (size == 0) return ary;
686
687 if (ST_DATA_COMPATIBLE_P(VALUE)) {
688 RARRAY_PTR_USE(ary, ptr, {
689 size = set_keys(RSET_TABLE(set), ptr, size);
690 });
691 rb_gc_writebarrier_remember(ary);
692 rb_ary_set_len(ary, size);
693 }
694 else {
695 set_iter(set, set_to_a_i, (st_data_t)ary);
696 }
697 return ary;
698}
699
700/*
701 * call-seq:
702 * to_set {|element| ... } -> new_set
703 * to_set -> new_set
704 *
705 * Returns a new set containing the elements of +self+;
706 * with a block given, the set contains the block's return values instead:
707 *
708 * [3, 1, 2, 1].to_set # => Set[3, 1, 2]
709 * [3, 1, 2, 1].to_set {|i| -i } # => Set[-3, -1, -2]
710 */
711static VALUE
712enum_to_set(VALUE obj)
713{
714 return rb_funcall_passing_block(rb_cSet, id_new, 1, &obj);
715}
716
717/*
718 * call-seq:
719 * to_set {|element| ... } -> new_set
720 * to_set -> self or new_set
721 *
722 * With a block given, creates and returns a new set;
723 * calls the block with each element of +self+,
724 * and adds the block's returns value to the new set:
725 *
726 * set = Set[*0..9] # => Set[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
727 * set.to_set {|i| i * 2 } # => Set[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
728 *
729 * With no block given, when +self+ is an instance of +Set+,
730 * returns +self+:
731 *
732 * set = Set[*0..9]
733 * set.to_set
734 * set.to_set.equal?(set) # => true
735 *
736 * With no block given, when +self+ is an instance of a subclass of +Set+,
737 * returns a set containing the elements of +self+:
738 *
739 * class MySet < Set; end
740 * my_set = MySet[*0..9] # => #<MySet: {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}>
741 * set = my_set.to_set # => Set[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
742 *
743 * Related: see {Methods for Converting}[rdoc-ref:Set@Methods+for+Converting].
744 */
745static VALUE
746set_i_to_set(VALUE set)
747{
749 return set;
750 }
751
752 return enum_to_set(set);
753}
754
755/*
756 * call-seq:
757 * join(separator = $,) -> string
758 *
759 * Returns the string formed by joining the string-converted elements of +self+
760 * with the given +separator+ (defaults to <tt>$,</tt>):
761 *
762 * $, # => nil
763 * Set[*%w[foo bar baz]].join
764 * # => "foobarbaz"
765 * Set[*%w[foo bar baz]].join(', ')
766 * # => "foo, bar, baz"
767 *
768 * Flattens nested arrays:
769 *
770 * Set[[:foo, [:bar, [:baz, :bat]]]].join
771 * # => "foobarbazbat"
772 *
773 * Does not flatten nested sets:
774 *
775 * Set[Set[:foo, Set[:bar, Set[:baz, :bat]]]].join
776 * # => "Set[:foo, Set[:bar, Set[:baz, :bat]]]"
777 *
778 * Related: see {Methods for Converting}[rdoc-ref:Set@Methods+for+Converting].
779 */
780static VALUE
781set_i_join(int argc, VALUE *argv, VALUE set)
782{
783 rb_check_arity(argc, 0, 1);
784 return rb_ary_join(set_i_to_a(set), argc == 0 ? Qnil : argv[0]);
785}
786
787/*
788 * call-seq:
789 * add(object) -> self
790 *
791 * Adds the given +object+ to +self+; returns +self+:
792 *
793 * set = Set[0, 1, 2]
794 * set.add(%w[a b c]) # => Set[0, 1, 2, ["a", "b", "c"]]
795 * set.add(0) # => Set[0, 1, 2, ["a", "b", "c"]]
796 *
797 * Related: see {Methods for Assigning}[rdoc-ref:Set@Methods+for+Assigning].
798 */
799static VALUE
800set_i_add(VALUE set, VALUE item)
801{
802 rb_check_frozen(set);
803 if (set_iterating_p(set)) {
804 if (!set_table_lookup(RSET_TABLE(set), (st_data_t)item)) {
805 no_new_item();
806 }
807 }
808 else {
809 set_insert_wb(set, item);
810 }
811 return set;
812}
813
814/*
815 * call-seq:
816 * add?(object) -> self or nil
817 *
818 * Like #add, but returns +nil+ if the given +object+ is already in +self+:
819 *
820 * set = Set[0, 1, 2]
821 * set.add?(:foo) # => Set[0, 1, 2, :foo]
822 * set.add?(0..9) # => Set[0, 1, 2, :foo, 0..9]
823 * set.add?(2) # => nil
824 *
825 * Related: see {Methods for Assigning}[rdoc-ref:Set@Methods+for+Assigning].
826 */
827static VALUE
828set_i_add_p(VALUE set, VALUE item)
829{
830 rb_check_frozen(set);
831 if (set_iterating_p(set)) {
832 if (!set_table_lookup(RSET_TABLE(set), (st_data_t)item)) {
833 no_new_item();
834 }
835 return Qnil;
836 }
837 else {
838 return set_insert_wb(set, item) ? Qnil : set;
839 }
840}
841
842/*
843 * call-seq:
844 * delete(object) -> self
845 *
846 * Removes the given +object+ from +self+ if +self+ includes the object;
847 * returns +self+:
848 *
849 * set = Set[0, 'zero', :zero]
850 * set.delete(0) # => Set["zero", :zero]
851 * set.delete(:nosuch) # => Set["zero", :zero]
852 *
853 * Related: see {Methods for Deleting}[rdoc-ref:Set@Methods+for+Deleting].
854 */
855static VALUE
856set_i_delete(VALUE set, VALUE item)
857{
858 st_data_t item_data = (st_data_t)item;
859 rb_check_frozen(set);
860 if (set_table_delete(RSET_TABLE(set), &item_data)) {
861 set_compact_after_delete(set);
862 }
863 return set;
864}
865
866/*
867 * call-seq:
868 * delete?(object) -> self or nil
869 *
870 * Like #delete, but returns +nil+ if the object is not in +self+:
871 *
872 * set = Set[0, 'zero', :zero]
873 * set.delete?(0) # => Set["zero", :zero]
874 * set.delete?(0) # => nil
875 *
876 * Related: see {Methods for Deleting}[rdoc-ref:Set@Methods+for+Deleting].
877 */
878static VALUE
879set_i_delete_p(VALUE set, VALUE item)
880{
881 st_data_t item_data = (st_data_t)item;
882 rb_check_frozen(set);
883 if (set_table_delete(RSET_TABLE(set), &item_data)) {
884 set_compact_after_delete(set);
885 return set;
886 }
887 return Qnil;
888}
889
890static int
891set_delete_if_i(st_data_t key, st_data_t dummy)
892{
893 return RTEST(rb_yield((VALUE)key)) ? ST_DELETE : ST_CONTINUE;
894}
895
896/*
897 * call-seq:
898 * delete_if {|element| ... } -> self
899 * delete_if -> enumerator
900 *
901 * With a block given, calls the block with each element in +self+;
902 * removes the element if the block returns a truthy value:
903 *
904 * set = Set[*0..9]
905 * # => Set[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
906 * set.delete_if {|element| element.even? }
907 * # => Set[1, 3, 5, 7, 9]
908 *
909 * With no block given, returns an Enumerator.
910 *
911 * Related: {Methods for Deleting}[rdoc-ref:Set@Methods+for+Deleting].
912 */
913static VALUE
914set_i_delete_if(VALUE set)
915{
916 RETURN_SIZED_ENUMERATOR(set, 0, 0, set_enum_size);
917 rb_check_frozen(set);
918 set_iter(set, set_delete_if_i, 0);
919 set_compact_after_delete(set);
920 return set;
921}
922
923/*
924 * call-seq:
925 * reject! {|element| ... } -> self or nil
926 * reject! -> enumerator
927 *
928 * With a block given, like #delete_if, but returns +nil+ if no changes were made:
929 *
930 * set = Set[*0..9] # => Set[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
931 * set.reject! {|element| element.even? } # => Set[1, 3, 5, 7, 9]
932 * set.reject! {|element| element.even? } # => nil
933 * set.reject! {|element| element.odd? } # => Set[]
934 *
935 * With no block given, returns an Enumerator.
936 *
937 * Related: see {Methods for Deleting}[rdoc-ref:Set@Methods+for+Deleting].
938 */
939static VALUE
940set_i_reject(VALUE set)
941{
942 RETURN_SIZED_ENUMERATOR(set, 0, 0, set_enum_size);
943 rb_check_frozen(set);
944
945 set_table *table = RSET_TABLE(set);
946 size_t n = set_table_size(table);
947 set_iter(set, set_delete_if_i, 0);
948
949 if (n == set_table_size(table)) return Qnil;
950
951 set_compact_after_delete(set);
952 return set;
953}
954
955static int
956set_classify_i(st_data_t key, st_data_t tmp)
957{
958 VALUE* args = (VALUE*)tmp;
959 VALUE hash = args[0];
960 VALUE hash_key = rb_yield(key);
961 VALUE set = rb_hash_lookup2(hash, hash_key, Qundef);
962 if (set == Qundef) {
963 set = set_s_alloc(args[1]);
964 if (RTEST(args[2])) {
965 set_i_compare_by_identity(set);
966 }
967 rb_hash_aset(hash, hash_key, set);
968 }
969 set_i_add(set, key);
970
971 return ST_CONTINUE;
972}
973
974/*
975 * call-seq:
976 * classify {|element| ... } -> hash
977 * classify -> enumerator
978 *
979 * With a block given, calls the block with each element of +self+;
980 * returns a hash whose keys are the block's return values.
981 * The value for each key is a set containing the elements
982 * for which the block returned that key.
983 *
984 * This example classifies elements by their classes:
985 *
986 * set = Set[*(5..7), *%w[foo bar]] # => Set[5, 6, 7, "foo", "bar"]
987 * set.classify {|element| element.class }
988 * # => {Integer => Set[5, 6, 7], String => Set["foo", "bar"]}
989 *
990 * With no block given, returns an Enumerator.
991 *
992 * Related: see {Methods for Converting}[rdoc-ref:Set@Methods+for+Converting].
993 */
994static VALUE
995set_i_classify(VALUE set)
996{
997 RETURN_SIZED_ENUMERATOR(set, 0, 0, set_enum_size);
998 VALUE args[3];
999 args[0] = rb_hash_new();
1000 args[1] = rb_obj_class(set);
1001 args[2] = RBOOL(RSET_COMPARE_BY_IDENTITY(set));
1002 set_iter(set, set_classify_i, (st_data_t)args);
1003 return args[0];
1004}
1005
1006// Union-find with path compression
1007static rb_len_t
1008set_divide_union_find_root(rb_len_t *uf_parents, rb_len_t index, rb_len_t *tmp_array)
1009{
1010 rb_len_t root = uf_parents[index];
1011 rb_len_t update_size = 0;
1012 while (root != index) {
1013 tmp_array[update_size++] = index;
1014 index = root;
1015 root = uf_parents[index];
1016 }
1017 for (rb_len_t j = 0; j < update_size; j++) {
1018 rb_len_t idx = tmp_array[j];
1019 uf_parents[idx] = root;
1020 }
1021 return root;
1022}
1023
1024static void
1025set_divide_union_find_merge(rb_len_t *uf_parents, rb_len_t i, rb_len_t j, rb_len_t *tmp_array)
1026{
1027 rb_len_t root_i = set_divide_union_find_root(uf_parents, i, tmp_array);
1028 rb_len_t root_j = set_divide_union_find_root(uf_parents, j, tmp_array);
1029 if (root_i != root_j) uf_parents[root_j] = root_i;
1030}
1031
1032static VALUE
1033set_divide_arity2(VALUE set)
1034{
1035 VALUE tmp, uf;
1036 rb_len_t size, *uf_parents, *tmp_array;
1037 VALUE set_class = rb_obj_class(set);
1038 VALUE items = set_i_to_a(set);
1039 rb_ary_freeze(items);
1040 size = RARRAY_LEN(items);
1041 tmp_array = ALLOCV_N(rb_len_t, tmp, size);
1042 uf_parents = ALLOCV_N(rb_len_t, uf, size);
1043 for (rb_len_t i = 0; i < size; i++) {
1044 uf_parents[i] = i;
1045 }
1046 for (rb_len_t i = 0; i < size - 1; i++) {
1047 VALUE item1 = RARRAY_AREF(items, i);
1048 for (rb_len_t j = i + 1; j < size; j++) {
1049 VALUE item2 = RARRAY_AREF(items, j);
1050 if (RTEST(rb_yield_values(2, item1, item2)) &&
1051 RTEST(rb_yield_values(2, item2, item1))) {
1052 set_divide_union_find_merge(uf_parents, i, j, tmp_array);
1053 }
1054 }
1055 }
1056 VALUE final_set = set_s_create(0, 0, rb_cSet);
1057 VALUE hash = rb_hash_new();
1058 for (rb_len_t i = 0; i < size; i++) {
1059 VALUE v = RARRAY_AREF(items, i);
1060 rb_len_t root = set_divide_union_find_root(uf_parents, i, tmp_array);
1061 VALUE subset = rb_hash_aref(hash, LEN2NUM(root));
1062 if (subset == Qnil) {
1063 subset = set_s_alloc(set_class);
1064 if (RSET_COMPARE_BY_IDENTITY(set)) {
1065 set_i_compare_by_identity(subset);
1066 }
1067 rb_hash_aset(hash, LEN2NUM(root), subset);
1068 set_i_add(final_set, subset);
1069 }
1070 set_i_add(subset, v);
1071 }
1072 ALLOCV_END(tmp);
1073 ALLOCV_END(uf);
1074 return final_set;
1075}
1076
1077static void set_merge_enum_into(VALUE set, VALUE arg);
1078
1079/*
1080 * call-seq:
1081 * divide {|ele| ... } -> new_set
1082 * divide {|ele0, ele1| ... } -> new_set
1083 * divide -> enumerator
1084 *
1085 * With a block given, returns a set of sets.
1086 *
1087 * For a block that accepts one argument,
1088 * calls the block with each element;
1089 * creates a set for each distinct block return value:
1090 *
1091 * set = Set[*0..9]
1092 * # => Set[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1093 * # Divide into mod 3 sets.
1094 * set.divide {|ele| ele % 3 }
1095 * # => Set[Set[0, 3, 6, 9], Set[1, 4, 7], Set[2, 5, 8]]
1096 * # Divide into mod 5 sets.
1097 * set.divide {|ele| ele % 5 }
1098 * # => Set[Set[0, 5], Set[1, 6], Set[2, 7], Set[3, 8], Set[4, 9]]
1099 *
1100 * Set[0].divide {|ele| anything } # => Set[Set[0]]
1101 * Set[].divide {|ele| not called } # => Set[]
1102 *
1103 * For a block that accepts two arguments,
1104 * divides +self+ into connected components based on the binary
1105 * relation defined by the block, calling the block with each 2-element
1106 * permutation of the elements of +self+:
1107 *
1108 * set = Set[*0..9]
1109 * # => Set[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1110 * # Divide into mod 2 sets.
1111 * set.divide {|i, j| (i - j) % 2 == 0 }
1112 * # => Set[Set[0, 2, 4, 6, 8], Set[1, 3, 5, 7, 9]]
1113 * # Divide into mod 3 sets.
1114 * set.divide {|i, j| (i - j) % 3 == 0 }
1115 * # => Set[Set[0, 3, 6, 9], Set[1, 4, 7], Set[2, 5, 8]]
1116 *
1117 * Set[0].divide {|i, j| not called } # => Set[Set[0]]
1118 * Set[].divide {|i, j| not called } # => Set[]
1119 *
1120 * With no block given, returns an Enumerator.
1121 *
1122 * Related: see {Methods for Converting}[rdoc-ref:Set@Methods+for+Converting].
1123 */
1124static VALUE
1125set_i_divide(VALUE set)
1126{
1127 RETURN_SIZED_ENUMERATOR(set, 0, 0, set_enum_size);
1128
1129 if (rb_block_arity() == 2) {
1130 return set_divide_arity2(set);
1131 }
1132
1133 VALUE values = rb_hash_values(set_i_classify(set));
1134 set = set_alloc_with_size(rb_cSet, RARRAY_LEN(values));
1135 set_merge_enum_into(set, values);
1136 return set;
1137}
1138
1139static int
1140set_clear_i(st_data_t key, st_data_t dummy)
1141{
1142 return ST_DELETE;
1143}
1144
1145/*
1146 * call-seq:
1147 * clear -> self
1148 *
1149 * Returns +self+ with all elements removed:
1150 *
1151 * Set[1, :one, 'one', 1.0].clear # => Set[]
1152 *
1153 * Related: see {Methods for Deleting}[rdoc-ref:Set@Methods+for+Deleting].
1154 */
1155static VALUE
1156set_i_clear(VALUE set)
1157{
1158 rb_check_frozen(set);
1159 if (RSET_SIZE(set) == 0) return set;
1160 if (set_iterating_p(set)) {
1161 set_iter(set, set_clear_i, 0);
1162 }
1163 else {
1164 set_table_clear(RSET_TABLE(set));
1165 set_compact_after_delete(set);
1166 }
1167 return set;
1168}
1169
1171 VALUE set;
1172 VALUE other_set;
1173 VALUE new_set;
1174 set_table *into;
1175 set_table *other;
1176};
1177
1178static int
1179set_intersection_i(st_data_t key, st_data_t tmp)
1180{
1181 struct set_intersection_data *data = MEMO_FOR(struct set_intersection_data, tmp);
1182 if (set_table_lookup(data->other, key)) {
1183 set_table_insert_wb(data->into, data->set, key);
1184 }
1185
1186 return ST_CONTINUE;
1187}
1188
1189static VALUE
1190set_intersection_block(RB_BLOCK_CALL_FUNC_ARGLIST(i, data))
1191{
1192 set_intersection_i((st_data_t)i, (st_data_t)data);
1193 return i;
1194}
1195
1196/*
1197 * call-seq:
1198 * self & enumerable -> new_set
1199 *
1200 * Returns a new set containing the {intersection}[https://en.wikipedia.org/wiki/Intersection_(set_theory)]
1201 * of +self+ and +enumerable+;
1202 * that is, containing all elements common to both, with no duplicates.
1203 * Argument +enumerable+ must be an Enumerable object:
1204 *
1205 * set = Set[*(0..6), *%w[ a b c]] # => Set[0, 1, 2, 3, 4, 5, 6, "a", "b", "c"]
1206 * set & ['c', 6, 8, 4] # => Set["c", 6, 4]
1207 * set & [:foo, :bar] # => Set[] # No elements in common.
1208 *
1209 * Related: see {Methods for Set Operations}[rdoc-ref:Set@Methods+for+Set+Operations].
1210 */
1211static VALUE
1212set_i_intersection(VALUE set, VALUE other)
1213{
1214 VALUE new_set = set_s_alloc(rb_obj_class(set));
1215 if (RSET_COMPARE_BY_IDENTITY(set)) {
1216 set_i_compare_by_identity(new_set);
1217 }
1218 set_table *stable = RSET_TABLE(set);
1219 set_table *ntable = RSET_TABLE(new_set);
1220 VALUE data;
1221
1222 if (rb_obj_is_kind_of(other, rb_cSet)) {
1223 set_table *otable = RSET_TABLE(other);
1224 if (set_table_size(stable) >= set_table_size(otable)) {
1225 /* Swap so we iterate over the smaller set */
1226 otable = stable;
1227 set = other;
1228 }
1229
1230 *NEW_PARTIAL_MEMO_FOR(struct set_intersection_data, data, into) = (struct set_intersection_data) {
1231 .set = new_set,
1232 .other_set = other,
1233 .new_set = new_set,
1234 .into = ntable,
1235 .other = otable,
1236 };
1237 set_iter(set, set_intersection_i, (st_data_t)data);
1238 }
1239 else {
1240 *NEW_PARTIAL_MEMO_FOR(struct set_intersection_data, data, into) = (struct set_intersection_data) {
1241 .set = new_set,
1242 .other_set = other,
1243 .new_set = new_set,
1244 .into = ntable,
1245 .other = stable,
1246 };
1247 rb_block_call(other, enum_method_id(other), 0, 0, set_intersection_block, data);
1248 }
1249 RB_GC_GUARD(data);
1250
1251 return new_set;
1252}
1253
1254/*
1255 * call-seq:
1256 * include?(object) -> true or false
1257 *
1258 * Returns whether the given +object+ is an element of +self+:
1259 *
1260 * set = Set[0, :zero, '0']
1261 * set.include?('0') # => true
1262 * set.include?('zero') # => false
1263 *
1264 * Tests equality using `hash` and `eql?`.
1265 *
1266 * Aliased as #===, which means that sets may be used in +case+ expressions:
1267 *
1268 * case :apple
1269 * when Set[:potato, :carrot]
1270 * 'vegetable'
1271 * when Set[:apple, :banana]
1272 * 'fruit'
1273 * else
1274 * 'unknown'
1275 * end
1276 * # => "fruit"
1277 *
1278 * Related: see {Methods for Querying}[rdoc-ref:Set@Methods+for+Querying].
1279 */
1280static VALUE
1281set_i_include(VALUE set, VALUE item)
1282{
1283 return RBOOL(RSET_IS_MEMBER(set, item));
1284}
1285
1287 VALUE set;
1288 set_table *into;
1289};
1290
1291static int
1292set_merge_i(st_data_t key, st_data_t data)
1293{
1294 struct set_merge_args *args = (struct set_merge_args *)data;
1295 set_table_insert_wb(args->into, args->set, key);
1296 return ST_CONTINUE;
1297}
1298
1299static VALUE
1300set_merge_block(RB_BLOCK_CALL_FUNC_ARGLIST(key, set))
1301{
1302 VALUE element = key;
1303 set_insert_wb(set, element);
1304 return element;
1305}
1306
1307static void
1308set_merge_enum_into(VALUE set, VALUE arg)
1309{
1310 if (rb_obj_is_kind_of(arg, rb_cSet)) {
1311 struct set_merge_args args = {
1312 .set = set,
1313 .into = RSET_TABLE(set)
1314 };
1315 set_iter(arg, set_merge_i, (st_data_t)&args);
1316 }
1317 else if (RB_TYPE_P(arg, T_ARRAY)) {
1318 rb_len_t i;
1319 set_table *into = RSET_TABLE(set);
1320 for (i=0; i<RARRAY_LEN(arg); i++) {
1321 set_table_insert_wb(into, set, RARRAY_AREF(arg, i));
1322 }
1323 RB_GC_GUARD(arg);
1324 }
1325 else {
1326 rb_block_call(arg, enum_method_id(arg), 0, 0, set_merge_block, set);
1327 }
1328}
1329
1330/*
1331 * call-seq:
1332 * merge(*enumerables, **nil) -> self
1333 *
1334 * Adds each element of each of the given +enumerables+ to +self+;
1335 * returns +self+:
1336 *
1337 * set = Set[*0..2] # => Set[0, 1, 2]
1338 * set.merge('a'..'c', %w[foo bar]) # => Set[0, 1, 2, "a", "b", "c", "foo", "bar"]
1339 * set.merge('a'..'c', %w[foo bar]) # => Set[0, 1, 2, "a", "b", "c", "foo", "bar"]
1340 *
1341 * Related: see {Methods for Assigning}[rdoc-ref:Set@Methods+for+Assigning].
1342 *
1343 */
1344static VALUE
1345set_i_merge(int argc, VALUE *argv, VALUE set)
1346{
1347 if (rb_keyword_given_p()) {
1348 rb_raise(rb_eArgError, "no keywords accepted");
1349 }
1350
1351 if (set_iterating_p(set)) {
1352 rb_raise(rb_eRuntimeError, "cannot add to set during iteration");
1353 }
1354
1355 rb_check_frozen(set);
1356
1357 int i;
1358
1359 for (i=0; i < argc; i++) {
1360 set_merge_enum_into(set, argv[i]);
1361 }
1362
1363 return set;
1364}
1365
1366static VALUE
1367set_reset_table_with_type(VALUE set, const struct st_hash_type *type)
1368{
1369 rb_check_frozen(set);
1370
1371 struct set_object *sobj;
1372 TypedData_Get_Struct(set, struct set_object, &set_data_type, sobj);
1373 set_table *old = &sobj->table;
1374
1375 size_t size = set_table_size(old);
1376 if (size > 0) {
1377 VALUE tmp = set_alloc_with_size_and_type(0, size, type);
1378 set_table *new = RSET_TABLE(tmp);
1379 struct set_merge_args args = {
1380 .set = tmp,
1381 .into = new
1382 };
1383 set_iter(set, set_merge_i, (st_data_t)&args);
1384 if (set_iterating_p(set)) {
1385 rb_raise(rb_eRuntimeError, "reset during iteration");
1386 }
1387 set_table old_table = sobj->table;
1388 sobj->table = *new;
1389 *new = old_table;
1390 rb_gc_writebarrier_remember(set);
1391 rb_gc_writebarrier_remember(tmp);
1392 RB_GC_GUARD(tmp);
1393 }
1394 else {
1395 sobj->table.type = type;
1396 }
1397
1398 return set;
1399}
1400
1401/*
1402 * call-seq:
1403 * compare_by_identity -> self
1404 *
1405 * Sets +self+ to compare by object identity
1406 * (rather than by object content, which is the initial setting);
1407 * returns +self+:
1408 *
1409 * set = Set.new
1410 * set.compare_by_identity
1411 * str = +"foo"
1412 * set.add(str)
1413 * # => Set["foo"]
1414 * set.include?(str)
1415 * # => true
1416 * set.add(str)
1417 * # => Set["foo"])
1418 * set.include?(+"foo")
1419 * # => false
1420 * set.add(+"foo")
1421 * # => Set["foo", "foo"])
1422 *
1423 * Once set, the compare-by-identity property may not be unset.
1424 *
1425 * Related: #compare_by_identity?.
1426 */
1427static VALUE
1428set_i_compare_by_identity(VALUE set)
1429{
1430 if (RSET_COMPARE_BY_IDENTITY(set)) return set;
1431
1432 if (set_iterating_p(set)) {
1433 rb_raise(rb_eRuntimeError, "compare_by_identity during iteration");
1434 }
1435
1436 return set_reset_table_with_type(set, &identhash);
1437}
1438
1439/*
1440 * call-seq:
1441 * compare_by_identity? -> true or false
1442 *
1443 * Returns whether +self+ compares elements by object identity
1444 * (rather than by content):
1445 *
1446 * set = Set[]
1447 * set.compare_by_identity? # => false
1448 * set.compare_by_identity
1449 * set.compare_by_identity? # => true
1450 *
1451 * Related: #compare_by_identity;
1452 * see also {Methods for Querying}[rdoc-ref:Set@Methods+for+Querying].
1453 */
1454static VALUE
1455set_i_compare_by_identity_p(VALUE set)
1456{
1457 return RBOOL(RSET_COMPARE_BY_IDENTITY(set));
1458}
1459
1460/*
1461 * call-seq:
1462 * size -> integer
1463 *
1464 * Returns the number of elements in +self+:
1465 *
1466 * Set[*0..9].size # => 10
1467 *
1468 * Related: see {Methods for Querying}[rdoc-ref:Set@Methods+for+Querying].
1469 */
1470static VALUE
1471set_i_size(VALUE set)
1472{
1473 return RSET_SIZE_NUM(set);
1474}
1475
1476/*
1477 * call-seq:
1478 * empty? -> true or false
1479 *
1480 * Returns whether +self+ contains no elements:
1481 *
1482 * Set[].empty? # => true
1483 * Set[0].empty? # => false
1484 *
1485 * Related: see {Methods for Querying}[rdoc-ref:Set@Methods+for+Querying].
1486 */
1487static VALUE
1488set_i_empty(VALUE set)
1489{
1490 return RBOOL(RSET_EMPTY(set));
1491}
1492
1493static int
1494set_xor_i(st_data_t key, st_data_t data)
1495{
1496 VALUE element = (VALUE)key;
1497 VALUE set = (VALUE)data;
1498 set_table *table = RSET_TABLE(set);
1499 if (set_table_insert_wb(table, set, element)) {
1500 set_table_delete(table, &element);
1501 }
1502 return ST_CONTINUE;
1503}
1504
1505/*
1506 * call-seq:
1507 * self ^ enumerable -> new_set
1508 *
1509 * Returns a new set containing
1510 * the {exclusive OR}[https://en.wikipedia.org/wiki/Exclusive_or]
1511 * of +self+ and the given +enumerable+;
1512 * that is, containing each element that is in either +self+ or +enumerable+,
1513 * but not in both:
1514 *
1515 * set = Set[0, 1, 2]
1516 * set ^ Set[1, 2, 3] # => Set[0, 3]
1517 * set ^ Set[2, 1] # => Set[0]
1518 * set ^ Set[2, *('a'..'c')] # => Set[0, 1, "a", "b", "c"]
1519 * set ^ Set[2, 1, 0] # => Set[]
1520 *
1521 * For \Set +set+ and \Enumerable +enumerable+, these expressions are equivalent:
1522 *
1523 * set ^ enumerable
1524 * ((set | enumerable) - (set & enumerable))
1525 *
1526 * Related: see {Methods for Set Operations}[rdoc-ref:Set@Methods+for+Set+Operations].
1527 */
1528static VALUE
1529set_i_xor(VALUE set, VALUE other)
1530{
1531 VALUE new_set = rb_obj_dup(set);
1532
1533 if (rb_obj_is_kind_of(other, rb_cSet)) {
1534 set_iter(other, set_xor_i, (st_data_t)new_set);
1535 }
1536 else {
1537 VALUE tmp = set_s_alloc(rb_obj_class(new_set));
1538 if (RSET_COMPARE_BY_IDENTITY(new_set)) {
1539 set_i_compare_by_identity(tmp);
1540 }
1541 set_merge_enum_into(tmp, other);
1542 set_iter(tmp, set_xor_i, (st_data_t)new_set);
1543 }
1544 set_compact_after_delete(new_set);
1545
1546 return new_set;
1547}
1548
1549/*
1550 * call-seq:
1551 * self | enumerable -> new_set
1552 *
1553 * Returns a new set containing
1554 * the {union}[https://en.wikipedia.org/wiki/Union_(set_theory)]
1555 * of +self+ and the given +enumerable+;
1556 * that is, containing the elements of both +self+ and +enumerable+.
1557 *
1558 * set = Set[0, 1, 2]
1559 * set | Set[2, 1, 'a'] # => Set[0, 1, 2, "a"]
1560 * set | set # => Set[0, 1, 2]
1561 *
1562 * Related: see {Methods for Set Operations}[rdoc-ref:Set@Methods+for+Set+Operations].
1563 */
1564static VALUE
1565set_i_union(VALUE set, VALUE other)
1566{
1567 set = rb_obj_dup(set);
1568 set_merge_enum_into(set, other);
1569 return set;
1570}
1571
1572static int
1573set_remove_i(st_data_t key, st_data_t from)
1574{
1575 st_data_t key_data = (st_data_t)key;
1576 set_table_delete((struct set_table *)from, &key_data);
1577 return ST_CONTINUE;
1578}
1579
1580static VALUE
1581set_remove_block(RB_BLOCK_CALL_FUNC_ARGLIST(key, set))
1582{
1583 st_data_t key_data = (st_data_t)key;
1584 rb_check_frozen(set);
1585 set_table_delete(RSET_TABLE(set), &key_data);
1586 return (VALUE)key_data;
1587}
1588
1589static void
1590set_remove_enum_from(VALUE set, VALUE arg)
1591{
1592 if (rb_obj_is_kind_of(arg, rb_cSet)) {
1593 set_iter(arg, set_remove_i, (st_data_t)RSET_TABLE(set));
1594 }
1595 else {
1596 rb_block_call(arg, enum_method_id(arg), 0, 0, set_remove_block, set);
1597 }
1598 set_compact_after_delete(set);
1599}
1600
1601/*
1602 * call-seq:
1603 * subtract(enumerable) -> self
1604 *
1605 * Deletes from +self+ every element found in the given +enumerable+;
1606 * returns +self+:
1607 *
1608 * set = Set[*0..9] # => Set[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1609 * set.subtract(5..14) # => Set[0, 1, 2, 3, 4]
1610 * set.subtract(Set[6, 2]) # => Set[0, 1, 3, 4]
1611 *
1612 * Related: see {Methods for Deleting}[rdoc-ref:Set@Methods+for+Deleting].
1613 */
1614static VALUE
1615set_i_subtract(VALUE set, VALUE other)
1616{
1617 rb_check_frozen(set);
1618 set_remove_enum_from(set, other);
1619 return set;
1620}
1621
1622/*
1623 * call-seq:
1624 * self - enumerable -> new_set
1625 *
1626 * Returns a new set containing the
1627 * {difference}[https://en.wikipedia.org/wiki/Complement_(set_theory)#Relative_complement]
1628 * of +self+ and argument +enumerable+;
1629 * that is, containing all elements in +self+ that are not in +enumerable+.
1630 *
1631 *
1632 * set = Set[*(0..6), *%w[ a b c]] # => Set[0, 1, 2, 3, 4, 5, 6, "a", "b", "c"]
1633 * set - ['b', 6, 4, 1] # => Set[0, 2, 3, 5, "a", "c"]
1634 * set - ['d', 7, 9] # => Set[0, 1, 2, 3, 4, 5, 6, "a", "b", "c"]
1635 *
1636 * Related: see {Methods for Set Operations}[rdoc-ref:Set@Methods+for+Set+Operations].
1637 */
1638static VALUE
1639set_i_difference(VALUE set, VALUE other)
1640{
1641 return set_i_subtract(rb_obj_dup(set), other);
1642}
1643
1644static int
1645set_each_i(st_data_t key, st_data_t dummy)
1646{
1647 rb_yield(key);
1648 return ST_CONTINUE;
1649}
1650
1651/*
1652 * call-seq:
1653 * each {|element| ... } -> self
1654 * each -> enumerator
1655 *
1656 * With a block given, calls the block once for each element in the set,
1657 * passing the element as a parameter;
1658 * returns +self+:
1659 *
1660 * sum = 0
1661 * Set[1, 2, 3].each {|i| sum += i }
1662 * sum # => 6
1663 *
1664 * With no block given, returns an Enumerator.
1665 */
1666static VALUE
1667set_i_each(VALUE set)
1668{
1669 RETURN_SIZED_ENUMERATOR(set, 0, 0, set_enum_size);
1670 set_iter(set, set_each_i, 0);
1671 return set;
1672}
1673
1674static int
1675set_collect_i(st_data_t key, st_data_t data)
1676{
1677 set_insert_wb((VALUE)data, rb_yield((VALUE)key));
1678 return ST_CONTINUE;
1679}
1680
1681/*
1682 * call-seq:
1683 * collect! {|element| ... } -> self
1684 * collect! -> enumerator
1685 *
1686 * With a block given, calls the block with each element in +self+;
1687 * replaces the element with the block's return value:
1688 *
1689 * Set[1, :one, 'one', 1.0].collect! {|element| element.class }
1690 * # => Set[Integer, Symbol, String, Float]
1691 *
1692 * With no block given, returns an Enumerator.
1693 *
1694 * Related: see {Methods for Converting}[rdoc-ref:Set@Methods+for+Converting].
1695 */
1696static VALUE
1697set_i_collect(VALUE set)
1698{
1699 RETURN_SIZED_ENUMERATOR(set, 0, 0, set_enum_size);
1700 rb_check_frozen(set);
1701
1702 VALUE new_set = set_s_alloc(rb_obj_class(set));
1703 if (RSET_COMPARE_BY_IDENTITY(set)) {
1704 set_i_compare_by_identity(new_set);
1705 }
1706 set_iter(set, set_collect_i, (st_data_t)new_set);
1707 set_i_initialize_copy(set, new_set);
1708
1709 return set;
1710}
1711
1712static int
1713set_keep_if_i(st_data_t key, st_data_t into)
1714{
1715 if (!RTEST(rb_yield((VALUE)key))) {
1716 set_table_delete((set_table *)into, &key);
1717 }
1718 return ST_CONTINUE;
1719}
1720
1721/*
1722 * call-seq:
1723 * keep_if {|element| ... } -> self
1724 * keep_if -> enumerator
1725 *
1726 * With a block given,
1727 * calls the block with each element in +self+,
1728 * deleting the element if the block returns +false+ or +nil+;
1729 * returns +self+:
1730 *
1731 * set = Set[*0..9] # => Set[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1732 * set.keep_if {|i| i.even? } # => Set[0, 2, 4, 6, 8]
1733 * set.keep_if {|i| i.odd? } # => Set[]
1734 *
1735 * With no block given, returns an Enumerator.
1736 *
1737 * Related: see {Methods for Deleting}[rdoc-ref:Set@Methods+for+Deleting].
1738 */
1739static VALUE
1740set_i_keep_if(VALUE set)
1741{
1742 RETURN_SIZED_ENUMERATOR(set, 0, 0, set_enum_size);
1743 rb_check_frozen(set);
1744
1745 set_iter(set, set_keep_if_i, (st_data_t)RSET_TABLE(set));
1746 set_compact_after_delete(set);
1747
1748 return set;
1749}
1750
1751/*
1752 * call-seq:
1753 * select! {|element| ... } -> self or nil
1754 * select! -> enumerator
1755 *
1756 * With a block given, like #keep_if, but returns +nil+ if no changes were made:
1757 *
1758 * set = Set[*0..9] # => Set[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1759 * set.select! {|i| i.even? } # => Set[0, 2, 4, 6, 8]
1760 * set.select! {|i| i.even? } # => nil
1761 * set.select! {|i| i.odd? } # => Set[]
1762 *
1763 * With no block given, returns an Enumerator.
1764 *
1765 * Related: see {Methods for Deleting}[rdoc-ref:Set@Methods+for+Deleting].
1766 */
1767static VALUE
1768set_i_select(VALUE set)
1769{
1770 RETURN_SIZED_ENUMERATOR(set, 0, 0, set_enum_size);
1771 rb_check_frozen(set);
1772
1773 set_table *table = RSET_TABLE(set);
1774 size_t n = set_table_size(table);
1775 set_iter(set, set_keep_if_i, (st_data_t)table);
1776 set_compact_after_delete(set);
1777
1778 return (n == set_table_size(table)) ? Qnil : set;
1779}
1780
1781/*
1782 * call-seq:
1783 * replace(enumerable) -> self
1784 *
1785 * Replaces the contents +self+ with the contents of the given +enumerable+;
1786 * returns +self+:
1787 *
1788 * set = Set[1, 'c', :s] # => Set[1, "c", :s]
1789 * set.replace([1, 2]) # => Set[1, 2]
1790 *
1791 * Related: see {Methods for Assigning}[rdoc-ref:Set@Methods+for+Assigning].
1792 */
1793static VALUE
1794set_i_replace(VALUE set, VALUE other)
1795{
1796 rb_check_frozen(set);
1797
1798 if (rb_obj_is_kind_of(other, rb_cSet)) {
1799 set_i_initialize_copy(set, other);
1800 }
1801 else {
1802 if (set_iterating_p(set)) {
1803 rb_raise(rb_eRuntimeError, "cannot replace set during iteration");
1804 }
1805
1806 // make sure enum is enumerable before calling clear
1807 enum_method_id(other);
1808
1809 set_table_clear(RSET_TABLE(set));
1810 set_merge_enum_into(set, other);
1811 }
1812 set_compact_after_delete(set);
1813
1814 return set;
1815}
1816
1817/*
1818 * call-seq:
1819 * reset -> self
1820 *
1821 * Resets the internal state of +self+; returns +self+.
1822 *
1823 * A set relies on the #hash results of each element being consistent.
1824 * Modifying an element in a way that changes the results of #hash
1825 * may allow duplicate elements in the set:
1826 *
1827 * array = [1]
1828 * set = Set[array] # => Set[[1]]
1829 * array << 2
1830 * set.add(array) # => Set[[1, 2], [1, 2]]
1831 *
1832 * Calling #reset will recalculate all of the hash values and remove
1833 * duplicate elements:
1834 *
1835 * set.reset # => Set[[1, 2]]
1836 *
1837 */
1838static VALUE
1839set_i_reset(VALUE set)
1840{
1841 if (set_iterating_p(set)) {
1842 rb_raise(rb_eRuntimeError, "reset during iteration");
1843 }
1844
1845 return set_reset_table_with_type(set, RSET_TABLE(set)->type);
1846}
1847
1848static void set_flatten_merge(VALUE set, VALUE from, VALUE seen);
1849
1850static int
1851set_flatten_merge_i(st_data_t item, st_data_t arg)
1852{
1853 VALUE *args = (VALUE *)arg;
1854 VALUE set = args[0];
1855 if (rb_obj_is_kind_of(item, rb_cSet)) {
1856 VALUE e_id = rb_obj_id(item);
1857 VALUE hash = args[2];
1858 switch(rb_hash_aref(hash, e_id)) {
1859 case Qfalse:
1860 return ST_CONTINUE;
1861 case Qtrue:
1862 rb_raise(rb_eArgError, "tried to flatten recursive Set");
1863 default:
1864 break;
1865 }
1866
1867 rb_hash_aset(hash, e_id, Qtrue);
1868 set_flatten_merge(set, item, hash);
1869 rb_hash_aset(hash, e_id, Qfalse);
1870 }
1871 else {
1872 set_i_add(set, item);
1873 }
1874 return ST_CONTINUE;
1875}
1876
1877static void
1878set_flatten_merge(VALUE set, VALUE from, VALUE hash)
1879{
1880 VALUE args[3] = {set, from, hash};
1881 set_iter(from, set_flatten_merge_i, (st_data_t)args);
1882}
1883
1884/*
1885 * call-seq:
1886 * flatten -> new_set
1887 *
1888 * Returns a new set that is a copy of +self+,
1889 * but with +self+ and its nested sets flattened;
1890 * that is, their elements become elements of +self+:
1891 *
1892 * Set[Set[0, 1], Set[2, 3]].flatten
1893 * # => Set[0, 1, 2, 3]
1894 * Set[Set[0, 1], Set[Set[2, 3], Set[3, 4]]].flatten
1895 * # => Set[0, 1, 2, 3, 4]
1896 *
1897 * Does not flatten nested arrays or hashes:
1898 *
1899 * Set[%w[foo bar]].flatten # => Set[["foo", "bar"]]
1900 * Set[{foo: 0, bar: 1}].flatten # => Set[{foo: 0, bar: 1}]
1901 *
1902 * Related: see {Methods for Converting}[rdoc-ref:Set@Methods+for+Converting].
1903 */
1904static VALUE
1905set_i_flatten(VALUE set)
1906{
1907 VALUE new_set = set_s_alloc(rb_obj_class(set));
1908 if (RSET_COMPARE_BY_IDENTITY(set)) {
1909 set_i_compare_by_identity(new_set);
1910 }
1911 set_flatten_merge(new_set, set, rb_hash_new());
1912 return new_set;
1913}
1914
1915static int
1916set_contains_set_i(st_data_t item, st_data_t arg)
1917{
1918 if (rb_obj_is_kind_of(item, rb_cSet)) {
1919 *(bool *)arg = true;
1920 return ST_STOP;
1921 }
1922 return ST_CONTINUE;
1923}
1924
1925/*
1926 * call-seq:
1927 * flatten! -> self or nil
1928 *
1929 * Like #flatten, but if any changes were made
1930 * replaces +self+ with the result and returns +self+:
1931 *
1932 * Set[Set[0, 1], Set[2, 3]].flatten!
1933 * # => Set[0, 1, 2, 3]
1934 * Set[Set[0, 1], Set[Set[2, 3], Set[3, 4]]].flatten!
1935 * # => Set[0, 1, 2, 3, 4]
1936 *
1937 * Returns +nil+ if no changes were made:
1938 *
1939 * Set[0, 1, 2].flatten! # => nil
1940 *
1941 * Related: see {Methods for Assigning}[rdoc-ref:Set@Methods+for+Assigning].
1942 */
1943static VALUE
1944set_i_flatten_bang(VALUE set)
1945{
1946 bool contains_set = false;
1947 set_iter(set, set_contains_set_i, (st_data_t)&contains_set);
1948 if (!contains_set) return Qnil;
1949 rb_check_frozen(set);
1950 return set_i_replace(set, set_i_flatten(set));
1951}
1952
1954 set_table *table;
1955 VALUE result;
1956};
1957
1958static int
1959set_le_i(st_data_t key, st_data_t arg)
1960{
1961 struct set_subset_data *data = (struct set_subset_data *)arg;
1962 if (set_table_lookup(data->table, key)) return ST_CONTINUE;
1963 data->result = Qfalse;
1964 return ST_STOP;
1965}
1966
1967static VALUE
1968set_le(VALUE set, VALUE other)
1969{
1970 struct set_subset_data data = {
1971 .table = RSET_TABLE(other),
1972 .result = Qtrue
1973 };
1974 set_iter(set, set_le_i, (st_data_t)&data);
1975 return data.result;
1976}
1977
1978/*
1979 * call-seq:
1980 * proper_subset?(other_set) -> true or false
1981 *
1982 * Returns whether +self+ is
1983 * a {proper subset}[https://en.wikipedia.org/wiki/Subset]
1984 * of the given +other_set+:
1985 *
1986 * set = Set[*'b'..'e']
1987 * set.proper_subset?(set) # => false
1988 * set.proper_subset?(Set[*'a'..'f']) # => true
1989 *
1990 * Related: {Methods for Querying}[rdoc-ref:Set@Methods+for+Querying].
1991 */
1992static VALUE
1993set_i_proper_subset(VALUE set, VALUE other)
1994{
1995 check_set(other);
1996 if (RSET_SIZE(set) >= RSET_SIZE(other)) return Qfalse;
1997 return set_le(set, other);
1998}
1999
2000/*
2001 * call-seq:
2002 * subset?(other_set) -> true or false
2003 *
2004 * Returns whether +self+ is a {subset}[https://en.wikipedia.org/wiki/Subset]
2005 * of the given +other_set+:
2006 *
2007 * set = Set[*'b'..'e']
2008 * set.subset?(set) # => true
2009 * set.subset?(Set[*'a'..'f']) # => true
2010 * set.subset?(Set[*'c'..'e']) # => false
2011 *
2012 * Related: {Methods for Querying}[rdoc-ref:Set@Methods+for+Querying].
2013 */
2014static VALUE
2015set_i_subset(VALUE set, VALUE other)
2016{
2017 check_set(other);
2018 if (RSET_SIZE(set) > RSET_SIZE(other)) return Qfalse;
2019 return set_le(set, other);
2020}
2021
2022/*
2023 * call-seq:
2024 * proper_superset?(other_set) -> true or false
2025 *
2026 * Returns whether +self+ is
2027 * a {proper superset}[https://en.wikipedia.org/wiki/Subset]
2028 * of the given +other_set+:
2029 *
2030 * set = Set[*'a'..'f']
2031 * set.proper_superset?(set) # => false
2032 * set.proper_superset?(Set[*'b'..'e']) # => true
2033 *
2034 * Related: {Methods for Querying}[rdoc-ref:Set@Methods+for+Querying].
2035 */
2036static VALUE
2037set_i_proper_superset(VALUE set, VALUE other)
2038{
2039 check_set(other);
2040 if (RSET_SIZE(set) <= RSET_SIZE(other)) return Qfalse;
2041 return set_le(other, set);
2042}
2043
2044/*
2045 * call-seq:
2046 * superset?(other_set) -> true or false
2047 *
2048 * Returns whether +self+ is a {superset}[https://en.wikipedia.org/wiki/Subset]
2049 * of the given +other_set+:
2050 *
2051 * set = Set[*'a'..'f'] # => Set["a", "b", "c", "d", "e", "f"]
2052 * set.superset?(set) # => true
2053 * set.superset?(Set[*'b'..'e']) # => true
2054 * set.superset?(Set[*'b'..'x']) # => false
2055 *
2056 * Related: {Methods for Querying}[rdoc-ref:Set@Methods+for+Querying].
2057 */
2058static VALUE
2059set_i_superset(VALUE set, VALUE other)
2060{
2061 check_set(other);
2062 if (RSET_SIZE(set) < RSET_SIZE(other)) return Qfalse;
2063 return set_le(other, set);
2064}
2065
2066static int
2067set_intersect_i(st_data_t key, st_data_t arg)
2068{
2069 VALUE *args = (VALUE *)arg;
2070 if (set_table_lookup((set_table *)args[0], key)) {
2071 args[1] = Qtrue;
2072 return ST_STOP;
2073 }
2074 return ST_CONTINUE;
2075}
2076
2077/*
2078 * call-seq:
2079 * intersect?(enumerable) -> true or false
2080 *
2081 * Returns whether +self+ and +enumerable+ have any elements in common:
2082 *
2083 * set = Set[0, 'zero', :zero]
2084 * set.intersect?([0, 1, 2]) # => true
2085 * set.intersect?(%w[zero one two]) # => true
2086 * set.intersect?(Set[3]) # => false
2087 *
2088 * Related: see {Methods for Querying}[rdoc-ref:Set@Methods+for+Querying].
2089 */
2090static VALUE
2091set_i_intersect(VALUE set, VALUE other)
2092{
2093 if (rb_obj_is_kind_of(other, rb_cSet)) {
2094 size_t set_size = RSET_SIZE(set);
2095 size_t other_size = RSET_SIZE(other);
2096 VALUE args[2];
2097 args[1] = Qfalse;
2098 VALUE iter_arg;
2099
2100 if (set_size < other_size) {
2101 iter_arg = set;
2102 args[0] = (VALUE)RSET_TABLE(other);
2103 }
2104 else {
2105 iter_arg = other;
2106 args[0] = (VALUE)RSET_TABLE(set);
2107 }
2108 set_iter(iter_arg, set_intersect_i, (st_data_t)args);
2109 return args[1];
2110 }
2111 else if (rb_obj_is_kind_of(other, rb_mEnumerable)) {
2112 return rb_funcall(other, id_any_p, 1, set);
2113 }
2114 else {
2115 rb_raise(rb_eArgError, "value must be enumerable");
2116 }
2117}
2118
2119/*
2120 * call-seq:
2121 * disjoint?(enumerable) -> true or false
2122 *
2123 * Returns whether no element of +enumerable+ is present in +self+:
2124 *
2125 * set = Set[0, 'zero', :zero]
2126 * set.disjoint?([1, 2, 3]) # => true
2127 * set.disjoint?([0, 1, 2, 3]) # => false
2128 *
2129 * Related: see {Methods for Querying}[rdoc-ref:Set@Methods+for+Querying].
2130 */
2131static VALUE
2132set_i_disjoint(VALUE set, VALUE other)
2133{
2134 return RBOOL(!RTEST(set_i_intersect(set, other)));
2135}
2136
2137/*
2138 * call-seq:
2139 * self <=> object -> -1, 0, 1, or nil
2140 *
2141 * Compares +self+ and +object+.
2142 *
2143 * If +object+ is another set, returns:
2144 *
2145 * - +-1+, if +self+ is a proper subset of +object+.
2146 * - +0+, if +self+ and +object+ have the same elements.
2147 * - +1+, if +self+ is a proper superset of +object+.
2148 * - +nil+, if none of the above;
2149 * that is, if +self+ and +object+ each have one or more elements
2150 * not included in the other.
2151 *
2152 * Examples:
2153 *
2154 * set = Set[0, 1, 2]
2155 * set <=> Set[3, 2, 1, 0] # => -1
2156 * set <=> Set[2, 1, 0] # => 0
2157 * set <=> Set[1, 0] # => 1
2158 * set <=> Set[1, 0, 3] # => nil
2159 *
2160 * Returns +nil+ if +object+ is not a set:
2161 *
2162 * set <=> [2, 1, 0] # => nil # Array, not Set.
2163 *
2164 * Related: see {Methods for Comparing}[rdoc-ref:Set@Methods+for+Comparing].
2165 */
2166static VALUE
2167set_i_compare(VALUE set, VALUE other)
2168{
2169 if (rb_obj_is_kind_of(other, rb_cSet)) {
2170 size_t set_size = RSET_SIZE(set);
2171 size_t other_size = RSET_SIZE(other);
2172
2173 if (set_size < other_size) {
2174 if (set_le(set, other) == Qtrue) {
2175 return INT2NUM(-1);
2176 }
2177 }
2178 else if (set_size > other_size) {
2179 if (set_le(other, set) == Qtrue) {
2180 return INT2NUM(1);
2181 }
2182 }
2183 else if (set_le(set, other) == Qtrue) {
2184 return INT2NUM(0);
2185 }
2186 }
2187
2188 return Qnil;
2189}
2190
2192 VALUE result;
2193 VALUE set;
2194};
2195
2196static int
2197set_eql_i(st_data_t item, st_data_t arg)
2198{
2199 struct set_equal_data *data = (struct set_equal_data *)arg;
2200
2201 if (!set_table_lookup(RSET_TABLE(data->set), item)) {
2202 data->result = Qfalse;
2203 return ST_STOP;
2204 }
2205 return ST_CONTINUE;
2206}
2207
2208static VALUE
2209set_recursive_eql(VALUE set, VALUE dt, int recur)
2210{
2211 if (recur) return Qtrue;
2212 struct set_equal_data *data = (struct set_equal_data*)dt;
2213 data->result = Qtrue;
2214 set_iter(set, set_eql_i, dt);
2215 return data->result;
2216}
2217
2218/*
2219 * call-seq:
2220 * self == object -> true or false
2221 *
2222 * Returns whether +object+ is a set, and has the same elements as +self+:
2223 *
2224 * set = Set[0, 1, 2]
2225 * set == Set[1, 2, 0] # => true
2226 * set == [1, 2, 3] # => false
2227 * set == Set[1, 2, '3'] # => false
2228 *
2229 * Related: see {Methods for Comparing}[rdoc-ref:Set@Methods+for+Comparing].
2230 */
2231static VALUE
2232set_i_eq(VALUE set, VALUE other)
2233{
2234 if (!rb_obj_is_kind_of(other, rb_cSet)) return Qfalse;
2235 if (set == other) return Qtrue;
2236
2237 set_table *stable = RSET_TABLE(set);
2238 set_table *otable = RSET_TABLE(other);
2239 size_t ssize = set_table_size(stable);
2240 size_t osize = set_table_size(otable);
2241
2242 if (ssize != osize) return Qfalse;
2243 if (ssize == 0 && osize == 0) return Qtrue;
2244 if (stable->type != otable->type) return Qfalse;
2245
2246 struct set_equal_data data;
2247 data.set = other;
2248 return rb_exec_recursive_paired(set_recursive_eql, set, other, (VALUE)&data);
2249}
2250
2251static int
2252set_hash_i(st_data_t item, st_data_t(arg))
2253{
2254 st_index_t *hval = (st_index_t *)arg;
2255 st_index_t ival = rb_hash(item);
2256 *hval ^= rb_st_hash(&ival, sizeof(st_index_t), 0);
2257 return ST_CONTINUE;
2258}
2259
2260/*
2261 * call-seq:
2262 * hash -> integer
2263 *
2264 * Returns the integer hash value for +self+.
2265 *
2266 * Two sets with the same content have the same hash value.
2267 *
2268 * Set[0, 1].hash == Set[1, 0].hash # => true
2269 * Set[0, 1].hash == Set[0].hash # => false
2270 */
2271static VALUE
2272set_i_hash(VALUE set)
2273{
2274 st_index_t size = RSET_SIZE(set);
2275 st_index_t hval = rb_st_hash_start(size);
2276 hval = rb_hash_uint(hval, (st_index_t)set_i_hash);
2277 if (size) {
2278 set_iter(set, set_hash_i, (VALUE)&hval);
2279 }
2280 hval = rb_st_hash_end(hval);
2281 return ST2FIX(hval);
2282}
2283
2284/* :nodoc: */
2285static int
2286set_to_hash_i(st_data_t key, st_data_t arg)
2287{
2288 rb_hash_aset((VALUE)arg, (VALUE)key, Qtrue);
2289 return ST_CONTINUE;
2290}
2291
2292static VALUE
2293set_i_to_h(VALUE set)
2294{
2295 rb_len_t size = RSET_SIZE(set);
2296 VALUE hash;
2297 if (RSET_COMPARE_BY_IDENTITY(set)) {
2298 hash = rb_ident_hash_new_capa(size);
2299 }
2300 else {
2301 hash = rb_hash_new_capa(size);
2302 }
2303 rb_hash_set_default(hash, Qfalse);
2304
2305 if (size == 0) return hash;
2306
2307 set_iter(set, set_to_hash_i, (st_data_t)hash);
2308 return hash;
2309}
2310
2311static VALUE
2312compat_dumper(VALUE set)
2313{
2314 VALUE dumper = rb_class_allocate_instance_capa(rb_cObject, 1);
2315 rb_ivar_set(dumper, id_i_hash, set_i_to_h(set));
2316 return dumper;
2317}
2318
2319static int
2320set_i_from_hash_i(st_data_t key, st_data_t val, st_data_t set)
2321{
2322 if ((VALUE)val != Qtrue) {
2323 rb_raise(rb_eRuntimeError, "expect true as Set value: %"PRIsVALUE, rb_obj_class((VALUE)val));
2324 }
2325 set_i_add((VALUE)set, (VALUE)key);
2326 return ST_CONTINUE;
2327}
2328
2329static VALUE
2330set_i_from_hash(VALUE set, VALUE hash)
2331{
2332 Check_Type(hash, T_HASH);
2333 if (rb_hash_compare_by_id_p(hash)) set_i_compare_by_identity(set);
2334 rb_hash_stlike_foreach(hash, set_i_from_hash_i, (st_data_t)set);
2335 return set;
2336}
2337
2338static VALUE
2339compat_loader(VALUE self, VALUE a)
2340{
2341 return set_i_from_hash(self, rb_ivar_get(a, id_i_hash));
2342}
2343
2344/* Internal C-API functions */
2345
2346VALUE
2347rb_ident_set_new(void)
2348{
2349 return set_alloc_with_size_and_type(rb_cSet, 0, &identhash);
2350}
2351
2352bool
2353rb_set_add_no_check(VALUE set, VALUE element)
2354{
2355 if (set_insert(RSET_TABLE(set), (st_data_t)element) == 0) {
2356 RB_OBJ_WRITTEN(set, Qundef, element);
2357 return true;
2358 }
2359 return false;
2360}
2361
2362bool
2363rb_set_delete_no_check(VALUE set, VALUE element)
2364{
2365 st_data_t element_data = (st_data_t)element;
2366 return set_table_delete(RSET_TABLE(set), &element_data) != 0;
2367}
2368
2369VALUE
2370rb_set_to_a(VALUE set)
2371{
2372 return set_i_to_a(set);
2373}
2374
2375/* C-API functions */
2376
2377void
2378rb_set_foreach(VALUE set, int (*func)(VALUE element, VALUE arg), VALUE arg)
2379{
2380 set_iter(set, func, arg);
2381}
2382
2383VALUE
2385{
2386 return set_alloc_with_size(rb_cSet, 0);
2387}
2388
2389VALUE
2391{
2392 return set_alloc_with_size(rb_cSet, (st_index_t)capa);
2393}
2394
2395bool
2397{
2398 return RSET_IS_MEMBER(set, element);
2399}
2400
2401bool
2403{
2404 return set_i_add_p(set, element) != Qnil;
2405}
2406
2407VALUE
2409{
2410 return set_i_clear(set);
2411}
2412
2413bool
2415{
2416 return set_i_delete_p(set, element) != Qnil;
2417}
2418
2419size_t
2421{
2422 return RSET_SIZE(set);
2423}
2424
2425/*
2426 * Document-class: Set
2427 *
2428 * An instance of class \Set contains a collection
2429 * of objects (elements), with no duplicates.
2430 *
2431 * By default:
2432 *
2433 * - Set determines equality via Object#eql? and Object#hash,
2434 * and assumes that these values do not change for a stored element.
2435 * If these values do change, the set enters an unreliable state;
2436 * see #reset.
2437 * - A String instance added to a set is stored as a frozen copy of the string,
2438 * unless it is already frozen.
2439 *
2440 * Calling #compare_by_identity causes:
2441 *
2442 * - All following determinations of equality
2443 * to use object identity instead of the methods mentioned above.
2444 * - A String added to a set is stored "as is", whether or not frozen.
2445 *
2446 * \Set includes module Enumerable, and is easy to use with other enumerable objects.
2447 * Many of its methods accept enumerable objects as arguments;
2448 * any enumerable object may be converted to a set via {#to_set}[rdoc-ref:Enumerable#to_set].
2449 *
2450 * == Contact
2451 *
2452 * - Akinori MUSHA <knu@iDaemons.org> (current maintainer)
2453 *
2454 * == Inheriting from \Set
2455 *
2456 * Before Ruby 4.0 (released in December, 2025),
2457 * class \Set had a different, less efficient implementation.
2458 * In Ruby 4.0, the class was reimplemented in C,
2459 * and the behaviors of some methods were adjusted.
2460 *
2461 * When compatibility with the older implementation is needed,
2462 * a \Set subclass should inherit directly from class +Set+;
2463 * this automatically includes module +Set::SubclassCompatible+,
2464 * which makes behaviors closer to those in the older implementation.
2465 *
2466 * A difference may be seen as follows:
2467 *
2468 * Set[[1, 2, 3]] # => Set[[1, 2, 3]]
2469 * class MySet < Set; end
2470 * MySet[[1, 2, 3]] # => #<MySet: {[1, 2, 3]}> # Same as in Ruby 3.4.
2471 *
2472 * When backward compatibility is not needed,
2473 * a \Set subclass should inherit from +Set::CoreSet+,
2474 * which avoids including the compatibility layer:
2475 *
2476 * class MyCoreSet < Set::CoreSet; end
2477 * MyCoreSet[[1, 2, 3]] # => MyCoreSet[[1, 2, 3]]
2478 *
2479 * == What's Here
2480 *
2481 * First, what's elsewhere. \Class \Set:
2482 *
2483 * - Inherits from {class Object}[rdoc-ref:Object@Whats+Here].
2484 * - Includes {module Enumerable}[rdoc-ref:Enumerable@Whats+Here],
2485 * which provides dozens of additional methods.
2486 *
2487 * In particular, class \Set does not have many methods of its own
2488 * for fetching or for iterating.
2489 * Instead, it relies on those in \Enumerable.
2490 *
2491 * Here, class \Set provides methods that are useful for:
2492 *
2493 * - {Creating a Set}[rdoc-ref:Set@Methods+for+Creating+a+Set]
2494 * - {Set Operations}[rdoc-ref:Set@Methods+for+Set+Operations]
2495 * - {Comparing}[rdoc-ref:Set@Methods+for+Comparing]
2496 * - {Querying}[rdoc-ref:Set@Methods+for+Querying]
2497 * - {Assigning}[rdoc-ref:Set@Methods+for+Assigning]
2498 * - {Deleting}[rdoc-ref:Set@Methods+for+Deleting]
2499 * - {Converting}[rdoc-ref:Set@Methods+for+Converting]
2500 * - {And more....}[rdoc-ref:Set@Other+Methods]
2501 *
2502 * === Methods for Creating a \Set
2503 *
2504 * - ::[]:
2505 * Returns a new set populated with the given objects.
2506 * - ::new:
2507 * Returns a new set based on the given object (if no block given),
2508 * or on the return values from the called block (if a block given).
2509 *
2510 * === Methods for \Set Operations
2511 *
2512 * - #& (aliased as #intersection):
2513 * Returns a new set containing the intersection of +self+ and the given enumerable.
2514 * - #- (aliased as #difference):
2515 * Returns a new set containing the difference of +self+ and the given enumerable.
2516 * - #^: Returns a new set containing the exclusive OR of +self+ and the given enumerable.
2517 * - #| (aliased as #union and #+):
2518 * Returns a new set containing the union of +self+ and the given enumerable.
2519 *
2520 * === Methods for Comparing
2521 *
2522 * - #<=>: Returns -1, 0, or 1 as +self+ is less than, equal to,
2523 * or greater than a given object.
2524 * - #==: Returns whether +self+ and a given enumerable are equal,
2525 * as determined by Object#eql?.
2526 * - #compare_by_identity?:
2527 * Returns whether +self+ considers only identity
2528 * when comparing elements.
2529 * - #proper_subset? (aliased as #<):
2530 * Returns whether +self+ is a proper subset of the given enumerable.
2531 * - #proper_superset? (aliased as #>):
2532 * Returns whether +self+ is a proper superset of the given enumerable.
2533 * - #subset? (aliased as #<=):
2534 * Returns whether +self+ is a subset of the given object.
2535 * - #superset? (aliased as #>=):
2536 * Returns whether +self+ is a superset of the given enumerable.
2537 *
2538 * === Methods for Querying
2539 *
2540 * - #disjoint?:
2541 * Returns whether no element of the given enumerable is present in +self+.
2542 * - #empty?:
2543 * Returns whether +self+ contains no elements.
2544 * - #include? (aliased as #member? and #===):
2545 * Returns whether the given object is an element of +self+.
2546 * - #intersect?:
2547 * Returns whether +self+ and the given enumerable have any elements in common.
2548 * - #size (aliased as #length):
2549 * Returns the number of elements in +self+.
2550 *
2551 * === Methods for Assigning
2552 *
2553 * - #add (aliased as #<<):
2554 * Adds the given object to +self+; returns +self+.
2555 * - #add?:
2556 * Like #add, but returns +nil+ if the given object is already in +self+.
2557 * - #merge:
2558 * Adds each element of each of the given enumerables to +self+; returns +self+.
2559 * - #replace:
2560 * Replaces the contents of +self+ with the contents of the given enumerable;
2561 * returns +self+.
2562 *
2563 * === Methods for Deleting
2564 *
2565 * - #clear:
2566 * Removes all elements from +self+; returns +self+.
2567 * - #delete:
2568 * Removes the given object from +self+ if +self+ includes the object; returns +self+.
2569 * - #delete?:
2570 * Like #delete, but returns +nil+ if the object is not in +self+.
2571 * - #delete_if:
2572 * Calls the block with each element in +self+;
2573 * removes the element if the block returns a truthy value.
2574 * - #keep_if:
2575 * Calls the block with each element in +self+,
2576 * deleting the element if the block returns +false+ or +nil+; returns +self+.
2577 * - #reject!
2578 * Like #delete_if, but returns +nil+ if no changes were made.
2579 * - #select! (aliased as #filter!):
2580 * Like #keep_if, but returns +nil+ if no changes were made.
2581 * - #subtract:
2582 * Deletes from +self+ every element found in the given enumerable; returns +self+:
2583 *
2584 * === Methods for Converting
2585 *
2586 * - #classify:
2587 * Returns a hash that partitions the elements,
2588 * as determined by the given block.
2589 * - #collect! (aliased as #map!):
2590 * Replaces each element with a block return-value.
2591 * - #divide:
2592 * Returns a set of sets that partition the elements,
2593 * as determined by the given block.
2594 * - #flatten:
2595 * Returns a new set that is a recursive flattening of +self+.
2596 * - #flatten!: Like #flatten, but if any changes were made
2597 * replaces +self+ with the result and returns +self+.
2598 * - #inspect (aliased as #to_s):
2599 * Returns a string representation of +self+.
2600 * - #join:
2601 * Returns the string formed by joining the string-converted elements of +self+
2602 * with the given separator.
2603 * - #to_a:
2604 * Returns an array containing the elements of +self+.
2605 * - #to_set:
2606 * With a block given, creates and returns a new set;
2607 * calls the block with each element of +self+,
2608 * and adds the block's returns value to the new set.
2609 *
2610 * === Other Methods
2611 *
2612 * - #compare_by_identity:
2613 * Sets +self+ to compare by object identity (rather than by object content).
2614 * - #each:
2615 * Calls the block with each successive element of +self+; returns +self+.
2616 * - #reset:
2617 * Resets the internal state of +self+; returns +self+.
2618 * Useful if an element has been modified while an element in the set.
2619 *
2620 */
2621void
2622Init_Set(void)
2623{
2624 rb_cSet = rb_define_class("Set", rb_cObject);
2626
2627 id_each_entry = rb_intern_const("each_entry");
2628 id_any_p = rb_intern_const("any?");
2629 id_new = rb_intern_const("new");
2630 id_i_hash = rb_intern_const("@hash");
2631 id_subclass_compatible = rb_intern_const("SubclassCompatible");
2632 id_class_methods = rb_intern_const("ClassMethods");
2633 id_set_iter_lev = rb_make_internal_id();
2634
2635 rb_define_alloc_func(rb_cSet, set_s_alloc);
2636 rb_define_singleton_method(rb_cSet, "[]", set_s_create, -1);
2637
2638 rb_define_method(rb_cSet, "initialize", set_i_initialize, -1);
2639 rb_define_method(rb_cSet, "initialize_copy", set_i_initialize_copy, 1);
2640
2641 rb_define_method(rb_cSet, "&", set_i_intersection, 1);
2642 rb_define_alias(rb_cSet, "intersection", "&");
2643 rb_define_method(rb_cSet, "-", set_i_difference, 1);
2644 rb_define_alias(rb_cSet, "difference", "-");
2645 rb_define_method(rb_cSet, "^", set_i_xor, 1);
2646 rb_define_method(rb_cSet, "|", set_i_union, 1);
2647 rb_define_alias(rb_cSet, "+", "|");
2648 rb_define_alias(rb_cSet, "union", "|");
2649 rb_define_method(rb_cSet, "<=>", set_i_compare, 1);
2650 rb_define_method(rb_cSet, "==", set_i_eq, 1);
2651 rb_define_alias(rb_cSet, "eql?", "==");
2652 rb_define_method(rb_cSet, "add", set_i_add, 1);
2653 rb_define_alias(rb_cSet, "<<", "add");
2654 rb_define_method(rb_cSet, "add?", set_i_add_p, 1);
2655 rb_define_method(rb_cSet, "classify", set_i_classify, 0);
2656 rb_define_method(rb_cSet, "clear", set_i_clear, 0);
2657 rb_define_method(rb_cSet, "collect!", set_i_collect, 0);
2658 rb_define_alias(rb_cSet, "map!", "collect!");
2659 rb_define_method(rb_cSet, "compare_by_identity", set_i_compare_by_identity, 0);
2660 rb_define_method(rb_cSet, "compare_by_identity?", set_i_compare_by_identity_p, 0);
2661 rb_define_method(rb_cSet, "delete", set_i_delete, 1);
2662 rb_define_method(rb_cSet, "delete?", set_i_delete_p, 1);
2663 rb_define_method(rb_cSet, "delete_if", set_i_delete_if, 0);
2664 rb_define_method(rb_cSet, "disjoint?", set_i_disjoint, 1);
2665 rb_define_method(rb_cSet, "divide", set_i_divide, 0);
2666 rb_define_method(rb_cSet, "each", set_i_each, 0);
2667 rb_define_method(rb_cSet, "empty?", set_i_empty, 0);
2668 rb_define_method(rb_cSet, "flatten", set_i_flatten, 0);
2669 rb_define_method(rb_cSet, "flatten!", set_i_flatten_bang, 0);
2670 rb_define_method(rb_cSet, "hash", set_i_hash, 0);
2671 rb_define_method(rb_cSet, "include?", set_i_include, 1);
2672 rb_define_alias(rb_cSet, "member?", "include?");
2673 rb_define_alias(rb_cSet, "===", "include?");
2674 rb_define_method(rb_cSet, "inspect", set_i_inspect, 0);
2675 rb_define_alias(rb_cSet, "to_s", "inspect");
2676 rb_define_method(rb_cSet, "intersect?", set_i_intersect, 1);
2677 rb_define_method(rb_cSet, "join", set_i_join, -1);
2678 rb_define_method(rb_cSet, "keep_if", set_i_keep_if, 0);
2679 rb_define_method(rb_cSet, "merge", set_i_merge, -1);
2680 rb_define_method(rb_cSet, "proper_subset?", set_i_proper_subset, 1);
2681 rb_define_alias(rb_cSet, "<", "proper_subset?");
2682 rb_define_method(rb_cSet, "proper_superset?", set_i_proper_superset, 1);
2683 rb_define_alias(rb_cSet, ">", "proper_superset?");
2684 rb_define_method(rb_cSet, "reject!", set_i_reject, 0);
2685 rb_define_method(rb_cSet, "replace", set_i_replace, 1);
2686 rb_define_method(rb_cSet, "reset", set_i_reset, 0);
2687 rb_define_method(rb_cSet, "size", set_i_size, 0);
2688 rb_define_alias(rb_cSet, "length", "size");
2689 rb_define_method(rb_cSet, "select!", set_i_select, 0);
2690 rb_define_alias(rb_cSet, "filter!", "select!");
2691 rb_define_method(rb_cSet, "subset?", set_i_subset, 1);
2692 rb_define_alias(rb_cSet, "<=", "subset?");
2693 rb_define_method(rb_cSet, "subtract", set_i_subtract, 1);
2694 rb_define_method(rb_cSet, "superset?", set_i_superset, 1);
2695 rb_define_alias(rb_cSet, ">=", "superset?");
2696 rb_define_method(rb_cSet, "to_a", set_i_to_a, 0);
2697 rb_define_method(rb_cSet, "to_set", set_i_to_set, 0);
2698
2699 rb_define_method(rb_mEnumerable, "to_set", enum_to_set, 0);
2700
2701 /* :nodoc: */
2702 VALUE compat = rb_define_class_under(rb_cSet, "compatible", rb_cObject);
2703 rb_marshal_define_compat(rb_cSet, compat, compat_dumper, compat_loader);
2704
2705 // Create Set::CoreSet before defining inherited, so it does not include
2706 // the backwards compatibility layer.
2707 rb_define_class_under(rb_cSet, "CoreSet", rb_cSet);
2708 rb_define_private_method(rb_singleton_class(rb_cSet), "inherited", set_s_inherited, 1);
2709
2710 rb_provide("set.rb");
2711}
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define rb_define_private_method(klass, mid, func, arity)
Defines klass#mid and makes it private.
static bool RB_OBJ_FROZEN(VALUE obj)
Checks if an object is frozen.
Definition fl_type.h:714
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1786
void rb_extend_object(VALUE obj, VALUE module)
Extend the object with the module.
Definition eval.c:1947
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:3074
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:3117
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
Definition eval.c:1055
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1042
#define rb_str_buf_cat2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1707
#define Qundef
Old name of RUBY_Qundef.
#define LEN2NUM
Old name of RB_LEN2NUM.
Definition len_t.h:33
#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 T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
#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 INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
#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 T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:408
#define POSFIXABLE
Old name of RB_POSFIXABLE.
Definition fixnum.h:29
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:409
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1455
VALUE rb_cSet
Set class.
Definition set.c:99
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_mEnumerable
Enumerable module.
Definition enum.c:28
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:230
VALUE rb_obj_dup(VALUE obj)
Duplicates the given object.
Definition object.c:552
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:665
VALUE rb_obj_is_instance_of(VALUE obj, VALUE klass)
Queries if the given object is a direct instance of the given class.
Definition object.c:846
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
Definition object.c:902
VALUE rb_cString
String class.
Definition string.c:86
#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:504
rb_encoding * rb_usascii_encoding(void)
Queries the encoding that represents US-ASCII.
Definition encoding.c:1650
VALUE rb_str_export_to_enc(VALUE obj, rb_encoding *enc)
Identical to rb_str_export(), except it additionally takes an encoding.
Definition string.c:1531
VALUE rb_funcall_passing_block(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcallv_public(), except you can pass the passed block.
Definition vm_eval.c:1225
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1162
VALUE rb_ary_new_capa(rb_len_t capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_ary_freeze(VALUE obj)
Freeze an array, preventing further modifications.
VALUE rb_ary_join(VALUE ary, VALUE sep)
Recursively stringises the elements of the passed array, flattens that result, then joins the sequenc...
#define RETURN_SIZED_ENUMERATOR(obj, argc, argv, size_fn)
This roughly resembles return enum_for(__callee__) unless block_given?.
Definition enumerator.h:208
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_new(void)
Creates a new, empty hash object.
Definition hash.c:1670
void rb_provide(const char *feature)
Declares that the given feature is already provided by someone else.
Definition load.c:963
void rb_marshal_define_compat(VALUE newclass, VALUE oldclass, VALUE(*dumper)(VALUE), VALUE(*loader)(VALUE, VALUE))
Marshal format compatibility layer.
Definition marshal.c:139
size_t rb_set_size(VALUE set)
Returns the number of elements in the set.
Definition set.c:2420
VALUE rb_set_clear(VALUE set)
Removes all entries from set.
Definition set.c:2408
bool rb_set_delete(VALUE set, VALUE element)
Removes the element from from set.
Definition set.c:2414
bool rb_set_add(VALUE set, VALUE element)
Adds element to set.
Definition set.c:2402
void rb_set_foreach(VALUE set, int(*func)(VALUE element, VALUE arg), VALUE arg)
Iterates over a set.
Definition set.c:2378
bool rb_set_lookup(VALUE set, VALUE element)
Whether the set contains the given element.
Definition set.c:2396
VALUE rb_set_new(void)
Creates a new, empty set object.
Definition set.c:2384
VALUE rb_set_new_capa(size_t capa)
Identical to rb_set_new(), except it additionally specifies how many elements it is expected to conta...
Definition set.c:2390
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
Definition string.h:967
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:3991
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:3967
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
Definition thread.c:5960
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:5971
VALUE rb_const_get(VALUE space, ID name)
Identical to rb_const_defined(), except it returns the actual defined value.
Definition variable.c:3553
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
Definition variable.c:2186
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:1665
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition variable.c:397
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition vm_method.c:3772
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
int capa
Designed capacity of the buffer.
Definition io.h:11
#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:1432
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1409
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:170
VALUE rb_block_call(VALUE q, ID w, int e, const VALUE *r, type *t, VALUE y)
Call a method with a block.
VALUE type(ANYARGS)
ANYARGS-ed function type.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
#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:323
#define RARRAY_AREF(a, i)
References an object in an array.
Definition rarray.h:398
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:773
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:239
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:604
VALUE rb_require(const char *feature)
Identical to rb_require_string(), except it takes C's string instead of Ruby's.
Definition load.c:1781
#define RTEST
This is an old name of RB_TEST.
set_table_entry * entries
Array of size 2^entry_power.
Definition set_table.h:31
long rb_len_t
A signed integer type for lengths and indices of objects such as String and Array.
Definition value.h:142
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:425
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