pancake_db_core/primitives/
floats.rs

1use pancake_db_idl::dml::field_value::Value;
2use pancake_db_idl::dtype::DataType;
3
4use crate::compression::Codec;
5use crate::compression::q_codec::{F64QCodec, F32QCodec};
6use crate::compression::Q_COMPRESS;
7use crate::errors::{CoreError, CoreResult};
8use crate::primitives::{Atom, Primitive};
9use crate::utils;
10
11impl Atom for f32 {
12  const BYTE_SIZE: usize = 4;
13
14  fn to_bytes(&self) -> Vec<u8> {
15    self.to_be_bytes().to_vec()
16  }
17
18  fn try_from_bytes(bytes: &[u8]) -> CoreResult<Self> where Self: Sized {
19    let byte_array = utils::try_byte_array::<4>(bytes)?;
20    Ok(f32::from_be_bytes(byte_array))
21  }
22}
23
24impl Atom for f64 {
25  const BYTE_SIZE: usize = 8;
26
27  fn to_bytes(&self) -> Vec<u8> {
28    self.to_be_bytes().to_vec()
29  }
30
31  fn try_from_bytes(bytes: &[u8]) -> CoreResult<Self> {
32    let byte_array = utils::try_byte_array::<8>(bytes)?;
33    Ok(f64::from_be_bytes(byte_array))
34  }
35}
36
37impl Primitive for f32 {
38  type A = Self;
39  const DTYPE: DataType = DataType::Float32;
40
41  const IS_ATOMIC: bool = true;
42
43  fn to_value(&self) -> Value {
44    Value::Float32Val(*self)
45  }
46
47  fn try_from_value(v: &Value) -> CoreResult<f32> {
48    match v {
49      Value::Float32Val(res) => Ok(*res),
50      _ => Err(CoreError::invalid("cannot read f32 from value")),
51    }
52  }
53
54  fn to_atoms(&self) -> Vec<Self> {
55    vec![*self]
56  }
57
58  fn try_from_atoms(atoms: &[Self]) -> CoreResult<Self> {
59    Ok(atoms[0])
60  }
61
62  fn new_codec(codec: &str) -> Option<Box<dyn Codec<P=Self>>> {
63    if codec == Q_COMPRESS {
64      Some(Box::new(F32QCodec {}))
65    } else {
66      None
67    }
68  }
69}
70
71impl Primitive for f64 {
72  type A = Self;
73  const DTYPE: DataType = DataType::Float64;
74
75  const IS_ATOMIC: bool = true;
76
77  fn to_value(&self) -> Value {
78    Value::Float64Val(*self)
79  }
80
81  fn try_from_value(v: &Value) -> CoreResult<f64> {
82    match v {
83      Value::Float64Val(res) => Ok(*res),
84      _ => Err(CoreError::invalid("cannot read f64 from value")),
85    }
86  }
87
88  fn to_atoms(&self) -> Vec<Self> {
89    vec![*self]
90  }
91
92  fn try_from_atoms(atoms: &[Self]) -> CoreResult<Self> {
93    Ok(atoms[0])
94  }
95
96  fn new_codec(codec: &str) -> Option<Box<dyn Codec<P=Self>>> {
97    if codec == Q_COMPRESS {
98      Some(Box::new(F64QCodec {}))
99    } else {
100      None
101    }
102  }
103}
104