Java Code Examples for java.util.LinkedList#listIterator()

The following examples show how to use java.util.LinkedList#listIterator() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AuthCacheImpl.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public synchronized AuthCacheValue get (String pkey, String skey) {
    AuthenticationInfo result = null;
    LinkedList<AuthCacheValue> list = hashtable.get (pkey);
    if (list == null || list.size() == 0) {
        return null;
    }
    if (skey == null) {
        // list should contain only one element
        return (AuthenticationInfo)list.get (0);
    }
    ListIterator<AuthCacheValue> iter = list.listIterator();
    while (iter.hasNext()) {
        AuthenticationInfo inf = (AuthenticationInfo)iter.next();
        if (skey.startsWith (inf.path)) {
            return inf;
        }
    }
    return null;
}
 
Example 2
Source File: AuthCacheImpl.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public synchronized void remove (String pkey, AuthCacheValue entry) {
    LinkedList<AuthCacheValue> list = hashtable.get (pkey);
    if (list == null) {
        return;
    }
    if (entry == null) {
        list.clear();
        return;
    }
    ListIterator<AuthCacheValue> iter = list.listIterator ();
    while (iter.hasNext()) {
        AuthenticationInfo inf = (AuthenticationInfo)iter.next();
        if (entry.equals(inf)) {
            iter.remove ();
        }
    }
}
 
Example 3
Source File: AuthCacheImpl.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public synchronized void put (String pkey, AuthCacheValue value) {
    LinkedList<AuthCacheValue> list = hashtable.get (pkey);
    String skey = value.getPath();
    if (list == null) {
        list = new LinkedList<AuthCacheValue>();
        hashtable.put(pkey, list);
    }
    // Check if the path already exists or a super-set of it exists
    ListIterator<AuthCacheValue> iter = list.listIterator();
    while (iter.hasNext()) {
        AuthenticationInfo inf = (AuthenticationInfo)iter.next();
        if (inf.path == null || inf.path.startsWith (skey)) {
            iter.remove ();
        }
    }
    iter.add(value);
}
 
Example 4
Source File: InternalCommandManager.java    From arthas with Apache License 2.0 6 votes vote down vote up
private void completeSingleCommand(Completion completion, LinkedList<CliToken> tokens) {
    ListIterator<CliToken> it = tokens.listIterator();
    while (it.hasNext()) {
        CliToken ct = it.next();
        it.remove();
        if (ct.isText()) {
            final List<CliToken> newTokens = new ArrayList<CliToken>();
            while (it.hasNext()) {
                newTokens.add(it.next());
            }
            StringBuilder tmp = new StringBuilder();
            for (CliToken token : newTokens) {
                tmp.append(token.raw());
            }
            final String line = tmp.toString();
            for (CommandResolver resolver : resolvers) {
                Command command = getCommand(resolver, ct.value());
                if (command != null) {
                    command.complete(new CommandCompletion(completion, line, newTokens));
                    return;
                }
            }
            completion.complete(Collections.<String>emptyList());
        }
    }
}
 
Example 5
Source File: PcepClientControllerImpl.java    From onos with Apache License 2.0 6 votes vote down vote up
private LspType getLspType(PcepSrpObject srpObj) {
    LspType lspType = WITH_SIGNALLING;

    if (null != srpObj) {
        LinkedList<PcepValueType> llOptionalTlv = srpObj.getOptionalTlv();
        ListIterator<PcepValueType> listIterator = llOptionalTlv.listIterator();

        while (listIterator.hasNext()) {
            PcepValueType tlv = listIterator.next();
            switch (tlv.getType()) {
            case PathSetupTypeTlv.TYPE:
                lspType = LspType.values()[Integer.valueOf(((PathSetupTypeTlv) tlv).getPst())];
                break;
            default:
                break;
            }
        }
    }
    return lspType;
}
 
Example 6
Source File: DiffOperationGenerator.java    From ContentAssist with MIT License 6 votes vote down vote up
/**
 * Obtains the deltas from a given difference information.
 * @param diffs the collection of difference information of the diff utility.
 * @return the collection of the code deltas
 */
