refix-dictionary 0.5.1

FIX protocol dictionary model and frontends for the ReFIX engine
Documentation
//! The authored form of a data dictionary.

use refix_message::Tag;
use std::borrow::Cow;
use std::fmt;

/// The fields, messages, components, header and trailer of one FIX version
/// or venue dialect, as authored.
///
/// A spec is plain data and makes no consistency guarantees. It is what
/// frontends parse into and what dialect authors construct by hand.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Spec {
    pub version: Version,
    /// The members every message starts with, in source order.
    pub header: Vec<Member>,
    pub messages: Vec<Message>,
    /// The members every message ends with, in source order.
    pub trailer: Vec<Member>,
    pub fields: Vec<Field>,
    pub components: Vec<Component>,
}

/// The definition of a FIX message type.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Message {
    /// The name of the message type.
    pub name: String,
    /// The wire value of `MsgType(35)`, verbatim, e.g. `"D"`.
    pub msg_type: String,
    /// The message's members in source order.
    pub members: Vec<Member>,
    /// The category of this message.
    pub category: Category,
}

/// A field definition, as listed in the dictionary's fields section.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Field {
    pub name: String,
    pub tag: Tag,
    pub data_type: DataType,
    /// For a data field, the tag of the field that gives its length.
    pub length_tag: Option<Tag>,
    pub values: Vec<EnumValue>,
}

/// A component definition, as listed in the dictionary's components section.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Component {
    /// The name of the component.
    pub name: String,
    /// The component's members in source order.
    pub members: Vec<Member>,
}

/// A member of a message, component or group instance.
///
/// This can be a field reference, a component reference or a repeating group.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Member {
    Field(FieldRef),
    Component(ComponentRef),
    Group(Group),
}

/// A field as used by one message or component (Orchestra's `fieldRef`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FieldRef {
    /// Tag of the referenced [`Field`] definition.
    pub tag: Tag,
    pub is_required: bool,
}

/// A component as used by one message or component.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ComponentRef {
    /// Name of the referenced [`Component`] definition.
    pub name: String,
    pub is_required: bool,
}

/// A repeating group, declared inline in a message, component or group
/// instance.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Group {
    /// Tag of the group's NumInGroup count field.
    pub count_tag: Tag,
    pub is_required: bool,
    /// The members of each instance, in source order.
    pub members: Vec<Member>,
}

/// An enum variant's value.
///
/// This models the `<value enum="..." description="..." />` elements in a field definition.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EnumValue {
    pub value: String,
    pub description: String,
}

/// The FIX data type of a field, as declared in the dictionary.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DataType {
    String,
    Int,
    Length,
    NumInGroup,
    SeqNum,
    TagNum,
    DayOfMonth,
    Float,
    Qty,
    Price,
    PriceOffset,
    Amt,
    Percentage,
    Char,
    Boolean,
    MultipleCharValue,
    /// Also FIX 4.4's `MultipleValueString`.
    MultipleStringValue,
    Currency,
    Exchange,
    Country,
    Language,
    Xid,
    XidRef,
    /// Also FIX 4.0 and 4.1's `Time`.
    UtcTimestamp,
    UtcTimeOnly,
    /// Also FIX 4.2 and 4.3's `UtcDate`.
    UtcDateOnly,
    /// Also FIX 4.0 and 4.1's `Date`.
    LocalMktDate,
    LocalMktTime,
    MonthYear,
    TzTimestamp,
    TzTimeOnly,
    Data,
    XmlData,
    /// A type outside the standard, such as a venue's own.
    Other(String),
}

/// The type's name in upper case, as dictionaries declare it, or a type outside
/// the standard as given.
impl fmt::Display for DataType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = match self {
            Self::String => "STRING",
            Self::Int => "INT",
            Self::Length => "LENGTH",
            Self::NumInGroup => "NUMINGROUP",
            Self::SeqNum => "SEQNUM",
            Self::TagNum => "TAGNUM",
            Self::DayOfMonth => "DAYOFMONTH",
            Self::Float => "FLOAT",
            Self::Qty => "QTY",
            Self::Price => "PRICE",
            Self::PriceOffset => "PRICEOFFSET",
            Self::Amt => "AMT",
            Self::Percentage => "PERCENTAGE",
            Self::Char => "CHAR",
            Self::Boolean => "BOOLEAN",
            Self::MultipleCharValue => "MULTIPLECHARVALUE",
            Self::MultipleStringValue => "MULTIPLESTRINGVALUE",
            Self::Currency => "CURRENCY",
            Self::Exchange => "EXCHANGE",
            Self::Country => "COUNTRY",
            Self::Language => "LANGUAGE",
            Self::Xid => "XID",
            Self::XidRef => "XIDREF",
            Self::UtcTimestamp => "UTCTIMESTAMP",
            Self::UtcTimeOnly => "UTCTIMEONLY",
            Self::UtcDateOnly => "UTCDATEONLY",
            Self::LocalMktDate => "LOCALMKTDATE",
            Self::LocalMktTime => "LOCALMKTTIME",
            Self::MonthYear => "MONTHYEAR",
            Self::TzTimestamp => "TZTIMESTAMP",
            Self::TzTimeOnly => "TZTIMEONLY",
            Self::Data => "DATA",
            Self::XmlData => "XMLDATA",
            Self::Other(name) => name,
        };
        f.write_str(name)
    }
}

