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