dbz-lib 0.2.2

Library for working with the Databento Binary Encoding (DBZ) format
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
use std::{
    fs::File,
    io::{self, BufReader, Read},
    marker::PhantomData,
    mem,
    path::Path,
};

use anyhow::{anyhow, Context};
use log::{debug, warn};
use serde::Serialize;
use streaming_iterator::StreamingIterator;
use zstd::Decoder;

use databento_defs::{
    enums::{Compression, SType, Schema},
    record::{transmute_record_bytes, ConstTypeId},
};

use crate::write::dbz::SCHEMA_VERSION;

/// Object for reading, parsing, and serializing a Databento Binary Encoding (DBZ) file.
#[derive(Debug)]
pub struct Dbz<R: io::BufRead> {
    reader: R,
    metadata: Metadata,
}

/// Information about the data contained in a DBZ file.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Metadata {
    /// The DBZ schema version number.
    pub version: u8,
    /// The dataset name.
    pub dataset: String,
    /// The data record schema. Specifies which record type is stored in the DBZ file.
    pub schema: Schema,
    /// The UNIX nanosecond timestamp of the query start, or the first record if the file was split.
    pub start: u64,
    /// The UNIX nanosecond timestamp of the query end, or the last record if the file was split.
    pub end: u64,
    /// The maximum number of records for the query.
    pub limit: u64,
    /// The total number of data records.
    pub record_count: u64,
    /// The data compression format (if any).
    pub compression: Compression,
    /// The input symbology type to map from.
    pub stype_in: SType,
    /// The output symbology type to map to.
    pub stype_out: SType,
    /// The original query input symbols from the request.
    pub symbols: Vec<String>,
    /// Symbols that did not resolve for _at least one day_ in the query time range.
    pub partial: Vec<String>,
    /// Symbols that did not resolve for _any_ day in the query time range.
    pub not_found: Vec<String>,
    /// Symbol mappings containing a native symbol and its mapping intervals.
    pub mappings: Vec<SymbolMapping>,
}

/// A native symbol and its symbol mappings for different time ranges within the query range.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(
    any(feature = "python", feature = "python-test"),
    derive(pyo3::FromPyObject)
)]
pub struct SymbolMapping {
    /// The native symbol.
    pub native: String,
    /// The mappings of `native` for different date ranges.
    pub intervals: Vec<MappingInterval>,
}

/// The resolved symbol for a date range.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct MappingInterval {
    /// UTC start date of interval.
    #[serde(serialize_with = "serialize_date")]
    pub start_date: time::Date,
    /// UTC end date of interval.
    #[serde(serialize_with = "serialize_date")]
    pub end_date: time::Date,
    /// The resolved symbol for this interval.
    pub symbol: String,
}

// Override `time::Date`'s serialization format to be ISO 8601.
fn serialize_date<S: serde::Serializer>(
    date: &time::Date,
    serializer: S,
) -> Result<S::Ok, S::Error> {
    serializer.serialize_str(&date.to_string()) // ISO 8601
}

impl Dbz<BufReader<File>> {
    /// Creates a new [`Dbz`] from the file at `path`. This function reads the metadata,
    /// but does not read the body of the file.
    ///
    /// # Errors
    /// This function will return an error if `path` doesn't exist. It will also return an error
    /// if it is unable to parse the metadata from the file.
    pub fn from_file(path: impl AsRef<Path>) -> anyhow::Result<Self> {
        let file = File::open(path.as_ref()).with_context(|| {
            format!(
                "Error opening dbz file at path '{}'",
                path.as_ref().display()
            )
        })?;
        let reader = BufReader::new(file);
        Self::new(reader)
    }
}

// `BufRead` instead of `Read` because the [zstd::Decoder] works with `BufRead` so accepting
// a `Read` could result in redundant `BufReader`s being created.
impl<R: io::BufRead> Dbz<R> {
    /// Creates a new [`Dbz`] from `reader`.
    ///
    /// # Errors
    /// This function will return an error if it is unable to parse the metadata in `reader`.
    pub fn new(mut reader: R) -> anyhow::Result<Self> {
        let metadata = Metadata::read(&mut reader)?;
        Ok(Self { reader, metadata })
    }

    /// Returns the [`Schema`] of the DBZ data. The schema also indicates the record type `T` for
    /// [`Self::try_into_iter`].
    pub fn schema(&self) -> Schema {
        self.metadata.schema
    }

