use std::path::Path;
use {
crate::bytes_helper::{ser_code_string, ser_date_string},
serde::{Serialize, Serializer},
};
pub mod fq;
#[derive(Debug, Clone, Copy, Serialize)]
pub struct Day {
#[serde(serialize_with = "ser_date_string")]
pub date: u32,
#[serde(serialize_with = "ser_code_string")]
pub code: u32,
pub open: f32,
pub high: f32,
pub low: f32,
pub close: f32,
pub amount: f32,
#[serde(serialize_with = "ser_vol")]
pub vol: u32,
}
fn ser_vol<S>(vol: &u32, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_f32(*vol as f32 / 100.)
}
impl Day {
pub fn from_bytes(code: u32, arr: &[u8]) -> Self {
use crate::bytes_helper::{f32_from_le_bytes, u32_from_le_bytes};
Self {
date: u32_from_le_bytes(arr, 0),
open: u32_from_le_bytes(arr, 4) as f32 / 100.,
high: u32_from_le_bytes(arr, 8) as f32 / 100.,
low: u32_from_le_bytes(arr, 12) as f32 / 100.,
close: u32_from_le_bytes(arr, 16) as f32 / 100.,
amount: f32_from_le_bytes(arr, 20),
vol: u32_from_le_bytes(arr, 24),
code,
}
}
pub fn from_file_into_vec<P: AsRef<Path>>(code: u32, p: P) -> crate::Result<Vec<Day>> {
Ok(std::fs::read(p)?
.chunks_exact(32)
.map(|b| Self::from_bytes(code, b))
.collect())
}
pub fn date_string(&self) -> String {
crate::bytes_helper::date_string(self.date)
}
pub fn ymd_arr(&self) -> [u32; 3] {
let x = self.date;
[x / 10000, x % 10000 / 100, x % 10000 % 100]
}
pub fn ymd(&self) -> chrono::naive::NaiveDate {
let [y, m, d] = self.ymd_arr();
chrono::naive::NaiveDate::from_ymd_opt(y as i32, m, d).unwrap()
}
}