rustyasn 0.7.4

Abstract Syntax Notation One (ASN.1) encoding 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
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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
//! ASN.1 message implementation with `FieldMap` trait support.
//!
//! This module provides the core message types that implement `RustyFix` traits
//! for seamless integration with the FIX protocol ecosystem.

use crate::field_types::{Asn1FieldError, Asn1String, Asn1UInteger};
use crate::generated::{Asn1Field, Asn1FixMessage, FixFieldTag, FixMessageType};
use crate::types::{Field, FixMessage};
use rustyfix::{FieldMap, FieldType, FieldValueError, RepeatingGroup};
use std::collections::HashMap;

/// ASN.1 message that implements `FieldMap` for rustyfix integration.
#[derive(Debug, Clone, PartialEq)]
pub struct Message {
    /// Message type
    pub msg_type: FixMessageType,
    /// Sender company ID
    pub sender_comp_id: String,
    /// Target company ID
    pub target_comp_id: String,
    /// Message sequence number
    pub msg_seq_num: u64,
    /// Sending time (optional)
    pub sending_time: Option<String>,
    /// Fields indexed by tag for fast lookup
    fields: HashMap<u32, Vec<u8>>,
    /// Original field order for groups
    field_order: Vec<u32>,
}

impl Message {
    /// Creates a new ASN.1 message.
    pub fn new(
        msg_type: FixMessageType,
        sender_comp_id: String,
        target_comp_id: String,
        msg_seq_num: u64,
    ) -> Self {
        let mut fields = HashMap::new();
        let mut field_order = Vec::new();

        // Add standard header fields
        fields.insert(35, msg_type.as_str().as_bytes().to_vec());
        field_order.push(35);

        fields.insert(49, sender_comp_id.as_bytes().to_vec());
        field_order.push(49);

        fields.insert(56, target_comp_id.as_bytes().to_vec());
        field_order.push(56);

        fields.insert(34, ToString::to_string(&msg_seq_num).as_bytes().to_vec());
        field_order.push(34);

        Self {
            msg_type,
            sender_comp_id,
            target_comp_id,
            msg_seq_num,
            sending_time: None,
            fields,
            field_order,
        }
    }

    /// Creates a message from a simple `FixMessage`.
    pub fn from_fix_message(fix_msg: &FixMessage) -> Option<Self> {
        let msg_type = FixMessageType::from_str(&fix_msg.msg_type)?;
        let mut message = Self::new(
            msg_type,
            fix_msg.sender_comp_id.clone(),
            fix_msg.target_comp_id.clone(),
            fix_msg.msg_seq_num,
        );

        // Extract sending_time from fields (tag 52) if present
        // Use as_bytes() to preserve exact format and prevent data loss
        if let Some(sending_time_field) = fix_msg.fields.iter().find(|f| f.tag == 52) {
            let sending_time_bytes = sending_time_field.value.as_bytes();
            let sending_time = String::from_utf8_lossy(&sending_time_bytes).to_string();
            message.sending_time = Some(sending_time);
            message.set_field(52, sending_time_bytes);
        }

        // Add additional fields
        for field in &fix_msg.fields {
            // Skip sending_time as it's already processed above
            if field.tag == 52 {
                continue;
            }
            message.set_field(field.tag, field.value.as_bytes().clone());
        }

        Some(message)
    }

    /// Creates a message from an ASN.1 FIX message.
    pub fn from_asn1_message(asn1_msg: &Asn1FixMessage) -> Self {
        let mut message = Self::new(
            asn1_msg.msg_type,
            asn1_msg.sender_comp_id.clone(),
            asn1_msg.target_comp_id.clone(),
            asn1_msg.msg_seq_num,
        );

        if let Some(ref sending_time) = asn1_msg.sending_time {
            message.sending_time = Some(sending_time.clone());
            message.set_field(52, sending_time.as_bytes().to_vec());
        }

        // Add ASN.1 fields
        for field in &asn1_msg.fields {
            message.set_field(field.tag.as_u32(), field.value.as_bytes().to_vec());
        }

        message
    }

