use num_bigint::BigUint;
use num_traits::ToPrimitive;
use crate::core::{AnoError, Integer};
pub struct Float {
number: Integer,
}
impl Float {
pub fn instantiate() -> Result<Self, AnoError> {
Ok(Self {
number: Integer::instantiate(16, 16)?,
})
}
pub fn encrypt(&self, key: &[u8; 32], tweak: &[u8], value: f64) -> Result<f64, AnoError> {
let big_uint = BigUint::from(value.to_bits());
let ciphertext = self.number.encrypt_big(key, tweak, &big_uint)?;
let num_bits = ciphertext.to_u64().ok_or_else(|| {
AnoError::FPE(format!(
"Failed converting the ciphertext value: {ciphertext}, to a number of bits as an \
u64"
))
})?;
Ok(f64::from_bits(num_bits))
}
pub fn decrypt(&self, key: &[u8; 32], tweak: &[u8], value: f64) -> Result<f64, AnoError> {
let big_uint = BigUint::from(value.to_bits());
let ciphertext = self.number.decrypt_big(key, tweak, &big_uint)?;
let num_bits = ciphertext.to_u64().ok_or_else(|| {
AnoError::FPE(format!(
"Failed converting the ciphertext value: {ciphertext}, to a number of bits as an \
u64"
))
})?;
Ok(f64::from_bits(num_bits))
}
}