Skip to content

Commit 5b7139a

Browse files
committed
Issue #7462: Implement the stringlib fast search algorithm for the rfind,
`rindex`, `rsplit` and `rpartition` methods. Patch by Florent Xicluna.
1 parent d3e3232 commit 5b7139a

File tree

11 files changed

+150
-151
lines changed

11 files changed

+150
-151
lines changed

Lib/test/string_tests.py

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,31 @@ def test_rfind(self):
230230
self.checkraises(TypeError, 'hello', 'rfind')
231231
self.checkraises(TypeError, 'hello', 'rfind', 42)
232232

233+
# For a variety of combinations,
234+
# verify that str.rfind() matches __contains__
235+
# and that the found substring is really at that location
236+
charset = ['', 'a', 'b', 'c']
237+
digits = 5
238+
base = len(charset)
239+
teststrings = set()
240+
for i in xrange(base ** digits):
241+
entry = []
242+
for j in xrange(digits):
243+
i, m = divmod(i, base)
244+
entry.append(charset[m])
245+
teststrings.add(''.join(entry))
246+
teststrings = list(teststrings)
247+
for i in teststrings:
248+
i = self.fixtype(i)
249+
for j in teststrings:
250+
loc = i.rfind(j)
251+
r1 = (loc != -1)
252+
r2 = j in i
253+
if r1 != r2:
254+
self.assertEqual(r1, r2)
255+
if loc != -1:
256+
self.assertEqual(i[loc:loc+len(j)], j)
257+
233258
def test_index(self):
234259
self.checkequal(0, 'abcdefghiabc', 'index', '')
235260
self.checkequal(3, 'abcdefghiabc', 'index', 'def')
@@ -686,8 +711,10 @@ def test_replace(self):
686711
EQ("bobobXbobob", "bobobobXbobobob", "replace", "bobob", "bob")
687712
EQ("BOBOBOB", "BOBOBOB", "replace", "bob", "bobby")
688713

689-
ba = buffer('a')
690-
bb = buffer('b')
714+
# Silence Py3k warning
715+
with test_support.check_warnings():
716+
ba = buffer('a')
717+
bb = buffer('b')
691718
EQ("bbc", "abc", "replace", ba, bb)
692719
EQ("aac", "abc", "replace", bb, ba)
693720

Lib/test/test_unicode.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -499,9 +499,12 @@ def __str__(self):
499499
)
500500

501501
if not sys.platform.startswith('java'):
502+
# Silence Py3k warning
503+
with test_support.check_warnings():
504+
buf = buffer('character buffers are decoded to unicode')
502505
self.assertEqual(
503506
unicode(
504-
buffer('character buffers are decoded to unicode'),
507+
buf,
505508
'utf-8',
506509
'strict'
507510
),

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ What's New in Python 2.7 alpha 2?
1212
Core and Builtins
1313
-----------------
1414

15+
- Issue #7462: Implement the stringlib fast search algorithm for the `rfind`,
16+
`rindex`, `rsplit` and `rpartition` methods. Patch by Florent Xicluna.
17+
1518
- Issue #5080: A number of functions and methods previously produced a
1619
DeprecationWarning when passed a float argument where an integer was
1720
expected. These functions and methods now raise TypeError instead.

Objects/bytearrayobject.c

Lines changed: 9 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1111,7 +1111,6 @@ bytearray_dealloc(PyByteArrayObject *self)
11111111
/* Methods */
11121112

11131113
#define STRINGLIB_CHAR char
1114-
#define STRINGLIB_CMP memcmp
11151114
#define STRINGLIB_LEN PyByteArray_GET_SIZE
11161115
#define STRINGLIB_STR PyByteArray_AS_STRING
11171116
#define STRINGLIB_NEW PyByteArray_FromStringAndSize
@@ -2282,14 +2281,11 @@ If maxsplit is given, at most maxsplit splits are done.");
22822281
static PyObject *
22832282
bytearray_split(PyByteArrayObject *self, PyObject *args)
22842283
{
2285-
Py_ssize_t len = PyByteArray_GET_SIZE(self), n, i, j;
2284+
Py_ssize_t len = PyByteArray_GET_SIZE(self), n, i, j, pos;
22862285
Py_ssize_t maxsplit = -1, count = 0;
22872286
const char *s = PyByteArray_AS_STRING(self), *sub;
22882287
PyObject *list, *str, *subobj = Py_None;
22892288
Py_buffer vsub;
2290-
#ifdef USE_FAST
2291-
Py_ssize_t pos;
2292-
#endif
22932289

22942290
if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit))
22952291
return NULL;
@@ -2321,7 +2317,6 @@ bytearray_split(PyByteArrayObject *self, PyObject *args)
23212317
return NULL;
23222318
}
23232319

