From 8fe8e46c6dce8292f2c12660d0c383e521f9233a Mon Sep 17 00:00:00 2001 From: Kaz Kylheku Date: Sat, 19 Jul 2014 19:19:21 -0700 Subject: * lib.c (search_str): Support negative starting index. Hoist uselessly repeated c_str operation out of loop. * txr.1: Document negative starting index for search-str. --- ChangeLog | 7 +++++++ lib.c | 18 ++++++++++++++---- txr.1 | 8 ++++++-- 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/ChangeLog b/ChangeLog index d2a40266..906b02b2 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,10 @@ +2014-07-19 Kaz Kylheku + + * lib.c (search_str): Support negative starting index. + Hoist uselessly repeated c_str operation out of loop. + + * txr.1: Document negative starting index for search-str. + 2014-07-19 Kaz Kylheku * hash.c (hash_construct): Nullify the pairs argument so that diff --git a/lib.c b/lib.c index 0f705211..3f38ab97 100644 --- a/lib.c +++ b/lib.c @@ -2145,11 +2145,14 @@ val search_str(val haystack, val needle, val start_num, val from_end) const wchar_t *n = c_str(needle), *h; if (!h_is_lazy) { - do { - const wchar_t *f; - h = c_str(haystack); + h = c_str(haystack); + + if (start < 0) + start += wcslen(h); - f = wcsstr(h + start, n); + nonlazy: + do { + const wchar_t *f = wcsstr(h + start, n); if (f) pos = f - h; @@ -2159,6 +2162,13 @@ val search_str(val haystack, val needle, val start_num, val from_end) } else { size_t ln = c_num(length_str(needle)); + if (start < 0) { + lazy_str_force(haystack); + h = c_str(haystack->ls.prefix); + start += wcslen(h); + goto nonlazy; + } + do { lazy_str_force_upto(haystack, plus(num(start + 1), length_str(needle))); h = c_str(haystack->ls.prefix); diff --git a/txr.1 b/txr.1 index 666d238c..b3f4b3b8 100644 --- a/txr.1 +++ b/txr.1 @@ -9337,8 +9337,12 @@ The search-str function finds an occurrence of the string inside the string and returns its position. If no such occurrence exists, it returns nil. -If a argument is specified, it gives the starting index for the -search. If the argument is specified and is not nil, it means +If a argument is not specified, it defaults to zero. If it is +a non-negative integer, it specifies the starting character position for +the search. Negative values of indicate positions from the end of the +string, such that -1 is the last character of the string. + +If the argument is specified and is not nil, it means that the search is conducted right-to-left. If multiple matches are possible, it will find the rightmost one rather than the leftmost one. -- cgit v1.2.3