    /// Returns a reference to all metadata read from the Dbz data in a [`Metadata`] object.
    pub fn metadata(&self) -> &Metadata {
        &self.metadata
    }

    /// Try to decode the DBZ file into a streaming iterator. This decodes the
    /// data lazily.
    ///
    /// # Errors
    /// This function will return an error if the zstd portion of the DBZ file
    /// was compressed in an unexpected manner.
    pub fn try_into_iter<T: ConstTypeId>(self) -> anyhow::Result<DbzStreamIter<R, T>> {
        DbzStreamIter::new(self.reader, self.metadata)
    }
}

/// A consuming iterator over a [`Dbz`]. Lazily decompresses and translates the contents of the file
/// or other buffer. This struct is created by the [`Dbz::try_into_iter`] method.
pub struct DbzStreamIter<R: io::BufRead, T> {
    /// [`Metadata`] about the file being iterated
    metadata: Metadata,
    /// Reference to the underlying [`Dbz`] object.
    /// Buffered zstd decoder of the DBZ file, so each call to [`DbzStreamIter::next()`] doesn't result in a
    /// separate system call.
    decoder: Decoder<'static, R>,
    /// Number of elements that have been decoded. Used for [`Iterator::size_hint`].
    i: usize,
    /// Reusable buffer for reading into.
    buffer: Vec<u8>,
    /// Required to associate [`DbzStreamIter`] with a `T`.
    _item: PhantomData<T>,
}

impl<R: io::BufRead, T> DbzStreamIter<R, T> {
    pub(crate) fn new(reader: R, metadata: Metadata) -> anyhow::Result<Self> {
        let decoder = Decoder::with_buffer(reader)?;
        Ok(DbzStreamIter {
            metadata,
            decoder,
            i: 0,
            buffer: vec![0; mem::size_of::<T>()],
            _item: PhantomData {},
        })
    }
}

impl<R: io::BufRead, T: ConstTypeId> StreamingIterator for DbzStreamIter<R, T> {
    type Item = T;

    fn advance(&mut self) {
        if let Err(e) = self.decoder.read_exact(&mut self.buffer) {
            warn!("Failed to read from DBZ decoder: {e:?}");
            self.i = self.metadata.record_count as usize + 1;
        }
        self.i += 1;
    }

    fn get(&self) -> Option<&Self::Item> {
        if self.i > self.metadata.record_count as usize {
            return None;
        }
        // Safety: `buffer` is specifically sized to `T`
        unsafe { transmute_record_bytes(self.buffer.as_slice()) }
    }

    /// Returns the lower bound and upper bounds of remaining length of iterator.
    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.metadata.record_count as usize - self.i;
        // assumes `record_count` is accurate. If it is not, the program won't crash but
        // performance will be suboptimal
        (remaining, Some(remaining))
    }
}

pub(crate) trait FromLittleEndianSlice {
    fn from_le_slice(slice: &[u8]) -> Self;
}

impl FromLittleEndianSlice for u64 {
    /// NOTE: assumes the length of `slice` is at least 8 bytes
    fn from_le_slice(slice: &[u8]) -> Self {
        let (bytes, _) = slice.split_at(mem::size_of::<Self>());
        Self::from_le_bytes(bytes.try_into().unwrap())
    }
}

impl FromLittleEndianSlice for i32 {
    /// NOTE: assumes the length of `slice` is at least 4 bytes
    fn from_le_slice(slice: &[u8]) -> Self {
        let (bytes, _) = slice.split_at(mem::size_of::<Self>());
        Self::from_le_bytes(bytes.try_into().unwrap())
    }
}

impl FromLittleEndianSlice for u32 {
    /// NOTE: assumes the length of `slice` is at least 4 bytes
    fn from_le_slice(slice: &[u8]) -> Self {
        let (bytes, _) = slice.split_at(mem::size_of::<Self>());
        Self::from_le_bytes(bytes.try_into().unwrap())
    }
}

impl FromLittleEndianSlice for u16 {
    /// NOTE: assumes the length of `slice` is at least 2 bytes
    fn from_le_slice(slice: &[u8]) -> Self {
        let (bytes, _) = slice.split_at(mem::size_of::<Self>());
        Self::from_le_bytes(bytes.try_into().unwrap())
    }
}

impl Metadata {
    const U32_SIZE: usize = mem::size_of::<u32>();

