hl7-parser 0.3.0

Parses the structure of HL7v2 messages, but does not validate the correctness of the messages.
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
//! All implementations here are implemented as `TryFrom` and `From` traits
//! between the `TimeStamp` struct and various `chrono` types. This allows for
//! easy conversion between the two types. The `TryFrom` implementations will
//! return an error if the conversion is not possible, such as if the date or
//! time components are invalid. The `From` implementations will always succeed
//! and will set missing components to zero or the epoch if necessary.
//!
//! View the `TimeStamp` struct's documentation for more information on exactly
//! which traits are implemented.
//!
//! # Examples
//!
//! ```
//! use hl7_parser::datetime::{TimeStamp, TimeStampOffset};
//! use chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, Utc, Datelike, Timelike};
//!
//! let ts = TimeStamp {
//!    year: 2023,
//!    month: Some(3),
//!    day: Some(12),
//!    hour: Some(19),
//!    minute: Some(59),
//!    second: Some(5),
//!    microsecond: Some(1234),
//!    offset: Some(TimeStampOffset {
//!        hours: -7,
//!        minutes: 0,
//!    })
//! };
//!
//! let datetime: DateTime<FixedOffset> = ts.try_into().unwrap();
//! assert_eq!(datetime.year(), 2023);
//! assert_eq!(datetime.month(), 3);
//! assert_eq!(datetime.day(), 12);
//! assert_eq!(datetime.hour(), 19);
//! assert_eq!(datetime.minute(), 59);
//! assert_eq!(datetime.second(), 5);
//! assert_eq!(datetime.nanosecond(), 1234 * 1000);
//! assert_eq!(datetime.offset().local_minus_utc() / 3600, -7);
//! assert_eq!(datetime.offset().local_minus_utc() % 3600, 0);
//! ```
//!
//! ```
//! use hl7_parser::datetime::{TimeStamp, TimeStampOffset};
//! use chrono::{DateTime, Utc, NaiveDate, TimeZone};
//!
//! let datetime = Utc.from_utc_datetime(
//!     &NaiveDate::from_ymd_opt(2023, 3, 12).unwrap()
//!     .and_hms_opt(19, 59, 5).unwrap(),
//! );
//!
//! let ts: TimeStamp = datetime.into();
//! assert_eq!(ts.year, 2023);
//! assert_eq!(ts.month, Some(3));
//! assert_eq!(ts.day, Some(12));
//! assert_eq!(ts.hour, Some(19));
//! assert_eq!(ts.minute, Some(59));
//! assert_eq!(ts.second, Some(5));
//! assert_eq!(ts.microsecond, Some(0));
//! assert_eq!(ts.offset, Some(TimeStampOffset {
//!    hours: 0,
//!    minutes: 0,
//! }));
//! ```

use super::{Date, DateTimeParseError, ErroredDateTimeComponent, Time, TimeStamp, TimeStampOffset};
use chrono::{
    offset::LocalResult, DateTime, Datelike, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime,
    TimeZone, Timelike,
};

/// Attempt to convert a `TimeStamp` into a `NaiveDate`. If the `TimeStamp` is
/// missing date components, those components will be set to `1`.
impl TryFrom<TimeStamp> for NaiveDate {
    type Error = DateTimeParseError;

    fn try_from(value: TimeStamp) -> Result<Self, Self::Error> {
        let TimeStamp {
            year, month, day, ..
        } = value;

        let month = month.unwrap_or(1);
        let day = day.unwrap_or(1);

        let date = NaiveDate::from_ymd_opt(year as i32, month as u32, day as u32).ok_or(
            DateTimeParseError::InvalidComponentRange(ErroredDateTimeComponent::Date),
        )?;
        Ok(date)
    }
}

/// Attempt to convert a `Date` into a `NaiveDate`. If the `Date` is missing
/// date components, those components will be set to `1`.
impl TryFrom<Date> for NaiveDate {
    type Error = DateTimeParseError;

