rustysbe 0.7.4

FIX Simple Binary Encoding (SBE) support for `rustyfix`
Documentation
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use anyhow::Result;
use heck::{ToPascalCase, ToSnakeCase};
use roxmltree::Node;
use std::env;
use std::fs;
use std::io::Write;
use std::path::Path;

// Define types directly in build script to avoid circular dependency

#[allow(dead_code)]
#[derive(Debug, Default)]
struct MessageSchema {
    package: String,
    version: u16,
    semantic_version: String,
    description: String,
    types: Vec<SbeType>,
    messages: Vec<SbeMessage>,
}

#[allow(dead_code)]
#[derive(Debug)]
enum SbeType {
    Composite(SbeComposite),
    Enum(SbeEnum),
}

#[allow(dead_code)]
#[derive(Debug)]
struct SbeComposite {
    name: String,
    types: Vec<SbeField>,
}

#[allow(dead_code)]
#[derive(Debug)]
struct SbeEnum {
    name: String,
    encoding_type: String,
    valid_values: Vec<SbeValidValue>,
}

#[allow(dead_code)]
#[derive(Debug)]
struct SbeField {
    name: String,
    id: u16,
    field_type: String,
    description: String,
    presence: String,
    offset: u16,
    length: usize,
}

#[allow(dead_code)]
#[derive(Debug)]
struct SbeGroup {
    name: String,
    id: u16,
    dimension_type: String,
    fields: Vec<SbeField>,
    groups: Vec<SbeGroup>,
}

#[allow(dead_code)]
#[derive(Debug)]
struct SbeMessage {
    name: String,
    id: u16,
    description: String,
    fields: Vec<SbeField>,
    groups: Vec<SbeGroup>,
    block_length: u16,
}

#[allow(dead_code)]
#[derive(Debug)]
struct SbeValidValue {
    name: String,
    value: String,
}

fn get_type_size(sbe_type: &str, schema: &MessageSchema) -> usize {
    match sbe_type {
        "char" => 1,
        "int8" => 1,
        "uint8" => 1,
        "int16" => 2,
        "uint16" => 2,
        "int32" => 4,
        "uint32" => 4,
        "int64" => 8,
        "uint64" => 8,
        "float" => 4,
        "double" => 8,
        _ => {
            // It might be a composite type
            for t in &schema.types {
                if let SbeType::Composite(c) = t {
                    if c.name == sbe_type {
                        return c
                            .types
                            .iter()
                            .map(|f| get_type_size(&f.field_type, schema) * f.length)
                            .sum();
                    }
                }
            }
            0
        }
    }
}

fn parse_field(node: &Node) -> SbeField {
    SbeField {
        name: node.attribute("name").unwrap_or("").to_string(),
        id: node.attribute("id").unwrap_or("0").parse().unwrap_or(0),
        field_type: node.attribute("type").unwrap_or("").to_string(),
        description: node.attribute("description").unwrap_or("").to_string(),
        presence: node.attribute("presence").unwrap_or("required").to_string(),
        offset: node.attribute("offset").unwrap_or("0").parse().unwrap_or(0),
        length: node.attribute("length").unwrap_or("1").parse().unwrap_or(1),
    }
}

fn parse_group(node: &Node) -> SbeGroup {
    let mut fields = Vec::new();
    let mut groups = Vec::new();

    for child in node.children().filter(Node::is_element) {
        match child.tag_name().name() {
            "field" => fields.push(parse_field(&child)),
            "group" => groups.push(parse_group(&child)),
            _ => {}
        }
    }

    SbeGroup {
        name: node.attribute("name").unwrap_or("").to_string(),
        id: node.attribute("id").unwrap_or("0").parse().unwrap_or(0),
        dimension_type: node.attribute("dimensionType").unwrap_or("").to_string(),
        fields,
        groups,
    }
}

