2018-12-17 19:45:35 -06:00
|
|
|
use std::error;
|
2017-01-29 18:53:20 -06:00
|
|
|
use std::fmt;
|
|
|
|
use std::str::{self, FromStr};
|
|
|
|
|
|
|
|
use serde::{de, ser};
|
|
|
|
|
|
|
|
/// A parsed TOML datetime value
|
|
|
|
///
|
|
|
|
/// This structure is intended to represent the datetime primitive type that can
|
|
|
|
/// be encoded into TOML documents. This type is a parsed version that contains
|
|
|
|
/// all metadata internally.
|
|
|
|
///
|
|
|
|
/// Currently this type is intentionally conservative and only supports
|
|
|
|
/// `to_string` as an accessor. Over time though it's intended that it'll grow
|
|
|
|
/// more support!
|
|
|
|
///
|
|
|
|
/// Note that if you're using `Deserialize` to deserialize a TOML document, you
|
|
|
|
/// can use this as a placeholder for where you're expecting a datetime to be
|
|
|
|
/// specified.
|
|
|
|
///
|
|
|
|
/// Also note though that while this type implements `Serialize` and
|
|
|
|
/// `Deserialize` it's only recommended to use this type with the TOML format,
|
|
|
|
/// otherwise encoded in other formats it may look a little odd.
|
|
|
|
#[derive(PartialEq, Clone)]
|
|
|
|
pub struct Datetime {
|
|
|
|
date: Option<Date>,
|
|
|
|
time: Option<Time>,
|
|
|
|
offset: Option<Offset>,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Error returned from parsing a `Datetime` in the `FromStr` implementation.
|
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
pub struct DatetimeParseError {
|
|
|
|
_private: (),
|
|
|
|
}
|
|
|
|
|
|
|
|
// Currently serde itself doesn't have a datetime type, so we map our `Datetime`
|
|
|
|
// to a special valid in the serde data model. Namely one with thiese special
|
|
|
|
// fields/struct names.
|
|
|
|
//
|
|
|
|
// In general the TOML encoder/decoder will catch this and not literally emit
|
|
|
|
// these strings but rather emit datetimes as they're intended.
|
2019-08-14 21:52:24 -05:00
|
|
|
pub const FIELD: &str = "$__toml_private_datetime";
|
|
|
|
pub const NAME: &str = "$__toml_private_Datetime";
|
2017-01-29 18:53:20 -06:00
|
|
|
|
|
|
|
#[derive(PartialEq, Clone)]
|
|
|
|
struct Date {
|
|
|
|
year: u16,
|
|
|
|
month: u8,
|
|
|
|
day: u8,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(PartialEq, Clone)]
|
|
|
|
struct Time {
|
|
|
|
hour: u8,
|
|
|
|
minute: u8,
|
|
|
|
second: u8,
|
2017-06-01 17:22:35 -05:00
|
|
|
nanosecond: u32,
|
2017-01-29 18:53:20 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(PartialEq, Clone)]
|
|
|
|
enum Offset {
|
|
|
|
Z,
|
|
|
|
Custom { hours: i8, minutes: u8 },
|
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Debug for Datetime {
|
2019-05-08 19:37:38 -05:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2017-01-29 18:53:20 -06:00
|
|
|
fmt::Display::fmt(self, f)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Display for Datetime {
|
2019-05-08 19:37:38 -05:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2017-01-29 18:53:20 -06:00
|
|
|
if let Some(ref date) = self.date {
|
|
|
|
write!(f, "{}", date)?;
|
|
|
|
}
|
|
|
|
if let Some(ref time) = self.time {
|
|
|
|
if self.date.is_some() {
|
|
|
|
write!(f, "T")?;
|
|
|
|
}
|
|
|
|
write!(f, "{}", time)?;
|
|
|
|
}
|
|
|
|
if let Some(ref offset) = self.offset {
|
|
|
|
write!(f, "{}", offset)?;
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Display for Date {
|
2019-05-08 19:37:38 -05:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2017-01-29 18:53:20 -06:00
|
|
|
write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Display for Time {
|
2019-05-08 19:37:38 -05:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2017-01-29 18:53:20 -06:00
|
|
|
write!(f, "{:02}:{:02}:{:02}", self.hour, self.minute, self.second)?;
|
2017-06-01 17:22:35 -05:00
|
|
|
if self.nanosecond != 0 {
|
|
|
|
let s = format!("{:09}", self.nanosecond);
|
2019-04-02 10:35:28 -05:00
|
|
|
write!(f, ".{}", s.trim_end_matches('0'))?;
|
2017-01-29 18:53:20 -06:00
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Display for Offset {
|
2019-05-08 19:37:38 -05:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2017-01-29 18:53:20 -06:00
|
|
|
match *self {
|
|
|
|
Offset::Z => write!(f, "Z"),
|
2018-12-17 19:45:35 -06:00
|
|
|
Offset::Custom { hours, minutes } => write!(f, "{:+03}:{:02}", hours, minutes),
|
2017-01-29 18:53:20 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl FromStr for Datetime {
|
|
|
|
type Err = DatetimeParseError;
|
|
|
|
|
|
|
|
fn from_str(date: &str) -> Result<Datetime, DatetimeParseError> {
|
|
|
|
// Accepted formats:
|
|
|
|
//
|
|
|
|
// 0000-00-00T00:00:00.00Z
|
|
|
|
// 0000-00-00T00:00:00.00
|
|
|
|
// 0000-00-00
|
|
|
|
// 00:00:00.00
|
|
|
|
if date.len() < 3 {
|
2018-12-17 19:45:35 -06:00
|
|
|
return Err(DatetimeParseError { _private: () });
|
2017-01-29 18:53:20 -06:00
|
|
|
}
|
|
|
|
let mut offset_allowed = true;
|
|
|
|
let mut chars = date.chars();
|
|
|
|
|
|
|
|
// First up, parse the full date if we can
|
|
|
|
let full_date = if chars.clone().nth(2) == Some(':') {
|
|
|
|
offset_allowed = false;
|
|
|
|
None
|
|
|
|
} else {
|
2019-08-14 21:52:24 -05:00
|
|
|
let y1 = u16::from(digit(&mut chars)?);
|
|
|
|
let y2 = u16::from(digit(&mut chars)?);
|
|
|
|
let y3 = u16::from(digit(&mut chars)?);
|
|
|
|
let y4 = u16::from(digit(&mut chars)?);
|
2017-01-29 18:53:20 -06:00
|
|
|
|
|
|
|
match chars.next() {
|
|
|
|
Some('-') => {}
|
|
|
|
_ => return Err(DatetimeParseError { _private: () }),
|
|
|
|
}
|
|
|
|
|
|
|
|
let m1 = digit(&mut chars)?;
|
|
|
|
let m2 = digit(&mut chars)?;
|
|
|
|
|
|
|
|
match chars.next() {
|
|
|
|
Some('-') => {}
|
|
|
|
_ => return Err(DatetimeParseError { _private: () }),
|
|
|
|
}
|
|
|
|
|
|
|
|
let d1 = digit(&mut chars)?;
|
|
|
|
let d2 = digit(&mut chars)?;
|
|
|
|
|
|
|
|
let date = Date {
|
|
|
|
year: y1 * 1000 + y2 * 100 + y3 * 10 + y4,
|
|
|
|
month: m1 * 10 + m2,
|
|
|
|
day: d1 * 10 + d2,
|
|
|
|
};
|
|
|
|
|
|
|
|
if date.month < 1 || date.month > 12 {
|
2018-12-17 19:45:35 -06:00
|
|
|
return Err(DatetimeParseError { _private: () });
|
2017-01-29 18:53:20 -06:00
|
|
|
}
|
|
|
|
if date.day < 1 || date.day > 31 {
|
2018-12-17 19:45:35 -06:00
|
|
|
return Err(DatetimeParseError { _private: () });
|
2017-01-29 18:53:20 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
Some(date)
|
|
|
|
};
|
|
|
|
|
|
|
|
// Next parse the "partial-time" if available
|
2019-02-19 12:59:42 -06:00
|
|
|
let next = chars.clone().next();
|
2018-12-17 19:45:35 -06:00
|
|
|
let partial_time = if full_date.is_some()
|
2019-02-19 12:59:42 -06:00
|
|
|
&& (next == Some('T') || next == Some('t') || next == Some(' '))
|
2018-12-17 19:45:35 -06:00
|
|
|
{
|
2017-01-29 18:53:20 -06:00
|
|
|
chars.next();
|
|
|
|
true
|
|
|
|
} else {
|
2017-03-30 06:40:27 -05:00
|
|
|
full_date.is_none()
|
2017-01-29 18:53:20 -06:00
|
|
|
};
|
2017-03-30 06:40:27 -05:00
|
|
|
|
2017-01-29 18:53:20 -06:00
|
|
|
let time = if partial_time {
|
|
|
|
let h1 = digit(&mut chars)?;
|
|
|
|
let h2 = digit(&mut chars)?;
|
|
|
|
match chars.next() {
|
|
|
|
Some(':') => {}
|
|
|
|
_ => return Err(DatetimeParseError { _private: () }),
|
|
|
|
}
|
|
|
|
let m1 = digit(&mut chars)?;
|
|
|
|
let m2 = digit(&mut chars)?;
|
|
|
|
match chars.next() {
|
|
|
|
Some(':') => {}
|
|
|
|
_ => return Err(DatetimeParseError { _private: () }),
|
|
|
|
}
|
|
|
|
let s1 = digit(&mut chars)?;
|
|
|
|
let s2 = digit(&mut chars)?;
|
|
|
|
|
2017-06-01 17:22:35 -05:00
|
|
|
let mut nanosecond = 0;
|
|
|
|
if chars.clone().next() == Some('.') {
|
2017-01-29 18:53:20 -06:00
|
|
|
chars.next();
|
|
|
|
let whole = chars.as_str();
|
2017-06-01 17:22:35 -05:00
|
|
|
|
2017-01-29 18:53:20 -06:00
|
|
|
let mut end = whole.len();
|
2017-06-01 17:22:35 -05:00
|
|
|
for (i, byte) in whole.bytes().enumerate() {
|
|
|
|
match byte {
|
2019-05-08 19:37:38 -05:00
|
|
|
b'0'..=b'9' => {
|
2017-06-01 17:22:35 -05:00
|
|
|
if i < 9 {
|
|
|
|
let p = 10_u32.pow(8 - i as u32);
|
2019-08-14 21:52:24 -05:00
|
|
|
nanosecond += p * u32::from(byte - b'0');
|
2017-06-01 17:22:35 -05:00
|
|
|
}
|
|
|
|
}
|
2017-01-29 18:53:20 -06:00
|
|
|
_ => {
|
|
|
|
end = i;
|
2017-06-01 17:22:35 -05:00
|
|
|
break;
|
2017-01-29 18:53:20 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-06-01 17:22:35 -05:00
|
|
|
if end == 0 {
|
2018-12-17 19:45:35 -06:00
|
|
|
return Err(DatetimeParseError { _private: () });
|
2017-01-29 18:53:20 -06:00
|
|
|
}
|
|
|
|
chars = whole[end..].chars();
|
2017-06-01 17:22:35 -05:00
|
|
|
}
|
2017-01-29 18:53:20 -06:00
|
|
|
|
|
|
|
let time = Time {
|
|
|
|
hour: h1 * 10 + h2,
|
|
|
|
minute: m1 * 10 + m2,
|
|
|
|
second: s1 * 10 + s2,
|
2019-08-14 21:52:24 -05:00
|
|
|
nanosecond,
|
2017-01-29 18:53:20 -06:00
|
|
|
};
|
|
|
|
|
|
|
|
if time.hour > 24 {
|
2018-12-17 19:45:35 -06:00
|
|
|
return Err(DatetimeParseError { _private: () });
|
2017-01-29 18:53:20 -06:00
|
|
|
}
|
|
|
|
if time.minute > 59 {
|
2018-12-17 19:45:35 -06:00
|
|
|
return Err(DatetimeParseError { _private: () });
|
2017-01-29 18:53:20 -06:00
|
|
|
}
|
2017-06-01 17:22:35 -05:00
|
|
|
if time.second > 59 {
|
2018-12-17 19:45:35 -06:00
|
|
|
return Err(DatetimeParseError { _private: () });
|
2017-06-01 17:22:35 -05:00
|
|
|
}
|
|
|
|
if time.nanosecond > 999_999_999 {
|
2018-12-17 19:45:35 -06:00
|
|
|
return Err(DatetimeParseError { _private: () });
|
2017-01-29 18:53:20 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
Some(time)
|
|
|
|
} else {
|
|
|
|
offset_allowed = false;
|
|
|
|
None
|
|
|
|
};
|
|
|
|
|
|
|
|
// And finally, parse the offset
|
|
|
|
let offset = if offset_allowed {
|
|
|
|
let next = chars.clone().next();
|
2019-02-19 12:59:42 -06:00
|
|
|
if next == Some('Z') || next == Some('z') {
|
2017-01-29 18:53:20 -06:00
|
|
|
chars.next();
|
|
|
|
Some(Offset::Z)
|
|
|
|
} else if next.is_none() {
|
|
|
|
None
|
|
|
|
} else {
|
|
|
|
let sign = match next {
|
|
|
|
Some('+') => 1,
|
|
|
|
Some('-') => -1,
|
|
|
|
_ => return Err(DatetimeParseError { _private: () }),
|
|
|
|
};
|
|
|
|
chars.next();
|
|
|
|
let h1 = digit(&mut chars)? as i8;
|
|
|
|
let h2 = digit(&mut chars)? as i8;
|
|
|
|
match chars.next() {
|
|
|
|
Some(':') => {}
|
|
|
|
_ => return Err(DatetimeParseError { _private: () }),
|
|
|
|
}
|
|
|
|
let m1 = digit(&mut chars)?;
|
|
|
|
let m2 = digit(&mut chars)?;
|
|
|
|
|
|
|
|
Some(Offset::Custom {
|
|
|
|
hours: sign * (h1 * 10 + h2),
|
|
|
|
minutes: m1 * 10 + m2,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
|
|
|
|
// Return an error if we didn't hit eof, otherwise return our parsed
|
|
|
|
// date
|
|
|
|
if chars.next().is_some() {
|
2018-12-17 19:45:35 -06:00
|
|
|
return Err(DatetimeParseError { _private: () });
|
2017-01-29 18:53:20 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok(Datetime {
|
|
|
|
date: full_date,
|
2019-08-14 21:52:24 -05:00
|
|
|
time,
|
|
|
|
offset,
|
2017-01-29 18:53:20 -06:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-08 19:37:38 -05:00
|
|
|
fn digit(chars: &mut str::Chars<'_>) -> Result<u8, DatetimeParseError> {
|
2017-01-29 18:53:20 -06:00
|
|
|
match chars.next() {
|
2017-03-30 06:40:27 -05:00
|
|
|
Some(c) if '0' <= c && c <= '9' => Ok(c as u8 - b'0'),
|
2017-01-29 18:53:20 -06:00
|
|
|
_ => Err(DatetimeParseError { _private: () }),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ser::Serialize for Datetime {
|
|
|
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
2018-12-17 19:45:35 -06:00
|
|
|
where
|
|
|
|
S: ser::Serializer,
|
2017-01-29 18:53:20 -06:00
|
|
|
{
|
|
|
|
use serde::ser::SerializeStruct;
|
|
|
|
|
2018-05-06 20:47:09 -05:00
|
|
|
let mut s = serializer.serialize_struct(NAME, 1)?;
|
|
|
|
s.serialize_field(FIELD, &self.to_string())?;
|
2017-01-29 18:53:20 -06:00
|
|
|
s.end()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-04-20 12:16:00 -05:00
|
|
|
impl<'de> de::Deserialize<'de> for Datetime {
|
2017-01-29 18:53:20 -06:00
|
|
|
fn deserialize<D>(deserializer: D) -> Result<Datetime, D::Error>
|
2018-12-17 19:45:35 -06:00
|
|
|
where
|
|
|
|
D: de::Deserializer<'de>,
|
2017-01-29 18:53:20 -06:00
|
|
|
{
|
|
|
|
struct DatetimeVisitor;
|
|
|
|
|
2017-04-20 12:16:00 -05:00
|
|
|
impl<'de> de::Visitor<'de> for DatetimeVisitor {
|
2017-01-29 18:53:20 -06:00
|
|
|
type Value = Datetime;
|
|
|
|
|
2019-05-08 19:37:38 -05:00
|
|
|
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2017-01-29 18:53:20 -06:00
|
|
|
formatter.write_str("a TOML datetime")
|
|
|
|
}
|
|
|
|
|
|
|
|
fn visit_map<V>(self, mut visitor: V) -> Result<Datetime, V::Error>
|
2018-12-17 19:45:35 -06:00
|
|
|
where
|
|
|
|
V: de::MapAccess<'de>,
|
2017-01-29 18:53:20 -06:00
|
|
|
{
|
2017-04-20 12:16:00 -05:00
|
|
|
let value = visitor.next_key::<DatetimeKey>()?;
|
2017-01-29 18:53:20 -06:00
|
|
|
if value.is_none() {
|
2018-12-17 19:45:35 -06:00
|
|
|
return Err(de::Error::custom("datetime key not found"));
|
2017-01-29 18:53:20 -06:00
|
|
|
}
|
2017-04-20 12:16:00 -05:00
|
|
|
let v: DatetimeFromString = visitor.next_value()?;
|
2017-01-29 18:53:20 -06:00
|
|
|
Ok(v.value)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-14 21:52:24 -05:00
|
|
|
static FIELDS: [&str; 1] = [FIELD];
|
2018-05-06 20:47:09 -05:00
|
|
|
deserializer.deserialize_struct(NAME, &FIELDS, DatetimeVisitor)
|
2017-01-29 18:53:20 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
struct DatetimeKey;
|
|
|
|
|
2017-04-20 12:16:00 -05:00
|
|
|
impl<'de> de::Deserialize<'de> for DatetimeKey {
|
2017-01-29 18:53:20 -06:00
|
|
|
fn deserialize<D>(deserializer: D) -> Result<DatetimeKey, D::Error>
|
2018-12-17 19:45:35 -06:00
|
|
|
where
|
|
|
|
D: de::Deserializer<'de>,
|
2017-01-29 18:53:20 -06:00
|
|
|
{
|
|
|
|
struct FieldVisitor;
|
|
|
|
|
2017-04-20 12:16:00 -05:00
|
|
|
impl<'de> de::Visitor<'de> for FieldVisitor {
|
2017-01-29 18:53:20 -06:00
|
|
|
type Value = ();
|
|
|
|
|
2019-05-08 19:37:38 -05:00
|
|
|
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2017-01-29 18:53:20 -06:00
|
|
|
formatter.write_str("a valid datetime field")
|
|
|
|
}
|
|
|
|
|
|
|
|
fn visit_str<E>(self, s: &str) -> Result<(), E>
|
2018-12-17 19:45:35 -06:00
|
|
|
where
|
|
|
|
E: de::Error,
|
2017-01-29 18:53:20 -06:00
|
|
|
{
|
2018-05-06 20:47:09 -05:00
|
|
|
if s == FIELD {
|
2017-01-29 18:53:20 -06:00
|
|
|
Ok(())
|
|
|
|
} else {
|
|
|
|
Err(de::Error::custom("expected field with custom name"))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-04-20 12:16:00 -05:00
|
|
|
deserializer.deserialize_identifier(FieldVisitor)?;
|
2017-01-29 18:53:20 -06:00
|
|
|
Ok(DatetimeKey)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct DatetimeFromString {
|
|
|
|
pub value: Datetime,
|
|
|
|
}
|
|
|
|
|
2017-04-20 12:16:00 -05:00
|
|
|
impl<'de> de::Deserialize<'de> for DatetimeFromString {
|
2017-01-29 18:53:20 -06:00
|
|
|
fn deserialize<D>(deserializer: D) -> Result<DatetimeFromString, D::Error>
|
2018-12-17 19:45:35 -06:00
|
|
|
where
|
|
|
|
D: de::Deserializer<'de>,
|
2017-01-29 18:53:20 -06:00
|
|
|
{
|
|
|
|
struct Visitor;
|
|
|
|
|
2017-04-20 12:16:00 -05:00
|
|
|
impl<'de> de::Visitor<'de> for Visitor {
|
2017-01-29 18:53:20 -06:00
|
|
|
type Value = DatetimeFromString;
|
|
|
|
|
2019-05-08 19:37:38 -05:00
|
|
|
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2017-01-29 18:53:20 -06:00
|
|
|
formatter.write_str("string containing a datetime")
|
|
|
|
}
|
|
|
|
|
|
|
|
fn visit_str<E>(self, s: &str) -> Result<DatetimeFromString, E>
|
2018-12-17 19:45:35 -06:00
|
|
|
where
|
|
|
|
E: de::Error,
|
2017-01-29 18:53:20 -06:00
|
|
|
{
|
|
|
|
match s.parse() {
|
|
|
|
Ok(date) => Ok(DatetimeFromString { value: date }),
|
|
|
|
Err(e) => Err(de::Error::custom(e)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
deserializer.deserialize_str(Visitor)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Display for DatetimeParseError {
|
2019-05-08 19:37:38 -05:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2017-01-29 18:53:20 -06:00
|
|
|
"failed to parse datetime".fmt(f)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl error::Error for DatetimeParseError {
|
|
|
|
fn description(&self) -> &str {
|
|
|
|
"failed to parse datetime"
|
|
|
|
}
|
|
|
|
}
|