Ruby: struct.c Source File

Ruby 4.0.6p0 (2026-07-14 revision 03b6d3f8898a28604fe6cb00eae3226b821168f4)

struct.c
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. */
33 VALUE rb_cStruct;
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 (;;) {
49 c = rb_class_superclass(c);
50 if (c == rb_cStruct || c == rb_cData || !RTEST(c))
51 return Qnil;
52 RUBY_ASSERT(RB_TYPE_P(c, T_CLASS));
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
61 VALUE
62rb_struct_s_keyword_init(VALUE klass)
63{
64 return struct_ivar_get(klass, id_keyword_init);
65}
66
67 VALUE
68rb_struct_s_members(VALUE klass)
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
81 VALUE
82rb_struct_members(VALUE s)
83{
84 VALUE members = rb_struct_s_members(rb_obj_class(s));
85
86 if (RSTRUCT_LEN(s) != RARRAY_LEN(members)) {
87 rb_raise(rb_eTypeError, "struct size differs (%ld required %ld given)",
88 RARRAY_LEN(members), RSTRUCT_LEN(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(s) != mask)) {
165 rb_raise(rb_eTypeError,
166 "struct size differs (%ld required %ld given)",
167 mask, RSTRUCT_LEN(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(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(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
232 VALUE
233rb_struct_getmember(VALUE obj, ID id)
234{
235 VALUE slot = ID2SYM(id);
236 int i = struct_member_pos(obj, slot);
237 if (i != -1) {
238 return RSTRUCT_GET(obj, i);
239 }
240 rb_name_err_raise("'%1$s' is not a struct member", obj, ID2SYM(id));
241
242 UNREACHABLE_RETURN(Qnil);
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);
360 rb_define_singleton_method(nstr, "new", rb_class_new_instance_pass_kw, -1);
361 rb_define_singleton_method(nstr, "[]", rb_class_new_instance_pass_kw, -1);
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
405 VALUE
406rb_struct_alloc_noinit(VALUE klass)
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
459 VALUE
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
472 VALUE
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
485 VALUE
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
505 VALUE
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
716 struct struct_hash_set_arg {
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);
725
726static int
727struct_hash_aset(VALUE key, VALUE val, struct struct_hash_set_arg *args, bool name_only)
728{
729 int i = rb_struct_pos(args->self, &key, name_only);
730 if (i < 0) {
731 if (NIL_P(args->unknown_keywords)) {
732 args->unknown_keywords = rb_ary_new();
733 }
734 rb_ary_push(args->unknown_keywords, key);
735 }
736 else {
737 rb_struct_modify(args->self);
738 RSTRUCT_SET(args->self, i, val);
739 }
740 return i;
741}
742
743static int
744struct_hash_set_i(VALUE key, VALUE val, VALUE arg)
745{
746 struct struct_hash_set_arg *args = (struct struct_hash_set_arg *)arg;
747 struct_hash_aset(key, val, args, false);
748 return ST_CONTINUE;
749}
750
751static VALUE
752rb_struct_initialize_m(int argc, const VALUE *argv, VALUE self)
753{
754 VALUE klass = rb_obj_class(self);
755 rb_struct_modify(self);
756 long n = num_members(klass);
757 if (argc == 0) {
758 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self), n);
759 return Qnil;
760 }
761
762 bool keyword_init = false;
763 switch (rb_struct_s_keyword_init(klass)) {
764 default:
765 if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) {
766 rb_error_arity(argc, 0, 0);
767 }
768 keyword_init = true;
769 break;
770 case Qfalse:
771 break;
772 case Qnil:
773 if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) {
774 break;
775 }
776 keyword_init = rb_keyword_given_p();
777 break;
778 }
779 if (keyword_init) {
780 struct struct_hash_set_arg arg = {
781 .self = self,
782 .unknown_keywords = Qnil,
783 };
784 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self), n);
785 rb_hash_foreach(argv[0], struct_hash_set_i, (VALUE)&arg);
786 if (UNLIKELY(!NIL_P(arg.unknown_keywords))) {
787 rb_raise(rb_eArgError, "unknown keywords: %s",
788 RSTRING_PTR(rb_ary_join(arg.unknown_keywords, rb_str_new2(", "))));
789 }
790 }
791 else {
792 if (n < argc) {
793 rb_raise(rb_eArgError, "struct size differs");
794 }
795 for (long i=0; i<argc; i++) {
796 RSTRUCT_SET(self, i, argv[i]);
797 }
798 if (n > argc) {
799 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self)+argc, n-argc);
800 }
801 }
802 return Qnil;
803}
804
805 VALUE
806rb_struct_initialize(VALUE self, VALUE values)
807{
808 rb_struct_initialize_m(RARRAY_LENINT(values), RARRAY_CONST_PTR(values), self);
809 if (rb_obj_is_kind_of(self, rb_cData)) OBJ_FREEZE(self);
810 RB_GC_GUARD(values);
811 return Qnil;
812}
813
814static VALUE *
815struct_heap_alloc(VALUE st, size_t len)
816{
817 return ALLOC_N(VALUE, len);
818}
819
820static VALUE
821struct_alloc(VALUE klass)
822{
823 long n = num_members(klass);
824 size_t embedded_size = offsetof(struct RStruct, as.ary) + (sizeof(VALUE) * n);
825 if (RCLASS_MAX_IV_COUNT(klass) > 0) {
826 embedded_size += sizeof(VALUE);
827 }
828
829 VALUE flags = T_STRUCT | (RGENGC_WB_PROTECTED_STRUCT ? FL_WB_PROTECTED : 0);
830
831 if (n > 0 && rb_gc_size_allocatable_p(embedded_size)) {
832 flags |= n << RSTRUCT_EMBED_LEN_SHIFT;
833 if (RCLASS_MAX_IV_COUNT(klass) == 0) {
834 // We set the flag before calling `NEWOBJ_OF` in case a NEWOBJ tracepoint does
835 // attempt to write fields. We'll remove it later if no fields was written to.
836 flags |= RSTRUCT_GEN_FIELDS;
837 }
838
839 NEWOBJ_OF(st, struct RStruct, klass, flags, embedded_size, 0);
840 if (RCLASS_MAX_IV_COUNT(klass) == 0) {
841 if (!rb_shape_obj_has_fields((VALUE)st)
842 && embedded_size < rb_gc_obj_slot_size((VALUE)st)) {
843 FL_UNSET_RAW((VALUE)st, RSTRUCT_GEN_FIELDS);
844 RSTRUCT_SET_FIELDS_OBJ((VALUE)st, 0);
845 }
846 }
847 else {
848 RSTRUCT_SET_FIELDS_OBJ((VALUE)st, 0);
849 }
850
851 rb_mem_clear((VALUE *)st->as.ary, n);
852
853 return (VALUE)st;
854 }
855 else {
856 NEWOBJ_OF(st, struct RStruct, klass, flags, sizeof(struct RStruct), 0);
857
858 st->as.heap.ptr = NULL;
859 st->as.heap.fields_obj = 0;
860 st->as.heap.len = 0;
861
862 st->as.heap.ptr = struct_heap_alloc((VALUE)st, n);
863 rb_mem_clear((VALUE *)st->as.heap.ptr, n);
864 st->as.heap.len = n;
865
866 return (VALUE)st;
867 }
868}
869
870 VALUE
871rb_struct_alloc(VALUE klass, VALUE values)
872{
873 return rb_class_new_instance(RARRAY_LENINT(values), RARRAY_CONST_PTR(values), klass);
874}
875
876 VALUE
877rb_struct_new(VALUE klass, ...)
878{
879 VALUE tmpargs[16], *mem = tmpargs;
880 int size, i;
881 va_list args;
882
883 size = rb_long2int(num_members(klass));
884 if (size > numberof(tmpargs)) {
885 tmpargs[0] = rb_ary_hidden_new(size);
886 mem = RARRAY_PTR(tmpargs[0]);
887 }
888 va_start(args, klass);
889 for (i=0; i<size; i++) {
890 mem[i] = va_arg(args, VALUE);
891 }
892 va_end(args);
893
894 return rb_class_new_instance(size, mem, klass);
895}
896
897static VALUE
898struct_enum_size(VALUE s, VALUE args, VALUE eobj)
899{
900 return rb_struct_size(s);
901}
902
903/*
904 * call-seq:
905 * each {|value| ... } -> self
906 * each -> enumerator
907 *
908 * Calls the given block with the value of each member; returns +self+:
909 *
910 * Customer = Struct.new(:name, :address, :zip)
911 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
912 * joe.each {|value| p value }
913 *
914 * Output:
915 *
916 * "Joe Smith"
917 * "123 Maple, Anytown NC"
918 * 12345
919 *
920 * Returns an Enumerator if no block is given.
921 *
922 * Related: #each_pair.
923 */
924
925static VALUE
926rb_struct_each(VALUE s)
927{
928 long i;
929
930 RETURN_SIZED_ENUMERATOR(s, 0, 0, struct_enum_size);
931 for (i=0; i<RSTRUCT_LEN(s); i++) {
932 rb_yield(RSTRUCT_GET(s, i));
933 }
934 return s;
935}
936
937/*
938 * call-seq:
939 * each_pair {|(name, value)| ... } -> self
940 * each_pair -> enumerator
941 *
942 * Calls the given block with each member name/value pair; returns +self+:
943 *
944 * Customer = Struct.new(:name, :address, :zip) # => Customer
945 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
946 * joe.each_pair {|(name, value)| p "#{name} => #{value}" }
947 *
948 * Output:
949 *
950 * "name => Joe Smith"
951 * "address => 123 Maple, Anytown NC"
952 * "zip => 12345"
953 *
954 * Returns an Enumerator if no block is given.
955 *
956 * Related: #each.
957 *
958 */
959
960static VALUE
961rb_struct_each_pair(VALUE s)
962{
963 VALUE members;
964 long i;
965
966 RETURN_SIZED_ENUMERATOR(s, 0, 0, struct_enum_size);
967 members = rb_struct_members(s);
968 if (rb_block_pair_yield_optimizable()) {
969 for (i=0; i<RSTRUCT_LEN(s); i++) {
970 VALUE key = rb_ary_entry(members, i);
971 VALUE value = RSTRUCT_GET(s, i);
972 rb_yield_values(2, key, value);
973 }
974 }
975 else {
976 for (i=0; i<RSTRUCT_LEN(s); i++) {
977 VALUE key = rb_ary_entry(members, i);
978 VALUE value = RSTRUCT_GET(s, i);
979 rb_yield(rb_assoc_new(key, value));
980 }
981 }
982 return s;
983}
984
985static VALUE
986inspect_struct(VALUE s, VALUE prefix, int recur)
987{
988 VALUE cname = rb_class_path(rb_obj_class(s));
989 VALUE members;
990 VALUE str = prefix;
991 long i, len;
992 char first = RSTRING_PTR(cname)[0];
993
994 if (recur || first != '#') {
995 rb_str_append(str, cname);
996 }
997 if (recur) {
998 return rb_str_cat2(str, ":...>");
999 }
1000
1001 members = rb_struct_members(s);
1002 len = RSTRUCT_LEN(s);
1003
1004 for (i=0; i<len; i++) {
1005 VALUE slot;
1006 ID id;
1007
1008 if (i > 0) {
1009 rb_str_cat2(str, ", ");
1010 }
1011 else if (first != '#') {
1012 rb_str_cat2(str, " ");
1013 }
1014 slot = RARRAY_AREF(members, i);
1015 id = SYM2ID(slot);
1016 if (rb_is_local_id(id) || rb_is_const_id(id)) {
1017 rb_str_append(str, rb_id2str(id));
1018 }
1019 else {
1020 rb_str_append(str, rb_inspect(slot));
1021 }
1022 rb_str_cat2(str, "=");
1023 rb_str_append(str, rb_inspect(RSTRUCT_GET(s, i)));
1024 }
1025 rb_str_cat2(str, ">");
1026
1027 return str;
1028}
1029
1030/*
1031 * call-seq:
1032 * inspect -> string
1033 *
1034 * Returns a string representation of +self+:
1035 *
1036 * Customer = Struct.new(:name, :address, :zip) # => Customer
1037 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1038 * joe.inspect # => "#<struct Customer name=\"Joe Smith\", address=\"123 Maple, Anytown NC\", zip=12345>"
1039 *
1040 */
1041
1042static VALUE
1043rb_struct_inspect(VALUE s)
1044{
1045 return rb_exec_recursive(inspect_struct, s, rb_str_new2("#<struct "));
1046}
1047
1048/*
1049 * call-seq:
1050 * to_a -> array
1051 *
1052 * Returns the values in +self+ as an array:
1053 *
1054 * Customer = Struct.new(:name, :address, :zip)
1055 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1056 * joe.to_a # => ["Joe Smith", "123 Maple, Anytown NC", 12345]
1057 *
1058 * Related: #members.
1059 */
1060
1061static VALUE
1062rb_struct_to_a(VALUE s)
1063{
1064 return rb_ary_new4(RSTRUCT_LEN(s), RSTRUCT_CONST_PTR(s));
1065}
1066
1067/*
1068 * call-seq:
1069 * to_h -> hash
1070 * to_h {|name, value| ... } -> hash
1071 *
1072 * Returns a hash containing the name and value for each member:
1073 *
1074 * Customer = Struct.new(:name, :address, :zip)
1075 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1076 * h = joe.to_h
1077 * h # => {:name=>"Joe Smith", :address=>"123 Maple, Anytown NC", :zip=>12345}
1078 *
1079 * If a block is given, it is called with each name/value pair;
1080 * the block should return a 2-element array whose elements will become
1081 * a key/value pair in the returned hash:
1082 *
1083 * h = joe.to_h{|name, value| [name.upcase, value.to_s.upcase]}
1084 * h # => {:NAME=>"JOE SMITH", :ADDRESS=>"123 MAPLE, ANYTOWN NC", :ZIP=>"12345"}
1085 *
1086 * Raises ArgumentError if the block returns an inappropriate value.
1087 *
1088 */
1089
1090static VALUE
1091rb_struct_to_h(VALUE s)
1092{
1093 VALUE h = rb_hash_new_with_size(RSTRUCT_LEN(s));
1094 VALUE members = rb_struct_members(s);
1095 long i;
1096 int block_given = rb_block_given_p();
1097
1098 for (i=0; i<RSTRUCT_LEN(s); i++) {
1099 VALUE k = rb_ary_entry(members, i), v = RSTRUCT_GET(s, i);
1100 if (block_given)
1101 rb_hash_set_pair(h, rb_yield_values(2, k, v));
1102 else
1103 rb_hash_aset(h, k, v);
1104 }
1105 return h;
1106}
1107
1108/*
1109 * call-seq:
1110 * deconstruct_keys(array_of_names) -> hash
1111 *
1112 * Returns a hash of the name/value pairs for the given member names.
1113 *
1114 * Customer = Struct.new(:name, :address, :zip)
1115 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1116 * h = joe.deconstruct_keys([:zip, :address])
1117 * h # => {:zip=>12345, :address=>"123 Maple, Anytown NC"}
1118 *
1119 * Returns all names and values if +array_of_names+ is +nil+:
1120 *
1121 * h = joe.deconstruct_keys(nil)
1122 * h # => {:name=>"Joseph Smith, Jr.", :address=>"123 Maple, Anytown NC", :zip=>12345}
1123 *
1124 */
1125static VALUE
1126rb_struct_deconstruct_keys(VALUE s, VALUE keys)
1127{
1128 return deconstruct_keys(s, keys, false);
1129}
1130
1131static VALUE
1132deconstruct_keys(VALUE s, VALUE keys, bool name_only)
1133{
1134 VALUE h;
1135 long i;
1136
1137 if (NIL_P(keys)) {
1138 return rb_struct_to_h(s);
1139 }
1140 if (UNLIKELY(!RB_TYPE_P(keys, T_ARRAY))) {
1141 rb_raise(rb_eTypeError,
1142 "wrong argument type %"PRIsVALUE" (expected Array or nil)",
1143 rb_obj_class(keys));
1144
1145 }
1146 if (RSTRUCT_LEN(s) < RARRAY_LEN(keys)) {
1147 return rb_hash_new_with_size(0);
1148 }
1149 h = rb_hash_new_with_size(RARRAY_LEN(keys));
1150 for (i=0; i<RARRAY_LEN(keys); i++) {
1151 VALUE key = RARRAY_AREF(keys, i);
1152 int i = rb_struct_pos(s, &key, name_only);
1153 if (i < 0) {
1154 return h;
1155 }
1156 rb_hash_aset(h, key, RSTRUCT_GET(s, i));
1157 }
1158 return h;
1159}
1160
1161/* :nodoc: */
1162 VALUE
1163rb_struct_init_copy(VALUE copy, VALUE s)
1164{
1165 long i, len;
1166
1167 if (!OBJ_INIT_COPY(copy, s)) return copy;
1168 if (RSTRUCT_LEN(copy) != RSTRUCT_LEN(s)) {
1169 rb_raise(rb_eTypeError, "struct size mismatch");
1170 }
1171
1172 for (i=0, len=RSTRUCT_LEN(copy); i<len; i++) {
1173 RSTRUCT_SET(copy, i, RSTRUCT_GET(s, i));
1174 }
1175
1176 return copy;
1177}
1178
1179static int
1180rb_struct_pos(VALUE s, VALUE *name, bool name_only)
1181{
1182 long i;
1183 VALUE idx = *name;
1184
1185 if (SYMBOL_P(idx)) {
1186 return struct_member_pos(s, idx);
1187 }
1188 else if (name_only || RB_TYPE_P(idx, T_STRING)) {
1189 idx = rb_check_symbol(name);
1190 if (NIL_P(idx)) return -1;
1191 return struct_member_pos(s, idx);
1192 }
1193 else {
1194 long len;
1195 i = NUM2LONG(idx);
1196 len = RSTRUCT_LEN(s);
1197 if (i < 0) {
1198 if (i + len < 0) {
1199 *name = LONG2FIX(i);
1200 return -1;
1201 }
1202 i += len;
1203 }
1204 else if (len <= i) {
1205 *name = LONG2FIX(i);
1206 return -1;
1207 }
1208 return (int)i;
1209 }
1210}
1211
1212static void
1213invalid_struct_pos(VALUE s, VALUE idx)
1214{
1215 if (FIXNUM_P(idx)) {
1216 long i = FIX2INT(idx), len = RSTRUCT_LEN(s);
1217 if (i < 0) {
1218 rb_raise(rb_eIndexError, "offset %ld too small for struct(size:%ld)",
1219 i, len);
1220 }
1221 else {
1222 rb_raise(rb_eIndexError, "offset %ld too large for struct(size:%ld)",
1223 i, len);
1224 }
1225 }
1226 else {
1227 rb_name_err_raise("no member '%1$s' in struct", s, idx);
1228 }
1229}
1230
1231/*
1232 * call-seq:
1233 * struct[name] -> object
1234 * struct[n] -> object
1235 *
1236 * Returns a value from +self+.
1237 *
1238 * With symbol or string argument +name+ given, returns the value for the named member:
1239 *
1240 * Customer = Struct.new(:name, :address, :zip)
1241 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1242 * joe[:zip] # => 12345
1243 *
1244 * Raises NameError if +name+ is not the name of a member.
1245 *
1246 * With integer argument +n+ given, returns <tt>self.values[n]</tt>
1247 * if +n+ is in range;
1248 * see Array@Array+Indexes:
1249 *
1250 * joe[2] # => 12345
1251 * joe[-2] # => "123 Maple, Anytown NC"
1252 *
1253 * Raises IndexError if +n+ is out of range.
1254 *
1255 */
1256
1257 VALUE
1258rb_struct_aref(VALUE s, VALUE idx)
1259{
1260 int i = rb_struct_pos(s, &idx, false);
1261 if (i < 0) invalid_struct_pos(s, idx);
1262 return RSTRUCT_GET(s, i);
1263}
1264
1265/*
1266 * call-seq:
1267 * struct[name] = value -> value
1268 * struct[n] = value -> value
1269 *
1270 * Assigns a value to a member.
1271 *
1272 * With symbol or string argument +name+ given, assigns the given +value+
1273 * to the named member; returns +value+:
1274 *
1275 * Customer = Struct.new(:name, :address, :zip)
1276 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1277 * joe[:zip] = 54321 # => 54321
1278 * joe # => #<struct Customer name="Joe Smith", address="123 Maple, Anytown NC", zip=54321>
1279 *
1280 * Raises NameError if +name+ is not the name of a member.
1281 *
1282 * With integer argument +n+ given, assigns the given +value+
1283 * to the +n+-th member if +n+ is in range;
1284 * see Array@Array+Indexes:
1285 *
1286 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1287 * joe[2] = 54321 # => 54321
1288 * joe[-3] = 'Joseph Smith' # => "Joseph Smith"
1289 * joe # => #<struct Customer name="Joseph Smith", address="123 Maple, Anytown NC", zip=54321>
1290 *
1291 * Raises IndexError if +n+ is out of range.
1292 *
1293 */
1294
1295 VALUE
1296rb_struct_aset(VALUE s, VALUE idx, VALUE val)
1297{
1298 int i = rb_struct_pos(s, &idx, false);
1299 if (i < 0) invalid_struct_pos(s, idx);
1300 rb_struct_modify(s);
1301 RSTRUCT_SET(s, i, val);
1302 return val;
1303}
1304
1305FUNC_MINIMIZED(VALUE rb_struct_lookup(VALUE s, VALUE idx));
1306NOINLINE(static VALUE rb_struct_lookup_default(VALUE s, VALUE idx, VALUE notfound, bool name_only));
1307
1308 VALUE
1309rb_struct_lookup(VALUE s, VALUE idx)
1310{
1311 return rb_struct_lookup_default(s, idx, Qnil, false);
1312}
1313
1314static VALUE
1315rb_struct_lookup_default(VALUE s, VALUE idx, VALUE notfound, bool name_only)
1316{
1317 int i = rb_struct_pos(s, &idx, name_only);
1318 if (i < 0) return notfound;
1319 return RSTRUCT_GET(s, i);
1320}
1321
1322static VALUE
1323struct_entry(VALUE s, long n)
1324{
1325 return rb_struct_aref(s, LONG2NUM(n));
1326}
1327
1328/*
1329 * call-seq:
1330 * values_at(*integers) -> array
1331 * values_at(integer_range) -> array
1332 *
1333 * Returns an array of values from +self+.
1334 *
1335 * With integer arguments +integers+ given,
1336 * returns an array containing each value given by one of +integers+:
1337 *
1338 * Customer = Struct.new(:name, :address, :zip)
1339 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1340 * joe.values_at(0, 2) # => ["Joe Smith", 12345]
1341 * joe.values_at(2, 0) # => [12345, "Joe Smith"]
1342 * joe.values_at(2, 1, 0) # => [12345, "123 Maple, Anytown NC", "Joe Smith"]
1343 * joe.values_at(0, -3) # => ["Joe Smith", "Joe Smith"]
1344 *
1345 * Raises IndexError if any of +integers+ is out of range;
1346 * see Array@Array+Indexes.
1347 *
1348 * With integer range argument +integer_range+ given,
1349 * returns an array containing each value given by the elements of the range;
1350 * fills with +nil+ values for range elements larger than the structure:
1351 *
1352 * joe.values_at(0..2)
1353 * # => ["Joe Smith", "123 Maple, Anytown NC", 12345]
1354 * joe.values_at(-3..-1)
1355 * # => ["Joe Smith", "123 Maple, Anytown NC", 12345]
1356 * joe.values_at(1..4) # => ["123 Maple, Anytown NC", 12345, nil, nil]
1357 *
1358 * Raises RangeError if any element of the range is negative and out of range;
1359 * see Array@Array+Indexes.
1360 *
1361 */
1362
1363static VALUE
1364rb_struct_values_at(int argc, VALUE *argv, VALUE s)
1365{
1366 return rb_get_values_at(s, RSTRUCT_LEN(s), argc, argv, struct_entry);
1367}
1368
1369/*
1370 * call-seq:
1371 * select {|value| ... } -> array
1372 * select -> enumerator
1373 *
1374 * With a block given, returns an array of values from +self+
1375 * for which the block returns a truthy value:
1376 *
1377 * Customer = Struct.new(:name, :address, :zip)
1378 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1379 * a = joe.select {|value| value.is_a?(String) }
1380 * a # => ["Joe Smith", "123 Maple, Anytown NC"]
1381 * a = joe.select {|value| value.is_a?(Integer) }
1382 * a # => [12345]
1383 *
1384 * With no block given, returns an Enumerator.
1385 */
1386
1387static VALUE
1388rb_struct_select(int argc, VALUE *argv, VALUE s)
1389{
1390 VALUE result;
1391 long i;
1392
1393 rb_check_arity(argc, 0, 0);
1394 RETURN_SIZED_ENUMERATOR(s, 0, 0, struct_enum_size);
1395 result = rb_ary_new();
1396 for (i = 0; i < RSTRUCT_LEN(s); i++) {
1397 if (RTEST(rb_yield(RSTRUCT_GET(s, i)))) {
1398 rb_ary_push(result, RSTRUCT_GET(s, i));
1399 }
1400 }
1401
1402 return result;
1403}
1404
1405static VALUE
1406recursive_equal(VALUE s, VALUE s2, int recur)
1407{
1408 long i, len;
1409
1410 if (recur) return Qtrue; /* Subtle! */
1411 len = RSTRUCT_LEN(s);
1412 for (i=0; i<len; i++) {
1413 if (!rb_equal(RSTRUCT_GET(s, i), RSTRUCT_GET(s2, i))) return Qfalse;
1414 }
1415 return Qtrue;
1416}
1417
1418
1419/*
1420 * call-seq:
1421 * self == other -> true or false
1422 *
1423 * Returns +true+ if and only if the following are true; otherwise returns +false+:
1424 *
1425 * - <tt>other.class == self.class</tt>.
1426 * - For each member name +name+, <tt>other.name == self.name</tt>.
1427 *
1428 * Examples:
1429 *
1430 * Customer = Struct.new(:name, :address, :zip)
1431 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1432 * joe_jr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1433 * joe_jr == joe # => true
1434 * joe_jr[:name] = 'Joe Smith, Jr.'
1435 * # => "Joe Smith, Jr."
1436 * joe_jr == joe # => false
1437 */
1438
1439static VALUE
1440rb_struct_equal(VALUE s, VALUE s2)
1441{
1442 if (s == s2) return Qtrue;
1443 if (!RB_TYPE_P(s2, T_STRUCT)) return Qfalse;
1444 if (rb_obj_class(s) != rb_obj_class(s2)) return Qfalse;
1445 if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) {
1446 rb_bug("inconsistent struct"); /* should never happen */
1447 }
1448
1449 return rb_exec_recursive_paired(recursive_equal, s, s2, s2);
1450}
1451
1452/*
1453 * call-seq:
1454 * hash -> integer
1455 *
1456 * Returns the integer hash value for +self+.
1457 *
1458 * Two structs of the same class and with the same content
1459 * will have the same hash code (and will compare using Struct#eql?):
1460 *
1461 * Customer = Struct.new(:name, :address, :zip)
1462 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1463 * joe_jr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1464 * joe.hash == joe_jr.hash # => true
1465 * joe_jr[:name] = 'Joe Smith, Jr.'
1466 * joe.hash == joe_jr.hash # => false
1467 *
1468 * Related: Object#hash.
1469 */
1470
1471static VALUE
1472rb_struct_hash(VALUE s)
1473{
1474 long i, len;
1475 st_index_t h;
1476 VALUE n;
1477
1478 h = rb_hash_start(rb_hash(rb_obj_class(s)));
1479 len = RSTRUCT_LEN(s);
1480 for (i = 0; i < len; i++) {
1481 n = rb_hash(RSTRUCT_GET(s, i));
1482 h = rb_hash_uint(h, NUM2LONG(n));
1483 }
1484 h = rb_hash_end(h);
1485 return ST2FIX(h);
1486}
1487
1488static VALUE
1489recursive_eql(VALUE s, VALUE s2, int recur)
1490{
1491 long i, len;
1492
1493 if (recur) return Qtrue; /* Subtle! */
1494 len = RSTRUCT_LEN(s);
1495 for (i=0; i<len; i++) {
1496 if (!rb_eql(RSTRUCT_GET(s, i), RSTRUCT_GET(s2, i))) return Qfalse;
1497 }
1498 return Qtrue;
1499}
1500
1501/*
1502 * call-seq:
1503 * eql?(other) -> true or false
1504 *
1505 * Returns +true+ if and only if the following are true; otherwise returns +false+:
1506 *
1507 * - <tt>other.class == self.class</tt>.
1508 * - For each member name +name+, <tt>other.name.eql?(self.name)</tt>.
1509 *
1510 * Customer = Struct.new(:name, :address, :zip)
1511 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1512 * joe_jr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1513 * joe_jr.eql?(joe) # => true
1514 * joe_jr[:name] = 'Joe Smith, Jr.'
1515 * joe_jr.eql?(joe) # => false
1516 *
1517 * Related: Object#==.
1518 */
1519
1520static VALUE
1521rb_struct_eql(VALUE s, VALUE s2)
1522{
1523 if (s == s2) return Qtrue;
1524 if (!RB_TYPE_P(s2, T_STRUCT)) return Qfalse;
1525 if (rb_obj_class(s) != rb_obj_class(s2)) return Qfalse;
1526 if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) {
1527 rb_bug("inconsistent struct"); /* should never happen */
1528 }
1529
1530 return rb_exec_recursive_paired(recursive_eql, s, s2, s2);
1531}
1532
1533/*
1534 * call-seq:
1535 * size -> integer
1536 *
1537 * Returns the number of members.
1538 *
1539 * Customer = Struct.new(:name, :address, :zip)
1540 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1541 * joe.size #=> 3
1542 *
1543 */
1544
1545 VALUE
1546rb_struct_size(VALUE s)
1547{
1548 return LONG2FIX(RSTRUCT_LEN(s));
1549}
1550
1551/*
1552 * call-seq:
1553 * dig(name, *identifiers) -> object
1554 * dig(n, *identifiers) -> object
1555 *
1556 * Finds and returns an object among nested objects.
1557 * The nested objects may be instances of various classes.
1558 * See {Dig Methods}[rdoc-ref:dig_methods.rdoc].
1559 *
1560 *
1561 * Given symbol or string argument +name+,
1562 * returns the object that is specified by +name+ and +identifiers+:
1563 *
1564 * Foo = Struct.new(:a)
1565 * f = Foo.new(Foo.new({b: [1, 2, 3]}))
1566 * f.dig(:a) # => #<struct Foo a={:b=>[1, 2, 3]}>
1567 * f.dig(:a, :a) # => {:b=>[1, 2, 3]}
1568 * f.dig(:a, :a, :b) # => [1, 2, 3]
1569 * f.dig(:a, :a, :b, 0) # => 1
1570 * f.dig(:b, 0) # => nil
1571 *
1572 * Given integer argument +n+,
1573 * returns the object that is specified by +n+ and +identifiers+:
1574 *
1575 * f.dig(0) # => #<struct Foo a={:b=>[1, 2, 3]}>
1576 * f.dig(0, 0) # => {:b=>[1, 2, 3]}
1577 * f.dig(0, 0, :b) # => [1, 2, 3]
1578 * f.dig(0, 0, :b, 0) # => 1
1579 * f.dig(:b, 0) # => nil
1580 *
1581 */
1582
1583static VALUE
1584rb_struct_dig(int argc, VALUE *argv, VALUE self)
1585{
1586 rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
1587 self = rb_struct_lookup(self, *argv);
1588 if (!--argc) return self;
1589 ++argv;
1590 return rb_obj_dig(argc, argv, self, Qnil);
1591}
1592
1593/*
1594 * Document-class: Data
1595 *
1596 * Class \Data provides a convenient way to define simple classes
1597 * for value-alike objects.
1598 *
1599 * The simplest example of usage:
1600 *
1601 * Measure = Data.define(:amount, :unit)
1602 *
1603 * # Positional arguments constructor is provided
1604 * distance = Measure.new(100, 'km')
1605 * #=> #<data Measure amount=100, unit="km">
1606 *
1607 * # Keyword arguments constructor is provided
1608 * weight = Measure.new(amount: 50, unit: 'kg')
1609 * #=> #<data Measure amount=50, unit="kg">
1610 *
1611 * # Alternative form to construct an object:
1612 * speed = Measure[10, 'mPh']
1613 * #=> #<data Measure amount=10, unit="mPh">
1614 *
1615 * # Works with keyword arguments, too:
1616 * area = Measure[amount: 1.5, unit: 'm^2']
1617 * #=> #<data Measure amount=1.5, unit="m^2">
1618 *
1619 * # Argument accessors are provided:
1620 * distance.amount #=> 100
1621 * distance.unit #=> "km"
1622 *
1623 * Constructed object also has a reasonable definitions of #==
1624 * operator, #to_h hash conversion, and #deconstruct / #deconstruct_keys
1625 * to be used in pattern matching.
1626 *
1627 * ::define method accepts an optional block and evaluates it in
1628 * the context of the newly defined class. That allows to define
1629 * additional methods:
1630 *
1631 * Measure = Data.define(:amount, :unit) do
1632 * def <=>(other)
1633 * return unless other.is_a?(self.class) && other.unit == unit
1634 * amount <=> other.amount
1635 * end
1636 *
1637 * include Comparable
1638 * end
1639 *
1640 * Measure[3, 'm'] < Measure[5, 'm'] #=> true
1641 * Measure[3, 'm'] < Measure[5, 'kg']
1642 * # comparison of Measure with Measure failed (ArgumentError)
1643 *
1644 * Data provides no member writers, or enumerators: it is meant
1645 * to be a storage for immutable atomic values. But note that
1646 * if some of data members is of a mutable class, Data does no additional
1647 * immutability enforcement:
1648 *
1649 * Event = Data.define(:time, :weekdays)
1650 * event = Event.new('18:00', %w[Tue Wed Fri])
1651 * #=> #<data Event time="18:00", weekdays=["Tue", "Wed", "Fri"]>
1652 *
1653 * # There is no #time= or #weekdays= accessors, but changes are
1654 * # still possible:
1655 * event.weekdays << 'Sat'
1656 * event
1657 * #=> #<data Event time="18:00", weekdays=["Tue", "Wed", "Fri", "Sat"]>
1658 *
1659 * See also Struct, which is a similar concept, but has more
1660 * container-alike API, allowing to change contents of the object
1661 * and enumerate it.
1662 */
1663
1664/*
1665 * call-seq:
1666 * define(*symbols) -> class
1667 *
1668 * Defines a new \Data class.
1669 *
1670 * measure = Data.define(:amount, :unit)
1671 * #=> #<Class:0x00007f70c6868498>
1672 * measure.new(1, 'km')
1673 * #=> #<data amount=1, unit="km">
1674 *
1675 * # It you store the new class in the constant, it will
1676 * # affect #inspect and will be more natural to use:
1677 * Measure = Data.define(:amount, :unit)
1678 * #=> Measure
1679 * Measure.new(1, 'km')
1680 * #=> #<data Measure amount=1, unit="km">
1681 *
1682 *
1683 * Note that member-less \Data is acceptable and might be a useful technique
1684 * for defining several homogeneous data classes, like
1685 *
1686 * class HTTPFetcher
1687 * Response = Data.define(:body)
1688 * NotFound = Data.define
1689 * # ... implementation
1690 * end
1691 *
1692 * Now, different kinds of responses from +HTTPFetcher+ would have consistent
1693 * representation:
1694 *
1695 * #<data HTTPFetcher::Response body="<html...">
1696 * #<data HTTPFetcher::NotFound>
1697 *
1698 * And are convenient to use in pattern matching:
1699 *
1700 * case fetcher.get(url)
1701 * in HTTPFetcher::Response(body)
1702 * # process body variable
1703 * in HTTPFetcher::NotFound
1704 * # handle not found case
1705 * end
1706 */
1707
1708static VALUE
1709rb_data_s_def(int argc, VALUE *argv, VALUE klass)
1710{
1711 VALUE rest;
1712 long i;
1713 VALUE data_class;
1714
1715 rest = rb_ident_hash_new();
1716 RBASIC_CLEAR_CLASS(rest);
1717 for (i=0; i<argc; i++) {
1718 VALUE mem = rb_to_symbol(argv[i]);
1719 if (rb_is_attrset_sym(mem)) {
1720 rb_raise(rb_eArgError, "invalid data member: %"PRIsVALUE, mem);
1721 }
1722 if (RTEST(rb_hash_has_key(rest, mem))) {
1723 rb_raise(rb_eArgError, "duplicate member: %"PRIsVALUE, mem);
1724 }
1725 rb_hash_aset(rest, mem, Qtrue);
1726 }
1727 rest = rb_hash_keys(rest);
1728 RBASIC_CLEAR_CLASS(rest);
1729 OBJ_FREEZE(rest);
1730 data_class = anonymous_struct(klass);
1731 setup_data(data_class, rest);
1732 if (rb_block_given_p()) {
1733 rb_mod_module_eval(0, 0, data_class);
1734 }
1735
1736 return data_class;
1737}
1738
1739 VALUE
1740rb_data_define(VALUE super, ...)
1741{
1742 va_list ar;
1743 VALUE ary;
1744 va_start(ar, super);
1745 ary = struct_make_members_list(ar);
1746 va_end(ar);
1747 if (!super) super = rb_cData;
1748 VALUE klass = setup_data(anonymous_struct(super), ary);
1749 rb_vm_register_global_object(klass);
1750 return klass;
1751}
1752
1753static int
1754data_hash_set_i(VALUE key, VALUE val, VALUE arg)
1755{
1756 struct struct_hash_set_arg *args = (struct struct_hash_set_arg *)arg;
1757 int i = struct_hash_aset(key, val, args, true);
1758 if (i >= 0 && args->missing_count > 0) {
1759 VALUE k = RARRAY_AREF(args->missing_keywords, i);
1760 if (!NIL_P(k)) {
1761 RARRAY_ASET(args->missing_keywords, i, Qnil);
1762 args->missing_count--;
1763 }
1764 }
1765 return ST_CONTINUE;
1766}
1767
1768/*
1769 * call-seq:
1770 * DataClass::members -> array_of_symbols
1771 *
1772 * Returns an array of member names of the data class:
1773 *
1774 * Measure = Data.define(:amount, :unit)
1775 * Measure.members # => [:amount, :unit]
1776 *
1777 */
1778
1779#define rb_data_s_members_m rb_struct_s_members_m
1780
1781
1782/*
1783 * call-seq:
1784 * new(*args) -> instance
1785 * new(**kwargs) -> instance
1786 * ::[](*args) -> instance
1787 * ::[](**kwargs) -> instance
1788 *
1789 * Constructors for classes defined with ::define accept both positional and
1790 * keyword arguments.
1791 *
1792 * Measure = Data.define(:amount, :unit)
1793 *
1794 * Measure.new(1, 'km')
1795 * #=> #<data Measure amount=1, unit="km">
1796 * Measure.new(amount: 1, unit: 'km')
1797 * #=> #<data Measure amount=1, unit="km">
1798 *
1799 * # Alternative shorter initialization with []
1800 * Measure[1, 'km']
1801 * #=> #<data Measure amount=1, unit="km">
1802 * Measure[amount: 1, unit: 'km']
1803 * #=> #<data Measure amount=1, unit="km">
1804 *
1805 * All arguments are mandatory (unlike Struct), and converted to keyword arguments:
1806 *
1807 * Measure.new(amount: 1)
1808 * # in `initialize': missing keyword: :unit (ArgumentError)
1809 *
1810 * Measure.new(1)
1811 * # in `initialize': missing keyword: :unit (ArgumentError)
1812 *
1813 * Note that <tt>Measure#initialize</tt> always receives keyword arguments, and that
1814 * mandatory arguments are checked in +initialize+, not in +new+. This can be
1815 * important for redefining initialize in order to convert arguments or provide
1816 * defaults:
1817 *
1818 * Measure = Data.define(:amount, :unit)
1819 * class Measure
1820 * NONE = Data.define
1821 *
1822 * def initialize(amount:, unit: NONE.new)
1823 * super(amount: Float(amount), unit:)
1824 * end
1825 * end
1826 *
1827 * Measure.new('10', 'km') # => #<data Measure amount=10.0, unit="km">
1828 * Measure.new(10_000) # => #<data Measure amount=10000.0, unit=#<data Measure::NONE>>
1829 *
1830 */
1831
1832static VALUE
1833rb_data_initialize_m(int argc, const VALUE *argv, VALUE self)
1834{
1835 VALUE klass = rb_obj_class(self);
1836 rb_struct_modify(self);
1837 VALUE members = struct_ivar_get(klass, id_members);
1838 size_t num_members = RARRAY_LEN(members);
1839
1840 if (argc == 0) {
1841 if (num_members > 0) {
1842 rb_exc_raise(rb_keyword_error_new("missing", members));
1843 }
1844 OBJ_FREEZE(self);
1845 return Qnil;
1846 }
1847 if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) {
1848 rb_error_arity(argc, 0, 0);
1849 }
1850
1851 VALUE missing = rb_ary_dup(members);
1852 RBASIC_CLEAR_CLASS(missing);
1853 struct struct_hash_set_arg arg = {
1854 .self = self,
1855 .unknown_keywords = Qnil,
1856 .missing_keywords = missing,
1857 .missing_count = (long)num_members,
1858 };
1859 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self), num_members);
1860 rb_hash_foreach(argv[0], data_hash_set_i, (VALUE)&arg);
1861 // Freeze early before potentially raising, so that we don't leave an
1862 // unfrozen copy on the heap, which could get exposed via ObjectSpace.
1863 OBJ_FREEZE(self);
1864 if (UNLIKELY(arg.missing_count > 0)) {
1865 rb_ary_compact_bang(missing);
1866 RUBY_ASSERT(RARRAY_LEN(missing) == arg.missing_count, "missing_count=%ld but %ld", arg.missing_count, RARRAY_LEN(missing));
1867 RBASIC_SET_CLASS_RAW(missing, rb_cArray);
1868 rb_exc_raise(rb_keyword_error_new("missing", missing));
1869 }
1870 VALUE unknown_keywords = arg.unknown_keywords;
1871 if (UNLIKELY(!NIL_P(unknown_keywords))) {
1872 RBASIC_SET_CLASS_RAW(unknown_keywords, rb_cArray);
1873 rb_exc_raise(rb_keyword_error_new("unknown", unknown_keywords));
1874 }
1875
1876 return Qnil;
1877}
1878
1879/* :nodoc: */
1880static VALUE
1881rb_data_init_copy(VALUE copy, VALUE s)
1882{
1883 copy = rb_struct_init_copy(copy, s);
1884 RB_OBJ_FREEZE(copy);
1885 return copy;
1886}
1887
1888/*
1889 * call-seq:
1890 * with(**kwargs) -> instance
1891 *
1892 * Returns a shallow copy of +self+ --- the instance variables of
1893 * +self+ are copied, but not the objects they reference.
1894 *
1895 * If the method is supplied any keyword arguments, the copy will
1896 * be created with the respective field values updated to use the
1897 * supplied keyword argument values. Note that it is an error to
1898 * supply a keyword that the Data class does not have as a member.
1899 *
1900 * Point = Data.define(:x, :y)
1901 *
1902 * origin = Point.new(x: 0, y: 0)
1903 *
1904 * up = origin.with(x: 1)
1905 * right = origin.with(y: 1)
1906 * up_and_right = up.with(y: 1)
1907 *
1908 * p origin # #<data Point x=0, y=0>
1909 * p up # #<data Point x=1, y=0>
1910 * p right # #<data Point x=0, y=1>
1911 * p up_and_right # #<data Point x=1, y=1>
1912 *
1913 * out = origin.with(z: 1) # ArgumentError: unknown keyword: :z
1914 * some_point = origin.with(1, 2) # ArgumentError: expected keyword arguments, got positional arguments
1915 *
1916 */
1917
1918static VALUE
1919rb_data_with(int argc, const VALUE *argv, VALUE self)
1920{
1921 VALUE kwargs;
1922 rb_scan_args(argc, argv, "0:", &kwargs);
1923 if (NIL_P(kwargs)) {
1924 return self;
1925 }
1926
1927 VALUE h = rb_struct_to_h(self);
1928 rb_hash_update_by(h, kwargs, 0);
1929 return rb_class_new_instance_kw(1, &h, rb_obj_class(self), TRUE);
1930}
1931
1932/*
1933 * call-seq:
1934 * inspect -> string
1935 * to_s -> string
1936 *
1937 * Returns a string representation of +self+:
1938 *
1939 * Measure = Data.define(:amount, :unit)
1940 *
1941 * distance = Measure[10, 'km']
1942 *
1943 * p distance # uses #inspect underneath
1944 * #<data Measure amount=10, unit="km">
1945 *
1946 * puts distance # uses #to_s underneath, same representation
1947 * #<data Measure amount=10, unit="km">
1948 *
1949 */
1950
1951static VALUE
1952rb_data_inspect(VALUE s)
1953{
1954 return rb_exec_recursive(inspect_struct, s, rb_str_new2("#<data "));
1955}
1956
1957/*
1958 * call-seq:
1959 * self == other -> true or false
1960 *
1961 * Returns +true+ if +other+ is the same class as +self+, and all members are
1962 * equal.
1963 *
1964 * Examples:
1965 *
1966 * Measure = Data.define(:amount, :unit)
1967 *
1968 * Measure[1, 'km'] == Measure[1, 'km'] #=> true
1969 * Measure[1, 'km'] == Measure[2, 'km'] #=> false
1970 * Measure[1, 'km'] == Measure[1, 'm'] #=> false
1971 *
1972 * Measurement = Data.define(:amount, :unit)
1973 * # Even though Measurement and Measure have the same "shape"
1974 * # their instances are never equal
1975 * Measure[1, 'km'] == Measurement[1, 'km'] #=> false
1976 */
1977
1978#define rb_data_equal rb_struct_equal
1979
1980/*
1981 * call-seq:
1982 * self.eql?(other) -> true or false
1983 *
1984 * Equality check that is used when two items of data are keys of a Hash.
1985 *
1986 * The subtle difference with #== is that members are also compared with their
1987 * #eql? method, which might be important in some cases:
1988 *
1989 * Measure = Data.define(:amount, :unit)
1990 *
1991 * Measure[1, 'km'] == Measure[1.0, 'km'] #=> true, they are equal as values
1992 * # ...but...
1993 * Measure[1, 'km'].eql? Measure[1.0, 'km'] #=> false, they represent different hash keys
1994 *
1995 * See also Object#eql? for further explanations of the method usage.
1996 */
1997
1998#define rb_data_eql rb_struct_eql
1999
2000/*
2001 * call-seq:
2002 * hash -> integer
2003 *
2004 * Redefines Object#hash (used to distinguish objects as Hash keys) so that
2005 * data objects of the same class with same content would have the same +hash+
2006 * value, and represented the same Hash key.
2007 *
2008 * Measure = Data.define(:amount, :unit)
2009 *
2010 * Measure[1, 'km'].hash == Measure[1, 'km'].hash #=> true
2011 * Measure[1, 'km'].hash == Measure[10, 'km'].hash #=> false
2012 * Measure[1, 'km'].hash == Measure[1, 'm'].hash #=> false
2013 * Measure[1, 'km'].hash == Measure[1.0, 'km'].hash #=> false
2014 *
2015 * # Structurally similar data class, but shouldn't be considered
2016 * # the same hash key
2017 * Measurement = Data.define(:amount, :unit)
2018 *
2019 * Measure[1, 'km'].hash == Measurement[1, 'km'].hash #=> false
2020 */
2021
2022#define rb_data_hash rb_struct_hash
2023
2024/*
2025 * call-seq:
2026 * to_h -> hash
2027 * to_h {|name, value| ... } -> hash
2028 *
2029 * Returns Hash representation of the data object.
2030 *
2031 * Measure = Data.define(:amount, :unit)
2032 * distance = Measure[10, 'km']
2033 *
2034 * distance.to_h
2035 * #=> {:amount=>10, :unit=>"km"}
2036 *
2037 * Like Enumerable#to_h, if the block is provided, it is expected to
2038 * produce key-value pairs to construct a hash:
2039 *
2040 *
2041 * distance.to_h { |name, val| [name.to_s, val.to_s] }
2042 * #=> {"amount"=>"10", "unit"=>"km"}
2043 *
2044 * Note that there is a useful symmetry between #to_h and #initialize:
2045 *
2046 * distance2 = Measure.new(**distance.to_h)
2047 * #=> #<data Measure amount=10, unit="km">
2048 * distance2 == distance
2049 * #=> true
2050 */
2051
2052#define rb_data_to_h rb_struct_to_h
2053
2054/*
2055 * call-seq:
2056 * members -> array_of_symbols
2057 *
2058 * Returns the member names from +self+ as an array:
2059 *
2060 * Measure = Data.define(:amount, :unit)
2061 * distance = Measure[10, 'km']
2062 *
2063 * distance.members #=> [:amount, :unit]
2064 *
2065 */
2066
2067#define rb_data_members_m rb_struct_members_m
2068
2069/*
2070 * call-seq:
2071 * deconstruct -> array
2072 *
2073 * Returns the values in +self+ as an array, to use in pattern matching:
2074 *
2075 * Measure = Data.define(:amount, :unit)
2076 *
2077 * distance = Measure[10, 'km']
2078 * distance.deconstruct #=> [10, "km"]
2079 *
2080 * # usage
2081 * case distance
2082 * in n, 'km' # calls #deconstruct underneath
2083 * puts "It is #{n} kilometers away"
2084 * else
2085 * puts "Don't know how to handle it"
2086 * end
2087 * # prints "It is 10 kilometers away"
2088 *
2089 * Or, with checking the class, too:
2090 *
2091 * case distance
2092 * in Measure(n, 'km')
2093 * puts "It is #{n} kilometers away"
2094 * # ...
2095 * end
2096 */
2097
2098#define rb_data_deconstruct rb_struct_to_a
2099
2100/*
2101 * call-seq:
2102 * deconstruct_keys(array_of_names_or_nil) -> hash
2103 *
2104 * Returns a hash of the name/value pairs, to use in pattern matching.
2105 *
2106 * Measure = Data.define(:amount, :unit)
2107 *
2108 * distance = Measure[10, 'km']
2109 * distance.deconstruct_keys(nil) #=> {:amount=>10, :unit=>"km"}
2110 * distance.deconstruct_keys([:amount]) #=> {:amount=>10}
2111 *
2112 * # usage
2113 * case distance
2114 * in amount:, unit: 'km' # calls #deconstruct_keys underneath
2115 * puts "It is #{amount} kilometers away"
2116 * else
2117 * puts "Don't know how to handle it"
2118 * end
2119 * # prints "It is 10 kilometers away"
2120 *
2121 * Or, with checking the class, too:
2122 *
2123 * case distance
2124 * in Measure(amount:, unit: 'km')
2125 * puts "It is #{amount} kilometers away"
2126 * # ...
2127 * end
2128 */
2129
2130static VALUE
2131rb_data_deconstruct_keys(VALUE s, VALUE keys)
2132{
2133 return deconstruct_keys(s, keys, true);
2134}
2135
2136/*
2137 * Document-class: Struct
2138 *
2139 * Class \Struct provides a convenient way to create a simple class
2140 * that can store and fetch values.
2141 *
2142 * This example creates a subclass of +Struct+, <tt>Struct::Customer</tt>;
2143 * the first argument, a string, is the name of the subclass;
2144 * the other arguments, symbols, determine the _members_ of the new subclass.
2145 *
2146 * Customer = Struct.new('Customer', :name, :address, :zip)
2147 * Customer.name # => "Struct::Customer"
2148 * Customer.class # => Class
2149 * Customer.superclass # => Struct
2150 *
2151 * Corresponding to each member are two methods, a writer and a reader,
2152 * that store and fetch values:
2153 *
2154 * methods = Customer.instance_methods false
2155 * methods # => [:zip, :address=, :zip=, :address, :name, :name=]
2156 *
2157 * An instance of the subclass may be created,
2158 * and its members assigned values, via method <tt>::new</tt>:
2159 *
2160 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
2161 * joe # => #<struct Struct::Customer name="Joe Smith", address="123 Maple, Anytown NC", zip=12345>
2162 *
2163 * The member values may be managed thus:
2164 *
2165 * joe.name # => "Joe Smith"
2166 * joe.name = 'Joseph Smith'
2167 * joe.name # => "Joseph Smith"
2168 *
2169 * And thus; note that member name may be expressed as either a string or a symbol:
2170 *
2171 * joe[:name] # => "Joseph Smith"
2172 * joe[:name] = 'Joseph Smith, Jr.'
2173 * joe['name'] # => "Joseph Smith, Jr."
2174 *
2175 * See Struct::new.
2176 *
2177 * == What's Here
2178 *
2179 * First, what's elsewhere. Class \Struct:
2180 *
2181 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
2182 * - Includes {module Enumerable}[rdoc-ref:Enumerable@What-27s+Here],
2183 * which provides dozens of additional methods.
2184 *
2185 * See also Data, which is a somewhat similar, but stricter concept for defining immutable
2186 * value objects.
2187 *
2188 * Here, class \Struct provides methods that are useful for:
2189 *
2190 * - {Creating a Struct Subclass}[rdoc-ref:Struct@Methods+for+Creating+a+Struct+Subclass]
2191 * - {Querying}[rdoc-ref:Struct@Methods+for+Querying]
2192 * - {Comparing}[rdoc-ref:Struct@Methods+for+Comparing]
2193 * - {Fetching}[rdoc-ref:Struct@Methods+for+Fetching]
2194 * - {Assigning}[rdoc-ref:Struct@Methods+for+Assigning]
2195 * - {Iterating}[rdoc-ref:Struct@Methods+for+Iterating]
2196 * - {Converting}[rdoc-ref:Struct@Methods+for+Converting]
2197 *
2198 * === Methods for Creating a Struct Subclass
2199 *
2200 * - ::new: Returns a new subclass of \Struct.
2201 *
2202 * === Methods for Querying
2203 *
2204 * - #hash: Returns the integer hash code.
2205 * - #size (aliased as #length): Returns the number of members.
2206 *
2207 * === Methods for Comparing
2208 *
2209 * - #==: Returns whether a given object is equal to +self+, using <tt>==</tt>
2210 * to compare member values.
2211 * - #eql?: Returns whether a given object is equal to +self+,
2212 * using <tt>eql?</tt> to compare member values.
2213 *
2214 * === Methods for Fetching
2215 *
2216 * - #[]: Returns the value associated with a given member name.
2217 * - #to_a (aliased as #values, #deconstruct): Returns the member values in +self+ as an array.
2218 * - #deconstruct_keys: Returns a hash of the name/value pairs
2219 * for given member names.
2220 * - #dig: Returns the object in nested objects that is specified
2221 * by a given member name and additional arguments.
2222 * - #members: Returns an array of the member names.
2223 * - #select (aliased as #filter): Returns an array of member values from +self+,
2224 * as selected by the given block.
2225 * - #values_at: Returns an array containing values for given member names.
2226 *
2227 * === Methods for Assigning
2228 *
2229 * - #[]=: Assigns a given value to a given member name.
2230 *
2231 * === Methods for Iterating
2232 *
2233 * - #each: Calls a given block with each member name.
2234 * - #each_pair: Calls a given block with each member name/value pair.
2235 *
2236 * === Methods for Converting
2237 *
2238 * - #inspect (aliased as #to_s): Returns a string representation of +self+.
2239 * - #to_h: Returns a hash of the member name/value pairs in +self+.
2240 *
2241 */
2242void
2243InitVM_Struct(void)
2244{
2245 rb_cStruct = rb_define_class("Struct", rb_cObject);
2246 rb_include_module(rb_cStruct, rb_mEnumerable);
2247
2248 rb_undef_alloc_func(rb_cStruct);
2249 rb_define_singleton_method(rb_cStruct, "new", rb_struct_s_def, -1);
2250#if 0 /* for RDoc */
2251 rb_define_singleton_method(rb_cStruct, "keyword_init?", rb_struct_s_keyword_init_p, 0);
2252 rb_define_singleton_method(rb_cStruct, "members", rb_struct_s_members_m, 0);
2253#endif
2254
2255 rb_define_method(rb_cStruct, "initialize", rb_struct_initialize_m, -1);
2256 rb_define_method(rb_cStruct, "initialize_copy", rb_struct_init_copy, 1);
2257
2258 rb_define_method(rb_cStruct, "==", rb_struct_equal, 1);
2259 rb_define_method(rb_cStruct, "eql?", rb_struct_eql, 1);
2260 rb_define_method(rb_cStruct, "hash", rb_struct_hash, 0);
2261
2262 rb_define_method(rb_cStruct, "inspect", rb_struct_inspect, 0);
2263 rb_define_alias(rb_cStruct, "to_s", "inspect");
2264 rb_define_method(rb_cStruct, "to_a", rb_struct_to_a, 0);
2265 rb_define_method(rb_cStruct, "to_h", rb_struct_to_h, 0);
2266 rb_define_method(rb_cStruct, "values", rb_struct_to_a, 0);
2267 rb_define_method(rb_cStruct, "size", rb_struct_size, 0);
2268 rb_define_method(rb_cStruct, "length", rb_struct_size, 0);
2269
2270 rb_define_method(rb_cStruct, "each", rb_struct_each, 0);
2271 rb_define_method(rb_cStruct, "each_pair", rb_struct_each_pair, 0);
2272 rb_define_method(rb_cStruct, "[]", rb_struct_aref, 1);
2273 rb_define_method(rb_cStruct, "[]=", rb_struct_aset, 2);
2274 rb_define_method(rb_cStruct, "select", rb_struct_select, -1);
2275 rb_define_method(rb_cStruct, "filter", rb_struct_select, -1);
2276 rb_define_method(rb_cStruct, "values_at", rb_struct_values_at, -1);
2277
2278 rb_define_method(rb_cStruct, "members", rb_struct_members_m, 0);
2279 rb_define_method(rb_cStruct, "dig", rb_struct_dig, -1);
2280
2281 rb_define_method(rb_cStruct, "deconstruct", rb_struct_to_a, 0);
2282 rb_define_method(rb_cStruct, "deconstruct_keys", rb_struct_deconstruct_keys, 1);
2283
2284 rb_cData = rb_define_class("Data", rb_cObject);
2285
2286 rb_undef_method(CLASS_OF(rb_cData), "new");
2287 rb_undef_alloc_func(rb_cData);
2288 rb_define_singleton_method(rb_cData, "define", rb_data_s_def, -1);
2289
2290#if 0 /* for RDoc */
2291 rb_define_singleton_method(rb_cData, "members", rb_data_s_members_m, 0);
2292#endif
2293
2294 rb_define_method(rb_cData, "initialize", rb_data_initialize_m, -1);
2295 rb_define_method(rb_cData, "initialize_copy", rb_data_init_copy, 1);
2296
2297 rb_define_method(rb_cData, "==", rb_data_equal, 1);
2298 rb_define_method(rb_cData, "eql?", rb_data_eql, 1);
2299 rb_define_method(rb_cData, "hash", rb_data_hash, 0);
2300
2301 rb_define_method(rb_cData, "inspect", rb_data_inspect, 0);
2302 rb_define_alias(rb_cData, "to_s", "inspect");
2303 rb_define_method(rb_cData, "to_h", rb_data_to_h, 0);
2304
2305 rb_define_method(rb_cData, "members", rb_data_members_m, 0);
2306
2307 rb_define_method(rb_cData, "deconstruct", rb_data_deconstruct, 0);
2308 rb_define_method(rb_cData, "deconstruct_keys", rb_data_deconstruct_keys, 1);
2309
2310 rb_define_method(rb_cData, "with", rb_data_with, -1);
2311}
2312
2313#undef rb_intern
2314void
2315Init_Struct(void)
2316{
2317 id_members = rb_intern("__members__");
2318 id_back_members = rb_intern("__members_back__");
2319 id_keyword_init = rb_intern("__keyword_init__");
2320
2321 InitVM(Struct);
2322}
RUBY_ASSERT
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
rb_define_method
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
Definition cxxanyargs.hpp:670
rb_define_singleton_method
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
Definition cxxanyargs.hpp:685
RB_OBJ_FREEZE
#define RB_OBJ_FREEZE
Just another name of rb_obj_freeze_inline.
Definition fl_type.h:92
rb_include_module
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1684
rb_define_class
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:1477
rb_class_new
VALUE rb_class_new(VALUE super)
Creates a new, anonymous class.
Definition class.c:852
rb_singleton_class
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:2799
rb_define_class_under
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition class.c:1508
rb_define_class_id_under
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:1547
rb_class_inherited
VALUE rb_class_inherited(VALUE super, VALUE klass)
Calls Class::inherited.
Definition class.c:1468
rb_define_alias
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2842
rb_undef_method
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2654
rb_scan_args
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3132
rb_keyword_given_p
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
Definition eval.c:1034
rb_block_given_p
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1021
rb_get_kwargs
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:2921
rb_str_new2
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1676
FL_UNSET_RAW
#define FL_UNSET_RAW
Old name of RB_FL_UNSET_RAW.
Definition fl_type.h:133
OBJ_INIT_COPY
#define OBJ_INIT_COPY(obj, orig)
Old name of RB_OBJ_INIT_COPY.
Definition object.h:41
T_STRING
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
INT2FIX
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
OBJ_FROZEN
#define OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
Definition fl_type.h:136
rb_str_cat2
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1684
ID2SYM
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
T_STRUCT
#define T_STRUCT
Old name of RUBY_T_STRUCT.
Definition value_type.h:79
OBJ_FREEZE
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:134
UNREACHABLE_RETURN
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
SYM2ID
#define SYM2ID
Old name of RB_SYM2ID.
Definition symbol.h:45
FIX2UINT
#define FIX2UINT
Old name of RB_FIX2UINT.
Definition int.h:42
CLASS_OF
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
rb_ary_new4
#define rb_ary_new4
Old name of rb_ary_new_from_values.
Definition array.h:659
LONG2FIX
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
FIX2INT
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
T_HASH
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
ALLOC_N
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:399
LONG2NUM
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
Qtrue
#define Qtrue
Old name of RUBY_Qtrue.
Definition special_consts.h:61
ST2FIX
#define ST2FIX
Old name of RB_ST2FIX.
Definition st_data_t.h:33
Qnil
#define Qnil
Old name of RUBY_Qnil.
Definition special_consts.h:60
Qfalse
#define Qfalse
Old name of RUBY_Qfalse.
Definition special_consts.h:59
T_ARRAY
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
NIL_P
#define NIL_P
Old name of RB_NIL_P.
Definition special_consts.h:55
FL_WB_PROTECTED
#define FL_WB_PROTECTED
Old name of RUBY_FL_WB_PROTECTED.
Definition fl_type.h:59
T_CLASS
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition value_type.h:58
NUM2LONG
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
FIXNUM_P
#define FIXNUM_P
Old name of RB_FIXNUM_P.
Definition special_consts.h:53
SYMBOL_P
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
rb_exc_raise
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:664
rb_eTypeError
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1431
rb_warn
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:466
rb_eIndexError
VALUE rb_eIndexError
IndexError exception.
Definition error.c:1433
rb_class_superclass
VALUE rb_class_superclass(VALUE klass)
Queries the parent of the given class.
Definition object.c:2264
rb_cArray
VALUE rb_cArray
Array class.
rb_class_new_instance
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
Definition object.c:2249
rb_class_new_instance_kw
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:2237
rb_mEnumerable
VALUE rb_mEnumerable
Enumerable module.
Definition enum.c:27
rb_cStruct
VALUE rb_cStruct
Struct class.
Definition struct.c:33
rb_class_new_instance_pass_kw
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:2226
rb_eql
int rb_eql(VALUE lhs, VALUE rhs)
Checks for equality of the passed objects, in terms of Object#eql?.
Definition object.c:189
rb_obj_class
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:264
rb_inspect
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:686
rb_equal
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:176
rb_obj_is_kind_of
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:923
RGENGC_WB_PROTECTED_STRUCT
#define RGENGC_WB_PROTECTED_STRUCT
This is a compile-time flag to enable/disable write barrier for struct RStruct.
Definition gc.h:468
rb_ary_dup
VALUE rb_ary_dup(VALUE ary)
Duplicates an array.
rb_get_values_at
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.
rb_ary_new
VALUE rb_ary_new(void)
Allocates a new, empty array.
rb_ary_hidden_new
VALUE rb_ary_hidden_new(long capa)
Allocates a hidden (no class) empty array.
rb_ary_push
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
rb_ary_entry
VALUE rb_ary_entry(VALUE ary, long off)
Queries an element of an array.
rb_assoc_new
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
rb_mem_clear
void rb_mem_clear(VALUE *buf, long len)
Fills the memory region with a series of RUBY_Qnil.
rb_ary_join
VALUE rb_ary_join(VALUE ary, VALUE sep)
Recursively stringises the elements of the passed array, flattens that result, then joins the sequenc...
rb_ary_store
void rb_ary_store(VALUE ary, long key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
RETURN_SIZED_ENUMERATOR
#define RETURN_SIZED_ENUMERATOR(obj, argc, argv, size_fn)
This roughly resembles return enum_for(__callee__) unless block_given?.
Definition enumerator.h:208
UNLIMITED_ARGUMENTS
#define UNLIMITED_ARGUMENTS
This macro is used in conjunction with rb_check_arity().
Definition error.h:35
rb_check_arity
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
rb_is_const_id
int rb_is_const_id(ID id)
Classifies the given ID, then sees if it is a constant.
Definition symbol.c:1079
rb_is_local_id
int rb_is_local_id(ID id)
Classifies the given ID, then sees if it is a local variable.
Definition symbol.c:1109
rb_hash_uint
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
Definition string.h:943
rb_hash_end
#define rb_hash_end(h)
Just another name of st_hash_end.
Definition string.h:946
rb_str_append
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:3799
rb_hash_start
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition random.c:1776
rb_str_cat_cstr
#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
rb_struct_define_without_accessor_under
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
rb_struct_define_under
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
rb_struct_new
VALUE rb_struct_new(VALUE klass,...)
Creates an instance of the given struct.
Definition struct.c:877
rb_struct_initialize
VALUE rb_struct_initialize(VALUE self, VALUE values)
Mass-assigns a struct's fields.
Definition struct.c:806
rb_struct_define_without_accessor
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
rb_struct_define
VALUE rb_struct_define(const char *name,...)
Defines a struct class.
Definition struct.c:486
rb_struct_alloc
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:871
rb_data_define
VALUE rb_data_define(VALUE super,...)
Defines an anonymous data class.
Definition struct.c:1740
rb_struct_alloc_noinit
VALUE rb_struct_alloc_noinit(VALUE klass)
Allocates an instance of the given class.
Definition struct.c:406
rb_struct_s_members
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
rb_struct_members
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
rb_struct_getmember
VALUE rb_struct_getmember(VALUE self, ID key)
Identical to rb_struct_aref(), except it takes ID instead of VALUE.
Definition struct.c:233
rb_exec_recursive
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
Definition thread.c:5606
rb_exec_recursive_paired
VALUE rb_exec_recursive_paired(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h)
Identical to rb_exec_recursive(), except it checks for the recursion on the ordered pair of { g,...
Definition thread.c:5617
rb_ivar_set
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:2030
rb_mod_remove_const
VALUE rb_mod_remove_const(VALUE space, VALUE name)
Resembles Module#remove_const.
Definition variable.c:3610
rb_class_name
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition variable.c:500
rb_const_defined_at
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:3843
rb_class_path
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition variable.c:380
rb_alloc_func_t
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
rb_undef_alloc_func
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1711
rb_mod_module_eval
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:2414
rb_define_alloc_func
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
rb_check_symbol
VALUE rb_check_symbol(volatile VALUE *namep)
Identical to rb_check_id(), except it returns an instance of rb_cSymbol instead.
Definition symbol.c:1190
rb_to_symbol
VALUE rb_to_symbol(VALUE name)
Identical to rb_intern_str(), except it generates a dynamic symbol if necessary.
Definition string.c:12674
rb_to_id
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:12664
off
int off
Offset inside of ptr.
Definition io.h:5
len
int len
Length of the buffer.
Definition io.h:8
rb_yield_values
VALUE rb_yield_values(int n,...)
Identical to rb_yield(), except it takes variadic number of parameters and pass them to the block.
Definition vm_eval.c:1395
rb_yield
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1372
rb_long2int
#define rb_long2int
Just another name of rb_long2int_inline.
Definition long.h:62
RB_GC_GUARD
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
ruby::backward::cxxanyargs::rb_hash_foreach
void rb_hash_foreach(VALUE q, int_type *w, VALUE e)
Iteration over the given hash.
Definition cxxanyargs.hpp:482
RARRAY_LEN
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
RARRAY_LENINT
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
Definition rarray.h:281
RARRAY_ASET
static void RARRAY_ASET(VALUE ary, long i, VALUE v)
Assigns an object in an array.
Definition rarray.h:386
RARRAY_PTR
static VALUE * RARRAY_PTR(VALUE ary)
Wild use of a C pointer.
Definition rarray.h:366
RARRAY_AREF
#define RARRAY_AREF(a, i)
Definition rarray.h:403
RARRAY_CONST_PTR
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:52
RBASIC
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
rb_str_to_str
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:1779
rb_struct_aset
VALUE rb_struct_aset(VALUE st, VALUE k, VALUE v)
Resembles Struct#[]=.
Definition struct.c:1296
rb_struct_size
VALUE rb_struct_size(VALUE st)
Returns the number of struct members.
Definition struct.c:1546
rb_struct_aref
VALUE rb_struct_aref(VALUE st, VALUE k)
Resembles Struct#[].
Definition struct.c:1258
InitVM
#define InitVM(ext)
This macro is for internal use.
Definition ruby.h:231
RB_PASS_KEYWORDS
#define RB_PASS_KEYWORDS
Pass keywords, final argument should be a hash of keywords.
Definition scan_args.h:72
RTEST
#define RTEST
This is an old name of RB_TEST.
Definition special_consts.h:51
RStruct
Definition struct.h:33
struct_hash_set_arg
Definition struct.c:716
ID
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
VALUE
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
RB_TYPE_P
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