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
)) {