use crate::{
Execution, Portability, Subnormals, Validation,
bf16::{MAX_BF16, ceil_bf16, decode_bf16_finite, expand_bf16, floor_bf16},
};
const ELIDE_LIMIT: f32 = 125.0;
pub const MAX_EXP_BOUND: f32 = MAX_BF16;
const MAGIC: u128 = 0xA;
const DOMAIN_SHIFT: u32 = 4;
const SUBNORM_SHIFT: u32 = 9;
const VALIDATION_SHIFT: u32 = 12;
const PREC_SHIFT: u32 = 15;
const PORTABILITY_SHIFT: u32 = 18;
const EXECUTION_SHIFT: u32 = 20;
const HAS_CUSTOM_BASE: u128 = 1 << 22;
const EXP_MODE_SHIFT: u32 = 23;
const SATURATE_OUTPUT: u128 = 1 << 25;
const RESERVED_MASK: u128 = ((1_u128 << 38) - 1) << 26;
const BASE_LO_SHIFT: u32 = 64;
const BASE_HI_SHIFT: u32 = 80;
const EXP_SLOT_SHIFT: u32 = 96;
const fn abs(x: f32) -> f32 {
if x < 0.0 { -x } else { x }
}
const fn canon_zero(x: f32) -> f32 {
if x == 0.0 { 0.0 } else { x }
}
const fn exponent_of(x: f32) -> i32 {
((x.to_bits() >> 23) & 0xff) as i32 - 127
}
const fn is_nonzero_subnormal_only_interval(lo: f32, hi: f32) -> bool {
(lo > 0.0 && hi < f32::MIN_POSITIVE) || (lo > -f32::MIN_POSITIVE && hi < 0.0)
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum PowfDomain {
#[default]
PositiveNormals,
NonNegative,
Unit,
PositiveUnit,
UnitEncode,
SdrGamma,
HdrGamma,
PositiveGamma,
PqRatio,
AllFloats,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum PowfPrecision {
#[default]
Midp,
Lowp,
Highp,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ExpSpec {
Default,
RangeBf16(u16, u16),
ConstF32(u32),
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PowfOptions {
domain: PowfDomain,
custom_base: Option<(u16, u16)>,
exp_spec: ExpSpec,
subnormals: Subnormals,
saturate: bool,
precision: PowfPrecision,
portability: Portability,
validation: Validation,
execution: Execution,
}
impl Default for PowfOptions {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl PowfOptions {
pub const fn new() -> Self {
Self {
domain: PowfDomain::PositiveNormals,
custom_base: None,
exp_spec: ExpSpec::Default,
subnormals: Subnormals::FlushOrClamp,
saturate: false,
precision: PowfPrecision::Midp,
portability: Portability::BitExact,
validation: Validation::Checked,
execution: Execution::Upgrade,
}
}
pub const fn domain(mut self, domain: PowfDomain) -> Self {
self.domain = domain;
self.custom_base = None;
if matches!(domain, PowfDomain::AllFloats) {
self.exp_spec = ExpSpec::Default;
self.subnormals = Subnormals::Reject;
}
self
}
pub const fn base_range(mut self, lo: f32, hi: f32) -> Self {
assert!(
lo >= f32::MIN_POSITIVE && lo <= hi && hi <= MAX_BF16,
"base range must be positive normal within MAX_BF16 (0x7f7f_0000) with lo <= hi"
);
self.custom_base = Some((floor_bf16(lo), ceil_bf16(hi)));
self
}
pub const fn exponent_range(mut self, lo: f32, hi: f32) -> Self {
assert!(
lo <= hi && abs(lo) <= MAX_BF16 && abs(hi) <= MAX_BF16,
"exponent range must be finite within ±MAX_BF16 (0x7f7f_0000) with lo <= hi"
);
self.exp_spec = ExpSpec::RangeBf16(floor_bf16(lo), ceil_bf16(hi));
self
}
pub const fn const_exponent(mut self, n: f32) -> Self {
assert!(
n.is_finite(),
"const_exponent requires a finite f32 exponent"
);
self.exp_spec = ExpSpec::ConstF32(canon_zero(n).to_bits());
self
}
pub const fn subnormals(mut self, policy: Subnormals) -> Self {
self.subnormals = policy;
self
}
pub const fn reject_subnormals(self) -> Self {
self.subnormals(Subnormals::Reject)
}
pub const fn flush_or_clamp_subnormals(self) -> Self {
self.subnormals(Subnormals::FlushOrClamp)
}
pub const fn admit_subnormals(self) -> Self {
self.subnormals(Subnormals::Normalize)
}
pub const fn admit_zero(mut self) -> Self {
self.domain = match self.domain {
PowfDomain::PositiveNormals => PowfDomain::NonNegative,
PowfDomain::PositiveUnit => PowfDomain::Unit,
PowfDomain::PositiveGamma => PowfDomain::HdrGamma,
other => other,
};
self
}
pub const fn admit_zero_base(self) -> Self {
self.admit_zero()
}
pub const fn gamma_domain(mut self) -> Self {
if !matches!(self.domain, PowfDomain::AllFloats) {
self.domain = PowfDomain::HdrGamma;
self.custom_base = None;
self.exp_spec = ExpSpec::Default;
self.subnormals = Subnormals::FlushOrClamp;
}
self
}
pub const fn gamma(self) -> Self {
self.gamma_domain()
}
pub const fn positive_gamma_domain(mut self) -> Self {
if !matches!(self.domain, PowfDomain::AllFloats) {
self.domain = PowfDomain::PositiveGamma;
self.custom_base = None;
self.exp_spec = ExpSpec::Default;
self.subnormals = Subnormals::FlushOrClamp;
}
self
}
pub const fn positive_gamma(self) -> Self {
self.positive_gamma_domain()
}
pub const fn unit_gamma_domain(mut self) -> Self {
if !matches!(self.domain, PowfDomain::AllFloats) {
self.domain = PowfDomain::SdrGamma;
self.custom_base = None;
self.exp_spec = ExpSpec::Default;
self.subnormals = Subnormals::FlushOrClamp;
}
self
}
pub const fn srgb_encode_domain(mut self) -> Self {
if !matches!(self.domain, PowfDomain::AllFloats) {
self.domain = PowfDomain::UnitEncode;
self.custom_base = None;
self.exp_spec = ExpSpec::Default;
self.subnormals = Subnormals::FlushOrClamp;
}
self
}
pub const fn admit_all_floats(self) -> Self {
self.domain(PowfDomain::AllFloats)
}
pub const fn full_domain(self) -> Self {
self.admit_all_floats()
}
pub const fn saturate_output(mut self) -> Self {
self.saturate = true;
self
}
pub const fn clamp_output(self) -> Self {
self.saturate_output()
}
pub const fn precision(mut self, value: PowfPrecision) -> Self {
self.precision = value;
self
}
pub const fn lowp(self) -> Self {
self.precision(PowfPrecision::Lowp)
}
pub const fn midp(self) -> Self {
self.precision(PowfPrecision::Midp)
}
pub const fn highp(self) -> Self {
self.precision(PowfPrecision::Highp)
}
pub const fn portability(mut self, value: Portability) -> Self {
self.portability = value;
self
}
pub const fn bit_exact(self) -> Self {
self.portability(Portability::BitExact)
}
pub const fn backend_dependent(self) -> Self {
self.portability(Portability::BackendDependent)
}
pub const fn validation(mut self, value: Validation) -> Self {
self.validation = value;
self
}
pub const fn error_on_out_of_bounds(self) -> Self {
self.validation(Validation::Checked)
}
pub const fn checked(self) -> Self {
self.error_on_out_of_bounds()
}
pub const fn clamp_out_of_bounds(self) -> Self {
self.validation(Validation::ClampOutOfBounds)
}
pub const fn clamp_finite(self) -> Self {
self.validation(Validation::ClampFinite)
}
pub const fn assume_in_bounds(self) -> Self {
self.validation(Validation::AssumeValid)
}
pub const fn unchecked(self) -> Self {
self.assume_in_bounds()
}
pub const fn execution(mut self, value: Execution) -> Self {
self.execution = value;
self
}
pub const fn upgrade(self) -> Self {
self.execution(Execution::Upgrade)
}
pub const fn caller(self) -> Self {
self.execution(Execution::Caller)
}
pub const fn selected_domain(&self) -> PowfDomain {
self.domain
}
pub const fn subnormals_policy(&self) -> Subnormals {
if self.is_full() {
Subnormals::Normalize
} else {
self.subnormals
}
}
pub const fn has_const_exponent(&self) -> bool {
matches!(self.exp_spec, ExpSpec::ConstF32(_))
}
pub const fn const_exponent_value(&self) -> Option<f32> {
match self.exp_spec {
ExpSpec::ConstF32(bits) => {
let n = f32::from_bits(bits);
if self.flushes_subnormals() {
let abs_b = bits & 0x7fff_ffff;
if abs_b != 0 && abs_b < 0x0080_0000 {
return Some(0.0);
}
}
Some(n)
}
_ => None,
}
}
pub(crate) const fn is_full(&self) -> bool {
matches!(self.domain, PowfDomain::AllFloats)
}
pub(crate) const fn admits_zero(&self) -> bool {
matches!(
self.domain,
PowfDomain::NonNegative
| PowfDomain::Unit
| PowfDomain::UnitEncode
| PowfDomain::SdrGamma
| PowfDomain::HdrGamma
)
}
pub(crate) const fn admits_subnormals(&self) -> bool {
!self.is_full() && matches!(self.subnormals, Subnormals::Normalize)
}
pub(crate) const fn flushes_subnormals(&self) -> bool {
!self.is_full() && matches!(self.subnormals, Subnormals::FlushOrClamp)
}
pub(crate) const fn base_bounds(&self) -> Option<(f32, f32)> {
if self.is_full() {
return None;
}
if let Some((lo, hi)) = self.custom_base {
return Some((expand_bf16(lo), expand_bf16(hi)));
}
match self.domain {
PowfDomain::PositiveNormals | PowfDomain::NonNegative | PowfDomain::AllFloats => None,
PowfDomain::Unit | PowfDomain::PositiveUnit | PowfDomain::UnitEncode => {
Some((f32::MIN_POSITIVE, 1.0))
}
PowfDomain::SdrGamma => Some((1.0 / 65_536.0, 1.0)),
PowfDomain::HdrGamma | PowfDomain::PositiveGamma => Some((1.0 / 65_536.0, 65_536.0)),
PowfDomain::PqRatio => Some((107.0 / 128.0, 1.0)),
}
}
pub(crate) const fn exponent_bounds(&self) -> Option<(f32, f32)> {
if self.is_full() {
return None;
}
match self.exp_spec {
ExpSpec::RangeBf16(lo, hi) => Some((expand_bf16(lo), expand_bf16(hi))),
ExpSpec::ConstF32(_) => {
let Some(n) = self.const_exponent_value() else {
return None;
};
Some((n, n))
}
ExpSpec::Default => match self.domain {
PowfDomain::UnitEncode => Some((0.0, 0.99)),
PowfDomain::SdrGamma | PowfDomain::HdrGamma | PowfDomain::PositiveGamma => {
Some((0.0, 4.0))
}
PowfDomain::PqRatio => Some((0.0, 80.0)),
_ => None,
},
}
}
pub(crate) const fn alg_kind(&self) -> u8 {
if self.is_full() {
return 0;
}
let Some(n) = self.const_exponent_value() else {
return 0;
};
if n == 0.0 {
1
} else if n == 1.0 {
2
} else if n == -1.0 {
3
} else if n == 2.0 {
4
} else if n == -2.0 {
5
} else if n == 3.0 {
6
} else if n == 4.0 {
7
} else if n == 0.5 {
8
} else if n == -0.5 {
9
} else if n == 1.5 {
10
} else if n == 0.25 {
11
} else {
0
}
}
pub const fn is_valid(&self) -> bool {
if self.is_full() {
if !matches!(self.precision, PowfPrecision::Highp) {
return false;
}
if self.custom_base.is_some()
|| !matches!(self.exp_spec, ExpSpec::Default)
|| !matches!(self.subnormals, Subnormals::Reject)
{
return false;
}
}
if matches!(self.precision, PowfPrecision::Highp) && self.saturate {
return false;
}
if matches!(
(self.precision, self.portability),
(PowfPrecision::Highp, Portability::BackendDependent)
) && !cfg!(feature = "std")
{
return false;
}
if self.admits_subnormals()
&& let Some((lo, _)) = self.base_bounds()
&& lo > f32::MIN_POSITIVE
{
return false;
}
match self.exp_spec {
ExpSpec::RangeBf16(lo_b, hi_b) => {
if !self.admits_subnormals()
&& is_nonzero_subnormal_only_interval(expand_bf16(lo_b), expand_bf16(hi_b))
{
return false;
}
}
ExpSpec::ConstF32(bits) => {
let abs_b = bits & 0x7fff_ffff;
if matches!(self.subnormals, Subnormals::Reject)
&& abs_b != 0
&& abs_b < 0x0080_0000
{
return false;
}
if self.admits_zero()
&& matches!(self.validation, Validation::AssumeValid)
&& let Some(n) = self.const_exponent_value()
&& n < 0.0
{
return false;
}
}
ExpSpec::Default => {}
}
true
}
#[doc(hidden)]
pub const fn validate(&self) {
if self.is_full() {
assert!(
matches!(self.precision, PowfPrecision::Highp),
"PowfDomain::AllFloats / full_domain requires PowfPrecision::Highp"
);
assert!(
self.custom_base.is_none()
&& matches!(self.exp_spec, ExpSpec::Default)
&& matches!(self.subnormals, Subnormals::Reject),
"PowfDomain::AllFloats cannot be combined with custom ranges, const_exponent, or subnormal overrides"
);
}
assert!(
!(matches!(self.precision, PowfPrecision::Highp) && self.saturate),
"saturate_output / clamp_output is only supported on Midp and Lowp"
);
assert!(
!(matches!(
(self.precision, self.portability),
(PowfPrecision::Highp, Portability::BackendDependent)
) && !cfg!(feature = "std")),
"BackendDependent Highp requires the `std` feature"
);
if self.admits_subnormals()
&& let Some((lo, _)) = self.base_bounds()
{
assert!(
lo <= f32::MIN_POSITIVE,
"admit_subnormals requires base lower bound == f32::MIN_POSITIVE (for example PowfDomain::Unit or PositiveNormals); use .flush_or_clamp_subnormals() on raised gamma bounds"
);
}
match self.exp_spec {
ExpSpec::RangeBf16(lo_b, hi_b) => {
assert!(
!(!self.admits_subnormals()
&& is_nonzero_subnormal_only_interval(
expand_bf16(lo_b),
expand_bf16(hi_b)
)),
"exponent_range contains only nonzero subnormals; enable .admit_subnormals(), or include 0.0 or a normal f32"
);
}
ExpSpec::ConstF32(bits) => {
let abs_b = bits & 0x7fff_ffff;
assert!(
!(matches!(self.subnormals, Subnormals::Reject)
&& abs_b != 0
&& abs_b < 0x0080_0000),
"nonzero subnormal const_exponent requires .admit_subnormals() or .flush_or_clamp_subnormals()"
);
if let Some(n) = self.const_exponent_value() {
assert!(
!(self.admits_zero()
&& matches!(self.validation, Validation::AssumeValid)
&& n < 0.0),
"negative const_exponent with zero-admitting domain cannot use assume_in_bounds; use a positive-only domain or checked/clamp validation"
);
}
}
ExpSpec::Default => {}
}
}
pub const fn is_infallible(&self) -> bool {
self.is_valid()
&& (matches!(
self.validation,
Validation::AssumeValid | Validation::ClampOutOfBounds | Validation::ClampFinite
) || self.is_full())
}
#[doc(hidden)]
pub const fn elides_range_check(&self) -> bool {
if self.is_full() {
return false;
}
let alg = self.alg_kind();
if matches!(alg, 1 | 8 | 11) || (alg == 2 && !self.admits_subnormals()) {
return true;
}
let Some((blo, bhi)) = self.base_bounds() else {
return false;
};
let Some((nlo, nhi)) = self.exponent_bounds() else {
return false;
};
if self.admits_zero() && nlo < 0.0 {
return false;
}
let eb_lo = if self.admits_subnormals() {
-149.0_f32
} else {
exponent_of(blo) as f32
};
let eb_hi = (exponent_of(bhi) + 1) as f32;
let p0 = eb_lo * nlo;
let p1 = eb_lo * nhi;
let p2 = eb_hi * nlo;
let p3 = eb_hi * nhi;
abs(p0) <= ELIDE_LIMIT
&& abs(p1) <= ELIDE_LIMIT
&& abs(p2) <= ELIDE_LIMIT
&& abs(p3) <= ELIDE_LIMIT
}
pub const fn bits(&self) -> u128 {
let dom: u128 = match self.domain {
PowfDomain::PositiveNormals => 0,
PowfDomain::NonNegative => 1,
PowfDomain::Unit => 2,
PowfDomain::PositiveUnit => 3,
PowfDomain::UnitEncode => 4,
PowfDomain::SdrGamma => 5,
PowfDomain::HdrGamma => 6,
PowfDomain::PositiveGamma => 7,
PowfDomain::PqRatio => 8,
PowfDomain::AllFloats => 9,
};
let sub: u128 = match self.subnormals {
Subnormals::Reject => 0,
Subnormals::FlushOrClamp => 1,
Subnormals::Normalize => 2,
};
let val: u128 = match self.validation {
Validation::Checked => 0,
Validation::ClampOutOfBounds => 1,
Validation::AssumeValid => 2,
Validation::ClampFinite => 3,
};
let prec: u128 = match self.precision {
PowfPrecision::Midp => 0,
PowfPrecision::Lowp => 1,
PowfPrecision::Highp => 2,
};
let port: u128 = match self.portability {
Portability::BitExact => 0,
Portability::BackendDependent => 1,
};
let exec: u128 = match self.execution {
Execution::Upgrade => 0,
Execution::Caller => 1,
};
let mut out = MAGIC
| (dom << DOMAIN_SHIFT)
| (sub << SUBNORM_SHIFT)
| (val << VALIDATION_SHIFT)
| (prec << PREC_SHIFT)
| (port << PORTABILITY_SHIFT)
| (exec << EXECUTION_SHIFT);
if let Some((lo, hi)) = self.custom_base {
out |= HAS_CUSTOM_BASE;
out |= (lo as u128) << BASE_LO_SHIFT;
out |= (hi as u128) << BASE_HI_SHIFT;
}
match self.exp_spec {
ExpSpec::Default => {}
ExpSpec::RangeBf16(lo, hi) => {
out |= 1_u128 << EXP_MODE_SHIFT;
let packed = (lo as u32) | ((hi as u32) << 16);
out |= (packed as u128) << EXP_SLOT_SHIFT;
}
ExpSpec::ConstF32(bits) => {
out |= 2_u128 << EXP_MODE_SHIFT;
out |= (bits as u128) << EXP_SLOT_SHIFT;
}
}
if self.saturate {
out |= SATURATE_OUTPUT;
}
out
}
const fn from_bits_raw(bits: u128) -> Option<Self> {
if (bits & 0xf) != MAGIC || (bits & RESERVED_MASK) != 0 {
return None;
}
let domain = match (bits >> DOMAIN_SHIFT) & 0x1f {
0 => PowfDomain::PositiveNormals,
1 => PowfDomain::NonNegative,
2 => PowfDomain::Unit,
3 => PowfDomain::PositiveUnit,
4 => PowfDomain::UnitEncode,
5 => PowfDomain::SdrGamma,
6 => PowfDomain::HdrGamma,
7 => PowfDomain::PositiveGamma,
8 => PowfDomain::PqRatio,
9 => PowfDomain::AllFloats,
_ => return None,
};
let subnormals = match (bits >> SUBNORM_SHIFT) & 0x7 {
0 => Subnormals::Reject,
1 => Subnormals::FlushOrClamp,
2 => Subnormals::Normalize,
_ => return None,
};
let validation = match (bits >> VALIDATION_SHIFT) & 0x7 {
0 => Validation::Checked,
1 => Validation::ClampOutOfBounds,
2 => Validation::AssumeValid,
3 => Validation::ClampFinite,
_ => return None,
};
let precision = match (bits >> PREC_SHIFT) & 0x7 {
0 => PowfPrecision::Midp,
1 => PowfPrecision::Lowp,
2 => PowfPrecision::Highp,
_ => return None,
};
let portability = match (bits >> PORTABILITY_SHIFT) & 0x3 {
0 => Portability::BitExact,
1 => Portability::BackendDependent,
_ => return None,
};
let execution = match (bits >> EXECUTION_SHIFT) & 0x3 {
0 => Execution::Upgrade,
1 => Execution::Caller,
_ => return None,
};
let has_base = (bits & HAS_CUSTOM_BASE) != 0;
let base_lo_u16 = ((bits >> BASE_LO_SHIFT) & 0xffff) as u16;
let base_hi_u16 = ((bits >> BASE_HI_SHIFT) & 0xffff) as u16;
let custom_base = if has_base {
let Some(lo) = decode_bf16_finite(base_lo_u16) else {
return None;
};
let Some(hi) = decode_bf16_finite(base_hi_u16) else {
return None;
};
if !(lo >= f32::MIN_POSITIVE && lo <= hi && hi <= MAX_BF16) {
return None;
}
Some((base_lo_u16, base_hi_u16))
} else {
if base_lo_u16 != 0 || base_hi_u16 != 0 {
return None;
}
None
};
let exp_slot = ((bits >> EXP_SLOT_SHIFT) & 0xffff_ffff) as u32;
let exp_spec = match (bits >> EXP_MODE_SHIFT) & 0x3 {
0 => {
if exp_slot != 0 {
return None;
}
ExpSpec::Default
}
1 => {
let lo_u16 = (exp_slot & 0xffff) as u16;
let hi_u16 = (exp_slot >> 16) as u16;
let Some(lo) = decode_bf16_finite(lo_u16) else {
return None;
};
let Some(hi) = decode_bf16_finite(hi_u16) else {
return None;
};
if !(lo <= hi && abs(lo) <= MAX_BF16 && abs(hi) <= MAX_BF16) {
return None;
}
ExpSpec::RangeBf16(lo_u16, hi_u16)
}
2 => {
if exp_slot == 0x8000_0000 || (exp_slot & 0x7f80_0000) == 0x7f80_0000 {
return None;
}
ExpSpec::ConstF32(exp_slot)
}
_ => return None,
};
Some(Self {
domain,
custom_base,
exp_spec,
subnormals,
saturate: (bits & SATURATE_OUTPUT) != 0,
precision,
portability,
validation,
execution,
})
}
pub const fn from_bits(bits: u128) -> Option<Self> {
let Some(opts) = Self::from_bits_raw(bits) else {
return None;
};
if opts.is_valid() { Some(opts) } else { None }
}
pub(crate) const fn decode_const(bits: u128) -> Self {
let Some(opts) = Self::from_bits_raw(bits) else {
panic!("invalid PowfOptions bit pattern");
};
opts.validate();
opts
}
#[inline]
pub const fn runtime(self) -> super::PowfRuntime {
super::PowfRuntime::new(self)
}
pub(crate) const fn is_lowp(&self) -> bool {
matches!(self.precision, PowfPrecision::Lowp)
}
pub(crate) const fn is_highp(&self) -> bool {
matches!(self.precision, PowfPrecision::Highp)
}
pub(crate) const fn is_backend(&self) -> bool {
matches!(self.portability, Portability::BackendDependent)
}
pub(crate) const fn assume_valid(&self) -> bool {
matches!(self.validation, Validation::AssumeValid)
}
pub(crate) const fn clamp_oob(&self) -> bool {
matches!(
self.validation,
Validation::ClampOutOfBounds | Validation::ClampFinite
)
}
pub(crate) const fn preserve_clamped_nan(&self) -> bool {
matches!(self.validation, Validation::ClampOutOfBounds)
}
pub(crate) const fn should_clamp(&self) -> bool {
self.saturate
}
pub(crate) const fn is_caller(&self) -> bool {
matches!(self.execution, Execution::Caller)
}
#[allow(dead_code)]
pub(crate) const fn selected_execution(&self) -> Execution {
self.execution
}
}