private static List<CodeDelta> getDeltas(LinkedList<Diff> diffs) {
    ArrayList<CodeDelta> deltas = new ArrayList<CodeDelta>();
    int offset = 0;
    
    for (ListIterator<Diff> pointer = diffs.listIterator(); pointer.hasNext(); ) { 
        Diff diff = pointer.next();
        
        if (diff.operation == Operation.INSERT) {
            deltas.add(new CodeDelta(offset, CodeDelta.Type.INSERT, diff.text));
            
        } else if (diff.operation == Operation.DELETE) {
            deltas.add(new CodeDelta(offset, CodeDelta.Type.DELETE, diff.text));
        }
        
        offset = offset + diff.text.length();
    }
    
    return deltas;
}
 
Example 7
Source File: GenericParser.java    From charliebot with GNU General Public License v2.0 6 votes vote down vote up
public int nodeCount(String s, LinkedList linkedlist, boolean flag) {
    int i = 0;
    if (linkedlist == null)
        return 0;
    for (ListIterator listiterator = linkedlist.listIterator(0); listiterator.hasNext(); ) {
        XMLNode xmlnode = (XMLNode) listiterator.next();
        if (xmlnode != null)
            switch (xmlnode.XMLType) {
                default:
                    break;

                case 0: // '\0'
                case 1: // '\001'
                    if (xmlnode.XMLData.equals(s) || flag)
                        i++;
                    break;
            }
    }

    return i;
}
 
Example 8
Source File: IteratingGSS.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Prunes the given list of hypothesis. All hypothesis with an upper utility bound less than the
 * parameter minUtility is pruned.
 */
public LinkedList<Hypothesis> prune(LinkedList<Hypothesis> hypoList, double minUtility, double totalWeight,
		double totalPositiveWeight, double delta_p) {
	double delta_hp = delta_p / hypoList.size();
	ListIterator<Hypothesis> it = hypoList.listIterator();
	while (it.hasNext()) {
		Hypothesis hypo = it.next();
		double upperBound = theUtility.getUpperBound(totalWeight, totalPositiveWeight, hypo, delta_hp);
		if (upperBound < minUtility) {
			it.remove();
		}
	}
	return hypoList;
}
 
Example 9
Source File: Remove.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static
void main(String[] args) {
    LinkedList list = new LinkedList();
    ListIterator e = list.listIterator();
    Object o = new Integer(1);
    e.add(o);
    e.previous();
    e.next();
    e.remove();
    e.add(o);
    if (!o.equals(list.get(0)))
        throw new RuntimeException("LinkedList ListIterator remove failed.");
}
 
Example 10
Source File: BgpOpenMsgVer4.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * returns length of capability tlvs.
 *
 * @param cb of type channel buffer
 * @param message of type BGPOpenMsgVer4
 * @return capParaLen of open message
 */
protected int packCapabilityTlv(ChannelBuffer cb, BgpOpenMsgVer4 message) {
    int startIndex = cb.writerIndex();
    int capParaLen = 0;
    int capParaLenIndex = 0;

    LinkedList<BgpValueType> capabilityTlv = message.capabilityTlv;
    ListIterator<BgpValueType> listIterator = capabilityTlv.listIterator();

    if (listIterator.hasNext()) {
        // Set optional parameter type as 2
        cb.writeByte(OPT_PARA_TYPE_CAPABILITY);

        // Store the index of capability parameter length and update length at the end
        capParaLenIndex = cb.writerIndex();

        // Set capability parameter length as 0
        cb.writeByte(0);

        // Update the startIndex to know the length of capability tlv
        startIndex = cb.writerIndex();
    }

    while (listIterator.hasNext()) {
        BgpValueType tlv = listIterator.next();
        if (tlv == null) {
            log.debug("Warning: TLV is null from CapabilityTlv list");
            continue;
        }
        tlv.write(cb);
    }

    capParaLen = cb.writerIndex() - startIndex;

    if (capParaLen != 0) {
        // Update capability parameter length
        cb.setByte(capParaLenIndex, (byte) capParaLen);
    }
    return capParaLen;
}
 
Example 11
Source File: Remove.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static
void main(String[] args) {
    LinkedList list = new LinkedList();
    ListIterator e = list.listIterator();
    Object o = new Integer(1);
    e.add(o);
    e.previous();
    e.next();
    e.remove();
    e.add(o);
    if (!o.equals(list.get(0)))
        throw new RuntimeException("LinkedList ListIterator remove failed.");
}
 