2324-
#ifdef USE_FAST
23252320
i = j = 0;
23262321
while (maxsplit-- > 0) {
23272322
pos = fastsearch(s+i, len-i, sub, n, FAST_SEARCH);
@@ -2331,18 +2326,6 @@ bytearray_split(PyByteArrayObject *self, PyObject *args)
23312326
SPLIT_ADD(s, i, j);
23322327
i = j + n;
23332328
}
2334-
#else
2335-
i = j = 0;
2336-
while ((j+n <= len) && (maxsplit-- > 0)) {
2337-
for (; j+n <= len; j++) {
2338-
if (Py_STRING_MATCH(s, j, sub, n)) {
2339-
SPLIT_ADD(s, i, j);
2340-
i = j = j + n;
2341-
break;
2342-
}
2343-
}
2344-
}
2345-
#endif
23462329
SPLIT_ADD(s, i, len);
23472330
FIX_PREALLOC_SIZE(list);
23482331
PyBuffer_Release(&vsub);
@@ -2520,7 +2503,7 @@ If maxsplit is given, at most maxsplit splits are done.");
25202503
static PyObject *
25212504
bytearray_rsplit(PyByteArrayObject *self, PyObject *args)
25222505
{
2523-
Py_ssize_t len = PyByteArray_GET_SIZE(self), n, i, j;
2506+
Py_ssize_t len = PyByteArray_GET_SIZE(self), n, j, pos;
25242507
Py_ssize_t maxsplit = -1, count = 0;
25252508
const char *s = PyByteArray_AS_STRING(self), *sub;
25262509
PyObject *list, *str, *subobj = Py_None;
@@ -2557,17 +2540,13 @@ bytearray_rsplit(PyByteArrayObject *self, PyObject *args)
25572540
}
25582541

25592542
j = len;
2560-
i = j - n;
2561-
2562-
while ( (i >= 0) && (maxsplit-- > 0) ) {
2563-
for (; i>=0; i--) {
2564-
if (Py_STRING_MATCH(s, i, sub, n)) {
2565-
SPLIT_ADD(s, i + n, j);
2566-
j = i;
2567-
i -= n;
2568-
break;
2569-
}
2570-
}
2543+
2544+
while (maxsplit-- > 0) {
2545+
pos = fastsearch(s, j, sub, n, FAST_RSEARCH);
2546+
if (pos < 0)
2547+
break;
2548+
SPLIT_ADD(s, pos + n, j);
2549+
j = pos;
25712550
}
25722551
SPLIT_ADD(s, 0, j);
25732552
FIX_PREALLOC_SIZE(list);

Objects/stringlib/README.txt

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,6 @@ STRINGLIB_EMPTY
1515

1616
a PyObject representing the empty string
1717

18-
int STRINGLIB_CMP(STRINGLIB_CHAR*, STRINGLIB_CHAR*, Py_ssize_t)
19-
20-
compares two strings. returns 0 if they match, and non-zero if not.
21-
2218
Py_ssize_t STRINGLIB_LEN(PyObject*)
2319

2420
returns the length of the given string object (which must be of the

Objects/stringlib/fastsearch.h

Lines changed: 77 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
/* fast search/count implementation, based on a mix between boyer-
77
moore and horspool, with a few more bells and whistles on the top.
8-
for some more background, see: http://effbot.org/stringlib.htm */
8+
for some more background, see: http://effbot.org/zone/stringlib.htm */
99

1010
/* note: fastsearch may access s[n], which isn't a problem when using
1111
Python's ordinary string types, but may cause problems if you're
@@ -16,6 +16,7 @@
1616

1717
#define FAST_COUNT 0
1818
#define FAST_SEARCH 1
19+
#define FAST_RSEARCH 2
1920

2021
Py_LOCAL_INLINE(Py_ssize_t)
2122
fastsearch(const STRINGLIB_CHAR* s, Py_ssize_t n,
@@ -41,51 +42,92 @@ fastsearch(const STRINGLIB_CHAR* s, Py_ssize_t n,
4142
if (s[i] == p[0])
4243
count++;
4344
return count;
44-
} else {
45+
} else if (mode == FAST_SEARCH) {
4546
for (i = 0; i < n; i++)
4647
if (s[i] == p[0])
4748
return i;
49+
} else { /* FAST_RSEARCH */
50+
for (i = n - 1; i > -1; i--)
51+
if (s[i] == p[0])
52+
return i;
4853
}
4954
return -1;
5055
}
5156