    /// Converts to a simple `FixMessage`.
    /// Uses string-based type inference for backward compatibility.
    pub fn to_fix_message(&self) -> FixMessage {
        let fields = self
            .field_order
            .iter()
            .filter_map(|&tag| {
                // Skip standard header fields that are already in the struct
                if matches!(tag, 35 | 49 | 56 | 34 | 52) {
                    return None;
                }
                self.fields.get(&tag).map(|value| Field {
                    tag,
                    value: crate::types::FixFieldValue::from_string(
                        String::from_utf8_lossy(value).to_string(),
                    ),
                })
            })
            .collect();

        FixMessage {
            msg_type: self.msg_type.as_str().to_string(),
            sender_comp_id: self.sender_comp_id.clone(),
            target_comp_id: self.target_comp_id.clone(),
            msg_seq_num: self.msg_seq_num,
            fields,
        }
    }

    /// Converts to a simple `FixMessage` using schema-based type conversion.
    /// This is more efficient and accurate than string-based type inference.
    pub fn to_fix_message_with_schema(
        &self,
        schema: &crate::schema::Schema,
    ) -> crate::Result<FixMessage> {
        let mut fields = Vec::with_capacity(self.field_order.len());

        for &tag in &self.field_order {
            // Skip standard header fields that are already in the struct
            if matches!(tag, 35 | 49 | 56 | 34 | 52) {
                continue;
            }

            if let Some(value) = self.fields.get(&tag) {
                let field_value =
                    crate::types::FixFieldValue::from_bytes_with_schema(value, tag as u16, schema)?;

                fields.push(Field {
                    tag,
                    value: field_value,
                });
            }
        }

        Ok(FixMessage {
            msg_type: self.msg_type.as_str().to_string(),
            sender_comp_id: self.sender_comp_id.clone(),
            target_comp_id: self.target_comp_id.clone(),
            msg_seq_num: self.msg_seq_num,
            fields,
        })
    }

    /// Converts to ASN.1 `FixMessage`.
    pub fn to_asn1_message(&self) -> Option<Asn1FixMessage> {
        let fields = self
            .field_order
            .iter()
            .filter_map(|&tag| {
                // Skip standard header fields
                if matches!(tag, 35 | 49 | 56 | 34 | 52) {
                    return None;
                }
                let field_tag = FixFieldTag::from_u32(tag)?;
                let value = self.fields.get(&tag)?;
                Some(Asn1Field {
                    tag: field_tag,
                    value: String::from_utf8_lossy(value).to_string(),
                })
            })
            .collect();

        Some(Asn1FixMessage {
            msg_type: self.msg_type,
            sender_comp_id: self.sender_comp_id.clone(),
            target_comp_id: self.target_comp_id.clone(),
            msg_seq_num: self.msg_seq_num,
            sending_time: self.sending_time.clone(),
            fields,
        })
    }

    /// Sets a field value.
    pub fn set_field(&mut self, tag: u32, value: Vec<u8>) {
        if !self.fields.contains_key(&tag) {
            self.field_order.push(tag);
        }
        self.fields.insert(tag, value);
    }

    /// Gets all field tags in order.
    pub fn field_tags(&self) -> &[u32] {
        &self.field_order
    }

    /// Gets the number of fields.
    pub fn field_count(&self) -> usize {
        self.fields.len()
    }

    /// Parses repeating group entries from the message fields.
    fn parse_group_entries(
        &self,
        count_tag: u32,
        count: usize,
    ) -> Result<Vec<Message>, Asn1FieldError> {
        // TODO: Implement proper repeating group parsing
        // This requires:
        // 1. Look up the group schema from a dictionary/schema
        // 2. Parse the fields in order based on the group definition
        // 3. Create proper Message instances for each group entry

        Err(Asn1FieldError::GroupParsingUnsupported {
            tag: count_tag,
            count,
        })
    }
}

impl FieldMap<u32> for Message {
    type Group = MessageGroup;

    fn get_raw(&self, field: u32) -> Option<&[u8]> {
        self.fields.get(&field).map(std::vec::Vec::as_slice)
    }

