22size_t levenshtein_n(
const char *a,
const size_t length,
const char *b,
const size_t bLength) {
36 size_t *cache = SAFE_CALLOC(length,
sizeof(
size_t),
size_t *);
49 while (index < length) {
50 cache[index] = index + 1;
55 while (bIndex < bLength) {
57 result = distance = bIndex++;
59 for (index = 0; index < length; index++) {
60 bDistance = code == a[index] ? distance : distance + 1;
61 distance = cache[index];
63 cache[index] = result = distance > result ? bDistance > result ? result + 1 : bDistance
64 : bDistance > distance ? distance + 1
83 if (char_count_a == SIZE_MAX || char_count_b == SIZE_MAX) {
88 if (char_count_a == 0) {
91 if (char_count_b == 0) {
95 uint32_t *codepoints_a = SAFE_MALLOC(char_count_a *
sizeof(uint32_t), uint32_t *);
96 uint32_t *codepoints_b = SAFE_MALLOC(char_count_b *
sizeof(uint32_t), uint32_t *);
98 if (!codepoints_a || !codepoints_b) {
99 SAFE_FREE(codepoints_a);
100 SAFE_FREE(codepoints_b);
107 if (decoded_a == SIZE_MAX || decoded_b == SIZE_MAX) {
108 SAFE_FREE(codepoints_a);
109 SAFE_FREE(codepoints_b);
114 size_t *cache = SAFE_CALLOC(char_count_a *
sizeof(
size_t), 1,
size_t *);
116 SAFE_FREE(codepoints_a);
117 SAFE_FREE(codepoints_b);
122 for (
size_t i = 0; i < char_count_a; i++) {
128 for (
size_t b_idx = 0; b_idx < char_count_b; b_idx++) {
129 uint32_t b_code = codepoints_b[b_idx];
130 result = distance = b_idx;
132 for (
size_t a_idx = 0; a_idx < char_count_a; a_idx++) {
133 uint32_t a_code = codepoints_a[a_idx];
134 size_t b_distance = (a_code == b_code) ? distance : distance + 1;
135 distance = cache[a_idx];
137 cache[a_idx] = result = (distance > result) ? ((b_distance > result) ? result + 1 : b_distance)
138 : ((b_distance > distance) ? distance + 1 : b_distance);
143 SAFE_FREE(codepoints_a);
144 SAFE_FREE(codepoints_b);
150 if (!unknown || !candidates) {
154 const char *best_match = NULL;
155 size_t best_distance = SIZE_MAX;
157 for (
int i = 0; candidates[i] != NULL; i++) {
159 if (dist < best_distance) {
160 best_distance = dist;
161 best_match = candidates[i];
166 if (best_distance <= LEVENSHTEIN_SUGGESTION_THRESHOLD) {