Commit 6d94883c
6d94883c4383Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 2 files · +1 added · ~1 modified
Description
Advance StringScanner#getch by a UTF-8 character, not a byte
getch incremented pos by exactly one byte, so a multi-byte character like
é (2 bytes) was returned split across getch calls -- corrupting the
character and misaligning pos / matched on any non-ASCII input. Advance by
the byte length of the UTF-8 character at the scan position instead, via a
small lead-byte-length helper (sp_runtime.h's sp_utf8_advance is static
inline and not visible from this translation unit).
Fixes #1264
Co-Authored-By: Claude Opus 4.8 [email protected]
Details
- Commit
- 6d94883c4383
- Parent
- 63f7f4505469
lib/sp_strscan.cmodifiedView file
@@ -107,6 +107,21 @@
107107
return out;108108
}109109
110+
/* Byte length of the UTF-8 character starting at src[pos], clamped so a111+
truncated or invalid lead byte near the end never reads past `len`.112+
Mirrors sp_utf8_advance in sp_runtime.h, which isn't visible from here113+
(this file includes only mruby_shim.h). */114+
static int64_t sc_char_len(const char *src, int64_t pos, int64_t len) {115+
unsigned char c = (unsigned char)src[pos];116+
int64_t n = 1;117+
if (c >= 0xF0) n = 4;118+
else if (c >= 0xE0) n = 3;119+
else if (c >= 0xC0) n = 2;120+
int64_t i = 1;121+
while (i < n && pos + i < len && ((unsigned char)src[pos + i] & 0xC0) == 0x80) i++;122+
return i;123+
}124+
110125
const char *sp_StringScanner_scan(sp_StringScanner *sc, mrb_regexp_pattern *pat) {111126
if (!sc || !pat) return sp_ext_str_empty();112127
int64_t slen = (int64_t)sp_ext_str_byte_len(sc->source);@@ -212,11 +227,12 @@
212227
sc->matched_p = 0;213228
return sp_ext_str_empty();214229
}215-
char *c = sc_substr(sc->source, sc->pos, 1);230+
int64_t clen = sc_char_len(sc->source, sc->pos, slen);231+
char *c = sc_substr(sc->source, sc->pos, clen);216232
sc->last_pos = sc->pos;217233
sc->matched = c;218234
sc->matched_p = 1;219-
sc->pos += 1;235+
sc->pos += clen;220236
return c;221237
}222238
test/string_scanner_getch_utf8.rbaddedView file
Loading diff…