|
9 | 9 |
|
10 | 10 | /* Calculate the Levenshtein distance between string1 and string2 */
|
11 | 11 | static size_t
|
12 |
| -levenshtein_distance(const char *a, const char *b) { |
13 |
| - |
14 |
| - const size_t a_size = strlen(a); |
15 |
| - const size_t b_size = strlen(b); |
| 12 | +levenshtein_distance(const char *a, size_t a_size, |
| 13 | + const char *b, size_t b_size) { |
16 | 14 |
|
17 | 15 | if (a_size > MAX_STRING_SIZE || b_size > MAX_STRING_SIZE) {
|
18 | 16 | return 0;
|
@@ -87,17 +85,20 @@ calculate_suggestions(PyObject *dir,
|
87 | 85 |
|
88 | 86 | Py_ssize_t suggestion_distance = PyUnicode_GetLength(name);
|
89 | 87 | PyObject *suggestion = NULL;
|
90 |
| - const char *name_str = PyUnicode_AsUTF8(name); |
| 88 | + Py_ssize_t name_size; |
| 89 | + const char *name_str = PyUnicode_AsUTF8AndSize(name, &name_size); |
91 | 90 | if (name_str == NULL) {
|
92 | 91 | return NULL;
|
93 | 92 | }
|
94 | 93 | for (int i = 0; i < dir_size; ++i) {
|
95 | 94 | PyObject *item = PyList_GET_ITEM(dir, i);
|
96 |
| - const char *item_str = PyUnicode_AsUTF8(item); |
| 95 | + Py_ssize_t item_size; |
| 96 | + const char *item_str = PyUnicode_AsUTF8AndSize(item, &item_size); |
97 | 97 | if (item_str == NULL) {
|
98 | 98 | return NULL;
|
99 | 99 | }
|
100 |
| - Py_ssize_t current_distance = levenshtein_distance(name_str, item_str); |
| 100 | + Py_ssize_t current_distance = levenshtein_distance( |
| 101 | + name_str, name_size, item_str, item_size); |
101 | 102 | if (current_distance == 0 || current_distance > MAX_DISTANCE) {
|
102 | 103 | continue;
|
103 | 104 | }
|
@@ -138,7 +139,8 @@ static PyObject *
|
138 | 139 | offer_suggestions_for_name_error(PyNameErrorObject *exc) {
|
139 | 140 | PyObject *name = exc->name; // borrowed reference
|
140 | 141 | PyTracebackObject *traceback = (PyTracebackObject *) exc->traceback; // borrowed reference
|
141 |
| - // Abort if we don't have an attribute name or we have an invalid one |
| 142 | + // Abort if we don't have a variable name or we have an invalid one |
| 143 | + // or if we don't have a traceback to work with |
142 | 144 | if (name == NULL || traceback == NULL || !PyUnicode_CheckExact(name)) {
|
143 | 145 | return NULL;
|
144 | 146 | }
|
|
0 commit comments