Skip to content

Commit 4095b26

Browse files
aardvark179eregon
authored andcommitted
Add a specs for printing VALUEs as pointers using rb_sprintf.
1 parent eb6e6f1 commit 4095b26

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

optional/capi/ext/string_spec.c

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -479,6 +479,15 @@ static VALUE string_spec_rb_sprintf6(VALUE self, VALUE width, VALUE precision, V
479479
return rb_sprintf("Result: %*.*" PRIsVALUE ".", FIX2INT(width), FIX2INT(precision), str);
480480
}
481481

482+
static VALUE string_spec_rb_sprintf7(VALUE self, VALUE str, VALUE obj) {
483+
VALUE results = rb_ary_new();
484+
rb_ary_push(results, rb_sprintf(RSTRING_PTR(str), obj));
485+
char cstr[256];
486+
int len = snprintf(cstr, 256, RSTRING_PTR(str), obj);
487+
rb_ary_push(results, rb_str_new(cstr, len));
488+
return results;
489+
}
490+
482491
PRINTF_ARGS(static VALUE string_spec_rb_vsprintf_worker(char* fmt, ...), 1, 2);
483492
static VALUE string_spec_rb_vsprintf_worker(char* fmt, ...) {
484493
va_list varargs;
@@ -638,6 +647,7 @@ void Init_string_spec(void) {
638647
rb_define_method(cls, "rb_sprintf4", string_spec_rb_sprintf4, 1);
639648
rb_define_method(cls, "rb_sprintf5", string_spec_rb_sprintf5, 3);
640649
rb_define_method(cls, "rb_sprintf6", string_spec_rb_sprintf6, 3);
650+
rb_define_method(cls, "rb_sprintf7", string_spec_rb_sprintf7, 2);
641651
rb_define_method(cls, "rb_vsprintf", string_spec_rb_vsprintf, 4);
642652
rb_define_method(cls, "rb_str_equal", string_spec_rb_str_equal, 2);
643653
rb_define_method(cls, "rb_usascii_str_new", string_spec_rb_usascii_str_new, 2);

optional/capi/string_spec.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1085,6 +1085,16 @@ def inspect
10851085
s = 'Result: Hello.'
10861086
@s.rb_sprintf6(8, 5, "Hello").should == s
10871087
end
1088+
1089+
it "can format a nil VALUE as a pointer and gives the same output as sprintf in C" do
1090+
res = @s.rb_sprintf7("%p", nil);
1091+
res[0].should == res[1]
1092+
end
1093+
1094+
it "can format a string VALUE as a pointer and gives the same output as sprintf in C" do
1095+
res = @s.rb_sprintf7("%p", "Hello")
1096+
res[0].should == res[1]
1097+
end
10881098
end
10891099

10901100
describe "rb_vsprintf" do

0 commit comments

Comments
 (0)