summaryrefslogtreecommitdiffhomepage
path: root/src/string.c
diff options
context:
space:
mode:
authordearblue <[email protected]>2019-06-22 16:32:17 +0900
committerdearblue <[email protected]>2019-06-22 22:36:58 +0900
commitbd2c93c2dfbb944f57b10b7b9c056caf852a5053 (patch)
tree0d8f1aa2f576ac43f02cca7859c3a9aadac3ad53 /src/string.c
parent7c6d6effaea6ec3cbac01cffc4f094744d53d8b9 (diff)
downloadmruby-bd2c93c2dfbb944f57b10b7b9c056caf852a5053.tar.gz
mruby-bd2c93c2dfbb944f57b10b7b9c056caf852a5053.zip
Change to UTF-8 string reversing with in place
Reverses UTF-8 strings without allocated heap for working memory. 1. String before reversing: ``` "!yburmの界世" # byte unit [33, 121, 98, 117, 114, 109, 227, 129, 174, 231, 149, 140, 228, 184, 150] ``` 2. Reverse the byte order of each character: ``` [33, 121, 98, 117, 114, 109, 174, 129, 227, 140, 149, 231, 150, 184, 228] ``` 3. Reverse the whole byte order and complete: ``` [228, 184, 150, 231, 149, 140, 227, 129, 174, 109, 114, 117, 98, 121, 33] # string "世界のmruby!" ```
Diffstat (limited to 'src/string.c')
-rw-r--r--src/string.c28
1 files changed, 8 insertions, 20 deletions
diff --git a/src/string.c b/src/string.c
index 282f8d776..6d01b773c 100644
--- a/src/string.c
+++ b/src/string.c
@@ -1693,40 +1693,28 @@ str_reverse(char *p, char *e)
static mrb_value
mrb_str_reverse_bang(mrb_state *mrb, mrb_value str)
{
+ struct RString *s = mrb_str_ptr(str);
+ char *p, *e;
+
#ifdef MRB_UTF8_STRING
mrb_int utf8_len = RSTRING_CHAR_LEN(str);
- mrb_int len = RSTRING_LEN(str);
+ mrb_int len = RSTR_LEN(s);
if (utf8_len == len) goto bytes;
if (utf8_len > 1) {
- char *buf;
- char *p, *e, *r;
-
- mrb_str_modify(mrb, mrb_str_ptr(str));
- len = RSTRING_LEN(str);
- buf = (char*)mrb_malloc(mrb, (size_t)len);
- p = buf;
- e = buf + len;
-
- memcpy(buf, RSTRING_PTR(str), len);
- r = RSTRING_PTR(str) + len;
-
+ mrb_str_modify(mrb, s);
+ p = RSTR_PTR(s);
+ e = p + RSTR_LEN(s);
while (p<e) {
mrb_int clen = utf8len(p, e);
- r -= clen;
- memcpy(r, p, clen);
+ str_reverse(p, p + clen - 1);
p += clen;
}
- mrb_free(mrb, buf);
}
- return str;
bytes:
#endif
{
- struct RString *s = mrb_str_ptr(str);
- char *p, *e;
-
mrb_str_modify(mrb, s);
if (RSTR_LEN(s) > 1) {
p = RSTR_PTR(s);