1 /**********************************************************************
6 created at: Tue Mar 22 18:44:30 JST 1995
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
10 **********************************************************************/
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"
24 /* only for struct[:field] access */
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. */
34 static VALUE rb_cData
;
35 static ID id_members
, id_back_members
, id_keyword_init
;
37 static VALUE
struct_alloc(VALUE
);
40 struct_ivar_get(VALUE c
, ID id
)
43 VALUE ivar
= rb_attr_get(c
, id
);
49 c
= rb_class_superclass(c
);
50 if (c
== rb_cStruct
|| c
== rb_cData
|| !RTEST(c
))
52 RUBY_ASSERT(RB_TYPE_P(c
, T_CLASS
));
53 ivar
= rb_attr_get(c
, id
);
55 return rb_ivar_set(orig
, id
, ivar
);
61 rb_struct_s_keyword_init(VALUE klass
)
63 return struct_ivar_get(klass
, id_keyword_init
);
67 rb_struct_s_members(VALUE klass
)
69 VALUE members
= struct_ivar_get(klass
, id_members
);
72 rb_raise(rb_eTypeError
, "uninitialized struct");
74 if (!RB_TYPE_P(members
, T_ARRAY
)) {
75 rb_raise(rb_eTypeError
, "corrupted struct");
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
));
93 struct_member_pos_ideal(VALUE name
, long mask
)
95 /* (id & (mask/2)) * 2 */
96 return (SYM2ID(name
) >> (ID_SCOPE_SHIFT
- 1)) & mask
;
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
;
107 struct_set_members(VALUE klass
, VALUE
/* frozen hidden array */ members
)
110 const long members_length
= RARRAY_LEN(members
);
112 if (members_length
<= AREF_HASH_THRESHOLD
) {
116 long i
, j
, mask
= 64;
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
);
131 if (!RTEST(RARRAY_AREF(back
, j
))) {
132 rb_ary_store(back
, j
, name
);
133 rb_ary_store(back
, j
+ 1, INT2FIX(i
));
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
);
148 struct_member_pos(VALUE s
, VALUE name
)
150 VALUE back
= struct_ivar_get(rb_obj_class(s
), id_back_members
);
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
)
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
));
181 j
= struct_member_pos_ideal(name
, mask
);
184 VALUE e
= RARRAY_AREF(back
, j
);
186 return FIX2INT(RARRAY_AREF(back
, j
+ 1));
190 j
= struct_member_pos_probe(j
, mask
);
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]
206 rb_struct_s_members_m(VALUE klass
)
208 VALUE members
= rb_struct_s_members(klass
);
210 return rb_ary_dup(members
);
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]
226 rb_struct_members_m(VALUE obj
)
228 return rb_struct_s_members_m(rb_obj_class(obj
));
232 rb_struct_getmember(VALUE obj
, ID id
)
234 VALUE slot
= ID2SYM(id
);
235 int i
= struct_member_pos(obj
, slot
);
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
);
245 rb_struct_modify(VALUE s
)
251 anonymous_struct(VALUE klass
)
255 nstr
= rb_class_new(klass
);
256 rb_make_metaclass(nstr
, RBASIC(klass
)->klass
);
257 rb_class_inherited(klass
, nstr
);
262 new_struct(VALUE name
, VALUE super
)
264 /* old style: should we warn? */
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",
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
));
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
);
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
);
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)");
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
);
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
);
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+.
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
344 rb_struct_s_keyword_init_p(VALUE obj
)
349 #define rb_struct_s_keyword_init_p rb_struct_s_keyword_init
352 setup_struct(VALUE nstr
, VALUE members
)
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
);
369 VALUE off
= LONG2NUM(i
);
371 define_aref_method(nstr
, sym
, off
);
372 define_aset_method(nstr
, ID2SYM(rb_id_attrset(id
)), off
);
379 setup_data(VALUE subclass
, VALUE members
)
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
);
405 rb_struct_alloc_noinit(VALUE klass
)
407 return struct_alloc(klass
);
411 struct_make_members_list(va_list ar
)
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
);
430 struct_define_without_accessor(VALUE outer
, const char *class_name
, VALUE super
, rb_alloc_func_t alloc
, VALUE members
)
436 klass
= rb_define_class_under(outer
, class_name
, super
);
439 klass
= rb_define_class(class_name
, super
);
443 klass
= anonymous_struct(super
);
446 struct_set_members(klass
, members
);
449 rb_define_alloc_func(klass
, alloc
);
452 rb_define_alloc_func(klass
, struct_alloc
);
459 rb_struct_define_without_accessor_under(VALUE outer
, const char *class_name
, VALUE super
, rb_alloc_func_t alloc
, ...)
465 members
= struct_make_members_list(ar
);
468 return struct_define_without_accessor(outer
, class_name
, super
, alloc
, members
);
472 rb_struct_define_without_accessor(const char *class_name
, VALUE super
, rb_alloc_func_t alloc
, ...)
478 members
= struct_make_members_list(ar
);
481 return struct_define_without_accessor(0, class_name
, super
, alloc
, members
);
485 rb_struct_define(const char *name
, ...)
491 ary
= struct_make_members_list(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
);
500 rb_struct_define_under(VALUE outer
, const char *name
, ...)
506 ary
= struct_make_members_list(ar
);
509 return setup_struct(rb_define_class_under(outer
, name
, rb_cStruct
), ary
);
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>
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
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}"
551 * "Hello #{name} at #{address}"
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>
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:
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>
633 * # => #<struct Any foo=1, bar=2>
637 rb_struct_s_def(int argc
, VALUE
*argv
, VALUE klass
)
639 VALUE name
= Qnil
, rest
, keyword_init
= Qnil
;
644 argc
= rb_scan_args(argc
, argv
, "0*:", NULL
, &opt
);
645 if (argc
>= 1 && !SYMBOL_P(argv
[0])) {
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
)) {
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
);
682 st
= anonymous_struct(klass
);
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
);
697 num_members(VALUE klass
)
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
{
712 VALUE unknown_keywords
;
715 static int rb_struct_pos(VALUE s
, VALUE
*name
);
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
);
723 if (NIL_P(args
->unknown_keywords
)) {
724 args
->unknown_keywords
= rb_ary_new();
726 rb_ary_push(args
->unknown_keywords
, key
);
729 rb_struct_modify(args
->self
);
730 RSTRUCT_SET(args
->self
, i
, val
);
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
);
742 rb_mem_clear((VALUE
*)RSTRUCT_CONST_PTR(self
), n
);
746 bool keyword_init
= false;
747 switch (rb_struct_s_keyword_init(klass
)) {
749 if (argc
> 1 || !RB_TYPE_P(argv
[0], T_HASH
)) {
750 rb_error_arity(argc
, 0, 0);
757 if (argc
> 1 || !RB_TYPE_P(argv
[0], T_HASH
)) {
760 keyword_init
= rb_keyword_given_p();
764 struct struct_hash_set_arg arg
;
765 rb_mem_clear((VALUE
*)RSTRUCT_CONST_PTR(self
), n
);
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(", "))));
776 rb_raise(rb_eArgError
, "struct size differs");
778 for (long i
=0; i
<argc
; i
++) {
779 RSTRUCT_SET(self
, i
, argv
[i
]);
782 rb_mem_clear((VALUE
*)RSTRUCT_CONST_PTR(self
)+argc
, n
-argc
);
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
);
798 struct_heap_alloc(VALUE st
, size_t len
)
800 return ALLOC_N(VALUE
, len
);
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
);
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
);
831 rb_struct_alloc(VALUE klass
, VALUE values
)
833 return rb_class_new_instance(RARRAY_LENINT(values
), RARRAY_CONST_PTR(values
), klass
);
837 rb_struct_new(VALUE klass
, ...)
839 VALUE tmpargs
[16], *mem
= tmpargs
;
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
);
854 return rb_class_new_instance(size
, mem
, klass
);
858 struct_enum_size(VALUE s
, VALUE args
, VALUE eobj
)
860 return rb_struct_size(s
);
865 * each {|value| ... } -> self
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 }
877 * "123 Maple, Anytown NC"
880 * Returns an Enumerator if no block is given.
882 * Related: #each_pair.
886 rb_struct_each(VALUE s
)
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
));
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}" }
910 * "name => Joe Smith"
911 * "address => 123 Maple, Anytown NC"
914 * Returns an Enumerator if no block is given.
921 rb_struct_each_pair(VALUE s
)
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
);
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
));
946 inspect_struct(VALUE s
, VALUE prefix
, int recur
)
948 VALUE cname
= rb_class_path(rb_obj_class(s
));
952 char first
= RSTRING_PTR(cname
)[0];
954 if (recur
|| first
!= '#') {
955 rb_str_append(str
, cname
);
958 return rb_str_cat2(str
, ":...>");
961 members
= rb_struct_members(s
);
962 len
= RSTRUCT_LEN(s
);
964 for (i
=0; i
<len
; i
++) {
969 rb_str_cat2(str
, ", ");
971 else if (first
!= '#') {
972 rb_str_cat2(str
, " ");
974 slot
= RARRAY_AREF(members
, i
);
976 if (rb_is_local_id(id
) || rb_is_const_id(id
)) {
977 rb_str_append(str
, rb_id2str(id
));
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
, ">");
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>"
1003 rb_struct_inspect(VALUE s
)
1005 return rb_exec_recursive(inspect_struct
, s
, rb_str_new2("#<struct "));
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.
1022 rb_struct_to_a(VALUE s
)
1024 return rb_ary_new4(RSTRUCT_LEN(s
), RSTRUCT_CONST_PTR(s
));
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)
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.
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
);
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
);
1061 rb_hash_set_pair(h
, rb_yield_values(2, k
, v
));
1063 rb_hash_aset(h
, k
, v
);
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}
1086 rb_struct_deconstruct_keys(VALUE s
, VALUE 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
);
1110 rb_hash_aset(h
, key
, RSTRUCT_GET(s
, i
));
1117 rb_struct_init_copy(VALUE copy
, VALUE s
)
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
));
1134 rb_struct_pos(VALUE s
, VALUE
*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
);
1150 len
= RSTRUCT_LEN(s
);
1153 *name
= LONG2FIX(i
);
1158 else if (len
<= i
) {
1159 *name
= LONG2FIX(i
);
1167 invalid_struct_pos(VALUE s
, VALUE idx
)
1169 if (FIXNUM_P(idx
)) {
1170 long i
= FIX2INT(idx
), len
= RSTRUCT_LEN(s
);
1172 rb_raise(rb_eIndexError
, "offset %ld too small for struct(size:%ld)",
1176 rb_raise(rb_eIndexError
, "offset %ld too large for struct(size:%ld)",
1181 rb_name_err_raise("no member '%1$s' in struct", s
, idx
);
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:
1205 * joe[-2] # => "123 Maple, Anytown NC"
1207 * Raises IndexError if +n+ is out of range.
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
);
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.
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
);
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
));
1263 rb_struct_lookup(VALUE s
, VALUE idx
)
1265 return rb_struct_lookup_default(s
, idx
, Qnil
);
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
);
1277 struct_entry(VALUE s
, long n
)
1279 return rb_struct_aref(s
, LONG2NUM(n
));
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.
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
);
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) }
1338 * With no block given, returns an Enumerator.
1342 rb_struct_select(int argc
, VALUE
*argv
, VALUE s
)
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
));
1360 recursive_equal(VALUE s
, VALUE s2
, int recur
)
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
;
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>.
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
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
);
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.
1426 rb_struct_hash(VALUE s
)
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
));
1443 recursive_eql(VALUE s
, VALUE s2
, int recur
)
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
;
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#==.
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
);
1491 * Returns the number of members.
1493 * Customer = Struct.new(:name, :address, :zip)
1494 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1500 rb_struct_size(VALUE s
)
1502 return LONG2FIX(RSTRUCT_LEN(s
));
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
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
;
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
1587 * return unless other.is_a?(self.class) && other.unit == unit
1588 * amount <=> other.amount
1591 * include Comparable
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
1609 * event.weekdays << 'Sat'
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
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)
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
1641 * Response = Data.define(:body)
1642 * NotFound = Data.define
1643 * # ... implementation
1646 * Now, different kinds of responses from +HTTPFetcher+ would have consistent
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
1663 rb_data_s_def(int argc
, VALUE
*argv
, VALUE klass
)
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
);
1694 rb_data_define(VALUE super
, ...)
1698 va_start(ar
, super
);
1699 ary
= struct_make_members_list(ar
);
1701 if (!super
) super
= rb_cData
;
1702 return setup_data(anonymous_struct(super
), ary
);
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
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 []
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)
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
1755 * Measure = Data.define(:amount, :unit) do
1756 * NONE = Data.define
1758 * def initialize(amount:, unit: NONE.new)
1759 * super(amount: Float(amount), unit:)
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>>
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
);
1777 if (num_members
> 0) {
1778 rb_exc_raise(rb_keyword_error_new("missing", members
));
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
);
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
));
1807 rb_data_init_copy(VALUE copy
, VALUE s
)
1809 copy
= rb_struct_init_copy(copy
, s
);
1810 RB_OBJ_FREEZE_RAW(copy
);
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
1845 rb_data_with(int argc
, const VALUE
*argv
, VALUE self
)
1848 rb_scan_args(argc
, argv
, "0:", &kwargs
);
1849 if (NIL_P(kwargs
)) {
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
);
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">
1878 rb_data_inspect(VALUE s
)
1880 return rb_exec_recursive(inspect_struct
, s
, rb_str_new2("#<data "));
1885 * self == other -> true or false
1887 * Returns +true+ if +other+ is the same class as +self+, and all members are
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
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
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
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
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']
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
1978 #define rb_data_to_h rb_struct_to_h
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
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"]
2008 * in n, 'km' # calls #deconstruct underneath
2009 * puts "It is #{n} kilometers away"
2011 * puts "Don't know how to handle it"
2013 * # prints "It is 10 kilometers away"
2015 * Or, with checking the class, too:
2018 * in Measure(n, 'km')
2019 * puts "It is #{n} kilometers away"
2024 #define rb_data_deconstruct rb_struct_to_a
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}
2040 * in amount:, unit: 'km' # calls #deconstruct_keys underneath
2041 * puts "It is #{amount} kilometers away"
2043 * puts "Don't know how to handle it"
2045 * # prints "It is 10 kilometers away"
2047 * Or, with checking the class, too:
2050 * in Measure(amount:, unit: 'km')
2051 * puts "It is #{amount} kilometers away"
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."
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
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+.
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);
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);
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);
2239 id_members
= rb_intern("__members__");
2240 id_back_members
= rb_intern("__members_back__");
2241 id_keyword_init
= rb_intern("__keyword_init__");