Example 12
Source File: JarDiff.java    From webstart with MIT License 5 votes vote down vote up
public String hasSameContent( JarFile2 file, JarEntry entry )
        throws IOException
{

    String thisName = null;

    Long crcL = entry.getCrc();

    // check if this jar contains files with the passed in entry's crc
    if ( _crcToEntryMap.containsKey( crcL ) )
    {
        // get the Linked List with files with the crc
        LinkedList ll = (LinkedList) _crcToEntryMap.get( crcL );
        // go through the list and check for content match
        ListIterator li = ll.listIterator( 0 );
        while ( li.hasNext() )
        {
            JarEntry thisEntry = (JarEntry) li.next();

            // check for content match
            InputStream oldIS = getJarFile().getInputStream( thisEntry );
            InputStream newIS = file.getJarFile().getInputStream( entry );

            if ( !differs( oldIS, newIS ) )
            {
                thisName = thisEntry.getName();
                return thisName;
            }
        }
    }

    return thisName;

}
 
Example 13
Source File: Remove.java    From native-obfuscator with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) {
    LinkedList list = new LinkedList();
    ListIterator e = list.listIterator();
    Object o = new Integer(1);
    e.add(o);
    e.previous();
    e.next();
    e.remove();
    e.add(o);
    if (!o.equals(list.get(0)))
        throw new RuntimeException("LinkedList ListIterator remove failed.");
}
 
Example 14
Source File: DRL6Parser.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private int getCurrentLocation() {
    LinkedList<DroolsSentence> ei = helper.getEditorInterface();
    LinkedList<?> content = ei.getLast().getContent();
    // the following call is efficient as it points to the tail of the list
    ListIterator<?> listIterator = content.listIterator(content.size());
    while (listIterator.hasPrevious()) {
        Object previous = listIterator.previous();
        if (previous instanceof Integer) {
            return ((Integer) previous).intValue();
        }
    }
    return Location.LOCATION_UNKNOWN;
}
 
Example 15
Source File: JRStyledTextUtil.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected FontMatch fontMatchRun(String text, int startIndex, int endIndex, List<Face> fonts)
{
	LinkedList<Face> validFonts = new LinkedList<Face>(fonts);
	Face lastValid = null;
	int charIndex = startIndex;
	int nextCharIndex = charIndex;
	while (charIndex < endIndex)
	{
		char textChar = text.charAt(charIndex);
		nextCharIndex = charIndex + 1;
		
		int codePoint;
		if (Character.isHighSurrogate(textChar))
		{
			if (charIndex + 1 >= endIndex)
			{
				//isolated high surrogate, not attempting to match fonts
				break;
			}
			
			char nextChar = text.charAt(charIndex + 1);
			if (!Character.isLowSurrogate(nextChar))
			{
				//unpaired high surrogate, not attempting to match fonts
				break;
			}
			codePoint = Character.toCodePoint(textChar, nextChar);
			++nextCharIndex;
		}
		else
		{
			codePoint = textChar;
		}

		for (ListIterator<Face> fontIt = validFonts.listIterator(); fontIt.hasNext();)
		{
			Face face = fontIt.next();
			
			if (!face.supports(codePoint))
			{
				fontIt.remove();
			}
		}
		
		if (validFonts.isEmpty())
		{
			break;
		}
		
		lastValid = validFonts.getFirst();
		charIndex = nextCharIndex;
	}
	
	FontMatch fontMatch = new FontMatch();
	fontMatch.endIndex = lastValid == null ? nextCharIndex : charIndex;
	fontMatch.fontInfo = lastValid == null ? null : lastValid.fontInfo;
	return fontMatch;
}
 
Example 16
Source File: diff_match_patch.java    From bluima with Apache License 2.0 4 votes vote down vote up
/**
 * Do a quick line-level diff on both strings, then rediff the parts for
 * greater accuracy. This speedup can produce non-minimal diffs.
 * 
 * @param text1
 *            Old string to be diffed.
 * @param text2
 *            New string to be diffed.
 * @param deadline
 *            Time when the diff should be complete by.
 * @return Linked List of Diff objects.
 */
