ironfix-core 0.3.0

Core types, traits, and error definitions for IronFix FIX protocol engine
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
/******************************************************************************
   Author: Joaquín Béjar García
   Email: jb@taunais.com
   Date: 27/1/26
******************************************************************************/

//! Message types and traits for FIX protocol.
//!
//! This module provides:
//! - [`RawMessage`]: Zero-copy view into a FIX message buffer
//! - [`OwnedMessage`]: Owned message for storage and cross-thread transfer
//! - [`MsgType`]: Enumeration of FIX message types
//! - [`FixMessage`]: Trait for typed message access

use crate::error::DecodeError;
use crate::field::FieldRef;
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use std::fmt;
use std::ops::Range;

/// Standard FIX message types.
///
/// This enum covers the most common administrative and application messages.
/// Custom or less common message types can be represented as `Custom(String)`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum MsgType {
    /// Heartbeat (0) - Session level.
    #[default]
    Heartbeat,
    /// Test Request (1) - Session level.
    TestRequest,
    /// Resend Request (2) - Session level.
    ResendRequest,
    /// Reject (3) - Session level.
    Reject,
    /// Sequence Reset (4) - Session level.
    SequenceReset,
    /// Logout (5) - Session level.
    Logout,
    /// Indication of Interest (6).
    IndicationOfInterest,
    /// Advertisement (7).
    Advertisement,
    /// Execution Report (8).
    ExecutionReport,
    /// Order Cancel Reject (9).
    OrderCancelReject,
    /// Logon (A) - Session level.
    Logon,
    /// News (B).
    News,
    /// Email (C).
    Email,
    /// New Order Single (D).
    NewOrderSingle,
    /// New Order List (E).
    NewOrderList,
    /// Order Cancel Request (F).
    OrderCancelRequest,
    /// Order Cancel/Replace Request (G).
    OrderCancelReplaceRequest,
    /// Order Status Request (H).
    OrderStatusRequest,
    /// Allocation Instruction (J).
    AllocationInstruction,
    /// List Cancel Request (K).
    ListCancelRequest,
    /// List Execute (L).
    ListExecute,
    /// List Status Request (M).
    ListStatusRequest,
    /// List Status (N).
    ListStatus,
    /// Allocation Instruction Ack (P).
    AllocationInstructionAck,
    /// Don't Know Trade (Q).
    DontKnowTrade,
    /// Quote Request (R).
    QuoteRequest,
    /// Quote (S).
    Quote,
    /// Settlement Instructions (T).
    SettlementInstructions,
    /// Market Data Request (V).
    MarketDataRequest,
    /// Market Data Snapshot/Full Refresh (W).
    MarketDataSnapshotFullRefresh,
    /// Market Data Incremental Refresh (X).
    MarketDataIncrementalRefresh,
    /// Market Data Request Reject (Y).
    MarketDataRequestReject,
    /// Quote Cancel (Z).
    QuoteCancel,
    /// Quote Status Request (a).
    QuoteStatusRequest,
    /// Mass Quote Acknowledgement (b).
    MassQuoteAcknowledgement,
    /// Security Definition Request (c).
    SecurityDefinitionRequest,
    /// Security Definition (d).
    SecurityDefinition,
    /// Security Status Request (e).
    SecurityStatusRequest,
    /// Security Status (f).
    SecurityStatus,
    /// Trading Session Status Request (g).
    TradingSessionStatusRequest,
    /// Trading Session Status (h).
    TradingSessionStatus,
    /// Mass Quote (i).
    MassQuote,
    /// Business Message Reject (j).
    BusinessMessageReject,
    /// Bid Request (k).
    BidRequest,
    /// Bid Response (l).
    BidResponse,
    /// List Strike Price (m).
    ListStrikePrice,
    /// XML Message (n).
    XmlMessage,
    /// Registration Instructions (o).
    RegistrationInstructions,
    /// Registration Instructions Response (p).
    RegistrationInstructionsResponse,
    /// Order Mass Cancel Request (q).
    OrderMassCancelRequest,
    /// Order Mass Cancel Report (r).
    OrderMassCancelReport,
    /// New Order Cross (s).
    NewOrderCross,
    /// Cross Order Cancel/Replace Request (t).
    CrossOrderCancelReplaceRequest,
    /// Cross Order Cancel Request (u).
    CrossOrderCancelRequest,
    /// Security Type Request (v).
    SecurityTypeRequest,
    /// Security Types (w).
    SecurityTypes,
    /// Security List Request (x).
    SecurityListRequest,
    /// Security List (y).
    SecurityList,
    /// Derivative Security List Request (z).
    DerivativeSecurityListRequest,
    /// Custom or unknown message type.
    Custom(String),
}