    fn get<'a, V: FieldType<'a>>(&'a self, field: u32) -> Result<V, FieldValueError<V::Error>> {
        self.get_raw(field)
            .ok_or(FieldValueError::Missing)
            .and_then(|data| V::deserialize(data).map_err(FieldValueError::Invalid))
    }

    fn get_opt<'a, V: FieldType<'a>>(&'a self, field: u32) -> Result<Option<V>, V::Error> {
        match self.get_raw(field) {
            Some(data) => V::deserialize(data).map(Some),
            None => Ok(None),
        }
    }

    fn get_lossy<'a, V: FieldType<'a>>(
        &'a self,
        field: u32,
    ) -> Result<V, FieldValueError<V::Error>> {
        self.get_raw(field)
            .ok_or(FieldValueError::Missing)
            .and_then(|data| V::deserialize_lossy(data).map_err(FieldValueError::Invalid))
    }

    fn get_lossy_opt<'a, V: FieldType<'a>>(&'a self, field: u32) -> Result<Option<V>, V::Error> {
        match self.get_raw(field) {
            Some(data) => V::deserialize_lossy(data).map(Some),
            None => Ok(None),
        }
    }

    /// Retrieves a repeating group from the message.
    ///
    /// # Note
    ///
    /// **Repeating groups are not yet supported** in the ASN.1 implementation.
    /// This method will currently return an error for any group field.
    /// Group parsing requires proper schema definition and field ordering
    /// logic that is not yet implemented.
    ///
    /// # Arguments
    ///
    /// * `field` - The field tag for the group count field
    ///
    /// # Returns
    ///
    /// Returns a `FieldValueError` with `GroupParsingUnsupported` error until
    /// group parsing is fully implemented.
    fn group(
        &self,
        field: u32,
    ) -> Result<Self::Group, FieldValueError<<usize as FieldType>::Error>> {
        // Get group count from the field
        let count: usize = self.get(field)?;

        // Parse the group entries
        let entries = self
            .parse_group_entries(field, count)
            .map_err(|_group_error| {
                // Log the specific group parsing error for debugging
                // TODO: Add proper logging when fastrace logging API is stable

                // Map to the required error type for the trait
                FieldValueError::Invalid(rustyfix::field_types::InvalidInt)
            })?;

        Ok(MessageGroup::new(entries))
    }

    /// Retrieves an optional repeating group from the message.
    ///
    /// # Note
    ///
    /// **Repeating groups are not yet supported** in the ASN.1 implementation.
    /// This method will currently return an error for any existing group field.
    /// Group parsing requires proper schema definition and field ordering
    /// logic that is not yet implemented.
    ///
    /// # Arguments
    ///
    /// * `field` - The field tag for the group count field
    ///
    /// # Returns
    ///
    /// Returns `Ok(None)` if the field doesn't exist, or returns a
    /// `GroupParsingUnsupported` error if the field exists but group parsing
    /// is not yet implemented.
    fn group_opt(&self, field: u32) -> Result<Option<Self::Group>, <usize as FieldType>::Error> {
        // Check if the count field exists
        match self.get_opt::<usize>(field) {
            Ok(Some(count)) => {
                // Parse the group entries
                let entries = self
                    .parse_group_entries(field, count)
                    .map_err(|_group_error| {
                        // Log the specific group parsing error for debugging
                        // TODO: Add proper logging when fastrace logging API is stable

                        // Map to the required error type for the trait
                        rustyfix::field_types::InvalidInt
                    })?;
                Ok(Some(MessageGroup::new(entries)))
            }
            Ok(None) => Ok(None),
            Err(e) => Err(e),
        }
    }
}

/// Repeating group implementation for ASN.1 messages.
#[derive(Debug, Clone, PartialEq)]
pub struct MessageGroup {
    entries: Vec<Message>,
}

impl MessageGroup {
    /// Creates a new message group.
    pub fn new(entries: Vec<Message>) -> Self {
        Self { entries }
    }

    /// Adds an entry to the group.
    pub fn add_entry(&mut self, entry: Message) {
        self.entries.push(entry);
    }
}

impl RepeatingGroup for MessageGroup {
    type Entry = Message;

    fn len(&self) -> usize {
        self.entries.len()
    }

    fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    fn get(&self, i: usize) -> Option<Self::Entry> {
        self.entries.get(i).cloned()
    }

    // Use default implementation from RepeatingGroup trait
}

/// Helper functions for common field access patterns.
impl Message {
    /// Gets message type field (tag 35).
    pub fn message_type(&self) -> Result<Asn1String, FieldValueError<Asn1FieldError>> {
        self.get(35)
    }

    /// Gets sender component ID field (tag 49).
    pub fn sender_comp_id(&self) -> Result<Asn1String, FieldValueError<Asn1FieldError>> {
        self.get(49)
    }

    /// Gets target component ID field (tag 56).
    pub fn target_comp_id(&self) -> Result<Asn1String, FieldValueError<Asn1FieldError>> {
        self.get(56)
    }

    /// Gets message sequence number field (tag 34).
    pub fn msg_seq_num(&self) -> Result<Asn1UInteger, FieldValueError<Asn1FieldError>> {
        self.get(34)
    }

    /// Gets sending time field (tag 52).
    pub fn sending_time(&self) -> Result<Option<Asn1String>, Asn1FieldError> {
        self.get_opt(52)
    }

    /// Gets symbol field (tag 55) if present.
    pub fn symbol(&self) -> Result<Option<Asn1String>, Asn1FieldError> {
        self.get_opt(55)
    }

    /// Gets side field (tag 54) if present.
    pub fn side(&self) -> Result<Option<Asn1String>, Asn1FieldError> {
        self.get_opt(54)
    }

    /// Gets order quantity field (tag 38) if present.
    pub fn order_qty(&self) -> Result<Option<Asn1UInteger>, Asn1FieldError> {
        self.get_opt(38)
    }