fn generate_code(schema: &MessageSchema, dest: &mut fs::File) -> Result<()> {
    writeln!(dest, "// Generated by `build.rs`. DO NOT EDIT.")?;
    writeln!(dest, "// SBE message types generated from schema")?;
    writeln!(dest)?;
    writeln!(dest, "#[allow(dead_code)]")?;
    writeln!(dest, "#[allow(unused_imports)]")?;
    writeln!(dest, "#[allow(non_snake_case)]")?;
    writeln!(dest, "#[allow(missing_docs)]")?;
    writeln!(dest)?;
    writeln!(
        dest,
        "use crate::{{SbeMessage, SbeDecoder, SbeEncoder, SbeResult}};"
    )?;
    writeln!(dest, "use zerocopy::{{IntoBytes, FromBytes, Unaligned}};")?;
    writeln!(dest)?;

    for sbe_type in &schema.types {
        match sbe_type {
            SbeType::Enum(e) => {
                writeln!(dest, "#[derive(Debug, Clone, Copy, PartialEq, Eq)]")?;
                writeln!(dest, "#[repr(u8)]")?;
                writeln!(dest, "pub enum {} {{", e.name.to_pascal_case())?;
                for (index, vv) in e.valid_values.iter().enumerate() {
                    let value = if let Ok(numeric_value) = vv.value.trim().parse::<u32>() {
                        numeric_value.to_string()
                    } else {
                        // If value is not numeric, use index
                        index.to_string()
                    };
                    writeln!(dest, "    {} = {},", vv.name.to_pascal_case(), value)?;
                }
                writeln!(dest, "}}")?;
                writeln!(dest)?;
            }
            SbeType::Composite(c) => {
                writeln!(
                    dest,
                    "#[derive(Debug, Clone, Copy, IntoBytes, FromBytes, Unaligned)]"
                )?;
                writeln!(dest, "#[repr(C, packed)]")?;
                writeln!(dest, "pub struct {} {{", c.name.to_pascal_case())?;
                for field in &c.types {
                    writeln!(
                        dest,
                        "    pub {}: {},",
                        field.name.to_snake_case(),
                        map_type(&field.field_type)
                    )?;
                }
                writeln!(dest, "}}")?;
                writeln!(dest)?;
            }
        }
    }

    for msg in &schema.messages {
        let name_pascal = msg.name.to_pascal_case();
        writeln!(dest, "/// {}", msg.description)?;
        writeln!(dest, "#[derive(Debug, Clone, Copy)]")?;
        writeln!(dest, "pub struct {name_pascal}<'a> {{")?;
        writeln!(dest, "    buffer: &'a [u8],")?;
        writeln!(dest, "    offset: usize,")?;
        writeln!(dest, "}}")?;
        writeln!(dest)?;

        writeln!(dest, "impl<'a> {name_pascal}<'a> {{")?;
        writeln!(dest, "    pub const TEMPLATE_ID: u16 = {};", msg.id)?;
        writeln!(
            dest,
            "    pub const SCHEMA_VERSION: u16 = {};",
            schema.version
        )?;
        writeln!(
            dest,
            "    pub const BLOCK_LENGTH: u16 = {};",
            msg.block_length
        )?;
        writeln!(dest)?;

        writeln!(
            dest,
            "    pub fn wrap(buffer: &'a [u8], offset: usize) -> Self {{"
        )?;
        writeln!(dest, "        Self {{ buffer, offset }}")?;
        writeln!(dest, "    }}")?;
        writeln!(dest)?;

        for field in &msg.fields {
            let _field_name_pascal = field.name.to_pascal_case();
            let return_type = map_type(&field.field_type);
            if field.presence != "constant" {
                writeln!(
                    dest,
                    "    pub fn {}(&self) -> {} {{",
                    field.name.to_snake_case(),
                    return_type
                )?;
                writeln!(
                    dest,
                    "        let range = self.offset + {}..;",
                    field.offset
                )?;
                // NOTE: This is a simplified example. A real implementation would need
                // to handle endianness correctly.
                writeln!(
                    dest,
                    "        unsafe {{ *(&self.buffer[range.start] as *const u8 as *const {return_type}) }}"
                )?;
                writeln!(dest, "    }}")?;
                writeln!(dest)?;
            } else {
                writeln!(
                    dest,
                    "    pub fn {}(&self) -> {} {{",
                    field.name.to_snake_case(),
                    return_type
                )?;
                // TODO: get constant value from schema
                writeln!(dest, "         todo!(\"constant value\")")?;
                writeln!(dest, "    }}")?;
                writeln!(dest)?;
            }
        }

        writeln!(dest, "}}")?;
        writeln!(dest)?;

        // Generate SbeMessage trait implementation
        writeln!(dest, "impl SbeMessage for {name_pascal}<'_> {{")?;
        writeln!(dest, "    const TEMPLATE_ID: u16 = {};", msg.id)?;
        writeln!(dest, "    const SCHEMA_VERSION: u16 = {};", schema.version)?;
        writeln!(dest, "    const BLOCK_LENGTH: u16 = {};", msg.block_length)?;
        writeln!(
            dest,
            "    const MESSAGE_NAME: &'static str = \"{}\";",
            msg.name
        )?;
        writeln!(dest, "}}")?;
        writeln!(dest)?;
    }

    Ok(())
}

