Skip to main content

easyfix_core/
version.rs

1//! FIX protocol version identification.
2//!
3//! [`Version`] represents one of the standard FIX protocol versions
4//! (FIX 2.7 - FIX 5.0 SP2, FIXT 1.1). Construction is restricted to the
5//! provided constants and the [`FromStr`] parser, which validates against
6//! the list of [`Version::known_versions`].
7
8use core::{fmt, str::FromStr};
9
10use crate::{
11    basic_types::{FixStr, FixString},
12    fix_str,
13};
14
15#[cfg(test)]
16mod tests;
17
18/// Which FIX protocol family a [`Version`] belongs to.
19///
20/// FIX (FIX 4.x, 5.x) bundles session and application messages under a
21/// single `BeginString`. FIXT (1.1) is the dedicated session-layer
22/// protocol; the application version is carried separately via
23/// `ApplVerID`.
24#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
25#[cfg_attr(feature = "serde-serialize", derive(serde::Serialize))]
26#[cfg_attr(feature = "serde-deserialize", derive(serde::Deserialize))]
27#[cfg_attr(
28    any(feature = "serde-serialize", feature = "serde-deserialize"),
29    serde(rename_all = "UPPERCASE")
30)]
31pub enum SessionProtocol {
32    Fix,
33    Fixt,
34}
35
36impl fmt::Display for SessionProtocol {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        match self {
39            SessionProtocol::Fix => f.write_str("FIX"),
40            SessionProtocol::Fixt => f.write_str("FIXT"),
41        }
42    }
43}
44
45/// A specific version of the FIX protocol.
46///
47/// Construct via the provided `Version::FIX*` / `Version::FIXT11`
48/// constants or via [`FromStr`] which parses standard `BeginString`
49/// representations (`"FIX.4.4"`, `"FIXT.1.1"`, `"FIX.5.0SP2"`).
50///
51/// Only versions listed in [`Version::known_versions`] are valid.
52#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
53pub struct Version {
54    session_protocol: SessionProtocol,
55    major: u8,
56    minor: u8,
57    servicepack: u8,
58}
59
60/// Error returned when constructing a [`Version`] from components or
61/// parsing one from a `BeginString` fails because the value is not
62/// among [`Version::known_versions`].
63#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
64#[error("Unknown FIX version")]
65pub struct UnknownVersionError;
66
67impl Version {
68    pub const FIX27: Version = Version {
69        session_protocol: SessionProtocol::Fix,
70        major: 2,
71        minor: 7,
72        servicepack: 0,
73    };
74    pub const FIX30: Version = Version {
75        session_protocol: SessionProtocol::Fix,
76        major: 3,
77        minor: 0,
78        servicepack: 0,
79    };
80    pub const FIX40: Version = Version {
81        session_protocol: SessionProtocol::Fix,
82        major: 4,
83        minor: 0,
84        servicepack: 0,
85    };
86    pub const FIX41: Version = Version {
87        session_protocol: SessionProtocol::Fix,
88        major: 4,
89        minor: 1,
90        servicepack: 0,
91    };
92    pub const FIX42: Version = Version {
93        session_protocol: SessionProtocol::Fix,
94        major: 4,
95        minor: 2,
96        servicepack: 0,
97    };
98    pub const FIX43: Version = Version {
99        session_protocol: SessionProtocol::Fix,
100        major: 4,
101        minor: 3,
102        servicepack: 0,
103    };
104    pub const FIX44: Version = Version {
105        session_protocol: SessionProtocol::Fix,
106        major: 4,
107        minor: 4,
108        servicepack: 0,
109    };
110    pub const FIX50: Version = Version {
111        session_protocol: SessionProtocol::Fix,
112        major: 5,
113        minor: 0,
114        servicepack: 0,
115    };
116    pub const FIX50SP1: Version = Version {
117        session_protocol: SessionProtocol::Fix,
118        major: 5,
119        minor: 0,
120        servicepack: 1,
121    };
122    pub const FIX50SP2: Version = Version {
123        session_protocol: SessionProtocol::Fix,
124        major: 5,
125        minor: 0,
126        servicepack: 2,
127    };
128    pub const FIXT11: Version = Version {
129        session_protocol: SessionProtocol::Fixt,
130        major: 1,
131        minor: 1,
132        servicepack: 0,
133    };
134    /// The rolling *FIX Latest* application layer, projected onto its base
135    /// (frozen) version.
136    ///
137    /// FIX Latest = FIX50SP2 plus the cumulative extension-pack stream
138    /// (FIX Session Layer ยง3.1.17), so on the version axis it equals
139    /// FIX50SP2 - until the FIX Trading Community ever cuts a new frozen
140    /// release. Alias: compares equal to [`Version::FIX50SP2`].
141    pub const FIX_LATEST: Version = Version::FIX50SP2;
142    /// Length of the longest `BeginString` among [`known_versions`]. A
143    /// `BeginString(8)` value running past this without its SOH cannot name
144    /// a version this crate frames, which is what lets a reader bound its
145    /// buffer before `BodyLength(9)` is even in sight.
146    ///
147    /// [`known_versions`]: Self::known_versions
148    pub const MAX_BEGIN_STRING_LEN: usize = {
149        let versions = Version::known_versions();
150        let mut max = 0;
151        let mut i = 0;
152        while i < versions.len() {
153            let len = versions[i].begin_str().len();
154            if len > max {
155                max = len;
156            }
157            i += 1;
158        }
159        max
160    };
161
162    /// All FIX versions recognized by this crate.
163    pub const fn known_versions() -> &'static [Version] {
164        &[
165            Version::FIX27,
166            Version::FIX30,
167            Version::FIX40,
168            Version::FIX41,
169            Version::FIX42,
170            Version::FIX43,
171            Version::FIX44,
172            Version::FIX50,
173            Version::FIX50SP1,
174            Version::FIX50SP2,
175            Version::FIXT11,
176        ]
177    }
178
179    /// Build a `Version` from its components.
180    ///
181    /// Returns [`UnknownVersionError`] if the combination does not
182    /// correspond to a version listed in [`Version::known_versions`].
183    pub fn new(
184        session_protocol: SessionProtocol,
185        major: u8,
186        minor: u8,
187        servicepack: u8,
188    ) -> Result<Version, UnknownVersionError> {
189        let candidate = Version {
190            session_protocol,
191            major,
192            minor,
193            servicepack,
194        };
195        if Version::known_versions().contains(&candidate) {
196            Ok(candidate)
197        } else {
198            Err(UnknownVersionError)
199        }
200    }
201
202    /// Returns true if this is a traditional FIX (FIX 4.x / FIX 5.x)
203    /// version.
204    pub const fn is_fix(&self) -> bool {
205        matches!(self.session_protocol, SessionProtocol::Fix)
206    }
207
208    /// Returns true if this is a FIXT version.
209    pub const fn is_fixt(&self) -> bool {
210        matches!(self.session_protocol, SessionProtocol::Fixt)
211    }
212
213    /// Returns the major version number.
214    pub const fn major(&self) -> u8 {
215        self.major
216    }
217
218    /// Returns the minor version number.
219    pub const fn minor(&self) -> u8 {
220        self.minor
221    }
222
223    /// Returns the service pack level.
224    pub const fn servicepack(&self) -> u8 {
225        self.servicepack
226    }
227
228    /// Returns the canonical `BeginString` representation as a
229    /// `&'static FixStr`. This is the zero-allocation form intended for
230    /// the serialization path.
231    pub const fn begin_str(&self) -> &'static FixStr {
232        use SessionProtocol::{Fix, Fixt};
233        match (
234            self.session_protocol,
235            self.major,
236            self.minor,
237            self.servicepack,
238        ) {
239            (Fix, 2, 7, 0) => fix_str!("FIX.2.7"),
240            (Fix, 3, 0, 0) => fix_str!("FIX.3.0"),
241            (Fix, 4, 0, 0) => fix_str!("FIX.4.0"),
242            (Fix, 4, 1, 0) => fix_str!("FIX.4.1"),
243            (Fix, 4, 2, 0) => fix_str!("FIX.4.2"),
244            (Fix, 4, 3, 0) => fix_str!("FIX.4.3"),
245            (Fix, 4, 4, 0) => fix_str!("FIX.4.4"),
246            (Fix, 5, 0, 0) => fix_str!("FIX.5.0"),
247            (Fix, 5, 0, 1) => fix_str!("FIX.5.0SP1"),
248            (Fix, 5, 0, 2) => fix_str!("FIX.5.0SP2"),
249            (Fixt, 1, 1, 0) => fix_str!("FIXT.1.1"),
250            _ => panic!("Version constructors only allow known versions"),
251        }
252    }
253
254    /// Returns an owned `FixString` copy of the canonical `BeginString`.
255    /// Convenience for callers that need to build outgoing FIX messages;
256    /// allocates. Prefer [`Version::begin_str`] on the hot path.
257    pub fn begin_string(&self) -> FixString {
258        self.begin_str().to_owned()
259    }
260}
261
262impl fmt::Display for Version {
263    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
264        f.write_str(self.begin_str().as_utf8())
265    }
266}
267
268impl FromStr for Version {
269    type Err = UnknownVersionError;
270
271    /// Parse a `BeginString` value into a [`Version`].
272    ///
273    /// Accepts strings in the format:
274    /// - `"FIX.MAJOR.MINOR"` (e.g., `"FIX.4.4"`)
275    /// - `"FIXT.MAJOR.MINOR"` (e.g., `"FIXT.1.1"`)
276    /// - `"FIX.MAJOR.MINORSPx"` (e.g., `"FIX.5.0SP2"`)
277    ///
278    /// Returns [`UnknownVersionError`] if the format is invalid or the
279    /// parsed version is not in [`Version::known_versions`].
280    fn from_str(s: &str) -> Result<Self, Self::Err> {
281        let parts: Vec<&str> = s.split('.').collect();
282
283        let [protocol, major, minor_and_sp] = parts.as_slice() else {
284            return Err(UnknownVersionError);
285        };
286
287        let session_protocol = match *protocol {
288            "FIX" => SessionProtocol::Fix,
289            "FIXT" => SessionProtocol::Fixt,
290            _ => return Err(UnknownVersionError),
291        };
292
293        let major = major.parse::<u8>().map_err(|_| UnknownVersionError)?;
294        let (minor, servicepack) = if let Some((minor_str, sp_str)) = minor_and_sp.split_once("SP")
295        {
296            let minor = minor_str.parse::<u8>().map_err(|_| UnknownVersionError)?;
297            let sp = sp_str.parse::<u8>().map_err(|_| UnknownVersionError)?;
298
299            (minor, sp)
300        } else {
301            let minor = minor_and_sp
302                .parse::<u8>()
303                .map_err(|_| UnknownVersionError)?;
304            (minor, 0)
305        };
306
307        Version::new(session_protocol, major, minor, servicepack)
308    }
309}
310
311#[cfg(feature = "serde-serialize")]
312impl serde::Serialize for Version {
313    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
314        serializer.serialize_str(self.begin_str().as_utf8())
315    }
316}
317
318#[cfg(feature = "serde-deserialize")]
319impl<'de> serde::Deserialize<'de> for Version {
320    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
321        use std::borrow;
322
323        use serde::de::Error;
324        let s = <borrow::Cow<'de, str>>::deserialize(deserializer)?;
325        Version::from_str(&s).map_err(D::Error::custom)
326    }
327}