|
| 1 | +/* Copyright (c) 2000-2006 hamcrest.org |
| 2 | + */ |
| 3 | +package org.hamcrest.number; |
| 4 | + |
| 5 | +import static org.hamcrest.core.IsEqual.eq; |
| 6 | +import static org.hamcrest.core.Or.or; |
| 7 | +import org.hamcrest.Matcher; |
| 8 | +import org.hamcrest.Description; |
| 9 | +import org.hamcrest.Factory; |
| 10 | + |
| 11 | +/** |
| 12 | + * Is the value less than or greater than another {@link java.lang.Comparable} value? |
| 13 | + */ |
| 14 | +public class IsComparableTo<T extends Comparable> implements Matcher<T> { |
| 15 | + |
| 16 | + public static enum Operator { |
| 17 | + LESS_THAN, |
| 18 | + GREATER_THAN |
| 19 | + } |
| 20 | + |
| 21 | + private final Comparable<T> compareTo; |
| 22 | + private final Operator operator; |
| 23 | + |
| 24 | + public IsComparableTo(Comparable<T> compareTo, Operator operator) { |
| 25 | + this.compareTo = compareTo; |
| 26 | + this.operator = operator; |
| 27 | + } |
| 28 | + |
| 29 | + public boolean match(T item) { |
| 30 | + int comparison = compareTo.compareTo(item); |
| 31 | + return operator == Operator.GREATER_THAN ? comparison < 0 : comparison > 0; |
| 32 | + } |
| 33 | + |
| 34 | + public void describeTo(Description description) { |
| 35 | + description.appendText("a value "); |
| 36 | + description.appendText(operator == Operator.GREATER_THAN ? "greater than " : "less than "); |
| 37 | + description.appendValue(compareTo); |
| 38 | + } |
| 39 | + |
| 40 | + @Factory |
| 41 | + public static <T extends Comparable> Matcher<Comparable<T>> greaterThan(Comparable<T> value) { |
| 42 | + return comparableTo(value, Operator.GREATER_THAN); |
| 43 | + } |
| 44 | + |
| 45 | + @Factory |
| 46 | + public static <T extends Comparable> Matcher<Comparable<T>> greaterThanOrEqualTo(Comparable<T> value) { |
| 47 | + return or(greaterThan(value), eq(value)); |
| 48 | + } |
| 49 | + |
| 50 | + @Factory |
| 51 | + public static <T extends Comparable> Matcher<Comparable<T>> lessThan(Comparable<T> value) { |
| 52 | + return comparableTo(value, Operator.LESS_THAN); |
| 53 | + } |
| 54 | + |
| 55 | + @Factory |
| 56 | + public static <T extends Comparable> Matcher<Comparable<T>> lessThanOrEqualTo(Comparable<T> value) { |
| 57 | + return or(lessThan(value), eq(value)); |
| 58 | + } |
| 59 | + |
| 60 | + private static <T extends Comparable> Matcher<Comparable<T>> comparableTo(Comparable<T> value, Operator operator) { |
| 61 | + return new IsComparableTo(value, operator); |
| 62 | + } |
| 63 | + |
| 64 | +} |
0 commit comments