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 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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 {@link SimilarityRenameDetector} to
  56. * compute scores between files.
  57. * <p>
  58. * To save space in memory, this index uses a space efficient encoding which
  59. * will not exceed 1 MiB per instance. The index starts out at a smaller size
  60. * (closer to 2 KiB), but may grow as more distinct blocks within the scanned
  61. * file are discovered.
  62. */
  63. class SimilarityIndex {
  64. /** A special {@link TableFullException} used in place of OutOfMemoryError. */
  65. private static final TableFullException TABLE_FULL_OUT_OF_MEMORY = new TableFullException();
  66. /**
  67. * Shift to apply before storing a key.
  68. * <p>
  69. * Within the 64 bit table record space, we leave the highest bit unset so
  70. * all values are positive. The lower 32 bits to count bytes.
  71. */
  72. private static final int KEY_SHIFT = 32;
  73. /** Maximum value of the count field, also mask to extract the count. */
  74. private static final long MAX_COUNT = (1L << KEY_SHIFT) - 1;
  75. /**
  76. * Total amount of bytes hashed into the structure, including \n. This is
  77. * usually the size of the file minus number of CRLF encounters.
  78. */
  79. private long hashedCnt;
  80. /** Number of non-zero entries in {@link #idHash}. */
  81. private int idSize;
  82. /** {@link #idSize} that triggers {@link #idHash} to double in size. */
  83. private int idGrowAt;
  84. /**
  85. * Pairings of content keys and counters.
  86. * <p>
  87. * Slots in the table are actually two ints wedged into a single long. The
  88. * upper 32 bits stores the content key, and the remaining lower bits stores
  89. * the number of bytes associated with that key. Empty slots are denoted by
  90. * 0, which cannot occur because the count cannot be 0. Values can only be
  91. * positive, which we enforce during key addition.
  92. */
  93. private long[] idHash;
  94. /** {@code idHash.length == 1 << idHashBits}. */
  95. private int idHashBits;
  96. SimilarityIndex() {
  97. idHashBits = 8;
  98. idHash = new long[1 << idHashBits];
  99. idGrowAt = growAt(idHashBits);
  100. }
  101. void hash(ObjectLoader obj) throws MissingObjectException, IOException,
  102. TableFullException {
  103. if (obj.isLarge()) {
  104. hashLargeObject(obj);
  105. } else {
  106. byte[] raw = obj.getCachedBytes();
  107. hash(raw, 0, raw.length);
  108. }
  109. }
  110. private void hashLargeObject(ObjectLoader obj) throws IOException,
  111. TableFullException {
  112. ObjectStream in1 = obj.openStream();
  113. boolean text;
  114. try {
  115. text = !RawText.isBinary(in1);
  116. } finally {
  117. in1.close();
  118. }
  119. ObjectStream in2 = obj.openStream();
  120. try {
  121. hash(in2, in2.getSize(), text);
  122. } finally {
  123. in2.close();
  124. }
  125. }
  126. void hash(byte[] raw, int ptr, final int end) throws TableFullException {
  127. final boolean text = !RawText.isBinary(raw);
  128. hashedCnt = 0;
  129. while (ptr < end) {
  130. int hash = 5381;
  131. int blockHashedCnt = 0;
  132. int start = ptr;
  133. // Hash one line, or one block, whichever occurs first.
  134. do {
  135. int c = raw[ptr++] & 0xff;
  136. // Ignore CR in CRLF sequence if text
  137. if (text && c == '\r' && ptr < end && raw[ptr] == '\n')
  138. continue;
  139. blockHashedCnt++;
  140. if (c == '\n')
  141. break;
  142. hash = (hash << 5) + hash + c;
  143. } while (ptr < end && ptr - start < 64);
  144. hashedCnt += blockHashedCnt;
  145. add(hash, blockHashedCnt);
  146. }
  147. }
  148. void hash(InputStream in, long remaining, boolean text) throws IOException,
  149. TableFullException {
  150. byte[] buf = new byte[4096];
  151. int ptr = 0;
  152. int cnt = 0;
  153. while (0 < remaining) {
  154. int hash = 5381;
  155. int blockHashedCnt = 0;
  156. // Hash one line, or one block, whichever occurs first.
  157. int n = 0;
  158. do {
  159. if (ptr == cnt) {
  160. ptr = 0;
  161. cnt = in.read(buf, 0, buf.length);
  162. if (cnt <= 0)
  163. throw new EOFException();
  164. }
  165. n++;
  166. int c = buf[ptr++] & 0xff;
  167. // Ignore CR in CRLF sequence if text
  168. if (text && c == '\r' && ptr < cnt && buf[ptr] == '\n')
  169. continue;
  170. blockHashedCnt++;
  171. if (c == '\n')
  172. break;
  173. hash = (hash << 5) + hash + c;
  174. } while (n < 64 && n < remaining);
  175. hashedCnt += blockHashedCnt;
  176. add(hash, blockHashedCnt);
  177. remaining -= n;
  178. }
  179. }
  180. /**
  181. * Sort the internal table so it can be used for efficient scoring.
  182. * <p>
  183. * Once sorted, additional lines/blocks cannot be added to the index.
  184. */
  185. void sort() {
  186. // Sort the array. All of the empty space will wind up at the front,
  187. // because we forced all of the keys to always be positive. Later
  188. // we only work with the back half of the array.
  189. //
  190. Arrays.sort(idHash);
  191. }
  192. int score(SimilarityIndex dst, int maxScore) {
  193. long max = Math.max(hashedCnt, dst.hashedCnt);
  194. if (max == 0)
  195. return maxScore;
  196. return (int) ((common(dst) * maxScore) / max);
  197. }
  198. long common(SimilarityIndex dst) {
  199. return common(this, dst);
  200. }
  201. private static long common(SimilarityIndex src, SimilarityIndex dst) {
  202. int srcIdx = src.packedIndex(0);
  203. int dstIdx = dst.packedIndex(0);
  204. long[] srcHash = src.idHash;
  205. long[] dstHash = dst.idHash;
  206. return common(srcHash, srcIdx, dstHash, dstIdx);
  207. }
  208. private static long common(long[] srcHash, int srcIdx, //
  209. long[] dstHash, int dstIdx) {
  210. if (srcIdx == srcHash.length || dstIdx == dstHash.length)
  211. return 0;
  212. long common = 0;
  213. int srcKey = keyOf(srcHash[srcIdx]);
  214. int dstKey = keyOf(dstHash[dstIdx]);
  215. for (;;) {
  216. if (srcKey == dstKey) {
  217. common += Math.min(countOf(srcHash[srcIdx]),
  218. countOf(dstHash[dstIdx]));
  219. if (++srcIdx == srcHash.length)
  220. break;
  221. srcKey = keyOf(srcHash[srcIdx]);
  222. if (++dstIdx == dstHash.length)
  223. break;
  224. dstKey = keyOf(dstHash[dstIdx]);
  225. } else if (srcKey < dstKey) {
  226. // Regions of src which do not appear in dst.
  227. if (++srcIdx == srcHash.length)
  228. break;
  229. srcKey = keyOf(srcHash[srcIdx]);
  230. } else /* if (dstKey < srcKey) */{
  231. // Regions of dst which do not appear in src.
  232. if (++dstIdx == dstHash.length)
  233. break;
  234. dstKey = keyOf(dstHash[dstIdx]);
  235. }
  236. }
  237. return common;
  238. }
  239. // Testing only
  240. int size() {
  241. return idSize;
  242. }
  243. // Testing only
  244. int key(int idx) {
  245. return keyOf(idHash[packedIndex(idx)]);
  246. }
  247. // Testing only
  248. long count(int idx) {
  249. return countOf(idHash[packedIndex(idx)]);
  250. }
  251. // Brute force approach only for testing.
  252. int findIndex(int key) {
  253. for (int i = 0; i < idSize; i++)
  254. if (key(i) == key)
  255. return i;
  256. return -1;
  257. }
  258. private int packedIndex(int idx) {
  259. return (idHash.length - idSize) + idx;
  260. }
  261. void add(int key, int cnt) throws TableFullException {
  262. key = (key * 0x9e370001) >>> 1; // Mix bits and ensure not negative.
  263. int j = slot(key);
  264. for (;;) {
  265. long v = idHash[j];
  266. if (v == 0) {
  267. // Empty slot in the table, store here.
  268. if (idGrowAt <= idSize) {
  269. grow();
  270. j = slot(key);
  271. continue;
  272. }
  273. idHash[j] = pair(key, cnt);
  274. idSize++;
  275. return;
  276. } else if (keyOf(v) == key) {
  277. // Same key, increment the counter. If it overflows, fail
  278. // indexing to prevent the key from being impacted.
  279. //
  280. idHash[j] = pair(key, countOf(v) + cnt);
  281. return;
  282. } else if (++j >= idHash.length) {
  283. j = 0;
  284. }
  285. }
  286. }
  287. private static long pair(int key, long cnt) throws TableFullException {
  288. if (MAX_COUNT < cnt)
  289. throw new TableFullException();
  290. return (((long) key) << KEY_SHIFT) | cnt;
  291. }
  292. private int slot(int key) {
  293. // We use 31 - idHashBits because the upper bit was already forced
  294. // to be 0 and we want the remaining high bits to be used as the
  295. // table slot.
  296. //
  297. return key >>> (31 - idHashBits);
  298. }
  299. private static int growAt(int idHashBits) {
  300. return (1 << idHashBits) * (idHashBits - 3) / idHashBits;
  301. }
  302. private void grow() throws TableFullException {
  303. if (idHashBits == 30)
  304. throw new TableFullException();
  305. long[] oldHash = idHash;
  306. int oldSize = idHash.length;
  307. idHashBits++;
  308. idGrowAt = growAt(idHashBits);
  309. try {
  310. idHash = new long[1 << idHashBits];
  311. } catch (OutOfMemoryError noMemory) {
  312. throw TABLE_FULL_OUT_OF_MEMORY;
  313. }
  314. for (int i = 0; i < oldSize; i++) {
  315. long v = oldHash[i];
  316. if (v != 0) {
  317. int j = slot(keyOf(v));
  318. while (idHash[j] != 0)
  319. if (++j >= idHash.length)
  320. j = 0;
  321. idHash[j] = v;
  322. }
  323. }
  324. }
  325. private static int keyOf(long v) {
  326. return (int) (v >>> KEY_SHIFT);
  327. }
  328. private static long countOf(long v) {
  329. return v & MAX_COUNT;
  330. }
  331. static class TableFullException extends Exception {
  332. private static final long serialVersionUID = 1L;
  333. }
  334. }