View Javadoc
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 	@Override
134 	public <S extends Sequence> void diffNonCommon(EditList edits,
135 			HashedSequenceComparator<S> cmp, HashedSequence<S> a,
136 			HashedSequence<S> b, Edit region) {
137 		new State<>(edits, cmp, a, b).diffRegion(region);
138 	}
139 
140 	private class State<S extends Sequence> {
141 		private final HashedSequenceComparator<S> cmp;
142 		private final HashedSequence<S> a;
143 		private final HashedSequence<S> b;
144 		private final List<Edit> queue = new ArrayList<>();
145 
146 		/** Result edits we have determined that must be made to convert a to b. */
147 		final EditList edits;
148 
149 		State(EditList edits, HashedSequenceComparator<S> cmp,
150 				HashedSequence<S> a, HashedSequence<S> b) {
151 			this.cmp = cmp;
152 			this.a = a;
153 			this.b = b;
154 			this.edits = edits;
155 		}
156 
157 		void diffRegion(Edit r) {
158 			diffReplace(r);
159 			while (!queue.isEmpty())
160 				diff(queue.remove(queue.size() - 1));
161 		}
162 
163 		private void diffReplace(Edit r) {
164 			Edit lcs = new HistogramDiffIndex<>(maxChainLength, cmp, a, b, r)
165 					.findLongestCommonSequence();
166 			if (lcs != null) {
167 				// If we were given an edit, we can prove a result here.
168 				//
169 				if (lcs.isEmpty()) {
170 					// An empty edit indicates there is nothing in common.
171 					// Replace the entire region.
172 					//
173 					edits.add(r);
174 				} else {
175 					queue.add(r.after(lcs));
176 					queue.add(r.before(lcs));
177 				}
178 
179 			} else if (fallback instanceof LowLevelDiffAlgorithm) {
180 				LowLevelDiffAlgorithm fb = (LowLevelDiffAlgorithm) fallback;
181 				fb.diffNonCommon(edits, cmp, a, b, r);
182 
183 			} else if (fallback != null) {
184 				SubsequenceComparator<HashedSequence<S>> cs = subcmp();
185 				Subsequence<HashedSequence<S>> as = Subsequence.a(a, r);
186 				Subsequence<HashedSequence<S>> bs = Subsequence.b(b, r);
187 
188 				EditList res = fallback.diffNonCommon(cs, as, bs);
189 				edits.addAll(Subsequence.toBase(res, as, bs));
190 
191 			} else {
192 				edits.add(r);
193 			}
194 		}
195 
196 		private void diff(Edit r) {
197 			switch (r.getType()) {
198 			case INSERT:
199 			case DELETE:
200 				edits.add(r);
201 				break;
202 
203 			case REPLACE:
204 				if (r.getLengthA() == 1 && r.getLengthB() == 1)
205 					edits.add(r);
206 				else
207 					diffReplace(r);
208 				break;
209 
210 			case EMPTY:
211 			default:
212 				throw new IllegalStateException();
213 			}
214 		}
215 
216 		private SubsequenceComparator<HashedSequence<S>> subcmp() {
217 			return new SubsequenceComparator<>(cmp);
218 		}
219 	}
220 }