    fn try_from(value: Date) -> Result<Self, Self::Error> {
        let Date { year, month, day } = value;

        let month = month.unwrap_or(1);
        let day = day.unwrap_or(1);

        let date = NaiveDate::from_ymd_opt(year as i32, month as u32, day as u32).ok_or(
            DateTimeParseError::InvalidComponentRange(ErroredDateTimeComponent::Date),
        )?;
        Ok(date)
    }
}

/// Attempt to convert a `TimeStamp` into a `NaiveTime`. If the `TimeStamp` is
/// missing time components, those components will be set to zero.
impl TryFrom<Time> for NaiveTime {
    type Error = DateTimeParseError;

    fn try_from(value: Time) -> Result<Self, Self::Error> {
        let Time {
            hour,
            minute,
            second,
            microsecond,
            ..
        } = value;

        let minute = minute.unwrap_or(0);
        let second = second.unwrap_or(0);
        let microsecond = microsecond.unwrap_or(0);

        let time =
            NaiveTime::from_hms_micro_opt(hour as u32, minute as u32, second as u32, microsecond)
                .ok_or(DateTimeParseError::InvalidComponentRange(
                ErroredDateTimeComponent::Time,
            ))?;
        Ok(time)
    }
}

/// Convert a `NaiveDate` into a `TimeStamp`. The `TimeStamp` will have the
/// date components set to the `NaiveDate`'s components and the time components
/// set to `None`.
impl From<NaiveDate> for TimeStamp {
    fn from(value: NaiveDate) -> Self {
        let year = value.year() as u16;
        let month = Some(value.month() as u8);
        let day = Some(value.day() as u8);
        let hour = None;
        let minute = None;
        let second = None;
        let microsecond = None;
        let offset = None;
        TimeStamp {
            year,
            month,
            day,
            hour,
            minute,
            second,
            microsecond,
            offset,
        }
    }
}

/// Convert a `NaiveDate` into a `Date`. The `Date` will have the date
/// components set to the `NaiveDate`'s components
impl From<NaiveDate> for Date {
    fn from(value: NaiveDate) -> Self {
        let year = value.year() as u16;
        let month = Some(value.month() as u8);
        let day = Some(value.day() as u8);
        Date { year, month, day }
    }
}

/// Convert a `NaiveTime` into a `Time`. The `Time` will have the time components
/// set to the `NaiveTime`'s components and the offset components set to `None`.
impl From<NaiveTime> for Time {
    fn from(value: NaiveTime) -> Self {
        let hour = value.hour() as u8;
        let minute = Some(value.minute() as u8);
        let second = Some(value.second() as u8);
        let microsecond = Some(value.nanosecond() / 1000);
        Time {
            hour,
            minute,
            second,
            microsecond,
            offset: None,
        }
    }
}

/// Attempt to convert a `TimeStamp` into a `NaiveDateTime`. If the `TimeStamp`
/// is missing time components, those components will be set to zero.
impl TryFrom<TimeStamp> for NaiveDateTime {
    type Error = DateTimeParseError;

    fn try_from(value: TimeStamp) -> Result<Self, Self::Error> {
        let date = NaiveDate::try_from(value)?;
        let time = NaiveTime::from_hms_micro_opt(
            value.hour.unwrap_or(0) as u32,
            value.minute.unwrap_or(0) as u32,
            value.second.unwrap_or(0) as u32,
            value.microsecond.unwrap_or(0),
        )
        .ok_or(DateTimeParseError::InvalidComponentRange(
            ErroredDateTimeComponent::Time,
        ))?;
        Ok(NaiveDateTime::new(date, time))
    }
}