impl std::str::FromStr for MsgType {
    type Err = std::convert::Infallible;

    /// Creates a MsgType from a string value.
    ///
    /// # Arguments
    /// * `s` - The message type string (e.g., "D" for NewOrderSingle)
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s {
            "0" => Self::Heartbeat,
            "1" => Self::TestRequest,
            "2" => Self::ResendRequest,
            "3" => Self::Reject,
            "4" => Self::SequenceReset,
            "5" => Self::Logout,
            "6" => Self::IndicationOfInterest,
            "7" => Self::Advertisement,
            "8" => Self::ExecutionReport,
            "9" => Self::OrderCancelReject,
            "A" => Self::Logon,
            "B" => Self::News,
            "C" => Self::Email,
            "D" => Self::NewOrderSingle,
            "E" => Self::NewOrderList,
            "F" => Self::OrderCancelRequest,
            "G" => Self::OrderCancelReplaceRequest,
            "H" => Self::OrderStatusRequest,
            "J" => Self::AllocationInstruction,
            "K" => Self::ListCancelRequest,
            "L" => Self::ListExecute,
            "M" => Self::ListStatusRequest,
            "N" => Self::ListStatus,
            "P" => Self::AllocationInstructionAck,
            "Q" => Self::DontKnowTrade,
            "R" => Self::QuoteRequest,
            "S" => Self::Quote,
            "T" => Self::SettlementInstructions,
            "V" => Self::MarketDataRequest,
            "W" => Self::MarketDataSnapshotFullRefresh,
            "X" => Self::MarketDataIncrementalRefresh,
            "Y" => Self::MarketDataRequestReject,
            "Z" => Self::QuoteCancel,
            "a" => Self::QuoteStatusRequest,
            "b" => Self::MassQuoteAcknowledgement,
            "c" => Self::SecurityDefinitionRequest,
            "d" => Self::SecurityDefinition,
            "e" => Self::SecurityStatusRequest,
            "f" => Self::SecurityStatus,
            "g" => Self::TradingSessionStatusRequest,
            "h" => Self::TradingSessionStatus,
            "i" => Self::MassQuote,
            "j" => Self::BusinessMessageReject,
            "k" => Self::BidRequest,
            "l" => Self::BidResponse,
            "m" => Self::ListStrikePrice,
            "n" => Self::XmlMessage,
            "o" => Self::RegistrationInstructions,
            "p" => Self::RegistrationInstructionsResponse,
            "q" => Self::OrderMassCancelRequest,
            "r" => Self::OrderMassCancelReport,
            "s" => Self::NewOrderCross,
            "t" => Self::CrossOrderCancelReplaceRequest,
            "u" => Self::CrossOrderCancelRequest,
            "v" => Self::SecurityTypeRequest,
            "w" => Self::SecurityTypes,
            "x" => Self::SecurityListRequest,
            "y" => Self::SecurityList,
            "z" => Self::DerivativeSecurityListRequest,
            other => Self::Custom(other.to_string()),
        })
    }
}

