Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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.util.ArrayList;
  45. import java.util.List;
  46. /**
  47. * An extended form of Bram Cohen's patience diff algorithm.
  48. * <p>
  49. * This implementation was derived by using the 4 rules that are outlined in
  50. * Bram Cohen's <a href="http://bramcohen.livejournal.com/73318.html">blog</a>,
  51. * and then was further extended to support low-occurrence common elements.
  52. * <p>
  53. * The basic idea of the algorithm is to create a histogram of occurrences for
  54. * each element of sequence A. Each element of sequence B is then considered in
  55. * turn. If the element also exists in sequence A, and has a lower occurrence
  56. * count, the positions are considered as a candidate for the longest common
  57. * subsequence (LCS). After scanning of B is complete the LCS that has the
  58. * lowest number of occurrences is chosen as a split point. The region is split
  59. * around the LCS, and the algorithm is recursively applied to the sections
  60. * before and after the LCS.
  61. * <p>
  62. * By always selecting a LCS position with the lowest occurrence count, this
  63. * algorithm behaves exactly like Bram Cohen's patience diff whenever there is a
  64. * unique common element available between the two sequences. When no unique
  65. * elements exist, the lowest occurrence element is chosen instead. This offers
  66. * more readable diffs than simply falling back on the standard Myers' O(ND)
  67. * algorithm would produce.
  68. * <p>
  69. * To prevent the algorithm from having an O(N^2) running time, an upper limit
  70. * on the number of unique elements in a histogram bucket is configured by
  71. * {@link #setMaxChainLength(int)}. If sequence A has more than this many
  72. * elements that hash into the same hash bucket, the algorithm passes the region
  73. * to {@link #setFallbackAlgorithm(DiffAlgorithm)}. If no fallback algorithm is
  74. * configured, the region is emitted as a replace edit.
  75. * <p>
  76. * During scanning of sequence B, any element of A that occurs more than
  77. * {@link #setMaxChainLength(int)} times is never considered for an LCS match
  78. * position, even if it is common between the two sequences. This limits the
  79. * number of locations in sequence A that must be considered to find the LCS,
  80. * and helps maintain a lower running time bound.
  81. * <p>
  82. * So long as {@link #setMaxChainLength(int)} is a small constant (such as 64),
  83. * the algorithm runs in O(N * D) time, where N is the sum of the input lengths
  84. * and D is the number of edits in the resulting EditList. If the supplied
  85. * {@link org.eclipse.jgit.diff.SequenceComparator} has a good hash function,
  86. * this implementation typically out-performs
  87. * {@link org.eclipse.jgit.diff.MyersDiff}, even though its theoretical running
  88. * time is the same.
  89. * <p>
  90. * This implementation has an internal limitation that prevents it from handling
  91. * sequences with more than 268,435,456 (2^28) elements.
  92. */
  93. public class HistogramDiff extends LowLevelDiffAlgorithm {
  94. /** Algorithm to use when there are too many element occurrences. */
  95. DiffAlgorithm fallback = MyersDiff.INSTANCE;
  96. /**
  97. * Maximum number of positions to consider for a given element hash.
  98. *
  99. * All elements with the same hash are stored into a single chain. The chain
  100. * size is capped to ensure search is linear time at O(len_A + len_B) rather
  101. * than quadratic at O(len_A * len_B).
  102. */
  103. int maxChainLength = 64;
  104. /**
  105. * Set the algorithm used when there are too many element occurrences.
  106. *
  107. * @param alg
  108. * the secondary algorithm. If null the region will be denoted as
  109. * a single REPLACE block.
  110. */
  111. public void setFallbackAlgorithm(DiffAlgorithm alg) {
  112. fallback = alg;
  113. }
  114. /**
  115. * Maximum number of positions to consider for a given element hash.
  116. *
  117. * All elements with the same hash are stored into a single chain. The chain
  118. * size is capped to ensure search is linear time at O(len_A + len_B) rather
  119. * than quadratic at O(len_A * len_B).
  120. *
  121. * @param maxLen
  122. * new maximum length.
  123. */
  124. public void setMaxChainLength(int maxLen) {
  125. maxChainLength = maxLen;
  126. }
  127. /** {@inheritDoc} */
  128. @Override
  129. public <S extends Sequence> void diffNonCommon(EditList edits,
  130. HashedSequenceComparator<S> cmp, HashedSequence<S> a,
  131. HashedSequence<S> b, Edit region) {
  132. new State<>(edits, cmp, a, b).diffRegion(region);
  133. }
  134. private class State<S extends Sequence> {
  135. private final HashedSequenceComparator<S> cmp;
  136. private final HashedSequence<S> a;
  137. private final HashedSequence<S> b;
  138. private final List<Edit> queue = new ArrayList<>();
  139. /** Result edits we have determined that must be made to convert a to b. */
  140. final EditList edits;
  141. State(EditList edits, HashedSequenceComparator<S> cmp,
  142. HashedSequence<S> a, HashedSequence<S> b) {
  143. this.cmp = cmp;
  144. this.a = a;
  145. this.b = b;
  146. this.edits = edits;
  147. }
  148. void diffRegion(Edit r) {
  149. diffReplace(r);
  150. while (!queue.isEmpty())
  151. diff(queue.remove(queue.size() - 1));
  152. }
  153. private void diffReplace(Edit r) {
  154. Edit lcs = new HistogramDiffIndex<>(maxChainLength, cmp, a, b, r)
  155. .findLongestCommonSequence();
  156. if (lcs != null) {
  157. // If we were given an edit, we can prove a result here.
  158. //
  159. if (lcs.isEmpty()) {
  160. // An empty edit indicates there is nothing in common.
  161. // Replace the entire region.
  162. //
  163. edits.add(r);
  164. } else {
  165. queue.add(r.after(lcs));
  166. queue.add(r.before(lcs));
  167. }
  168. } else if (fallback instanceof LowLevelDiffAlgorithm) {
  169. LowLevelDiffAlgorithm fb = (LowLevelDiffAlgorithm) fallback;
  170. fb.diffNonCommon(edits, cmp, a, b, r);
  171. } else if (fallback != null) {
  172. SubsequenceComparator<HashedSequence<S>> cs = subcmp();
  173. Subsequence<HashedSequence<S>> as = Subsequence.a(a, r);
  174. Subsequence<HashedSequence<S>> bs = Subsequence.b(b, r);
  175. EditList res = fallback.diffNonCommon(cs, as, bs);
  176. edits.addAll(Subsequence.toBase(res, as, bs));
  177. } else {
  178. edits.add(r);
  179. }
  180. }
  181. private void diff(Edit r) {
  182. switch (r.getType()) {
  183. case INSERT:
  184. case DELETE:
  185. edits.add(r);
  186. break;
  187. case REPLACE:
  188. if (r.getLengthA() == 1 && r.getLengthB() == 1)
  189. edits.add(r);
  190. else
  191. diffReplace(r);
  192. break;
  193. case EMPTY:
  194. default:
  195. throw new IllegalStateException();
  196. }
  197. }
  198. private SubsequenceComparator<HashedSequence<S>> subcmp() {
  199. return new SubsequenceComparator<>(cmp);
  200. }
  201. }
  202. }