fastlib 0.3.7

FAST (FIX Adapted for STreaming protocol) is a space and processing efficient encoding method for message oriented data streams.
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
use std::fmt::{Display, Formatter};

use crate::{Error, Result};

/// Represents a scaled decimal number.
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct Decimal {
    pub exponent: i32,
    pub mantissa: i64,
}

impl Decimal {
    #[must_use]
    pub fn new(exponent: i32, mantissa: i64) -> Decimal {
        Decimal { exponent, mantissa }
    }

    /// If the field is of type decimal, the value resulting from the conversion is normalized. The reason for this is that
    /// the exponent and mantissa must be predictable when operators are applied to them individually. A decimal value
    /// is normalized by adjusting the mantissa and exponent so that the integer remainder after dividing the mantissa
    /// by 10 is not zero: mant % 10 != 0. For example 100 would be normalized as 1 * 10^2. If the mantissa is zero,
    /// the normalized decimal has a zero mantissa and a zero exponent.
    /// # Errors
    /// Returns error if string is incorrect format.
    pub fn from_string(value: &str) -> Result<Decimal> {
        fn scale_down(mut value: i64) -> (i32, i64) {
            let mut scale = 0;
            if value != 0 {
                while value % 10 == 0 {
                    value /= 10;
                    scale += 1;
                }
            }
            (scale, value)
        }

        let mut parts = value.split('.');
        let Some(mantissa) = parts.next() else {
            return Err(Error::Static(format!("Not a decimal '{value}'")));
        };

        let Some(fractional) = parts.next() else {
            let (exponent, mantissa) = scale_down(mantissa.parse::<i64>()?);
            return Ok(Decimal::new(exponent, mantissa));
        };
        if parts.next().is_some() {
            return Err(Error::Static(format!("Not a decimal '{value}'")));
        }

        let mantissa = format!("{mantissa}{fractional}").parse::<i64>()?;
        if mantissa == 0 {
            return Ok(Decimal::new(0, 0));
        }
        let (exponent_fix, mantissa) = scale_down(mantissa);
        let exponent = -(fractional.len() as i32) + exponent_fix;
        Ok(Decimal::new(exponent, mantissa))
    }

    /// Creates decimal value from float.
    /// # Errors
    /// Returns error if number is not finite.
    pub fn from_float(value: f64) -> Result<Decimal> {
        if !value.is_finite() {
            return Err(Error::Static(format!("Not a finite decimal '{value}'")));
        }
        Decimal::from_string(&format!("{value}"))
    }

    /// If the number is in fact an integer, it is converted as if was of integer type. Otherwise, the number
    /// is represented by an integer part and a decimal part separated by a decimal point (‘.’). Each part is
    /// a sequence of digits ‘0’ – ‘9’. There must be at least one digit on each side of the decimal point.
    /// If the number is negative it is preceded by a minus sign (‘-’).
    /// The integer part must not have any leading zeroes.
    #[allow(clippy::inherent_to_string_shadow_display)]
    #[must_use]
    pub fn to_string(&self) -> String {
        if self.exponent >= 0 {
            (self.mantissa * 10i64.pow(self.exponent as u32)).to_string()
        } else {
            let divisor = 10i64.pow(-self.exponent as u32);
            if self.mantissa % divisor == 0 {
                (self.mantissa / divisor).to_string()
            } else {
                format!("{:.*}", -self.exponent as usize, self.to_float())
            }
        }
    }

    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn to_float(&self) -> f64 {
        // self.mantissa as f64 * 10_f64.powf(self.exponent as f64)

        // This is pretty ugly but gives MUCH better results than the implementation above!
        match self.exponent {
            0 => self.mantissa as f64,
            exponent if exponent > 0 => {
                let multiplier = 10i64.pow(exponent as u32);
                (self.mantissa * multiplier) as f64
            }
            exponent => {
                let divisor = 10u64.pow(-exponent as u32);
                self.mantissa as f64 / divisor as f64
            }
        }
    }
}

