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
pub mod sel;

use std::num::NonZeroU16;

pub mod sdr;

use crate::{fmt::LogItem, log_vec, Loggable};

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Timestamp(u32);

impl core::fmt::Display for Timestamp {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.0 == 0 {
            write!(f, "Unknown")
        } else {
            #[cfg(feature = "time")]
            {
                let timestamp = time::OffsetDateTime::from_unix_timestamp(self.0 as i64).unwrap();

                let time = timestamp
                    .format(&time::format_description::well_known::Rfc3339)
                    .unwrap();

                write!(f, "{}", time)
            }

            #[cfg(not(feature = "time"))]
            write!(f, "{}", self.0)
        }
    }
}

impl From<u32> for Timestamp {
    fn from(value: u32) -> Self {
        Self(value)
    }
}

#[derive(Debug, Clone)]
pub struct AllocInfo {
    pub num_alloc_units: Option<NonZeroU16>,
    pub alloc_unit_size: Option<NonZeroU16>,
    pub num_free_units: u16,
    pub largest_free_blk: u16,
    pub max_record_size: u8,
}

impl AllocInfo {
    pub fn parse(data: &[u8]) -> Option<Self> {
        if data.len() < 8 {
            return None;
        }

        let num_alloc_units = NonZeroU16::new(u16::from_le_bytes([data[0], data[1]]));
        let alloc_unit_size = NonZeroU16::new(u16::from_le_bytes([data[2], data[3]]));
        let num_free_units = u16::from_le_bytes([data[4], data[5]]);
        let largest_free_blk = u16::from_le_bytes([data[6], data[7]]);
        let max_record_size = data[8];

        Some(Self {
            num_alloc_units,
            alloc_unit_size,
            num_free_units,
            largest_free_blk,
            max_record_size,
        })
    }
}

impl Loggable for AllocInfo {
    fn into_log(&self) -> Vec<LogItem> {
        let unspecified_if_zero = |v: Option<NonZeroU16>| {
            if let Some(v) = v {
                format!("{}", v.get())
            } else {
                "Unspecified".into()
            }
        };

        let num_alloc_units = unspecified_if_zero(self.num_alloc_units);
        let alloc_unit_size = unspecified_if_zero(self.alloc_unit_size);

        log_vec!(
            (1, "# of units", num_alloc_units),
            (1, "Unit size", alloc_unit_size),
            (1, "# free units", self.num_free_units),
            (1, "Largest free block", self.largest_free_blk),
            (1, "Max record size", self.max_record_size),
        )
    }
}