* transcode_data.h (rb_trans_elem_t): new field: from and to.
[ruby-svn.git] / struct.c
blob027256869a49c91296e21c5656ef20e45270005f
1 /**********************************************************************
3 struct.c -
5 $Author$
6 created at: Tue Mar 22 18:44:30 JST 1995
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
10 **********************************************************************/
12 #include "ruby/ruby.h"
14 VALUE rb_cStruct;
16 static VALUE struct_alloc(VALUE);
18 VALUE
19 rb_struct_iv_get(VALUE c, const char *name)
21 ID id;
23 id = rb_intern(name);
24 for (;;) {
25 if (rb_ivar_defined(c, id))
26 return rb_ivar_get(c, id);
27 c = RCLASS_SUPER(c);
28 if (c == 0 || c == rb_cStruct)
29 return Qnil;
33 VALUE
34 rb_struct_s_members(VALUE klass)
36 VALUE members = rb_struct_iv_get(klass, "__members__");
38 if (NIL_P(members)) {
39 rb_raise(rb_eTypeError, "uninitialized struct");
41 if (TYPE(members) != T_ARRAY) {
42 rb_raise(rb_eTypeError, "corrupted struct");
44 return members;
47 VALUE
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));
56 return members;
59 static VALUE
60 rb_struct_s_members_m(VALUE klass)
62 VALUE members, ary;
63 VALUE *p, *pend;
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);
68 while (p < pend) {
69 rb_ary_push(ary, *p);
70 p++;
73 return ary;
77 * call-seq:
78 * struct.members => array
80 * Returns an array of strings representing the names of the instance
81 * variables.
83 * Customer = Struct.new(:name, :address, :zip)
84 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
85 * joe.members #=> [:name, :address, :zip]
88 static VALUE
89 rb_struct_members_m(VALUE obj)
91 return rb_struct_s_members_m(rb_obj_class(obj));
94 VALUE
95 rb_struct_getmember(VALUE obj, ID id)
97 VALUE members, slot;
98 long i;
100 members = rb_struct_members(obj);
101 slot = ID2SYM(id);
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 */
111 static VALUE
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) = {
131 rb_struct_ref0,
132 rb_struct_ref1,
133 rb_struct_ref2,
134 rb_struct_ref3,
135 rb_struct_ref4,
136 rb_struct_ref5,
137 rb_struct_ref6,
138 rb_struct_ref7,
139 rb_struct_ref8,
140 rb_struct_ref9,
143 static void
144 rb_struct_modify(VALUE s)
146 if (OBJ_FROZEN(s)) rb_error_frozen("Struct");
147 if (!OBJ_TAINTED(s) && rb_safe_level() >= 4)
148 rb_raise(rb_eSecurityError, "Insecure: can't modify Struct");
151 static VALUE
152 rb_struct_set(VALUE obj, VALUE val)
154 VALUE members, slot;
155 long i;
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 */
170 static VALUE
171 make_struct(VALUE name, VALUE members, VALUE klass)
173 VALUE nstr;
174 ID id;
175 long i;
177 OBJ_FREEZE(members);
178 if (NIL_P(name)) {
179 nstr = rb_class_new(klass);
180 rb_make_metaclass(nstr, RBASIC(klass)->klass);
181 rb_class_inherited(klass, nstr);
183 else {
184 /* old style: should we warn? */
185 name = rb_str_to_str(name);
186 id = rb_to_id(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);
208 else {
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);
215 return nstr;
218 VALUE
219 rb_struct_alloc_noinit(VALUE klass)
221 return struct_alloc(klass);
224 VALUE
225 rb_struct_define_without_accessor(const char *class_name, VALUE super, rb_alloc_func_t alloc, ...)
227 VALUE klass;
228 va_list ar;
229 VALUE members;
230 long i;
231 char *name;
233 members = rb_ary_new2(0);
234 va_start(ar, alloc);
235 i = 0;
236 while ((name = va_arg(ar, char*)) != NULL) {
237 rb_ary_push(members, ID2SYM(rb_intern(name)));
239 va_end(ar);
240 OBJ_FREEZE(members);
242 if (class_name) {
243 klass = rb_define_class(class_name, super);
245 else {
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);
253 if (alloc)
254 rb_define_alloc_func(klass, alloc);
255 else
256 rb_define_alloc_func(klass, struct_alloc);
258 return klass;
261 VALUE
262 rb_struct_define(const char *name, ...)
264 va_list ar;
265 VALUE nm, ary;
266 char *mem;
268 if (!name) nm = Qnil;
269 else nm = rb_str_new2(name);
270 ary = rb_ary_new();
272 va_start(ar, name);
273 while ((mem = va_arg(ar, char*)) != 0) {
274 ID slot = rb_intern(mem);
275 rb_ary_push(ary, ID2SYM(slot));
277 va_end(ar);
279 return make_struct(nm, ary, rb_cStruct);
283 * call-seq:
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">
316 static VALUE
317 rb_struct_s_def(int argc, VALUE *argv, VALUE klass)
319 VALUE name, rest;
320 long i;
321 VALUE st;
322 ID id;
324 rb_scan_args(argc, argv, "1*", &name, &rest);
325 if (!NIL_P(name) && SYMBOL_P(name)) {
326 rb_ary_unshift(rest, name);
327 name = Qnil;
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);
338 return st;
341 static size_t
342 num_members(VALUE klass)
344 VALUE members;
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);
355 VALUE
356 rb_struct_initialize(VALUE self, VALUE values)
358 VALUE klass = rb_obj_class(self);
359 long n;
361 rb_struct_modify(self);
362 n = num_members(klass);
363 if (n < RARRAY_LEN(values)) {
364 rb_raise(rb_eArgError, "struct size differs");
366 MEMCPY(RSTRUCT_PTR(self), RARRAY_PTR(values), VALUE, RARRAY_LEN(values));
367 if (n > RARRAY_LEN(values)) {
368 rb_mem_clear(RSTRUCT_PTR(self)+RARRAY_LEN(values),
369 n-RARRAY_LEN(values));
371 return Qnil;
374 static VALUE
375 struct_alloc(VALUE klass)
377 long n;
378 NEWOBJ(st, struct RStruct);
379 OBJSETUP(st, klass, T_STRUCT);
381 n = num_members(klass);
383 if (0 < n && n <= RSTRUCT_EMBED_LEN_MAX) {
384 RBASIC(st)->flags &= ~RSTRUCT_EMBED_LEN_MASK;
385 RBASIC(st)->flags |= n << RSTRUCT_EMBED_LEN_SHIFT;
386 rb_mem_clear(st->as.ary, n);
388 else {
389 st->as.heap.ptr = ALLOC_N(VALUE, n);
390 rb_mem_clear(st->as.heap.ptr, n);
391 st->as.heap.len = n;
394 return (VALUE)st;
397 VALUE
398 rb_struct_alloc(VALUE klass, VALUE values)
400 return rb_class_new_instance(RARRAY_LEN(values), RARRAY_PTR(values), klass);
403 VALUE
404 rb_struct_new(VALUE klass, ...)
406 VALUE *mem;
407 long size, i;
408 va_list args;
410 size = num_members(klass);
411 mem = ALLOCA_N(VALUE, size);
412 va_start(args, klass);
413 for (i=0; i<size; i++) {
414 mem[i] = va_arg(args, VALUE);
416 va_end(args);
418 return rb_class_new_instance(size, mem, klass);
422 * call-seq:
423 * struct.each {|obj| block } => struct
425 * Calls <i>block</i> once for each instance variable, passing the
426 * value as a parameter.
428 * Customer = Struct.new(:name, :address, :zip)
429 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
430 * joe.each {|x| puts(x) }
432 * <em>produces:</em>
434 * Joe Smith
435 * 123 Maple, Anytown NC
436 * 12345
439 static VALUE
440 rb_struct_each(VALUE s)
442 long i;
444 RETURN_ENUMERATOR(s, 0, 0);
445 for (i=0; i<RSTRUCT_LEN(s); i++) {
446 rb_yield(RSTRUCT_PTR(s)[i]);
448 return s;
452 * call-seq:
453 * struct.each_pair {|sym, obj| block } => struct
455 * Calls <i>block</i> once for each instance variable, passing the name
456 * (as a symbol) and the value as parameters.
458 * Customer = Struct.new(:name, :address, :zip)
459 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
460 * joe.each_pair {|name, value| puts("#{name} => #{value}") }
462 * <em>produces:</em>
464 * name => Joe Smith
465 * address => 123 Maple, Anytown NC
466 * zip => 12345
469 static VALUE
470 rb_struct_each_pair(VALUE s)
472 VALUE members;
473 long i;
475 RETURN_ENUMERATOR(s, 0, 0);
476 members = rb_struct_members(s);
477 for (i=0; i<RSTRUCT_LEN(s); i++) {
478 rb_yield_values(2, rb_ary_entry(members, i), RSTRUCT_PTR(s)[i]);
480 return s;
483 static VALUE
484 inspect_struct(VALUE s, VALUE dummy, int recur)
486 const char *cname = rb_class2name(rb_obj_class(s));
487 VALUE str, members;
488 long i;
490 if (recur) {
491 return rb_sprintf("#<struct %s:...>", cname);
494 members = rb_struct_members(s);
495 if (cname[0] == '#') {
496 str = rb_str_new2("#<struct ");
498 else {
499 str = rb_sprintf("#<struct %s ", cname);
501 for (i=0; i<RSTRUCT_LEN(s); i++) {
502 VALUE slot;
503 ID id;
505 if (i > 0) {
506 rb_str_cat2(str, ", ");
508 slot = RARRAY_PTR(members)[i];
509 id = SYM2ID(slot);
510 if (rb_is_local_id(id) || rb_is_const_id(id)) {
511 rb_str_append(str, rb_id2str(id));
513 else {
514 rb_str_append(str, rb_inspect(slot));
516 rb_str_cat2(str, "=");
517 rb_str_append(str, rb_inspect(RSTRUCT_PTR(s)[i]));
519 rb_str_cat2(str, ">");
520 OBJ_INFECT(str, s);
522 return str;
526 * call-seq:
527 * struct.to_s => string
528 * struct.inspect => string
530 * Describe the contents of this struct in a string.
533 static VALUE
534 rb_struct_inspect(VALUE s)
536 return rb_exec_recursive(inspect_struct, s, 0);
540 * call-seq:
541 * struct.to_a => array
542 * struct.values => array
544 * Returns the values for this instance as an array.
546 * Customer = Struct.new(:name, :address, :zip)
547 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
548 * joe.to_a[1] #=> "123 Maple, Anytown NC"
551 static VALUE
552 rb_struct_to_a(VALUE s)
554 return rb_ary_new4(RSTRUCT_LEN(s), RSTRUCT_PTR(s));
557 /* :nodoc: */
558 static VALUE
559 rb_struct_init_copy(VALUE copy, VALUE s)
561 if (copy == s) return copy;
562 rb_check_frozen(copy);
563 if (!rb_obj_is_instance_of(s, rb_obj_class(copy))) {
564 rb_raise(rb_eTypeError, "wrong argument class");
566 if (RSTRUCT_LEN(copy) != RSTRUCT_LEN(s)) {
567 rb_raise(rb_eTypeError, "struct size mismatch");
569 MEMCPY(RSTRUCT_PTR(copy), RSTRUCT_PTR(s), VALUE, RSTRUCT_LEN(copy));
571 return copy;
574 static VALUE
575 rb_struct_aref_id(VALUE s, ID id)
577 VALUE members;
578 long i, len;
580 members = rb_struct_members(s);
581 len = RARRAY_LEN(members);
582 for (i=0; i<len; i++) {
583 if (SYM2ID(RARRAY_PTR(members)[i]) == id) {
584 return RSTRUCT_PTR(s)[i];
587 rb_name_error(id, "no member '%s' in struct", rb_id2name(id));
588 return Qnil; /* not reached */
592 * call-seq:
593 * struct[symbol] => anObject
594 * struct[fixnum] => anObject
596 * Attribute Reference---Returns the value of the instance variable
597 * named by <i>symbol</i>, or indexed (0..length-1) by
598 * <i>fixnum</i>. Will raise <code>NameError</code> if the named
599 * variable does not exist, or <code>IndexError</code> if the index is
600 * out of range.
602 * Customer = Struct.new(:name, :address, :zip)
603 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
605 * joe["name"] #=> "Joe Smith"
606 * joe[:name] #=> "Joe Smith"
607 * joe[0] #=> "Joe Smith"
610 VALUE
611 rb_struct_aref(VALUE s, VALUE idx)
613 long i;
615 if (TYPE(idx) == T_STRING || TYPE(idx) == T_SYMBOL) {
616 return rb_struct_aref_id(s, rb_to_id(idx));
619 i = NUM2LONG(idx);
620 if (i < 0) i = RSTRUCT_LEN(s) + i;
621 if (i < 0)
622 rb_raise(rb_eIndexError, "offset %ld too small for struct(size:%ld)",
623 i, RSTRUCT_LEN(s));
624 if (RSTRUCT_LEN(s) <= i)
625 rb_raise(rb_eIndexError, "offset %ld too large for struct(size:%ld)",
626 i, RSTRUCT_LEN(s));
627 return RSTRUCT_PTR(s)[i];
630 static VALUE
631 rb_struct_aset_id(VALUE s, ID id, VALUE val)
633 VALUE members;
634 long i, len;
636 members = rb_struct_members(s);
637 rb_struct_modify(s);
638 len = RARRAY_LEN(members);
639 if (RSTRUCT_LEN(s) != RARRAY_LEN(members)) {
640 rb_raise(rb_eTypeError, "struct size differs (%ld required %ld given)",
641 RARRAY_LEN(members), RSTRUCT_LEN(s));
643 for (i=0; i<len; i++) {
644 if (SYM2ID(RARRAY_PTR(members)[i]) == id) {
645 RSTRUCT_PTR(s)[i] = val;
646 return val;
649 rb_name_error(id, "no member '%s' in struct", rb_id2name(id));
653 * call-seq:
654 * struct[symbol] = obj => obj
655 * struct[fixnum] = obj => obj
657 * Attribute Assignment---Assigns to the instance variable named by
658 * <i>symbol</i> or <i>fixnum</i> the value <i>obj</i> and
659 * returns it. Will raise a <code>NameError</code> if the named
660 * variable does not exist, or an <code>IndexError</code> if the index
661 * is out of range.
663 * Customer = Struct.new(:name, :address, :zip)
664 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
666 * joe["name"] = "Luke"
667 * joe[:zip] = "90210"
669 * joe.name #=> "Luke"
670 * joe.zip #=> "90210"
673 VALUE
674 rb_struct_aset(VALUE s, VALUE idx, VALUE val)
676 long i;
678 if (TYPE(idx) == T_STRING || TYPE(idx) == T_SYMBOL) {
679 return rb_struct_aset_id(s, rb_to_id(idx), val);
682 i = NUM2LONG(idx);
683 if (i < 0) i = RSTRUCT_LEN(s) + i;
684 if (i < 0) {
685 rb_raise(rb_eIndexError, "offset %ld too small for struct(size:%ld)",
686 i, RSTRUCT_LEN(s));
688 if (RSTRUCT_LEN(s) <= i) {
689 rb_raise(rb_eIndexError, "offset %ld too large for struct(size:%ld)",
690 i, RSTRUCT_LEN(s));
692 rb_struct_modify(s);
693 return RSTRUCT_PTR(s)[i] = val;
696 static VALUE
697 struct_entry(VALUE s, long n)
699 return rb_struct_aref(s, LONG2NUM(n));
703 * call-seq:
704 * struct.values_at(selector,... ) => an_array
706 * Returns an array containing the elements in
707 * _self_ corresponding to the given selector(s). The selectors
708 * may be either integer indices or ranges.
709 * See also </code>.select<code>.
711 * a = %w{ a b c d e f }
712 * a.values_at(1, 3, 5)
713 * a.values_at(1, 3, 5, 7)
714 * a.values_at(-1, -3, -5, -7)
715 * a.values_at(1..3, 2...5)
718 static VALUE
719 rb_struct_values_at(int argc, VALUE *argv, VALUE s)
721 return rb_get_values_at(s, RSTRUCT_LEN(s), argc, argv, struct_entry);
725 * call-seq:
726 * struct.select {|i| block } => array
728 * Invokes the block passing in successive elements from
729 * <i>struct</i>, returning an array containing those elements
730 * for which the block returns a true value (equivalent to
731 * <code>Enumerable#select</code>).
733 * Lots = Struct.new(:a, :b, :c, :d, :e, :f)
734 * l = Lots.new(11, 22, 33, 44, 55, 66)
735 * l.select {|v| (v % 2).zero? } #=> [22, 44, 66]
738 static VALUE
739 rb_struct_select(int argc, VALUE *argv, VALUE s)
741 VALUE result;
742 long i;
744 if (argc > 0) {
745 rb_raise(rb_eArgError, "wrong number of arguments (%d for 0)", argc);
747 result = rb_ary_new();
748 for (i = 0; i < RSTRUCT_LEN(s); i++) {
749 if (RTEST(rb_yield(RSTRUCT_PTR(s)[i]))) {
750 rb_ary_push(result, RSTRUCT_PTR(s)[i]);
754 return result;
758 * call-seq:
759 * struct == other_struct => true or false
761 * Equality---Returns <code>true</code> if <i>other_struct</i> is
762 * equal to this one: they must be of the same class as generated by
763 * <code>Struct::new</code>, and the values of all instance variables
764 * must be equal (according to <code>Object#==</code>).
766 * Customer = Struct.new(:name, :address, :zip)
767 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
768 * joejr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
769 * jane = Customer.new("Jane Doe", "456 Elm, Anytown NC", 12345)
770 * joe == joejr #=> true
771 * joe == jane #=> false
774 static VALUE
775 rb_struct_equal(VALUE s, VALUE s2)
777 long i;
779 if (s == s2) return Qtrue;
780 if (TYPE(s2) != T_STRUCT) return Qfalse;
781 if (rb_obj_class(s) != rb_obj_class(s2)) return Qfalse;
782 if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) {
783 rb_bug("inconsistent struct"); /* should never happen */
786 for (i=0; i<RSTRUCT_LEN(s); i++) {
787 if (!rb_equal(RSTRUCT_PTR(s)[i], RSTRUCT_PTR(s2)[i])) return Qfalse;
789 return Qtrue;
793 * call-seq:
794 * struct.hash => fixnum
796 * Return a hash value based on this struct's contents.
799 static VALUE
800 rb_struct_hash(VALUE s)
802 long i, h;
803 VALUE n;
805 h = rb_hash(rb_obj_class(s));
806 for (i = 0; i < RSTRUCT_LEN(s); i++) {
807 h = (h << 1) | (h<0 ? 1 : 0);
808 n = rb_hash(RSTRUCT_PTR(s)[i]);
809 h ^= NUM2LONG(n);
811 return LONG2FIX(h);
815 * code-seq:
816 * struct.eql?(other) => true or false
818 * Two structures are equal if they are the same object, or if all their
819 * fields are equal (using <code>eql?</code>).
822 static VALUE
823 rb_struct_eql(VALUE s, VALUE s2)
825 long i;
827 if (s == s2) return Qtrue;
828 if (TYPE(s2) != T_STRUCT) return Qfalse;
829 if (rb_obj_class(s) != rb_obj_class(s2)) return Qfalse;
830 if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) {
831 rb_bug("inconsistent struct"); /* should never happen */
834 for (i=0; i<RSTRUCT_LEN(s); i++) {
835 if (!rb_eql(RSTRUCT_PTR(s)[i], RSTRUCT_PTR(s2)[i])) return Qfalse;
837 return Qtrue;
841 * call-seq:
842 * struct.length => fixnum
843 * struct.size => fixnum
845 * Returns the number of instance variables.
847 * Customer = Struct.new(:name, :address, :zip)
848 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
849 * joe.length #=> 3
852 static VALUE
853 rb_struct_size(VALUE s)
855 return LONG2FIX(RSTRUCT_LEN(s));
859 * A <code>Struct</code> is a convenient way to bundle a number of
860 * attributes together, using accessor methods, without having to write
861 * an explicit class.
863 * The <code>Struct</code> class is a generator of specific classes,
864 * each one of which is defined to hold a set of variables and their
865 * accessors. In these examples, we'll call the generated class
866 * ``<i>Customer</i>Class,'' and we'll show an example instance of that
867 * class as ``<i>Customer</i>Inst.''
869 * In the descriptions that follow, the parameter <i>symbol</i> refers
870 * to a symbol, which is either a quoted string or a
871 * <code>Symbol</code> (such as <code>:name</code>).
873 void
874 Init_Struct(void)
876 rb_cStruct = rb_define_class("Struct", rb_cObject);
877 rb_include_module(rb_cStruct, rb_mEnumerable);
879 rb_undef_alloc_func(rb_cStruct);
880 rb_define_singleton_method(rb_cStruct, "new", rb_struct_s_def, -1);
882 rb_define_method(rb_cStruct, "initialize", rb_struct_initialize, -2);
883 rb_define_method(rb_cStruct, "initialize_copy", rb_struct_init_copy, 1);
885 rb_define_method(rb_cStruct, "==", rb_struct_equal, 1);
886 rb_define_method(rb_cStruct, "eql?", rb_struct_eql, 1);
887 rb_define_method(rb_cStruct, "hash", rb_struct_hash, 0);
889 rb_define_method(rb_cStruct, "to_s", rb_struct_inspect, 0);
890 rb_define_method(rb_cStruct, "inspect", rb_struct_inspect, 0);
891 rb_define_method(rb_cStruct, "to_a", rb_struct_to_a, 0);
892 rb_define_method(rb_cStruct, "values", rb_struct_to_a, 0);
893 rb_define_method(rb_cStruct, "size", rb_struct_size, 0);
894 rb_define_method(rb_cStruct, "length", rb_struct_size, 0);
896 rb_define_method(rb_cStruct, "each", rb_struct_each, 0);
897 rb_define_method(rb_cStruct, "each_pair", rb_struct_each_pair, 0);
898 rb_define_method(rb_cStruct, "[]", rb_struct_aref, 1);
899 rb_define_method(rb_cStruct, "[]=", rb_struct_aset, 2);
900 rb_define_method(rb_cStruct, "select", rb_struct_select, -1);
901 rb_define_method(rb_cStruct, "values_at", rb_struct_values_at, -1);
903 rb_define_method(rb_cStruct, "members", rb_struct_members_m, 0);