ironsbe-schema 0.3.0

SBE XML schema parser and type definitions for IronSBE
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
//! Intermediate representation for code generation.
//!
//! This module provides a flattened, resolved representation of the schema
//! that is easier to use for code generation.

use crate::types::{PrimitiveType, Schema, TypeDef};
use std::collections::HashMap;

/// Intermediate representation of a schema for code generation.
#[derive(Debug, Clone)]
pub struct SchemaIr {
    /// Package name.
    pub package: String,
    /// Schema ID.
    pub schema_id: u16,
    /// Schema version.
    pub schema_version: u16,
    /// Resolved types with their full information.
    pub types: HashMap<String, ResolvedType>,
    /// Messages with resolved field types.
    pub messages: Vec<ResolvedMessage>,
}

impl SchemaIr {
    /// Creates an intermediate representation from a parsed schema.
    #[must_use]
    pub fn from_schema(schema: &Schema) -> Self {
        let mut ir = Self {
            package: schema.package.clone(),
            schema_id: schema.id,
            schema_version: schema.version,
            types: HashMap::new(),
            messages: Vec::new(),
        };

        // Resolve types
        for type_def in &schema.types {
            let resolved = ResolvedType::from_type_def(type_def);
            ir.types.insert(resolved.name.clone(), resolved);
        }

        // Resolve messages
        for msg in &schema.messages {
            ir.messages
                .push(ResolvedMessage::from_message_def(msg, &ir.types));
        }

        ir
    }

    /// Gets a resolved type by name.
    #[must_use]
    pub fn get_type(&self, name: &str) -> Option<&ResolvedType> {
        self.types.get(name)
    }
}

/// Resolved type information.
#[derive(Debug, Clone)]
pub struct ResolvedType {
    /// Type name.
    pub name: String,
    /// Type kind.
    pub kind: TypeKind,
    /// Encoded length in bytes.
    pub encoded_length: usize,
    /// Rust type representation.
    pub rust_type: String,
    /// Whether this is an array type.
    pub is_array: bool,
    /// Array length (if array).
    pub array_length: Option<usize>,
}

impl ResolvedType {
    /// Creates a resolved type from a type definition.
    #[must_use]
    pub fn from_type_def(type_def: &TypeDef) -> Self {
        match type_def {
            TypeDef::Primitive(p) => Self {
                name: p.name.clone(),
                kind: TypeKind::Primitive(p.primitive_type),
                encoded_length: p.encoded_length(),
                rust_type: if p.is_array() {
                    format!(
                        "[{}; {}]",
                        p.primitive_type.rust_type(),
                        p.length.unwrap_or(1)
                    )
                } else {
                    p.primitive_type.rust_type().to_string()
                },
                is_array: p.is_array(),
                array_length: p.length,
            },
            TypeDef::Composite(c) => {
                let mut offset = 0usize;
                let fields = c
                    .fields
                    .iter()
                    .filter_map(|f| {
                        let field_offset = offset;
                        offset += f.encoded_length;
                        f.primitive_type.map(|prim| CompositeFieldInfo {
                            name: f.name.clone(),
                            primitive_type: prim,
                            offset: field_offset,
                            encoded_length: f.encoded_length,
                        })
                    })
                    .collect();
                Self {
                    name: c.name.clone(),
                    kind: TypeKind::Composite { fields },
                    encoded_length: c.encoded_length(),
                    rust_type: to_pascal_case(&c.name),
                    is_array: false,
                    array_length: None,
                }
            }
            TypeDef::Enum(e) => {
                let variants: Vec<EnumVariant> = e
                    .valid_values
                    .iter()
                    .filter_map(|v| {
                        // Use signed parsing for signed types, unsigned for others
                        let value = if e.encoding_type.is_signed() {
                            v.as_i64()
                        } else {
                            v.as_u64().map(|u| u as i64)
                        };
                        value.map(|val| EnumVariant {
                            name: v.name.clone(),
                            value: val,
                        })
                    })
                    .collect();
                Self {
                    name: e.name.clone(),
                    kind: TypeKind::Enum {
                        encoding: e.encoding_type,
                        variants,
                    },
                    encoded_length: e.encoding_type.size(),
                    rust_type: to_pascal_case(&e.name),
                    is_array: false,
                    array_length: None,
                }
            }
            TypeDef::Set(s) => {
                let choices = s
                    .choices
                    .iter()
                    .map(|c| SetVariant {
                        name: c.name.clone(),
                        bit_position: c.bit_position,
                    })
                    .collect();
                Self {
                    name: s.name.clone(),
                    kind: TypeKind::Set {
                        encoding: s.encoding_type,
                        choices,
                    },
                    encoded_length: s.encoding_type.size(),
                    rust_type: to_pascal_case(&s.name),
                    is_array: false,
                    array_length: None,
                }
            }
        }
    }