impl MsgType {
    /// Returns the string representation of this message type.
    #[must_use]
    pub fn as_str(&self) -> &str {
        match self {
            Self::Heartbeat => "0",
            Self::TestRequest => "1",
            Self::ResendRequest => "2",
            Self::Reject => "3",
            Self::SequenceReset => "4",
            Self::Logout => "5",
            Self::IndicationOfInterest => "6",
            Self::Advertisement => "7",
            Self::ExecutionReport => "8",
            Self::OrderCancelReject => "9",
            Self::Logon => "A",
            Self::News => "B",
            Self::Email => "C",
            Self::NewOrderSingle => "D",
            Self::NewOrderList => "E",
            Self::OrderCancelRequest => "F",
            Self::OrderCancelReplaceRequest => "G",
            Self::OrderStatusRequest => "H",
            Self::AllocationInstruction => "J",
            Self::ListCancelRequest => "K",
            Self::ListExecute => "L",
            Self::ListStatusRequest => "M",
            Self::ListStatus => "N",
            Self::AllocationInstructionAck => "P",
            Self::DontKnowTrade => "Q",
            Self::QuoteRequest => "R",
            Self::Quote => "S",
            Self::SettlementInstructions => "T",
            Self::MarketDataRequest => "V",
            Self::MarketDataSnapshotFullRefresh => "W",
            Self::MarketDataIncrementalRefresh => "X",
            Self::MarketDataRequestReject => "Y",
            Self::QuoteCancel => "Z",
            Self::QuoteStatusRequest => "a",
            Self::MassQuoteAcknowledgement => "b",
            Self::SecurityDefinitionRequest => "c",
            Self::SecurityDefinition => "d",
            Self::SecurityStatusRequest => "e",
            Self::SecurityStatus => "f",
            Self::TradingSessionStatusRequest => "g",
            Self::TradingSessionStatus => "h",
            Self::MassQuote => "i",
            Self::BusinessMessageReject => "j",
            Self::BidRequest => "k",
            Self::BidResponse => "l",
            Self::ListStrikePrice => "m",
            Self::XmlMessage => "n",
            Self::RegistrationInstructions => "o",
            Self::RegistrationInstructionsResponse => "p",
            Self::OrderMassCancelRequest => "q",
            Self::OrderMassCancelReport => "r",
            Self::NewOrderCross => "s",
            Self::CrossOrderCancelReplaceRequest => "t",
            Self::CrossOrderCancelRequest => "u",
            Self::SecurityTypeRequest => "v",
            Self::SecurityTypes => "w",
            Self::SecurityListRequest => "x",
            Self::SecurityList => "y",
            Self::DerivativeSecurityListRequest => "z",
            Self::Custom(s) => s.as_str(),
        }
    }

    /// Returns true if this is an administrative message.
    #[must_use]
    pub fn is_admin(&self) -> bool {
        matches!(
            self,
            Self::Heartbeat
                | Self::TestRequest
                | Self::ResendRequest
                | Self::Reject
                | Self::SequenceReset
                | Self::Logout
                | Self::Logon
        )
    }

    /// Returns true if this is an application message.
    #[must_use]
    pub fn is_app(&self) -> bool {
        !self.is_admin()
    }
}

impl fmt::Display for MsgType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Zero-copy view into a FIX message buffer.
///
/// This struct holds references to the original message buffer,
/// avoiding allocation during parsing. Fields are stored as
/// offset ranges into the buffer.
#[derive(Debug, Clone)]
pub struct RawMessage<'a> {
    /// The complete message buffer.
    buffer: &'a [u8],
    /// Range of the BeginString field value.
    begin_string: Range<usize>,
    /// Range of the message body (after BodyLength, before checksum).
    body: Range<usize>,
    /// The parsed message type.
    msg_type: MsgType,
    /// Parsed field references (tag and value ranges).
    fields: SmallVec<[FieldRef<'a>; 32]>,
}

impl<'a> RawMessage<'a> {
    /// Creates a new RawMessage from parsed components.
    ///
    /// # Arguments
    /// * `buffer` - The complete message buffer
    /// * `begin_string` - Range of the BeginString value
    /// * `body` - Range of the message body
    /// * `msg_type` - The parsed message type
    /// * `fields` - Parsed field references
    #[must_use]
    pub fn new(
        buffer: &'a [u8],
        begin_string: Range<usize>,
        body: Range<usize>,
        msg_type: MsgType,
        fields: SmallVec<[FieldRef<'a>; 32]>,
    ) -> Self {
        Self {
            buffer,
            begin_string,
            body,
            msg_type,
            fields,
        }
    }

    /// Returns the complete message buffer.
    #[inline]
    #[must_use]
    pub const fn buffer(&self) -> &'a [u8] {
        self.buffer
    }

