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

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