    /// Creates a resolved type for a built-in primitive.
    #[must_use]
    pub fn from_primitive(prim: PrimitiveType) -> Self {
        Self {
            name: prim.sbe_name().to_string(),
            kind: TypeKind::Primitive(prim),
            encoded_length: prim.size(),
            rust_type: prim.rust_type().to_string(),
            is_array: false,
            array_length: None,
        }
    }
}

/// Enum variant with name and discriminant value.
#[derive(Debug, Clone)]
pub struct EnumVariant {
    /// Variant name (will be converted to PascalCase).
    pub name: String,
    /// Discriminant value (i64 to support signed encodings).
    pub value: i64,
}

/// Set choice with name and bit position.
#[derive(Debug, Clone)]
pub struct SetVariant {
    /// Choice name (will be converted to PascalCase).
    pub name: String,
    /// Bit position (0-based).
    pub bit_position: u8,
}

/// Composite field information for code generation.
#[derive(Debug, Clone)]
pub struct CompositeFieldInfo {
    /// Field name.
    pub name: String,
    /// Primitive type of this field.
    pub primitive_type: PrimitiveType,
    /// Offset within the composite.
    pub offset: usize,
    /// Encoded length in bytes.
    pub encoded_length: usize,
}

/// Type kind enumeration.
#[derive(Debug, Clone)]
pub enum TypeKind {
    /// Primitive type.
    Primitive(PrimitiveType),
    /// Composite type with fields.
    Composite {
        /// Fields in the composite.
        fields: Vec<CompositeFieldInfo>,
    },
    /// Enum type with encoding and variants.
    Enum {
        /// Underlying encoding type.
        encoding: PrimitiveType,
        /// Enum variants with discriminant values.
        variants: Vec<EnumVariant>,
    },
    /// Set (bitfield) type with encoding and choices.
    Set {
        /// Underlying encoding type.
        encoding: PrimitiveType,
        /// Bit choices.
        choices: Vec<SetVariant>,
    },
}

/// Resolved message information.
#[derive(Debug, Clone)]
pub struct ResolvedMessage {
    /// Message name.
    pub name: String,
    /// Template ID.
    pub template_id: u16,
    /// Block length.
    pub block_length: u16,
    /// Resolved fields.
    pub fields: Vec<ResolvedField>,
    /// Resolved groups.
    pub groups: Vec<ResolvedGroup>,
    /// Variable data fields.
    pub var_data: Vec<ResolvedVarData>,
}

impl ResolvedMessage {
    /// Creates a resolved message from a message definition.
    #[must_use]
    pub fn from_message_def(
        msg: &crate::messages::MessageDef,
        types: &HashMap<String, ResolvedType>,
    ) -> Self {
        let fields = msg
            .fields
            .iter()
            .map(|f| ResolvedField::from_field_def(f, types))
            .collect();

        let groups = msg
            .groups
            .iter()
            .map(|g| ResolvedGroup::from_group_def(g, types))
            .collect();

        let var_data = msg
            .data_fields
            .iter()
            .map(|d| ResolvedVarData {
                name: d.name.clone(),
                id: d.id,
                type_name: d.type_name.clone(),
            })
            .collect();

        Self {
            name: msg.name.clone(),
            template_id: msg.id,
            block_length: msg.block_length,
            fields,
            groups,
            var_data,
        }
    }

    /// Returns the decoder struct name.
    #[must_use]
    pub fn decoder_name(&self) -> String {
        format!("{}Decoder", self.name)
    }

    /// Returns the encoder struct name.
    #[must_use]
    pub fn encoder_name(&self) -> String {
        format!("{}Encoder", self.name)
    }
}