/// Format the decimal as number with specific number of digits after the decimal point.
impl Display for Decimal {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        if self.exponent >= 0 {
            // keep .0 at the end even if the number is integer
            write!(f, "{}.0", self.mantissa * 10i64.pow(self.exponent as u32))
        } else {
            write!(f, "{:.*}", -self.exponent as usize, self.to_float())
        }
    }
}

impl Default for Decimal {
    fn default() -> Self {
        Decimal::new(0, 0)
    }
}

impl From<Decimal> for f64 {
    fn from(value: Decimal) -> Self {
        value.to_float()
    }
}

impl TryFrom<f64> for Decimal {
    type Error = Error;

    fn try_from(value: f64) -> Result<Self> {
        Self::from_float(value)
    }
}

#[cfg(feature = "rust_decimal")]
impl From<Decimal> for rust_decimal::Decimal {
    fn from(value: Decimal) -> Self {
        if value.exponent <= 0 {
            Self::new(value.mantissa, -value.exponent as u32)
        } else {
            let number = value.mantissa * 10i64.pow(value.exponent as u32);
            Self::new(number, 0)
        }
    }
}

#[cfg(feature = "rust_decimal")]
impl TryFrom<rust_decimal::Decimal> for Decimal {
    type Error = Error;

    fn try_from(value: rust_decimal::Decimal) -> Result<Self> {
        use rust_decimal::prelude::ToPrimitive;

        // Get mantissa and scale as mantissa and exponent and adjust as per
        // the FIX specification for decimals: the integer remainder after dividing
        // the mantissa by 10 is not zero.
        let mut exponent = -(value.scale() as i64);
        let mut mantissa = value.mantissa();
        if mantissa != 0 {
            while mantissa % 10 == 0 {
                mantissa /= 10;
                exponent += 1;
            }
        }
        // Check mantissa and exponent are within bounds.
        let mantissa = match mantissa.to_i64() {
            Some(m) => m,
            None => {
                return Err(Error::Static("Mantissa is too large".to_string()));
            }
        };
        let exponent = match exponent.to_i32() {
            Some(e) => e,
            None => {
                return Err(Error::Static("Exponent is too large".to_string()));
            }
        };
        Ok(Self::new(exponent, mantissa))
    }
}

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

    #[test]
    fn decimal_from_string() {
        struct TestCase {
            input: &'static str,
            components: (i32, i64),
            float: f64,
        }

        fn do_test(tts: Vec<TestCase>) {
            for tt in tts {
                let d = Decimal::from_string(tt.input).unwrap();
                assert_eq!((d.exponent, d.mantissa), tt.components);
                assert_eq!(d.to_float(), tt.float);
            }
        }

        do_test(vec![
            TestCase {
                input: "1200.45",
                components: (-2, 120045),
                float: 1200.45,
            },
            TestCase {
                input: "001200.4500",
                components: (-2, 120045),
                float: 1200.45,
            },
            TestCase {
                input: "0",
                components: (0, 0),
                float: 0.0,
            },
            TestCase {
                input: "0.0",
                components: (0, 0),
                float: 0.0,
            },
            TestCase {
                input: "1",
                components: (0, 1),
                float: 1.0,
            },
            TestCase {
                input: "10",
                components: (1, 1),
                float: 10.0,
            },
            TestCase {
                input: "-1",
                components: (0, -1),
                float: -1.0,
            },
            TestCase {
                input: "0.03",
                components: (-2, 3),
                float: 0.03,
            },
            TestCase {
                input: "-0.03",
                components: (-2, -3),
                float: -0.03,
            },
        ]);
    }

    #[test]
    fn decimal_to_string() {
        struct TestCase {
            components: (i32, i64),
            string: &'static str,
            display: &'static str,
        }

        fn do_test(tts: Vec<TestCase>) {
            for tt in tts {
                let d = Decimal::new(tt.components.0, tt.components.1);
                assert_eq!(d.to_string(), tt.string, "(string)");
                assert_eq!(&format!("{d}"), tt.display, "(display)");
            }
        }

        do_test(vec![
            TestCase {
                components: (0, 0),
                string: "0",
                display: "0.0", // keep .0 at the end even in the number in integer
            },
            TestCase {
                components: (2, 0),
                string: "0",
                display: "0.0", // keep .0 at the end even in the number in integer
            },
            TestCase {
                components: (1, 2),
                string: "20",
                display: "20.0", // keep .0 at the end even in the number in integer
            },
            TestCase {
                components: (-3, 1000),
                string: "1",
                display: "1.000",
            },
            TestCase {
                components: (-5, 100),
                string: "0.00100",
                display: "0.00100",
            },
            TestCase {
                components: (-2, 0),
                string: "0",
                display: "0.00",
            },
            TestCase {
                components: (1, -2),
                string: "-20",
                display: "-20.0", // keep .0 at the end even in the number in integer
            },
            TestCase {
                components: (-3, -1000),
                string: "-1",
                display: "-1.000",
            },
            TestCase {
                components: (-5, -100),
                string: "-0.00100",
                display: "-0.00100",
            },
        ]);
    }

    #[test]
    fn decimal_from_float() {
        struct TestCase {
            input: f64,
            components: (i32, i64),
        }

        fn do_test(tts: Vec<TestCase>) {
            for tt in tts {
                let d = Decimal::from_float(tt.input).unwrap();
                assert_eq!((d.exponent, d.mantissa), tt.components);
            }
        }

        do_test(vec![
            TestCase {
                input: 1200.45,
                components: (-2, 120045),
            },
            TestCase {
                input: 0.0,
                components: (0, 0),
            },
            TestCase {
                input: 1.0,
                components: (0, 1),
            },
            TestCase {
                input: 10.0,
                components: (1, 1),
            },
            TestCase {
                input: -1.0,
                components: (0, -1),
            },
            TestCase {
                input: 0.1,
                components: (-1, 1),
            },
        ]);
    }

    #[cfg(feature = "rust_decimal")]
    #[test]
    fn decimal_from_rust_decimal() {
        use rust_decimal::prelude::FromPrimitive;

        struct TestCase {
            float: f64,
            components: (i32, i64),
        }

        fn do_test(tts: Vec<TestCase>) {
            for tt in tts {
                let rd = rust_decimal::Decimal::from_f64(tt.float).unwrap();
                let d = Decimal::try_from(rd).unwrap();
                assert_eq!((d.exponent, d.mantissa), tt.components);
            }
        }

        do_test(vec![
            TestCase {
                float: 1200.45,
                components: (-2, 120045),
            },
            TestCase {
                float: 0.0,
                components: (0, 0),
            },
            TestCase {
                float: 1.0,
                components: (0, 1),
            },
            TestCase {
                float: 100.0,
                components: (2, 1),
            },
            TestCase {
                float: -1.0,
                components: (0, -1),
            },
            TestCase {
                float: 0.03,
                components: (-2, 3),
            },
            TestCase {
                float: -0.03,
                components: (-2, -3),
            },
        ]);
    }

    #[test]
    fn decimal_to_any() {
        struct TestCase {
            components: (i32, i64),
            float: f64,
        }

        fn do_test(tts: Vec<TestCase>) {
            #[cfg(feature = "rust_decimal")]
            use rust_decimal::prelude::ToPrimitive;

            for tt in tts {
                let d = Decimal::new(tt.components.0, tt.components.1);
                assert_eq!(d.to_float(), tt.float);
                assert_eq!(f64::from(d.clone()), tt.float);

                #[cfg(feature = "rust_decimal")]
                assert_eq!(rust_decimal::Decimal::from(d).to_f64().unwrap(), tt.float);
            }
        }

        do_test(vec![
            TestCase {
                components: (-2, 120045),
                float: 1200.45,
            },
            TestCase {
                components: (0, 0),
                float: 0.0,
            },
            TestCase {
                components: (0, 1),
                float: 1.0,
            },
            TestCase {
                components: (2, 1),
                float: 100.0,
            },
            TestCase {
                components: (0, -1),
                float: -1.0,
            },
            TestCase {
                components: (-2, 3),
                float: 0.03,
            },
            TestCase {
                components: (-2, -3),
                float: -0.03,
            },
        ]);
    }
}