Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions mrbgems/mruby-string-ext/test/string.rb
Original file line number Diff line number Diff line change
Expand Up @@ -797,6 +797,28 @@ def assert_upto(exp, receiver, *args)
assert_equal ["こ", "ん", "に", "ち", "は", "世", "界", "!"], chars
end if UTF8STRING

assert('String#chop! on a binary string removes one byte') do
# `chop!` walks to the last character, and a byte-indexed string ends in a
# byte rather than in a character. Walking it as UTF-8 took the whole of a
# multi-byte sequence off, or all of a string that held only one.
if UTF8STRING
s = "\u{1F600}".b # F0 9F 98 80: four bytes, one character
s.chop!
assert_equal "\xF0\x9F\x98".b, s
t = "a\u{1F600}".b
t.chop!
assert_equal "a\xF0\x9F\x98".b, t
# a string read as UTF-8 still loses the whole character
u = "\u{1F600}"
u.chop!
assert_equal "", u
# and the \r\n pair is still taken together
v = "a\r\n".b
v.chop!
assert_equal "a", v
end
end

assert('String#codepoints') do
expect = [104, 101, 108, 108, 111, 33]
assert_equal expect, "hello!".codepoints
Expand Down
20 changes: 13 additions & 7 deletions src/string.c
Original file line number Diff line number Diff line change
Expand Up @@ -1867,14 +1867,20 @@ mrb_str_chop_bang(mrb_state *mrb, mrb_value str)
if (RSTR_LEN(s) > 0) {
mrb_int len;
#ifdef MRB_UTF8_STRING
const char* t = RSTR_PTR(s), *p = t;
const char* e = p + RSTR_LEN(s);
while (p<e) {
mrb_int clen = mrb_utf8len(p, e);
if (p + clen>=e) break;
p += clen;
if (RSTR_BINARY_P(s)) {
/* The last position of a byte-indexed string is its last byte. */
len = RSTR_LEN(s) - 1;
}
else {
const char* t = RSTR_PTR(s), *p = t;
const char* e = p + RSTR_LEN(s);
while (p<e) {
mrb_int clen = mrb_utf8len(p, e);
if (p + clen>=e) break;
p += clen;
}
len = p - t;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}
len = p - t;
#else
len = RSTR_LEN(s) - 1;
#endif
Expand Down
Loading