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.

HistogramDiff.java 7.5KB

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