1 2 24 25 26 27 28 package com.lutris.util; 29 30 36 public class BMByteSearch 37 { 38 39 43 private byte[] P; 44 45 48 private int m; 49 50 55 private int[] charJump; 56 57 61 private int[] matchJump; 62 63 73 public 74 BMByteSearch(String pattern) 75 { 76 genPatternFromCharArray(pattern.toCharArray()); 77 computeJumps(); 78 computeMatchJumps(); 79 } 80 81 87 public 88 BMByteSearch(byte[] pattern) 89 { 90 genPatternFromByteArray(pattern, 0, pattern.length); 91 computeJumps(); 92 computeMatchJumps(); 93 } 94 95 103 public 104 BMByteSearch(byte[] pattern, int offset, int length) 105 { 106 genPatternFromByteArray(pattern, offset, length); 107 computeJumps(); 108 computeMatchJumps(); 109 } 110 111 118 private static final 119 int min(int i1, int i2) 120 { 121 return (i1 < i2) ? i1 : i2; 122 } 123 124 131 private static final 132 int max(int i1, int i2) 133 { 134 return (i1 > i2) ? i1 : i2; 135 } 136 137 147 private final 148 void genPatternFromByteArray(byte[] bytes, int off, int length) 149 { 150 int i,j; 151 m = length; 152 P = new byte[length+1]; 155 for (i=1, j=off; i <= length; i++, j++) P[i] = bytes[j]; 156 } 157 158 168 private final 169 void genPatternFromCharArray(char[] chars) 170 { 171 m = chars.length; 172 P = new byte[m + 1]; 173 for (int i=1; i<= m; i++) { 174 if (chars[i-1] > 127) P[i] = (byte) ((chars[i-1] - 256) & 0xff); 175 else P[i] = (byte) (chars[i-1] & 0xff); 176 } 177 } 178 179 183 private final 184 void computeJumps() 185 { 186 charJump = new int[256]; 187 for (int i=0; i<255; i++) charJump[i] = m; 188 for (int k=1; k<=m; k++) charJump[P[k] + 128] = m - k; 189 } 190 191 195 private 196 void computeMatchJumps() 197 { 198 int k, q, qq, mm; 199 int[] back = new int[m + 2]; 200 201 matchJump = new int[m + 2]; 202 mm = 2 * m; 203 204 for (k=1; k <= m; k++) matchJump[k] = mm - k; 205 k = m; q = m + 1; 206 while (k > 0) { 207 back[k] = q; 208 while ((q <= m) && (P[k] != P[q])) { 209 matchJump[q] = min(matchJump[q], m - k); 210 q = back[q]; 211 } 212 k = k - 1; q = q - 1; 213 } 214 for (k = 1; k <= q; k++) { 215 matchJump[k] = min(matchJump[k], m + q - k); 216 } 217 qq = back[q]; 218 while (q <= m) { 219 while (q <= qq) { 220 matchJump[q] = min(matchJump[q], qq - q + m); 221 q = q + 1; 222 } 223 qq = back[qq]; 224 } 225 } 226 227 232 public 233 int getPatternLength() 234 { 235 return(m); 236 } 237 238 249 public 250 int search(byte[] byteString) 251 { 252 return(search(byteString, 0, byteString.length)); 253 } 254 255 270 public 271 int search(byte[] byteString, int offset, int length) 272 { 273 int j, k, len; 274 j = m + offset; 275 k = m; 276 len = min(byteString.length, offset + length); 277 while ((j <= len) && (k > 0)) { 278 if ((byteString[j-1]) == P[k]) { 279 j = j - 1; k = k - 1; 280 } else { 281 j = j + max(charJump[byteString[j-1] + 128], matchJump[k]); 282 k = m; 283 } 284 } 285 if (k == 0) return(j); 286 return(-1); } 288 } 289 290 | Popular Tags |