You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SimilarityIndex.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. /*
  2. * Copyright (C) 2010, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.diff;
  44. import java.io.EOFException;
  45. import java.io.IOException;
  46. import java.io.InputStream;
  47. import java.util.Arrays;
  48. import org.eclipse.jgit.errors.MissingObjectException;
  49. import org.eclipse.jgit.lib.ObjectLoader;
  50. import org.eclipse.jgit.lib.ObjectStream;
  51. /**
  52. * Index structure of lines/blocks in one file.
  53. * <p>
  54. * This structure can be used to compute an approximation of the similarity
  55. * between two files. The index is used by
  56. * {@link org.eclipse.jgit.diff.SimilarityRenameDetector} to compute scores
  57. * between files.
  58. * <p>
  59. * To save space in memory, this index uses a space efficient encoding which
  60. * will not exceed 1 MiB per instance. The index starts out at a smaller size
  61. * (closer to 2 KiB), but may grow as more distinct blocks within the scanned
  62. * file are discovered.
  63. *
  64. * @since 4.0
  65. */
  66. public class SimilarityIndex {
  67. /** A special {@link TableFullException} used in place of OutOfMemoryError. */
  68. public static final TableFullException
  69. TABLE_FULL_OUT_OF_MEMORY = new TableFullException();
  70. /**
  71. * Shift to apply before storing a key.
  72. * <p>
  73. * Within the 64 bit table record space, we leave the highest bit unset so
  74. * all values are positive. The lower 32 bits to count bytes.
  75. */
  76. private static final int KEY_SHIFT = 32;
  77. /** Maximum value of the count field, also mask to extract the count. */
  78. private static final long MAX_COUNT = (1L << KEY_SHIFT) - 1;
  79. /**
  80. * Total amount of bytes hashed into the structure, including \n. This is
  81. * usually the size of the file minus number of CRLF encounters.
  82. */
  83. private long hashedCnt;
  84. /** Number of non-zero entries in {@link #idHash}. */
  85. private int idSize;
  86. /** {@link #idSize} that triggers {@link #idHash} to double in size. */
  87. private int idGrowAt;
  88. /**
  89. * Pairings of content keys and counters.
  90. * <p>
  91. * Slots in the table are actually two ints wedged into a single long. The
  92. * upper 32 bits stores the content key, and the remaining lower bits stores
  93. * the number of bytes associated with that key. Empty slots are denoted by
  94. * 0, which cannot occur because the count cannot be 0. Values can only be
  95. * positive, which we enforce during key addition.
  96. */
  97. private long[] idHash;
  98. /** {@code idHash.length == 1 << idHashBits}. */
  99. private int idHashBits;
  100. /**
  101. * Create a new similarity index for the given object
  102. *
  103. * @param obj
  104. * the object to hash
  105. * @return similarity index for this object
  106. * @throws java.io.IOException
  107. * file contents cannot be read from the repository.
  108. * @throws org.eclipse.jgit.diff.SimilarityIndex.TableFullException
  109. * object hashing overflowed the storage capacity of the
  110. * SimilarityIndex.
  111. */
  112. public static SimilarityIndex create(ObjectLoader obj) throws IOException,
  113. TableFullException {
  114. SimilarityIndex idx = new SimilarityIndex();
  115. idx.hash(obj);
  116. idx.sort();
  117. return idx;
  118. }
  119. SimilarityIndex() {
  120. idHashBits = 8;
  121. idHash = new long[1 << idHashBits];
  122. idGrowAt = growAt(idHashBits);
  123. }
  124. void hash(ObjectLoader obj) throws MissingObjectException, IOException,
  125. TableFullException {
  126. if (obj.isLarge()) {
  127. hashLargeObject(obj);
  128. } else {
  129. byte[] raw = obj.getCachedBytes();
  130. hash(raw, 0, raw.length);
  131. }
  132. }
  133. private void hashLargeObject(ObjectLoader obj) throws IOException,
  134. TableFullException {
  135. boolean text;
  136. try (ObjectStream in1 = obj.openStream()) {
  137. text = !RawText.isBinary(in1);
  138. }
  139. try (ObjectStream in2 = obj.openStream()) {
  140. hash(in2, in2.getSize(), text);
  141. }
  142. }
  143. void hash(byte[] raw, int ptr, int end) throws TableFullException {
  144. final boolean text = !RawText.isBinary(raw);
  145. hashedCnt = 0;
  146. while (ptr < end) {
  147. int hash = 5381;
  148. int blockHashedCnt = 0;
  149. int start = ptr;
  150. // Hash one line, or one block, whichever occurs first.
  151. do {
  152. int c = raw[ptr++] & 0xff;
  153. // Ignore CR in CRLF sequence if text
  154. if (text && c == '\r' && ptr < end && raw[ptr] == '\n')
  155. continue;
  156. blockHashedCnt++;
  157. if (c == '\n')
  158. break;
  159. hash = (hash << 5) + hash + c;
  160. } while (ptr < end && ptr - start < 64);
  161. hashedCnt += blockHashedCnt;
  162. add(hash, blockHashedCnt);
  163. }
  164. }
  165. void hash(InputStream in, long remaining, boolean text) throws IOException,
  166. TableFullException {
  167. byte[] buf = new byte[4096];
  168. int ptr = 0;
  169. int cnt = 0;
  170. while (0 < remaining) {
  171. int hash = 5381;
  172. int blockHashedCnt = 0;
  173. // Hash one line, or one block, whichever occurs first.
  174. int n = 0;
  175. do {
  176. if (ptr == cnt) {
  177. ptr = 0;
  178. cnt = in.read(buf, 0, buf.length);
  179. if (cnt <= 0)
  180. throw new EOFException();
  181. }
  182. n++;
  183. int c = buf[ptr++] & 0xff;
  184. // Ignore CR in CRLF sequence if text
  185. if (text && c == '\r' && ptr < cnt && buf[ptr] == '\n')
  186. continue;
  187. blockHashedCnt++;
  188. if (c == '\n')
  189. break;
  190. hash = (hash << 5) + hash + c;
  191. } while (n < 64 && n < remaining);
  192. hashedCnt += blockHashedCnt;
  193. add(hash, blockHashedCnt);
  194. remaining -= n;
  195. }
  196. }
  197. /**
  198. * Sort the internal table so it can be used for efficient scoring.
  199. * <p>
  200. * Once sorted, additional lines/blocks cannot be added to the index.
  201. */
  202. void sort() {
  203. // Sort the array. All of the empty space will wind up at the front,
  204. // because we forced all of the keys to always be positive. Later
  205. // we only work with the back half of the array.
  206. //
  207. Arrays.sort(idHash);
  208. }
  209. /**
  210. * Compute the similarity score between this index and another.
  211. * <p>
  212. * A region of a file is defined as a line in a text file or a fixed-size
  213. * block in a binary file. To prepare an index, each region in the file is
  214. * hashed; the values and counts of hashes are retained in a sorted table.
  215. * Define the similarity fraction F as the the count of matching regions
  216. * between the two files divided between the maximum count of regions in
  217. * either file. The similarity score is F multiplied by the maxScore
  218. * constant, yielding a range [0, maxScore]. It is defined as maxScore for
  219. * the degenerate case of two empty files.
  220. * <p>
  221. * The similarity score is symmetrical; i.e. a.score(b) == b.score(a).
  222. *
  223. * @param dst
  224. * the other index
  225. * @param maxScore
  226. * the score representing a 100% match
  227. * @return the similarity score
  228. */
  229. public int score(SimilarityIndex dst, int maxScore) {
  230. long max = Math.max(hashedCnt, dst.hashedCnt);
  231. if (max == 0)
  232. return maxScore;
  233. return (int) ((common(dst) * maxScore) / max);
  234. }
  235. long common(SimilarityIndex dst) {
  236. return common(this, dst);
  237. }
  238. private static long common(SimilarityIndex src, SimilarityIndex dst) {
  239. int srcIdx = src.packedIndex(0);
  240. int dstIdx = dst.packedIndex(0);
  241. long[] srcHash = src.idHash;
  242. long[] dstHash = dst.idHash;
  243. return common(srcHash, srcIdx, dstHash, dstIdx);
  244. }
  245. private static long common(long[] srcHash, int srcIdx, //
  246. long[] dstHash, int dstIdx) {
  247. if (srcIdx == srcHash.length || dstIdx == dstHash.length)
  248. return 0;
  249. long common = 0;
  250. int srcKey = keyOf(srcHash[srcIdx]);
  251. int dstKey = keyOf(dstHash[dstIdx]);
  252. for (;;) {
  253. if (srcKey == dstKey) {
  254. common += Math.min(countOf(srcHash[srcIdx]),
  255. countOf(dstHash[dstIdx]));
  256. if (++srcIdx == srcHash.length)
  257. break;
  258. srcKey = keyOf(srcHash[srcIdx]);
  259. if (++dstIdx == dstHash.length)
  260. break;
  261. dstKey = keyOf(dstHash[dstIdx]);
  262. } else if (srcKey < dstKey) {
  263. // Regions of src which do not appear in dst.
  264. if (++srcIdx == srcHash.length)
  265. break;
  266. srcKey = keyOf(srcHash[srcIdx]);
  267. } else /* if (dstKey < srcKey) */{
  268. // Regions of dst which do not appear in src.
  269. if (++dstIdx == dstHash.length)
  270. break;
  271. dstKey = keyOf(dstHash[dstIdx]);
  272. }
  273. }
  274. return common;
  275. }
  276. // Testing only
  277. int size() {
  278. return idSize;
  279. }
  280. // Testing only
  281. int key(int idx) {
  282. return keyOf(idHash[packedIndex(idx)]);
  283. }
  284. // Testing only
  285. long count(int idx) {
  286. return countOf(idHash[packedIndex(idx)]);
  287. }
  288. // Brute force approach only for testing.
  289. int findIndex(int key) {
  290. for (int i = 0; i < idSize; i++)
  291. if (key(i) == key)
  292. return i;
  293. return -1;
  294. }
  295. private int packedIndex(int idx) {
  296. return (idHash.length - idSize) + idx;
  297. }
  298. void add(int key, int cnt) throws TableFullException {
  299. key = (key * 0x9e370001) >>> 1; // Mix bits and ensure not negative.
  300. int j = slot(key);
  301. for (;;) {
  302. long v = idHash[j];
  303. if (v == 0) {
  304. // Empty slot in the table, store here.
  305. if (idGrowAt <= idSize) {
  306. grow();
  307. j = slot(key);
  308. continue;
  309. }
  310. idHash[j] = pair(key, cnt);
  311. idSize++;
  312. return;
  313. } else if (keyOf(v) == key) {
  314. // Same key, increment the counter. If it overflows, fail
  315. // indexing to prevent the key from being impacted.
  316. //
  317. idHash[j] = pair(key, countOf(v) + cnt);
  318. return;
  319. } else if (++j >= idHash.length) {
  320. j = 0;
  321. }
  322. }
  323. }
  324. private static long pair(int key, long cnt) throws TableFullException {
  325. if (MAX_COUNT < cnt)
  326. throw new TableFullException();
  327. return (((long) key) << KEY_SHIFT) | cnt;
  328. }
  329. private int slot(int key) {
  330. // We use 31 - idHashBits because the upper bit was already forced
  331. // to be 0 and we want the remaining high bits to be used as the
  332. // table slot.
  333. //
  334. return key >>> (31 - idHashBits);
  335. }
  336. private static int growAt(int idHashBits) {
  337. return (1 << idHashBits) * (idHashBits - 3) / idHashBits;
  338. }
  339. private void grow() throws TableFullException {
  340. if (idHashBits == 30)
  341. throw new TableFullException();
  342. long[] oldHash = idHash;
  343. int oldSize = idHash.length;
  344. idHashBits++;
  345. idGrowAt = growAt(idHashBits);
  346. try {
  347. idHash = new long[1 << idHashBits];
  348. } catch (OutOfMemoryError noMemory) {
  349. throw TABLE_FULL_OUT_OF_MEMORY;
  350. }
  351. for (int i = 0; i < oldSize; i++) {
  352. long v = oldHash[i];
  353. if (v != 0) {
  354. int j = slot(keyOf(v));
  355. while (idHash[j] != 0)
  356. if (++j >= idHash.length)
  357. j = 0;
  358. idHash[j] = v;
  359. }
  360. }
  361. }
  362. private static int keyOf(long v) {
  363. return (int) (v >>> KEY_SHIFT);
  364. }
  365. private static long countOf(long v) {
  366. return v & MAX_COUNT;
  367. }
  368. /** Thrown by {@code create()} when file is too large. */
  369. public static class TableFullException extends Exception {
  370. private static final long serialVersionUID = 1L;
  371. }
  372. }