    /// Gets price field (tag 44) if present.
    pub fn price(&self) -> Result<Option<Asn1String>, Asn1FieldError> {
        self.get_opt(44)
    }
}

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

    #[test]
    fn test_message_creation() {
        let msg_type =
            FixMessageType::from_str("D").expect("Failed to parse valid message type 'D'");
        let message = Message::new(msg_type, "SENDER".to_string(), "TARGET".to_string(), 123);

        assert_eq!(message.msg_type, msg_type);
        assert_eq!(message.sender_comp_id, "SENDER");
        assert_eq!(message.target_comp_id, "TARGET");
        assert_eq!(message.msg_seq_num, 123);
    }

    #[test]
    fn test_field_map_implementation() {
        let msg_type =
            FixMessageType::from_str("D").expect("Failed to parse valid message type 'D'");
        let mut message = Message::new(msg_type, "SENDER".to_string(), "TARGET".to_string(), 123);

        // Set a custom field
        message.set_field(55, b"EUR/USD".to_vec());

        // Test field access
        let symbol: Asn1String = message
            .get(55)
            .expect("Symbol field (55) should be present in test message");
        assert_eq!(symbol.as_str(), "EUR/USD");

        // Test missing field
        assert!(message.get_raw(999).is_none());

        // Test optional field access
        let symbol_opt: Option<Asn1String> = message
            .get_opt(55)
            .expect("get_opt should not fail for valid field access");
        assert!(symbol_opt.is_some());
        assert_eq!(
            symbol_opt.expect("Symbol should be present").as_str(),
            "EUR/USD"
        );

        let missing_opt: Option<Asn1String> = message
            .get_opt(999)
            .expect("get_opt should not fail even for missing fields");
        assert!(missing_opt.is_none());
    }

    #[test]
    fn test_conversion_from_fix_message() {
        let fix_msg = FixMessage {
            msg_type: "D".to_string(),
            sender_comp_id: "SENDER".to_string(),
            target_comp_id: "TARGET".to_string(),
            msg_seq_num: 123,
            fields: vec![
                Field {
                    tag: 55,
                    value: crate::types::FixFieldValue::String("EUR/USD".to_string()),
                },
                Field {
                    tag: 54,
                    value: crate::types::FixFieldValue::String("1".to_string()),
                },
            ],
        };

        let message = Message::from_fix_message(&fix_msg)
            .expect("Failed to convert valid FIX message to ASN.1 message");

        // Check standard fields
        assert_eq!(message.msg_type.as_str(), "D");
        assert_eq!(message.sender_comp_id, "SENDER");
        assert_eq!(message.target_comp_id, "TARGET");
        assert_eq!(message.msg_seq_num, 123);

        // Check custom fields
        let symbol: Asn1String = message
            .get(55)
            .expect("Symbol field (55) should be present in converted message");
        assert_eq!(symbol.as_str(), "EUR/USD");

        let side: Asn1String = message
            .get(54)
            .expect("Side field (54) should be present in converted message");
        assert_eq!(side.as_str(), "1");
    }

    #[test]
    fn test_conversion_from_fix_message_with_sending_time() {
        let fix_msg = FixMessage {
            msg_type: "D".to_string(),
            sender_comp_id: "SENDER".to_string(),
            target_comp_id: "TARGET".to_string(),
            msg_seq_num: 123,
            fields: vec![
                Field {
                    tag: 52, // SendingTime
                    value: crate::types::FixFieldValue::UtcTimestamp(
                        "20240101-12:30:45".to_string(),
                    ),
                },
                Field {
                    tag: 55,
                    value: crate::types::FixFieldValue::String("EUR/USD".to_string()),
                },
            ],
        };

        let message = Message::from_fix_message(&fix_msg)
            .expect("Failed to convert valid FIX message with sending time to ASN.1 message");

        // Check that sending_time is properly extracted
        assert_eq!(message.sending_time, Some("20240101-12:30:45".to_string()));

        // Check that sending_time is accessible via field map
        let sending_time = message
            .sending_time()
            .expect("SendingTime field (52) should be accessible via helper method");
        assert!(sending_time.is_some());
        assert_eq!(
            sending_time
                .expect("SendingTime should be present")
                .as_str(),
            "20240101-12:30:45"
        );

        // Check that conversion to ASN.1 preserves sending_time
        let asn1_message = message
            .to_asn1_message()
            .expect("Failed to convert message to ASN.1 format");
        assert_eq!(
            asn1_message.sending_time,
            Some("20240101-12:30:45".to_string())
        );
    }

    #[test]
    fn test_conversion_to_fix_message() {
        let msg_type =
            FixMessageType::from_str("D").expect("Failed to parse valid message type 'D'");
        let mut message = Message::new(msg_type, "SENDER".to_string(), "TARGET".to_string(), 123);

        message.set_field(55, b"EUR/USD".to_vec());
        message.set_field(54, b"1".to_vec());

        let fix_msg = message.to_fix_message();

        assert_eq!(fix_msg.msg_type, "D");
        assert_eq!(fix_msg.sender_comp_id, "SENDER");
        assert_eq!(fix_msg.target_comp_id, "TARGET");
        assert_eq!(fix_msg.msg_seq_num, 123);
        assert_eq!(fix_msg.fields.len(), 2);

        // Find fields
        let symbol_field = fix_msg
            .fields
            .iter()
            .find(|f| f.tag == 55)
            .expect("Symbol field should exist in converted message");
        assert_eq!(symbol_field.value.to_string(), "EUR/USD");

        let side_field = fix_msg
            .fields
            .iter()
            .find(|f| f.tag == 54)
            .expect("Side field should exist in converted message");
        assert_eq!(side_field.value.to_string(), "1");
    }

    #[test]
    fn test_conversion_to_fix_message_with_schema() {
        let dict = std::sync::Arc::new(
            rustyfix_dictionary::Dictionary::fix44()
                .expect("Failed to load FIX 4.4 dictionary for test"),
        );
        let schema = crate::schema::Schema::new(dict);

        let msg_type =
            FixMessageType::from_str("D").expect("Failed to parse valid message type 'D'");
        let mut message = Message::new(msg_type, "SENDER".to_string(), "TARGET".to_string(), 123);

        // Add fields with specific types that will be handled differently by schema
        message.set_field(55, b"EUR/USD".to_vec()); // Symbol - String type
        message.set_field(54, b"1".to_vec()); // Side - String/Char type  
        message.set_field(38, b"1000".to_vec()); // OrderQty - Qty type (decimal)
        message.set_field(44, b"1.2345".to_vec()); // Price - Price type (decimal)

        let fix_msg = message
            .to_fix_message_with_schema(&schema)
            .expect("Schema-based conversion should succeed");

        assert_eq!(fix_msg.msg_type, "D");
        assert_eq!(fix_msg.sender_comp_id, "SENDER");
        assert_eq!(fix_msg.target_comp_id, "TARGET");
        assert_eq!(fix_msg.msg_seq_num, 123);
        assert_eq!(fix_msg.fields.len(), 4);

        // Verify that fields are converted according to their actual types
        let symbol_field = fix_msg
            .fields
            .iter()
            .find(|f| f.tag == 55)
            .expect("Symbol field should exist");
        assert_eq!(symbol_field.value.to_string(), "EUR/USD");

        let price_field = fix_msg
            .fields
            .iter()
            .find(|f| f.tag == 44)
            .expect("Price field should exist");
        // Price should be stored as Decimal type with proper precision
        assert_eq!(price_field.value.to_string(), "1.2345");
        assert!(matches!(
            price_field.value,
            crate::types::FixFieldValue::Decimal(_)
        ));
    }

    #[test]
    fn test_schema_vs_string_conversion_performance_comparison() {
        use std::time::Instant;

        let dict = std::sync::Arc::new(
            rustyfix_dictionary::Dictionary::fix44()
                .expect("Failed to load FIX 4.4 dictionary for test"),
        );
        let schema = crate::schema::Schema::new(dict);

        let msg_type =
            FixMessageType::from_str("D").expect("Failed to parse valid message type 'D'");
        let mut message = Message::new(msg_type, "SENDER".to_string(), "TARGET".to_string(), 123);

        // Add known fields that exist in FIX 4.4 dictionary
        let known_fields = vec![
            (55, b"EUR/USD".as_slice()),  // Symbol
            (54, b"1".as_slice()),        // Side
            (38, b"1000".as_slice()),     // OrderQty
            (44, b"1.2345".as_slice()),   // Price
            (40, b"2".as_slice()),        // OrdType
            (59, b"0".as_slice()),        // TimeInForce
            (1, b"ACCOUNT1".as_slice()),  // Account
            (11, b"ORDER123".as_slice()), // ClOrdID
        ];

        for (tag, value) in &known_fields {
            message.set_field(*tag, value.to_vec());
        }

        // Test string-based conversion
        let start = Instant::now();
        let _fix_msg_string = message.to_fix_message();
        let string_duration = start.elapsed();

        // Test schema-based conversion
        let start = Instant::now();
        let _fix_msg_schema = message
            .to_fix_message_with_schema(&schema)
            .expect("Schema conversion should work");
        let schema_duration = start.elapsed();

        // This test documents the performance difference
        // Schema-based conversion should be more efficient for typed fields
        println!("String conversion: {string_duration:?}, Schema conversion: {schema_duration:?}");

        // Both should produce valid results
        assert!(_fix_msg_string.fields.len() == known_fields.len());
        assert!(_fix_msg_schema.fields.len() == known_fields.len());

        // Verify specific field types are preserved in schema conversion
        let price_field = _fix_msg_schema
            .fields
            .iter()
            .find(|f| f.tag == 44)
            .expect("Price field should exist");
        assert!(matches!(
            price_field.value,
            crate::types::FixFieldValue::Decimal(_)
        ));
    }

    #[test]
    fn test_schema_conversion_with_unknown_field() {
        let dict = std::sync::Arc::new(
            rustyfix_dictionary::Dictionary::fix44()
                .expect("Failed to load FIX 4.4 dictionary for test"),
        );
        let schema = crate::schema::Schema::new(dict);

        let msg_type =
            FixMessageType::from_str("D").expect("Failed to parse valid message type 'D'");
        let mut message = Message::new(msg_type, "SENDER".to_string(), "TARGET".to_string(), 123);

        // Add a field with an unknown tag (very high number unlikely to be in dictionary)
        message.set_field(9999, b"unknown_field".to_vec());

        // Schema-based conversion should fail gracefully for unknown fields
        let result = message.to_fix_message_with_schema(&schema);
        assert!(result.is_err(), "Should fail for unknown field tags");

        // String-based conversion should still work
        let fix_msg = message.to_fix_message();
        assert_eq!(fix_msg.fields.len(), 1);
    }

    #[test]
    fn test_helper_methods() {
        let msg_type =
            FixMessageType::from_str("D").expect("Failed to parse valid message type 'D'");
        let mut message = Message::new(msg_type, "SENDER".to_string(), "TARGET".to_string(), 123);

        message.set_field(55, b"EUR/USD".to_vec());

        // Test helper methods
        let msg_type_result = message
            .message_type()
            .expect("Message type should be accessible in test message");
        assert_eq!(msg_type_result.as_str(), "D");

        let sender = message
            .sender_comp_id()
            .expect("Sender company ID should be accessible in test message");
        assert_eq!(sender.as_str(), "SENDER");

        let symbol = message
            .symbol()
            .expect("Symbol should be accessible in test message");
        assert!(symbol.is_some());
        assert_eq!(
            symbol.expect("Symbol should be present").as_str(),
            "EUR/USD"
        );

        let missing = message
            .price()
            .expect("price() method should not fail even when field is missing");
        assert!(missing.is_none());
    }

    #[test]
    fn test_message_group() {
        let msg_type =
            FixMessageType::from_str("D").expect("Failed to parse valid message type 'D'");
        let message1 = Message::new(msg_type, "SENDER1".to_string(), "TARGET1".to_string(), 1);
        let message2 = Message::new(msg_type, "SENDER2".to_string(), "TARGET2".to_string(), 2);

        let mut group = MessageGroup::new(vec![message1.clone()]);
        group.add_entry(message2.clone());

        assert_eq!(group.len(), 2);
        assert!(!group.is_empty());

        let entry1 = group
            .get(0)
            .expect("First group entry should exist in test");
        assert_eq!(entry1.sender_comp_id, "SENDER1");

        let entry2 = group
            .get(1)
            .expect("Second group entry should exist in test");
        assert_eq!(entry2.sender_comp_id, "SENDER2");

        assert!(group.get(2).is_none());
    }

    #[test]
    fn test_repeating_group_parsing() {
        let msg_type =
            FixMessageType::from_str("D").expect("Failed to parse valid message type 'D'");
        let mut message = Message::new(msg_type, "SENDER".to_string(), "TARGET".to_string(), 123);

        // Add a group count field (tag 453 = NoPartyIDs)
        message.set_field(453, b"2".to_vec()); // 2 entries in the group

        // Test group() method - should fail since group parsing is unimplemented
        let group_result = message.group(453);
        assert!(
            group_result.is_err(),
            "group() should fail when group parsing is unimplemented"
        );

        // Test group_opt() method with existing field - should also fail
        let group_opt_result = message.group_opt(453);
        assert!(
            group_opt_result.is_err(),
            "group_opt() should fail when group parsing is unimplemented"
        );

        // Test group_opt() method with missing field - should return Ok(None)
        let missing_group_result = message.group_opt(999); // Non-existent field
        assert!(
            missing_group_result.is_ok(),
            "group_opt() should not fail for missing field"
        );

        let missing_group = missing_group_result.expect("group_opt should return Ok");
        assert!(
            missing_group.is_none(),
            "group_opt should return None for missing field"
        );
    }

    #[test]
    fn test_group_with_invalid_count() {
        let msg_type =
            FixMessageType::from_str("D").expect("Failed to parse valid message type 'D'");
        let mut message = Message::new(msg_type, "SENDER".to_string(), "TARGET".to_string(), 123);

        // Add a field with invalid count (not a number)
        message.set_field(453, b"invalid".to_vec());

        // Test that group() fails gracefully with invalid count
        let group_result = message.group(453);
        assert!(
            group_result.is_err(),
            "group() should fail with invalid count value"
        );

        // Test that group_opt() also fails gracefully
        let group_opt_result = message.group_opt(453);
        assert!(
            group_opt_result.is_err(),
            "group_opt() should fail with invalid count value"
        );
    }
}