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
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
//! # Integer Field Instructions
//!
//! Integer Numbers have unlimited size in the transfer encoding. However, applications typically use
//! fixed sizes for integers. An integer field instruction must therefore specify the bounds of the integer.
//! The encoding and decoding of a value is not affected by the size of the integer.
//!
use std::io::{ErrorKind, Read};

use bytes::Buf;

use crate::{Error, Result};

/// A trait that provides methods for reading basic primitive types.
pub trait Reader {
    /// Reads a single byte.
    /// # Errors
    /// Do not return [`Error::Eof`][crate::Error::Eof] from this method.
    /// Return [`Error::UnexpectedEof`][crate::Error::UnexpectedEof] instead.
    fn read_u8(&mut self) -> Result<u8>;

    /// Read the presence map. Return the bitmap and the number of bits in the bitmap.
    /// # Errors
    /// In case of error, return [`Error::Eof`][crate::Error::Eof] if the end of the stream is reached at the first byte
    /// of the presence map. Otherwise, return any other error, e.g.: [`Error::UnexpectedEof`][crate::Error::UnexpectedEof].
    fn read_presence_map(&mut self) -> Result<(u64, u8)> {
        let mut bitmap: u64 = 0;
        let mut size: u8 = 0;
        let mut byte = match self.read_u8() {
            Ok(b) => b,
            Err(Error::UnexpectedEof) => return Err(Error::Eof),
            Err(e) => return Err(e),
        };
        loop {
            bitmap <<= 7;
            bitmap |= u64::from(byte & 0x7f);
            size += 7;

            if byte & 0x80 == 0x80 {
                return Ok((bitmap, size));
            }
            byte = self.read_u8()?;
        }
    }

    /// Returns decoded non-nullable 64 bit unsigned integer.
    /// # Errors
    /// Returns error if can not read bytes len or bytes len mismatch.
    fn read_uint(&mut self) -> Result<u64> {
        let mut value: u64 = 0;
        loop {
            let byte = self.read_u8()?;
            value <<= 7;
            value |= u64::from(byte & 0x7f);
            if byte & 0x80 == 0x80 {
                return Ok(value);
            }
        }
    }

    /// Returns decoded nullable 64 bit unsigned integer.
    /// # Errors
    /// Returns error if can not read bytes len or bytes len mismatch.
    fn read_uint_nullable(&mut self) -> Result<Option<u64>> {
        let value = self.read_uint()?;
        if value == 0 {
            Ok(None)
        } else {
            Ok(Some(value - 1))
        }
    }

    /// Returns decoded non-nullable 64 bit signed integer.
    /// # Errors
    /// Returns error if can not read bytes len or bytes len mismatch.
    fn read_int(&mut self) -> Result<i64> {
        let mut value: i64 = 0;

        let mut byte = self.read_u8()?;
        if byte & 0x40 != 0 {
            // Negative Integer
            value = -1;
        }
        loop {
            value <<= 7;
            value |= i64::from(byte & 0x7f);

            if byte & 0x80 == 0x80 {
                return Ok(value);
            }
            byte = self.read_u8()?;
        }
    }

    /// Returns decoded nullable 64 bit signed integer.
    /// # Errors
    /// Returns error if can not read bytes len or bytes len mismatch.
    fn read_int_nullable(&mut self) -> Result<Option<i64>> {
        let value = self.read_int()?;
        match value {
            0 => Ok(None),
            value if value < 0 => Ok(Some(value)),
            value => Ok(Some(value - 1)),
        }
    }

    /// Returns decoded non-nullable ASCII encoded string.
    /// # Errors
    /// Returns error if can not read bytes len or bytes len mismatch.
    fn read_ascii_string(&mut self) -> Result<String> {
        let mut byte = self.read_u8()?;
        if byte == 0x80 {
            return Ok(String::new());
        }

        let mut buf: Vec<u8> = Vec::new();
        loop {
            buf.push(byte & 0x7f);
            if byte & 0x80 == 0x80 {
                break;
            }
            byte = self.read_u8()?;
        }
        // SAFETY: `buf` contains ASCII 7-bit characters
        unsafe { Ok(String::from_utf8_unchecked(buf)) }
    }

    /// Returns decoded nullable ASCII encoded string.
    /// # Errors
    /// Returns error if can not read bytes len or bytes len mismatch.
    fn read_ascii_string_nullable(&mut self) -> Result<Option<String>> {
        let mut byte = self.read_u8()?;

        if byte == 0x80 {
            return Ok(None);
        } else if byte == 0x00 {
            byte = self.read_u8()?;
            if byte == 0x80 {
                return Ok(Some(String::new()));
            }
        }

        let mut buf: Vec<u8> = Vec::new();
        loop {
            buf.push(byte & 0x7f);
            if byte & 0x80 == 0x80 {
                break;
            }
            byte = self.read_u8()?;
        }
        // SAFETY: `buf` contains ASCII 7-bit characters
        unsafe { Ok(Some(String::from_utf8_unchecked(buf))) }
    }

