api3_common/
datapoint.rs

1use crate::abi::Int;
2use crate::error;
3
4/// The data point struct in the original API3 beacon server contract
5#[derive(Clone, Default)]
6pub struct DataPoint {
7    pub value: Int,
8    pub timestamp: u32,
9}
10
11impl DataPoint {
12    /// Len of the data point as bytes, value is 32 bytes and timestamp is 4 bytes
13    const LEN: usize = 36;
14
15    pub fn new(value: Int, timestamp: u32) -> Self {
16        Self { value, timestamp }
17    }
18
19    pub fn from(raw: Vec<u8>) -> Result<Self, error::Error> {
20        if raw.len() != Self::LEN {
21            Err(error::Error::CannotDeserializeDataPoint)
22        } else {
23            let value = Int::from_big_endian(&raw[0..32]);
24            Ok(Self {
25                value,
26                timestamp: u32::from_be_bytes([raw[32], raw[33], raw[34], raw[35]]),
27            })
28        }
29    }
30}
31
32impl From<DataPoint> for Vec<u8> {
33    fn from(d: DataPoint) -> Self {
34        let mut v = vec![0u8; DataPoint::LEN];
35        d.value.to_big_endian(&mut v[0..32]);
36        v[32..].copy_from_slice(&d.timestamp.to_be_bytes());
37        v
38    }
39}
40
41impl From<DataPoint> for [u8; 36] {
42    fn from(d: DataPoint) -> Self {
43        let mut v = [0u8; DataPoint::LEN];
44        d.value.to_big_endian(&mut v[0..32]);
45        v[32..].copy_from_slice(&d.timestamp.to_be_bytes());
46        v
47    }
48}