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 "transient_heap.h"
28 AREF_HASH_THRESHOLD = 10
32static ID id_members, id_back_members, id_keyword_init;
57rb_struct_s_keyword_init(
VALUE klass)
59 return struct_ivar_get(klass, id_keyword_init);
65 VALUE members = struct_ivar_get(klass, id_members);
89struct_member_pos_ideal(
VALUE name,
long mask)
92 return (
SYM2ID(name) >> (ID_SCOPE_SHIFT - 1)) & mask;
96struct_member_pos_probe(
long prev,
long mask)
99 return (prev * AREF_HASH_UNIT + 2) & mask;
106 const long members_length =
RARRAY_LEN(members);
108 if (members_length <= AREF_HASH_THRESHOLD) {
112 long i, j, mask = 64;
115 while (mask < members_length * AREF_HASH_UNIT) mask *= 2;
117 back = rb_ary_tmp_new(mask + 1);
118 rb_ary_store(back, mask,
INT2FIX(members_length));
121 for (i=0; i < members_length; i++) {
124 j = struct_member_pos_ideal(name, mask);
128 rb_ary_store(back, j, name);
129 rb_ary_store(back, j + 1,
INT2FIX(i));
132 j = struct_member_pos_probe(j, mask);
149 if (UNLIKELY(
NIL_P(back))) {
158 if (mask <= AREF_HASH_THRESHOLD) {
159 if (UNLIKELY(RSTRUCT_LEN(s) != mask)) {
161 "struct size differs (%ld required %ld given)",
162 mask, RSTRUCT_LEN(s));
164 for (j = 0; j < mask; j++) {
177 j = struct_member_pos_ideal(name, mask);
186 j = struct_member_pos_probe(j, mask);
202rb_struct_s_members_m(
VALUE klass)
206 return rb_ary_dup(members);
222rb_struct_members_m(
VALUE obj)
231 int i = struct_member_pos(obj, slot);
233 return RSTRUCT_GET(obj, i);
235 rb_name_err_raise(
"`%1$s' is not a struct member", obj,
ID2SYM(
id));
241rb_struct_modify(
VALUE s)
247anonymous_struct(
VALUE klass)
252 rb_make_metaclass(nstr,
RBASIC(klass)->klass);
263 if (!rb_is_const_name(name)) {
264 rb_name_err_raise(
"identifier %1$s needs to be constant",
269 rb_warn(
"redefining constant %"PRIsVALUE
"::%"PRIsVALUE, super, name);
275NORETURN(
static void invalid_struct_pos(
VALUE s,
VALUE idx));
280 rb_add_method_optimized(nstr,
SYM2ID(name), OPTIMIZED_METHOD_TYPE_STRUCT_AREF,
FIX2UINT(off), METHOD_VISI_PUBLIC);
286 rb_add_method_optimized(nstr,
SYM2ID(name), OPTIMIZED_METHOD_TYPE_STRUCT_ASET,
FIX2UINT(off), METHOD_VISI_PUBLIC);
290rb_struct_s_inspect(
VALUE klass)
293 if (
RTEST(rb_struct_s_keyword_init(klass))) {
317rb_struct_s_keyword_init_p(
VALUE obj)
322#define rb_struct_s_keyword_init_p rb_struct_s_keyword_init
329 members = struct_set_members(nstr, members);
339 for (i=0; i< len; i++) {
344 define_aref_method(nstr, sym, off);
354 return struct_alloc(klass);
358struct_make_members_list(va_list ar)
361 VALUE ary, list = rb_ident_hash_new();
362 st_table *tbl = RHASH_TBL_RAW(list);
364 RBASIC_CLEAR_CLASS(list);
366 while ((mem = va_arg(ar,
char*)) != 0) {
367 VALUE sym = rb_sym_intern_ascii_cstr(mem);
368 if (st_insert(tbl, sym,
Qtrue)) {
372 ary = rb_hash_keys(list);
374 RBASIC_CLEAR_CLASS(ary);
393 klass = anonymous_struct(super);
396 struct_set_members(klass, members);
415 members = struct_make_members_list(ar);
418 return struct_define_without_accessor(outer, class_name, super, alloc, members);
428 members = struct_make_members_list(ar);
431 return struct_define_without_accessor(0, class_name, super, alloc, members);
441 ary = struct_make_members_list(ar);
446 return setup_struct(st, ary);
456 ary = struct_make_members_list(ar);
573rb_struct_s_def(
int argc,
VALUE *argv,
VALUE klass)
591 static ID keyword_ids[1];
593 if (!keyword_ids[0]) {
594 keyword_ids[0] =
rb_intern(
"keyword_init");
596 rb_get_kwargs(argv[argc-1], keyword_ids, 0, 1, &keyword_init);
597 if (keyword_init ==
Qundef) {
600 else if (
RTEST(keyword_init)) {
601 keyword_init =
Qtrue;
606 rest = rb_ident_hash_new();
607 RBASIC_CLEAR_CLASS(rest);
609 tbl = RHASH_TBL_RAW(rest);
610 for (i=0; i<argc; i++) {
612 if (rb_is_attrset_sym(mem)) {
615 if (st_insert(tbl, mem,
Qtrue)) {
619 rest = rb_hash_keys(rest);
621 RBASIC_CLEAR_CLASS(rest);
624 st = anonymous_struct(klass);
627 st = new_struct(name, klass);
629 setup_struct(st, rest);
639num_members(
VALUE klass)
642 members = struct_ivar_get(klass, id_members);
654 VALUE unknown_keywords;
657static int rb_struct_pos(
VALUE s,
VALUE *name);
663 int i = rb_struct_pos(args->self, &key);
665 if (
NIL_P(args->unknown_keywords)) {
666 args->unknown_keywords = rb_ary_new();
668 rb_ary_push(args->unknown_keywords, key);
671 rb_struct_modify(args->self);
672 RSTRUCT_SET(args->self, i, val);
678rb_struct_initialize_m(
int argc,
const VALUE *argv,
VALUE self)
681 rb_struct_modify(self);
682 long n = num_members(klass);
684 rb_mem_clear((
VALUE *)RSTRUCT_CONST_PTR(self), n);
688 VALUE keyword_init = rb_struct_s_keyword_init(klass);
689 if (
RTEST(keyword_init)) {
694 rb_mem_clear((
VALUE *)RSTRUCT_CONST_PTR(self), n);
696 arg.unknown_keywords =
Qnil;
698 if (arg.unknown_keywords !=
Qnil) {
708 rb_warn(
"Passing only keyword arguments to Struct#initialize will behave differently from Ruby 3.2. "\
709 "Please use a Hash literal like .new({k: v}) instead of .new(k: v).");
711 for (
long i=0; i<argc; i++) {
712 RSTRUCT_SET(self, i, argv[i]);
715 rb_mem_clear((
VALUE *)RSTRUCT_CONST_PTR(self)+argc, n-argc);
730struct_heap_alloc(
VALUE st,
size_t len)
735 RSTRUCT_TRANSIENT_SET(st);
739 RSTRUCT_TRANSIENT_UNSET(st);
744#if USE_TRANSIENT_HEAP
746rb_struct_transient_heap_evacuate(
VALUE obj,
int promote)
748 if (RSTRUCT_TRANSIENT_P(obj)) {
749 const VALUE *old_ptr = rb_struct_const_heap_ptr(obj);
751 long len = RSTRUCT_LEN(obj);
758 new_ptr = struct_heap_alloc(obj, len);
761 RSTRUCT(obj)->as.heap.ptr = new_ptr;
767struct_alloc(
VALUE klass)
772 n = num_members(klass);
774 if (0 < n && n <= RSTRUCT_EMBED_LEN_MAX) {
775 RBASIC(st)->flags &= ~RSTRUCT_EMBED_LEN_MASK;
776 RBASIC(st)->flags |= n << RSTRUCT_EMBED_LEN_SHIFT;
777 rb_mem_clear((
VALUE *)st->as.ary, n);
780 st->as.heap.ptr = struct_heap_alloc((
VALUE)st, n);
781 rb_mem_clear((
VALUE *)st->as.heap.ptr, n);
797 VALUE tmpargs[16], *mem = tmpargs;
802 if (size > numberof(tmpargs)) {
803 tmpargs[0] = rb_ary_tmp_new(size);
806 va_start(args, klass);
807 for (i=0; i<size; i++) {
808 mem[i] = va_arg(args,
VALUE);
844rb_struct_each(
VALUE s)
849 for (i=0; i<RSTRUCT_LEN(s); i++) {
879rb_struct_each_pair(
VALUE s)
886 if (rb_block_pair_yield_optimizable()) {
887 for (i=0; i<RSTRUCT_LEN(s); i++) {
888 VALUE key = rb_ary_entry(members, i);
889 VALUE value = RSTRUCT_GET(s, i);
894 for (i=0; i<RSTRUCT_LEN(s); i++) {
895 VALUE key = rb_ary_entry(members, i);
896 VALUE value = RSTRUCT_GET(s, i);
904inspect_struct(
VALUE s,
VALUE dummy,
int recur)
911 if (recur || first !=
'#') {
919 len = RSTRUCT_LEN(s);
921 for (i=0; i<len; i++) {
928 else if (first !=
'#') {
962rb_struct_inspect(
VALUE s)
983rb_struct_to_a(
VALUE s)
985 return rb_ary_new4(RSTRUCT_LEN(s), RSTRUCT_CONST_PTR(s));
1012rb_struct_to_h(
VALUE s)
1014 VALUE h = rb_hash_new_with_size(RSTRUCT_LEN(s));
1019 for (i=0; i<RSTRUCT_LEN(s); i++) {
1020 VALUE k = rb_ary_entry(members, i), v = RSTRUCT_GET(s, i);
1024 rb_hash_aset(h, k, v);
1047rb_struct_deconstruct_keys(
VALUE s,
VALUE keys)
1053 return rb_struct_to_h(s);
1057 "wrong argument type %"PRIsVALUE
" (expected Array or nil)",
1062 return rb_hash_new_with_size(0);
1067 int i = rb_struct_pos(s, &key);
1071 rb_hash_aset(h, key, RSTRUCT_GET(s, i));
1083 if (RSTRUCT_LEN(copy) != RSTRUCT_LEN(s)) {
1087 for (i=0, len=RSTRUCT_LEN(copy); i<len; i++) {
1088 RSTRUCT_SET(copy, i, RSTRUCT_GET(s, i));
1101 return struct_member_pos(s, idx);
1105 if (
NIL_P(idx))
return -1;
1106 return struct_member_pos(s, idx);
1111 len = RSTRUCT_LEN(s);
1119 else if (len <= i) {
1131 long i =
FIX2INT(idx), len = RSTRUCT_LEN(s);
1142 rb_name_err_raise(
"no member '%1$s' in struct", s, idx);
1175 int i = rb_struct_pos(s, &idx);
1176 if (i < 0) invalid_struct_pos(s, idx);
1177 return RSTRUCT_GET(s, i);
1213 int i = rb_struct_pos(s, &idx);
1214 if (i < 0) invalid_struct_pos(s, idx);
1215 rb_struct_modify(s);
1216 RSTRUCT_SET(s, i, val);
1226 return rb_struct_lookup_default(s, idx,
Qnil);
1232 int i = rb_struct_pos(s, &idx);
1233 if (i < 0)
return notfound;
1234 return RSTRUCT_GET(s, i);
1238struct_entry(
VALUE s,
long n)
1279rb_struct_values_at(
int argc,
VALUE *argv,
VALUE s)
1281 return rb_get_values_at(s, RSTRUCT_LEN(s), argc, argv, struct_entry);
1305rb_struct_select(
int argc,
VALUE *argv,
VALUE s)
1312 result = rb_ary_new();
1313 for (i = 0; i < RSTRUCT_LEN(s); i++) {
1315 rb_ary_push(result, RSTRUCT_GET(s, i));
1327 if (recur)
return Qtrue;
1328 len = RSTRUCT_LEN(s);
1329 for (i=0; i<len; i++) {
1330 if (!
rb_equal(RSTRUCT_GET(s, i), RSTRUCT_GET(s2, i)))
return Qfalse;
1359 if (s == s2)
return Qtrue;
1362 if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) {
1363 rb_bug(
"inconsistent struct");
1389rb_struct_hash(
VALUE s)
1396 len = RSTRUCT_LEN(s);
1397 for (i = 0; i < len; i++) {
1398 n = rb_hash(RSTRUCT_GET(s, i));
1410 if (recur)
return Qtrue;
1411 len = RSTRUCT_LEN(s);
1412 for (i=0; i<len; i++) {
1413 if (!
rb_eql(RSTRUCT_GET(s, i), RSTRUCT_GET(s2, i)))
return Qfalse;
1440 if (s == s2)
return Qtrue;
1443 if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) {
1444 rb_bug(
"inconsistent struct");
1502rb_struct_dig(
int argc,
VALUE *argv,
VALUE self)
1505 self = rb_struct_lookup(self, *argv);
1506 if (!--argc)
return self;
1508 return rb_obj_dig(argc, argv, self,
Qnil);
1662 id_back_members =
rb_intern(
"__members_back__");
1663 id_keyword_init =
rb_intern(
"__keyword_init__");
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
VALUE rb_class_new(VALUE super)
Creates a new, anonymous class.
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
VALUE rb_define_class_id_under(VALUE outer, ID id, VALUE super)
Identical to rb_define_class_under(), except it takes the name in ID instead of C's string.
VALUE rb_class_inherited(VALUE super, VALUE klass)
Calls Class::inherited.
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
int rb_block_given_p(void)
Determines if the current method is given a block.
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
#define rb_str_new2
Old name of rb_str_new_cstr.
#define NEWOBJ_OF
Old name of RB_NEWOBJ_OF.
#define FL_UNSET_RAW
Old name of RB_FL_UNSET_RAW.
#define OBJ_INIT_COPY(obj, orig)
Old name of RB_OBJ_INIT_COPY.
#define T_STRING
Old name of RUBY_T_STRING.
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
#define rb_str_cat2
Old name of rb_str_cat_cstr.
#define ID2SYM
Old name of RB_ID2SYM.
#define T_STRUCT
Old name of RUBY_T_STRUCT.
#define OBJ_FREEZE_RAW
Old name of RB_OBJ_FREEZE_RAW.
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
#define SYM2ID
Old name of RB_SYM2ID.
#define FIX2UINT
Old name of RB_FIX2UINT.
#define rb_ary_new4
Old name of rb_ary_new_from_values.
#define LONG2FIX
Old name of RB_INT2FIX.
#define FIX2INT
Old name of RB_FIX2INT.
#define T_HASH
Old name of RUBY_T_HASH.
#define ALLOC_N
Old name of RB_ALLOC_N.
#define LONG2NUM
Old name of RB_LONG2NUM.
#define Qtrue
Old name of RUBY_Qtrue.
#define ST2FIX
Old name of RB_ST2FIX.
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
#define NIL_P
Old name of RB_NIL_P.
#define FL_WB_PROTECTED
Old name of RUBY_FL_WB_PROTECTED.
#define NUM2LONG
Old name of RB_NUM2LONG.
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define OBJ_WB_UNPROTECT
Old name of RB_OBJ_WB_UNPROTECT.
#define SYMBOL_P
Old name of RB_SYMBOL_P.
void rb_raise(VALUE exc, const char *fmt,...)
Exception entry point.
void rb_bug(const char *fmt,...)
Interpreter panic switch.
VALUE rb_eTypeError
TypeError exception.
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports always regardless of runtime -W flag.
VALUE rb_eArgError
ArgumentError exception.
VALUE rb_eIndexError
IndexError exception.
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
VALUE rb_mEnumerable
Enumerable module.
VALUE rb_cStruct
Struct class.
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 ...
int rb_eql(VALUE lhs, VALUE rhs)
Checks for equality of the passed objects, in terms of Object#eql?.
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
#define RETURN_SIZED_ENUMERATOR(obj, argc, argv, size_fn)
This roughly resembles return enum_for(__callee__) unless block_given?.
#define UNLIMITED_ARGUMENTS
This macro is used in conjunction with rb_check_arity().
#define rb_check_frozen
Just another name of rb_check_frozen.
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
int rb_is_const_id(ID id)
Classifies the given ID, then sees if it is a constant.
ID rb_id_attrset(ID id)
Calculates an ID of attribute writer.
int rb_is_local_id(ID id)
Classifies the given ID, then sees if it is a local variable.
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
#define rb_hash_end(h)
Just another name of st_hash_end.
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
#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.
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...
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...
VALUE rb_struct_new(VALUE klass,...)
Creates an instance of the given struct.
VALUE rb_struct_initialize(VALUE self, VALUE values)
Mass-assigns a struct's fields.
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.
VALUE rb_struct_define(const char *name,...)
Defines a struct class.
VALUE rb_struct_alloc(VALUE klass, VALUE values)
Identical to rb_struct_new(), except it takes the field values as a Ruby array.
VALUE rb_struct_alloc_noinit(VALUE klass)
Allocates an instance of the given class.
VALUE rb_struct_s_members(VALUE klass)
Queries the list of the names of the fields of the given struct class.
VALUE rb_struct_members(VALUE self)
Queries the list of the names of the fields of the class of the given struct object.
VALUE rb_struct_getmember(VALUE self, ID key)
Identical to rb_struct_aref(), except it takes ID instead of VALUE.
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
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,...
VALUE rb_attr_get(VALUE obj, ID name)
Identical to rb_ivar_get()
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
VALUE rb_mod_remove_const(VALUE space, VALUE name)
Resembles Module#remove_const.
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
int rb_const_defined_at(VALUE space, ID name)
Identical to rb_const_defined(), except it doesn't look for parent classes.
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
VALUE(* rb_alloc_func_t)(VALUE klass)
This is the type of functions that ruby calls when trying to allocate an object.
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
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.
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.
ID rb_intern(const char *name)
Finds or creates a symbol of the given name.
VALUE rb_to_symbol(VALUE name)
Identical to rb_intern_str(), except it generates a dynamic symbol if necessary.
ID rb_to_id(VALUE str)
Identical to rb_intern(), except it takes an instance of rb_cString.
VALUE rb_yield_values(int n,...)
Identical to rb_yield(), except it takes variadic number of parameters and pass them to the block.
VALUE rb_yield(VALUE val)
Yields the block.
#define rb_long2int
Just another name of rb_long2int_inline.
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
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.
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
static VALUE * RARRAY_PTR(VALUE ary)
Wild use of a C pointer.
#define RARRAY_AREF(a, i)
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
#define RBASIC(obj)
Convenient casting macro.
#define RCLASS_SUPER
Just another name of rb_class_get_superclass.
#define RGENGC_WB_PROTECTED_STRUCT
This is a compile-time flag to enable/disable write barrier for struct RStruct.
VALUE rb_str_to_str(VALUE obj)
Identical to rb_check_string_type(), except it raises exceptions in case of conversion failures.
static char * RSTRING_PTR(VALUE str)
Queries the contents pointer of the string.
VALUE rb_struct_aset(VALUE st, VALUE k, VALUE v)
Resembles Struct#[]=.
VALUE rb_struct_size(VALUE st)
Returns the number of struct members.
VALUE rb_struct_aref(VALUE st, VALUE k)
Resembles Struct#[].
#define InitVM(ext)
This macro is for internal use.
#define RTEST
This is an old name of RB_TEST.
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
uintptr_t VALUE
Type that represents a Ruby object.
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.