    pub(crate) fn read(reader: &mut impl io::Read) -> anyhow::Result<Self> {
        let mut prelude_buffer = [0u8; 2 * mem::size_of::<i32>()];
        reader
            .read_exact(&mut prelude_buffer)
            .with_context(|| "Failed to read metadata prelude")?;
        let magic = u32::from_le_slice(&prelude_buffer[..4]);
        if !Self::ZSTD_MAGIC_RANGE.contains(&magic) {
            return Err(anyhow!("Invalid metadata: no zstd magic number"));
        }
        let frame_size = u32::from_le_slice(&prelude_buffer[4..]);
        debug!("magic={magic}, frame_size={frame_size}");
        if (frame_size as usize) < Self::FIXED_METADATA_LEN {
            return Err(anyhow!(
                "Frame length cannot be shorter than the fixed metadata size"
            ));
        }

        let mut metadata_buffer = vec![0u8; frame_size as usize];
        reader
            .read_exact(&mut metadata_buffer)
            .with_context(|| "Failed to read metadata")?;
        Self::decode(metadata_buffer)
    }

    fn decode(metadata_buffer: Vec<u8>) -> anyhow::Result<Self> {
        const U64_SIZE: usize = mem::size_of::<u64>();
        let mut pos = 0;
        if &metadata_buffer[pos..pos + 3] != b"DBZ" {
            return Err(anyhow!("Invalid version string"));
        }
        // Interpret 4th character as an u8, not a char to allow for 254 versions (0 omitted)
        let version = metadata_buffer[pos + 3] as u8;
        // assume not forwards compatible
        if version > SCHEMA_VERSION {
            return Err(anyhow!("Can't read newer version of DBZ"));
        }
        pos += Self::VERSION_CSTR_LEN;
        let dataset = std::str::from_utf8(&metadata_buffer[pos..pos + Self::DATASET_CSTR_LEN])
            .with_context(|| "Failed to read dataset from metadata")?
            // remove null bytes
            .trim_end_matches('\0')
            .to_owned();
        pos += Self::DATASET_CSTR_LEN;
        let schema = Schema::try_from(u16::from_le_slice(&metadata_buffer[pos..]))
            .with_context(|| format!("Failed to read schema: '{}'", metadata_buffer[pos]))?;
        pos += mem::size_of::<Schema>();
        let start = u64::from_le_slice(&metadata_buffer[pos..]);
        pos += U64_SIZE;
        let end = u64::from_le_slice(&metadata_buffer[pos..]);
        pos += U64_SIZE;
        let limit = u64::from_le_slice(&metadata_buffer[pos..]);
        pos += U64_SIZE;
        let record_count = u64::from_le_slice(&metadata_buffer[pos..]);
        pos += U64_SIZE;
        let compression = Compression::try_from(metadata_buffer[pos])
            .with_context(|| format!("Failed to parse compression '{}'", metadata_buffer[pos]))?;
        pos += mem::size_of::<Compression>();
        let stype_in = SType::try_from(metadata_buffer[pos])
            .with_context(|| format!("Failed to read stype_in: '{}'", metadata_buffer[pos]))?;
        pos += mem::size_of::<SType>();
        let stype_out = SType::try_from(metadata_buffer[pos])
            .with_context(|| format!("Failed to read stype_out: '{}'", metadata_buffer[pos]))?;
        pos += mem::size_of::<SType>();
        // skip reserved
        pos += Self::RESERVED_LEN;
        // remaining metadata is compressed
        let mut zstd_decoder = Decoder::new(&metadata_buffer[pos..])
            .with_context(|| "Failed to read zstd-zipped variable-length metadata".to_owned())?;

        // decompressed variable-length metadata buffer
        let buffer_capacity = (metadata_buffer.len() - pos) * 3; // 3x is arbitrary
        let mut var_buffer = Vec::with_capacity(buffer_capacity);
        zstd_decoder.read_to_end(&mut var_buffer)?;
        pos = 0;
        let schema_definition_length = u32::from_le_slice(&var_buffer[pos..]);
        if schema_definition_length != 0 {
            return Err(anyhow!(
                "This version of dbz can't parse schema definitions"
            ));
        }
        pos += Self::U32_SIZE + (schema_definition_length as usize);
        let symbols = Self::decode_repeated_symbol_cstr(var_buffer.as_slice(), &mut pos)
            .with_context(|| "Failed to parse symbols")?;
        let partial = Self::decode_repeated_symbol_cstr(var_buffer.as_slice(), &mut pos)
            .with_context(|| "Failed to parse partial")?;
        let not_found = Self::decode_repeated_symbol_cstr(var_buffer.as_slice(), &mut pos)
            .with_context(|| "Failed to parse not_found")?;
        let mappings = Self::decode_symbol_mappings(var_buffer.as_slice(), &mut pos)?;

        Ok(Self {
            version,
            dataset,
            schema,
            stype_in,
            stype_out,
            start,
            end,
            limit,
            compression,
            record_count,
            symbols,
            partial,
            not_found,
            mappings,
        })
    }

