use std::ops::RangeInclusive;
use super::ts_to_dt;
use crate::{Publisher, RType, RecordHeader};
pub trait Record: AsRef<[u8]> {
type Header: RecordHeaderKind;
fn record_size(&self) -> usize;
fn rtype(&self) -> crate::Result<RType>;
fn raw_rtype(&self) -> u16;
fn publisher_id(&self) -> u16;
fn publisher(&self) -> crate::Result<Publisher>;
fn instrument_id(&self) -> u64;
fn raw_ts_event(&self) -> u64;
fn raw_index_ts(&self) -> u64 {
self.raw_ts_event()
}
fn index_ts(&self) -> Option<time::OffsetDateTime> {
ts_to_dt(self.raw_index_ts())
}
fn index_date(&self) -> Option<time::Date> {
self.index_ts().map(|dt| dt.date())
}
}
pub trait RecordMut: Record {
fn header_mut(&mut self) -> &mut Self::Header;
}
pub trait HasRType: Record {
fn has_rtype(rtype: u16) -> bool;
}
pub trait RecordHeaderKind: private::Sealed + Copy + std::fmt::Debug + 'static {
const HEADER_LEN: usize = size_of::<Self>();
const DBN_VERSIONS: RangeInclusive<u8>;
fn frame_len(data: &[u8]) -> crate::Result<usize>;
fn record_size(&self) -> usize;
fn raw_rtype(&self) -> u16;
}
impl RecordHeaderKind for RecordHeader {
const DBN_VERSIONS: RangeInclusive<u8> = 1..=3;
fn frame_len(data: &[u8]) -> crate::Result<usize> {
let length = data[0] as usize * RecordHeader::LENGTH_MULTIPLIER;
if length < Self::HEADER_LEN {
return Err(crate::Error::decode(format!(
"invalid record with impossible length {length} which is shorter than the header"
)));
}
Ok(length)
}
fn record_size(&self) -> usize {
RecordHeader::record_size(self)
}
fn raw_rtype(&self) -> u16 {
self.rtype as u16
}
}
impl RecordHeaderKind for crate::v4::RecordHeader {
const DBN_VERSIONS: RangeInclusive<u8> = 4..=4;
fn frame_len(data: &[u8]) -> crate::Result<usize> {
Ok(Self::HEADER_LEN + u16::from_le_bytes([data[0], data[1]]) as usize)
}
fn record_size(&self) -> usize {
crate::v4::RecordHeader::record_size(self)
}
fn raw_rtype(&self) -> u16 {
self.rtype
}
}
mod private {
pub trait Sealed {}
impl Sealed for super::RecordHeader {}
impl Sealed for crate::v4::RecordHeader {}
}