Add ObjectSpace.memsize_of_all
MODIFY
mrbgems/mruby-objectspace/src/mruby_objectspace.c
mrbgems/mruby-objectspace/src/mruby_objectspace.c
@@ -344,6 +344,30 @@ os_memsize_of(mrb_state *mrb, mrb_value self)
return mrb_fixnum_value(total);
}
+struct os_memsize_of_all_cb_data {
+ mrb_int t;
+ struct RClass *type;
+};
+
+static int
+os_memsize_of_all_cb(mrb_state *mrb, struct RBasic *obj, void *d)
+{
+ struct os_memsize_of_all_cb_data *data = (struct os_memsize_of_all_cb_data *)d;
+ if(obj->c == data->type) data->t += os_memsize_of_object(mrb, mrb_obj_value(obj));
+ return 0;
+}
+
+static mrb_value
+os_memsize_of_all(mrb_state *mrb, mrb_value self)
+{
+ mrb_value type;
+ struct os_memsize_of_all_cb_data data = { 0 };
+ mrb_get_args(mrb, "C", &type);
+ data.type = mrb_class_ptr(type);
+ mrb_objspace_each_objects(mrb, os_memsize_of_all_cb, &data);
+ return mrb_fixnum_value(data.t);
+}
+
void
mrb_mruby_objectspace_gem_init(mrb_state *mrb)
{
@@ -351,6 +375,7 @@ mrb_mruby_objectspace_gem_init(mrb_state *mrb)
mrb_define_class_method(mrb, os, "count_objects", os_count_objects, MRB_ARGS_OPT(1));
mrb_define_class_method(mrb, os, "each_object", os_each_object, MRB_ARGS_OPT(1));
mrb_define_class_method(mrb, os, "memsize_of", os_memsize_of, MRB_ARGS_REQ(1)|MRB_ARGS_OPT(1));
+ mrb_define_class_method(mrb, os, "memsize_of_all", os_memsize_of_all, MRB_ARGS_REQ(1));
}
void

MODIFY
mrbgems/mruby-objectspace/test/objectspace.rb
mrbgems/mruby-objectspace/test/objectspace.rb
-# coding: cp932
assert('ObjectSpace.count_objects') do
h = {}
f = Fiber.new {} if Object.const_defined?(:Fiber)
@@ -134,3 +133,17 @@ assert 'ObjectSpace.memsize_of' do
#hash
assert_not_equal ObjectSpace.memsize_of({}), 0, 'empty hash size not zero'
end
+
+assert 'ObjectSpace.memsize_of_all' do
+ foo_class = Class.new do
+ def initialize
+ @a = 'a'
+ @b = 'b'
+ end
+ end
+
+ foos = Array.new(10) { foo_class.new }
+ foo_size = ObjectSpace.memsize_of(foos.first)
+
+ assert_equal ObjectSpace.memsize_of_all(foo_class), foo_size * foos.size, 'Memsize of all instance'
+end

Add ObjectSpace.memsize_of_all