/// Resolved field information.
#[derive(Debug, Clone)]
pub struct ResolvedField {
    /// Field name.
    pub name: String,
    /// Field ID.
    pub id: u16,
    /// Type name.
    pub type_name: String,
    /// Offset in bytes.
    pub offset: usize,
    /// Encoded length in bytes.
    pub encoded_length: usize,
    /// Rust type.
    pub rust_type: String,
    /// Getter method name.
    pub getter_name: String,
    /// Setter method name.
    pub setter_name: String,
    /// Whether the field is optional.
    pub is_optional: bool,
    /// Whether the field is an array.
    pub is_array: bool,
    /// Array length (if array).
    pub array_length: Option<usize>,
    /// Primitive type (if applicable).
    pub primitive_type: Option<PrimitiveType>,
}

impl ResolvedField {
    /// Creates a resolved field from a field definition.
    #[must_use]
    pub fn from_field_def(
        field: &crate::messages::FieldDef,
        types: &HashMap<String, ResolvedType>,
    ) -> Self {
        let resolved_type = types.get(&field.type_name).cloned().or_else(|| {
            PrimitiveType::from_sbe_name(&field.type_name).map(ResolvedType::from_primitive)
        });

        let (encoded_length, rust_type, is_array, array_length, primitive_type) =
            if let Some(rt) = &resolved_type {
                (
                    rt.encoded_length,
                    rt.rust_type.clone(),
                    rt.is_array,
                    rt.array_length,
                    match &rt.kind {
                        TypeKind::Primitive(p) => Some(*p),
                        _ => None,
                    },
                )
            } else {
                (field.encoded_length, "u64".to_string(), false, None, None)
            };

        Self {
            name: field.name.clone(),
            id: field.id,
            type_name: field.type_name.clone(),
            offset: field.offset,
            encoded_length,
            rust_type,
            getter_name: to_snake_case(&field.name),
            setter_name: format!("set_{}", to_snake_case(&field.name)),
            is_optional: field.is_optional(),
            is_array,
            array_length,
            primitive_type,
        }
    }
}

/// Resolved group information.
#[derive(Debug, Clone)]
pub struct ResolvedGroup {
    /// Group name.
    pub name: String,
    /// Group ID.
    pub id: u16,
    /// Block length per entry.
    pub block_length: u16,
    /// Resolved fields.
    pub fields: Vec<ResolvedField>,
    /// Nested groups.
    pub nested_groups: Vec<ResolvedGroup>,
    /// Variable data fields.
    pub var_data: Vec<ResolvedVarData>,
}

impl ResolvedGroup {
    /// Creates a resolved group from a group definition.
    #[must_use]
    pub fn from_group_def(
        group: &crate::messages::GroupDef,
        types: &HashMap<String, ResolvedType>,
    ) -> Self {
        let fields = group
            .fields
            .iter()
            .map(|f| ResolvedField::from_field_def(f, types))
            .collect();

        let nested_groups = group
            .nested_groups
            .iter()
            .map(|g| ResolvedGroup::from_group_def(g, types))
            .collect();

        let var_data = group
            .data_fields
            .iter()
            .map(|d| ResolvedVarData {
                name: d.name.clone(),
                id: d.id,
                type_name: d.type_name.clone(),
            })
            .collect();

        Self {
            name: group.name.clone(),
            id: group.id,
            block_length: group.block_length,
            fields,
            nested_groups,
            var_data,
        }
    }

    /// Returns the decoder struct name.
    #[must_use]
    pub fn decoder_name(&self) -> String {
        format!("{}GroupDecoder", to_pascal_case(&self.name))
    }

    /// Returns the entry decoder struct name.
    #[must_use]
    pub fn entry_decoder_name(&self) -> String {
        format!("{}EntryDecoder", to_pascal_case(&self.name))
    }

    /// Returns the encoder struct name.
    #[must_use]
    pub fn encoder_name(&self) -> String {
        format!("{}GroupEncoder", to_pascal_case(&self.name))
    }

    /// Returns the entry encoder struct name.
    #[must_use]
    pub fn entry_encoder_name(&self) -> String {
        format!("{}EntryEncoder", to_pascal_case(&self.name))
    }
}

/// Resolved variable data field.
#[derive(Debug, Clone)]
pub struct ResolvedVarData {
    /// Field name.
    pub name: String,
    /// Field ID.
    pub id: u16,
    /// Type name.
    pub type_name: String,
}

