sip2/
util.rs

1//! SIP utility functions
2use super::error;
3use super::spec;
4use chrono::{DateTime, FixedOffset, Local};
5use log::error;
6
7/// Clean up a string for inclusion in a SIP message
8///
9/// ```
10/// use sip2::util;
11/// let result = util::sip_string("howdy|par|dner");
12/// assert_eq!(result, "howdypardner");
13/// ```
14///
15pub fn sip_string(text: &str) -> String {
16    text.replace('|', "")
17}
18
19/// Current date + time in SIP format
20pub fn sip_date_now() -> String {
21    Local::now().format(spec::SIP_DATE_FORMAT).to_string()
22}
23
24/// Translate an iso8601-ish to SIP format
25///
26/// NOTE: Evergreen/Postgres dates are not parseable here, because
27/// PG does not use colons in its timezone offsets.  You have to
28/// use something like this instead:
29/// DateTime::parse_from_str(pg_iso_date, "%Y-%m-%dT%H:%M:%S%z")
30///
31/// ```
32/// use sip2::util;
33///
34/// let date_op = util::sip_date("1996-12-19T16:39:57-08:00");
35/// assert_eq!(date_op.is_ok(), true);
36///
37/// let result = date_op.unwrap();
38/// assert_eq!(result, "19961219    163957");
39///
40/// let date_op2 = util::sip_date("YARP!");
41/// assert_eq!(date_op2.is_err(), true);
42/// ```
43pub fn sip_date(iso_date: &str) -> Result<String, error::Error> {
44    match DateTime::parse_from_rfc3339(iso_date) {
45        Ok(dt) => Ok(dt.format(spec::SIP_DATE_FORMAT).to_string()),
46        Err(s) => {
47            error!("Error parsing sip date: {} : {}", iso_date, s);
48            Err(error::Error::DateFormatError)
49        }
50    }
51}
52
53/// Same as sip_date(), but starting from a DateTime object.
54pub fn sip_date_from_dt(dt: &DateTime<FixedOffset>) -> String {
55    dt.format(spec::SIP_DATE_FORMAT).to_string()
56}
57
58/// Returns "Y" on true, " " on false.
59pub fn space_bool(value: bool) -> &'static str {
60    match value {
61        true => "Y",
62        false => " ",
63    }
64}
65
66/// Return "Y" on true and "N" on false
67pub fn sip_bool(value: bool) -> &'static str {
68    match value {
69        true => "Y",
70        false => "N",
71    }
72}
73
74/// Returns "1" for true and "0" for false
75pub fn num_bool(value: bool) -> &'static str {
76    match value {
77        true => "1",
78        false => "0",
79    }
80}
81
82/// Stringify a number left padded with zeros to 4 spaces.
83pub fn sip_count4(value: usize) -> String {
84    format!("{value:0>4}")
85}