1 /**********************************************************************
6 created at: Tue Mar 22 18:44:30 JST 1995
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
10 **********************************************************************/
12 #include "ruby/ruby.h"
16 static VALUE struct_alloc(VALUE);
19 rb_struct_iv_get(VALUE c, const char *name)
25 if (rb_ivar_defined(c, id))
26 return rb_ivar_get(c, id);
28 if (c == 0 || c == rb_cStruct)
34 rb_struct_s_members(VALUE klass)
36 VALUE members = rb_struct_iv_get(klass, "__members__");
39 rb_raise(rb_eTypeError, "uninitialized struct");
41 if (TYPE(members) != T_ARRAY) {
42 rb_raise(rb_eTypeError, "corrupted struct");
48 rb_struct_members(VALUE s)
50 VALUE members = rb_struct_s_members(rb_obj_class(s));
52 if (RSTRUCT_LEN(s) != RARRAY_LEN(members)) {
53 rb_raise(rb_eTypeError, "struct size differs (%ld required %ld given)",
54 RARRAY_LEN(members), RSTRUCT_LEN(s));
60 rb_struct_s_members_m(VALUE klass)
65 members = rb_struct_s_members(klass);
66 ary = rb_ary_new2(RARRAY_LEN(members));
67 p = RARRAY_PTR(members); pend = p + RARRAY_LEN(members);
78 * struct.members => array
80 * Returns an array of strings representing the names of the instance
83 * Customer = Struct.new(:name, :address, :zip)
84 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
85 * joe.members #=> [:name, :address, :zip]
89 rb_struct_members_m(VALUE obj)
91 return rb_struct_s_members_m(rb_obj_class(obj));
95 rb_struct_getmember(VALUE obj, ID id)
100 members = rb_struct_members(obj);
102 for (i=0; i<RARRAY_LEN(members); i++) {
103 if (RARRAY_PTR(members)[i] == slot) {
104 return RSTRUCT_PTR(obj)[i];
107 rb_name_error(id, "%s is not struct member", rb_id2name(id));
108 return Qnil; /* not reached */
112 rb_struct_ref(VALUE obj)
114 return rb_struct_getmember(obj, rb_frame_this_func());
117 static VALUE rb_struct_ref0(VALUE obj) {return RSTRUCT_PTR(obj)[0];}
118 static VALUE rb_struct_ref1(VALUE obj) {return RSTRUCT_PTR(obj)[1];}
119 static VALUE rb_struct_ref2(VALUE obj) {return RSTRUCT_PTR(obj)[2];}
120 static VALUE rb_struct_ref3(VALUE obj) {return RSTRUCT_PTR(obj)[3];}
121 static VALUE rb_struct_ref4(VALUE obj) {return RSTRUCT_PTR(obj)[4];}
122 static VALUE rb_struct_ref5(VALUE obj) {return RSTRUCT_PTR(obj)[5];}
123 static VALUE rb_struct_ref6(VALUE obj) {return RSTRUCT_PTR(obj)[6];}
124 static VALUE rb_struct_ref7(VALUE obj) {return RSTRUCT_PTR(obj)[7];}
125 static VALUE rb_struct_ref8(VALUE obj) {return RSTRUCT_PTR(obj)[8];}
126 static VALUE rb_struct_ref9(VALUE obj) {return RSTRUCT_PTR(obj)[9];}
128 #define N_REF_FUNC (sizeof(ref_func) / sizeof(ref_func[0]))
130 static VALUE (*const ref_func[])(VALUE) = {
144 rb_struct_modify(VALUE s)
146 if (OBJ_FROZEN(s)) rb_error_frozen("Struct");
147 if (!OBJ_UNTRUSTED(s) && rb_safe_level() >= 4)
148 rb_raise(rb_eSecurityError, "Insecure: can't modify Struct");
152 rb_struct_set(VALUE obj, VALUE val)
157 members = rb_struct_members(obj);
158 rb_struct_modify(obj);
159 for (i=0; i<RARRAY_LEN(members); i++) {
160 slot = RARRAY_PTR(members)[i];
161 if (rb_id_attrset(SYM2ID(slot)) == rb_frame_this_func()) {
162 return RSTRUCT_PTR(obj)[i] = val;
165 rb_name_error(rb_frame_this_func(), "`%s' is not a struct member",
166 rb_id2name(rb_frame_this_func()));
167 return Qnil; /* not reached */
171 make_struct(VALUE name, VALUE members, VALUE klass)
179 nstr = rb_class_new(klass);
180 rb_make_metaclass(nstr, RBASIC(klass)->klass);
181 rb_class_inherited(klass, nstr);
184 /* old style: should we warn? */
185 name = rb_str_to_str(name);
187 if (!rb_is_const_id(id)) {
188 rb_name_error(id, "identifier %s needs to be constant", StringValuePtr(name));
190 if (rb_const_defined_at(klass, id)) {
191 rb_warn("redefining constant Struct::%s", StringValuePtr(name));
192 rb_mod_remove_const(klass, ID2SYM(id));
194 nstr = rb_define_class_under(klass, rb_id2name(id), klass);
196 rb_iv_set(nstr, "__members__", members);
198 rb_define_alloc_func(nstr, struct_alloc);
199 rb_define_singleton_method(nstr, "new", rb_class_new_instance, -1);
200 rb_define_singleton_method(nstr, "[]", rb_class_new_instance, -1);
201 rb_define_singleton_method(nstr, "members", rb_struct_s_members_m, 0);
202 for (i=0; i< RARRAY_LEN(members); i++) {
203 ID id = SYM2ID(RARRAY_PTR(members)[i]);
204 if (rb_is_local_id(id) || rb_is_const_id(id)) {
205 if (i < N_REF_FUNC) {
206 rb_define_method_id(nstr, id, ref_func[i], 0);
209 rb_define_method_id(nstr, id, rb_struct_ref, 0);
211 rb_define_method_id(nstr, rb_id_attrset(id), rb_struct_set, 1);
219 rb_struct_alloc_noinit(VALUE klass)
221 return struct_alloc(klass);
225 rb_struct_define_without_accessor(const char *class_name, VALUE super, rb_alloc_func_t alloc, ...)
233 members = rb_ary_new2(0);
236 while ((name = va_arg(ar, char*)) != NULL) {
237 rb_ary_push(members, ID2SYM(rb_intern(name)));
243 klass = rb_define_class(class_name, super);
246 klass = rb_class_new(super);
247 rb_make_metaclass(klass, RBASIC(super)->klass);
248 rb_class_inherited(super, klass);
251 rb_iv_set(klass, "__members__", members);
254 rb_define_alloc_func(klass, alloc);
256 rb_define_alloc_func(klass, struct_alloc);
262 rb_struct_define(const char *name, ...)
268 if (!name) nm = Qnil;
269 else nm = rb_str_new2(name);
273 while ((mem = va_arg(ar, char*)) != 0) {
274 ID slot = rb_intern(mem);
275 rb_ary_push(ary, ID2SYM(slot));
279 return make_struct(nm, ary, rb_cStruct);
284 * Struct.new( [aString] [, aSym]+> ) => StructClass
285 * StructClass.new(arg, ...) => obj
286 * StructClass[arg, ...] => obj
288 * Creates a new class, named by <i>aString</i>, containing accessor
289 * methods for the given symbols. If the name <i>aString</i> is
290 * omitted, an anonymous structure class will be created. Otherwise,
291 * the name of this struct will appear as a constant in class
292 * <code>Struct</code>, so it must be unique for all
293 * <code>Struct</code>s in the system and should start with a capital
294 * letter. Assigning a structure class to a constant effectively gives
295 * the class the name of the constant.
297 * <code>Struct::new</code> returns a new <code>Class</code> object,
298 * which can then be used to create specific instances of the new
299 * structure. The number of actual parameters must be
300 * less than or equal to the number of attributes defined for this
301 * class; unset parameters default to \nil{}. Passing too many
302 * parameters will raise an \E{ArgumentError}.
304 * The remaining methods listed in this section (class and instance)
305 * are defined for this generated class.
307 * # Create a structure with a name in Struct
308 * Struct.new("Customer", :name, :address) #=> Struct::Customer
309 * Struct::Customer.new("Dave", "123 Main") #=> #<struct Struct::Customer name="Dave", address="123 Main">
311 * # Create a structure named by its constant
312 * Customer = Struct.new(:name, :address) #=> Customer
313 * Customer.new("Dave", "123 Main") #=> #<struct Customer name="Dave", address="123 Main">
317 rb_struct_s_def(int argc, VALUE *argv, VALUE klass)
324 rb_scan_args(argc, argv, "1*", &name, &rest);
325 if (!NIL_P(name) && SYMBOL_P(name)) {
326 rb_ary_unshift(rest, name);
329 for (i=0; i<RARRAY_LEN(rest); i++) {
330 id = rb_to_id(RARRAY_PTR(rest)[i]);
331 RARRAY_PTR(rest)[i] = ID2SYM(id);
333 st = make_struct(name, rest, klass);
334 if (rb_block_given_p()) {
335 rb_mod_module_eval(0, 0, st);
342 num_members(VALUE klass)
345 members = rb_struct_iv_get(klass, "__members__");
346 if (TYPE(members) != T_ARRAY) {
347 rb_raise(rb_eTypeError, "broken members");
349 return RARRAY_LEN(members);
356 rb_struct_initialize_m(int argc, VALUE *argv, VALUE self)
358 VALUE klass = rb_obj_class(self);
361 rb_struct_modify(self);
362 n = num_members(klass);
364 rb_raise(rb_eArgError, "struct size differs");
366 MEMCPY(RSTRUCT_PTR(self), argv, VALUE, argc);
368 rb_mem_clear(RSTRUCT_PTR(self)+argc, n-argc);
374 rb_struct_initialize(VALUE self, VALUE values)
376 return rb_struct_initialize_m(RARRAY_LEN(values), RARRAY_PTR(values), self);
380 struct_alloc(VALUE klass)
383 NEWOBJ(st, struct RStruct);
384 OBJSETUP(st, klass, T_STRUCT);
386 n = num_members(klass);
388 if (0 < n && n <= RSTRUCT_EMBED_LEN_MAX) {
389 RBASIC(st)->flags &= ~RSTRUCT_EMBED_LEN_MASK;
390 RBASIC(st)->flags |= n << RSTRUCT_EMBED_LEN_SHIFT;
391 rb_mem_clear(st->as.ary, n);
394 st->as.heap.ptr = ALLOC_N(VALUE, n);
395 rb_mem_clear(st->as.heap.ptr, n);
403 rb_struct_alloc(VALUE klass, VALUE values)
405 return rb_class_new_instance(RARRAY_LEN(values), RARRAY_PTR(values), klass);
409 rb_struct_new(VALUE klass, ...)
415 size = num_members(klass);
416 mem = ALLOCA_N(VALUE, size);
417 va_start(args, klass);
418 for (i=0; i<size; i++) {
419 mem[i] = va_arg(args, VALUE);
423 return rb_class_new_instance(size, mem, klass);
428 * struct.each {|obj| block } => struct
430 * Calls <i>block</i> once for each instance variable, passing the
431 * value as a parameter.
433 * Customer = Struct.new(:name, :address, :zip)
434 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
435 * joe.each {|x| puts(x) }
440 * 123 Maple, Anytown NC
445 rb_struct_each(VALUE s)
449 RETURN_ENUMERATOR(s, 0, 0);
450 for (i=0; i<RSTRUCT_LEN(s); i++) {
451 rb_yield(RSTRUCT_PTR(s)[i]);
458 * struct.each_pair {|sym, obj| block } => struct
460 * Calls <i>block</i> once for each instance variable, passing the name
461 * (as a symbol) and the value as parameters.
463 * Customer = Struct.new(:name, :address, :zip)
464 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
465 * joe.each_pair {|name, value| puts("#{name} => #{value}") }
470 * address => 123 Maple, Anytown NC
475 rb_struct_each_pair(VALUE s)
480 RETURN_ENUMERATOR(s, 0, 0);
481 members = rb_struct_members(s);
482 for (i=0; i<RSTRUCT_LEN(s); i++) {
483 rb_yield_values(2, rb_ary_entry(members, i), RSTRUCT_PTR(s)[i]);
489 inspect_struct(VALUE s, VALUE dummy, int recur)
491 const char *cname = rb_class2name(rb_obj_class(s));
496 return rb_sprintf("#<struct %s:...>", cname);
499 members = rb_struct_members(s);
500 if (cname[0] == '#') {
501 str = rb_str_new2("#<struct ");
504 str = rb_sprintf("#<struct %s ", cname);
506 for (i=0; i<RSTRUCT_LEN(s); i++) {
511 rb_str_cat2(str, ", ");
513 slot = RARRAY_PTR(members)[i];
515 if (rb_is_local_id(id) || rb_is_const_id(id)) {
516 rb_str_append(str, rb_id2str(id));
519 rb_str_append(str, rb_inspect(slot));
521 rb_str_cat2(str, "=");
522 rb_str_append(str, rb_inspect(RSTRUCT_PTR(s)[i]));
524 rb_str_cat2(str, ">");
532 * struct.to_s => string
533 * struct.inspect => string
535 * Describe the contents of this struct in a string.
539 rb_struct_inspect(VALUE s)
541 return rb_exec_recursive(inspect_struct, s, 0);
546 * struct.to_a => array
547 * struct.values => array
549 * Returns the values for this instance as an array.
551 * Customer = Struct.new(:name, :address, :zip)
552 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
553 * joe.to_a[1] #=> "123 Maple, Anytown NC"
557 rb_struct_to_a(VALUE s)
559 return rb_ary_new4(RSTRUCT_LEN(s), RSTRUCT_PTR(s));
564 rb_struct_init_copy(VALUE copy, VALUE s)
566 if (copy == s) return copy;
567 rb_check_frozen(copy);
568 if (!rb_obj_is_instance_of(s, rb_obj_class(copy))) {
569 rb_raise(rb_eTypeError, "wrong argument class");
571 if (RSTRUCT_LEN(copy) != RSTRUCT_LEN(s)) {
572 rb_raise(rb_eTypeError, "struct size mismatch");
574 MEMCPY(RSTRUCT_PTR(copy), RSTRUCT_PTR(s), VALUE, RSTRUCT_LEN(copy));
580 rb_struct_aref_id(VALUE s, ID id)
585 members = rb_struct_members(s);
586 len = RARRAY_LEN(members);
587 for (i=0; i<len; i++) {
588 if (SYM2ID(RARRAY_PTR(members)[i]) == id) {
589 return RSTRUCT_PTR(s)[i];
592 rb_name_error(id, "no member '%s' in struct", rb_id2name(id));
593 return Qnil; /* not reached */
598 * struct[symbol] => anObject
599 * struct[fixnum] => anObject
601 * Attribute Reference---Returns the value of the instance variable
602 * named by <i>symbol</i>, or indexed (0..length-1) by
603 * <i>fixnum</i>. Will raise <code>NameError</code> if the named
604 * variable does not exist, or <code>IndexError</code> if the index is
607 * Customer = Struct.new(:name, :address, :zip)
608 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
610 * joe["name"] #=> "Joe Smith"
611 * joe[:name] #=> "Joe Smith"
612 * joe[0] #=> "Joe Smith"
616 rb_struct_aref(VALUE s, VALUE idx)
620 if (TYPE(idx) == T_STRING || TYPE(idx) == T_SYMBOL) {
621 return rb_struct_aref_id(s, rb_to_id(idx));
625 if (i < 0) i = RSTRUCT_LEN(s) + i;
627 rb_raise(rb_eIndexError, "offset %ld too small for struct(size:%ld)",
629 if (RSTRUCT_LEN(s) <= i)
630 rb_raise(rb_eIndexError, "offset %ld too large for struct(size:%ld)",
632 return RSTRUCT_PTR(s)[i];
636 rb_struct_aset_id(VALUE s, ID id, VALUE val)
641 members = rb_struct_members(s);
643 len = RARRAY_LEN(members);
644 if (RSTRUCT_LEN(s) != RARRAY_LEN(members)) {
645 rb_raise(rb_eTypeError, "struct size differs (%ld required %ld given)",
646 RARRAY_LEN(members), RSTRUCT_LEN(s));
648 for (i=0; i<len; i++) {
649 if (SYM2ID(RARRAY_PTR(members)[i]) == id) {
650 RSTRUCT_PTR(s)[i] = val;
654 rb_name_error(id, "no member '%s' in struct", rb_id2name(id));
659 * struct[symbol] = obj => obj
660 * struct[fixnum] = obj => obj
662 * Attribute Assignment---Assigns to the instance variable named by
663 * <i>symbol</i> or <i>fixnum</i> the value <i>obj</i> and
664 * returns it. Will raise a <code>NameError</code> if the named
665 * variable does not exist, or an <code>IndexError</code> if the index
668 * Customer = Struct.new(:name, :address, :zip)
669 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
671 * joe["name"] = "Luke"
672 * joe[:zip] = "90210"
674 * joe.name #=> "Luke"
675 * joe.zip #=> "90210"
679 rb_struct_aset(VALUE s, VALUE idx, VALUE val)
683 if (TYPE(idx) == T_STRING || TYPE(idx) == T_SYMBOL) {
684 return rb_struct_aset_id(s, rb_to_id(idx), val);
688 if (i < 0) i = RSTRUCT_LEN(s) + i;
690 rb_raise(rb_eIndexError, "offset %ld too small for struct(size:%ld)",
693 if (RSTRUCT_LEN(s) <= i) {
694 rb_raise(rb_eIndexError, "offset %ld too large for struct(size:%ld)",
698 return RSTRUCT_PTR(s)[i] = val;
702 struct_entry(VALUE s, long n)
704 return rb_struct_aref(s, LONG2NUM(n));
709 * struct.values_at(selector,... ) => an_array
711 * Returns an array containing the elements in
712 * _self_ corresponding to the given selector(s). The selectors
713 * may be either integer indices or ranges.
714 * See also </code>.select<code>.
716 * a = %w{ a b c d e f }
717 * a.values_at(1, 3, 5)
718 * a.values_at(1, 3, 5, 7)
719 * a.values_at(-1, -3, -5, -7)
720 * a.values_at(1..3, 2...5)
724 rb_struct_values_at(int argc, VALUE *argv, VALUE s)
726 return rb_get_values_at(s, RSTRUCT_LEN(s), argc, argv, struct_entry);
731 * struct.select {|i| block } => array
733 * Invokes the block passing in successive elements from
734 * <i>struct</i>, returning an array containing those elements
735 * for which the block returns a true value (equivalent to
736 * <code>Enumerable#select</code>).
738 * Lots = Struct.new(:a, :b, :c, :d, :e, :f)
739 * l = Lots.new(11, 22, 33, 44, 55, 66)
740 * l.select {|v| (v % 2).zero? } #=> [22, 44, 66]
744 rb_struct_select(int argc, VALUE *argv, VALUE s)
750 rb_raise(rb_eArgError, "wrong number of arguments (%d for 0)", argc);
752 result = rb_ary_new();
753 for (i = 0; i < RSTRUCT_LEN(s); i++) {
754 if (RTEST(rb_yield(RSTRUCT_PTR(s)[i]))) {
755 rb_ary_push(result, RSTRUCT_PTR(s)[i]);
764 * struct == other_struct => true or false
766 * Equality---Returns <code>true</code> if <i>other_struct</i> is
767 * equal to this one: they must be of the same class as generated by
768 * <code>Struct::new</code>, and the values of all instance variables
769 * must be equal (according to <code>Object#==</code>).
771 * Customer = Struct.new(:name, :address, :zip)
772 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
773 * joejr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
774 * jane = Customer.new("Jane Doe", "456 Elm, Anytown NC", 12345)
775 * joe == joejr #=> true
776 * joe == jane #=> false
780 rb_struct_equal(VALUE s, VALUE s2)
784 if (s == s2) return Qtrue;
785 if (TYPE(s2) != T_STRUCT) return Qfalse;
786 if (rb_obj_class(s) != rb_obj_class(s2)) return Qfalse;
787 if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) {
788 rb_bug("inconsistent struct"); /* should never happen */
791 for (i=0; i<RSTRUCT_LEN(s); i++) {
792 if (!rb_equal(RSTRUCT_PTR(s)[i], RSTRUCT_PTR(s2)[i])) return Qfalse;
799 * struct.hash => fixnum
801 * Return a hash value based on this struct's contents.
805 rb_struct_hash(VALUE s)
810 h = rb_hash(rb_obj_class(s));
811 for (i = 0; i < RSTRUCT_LEN(s); i++) {
812 h = (h << 1) | (h<0 ? 1 : 0);
813 n = rb_hash(RSTRUCT_PTR(s)[i]);
821 * struct.eql?(other) => true or false
823 * Two structures are equal if they are the same object, or if all their
824 * fields are equal (using <code>eql?</code>).
828 rb_struct_eql(VALUE s, VALUE s2)
832 if (s == s2) return Qtrue;
833 if (TYPE(s2) != T_STRUCT) return Qfalse;
834 if (rb_obj_class(s) != rb_obj_class(s2)) return Qfalse;
835 if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) {
836 rb_bug("inconsistent struct"); /* should never happen */
839 for (i=0; i<RSTRUCT_LEN(s); i++) {
840 if (!rb_eql(RSTRUCT_PTR(s)[i], RSTRUCT_PTR(s2)[i])) return Qfalse;
847 * struct.length => fixnum
848 * struct.size => fixnum
850 * Returns the number of instance variables.
852 * Customer = Struct.new(:name, :address, :zip)
853 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
858 rb_struct_size(VALUE s)
860 return LONG2FIX(RSTRUCT_LEN(s));
864 * A <code>Struct</code> is a convenient way to bundle a number of
865 * attributes together, using accessor methods, without having to write
868 * The <code>Struct</code> class is a generator of specific classes,
869 * each one of which is defined to hold a set of variables and their
870 * accessors. In these examples, we'll call the generated class
871 * ``<i>Customer</i>Class,'' and we'll show an example instance of that
872 * class as ``<i>Customer</i>Inst.''
874 * In the descriptions that follow, the parameter <i>symbol</i> refers
875 * to a symbol, which is either a quoted string or a
876 * <code>Symbol</code> (such as <code>:name</code>).
881 rb_cStruct = rb_define_class("Struct", rb_cObject);
882 rb_include_module(rb_cStruct, rb_mEnumerable);
884 rb_undef_alloc_func(rb_cStruct);
885 rb_define_singleton_method(rb_cStruct, "new", rb_struct_s_def, -1);
887 rb_define_method(rb_cStruct, "initialize", rb_struct_initialize_m, -1);
888 rb_define_method(rb_cStruct, "initialize_copy", rb_struct_init_copy, 1);
890 rb_define_method(rb_cStruct, "==", rb_struct_equal, 1);
891 rb_define_method(rb_cStruct, "eql?", rb_struct_eql, 1);
892 rb_define_method(rb_cStruct, "hash", rb_struct_hash, 0);
894 rb_define_method(rb_cStruct, "to_s", rb_struct_inspect, 0);
895 rb_define_method(rb_cStruct, "inspect", rb_struct_inspect, 0);
896 rb_define_method(rb_cStruct, "to_a", rb_struct_to_a, 0);
897 rb_define_method(rb_cStruct, "values", rb_struct_to_a, 0);
898 rb_define_method(rb_cStruct, "size", rb_struct_size, 0);
899 rb_define_method(rb_cStruct, "length", rb_struct_size, 0);
901 rb_define_method(rb_cStruct, "each", rb_struct_each, 0);
902 rb_define_method(rb_cStruct, "each_pair", rb_struct_each_pair, 0);
903 rb_define_method(rb_cStruct, "[]", rb_struct_aref, 1);
904 rb_define_method(rb_cStruct, "[]=", rb_struct_aset, 2);
905 rb_define_method(rb_cStruct, "select", rb_struct_select, -1);
906 rb_define_method(rb_cStruct, "values_at", rb_struct_values_at, -1);
908 rb_define_method(rb_cStruct, "members", rb_struct_members_m, 0);