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