Ruby 4.1.0dev (2026-04-19 revision 8f02f644eb5e021b3138b028b4292617650b614a)
struct.c (8f02f644eb5e021b3138b028b4292617650b614a)
1/**********************************************************************
2
3 struct.c -
4
5 $Author$
6 created at: Tue Mar 22 18:44:30 JST 1995
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9
10**********************************************************************/
11
12#include "id.h"
13#include "internal.h"
14#include "internal/class.h"
15#include "internal/error.h"
16#include "internal/hash.h"
17#include "internal/object.h"
18#include "internal/proc.h"
19#include "internal/struct.h"
20#include "internal/symbol.h"
21#include "vm_core.h"
22#include "builtin.h"
23
24/* only for struct[:field] access */
25enum {
26 AREF_HASH_UNIT = 5,
27 AREF_HASH_THRESHOLD = 10
28};
29
30/* Note: Data is a stricter version of the Struct: no attr writers & no
31 hash-alike/array-alike behavior. It shares most of the implementation
32 on the C level, but is unrelated on the Ruby level. */
34static VALUE rb_cData;
35static ID id_members, id_back_members, id_keyword_init;
36
37static VALUE struct_alloc(VALUE);
38
39static inline VALUE
40struct_ivar_get(VALUE c, ID id)
41{
42 VALUE orig = c;
43 VALUE ivar = rb_attr_get(c, id);
44
45 if (!NIL_P(ivar))
46 return ivar;
47
48 for (;;) {
50 if (c == rb_cStruct || c == rb_cData || !RTEST(c))
51 return Qnil;
53 ivar = rb_attr_get(c, id);
54 if (!NIL_P(ivar)) {
55 if (!OBJ_FROZEN(orig)) rb_ivar_set(orig, id, ivar);
56 return ivar;
57 }
58 }
59}
60
62rb_struct_s_keyword_init(VALUE klass)
63{
64 return struct_ivar_get(klass, id_keyword_init);
65}
66
69{
70 VALUE members = struct_ivar_get(klass, id_members);
71
72 if (NIL_P(members)) {
73 rb_raise(rb_eTypeError, "uninitialized struct");
74 }
75 if (!RB_TYPE_P(members, T_ARRAY)) {
76 rb_raise(rb_eTypeError, "corrupted struct");
77 }
78 return members;
79}
80
83{
85
86 if (RSTRUCT_LEN_RAW(s) != RARRAY_LEN(members)) {
87 rb_raise(rb_eTypeError, "struct size differs (%ld required %ld given)",
88 RARRAY_LEN(members), RSTRUCT_LEN_RAW(s));
89 }
90 return members;
91}
92
93static long
94struct_member_pos_ideal(VALUE name, long mask)
95{
96 /* (id & (mask/2)) * 2 */
97 return (SYM2ID(name) >> (ID_SCOPE_SHIFT - 1)) & mask;
98}
99
100static long
101struct_member_pos_probe(long prev, long mask)
102{
103 /* (((prev/2) * AREF_HASH_UNIT + 1) & (mask/2)) * 2 */
104 return (prev * AREF_HASH_UNIT + 2) & mask;
105}
106
107static VALUE
108struct_set_members(VALUE klass, VALUE /* frozen hidden array */ members)
109{
110 VALUE back;
111 const long members_length = RARRAY_LEN(members);
112
113 if (members_length <= AREF_HASH_THRESHOLD) {
114 back = members;
115 }
116 else {
117 long i, j, mask = 64;
118 VALUE name;
119
120 while (mask < members_length * AREF_HASH_UNIT) mask *= 2;
121
122 back = rb_ary_hidden_new(mask + 1);
123 rb_ary_store(back, mask, INT2FIX(members_length));
124 mask -= 2; /* mask = (2**k-1)*2 */
125
126 for (i=0; i < members_length; i++) {
127 name = RARRAY_AREF(members, i);
128
129 j = struct_member_pos_ideal(name, mask);
130
131 for (;;) {
132 if (!RTEST(RARRAY_AREF(back, j))) {
133 rb_ary_store(back, j, name);
134 rb_ary_store(back, j + 1, INT2FIX(i));
135 break;
136 }
137 j = struct_member_pos_probe(j, mask);
138 }
139 }
140 OBJ_FREEZE(back);
141 }
142 rb_ivar_set(klass, id_members, members);
143 rb_ivar_set(klass, id_back_members, back);
144
145 return members;
146}
147
148static inline int
149struct_member_pos(VALUE s, VALUE name)
150{
151 VALUE back = struct_ivar_get(rb_obj_class(s), id_back_members);
152 long j, mask;
153
154 if (UNLIKELY(NIL_P(back))) {
155 rb_raise(rb_eTypeError, "uninitialized struct");
156 }
157 if (UNLIKELY(!RB_TYPE_P(back, T_ARRAY))) {
158 rb_raise(rb_eTypeError, "corrupted struct");
159 }
160
161 mask = RARRAY_LEN(back);
162
163 if (mask <= AREF_HASH_THRESHOLD) {
164 if (UNLIKELY(RSTRUCT_LEN_RAW(s) != mask)) {
165 rb_raise(rb_eTypeError,
166 "struct size differs (%ld required %ld given)",
167 mask, RSTRUCT_LEN_RAW(s));
168 }
169 for (j = 0; j < mask; j++) {
170 if (RARRAY_AREF(back, j) == name)
171 return (int)j;
172 }
173 return -1;
174 }
175
176 if (UNLIKELY(RSTRUCT_LEN_RAW(s) != FIX2INT(RARRAY_AREF(back, mask-1)))) {
177 rb_raise(rb_eTypeError, "struct size differs (%d required %ld given)",
178 FIX2INT(RARRAY_AREF(back, mask-1)), RSTRUCT_LEN_RAW(s));
179 }
180
181 mask -= 3;
182 j = struct_member_pos_ideal(name, mask);
183
184 for (;;) {
185 VALUE e = RARRAY_AREF(back, j);
186 if (e == name)
187 return FIX2INT(RARRAY_AREF(back, j + 1));
188 if (!RTEST(e)) {
189 return -1;
190 }
191 j = struct_member_pos_probe(j, mask);
192 }
193}
194
195/*
196 * call-seq:
197 * StructClass::members -> array_of_symbols
198 *
199 * Returns the member names of the Struct descendant as an array:
200 *
201 * Customer = Struct.new(:name, :address, :zip)
202 * Customer.members # => [:name, :address, :zip]
203 *
204 */
205
206static VALUE
207rb_struct_s_members_m(VALUE klass)
208{
209 VALUE members = rb_struct_s_members(klass);
210
211 return rb_ary_dup(members);
212}
213
214/*
215 * call-seq:
216 * members -> array_of_symbols
217 *
218 * Returns the member names from +self+ as an array:
219 *
220 * Customer = Struct.new(:name, :address, :zip)
221 * Customer.new.members # => [:name, :address, :zip]
222 *
223 * Related: #to_a.
224 */
225
226static VALUE
227rb_struct_members_m(VALUE obj)
228{
229 return rb_struct_s_members_m(rb_obj_class(obj));
230}
231
232VALUE
234{
235 VALUE slot = ID2SYM(id);
236 int i = struct_member_pos(obj, slot);
237 if (i != -1) {
238 return RSTRUCT_GET_RAW(obj, i);
239 }
240 rb_name_err_raise("'%1$s' is not a struct member", obj, ID2SYM(id));
241
243}
244
245static void
246rb_struct_modify(VALUE s)
247{
248 rb_check_frozen(s);
249}
250
251static VALUE
252anonymous_struct(VALUE klass)
253{
254 VALUE nstr;
255
256 nstr = rb_class_new(klass);
257 rb_make_metaclass(nstr, RBASIC(klass)->klass);
258 rb_class_inherited(klass, nstr);
259 return nstr;
260}
261
262static VALUE
263new_struct(VALUE name, VALUE super)
264{
265 /* old style: should we warn? */
266 ID id;
267 name = rb_str_to_str(name);
268 if (!rb_is_const_name(name)) {
269 rb_name_err_raise("identifier %1$s needs to be constant",
270 super, name);
271 }
272 id = rb_to_id(name);
273 if (rb_const_defined_at(super, id)) {
274 rb_warn("redefining constant %"PRIsVALUE"::%"PRIsVALUE, super, name);
275 rb_mod_remove_const(super, ID2SYM(id));
276 }
277 return rb_define_class_id_under_no_pin(super, id, super);
278}
279
280NORETURN(static void invalid_struct_pos(VALUE s, VALUE idx));
281
282static void
283define_aref_method(VALUE nstr, VALUE name, VALUE off)
284{
285 rb_add_method_optimized(nstr, SYM2ID(name), OPTIMIZED_METHOD_TYPE_STRUCT_AREF, FIX2UINT(off), METHOD_VISI_PUBLIC);
286}
287
288static void
289define_aset_method(VALUE nstr, VALUE name, VALUE off)
290{
291 rb_add_method_optimized(nstr, SYM2ID(name), OPTIMIZED_METHOD_TYPE_STRUCT_ASET, FIX2UINT(off), METHOD_VISI_PUBLIC);
292}
293
294static VALUE
295rb_struct_s_inspect(VALUE klass)
296{
297 VALUE inspect = rb_class_name(klass);
298 if (RTEST(rb_struct_s_keyword_init(klass))) {
299 rb_str_cat_cstr(inspect, "(keyword_init: true)");
300 }
301 return inspect;
302}
303
304static VALUE
305rb_data_s_new(int argc, const VALUE *argv, VALUE klass)
306{
307 if (rb_keyword_given_p()) {
308 if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) {
309 rb_error_arity(argc, 0, 0);
310 }
311 return rb_class_new_instance_pass_kw(argc, argv, klass);
312 }
313 else {
314 VALUE members = struct_ivar_get(klass, id_members);
315 int num_members = RARRAY_LENINT(members);
316
317 rb_check_arity(argc, 0, num_members);
318 VALUE arg_hash = rb_hash_new_with_size(argc);
319 for (long i=0; i<argc; i++) {
320 VALUE k = rb_ary_entry(members, i), v = argv[i];
321 rb_hash_aset(arg_hash, k, v);
322 }
323 return rb_class_new_instance_kw(1, &arg_hash, klass, RB_PASS_KEYWORDS);
324 }
325}
326
327#if 0 /* for RDoc */
328
329/*
330 * call-seq:
331 * StructClass::keyword_init? -> true or falsy value
332 *
333 * Returns +true+ if the class was initialized with <tt>keyword_init: true</tt>.
334 * Otherwise returns +nil+ or +false+.
335 *
336 * Examples:
337 * Foo = Struct.new(:a)
338 * Foo.keyword_init? # => nil
339 * Bar = Struct.new(:a, keyword_init: true)
340 * Bar.keyword_init? # => true
341 * Baz = Struct.new(:a, keyword_init: false)
342 * Baz.keyword_init? # => false
343 */
344static VALUE
345rb_struct_s_keyword_init_p(VALUE obj)
346{
347}
348#endif
349
350#define rb_struct_s_keyword_init_p rb_struct_s_keyword_init
351
352static VALUE
353setup_struct(VALUE nstr, VALUE members)
354{
355 long i, len;
356
357 members = struct_set_members(nstr, members);
358
359 rb_define_alloc_func(nstr, struct_alloc);
362 rb_define_singleton_method(nstr, "members", rb_struct_s_members_m, 0);
363 rb_define_singleton_method(nstr, "inspect", rb_struct_s_inspect, 0);
364 rb_define_singleton_method(nstr, "keyword_init?", rb_struct_s_keyword_init_p, 0);
365
366 len = RARRAY_LEN(members);
367 for (i=0; i< len; i++) {
368 VALUE sym = RARRAY_AREF(members, i);
369 ID id = SYM2ID(sym);
370 VALUE off = LONG2NUM(i);
371
372 define_aref_method(nstr, sym, off);
373 define_aset_method(nstr, ID2SYM(rb_id_attrset(id)), off);
374 }
375
376 return nstr;
377}
378
379static VALUE
380setup_data(VALUE subclass, VALUE members)
381{
382 long i, len;
383
384 members = struct_set_members(subclass, members);
385
386 rb_define_alloc_func(subclass, struct_alloc);
387 VALUE sclass = rb_singleton_class(subclass);
388 rb_undef_method(sclass, "define");
389 rb_define_method(sclass, "new", rb_data_s_new, -1);
390 rb_define_method(sclass, "[]", rb_data_s_new, -1);
391 rb_define_method(sclass, "members", rb_struct_s_members_m, 0);
392 rb_define_method(sclass, "inspect", rb_struct_s_inspect, 0); // FIXME: just a separate method?..
393
394 len = RARRAY_LEN(members);
395 for (i=0; i< len; i++) {
396 VALUE sym = RARRAY_AREF(members, i);
397 VALUE off = LONG2NUM(i);
398
399 define_aref_method(subclass, sym, off);
400 }
401
402 return subclass;
403}
404
405VALUE
407{
408 return struct_alloc(klass);
409}
410
411static VALUE
412struct_make_members_list(va_list ar)
413{
414 char *mem;
415 VALUE ary, list = rb_ident_hash_new();
416 RBASIC_CLEAR_CLASS(list);
417 while ((mem = va_arg(ar, char*)) != 0) {
418 VALUE sym = rb_sym_intern_ascii_cstr(mem);
419 if (RTEST(rb_hash_has_key(list, sym))) {
420 rb_raise(rb_eArgError, "duplicate member: %s", mem);
421 }
422 rb_hash_aset(list, sym, Qtrue);
423 }
424 ary = rb_hash_keys(list);
425 RBASIC_CLEAR_CLASS(ary);
426 OBJ_FREEZE(ary);
427 return ary;
428}
429
430static VALUE
431struct_define_without_accessor(VALUE outer, const char *class_name, VALUE super, rb_alloc_func_t alloc, VALUE members)
432{
433 VALUE klass;
434
435 if (class_name) {
436 if (outer) {
437 klass = rb_define_class_under(outer, class_name, super);
438 }
439 else {
440 klass = rb_define_class(class_name, super);
441 }
442 }
443 else {
444 klass = anonymous_struct(super);
445 }
446
447 struct_set_members(klass, members);
448
449 if (alloc) {
450 rb_define_alloc_func(klass, alloc);
451 }
452 else {
453 rb_define_alloc_func(klass, struct_alloc);
454 }
455
456 return klass;
457}
458
459VALUE
460rb_struct_define_without_accessor_under(VALUE outer, const char *class_name, VALUE super, rb_alloc_func_t alloc, ...)
461{
462 va_list ar;
463 VALUE members;
464
465 va_start(ar, alloc);
466 members = struct_make_members_list(ar);
467 va_end(ar);
468
469 return struct_define_without_accessor(outer, class_name, super, alloc, members);
470}
471
472VALUE
473rb_struct_define_without_accessor(const char *class_name, VALUE super, rb_alloc_func_t alloc, ...)
474{
475 va_list ar;
476 VALUE members;
477
478 va_start(ar, alloc);
479 members = struct_make_members_list(ar);
480 va_end(ar);
481
482 return struct_define_without_accessor(0, class_name, super, alloc, members);
483}
484
485VALUE
486rb_struct_define(const char *name, ...)
487{
488 va_list ar;
489 VALUE st, ary;
490
491 va_start(ar, name);
492 ary = struct_make_members_list(ar);
493 va_end(ar);
494
495 if (!name) {
496 st = anonymous_struct(rb_cStruct);
497 }
498 else {
499 st = new_struct(rb_str_new2(name), rb_cStruct);
500 rb_vm_register_global_object(st);
501 }
502 return setup_struct(st, ary);
503}
504
505VALUE
506rb_struct_define_under(VALUE outer, const char *name, ...)
507{
508 va_list ar;
509 VALUE ary;
510
511 va_start(ar, name);
512 ary = struct_make_members_list(ar);
513 va_end(ar);
514
515 return setup_struct(rb_define_class_id_under(outer, rb_intern(name), rb_cStruct), ary);
516}
517
518/*
519 * call-seq:
520 * Struct.new(*member_names, keyword_init: nil){|Struct_subclass| ... } -> Struct_subclass
521 * Struct.new(class_name, *member_names, keyword_init: nil){|Struct_subclass| ... } -> Struct_subclass
522 * Struct_subclass.new(*member_names) -> Struct_subclass_instance
523 * Struct_subclass.new(**member_names) -> Struct_subclass_instance
524 *
525 * <tt>Struct.new</tt> returns a new subclass of +Struct+. The new subclass:
526 *
527 * - May be anonymous, or may have the name given by +class_name+.
528 * - May have members as given by +member_names+.
529 * - May have initialization via ordinary arguments, or via keyword arguments
530 *
531 * The new subclass has its own method <tt>::new</tt>; thus:
532 *
533 * Foo = Struct.new('Foo', :foo, :bar) # => Struct::Foo
534 * f = Foo.new(0, 1) # => #<struct Struct::Foo foo=0, bar=1>
535 *
536 * <b>Class Name</b>
537 *
538 * With string argument +class_name+,
539 * returns a new subclass of +Struct+ named <tt>Struct::<em>class_name</em></tt>:
540 *
541 * Foo = Struct.new('Foo', :foo, :bar) # => Struct::Foo
542 * Foo.name # => "Struct::Foo"
543 * Foo.superclass # => Struct
544 *
545 * Without string argument +class_name+,
546 * returns a new anonymous subclass of +Struct+:
547 *
548 * Struct.new(:foo, :bar).name # => nil
549 *
550 * <b>Block</b>
551 *
552 * With a block given, the created subclass is yielded to the block:
553 *
554 * Customer = Struct.new('Customer', :name, :address) do |new_class|
555 * p "The new subclass is #{new_class}"
556 * def greeting
557 * "Hello #{name} at #{address}"
558 * end
559 * end # => Struct::Customer
560 * dave = Customer.new('Dave', '123 Main')
561 * dave # => #<struct Struct::Customer name="Dave", address="123 Main">
562 * dave.greeting # => "Hello Dave at 123 Main"
563 *
564 * Output, from <tt>Struct.new</tt>:
565 *
566 * "The new subclass is Struct::Customer"
567 *
568 * <b>Member Names</b>
569 *
570 * Symbol arguments +member_names+
571 * determines the members of the new subclass:
572 *
573 * Struct.new(:foo, :bar).members # => [:foo, :bar]
574 * Struct.new('Foo', :foo, :bar).members # => [:foo, :bar]
575 *
576 * The new subclass has instance methods corresponding to +member_names+:
577 *
578 * Foo = Struct.new('Foo', :foo, :bar)
579 * Foo.instance_methods(false) # => [:foo, :bar, :foo=, :bar=]
580 * f = Foo.new # => #<struct Struct::Foo foo=nil, bar=nil>
581 * f.foo # => nil
582 * f.foo = 0 # => 0
583 * f.bar # => nil
584 * f.bar = 1 # => 1
585 * f # => #<struct Struct::Foo foo=0, bar=1>
586 *
587 * <b>Singleton Methods</b>
588 *
589 * A subclass returned by Struct.new has these singleton methods:
590 *
591 * - Method <tt>::new </tt> creates an instance of the subclass:
592 *
593 * Foo.new # => #<struct Struct::Foo foo=nil, bar=nil>
594 * Foo.new(0) # => #<struct Struct::Foo foo=0, bar=nil>
595 * Foo.new(0, 1) # => #<struct Struct::Foo foo=0, bar=1>
596 * Foo.new(0, 1, 2) # Raises ArgumentError: struct size differs
597 *
598 * # Initialization with keyword arguments:
599 * Foo.new(foo: 0) # => #<struct Struct::Foo foo=0, bar=nil>
600 * Foo.new(foo: 0, bar: 1) # => #<struct Struct::Foo foo=0, bar=1>
601 * Foo.new(foo: 0, bar: 1, baz: 2)
602 * # Raises ArgumentError: unknown keywords: baz
603 *
604 * - Method <tt>:inspect</tt> returns a string representation of the subclass:
605 *
606 * Foo.inspect
607 * # => "Struct::Foo"
608 *
609 * - Method <tt>::members</tt> returns an array of the member names:
610 *
611 * Foo.members # => [:foo, :bar]
612 *
613 * <b>Keyword Argument</b>
614 *
615 * By default, the arguments for initializing an instance of the new subclass
616 * can be both positional and keyword arguments.
617 *
618 * Optional keyword argument <tt>keyword_init:</tt> allows to force only one
619 * type of arguments to be accepted:
620 *
621 * KeywordsOnly = Struct.new(:foo, :bar, keyword_init: true)
622 * KeywordsOnly.new(bar: 1, foo: 0)
623 * # => #<struct KeywordsOnly foo=0, bar=1>
624 * KeywordsOnly.new(0, 1)
625 * # Raises ArgumentError: wrong number of arguments
626 *
627 * PositionalOnly = Struct.new(:foo, :bar, keyword_init: false)
628 * PositionalOnly.new(0, 1)
629 * # => #<struct PositionalOnly foo=0, bar=1>
630 * PositionalOnly.new(bar: 1, foo: 0)
631 * # => #<struct PositionalOnly foo={:foo=>1, :bar=>2}, bar=nil>
632 * # Note that no error is raised, but arguments treated as one hash value
633 *
634 * # Same as not providing keyword_init:
635 * Any = Struct.new(:foo, :bar, keyword_init: nil)
636 * Any.new(foo: 1, bar: 2)
637 * # => #<struct Any foo=1, bar=2>
638 * Any.new(1, 2)
639 * # => #<struct Any foo=1, bar=2>
640 */
641
642static VALUE
643rb_struct_s_def(int argc, VALUE *argv, VALUE klass)
644{
645 VALUE name = Qnil, rest, keyword_init = Qnil;
646 long i;
647 VALUE st;
648 VALUE opt;
649
650 argc = rb_scan_args(argc, argv, "0*:", NULL, &opt);
651 if (argc >= 1 && !SYMBOL_P(argv[0])) {
652 name = argv[0];
653 --argc;
654 ++argv;
655 }
656
657 if (!NIL_P(opt)) {
658 static ID keyword_ids[1];
659
660 if (!keyword_ids[0]) {
661 keyword_ids[0] = rb_intern("keyword_init");
662 }
663 rb_get_kwargs(opt, keyword_ids, 0, 1, &keyword_init);
664 if (UNDEF_P(keyword_init)) {
665 keyword_init = Qnil;
666 }
667 else if (RTEST(keyword_init)) {
668 keyword_init = Qtrue;
669 }
670 }
671
672 rest = rb_ident_hash_new();
673 RBASIC_CLEAR_CLASS(rest);
674 for (i=0; i<argc; i++) {
675 VALUE mem = rb_to_symbol(argv[i]);
676 if (rb_is_attrset_sym(mem)) {
677 rb_raise(rb_eArgError, "invalid struct member: %"PRIsVALUE, mem);
678 }
679 if (RTEST(rb_hash_has_key(rest, mem))) {
680 rb_raise(rb_eArgError, "duplicate member: %"PRIsVALUE, mem);
681 }
682 rb_hash_aset(rest, mem, Qtrue);
683 }
684 rest = rb_hash_keys(rest);
685 RBASIC_CLEAR_CLASS(rest);
686 OBJ_FREEZE(rest);
687 if (NIL_P(name)) {
688 st = anonymous_struct(klass);
689 }
690 else {
691 st = new_struct(name, klass);
692 }
693 setup_struct(st, rest);
694 rb_ivar_set(st, id_keyword_init, keyword_init);
695 if (rb_block_given_p()) {
696 rb_mod_module_eval(0, 0, st);
697 }
698
699 return st;
700}
701
702static long
703num_members(VALUE klass)
704{
705 VALUE members;
706 members = struct_ivar_get(klass, id_members);
707 if (!RB_TYPE_P(members, T_ARRAY)) {
708 rb_raise(rb_eTypeError, "broken members");
709 }
710 return RARRAY_LEN(members);
711}
712
713/*
714 */
715
717 VALUE self;
718 VALUE unknown_keywords;
719 VALUE missing_keywords;
720 long missing_count;
721};
722
723static int rb_struct_pos(VALUE s, VALUE *name, bool name_only);
724static VALUE deconstruct_keys(VALUE s, VALUE keys, bool name_only);
725static int rb_struct_pos(VALUE s, VALUE *name, bool name_only);
726
727static int
728struct_hash_aset(VALUE key, VALUE val, struct struct_hash_set_arg *args, bool name_only)
729{
730 int i = rb_struct_pos(args->self, &key, name_only);
731 if (i < 0) {
732 if (NIL_P(args->unknown_keywords)) {
733 args->unknown_keywords = rb_ary_new();
734 }
735 rb_ary_push(args->unknown_keywords, key);
736 }
737 else {
738 rb_struct_modify(args->self);
739 RSTRUCT_SET_RAW(args->self, i, val);
740 }
741 return i;
742}
743
744static int
745struct_hash_set_i(VALUE key, VALUE val, VALUE arg)
746{
747 struct struct_hash_set_arg *args = (struct struct_hash_set_arg *)arg;
748 struct_hash_aset(key, val, args, false);
749 return ST_CONTINUE;
750}
751
752static VALUE
753rb_struct_initialize_m(int argc, const VALUE *argv, VALUE self)
754{
755 VALUE klass = rb_obj_class(self);
756 rb_struct_modify(self);
757 long n = num_members(klass);
758 if (argc == 0) {
759 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self), n);
760 return Qnil;
761 }
762
763 bool keyword_init = false;
764 switch (rb_struct_s_keyword_init(klass)) {
765 default:
766 if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) {
767 rb_error_arity(argc, 0, 0);
768 }
769 keyword_init = true;
770 break;
771 case Qfalse:
772 break;
773 case Qnil:
774 if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) {
775 break;
776 }
777 keyword_init = rb_keyword_given_p();
778 break;
779 }
780 if (keyword_init) {
781 struct struct_hash_set_arg arg = {
782 .self = self,
783 .unknown_keywords = Qnil,
784 };
785 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self), n);
786 rb_hash_foreach(argv[0], struct_hash_set_i, (VALUE)&arg);
787 if (UNLIKELY(!NIL_P(arg.unknown_keywords))) {
788 rb_raise(rb_eArgError, "unknown keywords: %s",
789 RSTRING_PTR(rb_ary_join(arg.unknown_keywords, rb_str_new2(", "))));
790 }
791 }
792 else {
793 if (n < argc) {
794 rb_raise(rb_eArgError, "struct size differs");
795 }
796 for (long i=0; i<argc; i++) {
797 RSTRUCT_SET_RAW(self, i, argv[i]);
798 }
799 if (n > argc) {
800 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self)+argc, n-argc);
801 }
802 }
803 return Qnil;
804}
805
806VALUE
808{
809 rb_struct_initialize_m(RARRAY_LENINT(values), RARRAY_CONST_PTR(values), self);
810 if (rb_obj_is_kind_of(self, rb_cData)) OBJ_FREEZE(self);
811 RB_GC_GUARD(values);
812 return Qnil;
813}
814
815static VALUE *
816struct_heap_alloc(VALUE st, size_t len)
817{
818 return ALLOC_N(VALUE, len);
819}
820
821static VALUE
822struct_alloc(VALUE klass)
823{
824 long n = num_members(klass);
825 size_t embedded_size = offsetof(struct RStruct, as.ary) + (sizeof(VALUE) * n);
826 if (RCLASS_MAX_IV_COUNT(klass) > 0) {
827 embedded_size += sizeof(VALUE);
828 }
829
831
832 if (n > 0 && rb_gc_size_allocatable_p(embedded_size)) {
833 flags |= n << RSTRUCT_EMBED_LEN_SHIFT;
834 if (RCLASS_MAX_IV_COUNT(klass) == 0) {
835 // We set the flag before calling `NEWOBJ_OF` in case a NEWOBJ tracepoint does
836 // attempt to write fields. We'll remove it later if no fields was written to.
837 flags |= RSTRUCT_GEN_FIELDS;
838 }
839
840 NEWOBJ_OF(st, struct RStruct, klass, flags, embedded_size, 0);
841 if (RCLASS_MAX_IV_COUNT(klass) == 0) {
842 if (!rb_shape_obj_has_fields((VALUE)st)
843 && embedded_size < rb_gc_obj_slot_size((VALUE)st)) {
844 FL_UNSET_RAW((VALUE)st, RSTRUCT_GEN_FIELDS);
845 RSTRUCT_SET_FIELDS_OBJ((VALUE)st, 0);
846 }
847 }
848 else {
849 RSTRUCT_SET_FIELDS_OBJ((VALUE)st, 0);
850 }
851
852 rb_mem_clear((VALUE *)st->as.ary, n);
853
854 return (VALUE)st;
855 }
856 else {
857 NEWOBJ_OF(st, struct RStruct, klass, flags, sizeof(struct RStruct), 0);
858
859 st->as.heap.ptr = NULL;
860 st->as.heap.fields_obj = 0;
861 st->as.heap.len = 0;
862
863 st->as.heap.ptr = struct_heap_alloc((VALUE)st, n);
864 rb_mem_clear((VALUE *)st->as.heap.ptr, n);
865 st->as.heap.len = n;
866
867 return (VALUE)st;
868 }
869}
870
871VALUE
873{
874 return rb_class_new_instance(RARRAY_LENINT(values), RARRAY_CONST_PTR(values), klass);
875}
876
877VALUE
879{
880 VALUE tmpargs[16], *mem = tmpargs;
881 int size, i;
882 va_list args;
883
884 size = rb_long2int(num_members(klass));
885 if (size > numberof(tmpargs)) {
886 tmpargs[0] = rb_ary_hidden_new(size);
887 mem = RARRAY_PTR(tmpargs[0]);
888 }
889 va_start(args, klass);
890 for (i=0; i<size; i++) {
891 mem[i] = va_arg(args, VALUE);
892 }
893 va_end(args);
894
895 return rb_class_new_instance(size, mem, klass);
896}
897
898static VALUE
899struct_enum_size(VALUE s, VALUE args, VALUE eobj)
900{
901 return rb_struct_size(s);
902}
903
904/*
905 * call-seq:
906 * each {|value| ... } -> self
907 * each -> enumerator
908 *
909 * Calls the given block with the value of each member; returns +self+:
910 *
911 * Customer = Struct.new(:name, :address, :zip)
912 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
913 * joe.each {|value| p value }
914 *
915 * Output:
916 *
917 * "Joe Smith"
918 * "123 Maple, Anytown NC"
919 * 12345
920 *
921 * Returns an Enumerator if no block is given.
922 *
923 * Related: #each_pair.
924 */
925
926static VALUE
927rb_struct_each(VALUE s)
928{
929 long i;
930
931 RETURN_SIZED_ENUMERATOR(s, 0, 0, struct_enum_size);
932 for (i=0; i<RSTRUCT_LEN_RAW(s); i++) {
933 rb_yield(RSTRUCT_GET_RAW(s, i));
934 }
935 return s;
936}
937
938/*
939 * call-seq:
940 * each_pair {|(name, value)| ... } -> self
941 * each_pair -> enumerator
942 *
943 * Calls the given block with each member name/value pair; returns +self+:
944 *
945 * Customer = Struct.new(:name, :address, :zip) # => Customer
946 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
947 * joe.each_pair {|(name, value)| p "#{name} => #{value}" }
948 *
949 * Output:
950 *
951 * "name => Joe Smith"
952 * "address => 123 Maple, Anytown NC"
953 * "zip => 12345"
954 *
955 * Returns an Enumerator if no block is given.
956 *
957 * Related: #each.
958 *
959 */
960
961static VALUE
962rb_struct_each_pair(VALUE s)
963{
964 VALUE members;
965 long i;
966
967 RETURN_SIZED_ENUMERATOR(s, 0, 0, struct_enum_size);
968 members = rb_struct_members(s);
969 if (rb_block_pair_yield_optimizable()) {
970 for (i=0; i<RSTRUCT_LEN_RAW(s); i++) {
971 VALUE key = rb_ary_entry(members, i);
972 VALUE value = RSTRUCT_GET_RAW(s, i);
973 rb_yield_values(2, key, value);
974 }
975 }
976 else {
977 for (i=0; i<RSTRUCT_LEN_RAW(s); i++) {
978 VALUE key = rb_ary_entry(members, i);
979 VALUE value = RSTRUCT_GET_RAW(s, i);
980 rb_yield(rb_assoc_new(key, value));
981 }
982 }
983 return s;
984}
985
986static VALUE
987inspect_struct(VALUE s, VALUE prefix, int recur)
988{
989 VALUE cname = rb_class_path(rb_obj_class(s));
990 VALUE members;
991 VALUE str = prefix;
992 long i, len;
993 char first = RSTRING_PTR(cname)[0];
994
995 if (recur || first != '#') {
996 rb_str_cat2(str, " ");
997 rb_str_append(str, cname);
998 }
999 if (recur) {
1000 return rb_str_cat2(str, ":...>");
1001 }
1002
1003 members = rb_struct_members(s);
1004 len = RSTRUCT_LEN_RAW(s);
1005
1006 for (i=0; i<len; i++) {
1007 VALUE slot;
1008 ID id;
1009
1010 if (i > 0) {
1011 rb_str_cat2(str, ", ");
1012 }
1013 else {
1014 rb_str_cat2(str, " ");
1015 }
1016 slot = RARRAY_AREF(members, i);
1017 id = SYM2ID(slot);
1018 if (rb_is_local_id(id) || rb_is_const_id(id)) {
1019 rb_str_append(str, rb_id2str(id));
1020 }
1021 else {
1022 rb_str_append(str, rb_inspect(slot));
1023 }
1024 rb_str_cat2(str, "=");
1025 rb_str_append(str, rb_inspect(RSTRUCT_GET_RAW(s, i)));
1026 }
1027 rb_str_cat2(str, ">");
1028
1029 return str;
1030}
1031
1032/*
1033 * call-seq:
1034 * inspect -> string
1035 *
1036 * Returns a string representation of +self+:
1037 *
1038 * Customer = Struct.new(:name, :address, :zip) # => Customer
1039 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1040 * joe.inspect # => "#<struct Customer name=\"Joe Smith\", address=\"123 Maple, Anytown NC\", zip=12345>"
1041 *
1042 */
1043
1044static VALUE
1045rb_struct_inspect(VALUE s)
1046{
1047 return rb_exec_recursive(inspect_struct, s, rb_str_new2("#<struct"));
1048}
1049
1050/*
1051 * call-seq:
1052 * to_a -> array
1053 *
1054 * Returns the values in +self+ as an array:
1055 *
1056 * Customer = Struct.new(:name, :address, :zip)
1057 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1058 * joe.to_a # => ["Joe Smith", "123 Maple, Anytown NC", 12345]
1059 *
1060 * Related: #members.
1061 */
1062
1063static VALUE
1064rb_struct_to_a(VALUE s)
1065{
1066 return rb_ary_new4(RSTRUCT_LEN_RAW(s), RSTRUCT_CONST_PTR(s));
1067}
1068
1069/*
1070 * call-seq:
1071 * to_h -> hash
1072 * to_h {|name, value| ... } -> hash
1073 *
1074 * Returns a hash containing the name and value for each member:
1075 *
1076 * Customer = Struct.new(:name, :address, :zip)
1077 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1078 * h = joe.to_h
1079 * h # => {:name=>"Joe Smith", :address=>"123 Maple, Anytown NC", :zip=>12345}
1080 *
1081 * If a block is given, it is called with each name/value pair;
1082 * the block should return a 2-element array whose elements will become
1083 * a key/value pair in the returned hash:
1084 *
1085 * h = joe.to_h{|name, value| [name.upcase, value.to_s.upcase]}
1086 * h # => {:NAME=>"JOE SMITH", :ADDRESS=>"123 MAPLE, ANYTOWN NC", :ZIP=>"12345"}
1087 *
1088 * Raises ArgumentError if the block returns an inappropriate value.
1089 *
1090 */
1091
1092static VALUE
1093rb_struct_to_h(VALUE s)
1094{
1095 VALUE h = rb_hash_new_with_size(RSTRUCT_LEN_RAW(s));
1096 VALUE members = rb_struct_members(s);
1097 long i;
1098 int block_given = rb_block_given_p();
1099
1100 for (i=0; i<RSTRUCT_LEN_RAW(s); i++) {
1101 VALUE k = rb_ary_entry(members, i), v = RSTRUCT_GET_RAW(s, i);
1102 if (block_given)
1103 rb_hash_set_pair(h, rb_yield_values(2, k, v));
1104 else
1105 rb_hash_aset(h, k, v);
1106 }
1107 return h;
1108}
1109
1110/*
1111 * call-seq:
1112 * deconstruct_keys(array_of_names) -> hash
1113 *
1114 * Returns a hash of the name/value pairs for the given member names.
1115 *
1116 * Customer = Struct.new(:name, :address, :zip)
1117 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1118 * h = joe.deconstruct_keys([:zip, :address])
1119 * h # => {:zip=>12345, :address=>"123 Maple, Anytown NC"}
1120 *
1121 * Returns all names and values if +array_of_names+ is +nil+:
1122 *
1123 * h = joe.deconstruct_keys(nil)
1124 * h # => {:name=>"Joseph Smith, Jr.", :address=>"123 Maple, Anytown NC", :zip=>12345}
1125 *
1126 */
1127static VALUE
1128rb_struct_deconstruct_keys(VALUE s, VALUE keys)
1129{
1130 return deconstruct_keys(s, keys, false);
1131}
1132
1133static VALUE
1134deconstruct_keys(VALUE s, VALUE keys, bool name_only)
1135{
1136 VALUE h;
1137 long i;
1138
1139 if (NIL_P(keys)) {
1140 return rb_struct_to_h(s);
1141 }
1142 if (UNLIKELY(!RB_TYPE_P(keys, T_ARRAY))) {
1143 rb_raise(rb_eTypeError,
1144 "wrong argument type %"PRIsVALUE" (expected Array or nil)",
1145 rb_obj_class(keys));
1146
1147 }
1148 if (RSTRUCT_LEN_RAW(s) < RARRAY_LEN(keys)) {
1149 return rb_hash_new_with_size(0);
1150 }
1151 h = rb_hash_new_with_size(RARRAY_LEN(keys));
1152 for (i=0; i<RARRAY_LEN(keys); i++) {
1153 VALUE key = RARRAY_AREF(keys, i);
1154 int i = rb_struct_pos(s, &key, name_only);
1155 if (i < 0) {
1156 return h;
1157 }
1158 rb_hash_aset(h, key, RSTRUCT_GET_RAW(s, i));
1159 }
1160 return h;
1161}
1162
1163/* :nodoc: */
1164VALUE
1165rb_struct_init_copy(VALUE copy, VALUE s)
1166{
1167 long i, len;
1168
1169 if (!OBJ_INIT_COPY(copy, s)) return copy;
1170 if (RSTRUCT_LEN_RAW(copy) != RSTRUCT_LEN_RAW(s)) {
1171 rb_raise(rb_eTypeError, "struct size mismatch");
1172 }
1173
1174 for (i=0, len=RSTRUCT_LEN_RAW(copy); i<len; i++) {
1175 RSTRUCT_SET_RAW(copy, i, RSTRUCT_GET_RAW(s, i));
1176 }
1177
1178 return copy;
1179}
1180
1181static int
1182rb_struct_pos(VALUE s, VALUE *name, bool name_only)
1183{
1184 long i;
1185 VALUE idx = *name;
1186
1187 if (SYMBOL_P(idx)) {
1188 return struct_member_pos(s, idx);
1189 }
1190 else if (name_only || RB_TYPE_P(idx, T_STRING)) {
1191 idx = rb_check_symbol(name);
1192 if (NIL_P(idx)) return -1;
1193 return struct_member_pos(s, idx);
1194 }
1195 else {
1196 long len;
1197 i = NUM2LONG(idx);
1198 len = RSTRUCT_LEN_RAW(s);
1199 if (i < 0) {
1200 if (i + len < 0) {
1201 *name = LONG2FIX(i);
1202 return -1;
1203 }
1204 i += len;
1205 }
1206 else if (len <= i) {
1207 *name = LONG2FIX(i);
1208 return -1;
1209 }
1210 return (int)i;
1211 }
1212}
1213
1214static void
1215invalid_struct_pos(VALUE s, VALUE idx)
1216{
1217 if (FIXNUM_P(idx)) {
1218 long i = FIX2INT(idx), len = RSTRUCT_LEN_RAW(s);
1219 if (i < 0) {
1220 rb_raise(rb_eIndexError, "offset %ld too small for struct(size:%ld)",
1221 i, len);
1222 }
1223 else {
1224 rb_raise(rb_eIndexError, "offset %ld too large for struct(size:%ld)",
1225 i, len);
1226 }
1227 }
1228 else {
1229 rb_name_err_raise("no member '%1$s' in struct", s, idx);
1230 }
1231}
1232
1233/*
1234 * call-seq:
1235 * struct[name] -> object
1236 * struct[n] -> object
1237 *
1238 * Returns a value from +self+.
1239 *
1240 * With symbol or string argument +name+ given, returns the value for the named member:
1241 *
1242 * Customer = Struct.new(:name, :address, :zip)
1243 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1244 * joe[:zip] # => 12345
1245 *
1246 * Raises NameError if +name+ is not the name of a member.
1247 *
1248 * With integer argument +n+ given, returns <tt>self.values[n]</tt>
1249 * if +n+ is in range;
1250 * see Array@Array+Indexes:
1251 *
1252 * joe[2] # => 12345
1253 * joe[-2] # => "123 Maple, Anytown NC"
1254 *
1255 * Raises IndexError if +n+ is out of range.
1256 *
1257 */
1258
1259VALUE
1261{
1262 int i = rb_struct_pos(s, &idx, false);
1263 if (i < 0) invalid_struct_pos(s, idx);
1264 return RSTRUCT_GET_RAW(s, i);
1265}
1266
1267/*
1268 * call-seq:
1269 * struct[name] = value -> value
1270 * struct[n] = value -> value
1271 *
1272 * Assigns a value to a member.
1273 *
1274 * With symbol or string argument +name+ given, assigns the given +value+
1275 * to the named member; returns +value+:
1276 *
1277 * Customer = Struct.new(:name, :address, :zip)
1278 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1279 * joe[:zip] = 54321 # => 54321
1280 * joe # => #<struct Customer name="Joe Smith", address="123 Maple, Anytown NC", zip=54321>
1281 *
1282 * Raises NameError if +name+ is not the name of a member.
1283 *
1284 * With integer argument +n+ given, assigns the given +value+
1285 * to the +n+-th member if +n+ is in range;
1286 * see Array@Array+Indexes:
1287 *
1288 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1289 * joe[2] = 54321 # => 54321
1290 * joe[-3] = 'Joseph Smith' # => "Joseph Smith"
1291 * joe # => #<struct Customer name="Joseph Smith", address="123 Maple, Anytown NC", zip=54321>
1292 *
1293 * Raises IndexError if +n+ is out of range.
1294 *
1295 */
1296
1297VALUE
1299{
1300 int i = rb_struct_pos(s, &idx, false);
1301 if (i < 0) invalid_struct_pos(s, idx);
1302 rb_struct_modify(s);
1303 RSTRUCT_SET_RAW(s, i, val);
1304 return val;
1305}
1306
1307FUNC_MINIMIZED(VALUE rb_struct_lookup(VALUE s, VALUE idx));
1308NOINLINE(static VALUE rb_struct_lookup_default(VALUE s, VALUE idx, VALUE notfound, bool name_only));
1309
1310VALUE
1311rb_struct_lookup(VALUE s, VALUE idx)
1312{
1313 return rb_struct_lookup_default(s, idx, Qnil, false);
1314}
1315
1316static VALUE
1317rb_struct_lookup_default(VALUE s, VALUE idx, VALUE notfound, bool name_only)
1318{
1319 int i = rb_struct_pos(s, &idx, name_only);
1320 if (i < 0) return notfound;
1321 return RSTRUCT_GET_RAW(s, i);
1322}
1323
1324static VALUE
1325struct_entry(VALUE s, long n)
1326{
1327 return rb_struct_aref(s, LONG2NUM(n));
1328}
1329
1330/*
1331 * call-seq:
1332 * values_at(*integers) -> array
1333 * values_at(integer_range) -> array
1334 *
1335 * Returns an array of values from +self+.
1336 *
1337 * With integer arguments +integers+ given,
1338 * returns an array containing each value given by one of +integers+:
1339 *
1340 * Customer = Struct.new(:name, :address, :zip)
1341 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1342 * joe.values_at(0, 2) # => ["Joe Smith", 12345]
1343 * joe.values_at(2, 0) # => [12345, "Joe Smith"]
1344 * joe.values_at(2, 1, 0) # => [12345, "123 Maple, Anytown NC", "Joe Smith"]
1345 * joe.values_at(0, -3) # => ["Joe Smith", "Joe Smith"]
1346 *
1347 * Raises IndexError if any of +integers+ is out of range;
1348 * see Array@Array+Indexes.
1349 *
1350 * With integer range argument +integer_range+ given,
1351 * returns an array containing each value given by the elements of the range;
1352 * fills with +nil+ values for range elements larger than the structure:
1353 *
1354 * joe.values_at(0..2)
1355 * # => ["Joe Smith", "123 Maple, Anytown NC", 12345]
1356 * joe.values_at(-3..-1)
1357 * # => ["Joe Smith", "123 Maple, Anytown NC", 12345]
1358 * joe.values_at(1..4) # => ["123 Maple, Anytown NC", 12345, nil, nil]
1359 *
1360 * Raises RangeError if any element of the range is negative and out of range;
1361 * see Array@Array+Indexes.
1362 *
1363 */
1364
1365static VALUE
1366rb_struct_values_at(int argc, VALUE *argv, VALUE s)
1367{
1368 return rb_get_values_at(s, RSTRUCT_LEN_RAW(s), argc, argv, struct_entry);
1369}
1370
1371/*
1372 * call-seq:
1373 * select {|value| ... } -> array
1374 * select -> enumerator
1375 *
1376 * With a block given, returns an array of values from +self+
1377 * for which the block returns a truthy value:
1378 *
1379 * Customer = Struct.new(:name, :address, :zip)
1380 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1381 * a = joe.select {|value| value.is_a?(String) }
1382 * a # => ["Joe Smith", "123 Maple, Anytown NC"]
1383 * a = joe.select {|value| value.is_a?(Integer) }
1384 * a # => [12345]
1385 *
1386 * With no block given, returns an Enumerator.
1387 */
1388
1389static VALUE
1390rb_struct_select(int argc, VALUE *argv, VALUE s)
1391{
1392 VALUE result;
1393 long i;
1394
1395 rb_check_arity(argc, 0, 0);
1396 RETURN_SIZED_ENUMERATOR(s, 0, 0, struct_enum_size);
1397 result = rb_ary_new();
1398 for (i = 0; i < RSTRUCT_LEN_RAW(s); i++) {
1399 if (RTEST(rb_yield(RSTRUCT_GET_RAW(s, i)))) {
1400 rb_ary_push(result, RSTRUCT_GET_RAW(s, i));
1401 }
1402 }
1403
1404 return result;
1405}
1406
1407static VALUE
1408recursive_equal(VALUE s, VALUE s2, int recur)
1409{
1410 long i, len;
1411
1412 if (recur) return Qtrue; /* Subtle! */
1413 len = RSTRUCT_LEN_RAW(s);
1414 for (i=0; i<len; i++) {
1415 if (!rb_equal(RSTRUCT_GET_RAW(s, i), RSTRUCT_GET_RAW(s2, i))) return Qfalse;
1416 }
1417 return Qtrue;
1418}
1419
1420
1421/*
1422 * call-seq:
1423 * self == other -> true or false
1424 *
1425 * Returns whether both the following are true:
1426 *
1427 * - <tt>other.class == self.class</tt>.
1428 * - For each member name +name+, <tt>other.name == self.name</tt>.
1429 *
1430 * Examples:
1431 *
1432 * Customer = Struct.new(:name, :address, :zip)
1433 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1434 * joe_jr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1435 * joe_jr == joe # => true
1436 * joe_jr[:name] = 'Joe Smith, Jr.'
1437 * # => "Joe Smith, Jr."
1438 * joe_jr == joe # => false
1439 */
1440
1441static VALUE
1442rb_struct_equal(VALUE s, VALUE s2)
1443{
1444 if (s == s2) return Qtrue;
1445 if (!RB_TYPE_P(s2, T_STRUCT)) return Qfalse;
1446 if (rb_obj_class(s) != rb_obj_class(s2)) return Qfalse;
1447 if (RSTRUCT_LEN_RAW(s) != RSTRUCT_LEN_RAW(s2)) {
1448 rb_bug("inconsistent struct"); /* should never happen */
1449 }
1450
1451 return rb_exec_recursive_paired(recursive_equal, s, s2, s2);
1452}
1453
1454/*
1455 * call-seq:
1456 * hash -> integer
1457 *
1458 * Returns the integer hash value for +self+.
1459 *
1460 * Two structs of the same class and with the same content
1461 * will have the same hash code (and will compare using Struct#eql?):
1462 *
1463 * Customer = Struct.new(:name, :address, :zip)
1464 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1465 * joe_jr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1466 * joe.hash == joe_jr.hash # => true
1467 * joe_jr[:name] = 'Joe Smith, Jr.'
1468 * joe.hash == joe_jr.hash # => false
1469 *
1470 * Related: Object#hash.
1471 */
1472
1473static VALUE
1474rb_struct_hash(VALUE s)
1475{
1476 long i, len;
1477 st_index_t h;
1478 VALUE n;
1479
1480 h = rb_hash_start(rb_hash(rb_obj_class(s)));
1481 len = RSTRUCT_LEN_RAW(s);
1482 for (i = 0; i < len; i++) {
1483 n = rb_hash(RSTRUCT_GET_RAW(s, i));
1484 h = rb_hash_uint(h, NUM2LONG(n));
1485 }
1486 h = rb_hash_end(h);
1487 return ST2FIX(h);
1488}
1489
1490static VALUE
1491recursive_eql(VALUE s, VALUE s2, int recur)
1492{
1493 long i, len;
1494
1495 if (recur) return Qtrue; /* Subtle! */
1496 len = RSTRUCT_LEN_RAW(s);
1497 for (i=0; i<len; i++) {
1498 if (!rb_eql(RSTRUCT_GET_RAW(s, i), RSTRUCT_GET_RAW(s2, i))) return Qfalse;
1499 }
1500 return Qtrue;
1501}
1502
1503/*
1504 * call-seq:
1505 * eql?(other) -> true or false
1506 *
1507 * Returns +true+ if and only if the following are true; otherwise returns +false+:
1508 *
1509 * - <tt>other.class == self.class</tt>.
1510 * - For each member name +name+, <tt>other.name.eql?(self.name)</tt>.
1511 *
1512 * Customer = Struct.new(:name, :address, :zip)
1513 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1514 * joe_jr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1515 * joe_jr.eql?(joe) # => true
1516 * joe_jr[:name] = 'Joe Smith, Jr.'
1517 * joe_jr.eql?(joe) # => false
1518 *
1519 * Related: Object#==.
1520 */
1521
1522static VALUE
1523rb_struct_eql(VALUE s, VALUE s2)
1524{
1525 if (s == s2) return Qtrue;
1526 if (!RB_TYPE_P(s2, T_STRUCT)) return Qfalse;
1527 if (rb_obj_class(s) != rb_obj_class(s2)) return Qfalse;
1528 if (RSTRUCT_LEN_RAW(s) != RSTRUCT_LEN_RAW(s2)) {
1529 rb_bug("inconsistent struct"); /* should never happen */
1530 }
1531
1532 return rb_exec_recursive_paired(recursive_eql, s, s2, s2);
1533}
1534
1535/*
1536 * call-seq:
1537 * size -> integer
1538 *
1539 * Returns the number of members.
1540 *
1541 * Customer = Struct.new(:name, :address, :zip)
1542 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1543 * joe.size #=> 3
1544 *
1545 */
1546
1547VALUE
1549{
1550 return LONG2FIX(RSTRUCT_LEN_RAW(s));
1551}
1552
1553/*
1554 * call-seq:
1555 * dig(name, *identifiers) -> object
1556 * dig(n, *identifiers) -> object
1557 *
1558 * Finds and returns an object among nested objects.
1559 * The nested objects may be instances of various classes.
1560 * See {Dig Methods}[rdoc-ref:dig_methods.rdoc].
1561 *
1562 *
1563 * Given symbol or string argument +name+,
1564 * returns the object that is specified by +name+ and +identifiers+:
1565 *
1566 * Foo = Struct.new(:a)
1567 * f = Foo.new(Foo.new({b: [1, 2, 3]}))
1568 * f.dig(:a) # => #<struct Foo a={:b=>[1, 2, 3]}>
1569 * f.dig(:a, :a) # => {:b=>[1, 2, 3]}
1570 * f.dig(:a, :a, :b) # => [1, 2, 3]
1571 * f.dig(:a, :a, :b, 0) # => 1
1572 * f.dig(:b, 0) # => nil
1573 *
1574 * Given integer argument +n+,
1575 * returns the object that is specified by +n+ and +identifiers+:
1576 *
1577 * f.dig(0) # => #<struct Foo a={:b=>[1, 2, 3]}>
1578 * f.dig(0, 0) # => {:b=>[1, 2, 3]}
1579 * f.dig(0, 0, :b) # => [1, 2, 3]
1580 * f.dig(0, 0, :b, 0) # => 1
1581 * f.dig(:b, 0) # => nil
1582 *
1583 */
1584
1585static VALUE
1586rb_struct_dig(int argc, VALUE *argv, VALUE self)
1587{
1589 self = rb_struct_lookup(self, *argv);
1590 if (!--argc) return self;
1591 ++argv;
1592 return rb_obj_dig(argc, argv, self, Qnil);
1593}
1594
1595/*
1596 * Document-class: Data
1597 *
1598 * Class \Data provides a convenient way to define simple classes
1599 * for value-alike objects.
1600 *
1601 * The simplest example of usage:
1602 *
1603 * Measure = Data.define(:amount, :unit)
1604 *
1605 * # Positional arguments constructor is provided
1606 * distance = Measure.new(100, 'km')
1607 * #=> #<data Measure amount=100, unit="km">
1608 *
1609 * # Keyword arguments constructor is provided
1610 * weight = Measure.new(amount: 50, unit: 'kg')
1611 * #=> #<data Measure amount=50, unit="kg">
1612 *
1613 * # Alternative form to construct an object:
1614 * speed = Measure[10, 'mPh']
1615 * #=> #<data Measure amount=10, unit="mPh">
1616 *
1617 * # Works with keyword arguments, too:
1618 * area = Measure[amount: 1.5, unit: 'm^2']
1619 * #=> #<data Measure amount=1.5, unit="m^2">
1620 *
1621 * # Argument accessors are provided:
1622 * distance.amount #=> 100
1623 * distance.unit #=> "km"
1624 *
1625 * Constructed object also has a reasonable definitions of #==
1626 * operator, #to_h hash conversion, and #deconstruct / #deconstruct_keys
1627 * to be used in pattern matching.
1628 *
1629 * ::define method accepts an optional block and evaluates it in
1630 * the context of the newly defined class. That allows to define
1631 * additional methods:
1632 *
1633 * Measure = Data.define(:amount, :unit) do
1634 * def <=>(other)
1635 * return unless other.is_a?(self.class) && other.unit == unit
1636 * amount <=> other.amount
1637 * end
1638 *
1639 * include Comparable
1640 * end
1641 *
1642 * Measure[3, 'm'] < Measure[5, 'm'] #=> true
1643 * Measure[3, 'm'] < Measure[5, 'kg']
1644 * # comparison of Measure with Measure failed (ArgumentError)
1645 *
1646 * Data provides no member writers, or enumerators: it is meant
1647 * to be a storage for immutable atomic values. But note that
1648 * if some of data members is of a mutable class, Data does no additional
1649 * immutability enforcement:
1650 *
1651 * Event = Data.define(:time, :weekdays)
1652 * event = Event.new('18:00', %w[Tue Wed Fri])
1653 * #=> #<data Event time="18:00", weekdays=["Tue", "Wed", "Fri"]>
1654 *
1655 * # There is no #time= or #weekdays= accessors, but changes are
1656 * # still possible:
1657 * event.weekdays << 'Sat'
1658 * event
1659 * #=> #<data Event time="18:00", weekdays=["Tue", "Wed", "Fri", "Sat"]>
1660 *
1661 * See also Struct, which is a similar concept, but has more
1662 * container-alike API, allowing to change contents of the object
1663 * and enumerate it.
1664 */
1665
1666/*
1667 * call-seq:
1668 * define(*symbols) -> class
1669 *
1670 * Defines a new \Data class.
1671 *
1672 * measure = Data.define(:amount, :unit)
1673 * #=> #<Class:0x00007f70c6868498>
1674 * measure.new(1, 'km')
1675 * #=> #<data amount=1, unit="km">
1676 *
1677 * # It you store the new class in the constant, it will
1678 * # affect #inspect and will be more natural to use:
1679 * Measure = Data.define(:amount, :unit)
1680 * #=> Measure
1681 * Measure.new(1, 'km')
1682 * #=> #<data Measure amount=1, unit="km">
1683 *
1684 *
1685 * Note that member-less \Data is acceptable and might be a useful technique
1686 * for defining several homogeneous data classes, like
1687 *
1688 * class HTTPFetcher
1689 * Response = Data.define(:body)
1690 * NotFound = Data.define
1691 * # ... implementation
1692 * end
1693 *
1694 * Now, different kinds of responses from +HTTPFetcher+ would have consistent
1695 * representation:
1696 *
1697 * #<data HTTPFetcher::Response body="<html...">
1698 * #<data HTTPFetcher::NotFound>
1699 *
1700 * And are convenient to use in pattern matching:
1701 *
1702 * case fetcher.get(url)
1703 * in HTTPFetcher::Response(body)
1704 * # process body variable
1705 * in HTTPFetcher::NotFound
1706 * # handle not found case
1707 * end
1708 */
1709
1710static VALUE
1711rb_data_s_def(int argc, VALUE *argv, VALUE klass)
1712{
1713 VALUE rest;
1714 long i;
1715 VALUE data_class;
1716
1717 rest = rb_ident_hash_new();
1718 RBASIC_CLEAR_CLASS(rest);
1719 for (i=0; i<argc; i++) {
1720 VALUE mem = rb_to_symbol(argv[i]);
1721 if (rb_is_attrset_sym(mem)) {
1722 rb_raise(rb_eArgError, "invalid data member: %"PRIsVALUE, mem);
1723 }
1724 if (RTEST(rb_hash_has_key(rest, mem))) {
1725 rb_raise(rb_eArgError, "duplicate member: %"PRIsVALUE, mem);
1726 }
1727 rb_hash_aset(rest, mem, Qtrue);
1728 }
1729 rest = rb_hash_keys(rest);
1730 RBASIC_CLEAR_CLASS(rest);
1731 OBJ_FREEZE(rest);
1732 data_class = anonymous_struct(klass);
1733 setup_data(data_class, rest);
1734 if (rb_block_given_p()) {
1735 rb_mod_module_eval(0, 0, data_class);
1736 }
1737
1738 return data_class;
1739}
1740
1741VALUE
1743{
1744 va_list ar;
1745 VALUE ary;
1746 va_start(ar, super);
1747 ary = struct_make_members_list(ar);
1748 va_end(ar);
1749 if (!super) super = rb_cData;
1750 VALUE klass = setup_data(anonymous_struct(super), ary);
1751 rb_vm_register_global_object(klass);
1752 return klass;
1753}
1754
1755static int
1756data_hash_set_i(VALUE key, VALUE val, VALUE arg)
1757{
1758 struct struct_hash_set_arg *args = (struct struct_hash_set_arg *)arg;
1759 int i = struct_hash_aset(key, val, args, true);
1760 if (i >= 0 && args->missing_count > 0) {
1761 VALUE k = RARRAY_AREF(args->missing_keywords, i);
1762 if (!NIL_P(k)) {
1763 RARRAY_ASET(args->missing_keywords, i, Qnil);
1764 args->missing_count--;
1765 }
1766 }
1767 return ST_CONTINUE;
1768}
1769
1770/*
1771 * call-seq:
1772 * DataClass::members -> array_of_symbols
1773 *
1774 * Returns an array of member names of the data class:
1775 *
1776 * Measure = Data.define(:amount, :unit)
1777 * Measure.members # => [:amount, :unit]
1778 *
1779 */
1780
1781#define rb_data_s_members_m rb_struct_s_members_m
1782
1783
1784/*
1785 * call-seq:
1786 * new(*args) -> instance
1787 * new(**kwargs) -> instance
1788 * ::[](*args) -> instance
1789 * ::[](**kwargs) -> instance
1790 *
1791 * Constructors for classes defined with ::define accept both positional and
1792 * keyword arguments.
1793 *
1794 * Measure = Data.define(:amount, :unit)
1795 *
1796 * Measure.new(1, 'km')
1797 * #=> #<data Measure amount=1, unit="km">
1798 * Measure.new(amount: 1, unit: 'km')
1799 * #=> #<data Measure amount=1, unit="km">
1800 *
1801 * # Alternative shorter initialization with []
1802 * Measure[1, 'km']
1803 * #=> #<data Measure amount=1, unit="km">
1804 * Measure[amount: 1, unit: 'km']
1805 * #=> #<data Measure amount=1, unit="km">
1806 *
1807 * All arguments are mandatory (unlike Struct), and converted to keyword arguments:
1808 *
1809 * Measure.new(amount: 1)
1810 * # in `initialize': missing keyword: :unit (ArgumentError)
1811 *
1812 * Measure.new(1)
1813 * # in `initialize': missing keyword: :unit (ArgumentError)
1814 *
1815 * Note that <tt>Measure#initialize</tt> always receives keyword arguments, and that
1816 * mandatory arguments are checked in +initialize+, not in +new+. This can be
1817 * important for redefining initialize in order to convert arguments or provide
1818 * defaults:
1819 *
1820 * Measure = Data.define(:amount, :unit)
1821 * class Measure
1822 * NONE = Data.define
1823 *
1824 * def initialize(amount:, unit: NONE.new)
1825 * super(amount: Float(amount), unit:)
1826 * end
1827 * end
1828 *
1829 * Measure.new('10', 'km') # => #<data Measure amount=10.0, unit="km">
1830 * Measure.new(10_000) # => #<data Measure amount=10000.0, unit=#<data Measure::NONE>>
1831 *
1832 */
1833
1834static VALUE
1835rb_data_initialize_m(int argc, const VALUE *argv, VALUE self)
1836{
1837 VALUE klass = rb_obj_class(self);
1838 rb_struct_modify(self);
1839 VALUE members = struct_ivar_get(klass, id_members);
1840 size_t num_members = RARRAY_LEN(members);
1841
1842 if (argc == 0) {
1843 if (num_members > 0) {
1844 rb_exc_raise(rb_keyword_error_new("missing", members));
1845 }
1846 OBJ_FREEZE(self);
1847 return Qnil;
1848 }
1849 if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) {
1850 rb_error_arity(argc, 0, 0);
1851 }
1852
1853 VALUE missing = rb_ary_dup(members);
1854 RBASIC_CLEAR_CLASS(missing);
1855 struct struct_hash_set_arg arg = {
1856 .self = self,
1857 .unknown_keywords = Qnil,
1858 .missing_keywords = missing,
1859 .missing_count = (long)num_members,
1860 };
1861 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self), num_members);
1862 rb_hash_foreach(argv[0], data_hash_set_i, (VALUE)&arg);
1863 // Freeze early before potentially raising, so that we don't leave an
1864 // unfrozen copy on the heap, which could get exposed via ObjectSpace.
1865 OBJ_FREEZE(self);
1866 if (UNLIKELY(arg.missing_count > 0)) {
1867 rb_ary_compact_bang(missing);
1868 RUBY_ASSERT(RARRAY_LEN(missing) == arg.missing_count, "missing_count=%ld but %ld", arg.missing_count, RARRAY_LEN(missing));
1869 RBASIC_SET_CLASS_RAW(missing, rb_cArray);
1870 rb_exc_raise(rb_keyword_error_new("missing", missing));
1871 }
1872 VALUE unknown_keywords = arg.unknown_keywords;
1873 if (UNLIKELY(!NIL_P(unknown_keywords))) {
1874 RBASIC_SET_CLASS_RAW(unknown_keywords, rb_cArray);
1875 rb_exc_raise(rb_keyword_error_new("unknown", unknown_keywords));
1876 }
1877
1878 return Qnil;
1879}
1880
1881/* :nodoc: */
1882static VALUE
1883rb_data_init_copy(VALUE copy, VALUE s)
1884{
1885 copy = rb_struct_init_copy(copy, s);
1886 RB_OBJ_FREEZE(copy);
1887 return copy;
1888}
1889
1890/*
1891 * call-seq:
1892 * with(**kwargs) -> instance
1893 *
1894 * Returns a shallow copy of +self+ --- the instance variables of
1895 * +self+ are copied, but not the objects they reference.
1896 *
1897 * If the method is supplied any keyword arguments, the copy will
1898 * be created with the respective field values updated to use the
1899 * supplied keyword argument values. Note that it is an error to
1900 * supply a keyword that the Data class does not have as a member.
1901 *
1902 * Point = Data.define(:x, :y)
1903 *
1904 * origin = Point.new(x: 0, y: 0)
1905 *
1906 * up = origin.with(x: 1)
1907 * right = origin.with(y: 1)
1908 * up_and_right = up.with(y: 1)
1909 *
1910 * p origin # #<data Point x=0, y=0>
1911 * p up # #<data Point x=1, y=0>
1912 * p right # #<data Point x=0, y=1>
1913 * p up_and_right # #<data Point x=1, y=1>
1914 *
1915 * out = origin.with(z: 1) # ArgumentError: unknown keyword: :z
1916 * some_point = origin.with(1, 2) # ArgumentError: expected keyword arguments, got positional arguments
1917 *
1918 */
1919
1920static VALUE
1921rb_data_with(int argc, const VALUE *argv, VALUE self)
1922{
1923 VALUE kwargs;
1924 rb_scan_args(argc, argv, "0:", &kwargs);
1925 if (NIL_P(kwargs)) {
1926 return self;
1927 }
1928
1929 VALUE h = rb_struct_to_h(self);
1930 rb_hash_update_by(h, kwargs, 0);
1931 return rb_class_new_instance_kw(1, &h, rb_obj_class(self), TRUE);
1932}
1933
1934/*
1935 * call-seq:
1936 * inspect -> string
1937 * to_s -> string
1938 *
1939 * Returns a string representation of +self+:
1940 *
1941 * Measure = Data.define(:amount, :unit)
1942 *
1943 * distance = Measure[10, 'km']
1944 *
1945 * p distance # uses #inspect underneath
1946 * #<data Measure amount=10, unit="km">
1947 *
1948 * puts distance # uses #to_s underneath, same representation
1949 * #<data Measure amount=10, unit="km">
1950 *
1951 */
1952
1953static VALUE
1954rb_data_inspect(VALUE s)
1955{
1956 return rb_exec_recursive(inspect_struct, s, rb_str_new2("#<data"));
1957}
1958
1959/*
1960 * call-seq:
1961 * self == other -> true or false
1962 *
1963 * Returns whether +other+ is the same class as +self+, and all members are
1964 * equal.
1965 *
1966 * Examples:
1967 *
1968 * Measure = Data.define(:amount, :unit)
1969 *
1970 * Measure[1, 'km'] == Measure[1, 'km'] #=> true
1971 * Measure[1, 'km'] == Measure[2, 'km'] #=> false
1972 * Measure[1, 'km'] == Measure[1, 'm'] #=> false
1973 *
1974 * Measurement = Data.define(:amount, :unit)
1975 * # Even though Measurement and Measure have the same "shape"
1976 * # their instances are never equal
1977 * Measure[1, 'km'] == Measurement[1, 'km'] #=> false
1978 */
1979
1980#define rb_data_equal rb_struct_equal
1981
1982/*
1983 * call-seq:
1984 * self.eql?(other) -> true or false
1985 *
1986 * Equality check that is used when two items of data are keys of a Hash.
1987 *
1988 * The subtle difference with #== is that members are also compared with their
1989 * #eql? method, which might be important in some cases:
1990 *
1991 * Measure = Data.define(:amount, :unit)
1992 *
1993 * Measure[1, 'km'] == Measure[1.0, 'km'] #=> true, they are equal as values
1994 * # ...but...
1995 * Measure[1, 'km'].eql? Measure[1.0, 'km'] #=> false, they represent different hash keys
1996 *
1997 * See also Object#eql? for further explanations of the method usage.
1998 */
1999
2000#define rb_data_eql rb_struct_eql
2001
2002/*
2003 * call-seq:
2004 * hash -> integer
2005 *
2006 * Redefines Object#hash (used to distinguish objects as Hash keys) so that
2007 * data objects of the same class with same content would have the same +hash+
2008 * value, and represented the same Hash key.
2009 *
2010 * Measure = Data.define(:amount, :unit)
2011 *
2012 * Measure[1, 'km'].hash == Measure[1, 'km'].hash #=> true
2013 * Measure[1, 'km'].hash == Measure[10, 'km'].hash #=> false
2014 * Measure[1, 'km'].hash == Measure[1, 'm'].hash #=> false
2015 * Measure[1, 'km'].hash == Measure[1.0, 'km'].hash #=> false
2016 *
2017 * # Structurally similar data class, but shouldn't be considered
2018 * # the same hash key
2019 * Measurement = Data.define(:amount, :unit)
2020 *
2021 * Measure[1, 'km'].hash == Measurement[1, 'km'].hash #=> false
2022 */
2023
2024#define rb_data_hash rb_struct_hash
2025
2026/*
2027 * call-seq:
2028 * to_h -> hash
2029 * to_h {|name, value| ... } -> hash
2030 *
2031 * Returns Hash representation of the data object.
2032 *
2033 * Measure = Data.define(:amount, :unit)
2034 * distance = Measure[10, 'km']
2035 *
2036 * distance.to_h
2037 * #=> {:amount=>10, :unit=>"km"}
2038 *
2039 * Like Enumerable#to_h, if the block is provided, it is expected to
2040 * produce key-value pairs to construct a hash:
2041 *
2042 *
2043 * distance.to_h { |name, val| [name.to_s, val.to_s] }
2044 * #=> {"amount"=>"10", "unit"=>"km"}
2045 *
2046 * Note that there is a useful symmetry between #to_h and #initialize:
2047 *
2048 * distance2 = Measure.new(**distance.to_h)
2049 * #=> #<data Measure amount=10, unit="km">
2050 * distance2 == distance
2051 * #=> true
2052 */
2053
2054#define rb_data_to_h rb_struct_to_h
2055
2056/*
2057 * call-seq:
2058 * members -> array_of_symbols
2059 *
2060 * Returns the member names from +self+ as an array:
2061 *
2062 * Measure = Data.define(:amount, :unit)
2063 * distance = Measure[10, 'km']
2064 *
2065 * distance.members #=> [:amount, :unit]
2066 *
2067 */
2068
2069#define rb_data_members_m rb_struct_members_m
2070
2071/*
2072 * call-seq:
2073 * deconstruct -> array
2074 *
2075 * Returns the values in +self+ as an array, to use in pattern matching:
2076 *
2077 * Measure = Data.define(:amount, :unit)
2078 *
2079 * distance = Measure[10, 'km']
2080 * distance.deconstruct #=> [10, "km"]
2081 *
2082 * # usage
2083 * case distance
2084 * in n, 'km' # calls #deconstruct underneath
2085 * puts "It is #{n} kilometers away"
2086 * else
2087 * puts "Don't know how to handle it"
2088 * end
2089 * # prints "It is 10 kilometers away"
2090 *
2091 * Or, with checking the class, too:
2092 *
2093 * case distance
2094 * in Measure(n, 'km')
2095 * puts "It is #{n} kilometers away"
2096 * # ...
2097 * end
2098 */
2099
2100#define rb_data_deconstruct rb_struct_to_a
2101
2102/*
2103 * call-seq:
2104 * deconstruct_keys(array_of_names_or_nil) -> hash
2105 *
2106 * Returns a hash of the name/value pairs, to use in pattern matching.
2107 *
2108 * Measure = Data.define(:amount, :unit)
2109 *
2110 * distance = Measure[10, 'km']
2111 * distance.deconstruct_keys(nil) #=> {:amount=>10, :unit=>"km"}
2112 * distance.deconstruct_keys([:amount]) #=> {:amount=>10}
2113 *
2114 * # usage
2115 * case distance
2116 * in amount:, unit: 'km' # calls #deconstruct_keys underneath
2117 * puts "It is #{amount} kilometers away"
2118 * else
2119 * puts "Don't know how to handle it"
2120 * end
2121 * # prints "It is 10 kilometers away"
2122 *
2123 * Or, with checking the class, too:
2124 *
2125 * case distance
2126 * in Measure(amount:, unit: 'km')
2127 * puts "It is #{amount} kilometers away"
2128 * # ...
2129 * end
2130 */
2131
2132static VALUE
2133rb_data_deconstruct_keys(VALUE s, VALUE keys)
2134{
2135 return deconstruct_keys(s, keys, true);
2136}
2137
2138/*
2139 * Document-class: Struct
2140 *
2141 * Class \Struct provides a convenient way to create a simple class
2142 * that can store and fetch values.
2143 *
2144 * This example creates a subclass of +Struct+, <tt>Struct::Customer</tt>;
2145 * the first argument, a string, is the name of the subclass;
2146 * the other arguments, symbols, determine the _members_ of the new subclass.
2147 *
2148 * Customer = Struct.new('Customer', :name, :address, :zip)
2149 * Customer.name # => "Struct::Customer"
2150 * Customer.class # => Class
2151 * Customer.superclass # => Struct
2152 *
2153 * Corresponding to each member are two methods, a writer and a reader,
2154 * that store and fetch values:
2155 *
2156 * methods = Customer.instance_methods false
2157 * methods # => [:zip, :address=, :zip=, :address, :name, :name=]
2158 *
2159 * An instance of the subclass may be created,
2160 * and its members assigned values, via method <tt>::new</tt>:
2161 *
2162 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
2163 * joe # => #<struct Struct::Customer name="Joe Smith", address="123 Maple, Anytown NC", zip=12345>
2164 *
2165 * The member values may be managed thus:
2166 *
2167 * joe.name # => "Joe Smith"
2168 * joe.name = 'Joseph Smith'
2169 * joe.name # => "Joseph Smith"
2170 *
2171 * And thus; note that member name may be expressed as either a string or a symbol:
2172 *
2173 * joe[:name] # => "Joseph Smith"
2174 * joe[:name] = 'Joseph Smith, Jr.'
2175 * joe['name'] # => "Joseph Smith, Jr."
2176 *
2177 * See Struct::new.
2178 *
2179 * == What's Here
2180 *
2181 * First, what's elsewhere. Class \Struct:
2182 *
2183 * - Inherits from {class Object}[rdoc-ref:Object@Whats+Here].
2184 * - Includes {module Enumerable}[rdoc-ref:Enumerable@Whats+Here],
2185 * which provides dozens of additional methods.
2186 *
2187 * See also Data, which is a somewhat similar, but stricter concept for defining immutable
2188 * value objects.
2189 *
2190 * Here, class \Struct provides methods that are useful for:
2191 *
2192 * - {Creating a Struct Subclass}[rdoc-ref:Struct@Methods+for+Creating+a+Struct+Subclass]
2193 * - {Querying}[rdoc-ref:Struct@Methods+for+Querying]
2194 * - {Comparing}[rdoc-ref:Struct@Methods+for+Comparing]
2195 * - {Fetching}[rdoc-ref:Struct@Methods+for+Fetching]
2196 * - {Assigning}[rdoc-ref:Struct@Methods+for+Assigning]
2197 * - {Iterating}[rdoc-ref:Struct@Methods+for+Iterating]
2198 * - {Converting}[rdoc-ref:Struct@Methods+for+Converting]
2199 *
2200 * === Methods for Creating a Struct Subclass
2201 *
2202 * - ::new: Returns a new subclass of \Struct.
2203 *
2204 * === Methods for Querying
2205 *
2206 * - #hash: Returns the integer hash code.
2207 * - #size (aliased as #length): Returns the number of members.
2208 *
2209 * === Methods for Comparing
2210 *
2211 * - #==: Returns whether a given object is equal to +self+, using <tt>==</tt>
2212 * to compare member values.
2213 * - #eql?: Returns whether a given object is equal to +self+,
2214 * using <tt>eql?</tt> to compare member values.
2215 *
2216 * === Methods for Fetching
2217 *
2218 * - #[]: Returns the value associated with a given member name.
2219 * - #to_a (aliased as #values, #deconstruct): Returns the member values in +self+ as an array.
2220 * - #deconstruct_keys: Returns a hash of the name/value pairs
2221 * for given member names.
2222 * - #dig: Returns the object in nested objects that is specified
2223 * by a given member name and additional arguments.
2224 * - #members: Returns an array of the member names.
2225 * - #select (aliased as #filter): Returns an array of member values from +self+,
2226 * as selected by the given block.
2227 * - #values_at: Returns an array containing values for given member names.
2228 *
2229 * === Methods for Assigning
2230 *
2231 * - #[]=: Assigns a given value to a given member name.
2232 *
2233 * === Methods for Iterating
2234 *
2235 * - #each: Calls a given block with each member name.
2236 * - #each_pair: Calls a given block with each member name/value pair.
2237 *
2238 * === Methods for Converting
2239 *
2240 * - #inspect (aliased as #to_s): Returns a string representation of +self+.
2241 * - #to_h: Returns a hash of the member name/value pairs in +self+.
2242 *
2243 */
2244void
2245InitVM_Struct(void)
2246{
2249
2251 rb_define_singleton_method(rb_cStruct, "new", rb_struct_s_def, -1);
2252#if 0 /* for RDoc */
2253 rb_define_singleton_method(rb_cStruct, "keyword_init?", rb_struct_s_keyword_init_p, 0);
2254 rb_define_singleton_method(rb_cStruct, "members", rb_struct_s_members_m, 0);
2255#endif
2256
2257 rb_define_method(rb_cStruct, "initialize", rb_struct_initialize_m, -1);
2258 rb_define_method(rb_cStruct, "initialize_copy", rb_struct_init_copy, 1);
2259
2260 rb_define_method(rb_cStruct, "==", rb_struct_equal, 1);
2261 rb_define_method(rb_cStruct, "eql?", rb_struct_eql, 1);
2262 rb_define_method(rb_cStruct, "hash", rb_struct_hash, 0);
2263
2264 rb_define_method(rb_cStruct, "inspect", rb_struct_inspect, 0);
2265 rb_define_alias(rb_cStruct, "to_s", "inspect");
2266 rb_define_method(rb_cStruct, "to_a", rb_struct_to_a, 0);
2267 rb_define_method(rb_cStruct, "to_h", rb_struct_to_h, 0);
2268 rb_define_method(rb_cStruct, "values", rb_struct_to_a, 0);
2269 rb_define_method(rb_cStruct, "size", rb_struct_size, 0);
2270 rb_define_method(rb_cStruct, "length", rb_struct_size, 0);
2271
2272 rb_define_method(rb_cStruct, "each", rb_struct_each, 0);
2273 rb_define_method(rb_cStruct, "each_pair", rb_struct_each_pair, 0);
2274 rb_define_method(rb_cStruct, "[]", rb_struct_aref, 1);
2275 rb_define_method(rb_cStruct, "[]=", rb_struct_aset, 2);
2276 rb_define_method(rb_cStruct, "select", rb_struct_select, -1);
2277 rb_define_method(rb_cStruct, "filter", rb_struct_select, -1);
2278 rb_define_method(rb_cStruct, "values_at", rb_struct_values_at, -1);
2279
2280 rb_define_method(rb_cStruct, "members", rb_struct_members_m, 0);
2281 rb_define_method(rb_cStruct, "dig", rb_struct_dig, -1);
2282
2283 rb_define_method(rb_cStruct, "deconstruct", rb_struct_to_a, 0);
2284 rb_define_method(rb_cStruct, "deconstruct_keys", rb_struct_deconstruct_keys, 1);
2285
2286 rb_cData = rb_define_class("Data", rb_cObject);
2287
2288 rb_undef_method(CLASS_OF(rb_cData), "new");
2289 rb_undef_alloc_func(rb_cData);
2290 rb_define_singleton_method(rb_cData, "define", rb_data_s_def, -1);
2291
2292#if 0 /* for RDoc */
2293 rb_define_singleton_method(rb_cData, "members", rb_data_s_members_m, 0);
2294#endif
2295
2296 rb_define_method(rb_cData, "initialize", rb_data_initialize_m, -1);
2297 rb_define_method(rb_cData, "initialize_copy", rb_data_init_copy, 1);
2298
2299 rb_define_method(rb_cData, "==", rb_data_equal, 1);
2300 rb_define_method(rb_cData, "eql?", rb_data_eql, 1);
2301 rb_define_method(rb_cData, "hash", rb_data_hash, 0);
2302
2303 rb_define_method(rb_cData, "inspect", rb_data_inspect, 0);
2304 rb_define_alias(rb_cData, "to_s", "inspect");
2305 rb_define_method(rb_cData, "to_h", rb_data_to_h, 0);
2306
2307 rb_define_method(rb_cData, "members", rb_data_members_m, 0);
2308
2309 rb_define_method(rb_cData, "deconstruct", rb_data_deconstruct, 0);
2310 rb_define_method(rb_cData, "deconstruct_keys", rb_data_deconstruct_keys, 1);
2311
2312 rb_define_method(rb_cData, "with", rb_data_with, -1);
2313}
2314
2315#undef rb_intern
2316void
2317Init_Struct(void)
2318{
2319 id_members = rb_intern("__members__");
2320 id_back_members = rb_intern("__members_back__");
2321 id_keyword_init = rb_intern("__keyword_init__");
2322
2323 InitVM(Struct);
2324}
#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.
#define RB_OBJ_FREEZE
Just another name of rb_obj_freeze_inline.
Definition fl_type.h:91
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1733
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:1526
VALUE rb_class_new(VALUE super)
Creates a new, anonymous class.
Definition class.c:899
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:2850
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition class.c:1557
VALUE rb_define_class_id_under(VALUE outer, ID id, VALUE super)
Identical to rb_define_class_under(), except it takes the name in ID instead of C's string.
Definition class.c:1596
VALUE rb_class_inherited(VALUE super, VALUE klass)
Calls Class::inherited.
Definition class.c:1517
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2893
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2703
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:3183
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
Definition eval.c:1031
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1018
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:2972
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1676
#define FL_UNSET_RAW
Old name of RB_FL_UNSET_RAW.
Definition fl_type.h:130
#define OBJ_INIT_COPY(obj, orig)
Old name of RB_OBJ_INIT_COPY.
Definition object.h:41
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
Definition fl_type.h:133
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1684
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define T_STRUCT
Old name of RUBY_T_STRUCT.
Definition value_type.h:79
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define SYM2ID
Old name of RB_SYM2ID.
Definition symbol.h:45
#define FIX2UINT
Old name of RB_FIX2UINT.
Definition int.h:42
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define rb_ary_new4
Old name of rb_ary_new_from_values.
Definition array.h:659
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#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 LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#define Qtrue
Old name of RUBY_Qtrue.
#define ST2FIX
Old name of RB_ST2FIX.
Definition st_data_t.h:33
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define FL_WB_PROTECTED
Old name of RUBY_FL_WB_PROTECTED.
Definition fl_type.h:59
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition value_type.h:58
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:661
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1427
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:467
VALUE rb_eIndexError
IndexError exception.
Definition error.c:1429
VALUE rb_class_superclass(VALUE klass)
Queries the parent of the given class.
Definition object.c:2310
VALUE rb_cArray
Array class.
VALUE rb_cObject
Object class.
Definition object.c:61
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
Definition object.c:2295
VALUE rb_class_new_instance_kw(int argc, const VALUE *argv, VALUE klass, int kw_splat)
Identical to rb_class_new_instance(), except you can specify how to handle the last element of the gi...
Definition object.c:2283
VALUE rb_mEnumerable
Enumerable module.
Definition enum.c:27
VALUE rb_cStruct
Struct class.
Definition struct.c:33
VALUE rb_class_new_instance_pass_kw(int argc, const VALUE *argv, VALUE klass)
Identical to rb_class_new_instance(), except it passes the passed keywords if any to the #initialize ...
Definition object.c:2272
int rb_eql(VALUE lhs, VALUE rhs)
Checks for equality of the passed objects, in terms of Object#eql?.
Definition object.c:154
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:235
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:657
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:141
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:894
#define RGENGC_WB_PROTECTED_STRUCT
This is a compile-time flag to enable/disable write barrier for struct RStruct.
Definition gc.h:468
Defines RBIMPL_HAS_BUILTIN.
VALUE rb_ary_dup(VALUE ary)
Duplicates an array.
VALUE rb_get_values_at(VALUE obj, long olen, int argc, const VALUE *argv, VALUE(*func)(VALUE obj, long oidx))
This was a generalisation of Array#values_at, Struct#values_at, and MatchData#values_at.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_hidden_new(long capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_ary_entry(VALUE ary, long off)
Queries an element of an array.
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
void rb_mem_clear(VALUE *buf, long len)
Fills the memory region with a series of RUBY_Qnil.
VALUE rb_ary_join(VALUE ary, VALUE sep)
Recursively stringises the elements of the passed array, flattens that result, then joins the sequenc...
void rb_ary_store(VALUE ary, long key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
#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
int rb_is_const_id(ID id)
Classifies the given ID, then sees if it is a constant.
Definition symbol.c:1110
int rb_is_local_id(ID id)
Classifies the given ID, then sees if it is a local variable.
Definition symbol.c:1140
#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
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:3834
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition random.c:1785
#define rb_str_cat_cstr(buf, str)
Identical to rb_str_cat(), except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1657
VALUE rb_struct_define_without_accessor_under(VALUE outer, const char *class_name, VALUE super, rb_alloc_func_t alloc,...)
Identical to rb_struct_define_without_accessor(), except it defines the class under the specified nam...
Definition struct.c:460
VALUE rb_struct_define_under(VALUE space, const char *name,...)
Identical to rb_struct_define(), except it defines the class under the specified namespace instead of...
Definition struct.c:506
VALUE rb_struct_new(VALUE klass,...)
Creates an instance of the given struct.
Definition struct.c:878
VALUE rb_struct_initialize(VALUE self, VALUE values)
Mass-assigns a struct's fields.
Definition struct.c:807
VALUE rb_struct_define_without_accessor(const char *name, VALUE super, rb_alloc_func_t func,...)
Identical to rb_struct_define(), except it does not define accessor methods.
Definition struct.c:473
VALUE rb_struct_define(const char *name,...)
Defines a struct class.
Definition struct.c:486
VALUE rb_struct_alloc(VALUE klass, VALUE values)
Identical to rb_struct_new(), except it takes the field values as a Ruby array.
Definition struct.c:872
VALUE rb_data_define(VALUE super,...)
Defines an anonymous data class.
Definition struct.c:1742
VALUE rb_struct_alloc_noinit(VALUE klass)
Allocates an instance of the given class.
Definition struct.c:406
VALUE rb_struct_s_members(VALUE klass)
Queries the list of the names of the fields of the given struct class.
Definition struct.c:68
VALUE rb_struct_members(VALUE self)
Queries the list of the names of the fields of the class of the given struct object.
Definition struct.c:82
VALUE rb_struct_getmember(VALUE self, ID key)
Identical to rb_struct_aref(), except it takes ID instead of VALUE.
Definition struct.c:233
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
VALUE rb_exec_recursive_paired(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h)
Identical to rb_exec_recursive(), except it checks for the recursion on the ordered pair of { g,...
VALUE rb_ivar_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:2047
VALUE rb_mod_remove_const(VALUE space, VALUE name)
Resembles Module#remove_const.
Definition variable.c:3581
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition variable.c:500
int rb_const_defined_at(VALUE space, ID name)
Identical to rb_const_defined(), except it doesn't look for parent classes.
Definition variable.c:3814
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition variable.c:380
VALUE(* rb_alloc_func_t)(VALUE klass)
This is the type of functions that ruby calls when trying to allocate an object.
Definition vm.h:219
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1731
VALUE rb_mod_module_eval(int argc, const VALUE *argv, VALUE mod)
Identical to rb_obj_instance_eval(), except it evaluates within the context of module.
Definition vm_eval.c:2426
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
VALUE rb_check_symbol(volatile VALUE *namep)
Identical to rb_check_id(), except it returns an instance of rb_cSymbol instead.
Definition symbol.c:1221
VALUE rb_to_symbol(VALUE name)
Identical to rb_intern_str(), except it generates a dynamic symbol if necessary.
Definition string.c:12719
ID rb_to_id(VALUE str)
Identical to rb_intern_str(), except it tries to convert the parameter object to an instance of rb_cS...
Definition string.c:12709
int off
Offset inside of ptr.
Definition io.h:5
int len
Length of the buffer.
Definition io.h:8
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:1398
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1375
#define rb_long2int
Just another name of rb_long2int_inline.
Definition long.h:62
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
void rb_hash_foreach(VALUE q, int_type *w, VALUE e)
Iteration over the given hash.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
Definition rarray.h:281
static void RARRAY_ASET(VALUE ary, long i, VALUE v)
Assigns an object in an array.
Definition rarray.h:386
static VALUE * RARRAY_PTR(VALUE ary)
Wild use of a C pointer.
Definition rarray.h:366
#define RARRAY_AREF(a, i)
Definition rarray.h:403
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:52
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
VALUE rb_str_to_str(VALUE obj)
Identical to rb_check_string_type(), except it raises exceptions in case of conversion failures.
Definition string.c:1777
VALUE rb_struct_aset(VALUE st, VALUE k, VALUE v)
Resembles Struct#[]=.
Definition struct.c:1298
VALUE rb_struct_size(VALUE st)
Returns the number of struct members.
Definition struct.c:1548
VALUE rb_struct_aref(VALUE st, VALUE k)
Resembles Struct#[].
Definition struct.c:1260
#define InitVM(ext)
This macro is for internal use.
Definition ruby.h:231
#define RB_PASS_KEYWORDS
Pass keywords, final argument must be a hash of keywords.
Definition scan_args.h:72
#define RTEST
This is an old name of RB_TEST.
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 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