azure_core/
parsing.rs
1use crate::date;
4use crate::error::{Error, ErrorKind, ResultExt};
5
6pub trait FromStringOptional<T> {
7 fn from_str_optional(s: &str) -> crate::Result<T>;
8}
9
10impl FromStringOptional<u64> for u64 {
11 fn from_str_optional(s: &str) -> crate::Result<u64> {
12 s.parse::<u64>().map_kind(ErrorKind::DataConversion)
13 }
14}
15
16impl FromStringOptional<String> for String {
17 fn from_str_optional(s: &str) -> crate::Result<String> {
18 Ok(s.to_owned())
19 }
20}
21
22impl FromStringOptional<bool> for bool {
23 fn from_str_optional(s: &str) -> crate::Result<bool> {
24 match s {
25 "true" => Ok(true),
26 "false" => Ok(false),
27 _ => Err(Error::with_message(ErrorKind::DataConversion, || {
28 "error parsing bool '{s}'"
29 })),
30 }
31 }
32}
33
34impl FromStringOptional<time::OffsetDateTime> for time::OffsetDateTime {
35 fn from_str_optional(s: &str) -> crate::Result<time::OffsetDateTime> {
36 from_azure_time(s).with_context(ErrorKind::DataConversion, || {
37 format!("error parsing date time '{s}'")
38 })
39 }
40}
41
42#[cfg(not(feature = "azurite_workaround"))]
43pub fn from_azure_time(s: &str) -> crate::Result<time::OffsetDateTime> {
44 date::parse_rfc1123(s)
45}
46
47#[cfg(feature = "azurite_workaround")]
48pub fn from_azure_time(s: &str) -> crate::Result<time::OffsetDateTime> {
49 if let Ok(dt) = date::parse_rfc1123(s) {
50 Ok(dt)
51 } else {
52 tracing::warn!("Received an invalid date: {}, returning now()", s);
53 Ok(time::OffsetDateTime::now_utc())
54 }
55}
56
57#[cfg(test)]
58mod test {
59
60 #[test]
61 fn test_from_azure_time() {
62 let t = super::from_azure_time("Sun, 27 Sep 2009 17:26:40 GMT").unwrap();
63
64 assert_eq!(t.day(), 27);
65 assert_eq!(t.month(), time::Month::September);
66 assert_eq!(t.hour(), 17);
67 assert_eq!(t.second(), 40);
68 }
69}