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