Skip to content

Commit fe17d35

Browse files
GH-81057: remove static state from suggestions.c (#99411)
1 parent 59665d0 commit fe17d35

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

Python/suggestions.c

+19-8
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,8 @@ substitution_cost(char a, char b)
4141
static Py_ssize_t
4242
levenshtein_distance(const char *a, size_t a_size,
4343
const char *b, size_t b_size,
44-
size_t max_cost)
44+
size_t max_cost, size_t *buffer)
4545
{
46-
static size_t buffer[MAX_STRING_SIZE];
47-
4846
// Both strings are the same (by identity)
4947
if (a == b) {
5048
return 0;
@@ -147,12 +145,16 @@ calculate_suggestions(PyObject *dir,
147145
if (name_str == NULL) {
148146
return NULL;
149147
}
150-
148+
size_t *buffer = PyMem_New(size_t, MAX_STRING_SIZE);
149+
if (buffer == NULL) {
150+
return PyErr_NoMemory();
151+
}
151152
for (int i = 0; i < dir_size; ++i) {
152153
PyObject *item = PyList_GET_ITEM(dir, i);
153154
Py_ssize_t item_size;
154155
const char *item_str = PyUnicode_AsUTF8AndSize(item, &item_size);
155156
if (item_str == NULL) {
157+
PyMem_Free(buffer);
156158
return NULL;
157159
}
158160
if (PyUnicode_CompareWithASCIIString(name, item_str) == 0) {
@@ -163,8 +165,8 @@ calculate_suggestions(PyObject *dir,
163165
// Don't take matches we've already beaten.
164166
max_distance = Py_MIN(max_distance, suggestion_distance - 1);
165167
Py_ssize_t current_distance =
166-
levenshtein_distance(name_str, name_size,
167-
item_str, item_size, max_distance);
168+
levenshtein_distance(name_str, name_size, item_str,
169+
item_size, max_distance, buffer);
168170
if (current_distance > max_distance) {
169171
continue;
170172
}
@@ -173,6 +175,7 @@ calculate_suggestions(PyObject *dir,
173175
suggestion_distance = current_distance;
174176
}
175177
}
178+
PyMem_Free(buffer);
176179
return Py_XNewRef(suggestion);
177180
}
178181

@@ -238,7 +241,7 @@ get_suggestions_for_name_error(PyObject* name, PyFrameObject* frame)
238241
if (!self) {
239242
goto error;
240243
}
241-
244+
242245
if (PyObject_HasAttr(self, name)) {
243246
Py_DECREF(dir);
244247
return PyUnicode_FromFormat("self.%S", name);
@@ -401,6 +404,14 @@ _Py_UTF8_Edit_Cost(PyObject *a, PyObject *b, Py_ssize_t max_cost)
401404
if (max_cost == -1) {
402405
max_cost = MOVE_COST * Py_MAX(size_a, size_b);
403406
}
404-
return levenshtein_distance(utf8_a, size_a, utf8_b, size_b, max_cost);
407+
size_t *buffer = PyMem_New(size_t, MAX_STRING_SIZE);
408+
if (buffer == NULL) {
409+
PyErr_NoMemory();
410+
return -1;
411+
}
412+
Py_ssize_t res = levenshtein_distance(utf8_a, size_a,
413+
utf8_b, size_b, max_cost, buffer);
414+
PyMem_Free(buffer);
415+
return res;
405416
}
406417

0 commit comments

Comments
 (0)