blob: ba78dc81cabecc19c59a270fdaf2a3b50c28e601 [file] [log] [blame]
/*=============================================================================#
# Copyright (c) 2013, 2020 Stephan Wahlbrink and others.
#
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 2.0 which is available at
# https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
# which is available at https://www.apache.org/licenses/LICENSE-2.0.
#
# SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
#
# Contributors:
# Stephan Wahlbrink <sw@wahlbrink.eu> - initial API and implementation
#=============================================================================*/
package org.eclipse.statet.ltk.model.core.util;
import java.util.Comparator;
import com.ibm.icu.text.Collator;
import org.eclipse.statet.ltk.core.LTKUtils;
import org.eclipse.statet.ltk.model.core.elements.IModelElement;
import org.eclipse.statet.ltk.model.core.elements.ISourceElement;
import org.eclipse.statet.ltk.model.core.elements.ISourceUnit;
public class ElementComparator implements Comparator<IModelElement> {
private final Collator unitComparator;
private final Collator elementComparator;
public ElementComparator() {
this(Collator.getInstance());
}
public ElementComparator(final Collator elementComparator) {
this.unitComparator= Collator.getInstance();
this.elementComparator= elementComparator;
}
@Override
public int compare(final IModelElement e1, final IModelElement e2) {
final ISourceUnit u1= LTKUtils.getSourceUnit(e1);
final ISourceUnit u2= LTKUtils.getSourceUnit(e2);
int result= 0;
if (u1 != null && u2 != null) {
if (u1 != u2) {
result= this.unitComparator.compare(u1.getId(), u2.getId());
}
if (result != 0) {
return result;
}
if (e1 instanceof ISourceElement) {
if (e2 instanceof ISourceElement) {
return compareSourceElementsInUnit((ISourceElement) e1, (ISourceElement) e2);
}
return -1000000;
}
else if (e2 instanceof ISourceElement) { // && !(e1 instanceof ISourceUnit)
return 1000000;
}
else {
return this.elementComparator.compare(e1.getId(), e2.getId());
}
}
if (u1 == null && u2 != null) {
return Integer.MAX_VALUE;
}
if (u2 == null && u1 != null) {
return Integer.MIN_VALUE;
}
return 0;
}
protected int compareSourceElementsInUnit(final ISourceElement e1, final ISourceElement e2) {
return e1.getSourceRange().getStartOffset() - e2.getSourceRange().getStartOffset();
}
}