private LinkedList<Diff> diff_lineMode(String text1, String text2,
        long deadline) {
    // Scan the text on a line-by-line basis first.
    LinesToCharsResult b = diff_linesToChars(text1, text2);
    text1 = b.chars1;
    text2 = b.chars2;
    List<String> linearray = b.lineArray;

    LinkedList<Diff> diffs = diff_main(text1, text2, false, deadline);

    // Convert the diff back to original text.
    diff_charsToLines(diffs, linearray);
    // Eliminate freak matches (e.g. blank lines)
    diff_cleanupSemantic(diffs);

    // Rediff any replacement blocks, this time character-by-character.
    // Add a dummy entry at the end.
    diffs.add(new Diff(Operation.EQUAL, ""));
    int count_delete = 0;
    int count_insert = 0;
    String text_delete = "";
    String text_insert = "";
    ListIterator<Diff> pointer = diffs.listIterator();
    Diff thisDiff = pointer.next();
    while (thisDiff != null) {
        switch (thisDiff.operation) {
        case INSERT:
            count_insert++;
            text_insert += thisDiff.text;
            break;
        case DELETE:
            count_delete++;
            text_delete += thisDiff.text;
            break;
        case EQUAL:
            // Upon reaching an equality, check for prior redundancies.
            if (count_delete >= 1 && count_insert >= 1) {
                // Delete the offending records and add the merged ones.
                pointer.previous();
                for (int j = 0; j < count_delete + count_insert; j++) {
                    pointer.previous();
                    pointer.remove();
                }
                for (Diff newDiff : diff_main(text_delete, text_insert,
                        false, deadline)) {
                    pointer.add(newDiff);
                }
            }
            count_insert = 0;
            count_delete = 0;
            text_delete = "";
            text_insert = "";
            break;
        }
        thisDiff = pointer.hasNext() ? pointer.next() : null;
    }
    diffs.removeLast(); // Remove the dummy entry at the end.

    return diffs;
}
 
Example 17
Source File: HeapAndrew.java    From algorithms-nutshell-2ed with MIT License 4 votes vote down vote up
/**
 * Use Andrew's algorithm to return the computed convex hull for 
 * the input set of points. Implementation uses a Binary Heap rather
 * than sorting initial set.
 * 
 * @param points   a set of (n &ge; 3) two dimensional points.
 */
public IPoint[] compute (IPoint[] points) {
	int n = points.length;
	if (n < 3) { return points; }
	
	ExternalBinaryHeap<IPoint> heap = new ExternalBinaryHeap<IPoint> (n, IPoint.xy_sorter);

	// add points into sorted structure, using xy_sorter
	for (IPoint p : points) { heap.insert(p); }
	
	// While computing upper hull, build list of points in reverse order.
	LinkedList<IPoint> list = new LinkedList<IPoint>();
	IPoint p1 = heap.smallest();
	list.addFirst(p1);
	IPoint p2 = heap.smallest();
	list.addFirst(p2);
	PartialHull upper = new PartialHull(p1, p2);
	while (!heap.isEmpty()) {
		p1 = heap.smallest();
		list.addFirst(p1);
		
		upper.add(p1);
		while (upper.hasThree() && upper.areLastThreeNonRight()) {
			upper.removeMiddleOfLastThree();
		}
	}
	
	// process over the points and compute lower hull
	Iterator<IPoint> it = list.listIterator();
	p1 = it.next();
	p2 = it.next();
	PartialHull lower = new PartialHull(p1, p2);
	while (it.hasNext()) {
		p1 = it.next();
		
		lower.add(p1);
		while (lower.hasThree() && lower.areLastThreeNonRight()) {
			lower.removeMiddleOfLastThree();
		}
	}
	
	// remove duplicate end points when combining.
	IPoint[]hull = new IPoint[upper.size()+lower.size()-2];
	int idx = 0;
	Iterator<IPoint> pit = upper.points();
	while (pit.hasNext()) { hull[idx++] = pit.next();	}
	pit = lower.points();
	pit.next(); // skip point that already has been added
	while (idx < hull.length) { hull[idx++] = pit.next(); }
	return hull;
}
 
Example 18
Source File: diff_match_patch.java    From SAMLRaider with MIT License 4 votes vote down vote up
/**
 * Do a quick line-level diff on both strings, then rediff the parts for
 * greater accuracy.
 * This speedup can produce non-minimal diffs.
 * @param text1 Old string to be diffed.
 * @param text2 New string to be diffed.
 * @param deadline Time when the diff should be complete by.
 * @return Linked List of Diff objects.
 */
