use crate::{
Execution, Portability, Subnormals, Validation,
bf16::{MAX_BF16, ceil_bf16, decode_bf16_finite, expand_bf16, floor_bf16},
};
const MAGIC: u128 = 0xC;
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_RANGE: u128 = 1 << 22;
const EXTRA_ZERO: u128 = 1 << 23;
const RESERVED_LO_MASK: u128 = ((1_u128 << 40) - 1) << 24;
const IN_LO_SHIFT: u32 = 64;
const IN_HI_SHIFT: u32 = 80;
const RESERVED_HI_MASK: u128 = 0xffff_ffff_u128 << 96;
pub(crate) const MIDP_OCTAVE_LO_BITS: u32 = 0x3f35_04f3;
pub(crate) const MIDP_OCTAVE_HI_BITS: u32 = 0x3fb5_04f2;
pub(crate) const LOWP_OCTAVE_LO_BITS: u32 = 0x3f2a_aaab;
pub(crate) const LOWP_OCTAVE_HI_BITS: u32 = 0x3faa_aaaa;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum LogfDomain {
#[default]
PositiveNormals,
NonNegative,
Unit,
PositiveUnit,
Hdr,
PositiveHdr,
SingleOctave,
AllFloats,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum LogfPrecision {
#[default]
Midp,
Lowp,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct LogfOptions {
domain: LogfDomain,
custom_range: Option<(u16, u16)>,
extra_zero: bool,
subnormals: Subnormals,
precision: LogfPrecision,
portability: Portability,
validation: Validation,
execution: Execution,
}
impl Default for LogfOptions {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl LogfOptions {
pub const fn new() -> Self {
Self {
domain: LogfDomain::PositiveNormals,
custom_range: None,
extra_zero: false,
subnormals: Subnormals::FlushOrClamp,
precision: LogfPrecision::Midp,
portability: Portability::BitExact,
validation: Validation::Checked,
execution: Execution::Upgrade,
}
}
pub const fn domain(mut self, domain: LogfDomain) -> Self {
self.domain = domain;
self.custom_range = None;
self.extra_zero = false;
if matches!(domain, LogfDomain::AllFloats) {
self.subnormals = Subnormals::Reject;
}
self
}
pub const fn input_range(mut self, lo: f32, hi: f32) -> Self {
assert!(
lo >= 0.0 && lo <= hi && hi <= MAX_BF16,
"log input range must be non-negative finite within MAX_BF16 (0x7f7f_0000) with lo <= hi"
);
self.custom_range = Some((floor_bf16(lo), ceil_bf16(hi)));
self
}
pub const fn near_one_range(self) -> Self {
self.domain(LogfDomain::SingleOctave)
}
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 {
match self.domain {
LogfDomain::PositiveNormals => self.domain = LogfDomain::NonNegative,
LogfDomain::PositiveUnit => self.domain = LogfDomain::Unit,
LogfDomain::PositiveHdr => self.domain = LogfDomain::Hdr,
LogfDomain::SingleOctave => self.extra_zero = true,
_ => {}
}
self
}
pub const fn admit_all_floats(self) -> Self {
self.domain(LogfDomain::AllFloats)
}
pub const fn full_domain(self) -> Self {
self.admit_all_floats()
}
pub const fn precision(mut self, value: LogfPrecision) -> Self {
self.precision = value;
self
}
pub const fn lowp(self) -> Self {
self.precision(LogfPrecision::Lowp)
}
pub const fn midp(self) -> Self {
self.precision(LogfPrecision::Midp)
}
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) -> LogfDomain {
self.domain
}
pub const fn subnormals_policy(&self) -> Subnormals {
if self.is_specials() {
Subnormals::Normalize
} else {
self.subnormals
}
}
pub(crate) const fn is_specials(&self) -> bool {
matches!(self.domain, LogfDomain::AllFloats)
}
pub(crate) const fn admits_zero(&self) -> bool {
self.is_specials()
|| self.extra_zero
|| matches!(
self.domain,
LogfDomain::NonNegative | LogfDomain::Unit | LogfDomain::Hdr
)
}
pub(crate) const fn admits_subnormals(&self) -> bool {
self.is_specials() || matches!(self.subnormals, Subnormals::Normalize)
}
pub(crate) const fn flushes_subnormals(&self) -> bool {
!self.is_specials() && matches!(self.subnormals, Subnormals::FlushOrClamp)
}
pub(crate) const fn input_bounds(&self) -> Option<(f32, f32)> {
if self.is_specials() {
return None;
}
if let Some((lo, hi)) = self.custom_range {
return Some((expand_bf16(lo), expand_bf16(hi)));
}
match self.domain {
LogfDomain::PositiveNormals | LogfDomain::NonNegative | LogfDomain::AllFloats => None,
LogfDomain::Unit | LogfDomain::PositiveUnit => Some((
if self.admits_subnormals() {
f32::from_bits(1)
} else {
f32::MIN_POSITIVE
},
1.0,
)),
LogfDomain::Hdr | LogfDomain::PositiveHdr => Some((1.0 / 65_536.0, 65_536.0)),
LogfDomain::SingleOctave => {
if matches!(self.precision, LogfPrecision::Lowp) {
Some((
f32::from_bits(LOWP_OCTAVE_LO_BITS),
f32::from_bits(LOWP_OCTAVE_HI_BITS),
))
} else {
Some((
f32::from_bits(MIDP_OCTAVE_LO_BITS),
f32::from_bits(MIDP_OCTAVE_HI_BITS),
))
}
}
}
}
pub const fn is_valid(&self) -> bool {
if self.is_specials() {
return self.custom_range.is_none()
&& !self.extra_zero
&& matches!(self.subnormals, Subnormals::Reject);
}
if self.extra_zero && !matches!(self.domain, LogfDomain::SingleOctave) {
return false;
}
if let Some((lo, hi)) = self.input_bounds() {
if lo == 0.0 {
if !self.admits_zero() {
return false;
}
if hi > 0.0 && matches!(self.subnormals, Subnormals::Reject) {
return false;
}
if hi == 0.0 && matches!(self.subnormals, Subnormals::Normalize) {
return false;
}
} else if lo < f32::MIN_POSITIVE {
if matches!(self.subnormals, Subnormals::Reject) {
return false;
}
if hi < f32::MIN_POSITIVE && !self.admits_subnormals() {
return false;
}
}
if matches!(self.subnormals, Subnormals::Normalize) && lo >= f32::MIN_POSITIVE {
return false;
}
}
true
}
#[doc(hidden)]
pub const fn validate(&self) {
if self.is_specials() {
assert!(
self.custom_range.is_none()
&& !self.extra_zero
&& matches!(self.subnormals, Subnormals::Reject),
"LogfDomain::AllFloats / full_domain cannot be combined with custom input_range or subnormal overrides"
);
return;
}
assert!(
!(self.extra_zero && !matches!(self.domain, LogfDomain::SingleOctave)),
"internal extra_zero flag only valid with LogfDomain::SingleOctave"
);
if let Some((lo, hi)) = self.input_bounds() {
if lo == 0.0 {
assert!(
self.admits_zero(),
"log input_range starting at 0.0 requires .admit_zero() (or LogfDomain::Unit / NonNegative)"
);
assert!(
hi == 0.0 || !matches!(self.subnormals, Subnormals::Reject),
"log input_range starting at 0.0 with hi > 0 requires .admit_subnormals() or .flush_or_clamp_subnormals() (or use f32::MIN_POSITIVE / LogfDomain::Unit)"
);
assert!(
!(hi == 0.0 && matches!(self.subnormals, Subnormals::Normalize)),
"log input_range [0.0, 0.0] contains no nonzero subnormals"
);
} else {
assert!(
lo >= f32::MIN_POSITIVE || !matches!(self.subnormals, Subnormals::Reject),
"log input_range lower bound below f32::MIN_POSITIVE requires .admit_subnormals() or .flush_or_clamp_subnormals()"
);
assert!(
!(lo < f32::MIN_POSITIVE
&& hi < f32::MIN_POSITIVE
&& !self.admits_subnormals()),
"log input_range containing only nonzero subnormals requires .admit_subnormals()"
);
}
assert!(
!(matches!(self.subnormals, Subnormals::Normalize) && lo >= f32::MIN_POSITIVE),
"admit_subnormals requires input lower bound < f32::MIN_POSITIVE (or LogfDomain::Unit / PositiveNormals); use .flush_or_clamp_subnormals() on normal-only domains"
);
}
}
#[doc(hidden)]
pub const fn elides_reduction(&self) -> bool {
if self.is_specials() || self.admits_zero() || self.admits_subnormals() {
return false;
}
let Some((lo, hi)) = self.input_bounds() else {
return false;
};
if matches!(self.precision, LogfPrecision::Lowp) {
lo >= f32::from_bits(LOWP_OCTAVE_LO_BITS) && hi <= f32::from_bits(LOWP_OCTAVE_HI_BITS)
} else {
lo >= f32::from_bits(MIDP_OCTAVE_LO_BITS) && hi <= f32::from_bits(MIDP_OCTAVE_HI_BITS)
}
}
pub const fn is_infallible(&self) -> bool {
self.is_valid() && (self.assume_valid() || self.clamp_oob() || self.is_specials())
}
pub const fn bits(&self) -> u128 {
let dom: u128 = match self.domain {
LogfDomain::PositiveNormals => 0,
LogfDomain::NonNegative => 1,
LogfDomain::Unit => 2,
LogfDomain::PositiveUnit => 3,
LogfDomain::Hdr => 4,
LogfDomain::PositiveHdr => 5,
LogfDomain::SingleOctave => 6,
LogfDomain::AllFloats => 7,
};
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 {
LogfPrecision::Midp => 0,
LogfPrecision::Lowp => 1,
};
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 self.extra_zero {
out |= EXTRA_ZERO;
}
if let Some((lo, hi)) = self.custom_range {
out |= HAS_CUSTOM_RANGE | ((lo as u128) << IN_LO_SHIFT) | ((hi as u128) << IN_HI_SHIFT);
}
out
}
const fn from_bits_raw(bits: u128) -> Option<Self> {
if (bits & 0xf) != MAGIC || (bits & RESERVED_LO_MASK) != 0 || (bits & RESERVED_HI_MASK) != 0
{
return None;
}
let domain = match (bits >> DOMAIN_SHIFT) & 0x1f {
0 => LogfDomain::PositiveNormals,
1 => LogfDomain::NonNegative,
2 => LogfDomain::Unit,
3 => LogfDomain::PositiveUnit,
4 => LogfDomain::Hdr,
5 => LogfDomain::PositiveHdr,
6 => LogfDomain::SingleOctave,
7 => LogfDomain::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 => LogfPrecision::Midp,
1 => LogfPrecision::Lowp,
_ => 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 lo_u16 = ((bits >> IN_LO_SHIFT) & 0xffff) as u16;
let hi_u16 = ((bits >> IN_HI_SHIFT) & 0xffff) as u16;
let custom_range = if (bits & HAS_CUSTOM_RANGE) != 0 {
let Some(lo) = decode_bf16_finite(lo_u16) else {
return None;
};
let Some(hi) = decode_bf16_finite(hi_u16) else {
return None;
};
if !(lo >= 0.0 && lo <= hi && hi <= MAX_BF16) {
return None;
}
Some((lo_u16, hi_u16))
} else {
if lo_u16 != 0 || hi_u16 != 0 {
return None;
}
None
};
Some(Self {
domain,
custom_range,
extra_zero: (bits & EXTRA_ZERO) != 0,
subnormals,
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 logf const options bit pattern");
};
opts.validate();
opts
}
#[inline(always)]
pub const fn runtime(self) -> super::LogfRuntime {
super::LogfRuntime::new(self)
}
pub(crate) const fn is_lowp(&self) -> bool {
matches!(self.precision, LogfPrecision::Lowp)
}
pub(crate) const fn is_backend(&self) -> bool {
matches!(self.portability, Portability::BackendDependent)
}
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 assume_valid(&self) -> bool {
matches!(self.validation, Validation::AssumeValid)
}
pub(crate) const fn is_caller(&self) -> bool {
matches!(self.execution, Execution::Caller)
}
}