blob: 4cea2db4b2379b9b4a0e6a40570fd7f5fa85adc2 [file] [log] [blame]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001/* stringlib: find/index implementation */
2
3#ifndef STRINGLIB_FIND_H
4#define STRINGLIB_FIND_H
5
6#ifndef STRINGLIB_FASTSEARCH_H
7#error must include "stringlib/fastsearch.h" before including this module
8#endif
9
10Py_LOCAL_INLINE(Py_ssize_t)
11stringlib_find(const STRINGLIB_CHAR* str, Py_ssize_t str_len,
12 const STRINGLIB_CHAR* sub, Py_ssize_t sub_len,
13 Py_ssize_t offset)
14{
15 Py_ssize_t pos;
16
17 if (sub_len == 0)
18 return offset;
19
20 pos = fastsearch(str, str_len, sub, sub_len, FAST_SEARCH);
21
22 if (pos >= 0)
23 pos += offset;
24
25 return pos;
26}
27
28Py_LOCAL_INLINE(Py_ssize_t)
29stringlib_rfind(const STRINGLIB_CHAR* str, Py_ssize_t str_len,
30 const STRINGLIB_CHAR* sub, Py_ssize_t sub_len,
31 Py_ssize_t offset)
32{
33 Py_ssize_t pos;
34
35 /* XXX - create reversefastsearch helper! */
36 if (sub_len == 0)
37 pos = str_len + offset;
38 else {
39 Py_ssize_t j;
40 pos = -1;
41 for (j = str_len - sub_len; j >= 0; --j)
42 if (STRINGLIB_CMP(str+j, sub, sub_len) == 0) {
43 pos = j + offset;
44 break;
45 }
46 }
47
48 return pos;
49}
50
51Py_LOCAL_INLINE(Py_ssize_t)
52stringlib_find_slice(const STRINGLIB_CHAR* str, Py_ssize_t str_len,
53 const STRINGLIB_CHAR* sub, Py_ssize_t sub_len,
54 Py_ssize_t start, Py_ssize_t end)
55{
56 if (start < 0)
57 start += str_len;
58 if (start < 0)
59 start = 0;
60 if (end > str_len)
61 end = str_len;
62 if (end < 0)
63 end += str_len;
64 if (end < 0)
65 end = 0;
66
67 return stringlib_find(
68 str + start, end - start,
69 sub, sub_len, start
70 );
71}
72
73Py_LOCAL_INLINE(Py_ssize_t)
74stringlib_rfind_slice(const STRINGLIB_CHAR* str, Py_ssize_t str_len,
75 const STRINGLIB_CHAR* sub, Py_ssize_t sub_len,
76 Py_ssize_t start, Py_ssize_t end)
77{
78 if (start < 0)
79 start += str_len;
80 if (start < 0)
81 start = 0;
82 if (end > str_len)
83 end = str_len;
84 if (end < 0)
85 end += str_len;
86 if (end < 0)
87 end = 0;
88
89 return stringlib_rfind(str + start, end - start, sub, sub_len, start);
90}
91
92#ifdef STRINGLIB_STR
93
94Py_LOCAL_INLINE(int)
95stringlib_contains_obj(PyObject* str, PyObject* sub)
96{
97 return stringlib_find(
98 STRINGLIB_STR(str), STRINGLIB_LEN(str),
99 STRINGLIB_STR(sub), STRINGLIB_LEN(sub), 0
100 ) != -1;
101}
102
103#endif /* STRINGLIB_STR */
104
105#endif /* STRINGLIB_FIND_H */
106
107/*
108Local variables:
109c-basic-offset: 4
110indent-tabs-mode: nil
111End:
112*/