/// Converts a string to snake_case.
#[must_use]
pub fn to_snake_case(s: &str) -> String {
    let mut result = String::with_capacity(s.len() + 4);
    let mut prev_lower = false;
    let mut start = 0;
    let mut first = true;

    for segment in s.split(|c: char| !c.is_alphanumeric()) {
        if segment.is_empty() {
            continue;
        }
        let chars: Vec<char> = segment.chars().collect();
        let len = chars.len();

        for i in 0..len {
            let c = chars[i];
            let is_lower = c.is_lowercase();
            let is_upper = c.is_uppercase();

            if i > 0 {
                let prev = chars[i - 1];
                let next_is_lower = chars.get(i + 1).is_some_and(|n| n.is_lowercase());

                // Word boundary: lowercase->uppercase OR acronym end (XXXy -> XXX_Y)
                let boundary =
                    (prev_lower && is_upper) || (prev.is_uppercase() && is_upper && next_is_lower);

                if boundary {
                    if !first {
                        result.push('_');
                    }
                    for wc in &chars[start..i] {
                        result.push(wc.to_ascii_lowercase());
                    }
                    start = i;
                    first = false;
                }
            }

            prev_lower = is_lower;
        }

        // Output remaining chars
        if !first {
            result.push('_');
        }
        for wc in &chars[start..] {
            result.push(wc.to_ascii_lowercase());
        }
        first = false;
        start = 0;
    }

    result
}

/// Converts a string to SCREAMING_SNAKE_CASE.
/// Treats `-` as a word separator and normalizes to `_`.
#[must_use]
pub fn to_screaming_snake_case(s: &str) -> String {
    let mut result = String::with_capacity(s.len() + 4);
    let mut last_was_separator = false;
    for (i, c) in s.chars().enumerate() {
        if c == '-' {
            if !last_was_separator {
                result.push('_');
            }
            last_was_separator = true;
        } else if c.is_uppercase() && i > 0 && !last_was_separator {
            result.push('_');
            result.push(c.to_ascii_uppercase());
            last_was_separator = false;
        } else {
            result.push(c.to_ascii_uppercase());
            last_was_separator = false;
        }
    }
    result
}

