Skip to content

Commit

Permalink
refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
adamnemecek committed Jan 5, 2025
1 parent 8d6129c commit 497f283
Showing 1 changed file with 15 additions and 14 deletions.
29 changes: 15 additions & 14 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -339,37 +339,38 @@ pub fn partial_ge<T: PartialOrd>(a: &T, b: &T) -> bool {
/// Return the minimum of `a` and `b` if they are comparable.
#[inline]
pub fn partial_min<'a, T: PartialOrd>(a: &'a T, b: &'a T) -> Option<&'a T> {
a.partial_cmp(b).map(|ord| if ord.is_ge() { b } else { a })
a.partial_cmp(b).map(|ord| if ord.is_gt() { b } else { a })
}

/// Return the maximum of `a` and `b` if they are comparable.
#[inline]
pub fn partial_max<'a, T: PartialOrd>(a: &'a T, b: &'a T) -> Option<&'a T> {
a.partial_cmp(b).map(|ord| if ord.is_le() { b } else { a })
a.partial_cmp(b).map(|ord| if ord.is_lt() { b } else { a })
}

/// Clamp `value` between `min` and `max`. Returns `None` if `value` is not comparable to
/// `min` or `max`.
#[inline]
pub fn partial_clamp<'a, T: PartialOrd>(value: &'a T, min: &'a T, max: &'a T) -> Option<&'a T> {
if let (Some(cmp_min), Some(cmp_max)) = (value.partial_cmp(min), value.partial_cmp(max)) {
if cmp_min == Ordering::Less {
Some(min)
} else if cmp_max == Ordering::Greater {
Some(max)
} else {
Some(value)
}
} else {
None
}
value
.partial_cmp(min)
.zip(value.partial_cmp(max))
.map(|(cmp_min, cmp_max)| {
if cmp_min.is_lt() {
min
} else if cmp_max.is_gt() {
max
} else {
value
}
})
}

/// Sorts two values in increasing order using a partial ordering.
#[inline]
pub fn partial_sort2<'a, T: PartialOrd>(a: &'a T, b: &'a T) -> Option<(&'a T, &'a T)> {
a.partial_cmp(b)
.map(|ord| if ord.is_le() { (a, b) } else { (b, a) })
.map(|ord| if ord.is_lt() { (a, b) } else { (b, a) })
}

/*
Expand Down

0 comments on commit 497f283

Please sign in to comment.