use alloc::vec::Vec;
use crate::ber::{Encoder, Tag, Tlv, universal};
use crate::common::{DecodeReason, EntryTime, Error, Limits, Result};
use crate::proto::data::DataView;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TimeOfDay {
pub time: EntryTime,
pub dated: bool,
}
impl TimeOfDay {
pub const fn dated(time: EntryTime) -> TimeOfDay {
TimeOfDay { time, dated: true }
}
pub const fn from_unix_millis(millis: u64) -> TimeOfDay {
TimeOfDay::dated(EntryTime::from_unix_millis(millis))
}
pub fn from_octets(bytes: &[u8]) -> Result<TimeOfDay> {
match bytes {
[a, b, c, d] => Ok(TimeOfDay { time: EntryTime { millis_of_day: u32::from_be_bytes([*a, *b, *c, *d]), days_since_1984: 0 }, dated: false }),
_ if bytes.len() == 6 => {
let six = <[u8; 6]>::try_from(bytes).map_err(|_| Error::decode(DecodeReason::BadValue, 0))?;
Ok(TimeOfDay::dated(EntryTime::from_octets(six)))
}
_ => Err(Error::decode(DecodeReason::BadValue, 0)),
}
}
pub fn to_octets(self) -> Vec<u8> {
let six = self.time.to_octets();
if self.dated { six.to_vec() } else { six.get(..4).unwrap_or(&six).to_vec() }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RangeStart<'a> {
Time(TimeOfDay),
Entry(&'a [u8]),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RangeStop {
Time(TimeOfDay),
Count(i32),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AfterEntry<'a> {
pub time: TimeOfDay,
pub entry_id: &'a [u8],
}
pub const REASON_CODE_TAG: &str = "ReasonCode";
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct JournalVariable<'a> {
pub tag: &'a str,
pub value: Tlv<'a>,
}
impl<'a> JournalVariable<'a> {
pub fn value(&self) -> Option<DataView<'a>> {
DataView::from_tlv(self.value).ok()
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct JournalEntry<'a> {
pub entry_id: &'a [u8],
pub occurred: TimeOfDay,
pub variables: Vec<JournalVariable<'a>>,
pub annotation: Option<&'a str>,
origin: Option<Tlv<'a>>,
}
const TAG_SEQUENCE: Tag = Tag::universal(universal::SEQUENCE, true);
impl<'a> JournalEntry<'a> {
pub fn new(entry_id: &'a [u8], occurred: TimeOfDay, variables: Vec<JournalVariable<'a>>) -> JournalEntry<'a> {
JournalEntry { entry_id, occurred, variables, annotation: None, origin: None }
}
pub fn annotated(entry_id: &'a [u8], occurred: TimeOfDay, annotation: &'a str) -> JournalEntry<'a> {
JournalEntry { entry_id, occurred, variables: Vec::new(), annotation: Some(annotation), origin: None }
}
pub(super) fn parse(t: &Tlv<'a>, limits: &Limits) -> Result<JournalEntry<'a>> {
let mut c = t.expect(TAG_SEQUENCE)?.children();
let entry_id = c.next_tag(Tag::context(0))?.value;
if entry_id.len() > limits.max_primitive_len {
return Err(Error::LimitExceeded { limit: "max_primitive_len", value: entry_id.len() });
}
let origin = c.next_if_tag(Tag::context_constructed(1))?;
let content = c.next_tag(Tag::context_constructed(2))?;
let mut cc = content.children();
let occurred = TimeOfDay::from_octets(cc.next_tag(Tag::context(0))?.value)?;
let _ = cc.next_if_tag(Tag::context_constructed(1))?;
let mut variables = Vec::new();
let mut annotation = None;
match cc.next_required() {
Ok(form) if form.tag == Tag::context_constructed(2) => {
let mut f = form.children();
let _ = f.next_if_tag(Tag::context_constructed(0))?;
if let Some(list) = f.next_if_tag(Tag::context_constructed(1))? {
for v in list.children() {
if variables.len() >= limits.max_dataset_members {
return Err(Error::LimitExceeded { limit: "max_dataset_members", value: variables.len() + 1 });
}
let mut m = v?.expect(TAG_SEQUENCE)?.children();
let tag = m.next_tag(Tag::context(0))?.visible_string()?;
let value = m.next_tag(Tag::context_constructed(1))?.children().next_required()?;
DataView::from_tlv(value)?;
variables.push(JournalVariable { tag, value });
}
}
}
Ok(form) if form.tag == Tag::context(3) => annotation = Some(form.visible_string()?),
Ok(form) => return Err(Error::decode(DecodeReason::UnexpectedTag, form.offset)),
Err(e) => return Err(e),
}
Ok(JournalEntry { entry_id, occurred, variables, annotation, origin })
}
pub(super) fn write(&self, e: &mut Encoder) -> Result<()> {
e.constructed(TAG_SEQUENCE, |e| {
e.primitive(Tag::context(0), self.entry_id)?;
match self.origin {
Some(o) => {
e.primitive(o.tag, o.value)?;
}
None => {
e.constructed(Tag::context_constructed(1), |e| {
e.constructed(TAG_SEQUENCE, |_| Ok(()))?;
Ok(())
})?;
}
}
e.constructed(Tag::context_constructed(2), |e| {
e.primitive(Tag::context(0), &self.occurred.to_octets())?;
match self.annotation {
Some(a) => {
e.visible_string(Tag::context(3), a)?;
}
None => {
e.constructed(Tag::context_constructed(2), |e| {
e.constructed(Tag::context_constructed(1), |e| {
for v in &self.variables {
e.constructed(TAG_SEQUENCE, |e| {
e.visible_string(Tag::context(0), v.tag)?;
e.constructed(Tag::context_constructed(1), |e| {
e.primitive(v.value.tag, v.value.value)?;
Ok(())
})?;
Ok(())
})?;
}
Ok(())
})?;
Ok(())
})?;
}
}
Ok(())
})?;
Ok(())
})?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ber::Cursor;
#[test]
fn a_journal_entry_always_names_an_originating_application() {
let entry = JournalEntry::annotated(&[0, 0, 0, 0, 0, 0, 0, 1], TimeOfDay::from_unix_millis(1_700_000_000_000), "started");
let mut e = Encoder::new();
entry.write(&mut e).expect("encode");
let bytes = e.into_vec();
let mut c = Cursor::new(&bytes).next_required().expect("entry").children();
assert_eq!(c.next_required().expect("entryIdentifier").tag, Tag::context(0));
let origin = c.next_required().expect("originatingApplication");
assert_eq!(origin.tag, Tag::context_constructed(1));
assert_eq!(origin.value, &[0x30, 0x00], "an empty ApplicationReference is a SEQUENCE with no fields");
assert_eq!(c.next_required().expect("entryContent").tag, Tag::context_constructed(2));
let back = JournalEntry::parse(&Cursor::new(&bytes).next_required().expect("tlv"), &Limits::DEFAULT).expect("decode");
let mut re = Encoder::new();
back.write(&mut re).expect("re-encode");
assert_eq!(re.into_vec(), bytes);
assert_eq!(back.annotation, Some("started"));
}
#[test]
fn a_time_of_day_keeps_the_width_it_arrived_in() {
let dated = TimeOfDay::from_unix_millis(1_700_000_000_500);
assert!(dated.dated);
assert_eq!(dated.to_octets().len(), 6);
assert_eq!(TimeOfDay::from_octets(&dated.to_octets()).unwrap(), dated);
let plain = TimeOfDay::from_octets(&[0, 0, 0x27, 0x10]).unwrap();
assert!(!plain.dated);
assert_eq!(plain.time.millis_of_day, 10_000);
assert_eq!(plain.to_octets(), [0, 0, 0x27, 0x10]);
assert!(TimeOfDay::from_octets(&[0, 0, 0]).is_err());
}
}