use std::f64::consts::FRAC_1_SQRT_2;
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Fixed {
min: f64,
quantum: f64,
bits: u32,
}
impl Fixed {
pub const MAX_BITS: u32 = 32;
#[must_use]
pub const fn new(min: f64, max: f64, bits: u32) -> Self {
assert!(
bits >= 1 && bits <= Self::MAX_BITS,
"a fixed-point code needs between 1 and 32 bits"
);
assert!(
min.is_finite() && max.is_finite() && min < max,
"a fixed-point range needs finite bounds with min < max"
);
Self {
min,
quantum: (max - min) / (1u64 << bits) as f64,
bits,
}
}
#[must_use]
pub const fn bits(&self) -> u32 {
self.bits
}
#[must_use]
pub const fn quantum(&self) -> f64 {
self.quantum
}
#[must_use]
pub const fn min(&self) -> f64 {
self.min
}
#[must_use]
pub const fn max_code(&self) -> u32 {
((1u64 << self.bits) - 1) as u32
}
#[must_use]
pub fn encode(&self, value: f64) -> Option<u32> {
if !value.is_finite() {
return None;
}
let code = ((value - self.min) / self.quantum + 0.5).floor();
if !(0.0..=f64::from(self.max_code())).contains(&code) {
return None;
}
Some(code as u32)
}
#[must_use]
pub fn decode(&self, code: u32) -> Option<f64> {
(code <= self.max_code()).then(|| self.min + f64::from(code) * self.quantum)
}
}
const F64_MANTISSA_BITS: u32 = 52;
const F64_EXPONENT_BIAS: i32 = 1023;
const F64_EXPONENT_SPECIAL: u64 = 0x7FF;
const HALF_MANTISSA_BITS: u32 = 10;
const HALF_EXPONENT_BIAS: i32 = 15;
const HALF_EXPONENT_SPECIAL: u16 = 0x1F;
const HALF_SIGN: u16 = 0x8000;
const HALF_INFINITY: u16 = HALF_EXPONENT_SPECIAL << HALF_MANTISSA_BITS;
const HALF_QUIET: u16 = 1 << (HALF_MANTISSA_BITS - 1);
const HALF_MAX_EXPONENT: i32 = 15;
const HALF_MIN_EXPONENT: i32 = -14;
const HALF_SUBNORMAL_EXPONENT: i32 = HALF_MIN_EXPONENT - HALF_MANTISSA_BITS as i32;
const HALF_SUBNORMAL_STEP: f64 =
f64::from_bits(((HALF_SUBNORMAL_EXPONENT + F64_EXPONENT_BIAS) as u64) << F64_MANTISSA_BITS);
#[must_use]
pub fn to_binary16(value: f64) -> u16 {
let bits = value.to_bits();
let sign = ((bits >> 48) as u16) & HALF_SIGN;
let exponent_field = (bits >> F64_MANTISSA_BITS) & F64_EXPONENT_SPECIAL;
let mantissa = bits & ((1 << F64_MANTISSA_BITS) - 1);
if exponent_field == F64_EXPONENT_SPECIAL {
if mantissa == 0 {
return sign | HALF_INFINITY;
}
let payload = (mantissa >> (F64_MANTISSA_BITS - HALF_MANTISSA_BITS)) as u16;
return sign | HALF_INFINITY | HALF_QUIET | payload;
}
if exponent_field == 0 {
return sign;
}
let exponent = exponent_field as i32 - F64_EXPONENT_BIAS;
if exponent > HALF_MAX_EXPONENT {
return sign | HALF_INFINITY;
}
if exponent < HALF_SUBNORMAL_EXPONENT - 1 {
return sign;
}
let significand = mantissa | (1 << F64_MANTISSA_BITS);
let (shift, base) = if exponent >= HALF_MIN_EXPONENT {
let biased = (exponent + HALF_EXPONENT_BIAS) as u64;
let shift = F64_MANTISSA_BITS - HALF_MANTISSA_BITS;
(shift, (biased << HALF_MANTISSA_BITS) | (mantissa >> shift))
} else {
let shift = (F64_MANTISSA_BITS as i32 - (exponent - HALF_SUBNORMAL_EXPONENT)) as u32;
(shift, significand >> shift)
};
let remainder = significand & ((1 << shift) - 1);
let halfway = 1 << (shift - 1);
let round_up = remainder > halfway || (remainder == halfway && base & 1 == 1);
sign | (base + u64::from(round_up)) as u16
}
#[must_use]
pub fn from_binary16(bits: u16) -> f64 {
let sign = u64::from(bits & HALF_SIGN) << 48;
let exponent_field = (bits >> HALF_MANTISSA_BITS) & HALF_EXPONENT_SPECIAL;
let mantissa = u64::from(bits & ((1 << HALF_MANTISSA_BITS) - 1));
let shift = F64_MANTISSA_BITS - HALF_MANTISSA_BITS;
let magnitude = match exponent_field {
0 => {
let value = mantissa as f64 * HALF_SUBNORMAL_STEP;
return f64::from_bits(sign | value.to_bits());
}
HALF_EXPONENT_SPECIAL => (F64_EXPONENT_SPECIAL << F64_MANTISSA_BITS) | (mantissa << shift),
_ => {
let exponent = i32::from(exponent_field) - HALF_EXPONENT_BIAS + F64_EXPONENT_BIAS;
((exponent as u64) << F64_MANTISSA_BITS) | (mantissa << shift)
}
};
f64::from_bits(sign | magnitude)
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SmallestThree {
bits: u32,
}
const SMALLEST_THREE_RANGE: f64 = FRAC_1_SQRT_2;
const SMALLEST_THREE_INDEX_BITS: u32 = 2;
impl SmallestThree {
pub const MIN_BITS: u32 = 2;
pub const MAX_BITS: u32 = 32;
#[must_use]
pub const fn new(bits: u32) -> Self {
assert!(
bits >= Self::MIN_BITS && bits <= Self::MAX_BITS,
"a smallest-three component needs between 2 and 32 bits"
);
Self { bits }
}
#[must_use]
pub const fn bits(&self) -> u32 {
self.bits
}
#[must_use]
pub const fn encoded_bits(&self) -> u32 {
SMALLEST_THREE_INDEX_BITS + 3 * self.bits
}
#[must_use]
pub fn quantum(&self) -> f64 {
2.0 * SMALLEST_THREE_RANGE / self.max_code() as f64
}
#[must_use]
pub const fn max_code(&self) -> u32 {
((1u64 << self.bits) - 2) as u32
}
const fn centre(&self) -> u32 {
self.max_code() / 2
}
#[must_use]
pub fn encode(&self, quaternion: [f64; 4]) -> Option<(u8, [u32; 3])> {
let length = quaternion.iter().map(|c| c * c).sum::<f64>().sqrt();
if !length.is_finite() || length == 0.0 {
return None;
}
let mut largest = 0;
for (i, component) in quaternion.iter().enumerate() {
if component.abs() > quaternion[largest].abs() {
largest = i;
}
}
let scale = if quaternion[largest] < 0.0 {
-1.0 / length
} else {
1.0 / length
};
let quantum = self.quantum();
let mut codes = [0u32; 3];
let others = (0..4).filter(|&i| i != largest);
for (code, i) in codes.iter_mut().zip(others) {
let value = (quaternion[i] * scale).clamp(-SMALLEST_THREE_RANGE, SMALLEST_THREE_RANGE);
let offset = (value / quantum + 0.5).floor() as i64;
*code = (i64::from(self.centre()) + offset).clamp(0, i64::from(self.max_code())) as u32;
}
Some((largest as u8, codes))
}
#[must_use]
pub fn decode(&self, index: u8, codes: [u32; 3]) -> Option<[f64; 4]> {
let largest = usize::from(index);
if largest > 3 || codes.iter().any(|&code| code > self.max_code()) {
return None;
}
let quantum = self.quantum();
let mut quaternion = [0.0; 4];
let others = (0..4).filter(|&i| i != largest);
for (&code, i) in codes.iter().zip(others) {
quaternion[i] = (f64::from(code) - f64::from(self.centre())) * quantum;
}
let rest: f64 = quaternion.iter().map(|c| c * c).sum();
quaternion[largest] = (1.0 - rest).max(0.0).sqrt();
let length = quaternion.iter().map(|c| c * c).sum::<f64>().sqrt();
Some(quaternion.map(|c| c / length))
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Codec {
Exact,
Fixed(Fixed),
Half,
Rotation(SmallestThree),
}
const EXACT_BITS: u32 = 64;
const HALF_BITS: u32 = 16;
impl Codec {
#[must_use]
pub const fn values(&self) -> usize {
match self {
Self::Rotation(_) => 4,
Self::Exact | Self::Fixed(_) | Self::Half => 1,
}
}
#[must_use]
pub const fn bits(&self) -> u32 {
match self {
Self::Exact => EXACT_BITS,
Self::Fixed(fixed) => fixed.bits(),
Self::Half => HALF_BITS,
Self::Rotation(rotation) => rotation.encoded_bits(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Field {
pub name: &'static str,
pub codec: Codec,
}
#[must_use]
pub const fn value_count(schema: &[Field]) -> usize {
let mut count = 0;
let mut i = 0;
while i < schema.len() {
count += schema[i].codec.values();
i += 1;
}
count
}
#[must_use]
pub const fn encoded_len(schema: &[Field]) -> usize {
let mut bits = 0usize;
let mut i = 0;
while i < schema.len() {
bits += schema[i].codec.bits() as usize;
i += 1;
}
bits.div_ceil(8)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuantizeError {
ValueCount {
expected: usize,
actual: usize,
},
Unrepresentable {
field: &'static str,
},
Length {
expected: usize,
actual: usize,
},
NonCanonical {
field: &'static str,
},
Refused,
}
impl fmt::Display for QuantizeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ValueCount { expected, actual } => {
write!(f, "schema consumes {expected} values, {actual} supplied")
}
Self::Unrepresentable { field } => {
write!(f, "field {field} cannot represent its value")
}
Self::Length { expected, actual } => {
write!(f, "payload is {actual} bytes, schema wants {expected}")
}
Self::NonCanonical { field } => write!(f, "field {field} holds a code never written"),
Self::Refused => f.write_str("the component refused the decoded values"),
}
}
}
impl std::error::Error for QuantizeError {}
struct BitWriter<'a> {
out: &'a mut Vec<u8>,
pending: u128,
pending_bits: u32,
}
impl BitWriter<'_> {
fn write(&mut self, value: u64, bits: u32) {
let masked = if bits == 64 {
value
} else {
value & ((1 << bits) - 1)
};
self.pending |= u128::from(masked) << self.pending_bits;
self.pending_bits += bits;
while self.pending_bits >= 8 {
self.out.push(self.pending as u8);
self.pending >>= 8;
self.pending_bits -= 8;
}
}
fn finish(self) {
if self.pending_bits > 0 {
self.out.push(self.pending as u8);
}
}
}
struct BitReader<'a> {
data: &'a [u8],
next: usize,
pending: u128,
pending_bits: u32,
}
impl BitReader<'_> {
fn read(&mut self, bits: u32) -> u64 {
while self.pending_bits < bits {
self.pending |= u128::from(self.data[self.next]) << self.pending_bits;
self.next += 1;
self.pending_bits += 8;
}
let value = if bits == 64 {
self.pending as u64
} else {
(self.pending as u64) & ((1 << bits) - 1)
};
self.pending >>= bits;
self.pending_bits -= bits;
value
}
}
pub fn encode_values(
schema: &[Field],
values: &[f64],
out: &mut Vec<u8>,
) -> Result<(), QuantizeError> {
let expected = value_count(schema);
if values.len() != expected {
return Err(QuantizeError::ValueCount {
expected,
actual: values.len(),
});
}
let start = out.len();
let result = write_fields(schema, values, out);
if result.is_err() {
out.truncate(start);
}
result
}
fn write_fields(schema: &[Field], values: &[f64], out: &mut Vec<u8>) -> Result<(), QuantizeError> {
let mut writer = BitWriter {
out,
pending: 0,
pending_bits: 0,
};
let mut cursor = 0;
for field in schema {
let taken = &values[cursor..cursor + field.codec.values()];
cursor += taken.len();
let unrepresentable = QuantizeError::Unrepresentable { field: field.name };
match field.codec {
Codec::Exact => writer.write(taken[0].to_bits(), EXACT_BITS),
Codec::Fixed(fixed) => {
let code = fixed.encode(taken[0]).ok_or(unrepresentable)?;
writer.write(u64::from(code), fixed.bits());
}
Codec::Half => {
let half = to_binary16(taken[0]);
if !taken[0].is_finite() || half & !HALF_SIGN == HALF_INFINITY {
return Err(unrepresentable);
}
writer.write(u64::from(half), HALF_BITS);
}
Codec::Rotation(rotation) => {
let quaternion = [taken[0], taken[1], taken[2], taken[3]];
let (index, codes) = rotation.encode(quaternion).ok_or(unrepresentable)?;
writer.write(u64::from(index), SMALLEST_THREE_INDEX_BITS);
for code in codes {
writer.write(u64::from(code), rotation.bits());
}
}
}
}
writer.finish();
Ok(())
}
pub fn decode_values(
schema: &[Field],
data: &[u8],
values: &mut [f64],
) -> Result<(), QuantizeError> {
let expected = value_count(schema);
if values.len() != expected {
return Err(QuantizeError::ValueCount {
expected,
actual: values.len(),
});
}
let expected_len = encoded_len(schema);
if data.len() != expected_len {
return Err(QuantizeError::Length {
expected: expected_len,
actual: data.len(),
});
}
let mut reader = BitReader {
data,
next: 0,
pending: 0,
pending_bits: 0,
};
let mut cursor = 0;
for field in schema {
let non_canonical = QuantizeError::NonCanonical { field: field.name };
let slots = &mut values[cursor..cursor + field.codec.values()];
cursor += slots.len();
match field.codec {
Codec::Exact => slots[0] = f64::from_bits(reader.read(EXACT_BITS)),
Codec::Fixed(fixed) => {
let code = reader.read(fixed.bits()) as u32;
slots[0] = fixed.decode(code).ok_or(non_canonical)?;
}
Codec::Half => slots[0] = from_binary16(reader.read(HALF_BITS) as u16),
Codec::Rotation(rotation) => {
let index = reader.read(SMALLEST_THREE_INDEX_BITS) as u8;
let codes = [(); 3].map(|()| reader.read(rotation.bits()) as u32);
slots.copy_from_slice(&rotation.decode(index, codes).ok_or(non_canonical)?);
}
}
}
if reader.pending != 0 {
return Err(QuantizeError::NonCanonical { field: "padding" });
}
Ok(())
}
pub trait Quantized: Sized {
const SCHEMA: &'static [Field];
type Values: AsRef<[f64]> + AsMut<[f64]> + Default;
fn to_values(&self) -> Self::Values;
fn from_values(values: &Self::Values) -> Option<Self>;
}
pub fn encode<T: Quantized>(component: &T, out: &mut Vec<u8>) -> Result<(), QuantizeError> {
encode_values(T::SCHEMA, component.to_values().as_ref(), out)
}
pub fn decode<T: Quantized>(data: &[u8]) -> Result<T, QuantizeError> {
let mut values = T::Values::default();
decode_values(T::SCHEMA, data, values.as_mut())?;
T::from_values(&values).ok_or(QuantizeError::Refused)
}
#[cfg(test)]
mod tests;