Avoid needless object allocation
This commit is contained in:
parent
822d7ae316
commit
2439948bcc
5
struct.c
5
struct.c
@ -957,12 +957,15 @@ rb_struct_deconstruct_keys(VALUE s, VALUE keys)
|
|||||||
rb_obj_class(keys));
|
rb_obj_class(keys));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
if (RSTRUCT_LEN(s) < RARRAY_LEN(keys)) {
|
||||||
|
return rb_hash_new_with_size(0);
|
||||||
|
}
|
||||||
h = rb_hash_new_with_size(RARRAY_LEN(keys));
|
h = rb_hash_new_with_size(RARRAY_LEN(keys));
|
||||||
for (i=0; i<RARRAY_LEN(keys); i++) {
|
for (i=0; i<RARRAY_LEN(keys); i++) {
|
||||||
VALUE key = RARRAY_AREF(keys, i);
|
VALUE key = RARRAY_AREF(keys, i);
|
||||||
int i = rb_struct_pos(s, &key);
|
int i = rb_struct_pos(s, &key);
|
||||||
if (i < 0) {
|
if (i < 0) {
|
||||||
return rb_hash_new_with_size(0);
|
return h;
|
||||||
}
|
}
|
||||||
rb_hash_aset(h, key, RSTRUCT_GET(s, i));
|
rb_hash_aset(h, key, RSTRUCT_GET(s, i));
|
||||||
}
|
}
|
||||||
|
@ -1250,6 +1250,8 @@ END
|
|||||||
case s[a: 0, b: 1]
|
case s[a: 0, b: 1]
|
||||||
in a:, c:
|
in a:, c:
|
||||||
flunk
|
flunk
|
||||||
|
in a:, b:, c:
|
||||||
|
flunk
|
||||||
in b:
|
in b:
|
||||||
b == 1
|
b == 1
|
||||||
end
|
end
|
||||||
|
@ -437,7 +437,7 @@ module TestStruct
|
|||||||
assert_equal({a: 1, b: 2}, o.deconstruct_keys(nil))
|
assert_equal({a: 1, b: 2}, o.deconstruct_keys(nil))
|
||||||
assert_equal({a: 1, b: 2}, o.deconstruct_keys([:b, :a]))
|
assert_equal({a: 1, b: 2}, o.deconstruct_keys([:b, :a]))
|
||||||
assert_equal({a: 1}, o.deconstruct_keys([:a]))
|
assert_equal({a: 1}, o.deconstruct_keys([:a]))
|
||||||
assert_equal({}, o.deconstruct_keys([:a, :c]))
|
assert_not_send([o.deconstruct_keys([:a, :c]), :key?, :c])
|
||||||
assert_raise(TypeError) {
|
assert_raise(TypeError) {
|
||||||
o.deconstruct_keys(0)
|
o.deconstruct_keys(0)
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user