Commit b11ae3fd authored by Yukihiro "Matz" Matsumoto's avatar Yukihiro "Matz" Matsumoto

Merge pull request #1484 from fjmilens3/string_start_with

Bug in String#start_with? resulting from incorrect length determination
parents 975d670a 2548569f
...@@ -107,6 +107,7 @@ mrb_str_concat2(mrb_state *mrb, mrb_value self) ...@@ -107,6 +107,7 @@ mrb_str_concat2(mrb_state *mrb, mrb_value self)
* # returns true if one of the prefixes matches. * # returns true if one of the prefixes matches.
* "hello".start_with?("heaven", "hell") #=> true * "hello".start_with?("heaven", "hell") #=> true
* "hello".start_with?("heaven", "paradise") #=> false * "hello".start_with?("heaven", "paradise") #=> false
* "h".start_with?("heaven", "hell") #=> false
*/ */
static mrb_value static mrb_value
mrb_str_start_with(mrb_state *mrb, mrb_value self) mrb_str_start_with(mrb_state *mrb, mrb_value self)
...@@ -116,14 +117,15 @@ mrb_str_start_with(mrb_state *mrb, mrb_value self) ...@@ -116,14 +117,15 @@ mrb_str_start_with(mrb_state *mrb, mrb_value self)
mrb_get_args(mrb, "*", &argv, &argc); mrb_get_args(mrb, "*", &argv, &argc);
for (i = 0; i < argc; i++) { for (i = 0; i < argc; i++) {
size_t len_l, len_r, len_cmp; size_t len_l, len_r;
len_l = RSTRING_LEN(self); len_l = RSTRING_LEN(self);
len_r = RSTRING_LEN(argv[i]); len_r = RSTRING_LEN(argv[i]);
len_cmp = (len_l > len_r) ? len_r : len_l; if (len_l >= len_r) {
if (memcmp(RSTRING_PTR(self), RSTRING_PTR(argv[i]), len_cmp) == 0) { if (memcmp(RSTRING_PTR(self), RSTRING_PTR(argv[i]), len_r) == 0) {
return mrb_true_value(); return mrb_true_value();
} }
} }
}
return mrb_false_value(); return mrb_false_value();
} }
......
...@@ -104,6 +104,7 @@ end ...@@ -104,6 +104,7 @@ end
assert('String#start_with?') do assert('String#start_with?') do
assert_true "hello".start_with?("heaven", "hell") assert_true "hello".start_with?("heaven", "hell")
assert_true !"hello".start_with?("heaven", "paradise") assert_true !"hello".start_with?("heaven", "paradise")
assert_true !"h".start_with?("heaven", "hell")
end end
assert('String#end_with?') do assert('String#end_with?') do
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment