semisafe 1.2.0

Semi-safe utilities for performance-critical Rust
Documentation
//! Provides semi-safe helpers for comparison operations.

use std::hint::assert_unchecked;

/// Clamps `val` to the range `[min, max]` without checking that `min <= max`
/// in release builds.
///
/// Use this only when surrounding code guarantees that `max >= min`. In debug
/// builds this uses [`debug_assert!`] to verify the precondition and panics on
/// violation. In release builds, passing `max < min` causes undefined behavior.
///
/// # Panics
///
/// Panics in debug builds if `max < min`.
///
/// # Examples
///
/// ```
/// assert_eq!(semisafe::cmp::clamp(5, 0, 10), 5);
/// assert_eq!(semisafe::cmp::clamp(-1, 0, 10), 0);
/// assert_eq!(semisafe::cmp::clamp(15, 0, 10), 10);
/// ```
pub fn clamp<T: PartialOrd>(val: T, min: T, max: T) -> T {
    debug_assert!(max >= min);
    unsafe {
        assert_unchecked(max >= min);
    }

    if val < min {
        min
    } else if val > max {
        max
    } else {
        val
    }
}