private LinkedList<Diff> diff_lineMode(String text1, String text2,
                                       long deadline) {
  // Scan the text on a line-by-line basis first.
  LinesToCharsResult b = diff_linesToChars(text1, text2);
  text1 = b.chars1;
  text2 = b.chars2;
  List<String> linearray = b.lineArray;

  LinkedList<Diff> diffs = diff_main(text1, text2, false, deadline);

  // Convert the diff back to original text.
  diff_charsToLines(diffs, linearray);
  // Eliminate freak matches (e.g. blank lines)
  diff_cleanupSemantic(diffs);

  // Rediff any replacement blocks, this time character-by-character.
  // Add a dummy entry at the end.
  diffs.add(new Diff(Operation.EQUAL, ""));
  int count_delete = 0;
  int count_insert = 0;
  String text_delete = "";
  String text_insert = "";
  ListIterator<Diff> pointer = diffs.listIterator();
  Diff thisDiff = pointer.next();
  while (thisDiff != null) {
    switch (thisDiff.operation) {
    case INSERT:
      count_insert++;
      text_insert += thisDiff.text;
      break;
    case DELETE:
      count_delete++;
      text_delete += thisDiff.text;
      break;
    case EQUAL:
      // Upon reaching an equality, check for prior redundancies.
      if (count_delete >= 1 && count_insert >= 1) {
        // Delete the offending records and add the merged ones.
        pointer.previous();
        for (int j = 0; j < count_delete + count_insert; j++) {
          pointer.previous();
          pointer.remove();
        }
        for (Diff newDiff : diff_main(text_delete, text_insert, false,
            deadline)) {
          pointer.add(newDiff);
        }
      }
      count_insert = 0;
      count_delete = 0;
      text_delete = "";
      text_insert = "";
      break;
    }
    thisDiff = pointer.hasNext() ? pointer.next() : null;
  }
  diffs.removeLast();  // Remove the dummy entry at the end.

  return diffs;
}
 
Example 19
Source File: diff_match_patch.java    From QuranyApp with Apache License 2.0 4 votes vote down vote up
/**
 * Look for single edits surrounded on both sides by equalities
 * which can be shifted sideways to align the edit to a word boundary.
 * e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
 *
 * @param diffs LinkedList of Diff objects.
 */
public void diff_cleanupSemanticLossless(LinkedList<Diff> diffs) {
    String equality1, edit, equality2;
    String commonString;
    int commonOffset;
    int score, bestScore;
    String bestEquality1, bestEdit, bestEquality2;
    // Create a new iterator at the start.
    ListIterator<Diff> pointer = diffs.listIterator();
    Diff prevDiff = pointer.hasNext() ? pointer.next() : null;
    Diff thisDiff = pointer.hasNext() ? pointer.next() : null;
    Diff nextDiff = pointer.hasNext() ? pointer.next() : null;
    // Intentionally ignore the first and last element (don't need checking).
    while (nextDiff != null) {
        if (prevDiff.operation == Operation.EQUAL &&
                nextDiff.operation == Operation.EQUAL) {
            // This is a single edit surrounded by equalities.
            equality1 = prevDiff.text;
            edit = thisDiff.text;
            equality2 = nextDiff.text;

            // First, shift the edit as far left as possible.
            commonOffset = diff_commonSuffix(equality1, edit);
            if (commonOffset != 0) {
                commonString = edit.substring(edit.length() - commonOffset);
                equality1 = equality1.substring(0, equality1.length() - commonOffset);
                edit = commonString + edit.substring(0, edit.length() - commonOffset);
                equality2 = commonString + equality2;
            }

            // Second, step character by character right, looking for the best fit.
            bestEquality1 = equality1;
            bestEdit = edit;
            bestEquality2 = equality2;
            bestScore = diff_cleanupSemanticScore(equality1, edit)
                    + diff_cleanupSemanticScore(edit, equality2);
            while (edit.length() != 0 && equality2.length() != 0
                    && edit.charAt(0) == equality2.charAt(0)) {
                equality1 += edit.charAt(0);
                edit = edit.substring(1) + equality2.charAt(0);
                equality2 = equality2.substring(1);
                score = diff_cleanupSemanticScore(equality1, edit)
                        + diff_cleanupSemanticScore(edit, equality2);
                // The >= encourages trailing rather than leading whitespace on edits.
                if (score >= bestScore) {
                    bestScore = score;
                    bestEquality1 = equality1;
                    bestEdit = edit;
                    bestEquality2 = equality2;
                }
            }

            if (!prevDiff.text.equals(bestEquality1)) {
                // We have an improvement, save it back to the diff.
                if (bestEquality1.length() != 0) {
                    prevDiff.text = bestEquality1;
                } else {
                    pointer.previous(); // Walk past nextDiff.
                    pointer.previous(); // Walk past thisDiff.
                    pointer.previous(); // Walk past prevDiff.
                    pointer.remove(); // Delete prevDiff.
                    pointer.next(); // Walk past thisDiff.
                    pointer.next(); // Walk past nextDiff.
                }
                thisDiff.text = bestEdit;
                if (bestEquality2.length() != 0) {
                    nextDiff.text = bestEquality2;
                } else {
                    pointer.remove(); // Delete nextDiff.
                    nextDiff = thisDiff;
                    thisDiff = prevDiff;
                }
            }
        }
        prevDiff = thisDiff;
        thisDiff = nextDiff;
        nextDiff = pointer.hasNext() ? pointer.next() : null;
    }
}
 
