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

/jEdit/tags/jedit-4-3-pre5/org/gjt/sp/jedit/search/BoyerMooreSearchMatcher.java

#
Java | 307 lines | 142 code | 40 blank | 125 comment | 29 complexity | 09b28db84df4f0899cf63df84d6163a1 MD5 | raw file
Possible License(s): BSD-3-Clause, AGPL-1.0, Apache-2.0, LGPL-2.0, LGPL-3.0, GPL-2.0, CC-BY-SA-3.0, LGPL-2.1, GPL-3.0, MPL-2.0-no-copyleft-exception, IPL-1.0
  1. /*
  2. * BoyerMooreSearchMatcher.java - Literal pattern String matcher utilizing the
  3. * Boyer-Moore algorithm
  4. * :tabSize=8:indentSize=8:noTabs=false:
  5. * :folding=explicit:collapseFolds=1:
  6. *
  7. * Copyright (C) 1999, 2000 mike dillon
  8. * Portions copyright (C) 2001 Tom Locke
  9. * Portions copyright (C) 2001, 2002 Slava Pestov
  10. *
  11. * This program is free software; you can redistribute it and/or
  12. * modify it under the terms of the GNU General Public License
  13. * as published by the Free Software Foundation; either version 2
  14. * of the License, or any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU General Public License
  22. * along with this program; if not, write to the Free Software
  23. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  24. */
  25. package org.gjt.sp.jedit.search;
  26. /**
  27. * Implements literal search using the Boyer-Moore algorithm.
  28. */
  29. public class BoyerMooreSearchMatcher extends SearchMatcher
  30. {
  31. //{{{ BoyerMooreSearchMatcher constructor
  32. /**
  33. * Creates a new string literal matcher.
  34. */
  35. public BoyerMooreSearchMatcher(String pattern, boolean ignoreCase)
  36. {
  37. this.pattern = pattern.toCharArray();
  38. if(ignoreCase)
  39. {
  40. for(int i = 0; i < this.pattern.length; i++)
  41. {
  42. this.pattern[i] = Character.toUpperCase(
  43. this.pattern[i]);
  44. }
  45. }
  46. this.ignoreCase = ignoreCase;
  47. pattern_end = this.pattern.length - 1;
  48. } //}}}
  49. //{{{ nextMatch() method
  50. /**
  51. * Returns the offset of the first match of the specified text
  52. * within this matcher.
  53. * @param text The text to search in
  54. * @param start True if the start of the segment is the beginning of the
  55. * buffer
  56. * @param end True if the end of the segment is the end of the buffer
  57. * @param firstTime If false and the search string matched at the start
  58. * offset with length zero, automatically find next match
  59. * @param reverse If true, searching will be performed in a backward
  60. * direction.
  61. * @return an array where the first element is the start offset
  62. * of the match, and the second element is the end offset of
  63. * the match
  64. * @since jEdit 4.2pre4
  65. */
  66. public SearchMatcher.Match nextMatch(CharSequence text,
  67. boolean start, boolean end, boolean firstTime,
  68. boolean reverse)
  69. {
  70. int pos = match(text,reverse);
  71. if (pos == -1)
  72. {
  73. return null;
  74. }
  75. else
  76. {
  77. returnValue.start = pos;
  78. returnValue.end = pos + pattern.length;
  79. return returnValue;
  80. }
  81. } //}}}
  82. //{{{ match() method
  83. /**
  84. * a good introduction to the Boyer-Moore fast string matching
  85. * algorithm may be found on Moore's website at:
  86. *
  87. * http://www.cs.utexas.edu/users/moore/best-ideas/string-searching/
  88. *
  89. * @since jEdit 4.3pre5
  90. */
  91. public int match(CharSequence text, boolean reverse)
  92. {
  93. //{{{
  94. // lazily create skip and suffix arrays for either the
  95. // search pattern, or the reversed search pattern
  96. int[] skip, suffix;
  97. if(reverse)
  98. {
  99. if(back_skip == null)
  100. {
  101. back_skip = generateSkipArray(true);
  102. back_suffix = generateSuffixArray(true);
  103. }
  104. skip = back_skip;
  105. suffix = back_suffix;
  106. }
  107. else
  108. {
  109. if(fwd_skip == null)
  110. {
  111. fwd_skip = generateSkipArray(false);
  112. fwd_suffix = generateSuffixArray(false);
  113. }
  114. skip = fwd_skip;
  115. suffix = fwd_suffix;
  116. } //}}}
  117. // position variable for pattern test position
  118. int pos;
  119. // position variable for pattern start
  120. int anchor = 0;
  121. // last possible start position of a match with this pattern;
  122. // this is negative if the pattern is longer than the text
  123. // causing the search loop below to immediately fail
  124. //int last_anchor = reverseSearch
  125. // ? offset + pattern.length - 1
  126. // : length - pattern.length;
  127. char ch = 0;
  128. int bad_char;
  129. int good_suffix;
  130. // the search works by starting the anchor (first character
  131. // of the pattern) at the initial offset. as long as the
  132. // anchor is far enough from the enough of the text for the
  133. // pattern to match, and until the pattern matches, we
  134. // compare the pattern to the text from the last character
  135. // to the first character in reverse order. where a character
  136. // in the pattern mismatches, we use the two heuristics
  137. // based on the mismatch character and its position in the
  138. // pattern to determine the furthest we can move the anchor
  139. // without missing any potential pattern matches.
  140. SEARCH:
  141. while (anchor + pattern_end < text.length())
  142. {
  143. for (pos = pattern_end; pos >= 0; --pos)
  144. {
  145. ch = text.charAt(pos + anchor);
  146. if(ignoreCase)
  147. ch = Character.toUpperCase(ch);
  148. // pattern test
  149. if ((reverse ? ch != pattern[pattern_end - pos]
  150. : ch != pattern[pos]))
  151. {
  152. // character mismatch, determine how many characters to skip
  153. // heuristic #1
  154. bad_char = pos - skip[getSkipIndex(ch)];
  155. // heuristic #2
  156. good_suffix = suffix[pos];
  157. // skip the greater of the two distances provided by the
  158. // heuristics
  159. int skip_index = (bad_char > good_suffix) ? bad_char : good_suffix;
  160. anchor += skip_index;
  161. // go back to the while loop
  162. continue SEARCH;
  163. }
  164. }
  165. // MATCH: return the position of its first character
  166. return anchor;
  167. }
  168. // MISMATCH: return -1 as defined by API
  169. return -1;
  170. } //}}}
  171. //{{{ Private members
  172. private char[] pattern;
  173. private int pattern_end;
  174. private boolean ignoreCase;
  175. // Boyer-Moore member fields
  176. private int[] fwd_skip;
  177. private int[] fwd_suffix;
  178. private int[] back_skip;
  179. private int[] back_suffix;
  180. //}}}
  181. // Boyer-Moore helper methods
  182. //{{{ generateSkipArray() method
  183. /*
  184. * the 'skip' array is used to determine for each index in the
  185. * hashed alphabet how many characters can be skipped if
  186. * a mismatch occurs on a characater hashing to that index.
  187. */
  188. private int[] generateSkipArray(boolean reverse)
  189. {
  190. // initialize the skip array to all zeros
  191. int[] skip = new int[256];
  192. // leave the table cleanly-initialized for an empty pattern
  193. if (pattern.length == 0)
  194. return skip;
  195. int pos = 0;
  196. do
  197. {
  198. skip[getSkipIndex(pattern[reverse ? pattern_end - pos : pos])] = pos;
  199. }
  200. while (++pos < pattern.length);
  201. return skip;
  202. } //}}}
  203. //{{{ getSkipIndex() method
  204. /*
  205. * to avoid our skip table having a length of 2 ^ 16, we hash each
  206. * character of the input into a character in the alphabet [\x00-\xFF]
  207. * using the lower 8 bits of the character's value (resulting in
  208. * a more reasonable skip table of length 2 ^ 8).
  209. *
  210. * the result of this is that more than one character can hash to the
  211. * same index, but since the skip table encodes the position of
  212. * occurence of the character furthest into the string with a particular
  213. * index (whether or not it is the only character with that index), an
  214. * index collision only means that that this heuristic will give a
  215. * sub-optimal skip (i.e. a complete skip table could use the differences
  216. * between colliding characters to maximal effect, at the expense of
  217. * building a table that is over 2 orders of magnitude larger and very
  218. * sparse).
  219. */
  220. private static final int getSkipIndex(char ch)
  221. {
  222. return ch & 0x000000FF;
  223. } //}}}
  224. //{{{ generateSuffixArray() method
  225. /*
  226. * XXX: hairy code that is basically just a functional(?) port of some
  227. * other code i barely understood
  228. */
  229. private int[] generateSuffixArray(boolean reverse)
  230. {
  231. int m = pattern.length;
  232. int j = m + 1;
  233. int[] suffix = new int[j];
  234. int[] tmp = new int[j];
  235. tmp[m] = j;
  236. for (int i = m; i > 0; --i)
  237. {
  238. while (j <= m && pattern[reverse ? pattern_end - i + 1 : i - 1]
  239. != pattern[reverse ? pattern_end - j + 1 : j - 1])
  240. {
  241. if (suffix[j] == 0)
  242. {
  243. suffix[j] = j - i;
  244. }
  245. j = tmp[j];
  246. }
  247. tmp[i - 1] = --j;
  248. }
  249. int k = tmp[0];
  250. for (j = 0; j <= m; j++)
  251. {
  252. // the code above builds a 1-indexed suffix array,
  253. // but we shift it to be 0-indexed, ignoring the
  254. // original 0-th element
  255. if (j > 0)
  256. {
  257. suffix[j - 1] = (suffix[j] == 0) ? k : suffix[j];
  258. }
  259. if (j == k)
  260. {
  261. k = tmp[k];
  262. }
  263. }
  264. return suffix;
  265. } //}}}
  266. //}}}
  267. }