nodes/packages/utils/src/encoding.rs

39 lines
915 B
Rust
Raw Normal View History

2024-04-16 15:32:23 +02:00
pub fn encode_float(f: f32) -> i32 {
// Convert f32 to u32 using to_bits, then safely cast to i32
let bits = f.to_bits();
2024-04-16 15:32:23 +02:00
bits as i32
}
2024-04-16 15:32:23 +02:00
pub fn decode_float(bits: i32) -> f32 {
// Convert i32 to u32 safely, then use from_bits to get f32
let bits = bits as u32;
f32::from_bits(bits)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
2024-04-16 15:32:23 +02:00
fn test_decode_float_simple() {
let test_values: [f32; 6] = [
0.0,
-0.0,
123.456,
-123.456,
std::f32::INFINITY,
std::f32::NEG_INFINITY,
];
2024-04-16 15:32:23 +02:00
for &value in &test_values {
let encoded = encode_float(value);
let decoded = decode_float(encoded);
assert_eq!(
decoded.to_bits(),
value.to_bits(),
"Failed for value {}",
value
);
}
}
}