1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
use pancake_db_idl::dml::field_value::Value;
use pancake_db_idl::dtype::DataType;

use crate::compression::Codec;
use crate::compression::q_codec::{F64QCodec, F32QCodec};
use crate::compression::Q_COMPRESS;
use crate::errors::{CoreError, CoreResult};
use crate::primitives::{Atom, Primitive};
use crate::utils;

impl Atom for f32 {
  const BYTE_SIZE: usize = 4;

  fn to_bytes(&self) -> Vec<u8> {
    self.to_be_bytes().to_vec()
  }

  fn try_from_bytes(bytes: &[u8]) -> CoreResult<Self> where Self: Sized {
    let byte_array = utils::try_byte_array::<4>(bytes)?;
    Ok(f32::from_be_bytes(byte_array))
  }
}

impl Atom for f64 {
  const BYTE_SIZE: usize = 8;

  fn to_bytes(&self) -> Vec<u8> {
    self.to_be_bytes().to_vec()
  }

  fn try_from_bytes(bytes: &[u8]) -> CoreResult<Self> {
    let byte_array = utils::try_byte_array::<8>(bytes)?;
    Ok(f64::from_be_bytes(byte_array))
  }
}

impl Primitive for f32 {
  type A = Self;
  const DTYPE: DataType = DataType::FLOAT32;

  const IS_ATOMIC: bool = true;

  fn to_value(&self) -> Value {
    Value::float32_val(*self)
  }

  fn try_from_value(v: &Value) -> CoreResult<f32> {
    match v {
      Value::float32_val(res) => Ok(*res),
      _ => Err(CoreError::invalid("cannot read f32 from value")),
    }
  }

  fn to_atoms(&self) -> Vec<Self> {
    vec![*self]
  }

  fn try_from_atoms(atoms: &[Self]) -> CoreResult<Self> {
    Ok(atoms[0])
  }

  fn new_codec(codec: &str) -> Option<Box<dyn Codec<P=Self>>> {
    if codec == Q_COMPRESS {
      Some(Box::new(F32QCodec {}))
    } else {
      None
    }
  }
}

impl Primitive for f64 {
  type A = Self;
  const DTYPE: DataType = DataType::FLOAT64;

  const IS_ATOMIC: bool = true;

  fn to_value(&self) -> Value {
    Value::float64_val(*self)
  }

  fn try_from_value(v: &Value) -> CoreResult<f64> {
    match v {
      Value::float64_val(res) => Ok(*res),
      _ => Err(CoreError::invalid("cannot read f64 from value")),
    }
  }

  fn to_atoms(&self) -> Vec<Self> {
    vec![*self]
  }

  fn try_from_atoms(atoms: &[Self]) -> CoreResult<Self> {
    Ok(atoms[0])
  }

  fn new_codec(codec: &str) -> Option<Box<dyn Codec<P=Self>>> {
    if codec == Q_COMPRESS {
      Some(Box::new(F64QCodec {}))
    } else {
      None
    }
  }
}