PageRenderTime 24ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/src/backend/utils/adt/levenshtein.c

https://gitlab.com/kajan-rezg/postgres
C | 401 lines | 188 code | 37 blank | 176 comment | 41 complexity | 25d11d86e8ec21e161ad332fa78457a8 MD5 | raw file
  1. /*-------------------------------------------------------------------------
  2. *
  3. * levenshtein.c
  4. * Levenshtein distance implementation.
  5. *
  6. * Original author: Joe Conway <mail@joeconway.com>
  7. *
  8. * This file is included by varlena.c twice, to provide matching code for (1)
  9. * Levenshtein distance with custom costings, and (2) Levenshtein distance with
  10. * custom costings and a "max" value above which exact distances are not
  11. * interesting. Before the inclusion, we rely on the presence of the inline
  12. * function rest_of_char_same().
  13. *
  14. * Written based on a description of the algorithm by Michael Gilleland found
  15. * at http://www.merriampark.com/ld.htm. Also looked at levenshtein.c in the
  16. * PHP 4.0.6 distribution for inspiration. Configurable penalty costs
  17. * extension is introduced by Volkan YAZICI <volkan.yazici@gmail.com.
  18. *
  19. * Copyright (c) 2001-2016, PostgreSQL Global Development Group
  20. *
  21. * IDENTIFICATION
  22. * src/backend/utils/adt/levenshtein.c
  23. *
  24. *-------------------------------------------------------------------------
  25. */
  26. #define MAX_LEVENSHTEIN_STRLEN 255
  27. /*
  28. * Calculates Levenshtein distance metric between supplied strings, which are
  29. * not necessarily null-terminated.
  30. *
  31. * source: source string, of length slen bytes.
  32. * target: target string, of length tlen bytes.
  33. * ins_c, del_c, sub_c: costs to charge for character insertion, deletion,
  34. * and substitution respectively; (1, 1, 1) costs suffice for common
  35. * cases, but your mileage may vary.
  36. * max_d: if provided and >= 0, maximum distance we care about; see below.
  37. * trusted: caller is trusted and need not obey MAX_LEVENSHTEIN_STRLEN.
  38. *
  39. * One way to compute Levenshtein distance is to incrementally construct
  40. * an (m+1)x(n+1) matrix where cell (i, j) represents the minimum number
  41. * of operations required to transform the first i characters of s into
  42. * the first j characters of t. The last column of the final row is the
  43. * answer.
  44. *
  45. * We use that algorithm here with some modification. In lieu of holding
  46. * the entire array in memory at once, we'll just use two arrays of size
  47. * m+1 for storing accumulated values. At each step one array represents
  48. * the "previous" row and one is the "current" row of the notional large
  49. * array.
  50. *
  51. * If max_d >= 0, we only need to provide an accurate answer when that answer
  52. * is less than or equal to max_d. From any cell in the matrix, there is
  53. * theoretical "minimum residual distance" from that cell to the last column
  54. * of the final row. This minimum residual distance is zero when the
  55. * untransformed portions of the strings are of equal length (because we might
  56. * get lucky and find all the remaining characters matching) and is otherwise
  57. * based on the minimum number of insertions or deletions needed to make them
  58. * equal length. The residual distance grows as we move toward the upper
  59. * right or lower left corners of the matrix. When the max_d bound is
  60. * usefully tight, we can use this property to avoid computing the entirety
  61. * of each row; instead, we maintain a start_column and stop_column that
  62. * identify the portion of the matrix close to the diagonal which can still
  63. * affect the final answer.
  64. */
  65. int
  66. #ifdef LEVENSHTEIN_LESS_EQUAL
  67. varstr_levenshtein_less_equal(const char *source, int slen,
  68. const char *target, int tlen,
  69. int ins_c, int del_c, int sub_c,
  70. int max_d, bool trusted)
  71. #else
  72. varstr_levenshtein(const char *source, int slen,
  73. const char *target, int tlen,
  74. int ins_c, int del_c, int sub_c,
  75. bool trusted)
  76. #endif
  77. {
  78. int m,
  79. n;
  80. int *prev;
  81. int *curr;
  82. int *s_char_len = NULL;
  83. int i,
  84. j;
  85. const char *y;
  86. /*
  87. * For varstr_levenshtein_less_equal, we have real variables called
  88. * start_column and stop_column; otherwise it's just short-hand for 0 and
  89. * m.
  90. */
  91. #ifdef LEVENSHTEIN_LESS_EQUAL
  92. int start_column,
  93. stop_column;
  94. #undef START_COLUMN
  95. #undef STOP_COLUMN
  96. #define START_COLUMN start_column
  97. #define STOP_COLUMN stop_column
  98. #else
  99. #undef START_COLUMN
  100. #undef STOP_COLUMN
  101. #define START_COLUMN 0
  102. #define STOP_COLUMN m
  103. #endif
  104. /* Convert string lengths (in bytes) to lengths in characters */
  105. m = pg_mbstrlen_with_len(source, slen);
  106. n = pg_mbstrlen_with_len(target, tlen);
  107. /*
  108. * We can transform an empty s into t with n insertions, or a non-empty t
  109. * into an empty s with m deletions.
  110. */
  111. if (!m)
  112. return n * ins_c;
  113. if (!n)
  114. return m * del_c;
  115. /*
  116. * For security concerns, restrict excessive CPU+RAM usage. (This
  117. * implementation uses O(m) memory and has O(mn) complexity.) If
  118. * "trusted" is true, caller is responsible for not making excessive
  119. * requests, typically by using a small max_d along with strings that are
  120. * bounded, though not necessarily to MAX_LEVENSHTEIN_STRLEN exactly.
  121. */
  122. if (!trusted &&
  123. (m > MAX_LEVENSHTEIN_STRLEN ||
  124. n > MAX_LEVENSHTEIN_STRLEN))
  125. ereport(ERROR,
  126. (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
  127. errmsg("levenshtein argument exceeds maximum length of %d characters",
  128. MAX_LEVENSHTEIN_STRLEN)));
  129. #ifdef LEVENSHTEIN_LESS_EQUAL
  130. /* Initialize start and stop columns. */
  131. start_column = 0;
  132. stop_column = m + 1;
  133. /*
  134. * If max_d >= 0, determine whether the bound is impossibly tight. If so,
  135. * return max_d + 1 immediately. Otherwise, determine whether it's tight
  136. * enough to limit the computation we must perform. If so, figure out
  137. * initial stop column.
  138. */
  139. if (max_d >= 0)
  140. {
  141. int min_theo_d; /* Theoretical minimum distance. */
  142. int max_theo_d; /* Theoretical maximum distance. */
  143. int net_inserts = n - m;
  144. min_theo_d = net_inserts < 0 ?
  145. -net_inserts * del_c : net_inserts * ins_c;
  146. if (min_theo_d > max_d)
  147. return max_d + 1;
  148. if (ins_c + del_c < sub_c)
  149. sub_c = ins_c + del_c;
  150. max_theo_d = min_theo_d + sub_c * Min(m, n);
  151. if (max_d >= max_theo_d)
  152. max_d = -1;
  153. else if (ins_c + del_c > 0)
  154. {
  155. /*
  156. * Figure out how much of the first row of the notional matrix we
  157. * need to fill in. If the string is growing, the theoretical
  158. * minimum distance already incorporates the cost of deleting the
  159. * number of characters necessary to make the two strings equal in
  160. * length. Each additional deletion forces another insertion, so
  161. * the best-case total cost increases by ins_c + del_c. If the
  162. * string is shrinking, the minimum theoretical cost assumes no
  163. * excess deletions; that is, we're starting no further right than
  164. * column n - m. If we do start further right, the best-case
  165. * total cost increases by ins_c + del_c for each move right.
  166. */
  167. int slack_d = max_d - min_theo_d;
  168. int best_column = net_inserts < 0 ? -net_inserts : 0;
  169. stop_column = best_column + (slack_d / (ins_c + del_c)) + 1;
  170. if (stop_column > m)
  171. stop_column = m + 1;
  172. }
  173. }
  174. #endif
  175. /*
  176. * In order to avoid calling pg_mblen() repeatedly on each character in s,
  177. * we cache all the lengths before starting the main loop -- but if all
  178. * the characters in both strings are single byte, then we skip this and
  179. * use a fast-path in the main loop. If only one string contains
  180. * multi-byte characters, we still build the array, so that the fast-path
  181. * needn't deal with the case where the array hasn't been initialized.
  182. */
  183. if (m != slen || n != tlen)
  184. {
  185. int i;
  186. const char *cp = source;
  187. s_char_len = (int *) palloc((m + 1) * sizeof(int));
  188. for (i = 0; i < m; ++i)
  189. {
  190. s_char_len[i] = pg_mblen(cp);
  191. cp += s_char_len[i];
  192. }
  193. s_char_len[i] = 0;
  194. }
  195. /* One more cell for initialization column and row. */
  196. ++m;
  197. ++n;
  198. /* Previous and current rows of notional array. */
  199. prev = (int *) palloc(2 * m * sizeof(int));
  200. curr = prev + m;
  201. /*
  202. * To transform the first i characters of s into the first 0 characters of
  203. * t, we must perform i deletions.
  204. */
  205. for (i = START_COLUMN; i < STOP_COLUMN; i++)
  206. prev[i] = i * del_c;
  207. /* Loop through rows of the notional array */
  208. for (y = target, j = 1; j < n; j++)
  209. {
  210. int *temp;
  211. const char *x = source;
  212. int y_char_len = n != tlen + 1 ? pg_mblen(y) : 1;
  213. #ifdef LEVENSHTEIN_LESS_EQUAL
  214. /*
  215. * In the best case, values percolate down the diagonal unchanged, so
  216. * we must increment stop_column unless it's already on the right end
  217. * of the array. The inner loop will read prev[stop_column], so we
  218. * have to initialize it even though it shouldn't affect the result.
  219. */
  220. if (stop_column < m)
  221. {
  222. prev[stop_column] = max_d + 1;
  223. ++stop_column;
  224. }
  225. /*
  226. * The main loop fills in curr, but curr[0] needs a special case: to
  227. * transform the first 0 characters of s into the first j characters
  228. * of t, we must perform j insertions. However, if start_column > 0,
  229. * this special case does not apply.
  230. */
  231. if (start_column == 0)
  232. {
  233. curr[0] = j * ins_c;
  234. i = 1;
  235. }
  236. else
  237. i = start_column;
  238. #else
  239. curr[0] = j * ins_c;
  240. i = 1;
  241. #endif
  242. /*
  243. * This inner loop is critical to performance, so we include a
  244. * fast-path to handle the (fairly common) case where no multibyte
  245. * characters are in the mix. The fast-path is entitled to assume
  246. * that if s_char_len is not initialized then BOTH strings contain
  247. * only single-byte characters.
  248. */
  249. if (s_char_len != NULL)
  250. {
  251. for (; i < STOP_COLUMN; i++)
  252. {
  253. int ins;
  254. int del;
  255. int sub;
  256. int x_char_len = s_char_len[i - 1];
  257. /*
  258. * Calculate costs for insertion, deletion, and substitution.
  259. *
  260. * When calculating cost for substitution, we compare the last
  261. * character of each possibly-multibyte character first,
  262. * because that's enough to rule out most mis-matches. If we
  263. * get past that test, then we compare the lengths and the
  264. * remaining bytes.
  265. */
  266. ins = prev[i] + ins_c;
  267. del = curr[i - 1] + del_c;
  268. if (x[x_char_len - 1] == y[y_char_len - 1]
  269. && x_char_len == y_char_len &&
  270. (x_char_len == 1 || rest_of_char_same(x, y, x_char_len)))
  271. sub = prev[i - 1];
  272. else
  273. sub = prev[i - 1] + sub_c;
  274. /* Take the one with minimum cost. */
  275. curr[i] = Min(ins, del);
  276. curr[i] = Min(curr[i], sub);
  277. /* Point to next character. */
  278. x += x_char_len;
  279. }
  280. }
  281. else
  282. {
  283. for (; i < STOP_COLUMN; i++)
  284. {
  285. int ins;
  286. int del;
  287. int sub;
  288. /* Calculate costs for insertion, deletion, and substitution. */
  289. ins = prev[i] + ins_c;
  290. del = curr[i - 1] + del_c;
  291. sub = prev[i - 1] + ((*x == *y) ? 0 : sub_c);
  292. /* Take the one with minimum cost. */
  293. curr[i] = Min(ins, del);
  294. curr[i] = Min(curr[i], sub);
  295. /* Point to next character. */
  296. x++;
  297. }
  298. }
  299. /* Swap current row with previous row. */
  300. temp = curr;
  301. curr = prev;
  302. prev = temp;
  303. /* Point to next character. */
  304. y += y_char_len;
  305. #ifdef LEVENSHTEIN_LESS_EQUAL
  306. /*
  307. * This chunk of code represents a significant performance hit if used
  308. * in the case where there is no max_d bound. This is probably not
  309. * because the max_d >= 0 test itself is expensive, but rather because
  310. * the possibility of needing to execute this code prevents tight
  311. * optimization of the loop as a whole.
  312. */
  313. if (max_d >= 0)
  314. {
  315. /*
  316. * The "zero point" is the column of the current row where the
  317. * remaining portions of the strings are of equal length. There
  318. * are (n - 1) characters in the target string, of which j have
  319. * been transformed. There are (m - 1) characters in the source
  320. * string, so we want to find the value for zp where (n - 1) - j =
  321. * (m - 1) - zp.
  322. */
  323. int zp = j - (n - m);
  324. /* Check whether the stop column can slide left. */
  325. while (stop_column > 0)
  326. {
  327. int ii = stop_column - 1;
  328. int net_inserts = ii - zp;
  329. if (prev[ii] + (net_inserts > 0 ? net_inserts * ins_c :
  330. -net_inserts * del_c) <= max_d)
  331. break;
  332. stop_column--;
  333. }
  334. /* Check whether the start column can slide right. */
  335. while (start_column < stop_column)
  336. {
  337. int net_inserts = start_column - zp;
  338. if (prev[start_column] +
  339. (net_inserts > 0 ? net_inserts * ins_c :
  340. -net_inserts * del_c) <= max_d)
  341. break;
  342. /*
  343. * We'll never again update these values, so we must make sure
  344. * there's nothing here that could confuse any future
  345. * iteration of the outer loop.
  346. */
  347. prev[start_column] = max_d + 1;
  348. curr[start_column] = max_d + 1;
  349. if (start_column != 0)
  350. source += (s_char_len != NULL) ? s_char_len[start_column - 1] : 1;
  351. start_column++;
  352. }
  353. /* If they cross, we're going to exceed the bound. */
  354. if (start_column >= stop_column)
  355. return max_d + 1;
  356. }
  357. #endif
  358. }
  359. /*
  360. * Because the final value was swapped from the previous row to the
  361. * current row, that's where we'll find it.
  362. */
  363. return prev[m - 1];
  364. }