Example 20
Source File: DiffMatchPatch.java    From titan-hotfix with Apache License 2.0 4 votes vote down vote up
/**
 * Look for single edits surrounded on both sides by equalities
 * which can be shifted sideways to align the edit to a word boundary.
 * e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
 *
 * @param diffs LinkedList of Diff objects.
 */
public void diffCleanupSemanticLossless(LinkedList<Diff> diffs) {
    String equality1;
    String edit;
    String equality2;
    String commonString;
    int commonOffset;
    int score;
    int bestScore;
    String bestEquality1;
    String bestEdit;
    String bestEquality2;
    // Create a new iterator at the start.
    ListIterator<Diff> pointer = diffs.listIterator();
    Diff prevDiff = pointer.hasNext() ? pointer.next() : null;
    Diff thisDiff = pointer.hasNext() ? pointer.next() : null;
    Diff nextDiff = pointer.hasNext() ? pointer.next() : null;
    // Intentionally ignore the first and last element (don't need checking).
    while (nextDiff != null) {
        if (prevDiff.operation == Operation.EQUAL
                && nextDiff.operation == Operation.EQUAL) {
            // This is a single edit surrounded by equalities.
            equality1 = prevDiff.text;
            edit = thisDiff.text;
            equality2 = nextDiff.text;

            // First, shift the edit as far left as possible.
            commonOffset = diffCommonSuffix(equality1, edit);
            if (commonOffset != 0) {
                commonString = edit.substring(edit.length() - commonOffset);
                equality1 = equality1.substring(0, equality1.length() - commonOffset);
                edit = commonString + edit.substring(0, edit.length() - commonOffset);
                equality2 = commonString + equality2;
            }

            // Second, step character by character right, looking for the best fit.
            bestEquality1 = equality1;
            bestEdit = edit;
            bestEquality2 = equality2;
            bestScore = diffCleanupSemanticScore(equality1, edit)
                    + diffCleanupSemanticScore(edit, equality2);
            while (edit.length() != 0 && equality2.length() != 0
                    && edit.charAt(0) == equality2.charAt(0)) {
                equality1 += edit.charAt(0);
                edit = edit.substring(1) + equality2.charAt(0);
                equality2 = equality2.substring(1);
                score = diffCleanupSemanticScore(equality1, edit)
                        + diffCleanupSemanticScore(edit, equality2);
                // The >= encourages trailing rather than leading whitespace on edits.
                if (score >= bestScore) {
                    bestScore = score;
                    bestEquality1 = equality1;
                    bestEdit = edit;
                    bestEquality2 = equality2;
                }
            }

            if (!prevDiff.text.equals(bestEquality1)) {
                // We have an improvement, save it back to the diff.
                if (bestEquality1.length() != 0) {
                    prevDiff.text = bestEquality1;
                } else {
                    pointer.previous(); // Walk past nextDiff.
                    pointer.previous(); // Walk past thisDiff.
                    pointer.previous(); // Walk past prevDiff.
                    pointer.remove(); // Delete prevDiff.
                    pointer.next(); // Walk past thisDiff.
                    pointer.next(); // Walk past nextDiff.
                }
                thisDiff.text = bestEdit;
                if (bestEquality2.length() != 0) {
                    nextDiff.text = bestEquality2;
                } else {
                    pointer.remove(); // Delete nextDiff.
                    nextDiff = thisDiff;
                    thisDiff = prevDiff;
                }
            }
        }
        prevDiff = thisDiff;
        thisDiff = nextDiff;
        nextDiff = pointer.hasNext() ? pointer.next() : null;
    }
}