    /// Returns the BeginString value (e.g., "FIX.4.4").
    #[must_use]
    pub fn begin_string(&self) -> &'a str {
        std::str::from_utf8(&self.buffer[self.begin_string.clone()]).unwrap_or("")
    }

    /// Returns the message type.
    #[inline]
    #[must_use]
    pub fn msg_type(&self) -> &MsgType {
        &self.msg_type
    }

    /// Returns an iterator over all fields.
    #[inline]
    pub fn fields(&self) -> impl Iterator<Item = &FieldRef<'a>> {
        self.fields.iter()
    }

    /// Returns the number of fields in the message.
    #[inline]
    #[must_use]
    pub fn field_count(&self) -> usize {
        self.fields.len()
    }

    /// Gets a field by tag number.
    ///
    /// # Arguments
    /// * `tag` - The field tag number
    ///
    /// # Returns
    /// The first field with the given tag, or `None` if not found.
    #[must_use]
    pub fn get_field(&self, tag: u32) -> Option<&FieldRef<'a>> {
        self.fields.iter().find(|f| f.tag == tag)
    }

    /// Gets a field value as a string.
    ///
    /// # Arguments
    /// * `tag` - The field tag number
    ///
    /// # Returns
    /// The field value as a string, or `None` if not found or invalid UTF-8.
    #[must_use]
    pub fn get_field_str(&self, tag: u32) -> Option<&'a str> {
        self.get_field(tag).and_then(|f| f.as_str().ok())
    }

    /// Gets a field value parsed as the specified type.
    ///
    /// # Arguments
    /// * `tag` - The field tag number
    ///
    /// # Errors
    /// Returns `DecodeError` if the field is not found or cannot be parsed.
    pub fn get_field_as<T: std::str::FromStr>(&self, tag: u32) -> Result<T, DecodeError> {
        self.get_field(tag)
            .ok_or(DecodeError::MissingRequiredField { tag })?
            .parse()
    }

    /// Returns the message body range.
    #[inline]
    #[must_use]
    pub fn body_range(&self) -> &Range<usize> {
        &self.body
    }

    /// Returns the message length in bytes.
    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.buffer.len()
    }

    /// Returns true if the message is empty.
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.buffer.is_empty()
    }

    /// Converts this borrowed message to an owned message.
    #[must_use]
    pub fn to_owned(&self) -> OwnedMessage {
        OwnedMessage::from_raw(self)
    }
}

/// Owned FIX message for storage and cross-thread transfer.
///
/// Unlike [`RawMessage`], this struct owns its data and can be
/// safely sent across threads or stored for later use.
#[derive(Debug, Clone)]
pub struct OwnedMessage {
    /// The complete message buffer.
    buffer: Bytes,
    /// The parsed message type.
    msg_type: MsgType,
    /// Field offsets: (tag, value_range).
    field_offsets: Vec<(u32, Range<usize>)>,
}

impl OwnedMessage {
    /// Creates an OwnedMessage from a RawMessage.
    ///
    /// # Arguments
    /// * `raw` - The raw message to copy
    #[must_use]
    pub fn from_raw(raw: &RawMessage<'_>) -> Self {
        let buffer = Bytes::copy_from_slice(raw.buffer);
        let field_offsets = raw
            .fields
            .iter()
            .map(|f| {
                let start = f.value.as_ptr() as usize - raw.buffer.as_ptr() as usize;
                let end = start + f.value.len();
                (f.tag, start..end)
            })
            .collect();

        Self {
            buffer,
            msg_type: raw.msg_type.clone(),
            field_offsets,
        }
    }

    /// Creates an OwnedMessage from raw bytes.
    ///
    /// # Arguments
    /// * `buffer` - The message bytes
    /// * `msg_type` - The message type
    /// * `field_offsets` - Field tag and value range pairs
    #[must_use]
    pub fn new(buffer: Bytes, msg_type: MsgType, field_offsets: Vec<(u32, Range<usize>)>) -> Self {
        Self {
            buffer,
            msg_type,
            field_offsets,
        }
    }

    /// Returns the message type.
    #[inline]
    #[must_use]
    pub fn msg_type(&self) -> &MsgType {
        &self.msg_type
    }

