OSDN Git Service

7e6da06c68151fb304fdc3841664e36de3b7dbcc
[splhack/AndroidRuby.git] / lib / ruby-1.9.1-rc1 / struct.c
1 /**********************************************************************
2
3   struct.c -
4
5   $Author: yugui $
6   created at: Tue Mar 22 18:44:30 JST 1995
7
8   Copyright (C) 1993-2007 Yukihiro Matsumoto
9
10 **********************************************************************/
11
12 #include "ruby/ruby.h"
13
14 VALUE rb_cStruct;
15
16 static VALUE struct_alloc(VALUE);
17
18 VALUE
19 rb_struct_iv_get(VALUE c, const char *name)
20 {
21     ID id;
22
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;
30     }
31 }
32
33 VALUE
34 rb_struct_s_members(VALUE klass)
35 {
36     VALUE members = rb_struct_iv_get(klass, "__members__");
37
38     if (NIL_P(members)) {
39         rb_raise(rb_eTypeError, "uninitialized struct");
40     }
41     if (TYPE(members) != T_ARRAY) {
42         rb_raise(rb_eTypeError, "corrupted struct");
43     }
44     return members;
45 }
46
47 VALUE
48 rb_struct_members(VALUE s)
49 {
50     VALUE members = rb_struct_s_members(rb_obj_class(s));
51
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));
55     }
56     return members;
57 }
58
59 static VALUE
60 rb_struct_s_members_m(VALUE klass)
61 {
62     VALUE members, ary;
63     VALUE *p, *pend;
64
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++;
71     }
72
73     return ary;
74 }
75
76 /*
77  *  call-seq:
78  *     struct.members    => array
79  *  
80  *  Returns an array of strings representing the names of the instance
81  *  variables.
82  *     
83  *     Customer = Struct.new(:name, :address, :zip)
84  *     joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
85  *     joe.members   #=> [:name, :address, :zip]
86  */
87
88 static VALUE
89 rb_struct_members_m(VALUE obj)
90 {
91     return rb_struct_s_members_m(rb_obj_class(obj));
92 }
93
94 VALUE
95 rb_struct_getmember(VALUE obj, ID id)
96 {
97     VALUE members, slot;
98     long i;
99
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];
105         }
106     }
107     rb_name_error(id, "%s is not struct member", rb_id2name(id));
108     return Qnil;                /* not reached */
109 }
110
111 static VALUE
112 rb_struct_ref(VALUE obj)
113 {
114     return rb_struct_getmember(obj, rb_frame_this_func());
115 }
116
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];}
127
128 #define N_REF_FUNC (sizeof(ref_func) / sizeof(ref_func[0]))
129
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,
141 };
142
143 static void
144 rb_struct_modify(VALUE s)
145 {
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");
149 }
150
151 static VALUE
152 rb_struct_set(VALUE obj, VALUE val)
153 {
154     VALUE members, slot;
155     long i;
156
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;
163         }
164     }
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 */
168 }
169
170 static VALUE
171 make_struct(VALUE name, VALUE members, VALUE klass)
172 {
173     VALUE nstr;
174     ID id;
175     long i;
176
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);
182     }
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));
189         }
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));
193         }
194         nstr = rb_define_class_under(klass, rb_id2name(id), klass);
195     }
196     rb_iv_set(nstr, "__members__", members);
197
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);
207             }
208             else {
209                 rb_define_method_id(nstr, id, rb_struct_ref, 0);
210             }
211             rb_define_method_id(nstr, rb_id_attrset(id), rb_struct_set, 1);
212         }
213     }
214
215     return nstr;
216 }
217
218 VALUE
219 rb_struct_alloc_noinit(VALUE klass)
220 {
221     return struct_alloc(klass);
222 }
223
224 VALUE
225 rb_struct_define_without_accessor(const char *class_name, VALUE super, rb_alloc_func_t alloc, ...)
226 {
227     VALUE klass;
228     va_list ar;
229     VALUE members;
230     long i;
231     char *name;
232
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)));
238     }
239     va_end(ar);
240     OBJ_FREEZE(members);
241
242     if (class_name) {
243         klass = rb_define_class(class_name, super);
244     }
245     else {
246         klass = rb_class_new(super);
247         rb_make_metaclass(klass, RBASIC(super)->klass);
248         rb_class_inherited(super, klass);
249     }
250
251     rb_iv_set(klass, "__members__", members);
252
253     if (alloc)
254         rb_define_alloc_func(klass, alloc);
255     else
256         rb_define_alloc_func(klass, struct_alloc);
257
258     return klass;
259 }
260
261 VALUE
262 rb_struct_define(const char *name, ...)
263 {
264     va_list ar;
265     VALUE nm, ary;
266     char *mem;
267
268     if (!name) nm = Qnil;
269     else nm = rb_str_new2(name);
270     ary = rb_ary_new();
271
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));
276     }
277     va_end(ar);
278
279     return make_struct(nm, ary, rb_cStruct);
280 }
281
282 /*
283  *  call-seq:
284  *     Struct.new( [aString] [, aSym]+> )    => StructClass
285  *     StructClass.new(arg, ...)             => obj
286  *     StructClass[arg, ...]                 => obj
287  *
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.
296  *     
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}.
303  *
304  *  The remaining methods listed in this section (class and instance)
305  *  are defined for this generated class. 
306  *     
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">
310  *     
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">
314  */
315
316 static VALUE
317 rb_struct_s_def(int argc, VALUE *argv, VALUE klass)
318 {
319     VALUE name, rest;
320     long i;
321     VALUE st;
322     ID id;
323
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;
328     }
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);
332     }
333     st = make_struct(name, rest, klass);
334     if (rb_block_given_p()) {
335         rb_mod_module_eval(0, 0, st);
336     }
337
338     return st;
339 }
340
341 static size_t
342 num_members(VALUE klass)
343 {
344     VALUE members;
345     members = rb_struct_iv_get(klass, "__members__");
346     if (TYPE(members) != T_ARRAY) {
347         rb_raise(rb_eTypeError, "broken members");
348     }
349     return RARRAY_LEN(members);
350 }
351
352 /*
353  */
354
355 static VALUE
356 rb_struct_initialize_m(int argc, VALUE *argv, VALUE self)
357 {
358     VALUE klass = rb_obj_class(self);
359     long n;
360
361     rb_struct_modify(self);
362     n = num_members(klass);
363     if (n < argc) {
364         rb_raise(rb_eArgError, "struct size differs");
365     }
366     MEMCPY(RSTRUCT_PTR(self), argv, VALUE, argc);
367     if (n > argc) {
368         rb_mem_clear(RSTRUCT_PTR(self)+argc, n-argc);
369     }
370     return Qnil;
371 }
372
373 VALUE
374 rb_struct_initialize(VALUE self, VALUE values)
375 {
376     return rb_struct_initialize_m(RARRAY_LEN(values), RARRAY_PTR(values), self);
377 }
378
379 static VALUE
380 struct_alloc(VALUE klass)
381 {
382     long n;
383     NEWOBJ(st, struct RStruct);
384     OBJSETUP(st, klass, T_STRUCT);
385
386     n = num_members(klass);
387
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);
392     }
393     else {
394         st->as.heap.ptr = ALLOC_N(VALUE, n);
395         rb_mem_clear(st->as.heap.ptr, n);
396         st->as.heap.len = n;
397     }
398
399     return (VALUE)st;
400 }
401
402 VALUE
403 rb_struct_alloc(VALUE klass, VALUE values)
404 {
405     return rb_class_new_instance(RARRAY_LEN(values), RARRAY_PTR(values), klass);
406 }
407
408 VALUE
409 rb_struct_new(VALUE klass, ...)
410 {
411     VALUE *mem;
412     long size, i;
413     va_list args;
414
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);
420     }
421     va_end(args);
422
423     return rb_class_new_instance(size, mem, klass);
424 }
425
426 /*
427  *  call-seq:
428  *     struct.each {|obj| block }  => struct
429  *  
430  *  Calls <i>block</i> once for each instance variable, passing the
431  *  value as a parameter.
432  *     
433  *     Customer = Struct.new(:name, :address, :zip)
434  *     joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
435  *     joe.each {|x| puts(x) }
436  *     
437  *  <em>produces:</em>
438  *     
439  *     Joe Smith
440  *     123 Maple, Anytown NC
441  *     12345
442  */
443
444 static VALUE
445 rb_struct_each(VALUE s)
446 {
447     long i;
448
449     RETURN_ENUMERATOR(s, 0, 0);
450     for (i=0; i<RSTRUCT_LEN(s); i++) {
451         rb_yield(RSTRUCT_PTR(s)[i]);
452     }
453     return s;
454 }
455
456 /*
457  *  call-seq:
458  *     struct.each_pair {|sym, obj| block }     => struct
459  *  
460  *  Calls <i>block</i> once for each instance variable, passing the name
461  *  (as a symbol) and the value as parameters.
462  *     
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}") }
466  *     
467  *  <em>produces:</em>
468  *     
469  *     name => Joe Smith
470  *     address => 123 Maple, Anytown NC
471  *     zip => 12345
472  */
473
474 static VALUE
475 rb_struct_each_pair(VALUE s)
476 {
477     VALUE members;
478     long i;
479
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]);
484     }
485     return s;
486 }
487
488 static VALUE
489 inspect_struct(VALUE s, VALUE dummy, int recur)
490 {
491     const char *cname = rb_class2name(rb_obj_class(s));
492     VALUE str, members;
493     long i;
494
495     if (recur) {
496         return rb_sprintf("#<struct %s:...>", cname);
497     }
498
499     members = rb_struct_members(s);
500     if (cname[0] == '#') {
501         str = rb_str_new2("#<struct ");
502     }
503     else {
504         str = rb_sprintf("#<struct %s ", cname);
505     }
506     for (i=0; i<RSTRUCT_LEN(s); i++) {
507         VALUE slot;
508         ID id;
509
510         if (i > 0) {
511             rb_str_cat2(str, ", ");
512         }
513         slot = RARRAY_PTR(members)[i];
514         id = SYM2ID(slot);
515         if (rb_is_local_id(id) || rb_is_const_id(id)) {
516             rb_str_append(str, rb_id2str(id));
517         }
518         else {
519             rb_str_append(str, rb_inspect(slot));
520         }
521         rb_str_cat2(str, "=");
522         rb_str_append(str, rb_inspect(RSTRUCT_PTR(s)[i]));
523     }
524     rb_str_cat2(str, ">");
525     OBJ_INFECT(str, s);
526
527     return str;
528 }
529
530 /*
531  * call-seq:
532  *   struct.to_s      => string
533  *   struct.inspect   => string
534  *
535  * Describe the contents of this struct in a string.
536  */
537
538 static VALUE
539 rb_struct_inspect(VALUE s)
540 {
541     return rb_exec_recursive(inspect_struct, s, 0);
542 }
543
544 /*
545  *  call-seq:
546  *     struct.to_a     => array
547  *     struct.values   => array
548  *  
549  *  Returns the values for this instance as an array.
550  *     
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"
554  */
555
556 static VALUE
557 rb_struct_to_a(VALUE s)
558 {
559     return rb_ary_new4(RSTRUCT_LEN(s), RSTRUCT_PTR(s));
560 }
561
562 /* :nodoc: */
563 VALUE
564 rb_struct_init_copy(VALUE copy, VALUE s)
565 {
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");
570     }
571     if (RSTRUCT_LEN(copy) != RSTRUCT_LEN(s)) {
572         rb_raise(rb_eTypeError, "struct size mismatch");
573     }
574     MEMCPY(RSTRUCT_PTR(copy), RSTRUCT_PTR(s), VALUE, RSTRUCT_LEN(copy));
575
576     return copy;
577 }
578
579 static VALUE
580 rb_struct_aref_id(VALUE s, ID id)
581 {
582     VALUE members;
583     long i, len;
584
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];
590         }
591     }
592     rb_name_error(id, "no member '%s' in struct", rb_id2name(id));
593     return Qnil;                /* not reached */
594 }
595
596 /*
597  *  call-seq:
598  *     struct[symbol]    => anObject
599  *     struct[fixnum]    => anObject 
600  *  
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
605  *  out of range.
606  *     
607  *     Customer = Struct.new(:name, :address, :zip)
608  *     joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
609  *     
610  *     joe["name"]   #=> "Joe Smith"
611  *     joe[:name]    #=> "Joe Smith"
612  *     joe[0]        #=> "Joe Smith"
613  */
614
615 VALUE
616 rb_struct_aref(VALUE s, VALUE idx)
617 {
618     long i;
619
620     if (TYPE(idx) == T_STRING || TYPE(idx) == T_SYMBOL) {
621         return rb_struct_aref_id(s, rb_to_id(idx));
622     }
623
624     i = NUM2LONG(idx);
625     if (i < 0) i = RSTRUCT_LEN(s) + i;
626     if (i < 0)
627         rb_raise(rb_eIndexError, "offset %ld too small for struct(size:%ld)",
628                  i, RSTRUCT_LEN(s));
629     if (RSTRUCT_LEN(s) <= i)
630         rb_raise(rb_eIndexError, "offset %ld too large for struct(size:%ld)",
631                  i, RSTRUCT_LEN(s));
632     return RSTRUCT_PTR(s)[i];
633 }
634
635 static VALUE
636 rb_struct_aset_id(VALUE s, ID id, VALUE val)
637 {
638     VALUE members;
639     long i, len;
640
641     members = rb_struct_members(s);
642     rb_struct_modify(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));
647     }
648     for (i=0; i<len; i++) {
649         if (SYM2ID(RARRAY_PTR(members)[i]) == id) {
650             RSTRUCT_PTR(s)[i] = val;
651             return val;
652         }
653     }
654     rb_name_error(id, "no member '%s' in struct", rb_id2name(id));
655 }
656
657 /*
658  *  call-seq:
659  *     struct[symbol] = obj    => obj
660  *     struct[fixnum] = obj    => obj
661  *  
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
666  *  is out of range.
667  *     
668  *     Customer = Struct.new(:name, :address, :zip)
669  *     joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
670  *     
671  *     joe["name"] = "Luke"
672  *     joe[:zip]   = "90210"
673  *     
674  *     joe.name   #=> "Luke"
675  *     joe.zip    #=> "90210"
676  */
677
678 VALUE
679 rb_struct_aset(VALUE s, VALUE idx, VALUE val)
680 {
681     long i;
682
683     if (TYPE(idx) == T_STRING || TYPE(idx) == T_SYMBOL) {
684         return rb_struct_aset_id(s, rb_to_id(idx), val);
685     }
686
687     i = NUM2LONG(idx);
688     if (i < 0) i = RSTRUCT_LEN(s) + i;
689     if (i < 0) {
690         rb_raise(rb_eIndexError, "offset %ld too small for struct(size:%ld)",
691                  i, RSTRUCT_LEN(s));
692     }
693     if (RSTRUCT_LEN(s) <= i) {
694         rb_raise(rb_eIndexError, "offset %ld too large for struct(size:%ld)",
695                  i, RSTRUCT_LEN(s));
696     }
697     rb_struct_modify(s);
698     return RSTRUCT_PTR(s)[i] = val;
699 }
700
701 static VALUE
702 struct_entry(VALUE s, long n)
703 {
704     return rb_struct_aref(s, LONG2NUM(n));
705 }
706
707 /* 
708  * call-seq:
709  *   struct.values_at(selector,... )  => an_array
710  *
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>.
715  * 
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)
721  */
722
723 static VALUE
724 rb_struct_values_at(int argc, VALUE *argv, VALUE s)
725 {
726     return rb_get_values_at(s, RSTRUCT_LEN(s), argc, argv, struct_entry);
727 }
728
729 /*
730  *  call-seq:
731  *     struct.select {|i| block }    => array
732  *  
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>).
737  *     
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]
741  */
742
743 static VALUE
744 rb_struct_select(int argc, VALUE *argv, VALUE s)
745 {
746     VALUE result;
747     long i;
748
749     if (argc > 0) {
750         rb_raise(rb_eArgError, "wrong number of arguments (%d for 0)", argc);
751     }
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]);
756         }
757     }
758
759     return result;
760 }
761
762 /*
763  *  call-seq:
764  *     struct == other_struct     => true or false
765  *  
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>).
770  *     
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
777  */
778
779 static VALUE
780 rb_struct_equal(VALUE s, VALUE s2)
781 {
782     long i;
783
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 */
789     }
790
791     for (i=0; i<RSTRUCT_LEN(s); i++) {
792         if (!rb_equal(RSTRUCT_PTR(s)[i], RSTRUCT_PTR(s2)[i])) return Qfalse;
793     }
794     return Qtrue;
795 }
796
797 /*
798  * call-seq:
799  *   struct.hash   => fixnum
800  *
801  * Return a hash value based on this struct's contents.
802  */
803
804 static VALUE
805 rb_struct_hash(VALUE s)
806 {
807     long i, h;
808     VALUE n;
809
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]);
814         h ^= NUM2LONG(n);
815     }
816     return LONG2FIX(h);
817 }
818
819 /*
820  * code-seq:
821  *   struct.eql?(other)   => true or false
822  *
823  * Two structures are equal if they are the same object, or if all their
824  * fields are equal (using <code>eql?</code>).
825  */
826
827 static VALUE
828 rb_struct_eql(VALUE s, VALUE s2)
829 {
830     long i;
831
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 */
837     }
838
839     for (i=0; i<RSTRUCT_LEN(s); i++) {
840         if (!rb_eql(RSTRUCT_PTR(s)[i], RSTRUCT_PTR(s2)[i])) return Qfalse;
841     }
842     return Qtrue;
843 }
844
845 /*
846  *  call-seq:
847  *     struct.length    => fixnum
848  *     struct.size      => fixnum
849  *  
850  *  Returns the number of instance variables.
851  *     
852  *     Customer = Struct.new(:name, :address, :zip)
853  *     joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
854  *     joe.length   #=> 3
855  */
856
857 static VALUE
858 rb_struct_size(VALUE s)
859 {
860     return LONG2FIX(RSTRUCT_LEN(s));
861 }
862
863 /*
864  *  A <code>Struct</code> is a convenient way to bundle a number of
865  *  attributes together, using accessor methods, without having to write
866  *  an explicit class.
867  *     
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.''
873  *     
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>).
877  */
878 void
879 Init_Struct(void)
880 {
881     rb_cStruct = rb_define_class("Struct", rb_cObject);
882     rb_include_module(rb_cStruct, rb_mEnumerable);
883
884     rb_undef_alloc_func(rb_cStruct);
885     rb_define_singleton_method(rb_cStruct, "new", rb_struct_s_def, -1);
886
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);
889
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);
893
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);
900
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);
907
908     rb_define_method(rb_cStruct, "members", rb_struct_members_m, 0);
909 }