    /// Returns decoded non-nullable unicode encoded string.
    /// # Errors
    /// Returns error if can not read bytes len or bytes len mismatch.
    fn read_unicode_string(&mut self) -> Result<String> {
        Ok(String::from_utf8(self.read_bytes()?)?)
    }

    /// Returns decoded nullable unicode encoded string.
    /// # Errors
    /// Returns error if can not read bytes len or bytes len mismatch.
    fn read_unicode_string_nullable(&mut self) -> Result<Option<String>> {
        match self.read_bytes_nullable()? {
            None => Ok(None),
            Some(bytes) => Ok(Some(String::from_utf8(bytes)?)),
        }
    }

    /// Returns decoded non-nullable bytes.
    /// # Errors
    /// Returns error if can not read bytes len or bytes len mismatch.
    fn read_bytes(&mut self) -> Result<Vec<u8>> {
        let length = self.read_uint()?;
        let mut buf = Vec::with_capacity(length as usize);
        for _ in 0..length {
            buf.push(self.read_u8()?);
        }
        Ok(buf)
    }

    /// Returns decoded nullable bytes.
    /// # Errors
    /// Returns error if can not read bytes len or bytes len mismatch.
    fn read_bytes_nullable(&mut self) -> Result<Option<Vec<u8>>> {
        match self.read_uint_nullable()? {
            None => Ok(None),
            Some(length) => {
                let mut buf = Vec::with_capacity(length as usize);
                for _ in 0..length {
                    buf.push(self.read_u8()?);
                }
                Ok(Some(buf))
            }
        }
    }
}

impl Reader for bytes::Bytes {
    fn read_u8(&mut self) -> Result<u8> {
        if self.is_empty() {
            return Err(Error::UnexpectedEof);
        }
        let b = self.get_u8();
        Ok(b)
    }
}

/// Wrapper around `std::io::Read` that implements [`fastlib::Reader`][crate::decoder::reader::Reader].
pub(crate) struct StreamReader<'a> {
    stream: &'a mut dyn Read,
}

impl<'a> StreamReader<'a> {
    pub fn new(stream: &'a mut dyn Read) -> Self {
        Self { stream }
    }
}

