lokacore 0.3.0

Lokathor's core-only odds and ends
Documentation
use lokacore::*;

#[test]
fn test_branchless_abs() {
  const _ABS_IS_CONST: i8 = branchless_abs!(-7, i8);
  for x in core::i8::MIN..=core::i8::MAX {
    assert_eq!(branchless_abs!(x, i8), x.wrapping_abs());
  }
}

#[test]
fn test_branchless_min_and_max() {
  const _MIN_IS_CONST: u8 = branchless_min!(2, 3, u8);
  const _MAX_IS_CONST: u8 = branchless_max!(8, 10, u8);
  for x in core::u8::MIN..=core::u8::MAX {
    for y in core::u8::MIN..=core::u8::MAX {
      assert_eq!(branchless_min!(x, y, u8), x.min(y));
      assert_eq!(branchless_max!(x, y, u8), x.max(y));
    }
  }
  for x in core::i8::MIN..=core::i8::MAX {
    for y in core::i8::MIN..=core::i8::MAX {
      assert_eq!(branchless_min!(x, y, i8), x.min(y));
      assert_eq!(branchless_max!(x, y, i8), x.max(y));
    }
  }
}

#[test]
#[allow(clippy::bad_bit_mask)]
#[allow(clippy::assertions_on_constants)]
fn test_branchless_pow_of_2_or_zero() {
  const ZERO_COUNTS: bool = branchless_pow_of_2_or_zero!(0_u8);
  assert!(ZERO_COUNTS);
  for x in 1..=core::u8::MAX {
    assert_eq!(branchless_pow_of_2_or_zero!(x), x.is_power_of_two());
  }
}

#[test]
fn test_branchless_opposite_sign() {
  const _MACRO_IS_CONST: bool = branchless_opposite_sign!(0, 0);
  for x in core::i8::MIN..=core::i8::MAX {
    for y in core::i8::MIN..=core::i8::MAX {
      assert_eq!(
        branchless_opposite_sign!(x, y),
        if x >= 0 { y < 0 } else { y >= 0 }
      );
    }
  }
}

#[test]
fn test_branchless_force_bits() {
  const ONE: u32 = branchless_force_bits!(true, 0b1, 0, u32);
  assert_eq!(ONE, 1);
  const FIVE: u32 = branchless_force_bits!(false, 0b10, 0b111, u32);
  assert_eq!(FIVE, 0b101);
}

#[test]
fn test_branchless_negate() {
  const ONE: i32 = branchless_negate!(true, -1, i32);
  assert_eq!(ONE, 1);
  const NEG_ONE: i32 = branchless_negate!(true, 1, i32);
  assert_eq!(NEG_ONE, -1);
  const TWO: i32 = branchless_negate!(false, 2, i32);
  assert_eq!(TWO, 2);
}

#[test]
fn test_branchless_masked_merge() {
  const A: u32 = branchless_masked_merge!(core::u32::MAX, 0, 0b1);
  assert_eq!(A, 1);
  const B: u32 = branchless_masked_merge!(core::u32::MAX, 0, 0b10101);
  assert_eq!(B, 0b10101);

  const C: u32 = branchless_masked_merge!(0, core::u32::MAX, 0b1);
  assert_eq!(C, core::u32::MAX - 1);
}