    fn decode_repeated_symbol_cstr(buffer: &[u8], pos: &mut usize) -> anyhow::Result<Vec<String>> {
        if *pos + Self::U32_SIZE > buffer.len() {
            return Err(anyhow!("Unexpected end of metadata buffer"));
        }
        let count = u32::from_le_slice(&buffer[*pos..]) as usize;
        *pos += Self::U32_SIZE;
        let read_size = count * Self::SYMBOL_CSTR_LEN;
        if *pos + read_size > buffer.len() {
            return Err(anyhow!("Unexpected end of metadata buffer"));
        }
        let mut res = Vec::with_capacity(count);
        for i in 0..count {
            res.push(
                Self::decode_symbol(buffer, pos)
                    .with_context(|| format!("Failed to decode symbol at index {i}"))?,
            );
        }
        Ok(res)
    }

    fn decode_symbol_mappings(
        buffer: &[u8],
        pos: &mut usize,
    ) -> anyhow::Result<Vec<SymbolMapping>> {
        if *pos + Self::U32_SIZE > buffer.len() {
            return Err(anyhow!("Unexpected end of metadata buffer"));
        }
        let count = u32::from_le_slice(&buffer[*pos..]) as usize;
        *pos += Self::U32_SIZE;
        let mut res = Vec::with_capacity(count);
        // Because each `SymbolMapping` itself is of a variable length, decoding it requires frequent bounds checks
        for i in 0..count {
            res.push(
                Self::decode_symbol_mapping(buffer, pos)
                    .with_context(|| format!("Failed to parse symbol mapping at index {i}"))?,
            );
        }
        Ok(res)
    }

    fn decode_symbol_mapping(buffer: &[u8], pos: &mut usize) -> anyhow::Result<SymbolMapping> {
        const MIN_SYMBOL_MAPPING_ENCODED_SIZE: usize =
            Metadata::SYMBOL_CSTR_LEN + Metadata::U32_SIZE;
        const MAPPING_INTERVAL_ENCODED_SIZE: usize =
            Metadata::U32_SIZE * 2 + Metadata::SYMBOL_CSTR_LEN;

        if *pos + MIN_SYMBOL_MAPPING_ENCODED_SIZE > buffer.len() {
            return Err(anyhow!(
                "Unexpected end of metadata buffer while parsing symbol mapping"
            ));
        }
        let native =
            Self::decode_symbol(buffer, pos).with_context(|| "Couldn't parse native symbol")?;
        let interval_count = u32::from_le_slice(&buffer[*pos..]) as usize;
        *pos += Self::U32_SIZE;
        let read_size = interval_count * MAPPING_INTERVAL_ENCODED_SIZE;
        if *pos + read_size > buffer.len() {
            return Err(anyhow!(
                "Symbol mapping interval_count ({interval_count}) doesn't match size of buffer \
                which only contains space for {} intervals",
                (buffer.len() - *pos) / MAPPING_INTERVAL_ENCODED_SIZE
            ));
        }
        let mut intervals = Vec::with_capacity(interval_count);
        for i in 0..interval_count {
            let raw_start_date = u32::from_le_slice(&buffer[*pos..]);
            *pos += Metadata::U32_SIZE;
            let start_date = Self::decode_iso8601(raw_start_date).with_context(|| {
                format!("Failed to parse start date of mapping interval at index {i}")
            })?;
            let raw_end_date = u32::from_le_slice(&buffer[*pos..]);
            *pos += Metadata::U32_SIZE;
            let end_date = Self::decode_iso8601(raw_end_date).with_context(|| {
                format!("Failed to parse end date of mapping interval at index {i}")
            })?;
            let symbol = Self::decode_symbol(buffer, pos).with_context(|| {
                format!("Failed to parse symbol for mapping interval at index {i}")
            })?;
            intervals.push(MappingInterval {
                start_date,
                end_date,
                symbol,
            });
        }
        Ok(SymbolMapping { native, intervals })
    }

