fstrcmp.c 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. /* Functions to make fuzzy comparisons between strings
  2. Copyright (C) 1988-1989, 1992-1993, 1995, 2001-2003, 2006, 2008-2020 Free
  3. Software Foundation, Inc.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <https://www.gnu.org/licenses/>. */
  14. #include <config.h>
  15. /* Specification. */
  16. #include "fstrcmp.h"
  17. #include <string.h>
  18. #include <stdbool.h>
  19. #include <stddef.h>
  20. #include <stdio.h>
  21. #include <stdint.h>
  22. #include <stdlib.h>
  23. #include <limits.h>
  24. #include "glthread/lock.h"
  25. #include "glthread/tls.h"
  26. #include "minmax.h"
  27. #include "xalloc.h"
  28. #define ELEMENT char
  29. #define EQUAL(x,y) ((x) == (y))
  30. #define OFFSET ptrdiff_t
  31. #define EXTRA_CONTEXT_FIELDS \
  32. /* The number of edits beyond which the computation can be aborted. */ \
  33. ptrdiff_t edit_count_limit; \
  34. /* The number of edits (= number of elements inserted, plus the number of \
  35. elements deleted), temporarily minus edit_count_limit. */ \
  36. ptrdiff_t edit_count;
  37. #define NOTE_DELETE(ctxt, xoff) ctxt->edit_count++
  38. #define NOTE_INSERT(ctxt, yoff) ctxt->edit_count++
  39. #define NOTE_ORDERED false
  40. #define EARLY_ABORT(ctxt) ctxt->edit_count > 0
  41. /* We don't need USE_HEURISTIC, since it is unlikely in typical uses of
  42. fstrcmp(). */
  43. #include "diffseq.h"
  44. /* Because fstrcmp is typically called multiple times, attempt to minimize
  45. the number of memory allocations performed. Thus, let a call reuse the
  46. memory already allocated by the previous call, if it is sufficient.
  47. To make it multithread-safe, without need for a lock that protects the
  48. already allocated memory, store the allocated memory per thread. Free
  49. it only when the thread exits. */
  50. static gl_tls_key_t buffer_key; /* TLS key for a 'ptrdiff_t *' */
  51. static gl_tls_key_t bufmax_key; /* TLS key for a 'uintptr_t' */
  52. static void
  53. keys_init (void)
  54. {
  55. gl_tls_key_init (buffer_key, free);
  56. gl_tls_key_init (bufmax_key, NULL);
  57. /* The per-thread initial values are NULL and 0, respectively. */
  58. }
  59. /* Ensure that keys_init is called once only. */
  60. gl_once_define(static, keys_init_once)
  61. void
  62. fstrcmp_free_resources (void)
  63. {
  64. ptrdiff_t *buffer;
  65. gl_once (keys_init_once, keys_init);
  66. buffer = gl_tls_get (buffer_key);
  67. if (buffer != NULL)
  68. {
  69. gl_tls_set (buffer_key, NULL);
  70. gl_tls_set (bufmax_key, (void *) (uintptr_t) 0);
  71. free (buffer);
  72. }
  73. }
  74. /* In the code below, branch probabilities were measured by Ralf Wildenhues,
  75. by running "msgmerge LL.po coreutils.pot" with msgmerge 0.18 for many
  76. values of LL. The probability indicates that the condition evaluates
  77. to true; whether that leads to a branch or a non-branch in the code,
  78. depends on the compiler's reordering of basic blocks. */
  79. double
  80. fstrcmp_bounded (const char *string1, const char *string2, double lower_bound)
  81. {
  82. struct context ctxt;
  83. size_t xvec_length = strlen (string1);
  84. size_t yvec_length = strlen (string2);
  85. size_t length_sum = xvec_length + yvec_length;
  86. ptrdiff_t i;
  87. ptrdiff_t fdiag_len;
  88. ptrdiff_t *buffer;
  89. uintptr_t bufmax;
  90. /* short-circuit obvious comparisons */
  91. if (xvec_length == 0 || yvec_length == 0) /* Prob: 1% */
  92. return length_sum == 0;
  93. if (! (xvec_length <= length_sum
  94. && length_sum <= MIN (UINTPTR_MAX, PTRDIFF_MAX) - 3))
  95. xalloc_die ();
  96. if (lower_bound > 0)
  97. {
  98. /* Compute a quick upper bound.
  99. Each edit is an insertion or deletion of an element, hence modifies
  100. the length of the sequence by at most 1.
  101. Therefore, when starting from a sequence X and ending at a sequence Y,
  102. with N edits, | yvec_length - xvec_length | <= N. (Proof by
  103. induction over N.)
  104. So, at the end, we will have
  105. edit_count >= | xvec_length - yvec_length |.
  106. and hence
  107. result
  108. = (xvec_length + yvec_length - edit_count)
  109. / (xvec_length + yvec_length)
  110. <= (xvec_length + yvec_length - | yvec_length - xvec_length |)
  111. / (xvec_length + yvec_length)
  112. = 2 * min (xvec_length, yvec_length) / (xvec_length + yvec_length).
  113. */
  114. ptrdiff_t length_min = MIN (xvec_length, yvec_length);
  115. volatile double upper_bound = 2.0 * length_min / length_sum;
  116. if (upper_bound < lower_bound) /* Prob: 74% */
  117. /* Return an arbitrary value < LOWER_BOUND. */
  118. return 0.0;
  119. #if CHAR_BIT <= 8
  120. /* When X and Y are both small, avoid the overhead of setting up an
  121. array of size 256. */
  122. if (length_sum >= 20) /* Prob: 99% */
  123. {
  124. /* Compute a less quick upper bound.
  125. Each edit is an insertion or deletion of a character, hence
  126. modifies the occurrence count of a character by 1 and leaves the
  127. other occurrence counts unchanged.
  128. Therefore, when starting from a sequence X and ending at a
  129. sequence Y, and denoting the occurrence count of C in X with
  130. OCC (X, C), with N edits,
  131. sum_C | OCC (X, C) - OCC (Y, C) | <= N.
  132. (Proof by induction over N.)
  133. So, at the end, we will have
  134. edit_count >= sum_C | OCC (X, C) - OCC (Y, C) |,
  135. and hence
  136. result
  137. = (xvec_length + yvec_length - edit_count)
  138. / (xvec_length + yvec_length)
  139. <= (xvec_length + yvec_length - sum_C | OCC(X,C) - OCC(Y,C) |)
  140. / (xvec_length + yvec_length).
  141. */
  142. ptrdiff_t occ_diff[UCHAR_MAX + 1]; /* array C -> OCC(X,C) - OCC(Y,C) */
  143. ptrdiff_t sum;
  144. double dsum;
  145. /* Determine the occurrence counts in X. */
  146. memset (occ_diff, 0, sizeof (occ_diff));
  147. for (i = xvec_length - 1; i >= 0; i--)
  148. occ_diff[(unsigned char) string1[i]]++;
  149. /* Subtract the occurrence counts in Y. */
  150. for (i = yvec_length - 1; i >= 0; i--)
  151. occ_diff[(unsigned char) string2[i]]--;
  152. /* Sum up the absolute values. */
  153. sum = 0;
  154. for (i = 0; i <= UCHAR_MAX; i++)
  155. {
  156. ptrdiff_t d = occ_diff[i];
  157. sum += (d >= 0 ? d : -d);
  158. }
  159. dsum = sum;
  160. upper_bound = 1.0 - dsum / length_sum;
  161. if (upper_bound < lower_bound) /* Prob: 66% */
  162. /* Return an arbitrary value < LOWER_BOUND. */
  163. return 0.0;
  164. }
  165. #endif
  166. }
  167. /* set the info for each string. */
  168. ctxt.xvec = string1;
  169. ctxt.yvec = string2;
  170. /* Set TOO_EXPENSIVE to be approximate square root of input size,
  171. bounded below by 4096. */
  172. ctxt.too_expensive = 1;
  173. for (i = xvec_length + yvec_length; i != 0; i >>= 2)
  174. ctxt.too_expensive <<= 1;
  175. if (ctxt.too_expensive < 4096)
  176. ctxt.too_expensive = 4096;
  177. /* Allocate memory for fdiag and bdiag from a thread-local pool. */
  178. fdiag_len = length_sum + 3;
  179. gl_once (keys_init_once, keys_init);
  180. buffer = gl_tls_get (buffer_key);
  181. bufmax = (uintptr_t) gl_tls_get (bufmax_key);
  182. if (fdiag_len > bufmax)
  183. {
  184. /* Need more memory. */
  185. bufmax = 2 * bufmax;
  186. if (fdiag_len > bufmax)
  187. bufmax = fdiag_len;
  188. /* Calling xrealloc would be a waste: buffer's contents does not need
  189. to be preserved. */
  190. free (buffer);
  191. buffer = xnmalloc (bufmax, 2 * sizeof *buffer);
  192. gl_tls_set (buffer_key, buffer);
  193. gl_tls_set (bufmax_key, (void *) (uintptr_t) bufmax);
  194. }
  195. ctxt.fdiag = buffer + yvec_length + 1;
  196. ctxt.bdiag = ctxt.fdiag + fdiag_len;
  197. /* The edit_count is only ever increased. The computation can be aborted
  198. when
  199. (xvec_length + yvec_length - edit_count) / (xvec_length + yvec_length)
  200. < lower_bound,
  201. or equivalently
  202. edit_count > (xvec_length + yvec_length) * (1 - lower_bound)
  203. or equivalently
  204. edit_count > floor((xvec_length + yvec_length) * (1 - lower_bound)).
  205. We need to add an epsilon inside the floor(...) argument, to neutralize
  206. rounding errors. */
  207. ctxt.edit_count_limit =
  208. (lower_bound < 1.0
  209. ? (ptrdiff_t) (length_sum * (1.0 - lower_bound + 0.000001))
  210. : 0);
  211. /* Now do the main comparison algorithm */
  212. ctxt.edit_count = - ctxt.edit_count_limit;
  213. if (compareseq (0, xvec_length, 0, yvec_length, 0, &ctxt)) /* Prob: 98% */
  214. /* The edit_count passed the limit. Hence the result would be
  215. < lower_bound. We can return any value < lower_bound instead. */
  216. return 0.0;
  217. ctxt.edit_count += ctxt.edit_count_limit;
  218. /* The result is
  219. ((number of chars in common) / (average length of the strings)).
  220. The numerator is
  221. = xvec_length - (number of calls to NOTE_DELETE)
  222. = yvec_length - (number of calls to NOTE_INSERT)
  223. = 1/2 * (xvec_length + yvec_length - (number of edits)).
  224. This is admittedly biased towards finding that the strings are
  225. similar, however it does produce meaningful results. */
  226. return ((double) (xvec_length + yvec_length - ctxt.edit_count)
  227. / (xvec_length + yvec_length));
  228. }