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