    fn decode_symbol(buffer: &[u8], pos: &mut usize) -> anyhow::Result<String> {
        let symbol_slice = &buffer[*pos..*pos + Self::SYMBOL_CSTR_LEN];
        let symbol = std::str::from_utf8(symbol_slice)
            .with_context(|| format!("Failed to decode bytes {symbol_slice:?}"))?
            // remove null bytes
            .trim_end_matches('\0')
            .to_owned();
        *pos += Self::SYMBOL_CSTR_LEN;
        Ok(symbol)
    }

    fn decode_iso8601(raw: u32) -> anyhow::Result<time::Date> {
        let year = raw / 10_000;
        let remaining = raw % 10_000;
        let raw_month = remaining / 100;
        let month = u8::try_from(raw_month)
            .map_err(|e| anyhow!(e))
            .and_then(|m| time::Month::try_from(m).map_err(|e| anyhow!(e)))
            .with_context(|| {
                format!("Invalid month {raw_month} while parsing {raw} into a date")
            })?;
        let day = remaining % 100;
        time::Date::from_calendar_date(year as i32, month, day as u8)
            .with_context(|| format!("Couldn't convert {raw} to a valid date"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use databento_defs::record::{Mbp10Msg, Mbp1Msg, OhlcvMsg, TbboMsg, TickMsg, TradeMsg};

    const DBZ_PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/data");

    /// there are crates like rstest that provide pytest-like parameterized tests, however
    /// they don't support passing types
    macro_rules! test_reading_dbz {
        // Rust doesn't allow concatenating identifiers in stable rust, so each test case needs
        // to be named explicitly
        ($test_name:ident, $record_type:ident, $schema:expr) => {
            #[test]
            fn $test_name() {
                let target =
                    Dbz::from_file(format!("{DBZ_PATH}/test_data.{}.dbz", $schema.as_str()))
                        .unwrap();
                let exp_row_count = target.metadata().record_count;
                assert_eq!(target.schema(), $schema);
                let actual_row_count = target.try_into_iter::<$record_type>().unwrap().count();
                assert_eq!(exp_row_count as usize, actual_row_count);
            }
        };
    }

    test_reading_dbz!(test_reading_mbo, TickMsg, Schema::Mbo);
    test_reading_dbz!(test_reading_mbp1, Mbp1Msg, Schema::Mbp1);
    test_reading_dbz!(test_reading_mbp10, Mbp10Msg, Schema::Mbp10);
    test_reading_dbz!(test_reading_ohlcv1d, OhlcvMsg, Schema::Ohlcv1D);
    test_reading_dbz!(test_reading_ohlcv1h, OhlcvMsg, Schema::Ohlcv1H);
    test_reading_dbz!(test_reading_ohlcv1m, OhlcvMsg, Schema::Ohlcv1M);
    test_reading_dbz!(test_reading_ohlcv1s, OhlcvMsg, Schema::Ohlcv1S);
    test_reading_dbz!(test_reading_tbbo, TbboMsg, Schema::Tbbo);
    test_reading_dbz!(test_reading_trades, TradeMsg, Schema::Trades);

    #[test]
    fn test_decode_symbol() {
        let bytes = b"SPX.1.2\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
        assert_eq!(bytes.len(), Metadata::SYMBOL_CSTR_LEN);
        let mut pos = 0;
        let res = Metadata::decode_symbol(bytes.as_slice(), &mut pos).unwrap();
        assert_eq!(pos, Metadata::SYMBOL_CSTR_LEN);
        assert_eq!(&res, "SPX.1.2");
    }

    #[test]
    fn test_decode_symbol_invalid_utf8() {
        const BYTES: [u8; 22] = [
            // continuation byte
            0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        ];
        let mut pos = 0;
        let res = Metadata::decode_symbol(BYTES.as_slice(), &mut pos);
        assert!(matches!(res, Err(e) if e.to_string().contains("Failed to decode bytes [")));
    }

    #[test]
    fn test_decode_iso8601_valid() {
        let res = Metadata::decode_iso8601(20151031).unwrap();
        let exp: time::Date =
            time::Date::from_calendar_date(2015, time::Month::October, 31).unwrap();
        assert_eq!(res, exp);
    }

    #[test]
    fn test_decode_iso8601_invalid_month() {
        let res = Metadata::decode_iso8601(20101305);
        assert!(matches!(res, Err(e) if e.to_string().contains("Invalid month")));
    }

    #[test]
    fn test_decode_iso8601_invalid_day() {
        let res = Metadata::decode_iso8601(20100600);
        assert!(matches!(res, Err(e) if e.to_string().contains("a valid date")));
    }
}