pub fn i128_to_ordered_string(value: i128) -> String {
if value < 0 {
let offset = (i128::MAX as u128)
.wrapping_add(1)
.wrapping_add(value as u128);
format!("0{:0>39}", offset)
} else {
format!("1{:0>39}", value)
}
}
pub fn f64_to_ordered_string(value: f64) -> String {
if value.is_nan() {
panic!("NaN value");
}
if value == f64::INFINITY {
return "2".to_string();
}
if value == f64::NEG_INFINITY {
return "0".to_string();
}
let bits = value.to_bits();
if value < 0.0 {
let flipped_bits = !bits;
format!("1{:0>16x}", flipped_bits)
} else {
let modified_bits = bits ^ 0x8000000000000000;
format!("1{:0>16x}", modified_bits)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_i128_to_ordered_string() {
let items = vec![
i128_to_ordered_string(i128::MIN),
i128_to_ordered_string(-11),
i128_to_ordered_string(-2),
i128_to_ordered_string(-1),
i128_to_ordered_string(0),
i128_to_ordered_string(1),
i128_to_ordered_string(2),
i128_to_ordered_string(11),
i128_to_ordered_string(111),
i128_to_ordered_string(i128::MAX),
];
println!("{:#?}", items);
assert!(items.is_sorted());
}
#[test]
fn test_f64_to_ordered_string() {
let items = vec![
f64_to_ordered_string(f64::NEG_INFINITY),
f64_to_ordered_string(f64::MIN),
f64_to_ordered_string(-11.11),
f64_to_ordered_string(-11.1),
f64_to_ordered_string(-2.0),
f64_to_ordered_string(-1.0),
f64_to_ordered_string(0.0),
f64_to_ordered_string(1.0),
f64_to_ordered_string(2.0),
f64_to_ordered_string(11.1),
f64_to_ordered_string(11.11),
f64_to_ordered_string(f64::MAX),
f64_to_ordered_string(f64::INFINITY),
];
println!("{:#?}", items);
assert!(items.is_sorted());
}
}