fn map_type(sbe_type: &str) -> String {
    match sbe_type {
        "" => "u8".to_string(), // Fallback for empty types
        "char" => "u8".to_string(),
        "int8" => "i8".to_string(),
        "uint8" => "u8".to_string(),
        "int16" => "i16".to_string(),
        "uint16" => "u16".to_string(),
        "int32" => "i32".to_string(),
        "uint32" => "u32".to_string(),
        "int64" => "i64".to_string(),
        "uint64" => "u64".to_string(),
        "float" => "f32".to_string(),
        "double" => "f64".to_string(),
        _ => sbe_type.to_pascal_case(), // For composite types, enums, etc.
    }
}

fn main() -> Result<()> {
    println!("cargo:rerun-if-changed=build.rs");
    println!("cargo:rerun-if-changed=resources/sbe.xml");

    let xml_string = fs::read_to_string("resources/sbe.xml")?;
    let doc = roxmltree::Document::parse(&xml_string)?;
    let root = doc.root_element();

    let mut schema = MessageSchema {
        package: root.attribute("package").unwrap_or("rustysbe").to_string(),
        version: root.attribute("version").unwrap_or("0").parse()?,
        semantic_version: root.attribute("semanticVersion").unwrap_or("").to_string(),
        description: root.attribute("description").unwrap_or("").to_string(),
        ..Default::default()
    };

    for node in root.children().filter(Node::is_element) {
        match node.tag_name().name() {
            "types" => {
                for type_node in node.children().filter(Node::is_element) {
                    match type_node.tag_name().name() {
                        "composite" => {
                            let types = type_node
                                .children()
                                .filter(Node::is_element)
                                .map(|n| parse_field(&n))
                                .collect();
                            schema.types.push(SbeType::Composite(SbeComposite {
                                name: type_node.attribute("name").unwrap_or("").to_string(),
                                types,
                            }));
                        }
                        "enum" => {
                            let valid_values = type_node
                                .children()
                                .filter(Node::is_element)
                                .map(|n| SbeValidValue {
                                    name: n.attribute("name").unwrap_or("").to_string(),
                                    value: n.text().unwrap_or("").to_string(),
                                })
                                .collect();
                            schema.types.push(SbeType::Enum(SbeEnum {
                                name: type_node.attribute("name").unwrap_or("").to_string(),
                                encoding_type: type_node
                                    .attribute("encodingType")
                                    .unwrap_or("")
                                    .to_string(),
                                valid_values,
                            }));
                        }
                        _ => {}
                    }
                }
            }
            "message" => {
                let mut fields = Vec::new();
                let mut groups = Vec::new();

                for child in node.children().filter(Node::is_element) {
                    match child.tag_name().name() {
                        "field" => fields.push(parse_field(&child)),
                        "group" => groups.push(parse_group(&child)),
                        _ => {}
                    }
                }

                let block_length = if let Some(bl) = node.attribute("blockLength") {
                    bl.parse()?
                } else {
                    fields
                        .iter()
                        .map(|f| get_type_size(&f.field_type, &schema) * f.length)
                        .sum::<usize>() as u16
                };

                schema.messages.push(SbeMessage {
                    name: node.attribute("name").unwrap_or("").to_string(),
                    id: node.attribute("id").unwrap_or("0").parse()?,
                    description: node.attribute("description").unwrap_or("").to_string(),
                    fields,
                    groups,
                    block_length,
                });
            }
            _ => {}
        }
    }

    // Debug output removed - was causing noisy build warnings
    // println!("cargo:warning=Parsed SBE schema: {schema:#?}");

    let out_dir = env::var_os("OUT_DIR").unwrap();
    let dest_path = Path::new(&out_dir).join("sbe.rs");
    let mut file = fs::File::create(&dest_path)?;

    generate_code(&schema, &mut file)?;

    Ok(())
}