5257
mlast = m - 1;
53-
54-
/* create compressed boyer-moore delta 1 table */
5558
skip = mlast - 1;
56-
/* process pattern[:-1] */
57-
for (mask = i = 0; i < mlast; i++) {
58-
mask |= (1 << (p[i] & 0x1F));
59-
if (p[i] == p[mlast])
60-
skip = mlast - i - 1;
61-
}
62-
/* process pattern[-1] outside the loop */
63-
mask |= (1 << (p[mlast] & 0x1F));
64-
65-
for (i = 0; i <= w; i++) {
66-
/* note: using mlast in the skip path slows things down on x86 */
67-
if (s[i+m-1] == p[m-1]) {
68-
/* candidate match */
69-
for (j = 0; j < mlast; j++)
70-
if (s[i+j] != p[j])
71-
break;
72-
if (j == mlast) {
73-
/* got a match! */
74-
if (mode != FAST_COUNT)
59+
60+
if (mode != FAST_RSEARCH) {
61+
62+
/* create compressed boyer-moore delta 1 table */
63+
64+
/* process pattern[:-1] */
65+
for (mask = i = 0; i < mlast; i++) {
66+
mask |= (1 << (p[i] & 0x1F));
67+
if (p[i] == p[mlast])
68+
skip = mlast - i - 1;
69+
}
70+
/* process pattern[-1] outside the loop */
71+
mask |= (1 << (p[mlast] & 0x1F));
72+
73+
for (i = 0; i <= w; i++) {
74+
/* note: using mlast in the skip path slows things down on x86 */
75+
if (s[i+m-1] == p[m-1]) {
76+
/* candidate match */
77+
for (j = 0; j < mlast; j++)
78+
if (s[i+j] != p[j])
79+
break;
80+
if (j == mlast) {
81+
/* got a match! */
82+
if (mode != FAST_COUNT)
83+
return i;
84+
count++;
85+
i = i + mlast;
86+
continue;
87+
}
88+
/* miss: check if next character is part of pattern */
89+
if (!(mask & (1 << (s[i+m] & 0x1F))))
90+
i = i + m;
91+
else
92+
i = i + skip;
93+
} else {
94+
/* skip: check if next character is part of pattern */
95+
if (!(mask & (1 << (s[i+m] & 0x1F))))
96+
i = i + m;
97+
}
98+
}
99+
} else { /* FAST_RSEARCH */
100+
101+
/* create compressed boyer-moore delta 1 table */
102+
103+
/* process pattern[0] outside the loop */
104+
mask = (1 << (p[0] & 0x1F));
105+
/* process pattern[:0:-1] */
106+
for (i = mlast; i > 0; i--) {
107+
mask |= (1 << (p[i] & 0x1F));
108+
if (p[i] == p[0])
109+
skip = i - 1;
110+
}
111+
112+
for (i = w; i >= 0; i--) {
113+
if (s[i] == p[0]) {
114+
/* candidate match */
115+
for (j = mlast; j > 0; j--)
116+
if (s[i+j] != p[j])
117+
break;
118+
if (j == 0)
119+
/* got a match! */
75120
return i;
76-
count++;
77-
i = i + mlast;
78-
continue;
121+
/* miss: check if previous character is part of pattern */
122+
if (!(mask & (1 << (s[i-1] & 0x1F))))
123+
i = i - m;
124+
else
125+
i = i - skip;
126+
} else {
127+
/* skip: check if previous character is part of pattern */
128+
if (!(mask & (1 << (s[i-1] & 0x1F))))
129+
i = i - m;
79130
}
80-
/* miss: check if next character is part of pattern */
81-
if (!(mask & (1 << (s[i+m] & 0x1F))))
82-
i = i + m;
83-
else
84-
i = i + skip;
85-
} else {
86-
/* skip: check if next character is part of pattern */
87-
if (!(mask & (1 << (s[i+m] & 0x1F))))
88-
i = i + m;
89131
}
90132
}
91133

Objects/stringlib/find.h

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -32,20 +32,19 @@ stringlib_rfind(const STRINGLIB_CHAR* str, Py_ssize_t str_len,
3232
const STRINGLIB_CHAR* sub, Py_ssize_t sub_len,
3333
Py_ssize_t offset)
3434
{
35-
/* XXX - create reversefastsearch helper! */
36-
if (sub_len == 0) {
37-
if (str_len < 0)
38-
return -1;
39-
return str_len + offset;
40-
} else {
41-
Py_ssize_t j, pos = -1;
42-
for (j = str_len - sub_len; j >= 0; --j)
43-
if (STRINGLIB_CMP(str+j, sub, sub_len) == 0) {
44-
pos = j + offset;
45-
break;
46-
}
47-
return pos;
48-
}
35+
Py_ssize_t pos;
36+
37+
if (str_len < 0)
38+
return -1;
39+
if (sub_len == 0)
40+
return str_len + offset;
41+
42+
pos = fastsearch(str, str_len, sub, sub_len, FAST_RSEARCH);
43+
44+
if (pos >= 0)
45+
pos += offset;
46+
47+
return pos;
4948
}
5049

5150
Py_LOCAL_INLINE(Py_ssize_t)
@@ -64,10 +63,7 @@ stringlib_find_slice(const STRINGLIB_CHAR* str, Py_ssize_t str_len,
6463
if (end < 0)
6564
end = 0;
6665

67-
return stringlib_find(
68-
str + start, end - start,
69-
sub, sub_len, start
70-
);
66+
return stringlib_find(str + start, end - start, sub, sub_len, start);
7167
}
7268

7369
Py_LOCAL_INLINE(Py_ssize_t)

Objects/stringlib/partition.h

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ stringlib_rpartition(
5858
)
5959
{
6060
PyObject* out;
61-
Py_ssize_t pos, j;
61+
Py_ssize_t pos;
6262

6363
if (sep_len == 0) {
6464
PyErr_SetString(PyExc_ValueError, "empty separator");
@@ -69,20 +69,14 @@ stringlib_rpartition(
6969
if (!out)
7070
return NULL;
7171

72-
/* XXX - create reversefastsearch helper! */
73-
pos = -1;
74-
for (j = str_len - sep_len; j >= 0; --j)
75-
if (STRINGLIB_CMP(str+j, sep, sep_len) == 0) {
76-
pos = j;
77-
break;
78-
}
72+
pos = fastsearch(str, str_len, sep, sep_len, FAST_RSEARCH);
7973

8074
if (pos < 0) {
8175
Py_INCREF(STRINGLIB_EMPTY);
8276
PyTuple_SET_ITEM(out, 0, (PyObject*) STRINGLIB_EMPTY);
8377
Py_INCREF(STRINGLIB_EMPTY);
8478
PyTuple_SET_ITEM(out, 1, (PyObject*) STRINGLIB_EMPTY);
85-
Py_INCREF(str_obj);
79+
Py_INCREF(str_obj);
8680
PyTuple_SET_ITEM(out, 2, (PyObject*) str_obj);
8781
return out;
8882
}

Objects/stringlib/stringdefs.h

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
#define STRINGLIB_NEW PyString_FromStringAndSize
2222
#define STRINGLIB_RESIZE _PyString_Resize
2323
#define STRINGLIB_CHECK PyString_Check
24-
#define STRINGLIB_CMP memcmp
2524
#define STRINGLIB_TOSTR PyObject_Str
2625
#define STRINGLIB_GROUPING _PyString_InsertThousandsGrouping
2726
#define STRINGLIB_GROUPING_LOCALE _PyString_InsertThousandsGroupingLocale

0 commit comments

Comments
 (0)