Skip to content

Commit d6cfcaf

Browse files
committed
Runtime: optimize re_search_forward and re_search_backward
1 parent 3c4e31c commit d6cfcaf

File tree

1 file changed

+44
-12
lines changed

1 file changed

+44
-12
lines changed

runtime/js/str.js

Lines changed: 44 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,7 @@ var re_match = (function () {
7070
cpool = caml_js_from_array(re[2]),
7171
normtable = caml_jsbytes_of_string(re[3]),
7272
numgroups = re[4] | 0,
73-
numregisters = re[5] | 0,
74-
startchars = re[6] | 0;
73+
numregisters = re[5] | 0;
7574

7675
var s = caml_uint8_array_of_string(s);
7776

@@ -293,29 +292,62 @@ var re_match = (function () {
293292

294293
//Provides: re_search_forward
295294
//Requires: re_match, caml_ml_string_length, caml_invalid_argument
295+
//Requires: caml_string_get
296296
function re_search_forward(re, s, pos) {
297297
if (pos < 0 || pos > caml_ml_string_length(s))
298298
caml_invalid_argument("Str.search_forward");
299-
while (pos <= caml_ml_string_length(s)) {
300-
var res = re_match(re, s, pos, 0);
301-
if (res) return res;
302-
pos++;
299+
var startchars = re[6] | 0;
300+
var len = caml_ml_string_length(s);
301+
if (startchars >= 0) {
302+
startchars = re[2][startchars + 1];
303+
do {
304+
while (
305+
pos < len &&
306+
caml_string_get(startchars, caml_string_get(s, pos)) === 0
307+
)
308+
pos++;
309+
var res = re_match(re, s, pos, 0);
310+
if (res) return res;
311+
pos++;
312+
} while (pos <= len);
313+
} else {
314+
do {
315+
var res = re_match(re, s, pos, 0);
316+
if (res) return res;
317+
pos++;
318+
} while (pos <= len);
303319
}
304-
305320
return [0]; /* [||] : int array */
306321
}
307322

308323
//Provides: re_search_backward
309324
//Requires: re_match, caml_ml_string_length, caml_invalid_argument
325+
//Requires: caml_string_get
310326
function re_search_backward(re, s, pos) {
311327
if (pos < 0 || pos > caml_ml_string_length(s))
312328
caml_invalid_argument("Str.search_backward");
313-
while (pos >= 0) {
314-
var res = re_match(re, s, pos, 0);
315-
if (res) return res;
316-
pos--;
329+
var startchars = re[6] | 0;
330+
if (startchars >= 0) {
331+
startchars = re[2][startchars + 1];
332+
var len = caml_ml_string_length(s);
333+
do {
334+
while (
335+
pos > 0 &&
336+
pos < len &&
337+
caml_string_get(startchars, caml_string_get(s, pos)) === 0
338+
)
339+
pos--;
340+
var res = re_match(re, s, pos, 0);
341+
if (res) return res;
342+
pos--;
343+
} while (pos >= 0);
344+
} else {
345+
do {
346+
var res = re_match(re, s, pos, 0);
347+
if (res) return res;
348+
pos--;
349+
} while (pos >= 0);
317350
}
318-
319351
return [0]; /* [||] : int array */
320352
}
321353

0 commit comments

Comments
 (0)