/// Convert a `NaiveDateTime` into a `TimeStamp`. The `TimeStamp` will have the
/// date and time components set to the `NaiveDateTime`'s components and the
/// offset components set to `None`.
impl From<NaiveDateTime> for TimeStamp {
    fn from(value: NaiveDateTime) -> Self {
        let year = value.year() as u16;
        let month = Some(value.month() as u8);
        let day = Some(value.day() as u8);
        let hour = Some(value.hour() as u8);
        let minute = Some(value.minute() as u8);
        let second = Some(value.second() as u8);
        let microsecond = Some(value.nanosecond() / 1000);
        let offset = None;
        TimeStamp {
            year,
            month,
            day,
            hour,
            minute,
            second,
            microsecond,
            offset,
        }
    }
}

/// Attempt to convert a `TimeStamp` into a `DateTime<FixedOffset>`. If the
/// `TimeStamp` is missing date components, those components will be set to `1`.
/// If the `TimeStamp` is missing time components, those components will be set
/// to zero. If the `TimeStamp` is missing offset components, those components
/// will be set to zero.
impl TryFrom<TimeStamp> for LocalResult<DateTime<FixedOffset>> {
    type Error = DateTimeParseError;

    fn try_from(value: TimeStamp) -> Result<Self, Self::Error> {
        let TimeStamp {
            year,
            month,
            day,
            hour,
            minute,
            second,
            microsecond,
            offset,
        } = value;

        let month = month.unwrap_or(1);
        let day = day.unwrap_or(1);
        let date = NaiveDate::from_ymd_opt(year as i32, month as u32, day as u32).ok_or(
            DateTimeParseError::InvalidComponentRange(ErroredDateTimeComponent::Date),
        )?;

        let hour = hour.unwrap_or(0);
        let minute = minute.unwrap_or(0);
        let second = second.unwrap_or(0);
        let microsecond = microsecond.unwrap_or(0);

        let time =
            NaiveTime::from_hms_micro_opt(hour as u32, minute as u32, second as u32, microsecond)
                .ok_or(DateTimeParseError::InvalidComponentRange(
                ErroredDateTimeComponent::Time,
            ))?;

        let offset = offset.unwrap_or_default();
        let offset_hours = offset.hours as i32;
        let offset_minutes = offset.minutes as i32;
        let offset = FixedOffset::east_opt(offset_hours * 3600 + offset_minutes * 60).ok_or(
            DateTimeParseError::InvalidComponentRange(ErroredDateTimeComponent::Offset),
        )?;

        let datetime = NaiveDateTime::new(date, time);
        let datetime = datetime.and_local_timezone(offset);
        Ok(datetime)
    }
}

/// Attempt to convert a `TimeStamp` into a `DateTime<Tz>`. If the `TimeStamp` is
/// missing date components, those components will be set to `1`. If the
/// `TimeStamp` is missing time components, those components will be set to zero.
/// If the `TimeStamp` is missing offset components, those components will be set
/// to zero.
///
/// Note that this implementation will return an error if the `TimeStamp` is
/// ambiguous or does not exist.
impl<Tz> TryFrom<TimeStamp> for DateTime<Tz>
where
    Tz: TimeZone,
    DateTime<Tz>: From<DateTime<FixedOffset>>,
{
    type Error = DateTimeParseError;

    fn try_from(value: TimeStamp) -> Result<Self, Self::Error> {
        let datetime: LocalResult<DateTime<FixedOffset>> = LocalResult::try_from(value)?;
        match datetime {
            LocalResult::Single(datetime) => Ok(datetime.into()),
            LocalResult::Ambiguous(earliest, latest) => Err(DateTimeParseError::AmbiguousTime(
                earliest.to_rfc3339(),
                latest.to_rfc3339(),
            )),
            LocalResult::None => Err(DateTimeParseError::InvalidComponentRange(
                ErroredDateTimeComponent::DateTime,
            )),
        }
    }
}

