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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
use anyhow::{ensure, Result};
use funty::{Floating, Integral};
use structpack::{
    FloatingField, GenericFloatingField, GenericIntegralField, IntegralField, NumericField,
    SizedField,
};
use tlmcmddb::{cmd as cmddb, Component};

use super::Writer;

#[derive(Debug, Clone)]
pub struct Metadata {
    pub component_name: String,
    pub command_name: String,
    pub cmd_id: u16,
}

#[derive(Debug, Clone)]
pub struct CommandSchema {
    pub sized_parameters: Vec<NumericField>,
    pub static_size: usize,
    pub has_trailer_parameter: bool,
}

impl CommandSchema {
    pub fn build_writer<'b>(
        &'b self,
        bytes: &'b mut [u8],
    ) -> Writer<'b, std::slice::Iter<'b, NumericField>> {
        Writer::new(
            self.sized_parameters.iter(),
            self.static_size,
            self.has_trailer_parameter,
            bytes,
        )
    }
}

pub fn from_tlmcmddb(db: &tlmcmddb::Database) -> ComponentIter {
    ComponentIter {
        iter: db.components.iter(),
    }
}

pub struct ComponentIter<'a> {
    iter: std::slice::Iter<'a, Component>,
}

impl<'a> Iterator for ComponentIter<'a> {
    type Item = Iter<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        let component = self.iter.next()?;
        Some(Iter {
            name: &component.name,
            entries: component.cmd.entries.iter(),
        })
    }
}

pub struct Iter<'a> {
    name: &'a str,
    entries: std::slice::Iter<'a, cmddb::Entry>,
}

impl<'a> Iterator for Iter<'a> {
    type Item = Result<(Metadata, CommandSchema)>;

    fn next(&mut self) -> Option<Self::Item> {
        #[allow(clippy::never_loop)]
        loop {
            let cmddb::Entry::Command(command) = self.entries.next()? else {
                continue;
            };
            let metadata = Metadata {
                component_name: self.name.to_string(),
                command_name: command.name.to_string(),
                cmd_id: command.code,
            };
            return build_schema(command)
                .map(|schema| Some((metadata, schema)))
                .transpose();
        }
    }
}

fn build_schema(db: &cmddb::Command) -> Result<CommandSchema> {
    let mut params_iter = db.parameters.iter();
    let mut static_size_bits = 0;
    let mut sized_parameters = vec![];
    let mut has_trailer_parameter = false;
    for parameter in params_iter.by_ref() {
        if let Some(field) = build_numeric_field(static_size_bits, parameter) {
            static_size_bits += field.bit_len();
            sized_parameters.push(field);
        } else {
            // raw parameter is present
            has_trailer_parameter = true;
            break;
        }
    }
    ensure!(
        params_iter.next().is_none(),
        "trailer(RAW) parameter is valid only if at the last position"
    );
    let static_size = if static_size_bits == 0 {
        0
    } else {
        (static_size_bits - 1) / 8 + 1
    };
    Ok(CommandSchema {
        sized_parameters,
        static_size,
        has_trailer_parameter,
    })
}

fn build_numeric_field(offset: usize, parameter: &cmddb::Parameter) -> Option<NumericField> {
    match parameter.data_type {
        cmddb::DataType::Int8 => Some(NumericField::Integral(GenericIntegralField::I8(
            build_command_integral_field(offset, 8),
        ))),
        cmddb::DataType::Int16 => Some(NumericField::Integral(GenericIntegralField::I16(
            build_command_integral_field(offset, 16),
        ))),
        cmddb::DataType::Int32 => Some(NumericField::Integral(GenericIntegralField::I32(
            build_command_integral_field(offset, 32),
        ))),
        cmddb::DataType::Uint8 => Some(NumericField::Integral(GenericIntegralField::U8(
            build_command_integral_field(offset, 8),
        ))),
        cmddb::DataType::Uint16 => Some(NumericField::Integral(GenericIntegralField::U16(
            build_command_integral_field(offset, 16),
        ))),
        cmddb::DataType::Uint32 => Some(NumericField::Integral(GenericIntegralField::U32(
            build_command_integral_field(offset, 32),
        ))),
        cmddb::DataType::Float => Some(NumericField::Floating(GenericFloatingField::F32(
            build_command_floating_field(offset, 32),
        ))),
        cmddb::DataType::Double => Some(NumericField::Floating(GenericFloatingField::F64(
            build_command_floating_field(offset, 64),
        ))),
        cmddb::DataType::Raw => None,
    }
}

fn build_command_integral_field<T: Integral>(offset: usize, len: usize) -> IntegralField<T> {
    IntegralField::new(offset..offset + len).expect("never fails")
}

fn build_command_floating_field<T: Floating>(offset: usize, len: usize) -> FloatingField<T> {
    FloatingField::new(offset..offset + len).expect("never fails")
}