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