1 /* 2 * CDDL HEADER START 3 * 4 * The contents of this file are subject to the terms of the 5 * Common Development and Distribution License (the "License"). 6 * You may not use this file except in compliance with the License. 7 * 8 * See LICENSE.txt included in this distribution for the specific 9 * language governing permissions and limitations under the License. 10 * 11 * When distributing Covered Code, include this CDDL HEADER in each 12 * file and include the License file at LICENSE.txt. 13 * If applicable, add the following below this CDDL HEADER, with the 14 * fields enclosed by brackets "[]" replaced with your own identifying 15 * information: Portions Copyright [yyyy] [name of copyright owner] 16 * 17 * CDDL HEADER END 18 */ 19 20 /* 21 * Copyright (c) 2018, Chris Fraire <cfraire@me.com>. 22 */ 23 package org.opengrok.indexer.search.context; 24 25 import java.util.Comparator; 26 27 /** 28 * Represents a {@link Comparator} for {@link PhraseHighlight}. 29 */ 30 public class PhraseHighlightComparator implements Comparator<PhraseHighlight> { 31 32 public static final PhraseHighlightComparator INSTANCE = new PhraseHighlightComparator(); 33 34 /** 35 * Compares two {@link PhraseHighlight} instances for order by first 36 * comparing using {@link Integer#compare(int, int)} the 37 * {@link PhraseHighlight#lineStart} values of {@code o1} and {@code o2} and 38 * subsequently, if identical, comparing the {@link PhraseHighlight#lineEnd} 39 * values of {@code o2} and {@code o1} (i.e. inverted). 40 * <p>The ordering allows to iterate through a collection afterward and 41 * easily subsume where necessary a {@link PhraseHighlight} instance into 42 * its immediate predecessor. 43 * @param o1 a required instance 44 * @param o2 a required instance 45 * @return a negative integer, zero, or a positive integer as the first 46 * argument is less than, equal to, or greater than the second 47 */ 48 @Override compare(PhraseHighlight o1, PhraseHighlight o2)49 public int compare(PhraseHighlight o1, PhraseHighlight o2) { 50 int cmp; 51 if (o1.getLineStart() < 0) { 52 if (o2.getLineStart() >= 0) { 53 return -1; 54 } 55 cmp = 0; 56 } else if (o2.getLineStart() < 0) { 57 return 1; 58 } else { 59 cmp = Integer.compare(o1.getLineStart(), o2.getLineStart()); 60 } 61 if (cmp != 0) { 62 return cmp; 63 } 64 cmp = Integer.compare(o2.getLineEnd(), o1.getLineEnd()); 65 return cmp; 66 } 67 68 /** Private to enforce singleton. */ PhraseHighlightComparator()69 private PhraseHighlightComparator() { 70 } 71 } 72