c47d8d086bf619a6c14ffe82d6547f664e85d132
[ruby.git] / struct.c
blobc47d8d086bf619a6c14ffe82d6547f664e85d132
1 /**********************************************************************
3 struct.c -
5 $Author$
6 created at: Tue Mar 22 18:44:30 JST 1995
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
10 **********************************************************************/
12 #include "id.h"
13 #include "internal.h"
14 #include "internal/class.h"
15 #include "internal/error.h"
16 #include "internal/hash.h"
17 #include "internal/object.h"
18 #include "internal/proc.h"
19 #include "internal/struct.h"
20 #include "internal/symbol.h"
21 #include "vm_core.h"
22 #include "builtin.h"
24 /* only for struct[:field] access */
25 enum {
26 AREF_HASH_UNIT = 5,
27 AREF_HASH_THRESHOLD = 10
30 /* Note: Data is a stricter version of the Struct: no attr writers & no
31 hash-alike/array-alike behavior. It shares most of the implementation
32 on the C level, but is unrelated on the Ruby level. */
33 VALUE rb_cStruct;
34 static VALUE rb_cData;
35 static ID id_members, id_back_members, id_keyword_init;
37 static VALUE struct_alloc(VALUE);
39 static inline VALUE
40 struct_ivar_get(VALUE c, ID id)
42 VALUE orig = c;
43 VALUE ivar = rb_attr_get(c, id);
45 if (!NIL_P(ivar))
46 return ivar;
48 for (;;) {
49 c = rb_class_superclass(c);
50 if (c == rb_cStruct || c == rb_cData || !RTEST(c))
51 return Qnil;
52 RUBY_ASSERT(RB_TYPE_P(c, T_CLASS));
53 ivar = rb_attr_get(c, id);
54 if (!NIL_P(ivar)) {
55 return rb_ivar_set(orig, id, ivar);
60 VALUE
61 rb_struct_s_keyword_init(VALUE klass)
63 return struct_ivar_get(klass, id_keyword_init);
66 VALUE
67 rb_struct_s_members(VALUE klass)
69 VALUE members = struct_ivar_get(klass, id_members);
71 if (NIL_P(members)) {
72 rb_raise(rb_eTypeError, "uninitialized struct");
74 if (!RB_TYPE_P(members, T_ARRAY)) {
75 rb_raise(rb_eTypeError, "corrupted struct");
77 return members;
80 VALUE
81 rb_struct_members(VALUE s)
83 VALUE members = rb_struct_s_members(rb_obj_class(s));
85 if (RSTRUCT_LEN(s) != RARRAY_LEN(members)) {
86 rb_raise(rb_eTypeError, "struct size differs (%ld required %ld given)",
87 RARRAY_LEN(members), RSTRUCT_LEN(s));
89 return members;
92 static long
93 struct_member_pos_ideal(VALUE name, long mask)
95 /* (id & (mask/2)) * 2 */
96 return (SYM2ID(name) >> (ID_SCOPE_SHIFT - 1)) & mask;
99 static long
100 struct_member_pos_probe(long prev, long mask)
102 /* (((prev/2) * AREF_HASH_UNIT + 1) & (mask/2)) * 2 */
103 return (prev * AREF_HASH_UNIT + 2) & mask;
106 static VALUE
107 struct_set_members(VALUE klass, VALUE /* frozen hidden array */ members)
109 VALUE back;
110 const long members_length = RARRAY_LEN(members);
112 if (members_length <= AREF_HASH_THRESHOLD) {
113 back = members;
115 else {
116 long i, j, mask = 64;
117 VALUE name;
119 while (mask < members_length * AREF_HASH_UNIT) mask *= 2;
121 back = rb_ary_hidden_new(mask + 1);
122 rb_ary_store(back, mask, INT2FIX(members_length));
123 mask -= 2; /* mask = (2**k-1)*2 */
125 for (i=0; i < members_length; i++) {
126 name = RARRAY_AREF(members, i);
128 j = struct_member_pos_ideal(name, mask);
130 for (;;) {
131 if (!RTEST(RARRAY_AREF(back, j))) {
132 rb_ary_store(back, j, name);
133 rb_ary_store(back, j + 1, INT2FIX(i));
134 break;
136 j = struct_member_pos_probe(j, mask);
139 OBJ_FREEZE_RAW(back);
141 rb_ivar_set(klass, id_members, members);
142 rb_ivar_set(klass, id_back_members, back);
144 return members;
147 static inline int
148 struct_member_pos(VALUE s, VALUE name)
150 VALUE back = struct_ivar_get(rb_obj_class(s), id_back_members);
151 long j, mask;
153 if (UNLIKELY(NIL_P(back))) {
154 rb_raise(rb_eTypeError, "uninitialized struct");
156 if (UNLIKELY(!RB_TYPE_P(back, T_ARRAY))) {
157 rb_raise(rb_eTypeError, "corrupted struct");
160 mask = RARRAY_LEN(back);
162 if (mask <= AREF_HASH_THRESHOLD) {
163 if (UNLIKELY(RSTRUCT_LEN(s) != mask)) {
164 rb_raise(rb_eTypeError,
165 "struct size differs (%ld required %ld given)",
166 mask, RSTRUCT_LEN(s));
168 for (j = 0; j < mask; j++) {
169 if (RARRAY_AREF(back, j) == name)
170 return (int)j;
172 return -1;
175 if (UNLIKELY(RSTRUCT_LEN(s) != FIX2INT(RARRAY_AREF(back, mask-1)))) {
176 rb_raise(rb_eTypeError, "struct size differs (%d required %ld given)",
177 FIX2INT(RARRAY_AREF(back, mask-1)), RSTRUCT_LEN(s));
180 mask -= 3;
181 j = struct_member_pos_ideal(name, mask);
183 for (;;) {
184 VALUE e = RARRAY_AREF(back, j);
185 if (e == name)
186 return FIX2INT(RARRAY_AREF(back, j + 1));
187 if (!RTEST(e)) {
188 return -1;
190 j = struct_member_pos_probe(j, mask);
195 * call-seq:
196 * StructClass::members -> array_of_symbols
198 * Returns the member names of the Struct descendant as an array:
200 * Customer = Struct.new(:name, :address, :zip)
201 * Customer.members # => [:name, :address, :zip]
205 static VALUE
206 rb_struct_s_members_m(VALUE klass)
208 VALUE members = rb_struct_s_members(klass);
210 return rb_ary_dup(members);
214 * call-seq:
215 * members -> array_of_symbols
217 * Returns the member names from +self+ as an array:
219 * Customer = Struct.new(:name, :address, :zip)
220 * Customer.new.members # => [:name, :address, :zip]
222 * Related: #to_a.
225 static VALUE
226 rb_struct_members_m(VALUE obj)
228 return rb_struct_s_members_m(rb_obj_class(obj));
231 VALUE
232 rb_struct_getmember(VALUE obj, ID id)
234 VALUE slot = ID2SYM(id);
235 int i = struct_member_pos(obj, slot);
236 if (i != -1) {
237 return RSTRUCT_GET(obj, i);
239 rb_name_err_raise("`%1$s' is not a struct member", obj, ID2SYM(id));
241 UNREACHABLE_RETURN(Qnil);
244 static void
245 rb_struct_modify(VALUE s)
247 rb_check_frozen(s);
250 static VALUE
251 anonymous_struct(VALUE klass)
253 VALUE nstr;
255 nstr = rb_class_new(klass);
256 rb_make_metaclass(nstr, RBASIC(klass)->klass);
257 rb_class_inherited(klass, nstr);
258 return nstr;
261 static VALUE
262 new_struct(VALUE name, VALUE super)
264 /* old style: should we warn? */
265 ID id;
266 name = rb_str_to_str(name);
267 if (!rb_is_const_name(name)) {
268 rb_name_err_raise("identifier %1$s needs to be constant",
269 super, name);
271 id = rb_to_id(name);
272 if (rb_const_defined_at(super, id)) {
273 rb_warn("redefining constant %"PRIsVALUE"::%"PRIsVALUE, super, name);
274 rb_mod_remove_const(super, ID2SYM(id));
276 return rb_define_class_id_under(super, id, super);
279 NORETURN(static void invalid_struct_pos(VALUE s, VALUE idx));
281 static void
282 define_aref_method(VALUE nstr, VALUE name, VALUE off)
284 rb_add_method_optimized(nstr, SYM2ID(name), OPTIMIZED_METHOD_TYPE_STRUCT_AREF, FIX2UINT(off), METHOD_VISI_PUBLIC);
287 static void
288 define_aset_method(VALUE nstr, VALUE name, VALUE off)
290 rb_add_method_optimized(nstr, SYM2ID(name), OPTIMIZED_METHOD_TYPE_STRUCT_ASET, FIX2UINT(off), METHOD_VISI_PUBLIC);
293 static VALUE
294 rb_struct_s_inspect(VALUE klass)
296 VALUE inspect = rb_class_name(klass);
297 if (RTEST(rb_struct_s_keyword_init(klass))) {
298 rb_str_cat_cstr(inspect, "(keyword_init: true)");
300 return inspect;
303 static VALUE
304 rb_data_s_new(int argc, const VALUE *argv, VALUE klass)
306 if (rb_keyword_given_p()) {
307 if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) {
308 rb_error_arity(argc, 0, 0);
310 return rb_class_new_instance_pass_kw(argc, argv, klass);
312 else {
313 VALUE members = struct_ivar_get(klass, id_members);
314 int num_members = RARRAY_LENINT(members);
316 rb_check_arity(argc, 0, num_members);
317 VALUE arg_hash = rb_hash_new_with_size(argc);
318 for (long i=0; i<argc; i++) {
319 VALUE k = rb_ary_entry(members, i), v = argv[i];
320 rb_hash_aset(arg_hash, k, v);
322 return rb_class_new_instance_kw(1, &arg_hash, klass, RB_PASS_KEYWORDS);
326 #if 0 /* for RDoc */
329 * call-seq:
330 * StructClass::keyword_init? -> true or falsy value
332 * Returns +true+ if the class was initialized with <tt>keyword_init: true</tt>.
333 * Otherwise returns +nil+ or +false+.
335 * Examples:
336 * Foo = Struct.new(:a)
337 * Foo.keyword_init? # => nil
338 * Bar = Struct.new(:a, keyword_init: true)
339 * Bar.keyword_init? # => true
340 * Baz = Struct.new(:a, keyword_init: false)
341 * Baz.keyword_init? # => false
343 static VALUE
344 rb_struct_s_keyword_init_p(VALUE obj)
347 #endif
349 #define rb_struct_s_keyword_init_p rb_struct_s_keyword_init
351 static VALUE
352 setup_struct(VALUE nstr, VALUE members)
354 long i, len;
356 members = struct_set_members(nstr, members);
358 rb_define_alloc_func(nstr, struct_alloc);
359 rb_define_singleton_method(nstr, "new", rb_class_new_instance_pass_kw, -1);
360 rb_define_singleton_method(nstr, "[]", rb_class_new_instance_pass_kw, -1);
361 rb_define_singleton_method(nstr, "members", rb_struct_s_members_m, 0);
362 rb_define_singleton_method(nstr, "inspect", rb_struct_s_inspect, 0);
363 rb_define_singleton_method(nstr, "keyword_init?", rb_struct_s_keyword_init_p, 0);
365 len = RARRAY_LEN(members);
366 for (i=0; i< len; i++) {
367 VALUE sym = RARRAY_AREF(members, i);
368 ID id = SYM2ID(sym);
369 VALUE off = LONG2NUM(i);
371 define_aref_method(nstr, sym, off);
372 define_aset_method(nstr, ID2SYM(rb_id_attrset(id)), off);
375 return nstr;
378 static VALUE
379 setup_data(VALUE subclass, VALUE members)
381 long i, len;
383 members = struct_set_members(subclass, members);
385 rb_define_alloc_func(subclass, struct_alloc);
386 VALUE sclass = rb_singleton_class(subclass);
387 rb_undef_method(sclass, "define");
388 rb_define_method(sclass, "new", rb_data_s_new, -1);
389 rb_define_method(sclass, "[]", rb_data_s_new, -1);
390 rb_define_method(sclass, "members", rb_struct_s_members_m, 0);
391 rb_define_method(sclass, "inspect", rb_struct_s_inspect, 0); // FIXME: just a separate method?..
393 len = RARRAY_LEN(members);
394 for (i=0; i< len; i++) {
395 VALUE sym = RARRAY_AREF(members, i);
396 VALUE off = LONG2NUM(i);
398 define_aref_method(subclass, sym, off);
401 return subclass;
404 VALUE
405 rb_struct_alloc_noinit(VALUE klass)
407 return struct_alloc(klass);
410 static VALUE
411 struct_make_members_list(va_list ar)
413 char *mem;
414 VALUE ary, list = rb_ident_hash_new();
415 RBASIC_CLEAR_CLASS(list);
416 while ((mem = va_arg(ar, char*)) != 0) {
417 VALUE sym = rb_sym_intern_ascii_cstr(mem);
418 if (RTEST(rb_hash_has_key(list, sym))) {
419 rb_raise(rb_eArgError, "duplicate member: %s", mem);
421 rb_hash_aset(list, sym, Qtrue);
423 ary = rb_hash_keys(list);
424 RBASIC_CLEAR_CLASS(ary);
425 OBJ_FREEZE_RAW(ary);
426 return ary;
429 static VALUE
430 struct_define_without_accessor(VALUE outer, const char *class_name, VALUE super, rb_alloc_func_t alloc, VALUE members)
432 VALUE klass;
434 if (class_name) {
435 if (outer) {
436 klass = rb_define_class_under(outer, class_name, super);
438 else {
439 klass = rb_define_class(class_name, super);
442 else {
443 klass = anonymous_struct(super);
446 struct_set_members(klass, members);
448 if (alloc) {
449 rb_define_alloc_func(klass, alloc);
451 else {
452 rb_define_alloc_func(klass, struct_alloc);
455 return klass;
458 VALUE
459 rb_struct_define_without_accessor_under(VALUE outer, const char *class_name, VALUE super, rb_alloc_func_t alloc, ...)
461 va_list ar;
462 VALUE members;
464 va_start(ar, alloc);
465 members = struct_make_members_list(ar);
466 va_end(ar);
468 return struct_define_without_accessor(outer, class_name, super, alloc, members);
471 VALUE
472 rb_struct_define_without_accessor(const char *class_name, VALUE super, rb_alloc_func_t alloc, ...)
474 va_list ar;
475 VALUE members;
477 va_start(ar, alloc);
478 members = struct_make_members_list(ar);
479 va_end(ar);
481 return struct_define_without_accessor(0, class_name, super, alloc, members);
484 VALUE
485 rb_struct_define(const char *name, ...)
487 va_list ar;
488 VALUE st, ary;
490 va_start(ar, name);
491 ary = struct_make_members_list(ar);
492 va_end(ar);
494 if (!name) st = anonymous_struct(rb_cStruct);
495 else st = new_struct(rb_str_new2(name), rb_cStruct);
496 return setup_struct(st, ary);
499 VALUE
500 rb_struct_define_under(VALUE outer, const char *name, ...)
502 va_list ar;
503 VALUE ary;
505 va_start(ar, name);
506 ary = struct_make_members_list(ar);
507 va_end(ar);
509 return setup_struct(rb_define_class_under(outer, name, rb_cStruct), ary);
513 * call-seq:
514 * Struct.new(*member_names, keyword_init: nil){|Struct_subclass| ... } -> Struct_subclass
515 * Struct.new(class_name, *member_names, keyword_init: nil){|Struct_subclass| ... } -> Struct_subclass
516 * Struct_subclass.new(*member_names) -> Struct_subclass_instance
517 * Struct_subclass.new(**member_names) -> Struct_subclass_instance
519 * <tt>Struct.new</tt> returns a new subclass of +Struct+. The new subclass:
521 * - May be anonymous, or may have the name given by +class_name+.
522 * - May have members as given by +member_names+.
523 * - May have initialization via ordinary arguments, or via keyword arguments
525 * The new subclass has its own method <tt>::new</tt>; thus:
527 * Foo = Struct.new('Foo', :foo, :bar) # => Struct::Foo
528 * f = Foo.new(0, 1) # => #<struct Struct::Foo foo=0, bar=1>
530 * <b>\Class Name</b>
532 * With string argument +class_name+,
533 * returns a new subclass of +Struct+ named <tt>Struct::<em>class_name</em></tt>:
535 * Foo = Struct.new('Foo', :foo, :bar) # => Struct::Foo
536 * Foo.name # => "Struct::Foo"
537 * Foo.superclass # => Struct
539 * Without string argument +class_name+,
540 * returns a new anonymous subclass of +Struct+:
542 * Struct.new(:foo, :bar).name # => nil
544 * <b>Block</b>
546 * With a block given, the created subclass is yielded to the block:
548 * Customer = Struct.new('Customer', :name, :address) do |new_class|
549 * p "The new subclass is #{new_class}"
550 * def greeting
551 * "Hello #{name} at #{address}"
552 * end
553 * end # => Struct::Customer
554 * dave = Customer.new('Dave', '123 Main')
555 * dave # => #<struct Struct::Customer name="Dave", address="123 Main">
556 * dave.greeting # => "Hello Dave at 123 Main"
558 * Output, from <tt>Struct.new</tt>:
560 * "The new subclass is Struct::Customer"
562 * <b>Member Names</b>
564 * \Symbol arguments +member_names+
565 * determines the members of the new subclass:
567 * Struct.new(:foo, :bar).members # => [:foo, :bar]
568 * Struct.new('Foo', :foo, :bar).members # => [:foo, :bar]
570 * The new subclass has instance methods corresponding to +member_names+:
572 * Foo = Struct.new('Foo', :foo, :bar)
573 * Foo.instance_methods(false) # => [:foo, :bar, :foo=, :bar=]
574 * f = Foo.new # => #<struct Struct::Foo foo=nil, bar=nil>
575 * f.foo # => nil
576 * f.foo = 0 # => 0
577 * f.bar # => nil
578 * f.bar = 1 # => 1
579 * f # => #<struct Struct::Foo foo=0, bar=1>
581 * <b>Singleton Methods</b>
583 * A subclass returned by Struct.new has these singleton methods:
585 * - \Method <tt>::new </tt> creates an instance of the subclass:
587 * Foo.new # => #<struct Struct::Foo foo=nil, bar=nil>
588 * Foo.new(0) # => #<struct Struct::Foo foo=0, bar=nil>
589 * Foo.new(0, 1) # => #<struct Struct::Foo foo=0, bar=1>
590 * Foo.new(0, 1, 2) # Raises ArgumentError: struct size differs
592 * # Initialization with keyword arguments:
593 * Foo.new(foo: 0) # => #<struct Struct::Foo foo=0, bar=nil>
594 * Foo.new(foo: 0, bar: 1) # => #<struct Struct::Foo foo=0, bar=1>
595 * Foo.new(foo: 0, bar: 1, baz: 2)
596 * # Raises ArgumentError: unknown keywords: baz
598 * - \Method <tt>:inspect</tt> returns a string representation of the subclass:
600 * Foo.inspect
601 * # => "Struct::Foo"
603 * - \Method <tt>::members</tt> returns an array of the member names:
605 * Foo.members # => [:foo, :bar]
607 * <b>Keyword Argument</b>
609 * By default, the arguments for initializing an instance of the new subclass
610 * can be both positional and keyword arguments.
612 * Optional keyword argument <tt>keyword_init:</tt> allows to force only one
613 * type of arguments to be accepted:
615 * KeywordsOnly = Struct.new(:foo, :bar, keyword_init: true)
616 * KeywordsOnly.new(bar: 1, foo: 0)
617 * # => #<struct KeywordsOnly foo=0, bar=1>
618 * KeywordsOnly.new(0, 1)
619 * # Raises ArgumentError: wrong number of arguments
621 * PositionalOnly = Struct.new(:foo, :bar, keyword_init: false)
622 * PositionalOnly.new(0, 1)
623 * # => #<struct PositionalOnly foo=0, bar=1>
624 * PositionalOnly.new(bar: 1, foo: 0)
625 * # => #<struct PositionalOnly foo={:foo=>1, :bar=>2}, bar=nil>
626 * # Note that no error is raised, but arguments treated as one hash value
628 * # Same as not providing keyword_init:
629 * Any = Struct.new(:foo, :bar, keyword_init: nil)
630 * Any.new(foo: 1, bar: 2)
631 * # => #<struct Any foo=1, bar=2>
632 * Any.new(1, 2)
633 * # => #<struct Any foo=1, bar=2>
636 static VALUE
637 rb_struct_s_def(int argc, VALUE *argv, VALUE klass)
639 VALUE name = Qnil, rest, keyword_init = Qnil;
640 long i;
641 VALUE st;
642 VALUE opt;
644 argc = rb_scan_args(argc, argv, "0*:", NULL, &opt);
645 if (argc >= 1 && !SYMBOL_P(argv[0])) {
646 name = argv[0];
647 --argc;
648 ++argv;
651 if (!NIL_P(opt)) {
652 static ID keyword_ids[1];
654 if (!keyword_ids[0]) {
655 keyword_ids[0] = rb_intern("keyword_init");
657 rb_get_kwargs(opt, keyword_ids, 0, 1, &keyword_init);
658 if (UNDEF_P(keyword_init)) {
659 keyword_init = Qnil;
661 else if (RTEST(keyword_init)) {
662 keyword_init = Qtrue;
666 rest = rb_ident_hash_new();
667 RBASIC_CLEAR_CLASS(rest);
668 for (i=0; i<argc; i++) {
669 VALUE mem = rb_to_symbol(argv[i]);
670 if (rb_is_attrset_sym(mem)) {
671 rb_raise(rb_eArgError, "invalid struct member: %"PRIsVALUE, mem);
673 if (RTEST(rb_hash_has_key(rest, mem))) {
674 rb_raise(rb_eArgError, "duplicate member: %"PRIsVALUE, mem);
676 rb_hash_aset(rest, mem, Qtrue);
678 rest = rb_hash_keys(rest);
679 RBASIC_CLEAR_CLASS(rest);
680 OBJ_FREEZE_RAW(rest);
681 if (NIL_P(name)) {
682 st = anonymous_struct(klass);
684 else {
685 st = new_struct(name, klass);
687 setup_struct(st, rest);
688 rb_ivar_set(st, id_keyword_init, keyword_init);
689 if (rb_block_given_p()) {
690 rb_mod_module_eval(0, 0, st);
693 return st;
696 static long
697 num_members(VALUE klass)
699 VALUE members;
700 members = struct_ivar_get(klass, id_members);
701 if (!RB_TYPE_P(members, T_ARRAY)) {
702 rb_raise(rb_eTypeError, "broken members");
704 return RARRAY_LEN(members);
710 struct struct_hash_set_arg {
711 VALUE self;
712 VALUE unknown_keywords;
715 static int rb_struct_pos(VALUE s, VALUE *name);
717 static int
718 struct_hash_set_i(VALUE key, VALUE val, VALUE arg)
720 struct struct_hash_set_arg *args = (struct struct_hash_set_arg *)arg;
721 int i = rb_struct_pos(args->self, &key);
722 if (i < 0) {
723 if (NIL_P(args->unknown_keywords)) {
724 args->unknown_keywords = rb_ary_new();
726 rb_ary_push(args->unknown_keywords, key);
728 else {
729 rb_struct_modify(args->self);
730 RSTRUCT_SET(args->self, i, val);
732 return ST_CONTINUE;
735 static VALUE
736 rb_struct_initialize_m(int argc, const VALUE *argv, VALUE self)
738 VALUE klass = rb_obj_class(self);
739 rb_struct_modify(self);
740 long n = num_members(klass);
741 if (argc == 0) {
742 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self), n);
743 return Qnil;
746 bool keyword_init = false;
747 switch (rb_struct_s_keyword_init(klass)) {
748 default:
749 if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) {
750 rb_error_arity(argc, 0, 0);
752 keyword_init = true;
753 break;
754 case Qfalse:
755 break;
756 case Qnil:
757 if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) {
758 break;
760 keyword_init = rb_keyword_given_p();
761 break;
763 if (keyword_init) {
764 struct struct_hash_set_arg arg;
765 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self), n);
766 arg.self = self;
767 arg.unknown_keywords = Qnil;
768 rb_hash_foreach(argv[0], struct_hash_set_i, (VALUE)&arg);
769 if (arg.unknown_keywords != Qnil) {
770 rb_raise(rb_eArgError, "unknown keywords: %s",
771 RSTRING_PTR(rb_ary_join(arg.unknown_keywords, rb_str_new2(", "))));
774 else {
775 if (n < argc) {
776 rb_raise(rb_eArgError, "struct size differs");
778 for (long i=0; i<argc; i++) {
779 RSTRUCT_SET(self, i, argv[i]);
781 if (n > argc) {
782 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self)+argc, n-argc);
785 return Qnil;
788 VALUE
789 rb_struct_initialize(VALUE self, VALUE values)
791 rb_struct_initialize_m(RARRAY_LENINT(values), RARRAY_CONST_PTR(values), self);
792 if (rb_obj_is_kind_of(self, rb_cData)) OBJ_FREEZE_RAW(self);
793 RB_GC_GUARD(values);
794 return Qnil;
797 static VALUE *
798 struct_heap_alloc(VALUE st, size_t len)
800 return ALLOC_N(VALUE, len);
803 static VALUE
804 struct_alloc(VALUE klass)
806 long n = num_members(klass);
807 size_t embedded_size = offsetof(struct RStruct, as.ary) + (sizeof(VALUE) * n);
808 VALUE flags = T_STRUCT | (RGENGC_WB_PROTECTED_STRUCT ? FL_WB_PROTECTED : 0);
810 if (n > 0 && rb_gc_size_allocatable_p(embedded_size)) {
811 flags |= n << RSTRUCT_EMBED_LEN_SHIFT;
813 NEWOBJ_OF(st, struct RStruct, klass, flags, embedded_size, 0);
815 rb_mem_clear((VALUE *)st->as.ary, n);
817 return (VALUE)st;
819 else {
820 NEWOBJ_OF(st, struct RStruct, klass, flags, sizeof(struct RStruct), 0);
822 st->as.heap.ptr = struct_heap_alloc((VALUE)st, n);
823 rb_mem_clear((VALUE *)st->as.heap.ptr, n);
824 st->as.heap.len = n;
826 return (VALUE)st;
830 VALUE
831 rb_struct_alloc(VALUE klass, VALUE values)
833 return rb_class_new_instance(RARRAY_LENINT(values), RARRAY_CONST_PTR(values), klass);
836 VALUE
837 rb_struct_new(VALUE klass, ...)
839 VALUE tmpargs[16], *mem = tmpargs;
840 int size, i;
841 va_list args;
843 size = rb_long2int(num_members(klass));
844 if (size > numberof(tmpargs)) {
845 tmpargs[0] = rb_ary_hidden_new(size);
846 mem = RARRAY_PTR(tmpargs[0]);
848 va_start(args, klass);
849 for (i=0; i<size; i++) {
850 mem[i] = va_arg(args, VALUE);
852 va_end(args);
854 return rb_class_new_instance(size, mem, klass);
857 static VALUE
858 struct_enum_size(VALUE s, VALUE args, VALUE eobj)
860 return rb_struct_size(s);
864 * call-seq:
865 * each {|value| ... } -> self
866 * each -> enumerator
868 * Calls the given block with the value of each member; returns +self+:
870 * Customer = Struct.new(:name, :address, :zip)
871 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
872 * joe.each {|value| p value }
874 * Output:
876 * "Joe Smith"
877 * "123 Maple, Anytown NC"
878 * 12345
880 * Returns an Enumerator if no block is given.
882 * Related: #each_pair.
885 static VALUE
886 rb_struct_each(VALUE s)
888 long i;
890 RETURN_SIZED_ENUMERATOR(s, 0, 0, struct_enum_size);
891 for (i=0; i<RSTRUCT_LEN(s); i++) {
892 rb_yield(RSTRUCT_GET(s, i));
894 return s;
898 * call-seq:
899 * each_pair {|(name, value)| ... } -> self
900 * each_pair -> enumerator
902 * Calls the given block with each member name/value pair; returns +self+:
904 * Customer = Struct.new(:name, :address, :zip) # => Customer
905 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
906 * joe.each_pair {|(name, value)| p "#{name} => #{value}" }
908 * Output:
910 * "name => Joe Smith"
911 * "address => 123 Maple, Anytown NC"
912 * "zip => 12345"
914 * Returns an Enumerator if no block is given.
916 * Related: #each.
920 static VALUE
921 rb_struct_each_pair(VALUE s)
923 VALUE members;
924 long i;
926 RETURN_SIZED_ENUMERATOR(s, 0, 0, struct_enum_size);
927 members = rb_struct_members(s);
928 if (rb_block_pair_yield_optimizable()) {
929 for (i=0; i<RSTRUCT_LEN(s); i++) {
930 VALUE key = rb_ary_entry(members, i);
931 VALUE value = RSTRUCT_GET(s, i);
932 rb_yield_values(2, key, value);
935 else {
936 for (i=0; i<RSTRUCT_LEN(s); i++) {
937 VALUE key = rb_ary_entry(members, i);
938 VALUE value = RSTRUCT_GET(s, i);
939 rb_yield(rb_assoc_new(key, value));
942 return s;
945 static VALUE
946 inspect_struct(VALUE s, VALUE prefix, int recur)
948 VALUE cname = rb_class_path(rb_obj_class(s));
949 VALUE members;
950 VALUE str = prefix;
951 long i, len;
952 char first = RSTRING_PTR(cname)[0];
954 if (recur || first != '#') {
955 rb_str_append(str, cname);
957 if (recur) {
958 return rb_str_cat2(str, ":...>");
961 members = rb_struct_members(s);
962 len = RSTRUCT_LEN(s);
964 for (i=0; i<len; i++) {
965 VALUE slot;
966 ID id;
968 if (i > 0) {
969 rb_str_cat2(str, ", ");
971 else if (first != '#') {
972 rb_str_cat2(str, " ");
974 slot = RARRAY_AREF(members, i);
975 id = SYM2ID(slot);
976 if (rb_is_local_id(id) || rb_is_const_id(id)) {
977 rb_str_append(str, rb_id2str(id));
979 else {
980 rb_str_append(str, rb_inspect(slot));
982 rb_str_cat2(str, "=");
983 rb_str_append(str, rb_inspect(RSTRUCT_GET(s, i)));
985 rb_str_cat2(str, ">");
987 return str;
991 * call-seq:
992 * inspect -> string
994 * Returns a string representation of +self+:
996 * Customer = Struct.new(:name, :address, :zip) # => Customer
997 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
998 * joe.inspect # => "#<struct Customer name=\"Joe Smith\", address=\"123 Maple, Anytown NC\", zip=12345>"
1002 static VALUE
1003 rb_struct_inspect(VALUE s)
1005 return rb_exec_recursive(inspect_struct, s, rb_str_new2("#<struct "));
1009 * call-seq:
1010 * to_a -> array
1012 * Returns the values in +self+ as an array:
1014 * Customer = Struct.new(:name, :address, :zip)
1015 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1016 * joe.to_a # => ["Joe Smith", "123 Maple, Anytown NC", 12345]
1018 * Related: #members.
1021 static VALUE
1022 rb_struct_to_a(VALUE s)
1024 return rb_ary_new4(RSTRUCT_LEN(s), RSTRUCT_CONST_PTR(s));
1028 * call-seq:
1029 * to_h -> hash
1030 * to_h {|name, value| ... } -> hash
1032 * Returns a hash containing the name and value for each member:
1034 * Customer = Struct.new(:name, :address, :zip)
1035 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1036 * h = joe.to_h
1037 * h # => {:name=>"Joe Smith", :address=>"123 Maple, Anytown NC", :zip=>12345}
1039 * If a block is given, it is called with each name/value pair;
1040 * the block should return a 2-element array whose elements will become
1041 * a key/value pair in the returned hash:
1043 * h = joe.to_h{|name, value| [name.upcase, value.to_s.upcase]}
1044 * h # => {:NAME=>"JOE SMITH", :ADDRESS=>"123 MAPLE, ANYTOWN NC", :ZIP=>"12345"}
1046 * Raises ArgumentError if the block returns an inappropriate value.
1050 static VALUE
1051 rb_struct_to_h(VALUE s)
1053 VALUE h = rb_hash_new_with_size(RSTRUCT_LEN(s));
1054 VALUE members = rb_struct_members(s);
1055 long i;
1056 int block_given = rb_block_given_p();
1058 for (i=0; i<RSTRUCT_LEN(s); i++) {
1059 VALUE k = rb_ary_entry(members, i), v = RSTRUCT_GET(s, i);
1060 if (block_given)
1061 rb_hash_set_pair(h, rb_yield_values(2, k, v));
1062 else
1063 rb_hash_aset(h, k, v);
1065 return h;
1069 * call-seq:
1070 * deconstruct_keys(array_of_names) -> hash
1072 * Returns a hash of the name/value pairs for the given member names.
1074 * Customer = Struct.new(:name, :address, :zip)
1075 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1076 * h = joe.deconstruct_keys([:zip, :address])
1077 * h # => {:zip=>12345, :address=>"123 Maple, Anytown NC"}
1079 * Returns all names and values if +array_of_names+ is +nil+:
1081 * h = joe.deconstruct_keys(nil)
1082 * h # => {:name=>"Joseph Smith, Jr.", :address=>"123 Maple, Anytown NC", :zip=>12345}
1085 static VALUE
1086 rb_struct_deconstruct_keys(VALUE s, VALUE keys)
1088 VALUE h;
1089 long i;
1091 if (NIL_P(keys)) {
1092 return rb_struct_to_h(s);
1094 if (UNLIKELY(!RB_TYPE_P(keys, T_ARRAY))) {
1095 rb_raise(rb_eTypeError,
1096 "wrong argument type %"PRIsVALUE" (expected Array or nil)",
1097 rb_obj_class(keys));
1100 if (RSTRUCT_LEN(s) < RARRAY_LEN(keys)) {
1101 return rb_hash_new_with_size(0);
1103 h = rb_hash_new_with_size(RARRAY_LEN(keys));
1104 for (i=0; i<RARRAY_LEN(keys); i++) {
1105 VALUE key = RARRAY_AREF(keys, i);
1106 int i = rb_struct_pos(s, &key);
1107 if (i < 0) {
1108 return h;
1110 rb_hash_aset(h, key, RSTRUCT_GET(s, i));
1112 return h;
1115 /* :nodoc: */
1116 VALUE
1117 rb_struct_init_copy(VALUE copy, VALUE s)
1119 long i, len;
1121 if (!OBJ_INIT_COPY(copy, s)) return copy;
1122 if (RSTRUCT_LEN(copy) != RSTRUCT_LEN(s)) {
1123 rb_raise(rb_eTypeError, "struct size mismatch");
1126 for (i=0, len=RSTRUCT_LEN(copy); i<len; i++) {
1127 RSTRUCT_SET(copy, i, RSTRUCT_GET(s, i));
1130 return copy;
1133 static int
1134 rb_struct_pos(VALUE s, VALUE *name)
1136 long i;
1137 VALUE idx = *name;
1139 if (SYMBOL_P(idx)) {
1140 return struct_member_pos(s, idx);
1142 else if (RB_TYPE_P(idx, T_STRING)) {
1143 idx = rb_check_symbol(name);
1144 if (NIL_P(idx)) return -1;
1145 return struct_member_pos(s, idx);
1147 else {
1148 long len;
1149 i = NUM2LONG(idx);
1150 len = RSTRUCT_LEN(s);
1151 if (i < 0) {
1152 if (i + len < 0) {
1153 *name = LONG2FIX(i);
1154 return -1;
1156 i += len;
1158 else if (len <= i) {
1159 *name = LONG2FIX(i);
1160 return -1;
1162 return (int)i;
1166 static void
1167 invalid_struct_pos(VALUE s, VALUE idx)
1169 if (FIXNUM_P(idx)) {
1170 long i = FIX2INT(idx), len = RSTRUCT_LEN(s);
1171 if (i < 0) {
1172 rb_raise(rb_eIndexError, "offset %ld too small for struct(size:%ld)",
1173 i, len);
1175 else {
1176 rb_raise(rb_eIndexError, "offset %ld too large for struct(size:%ld)",
1177 i, len);
1180 else {
1181 rb_name_err_raise("no member '%1$s' in struct", s, idx);
1186 * call-seq:
1187 * struct[name] -> object
1188 * struct[n] -> object
1190 * Returns a value from +self+.
1192 * With symbol or string argument +name+ given, returns the value for the named member:
1194 * Customer = Struct.new(:name, :address, :zip)
1195 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1196 * joe[:zip] # => 12345
1198 * Raises NameError if +name+ is not the name of a member.
1200 * With integer argument +n+ given, returns <tt>self.values[n]</tt>
1201 * if +n+ is in range;
1202 * see Array@Array+Indexes:
1204 * joe[2] # => 12345
1205 * joe[-2] # => "123 Maple, Anytown NC"
1207 * Raises IndexError if +n+ is out of range.
1211 VALUE
1212 rb_struct_aref(VALUE s, VALUE idx)
1214 int i = rb_struct_pos(s, &idx);
1215 if (i < 0) invalid_struct_pos(s, idx);
1216 return RSTRUCT_GET(s, i);
1220 * call-seq:
1221 * struct[name] = value -> value
1222 * struct[n] = value -> value
1224 * Assigns a value to a member.
1226 * With symbol or string argument +name+ given, assigns the given +value+
1227 * to the named member; returns +value+:
1229 * Customer = Struct.new(:name, :address, :zip)
1230 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1231 * joe[:zip] = 54321 # => 54321
1232 * joe # => #<struct Customer name="Joe Smith", address="123 Maple, Anytown NC", zip=54321>
1234 * Raises NameError if +name+ is not the name of a member.
1236 * With integer argument +n+ given, assigns the given +value+
1237 * to the +n+-th member if +n+ is in range;
1238 * see Array@Array+Indexes:
1240 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1241 * joe[2] = 54321 # => 54321
1242 * joe[-3] = 'Joseph Smith' # => "Joseph Smith"
1243 * joe # => #<struct Customer name="Joseph Smith", address="123 Maple, Anytown NC", zip=54321>
1245 * Raises IndexError if +n+ is out of range.
1249 VALUE
1250 rb_struct_aset(VALUE s, VALUE idx, VALUE val)
1252 int i = rb_struct_pos(s, &idx);
1253 if (i < 0) invalid_struct_pos(s, idx);
1254 rb_struct_modify(s);
1255 RSTRUCT_SET(s, i, val);
1256 return val;
1259 FUNC_MINIMIZED(VALUE rb_struct_lookup(VALUE s, VALUE idx));
1260 NOINLINE(static VALUE rb_struct_lookup_default(VALUE s, VALUE idx, VALUE notfound));
1262 VALUE
1263 rb_struct_lookup(VALUE s, VALUE idx)
1265 return rb_struct_lookup_default(s, idx, Qnil);
1268 static VALUE
1269 rb_struct_lookup_default(VALUE s, VALUE idx, VALUE notfound)
1271 int i = rb_struct_pos(s, &idx);
1272 if (i < 0) return notfound;
1273 return RSTRUCT_GET(s, i);
1276 static VALUE
1277 struct_entry(VALUE s, long n)
1279 return rb_struct_aref(s, LONG2NUM(n));
1283 * call-seq:
1284 * values_at(*integers) -> array
1285 * values_at(integer_range) -> array
1287 * Returns an array of values from +self+.
1289 * With integer arguments +integers+ given,
1290 * returns an array containing each value given by one of +integers+:
1292 * Customer = Struct.new(:name, :address, :zip)
1293 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1294 * joe.values_at(0, 2) # => ["Joe Smith", 12345]
1295 * joe.values_at(2, 0) # => [12345, "Joe Smith"]
1296 * joe.values_at(2, 1, 0) # => [12345, "123 Maple, Anytown NC", "Joe Smith"]
1297 * joe.values_at(0, -3) # => ["Joe Smith", "Joe Smith"]
1299 * Raises IndexError if any of +integers+ is out of range;
1300 * see Array@Array+Indexes.
1302 * With integer range argument +integer_range+ given,
1303 * returns an array containing each value given by the elements of the range;
1304 * fills with +nil+ values for range elements larger than the structure:
1306 * joe.values_at(0..2)
1307 * # => ["Joe Smith", "123 Maple, Anytown NC", 12345]
1308 * joe.values_at(-3..-1)
1309 * # => ["Joe Smith", "123 Maple, Anytown NC", 12345]
1310 * joe.values_at(1..4) # => ["123 Maple, Anytown NC", 12345, nil, nil]
1312 * Raises RangeError if any element of the range is negative and out of range;
1313 * see Array@Array+Indexes.
1317 static VALUE
1318 rb_struct_values_at(int argc, VALUE *argv, VALUE s)
1320 return rb_get_values_at(s, RSTRUCT_LEN(s), argc, argv, struct_entry);
1324 * call-seq:
1325 * select {|value| ... } -> array
1326 * select -> enumerator
1328 * With a block given, returns an array of values from +self+
1329 * for which the block returns a truthy value:
1331 * Customer = Struct.new(:name, :address, :zip)
1332 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1333 * a = joe.select {|value| value.is_a?(String) }
1334 * a # => ["Joe Smith", "123 Maple, Anytown NC"]
1335 * a = joe.select {|value| value.is_a?(Integer) }
1336 * a # => [12345]
1338 * With no block given, returns an Enumerator.
1341 static VALUE
1342 rb_struct_select(int argc, VALUE *argv, VALUE s)
1344 VALUE result;
1345 long i;
1347 rb_check_arity(argc, 0, 0);
1348 RETURN_SIZED_ENUMERATOR(s, 0, 0, struct_enum_size);
1349 result = rb_ary_new();
1350 for (i = 0; i < RSTRUCT_LEN(s); i++) {
1351 if (RTEST(rb_yield(RSTRUCT_GET(s, i)))) {
1352 rb_ary_push(result, RSTRUCT_GET(s, i));
1356 return result;
1359 static VALUE
1360 recursive_equal(VALUE s, VALUE s2, int recur)
1362 long i, len;
1364 if (recur) return Qtrue; /* Subtle! */
1365 len = RSTRUCT_LEN(s);
1366 for (i=0; i<len; i++) {
1367 if (!rb_equal(RSTRUCT_GET(s, i), RSTRUCT_GET(s2, i))) return Qfalse;
1369 return Qtrue;
1374 * call-seq:
1375 * self == other -> true or false
1377 * Returns +true+ if and only if the following are true; otherwise returns +false+:
1379 * - <tt>other.class == self.class</tt>.
1380 * - For each member name +name+, <tt>other.name == self.name</tt>.
1382 * Examples:
1384 * Customer = Struct.new(:name, :address, :zip)
1385 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1386 * joe_jr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1387 * joe_jr == joe # => true
1388 * joe_jr[:name] = 'Joe Smith, Jr.'
1389 * # => "Joe Smith, Jr."
1390 * joe_jr == joe # => false
1393 static VALUE
1394 rb_struct_equal(VALUE s, VALUE s2)
1396 if (s == s2) return Qtrue;
1397 if (!RB_TYPE_P(s2, T_STRUCT)) return Qfalse;
1398 if (rb_obj_class(s) != rb_obj_class(s2)) return Qfalse;
1399 if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) {
1400 rb_bug("inconsistent struct"); /* should never happen */
1403 return rb_exec_recursive_paired(recursive_equal, s, s2, s2);
1407 * call-seq:
1408 * hash -> integer
1410 * Returns the integer hash value for +self+.
1412 * Two structs of the same class and with the same content
1413 * will have the same hash code (and will compare using Struct#eql?):
1415 * Customer = Struct.new(:name, :address, :zip)
1416 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1417 * joe_jr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1418 * joe.hash == joe_jr.hash # => true
1419 * joe_jr[:name] = 'Joe Smith, Jr.'
1420 * joe.hash == joe_jr.hash # => false
1422 * Related: Object#hash.
1425 static VALUE
1426 rb_struct_hash(VALUE s)
1428 long i, len;
1429 st_index_t h;
1430 VALUE n;
1432 h = rb_hash_start(rb_hash(rb_obj_class(s)));
1433 len = RSTRUCT_LEN(s);
1434 for (i = 0; i < len; i++) {
1435 n = rb_hash(RSTRUCT_GET(s, i));
1436 h = rb_hash_uint(h, NUM2LONG(n));
1438 h = rb_hash_end(h);
1439 return ST2FIX(h);
1442 static VALUE
1443 recursive_eql(VALUE s, VALUE s2, int recur)
1445 long i, len;
1447 if (recur) return Qtrue; /* Subtle! */
1448 len = RSTRUCT_LEN(s);
1449 for (i=0; i<len; i++) {
1450 if (!rb_eql(RSTRUCT_GET(s, i), RSTRUCT_GET(s2, i))) return Qfalse;
1452 return Qtrue;
1456 * call-seq:
1457 * eql?(other) -> true or false
1459 * Returns +true+ if and only if the following are true; otherwise returns +false+:
1461 * - <tt>other.class == self.class</tt>.
1462 * - For each member name +name+, <tt>other.name.eql?(self.name)</tt>.
1464 * Customer = Struct.new(:name, :address, :zip)
1465 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1466 * joe_jr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1467 * joe_jr.eql?(joe) # => true
1468 * joe_jr[:name] = 'Joe Smith, Jr.'
1469 * joe_jr.eql?(joe) # => false
1471 * Related: Object#==.
1474 static VALUE
1475 rb_struct_eql(VALUE s, VALUE s2)
1477 if (s == s2) return Qtrue;
1478 if (!RB_TYPE_P(s2, T_STRUCT)) return Qfalse;
1479 if (rb_obj_class(s) != rb_obj_class(s2)) return Qfalse;
1480 if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) {
1481 rb_bug("inconsistent struct"); /* should never happen */
1484 return rb_exec_recursive_paired(recursive_eql, s, s2, s2);
1488 * call-seq:
1489 * size -> integer
1491 * Returns the number of members.
1493 * Customer = Struct.new(:name, :address, :zip)
1494 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1495 * joe.size #=> 3
1499 VALUE
1500 rb_struct_size(VALUE s)
1502 return LONG2FIX(RSTRUCT_LEN(s));
1506 * call-seq:
1507 * dig(name, *identifiers) -> object
1508 * dig(n, *identifiers) -> object
1510 * Finds and returns an object among nested objects.
1511 * The nested objects may be instances of various classes.
1512 * See {Dig Methods}[rdoc-ref:dig_methods.rdoc].
1515 * Given symbol or string argument +name+,
1516 * returns the object that is specified by +name+ and +identifiers+:
1518 * Foo = Struct.new(:a)
1519 * f = Foo.new(Foo.new({b: [1, 2, 3]}))
1520 * f.dig(:a) # => #<struct Foo a={:b=>[1, 2, 3]}>
1521 * f.dig(:a, :a) # => {:b=>[1, 2, 3]}
1522 * f.dig(:a, :a, :b) # => [1, 2, 3]
1523 * f.dig(:a, :a, :b, 0) # => 1
1524 * f.dig(:b, 0) # => nil
1526 * Given integer argument +n+,
1527 * returns the object that is specified by +n+ and +identifiers+:
1529 * f.dig(0) # => #<struct Foo a={:b=>[1, 2, 3]}>
1530 * f.dig(0, 0) # => {:b=>[1, 2, 3]}
1531 * f.dig(0, 0, :b) # => [1, 2, 3]
1532 * f.dig(0, 0, :b, 0) # => 1
1533 * f.dig(:b, 0) # => nil
1537 static VALUE
1538 rb_struct_dig(int argc, VALUE *argv, VALUE self)
1540 rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
1541 self = rb_struct_lookup(self, *argv);
1542 if (!--argc) return self;
1543 ++argv;
1544 return rb_obj_dig(argc, argv, self, Qnil);
1548 * Document-class: Data
1550 * \Class \Data provides a convenient way to define simple classes
1551 * for value-alike objects.
1553 * The simplest example of usage:
1555 * Measure = Data.define(:amount, :unit)
1557 * # Positional arguments constructor is provided
1558 * distance = Measure.new(100, 'km')
1559 * #=> #<data Measure amount=100, unit="km">
1561 * # Keyword arguments constructor is provided
1562 * weight = Measure.new(amount: 50, unit: 'kg')
1563 * #=> #<data Measure amount=50, unit="kg">
1565 * # Alternative form to construct an object:
1566 * speed = Measure[10, 'mPh']
1567 * #=> #<data Measure amount=10, unit="mPh">
1569 * # Works with keyword arguments, too:
1570 * area = Measure[amount: 1.5, unit: 'm^2']
1571 * #=> #<data Measure amount=1.5, unit="m^2">
1573 * # Argument accessors are provided:
1574 * distance.amount #=> 100
1575 * distance.unit #=> "km"
1577 * Constructed object also has a reasonable definitions of #==
1578 * operator, #to_h hash conversion, and #deconstruct / #deconstruct_keys
1579 * to be used in pattern matching.
1581 * ::define method accepts an optional block and evaluates it in
1582 * the context of the newly defined class. That allows to define
1583 * additional methods:
1585 * Measure = Data.define(:amount, :unit) do
1586 * def <=>(other)
1587 * return unless other.is_a?(self.class) && other.unit == unit
1588 * amount <=> other.amount
1589 * end
1591 * include Comparable
1592 * end
1594 * Measure[3, 'm'] < Measure[5, 'm'] #=> true
1595 * Measure[3, 'm'] < Measure[5, 'kg']
1596 * # comparison of Measure with Measure failed (ArgumentError)
1598 * Data provides no member writers, or enumerators: it is meant
1599 * to be a storage for immutable atomic values. But note that
1600 * if some of data members is of a mutable class, Data does no additional
1601 * immutability enforcement:
1603 * Event = Data.define(:time, :weekdays)
1604 * event = Event.new('18:00', %w[Tue Wed Fri])
1605 * #=> #<data Event time="18:00", weekdays=["Tue", "Wed", "Fri"]>
1607 * # There is no #time= or #weekdays= accessors, but changes are
1608 * # still possible:
1609 * event.weekdays << 'Sat'
1610 * event
1611 * #=> #<data Event time="18:00", weekdays=["Tue", "Wed", "Fri", "Sat"]>
1613 * See also Struct, which is a similar concept, but has more
1614 * container-alike API, allowing to change contents of the object
1615 * and enumerate it.
1619 * call-seq:
1620 * define(*symbols) -> class
1622 * Defines a new \Data class.
1624 * measure = Data.define(:amount, :unit)
1625 * #=> #<Class:0x00007f70c6868498>
1626 * measure.new(1, 'km')
1627 * #=> #<data amount=1, unit="km">
1629 * # It you store the new class in the constant, it will
1630 * # affect #inspect and will be more natural to use:
1631 * Measure = Data.define(:amount, :unit)
1632 * #=> Measure
1633 * Measure.new(1, 'km')
1634 * #=> #<data Measure amount=1, unit="km">
1637 * Note that member-less \Data is acceptable and might be a useful technique
1638 * for defining several homogenous data classes, like
1640 * class HTTPFetcher
1641 * Response = Data.define(:body)
1642 * NotFound = Data.define
1643 * # ... implementation
1644 * end
1646 * Now, different kinds of responses from +HTTPFetcher+ would have consistent
1647 * representation:
1649 * #<data HTTPFetcher::Response body="<html...">
1650 * #<data HTTPFetcher::NotFound>
1652 * And are convenient to use in pattern matching:
1654 * case fetcher.get(url)
1655 * in HTTPFetcher::Response(body)
1656 * # process body variable
1657 * in HTTPFetcher::NotFound
1658 * # handle not found case
1659 * end
1662 static VALUE
1663 rb_data_s_def(int argc, VALUE *argv, VALUE klass)
1665 VALUE rest;
1666 long i;
1667 VALUE data_class;
1669 rest = rb_ident_hash_new();
1670 RBASIC_CLEAR_CLASS(rest);
1671 for (i=0; i<argc; i++) {
1672 VALUE mem = rb_to_symbol(argv[i]);
1673 if (rb_is_attrset_sym(mem)) {
1674 rb_raise(rb_eArgError, "invalid data member: %"PRIsVALUE, mem);
1676 if (RTEST(rb_hash_has_key(rest, mem))) {
1677 rb_raise(rb_eArgError, "duplicate member: %"PRIsVALUE, mem);
1679 rb_hash_aset(rest, mem, Qtrue);
1681 rest = rb_hash_keys(rest);
1682 RBASIC_CLEAR_CLASS(rest);
1683 OBJ_FREEZE_RAW(rest);
1684 data_class = anonymous_struct(klass);
1685 setup_data(data_class, rest);
1686 if (rb_block_given_p()) {
1687 rb_mod_module_eval(0, 0, data_class);
1690 return data_class;
1693 VALUE
1694 rb_data_define(VALUE super, ...)
1696 va_list ar;
1697 VALUE ary;
1698 va_start(ar, super);
1699 ary = struct_make_members_list(ar);
1700 va_end(ar);
1701 if (!super) super = rb_cData;
1702 return setup_data(anonymous_struct(super), ary);
1706 * call-seq:
1707 * DataClass::members -> array_of_symbols
1709 * Returns an array of member names of the data class:
1711 * Measure = Data.define(:amount, :unit)
1712 * Measure.members # => [:amount, :unit]
1716 #define rb_data_s_members_m rb_struct_s_members_m
1720 * call-seq:
1721 * new(*args) -> instance
1722 * new(**kwargs) -> instance
1723 * ::[](*args) -> instance
1724 * ::[](**kwargs) -> instance
1726 * Constructors for classes defined with ::define accept both positional and
1727 * keyword arguments.
1729 * Measure = Data.define(:amount, :unit)
1731 * Measure.new(1, 'km')
1732 * #=> #<data Measure amount=1, unit="km">
1733 * Measure.new(amount: 1, unit: 'km')
1734 * #=> #<data Measure amount=1, unit="km">
1736 * # Alternative shorter initialization with []
1737 * Measure[1, 'km']
1738 * #=> #<data Measure amount=1, unit="km">
1739 * Measure[amount: 1, unit: 'km']
1740 * #=> #<data Measure amount=1, unit="km">
1742 * All arguments are mandatory (unlike Struct), and converted to keyword arguments:
1744 * Measure.new(amount: 1)
1745 * # in `initialize': missing keyword: :unit (ArgumentError)
1747 * Measure.new(1)
1748 * # in `initialize': missing keyword: :unit (ArgumentError)
1750 * Note that <tt>Measure#initialize</tt> always receives keyword arguments, and that
1751 * mandatory arguments are checked in +initialize+, not in +new+. This can be
1752 * important for redefining initialize in order to convert arguments or provide
1753 * defaults:
1755 * Measure = Data.define(:amount, :unit) do
1756 * NONE = Data.define
1758 * def initialize(amount:, unit: NONE.new)
1759 * super(amount: Float(amount), unit:)
1760 * end
1761 * end
1763 * Measure.new('10', 'km') # => #<data Measure amount=10.0, unit="km">
1764 * Measure.new(10_000) # => #<data Measure amount=10000.0, unit=#<data NONE>>
1768 static VALUE
1769 rb_data_initialize_m(int argc, const VALUE *argv, VALUE self)
1771 VALUE klass = rb_obj_class(self);
1772 rb_struct_modify(self);
1773 VALUE members = struct_ivar_get(klass, id_members);
1774 size_t num_members = RARRAY_LEN(members);
1776 if (argc == 0) {
1777 if (num_members > 0) {
1778 rb_exc_raise(rb_keyword_error_new("missing", members));
1780 return Qnil;
1782 if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) {
1783 rb_error_arity(argc, 0, 0);
1786 if (RHASH_SIZE(argv[0]) < num_members) {
1787 VALUE missing = rb_ary_diff(members, rb_hash_keys(argv[0]));
1788 rb_exc_raise(rb_keyword_error_new("missing", missing));
1791 struct struct_hash_set_arg arg;
1792 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self), num_members);
1793 arg.self = self;
1794 arg.unknown_keywords = Qnil;
1795 rb_hash_foreach(argv[0], struct_hash_set_i, (VALUE)&arg);
1796 // Freeze early before potentially raising, so that we don't leave an
1797 // unfrozen copy on the heap, which could get exposed via ObjectSpace.
1798 OBJ_FREEZE_RAW(self);
1799 if (arg.unknown_keywords != Qnil) {
1800 rb_exc_raise(rb_keyword_error_new("unknown", arg.unknown_keywords));
1802 return Qnil;
1805 /* :nodoc: */
1806 static VALUE
1807 rb_data_init_copy(VALUE copy, VALUE s)
1809 copy = rb_struct_init_copy(copy, s);
1810 RB_OBJ_FREEZE_RAW(copy);
1811 return copy;
1815 * call-seq:
1816 * with(**kwargs) -> instance
1818 * Returns a shallow copy of +self+ --- the instance variables of
1819 * +self+ are copied, but not the objects they reference.
1821 * If the method is supplied any keyword arguments, the copy will
1822 * be created with the respective field values updated to use the
1823 * supplied keyword argument values. Note that it is an error to
1824 * supply a keyword that the Data class does not have as a member.
1826 * Point = Data.define(:x, :y)
1828 * origin = Point.new(x: 0, y: 0)
1830 * up = origin.with(x: 1)
1831 * right = origin.with(y: 1)
1832 * up_and_right = up.with(y: 1)
1834 * p origin # #<data Point x=0, y=0>
1835 * p up # #<data Point x=1, y=0>
1836 * p right # #<data Point x=0, y=1>
1837 * p up_and_right # #<data Point x=1, y=1>
1839 * out = origin.with(z: 1) # ArgumentError: unknown keyword: :z
1840 * some_point = origin.with(1, 2) # ArgumentError: expected keyword arguments, got positional arguments
1844 static VALUE
1845 rb_data_with(int argc, const VALUE *argv, VALUE self)
1847 VALUE kwargs;
1848 rb_scan_args(argc, argv, "0:", &kwargs);
1849 if (NIL_P(kwargs)) {
1850 return self;
1853 VALUE h = rb_struct_to_h(self);
1854 rb_hash_update_by(h, kwargs, 0);
1855 return rb_class_new_instance_kw(1, &h, rb_obj_class(self), TRUE);
1859 * call-seq:
1860 * inspect -> string
1861 * to_s -> string
1863 * Returns a string representation of +self+:
1865 * Measure = Data.define(:amount, :unit)
1867 * distance = Measure[10, 'km']
1869 * p distance # uses #inspect underneath
1870 * #<data Measure amount=10, unit="km">
1872 * puts distance # uses #to_s underneath, same representation
1873 * #<data Measure amount=10, unit="km">
1877 static VALUE
1878 rb_data_inspect(VALUE s)
1880 return rb_exec_recursive(inspect_struct, s, rb_str_new2("#<data "));
1884 * call-seq:
1885 * self == other -> true or false
1887 * Returns +true+ if +other+ is the same class as +self+, and all members are
1888 * equal.
1890 * Examples:
1892 * Measure = Data.define(:amount, :unit)
1894 * Measure[1, 'km'] == Measure[1, 'km'] #=> true
1895 * Measure[1, 'km'] == Measure[2, 'km'] #=> false
1896 * Measure[1, 'km'] == Measure[1, 'm'] #=> false
1898 * Measurement = Data.define(:amount, :unit)
1899 * # Even though Measurement and Measure have the same "shape"
1900 * # their instances are never equal
1901 * Measure[1, 'km'] == Measurement[1, 'km'] #=> false
1904 #define rb_data_equal rb_struct_equal
1907 * call-seq:
1908 * self.eql?(other) -> true or false
1910 * Equality check that is used when two items of data are keys of a Hash.
1912 * The subtle difference with #== is that members are also compared with their
1913 * #eql? method, which might be important in some cases:
1915 * Measure = Data.define(:amount, :unit)
1917 * Measure[1, 'km'] == Measure[1.0, 'km'] #=> true, they are equal as values
1918 * # ...but...
1919 * Measure[1, 'km'].eql? Measure[1.0, 'km'] #=> false, they represent different hash keys
1921 * See also Object#eql? for further explanations of the method usage.
1924 #define rb_data_eql rb_struct_eql
1927 * call-seq:
1928 * hash -> integer
1930 * Redefines Object#hash (used to distinguish objects as Hash keys) so that
1931 * data objects of the same class with same content would have the same +hash+
1932 * value, and represented the same Hash key.
1934 * Measure = Data.define(:amount, :unit)
1936 * Measure[1, 'km'].hash == Measure[1, 'km'].hash #=> true
1937 * Measure[1, 'km'].hash == Measure[10, 'km'].hash #=> false
1938 * Measure[1, 'km'].hash == Measure[1, 'm'].hash #=> false
1939 * Measure[1, 'km'].hash == Measure[1.0, 'km'].hash #=> false
1941 * # Structurally similar data class, but shouldn't be considered
1942 * # the same hash key
1943 * Measurement = Data.define(:amount, :unit)
1945 * Measure[1, 'km'].hash == Measurement[1, 'km'].hash #=> false
1948 #define rb_data_hash rb_struct_hash
1951 * call-seq:
1952 * to_h -> hash
1953 * to_h {|name, value| ... } -> hash
1955 * Returns Hash representation of the data object.
1957 * Measure = Data.define(:amount, :unit)
1958 * distance = Measure[10, 'km']
1960 * distance.to_h
1961 * #=> {:amount=>10, :unit=>"km"}
1963 * Like Enumerable#to_h, if the block is provided, it is expected to
1964 * produce key-value pairs to construct a hash:
1967 * distance.to_h { |name, val| [name.to_s, val.to_s] }
1968 * #=> {"amount"=>"10", "unit"=>"km"}
1970 * Note that there is a useful symmetry between #to_h and #initialize:
1972 * distance2 = Measure.new(**distance.to_h)
1973 * #=> #<data Measure amount=10, unit="km">
1974 * distance2 == distance
1975 * #=> true
1978 #define rb_data_to_h rb_struct_to_h
1981 * call-seq:
1982 * members -> array_of_symbols
1984 * Returns the member names from +self+ as an array:
1986 * Measure = Data.define(:amount, :unit)
1987 * distance = Measure[10, 'km']
1989 * distance.members #=> [:amount, :unit]
1993 #define rb_data_members_m rb_struct_members_m
1996 * call-seq:
1997 * deconstruct -> array
1999 * Returns the values in +self+ as an array, to use in pattern matching:
2001 * Measure = Data.define(:amount, :unit)
2003 * distance = Measure[10, 'km']
2004 * distance.deconstruct #=> [10, "km"]
2006 * # usage
2007 * case distance
2008 * in n, 'km' # calls #deconstruct underneath
2009 * puts "It is #{n} kilometers away"
2010 * else
2011 * puts "Don't know how to handle it"
2012 * end
2013 * # prints "It is 10 kilometers away"
2015 * Or, with checking the class, too:
2017 * case distance
2018 * in Measure(n, 'km')
2019 * puts "It is #{n} kilometers away"
2020 * # ...
2021 * end
2024 #define rb_data_deconstruct rb_struct_to_a
2027 * call-seq:
2028 * deconstruct_keys(array_of_names_or_nil) -> hash
2030 * Returns a hash of the name/value pairs, to use in pattern matching.
2032 * Measure = Data.define(:amount, :unit)
2034 * distance = Measure[10, 'km']
2035 * distance.deconstruct_keys(nil) #=> {:amount=>10, :unit=>"km"}
2036 * distance.deconstruct_keys([:amount]) #=> {:amount=>10}
2038 * # usage
2039 * case distance
2040 * in amount:, unit: 'km' # calls #deconstruct_keys underneath
2041 * puts "It is #{amount} kilometers away"
2042 * else
2043 * puts "Don't know how to handle it"
2044 * end
2045 * # prints "It is 10 kilometers away"
2047 * Or, with checking the class, too:
2049 * case distance
2050 * in Measure(amount:, unit: 'km')
2051 * puts "It is #{amount} kilometers away"
2052 * # ...
2053 * end
2056 #define rb_data_deconstruct_keys rb_struct_deconstruct_keys
2059 * Document-class: Struct
2061 * \Class \Struct provides a convenient way to create a simple class
2062 * that can store and fetch values.
2064 * This example creates a subclass of +Struct+, <tt>Struct::Customer</tt>;
2065 * the first argument, a string, is the name of the subclass;
2066 * the other arguments, symbols, determine the _members_ of the new subclass.
2068 * Customer = Struct.new('Customer', :name, :address, :zip)
2069 * Customer.name # => "Struct::Customer"
2070 * Customer.class # => Class
2071 * Customer.superclass # => Struct
2073 * Corresponding to each member are two methods, a writer and a reader,
2074 * that store and fetch values:
2076 * methods = Customer.instance_methods false
2077 * methods # => [:zip, :address=, :zip=, :address, :name, :name=]
2079 * An instance of the subclass may be created,
2080 * and its members assigned values, via method <tt>::new</tt>:
2082 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
2083 * joe # => #<struct Struct::Customer name="Joe Smith", address="123 Maple, Anytown NC", zip=12345>
2085 * The member values may be managed thus:
2087 * joe.name # => "Joe Smith"
2088 * joe.name = 'Joseph Smith'
2089 * joe.name # => "Joseph Smith"
2091 * And thus; note that member name may be expressed as either a string or a symbol:
2093 * joe[:name] # => "Joseph Smith"
2094 * joe[:name] = 'Joseph Smith, Jr.'
2095 * joe['name'] # => "Joseph Smith, Jr."
2097 * See Struct::new.
2099 * == What's Here
2101 * First, what's elsewhere. \Class \Struct:
2103 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
2104 * - Includes {module Enumerable}[rdoc-ref:Enumerable@What-27s+Here],
2105 * which provides dozens of additional methods.
2107 * See also Data, which is a somewhat similar, but stricter concept for defining immutable
2108 * value objects.
2110 * Here, class \Struct provides methods that are useful for:
2112 * - {Creating a Struct Subclass}[rdoc-ref:Struct@Methods+for+Creating+a+Struct+Subclass]
2113 * - {Querying}[rdoc-ref:Struct@Methods+for+Querying]
2114 * - {Comparing}[rdoc-ref:Struct@Methods+for+Comparing]
2115 * - {Fetching}[rdoc-ref:Struct@Methods+for+Fetching]
2116 * - {Assigning}[rdoc-ref:Struct@Methods+for+Assigning]
2117 * - {Iterating}[rdoc-ref:Struct@Methods+for+Iterating]
2118 * - {Converting}[rdoc-ref:Struct@Methods+for+Converting]
2120 * === Methods for Creating a Struct Subclass
2122 * - ::new: Returns a new subclass of \Struct.
2124 * === Methods for Querying
2126 * - #hash: Returns the integer hash code.
2127 * - #length, #size: Returns the number of members.
2129 * === Methods for Comparing
2131 * - #==: Returns whether a given object is equal to +self+, using <tt>==</tt>
2132 * to compare member values.
2133 * - #eql?: Returns whether a given object is equal to +self+,
2134 * using <tt>eql?</tt> to compare member values.
2136 * === Methods for Fetching
2138 * - #[]: Returns the value associated with a given member name.
2139 * - #to_a, #values, #deconstruct: Returns the member values in +self+ as an array.
2140 * - #deconstruct_keys: Returns a hash of the name/value pairs
2141 * for given member names.
2142 * - #dig: Returns the object in nested objects that is specified
2143 * by a given member name and additional arguments.
2144 * - #members: Returns an array of the member names.
2145 * - #select, #filter: Returns an array of member values from +self+,
2146 * as selected by the given block.
2147 * - #values_at: Returns an array containing values for given member names.
2149 * === Methods for Assigning
2151 * - #[]=: Assigns a given value to a given member name.
2153 * === Methods for Iterating
2155 * - #each: Calls a given block with each member name.
2156 * - #each_pair: Calls a given block with each member name/value pair.
2158 * === Methods for Converting
2160 * - #inspect, #to_s: Returns a string representation of +self+.
2161 * - #to_h: Returns a hash of the member name/value pairs in +self+.
2164 void
2165 InitVM_Struct(void)
2167 rb_cStruct = rb_define_class("Struct", rb_cObject);
2168 rb_include_module(rb_cStruct, rb_mEnumerable);
2170 rb_undef_alloc_func(rb_cStruct);
2171 rb_define_singleton_method(rb_cStruct, "new", rb_struct_s_def, -1);
2172 #if 0 /* for RDoc */
2173 rb_define_singleton_method(rb_cStruct, "keyword_init?", rb_struct_s_keyword_init_p, 0);
2174 rb_define_singleton_method(rb_cStruct, "members", rb_struct_s_members_m, 0);
2175 #endif
2177 rb_define_method(rb_cStruct, "initialize", rb_struct_initialize_m, -1);
2178 rb_define_method(rb_cStruct, "initialize_copy", rb_struct_init_copy, 1);
2180 rb_define_method(rb_cStruct, "==", rb_struct_equal, 1);
2181 rb_define_method(rb_cStruct, "eql?", rb_struct_eql, 1);
2182 rb_define_method(rb_cStruct, "hash", rb_struct_hash, 0);
2184 rb_define_method(rb_cStruct, "inspect", rb_struct_inspect, 0);
2185 rb_define_alias(rb_cStruct, "to_s", "inspect");
2186 rb_define_method(rb_cStruct, "to_a", rb_struct_to_a, 0);
2187 rb_define_method(rb_cStruct, "to_h", rb_struct_to_h, 0);
2188 rb_define_method(rb_cStruct, "values", rb_struct_to_a, 0);
2189 rb_define_method(rb_cStruct, "size", rb_struct_size, 0);
2190 rb_define_method(rb_cStruct, "length", rb_struct_size, 0);
2192 rb_define_method(rb_cStruct, "each", rb_struct_each, 0);
2193 rb_define_method(rb_cStruct, "each_pair", rb_struct_each_pair, 0);
2194 rb_define_method(rb_cStruct, "[]", rb_struct_aref, 1);
2195 rb_define_method(rb_cStruct, "[]=", rb_struct_aset, 2);
2196 rb_define_method(rb_cStruct, "select", rb_struct_select, -1);
2197 rb_define_method(rb_cStruct, "filter", rb_struct_select, -1);
2198 rb_define_method(rb_cStruct, "values_at", rb_struct_values_at, -1);
2200 rb_define_method(rb_cStruct, "members", rb_struct_members_m, 0);
2201 rb_define_method(rb_cStruct, "dig", rb_struct_dig, -1);
2203 rb_define_method(rb_cStruct, "deconstruct", rb_struct_to_a, 0);
2204 rb_define_method(rb_cStruct, "deconstruct_keys", rb_struct_deconstruct_keys, 1);
2206 rb_cData = rb_define_class("Data", rb_cObject);
2208 rb_undef_method(CLASS_OF(rb_cData), "new");
2209 rb_undef_alloc_func(rb_cData);
2210 rb_define_singleton_method(rb_cData, "define", rb_data_s_def, -1);
2212 #if 0 /* for RDoc */
2213 rb_define_singleton_method(rb_cData, "members", rb_data_s_members_m, 0);
2214 #endif
2216 rb_define_method(rb_cData, "initialize", rb_data_initialize_m, -1);
2217 rb_define_method(rb_cData, "initialize_copy", rb_data_init_copy, 1);
2219 rb_define_method(rb_cData, "==", rb_data_equal, 1);
2220 rb_define_method(rb_cData, "eql?", rb_data_eql, 1);
2221 rb_define_method(rb_cData, "hash", rb_data_hash, 0);
2223 rb_define_method(rb_cData, "inspect", rb_data_inspect, 0);
2224 rb_define_alias(rb_cData, "to_s", "inspect");
2225 rb_define_method(rb_cData, "to_h", rb_data_to_h, 0);
2227 rb_define_method(rb_cData, "members", rb_data_members_m, 0);
2229 rb_define_method(rb_cData, "deconstruct", rb_data_deconstruct, 0);
2230 rb_define_method(rb_cData, "deconstruct_keys", rb_data_deconstruct_keys, 1);
2232 rb_define_method(rb_cData, "with", rb_data_with, -1);
2235 #undef rb_intern
2236 void
2237 Init_Struct(void)
2239 id_members = rb_intern("__members__");
2240 id_back_members = rb_intern("__members_back__");
2241 id_keyword_init = rb_intern("__keyword_init__");
2243 InitVM(Struct);