impl Reader for StreamReader<'_> {
    fn read_u8(&mut self) -> Result<u8> {
        let mut buf = [0; 1];
        match self.stream.read_exact(&mut buf) {
            Ok(()) => {}
            Err(err) => {
                if err.kind() == ErrorKind::UnexpectedEof {
                    return Err(Error::UnexpectedEof);
                }
                return Err(Error::Dynamic(format!("Stream read error: {err}")));
            }
        }
        Ok(buf[0])
    }
}

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

    #[test]
    fn read_presence_map() {
        struct TestCase {
            input: Vec<u8>,
            pmap: (u64, u8),
        }
        let test_cases: Vec<TestCase> = vec![
            TestCase {
                input: vec![0x80],
                pmap: (0b0, 7),
            },
            TestCase {
                input: vec![0x81],
                pmap: (0b1, 7),
            },
            TestCase {
                input: vec![0x0f, 0x8f],
                pmap: (0b11110001111, 14),
            },
        ];
        for tc in test_cases {
            let mut buf = bytes::Bytes::from(tc.input);
            let pmap = buf.read_presence_map().unwrap();
            assert_eq!(pmap, tc.pmap);
        }
    }

    #[test]
    fn read_uint() {
        struct TestCase {
            input: Vec<u8>,
            value: u64,
        }
        let test_cases: Vec<TestCase> = vec![
            TestCase {
                input: vec![0x80],
                value: 0,
            },
            TestCase {
                input: vec![0x81],
                value: 1,
            },
            TestCase {
                input: vec![0x39, 0x45, 0xa3],
                value: 942755,
            },
        ];
        for tc in test_cases {
            let mut buf = bytes::Bytes::from(tc.input);
            let value = buf.read_uint().unwrap();
            assert_eq!(value, tc.value);
        }
    }

    #[test]
    fn read_uint_nullable() {
        struct TestCase {
            input: Vec<u8>,
            value: Option<u64>,
        }
        let test_cases: Vec<TestCase> = vec![
            TestCase {
                input: vec![0x80],
                value: None,
            },
            TestCase {
                input: vec![0x81],
                value: Some(0),
            },
            TestCase {
                input: vec![0x39, 0x45, 0xa4],
                value: Some(942755),
            },
        ];
        for tc in test_cases {
            let mut buf = bytes::Bytes::from(tc.input);
            let value = buf.read_uint_nullable().unwrap();
            assert_eq!(value, tc.value);
        }
    }

    #[test]
    fn read_int() {
        struct TestCase {
            input: Vec<u8>,
            value: i64,
        }
        let test_cases: Vec<TestCase> = vec![
            // Mandatory Positive Number
            TestCase {
                input: vec![0x39, 0x45, 0xa3],
                value: 942755,
            },
            // Mandatory Negative Number
            TestCase {
                input: vec![0x7c, 0x1b, 0x1b, 0x9d],
                value: -7942755,
            },
            // Mandatory Positive Number with sign-bit extension
            TestCase {
                input: vec![0x00, 0x40, 0x81],
                value: 8193,
            },
            // Mandatory Negative Number with sign-bit extension
            TestCase {
                input: vec![0x7f, 0x3f, 0xff],
                value: -8193,
            },
        ];
        for tc in test_cases {
            let mut buf = bytes::Bytes::from(tc.input);
            let value = buf.read_int().unwrap();
            assert_eq!(value, tc.value);
        }
    }

    #[test]
    fn read_int_nullable() {
        struct TestCase {
            input: Vec<u8>,
            value: Option<i64>,
        }
        let test_cases: Vec<TestCase> = vec![
            TestCase {
                input: vec![0x80],
                value: None,
            },
            // Optional Positive Number
            TestCase {
                input: vec![0x39, 0x45, 0xa4],
                value: Some(942755),
            },
            // Optional Negative Number
            TestCase {
                input: vec![0x46, 0x3a, 0xdd],
                value: Some(-942755),
            },
        ];
        for tc in test_cases {
            let mut buf = bytes::Bytes::from(tc.input);
            let value = buf.read_int_nullable().unwrap();
            assert_eq!(value, tc.value);
        }
    }

    #[test]
    fn read_ascii_string() {
        struct TestCase {
            input: Vec<u8>,
            value: String,
        }
        let test_cases: Vec<TestCase> = vec![
            TestCase {
                input: vec![0x80],
                value: "".to_string(),
            },
            TestCase {
                input: vec![0x41, 0x42, 0xc3],
                value: "ABC".to_string(),
            },
        ];
        for tc in test_cases {
            let mut buf = bytes::Bytes::from(tc.input);
            let value = buf.read_ascii_string().unwrap();
            assert_eq!(value, tc.value);
        }
    }

    #[test]
    fn read_ascii_string_nullable() {
        struct TestCase {
            input: Vec<u8>,
            value: Option<String>,
        }
        let test_cases: Vec<TestCase> = vec![
            TestCase {
                input: vec![0x80],
                value: None,
            },
            TestCase {
                input: vec![0x00, 0x80],
                value: Some("".to_string()),
            },
            TestCase {
                input: vec![0x41, 0x42, 0xc3],
                value: Some("ABC".to_string()),
            },
        ];
        for tc in test_cases {
            let mut buf = bytes::Bytes::from(tc.input);
            let value = buf.read_ascii_string_nullable().unwrap();
            assert_eq!(value, tc.value);
        }
    }

    #[test]
    fn read_unicode_string() {
        struct TestCase {
            input: Vec<u8>,
            value: String,
        }
        let test_cases: Vec<TestCase> = vec![
            TestCase {
                input: vec![0x80],
                value: "".to_string(),
            },
            TestCase {
                input: vec![0x83, 0x41, 0x42, 0x43],
                value: "ABC".to_string(),
            },
        ];
        for tc in test_cases {
            let mut buf = bytes::Bytes::from(tc.input);
            let value = buf.read_unicode_string().unwrap();
            assert_eq!(value, tc.value);
        }
    }

    #[test]
    fn read_unicode_string_nullable() {
        struct TestCase {
            input: Vec<u8>,
            value: Option<String>,
        }
        let test_cases: Vec<TestCase> = vec![
            TestCase {
                input: vec![0x80],
                value: None,
            },
            TestCase {
                input: vec![0x81],
                value: Some("".to_string()),
            },
            TestCase {
                input: vec![0x84, 0x41, 0x42, 0x43],
                value: Some("ABC".to_string()),
            },
        ];
        for tc in test_cases {
            let mut buf = bytes::Bytes::from(tc.input);
            let value = buf.read_unicode_string_nullable().unwrap();
            assert_eq!(value, tc.value);
        }
    }

    #[test]
    fn read_bytes() {
        struct TestCase {
            input: Vec<u8>,
            value: Vec<u8>,
        }
        let test_cases: Vec<TestCase> = vec![
            TestCase {
                input: vec![0x80],
                value: vec![],
            },
            TestCase {
                input: vec![0x83, 0x41, 0x42, 0x43],
                value: vec![0x41, 0x42, 0x43],
            },
        ];
        for tc in test_cases {
            let mut buf = bytes::Bytes::from(tc.input);
            let value = buf.read_bytes().unwrap();
            assert_eq!(value, tc.value);
        }
    }

    #[test]
    fn read_bytes_nullable() {
        struct TestCase {
            input: Vec<u8>,
            value: Option<Vec<u8>>,
        }
        let test_cases: Vec<TestCase> = vec![
            TestCase {
                input: vec![0x80],
                value: None,
            },
            TestCase {
                input: vec![0x81],
                value: Some(vec![]),
            },
            TestCase {
                input: vec![0x84, 0x41, 0x42, 0x43],
                value: Some(vec![0x41, 0x42, 0x43]),
            },
        ];
        for tc in test_cases {
            let mut buf = bytes::Bytes::from(tc.input);
            let value = buf.read_bytes_nullable().unwrap();
            assert_eq!(value, tc.value);
        }
    }
}