Skip to content

Commit

Permalink
Add String#prepend
Browse files Browse the repository at this point in the history
  • Loading branch information
suzukaze committed Dec 16, 2014
1 parent ab72410 commit 7ea38ce
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
39 changes: 39 additions & 0 deletions mrbgems/mruby-string-ext/src/string.c
Expand Up @@ -331,6 +331,44 @@ mrb_str_succ(mrb_state *mrb, mrb_value self)
return str;
}

/*
* call-seq:
* str.prepend(other_str) -> str
*
* Prepend---Prepend the given string to <i>str</i>.
*
* a = "world"
* a.prepend("hello ") #=> "hello world"
* a #=> "hello world"
*/
static mrb_value
mrb_str_prepend(mrb_state *mrb, mrb_value self)
{
struct RString *s1 = mrb_str_ptr(self), *s2, *temp_s;
mrb_int len;
mrb_value other, temp_str;

mrb_get_args(mrb, "S", &other);

mrb_str_modify(mrb, s1);
if (!mrb_string_p(other)) {
other = mrb_str_to_str(mrb, other);
}
s2 = mrb_str_ptr(other);
len = RSTR_LEN(s1) + RSTR_LEN(s2);
temp_str = mrb_str_new(mrb, "", RSTR_LEN(s1));
temp_s = mrb_str_ptr(temp_str);
memcpy(RSTR_PTR(temp_s), RSTR_PTR(s1), RSTR_LEN(s1));
if (RSTRING_CAPA(self) < len) {
mrb_str_resize(mrb, self, len);
}
memcpy(RSTR_PTR(s1), RSTR_PTR(s2), RSTR_LEN(s2));
memcpy(RSTR_PTR(s1) + RSTR_LEN(s2), RSTR_PTR(temp_s), RSTR_LEN(temp_s));
RSTR_SET_LEN(s1, len);
RSTR_PTR(s1)[len] = '\0';
return self;
}

void
mrb_mruby_string_ext_gem_init(mrb_state* mrb)
{
Expand All @@ -350,6 +388,7 @@ mrb_mruby_string_ext_gem_init(mrb_state* mrb)
mrb_define_method(mrb, s, "lines", mrb_str_lines, MRB_ARGS_NONE());
mrb_define_method(mrb, s, "succ", mrb_str_succ, MRB_ARGS_NONE());
mrb_define_method(mrb, s, "succ!", mrb_str_succ_bang, MRB_ARGS_NONE());
mrb_define_method(mrb, s, "prepend", mrb_str_prepend, MRB_ARGS_REQ(1));
mrb_alias_method(mrb, s, mrb_intern_lit(mrb, "next"), mrb_intern_lit(mrb, "succ"));
mrb_alias_method(mrb, s, mrb_intern_lit(mrb, "next!"), mrb_intern_lit(mrb, "succ!"));
}
Expand Down
6 changes: 6 additions & 0 deletions mrbgems/mruby-string-ext/test/string.rb
Expand Up @@ -380,3 +380,9 @@ def o.to_str
assert_raise(IndexError) { "abcd".insert(5, 'X') }
assert_raise(IndexError) { "abcd".insert(-6, 'X') }
end

assert('String#prepend') do
a = "world"
assert_equal "hello world", a.prepend("hello ")
assert_equal "hello world", a
end

0 comments on commit 7ea38ce

Please sign in to comment.