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
);
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_no_pin(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
);
495 st
= anonymous_struct(rb_cStruct
);
498 st
= new_struct(rb_str_new2(name
), rb_cStruct
);
499 rb_vm_register_global_object(st
);
501 return setup_struct(st
, ary
);
505 rb_struct_define_under(VALUE outer
, const char *name
, ...)
511 ary
= struct_make_members_list(ar
);
514 return setup_struct(rb_define_class_id_under(outer
, rb_intern(name
), rb_cStruct
), ary
);
519 * Struct.new(*member_names, keyword_init: nil){|Struct_subclass| ... } -> Struct_subclass
520 * Struct.new(class_name, *member_names, keyword_init: nil){|Struct_subclass| ... } -> Struct_subclass
521 * Struct_subclass.new(*member_names) -> Struct_subclass_instance
522 * Struct_subclass.new(**member_names) -> Struct_subclass_instance
524 * <tt>Struct.new</tt> returns a new subclass of +Struct+. The new subclass:
526 * - May be anonymous, or may have the name given by +class_name+.
527 * - May have members as given by +member_names+.
528 * - May have initialization via ordinary arguments, or via keyword arguments
530 * The new subclass has its own method <tt>::new</tt>; thus:
532 * Foo = Struct.new('Foo', :foo, :bar) # => Struct::Foo
533 * f = Foo.new(0, 1) # => #<struct Struct::Foo foo=0, bar=1>
537 * With string argument +class_name+,
538 * returns a new subclass of +Struct+ named <tt>Struct::<em>class_name</em></tt>:
540 * Foo = Struct.new('Foo', :foo, :bar) # => Struct::Foo
541 * Foo.name # => "Struct::Foo"
542 * Foo.superclass # => Struct
544 * Without string argument +class_name+,
545 * returns a new anonymous subclass of +Struct+:
547 * Struct.new(:foo, :bar).name # => nil
551 * With a block given, the created subclass is yielded to the block:
553 * Customer = Struct.new('Customer', :name, :address) do |new_class|
554 * p "The new subclass is #{new_class}"
556 * "Hello #{name} at #{address}"
558 * end # => Struct::Customer
559 * dave = Customer.new('Dave', '123 Main')
560 * dave # => #<struct Struct::Customer name="Dave", address="123 Main">
561 * dave.greeting # => "Hello Dave at 123 Main"
563 * Output, from <tt>Struct.new</tt>:
565 * "The new subclass is Struct::Customer"
567 * <b>Member Names</b>
569 * Symbol arguments +member_names+
570 * determines the members of the new subclass:
572 * Struct.new(:foo, :bar).members # => [:foo, :bar]
573 * Struct.new('Foo', :foo, :bar).members # => [:foo, :bar]
575 * The new subclass has instance methods corresponding to +member_names+:
577 * Foo = Struct.new('Foo', :foo, :bar)
578 * Foo.instance_methods(false) # => [:foo, :bar, :foo=, :bar=]
579 * f = Foo.new # => #<struct Struct::Foo foo=nil, bar=nil>
584 * f # => #<struct Struct::Foo foo=0, bar=1>
586 * <b>Singleton Methods</b>
588 * A subclass returned by Struct.new has these singleton methods:
590 * - \Method <tt>::new </tt> creates an instance of the subclass:
592 * Foo.new # => #<struct Struct::Foo foo=nil, bar=nil>
593 * Foo.new(0) # => #<struct Struct::Foo foo=0, bar=nil>
594 * Foo.new(0, 1) # => #<struct Struct::Foo foo=0, bar=1>
595 * Foo.new(0, 1, 2) # Raises ArgumentError: struct size differs
597 * # Initialization with keyword arguments:
598 * Foo.new(foo: 0) # => #<struct Struct::Foo foo=0, bar=nil>
599 * Foo.new(foo: 0, bar: 1) # => #<struct Struct::Foo foo=0, bar=1>
600 * Foo.new(foo: 0, bar: 1, baz: 2)
601 * # Raises ArgumentError: unknown keywords: baz
603 * - \Method <tt>:inspect</tt> returns a string representation of the subclass:
608 * - \Method <tt>::members</tt> returns an array of the member names:
610 * Foo.members # => [:foo, :bar]
612 * <b>Keyword Argument</b>
614 * By default, the arguments for initializing an instance of the new subclass
615 * can be both positional and keyword arguments.
617 * Optional keyword argument <tt>keyword_init:</tt> allows to force only one
618 * type of arguments to be accepted:
620 * KeywordsOnly = Struct.new(:foo, :bar, keyword_init: true)
621 * KeywordsOnly.new(bar: 1, foo: 0)
622 * # => #<struct KeywordsOnly foo=0, bar=1>
623 * KeywordsOnly.new(0, 1)
624 * # Raises ArgumentError: wrong number of arguments
626 * PositionalOnly = Struct.new(:foo, :bar, keyword_init: false)
627 * PositionalOnly.new(0, 1)
628 * # => #<struct PositionalOnly foo=0, bar=1>
629 * PositionalOnly.new(bar: 1, foo: 0)
630 * # => #<struct PositionalOnly foo={:foo=>1, :bar=>2}, bar=nil>
631 * # Note that no error is raised, but arguments treated as one hash value
633 * # Same as not providing keyword_init:
634 * Any = Struct.new(:foo, :bar, keyword_init: nil)
635 * Any.new(foo: 1, bar: 2)
636 * # => #<struct Any foo=1, bar=2>
638 * # => #<struct Any foo=1, bar=2>
642 rb_struct_s_def(int argc
, VALUE
*argv
, VALUE klass
)
644 VALUE name
= Qnil
, rest
, keyword_init
= Qnil
;
649 argc
= rb_scan_args(argc
, argv
, "0*:", NULL
, &opt
);
650 if (argc
>= 1 && !SYMBOL_P(argv
[0])) {
657 static ID keyword_ids
[1];
659 if (!keyword_ids
[0]) {
660 keyword_ids
[0] = rb_intern("keyword_init");
662 rb_get_kwargs(opt
, keyword_ids
, 0, 1, &keyword_init
);
663 if (UNDEF_P(keyword_init
)) {
666 else if (RTEST(keyword_init
)) {
667 keyword_init
= Qtrue
;
671 rest
= rb_ident_hash_new();
672 RBASIC_CLEAR_CLASS(rest
);
673 for (i
=0; i
<argc
; i
++) {
674 VALUE mem
= rb_to_symbol(argv
[i
]);
675 if (rb_is_attrset_sym(mem
)) {
676 rb_raise(rb_eArgError
, "invalid struct member: %"PRIsVALUE
, mem
);
678 if (RTEST(rb_hash_has_key(rest
, mem
))) {
679 rb_raise(rb_eArgError
, "duplicate member: %"PRIsVALUE
, mem
);
681 rb_hash_aset(rest
, mem
, Qtrue
);
683 rest
= rb_hash_keys(rest
);
684 RBASIC_CLEAR_CLASS(rest
);
687 st
= anonymous_struct(klass
);
690 st
= new_struct(name
, klass
);
692 setup_struct(st
, rest
);
693 rb_ivar_set(st
, id_keyword_init
, keyword_init
);
694 if (rb_block_given_p()) {
695 rb_mod_module_eval(0, 0, st
);
702 num_members(VALUE klass
)
705 members
= struct_ivar_get(klass
, id_members
);
706 if (!RB_TYPE_P(members
, T_ARRAY
)) {
707 rb_raise(rb_eTypeError
, "broken members");
709 return RARRAY_LEN(members
);
715 struct struct_hash_set_arg
{
717 VALUE unknown_keywords
;
720 static int rb_struct_pos(VALUE s
, VALUE
*name
);
723 struct_hash_set_i(VALUE key
, VALUE val
, VALUE arg
)
725 struct struct_hash_set_arg
*args
= (struct struct_hash_set_arg
*)arg
;
726 int i
= rb_struct_pos(args
->self
, &key
);
728 if (NIL_P(args
->unknown_keywords
)) {
729 args
->unknown_keywords
= rb_ary_new();
731 rb_ary_push(args
->unknown_keywords
, key
);
734 rb_struct_modify(args
->self
);
735 RSTRUCT_SET(args
->self
, i
, val
);
741 rb_struct_initialize_m(int argc
, const VALUE
*argv
, VALUE self
)
743 VALUE klass
= rb_obj_class(self
);
744 rb_struct_modify(self
);
745 long n
= num_members(klass
);
747 rb_mem_clear((VALUE
*)RSTRUCT_CONST_PTR(self
), n
);
751 bool keyword_init
= false;
752 switch (rb_struct_s_keyword_init(klass
)) {
754 if (argc
> 1 || !RB_TYPE_P(argv
[0], T_HASH
)) {
755 rb_error_arity(argc
, 0, 0);
762 if (argc
> 1 || !RB_TYPE_P(argv
[0], T_HASH
)) {
765 keyword_init
= rb_keyword_given_p();
769 struct struct_hash_set_arg arg
;
770 rb_mem_clear((VALUE
*)RSTRUCT_CONST_PTR(self
), n
);
772 arg
.unknown_keywords
= Qnil
;
773 rb_hash_foreach(argv
[0], struct_hash_set_i
, (VALUE
)&arg
);
774 if (arg
.unknown_keywords
!= Qnil
) {
775 rb_raise(rb_eArgError
, "unknown keywords: %s",
776 RSTRING_PTR(rb_ary_join(arg
.unknown_keywords
, rb_str_new2(", "))));
781 rb_raise(rb_eArgError
, "struct size differs");
783 for (long i
=0; i
<argc
; i
++) {
784 RSTRUCT_SET(self
, i
, argv
[i
]);
787 rb_mem_clear((VALUE
*)RSTRUCT_CONST_PTR(self
)+argc
, n
-argc
);
794 rb_struct_initialize(VALUE self
, VALUE values
)
796 rb_struct_initialize_m(RARRAY_LENINT(values
), RARRAY_CONST_PTR(values
), self
);
797 if (rb_obj_is_kind_of(self
, rb_cData
)) OBJ_FREEZE(self
);
803 struct_heap_alloc(VALUE st
, size_t len
)
805 return ALLOC_N(VALUE
, len
);
809 struct_alloc(VALUE klass
)
811 long n
= num_members(klass
);
812 size_t embedded_size
= offsetof(struct RStruct
, as
.ary
) + (sizeof(VALUE
) * n
);
813 VALUE flags
= T_STRUCT
| (RGENGC_WB_PROTECTED_STRUCT
? FL_WB_PROTECTED
: 0);
815 if (n
> 0 && rb_gc_size_allocatable_p(embedded_size
)) {
816 flags
|= n
<< RSTRUCT_EMBED_LEN_SHIFT
;
818 NEWOBJ_OF(st
, struct RStruct
, klass
, flags
, embedded_size
, 0);
820 rb_mem_clear((VALUE
*)st
->as
.ary
, n
);
825 NEWOBJ_OF(st
, struct RStruct
, klass
, flags
, sizeof(struct RStruct
), 0);
827 st
->as
.heap
.ptr
= struct_heap_alloc((VALUE
)st
, n
);
828 rb_mem_clear((VALUE
*)st
->as
.heap
.ptr
, n
);
836 rb_struct_alloc(VALUE klass
, VALUE values
)
838 return rb_class_new_instance(RARRAY_LENINT(values
), RARRAY_CONST_PTR(values
), klass
);
842 rb_struct_new(VALUE klass
, ...)
844 VALUE tmpargs
[16], *mem
= tmpargs
;
848 size
= rb_long2int(num_members(klass
));
849 if (size
> numberof(tmpargs
)) {
850 tmpargs
[0] = rb_ary_hidden_new(size
);
851 mem
= RARRAY_PTR(tmpargs
[0]);
853 va_start(args
, klass
);
854 for (i
=0; i
<size
; i
++) {
855 mem
[i
] = va_arg(args
, VALUE
);
859 return rb_class_new_instance(size
, mem
, klass
);
863 struct_enum_size(VALUE s
, VALUE args
, VALUE eobj
)
865 return rb_struct_size(s
);
870 * each {|value| ... } -> self
873 * Calls the given block with the value of each member; returns +self+:
875 * Customer = Struct.new(:name, :address, :zip)
876 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
877 * joe.each {|value| p value }
882 * "123 Maple, Anytown NC"
885 * Returns an Enumerator if no block is given.
887 * Related: #each_pair.
891 rb_struct_each(VALUE s
)
895 RETURN_SIZED_ENUMERATOR(s
, 0, 0, struct_enum_size
);
896 for (i
=0; i
<RSTRUCT_LEN(s
); i
++) {
897 rb_yield(RSTRUCT_GET(s
, i
));
904 * each_pair {|(name, value)| ... } -> self
905 * each_pair -> enumerator
907 * Calls the given block with each member name/value pair; returns +self+:
909 * Customer = Struct.new(:name, :address, :zip) # => Customer
910 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
911 * joe.each_pair {|(name, value)| p "#{name} => #{value}" }
915 * "name => Joe Smith"
916 * "address => 123 Maple, Anytown NC"
919 * Returns an Enumerator if no block is given.
926 rb_struct_each_pair(VALUE s
)
931 RETURN_SIZED_ENUMERATOR(s
, 0, 0, struct_enum_size
);
932 members
= rb_struct_members(s
);
933 if (rb_block_pair_yield_optimizable()) {
934 for (i
=0; i
<RSTRUCT_LEN(s
); i
++) {
935 VALUE key
= rb_ary_entry(members
, i
);
936 VALUE value
= RSTRUCT_GET(s
, i
);
937 rb_yield_values(2, key
, value
);
941 for (i
=0; i
<RSTRUCT_LEN(s
); i
++) {
942 VALUE key
= rb_ary_entry(members
, i
);
943 VALUE value
= RSTRUCT_GET(s
, i
);
944 rb_yield(rb_assoc_new(key
, value
));
951 inspect_struct(VALUE s
, VALUE prefix
, int recur
)
953 VALUE cname
= rb_class_path(rb_obj_class(s
));
957 char first
= RSTRING_PTR(cname
)[0];
959 if (recur
|| first
!= '#') {
960 rb_str_append(str
, cname
);
963 return rb_str_cat2(str
, ":...>");
966 members
= rb_struct_members(s
);
967 len
= RSTRUCT_LEN(s
);
969 for (i
=0; i
<len
; i
++) {
974 rb_str_cat2(str
, ", ");
976 else if (first
!= '#') {
977 rb_str_cat2(str
, " ");
979 slot
= RARRAY_AREF(members
, i
);
981 if (rb_is_local_id(id
) || rb_is_const_id(id
)) {
982 rb_str_append(str
, rb_id2str(id
));
985 rb_str_append(str
, rb_inspect(slot
));
987 rb_str_cat2(str
, "=");
988 rb_str_append(str
, rb_inspect(RSTRUCT_GET(s
, i
)));
990 rb_str_cat2(str
, ">");
999 * Returns a string representation of +self+:
1001 * Customer = Struct.new(:name, :address, :zip) # => Customer
1002 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1003 * joe.inspect # => "#<struct Customer name=\"Joe Smith\", address=\"123 Maple, Anytown NC\", zip=12345>"
1008 rb_struct_inspect(VALUE s
)
1010 return rb_exec_recursive(inspect_struct
, s
, rb_str_new2("#<struct "));
1017 * Returns the values in +self+ as an array:
1019 * Customer = Struct.new(:name, :address, :zip)
1020 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1021 * joe.to_a # => ["Joe Smith", "123 Maple, Anytown NC", 12345]
1023 * Related: #members.
1027 rb_struct_to_a(VALUE s
)
1029 return rb_ary_new4(RSTRUCT_LEN(s
), RSTRUCT_CONST_PTR(s
));
1035 * to_h {|name, value| ... } -> hash
1037 * Returns a hash containing the name and value for each member:
1039 * Customer = Struct.new(:name, :address, :zip)
1040 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1042 * h # => {:name=>"Joe Smith", :address=>"123 Maple, Anytown NC", :zip=>12345}
1044 * If a block is given, it is called with each name/value pair;
1045 * the block should return a 2-element array whose elements will become
1046 * a key/value pair in the returned hash:
1048 * h = joe.to_h{|name, value| [name.upcase, value.to_s.upcase]}
1049 * h # => {:NAME=>"JOE SMITH", :ADDRESS=>"123 MAPLE, ANYTOWN NC", :ZIP=>"12345"}
1051 * Raises ArgumentError if the block returns an inappropriate value.
1056 rb_struct_to_h(VALUE s
)
1058 VALUE h
= rb_hash_new_with_size(RSTRUCT_LEN(s
));
1059 VALUE members
= rb_struct_members(s
);
1061 int block_given
= rb_block_given_p();
1063 for (i
=0; i
<RSTRUCT_LEN(s
); i
++) {
1064 VALUE k
= rb_ary_entry(members
, i
), v
= RSTRUCT_GET(s
, i
);
1066 rb_hash_set_pair(h
, rb_yield_values(2, k
, v
));
1068 rb_hash_aset(h
, k
, v
);
1075 * deconstruct_keys(array_of_names) -> hash
1077 * Returns a hash of the name/value pairs for the given member names.
1079 * Customer = Struct.new(:name, :address, :zip)
1080 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1081 * h = joe.deconstruct_keys([:zip, :address])
1082 * h # => {:zip=>12345, :address=>"123 Maple, Anytown NC"}
1084 * Returns all names and values if +array_of_names+ is +nil+:
1086 * h = joe.deconstruct_keys(nil)
1087 * h # => {:name=>"Joseph Smith, Jr.", :address=>"123 Maple, Anytown NC", :zip=>12345}
1091 rb_struct_deconstruct_keys(VALUE s
, VALUE keys
)
1097 return rb_struct_to_h(s
);
1099 if (UNLIKELY(!RB_TYPE_P(keys
, T_ARRAY
))) {
1100 rb_raise(rb_eTypeError
,
1101 "wrong argument type %"PRIsVALUE
" (expected Array or nil)",
1102 rb_obj_class(keys
));
1105 if (RSTRUCT_LEN(s
) < RARRAY_LEN(keys
)) {
1106 return rb_hash_new_with_size(0);
1108 h
= rb_hash_new_with_size(RARRAY_LEN(keys
));
1109 for (i
=0; i
<RARRAY_LEN(keys
); i
++) {
1110 VALUE key
= RARRAY_AREF(keys
, i
);
1111 int i
= rb_struct_pos(s
, &key
);
1115 rb_hash_aset(h
, key
, RSTRUCT_GET(s
, i
));
1122 rb_struct_init_copy(VALUE copy
, VALUE s
)
1126 if (!OBJ_INIT_COPY(copy
, s
)) return copy
;
1127 if (RSTRUCT_LEN(copy
) != RSTRUCT_LEN(s
)) {
1128 rb_raise(rb_eTypeError
, "struct size mismatch");
1131 for (i
=0, len
=RSTRUCT_LEN(copy
); i
<len
; i
++) {
1132 RSTRUCT_SET(copy
, i
, RSTRUCT_GET(s
, i
));
1139 rb_struct_pos(VALUE s
, VALUE
*name
)
1144 if (SYMBOL_P(idx
)) {
1145 return struct_member_pos(s
, idx
);
1147 else if (RB_TYPE_P(idx
, T_STRING
)) {
1148 idx
= rb_check_symbol(name
);
1149 if (NIL_P(idx
)) return -1;
1150 return struct_member_pos(s
, idx
);
1155 len
= RSTRUCT_LEN(s
);
1158 *name
= LONG2FIX(i
);
1163 else if (len
<= i
) {
1164 *name
= LONG2FIX(i
);
1172 invalid_struct_pos(VALUE s
, VALUE idx
)
1174 if (FIXNUM_P(idx
)) {
1175 long i
= FIX2INT(idx
), len
= RSTRUCT_LEN(s
);
1177 rb_raise(rb_eIndexError
, "offset %ld too small for struct(size:%ld)",
1181 rb_raise(rb_eIndexError
, "offset %ld too large for struct(size:%ld)",
1186 rb_name_err_raise("no member '%1$s' in struct", s
, idx
);
1192 * struct[name] -> object
1193 * struct[n] -> object
1195 * Returns a value from +self+.
1197 * With symbol or string argument +name+ given, returns the value for the named member:
1199 * Customer = Struct.new(:name, :address, :zip)
1200 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1201 * joe[:zip] # => 12345
1203 * Raises NameError if +name+ is not the name of a member.
1205 * With integer argument +n+ given, returns <tt>self.values[n]</tt>
1206 * if +n+ is in range;
1207 * see Array@Array+Indexes:
1210 * joe[-2] # => "123 Maple, Anytown NC"
1212 * Raises IndexError if +n+ is out of range.
1217 rb_struct_aref(VALUE s
, VALUE idx
)
1219 int i
= rb_struct_pos(s
, &idx
);
1220 if (i
< 0) invalid_struct_pos(s
, idx
);
1221 return RSTRUCT_GET(s
, i
);
1226 * struct[name] = value -> value
1227 * struct[n] = value -> value
1229 * Assigns a value to a member.
1231 * With symbol or string argument +name+ given, assigns the given +value+
1232 * to the named member; returns +value+:
1234 * Customer = Struct.new(:name, :address, :zip)
1235 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1236 * joe[:zip] = 54321 # => 54321
1237 * joe # => #<struct Customer name="Joe Smith", address="123 Maple, Anytown NC", zip=54321>
1239 * Raises NameError if +name+ is not the name of a member.
1241 * With integer argument +n+ given, assigns the given +value+
1242 * to the +n+-th member if +n+ is in range;
1243 * see Array@Array+Indexes:
1245 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1246 * joe[2] = 54321 # => 54321
1247 * joe[-3] = 'Joseph Smith' # => "Joseph Smith"
1248 * joe # => #<struct Customer name="Joseph Smith", address="123 Maple, Anytown NC", zip=54321>
1250 * Raises IndexError if +n+ is out of range.
1255 rb_struct_aset(VALUE s
, VALUE idx
, VALUE val
)
1257 int i
= rb_struct_pos(s
, &idx
);
1258 if (i
< 0) invalid_struct_pos(s
, idx
);
1259 rb_struct_modify(s
);
1260 RSTRUCT_SET(s
, i
, val
);
1264 FUNC_MINIMIZED(VALUE
rb_struct_lookup(VALUE s
, VALUE idx
));
1265 NOINLINE(static VALUE
rb_struct_lookup_default(VALUE s
, VALUE idx
, VALUE notfound
));
1268 rb_struct_lookup(VALUE s
, VALUE idx
)
1270 return rb_struct_lookup_default(s
, idx
, Qnil
);
1274 rb_struct_lookup_default(VALUE s
, VALUE idx
, VALUE notfound
)
1276 int i
= rb_struct_pos(s
, &idx
);
1277 if (i
< 0) return notfound
;
1278 return RSTRUCT_GET(s
, i
);
1282 struct_entry(VALUE s
, long n
)
1284 return rb_struct_aref(s
, LONG2NUM(n
));
1289 * values_at(*integers) -> array
1290 * values_at(integer_range) -> array
1292 * Returns an array of values from +self+.
1294 * With integer arguments +integers+ given,
1295 * returns an array containing each value given by one of +integers+:
1297 * Customer = Struct.new(:name, :address, :zip)
1298 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1299 * joe.values_at(0, 2) # => ["Joe Smith", 12345]
1300 * joe.values_at(2, 0) # => [12345, "Joe Smith"]
1301 * joe.values_at(2, 1, 0) # => [12345, "123 Maple, Anytown NC", "Joe Smith"]
1302 * joe.values_at(0, -3) # => ["Joe Smith", "Joe Smith"]
1304 * Raises IndexError if any of +integers+ is out of range;
1305 * see Array@Array+Indexes.
1307 * With integer range argument +integer_range+ given,
1308 * returns an array containing each value given by the elements of the range;
1309 * fills with +nil+ values for range elements larger than the structure:
1311 * joe.values_at(0..2)
1312 * # => ["Joe Smith", "123 Maple, Anytown NC", 12345]
1313 * joe.values_at(-3..-1)
1314 * # => ["Joe Smith", "123 Maple, Anytown NC", 12345]
1315 * joe.values_at(1..4) # => ["123 Maple, Anytown NC", 12345, nil, nil]
1317 * Raises RangeError if any element of the range is negative and out of range;
1318 * see Array@Array+Indexes.
1323 rb_struct_values_at(int argc
, VALUE
*argv
, VALUE s
)
1325 return rb_get_values_at(s
, RSTRUCT_LEN(s
), argc
, argv
, struct_entry
);
1330 * select {|value| ... } -> array
1331 * select -> enumerator
1333 * With a block given, returns an array of values from +self+
1334 * for which the block returns a truthy value:
1336 * Customer = Struct.new(:name, :address, :zip)
1337 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1338 * a = joe.select {|value| value.is_a?(String) }
1339 * a # => ["Joe Smith", "123 Maple, Anytown NC"]
1340 * a = joe.select {|value| value.is_a?(Integer) }
1343 * With no block given, returns an Enumerator.
1347 rb_struct_select(int argc
, VALUE
*argv
, VALUE s
)
1352 rb_check_arity(argc
, 0, 0);
1353 RETURN_SIZED_ENUMERATOR(s
, 0, 0, struct_enum_size
);
1354 result
= rb_ary_new();
1355 for (i
= 0; i
< RSTRUCT_LEN(s
); i
++) {
1356 if (RTEST(rb_yield(RSTRUCT_GET(s
, i
)))) {
1357 rb_ary_push(result
, RSTRUCT_GET(s
, i
));
1365 recursive_equal(VALUE s
, VALUE s2
, int recur
)
1369 if (recur
) return Qtrue
; /* Subtle! */
1370 len
= RSTRUCT_LEN(s
);
1371 for (i
=0; i
<len
; i
++) {
1372 if (!rb_equal(RSTRUCT_GET(s
, i
), RSTRUCT_GET(s2
, i
))) return Qfalse
;
1380 * self == other -> true or false
1382 * Returns +true+ if and only if the following are true; otherwise returns +false+:
1384 * - <tt>other.class == self.class</tt>.
1385 * - For each member name +name+, <tt>other.name == self.name</tt>.
1389 * Customer = Struct.new(:name, :address, :zip)
1390 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1391 * joe_jr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1392 * joe_jr == joe # => true
1393 * joe_jr[:name] = 'Joe Smith, Jr.'
1394 * # => "Joe Smith, Jr."
1395 * joe_jr == joe # => false
1399 rb_struct_equal(VALUE s
, VALUE s2
)
1401 if (s
== s2
) return Qtrue
;
1402 if (!RB_TYPE_P(s2
, T_STRUCT
)) return Qfalse
;
1403 if (rb_obj_class(s
) != rb_obj_class(s2
)) return Qfalse
;
1404 if (RSTRUCT_LEN(s
) != RSTRUCT_LEN(s2
)) {
1405 rb_bug("inconsistent struct"); /* should never happen */
1408 return rb_exec_recursive_paired(recursive_equal
, s
, s2
, s2
);
1415 * Returns the integer hash value for +self+.
1417 * Two structs of the same class and with the same content
1418 * will have the same hash code (and will compare using Struct#eql?):
1420 * Customer = Struct.new(:name, :address, :zip)
1421 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1422 * joe_jr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1423 * joe.hash == joe_jr.hash # => true
1424 * joe_jr[:name] = 'Joe Smith, Jr.'
1425 * joe.hash == joe_jr.hash # => false
1427 * Related: Object#hash.
1431 rb_struct_hash(VALUE s
)
1437 h
= rb_hash_start(rb_hash(rb_obj_class(s
)));
1438 len
= RSTRUCT_LEN(s
);
1439 for (i
= 0; i
< len
; i
++) {
1440 n
= rb_hash(RSTRUCT_GET(s
, i
));
1441 h
= rb_hash_uint(h
, NUM2LONG(n
));
1448 recursive_eql(VALUE s
, VALUE s2
, int recur
)
1452 if (recur
) return Qtrue
; /* Subtle! */
1453 len
= RSTRUCT_LEN(s
);
1454 for (i
=0; i
<len
; i
++) {
1455 if (!rb_eql(RSTRUCT_GET(s
, i
), RSTRUCT_GET(s2
, i
))) return Qfalse
;
1462 * eql?(other) -> true or false
1464 * Returns +true+ if and only if the following are true; otherwise returns +false+:
1466 * - <tt>other.class == self.class</tt>.
1467 * - For each member name +name+, <tt>other.name.eql?(self.name)</tt>.
1469 * Customer = Struct.new(:name, :address, :zip)
1470 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1471 * joe_jr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1472 * joe_jr.eql?(joe) # => true
1473 * joe_jr[:name] = 'Joe Smith, Jr.'
1474 * joe_jr.eql?(joe) # => false
1476 * Related: Object#==.
1480 rb_struct_eql(VALUE s
, VALUE s2
)
1482 if (s
== s2
) return Qtrue
;
1483 if (!RB_TYPE_P(s2
, T_STRUCT
)) return Qfalse
;
1484 if (rb_obj_class(s
) != rb_obj_class(s2
)) return Qfalse
;
1485 if (RSTRUCT_LEN(s
) != RSTRUCT_LEN(s2
)) {
1486 rb_bug("inconsistent struct"); /* should never happen */
1489 return rb_exec_recursive_paired(recursive_eql
, s
, s2
, s2
);
1496 * Returns the number of members.
1498 * Customer = Struct.new(:name, :address, :zip)
1499 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1505 rb_struct_size(VALUE s
)
1507 return LONG2FIX(RSTRUCT_LEN(s
));
1512 * dig(name, *identifiers) -> object
1513 * dig(n, *identifiers) -> object
1515 * Finds and returns an object among nested objects.
1516 * The nested objects may be instances of various classes.
1517 * See {Dig Methods}[rdoc-ref:dig_methods.rdoc].
1520 * Given symbol or string argument +name+,
1521 * returns the object that is specified by +name+ and +identifiers+:
1523 * Foo = Struct.new(:a)
1524 * f = Foo.new(Foo.new({b: [1, 2, 3]}))
1525 * f.dig(:a) # => #<struct Foo a={:b=>[1, 2, 3]}>
1526 * f.dig(:a, :a) # => {:b=>[1, 2, 3]}
1527 * f.dig(:a, :a, :b) # => [1, 2, 3]
1528 * f.dig(:a, :a, :b, 0) # => 1
1529 * f.dig(:b, 0) # => nil
1531 * Given integer argument +n+,
1532 * returns the object that is specified by +n+ and +identifiers+:
1534 * f.dig(0) # => #<struct Foo a={:b=>[1, 2, 3]}>
1535 * f.dig(0, 0) # => {:b=>[1, 2, 3]}
1536 * f.dig(0, 0, :b) # => [1, 2, 3]
1537 * f.dig(0, 0, :b, 0) # => 1
1538 * f.dig(:b, 0) # => nil
1543 rb_struct_dig(int argc
, VALUE
*argv
, VALUE self
)
1545 rb_check_arity(argc
, 1, UNLIMITED_ARGUMENTS
);
1546 self
= rb_struct_lookup(self
, *argv
);
1547 if (!--argc
) return self
;
1549 return rb_obj_dig(argc
, argv
, self
, Qnil
);
1553 * Document-class: Data
1555 * \Class \Data provides a convenient way to define simple classes
1556 * for value-alike objects.
1558 * The simplest example of usage:
1560 * Measure = Data.define(:amount, :unit)
1562 * # Positional arguments constructor is provided
1563 * distance = Measure.new(100, 'km')
1564 * #=> #<data Measure amount=100, unit="km">
1566 * # Keyword arguments constructor is provided
1567 * weight = Measure.new(amount: 50, unit: 'kg')
1568 * #=> #<data Measure amount=50, unit="kg">
1570 * # Alternative form to construct an object:
1571 * speed = Measure[10, 'mPh']
1572 * #=> #<data Measure amount=10, unit="mPh">
1574 * # Works with keyword arguments, too:
1575 * area = Measure[amount: 1.5, unit: 'm^2']
1576 * #=> #<data Measure amount=1.5, unit="m^2">
1578 * # Argument accessors are provided:
1579 * distance.amount #=> 100
1580 * distance.unit #=> "km"
1582 * Constructed object also has a reasonable definitions of #==
1583 * operator, #to_h hash conversion, and #deconstruct / #deconstruct_keys
1584 * to be used in pattern matching.
1586 * ::define method accepts an optional block and evaluates it in
1587 * the context of the newly defined class. That allows to define
1588 * additional methods:
1590 * Measure = Data.define(:amount, :unit) do
1592 * return unless other.is_a?(self.class) && other.unit == unit
1593 * amount <=> other.amount
1596 * include Comparable
1599 * Measure[3, 'm'] < Measure[5, 'm'] #=> true
1600 * Measure[3, 'm'] < Measure[5, 'kg']
1601 * # comparison of Measure with Measure failed (ArgumentError)
1603 * Data provides no member writers, or enumerators: it is meant
1604 * to be a storage for immutable atomic values. But note that
1605 * if some of data members is of a mutable class, Data does no additional
1606 * immutability enforcement:
1608 * Event = Data.define(:time, :weekdays)
1609 * event = Event.new('18:00', %w[Tue Wed Fri])
1610 * #=> #<data Event time="18:00", weekdays=["Tue", "Wed", "Fri"]>
1612 * # There is no #time= or #weekdays= accessors, but changes are
1614 * event.weekdays << 'Sat'
1616 * #=> #<data Event time="18:00", weekdays=["Tue", "Wed", "Fri", "Sat"]>
1618 * See also Struct, which is a similar concept, but has more
1619 * container-alike API, allowing to change contents of the object
1625 * define(*symbols) -> class
1627 * Defines a new \Data class.
1629 * measure = Data.define(:amount, :unit)
1630 * #=> #<Class:0x00007f70c6868498>
1631 * measure.new(1, 'km')
1632 * #=> #<data amount=1, unit="km">
1634 * # It you store the new class in the constant, it will
1635 * # affect #inspect and will be more natural to use:
1636 * Measure = Data.define(:amount, :unit)
1638 * Measure.new(1, 'km')
1639 * #=> #<data Measure amount=1, unit="km">
1642 * Note that member-less \Data is acceptable and might be a useful technique
1643 * for defining several homogenous data classes, like
1646 * Response = Data.define(:body)
1647 * NotFound = Data.define
1648 * # ... implementation
1651 * Now, different kinds of responses from +HTTPFetcher+ would have consistent
1654 * #<data HTTPFetcher::Response body="<html...">
1655 * #<data HTTPFetcher::NotFound>
1657 * And are convenient to use in pattern matching:
1659 * case fetcher.get(url)
1660 * in HTTPFetcher::Response(body)
1661 * # process body variable
1662 * in HTTPFetcher::NotFound
1663 * # handle not found case
1668 rb_data_s_def(int argc
, VALUE
*argv
, VALUE klass
)
1674 rest
= rb_ident_hash_new();
1675 RBASIC_CLEAR_CLASS(rest
);
1676 for (i
=0; i
<argc
; i
++) {
1677 VALUE mem
= rb_to_symbol(argv
[i
]);
1678 if (rb_is_attrset_sym(mem
)) {
1679 rb_raise(rb_eArgError
, "invalid data member: %"PRIsVALUE
, mem
);
1681 if (RTEST(rb_hash_has_key(rest
, mem
))) {
1682 rb_raise(rb_eArgError
, "duplicate member: %"PRIsVALUE
, mem
);
1684 rb_hash_aset(rest
, mem
, Qtrue
);
1686 rest
= rb_hash_keys(rest
);
1687 RBASIC_CLEAR_CLASS(rest
);
1689 data_class
= anonymous_struct(klass
);
1690 setup_data(data_class
, rest
);
1691 if (rb_block_given_p()) {
1692 rb_mod_module_eval(0, 0, data_class
);
1699 rb_data_define(VALUE super
, ...)
1703 va_start(ar
, super
);
1704 ary
= struct_make_members_list(ar
);
1706 if (!super
) super
= rb_cData
;
1707 VALUE klass
= setup_data(anonymous_struct(super
), ary
);
1708 rb_vm_register_global_object(klass
);
1714 * DataClass::members -> array_of_symbols
1716 * Returns an array of member names of the data class:
1718 * Measure = Data.define(:amount, :unit)
1719 * Measure.members # => [:amount, :unit]
1723 #define rb_data_s_members_m rb_struct_s_members_m
1728 * new(*args) -> instance
1729 * new(**kwargs) -> instance
1730 * ::[](*args) -> instance
1731 * ::[](**kwargs) -> instance
1733 * Constructors for classes defined with ::define accept both positional and
1734 * keyword arguments.
1736 * Measure = Data.define(:amount, :unit)
1738 * Measure.new(1, 'km')
1739 * #=> #<data Measure amount=1, unit="km">
1740 * Measure.new(amount: 1, unit: 'km')
1741 * #=> #<data Measure amount=1, unit="km">
1743 * # Alternative shorter initialization with []
1745 * #=> #<data Measure amount=1, unit="km">
1746 * Measure[amount: 1, unit: 'km']
1747 * #=> #<data Measure amount=1, unit="km">
1749 * All arguments are mandatory (unlike Struct), and converted to keyword arguments:
1751 * Measure.new(amount: 1)
1752 * # in `initialize': missing keyword: :unit (ArgumentError)
1755 * # in `initialize': missing keyword: :unit (ArgumentError)
1757 * Note that <tt>Measure#initialize</tt> always receives keyword arguments, and that
1758 * mandatory arguments are checked in +initialize+, not in +new+. This can be
1759 * important for redefining initialize in order to convert arguments or provide
1762 * Measure = Data.define(:amount, :unit) do
1763 * NONE = Data.define
1765 * def initialize(amount:, unit: NONE.new)
1766 * super(amount: Float(amount), unit:)
1770 * Measure.new('10', 'km') # => #<data Measure amount=10.0, unit="km">
1771 * Measure.new(10_000) # => #<data Measure amount=10000.0, unit=#<data NONE>>
1776 rb_data_initialize_m(int argc
, const VALUE
*argv
, VALUE self
)
1778 VALUE klass
= rb_obj_class(self
);
1779 rb_struct_modify(self
);
1780 VALUE members
= struct_ivar_get(klass
, id_members
);
1781 size_t num_members
= RARRAY_LEN(members
);
1784 if (num_members
> 0) {
1785 rb_exc_raise(rb_keyword_error_new("missing", members
));
1789 if (argc
> 1 || !RB_TYPE_P(argv
[0], T_HASH
)) {
1790 rb_error_arity(argc
, 0, 0);
1793 if (RHASH_SIZE(argv
[0]) < num_members
) {
1794 VALUE missing
= rb_ary_diff(members
, rb_hash_keys(argv
[0]));
1795 rb_exc_raise(rb_keyword_error_new("missing", missing
));
1798 struct struct_hash_set_arg arg
;
1799 rb_mem_clear((VALUE
*)RSTRUCT_CONST_PTR(self
), num_members
);
1801 arg
.unknown_keywords
= Qnil
;
1802 rb_hash_foreach(argv
[0], struct_hash_set_i
, (VALUE
)&arg
);
1803 // Freeze early before potentially raising, so that we don't leave an
1804 // unfrozen copy on the heap, which could get exposed via ObjectSpace.
1806 if (arg
.unknown_keywords
!= Qnil
) {
1807 rb_exc_raise(rb_keyword_error_new("unknown", arg
.unknown_keywords
));
1814 rb_data_init_copy(VALUE copy
, VALUE s
)
1816 copy
= rb_struct_init_copy(copy
, s
);
1817 RB_OBJ_FREEZE(copy
);
1823 * with(**kwargs) -> instance
1825 * Returns a shallow copy of +self+ --- the instance variables of
1826 * +self+ are copied, but not the objects they reference.
1828 * If the method is supplied any keyword arguments, the copy will
1829 * be created with the respective field values updated to use the
1830 * supplied keyword argument values. Note that it is an error to
1831 * supply a keyword that the Data class does not have as a member.
1833 * Point = Data.define(:x, :y)
1835 * origin = Point.new(x: 0, y: 0)
1837 * up = origin.with(x: 1)
1838 * right = origin.with(y: 1)
1839 * up_and_right = up.with(y: 1)
1841 * p origin # #<data Point x=0, y=0>
1842 * p up # #<data Point x=1, y=0>
1843 * p right # #<data Point x=0, y=1>
1844 * p up_and_right # #<data Point x=1, y=1>
1846 * out = origin.with(z: 1) # ArgumentError: unknown keyword: :z
1847 * some_point = origin.with(1, 2) # ArgumentError: expected keyword arguments, got positional arguments
1852 rb_data_with(int argc
, const VALUE
*argv
, VALUE self
)
1855 rb_scan_args(argc
, argv
, "0:", &kwargs
);
1856 if (NIL_P(kwargs
)) {
1860 VALUE h
= rb_struct_to_h(self
);
1861 rb_hash_update_by(h
, kwargs
, 0);
1862 return rb_class_new_instance_kw(1, &h
, rb_obj_class(self
), TRUE
);
1870 * Returns a string representation of +self+:
1872 * Measure = Data.define(:amount, :unit)
1874 * distance = Measure[10, 'km']
1876 * p distance # uses #inspect underneath
1877 * #<data Measure amount=10, unit="km">
1879 * puts distance # uses #to_s underneath, same representation
1880 * #<data Measure amount=10, unit="km">
1885 rb_data_inspect(VALUE s
)
1887 return rb_exec_recursive(inspect_struct
, s
, rb_str_new2("#<data "));
1892 * self == other -> true or false
1894 * Returns +true+ if +other+ is the same class as +self+, and all members are
1899 * Measure = Data.define(:amount, :unit)
1901 * Measure[1, 'km'] == Measure[1, 'km'] #=> true
1902 * Measure[1, 'km'] == Measure[2, 'km'] #=> false
1903 * Measure[1, 'km'] == Measure[1, 'm'] #=> false
1905 * Measurement = Data.define(:amount, :unit)
1906 * # Even though Measurement and Measure have the same "shape"
1907 * # their instances are never equal
1908 * Measure[1, 'km'] == Measurement[1, 'km'] #=> false
1911 #define rb_data_equal rb_struct_equal
1915 * self.eql?(other) -> true or false
1917 * Equality check that is used when two items of data are keys of a Hash.
1919 * The subtle difference with #== is that members are also compared with their
1920 * #eql? method, which might be important in some cases:
1922 * Measure = Data.define(:amount, :unit)
1924 * Measure[1, 'km'] == Measure[1.0, 'km'] #=> true, they are equal as values
1926 * Measure[1, 'km'].eql? Measure[1.0, 'km'] #=> false, they represent different hash keys
1928 * See also Object#eql? for further explanations of the method usage.
1931 #define rb_data_eql rb_struct_eql
1937 * Redefines Object#hash (used to distinguish objects as Hash keys) so that
1938 * data objects of the same class with same content would have the same +hash+
1939 * value, and represented the same Hash key.
1941 * Measure = Data.define(:amount, :unit)
1943 * Measure[1, 'km'].hash == Measure[1, 'km'].hash #=> true
1944 * Measure[1, 'km'].hash == Measure[10, 'km'].hash #=> false
1945 * Measure[1, 'km'].hash == Measure[1, 'm'].hash #=> false
1946 * Measure[1, 'km'].hash == Measure[1.0, 'km'].hash #=> false
1948 * # Structurally similar data class, but shouldn't be considered
1949 * # the same hash key
1950 * Measurement = Data.define(:amount, :unit)
1952 * Measure[1, 'km'].hash == Measurement[1, 'km'].hash #=> false
1955 #define rb_data_hash rb_struct_hash
1960 * to_h {|name, value| ... } -> hash
1962 * Returns Hash representation of the data object.
1964 * Measure = Data.define(:amount, :unit)
1965 * distance = Measure[10, 'km']
1968 * #=> {:amount=>10, :unit=>"km"}
1970 * Like Enumerable#to_h, if the block is provided, it is expected to
1971 * produce key-value pairs to construct a hash:
1974 * distance.to_h { |name, val| [name.to_s, val.to_s] }
1975 * #=> {"amount"=>"10", "unit"=>"km"}
1977 * Note that there is a useful symmetry between #to_h and #initialize:
1979 * distance2 = Measure.new(**distance.to_h)
1980 * #=> #<data Measure amount=10, unit="km">
1981 * distance2 == distance
1985 #define rb_data_to_h rb_struct_to_h
1989 * members -> array_of_symbols
1991 * Returns the member names from +self+ as an array:
1993 * Measure = Data.define(:amount, :unit)
1994 * distance = Measure[10, 'km']
1996 * distance.members #=> [:amount, :unit]
2000 #define rb_data_members_m rb_struct_members_m
2004 * deconstruct -> array
2006 * Returns the values in +self+ as an array, to use in pattern matching:
2008 * Measure = Data.define(:amount, :unit)
2010 * distance = Measure[10, 'km']
2011 * distance.deconstruct #=> [10, "km"]
2015 * in n, 'km' # calls #deconstruct underneath
2016 * puts "It is #{n} kilometers away"
2018 * puts "Don't know how to handle it"
2020 * # prints "It is 10 kilometers away"
2022 * Or, with checking the class, too:
2025 * in Measure(n, 'km')
2026 * puts "It is #{n} kilometers away"
2031 #define rb_data_deconstruct rb_struct_to_a
2035 * deconstruct_keys(array_of_names_or_nil) -> hash
2037 * Returns a hash of the name/value pairs, to use in pattern matching.
2039 * Measure = Data.define(:amount, :unit)
2041 * distance = Measure[10, 'km']
2042 * distance.deconstruct_keys(nil) #=> {:amount=>10, :unit=>"km"}
2043 * distance.deconstruct_keys([:amount]) #=> {:amount=>10}
2047 * in amount:, unit: 'km' # calls #deconstruct_keys underneath
2048 * puts "It is #{amount} kilometers away"
2050 * puts "Don't know how to handle it"
2052 * # prints "It is 10 kilometers away"
2054 * Or, with checking the class, too:
2057 * in Measure(amount:, unit: 'km')
2058 * puts "It is #{amount} kilometers away"
2063 #define rb_data_deconstruct_keys rb_struct_deconstruct_keys
2066 * Document-class: Struct
2068 * \Class \Struct provides a convenient way to create a simple class
2069 * that can store and fetch values.
2071 * This example creates a subclass of +Struct+, <tt>Struct::Customer</tt>;
2072 * the first argument, a string, is the name of the subclass;
2073 * the other arguments, symbols, determine the _members_ of the new subclass.
2075 * Customer = Struct.new('Customer', :name, :address, :zip)
2076 * Customer.name # => "Struct::Customer"
2077 * Customer.class # => Class
2078 * Customer.superclass # => Struct
2080 * Corresponding to each member are two methods, a writer and a reader,
2081 * that store and fetch values:
2083 * methods = Customer.instance_methods false
2084 * methods # => [:zip, :address=, :zip=, :address, :name, :name=]
2086 * An instance of the subclass may be created,
2087 * and its members assigned values, via method <tt>::new</tt>:
2089 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
2090 * joe # => #<struct Struct::Customer name="Joe Smith", address="123 Maple, Anytown NC", zip=12345>
2092 * The member values may be managed thus:
2094 * joe.name # => "Joe Smith"
2095 * joe.name = 'Joseph Smith'
2096 * joe.name # => "Joseph Smith"
2098 * And thus; note that member name may be expressed as either a string or a symbol:
2100 * joe[:name] # => "Joseph Smith"
2101 * joe[:name] = 'Joseph Smith, Jr.'
2102 * joe['name'] # => "Joseph Smith, Jr."
2108 * First, what's elsewhere. \Class \Struct:
2110 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
2111 * - Includes {module Enumerable}[rdoc-ref:Enumerable@What-27s+Here],
2112 * which provides dozens of additional methods.
2114 * See also Data, which is a somewhat similar, but stricter concept for defining immutable
2117 * Here, class \Struct provides methods that are useful for:
2119 * - {Creating a Struct Subclass}[rdoc-ref:Struct@Methods+for+Creating+a+Struct+Subclass]
2120 * - {Querying}[rdoc-ref:Struct@Methods+for+Querying]
2121 * - {Comparing}[rdoc-ref:Struct@Methods+for+Comparing]
2122 * - {Fetching}[rdoc-ref:Struct@Methods+for+Fetching]
2123 * - {Assigning}[rdoc-ref:Struct@Methods+for+Assigning]
2124 * - {Iterating}[rdoc-ref:Struct@Methods+for+Iterating]
2125 * - {Converting}[rdoc-ref:Struct@Methods+for+Converting]
2127 * === Methods for Creating a Struct Subclass
2129 * - ::new: Returns a new subclass of \Struct.
2131 * === Methods for Querying
2133 * - #hash: Returns the integer hash code.
2134 * - #length, #size: Returns the number of members.
2136 * === Methods for Comparing
2138 * - #==: Returns whether a given object is equal to +self+, using <tt>==</tt>
2139 * to compare member values.
2140 * - #eql?: Returns whether a given object is equal to +self+,
2141 * using <tt>eql?</tt> to compare member values.
2143 * === Methods for Fetching
2145 * - #[]: Returns the value associated with a given member name.
2146 * - #to_a, #values, #deconstruct: Returns the member values in +self+ as an array.
2147 * - #deconstruct_keys: Returns a hash of the name/value pairs
2148 * for given member names.
2149 * - #dig: Returns the object in nested objects that is specified
2150 * by a given member name and additional arguments.
2151 * - #members: Returns an array of the member names.
2152 * - #select, #filter: Returns an array of member values from +self+,
2153 * as selected by the given block.
2154 * - #values_at: Returns an array containing values for given member names.
2156 * === Methods for Assigning
2158 * - #[]=: Assigns a given value to a given member name.
2160 * === Methods for Iterating
2162 * - #each: Calls a given block with each member name.
2163 * - #each_pair: Calls a given block with each member name/value pair.
2165 * === Methods for Converting
2167 * - #inspect, #to_s: Returns a string representation of +self+.
2168 * - #to_h: Returns a hash of the member name/value pairs in +self+.
2174 rb_cStruct
= rb_define_class("Struct", rb_cObject
);
2175 rb_include_module(rb_cStruct
, rb_mEnumerable
);
2177 rb_undef_alloc_func(rb_cStruct
);
2178 rb_define_singleton_method(rb_cStruct
, "new", rb_struct_s_def
, -1);
2179 #if 0 /* for RDoc */
2180 rb_define_singleton_method(rb_cStruct
, "keyword_init?", rb_struct_s_keyword_init_p
, 0);
2181 rb_define_singleton_method(rb_cStruct
, "members", rb_struct_s_members_m
, 0);
2184 rb_define_method(rb_cStruct
, "initialize", rb_struct_initialize_m
, -1);
2185 rb_define_method(rb_cStruct
, "initialize_copy", rb_struct_init_copy
, 1);
2187 rb_define_method(rb_cStruct
, "==", rb_struct_equal
, 1);
2188 rb_define_method(rb_cStruct
, "eql?", rb_struct_eql
, 1);
2189 rb_define_method(rb_cStruct
, "hash", rb_struct_hash
, 0);
2191 rb_define_method(rb_cStruct
, "inspect", rb_struct_inspect
, 0);
2192 rb_define_alias(rb_cStruct
, "to_s", "inspect");
2193 rb_define_method(rb_cStruct
, "to_a", rb_struct_to_a
, 0);
2194 rb_define_method(rb_cStruct
, "to_h", rb_struct_to_h
, 0);
2195 rb_define_method(rb_cStruct
, "values", rb_struct_to_a
, 0);
2196 rb_define_method(rb_cStruct
, "size", rb_struct_size
, 0);
2197 rb_define_method(rb_cStruct
, "length", rb_struct_size
, 0);
2199 rb_define_method(rb_cStruct
, "each", rb_struct_each
, 0);
2200 rb_define_method(rb_cStruct
, "each_pair", rb_struct_each_pair
, 0);
2201 rb_define_method(rb_cStruct
, "[]", rb_struct_aref
, 1);
2202 rb_define_method(rb_cStruct
, "[]=", rb_struct_aset
, 2);
2203 rb_define_method(rb_cStruct
, "select", rb_struct_select
, -1);
2204 rb_define_method(rb_cStruct
, "filter", rb_struct_select
, -1);
2205 rb_define_method(rb_cStruct
, "values_at", rb_struct_values_at
, -1);
2207 rb_define_method(rb_cStruct
, "members", rb_struct_members_m
, 0);
2208 rb_define_method(rb_cStruct
, "dig", rb_struct_dig
, -1);
2210 rb_define_method(rb_cStruct
, "deconstruct", rb_struct_to_a
, 0);
2211 rb_define_method(rb_cStruct
, "deconstruct_keys", rb_struct_deconstruct_keys
, 1);
2213 rb_cData
= rb_define_class("Data", rb_cObject
);
2215 rb_undef_method(CLASS_OF(rb_cData
), "new");
2216 rb_undef_alloc_func(rb_cData
);
2217 rb_define_singleton_method(rb_cData
, "define", rb_data_s_def
, -1);
2219 #if 0 /* for RDoc */
2220 rb_define_singleton_method(rb_cData
, "members", rb_data_s_members_m
, 0);
2223 rb_define_method(rb_cData
, "initialize", rb_data_initialize_m
, -1);
2224 rb_define_method(rb_cData
, "initialize_copy", rb_data_init_copy
, 1);
2226 rb_define_method(rb_cData
, "==", rb_data_equal
, 1);
2227 rb_define_method(rb_cData
, "eql?", rb_data_eql
, 1);
2228 rb_define_method(rb_cData
, "hash", rb_data_hash
, 0);
2230 rb_define_method(rb_cData
, "inspect", rb_data_inspect
, 0);
2231 rb_define_alias(rb_cData
, "to_s", "inspect");
2232 rb_define_method(rb_cData
, "to_h", rb_data_to_h
, 0);
2234 rb_define_method(rb_cData
, "members", rb_data_members_m
, 0);
2236 rb_define_method(rb_cData
, "deconstruct", rb_data_deconstruct
, 0);
2237 rb_define_method(rb_cData
, "deconstruct_keys", rb_data_deconstruct_keys
, 1);
2239 rb_define_method(rb_cData
, "with", rb_data_with
, -1);
2246 id_members
= rb_intern("__members__");
2247 id_back_members
= rb_intern("__members_back__");
2248 id_keyword_init
= rb_intern("__keyword_init__");