/// Convert a `DateTime` into a `TimeStamp`. The `TimeStamp` will have the date
/// and time components set to the `DateTime`'s components and the offset
/// components set to the `DateTime`'s offset components.
impl<Tz> From<DateTime<Tz>> for TimeStamp
where
    Tz: TimeZone,
    DateTime<Tz>: Into<DateTime<FixedOffset>>,
{
    fn from(value: DateTime<Tz>) -> Self {
        let datetime: DateTime<FixedOffset> = value.into();

        let year = datetime.year() as u16;
        let month = Some(datetime.month() as u8);
        let day = Some(datetime.day() as u8);
        let hour = Some(datetime.hour() as u8);
        let minute = Some(datetime.minute() as u8);
        let second = Some(datetime.second() as u8);
        let microsecond = Some(datetime.nanosecond() / 1000);
        let offset = Some(TimeStampOffset {
            hours: (datetime.offset().local_minus_utc() / 3600) as i8,
            minutes: (datetime.offset().local_minus_utc() % 3600) as u8,
        });

        TimeStamp {
            year,
            month,
            day,
            hour,
            minute,
            second,
            microsecond,
            offset,
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::datetime::TimeStampOffset;
    use chrono::{Timelike, Utc};

    use super::*;

    #[test]
    fn can_convert_timestamp_to_date() {
        let ts = TimeStamp {
            year: 2023,
            month: Some(3),
            day: Some(12),
            hour: Some(19),
            minute: Some(59),
            second: None,
            microsecond: None,
            offset: None,
        };
        let actual = NaiveDate::try_from(ts).unwrap();
        assert_eq!(actual.year(), 2023);
        assert_eq!(actual.month(), 3);
        assert_eq!(actual.day(), 12);
    }

    #[test]
    fn can_convert_timestamp_to_datetime_with_fixed_offset() {
        let ts = TimeStamp {
            year: 2023,
            month: Some(3),
            day: Some(12),
            hour: Some(19),
            minute: Some(59),
            second: Some(5),
            microsecond: Some(1234),
            offset: Some(TimeStampOffset {
                hours: -7,
                minutes: 0,
            }),
        };
        let actual = DateTime::<FixedOffset>::try_from(ts).unwrap();
        assert_eq!(actual.year(), 2023);
        assert_eq!(actual.month(), 3);
        assert_eq!(actual.day(), 12);
        assert_eq!(actual.hour(), 19);
        assert_eq!(actual.minute(), 59);
        assert_eq!(actual.second(), 5);
        assert_eq!(actual.nanosecond(), 1234 * 1000);
        assert_eq!(actual.offset().local_minus_utc() / 3600, -7);
        assert_eq!(actual.offset().local_minus_utc() % 3600, 0);
    }

    #[test]
    fn can_convert_timestamp_datetime_with_utc_offset() {
        let ts = TimeStamp {
            year: 2023,
            month: Some(3),
            day: Some(12),
            hour: Some(19),
            minute: Some(59),
            second: Some(5),
            microsecond: Some(1234),
            offset: Some(TimeStampOffset {
                hours: -7,
                minutes: 0,
            }),
        };
        let actual = DateTime::<Utc>::try_from(ts).unwrap();

        assert_eq!(actual.year(), 2023);
        assert_eq!(actual.month(), 3);
        assert_eq!(actual.day(), 13);
        assert_eq!(actual.hour(), 2);
        assert_eq!(actual.minute(), 59);
        assert_eq!(actual.second(), 5);
        assert_eq!(actual.nanosecond(), 1234 * 1000);
    }

    #[test]
    fn can_convert_datetime_to_timestamp() {
        let datetime = Utc.from_utc_datetime(
            &NaiveDate::from_ymd_opt(2023, 3, 12)
                .unwrap()
                .and_hms_opt(19, 59, 5)
                .unwrap(),
        );
        let actual = TimeStamp::from(datetime);
        assert_eq!(actual.year, 2023);
        assert_eq!(actual.month, Some(3));
        assert_eq!(actual.day, Some(12));
        assert_eq!(actual.hour, Some(19));
        assert_eq!(actual.minute, Some(59));
        assert_eq!(actual.second, Some(5));
        assert_eq!(actual.microsecond, Some(0));
        assert_eq!(
            actual.offset,
            Some(TimeStampOffset {
                hours: 0,
                minutes: 0
            })
        );
    }
}