Commit 89ecfd6b

89ecfd6b3673Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 4 files · +2 added · ~2 modified

Description

Merge pull request #1064 from neidiom/fix/str-match-position

Fix String#match/match? with position argument

Details

Commit
89ecfd6b3673
Parent
1b0cb716ccf8
Merge parent
9f24638221eb

lib/sp_runtime.hmodifiedView file

@@ -1955,6 +1955,18 @@
19551955 int caps[2];
19561956 return re_exec(pat, str, slen, (mrb_int)pos, caps, 2) > 0;
19571957 }
1958+/* String#match?(/re/, pos) — pos is a codepoint index (CRuby semantics),
1959+ unlike Regexp#match?(str, pos) which uses byte offset. Convert the
1960+ codepoint index to a byte offset before dispatching to re_exec. */
1961+static mrb_bool sp_str_re_match_p_at(mrb_regexp_pattern *pat, const char *str, mrb_int cpos) {
1962+ mrb_int cl = sp_str_length(str);
1963+ if (cpos < 0) cpos += cl;
1964+ if (cpos < 0 || cpos > cl) return FALSE;
1965+ size_t boff = sp_utf8_byte_offset(str, cpos);
1966+ int64_t slen = (int64_t)strlen(str);
1967+ int caps[2];
1968+ return re_exec(pat, str, slen, (mrb_int)boff, caps, 2) > 0;
1969+}
19581970
19591971 /* Issue #855: expand `\1`..`\9` / `\&` / `\0` backreferences in
19601972 the replacement string against the current caps[] array. `\\`
@@ -2582,6 +2594,29 @@
25822594 for (int i = 0; i < pairs * 2; i++) m->caps[i] = caps[i];
25832595 return m;
25842596 }
2597+/* String#match(/re/, pos) — pos is a codepoint index (CRuby semantics). */
2598+static sp_MatchData *sp_re_matchdata_at(mrb_regexp_pattern *pat, const char *str, mrb_int cpos) {
2599+ mrb_int cl = sp_str_length(str);
2600+ if (cpos < 0) cpos += cl;
2601+ if (cpos < 0 || cpos > cl) return NULL;
2602+ size_t boff = sp_utf8_byte_offset(str, cpos);
2603+ int64_t slen = (int64_t)strlen(str);
2604+ int caps[64];
2605+ int n = re_exec(pat, str, slen, (mrb_int)boff, caps, 64);
2606+ if (n <= 0 || caps[0] < 0) {
2607+ for (int i = 0; i < 10; i++) sp_re_captures[i] = NULL;
2608+ sp_re_last_str = NULL; sp_re_match_str = NULL;
2609+ sp_re_match_pre = NULL; sp_re_match_post = NULL;
2610+ return NULL;
2611+ }
2612+ int pairs = (n > 64 ? 64 : n) / 2;
2613+ sp_re_set_captures(str, caps, pairs);
2614+ sp_MatchData *m = (sp_MatchData *)sp_gc_alloc(sizeof(sp_MatchData), NULL, sp_MatchData_scan);
2615+ m->source = str;
2616+ m->ncap = pairs;
2617+ for (int i = 0; i < pairs * 2; i++) m->caps[i] = caps[i];
2618+ return m;
2619+}
25852620 /* group i substring, or NULL for a non-participating / out-of-range group */
25862621 static const char *sp_MatchData_aref(sp_MatchData *m, mrb_int i) {
25872622 if (!m || i < 0 || i >= m->ncap) return NULL;