fix: reject inverted range when comparer returns negative other than -1
RangeValidator's constructor guarded against an inverted range with
comparer.Compare(to, from) == -1. The IComparer<T>/IComparable<T> contract
only guarantees the sign of the result, not the magnitude, so the guard
silently failed for comparers returning other negatives, e.g. char.CompareTo
('a'.CompareTo('c') == -2) or custom comparers that return x - y. This let
InclusiveBetween('c', 'a') build a validator that can never pass instead of
throwing, unlike the int case which happens to return -1.
Compare against < 0 to honor the comparer contract. Add char-bound throw
tests to the inclusive and exclusive between suites.
This commit is contained in:
1 parent
cbfaed6ee6
commit
e9c920f846
3 files changed
+14
-1
No files matched your search
@@ -34,7 +34,8 @@ public abstract class RangeValidator<T, TProperty> : PropertyValidator<T, TPrope
|
||||
|
||||
_explicitComparer = comparer;
|
||||
|
||||
if (comparer.Compare(to, from) == -1) {
|
||||
// IComparer<T> only guarantees the sign, not the magnitude.
|
||||
if (comparer.Compare(to, from) < 0) {
|
||||
throw new ArgumentOutOfRangeException(nameof(to), "To should be larger than from.");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user