Ruby 3.1.3p185 (2022-11-24 revision 1a6b16756e0ba6b95ab71a441357ed5484e33498)
struct.c
1/**********************************************************************
2
3 struct.c -
4
5 $Author$
6 created at: Tue Mar 22 18:44:30 JST 1995
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9
10**********************************************************************/
11
12#include "id.h"
13#include "internal.h"
14#include "internal/class.h"
15#include "internal/error.h"
16#include "internal/hash.h"
17#include "internal/object.h"
18#include "internal/proc.h"
19#include "internal/struct.h"
20#include "internal/symbol.h"
21#include "transient_heap.h"
22#include "vm_core.h"
23#include "builtin.h"
24
25/* only for struct[:field] access */
26enum {
27 AREF_HASH_UNIT = 5,
28 AREF_HASH_THRESHOLD = 10
29};
30
32static ID id_members, id_back_members, id_keyword_init;
33
34static VALUE struct_alloc(VALUE);
35
36static inline VALUE
37struct_ivar_get(VALUE c, ID id)
38{
39 VALUE orig = c;
40 VALUE ivar = rb_attr_get(c, id);
41
42 if (!NIL_P(ivar))
43 return ivar;
44
45 for (;;) {
46 c = RCLASS_SUPER(c);
47 if (c == 0 || c == rb_cStruct)
48 return Qnil;
49 ivar = rb_attr_get(c, id);
50 if (!NIL_P(ivar)) {
51 return rb_ivar_set(orig, id, ivar);
52 }
53 }
54}
55
56VALUE
57rb_struct_s_keyword_init(VALUE klass)
58{
59 return struct_ivar_get(klass, id_keyword_init);
60}
61
62VALUE
64{
65 VALUE members = struct_ivar_get(klass, id_members);
66
67 if (NIL_P(members)) {
68 rb_raise(rb_eTypeError, "uninitialized struct");
69 }
70 if (!RB_TYPE_P(members, T_ARRAY)) {
71 rb_raise(rb_eTypeError, "corrupted struct");
72 }
73 return members;
74}
75
76VALUE
78{
79 VALUE members = rb_struct_s_members(rb_obj_class(s));
80
81 if (RSTRUCT_LEN(s) != RARRAY_LEN(members)) {
82 rb_raise(rb_eTypeError, "struct size differs (%ld required %ld given)",
83 RARRAY_LEN(members), RSTRUCT_LEN(s));
84 }
85 return members;
86}
87
88static long
89struct_member_pos_ideal(VALUE name, long mask)
90{
91 /* (id & (mask/2)) * 2 */
92 return (SYM2ID(name) >> (ID_SCOPE_SHIFT - 1)) & mask;
93}
94
95static long
96struct_member_pos_probe(long prev, long mask)
97{
98 /* (((prev/2) * AREF_HASH_UNIT + 1) & (mask/2)) * 2 */
99 return (prev * AREF_HASH_UNIT + 2) & mask;
100}
101
102static VALUE
103struct_set_members(VALUE klass, VALUE /* frozen hidden array */ members)
104{
105 VALUE back;
106 const long members_length = RARRAY_LEN(members);
107
108 if (members_length <= AREF_HASH_THRESHOLD) {
109 back = members;
110 }
111 else {
112 long i, j, mask = 64;
113 VALUE name;
114
115 while (mask < members_length * AREF_HASH_UNIT) mask *= 2;
116
117 back = rb_ary_tmp_new(mask + 1);
118 rb_ary_store(back, mask, INT2FIX(members_length));
119 mask -= 2; /* mask = (2**k-1)*2 */
120
121 for (i=0; i < members_length; i++) {
122 name = RARRAY_AREF(members, i);
123
124 j = struct_member_pos_ideal(name, mask);
125
126 for (;;) {
127 if (!RTEST(RARRAY_AREF(back, j))) {
128 rb_ary_store(back, j, name);
129 rb_ary_store(back, j + 1, INT2FIX(i));
130 break;
131 }
132 j = struct_member_pos_probe(j, mask);
133 }
134 }
135 OBJ_FREEZE_RAW(back);
136 }
137 rb_ivar_set(klass, id_members, members);
138 rb_ivar_set(klass, id_back_members, back);
139
140 return members;
141}
142
143static inline int
144struct_member_pos(VALUE s, VALUE name)
145{
146 VALUE back = struct_ivar_get(rb_obj_class(s), id_back_members);
147 long j, mask;
148
149 if (UNLIKELY(NIL_P(back))) {
150 rb_raise(rb_eTypeError, "uninitialized struct");
151 }
152 if (UNLIKELY(!RB_TYPE_P(back, T_ARRAY))) {
153 rb_raise(rb_eTypeError, "corrupted struct");
154 }
155
156 mask = RARRAY_LEN(back);
157
158 if (mask <= AREF_HASH_THRESHOLD) {
159 if (UNLIKELY(RSTRUCT_LEN(s) != mask)) {
160 rb_raise(rb_eTypeError,
161 "struct size differs (%ld required %ld given)",
162 mask, RSTRUCT_LEN(s));
163 }
164 for (j = 0; j < mask; j++) {
165 if (RARRAY_AREF(back, j) == name)
166 return (int)j;
167 }
168 return -1;
169 }
170
171 if (UNLIKELY(RSTRUCT_LEN(s) != FIX2INT(RARRAY_AREF(back, mask-1)))) {
172 rb_raise(rb_eTypeError, "struct size differs (%d required %ld given)",
173 FIX2INT(RARRAY_AREF(back, mask-1)), RSTRUCT_LEN(s));
174 }
175
176 mask -= 3;
177 j = struct_member_pos_ideal(name, mask);
178
179 for (;;) {
180 VALUE e = RARRAY_AREF(back, j);
181 if (e == name)
182 return FIX2INT(RARRAY_AREF(back, j + 1));
183 if (!RTEST(e)) {
184 return -1;
185 }
186 j = struct_member_pos_probe(j, mask);
187 }
188}
189
190/*
191 * call-seq:
192 * StructClass::members -> array_of_symbols
193 *
194 * Returns the member names of the Struct descendant as an array:
195 *
196 * Customer = Struct.new(:name, :address, :zip)
197 * Customer.members # => [:name, :address, :zip]
198 *
199 */
200
201static VALUE
202rb_struct_s_members_m(VALUE klass)
203{
204 VALUE members = rb_struct_s_members(klass);
205
206 return rb_ary_dup(members);
207}
208
209/*
210 * call-seq:
211 * members -> array_of_symbols
212 *
213 * Returns the member names from +self+ as an array:
214 *
215 * Customer = Struct.new(:name, :address, :zip)
216 * Customer.new.members # => [:name, :address, :zip]
217 *
218 * Related: #to_a.
219 */
220
221static VALUE
222rb_struct_members_m(VALUE obj)
223{
224 return rb_struct_s_members_m(rb_obj_class(obj));
225}
226
227VALUE
228rb_struct_getmember(VALUE obj, ID id)
229{
230 VALUE slot = ID2SYM(id);
231 int i = struct_member_pos(obj, slot);
232 if (i != -1) {
233 return RSTRUCT_GET(obj, i);
234 }
235 rb_name_err_raise("`%1$s' is not a struct member", obj, ID2SYM(id));
236
238}
239
240static void
241rb_struct_modify(VALUE s)
242{
244}
245
246static VALUE
247anonymous_struct(VALUE klass)
248{
249 VALUE nstr;
250
251 nstr = rb_class_new(klass);
252 rb_make_metaclass(nstr, RBASIC(klass)->klass);
253 rb_class_inherited(klass, nstr);
254 return nstr;
255}
256
257static VALUE
258new_struct(VALUE name, VALUE super)
259{
260 /* old style: should we warn? */
261 ID id;
262 name = rb_str_to_str(name);
263 if (!rb_is_const_name(name)) {
264 rb_name_err_raise("identifier %1$s needs to be constant",
265 super, name);
266 }
267 id = rb_to_id(name);
268 if (rb_const_defined_at(super, id)) {
269 rb_warn("redefining constant %"PRIsVALUE"::%"PRIsVALUE, super, name);
270 rb_mod_remove_const(super, ID2SYM(id));
271 }
272 return rb_define_class_id_under(super, id, super);
273}
274
275NORETURN(static void invalid_struct_pos(VALUE s, VALUE idx));
276
277static void
278define_aref_method(VALUE nstr, VALUE name, VALUE off)
279{
280 rb_add_method_optimized(nstr, SYM2ID(name), OPTIMIZED_METHOD_TYPE_STRUCT_AREF, FIX2UINT(off), METHOD_VISI_PUBLIC);
281}
282
283static void
284define_aset_method(VALUE nstr, VALUE name, VALUE off)
285{
286 rb_add_method_optimized(nstr, SYM2ID(name), OPTIMIZED_METHOD_TYPE_STRUCT_ASET, FIX2UINT(off), METHOD_VISI_PUBLIC);
287}
288
289static VALUE
290rb_struct_s_inspect(VALUE klass)
291{
292 VALUE inspect = rb_class_name(klass);
293 if (RTEST(rb_struct_s_keyword_init(klass))) {
294 rb_str_cat_cstr(inspect, "(keyword_init: true)");
295 }
296 return inspect;
297}
298
299#if 0 /* for RDoc */
300
301/*
302 * call-seq:
303 * StructClass::keyword_init? -> true or falsy value
304 *
305 * Returns +true+ if the class was initialized with <tt>keyword_init: true</tt>.
306 * Otherwise returns +nil+ or +false+.
307 *
308 * Examples:
309 * Foo = Struct.new(:a)
310 * Foo.keyword_init? # => nil
311 * Bar = Struct.new(:a, keyword_init: true)
312 * Bar.keyword_init? # => true
313 * Baz = Struct.new(:a, keyword_init: false)
314 * Baz.keyword_init? # => false
315 */
316static VALUE
317rb_struct_s_keyword_init_p(VALUE obj)
318{
319}
320#endif
321
322#define rb_struct_s_keyword_init_p rb_struct_s_keyword_init
323
324static VALUE
325setup_struct(VALUE nstr, VALUE members)
326{
327 long i, len;
328
329 members = struct_set_members(nstr, members);
330
331 rb_define_alloc_func(nstr, struct_alloc);
332 rb_define_singleton_method(nstr, "new", rb_class_new_instance_pass_kw, -1);
333 rb_define_singleton_method(nstr, "[]", rb_class_new_instance_pass_kw, -1);
334 rb_define_singleton_method(nstr, "members", rb_struct_s_members_m, 0);
335 rb_define_singleton_method(nstr, "inspect", rb_struct_s_inspect, 0);
336 rb_define_singleton_method(nstr, "keyword_init?", rb_struct_s_keyword_init_p, 0);
337
338 len = RARRAY_LEN(members);
339 for (i=0; i< len; i++) {
340 VALUE sym = RARRAY_AREF(members, i);
341 ID id = SYM2ID(sym);
342 VALUE off = LONG2NUM(i);
343
344 define_aref_method(nstr, sym, off);
345 define_aset_method(nstr, ID2SYM(rb_id_attrset(id)), off);
346 }
347
348 return nstr;
349}
350
351VALUE
353{
354 return struct_alloc(klass);
355}
356
357static VALUE
358struct_make_members_list(va_list ar)
359{
360 char *mem;
361 VALUE ary, list = rb_ident_hash_new();
362 st_table *tbl = RHASH_TBL_RAW(list);
363
364 RBASIC_CLEAR_CLASS(list);
365 OBJ_WB_UNPROTECT(list);
366 while ((mem = va_arg(ar, char*)) != 0) {
367 VALUE sym = rb_sym_intern_ascii_cstr(mem);
368 if (st_insert(tbl, sym, Qtrue)) {
369 rb_raise(rb_eArgError, "duplicate member: %s", mem);
370 }
371 }
372 ary = rb_hash_keys(list);
373 st_clear(tbl);
374 RBASIC_CLEAR_CLASS(ary);
375 OBJ_FREEZE_RAW(ary);
376 return ary;
377}
378
379static VALUE
380struct_define_without_accessor(VALUE outer, const char *class_name, VALUE super, rb_alloc_func_t alloc, VALUE members)
381{
382 VALUE klass;
383
384 if (class_name) {
385 if (outer) {
386 klass = rb_define_class_under(outer, class_name, super);
387 }
388 else {
389 klass = rb_define_class(class_name, super);
390 }
391 }
392 else {
393 klass = anonymous_struct(super);
394 }
395
396 struct_set_members(klass, members);
397
398 if (alloc) {
399 rb_define_alloc_func(klass, alloc);
400 }
401 else {
402 rb_define_alloc_func(klass, struct_alloc);
403 }
404
405 return klass;
406}
407
408VALUE
409rb_struct_define_without_accessor_under(VALUE outer, const char *class_name, VALUE super, rb_alloc_func_t alloc, ...)
410{
411 va_list ar;
412 VALUE members;
413
414 va_start(ar, alloc);
415 members = struct_make_members_list(ar);
416 va_end(ar);
417
418 return struct_define_without_accessor(outer, class_name, super, alloc, members);
419}
420
421VALUE
422rb_struct_define_without_accessor(const char *class_name, VALUE super, rb_alloc_func_t alloc, ...)
423{
424 va_list ar;
425 VALUE members;
426
427 va_start(ar, alloc);
428 members = struct_make_members_list(ar);
429 va_end(ar);
430
431 return struct_define_without_accessor(0, class_name, super, alloc, members);
432}
433
434VALUE
435rb_struct_define(const char *name, ...)
436{
437 va_list ar;
438 VALUE st, ary;
439
440 va_start(ar, name);
441 ary = struct_make_members_list(ar);
442 va_end(ar);
443
444 if (!name) st = anonymous_struct(rb_cStruct);
445 else st = new_struct(rb_str_new2(name), rb_cStruct);
446 return setup_struct(st, ary);
447}
448
449VALUE
450rb_struct_define_under(VALUE outer, const char *name, ...)
451{
452 va_list ar;
453 VALUE ary;
454
455 va_start(ar, name);
456 ary = struct_make_members_list(ar);
457 va_end(ar);
458
459 return setup_struct(rb_define_class_under(outer, name, rb_cStruct), ary);
460}
461
462/*
463 * call-seq:
464 * Struct.new(*member_names, keyword_init: false){|Struct_subclass| ... } -> Struct_subclass
465 * Struct.new(class_name, *member_names, keyword_init: false){|Struct_subclass| ... } -> Struct_subclass
466 * Struct_subclass.new(*member_names) -> Struct_subclass_instance
467 * Struct_subclass.new(**member_names) -> Struct_subclass_instance
468 *
469 * <tt>Struct.new</tt> returns a new subclass of +Struct+. The new subclass:
470 *
471 * - May be anonymous, or may have the name given by +class_name+.
472 * - May have members as given by +member_names+.
473 * - May have initialization via ordinary arguments (the default)
474 * or via keyword arguments (if <tt>keyword_init: true</tt> is given).
475 *
476 * The new subclass has its own method <tt>::new</tt>; thus:
477 *
478 * Foo = Struct.new('Foo', :foo, :bar) # => Struct::Foo
479 * f = Foo.new(0, 1) # => #<struct Struct::Foo foo=0, bar=1>
480 *
481 * <b>\Class Name</b>
482 *
483 * With string argument +class_name+,
484 * returns a new subclass of +Struct+ named <tt>Struct::<em>class_name</em></tt>:
485 *
486 * Foo = Struct.new('Foo', :foo, :bar) # => Struct::Foo
487 * Foo.name # => "Struct::Foo"
488 * Foo.superclass # => Struct
489 *
490 * Without string argument +class_name+,
491 * returns a new anonymous subclass of +Struct+:
492 *
493 * Struct.new(:foo, :bar).name # => nil
494 *
495 * <b>Block</b>
496 *
497 * With a block given, the created subclass is yielded to the block:
498 *
499 * Customer = Struct.new('Customer', :name, :address) do |new_class|
500 * p "The new subclass is #{new_class}"
501 * def greeting
502 * "Hello #{name} at #{address}"
503 * end
504 * end # => Struct::Customer
505 * dave = Customer.new('Dave', '123 Main')
506 * dave # => #<struct Struct::Customer name="Dave", address="123 Main">
507 * dave.greeting # => "Hello Dave at 123 Main"
508 *
509 * Output, from <tt>Struct.new</tt>:
510 *
511 * "The new subclass is Struct::Customer"
512 *
513 * <b>Member Names</b>
514 *
515 * \Symbol arguments +member_names+
516 * determines the members of the new subclass:
517 *
518 * Struct.new(:foo, :bar).members # => [:foo, :bar]
519 * Struct.new('Foo', :foo, :bar).members # => [:foo, :bar]
520 *
521 * The new subclass has instance methods corresponding to +member_names+:
522 *
523 * Foo = Struct.new('Foo', :foo, :bar)
524 * Foo.instance_methods(false) # => [:foo, :bar, :foo=, :bar=]
525 * f = Foo.new # => #<struct Struct::Foo foo=nil, bar=nil>
526 * f.foo # => nil
527 * f.foo = 0 # => 0
528 * f.bar # => nil
529 * f.bar = 1 # => 1
530 * f # => #<struct Struct::Foo foo=0, bar=1>
531 *
532 * <b>Singleton Methods</b>
533 *
534 * A subclass returned by Struct.new has these singleton methods:
535 *
536 * - \Method <tt>::new </tt> creates an instance of the subclass:
537 *
538 * Foo.new # => #<struct Struct::Foo foo=nil, bar=nil>
539 * Foo.new(0) # => #<struct Struct::Foo foo=0, bar=nil>
540 * Foo.new(0, 1) # => #<struct Struct::Foo foo=0, bar=1>
541 * Foo.new(0, 1, 2) # Raises ArgumentError: struct size differs
542 *
543 * \Method <tt>::[]</tt> is an alias for method <tt>::new</tt>.
544 *
545 * - \Method <tt>:inspect</tt> returns a string representation of the subclass:
546 *
547 * Foo.inspect
548 * # => "Struct::Foo"
549 *
550 * - \Method <tt>::members</tt> returns an array of the member names:
551 *
552 * Foo.members # => [:foo, :bar]
553 *
554 * <b>Keyword Argument</b>
555 *
556 * By default, the arguments for initializing an instance of the new subclass
557 * are ordinary arguments (not keyword arguments).
558 * With optional keyword argument <tt>keyword_init: true</tt>,
559 * the new subclass is initialized with keyword arguments:
560 *
561 * # Without keyword_init: true.
562 * Foo = Struct.new('Foo', :foo, :bar)
563 * Foo # => Struct::Foo
564 * Foo.new(0, 1) # => #<struct Struct::Foo foo=0, bar=1>
565 * # With keyword_init: true.
566 * Bar = Struct.new(:foo, :bar, keyword_init: true)
567 * Bar # => # => Bar(keyword_init: true)
568 * Bar.new(bar: 1, foo: 0) # => #<struct Bar foo=0, bar=1>
569 *
570 */
571
572static VALUE
573rb_struct_s_def(int argc, VALUE *argv, VALUE klass)
574{
575 VALUE name, rest, keyword_init = Qnil;
576 long i;
577 VALUE st;
578 st_table *tbl;
579
581 name = argv[0];
582 if (SYMBOL_P(name)) {
583 name = Qnil;
584 }
585 else {
586 --argc;
587 ++argv;
588 }
589
590 if (RB_TYPE_P(argv[argc-1], T_HASH)) {
591 static ID keyword_ids[1];
592
593 if (!keyword_ids[0]) {
594 keyword_ids[0] = rb_intern("keyword_init");
595 }
596 rb_get_kwargs(argv[argc-1], keyword_ids, 0, 1, &keyword_init);
597 if (keyword_init == Qundef) {
598 keyword_init = Qnil;
599 }
600 else if (RTEST(keyword_init)) {
601 keyword_init = Qtrue;
602 }
603 --argc;
604 }
605
606 rest = rb_ident_hash_new();
607 RBASIC_CLEAR_CLASS(rest);
608 OBJ_WB_UNPROTECT(rest);
609 tbl = RHASH_TBL_RAW(rest);
610 for (i=0; i<argc; i++) {
611 VALUE mem = rb_to_symbol(argv[i]);
612 if (rb_is_attrset_sym(mem)) {
613 rb_raise(rb_eArgError, "invalid struct member: %"PRIsVALUE, mem);
614 }
615 if (st_insert(tbl, mem, Qtrue)) {
616 rb_raise(rb_eArgError, "duplicate member: %"PRIsVALUE, mem);
617 }
618 }
619 rest = rb_hash_keys(rest);
620 st_clear(tbl);
621 RBASIC_CLEAR_CLASS(rest);
622 OBJ_FREEZE_RAW(rest);
623 if (NIL_P(name)) {
624 st = anonymous_struct(klass);
625 }
626 else {
627 st = new_struct(name, klass);
628 }
629 setup_struct(st, rest);
630 rb_ivar_set(st, id_keyword_init, keyword_init);
631 if (rb_block_given_p()) {
632 rb_mod_module_eval(0, 0, st);
633 }
634
635 return st;
636}
637
638static long
639num_members(VALUE klass)
640{
641 VALUE members;
642 members = struct_ivar_get(klass, id_members);
643 if (!RB_TYPE_P(members, T_ARRAY)) {
644 rb_raise(rb_eTypeError, "broken members");
645 }
646 return RARRAY_LEN(members);
647}
648
649/*
650 */
651
653 VALUE self;
654 VALUE unknown_keywords;
655};
656
657static int rb_struct_pos(VALUE s, VALUE *name);
658
659static int
660struct_hash_set_i(VALUE key, VALUE val, VALUE arg)
661{
662 struct struct_hash_set_arg *args = (struct struct_hash_set_arg *)arg;
663 int i = rb_struct_pos(args->self, &key);
664 if (i < 0) {
665 if (NIL_P(args->unknown_keywords)) {
666 args->unknown_keywords = rb_ary_new();
667 }
668 rb_ary_push(args->unknown_keywords, key);
669 }
670 else {
671 rb_struct_modify(args->self);
672 RSTRUCT_SET(args->self, i, val);
673 }
674 return ST_CONTINUE;
675}
676
677static VALUE
678rb_struct_initialize_m(int argc, const VALUE *argv, VALUE self)
679{
680 VALUE klass = rb_obj_class(self);
681 rb_struct_modify(self);
682 long n = num_members(klass);
683 if (argc == 0) {
684 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self), n);
685 return Qnil;
686 }
687
688 VALUE keyword_init = rb_struct_s_keyword_init(klass);
689 if (RTEST(keyword_init)) {
690 struct struct_hash_set_arg arg;
691 if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) {
692 rb_raise(rb_eArgError, "wrong number of arguments (given %d, expected 0)", argc);
693 }
694 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self), n);
695 arg.self = self;
696 arg.unknown_keywords = Qnil;
697 rb_hash_foreach(argv[0], struct_hash_set_i, (VALUE)&arg);
698 if (arg.unknown_keywords != Qnil) {
699 rb_raise(rb_eArgError, "unknown keywords: %s",
700 RSTRING_PTR(rb_ary_join(arg.unknown_keywords, rb_str_new2(", "))));
701 }
702 }
703 else {
704 if (n < argc) {
705 rb_raise(rb_eArgError, "struct size differs");
706 }
707 if (NIL_P(keyword_init) && argc == 1 && RB_TYPE_P(argv[0], T_HASH) && rb_keyword_given_p()) {
708 rb_warn("Passing only keyword arguments to Struct#initialize will behave differently from Ruby 3.2. "\
709 "Please use a Hash literal like .new({k: v}) instead of .new(k: v).");
710 }
711 for (long i=0; i<argc; i++) {
712 RSTRUCT_SET(self, i, argv[i]);
713 }
714 if (n > argc) {
715 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self)+argc, n-argc);
716 }
717 }
718 return Qnil;
719}
720
721VALUE
722rb_struct_initialize(VALUE self, VALUE values)
723{
724 rb_struct_initialize_m(RARRAY_LENINT(values), RARRAY_CONST_PTR(values), self);
725 RB_GC_GUARD(values);
726 return Qnil;
727}
728
729static VALUE *
730struct_heap_alloc(VALUE st, size_t len)
731{
732 VALUE *ptr = rb_transient_heap_alloc((VALUE)st, sizeof(VALUE) * len);
733
734 if (ptr) {
735 RSTRUCT_TRANSIENT_SET(st);
736 return ptr;
737 }
738 else {
739 RSTRUCT_TRANSIENT_UNSET(st);
740 return ALLOC_N(VALUE, len);
741 }
742}
743
744#if USE_TRANSIENT_HEAP
745void
746rb_struct_transient_heap_evacuate(VALUE obj, int promote)
747{
748 if (RSTRUCT_TRANSIENT_P(obj)) {
749 const VALUE *old_ptr = rb_struct_const_heap_ptr(obj);
750 VALUE *new_ptr;
751 long len = RSTRUCT_LEN(obj);
752
753 if (promote) {
754 new_ptr = ALLOC_N(VALUE, len);
755 FL_UNSET_RAW(obj, RSTRUCT_TRANSIENT_FLAG);
756 }
757 else {
758 new_ptr = struct_heap_alloc(obj, len);
759 }
760 MEMCPY(new_ptr, old_ptr, VALUE, len);
761 RSTRUCT(obj)->as.heap.ptr = new_ptr;
762 }
763}
764#endif
765
766static VALUE
767struct_alloc(VALUE klass)
768{
769 long n;
771
772 n = num_members(klass);
773
774 if (0 < n && n <= RSTRUCT_EMBED_LEN_MAX) {
775 RBASIC(st)->flags &= ~RSTRUCT_EMBED_LEN_MASK;
776 RBASIC(st)->flags |= n << RSTRUCT_EMBED_LEN_SHIFT;
777 rb_mem_clear((VALUE *)st->as.ary, n);
778 }
779 else {
780 st->as.heap.ptr = struct_heap_alloc((VALUE)st, n);
781 rb_mem_clear((VALUE *)st->as.heap.ptr, n);
782 st->as.heap.len = n;
783 }
784
785 return (VALUE)st;
786}
787
788VALUE
789rb_struct_alloc(VALUE klass, VALUE values)
790{
791 return rb_class_new_instance(RARRAY_LENINT(values), RARRAY_CONST_PTR(values), klass);
792}
793
794VALUE
795rb_struct_new(VALUE klass, ...)
796{
797 VALUE tmpargs[16], *mem = tmpargs;
798 int size, i;
799 va_list args;
800
801 size = rb_long2int(num_members(klass));
802 if (size > numberof(tmpargs)) {
803 tmpargs[0] = rb_ary_tmp_new(size);
804 mem = RARRAY_PTR(tmpargs[0]);
805 }
806 va_start(args, klass);
807 for (i=0; i<size; i++) {
808 mem[i] = va_arg(args, VALUE);
809 }
810 va_end(args);
811
812 return rb_class_new_instance(size, mem, klass);
813}
814
815static VALUE
816struct_enum_size(VALUE s, VALUE args, VALUE eobj)
817{
818 return rb_struct_size(s);
819}
820
821/*
822 * call-seq:
823 * each {|value| ... } -> self
824 * each -> enumerator
825 *
826 * Calls the given block with the value of each member; returns +self+:
827 *
828 * Customer = Struct.new(:name, :address, :zip)
829 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
830 * joe.each {|value| p value }
831 *
832 * Output:
833 *
834 * "Joe Smith"
835 * "123 Maple, Anytown NC"
836 * 12345
837 *
838 * Returns an Enumerator if no block is given.
839 *
840 * Related: #each_pair.
841 */
842
843static VALUE
844rb_struct_each(VALUE s)
845{
846 long i;
847
848 RETURN_SIZED_ENUMERATOR(s, 0, 0, struct_enum_size);
849 for (i=0; i<RSTRUCT_LEN(s); i++) {
850 rb_yield(RSTRUCT_GET(s, i));
851 }
852 return s;
853}
854
855/*
856 * call-seq:
857 * each_pair {|(name, value)| ... } -> self
858 * each_pair -> enumerator
859 *
860 * Calls the given block with each member name/value pair; returns +self+:
861 *
862 * Customer = Struct.new(:name, :address, :zip) # => Customer
863 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
864 * joe.each_pair {|(name, value)| p "#{name} => #{value}" }
865 *
866 * Output:
867 *
868 * "name => Joe Smith"
869 * "address => 123 Maple, Anytown NC"
870 * "zip => 12345"
871 *
872 * Returns an Enumerator if no block is given.
873 *
874 * Related: #each.
875 *
876 */
877
878static VALUE
879rb_struct_each_pair(VALUE s)
880{
881 VALUE members;
882 long i;
883
884 RETURN_SIZED_ENUMERATOR(s, 0, 0, struct_enum_size);
885 members = rb_struct_members(s);
886 if (rb_block_pair_yield_optimizable()) {
887 for (i=0; i<RSTRUCT_LEN(s); i++) {
888 VALUE key = rb_ary_entry(members, i);
889 VALUE value = RSTRUCT_GET(s, i);
890 rb_yield_values(2, key, value);
891 }
892 }
893 else {
894 for (i=0; i<RSTRUCT_LEN(s); i++) {
895 VALUE key = rb_ary_entry(members, i);
896 VALUE value = RSTRUCT_GET(s, i);
897 rb_yield(rb_assoc_new(key, value));
898 }
899 }
900 return s;
901}
902
903static VALUE
904inspect_struct(VALUE s, VALUE dummy, int recur)
905{
906 VALUE cname = rb_class_path(rb_obj_class(s));
907 VALUE members, str = rb_str_new2("#<struct ");
908 long i, len;
909 char first = RSTRING_PTR(cname)[0];
910
911 if (recur || first != '#') {
912 rb_str_append(str, cname);
913 }
914 if (recur) {
915 return rb_str_cat2(str, ":...>");
916 }
917
918 members = rb_struct_members(s);
919 len = RSTRUCT_LEN(s);
920
921 for (i=0; i<len; i++) {
922 VALUE slot;
923 ID id;
924
925 if (i > 0) {
926 rb_str_cat2(str, ", ");
927 }
928 else if (first != '#') {
929 rb_str_cat2(str, " ");
930 }
931 slot = RARRAY_AREF(members, i);
932 id = SYM2ID(slot);
933 if (rb_is_local_id(id) || rb_is_const_id(id)) {
934 rb_str_append(str, rb_id2str(id));
935 }
936 else {
937 rb_str_append(str, rb_inspect(slot));
938 }
939 rb_str_cat2(str, "=");
940 rb_str_append(str, rb_inspect(RSTRUCT_GET(s, i)));
941 }
942 rb_str_cat2(str, ">");
943
944 return str;
945}
946
947/*
948 * call-seq:
949 * inspect -> string
950 *
951 * Returns a string representation of +self+:
952 *
953 * Customer = Struct.new(:name, :address, :zip) # => Customer
954 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
955 * joe.inspect # => "#<struct Customer name=\"Joe Smith\", address=\"123 Maple, Anytown NC\", zip=12345>"
956 *
957 * Struct#to_s is an alias for Struct#inspect.
958 *
959 */
960
961static VALUE
962rb_struct_inspect(VALUE s)
963{
964 return rb_exec_recursive(inspect_struct, s, 0);
965}
966
967/*
968 * call-seq:
969 * to_a -> array
970 *
971 * Returns the values in +self+ as an array:
972 *
973 * Customer = Struct.new(:name, :address, :zip)
974 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
975 * joe.to_a # => ["Joe Smith", "123 Maple, Anytown NC", 12345]
976 *
977 * Struct#values and Struct#deconstruct are aliases for Struct#to_a.
978 *
979 * Related: #members.
980 */
981
982static VALUE
983rb_struct_to_a(VALUE s)
984{
985 return rb_ary_new4(RSTRUCT_LEN(s), RSTRUCT_CONST_PTR(s));
986}
987
988/*
989 * call-seq:
990 * to_h -> hash
991 * to_h {|name, value| ... } -> hash
992 *
993 * Returns a hash containing the name and value for each member:
994 *
995 * Customer = Struct.new(:name, :address, :zip)
996 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
997 * h = joe.to_h
998 * h # => {:name=>"Joe Smith", :address=>"123 Maple, Anytown NC", :zip=>12345}
999 *
1000 * If a block is given, it is called with each name/value pair;
1001 * the block should return a 2-element array whose elements will become
1002 * a key/value pair in the returned hash:
1003 *
1004 * h = joe.to_h{|name, value| [name.upcase, value.to_s.upcase]}
1005 * h # => {:NAME=>"JOE SMITH", :ADDRESS=>"123 MAPLE, ANYTOWN NC", :ZIP=>"12345"}
1006 *
1007 * Raises ArgumentError if the block returns an inappropriate value.
1008 *
1009 */
1010
1011static VALUE
1012rb_struct_to_h(VALUE s)
1013{
1014 VALUE h = rb_hash_new_with_size(RSTRUCT_LEN(s));
1015 VALUE members = rb_struct_members(s);
1016 long i;
1017 int block_given = rb_block_given_p();
1018
1019 for (i=0; i<RSTRUCT_LEN(s); i++) {
1020 VALUE k = rb_ary_entry(members, i), v = RSTRUCT_GET(s, i);
1021 if (block_given)
1022 rb_hash_set_pair(h, rb_yield_values(2, k, v));
1023 else
1024 rb_hash_aset(h, k, v);
1025 }
1026 return h;
1027}
1028
1029/*
1030 * call-seq:
1031 * deconstruct_keys(array_of_names) -> hash
1032 *
1033 * Returns a hash of the name/value pairs for the given member names.
1034 *
1035 * Customer = Struct.new(:name, :address, :zip)
1036 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1037 * h = joe.deconstruct_keys([:zip, :address])
1038 * h # => {:zip=>12345, :address=>"123 Maple, Anytown NC"}
1039 *
1040 * Returns all names and values if +array_of_names+ is +nil+:
1041 *
1042 * h = joe.deconstruct_keys(nil)
1043 * h # => {:name=>"Joseph Smith, Jr.", :address=>"123 Maple, Anytown NC", :zip=>12345}
1044 *
1045 */
1046static VALUE
1047rb_struct_deconstruct_keys(VALUE s, VALUE keys)
1048{
1049 VALUE h;
1050 long i;
1051
1052 if (NIL_P(keys)) {
1053 return rb_struct_to_h(s);
1054 }
1055 if (UNLIKELY(!RB_TYPE_P(keys, T_ARRAY))) {
1056 rb_raise(rb_eTypeError,
1057 "wrong argument type %"PRIsVALUE" (expected Array or nil)",
1058 rb_obj_class(keys));
1059
1060 }
1061 if (RSTRUCT_LEN(s) < RARRAY_LEN(keys)) {
1062 return rb_hash_new_with_size(0);
1063 }
1064 h = rb_hash_new_with_size(RARRAY_LEN(keys));
1065 for (i=0; i<RARRAY_LEN(keys); i++) {
1066 VALUE key = RARRAY_AREF(keys, i);
1067 int i = rb_struct_pos(s, &key);
1068 if (i < 0) {
1069 return h;
1070 }
1071 rb_hash_aset(h, key, RSTRUCT_GET(s, i));
1072 }
1073 return h;
1074}
1075
1076/* :nodoc: */
1077VALUE
1078rb_struct_init_copy(VALUE copy, VALUE s)
1079{
1080 long i, len;
1081
1082 if (!OBJ_INIT_COPY(copy, s)) return copy;
1083 if (RSTRUCT_LEN(copy) != RSTRUCT_LEN(s)) {
1084 rb_raise(rb_eTypeError, "struct size mismatch");
1085 }
1086
1087 for (i=0, len=RSTRUCT_LEN(copy); i<len; i++) {
1088 RSTRUCT_SET(copy, i, RSTRUCT_GET(s, i));
1089 }
1090
1091 return copy;
1092}
1093
1094static int
1095rb_struct_pos(VALUE s, VALUE *name)
1096{
1097 long i;
1098 VALUE idx = *name;
1099
1100 if (SYMBOL_P(idx)) {
1101 return struct_member_pos(s, idx);
1102 }
1103 else if (RB_TYPE_P(idx, T_STRING)) {
1104 idx = rb_check_symbol(name);
1105 if (NIL_P(idx)) return -1;
1106 return struct_member_pos(s, idx);
1107 }
1108 else {
1109 long len;
1110 i = NUM2LONG(idx);
1111 len = RSTRUCT_LEN(s);
1112 if (i < 0) {
1113 if (i + len < 0) {
1114 *name = LONG2FIX(i);
1115 return -1;
1116 }
1117 i += len;
1118 }
1119 else if (len <= i) {
1120 *name = LONG2FIX(i);
1121 return -1;
1122 }
1123 return (int)i;
1124 }
1125}
1126
1127static void
1128invalid_struct_pos(VALUE s, VALUE idx)
1129{
1130 if (FIXNUM_P(idx)) {
1131 long i = FIX2INT(idx), len = RSTRUCT_LEN(s);
1132 if (i < 0) {
1133 rb_raise(rb_eIndexError, "offset %ld too small for struct(size:%ld)",
1134 i, len);
1135 }
1136 else {
1137 rb_raise(rb_eIndexError, "offset %ld too large for struct(size:%ld)",
1138 i, len);
1139 }
1140 }
1141 else {
1142 rb_name_err_raise("no member '%1$s' in struct", s, idx);
1143 }
1144}
1145
1146/*
1147 * call-seq:
1148 * struct[name] -> object
1149 * struct[n] -> object
1150 *
1151 * Returns a value from +self+.
1152 *
1153 * With symbol or string argument +name+ given, returns the value for the named member:
1154 *
1155 * Customer = Struct.new(:name, :address, :zip)
1156 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1157 * joe[:zip] # => 12345
1158 *
1159 * Raises NameError if +name+ is not the name of a member.
1160 *
1161 * With integer argument +n+ given, returns <tt>self.values[n]</tt>
1162 * if +n+ is in range;
1163 * see {Array Indexes}[Array.html#class-Array-label-Array+Indexes]:
1164 *
1165 * joe[2] # => 12345
1166 * joe[-2] # => "123 Maple, Anytown NC"
1167 *
1168 * Raises IndexError if +n+ is out of range.
1169 *
1170 */
1171
1172VALUE
1173rb_struct_aref(VALUE s, VALUE idx)
1174{
1175 int i = rb_struct_pos(s, &idx);
1176 if (i < 0) invalid_struct_pos(s, idx);
1177 return RSTRUCT_GET(s, i);
1178}
1179
1180/*
1181 * call-seq:
1182 * struct[name] = value -> value
1183 * struct[n] = value -> value
1184 *
1185 * Assigns a value to a member.
1186 *
1187 * With symbol or string argument +name+ given, assigns the given +value+
1188 * to the named member; returns +value+:
1189 *
1190 * Customer = Struct.new(:name, :address, :zip)
1191 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1192 * joe[:zip] = 54321 # => 54321
1193 * joe # => #<struct Customer name="Joe Smith", address="123 Maple, Anytown NC", zip=54321>
1194 *
1195 * Raises NameError if +name+ is not the name of a member.
1196 *
1197 * With integer argument +n+ given, assigns the given +value+
1198 * to the +n+-th member if +n+ is in range;
1199 * see {Array Indexes}[Array.html#class-Array-label-Array+Indexes]:
1200 *
1201 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1202 * joe[2] = 54321 # => 54321
1203 * joe[-3] = 'Joseph Smith' # => "Joseph Smith"
1204 * joe # => #<struct Customer name="Joseph Smith", address="123 Maple, Anytown NC", zip=54321>
1205 *
1206 * Raises IndexError if +n+ is out of range.
1207 *
1208 */
1209
1210VALUE
1211rb_struct_aset(VALUE s, VALUE idx, VALUE val)
1212{
1213 int i = rb_struct_pos(s, &idx);
1214 if (i < 0) invalid_struct_pos(s, idx);
1215 rb_struct_modify(s);
1216 RSTRUCT_SET(s, i, val);
1217 return val;
1218}
1219
1220FUNC_MINIMIZED(VALUE rb_struct_lookup(VALUE s, VALUE idx));
1221NOINLINE(static VALUE rb_struct_lookup_default(VALUE s, VALUE idx, VALUE notfound));
1222
1223VALUE
1224rb_struct_lookup(VALUE s, VALUE idx)
1225{
1226 return rb_struct_lookup_default(s, idx, Qnil);
1227}
1228
1229static VALUE
1230rb_struct_lookup_default(VALUE s, VALUE idx, VALUE notfound)
1231{
1232 int i = rb_struct_pos(s, &idx);
1233 if (i < 0) return notfound;
1234 return RSTRUCT_GET(s, i);
1235}
1236
1237static VALUE
1238struct_entry(VALUE s, long n)
1239{
1240 return rb_struct_aref(s, LONG2NUM(n));
1241}
1242
1243/*
1244 * call-seq:
1245 * values_at(*integers) -> array
1246 * values_at(integer_range) -> array
1247 *
1248 * Returns an array of values from +self+.
1249 *
1250 * With integer arguments +integers+ given,
1251 * returns an array containing each value given by one of +integers+:
1252 *
1253 * Customer = Struct.new(:name, :address, :zip)
1254 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1255 * joe.values_at(0, 2) # => ["Joe Smith", 12345]
1256 * joe.values_at(2, 0) # => [12345, "Joe Smith"]
1257 * joe.values_at(2, 1, 0) # => [12345, "123 Maple, Anytown NC", "Joe Smith"]
1258 * joe.values_at(0, -3) # => ["Joe Smith", "Joe Smith"]
1259 *
1260 * Raises IndexError if any of +integers+ is out of range;
1261 * see {Array Indexes}[Array.html#class-Array-label-Array+Indexes].
1262 *
1263 * With integer range argument +integer_range+ given,
1264 * returns an array containing each value given by the elements of the range;
1265 * fills with +nil+ values for range elements larger than the structure:
1266 *
1267 * joe.values_at(0..2)
1268 * # => ["Joe Smith", "123 Maple, Anytown NC", 12345]
1269 * joe.values_at(-3..-1)
1270 * # => ["Joe Smith", "123 Maple, Anytown NC", 12345]
1271 * joe.values_at(1..4) # => ["123 Maple, Anytown NC", 12345, nil, nil]
1272 *
1273 * Raises RangeError if any element of the range is negative and out of range;
1274 * see {Array Indexes}[Array.html#class-Array-label-Array+Indexes].
1275 *
1276 */
1277
1278static VALUE
1279rb_struct_values_at(int argc, VALUE *argv, VALUE s)
1280{
1281 return rb_get_values_at(s, RSTRUCT_LEN(s), argc, argv, struct_entry);
1282}
1283
1284/*
1285 * call-seq:
1286 * select {|value| ... } -> array
1287 * select -> enumerator
1288 *
1289 * With a block given, returns an array of values from +self+
1290 * for which the block returns a truthy value:
1291 *
1292 * Customer = Struct.new(:name, :address, :zip)
1293 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1294 * a = joe.select {|value| value.is_a?(String) }
1295 * a # => ["Joe Smith", "123 Maple, Anytown NC"]
1296 * a = joe.select {|value| value.is_a?(Integer) }
1297 * a # => [12345]
1298 *
1299 * With no block given, returns an Enumerator.
1300 *
1301 * Struct#filter is an alias for Struct#select.
1302 */
1303
1304static VALUE
1305rb_struct_select(int argc, VALUE *argv, VALUE s)
1306{
1307 VALUE result;
1308 long i;
1309
1310 rb_check_arity(argc, 0, 0);
1311 RETURN_SIZED_ENUMERATOR(s, 0, 0, struct_enum_size);
1312 result = rb_ary_new();
1313 for (i = 0; i < RSTRUCT_LEN(s); i++) {
1314 if (RTEST(rb_yield(RSTRUCT_GET(s, i)))) {
1315 rb_ary_push(result, RSTRUCT_GET(s, i));
1316 }
1317 }
1318
1319 return result;
1320}
1321
1322static VALUE
1323recursive_equal(VALUE s, VALUE s2, int recur)
1324{
1325 long i, len;
1326
1327 if (recur) return Qtrue; /* Subtle! */
1328 len = RSTRUCT_LEN(s);
1329 for (i=0; i<len; i++) {
1330 if (!rb_equal(RSTRUCT_GET(s, i), RSTRUCT_GET(s2, i))) return Qfalse;
1331 }
1332 return Qtrue;
1333}
1334
1335
1336/*
1337 * call-seq:
1338 * self == other -> true or false
1339 *
1340 * Returns +true+ if and only if the following are true; otherwise returns +false+:
1341 *
1342 * - <tt>other.class == self.class</tt>.
1343 * - For each member name +name+, <tt>other.name == self.name</tt>.
1344 *
1345 * Examples:
1346 *
1347 * Customer = Struct.new(:name, :address, :zip)
1348 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1349 * joe_jr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1350 * joe_jr == joe # => true
1351 * joe_jr[:name] = 'Joe Smith, Jr.'
1352 * # => "Joe Smith, Jr."
1353 * joe_jr == joe # => false
1354 */
1355
1356static VALUE
1357rb_struct_equal(VALUE s, VALUE s2)
1358{
1359 if (s == s2) return Qtrue;
1360 if (!RB_TYPE_P(s2, T_STRUCT)) return Qfalse;
1361 if (rb_obj_class(s) != rb_obj_class(s2)) return Qfalse;
1362 if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) {
1363 rb_bug("inconsistent struct"); /* should never happen */
1364 }
1365
1366 return rb_exec_recursive_paired(recursive_equal, s, s2, s2);
1367}
1368
1369/*
1370 * call-seq:
1371 * hash -> integer
1372 *
1373 * Returns the integer hash value for +self+.
1374 *
1375 * Two structs of the same class and with the same content
1376 * will have the same hash code (and will compare using Struct#eql?):
1377 *
1378 * Customer = Struct.new(:name, :address, :zip)
1379 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1380 * joe_jr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1381 * joe.hash == joe_jr.hash # => true
1382 * joe_jr[:name] = 'Joe Smith, Jr.'
1383 * joe.hash == joe_jr.hash # => false
1384 *
1385 * Related: Object#hash.
1386 */
1387
1388static VALUE
1389rb_struct_hash(VALUE s)
1390{
1391 long i, len;
1392 st_index_t h;
1393 VALUE n;
1394
1395 h = rb_hash_start(rb_hash(rb_obj_class(s)));
1396 len = RSTRUCT_LEN(s);
1397 for (i = 0; i < len; i++) {
1398 n = rb_hash(RSTRUCT_GET(s, i));
1399 h = rb_hash_uint(h, NUM2LONG(n));
1400 }
1401 h = rb_hash_end(h);
1402 return ST2FIX(h);
1403}
1404
1405static VALUE
1406recursive_eql(VALUE s, VALUE s2, int recur)
1407{
1408 long i, len;
1409
1410 if (recur) return Qtrue; /* Subtle! */
1411 len = RSTRUCT_LEN(s);
1412 for (i=0; i<len; i++) {
1413 if (!rb_eql(RSTRUCT_GET(s, i), RSTRUCT_GET(s2, i))) return Qfalse;
1414 }
1415 return Qtrue;
1416}
1417
1418/*
1419 * call-seq:
1420 * eql?(other) -> true or false
1421 *
1422 * Returns +true+ if and only if the following are true; otherwise returns +false+:
1423 *
1424 * - <tt>other.class == self.class</tt>.
1425 * - For each member name +name+, <tt>other.name.eql?(self.name)</tt>.
1426 *
1427 * Customer = Struct.new(:name, :address, :zip)
1428 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1429 * joe_jr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1430 * joe_jr.eql?(joe) # => true
1431 * joe_jr[:name] = 'Joe Smith, Jr.'
1432 * joe_jr.eql?(joe) # => false
1433 *
1434 * Related: Object#==.
1435 */
1436
1437static VALUE
1438rb_struct_eql(VALUE s, VALUE s2)
1439{
1440 if (s == s2) return Qtrue;
1441 if (!RB_TYPE_P(s2, T_STRUCT)) return Qfalse;
1442 if (rb_obj_class(s) != rb_obj_class(s2)) return Qfalse;
1443 if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) {
1444 rb_bug("inconsistent struct"); /* should never happen */
1445 }
1446
1447 return rb_exec_recursive_paired(recursive_eql, s, s2, s2);
1448}
1449
1450/*
1451 * call-seq:
1452 * size -> integer
1453 *
1454 * Returns the number of members.
1455 *
1456 * Customer = Struct.new(:name, :address, :zip)
1457 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1458 * joe.size #=> 3
1459 *
1460 * Struct#length is an alias for Struct#size.
1461 */
1462
1463VALUE
1465{
1466 return LONG2FIX(RSTRUCT_LEN(s));
1467}
1468
1469/*
1470 * call-seq:
1471 * dig(name, *identifiers) -> object
1472 * dig(n, *identifiers) -> object
1473 *
1474 * Finds and returns an object among nested objects.
1475 * The nested objects may be instances of various classes.
1476 * See {Dig Methods}[rdoc-ref:dig_methods.rdoc].
1477 *
1478 *
1479 * Given symbol or string argument +name+,
1480 * returns the object that is specified by +name+ and +identifiers+:
1481 *
1482 * Foo = Struct.new(:a)
1483 * f = Foo.new(Foo.new({b: [1, 2, 3]}))
1484 * f.dig(:a) # => #<struct Foo a={:b=>[1, 2, 3]}>
1485 * f.dig(:a, :a) # => {:b=>[1, 2, 3]}
1486 * f.dig(:a, :a, :b) # => [1, 2, 3]
1487 * f.dig(:a, :a, :b, 0) # => 1
1488 * f.dig(:b, 0) # => nil
1489 *
1490 * Given integer argument +n+,
1491 * returns the object that is specified by +n+ and +identifiers+:
1492 *
1493 * f.dig(0) # => #<struct Foo a={:b=>[1, 2, 3]}>
1494 * f.dig(0, 0) # => {:b=>[1, 2, 3]}
1495 * f.dig(0, 0, :b) # => [1, 2, 3]
1496 * f.dig(0, 0, :b, 0) # => 1
1497 * f.dig(:b, 0) # => nil
1498 *
1499 */
1500
1501static VALUE
1502rb_struct_dig(int argc, VALUE *argv, VALUE self)
1503{
1505 self = rb_struct_lookup(self, *argv);
1506 if (!--argc) return self;
1507 ++argv;
1508 return rb_obj_dig(argc, argv, self, Qnil);
1509}
1510
1511/*
1512 * Document-class: Struct
1513 *
1514 * \Class \Struct provides a convenient way to create a simple class
1515 * that can store and fetch values.
1516 *
1517 * This example creates a subclass of +Struct+, <tt>Struct::Customer</tt>;
1518 * the first argument, a string, is the name of the subclass;
1519 * the other arguments, symbols, determine the _members_ of the new subclass.
1520 *
1521 * Customer = Struct.new('Customer', :name, :address, :zip)
1522 * Customer.name # => "Struct::Customer"
1523 * Customer.class # => Class
1524 * Customer.superclass # => Struct
1525 *
1526 * Corresponding to each member are two methods, a writer and a reader,
1527 * that store and fetch values:
1528 *
1529 * methods = Customer.instance_methods false
1530 * methods # => [:zip, :address=, :zip=, :address, :name, :name=]
1531 *
1532 * An instance of the subclass may be created,
1533 * and its members assigned values, via method <tt>::new</tt>:
1534 *
1535 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1536 * joe # => #<struct Struct::Customer name="Joe Smith", address="123 Maple, Anytown NC", zip=12345>
1537 *
1538 * The member values may be managed thus:
1539 *
1540 * joe.name # => "Joe Smith"
1541 * joe.name = 'Joseph Smith'
1542 * joe.name # => "Joseph Smith"
1543 *
1544 * And thus; note that member name may be expressed as either a string or a symbol:
1545 *
1546 * joe[:name] # => "Joseph Smith"
1547 * joe[:name] = 'Joseph Smith, Jr.'
1548 * joe['name'] # => "Joseph Smith, Jr."
1549 *
1550 * See Struct::new.
1551 *
1552 * == What's Here
1553 *
1554 * First, what's elsewhere. \Class \Struct:
1555 *
1556 * - Inherits from {class Object}[Object.html#class-Object-label-What-27s+Here].
1557 * - Includes {module Enumerable}[Enumerable.html#module-Enumerable-label-What-27s+Here],
1558 * which provides dozens of additional methods.
1559 *
1560 * Here, class \Struct provides methods that are useful for:
1561 *
1562 * - {Creating a Struct Subclass}[#class-Struct-label-Methods+for+Creating+a+Struct+Subclass]
1563 * - {Querying}[#class-Struct-label-Methods+for+Querying]
1564 * - {Comparing}[#class-Struct-label-Methods+for+Comparing]
1565 * - {Fetching}[#class-Struct-label-Methods+for+Fetching]
1566 * - {Assigning}[#class-Struct-label-Methods+for+Assigning]
1567 * - {Iterating}[#class-Struct-label-Methods+for+Iterating]
1568 * - {Converting}[#class-Struct-label-Methods+for+Converting]
1569 *
1570 * === Methods for Creating a Struct Subclass
1571 *
1572 * ::new:: Returns a new subclass of \Struct.
1573 *
1574 * === Methods for Querying
1575 *
1576 * #hash:: Returns the integer hash code.
1577 * #length, #size:: Returns the number of members.
1578 *
1579 * === Methods for Comparing
1580 *
1581 * {#==}[#method-i-3D-3D]:: Returns whether a given object is equal to +self+,
1582 * using <tt>==</tt> to compare member values.
1583 * #eql?:: Returns whether a given object is equal to +self+,
1584 * using <tt>eql?</tt> to compare member values.
1585 *
1586 * === Methods for Fetching
1587 *
1588 * #[]:: Returns the value associated with a given member name.
1589 * #to_a, #values, #deconstruct:: Returns the member values in +self+ as an array.
1590 * #deconstruct_keys:: Returns a hash of the name/value pairs
1591 * for given member names.
1592 * #dig:: Returns the object in nested objects that is specified
1593 * by a given member name and additional arguments.
1594 * #members:: Returns an array of the member names.
1595 * #select, #filter:: Returns an array of member values from +self+,
1596 * as selected by the given block.
1597 * #values_at:: Returns an array containing values for given member names.
1598 *
1599 * === Methods for Assigning
1600 *
1601 * #[]=:: Assigns a given value to a given member name.
1602 *
1603 * === Methods for Iterating
1604 *
1605 * #each:: Calls a given block with each member name.
1606 * #each_pair:: Calls a given block with each member name/value pair.
1607 *
1608 * === Methods for Converting
1609 *
1610 * #inspect, #to_s:: Returns a string representation of +self+.
1611 * #to_h:: Returns a hash of the member name/value pairs in +self+.
1612 *
1613 */
1614void
1615InitVM_Struct(void)
1616{
1617 rb_cStruct = rb_define_class("Struct", rb_cObject);
1619
1621 rb_define_singleton_method(rb_cStruct, "new", rb_struct_s_def, -1);
1622#if 0 /* for RDoc */
1623 rb_define_singleton_method(rb_cStruct, "keyword_init?", rb_struct_s_keyword_init_p, 0);
1624 rb_define_singleton_method(rb_cStruct, "members", rb_struct_s_members_m, 0);
1625#endif
1626
1627 rb_define_method(rb_cStruct, "initialize", rb_struct_initialize_m, -1);
1628 rb_define_method(rb_cStruct, "initialize_copy", rb_struct_init_copy, 1);
1629
1630 rb_define_method(rb_cStruct, "==", rb_struct_equal, 1);
1631 rb_define_method(rb_cStruct, "eql?", rb_struct_eql, 1);
1632 rb_define_method(rb_cStruct, "hash", rb_struct_hash, 0);
1633
1634 rb_define_method(rb_cStruct, "inspect", rb_struct_inspect, 0);
1635 rb_define_alias(rb_cStruct, "to_s", "inspect");
1636 rb_define_method(rb_cStruct, "to_a", rb_struct_to_a, 0);
1637 rb_define_method(rb_cStruct, "to_h", rb_struct_to_h, 0);
1638 rb_define_method(rb_cStruct, "values", rb_struct_to_a, 0);
1641
1642 rb_define_method(rb_cStruct, "each", rb_struct_each, 0);
1643 rb_define_method(rb_cStruct, "each_pair", rb_struct_each_pair, 0);
1646 rb_define_method(rb_cStruct, "select", rb_struct_select, -1);
1647 rb_define_method(rb_cStruct, "filter", rb_struct_select, -1);
1648 rb_define_method(rb_cStruct, "values_at", rb_struct_values_at, -1);
1649
1650 rb_define_method(rb_cStruct, "members", rb_struct_members_m, 0);
1651 rb_define_method(rb_cStruct, "dig", rb_struct_dig, -1);
1652
1653 rb_define_method(rb_cStruct, "deconstruct", rb_struct_to_a, 0);
1654 rb_define_method(rb_cStruct, "deconstruct_keys", rb_struct_deconstruct_keys, 1);
1655}
1656
1657#undef rb_intern
1658void
1659Init_Struct(void)
1660{
1661 id_members = rb_intern("__members__");
1662 id_back_members = rb_intern("__members_back__");
1663 id_keyword_init = rb_intern("__keyword_init__");
1664
1665 InitVM(Struct);
1666}
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
Definition: cxxanyargs.hpp:685
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition: class.c:1043
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition: class.c:837
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition: class.c:869
VALUE rb_class_inherited(VALUE, VALUE)
Calls Class::inherited.
Definition: class.c:828
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition: class.c:2116
void rb_define_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a method.
Definition: class.c:1914
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
Definition: eval.c:863
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition: eval.c:850
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition: class.c:2195
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition: string.h:1738
#define NEWOBJ_OF
Old name of RB_NEWOBJ_OF.
Definition: newobj.h:61
#define FL_UNSET_RAW
Old name of RB_FL_UNSET_RAW.
Definition: fl_type.h:142
#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 Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition: long.h:48
#define ID2SYM
Old name of RB_ID2SYM.
Definition: symbol.h:44
#define T_STRUCT
Old name of RUBY_T_STRUCT.
Definition: value_type.h:79
#define OBJ_FREEZE_RAW
Old name of RB_OBJ_FREEZE_RAW.
Definition: fl_type.h:144
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition: assume.h:31
#define SYM2ID
Old name of RB_SYM2ID.
Definition: symbol.h:45
#define FIX2UINT
Old name of RB_FIX2UINT.
Definition: int.h:42
#define rb_ary_new4
Old name of rb_ary_new_from_values.
Definition: array.h:653
#define LONG2FIX
Old name of RB_INT2FIX.
Definition: long.h:49
#define FIX2INT
Old name of RB_FIX2INT.
Definition: int.h:41
#define T_HASH
Old name of RUBY_T_HASH.
Definition: value_type.h:65
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition: memory.h:393
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition: long.h:50
#define Qtrue
Old name of RUBY_Qtrue.
#define ST2FIX
Old name of RB_ST2FIX.
Definition: st_data_t.h:33
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition: value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define FL_WB_PROTECTED
Old name of RUBY_FL_WB_PROTECTED.
Definition: fl_type.h:59
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition: long.h:51
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define OBJ_WB_UNPROTECT
Old name of RB_OBJ_WB_UNPROTECT.
Definition: rgengc.h:238
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition: value_type.h:88
void rb_raise(VALUE exc, const char *fmt,...)
Exception entry point.
Definition: error.c:3021
void rb_bug(const char *fmt,...)
Interpreter panic switch.
Definition: error.c:802
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports always regardless of runtime -W flag.
Definition: error.c:418
VALUE rb_mEnumerable
Enumerable module.
Definition: enum.c:27
VALUE rb_cStruct
Struct class.
Definition: struct.c:31
Defines RBIMPL_HAS_BUILTIN.
VALUE rb_ary_dup(VALUE ary)
Duplicates an array.
Definition: array.c:2663
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.
Definition: array.c:750
VALUE rb_ary_tmp_new(long capa)
Allocates a "temporary" array.
Definition: array.c:847
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
Definition: array.c:1308
VALUE rb_ary_entry(VALUE ary, long off)
Queries an element of an array.
Definition: array.c:1679
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
Definition: array.c:976
void rb_mem_clear(VALUE *buf, long len)
Fills the memory region with a series of RUBY_Qnil.
Definition: array.c:260
VALUE rb_ary_join(VALUE ary, VALUE sep)
Recursively stringises the elements of the passed array, flattens that result, then joins the sequenc...
Definition: array.c:2777
void rb_ary_store(VALUE ary, long key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
Definition: array.c:1148
#define RETURN_SIZED_ENUMERATOR(obj, argc, argv, size_fn)
This roughly resembles return enum_for(__callee__) unless block_given?.
Definition: enumerator.h:206
#define UNLIMITED_ARGUMENTS
This macro is used in conjunction with rb_check_arity().
Definition: error.h:35
#define rb_check_frozen
Just another name of rb_check_frozen.
Definition: error.h:278
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition: error.h:294
void rb_hash_foreach(VALUE hash, int(*func)(VALUE key, VALUE val, VALUE arg), VALUE arg)
Iterates over a hash.
VALUE rb_hash_aset(VALUE hash, VALUE key, VALUE val)
Inserts or replaces ("upsert"s) the objects into the given hash table.
Definition: hash.c:2903
VALUE rb_hash(VALUE obj)
Calculates a message authentication code of the passed object.
Definition: hash.c:227
int rb_is_const_id(ID id)
Classifies the given ID, then sees if it is a constant.
Definition: symbol.c:1012
ID rb_id_attrset(ID id)
Calculates an ID of attribute writer.
Definition: symbol.c:113
int rb_is_local_id(ID id)
Classifies the given ID, then sees if it is a local variable.
Definition: symbol.c:1042
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
Definition: string.h:973
#define rb_hash_end(h)
Just another name of st_hash_end.
Definition: string.h:976
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:3317
VALUE rb_str_cat2(VALUE, const char *)
Just another name of rb_str_cat_cstr.
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition: random.c:1714
VALUE rb_str_cat_cstr(VALUE dst, const char *src)
Identical to rb_str_cat(), except it assumes the passed pointer is a pointer to a C string.
Definition: string.c:3171
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:409
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:450
VALUE rb_struct_new(VALUE klass,...)
Creates an instance of the given struct.
Definition: struct.c:795
VALUE rb_struct_initialize(VALUE self, VALUE values)
Mass-assigns a struct's fields.
Definition: struct.c:722
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:422
VALUE rb_struct_define(const char *name,...)
Defines a struct class.
Definition: struct.c:435
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:789
VALUE rb_struct_alloc_noinit(VALUE klass)
Allocates an instance of the given class.
Definition: struct.c:352
VALUE rb_struct_s_members(VALUE klass)
Queries the list of the names of the fields of the given struct class.
Definition: struct.c:63
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:77
VALUE rb_struct_getmember(VALUE self, ID key)
Identical to rb_struct_aref(), except it takes ID instead of VALUE.
Definition: struct.c:228
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_attr_get(VALUE obj, ID name)
Identical to rb_ivar_get()
Definition: variable.c:1293
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:1575
VALUE rb_mod_remove_const(VALUE space, VALUE name)
Resembles Module#remove_const.
Definition: variable.c:2825
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition: variable.c:294
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:3043
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition: variable.c:172
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:1117
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:2138
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:1099
ID rb_intern(const char *name)
Finds or creates a symbol of the given name.
Definition: symbol.c:782
VALUE rb_to_symbol(VALUE name)
Identical to rb_intern_str(), except it generates a dynamic symbol if necessary.
Definition: string.c:11902
ID rb_to_id(VALUE str)
Identical to rb_intern(), except it takes an instance of rb_cString.
Definition: string.c:11892
VALUE rb_id2str(ID id)
Identical to rb_id2name(), except it returns a Ruby's String instead of C's.
Definition: symbol.c:935
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:1369
VALUE rb_yield(VALUE val)
Yields the block.
Definition: vm_eval.c:1357
#define rb_long2int
Just another name of rb_long2int_inline.
Definition: long.h:62
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition: memory.h:366
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition: memory.h:161
#define RARRAY_LEN
Just another name of rb_array_len.
Definition: rarray.h:68
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
Definition: rarray.h:324
static VALUE * RARRAY_PTR(VALUE ary)
Wild use of a C pointer.
Definition: rarray.h:551
#define RARRAY_AREF(a, i)
Definition: rarray.h:588
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition: rarray.h:69
#define RBASIC(obj)
Convenient casting macro.
Definition: rbasic.h:40
#define RCLASS_SUPER
Just another name of rb_class_get_superclass.
Definition: rclass.h:46
#define RGENGC_WB_PROTECTED_STRUCT
This is a compile-time flag to enable/disable write barrier for struct RStruct.
Definition: rgengc.h:96
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:1584
static char * RSTRING_PTR(VALUE str)
Queries the contents pointer of the string.
Definition: rstring.h:497
static long RSTRUCT_LEN(VALUE st)
Returns the number of struct members.
Definition: rstruct.h:94
static VALUE RSTRUCT_SET(VALUE st, int k, VALUE v)
Resembles Struct#[]=.
Definition: rstruct.h:104
static VALUE RSTRUCT_GET(VALUE st, int k)
Resembles Struct#[].
Definition: rstruct.h:114
VALUE rb_struct_aset(VALUE st, VALUE k, VALUE v)
Resembles Struct#[]=.
Definition: struct.c:1211
VALUE rb_struct_size(VALUE st)
Returns the number of struct members.
Definition: struct.c:1464
VALUE rb_struct_aref(VALUE st, VALUE k)
Resembles Struct#[].
Definition: struct.c:1173
#define InitVM(ext)
This macro is for internal use.
Definition: ruby.h:229
#define RTEST
This is an old name of RB_TEST.
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:375