    /// Returns the message bytes.
    #[inline]
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        &self.buffer
    }

    /// Returns the message length in bytes.
    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.buffer.len()
    }

    /// Returns true if the message is empty.
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.buffer.is_empty()
    }

    /// Gets a field value by tag.
    ///
    /// # Arguments
    /// * `tag` - The field tag number
    ///
    /// # Returns
    /// The field value bytes, or `None` if not found.
    #[must_use]
    pub fn get_field(&self, tag: u32) -> Option<&[u8]> {
        self.field_offsets
            .iter()
            .find(|(t, _)| *t == tag)
            .map(|(_, range)| &self.buffer[range.clone()])
    }

    /// Gets a field value as a string.
    ///
    /// # Arguments
    /// * `tag` - The field tag number
    ///
    /// # Returns
    /// The field value as a string, or `None` if not found or invalid UTF-8.
    #[must_use]
    pub fn get_field_str(&self, tag: u32) -> Option<&str> {
        self.get_field(tag)
            .and_then(|b| std::str::from_utf8(b).ok())
    }

    /// Returns the number of fields.
    #[inline]
    #[must_use]
    pub fn field_count(&self) -> usize {
        self.field_offsets.len()
    }

    /// Consumes the message and returns the underlying buffer.
    #[must_use]
    pub fn into_bytes(self) -> Bytes {
        self.buffer
    }
}

/// Trait for typed FIX message access.
///
/// This trait is implemented by generated message types to provide
/// type-safe encoding and decoding.
pub trait FixMessage: Sized {
    /// The message type string (e.g., "D" for NewOrderSingle).
    const MSG_TYPE: &'static str;

    /// Decodes a message from a raw message.
    ///
    /// # Arguments
    /// * `raw` - The raw message to decode
    ///
    /// # Errors
    /// Returns `DecodeError` if the message cannot be decoded.
    fn from_raw(raw: &RawMessage<'_>) -> Result<Self, DecodeError>;

    /// Encodes the message to a buffer.
    ///
    /// # Arguments
    /// * `buf` - The buffer to write to
    ///
    /// # Errors
    /// Returns `EncodeError` if the message cannot be encoded.
    fn encode(&self, buf: &mut Vec<u8>) -> Result<(), crate::error::EncodeError>;
}

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

    #[test]
    fn test_msg_type_from_str() {
        assert_eq!("0".parse::<MsgType>().unwrap(), MsgType::Heartbeat);
        assert_eq!("A".parse::<MsgType>().unwrap(), MsgType::Logon);
        assert_eq!("D".parse::<MsgType>().unwrap(), MsgType::NewOrderSingle);
        assert_eq!("8".parse::<MsgType>().unwrap(), MsgType::ExecutionReport);
    }

    #[test]
    fn test_msg_type_as_str() {
        assert_eq!(MsgType::Heartbeat.as_str(), "0");
        assert_eq!(MsgType::Logon.as_str(), "A");
        assert_eq!(MsgType::NewOrderSingle.as_str(), "D");
    }

    #[test]
    fn test_msg_type_is_admin() {
        assert!(MsgType::Heartbeat.is_admin());
        assert!(MsgType::Logon.is_admin());
        assert!(MsgType::Logout.is_admin());
        assert!(!MsgType::NewOrderSingle.is_admin());
        assert!(!MsgType::ExecutionReport.is_admin());
    }

    #[test]
    fn test_msg_type_custom() {
        let custom: MsgType = "XX".parse().unwrap();
        assert!(matches!(custom, MsgType::Custom(_)));
        assert_eq!(custom.as_str(), "XX");
    }

    #[test]
    fn test_owned_message_field_access() {
        // Buffer: "8=FIX.4.4\x0135=D\x0149=SENDER\x01"
        // Offsets: 8=FIX.4.4 (0-9), \x01 (9), 35=D (10-13), \x01 (14), 49=SENDER (15-23), \x01 (24)
        // FIX.4.4 is at 2..9, D is at 13..14, SENDER is at 18..24
        let buffer = Bytes::from_static(b"8=FIX.4.4\x0135=D\x0149=SENDER\x01");
        let field_offsets = vec![(8, 2..9), (35, 13..14), (49, 18..24)];
        let msg = OwnedMessage::new(buffer, MsgType::NewOrderSingle, field_offsets);

        assert_eq!(msg.get_field_str(8), Some("FIX.4.4"));
        assert_eq!(msg.get_field_str(35), Some("D"));
        assert_eq!(msg.get_field_str(49), Some("SENDER"));
        assert_eq!(msg.get_field_str(999), None);
    }
}