concrete_core/backends/default/implementation/entities/
encoder.rs

1use crate::commons::crypto::encoding::FloatEncoder as ImplFloatEncoder;
2use crate::prelude::markers::EncoderKind;
3use crate::prelude::{AbstractEntity, EncoderEntity};
4#[cfg(feature = "backend_default_serialization")]
5use serde::{Deserialize, Serialize};
6
7/// An encoder for 64 bits floating point numbers.
8#[derive(Debug, PartialEq)]
9pub struct FloatEncoder(pub(crate) ImplFloatEncoder);
10
11impl AbstractEntity for FloatEncoder {
12    type Kind = EncoderKind;
13}
14impl EncoderEntity for FloatEncoder {}
15
16#[cfg(feature = "backend_default_serialization")]
17#[derive(Serialize, Deserialize)]
18pub(crate) enum FloatEncoderVersion {
19    V0,
20    #[serde(other)]
21    Unsupported,
22}
23
24/// Parameters allowing to construct a `FloatEncoder` from the bounds of the range to be
25/// represented.
26#[derive(Debug, PartialEq, Clone)]
27pub struct FloatEncoderMinMaxConfig {
28    pub min: f64,
29    pub max: f64,
30    pub nb_bit_precision: usize,
31    pub nb_bit_padding: usize,
32}
33
34impl FloatEncoderMinMaxConfig {
35    pub(crate) fn to_commons(&self) -> ImplFloatEncoder {
36        assert!(
37            self.min < self.max,
38            "Min and max bounds are in the wrong order."
39        );
40        assert_ne!(
41            self.nb_bit_precision, 0,
42            "The number of bits of precision must be strictly positive."
43        );
44        let margin: f64 =
45            (self.max - self.min) / (f64::powi(2., self.nb_bit_precision as i32) - 1.);
46        ImplFloatEncoder {
47            o: self.min,
48            delta: self.max - self.min + margin,
49            nb_bit_precision: self.nb_bit_precision,
50            nb_bit_padding: self.nb_bit_padding,
51            round: false,
52        }
53    }
54}
55
56/// Parameters allowing to construct a `FloatEncoder` from the center and radius of the range to be
57/// represented.
58#[derive(Debug, PartialEq, Clone)]
59pub struct FloatEncoderCenterRadiusConfig {
60    pub center: f64,
61    pub radius: f64,
62    pub nb_bit_precision: usize,
63    pub nb_bit_padding: usize,
64}
65
66impl FloatEncoderCenterRadiusConfig {
67    pub(crate) fn to_commons(&self) -> ImplFloatEncoder {
68        assert!(self.radius > 0., "Radius must be greater than zero.");
69        assert_ne!(
70            self.nb_bit_precision, 0,
71            "The number of bits of precision must be strictly positive"
72        );
73        FloatEncoderMinMaxConfig {
74            min: self.center - self.radius,
75            max: self.center + self.radius,
76            nb_bit_precision: self.nb_bit_precision,
77            nb_bit_padding: self.nb_bit_padding,
78        }
79        .to_commons()
80    }
81}