Ruby 4.1.0dev (2026-11-23 revision cdaa37faa464d79ec79af428a7ae956a020f654e)
struct.c (cdaa37faa464d79ec79af428a7ae956a020f654e)
1/**********************************************************************
2
3 struct.c -
4
5 $Author$
6 created at: Tue Mar 22 18:44:30 JST 1995
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9
10**********************************************************************/
11
12#include "id.h"
13#include "internal.h"
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"
21#include "vm_core.h"
22#include "builtin.h"
23
24/* only for struct[:field] access */
25enum {
26 AREF_HASH_UNIT = 5,
27 AREF_HASH_THRESHOLD = 10
28};
29
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. */
34static VALUE rb_cData;
35
36// The classes that Struct.new, Data.define and the C API make have one inline
37// field, holding a hidden object that wraps this. Their subclasses share it.
39 VALUE members; // frozen hidden Array of the member names
40 VALUE back_members; // what struct_member_pos() searches
41 VALUE keyword_init; // the keyword_init option of Struct.new
42};
43
44RUBY_REFERENCES(struct_info_refs) = {
45 RUBY_REF_EDGE(struct struct_info, members),
46 RUBY_REF_EDGE(struct struct_info, back_members),
47 RUBY_REF_EDGE(struct struct_info, keyword_init),
48 RUBY_REF_END
49};
50
51static const rb_data_type_t struct_info_type = {
52 "struct/info",
53 {
54 RUBY_REFS_LIST_PTR(struct_info_refs),
56 NULL, // Nothing allocated outside of the object
57 },
58 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_DECL_MARKING | RUBY_TYPED_EMBEDDABLE
59};
60
61static VALUE struct_alloc(VALUE);
62
63// NULL when +klass+ is not a Struct / Data class.
64static inline const struct struct_info *
65struct_info_of(VALUE klass)
66{
67 if (LIKELY(RCLASS_HAS_STRUCT_INLINE_FIELD(klass))) {
68 VALUE info = RCLASS_STRUCT_INLINE_FIELD(klass);
69 if (LIKELY(!NIL_P(info))) return RTYPEDDATA_GET_DATA(info);
70 }
71 return NULL;
72}
73
74// nil for a class that is not a Struct / Data class.
75static inline VALUE
76struct_s_members(VALUE klass)
77{
78 const struct struct_info *info = struct_info_of(klass);
79 return info ? info->members : Qnil;
80}
81
83rb_struct_s_keyword_init(VALUE klass)
84{
85 const struct struct_info *info = struct_info_of(klass);
86 return info ? info->keyword_init : Qnil;
87}
88
91{
92 Check_Type(klass, T_CLASS);
93 VALUE members = struct_s_members(klass);
94
95 if (NIL_P(members)) {
96 rb_raise(rb_eTypeError, "uninitialized struct");
97 }
98 return members;
99}
100
101VALUE
103{
105
106 if (RSTRUCT_LEN_RAW(s) != RARRAY_LEN(members)) {
107 rb_raise(rb_eTypeError, "struct size differs (%"PRIdLEN" required %"PRIdLEN" given)",
108 RARRAY_LEN(members), RSTRUCT_LEN_RAW(s));
109 }
110 return members;
111}
112
113static rb_len_t
114struct_member_pos_ideal(VALUE name, rb_len_t mask)
115{
116 /* (id & (mask/2)) * 2 */
117 return (SYM2ID(name) >> (ID_SCOPE_SHIFT - 1)) & mask;
118}
119
120static rb_len_t
121struct_member_pos_probe(rb_len_t prev, rb_len_t mask)
122{
123 /* (((prev/2) * AREF_HASH_UNIT + 1) & (mask/2)) * 2 */
124 return (prev * AREF_HASH_UNIT + 2) & mask;
125}
126
127static VALUE
128struct_set_members(VALUE klass, VALUE /* frozen hidden array */ members)
129{
130 VALUE back;
131 const rb_len_t members_length = RARRAY_LEN(members);
132
133 if (members_length <= AREF_HASH_THRESHOLD) {
134 back = members;
135 }
136 else {
137 rb_len_t i, j, mask = 64;
138 VALUE name;
139
140 while (mask < members_length * AREF_HASH_UNIT) mask *= 2;
141
142 back = rb_ary_hidden_new(mask + 1);
143 rb_ary_store(back, mask, INT2FIX(members_length));
144 mask -= 2; /* mask = (2**k-1)*2 */
145
146 for (i=0; i < members_length; i++) {
147 name = RARRAY_AREF(members, i);
148
149 j = struct_member_pos_ideal(name, mask);
150
151 for (;;) {
152 if (!RTEST(RARRAY_AREF(back, j))) {
153 rb_ary_store(back, j, name);
154 rb_ary_store(back, j + 1, INT2FIX(i));
155 break;
156 }
157 j = struct_member_pos_probe(j, mask);
158 }
159 }
160 OBJ_FREEZE(back);
161 }
162 struct struct_info *info;
163 VALUE info_obj = TypedData_Make_Struct(0, struct struct_info, &struct_info_type, info);
164 RB_OBJ_WRITE(info_obj, &info->members, members);
165 RB_OBJ_WRITE(info_obj, &info->back_members, back);
166 info->keyword_init = Qnil;
167 RCLASS_SET_STRUCT_INLINE_FIELD(klass, info_obj);
168
169 return members;
170}
171
172static inline int
173struct_member_pos(VALUE s, VALUE name)
174{
175 const struct struct_info *info = struct_info_of(rb_obj_class(s));
176 rb_len_t j, mask;
177
178 if (UNLIKELY(!info)) {
179 rb_raise(rb_eTypeError, "uninitialized struct");
180 }
181 VALUE back = info->back_members;
182
183 mask = RARRAY_LEN(back);
184
185 if (mask <= AREF_HASH_THRESHOLD) {
186 if (UNLIKELY(RSTRUCT_LEN_RAW(s) != mask)) {
187 rb_raise(rb_eTypeError,
188 "struct size differs (%"PRIdLEN" required %"PRIdLEN" given)",
189 mask, RSTRUCT_LEN_RAW(s));
190 }
191 for (j = 0; j < mask; j++) {
192 if (RARRAY_AREF(back, j) == name)
193 return (int)j;
194 }
195 return -1;
196 }
197
198 if (UNLIKELY(RSTRUCT_LEN_RAW(s) != FIX2INT(RARRAY_AREF(back, mask-1)))) {
199 rb_raise(rb_eTypeError, "struct size differs (%d required %"PRIdLEN" given)",
200 FIX2INT(RARRAY_AREF(back, mask-1)), RSTRUCT_LEN_RAW(s));
201 }
202
203 mask -= 3;
204 j = struct_member_pos_ideal(name, mask);
205
206 for (;;) {
207 VALUE e = RARRAY_AREF(back, j);
208 if (e == name)
209 return FIX2INT(RARRAY_AREF(back, j + 1));
210 if (!RTEST(e)) {
211 return -1;
212 }
213 j = struct_member_pos_probe(j, mask);
214 }
215}
216
217/*
218 * call-seq:
219 * StructClass::members -> array_of_symbols
220 *
221 * Returns the member names of the Struct descendant as an array:
222 *
223 * Customer = Struct.new(:name, :address, :zip)
224 * Customer.members # => [:name, :address, :zip]
225 *
226 */
227
228static VALUE
229rb_struct_s_members_m(VALUE klass)
230{
231 VALUE members = rb_struct_s_members(klass);
232
233 return rb_ary_dup(members);
234}
235
236/*
237 * call-seq:
238 * members -> array_of_symbols
239 *
240 * Returns the member names from +self+ as an array:
241 *
242 * Customer = Struct.new(:name, :address, :zip)
243 * Customer.new.members # => [:name, :address, :zip]
244 *
245 * Related: #to_a.
246 */
247
248static VALUE
249rb_struct_members_m(VALUE obj)
250{
251 return rb_struct_s_members_m(rb_obj_class(obj));
252}
253
254VALUE
256{
257 VALUE slot = ID2SYM(id);
258 int i = struct_member_pos(obj, slot);
259 if (i != -1) {
260 return RSTRUCT_GET_RAW(obj, i);
261 }
262 rb_name_err_raise("'%1$s' is not a struct member", obj, ID2SYM(id));
263
265}
266
267static void
268rb_struct_modify(VALUE s)
269{
270 rb_check_frozen(s);
271}
272
273static VALUE
274anonymous_struct(VALUE klass)
275{
276 VALUE nstr = rb_class_new_with_struct_inline_field(klass);
277 rb_make_metaclass(nstr, RBASIC(klass)->klass);
278 return nstr;
279}
280
281NORETURN(static void invalid_struct_pos(VALUE s, VALUE idx));
282
283static void
284define_aref_method(VALUE nstr, VALUE name, VALUE off)
285{
286 rb_add_method_optimized(nstr, SYM2ID(name), OPTIMIZED_METHOD_TYPE_STRUCT_AREF, FIX2UINT(off), METHOD_VISI_PUBLIC);
287}
288
289void
290rb_struct_define_aref_method(VALUE nstr, ID name, unsigned int off)
291{
292 rb_add_method_optimized(nstr, name, OPTIMIZED_METHOD_TYPE_STRUCT_AREF, off, METHOD_VISI_PUBLIC);
293}
294
295static void
296define_aset_method(VALUE nstr, VALUE name, VALUE off)
297{
298 rb_add_method_optimized(nstr, SYM2ID(name), OPTIMIZED_METHOD_TYPE_STRUCT_ASET, FIX2UINT(off), METHOD_VISI_PUBLIC);
299}
300
301static VALUE
302rb_struct_s_inspect(VALUE klass)
303{
304 VALUE inspect = rb_class_name(klass);
305 if (RTEST(rb_struct_s_keyword_init(klass))) {
306 rb_str_cat_cstr(inspect, "(keyword_init: true)");
307 }
308 return inspect;
309}
310
311static VALUE rb_data_initialize_m(int argc, const VALUE *argv, VALUE self);
312
313// Given every member, Data#initialize can only store them and freeze the
314// instance: it raises nothing and calls no Ruby code. So when initialize is
315// that method, the members can be stored without calling it.
316static bool
317data_initialize_default_p(VALUE klass)
318{
319 const rb_callable_method_entry_t *cme = rb_callable_method_entry(klass, idInitialize);
320 return cme && cme->def->type == VM_METHOD_TYPE_CFUNC &&
321 cme->def->body.cfunc.func == (rb_cfunc_t)rb_data_initialize_m;
322}
323
324static VALUE
325rb_data_s_new(int argc, const VALUE *argv, VALUE klass)
326{
327 if (rb_keyword_given_p()) {
328 if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) {
329 rb_error_arity(argc, 0, 0);
330 }
331 return rb_class_new_instance_pass_kw(argc, argv, klass);
332 }
333 else {
334 VALUE members = struct_s_members(klass);
335 int num_members = RARRAY_LENINT(members);
336
337 rb_check_arity(argc, 0, num_members);
338 if (argc == num_members && data_initialize_default_p(klass)) {
339 VALUE self = rb_obj_alloc(klass);
340 for (rb_len_t i=0; i<argc; i++) {
341 RSTRUCT_SET_RAW(self, i, argv[i]);
342 }
343 OBJ_FREEZE(self);
344 return self;
345 }
346 VALUE arg_hash = rb_hash_new_capa(argc);
347 for (rb_len_t i=0; i<argc; i++) {
348 VALUE k = rb_ary_entry(members, i), v = argv[i];
349 rb_hash_aset(arg_hash, k, v);
350 }
351 return rb_class_new_instance_kw(1, &arg_hash, klass, RB_PASS_KEYWORDS);
352 }
353}
354
355#if 0 /* for RDoc */
356
357/*
358 * call-seq:
359 * StructClass::keyword_init? -> true or falsy value
360 *
361 * Returns +true+ if the class was initialized with <tt>keyword_init: true</tt>.
362 * Otherwise returns +nil+ or +false+.
363 *
364 * Examples:
365 * Foo = Struct.new(:a)
366 * Foo.keyword_init? # => nil
367 * Bar = Struct.new(:a, keyword_init: true)
368 * Bar.keyword_init? # => true
369 * Baz = Struct.new(:a, keyword_init: false)
370 * Baz.keyword_init? # => false
371 */
372static VALUE
373rb_struct_s_keyword_init_p(VALUE obj)
374{
375}
376#endif
377
378#define rb_struct_s_keyword_init_p rb_struct_s_keyword_init
379
380static VALUE
381setup_struct(VALUE nstr, VALUE members)
382{
383 rb_len_t i, len;
384
385 members = struct_set_members(nstr, members);
386
387 rb_define_alloc_func(nstr, struct_alloc);
390 rb_define_singleton_method(nstr, "members", rb_struct_s_members_m, 0);
391 rb_define_singleton_method(nstr, "inspect", rb_struct_s_inspect, 0);
392 rb_define_singleton_method(nstr, "keyword_init?", rb_struct_s_keyword_init_p, 0);
393
394 len = RARRAY_LEN(members);
395 for (i=0; i< len; i++) {
396 VALUE sym = RARRAY_AREF(members, i);
397 ID id = SYM2ID(sym);
398 VALUE off = LEN2NUM(i);
399
400 define_aref_method(nstr, sym, off);
401 define_aset_method(nstr, ID2SYM(rb_id_attrset(id)), off);
402 }
403
404 return nstr;
405}
406
407static VALUE
408setup_data(VALUE subclass, VALUE members)
409{
410 rb_len_t i, len;
411
412 members = struct_set_members(subclass, members);
413
414 rb_define_alloc_func(subclass, struct_alloc);
415 VALUE sclass = rb_singleton_class(subclass);
416 rb_undef_method(sclass, "define");
417 rb_define_method(sclass, "new", rb_data_s_new, -1);
418 rb_define_method(sclass, "[]", rb_data_s_new, -1);
419 rb_define_method(sclass, "members", rb_struct_s_members_m, 0);
420 rb_define_method(sclass, "inspect", rb_struct_s_inspect, 0); // FIXME: just a separate method?..
421
422 len = RARRAY_LEN(members);
423 for (i=0; i< len; i++) {
424 VALUE sym = RARRAY_AREF(members, i);
425 VALUE off = LEN2NUM(i);
426
427 define_aref_method(subclass, sym, off);
428 }
429
430 return subclass;
431}
432
433VALUE
435{
436 return struct_alloc(klass);
437}
438
439static VALUE
440struct_make_members_list(va_list ar)
441{
442 char *mem;
443 VALUE ary, list = rb_ident_hash_new();
444 RBASIC_CLEAR_CLASS(list);
445 while ((mem = va_arg(ar, char*)) != 0) {
446 VALUE sym = rb_sym_intern_ascii_cstr(mem);
447 if (RTEST(rb_hash_has_key(list, sym))) {
448 rb_raise(rb_eArgError, "duplicate member: %s", mem);
449 }
450 rb_hash_aset(list, sym, Qtrue);
451 }
452 ary = rb_hash_keys(list);
453 RBASIC_CLEAR_CLASS(ary);
454 OBJ_FREEZE(ary);
455 return ary;
456}
457
458static void
459struct_register_under(VALUE outer, VALUE name, VALUE klass)
460{
461 if (!outer) outer = rb_cObject;
462
463 name = rb_str_to_str(name);
464
465 if (!rb_is_const_name(name)) {
466 rb_name_err_raise("identifier %1$s needs to be constant",
467 outer, name);
468 }
469
470 ID id = rb_to_id(name);
471 if (rb_const_defined_at(outer, id)) {
472 rb_warn("redefining constant %"PRIsVALUE"::%"PRIsVALUE, outer, name);
473 rb_mod_remove_const(outer, ID2SYM(id));
474 }
475
476 rb_set_class_path_string(klass, outer, name);
477 rb_const_set(outer, id, klass);
478}
479
480static VALUE
481struct_define_without_accessor(VALUE outer, const char *class_name, VALUE super, rb_alloc_func_t alloc, VALUE members)
482{
483 VALUE klass = anonymous_struct(super);
484 struct_set_members(klass, members);
485
486 if (alloc) {
487 rb_define_alloc_func(klass, alloc);
488 }
489 else {
490 rb_define_alloc_func(klass, struct_alloc);
491 }
492
493 if (class_name) {
495 struct_register_under(outer, name, klass);
496 rb_vm_register_global_object(klass);
497 }
498
499 rb_class_inherited(super, klass);
500
501 return klass;
502}
503
504VALUE
505rb_struct_define_without_accessor_under(VALUE outer, const char *class_name, VALUE super, rb_alloc_func_t alloc, ...)
506{
507 va_list ar;
508 VALUE members;
509
510 va_start(ar, alloc);
511 members = struct_make_members_list(ar);
512 va_end(ar);
513
514 return struct_define_without_accessor(outer, class_name, super, alloc, members);
515}
516
517VALUE
518rb_struct_define_without_accessor(const char *class_name, VALUE super, rb_alloc_func_t alloc, ...)
519{
520 va_list ar;
521 VALUE members;
522
523 va_start(ar, alloc);
524 members = struct_make_members_list(ar);
525 va_end(ar);
526
527 return struct_define_without_accessor(0, class_name, super, alloc, members);
528}
529
530VALUE
531rb_struct_define(const char *class_name, ...)
532{
533 va_list ar;
534
535 va_start(ar, class_name);
536 VALUE ary = struct_make_members_list(ar);
537 va_end(ar);
538
539 VALUE klass = anonymous_struct(rb_cStruct);
540 setup_struct(klass, ary);
541
542 if (class_name) {
544 struct_register_under(rb_cStruct, name, klass);
545 rb_vm_register_global_object(klass);
546 }
547
549
550 return klass;
551}
552
553VALUE
554rb_struct_define_under(VALUE outer, const char *class_name, ...)
555{
556 va_list ar;
557 VALUE ary;
558
559 va_start(ar, class_name);
560 ary = struct_make_members_list(ar);
561 va_end(ar);
562
563 VALUE klass = anonymous_struct(rb_cStruct);
564 setup_struct(klass, ary);
565
567 struct_register_under(outer, name, klass);
568 rb_vm_register_global_object(klass);
569
571
572 return klass;
573}
574
575/*
576 * call-seq:
577 * Struct.new(*member_names, keyword_init: nil){|Struct_subclass| ... } -> Struct_subclass
578 * Struct.new(class_name, *member_names, keyword_init: nil){|Struct_subclass| ... } -> Struct_subclass
579 * Struct_subclass.new(*member_names) -> Struct_subclass_instance
580 * Struct_subclass.new(**member_names) -> Struct_subclass_instance
581 *
582 * <tt>Struct.new</tt> returns a new subclass of +Struct+. The new subclass:
583 *
584 * - May be anonymous, or may have the name given by +class_name+.
585 * - May have members as given by +member_names+.
586 * - May have initialization via ordinary arguments, or via keyword arguments
587 *
588 * The new subclass has its own method <tt>::new</tt>; thus:
589 *
590 * Foo = Struct.new('Foo', :foo, :bar) # => Struct::Foo
591 * f = Foo.new(0, 1) # => #<struct Struct::Foo foo=0, bar=1>
592 *
593 * <b>Class Name</b>
594 *
595 * With string argument +class_name+,
596 * returns a new subclass of +Struct+ named <tt>Struct::<em>class_name</em></tt>:
597 *
598 * Foo = Struct.new('Foo', :foo, :bar) # => Struct::Foo
599 * Foo.name # => "Struct::Foo"
600 * Foo.superclass # => Struct
601 *
602 * Without string argument +class_name+,
603 * returns a new anonymous subclass of +Struct+:
604 *
605 * Struct.new(:foo, :bar).name # => nil
606 *
607 * <b>Block</b>
608 *
609 * With a block given, the created subclass is yielded to the block:
610 *
611 * Customer = Struct.new('Customer', :name, :address) do |new_class|
612 * p "The new subclass is #{new_class}"
613 * def greeting
614 * "Hello #{name} at #{address}"
615 * end
616 * end # => Struct::Customer
617 * dave = Customer.new('Dave', '123 Main')
618 * dave # => #<struct Struct::Customer name="Dave", address="123 Main">
619 * dave.greeting # => "Hello Dave at 123 Main"
620 *
621 * Output, from <tt>Struct.new</tt>:
622 *
623 * "The new subclass is Struct::Customer"
624 *
625 * <b>Member Names</b>
626 *
627 * Symbol arguments +member_names+
628 * determines the members of the new subclass:
629 *
630 * Struct.new(:foo, :bar).members # => [:foo, :bar]
631 * Struct.new('Foo', :foo, :bar).members # => [:foo, :bar]
632 *
633 * The new subclass has instance methods corresponding to +member_names+:
634 *
635 * Foo = Struct.new('Foo', :foo, :bar)
636 * Foo.instance_methods(false) # => [:foo, :bar, :foo=, :bar=]
637 * f = Foo.new # => #<struct Struct::Foo foo=nil, bar=nil>
638 * f.foo # => nil
639 * f.foo = 0 # => 0
640 * f.bar # => nil
641 * f.bar = 1 # => 1
642 * f # => #<struct Struct::Foo foo=0, bar=1>
643 *
644 * <b>Singleton Methods</b>
645 *
646 * A subclass returned by Struct.new has these singleton methods:
647 *
648 * - Method <tt>::new </tt> creates an instance of the subclass:
649 *
650 * Foo.new # => #<struct Struct::Foo foo=nil, bar=nil>
651 * Foo.new(0) # => #<struct Struct::Foo foo=0, bar=nil>
652 * Foo.new(0, 1) # => #<struct Struct::Foo foo=0, bar=1>
653 * Foo.new(0, 1, 2) # Raises ArgumentError: struct size differs
654 *
655 * # Initialization with keyword arguments:
656 * Foo.new(foo: 0) # => #<struct Struct::Foo foo=0, bar=nil>
657 * Foo.new(foo: 0, bar: 1) # => #<struct Struct::Foo foo=0, bar=1>
658 * Foo.new(foo: 0, bar: 1, baz: 2)
659 * # Raises ArgumentError: unknown keywords: baz
660 *
661 * - Method <tt>:inspect</tt> returns a string representation of the subclass:
662 *
663 * Foo.inspect
664 * # => "Struct::Foo"
665 *
666 * - Method <tt>::members</tt> returns an array of the member names:
667 *
668 * Foo.members # => [:foo, :bar]
669 *
670 * <b>Keyword Argument</b>
671 *
672 * By default, the arguments for initializing an instance of the new subclass
673 * can be both positional and keyword arguments.
674 *
675 * Optional keyword argument <tt>keyword_init:</tt> allows to force only one
676 * type of arguments to be accepted:
677 *
678 * KeywordsOnly = Struct.new(:foo, :bar, keyword_init: true)
679 * KeywordsOnly.new(bar: 1, foo: 0)
680 * # => #<struct KeywordsOnly foo=0, bar=1>
681 * KeywordsOnly.new(0, 1)
682 * # Raises ArgumentError: wrong number of arguments
683 *
684 * PositionalOnly = Struct.new(:foo, :bar, keyword_init: false)
685 * PositionalOnly.new(0, 1)
686 * # => #<struct PositionalOnly foo=0, bar=1>
687 * PositionalOnly.new(bar: 1, foo: 0)
688 * # => #<struct PositionalOnly foo={foo: 1, bar: 2}, bar=nil>
689 * # Note that no error is raised, but arguments treated as one hash value
690 *
691 * # Same as not providing keyword_init:
692 * Any = Struct.new(:foo, :bar, keyword_init: nil)
693 * Any.new(foo: 1, bar: 2)
694 * # => #<struct Any foo=1, bar=2>
695 * Any.new(1, 2)
696 * # => #<struct Any foo=1, bar=2>
697 */
698
699static VALUE
700rb_struct_s_def(int argc, VALUE *argv, VALUE super)
701{
702 VALUE name = Qnil, keyword_init = Qnil;
703 VALUE opt;
704
705 argc = rb_scan_args(argc, argv, "0*:", NULL, &opt);
706 if (argc >= 1 && !SYMBOL_P(argv[0])) {
707 name = argv[0];
708 --argc;
709 ++argv;
710 }
711
712 if (!NIL_P(opt)) {
713 static ID keyword_ids[1];
714
715 if (!keyword_ids[0]) {
716 keyword_ids[0] = rb_intern("keyword_init");
717 }
718 rb_get_kwargs(opt, keyword_ids, 0, 1, &keyword_init);
719 if (UNDEF_P(keyword_init)) {
720 keyword_init = Qnil;
721 }
722 else if (RTEST(keyword_init)) {
723 keyword_init = Qtrue;
724 }
725 }
726
727 VALUE rest = rb_ident_hash_new();
728 RBASIC_CLEAR_CLASS(rest);
729 for (int i = 0; i < argc; i++) {
730 VALUE mem = rb_to_symbol(argv[i]);
731 if (rb_is_attrset_sym(mem)) {
732 rb_raise(rb_eArgError, "invalid struct member: %"PRIsVALUE, mem);
733 }
734 if (RTEST(rb_hash_has_key(rest, mem))) {
735 rb_raise(rb_eArgError, "duplicate member: %"PRIsVALUE, mem);
736 }
737 rb_hash_aset(rest, mem, Qtrue);
738 }
739 rest = rb_hash_keys(rest);
740 RBASIC_CLEAR_CLASS(rest);
741 OBJ_FREEZE(rest);
742
743 VALUE klass = anonymous_struct(super);
744 setup_struct(klass, rest);
745 VALUE info_obj = RCLASS_STRUCT_INLINE_FIELD(klass);
746 struct struct_info *info = RTYPEDDATA_GET_DATA(info_obj);
747 RB_OBJ_WRITE(info_obj, &info->keyword_init, keyword_init);
748
749 if (!NIL_P(name)) {
750 struct_register_under(super, rb_str_to_str(name), klass);
751 }
752
753 rb_class_inherited(super, klass);
754
755 if (rb_block_given_p()) {
756 rb_mod_module_eval(0, 0, klass);
757 }
758
759 return klass;
760}
761
762static rb_len_t
763num_members(VALUE klass)
764{
765 VALUE members;
766 members = struct_s_members(klass);
767 if (!RB_TYPE_P(members, T_ARRAY)) {
768 rb_bug("broken members"); /* should never happen */
769 }
770 return RARRAY_LEN(members);
771}
772
774rb_zjit_struct_num_members(VALUE klass)
775{
776 return num_members(klass);
777}
778
779/*
780 */
781
783 VALUE self;
784 VALUE unknown_keywords;
785 bool *found; // Data#initialize: which members were given
786 rb_len_t missing_count;
787};
788
789static int rb_struct_pos(VALUE s, VALUE *name, bool name_only);
790static VALUE deconstruct_keys(VALUE s, VALUE keys, bool name_only);
791static int rb_struct_pos(VALUE s, VALUE *name, bool name_only);
792
793static int
794struct_hash_aset(VALUE key, VALUE val, struct struct_hash_set_arg *args, bool name_only)
795{
796 int i = rb_struct_pos(args->self, &key, name_only);
797 if (i < 0) {
798 if (!args->unknown_keywords) {
799 args->unknown_keywords = rb_ary_new();
800 }
801 rb_ary_push(args->unknown_keywords, key);
802 }
803 else {
804 rb_struct_modify(args->self);
805 RSTRUCT_SET_RAW(args->self, i, val);
806 }
807 return i;
808}
809
810static int
811struct_hash_set_i(VALUE key, VALUE val, VALUE arg)
812{
813 struct struct_hash_set_arg *args = (struct struct_hash_set_arg *)arg;
814 struct_hash_aset(key, val, args, false);
815 return ST_CONTINUE;
816}
817
818static VALUE
819rb_struct_initialize_m(int argc, const VALUE *argv, VALUE self)
820{
821 VALUE klass = rb_obj_class(self);
822 rb_struct_modify(self);
823 rb_len_t n = RSTRUCT_LEN_RAW(self);
824 if (argc == 0) {
825 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self), n);
826 return Qnil;
827 }
828
829 bool keyword_init = false;
830 switch (rb_struct_s_keyword_init(klass)) {
831 default:
832 if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) {
833 rb_error_arity(argc, 0, 0);
834 }
835 keyword_init = true;
836 break;
837 case Qfalse:
838 break;
839 case Qnil:
840 if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) {
841 break;
842 }
843 keyword_init = rb_keyword_given_p();
844 break;
845 }
846 if (keyword_init) {
847 struct struct_hash_set_arg arg = {
848 .self = self,
849 };
850 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self), n);
851 rb_hash_foreach(argv[0], struct_hash_set_i, (VALUE)&arg);
852 if (UNLIKELY(arg.unknown_keywords)) {
853 rb_raise(rb_eArgError, "unknown keywords: %"PRIsVALUE,
854 rb_ary_join(arg.unknown_keywords, rb_str_new2(", ")));
855 }
856 }
857 else {
858 if (n < argc) {
859 rb_raise(rb_eArgError, "struct size differs");
860 }
861 for (rb_len_t i=0; i<argc; i++) {
862 RSTRUCT_SET_RAW(self, i, argv[i]);
863 }
864 if (n > argc) {
865 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self)+argc, n-argc);
866 }
867 }
868 return Qnil;
869}
870
871VALUE
873{
874 rb_struct_initialize_m(RARRAY_LENINT(values), RARRAY_CONST_PTR(values), self);
875 if (rb_obj_is_kind_of(self, rb_cData)) OBJ_FREEZE(self);
876 RB_GC_GUARD(values);
877 return Qnil;
878}
879
880static VALUE *
881struct_heap_alloc(VALUE st, size_t len)
882{
883 return ALLOC_N(VALUE, len);
884}
885
886STATIC_ASSERT(robject_rstruct_fields_offset, offsetof(struct RObject, as.extended) == offsetof(struct RStruct, fields_obj));
887
888static inline bool
889struct_embedded_p(rb_len_t n)
890{
891 size_t embedded_size = offsetof(struct RStruct, as.ary) + (sizeof(VALUE) * n);
892 const rb_len_t embed_len_max = RSTRUCT_EMBED_LEN_MASK >> RSTRUCT_EMBED_LEN_SHIFT;
893 return n > 0 && n <= embed_len_max && rb_gc_size_allocatable_p(embedded_size);
894}
895
896bool
897rb_zjit_struct_embedded_p(rb_len_t num_members)
898{
899 return struct_embedded_p(num_members);
900}
901
902static VALUE
903struct_alloc(VALUE klass)
904{
905 rb_len_t n = num_members(klass);
906 size_t embedded_size = offsetof(struct RStruct, as.ary) + (sizeof(VALUE) * n);
907 VALUE flags = T_STRUCT;
908
909 if (struct_embedded_p(n)) {
910 flags |= n << RSTRUCT_EMBED_LEN_SHIFT;
911
912 VALUE st = rb_newobj(GET_EC(), klass, flags, ROOT_SHAPE_ID | SHAPE_ID_LAYOUT_EXTENDED, true, embedded_size);
913 RSTRUCT_SET_FIELDS_OBJ(st, 0);
914 rb_mem_clear((VALUE *)RSTRUCT(st)->as.ary, n);
915
916 return st;
917 }
918 else {
919 VALUE obj = rb_newobj(GET_EC(), klass, flags, ROOT_SHAPE_ID | SHAPE_ID_LAYOUT_EXTENDED, true, sizeof(struct RStruct));
920 struct RStruct *st = RSTRUCT(obj);
921
922 st->fields_obj = 0;
923 st->as.heap.ptr = NULL;
924 st->as.heap.len = 0;
925
926 st->as.heap.ptr = struct_heap_alloc((VALUE)st, n);
927 rb_mem_clear((VALUE *)st->as.heap.ptr, n);
928 st->as.heap.len = n;
929
930 return obj;
931 }
932}
933
934// Whether `klass` allocates its instances with struct_alloc.
935bool
936rb_zjit_class_has_struct_allocator(VALUE klass)
937{
938 return rb_get_alloc_func(klass) == struct_alloc;
939}
940
941// The ID of the `index`th member of the Struct class `klass`. `index` must be in bounds
942// according to rb_zjit_struct_num_members().
943ID
944rb_zjit_struct_member_id(VALUE klass, rb_len_t index)
945{
946 VALUE members = struct_s_members(klass);
947 RUBY_ASSERT(RB_TYPE_P(members, T_ARRAY));
948 RUBY_ASSERT(index >= 0 && index < RARRAY_LEN(members));
949 return SYM2ID(RARRAY_AREF(members, index));
950}
951
952VALUE
954{
955 return rb_class_new_instance(RARRAY_LENINT(values), RARRAY_CONST_PTR(values), klass);
956}
957
958VALUE
960{
961 VALUE tmpargs[16], *mem = tmpargs;
962 int size, i;
963 va_list args;
964
965 size = rb_len2int(num_members(klass));
966 if (size > numberof(tmpargs)) {
967 tmpargs[0] = rb_ary_hidden_new(size);
968 mem = RARRAY_PTR(tmpargs[0]);
969 }
970 va_start(args, klass);
971 for (i=0; i<size; i++) {
972 mem[i] = va_arg(args, VALUE);
973 }
974 va_end(args);
975
976 return rb_class_new_instance(size, mem, klass);
977}
978
979static VALUE
980struct_enum_size(VALUE s, VALUE args, VALUE eobj)
981{
982 return rb_struct_size(s);
983}
984
985/*
986 * call-seq:
987 * each {|value| ... } -> self
988 * each -> enumerator
989 *
990 * Calls the given block with the value of each member; returns +self+:
991 *
992 * Customer = Struct.new(:name, :address, :zip)
993 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
994 * joe.each {|value| p value }
995 *
996 * Output:
997 *
998 * "Joe Smith"
999 * "123 Maple, Anytown NC"
1000 * 12345
1001 *
1002 * Returns an Enumerator if no block is given.
1003 *
1004 * Related: #each_pair.
1005 */
1006
1007static VALUE
1008rb_struct_each(VALUE s)
1009{
1010 rb_len_t i;
1011
1012 RETURN_SIZED_ENUMERATOR(s, 0, 0, struct_enum_size);
1013 for (i=0; i<RSTRUCT_LEN_RAW(s); i++) {
1014 rb_yield(RSTRUCT_GET_RAW(s, i));
1015 }
1016 return s;
1017}
1018
1019/*
1020 * call-seq:
1021 * each_pair {|(name, value)| ... } -> self
1022 * each_pair -> enumerator
1023 *
1024 * Calls the given block with each member name/value pair; returns +self+:
1025 *
1026 * Customer = Struct.new(:name, :address, :zip) # => Customer
1027 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1028 * joe.each_pair {|(name, value)| p "#{name} => #{value}" }
1029 *
1030 * Output:
1031 *
1032 * "name => Joe Smith"
1033 * "address => 123 Maple, Anytown NC"
1034 * "zip => 12345"
1035 *
1036 * Returns an Enumerator if no block is given.
1037 *
1038 * Related: #each.
1039 *
1040 */
1041
1042static VALUE
1043rb_struct_each_pair(VALUE s)
1044{
1045 VALUE members;
1046 rb_len_t i;
1047
1048 RETURN_SIZED_ENUMERATOR(s, 0, 0, struct_enum_size);
1049 members = rb_struct_members(s);
1050 if (rb_block_pair_yield_optimizable()) {
1051 for (i=0; i<RSTRUCT_LEN_RAW(s); i++) {
1052 VALUE key = rb_ary_entry(members, i);
1053 VALUE value = RSTRUCT_GET_RAW(s, i);
1054 rb_yield_values(2, key, value);
1055 }
1056 }
1057 else {
1058 for (i=0; i<RSTRUCT_LEN_RAW(s); i++) {
1059 VALUE key = rb_ary_entry(members, i);
1060 VALUE value = RSTRUCT_GET_RAW(s, i);
1061 rb_yield(rb_assoc_new(key, value));
1062 }
1063 }
1064 return s;
1065}
1066
1067static VALUE
1068inspect_struct(VALUE s, VALUE prefix, int recur)
1069{
1070 VALUE cname = rb_class_path(rb_obj_class(s));
1071 VALUE members;
1072 VALUE str = prefix;
1073 rb_len_t i, len;
1074 char first = RSTRING_PTR(cname)[0];
1075
1076 if (recur || first != '#') {
1077 rb_str_cat2(str, " ");
1078 rb_str_append(str, cname);
1079 }
1080 if (recur) {
1081 return rb_str_cat2(str, ":...>");
1082 }
1083
1084 members = rb_struct_members(s);
1085 len = RSTRUCT_LEN_RAW(s);
1086
1087 for (i=0; i<len; i++) {
1088 VALUE slot;
1089 ID id;
1090
1091 if (i > 0) {
1092 rb_str_cat2(str, ", ");
1093 }
1094 else {
1095 rb_str_cat2(str, " ");
1096 }
1097 slot = RARRAY_AREF(members, i);
1098 id = SYM2ID(slot);
1099 if (rb_is_local_id(id) || rb_is_const_id(id)) {
1100 rb_str_append(str, rb_sym2str(slot));
1101 }
1102 else {
1103 rb_str_append(str, rb_inspect(slot));
1104 }
1105 rb_str_cat2(str, "=");
1106 rb_str_append(str, rb_inspect(RSTRUCT_GET_RAW(s, i)));
1107 }
1108 rb_str_cat2(str, ">");
1109
1110 return str;
1111}
1112
1113/*
1114 * call-seq:
1115 * inspect -> string
1116 *
1117 * Returns a string representation of +self+:
1118 *
1119 * Customer = Struct.new(:name, :address, :zip) # => Customer
1120 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1121 * joe.inspect # => "#<struct Customer name=\"Joe Smith\", address=\"123 Maple, Anytown NC\", zip=12345>"
1122 *
1123 */
1124
1125static VALUE
1126rb_struct_inspect(VALUE s)
1127{
1128 return rb_exec_recursive(inspect_struct, s, rb_str_new2("#<struct"));
1129}
1130
1131/*
1132 * call-seq:
1133 * to_a -> array
1134 *
1135 * Returns the values in +self+ as an array:
1136 *
1137 * Customer = Struct.new(:name, :address, :zip)
1138 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1139 * joe.to_a # => ["Joe Smith", "123 Maple, Anytown NC", 12345]
1140 *
1141 * Related: #members.
1142 */
1143
1144static VALUE
1145rb_struct_to_a(VALUE s)
1146{
1147 return rb_ary_new4(RSTRUCT_LEN_RAW(s), RSTRUCT_CONST_PTR(s));
1148}
1149
1150/*
1151 * call-seq:
1152 * to_h -> hash
1153 * to_h {|name, value| ... } -> hash
1154 *
1155 * Returns a hash containing the name and value for each member:
1156 *
1157 * Customer = Struct.new(:name, :address, :zip)
1158 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1159 * h = joe.to_h
1160 * h # => {name: "Joe Smith", address: "123 Maple, Anytown NC", zip: 12345}
1161 *
1162 * If a block is given, it is called with each name/value pair;
1163 * the block should return a 2-element array whose elements will become
1164 * a key/value pair in the returned hash:
1165 *
1166 * h = joe.to_h{|name, value| [name.upcase, value.to_s.upcase]}
1167 * h # => {NAME: "JOE SMITH", ADDRESS: "123 MAPLE, ANYTOWN NC", ZIP: "12345"}
1168 *
1169 * Raises ArgumentError if the block returns an inappropriate value.
1170 *
1171 */
1172
1173static VALUE
1174rb_struct_to_h(VALUE s)
1175{
1176 VALUE h = rb_hash_new_capa(RSTRUCT_LEN_RAW(s));
1177 VALUE members = rb_struct_members(s);
1178 rb_len_t i;
1179 int block_given = rb_block_given_p();
1180
1181 for (i=0; i<RSTRUCT_LEN_RAW(s); i++) {
1182 VALUE k = rb_ary_entry(members, i), v = RSTRUCT_GET_RAW(s, i);
1183 if (block_given)
1184 rb_hash_set_pair(h, rb_yield_values(2, k, v));
1185 else
1186 rb_hash_aset(h, k, v);
1187 }
1188 return h;
1189}
1190
1191/*
1192 * call-seq:
1193 * deconstruct_keys(array_of_names) -> hash
1194 *
1195 * Returns a hash of the name/value pairs for the given member names.
1196 *
1197 * Customer = Struct.new(:name, :address, :zip)
1198 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1199 * h = joe.deconstruct_keys([:zip, :address])
1200 * h # => {zip: 12345, address: "123 Maple, Anytown NC"}
1201 *
1202 * Returns all names and values if +array_of_names+ is +nil+:
1203 *
1204 * h = joe.deconstruct_keys(nil)
1205 * h # => {name: "Joseph Smith, Jr.", address: "123 Maple, Anytown NC", zip: 12345}
1206 *
1207 */
1208static VALUE
1209rb_struct_deconstruct_keys(VALUE s, VALUE keys)
1210{
1211 return deconstruct_keys(s, keys, false);
1212}
1213
1214static VALUE
1215deconstruct_keys(VALUE s, VALUE keys, bool name_only)
1216{
1217 VALUE h;
1218 rb_len_t i;
1219
1220 if (NIL_P(keys)) {
1221 return rb_struct_to_h(s);
1222 }
1223 if (UNLIKELY(!RB_TYPE_P(keys, T_ARRAY))) {
1224 rb_raise(rb_eTypeError,
1225 "wrong argument type %"PRIsVALUE" (expected Array or nil)",
1226 rb_obj_class(keys));
1227
1228 }
1229 if (RSTRUCT_LEN_RAW(s) < RARRAY_LEN(keys)) {
1230 return rb_hash_new();
1231 }
1232 h = rb_hash_new_capa(RARRAY_LEN(keys));
1233 for (i=0; i<RARRAY_LEN(keys); i++) {
1234 VALUE key = RARRAY_AREF(keys, i);
1235 int i = rb_struct_pos(s, &key, name_only);
1236 if (i < 0) {
1237 return h;
1238 }
1239 rb_hash_aset(h, key, RSTRUCT_GET_RAW(s, i));
1240 }
1241 return h;
1242}
1243
1244/* :nodoc: */
1245VALUE
1246rb_struct_init_copy(VALUE copy, VALUE s)
1247{
1248 rb_len_t i, len;
1249
1250 if (!OBJ_INIT_COPY(copy, s)) return copy;
1251 if (RSTRUCT_LEN_RAW(copy) != RSTRUCT_LEN_RAW(s)) {
1252 rb_raise(rb_eTypeError, "struct size mismatch");
1253 }
1254
1255 for (i=0, len=RSTRUCT_LEN_RAW(copy); i<len; i++) {
1256 RSTRUCT_SET_RAW(copy, i, RSTRUCT_GET_RAW(s, i));
1257 }
1258
1259 return copy;
1260}
1261
1262static int
1263rb_struct_pos(VALUE s, VALUE *name, bool name_only)
1264{
1265 rb_len_t i;
1266 VALUE idx = *name;
1267
1268 if (SYMBOL_P(idx)) {
1269 return struct_member_pos(s, idx);
1270 }
1271 else if (name_only || RB_TYPE_P(idx, T_STRING)) {
1272 idx = rb_check_symbol(name);
1273 if (NIL_P(idx)) return -1;
1274 return struct_member_pos(s, idx);
1275 }
1276 else {
1277 rb_len_t len;
1278 i = NUM2LEN(idx);
1279 len = RSTRUCT_LEN_RAW(s);
1280 if (i < 0) {
1281 if (i + len < 0) {
1282 *name = LEN2NUM(i);
1283 return -1;
1284 }
1285 i += len;
1286 }
1287 else if (len <= i) {
1288 *name = LEN2NUM(i);
1289 return -1;
1290 }
1291 return (int)i;
1292 }
1293}
1294
1295static void
1296invalid_struct_pos(VALUE s, VALUE idx)
1297{
1298 if (RB_INTEGER_TYPE_P(idx)) {
1299 rb_len_t i = NUM2LEN(idx), len = RSTRUCT_LEN_RAW(s);
1300 if (i < 0) {
1301 rb_raise(rb_eIndexError, "offset %"PRIdLEN" too small for struct(size:%"PRIdLEN")",
1302 i, len);
1303 }
1304 else {
1305 rb_raise(rb_eIndexError, "offset %"PRIdLEN" too large for struct(size:%"PRIdLEN")",
1306 i, len);
1307 }
1308 }
1309 else {
1310 rb_name_err_raise("no member '%1$s' in struct", s, idx);
1311 }
1312}
1313
1314/*
1315 * call-seq:
1316 * struct[name] -> object
1317 * struct[n] -> object
1318 *
1319 * Returns a value from +self+.
1320 *
1321 * With symbol or string argument +name+ given, returns the value for the named member:
1322 *
1323 * Customer = Struct.new(:name, :address, :zip)
1324 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1325 * joe[:zip] # => 12345
1326 *
1327 * Raises NameError if +name+ is not the name of a member.
1328 *
1329 * With integer argument +n+ given, returns <tt>self.values[n]</tt>
1330 * if +n+ is in range;
1331 * see Array@Array+Indexes:
1332 *
1333 * joe[2] # => 12345
1334 * joe[-2] # => "123 Maple, Anytown NC"
1335 *
1336 * Raises IndexError if +n+ is out of range.
1337 *
1338 */
1339
1340VALUE
1342{
1343 int i = rb_struct_pos(s, &idx, false);
1344 if (i < 0) invalid_struct_pos(s, idx);
1345 return RSTRUCT_GET_RAW(s, i);
1346}
1347
1348/*
1349 * call-seq:
1350 * struct[name] = value -> value
1351 * struct[n] = value -> value
1352 *
1353 * Assigns a value to a member.
1354 *
1355 * With symbol or string argument +name+ given, assigns the given +value+
1356 * to the named member; returns +value+:
1357 *
1358 * Customer = Struct.new(:name, :address, :zip)
1359 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1360 * joe[:zip] = 54321 # => 54321
1361 * joe # => #<struct Customer name="Joe Smith", address="123 Maple, Anytown NC", zip=54321>
1362 *
1363 * Raises NameError if +name+ is not the name of a member.
1364 *
1365 * With integer argument +n+ given, assigns the given +value+
1366 * to the +n+-th member if +n+ is in range;
1367 * see Array@Array+Indexes:
1368 *
1369 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1370 * joe[2] = 54321 # => 54321
1371 * joe[-3] = 'Joseph Smith' # => "Joseph Smith"
1372 * joe # => #<struct Customer name="Joseph Smith", address="123 Maple, Anytown NC", zip=54321>
1373 *
1374 * Raises IndexError if +n+ is out of range.
1375 *
1376 */
1377
1378VALUE
1380{
1381 int i = rb_struct_pos(s, &idx, false);
1382 if (i < 0) invalid_struct_pos(s, idx);
1383 rb_struct_modify(s);
1384 RSTRUCT_SET_RAW(s, i, val);
1385 return val;
1386}
1387
1388FUNC_MINIMIZED(VALUE rb_struct_lookup(VALUE s, VALUE idx));
1389NOINLINE(static VALUE rb_struct_lookup_default(VALUE s, VALUE idx, VALUE notfound, bool name_only));
1390
1391VALUE
1392rb_struct_lookup(VALUE s, VALUE idx)
1393{
1394 return rb_struct_lookup_default(s, idx, Qnil, false);
1395}
1396
1397static VALUE
1398rb_struct_lookup_default(VALUE s, VALUE idx, VALUE notfound, bool name_only)
1399{
1400 int i = rb_struct_pos(s, &idx, name_only);
1401 if (i < 0) return notfound;
1402 return RSTRUCT_GET_RAW(s, i);
1403}
1404
1405static VALUE
1406struct_entry(VALUE s, rb_len_t n)
1407{
1408 return rb_struct_aref(s, LEN2NUM(n));
1409}
1410
1411/*
1412 * call-seq:
1413 * values_at(*integers) -> array
1414 * values_at(integer_range) -> array
1415 *
1416 * Returns an array of values from +self+.
1417 *
1418 * With integer arguments +integers+ given,
1419 * returns an array containing each value given by one of +integers+:
1420 *
1421 * Customer = Struct.new(:name, :address, :zip)
1422 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1423 * joe.values_at(0, 2) # => ["Joe Smith", 12345]
1424 * joe.values_at(2, 0) # => [12345, "Joe Smith"]
1425 * joe.values_at(2, 1, 0) # => [12345, "123 Maple, Anytown NC", "Joe Smith"]
1426 * joe.values_at(0, -3) # => ["Joe Smith", "Joe Smith"]
1427 *
1428 * Raises IndexError if any of +integers+ is out of range;
1429 * see Array@Array+Indexes.
1430 *
1431 * With integer range argument +integer_range+ given,
1432 * returns an array containing each value given by the elements of the range;
1433 * fills with +nil+ values for range elements larger than the structure:
1434 *
1435 * joe.values_at(0..2)
1436 * # => ["Joe Smith", "123 Maple, Anytown NC", 12345]
1437 * joe.values_at(-3..-1)
1438 * # => ["Joe Smith", "123 Maple, Anytown NC", 12345]
1439 * joe.values_at(1..4) # => ["123 Maple, Anytown NC", 12345, nil, nil]
1440 *
1441 * Raises RangeError if any element of the range is negative and out of range;
1442 * see Array@Array+Indexes.
1443 *
1444 */
1445
1446static VALUE
1447rb_struct_values_at(int argc, VALUE *argv, VALUE s)
1448{
1449 return rb_get_values_at(s, RSTRUCT_LEN_RAW(s), argc, argv, struct_entry);
1450}
1451
1452/*
1453 * call-seq:
1454 * select {|value| ... } -> array
1455 * select -> enumerator
1456 *
1457 * With a block given, returns an array of values from +self+
1458 * for which the block returns a truthy value:
1459 *
1460 * Customer = Struct.new(:name, :address, :zip)
1461 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1462 * a = joe.select {|value| value.is_a?(String) }
1463 * a # => ["Joe Smith", "123 Maple, Anytown NC"]
1464 * a = joe.select {|value| value.is_a?(Integer) }
1465 * a # => [12345]
1466 *
1467 * With no block given, returns an Enumerator.
1468 */
1469
1470static VALUE
1471rb_struct_select(int argc, VALUE *argv, VALUE s)
1472{
1473 VALUE result;
1474 rb_len_t i;
1475
1476 rb_check_arity(argc, 0, 0);
1477 RETURN_SIZED_ENUMERATOR(s, 0, 0, struct_enum_size);
1478 result = rb_ary_new();
1479 for (i = 0; i < RSTRUCT_LEN_RAW(s); i++) {
1480 if (RTEST(rb_yield(RSTRUCT_GET_RAW(s, i)))) {
1481 rb_ary_push(result, RSTRUCT_GET_RAW(s, i));
1482 }
1483 }
1484
1485 return result;
1486}
1487
1488static VALUE
1489recursive_equal(VALUE s, VALUE s2, int recur)
1490{
1491 rb_len_t i, len;
1492
1493 if (recur) return Qtrue; /* Subtle! */
1494 len = RSTRUCT_LEN_RAW(s);
1495 for (i=0; i<len; i++) {
1496 if (!rb_equal(RSTRUCT_GET_RAW(s, i), RSTRUCT_GET_RAW(s2, i))) return Qfalse;
1497 }
1498 return Qtrue;
1499}
1500
1501
1502/*
1503 * call-seq:
1504 * self == other -> true or false
1505 *
1506 * Returns whether both the following are true:
1507 *
1508 * - <tt>other.class == self.class</tt>.
1509 * - For each member name +name+, <tt>other.name == self.name</tt>.
1510 *
1511 * Examples:
1512 *
1513 * Customer = Struct.new(:name, :address, :zip)
1514 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1515 * joe_jr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1516 * joe_jr == joe # => true
1517 * joe_jr[:name] = 'Joe Smith, Jr.'
1518 * # => "Joe Smith, Jr."
1519 * joe_jr == joe # => false
1520 */
1521
1522static VALUE
1523rb_struct_equal(VALUE s, VALUE s2)
1524{
1525 if (s == s2) return Qtrue;
1526 if (!RB_TYPE_P(s2, T_STRUCT)) return Qfalse;
1527 if (rb_obj_class(s) != rb_obj_class(s2)) return Qfalse;
1528 if (RSTRUCT_LEN_RAW(s) != RSTRUCT_LEN_RAW(s2)) {
1529 rb_bug("inconsistent struct"); /* should never happen */
1530 }
1531
1532 return rb_exec_recursive_paired(recursive_equal, s, s2, s2);
1533}
1534
1535/*
1536 * call-seq:
1537 * hash -> integer
1538 *
1539 * Returns the integer hash value for +self+.
1540 *
1541 * Two structs of the same class and with the same content
1542 * will have the same hash code (and will compare using Struct#eql?):
1543 *
1544 * Customer = Struct.new(:name, :address, :zip)
1545 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1546 * joe_jr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1547 * joe.hash == joe_jr.hash # => true
1548 * joe_jr[:name] = 'Joe Smith, Jr.'
1549 * joe.hash == joe_jr.hash # => false
1550 *
1551 * Related: Object#hash.
1552 */
1553
1554static VALUE
1555rb_struct_hash(VALUE s)
1556{
1557 rb_len_t i, len;
1558 st_index_t h;
1559 VALUE n;
1560
1561 h = rb_hash_start(rb_hash(rb_obj_class(s)));
1562 len = RSTRUCT_LEN_RAW(s);
1563 for (i = 0; i < len; i++) {
1564 n = rb_hash(RSTRUCT_GET_RAW(s, i));
1565 h = rb_hash_uint(h, NUM2LONG(n));
1566 }
1567 h = rb_hash_end(h);
1568 return ST2FIX(h);
1569}
1570
1571static VALUE
1572recursive_eql(VALUE s, VALUE s2, int recur)
1573{
1574 rb_len_t i, len;
1575
1576 if (recur) return Qtrue; /* Subtle! */
1577 len = RSTRUCT_LEN_RAW(s);
1578 for (i=0; i<len; i++) {
1579 if (!rb_eql(RSTRUCT_GET_RAW(s, i), RSTRUCT_GET_RAW(s2, i))) return Qfalse;
1580 }
1581 return Qtrue;
1582}
1583
1584/*
1585 * call-seq:
1586 * eql?(other) -> true or false
1587 *
1588 * Returns +true+ if and only if the following are true; otherwise returns +false+:
1589 *
1590 * - <tt>other.class == self.class</tt>.
1591 * - For each member name +name+, <tt>other.name.eql?(self.name)</tt>.
1592 *
1593 * Customer = Struct.new(:name, :address, :zip)
1594 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1595 * joe_jr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1596 * joe_jr.eql?(joe) # => true
1597 * joe_jr[:name] = 'Joe Smith, Jr.'
1598 * joe_jr.eql?(joe) # => false
1599 *
1600 * Related: Object#==.
1601 */
1602
1603static VALUE
1604rb_struct_eql(VALUE s, VALUE s2)
1605{
1606 if (s == s2) return Qtrue;
1607 if (!RB_TYPE_P(s2, T_STRUCT)) return Qfalse;
1608 if (rb_obj_class(s) != rb_obj_class(s2)) return Qfalse;
1609 if (RSTRUCT_LEN_RAW(s) != RSTRUCT_LEN_RAW(s2)) {
1610 rb_bug("inconsistent struct"); /* should never happen */
1611 }
1612
1613 return rb_exec_recursive_paired(recursive_eql, s, s2, s2);
1614}
1615
1616/*
1617 * call-seq:
1618 * size -> integer
1619 *
1620 * Returns the number of members.
1621 *
1622 * Customer = Struct.new(:name, :address, :zip)
1623 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1624 * joe.size #=> 3
1625 *
1626 */
1627
1628VALUE
1630{
1631 return LEN2NUM(RSTRUCT_LEN_RAW(s));
1632}
1633
1634/*
1635 * call-seq:
1636 * dig(name, *identifiers) -> object
1637 * dig(n, *identifiers) -> object
1638 *
1639 * Finds and returns an object among nested objects.
1640 * The nested objects may be instances of various classes.
1641 * See {Dig Methods}[rdoc-ref:dig_methods.rdoc].
1642 *
1643 *
1644 * Given symbol or string argument +name+,
1645 * returns the object that is specified by +name+ and +identifiers+:
1646 *
1647 * Foo = Struct.new(:a)
1648 * f = Foo.new(Foo.new({b: [1, 2, 3]}))
1649 * f.dig(:a) # => #<struct Foo a={b: [1, 2, 3]}>
1650 * f.dig(:a, :a) # => {b: [1, 2, 3]}
1651 * f.dig(:a, :a, :b) # => [1, 2, 3]
1652 * f.dig(:a, :a, :b, 0) # => 1
1653 * f.dig(:b, 0) # => nil
1654 *
1655 * Given integer argument +n+,
1656 * returns the object that is specified by +n+ and +identifiers+:
1657 *
1658 * f.dig(0) # => #<struct Foo a={b: [1, 2, 3]}>
1659 * f.dig(0, 0) # => {b: [1, 2, 3]}
1660 * f.dig(0, 0, :b) # => [1, 2, 3]
1661 * f.dig(0, 0, :b, 0) # => 1
1662 * f.dig(:b, 0) # => nil
1663 *
1664 */
1665
1666static VALUE
1667rb_struct_dig(int argc, VALUE *argv, VALUE self)
1668{
1670 self = rb_struct_lookup(self, *argv);
1671 if (!--argc) return self;
1672 ++argv;
1673 return rb_obj_dig(argc, argv, self, Qnil);
1674}
1675
1676/*
1677 * Document-class: Data
1678 *
1679 * Class \Data provides a convenient way to define simple classes
1680 * for value-alike objects.
1681 *
1682 * The simplest example of usage:
1683 *
1684 * Measure = Data.define(:amount, :unit)
1685 *
1686 * # Positional arguments constructor is provided
1687 * distance = Measure.new(100, 'km')
1688 * #=> #<data Measure amount=100, unit="km">
1689 *
1690 * # Keyword arguments constructor is provided
1691 * weight = Measure.new(amount: 50, unit: 'kg')
1692 * #=> #<data Measure amount=50, unit="kg">
1693 *
1694 * # Alternative form to construct an object:
1695 * speed = Measure[10, 'mPh']
1696 * #=> #<data Measure amount=10, unit="mPh">
1697 *
1698 * # Works with keyword arguments, too:
1699 * area = Measure[amount: 1.5, unit: 'm^2']
1700 * #=> #<data Measure amount=1.5, unit="m^2">
1701 *
1702 * # Argument accessors are provided:
1703 * distance.amount #=> 100
1704 * distance.unit #=> "km"
1705 *
1706 * Constructed object also has a reasonable definitions of #==
1707 * operator, #to_h hash conversion, and #deconstruct / #deconstruct_keys
1708 * to be used in pattern matching.
1709 *
1710 * ::define method accepts an optional block and evaluates it in
1711 * the context of the newly defined class. That allows to define
1712 * additional methods:
1713 *
1714 * Measure = Data.define(:amount, :unit) do
1715 * def <=>(other)
1716 * return unless other.is_a?(self.class) && other.unit == unit
1717 * amount <=> other.amount
1718 * end
1719 *
1720 * include Comparable
1721 * end
1722 *
1723 * Measure[3, 'm'] < Measure[5, 'm'] #=> true
1724 * Measure[3, 'm'] < Measure[5, 'kg']
1725 * # comparison of Measure with Measure failed (ArgumentError)
1726 *
1727 * Data provides no member writers, or enumerators: it is meant
1728 * to be a storage for immutable atomic values. But note that
1729 * if some of data members is of a mutable class, Data does no additional
1730 * immutability enforcement:
1731 *
1732 * Event = Data.define(:time, :weekdays)
1733 * event = Event.new('18:00', %w[Tue Wed Fri])
1734 * #=> #<data Event time="18:00", weekdays=["Tue", "Wed", "Fri"]>
1735 *
1736 * # There is no #time= or #weekdays= accessors, but changes are
1737 * # still possible:
1738 * event.weekdays << 'Sat'
1739 * event
1740 * #=> #<data Event time="18:00", weekdays=["Tue", "Wed", "Fri", "Sat"]>
1741 *
1742 * See also Struct, which is a similar concept, but has more
1743 * container-alike API, allowing to change contents of the object
1744 * and enumerate it.
1745 */
1746
1747/*
1748 * call-seq:
1749 * define(*symbols) -> class
1750 *
1751 * Defines a new \Data class.
1752 *
1753 * measure = Data.define(:amount, :unit)
1754 * #=> #<Class:0x00007f70c6868498>
1755 * measure.new(1, 'km')
1756 * #=> #<data amount=1, unit="km">
1757 *
1758 * # It you store the new class in the constant, it will
1759 * # affect #inspect and will be more natural to use:
1760 * Measure = Data.define(:amount, :unit)
1761 * #=> Measure
1762 * Measure.new(1, 'km')
1763 * #=> #<data Measure amount=1, unit="km">
1764 *
1765 *
1766 * Note that member-less \Data is acceptable and might be a useful technique
1767 * for defining several homogeneous data classes, like
1768 *
1769 * class HTTPFetcher
1770 * Response = Data.define(:body)
1771 * NotFound = Data.define
1772 * # ... implementation
1773 * end
1774 *
1775 * Now, different kinds of responses from +HTTPFetcher+ would have consistent
1776 * representation:
1777 *
1778 * #<data HTTPFetcher::Response body="<html...">
1779 * #<data HTTPFetcher::NotFound>
1780 *
1781 * And are convenient to use in pattern matching:
1782 *
1783 * case fetcher.get(url)
1784 * in HTTPFetcher::Response(body)
1785 * # process body variable
1786 * in HTTPFetcher::NotFound
1787 * # handle not found case
1788 * end
1789 */
1790
1791static VALUE
1792rb_data_s_def(int argc, VALUE *argv, VALUE super)
1793{
1794 VALUE rest = rb_ident_hash_new();
1795 RBASIC_CLEAR_CLASS(rest);
1796 for (int i = 0; i < argc; i++) {
1797 VALUE mem = rb_to_symbol(argv[i]);
1798 if (rb_is_attrset_sym(mem)) {
1799 rb_raise(rb_eArgError, "invalid data member: %"PRIsVALUE, mem);
1800 }
1801 if (RTEST(rb_hash_has_key(rest, mem))) {
1802 rb_raise(rb_eArgError, "duplicate member: %"PRIsVALUE, mem);
1803 }
1804 rb_hash_aset(rest, mem, Qtrue);
1805 }
1806 rest = rb_hash_keys(rest);
1807 RBASIC_CLEAR_CLASS(rest);
1808 OBJ_FREEZE(rest);
1809
1810 VALUE klass = anonymous_struct(super);
1811 setup_data(klass, rest);
1812
1813 rb_class_inherited(super, klass);
1814
1815 if (rb_block_given_p()) {
1816 rb_mod_module_eval(0, 0, klass);
1817 }
1818
1819 return klass;
1820}
1821
1822VALUE
1824{
1825 va_list ar;
1826 VALUE ary;
1827 va_start(ar, super);
1828 ary = struct_make_members_list(ar);
1829 va_end(ar);
1830 if (!super) super = rb_cData;
1831 VALUE klass = setup_data(anonymous_struct(super), ary);
1832 rb_vm_register_global_object(klass);
1833 rb_class_inherited(super, klass);
1834 return klass;
1835}
1836
1837static int
1838data_hash_set_i(VALUE key, VALUE val, VALUE arg)
1839{
1840 struct struct_hash_set_arg *args = (struct struct_hash_set_arg *)arg;
1841 int i = struct_hash_aset(key, val, args, true);
1842 if (i >= 0 && !args->found[i]) {
1843 args->found[i] = true;
1844 args->missing_count--;
1845 }
1846 return ST_CONTINUE;
1847}
1848
1849/*
1850 * call-seq:
1851 * DataClass::members -> array_of_symbols
1852 *
1853 * Returns an array of member names of the data class:
1854 *
1855 * Measure = Data.define(:amount, :unit)
1856 * Measure.members # => [:amount, :unit]
1857 *
1858 */
1859
1860#define rb_data_s_members_m rb_struct_s_members_m
1861
1862
1863/*
1864 * call-seq:
1865 * new(*args) -> instance
1866 * new(**kwargs) -> instance
1867 * ::[](*args) -> instance
1868 * ::[](**kwargs) -> instance
1869 *
1870 * Constructors for classes defined with ::define accept both positional and
1871 * keyword arguments.
1872 *
1873 * Measure = Data.define(:amount, :unit)
1874 *
1875 * Measure.new(1, 'km')
1876 * #=> #<data Measure amount=1, unit="km">
1877 * Measure.new(amount: 1, unit: 'km')
1878 * #=> #<data Measure amount=1, unit="km">
1879 *
1880 * # Alternative shorter initialization with []
1881 * Measure[1, 'km']
1882 * #=> #<data Measure amount=1, unit="km">
1883 * Measure[amount: 1, unit: 'km']
1884 * #=> #<data Measure amount=1, unit="km">
1885 *
1886 * All arguments are mandatory (unlike Struct), and converted to keyword arguments:
1887 *
1888 * Measure.new(amount: 1)
1889 * # in `initialize': missing keyword: :unit (ArgumentError)
1890 *
1891 * Measure.new(1)
1892 * # in `initialize': missing keyword: :unit (ArgumentError)
1893 *
1894 * Note that <tt>Measure#initialize</tt> always receives keyword arguments, and that
1895 * mandatory arguments are checked in +initialize+, not in +new+. This can be
1896 * important for redefining initialize in order to convert arguments or provide
1897 * defaults:
1898 *
1899 * Measure = Data.define(:amount, :unit)
1900 * class Measure
1901 * NONE = Data.define
1902 *
1903 * def initialize(amount:, unit: NONE.new)
1904 * super(amount: Float(amount), unit:)
1905 * end
1906 * end
1907 *
1908 * Measure.new('10', 'km') # => #<data Measure amount=10.0, unit="km">
1909 * Measure.new(10_000) # => #<data Measure amount=10000.0, unit=#<data Measure::NONE>>
1910 *
1911 */
1912
1913static VALUE
1914rb_data_initialize_m(int argc, const VALUE *argv, VALUE self)
1915{
1916 rb_struct_modify(self);
1917 rb_len_t num_members = RSTRUCT_LEN_RAW(self);
1918
1919 if (argc == 0) {
1920 if (num_members > 0) {
1921 rb_exc_raise(rb_keyword_error_new("missing", struct_s_members(rb_obj_class(self))));
1922 }
1923 OBJ_FREEZE(self);
1924 return Qnil;
1925 }
1926 if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) {
1927 rb_error_arity(argc, 0, 0);
1928 }
1929
1930 VALUE found_buffer = 0;
1931 bool *found = NULL;
1932 if (num_members > 0) {
1933 found = ALLOCV_N(bool, found_buffer, num_members);
1934 MEMZERO(found, bool, num_members);
1935 }
1936 struct struct_hash_set_arg arg = {
1937 .self = self,
1938 .found = found,
1939 .missing_count = num_members,
1940 };
1941 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self), num_members);
1942 rb_hash_foreach(argv[0], data_hash_set_i, (VALUE)&arg);
1943
1944 // Freeze early before potentially raising, so that we don't leave an
1945 // unfrozen copy on the heap, which could get exposed via ObjectSpace.
1946 OBJ_FREEZE(self);
1947 if (UNLIKELY(arg.missing_count > 0)) {
1948 VALUE members = struct_s_members(rb_obj_class(self));
1949 RUBY_ASSERT(RARRAY_LEN(members) == num_members);
1950 VALUE missing = rb_ary_new_capa(arg.missing_count);
1951 for (rb_len_t i = 0; i < num_members; i++) {
1952 if (!found[i]) rb_ary_push(missing, RARRAY_AREF(members, i));
1953 }
1954 RUBY_ASSERT(RARRAY_LEN(missing) == arg.missing_count, "missing_count=%"PRIdLEN" but %"PRIdLEN, arg.missing_count, RARRAY_LEN(missing));
1955 rb_exc_raise(rb_keyword_error_new("missing", missing));
1956 }
1957
1958 ALLOCV_END(found_buffer);
1959 if (UNLIKELY(arg.unknown_keywords)) {
1960 rb_exc_raise(rb_keyword_error_new("unknown", arg.unknown_keywords));
1961 }
1962
1963 return Qnil;
1964}
1965
1966/* :nodoc: */
1967static VALUE
1968rb_data_init_copy(VALUE copy, VALUE s)
1969{
1970 copy = rb_struct_init_copy(copy, s);
1971 RB_OBJ_FREEZE(copy);
1972 return copy;
1973}
1974
1975/*
1976 * call-seq:
1977 * with(**kwargs) -> instance
1978 *
1979 * Returns a shallow copy of +self+ --- the instance variables of
1980 * +self+ are copied, but not the objects they reference.
1981 *
1982 * If the method is supplied any keyword arguments, the copy will
1983 * be created with the respective field values updated to use the
1984 * supplied keyword argument values. Note that it is an error to
1985 * supply a keyword that the Data class does not have as a member.
1986 *
1987 * Point = Data.define(:x, :y)
1988 *
1989 * origin = Point.new(x: 0, y: 0)
1990 *
1991 * up = origin.with(x: 1)
1992 * right = origin.with(y: 1)
1993 * up_and_right = up.with(y: 1)
1994 *
1995 * p origin # #<data Point x=0, y=0>
1996 * p up # #<data Point x=1, y=0>
1997 * p right # #<data Point x=0, y=1>
1998 * p up_and_right # #<data Point x=1, y=1>
1999 *
2000 * out = origin.with(z: 1) # ArgumentError: unknown keyword: :z
2001 * some_point = origin.with(1, 2) # ArgumentError: expected keyword arguments, got positional arguments
2002 *
2003 */
2004
2005static VALUE
2006rb_data_with(int argc, const VALUE *argv, VALUE self)
2007{
2008 VALUE kwargs;
2009 rb_scan_args(argc, argv, "0:", &kwargs);
2010 if (NIL_P(kwargs)) {
2011 return self;
2012 }
2013
2014 VALUE h = rb_struct_to_h(self);
2015 rb_hash_update_by(h, kwargs, 0);
2016 return rb_class_new_instance_kw(1, &h, rb_obj_class(self), TRUE);
2017}
2018
2019/*
2020 * call-seq:
2021 * inspect -> string
2022 * to_s -> string
2023 *
2024 * Returns a string representation of +self+:
2025 *
2026 * Measure = Data.define(:amount, :unit)
2027 *
2028 * distance = Measure[10, 'km']
2029 *
2030 * p distance # uses #inspect underneath
2031 * #<data Measure amount=10, unit="km">
2032 *
2033 * puts distance # uses #to_s underneath, same representation
2034 * #<data Measure amount=10, unit="km">
2035 *
2036 */
2037
2038static VALUE
2039rb_data_inspect(VALUE s)
2040{
2041 return rb_exec_recursive(inspect_struct, s, rb_str_new2("#<data"));
2042}
2043
2044/*
2045 * call-seq:
2046 * self == other -> true or false
2047 *
2048 * Returns whether +other+ is the same class as +self+, and all members are
2049 * equal.
2050 *
2051 * Examples:
2052 *
2053 * Measure = Data.define(:amount, :unit)
2054 *
2055 * Measure[1, 'km'] == Measure[1, 'km'] #=> true
2056 * Measure[1, 'km'] == Measure[2, 'km'] #=> false
2057 * Measure[1, 'km'] == Measure[1, 'm'] #=> false
2058 *
2059 * Measurement = Data.define(:amount, :unit)
2060 * # Even though Measurement and Measure have the same "shape"
2061 * # their instances are never equal
2062 * Measure[1, 'km'] == Measurement[1, 'km'] #=> false
2063 */
2064
2065#define rb_data_equal rb_struct_equal
2066
2067/*
2068 * call-seq:
2069 * self.eql?(other) -> true or false
2070 *
2071 * Equality check that is used when two items of data are keys of a Hash.
2072 *
2073 * The subtle difference with #== is that members are also compared with their
2074 * #eql? method, which might be important in some cases:
2075 *
2076 * Measure = Data.define(:amount, :unit)
2077 *
2078 * Measure[1, 'km'] == Measure[1.0, 'km'] #=> true, they are equal as values
2079 * # ...but...
2080 * Measure[1, 'km'].eql? Measure[1.0, 'km'] #=> false, they represent different hash keys
2081 *
2082 * See also Object#eql? for further explanations of the method usage.
2083 */
2084
2085#define rb_data_eql rb_struct_eql
2086
2087/*
2088 * call-seq:
2089 * hash -> integer
2090 *
2091 * Redefines Object#hash (used to distinguish objects as Hash keys) so that
2092 * data objects of the same class with same content would have the same +hash+
2093 * value, and represented the same Hash key.
2094 *
2095 * Measure = Data.define(:amount, :unit)
2096 *
2097 * Measure[1, 'km'].hash == Measure[1, 'km'].hash #=> true
2098 * Measure[1, 'km'].hash == Measure[10, 'km'].hash #=> false
2099 * Measure[1, 'km'].hash == Measure[1, 'm'].hash #=> false
2100 * Measure[1, 'km'].hash == Measure[1.0, 'km'].hash #=> false
2101 *
2102 * # Structurally similar data class, but shouldn't be considered
2103 * # the same hash key
2104 * Measurement = Data.define(:amount, :unit)
2105 *
2106 * Measure[1, 'km'].hash == Measurement[1, 'km'].hash #=> false
2107 */
2108
2109#define rb_data_hash rb_struct_hash
2110
2111/*
2112 * call-seq:
2113 * to_h -> hash
2114 * to_h {|name, value| ... } -> hash
2115 *
2116 * Returns Hash representation of the data object.
2117 *
2118 * Measure = Data.define(:amount, :unit)
2119 * distance = Measure[10, 'km']
2120 *
2121 * distance.to_h
2122 * #=> {amount: 10, unit: "km"}
2123 *
2124 * Like Enumerable#to_h, if the block is provided, it is expected to
2125 * produce key-value pairs to construct a hash:
2126 *
2127 *
2128 * distance.to_h { |name, val| [name.to_s, val.to_s] }
2129 * #=> {"amount"=>"10", "unit"=>"km"}
2130 *
2131 * Note that there is a useful symmetry between #to_h and #initialize:
2132 *
2133 * distance2 = Measure.new(**distance.to_h)
2134 * #=> #<data Measure amount=10, unit="km">
2135 * distance2 == distance
2136 * #=> true
2137 */
2138
2139#define rb_data_to_h rb_struct_to_h
2140
2141/*
2142 * call-seq:
2143 * members -> array_of_symbols
2144 *
2145 * Returns the member names from +self+ as an array:
2146 *
2147 * Measure = Data.define(:amount, :unit)
2148 * distance = Measure[10, 'km']
2149 *
2150 * distance.members #=> [:amount, :unit]
2151 *
2152 */
2153
2154#define rb_data_members_m rb_struct_members_m
2155
2156/*
2157 * call-seq:
2158 * deconstruct -> array
2159 *
2160 * Returns the values in +self+ as an array, to use in pattern matching:
2161 *
2162 * Measure = Data.define(:amount, :unit)
2163 *
2164 * distance = Measure[10, 'km']
2165 * distance.deconstruct #=> [10, "km"]
2166 *
2167 * # usage
2168 * case distance
2169 * in n, 'km' # calls #deconstruct underneath
2170 * puts "It is #{n} kilometers away"
2171 * else
2172 * puts "Don't know how to handle it"
2173 * end
2174 * # prints "It is 10 kilometers away"
2175 *
2176 * Or, with checking the class, too:
2177 *
2178 * case distance
2179 * in Measure(n, 'km')
2180 * puts "It is #{n} kilometers away"
2181 * # ...
2182 * end
2183 */
2184
2185#define rb_data_deconstruct rb_struct_to_a
2186
2187/*
2188 * call-seq:
2189 * deconstruct_keys(array_of_names_or_nil) -> hash
2190 *
2191 * Returns a hash of the name/value pairs, to use in pattern matching.
2192 *
2193 * Measure = Data.define(:amount, :unit)
2194 *
2195 * distance = Measure[10, 'km']
2196 * distance.deconstruct_keys(nil) #=> {amount: 10, unit: "km"}
2197 * distance.deconstruct_keys([:amount]) #=> {amount: 10}
2198 *
2199 * # usage
2200 * case distance
2201 * in amount:, unit: 'km' # calls #deconstruct_keys underneath
2202 * puts "It is #{amount} kilometers away"
2203 * else
2204 * puts "Don't know how to handle it"
2205 * end
2206 * # prints "It is 10 kilometers away"
2207 *
2208 * Or, with checking the class, too:
2209 *
2210 * case distance
2211 * in Measure(amount:, unit: 'km')
2212 * puts "It is #{amount} kilometers away"
2213 * # ...
2214 * end
2215 */
2216
2217static VALUE
2218rb_data_deconstruct_keys(VALUE s, VALUE keys)
2219{
2220 return deconstruct_keys(s, keys, true);
2221}
2222
2223/*
2224 * Document-class: Struct
2225 *
2226 * Class \Struct provides a convenient way to create a simple class
2227 * that can store and fetch values.
2228 *
2229 * This example creates a subclass of +Struct+, <tt>Struct::Customer</tt>;
2230 * the first argument, a string, is the name of the subclass;
2231 * the other arguments, symbols, determine the _members_ of the new subclass.
2232 *
2233 * Customer = Struct.new('Customer', :name, :address, :zip)
2234 * Customer.name # => "Struct::Customer"
2235 * Customer.class # => Class
2236 * Customer.superclass # => Struct
2237 *
2238 * Corresponding to each member are two methods, a writer and a reader,
2239 * that store and fetch values:
2240 *
2241 * methods = Customer.instance_methods false
2242 * methods # => [:zip, :address=, :zip=, :address, :name, :name=]
2243 *
2244 * An instance of the subclass may be created,
2245 * and its members assigned values, via method <tt>::new</tt>:
2246 *
2247 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
2248 * joe # => #<struct Struct::Customer name="Joe Smith", address="123 Maple, Anytown NC", zip=12345>
2249 *
2250 * The member values may be managed thus:
2251 *
2252 * joe.name # => "Joe Smith"
2253 * joe.name = 'Joseph Smith'
2254 * joe.name # => "Joseph Smith"
2255 *
2256 * And thus; note that member name may be expressed as either a string or a symbol:
2257 *
2258 * joe[:name] # => "Joseph Smith"
2259 * joe[:name] = 'Joseph Smith, Jr.'
2260 * joe['name'] # => "Joseph Smith, Jr."
2261 *
2262 * See Struct::new.
2263 *
2264 * == What's Here
2265 *
2266 * First, what's elsewhere. Class \Struct:
2267 *
2268 * - Inherits from {class Object}[rdoc-ref:Object@Whats+Here].
2269 * - Includes {module Enumerable}[rdoc-ref:Enumerable@Whats+Here],
2270 * which provides dozens of additional methods.
2271 *
2272 * See also Data, which is a somewhat similar, but stricter concept for defining immutable
2273 * value objects.
2274 *
2275 * Here, class \Struct provides methods that are useful for:
2276 *
2277 * - {Creating a Struct Subclass}[rdoc-ref:Struct@Methods+for+Creating+a+Struct+Subclass]
2278 * - {Querying}[rdoc-ref:Struct@Methods+for+Querying]
2279 * - {Comparing}[rdoc-ref:Struct@Methods+for+Comparing]
2280 * - {Fetching}[rdoc-ref:Struct@Methods+for+Fetching]
2281 * - {Assigning}[rdoc-ref:Struct@Methods+for+Assigning]
2282 * - {Iterating}[rdoc-ref:Struct@Methods+for+Iterating]
2283 * - {Converting}[rdoc-ref:Struct@Methods+for+Converting]
2284 *
2285 * === Methods for Creating a Struct Subclass
2286 *
2287 * - ::new: Returns a new subclass of \Struct.
2288 *
2289 * === Methods for Querying
2290 *
2291 * - #hash: Returns the integer hash code.
2292 * - #size (aliased as #length): Returns the number of members.
2293 *
2294 * === Methods for Comparing
2295 *
2296 * - #==: Returns whether a given object is equal to +self+, using <tt>==</tt>
2297 * to compare member values.
2298 * - #eql?: Returns whether a given object is equal to +self+,
2299 * using <tt>eql?</tt> to compare member values.
2300 *
2301 * === Methods for Fetching
2302 *
2303 * - #[]: Returns the value associated with a given member name.
2304 * - #to_a (aliased as #values, #deconstruct): Returns the member values in +self+ as an array.
2305 * - #deconstruct_keys: Returns a hash of the name/value pairs
2306 * for given member names.
2307 * - #dig: Returns the object in nested objects that is specified
2308 * by a given member name and additional arguments.
2309 * - #members: Returns an array of the member names.
2310 * - #select (aliased as #filter): Returns an array of member values from +self+,
2311 * as selected by the given block.
2312 * - #values_at: Returns an array containing values for given member names.
2313 *
2314 * === Methods for Assigning
2315 *
2316 * - #[]=: Assigns a given value to a given member name.
2317 *
2318 * === Methods for Iterating
2319 *
2320 * - #each: Calls a given block with each member name.
2321 * - #each_pair: Calls a given block with each member name/value pair.
2322 *
2323 * === Methods for Converting
2324 *
2325 * - #inspect (aliased as #to_s): Returns a string representation of +self+.
2326 * - #to_h: Returns a hash of the member name/value pairs in +self+.
2327 *
2328 */
2329void
2330InitVM_Struct(void)
2331{
2332 rb_cStruct = rb_define_class("Struct", rb_cObject);
2334
2336 rb_define_singleton_method(rb_cStruct, "new", rb_struct_s_def, -1);
2337#if 0 /* for RDoc */
2338 rb_define_singleton_method(rb_cStruct, "keyword_init?", rb_struct_s_keyword_init_p, 0);
2339 rb_define_singleton_method(rb_cStruct, "members", rb_struct_s_members_m, 0);
2340#endif
2341
2342 rb_define_method(rb_cStruct, "initialize", rb_struct_initialize_m, -1);
2343 rb_define_method(rb_cStruct, "initialize_copy", rb_struct_init_copy, 1);
2344
2345 rb_define_method(rb_cStruct, "==", rb_struct_equal, 1);
2346 rb_define_method(rb_cStruct, "eql?", rb_struct_eql, 1);
2347 rb_define_method(rb_cStruct, "hash", rb_struct_hash, 0);
2348
2349 rb_define_method(rb_cStruct, "inspect", rb_struct_inspect, 0);
2350 rb_define_alias(rb_cStruct, "to_s", "inspect");
2351 rb_define_method(rb_cStruct, "to_a", rb_struct_to_a, 0);
2352 rb_define_method(rb_cStruct, "to_h", rb_struct_to_h, 0);
2353 rb_define_method(rb_cStruct, "values", rb_struct_to_a, 0);
2356
2357 rb_define_method(rb_cStruct, "each", rb_struct_each, 0);
2358 rb_define_method(rb_cStruct, "each_pair", rb_struct_each_pair, 0);
2361 rb_define_method(rb_cStruct, "select", rb_struct_select, -1);
2362 rb_define_method(rb_cStruct, "filter", rb_struct_select, -1);
2363 rb_define_method(rb_cStruct, "values_at", rb_struct_values_at, -1);
2364
2365 rb_define_method(rb_cStruct, "members", rb_struct_members_m, 0);
2366 rb_define_method(rb_cStruct, "dig", rb_struct_dig, -1);
2367
2368 rb_define_method(rb_cStruct, "deconstruct", rb_struct_to_a, 0);
2369 rb_define_method(rb_cStruct, "deconstruct_keys", rb_struct_deconstruct_keys, 1);
2370
2371 rb_cData = rb_define_class("Data", rb_cObject);
2372
2373 rb_undef_method(CLASS_OF(rb_cData), "new");
2374 rb_undef_alloc_func(rb_cData);
2375 rb_define_singleton_method(rb_cData, "define", rb_data_s_def, -1);
2376
2377#if 0 /* for RDoc */
2378 rb_define_singleton_method(rb_cData, "members", rb_data_s_members_m, 0);
2379#endif
2380
2381 rb_define_method(rb_cData, "initialize", rb_data_initialize_m, -1);
2382 rb_define_method(rb_cData, "initialize_copy", rb_data_init_copy, 1);
2383
2384 rb_define_method(rb_cData, "==", rb_data_equal, 1);
2385 rb_define_method(rb_cData, "eql?", rb_data_eql, 1);
2386 rb_define_method(rb_cData, "hash", rb_data_hash, 0);
2387
2388 rb_define_method(rb_cData, "inspect", rb_data_inspect, 0);
2389 rb_define_alias(rb_cData, "to_s", "inspect");
2390 rb_define_method(rb_cData, "to_h", rb_data_to_h, 0);
2391
2392 rb_define_method(rb_cData, "members", rb_data_members_m, 0);
2393
2394 rb_define_method(rb_cData, "deconstruct", rb_data_deconstruct, 0);
2395 rb_define_method(rb_cData, "deconstruct_keys", rb_data_deconstruct_keys, 1);
2396
2397 rb_define_method(rb_cData, "with", rb_data_with, -1);
2398}
2399
2400#undef rb_intern
2401void
2402Init_Struct(void)
2403{
2404 InitVM(Struct);
2405}
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
static void RB_OBJ_FREEZE(VALUE obj)
Freeze the given object if it is not frozen yet.
Definition fl_type.h:756
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1773
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:3061
VALUE rb_class_inherited(VALUE super, VALUE klass)
Calls Class::inherited.
Definition class.c:1565
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:3104
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2907
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3394
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
Definition eval.c:1054
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1041
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:3183
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1700
#define RB_INTEGER_TYPE_P
Old name of rb_integer_type_p.
Definition value_type.h:87
#define OBJ_INIT_COPY(obj, orig)
Old name of RB_OBJ_INIT_COPY.
Definition object.h:41
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define LEN2NUM
Old name of RB_LEN2NUM.
Definition len_t.h:33
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1708
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define T_STRUCT
Old name of RUBY_T_STRUCT.
Definition value_type.h:79
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define SYM2ID
Old name of RB_SYM2ID.
Definition symbol.h:45
#define FIX2UINT
Old name of RB_FIX2UINT.
Definition int.h:42
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define rb_ary_new4
Old name of rb_ary_new_from_values.
Definition array.h:659
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:402
#define Qtrue
Old name of RUBY_Qtrue.
#define ST2FIX
Old name of RB_ST2FIX.
Definition st_data_t.h:33
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:408
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition value_type.h:58
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define NUM2LEN
Old name of RB_NUM2LEN.
Definition len_t.h:34
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:409
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:678
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1457
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:464
VALUE rb_eIndexError
IndexError exception.
Definition error.c:1459
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_obj_alloc(VALUE klass)
Allocates an instance of the given class.
Definition object.c:2264
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
Definition object.c:2305
VALUE rb_class_new_instance_kw(int argc, const VALUE *argv, VALUE klass, int kw_splat)
Identical to rb_class_new_instance(), except you can specify how to handle the last element of the gi...
Definition object.c:2293
VALUE rb_mEnumerable
Enumerable module.
Definition enum.c:28
VALUE rb_cStruct
Struct class.
Definition struct.c:33
VALUE rb_class_new_instance_pass_kw(int argc, const VALUE *argv, VALUE klass)
Identical to rb_class_new_instance(), except it passes the passed keywords if any to the #initialize ...
Definition object.c:2282
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:230
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:665
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
Definition object.c:902
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:492
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
rb_encoding * rb_usascii_encoding(void)
Queries the encoding that represents US-ASCII.
Definition encoding.c:1590
VALUE rb_enc_interned_str_cstr(const char *ptr, rb_encoding *enc)
Identical to rb_enc_str_new_cstr(), except it returns a "f"string.
Definition string.c:16391
VALUE rb_ary_entry(VALUE ary, rb_len_t off)
Queries an element of an array.
VALUE rb_ary_dup(VALUE ary)
Duplicates an array.
VALUE rb_ary_new_capa(rb_len_t capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
void rb_ary_store(VALUE ary, rb_len_t key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_hidden_new(rb_len_t capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
void rb_mem_clear(VALUE *buf, rb_len_t len)
Fills the memory region with a series of RUBY_Qnil.
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
VALUE rb_ary_join(VALUE ary, VALUE sep)
Recursively stringises the elements of the passed array, flattens that result, then joins the sequenc...
VALUE rb_get_values_at(VALUE obj, rb_len_t olen, int argc, const VALUE *argv, VALUE(*func)(VALUE obj, rb_len_t oidx))
This was a generalisation of Array#values_at, Struct#values_at, and MatchData#values_at.
#define RETURN_SIZED_ENUMERATOR(obj, argc, argv, size_fn)
This roughly resembles return enum_for(__callee__) unless block_given?.
Definition enumerator.h:208
#define UNLIMITED_ARGUMENTS
This macro is used in conjunction with rb_check_arity().
Definition error.h:35
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
VALUE rb_hash_new(void)
Creates a new, empty hash object.
Definition hash.c:1646
int rb_is_const_id(ID id)
Classifies the given ID, then sees if it is a constant.
Definition symbol.c:1242
int rb_is_local_id(ID id)
Classifies the given ID, then sees if it is a local variable.
Definition symbol.c:1272
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
Definition string.h:967
#define rb_hash_end(h)
Just another name of st_hash_end.
Definition string.h:970
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:3949
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition random.c:1714
#define rb_str_cat_cstr(buf, str)
Identical to rb_str_cat(), except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1681
VALUE rb_struct_define_without_accessor_under(VALUE outer, const char *class_name, VALUE super, rb_alloc_func_t alloc,...)
Identical to rb_struct_define_without_accessor(), except it defines the class under the specified nam...
Definition struct.c:505
VALUE rb_struct_define_under(VALUE space, const char *name,...)
Identical to rb_struct_define(), except it defines the class under the specified namespace instead of...
Definition struct.c:554
VALUE rb_struct_new(VALUE klass,...)
Creates an instance of the given struct.
Definition struct.c:959
VALUE rb_struct_initialize(VALUE self, VALUE values)
Mass-assigns a struct's fields.
Definition struct.c:872
VALUE rb_struct_define_without_accessor(const char *name, VALUE super, rb_alloc_func_t func,...)
Identical to rb_struct_define(), except it does not define accessor methods.
Definition struct.c:518
VALUE rb_struct_define(const char *name,...)
Defines a struct class.
Definition struct.c:531
VALUE rb_struct_alloc(VALUE klass, VALUE values)
Identical to rb_struct_new(), except it takes the field values as a Ruby array.
Definition struct.c:953
VALUE rb_data_define(VALUE super,...)
Defines an anonymous data class.
Definition struct.c:1823
VALUE rb_struct_alloc_noinit(VALUE klass)
Allocates an instance of the given class.
Definition struct.c:434
VALUE rb_struct_s_members(VALUE klass)
Queries the list of the names of the fields of the given struct class.
Definition struct.c:90
VALUE rb_struct_members(VALUE self)
Queries the list of the names of the fields of the class of the given struct object.
Definition struct.c:102
VALUE rb_struct_getmember(VALUE self, ID key)
Identical to rb_struct_aref(), except it takes ID instead of VALUE.
Definition struct.c:255
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
Definition thread.c:5960
VALUE rb_exec_recursive_paired(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h)
Identical to rb_exec_recursive(), except it checks for the recursion on the ordered pair of { g,...
Definition thread.c:5971
VALUE rb_mod_remove_const(VALUE space, VALUE name)
Resembles Module#remove_const.
Definition variable.c:3640
void rb_const_set(VALUE space, ID name, VALUE val)
Names a constant.
Definition variable.c:4018
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition variable.c:517
void rb_set_class_path_string(VALUE klass, VALUE space, VALUE name)
Identical to rb_set_class_path(), except it accepts the name as Ruby's string instead of C's.
Definition variable.c:440
int rb_const_defined_at(VALUE space, ID name)
Identical to rb_const_defined(), except it doesn't look for parent classes.
Definition variable.c:3876
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition variable.c:397
VALUE(* rb_alloc_func_t)(VALUE klass)
This is the type of functions that ruby calls when trying to allocate an object.
Definition vm.h:219
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1892
rb_alloc_func_t rb_get_alloc_func(VALUE klass)
Queries the allocator function of a class.
Definition vm_method.c:1901
VALUE rb_mod_module_eval(int argc, const VALUE *argv, VALUE mod)
Identical to rb_obj_instance_eval(), except it evaluates within the context of module.
Definition vm_eval.c:2500
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
VALUE rb_check_symbol(volatile VALUE *namep)
Identical to rb_check_id(), except it returns an instance of rb_cSymbol instead.
Definition symbol.c:1355
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:1155
VALUE rb_to_symbol(VALUE name)
Identical to rb_intern_str(), except it generates a dynamic symbol if necessary.
Definition string.c:16313
ID rb_to_id(VALUE str)
Identical to rb_intern_str(), except it tries to convert the parameter object to an instance of rb_cS...
Definition string.c:16303
int off
Offset inside of ptr.
Definition io.h:5
int len
Length of the buffer.
Definition io.h:8
VALUE rb_yield_values(int n,...)
Identical to rb_yield(), except it takes variadic number of parameters and pass them to the block.
Definition vm_eval.c:1419
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1396
#define rb_len2int
Just another name of rb_len2int_inline.
Definition len_t.h:37
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
Definition memory.h:363
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:170
void rb_hash_foreach(VALUE q, int_type *w, VALUE e)
Iteration over the given hash.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:50
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
Definition rarray.h:280
static VALUE * RARRAY_PTR(VALUE ary)
Wild use of a C pointer.
Definition rarray.h:365
#define RARRAY_AREF(a, i)
References an object in an array.
Definition rarray.h:422
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:51
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
VALUE rb_str_to_str(VALUE obj)
Identical to rb_check_string_type(), except it raises exceptions in case of conversion failures.
Definition string.c:1846
VALUE rb_struct_aset(VALUE st, VALUE k, VALUE v)
Resembles Struct#[]=.
Definition struct.c:1379
VALUE rb_struct_size(VALUE st)
Returns the number of struct members.
Definition struct.c:1629
VALUE rb_struct_aref(VALUE st, VALUE k)
Resembles Struct#[].
Definition struct.c:1341
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
Definition rtypeddata.h:81
#define RUBY_TYPED_FREE_IMMEDIATELY
Macros to see if each corresponding flag is defined.
Definition rtypeddata.h:122
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:239
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:604
#define InitVM(ext)
This macro is for internal use.
Definition ruby.h:231
#define RB_PASS_KEYWORDS
Pass keywords, final argument must be a hash of keywords.
Definition scan_args.h:72
#define RTEST
This is an old name of RB_TEST.
Ruby's ordinal objects.
Definition robject.h:51
VALUE extended
When an object slot is too small or too complex to store instance variables inline,...
Definition robject.h:73
long rb_len_t
A signed integer type for lengths and indices of objects such as String and Array.
Definition value.h:142
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static void Check_Type(VALUE v, enum ruby_value_type t)
Identical to RB_TYPE_P(), except it raises exceptions on predication failure.
Definition value_type.h:425
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376