/// Converts a string to PascalCase.
#[must_use]
pub fn to_pascal_case(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut capitalize_next = true;

    for c in s.chars() {
        if c == '_' || c == '-' {
            capitalize_next = true;
        } else if capitalize_next {
            result.push(c.to_ascii_uppercase());
            capitalize_next = false;
        } else {
            result.push(c);
        }
    }

    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::parse_schema;

    #[test]
    fn test_to_snake_case() {
        assert_eq!(to_snake_case("clOrdId"), "cl_ord_id");
        assert_eq!(to_snake_case("symbol"), "symbol");
        assert_eq!(to_snake_case("MDEntryPx"), "md_entry_px");
        assert_eq!(to_snake_case("some-hyphenated"), "some_hyphenated");
        // Hyphen followed by uppercase should not produce double underscore
        assert_eq!(to_snake_case("some-Hyphen"), "some_hyphen");
        // Underscores are treated as word separators
        assert_eq!(to_snake_case("some_underscore"), "some_underscore");
        assert_eq!(
            to_snake_case("some-mixed_separator"),
            "some_mixed_separator"
        );
        assert_eq!(
            to_snake_case("some__double_underscore"),
            "some_double_underscore"
        );
        assert_eq!(to_snake_case("some--double-hyphen"), "some_double_hyphen");
        // Leading uppercase with underscore
        assert_eq!(to_snake_case("AB_C"), "ab_c");
        assert_eq!(to_snake_case("ABC"), "abc");
        // Issue #7: set choice names with underscores
        assert_eq!(to_snake_case("REDUCE_ONLY"), "reduce_only");
        assert_eq!(to_snake_case("DISABLE_SELF_TRADE"), "disable_self_trade");
    }

    #[test]
    fn test_to_screaming_snake_case() {
        assert_eq!(to_screaming_snake_case("clOrdId"), "CL_ORD_ID");
        assert_eq!(to_screaming_snake_case("symbol"), "SYMBOL");
        assert_eq!(
            to_screaming_snake_case("some-hyphenated"),
            "SOME_HYPHENATED"
        );
        // Hyphen followed by uppercase should not produce double underscore
        assert_eq!(to_screaming_snake_case("some-Hyphen"), "SOME_HYPHEN");
    }

    #[test]
    fn test_to_pascal_case() {
        assert_eq!(to_pascal_case("message_header"), "MessageHeader");
        assert_eq!(to_pascal_case("side"), "Side");
        assert_eq!(to_pascal_case("order-type"), "OrderType");
    }

    #[test]
    fn test_schema_ir_from_schema() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<sbe:messageSchema xmlns:sbe="http://fixprotocol.io/2016/sbe"
                   package="test" id="1" version="1" byteOrder="littleEndian">
    <types>
        <type name="uint64" primitiveType="uint64"/>
    </types>
    <sbe:message name="Test" id="1" blockLength="8">
        <field name="value" id="1" type="uint64" offset="0"/>
    </sbe:message>
</sbe:messageSchema>"#;

        let schema = parse_schema(xml).expect("Failed to parse");
        let ir = SchemaIr::from_schema(&schema);

        assert_eq!(ir.package, "test");
        assert_eq!(ir.schema_id, 1);
        assert_eq!(ir.schema_version, 1);
        assert!(!ir.messages.is_empty());
    }

    #[test]
    fn test_resolved_type_from_primitive() {
        let resolved = ResolvedType::from_primitive(PrimitiveType::Uint64);
        assert_eq!(resolved.name, "uint64");
        assert_eq!(resolved.encoded_length, 8);
        assert_eq!(resolved.rust_type, "u64");
        assert!(!resolved.is_array);
    }

    #[test]
    fn test_type_kind_debug() {
        let kind = TypeKind::Primitive(PrimitiveType::Int32);
        let debug_str = format!("{:?}", kind);
        assert!(debug_str.contains("Primitive"));

        let kind = TypeKind::Composite { fields: vec![] };
        let debug_str = format!("{:?}", kind);
        assert!(debug_str.contains("Composite"));

        let kind = TypeKind::Enum {
            encoding: PrimitiveType::Uint8,
            variants: vec![],
        };
        let debug_str = format!("{:?}", kind);
        assert!(debug_str.contains("Enum"));

        let kind = TypeKind::Set {
            encoding: PrimitiveType::Uint16,
            choices: vec![],
        };
        let debug_str = format!("{:?}", kind);
        assert!(debug_str.contains("Set"));
    }

    #[test]
    fn test_resolved_type_clone() {
        let resolved = ResolvedType::from_primitive(PrimitiveType::Float);
        let cloned = resolved.clone();
        assert_eq!(resolved.name, cloned.name);
        assert_eq!(resolved.encoded_length, cloned.encoded_length);
    }

    #[test]
    fn test_schema_ir_with_enum() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<sbe:messageSchema xmlns:sbe="http://fixprotocol.io/2016/sbe"
                   package="test" id="1" version="1" byteOrder="littleEndian">
    <types>
        <enum name="Side" encodingType="uint8">
            <validValue name="Buy">1</validValue>
            <validValue name="Sell">2</validValue>
        </enum>
    </types>
    <sbe:message name="Test" id="1" blockLength="1">
        <field name="side" id="1" type="Side" offset="0"/>
    </sbe:message>
</sbe:messageSchema>"#;

        let schema = parse_schema(xml).expect("Failed to parse");
        let ir = SchemaIr::from_schema(&schema);

        assert!(ir.types.contains_key("Side"));
    }

    #[test]
    fn test_schema_ir_with_composite() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<sbe:messageSchema xmlns:sbe="http://fixprotocol.io/2016/sbe"
                   package="test" id="1" version="1" byteOrder="littleEndian">
    <types>
        <composite name="Decimal">
            <type name="mantissa" primitiveType="int64"/>
            <type name="exponent" primitiveType="int8"/>
        </composite>
    </types>
    <sbe:message name="Test" id="1" blockLength="9">
        <field name="price" id="1" type="Decimal" offset="0"/>
    </sbe:message>
</sbe:messageSchema>"#;

        let schema = parse_schema(xml).expect("Failed to parse");
        let ir = SchemaIr::from_schema(&schema);

        assert!(ir.types.contains_key("Decimal"));
    }
}