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