impl DataType {
    /// Whether the type is `Int` or one of its subtypes.
    pub fn is_int_based(&self) -> bool {
        matches!(
            self,
            Self::Int
                | Self::Length
                | Self::NumInGroup
                | Self::SeqNum
                | Self::TagNum
                | Self::DayOfMonth
        )
    }

    /// Whether the type is `Float` or one of its subtypes.
    pub fn is_float_based(&self) -> bool {
        matches!(
            self,
            Self::Float
                | Self::Qty
                | Self::Price
                | Self::PriceOffset
                | Self::Amt
                | Self::Percentage
        )
    }

    /// Whether the type holds space-delimited values, as `ExecInst(18)` does.
    pub fn is_multiple_value(&self) -> bool {
        matches!(self, Self::MultipleCharValue | Self::MultipleStringValue)
    }

    /// Whether a field of this type takes its length from another field, as
    /// `RawData(96)` does.
    pub(crate) fn has_length_field(&self) -> bool {
        matches!(self, Self::Data | Self::XmlData)
    }

    /// A code in the form every code for its value shares.
    ///
    /// An int-based type reads codes as numbers, so `01` and `1` agree.
    pub(crate) fn canonical_code<'a>(&self, code: &'a str) -> Cow<'a, str> {
        match code.parse::<i64>() {
            Ok(number) if self.is_int_based() => Cow::Owned(number.to_string()),
            _ => Cow::Borrowed(code),
        }
    }
}

/// The FIX version a dictionary describes, e.g. FIX 4.4 or FIXT 1.1.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Version {
    pub protocol: Protocol,
    pub major: u8,
    pub minor: u8,
    pub service_pack: u8,
}

/// The protocol family a dictionary belongs to.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Protocol {
    /// Classic FIX (4.x and earlier), session and application layers in
    /// one dictionary.
    Fix,
    /// The FIXT transport (FIX 5.x onwards), where the session layer is
    /// versioned separately from application semantics.
    Fixt,
}

/// Whether a message belongs to the session layer or the application layer.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Category {
    /// Session-level machinery: Logon, Heartbeat, Reject, etc.
    Admin,
    /// Business messages: orders, executions, market data.
    App,
}

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

    #[test]
    fn the_int_family_is_int_based() {
        for data_type in [
            DataType::Int,
            DataType::Length,
            DataType::NumInGroup,
            DataType::SeqNum,
            DataType::TagNum,
            DataType::DayOfMonth,
        ] {
            assert!(data_type.is_int_based(), "{data_type:?}");
        }
    }

    #[test]
    fn other_types_are_not_int_based() {
        for data_type in [
            DataType::String,
            DataType::Char,
            DataType::MultipleStringValue,
            DataType::Price,
            DataType::Other("CUSTOM".to_owned()),
        ] {
            assert!(!data_type.is_int_based(), "{data_type:?}");
        }
    }

    #[test]
    fn the_float_family_is_float_based() {
        for data_type in [
            DataType::Float,
            DataType::Qty,
            DataType::Price,
            DataType::PriceOffset,
            DataType::Amt,
            DataType::Percentage,
        ] {
            assert!(data_type.is_float_based(), "{data_type:?}");
        }
    }

    #[test]
    fn other_types_are_not_float_based() {
        for data_type in [
            DataType::Int,
            DataType::String,
            DataType::UtcTimestamp,
            DataType::Other("CUSTOM".to_owned()),
        ] {
            assert!(!data_type.is_float_based(), "{data_type:?}");
        }
    }

    #[test]
    fn the_multiple_value_types_hold_multiple_values() {
        assert!(DataType::MultipleCharValue.is_multiple_value());
        assert!(DataType::MultipleStringValue.is_multiple_value());
        assert!(!DataType::String.is_multiple_value());
        assert!(!DataType::Char.is_multiple_value());
    }

    #[test]
    fn int_codes_are_canonical_as_numbers() {
        assert_eq!(DataType::Int.canonical_code("01"), "1");
        assert_eq!(DataType::Int.canonical_code("-007"), "-7");
        assert_eq!(DataType::Char.canonical_code("01"), "01");
    }
}