Skip to content

Commit

Permalink
Added RHASH_SET_IFNONE/rb_hash_set_ifnone
Browse files Browse the repository at this point in the history
These are basically the C equivalents of Hash#default=.
  • Loading branch information
Yorick Peterse committed May 8, 2015
1 parent 8d6cfbe commit c01b664
Show file tree
Hide file tree
Showing 5 changed files with 31 additions and 0 deletions.
10 changes: 10 additions & 0 deletions spec/ruby/optional/capi/ext/hash_spec.c
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,12 @@ VALUE hash_spec_rb_hash_size(VALUE self, VALUE hash) {
}
#endif

#ifdef HAVE_RB_HASH_SET_IFNONE
VALUE hash_spec_rb_hash_set_ifnone(VALUE self, VALUE hash, VALUE def) {
return rb_hash_set_ifnone(hash, def);
}
#endif

void Init_hash_spec() {
VALUE cls;
cls = rb_define_class("CApiHashSpecs", rb_cObject);
Expand Down Expand Up @@ -152,6 +158,10 @@ void Init_hash_spec() {
#ifdef HAVE_RB_HASH_SIZE
rb_define_method(cls, "rb_hash_size", hash_spec_rb_hash_size, 1);
#endif

#ifdef HAVE_RB_HASH_SET_IFNONE
rb_define_method(cls, "rb_hash_set_ifnone", hash_spec_rb_hash_set_ifnone, 2);
#endif
}

#ifdef __cplusplus
Expand Down
1 change: 1 addition & 0 deletions spec/ruby/optional/capi/ext/rubyspec.h
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,7 @@
#define HAVE_RB_HASH_LOOKUP2 1
#define HAVE_RB_HASH_NEW 1
#define HAVE_RB_HASH_SIZE 1
#define HAVE_RB_HASH_SET_IFNONE 1

/* Integer */
#ifdef RUBY_VERSION_IS_2_1
Expand Down
10 changes: 10 additions & 0 deletions spec/ruby/optional/capi/hash_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -168,4 +168,14 @@
end
end
end

describe "rb_hash_set_ifnone" do
it "sets the default value of non existing keys" do
hash = {}

@s.rb_hash_set_ifnone(hash, 10)

hash[:chunky].should == 10
end
end
end
6 changes: 6 additions & 0 deletions vm/capi/hash.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,10 @@ extern "C" {
}
}
}

VALUE rb_hash_set_ifnone(VALUE hash, VALUE def) {
capi_fast_call(hash, rb_intern("default="), 1, def);

return hash;
}
}
4 changes: 4 additions & 0 deletions vm/include/capi/ruby/ruby.h
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,8 @@ struct RFloat {
#define RHASH(obj) ({ C_API_RHASH_is_not_supported_in_Rubinius })
#define RHASH_TBL(obj) ({ C_API_RHASH_TBL_is_not_supported_in_Rubinius })

#define RHASH_SET_IFNONE(hash, def) rb_hash_set_ifnone(hash, def)

typedef struct rb_io_t {
VALUE handle;
int fd;
Expand Down Expand Up @@ -1462,6 +1464,8 @@ struct RTypedData {
int (*func)(ANYARGS),
VALUE farg);

VALUE rb_hash_set_ifnone(VALUE hash, VALUE def);

void rb_eof_error();

VALUE rb_io_addstr(VALUE, VALUE);
Expand Down

0 comments on commit c01b664

Please sign in to comment.