2018-08-01 23:27:49 -04:00
|
|
|
#![deny(missing_docs)]
|
2020-06-11 13:33:09 -04:00
|
|
|
#![cfg_attr(test, allow(unknown_lints))]
|
2018-07-30 23:33:46 -04:00
|
|
|
#![cfg_attr(test, deny(warnings))]
|
|
|
|
|
|
|
|
//! # dtparse
|
|
|
|
//! The fully-featured "even I couldn't understand that" time parser.
|
|
|
|
//! Designed to take in strings and give back sensible dates and times.
|
2019-11-13 23:18:37 -05:00
|
|
|
//!
|
2018-07-30 23:33:46 -04:00
|
|
|
//! dtparse has its foundations in the [`dateutil`](dateutil) library for
|
|
|
|
//! Python, which excels at taking "interesting" strings and trying to make
|
|
|
|
//! sense of the dates and times they contain. A couple of quick examples
|
|
|
|
//! from the test cases should give some context:
|
2019-11-13 23:18:37 -05:00
|
|
|
//!
|
2018-08-10 22:15:27 -04:00
|
|
|
//! ```rust,ignore (tests-dont-compile-on-old-rust)
|
2018-08-01 23:27:49 -04:00
|
|
|
//! # extern crate chrono;
|
|
|
|
//! # extern crate dtparse;
|
2018-07-30 23:33:46 -04:00
|
|
|
//! use chrono::prelude::*;
|
|
|
|
//! use dtparse::parse;
|
2019-11-13 23:18:37 -05:00
|
|
|
//!
|
2018-07-30 23:33:46 -04:00
|
|
|
//! assert_eq!(
|
|
|
|
//! parse("2008.12.30"),
|
|
|
|
//! Ok((NaiveDate::from_ymd(2008, 12, 30).and_hms(0, 0, 0), None))
|
|
|
|
//! );
|
2019-11-13 23:18:37 -05:00
|
|
|
//!
|
2018-07-30 23:33:46 -04:00
|
|
|
//! // It can even handle timezones!
|
|
|
|
//! assert_eq!(
|
|
|
|
//! parse("January 4, 2024; 18:30:04 +02:00"),
|
|
|
|
//! Ok((
|
|
|
|
//! NaiveDate::from_ymd(2024, 1, 4).and_hms(18, 30, 4),
|
|
|
|
//! Some(FixedOffset::east(7200))
|
|
|
|
//! ))
|
|
|
|
//! );
|
|
|
|
//! ```
|
2019-11-13 23:18:37 -05:00
|
|
|
//!
|
2018-07-30 23:33:46 -04:00
|
|
|
//! And we can even handle fuzzy strings where dates/times aren't the
|
|
|
|
//! only content if we dig into the implementation a bit!
|
2019-11-13 23:18:37 -05:00
|
|
|
//!
|
2018-08-10 22:15:27 -04:00
|
|
|
//! ```rust,ignore (tests-dont-compile-on-old-rust)
|
2018-08-01 23:27:49 -04:00
|
|
|
//! # extern crate chrono;
|
|
|
|
//! # extern crate dtparse;
|
2018-07-30 23:33:46 -04:00
|
|
|
//! use chrono::prelude::*;
|
|
|
|
//! use dtparse::Parser;
|
2018-08-01 23:27:49 -04:00
|
|
|
//! # use std::collections::HashMap;
|
2019-11-13 23:18:37 -05:00
|
|
|
//!
|
2018-07-30 23:33:46 -04:00
|
|
|
//! let mut p = Parser::default();
|
|
|
|
//! assert_eq!(
|
|
|
|
//! p.parse(
|
|
|
|
//! "I first released this library on the 17th of June, 2018.",
|
|
|
|
//! None, None,
|
|
|
|
//! true /* turns on fuzzy mode */,
|
|
|
|
//! true /* gives us the tokens that weren't recognized */,
|
|
|
|
//! None, false, &HashMap::new()
|
|
|
|
//! ),
|
|
|
|
//! Ok((
|
|
|
|
//! NaiveDate::from_ymd(2018, 6, 17).and_hms(0, 0, 0),
|
|
|
|
//! None,
|
|
|
|
//! Some(vec!["I first released this library on the ",
|
|
|
|
//! " of ", ", "].iter().map(|&s| s.into()).collect())
|
|
|
|
//! ))
|
|
|
|
//! );
|
|
|
|
//! ```
|
2019-11-13 23:18:37 -05:00
|
|
|
//!
|
2018-07-30 23:33:46 -04:00
|
|
|
//! Further examples can be found in the `examples` directory on international usage.
|
2018-08-14 22:49:24 -04:00
|
|
|
//!
|
|
|
|
//! # Usage
|
|
|
|
//!
|
2019-11-25 20:57:56 -05:00
|
|
|
//! `dtparse` requires a minimum Rust version of 1.28 to build, but is tested on Windows, OSX,
|
2018-08-14 22:49:24 -04:00
|
|
|
//! BSD, Linux, and WASM. The build is also compiled against the iOS and Android SDK's, but is not
|
|
|
|
//! tested against them.
|
2019-11-13 23:18:37 -05:00
|
|
|
//!
|
2018-07-30 23:33:46 -04:00
|
|
|
//! [dateutil]: https://github.com/dateutil/dateutil
|
|
|
|
|
2018-05-26 20:14:30 -04:00
|
|
|
#[macro_use]
|
|
|
|
extern crate lazy_static;
|
|
|
|
|
2018-05-13 16:18:45 -04:00
|
|
|
extern crate chrono;
|
2018-05-26 20:14:30 -04:00
|
|
|
extern crate num_traits;
|
2018-05-25 00:00:15 -04:00
|
|
|
extern crate rust_decimal;
|
2018-05-13 16:18:45 -04:00
|
|
|
|
2023-03-24 22:29:55 -04:00
|
|
|
#[cfg(test)]
|
|
|
|
extern crate base64;
|
|
|
|
|
2018-05-17 22:56:46 -04:00
|
|
|
use chrono::Datelike;
|
2018-06-24 23:53:33 -04:00
|
|
|
use chrono::Duration;
|
2018-05-24 22:28:06 -04:00
|
|
|
use chrono::FixedOffset;
|
2018-05-17 22:56:46 -04:00
|
|
|
use chrono::Local;
|
2018-05-26 22:40:32 -04:00
|
|
|
use chrono::NaiveDate;
|
2018-05-23 21:53:33 -04:00
|
|
|
use chrono::NaiveDateTime;
|
|
|
|
use chrono::NaiveTime;
|
2019-11-13 23:18:37 -05:00
|
|
|
use chrono::Timelike;
|
2018-05-26 20:14:30 -04:00
|
|
|
use num_traits::cast::ToPrimitive;
|
2018-05-25 00:00:15 -04:00
|
|
|
use rust_decimal::Decimal;
|
|
|
|
use rust_decimal::Error as DecimalError;
|
2018-06-17 21:43:43 -04:00
|
|
|
use std::cmp::min;
|
2019-11-13 23:18:37 -05:00
|
|
|
use std::collections::HashMap;
|
2020-06-11 11:29:37 -04:00
|
|
|
use std::error::Error;
|
|
|
|
use std::fmt;
|
2018-05-25 00:00:15 -04:00
|
|
|
use std::num::ParseIntError;
|
|
|
|
use std::str::FromStr;
|
2018-05-15 00:50:14 -04:00
|
|
|
use std::vec::Vec;
|
2018-05-13 16:18:45 -04:00
|
|
|
|
2018-06-29 23:04:10 -04:00
|
|
|
mod tokenize;
|
2018-06-24 23:53:33 -04:00
|
|
|
mod weekday;
|
|
|
|
|
2018-06-25 23:08:03 -04:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests;
|
|
|
|
|
2018-06-29 23:04:10 -04:00
|
|
|
use tokenize::Tokenizer;
|
2018-06-24 23:53:33 -04:00
|
|
|
use weekday::day_of_week;
|
|
|
|
use weekday::DayOfWeek;
|
|
|
|
|
2018-05-26 20:14:30 -04:00
|
|
|
lazy_static! {
|
|
|
|
static ref ZERO: Decimal = Decimal::new(0, 0);
|
|
|
|
static ref ONE: Decimal = Decimal::new(1, 0);
|
|
|
|
static ref TWENTY_FOUR: Decimal = Decimal::new(24, 0);
|
|
|
|
static ref SIXTY: Decimal = Decimal::new(60, 0);
|
2018-09-17 22:19:30 -04:00
|
|
|
static ref DEFAULT_PARSER: Parser = Parser::default();
|
2018-05-26 20:14:30 -04:00
|
|
|
}
|
2018-05-15 00:50:14 -04:00
|
|
|
|
2018-07-24 23:28:38 -04:00
|
|
|
impl From<DecimalError> for ParseError {
|
|
|
|
fn from(err: DecimalError) -> Self {
|
|
|
|
ParseError::InvalidNumeric(format!("{}", err))
|
2018-05-26 20:14:30 -04:00
|
|
|
}
|
2018-05-25 00:00:15 -04:00
|
|
|
}
|
|
|
|
|
2018-07-24 23:28:38 -04:00
|
|
|
impl From<ParseIntError> for ParseError {
|
|
|
|
fn from(err: ParseIntError) -> Self {
|
|
|
|
ParseError::InvalidNumeric(format!("{}", err))
|
2018-05-26 20:14:30 -04:00
|
|
|
}
|
2018-05-25 00:00:15 -04:00
|
|
|
}
|
|
|
|
|
2018-08-01 23:27:49 -04:00
|
|
|
/// Potential errors that come up when trying to parse time strings
|
2018-06-25 23:08:03 -04:00
|
|
|
#[derive(Debug, PartialEq)]
|
2018-05-25 00:00:15 -04:00
|
|
|
pub enum ParseError {
|
2018-08-01 23:27:49 -04:00
|
|
|
/// Attempted to specify "AM" or "PM" without indicating an hour
|
2018-05-26 22:40:32 -04:00
|
|
|
AmPmWithoutHour,
|
2018-08-01 23:27:49 -04:00
|
|
|
/// Impossible value for a category; the 32nd day of a month is impossible
|
2018-07-02 01:56:48 -04:00
|
|
|
ImpossibleTimestamp(&'static str),
|
2018-08-01 23:27:49 -04:00
|
|
|
/// Unable to parse a numeric value from a token expected to be numeric
|
2018-07-24 23:28:38 -04:00
|
|
|
InvalidNumeric(String),
|
2018-08-01 23:27:49 -04:00
|
|
|
/// Generally unrecognized date string; please report to maintainer so
|
|
|
|
/// new test cases can be developed
|
2018-07-24 23:28:38 -04:00
|
|
|
UnrecognizedFormat,
|
2018-08-01 23:27:49 -04:00
|
|
|
/// A token the parser did not recognize was in the string, and fuzzy mode was off
|
2018-07-24 23:28:38 -04:00
|
|
|
UnrecognizedToken(String),
|
2018-08-01 23:27:49 -04:00
|
|
|
/// A timezone could not be handled; please report to maintainer as the timestring
|
|
|
|
/// likely exposes a bug in the implementation
|
2018-07-24 23:28:38 -04:00
|
|
|
TimezoneUnsupported,
|
2018-08-01 23:27:49 -04:00
|
|
|
/// Parser unable to make sense of year/month/day parameters in the time string;
|
|
|
|
/// please report to maintainer as the timestring likely exposes a bug in implementation
|
2018-07-24 23:28:38 -04:00
|
|
|
YearMonthDayError(&'static str),
|
2020-06-11 15:00:37 -04:00
|
|
|
/// Parser unable to find any date/time-related content in the supplied string
|
|
|
|
NoDate,
|
2018-05-25 00:00:15 -04:00
|
|
|
}
|
|
|
|
|
2020-06-11 11:29:37 -04:00
|
|
|
impl fmt::Display for ParseError {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
|
write!(f, "{:?}", self)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Error for ParseError {}
|
|
|
|
|
2018-05-18 23:50:53 -04:00
|
|
|
type ParseResult<I> = Result<I, ParseError>;
|
|
|
|
|
2018-07-24 22:47:22 -04:00
|
|
|
pub(crate) fn tokenize(parse_string: &str) -> Vec<String> {
|
2018-07-07 23:37:02 -04:00
|
|
|
let tokenizer = Tokenizer::new(parse_string);
|
2018-05-15 00:50:14 -04:00
|
|
|
tokenizer.collect()
|
|
|
|
}
|
2018-05-17 22:56:46 -04:00
|
|
|
|
2018-08-01 23:27:49 -04:00
|
|
|
/// Utility function for `ParserInfo` that helps in constructing
|
|
|
|
/// the attributes that make up the `ParserInfo` container
|
|
|
|
pub fn parse_info(vec: Vec<Vec<&str>>) -> HashMap<String, usize> {
|
2018-05-17 22:56:46 -04:00
|
|
|
let mut m = HashMap::new();
|
|
|
|
|
|
|
|
if vec.len() == 1 {
|
2020-06-11 13:33:09 -04:00
|
|
|
for (i, val) in vec.get(0).unwrap().iter().enumerate() {
|
2018-05-17 22:56:46 -04:00
|
|
|
m.insert(val.to_lowercase(), i);
|
|
|
|
}
|
|
|
|
} else {
|
2020-06-11 13:33:09 -04:00
|
|
|
for (i, val_vec) in vec.iter().enumerate() {
|
2018-08-10 23:24:02 -04:00
|
|
|
for val in val_vec {
|
2018-05-17 22:56:46 -04:00
|
|
|
m.insert(val.to_lowercase(), i);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
m
|
|
|
|
}
|
|
|
|
|
2018-08-01 23:27:49 -04:00
|
|
|
/// Container for specific tokens to be recognized during parsing.
|
2019-11-13 23:18:37 -05:00
|
|
|
///
|
2018-08-01 23:27:49 -04:00
|
|
|
/// - `jump`: Values that indicate the end of a token for parsing and can be ignored
|
|
|
|
/// - `weekday`: Names of the days of the week
|
|
|
|
/// - `months`: Names of the months
|
|
|
|
/// - `hms`: Names for the units of time - hours, minutes, seconds in English
|
|
|
|
/// - `ampm`: AM and PM tokens
|
|
|
|
/// - `utczone`: Tokens indicating a UTC-timezone string
|
|
|
|
/// - `pertain`: Tokens indicating a "belongs to" relationship; in English this is just "of"
|
|
|
|
/// - `tzoffset`:
|
|
|
|
/// - `dayfirst`: Upon encountering an ambiguous date, treat the first value as the day
|
|
|
|
/// - `yearfirst`: Upon encountering an ambiguous date, treat the first value as the year
|
|
|
|
/// - `year`: The current year
|
|
|
|
/// - `century`: The first year in the current century
|
2019-11-13 23:18:37 -05:00
|
|
|
///
|
2018-08-01 23:27:49 -04:00
|
|
|
/// Please note that if both `dayfirst` and `yearfirst` are true, years take precedence
|
|
|
|
/// and will be parsed as "YDM"
|
2018-05-26 20:14:30 -04:00
|
|
|
#[derive(Debug, PartialEq)]
|
2018-05-29 21:07:22 -04:00
|
|
|
pub struct ParserInfo {
|
2018-08-03 23:40:54 -04:00
|
|
|
/// Tokens that can be safely ignored
|
|
|
|
pub jump: HashMap<String, usize>,
|
|
|
|
/// Names of all seven weekdays
|
|
|
|
pub weekday: HashMap<String, usize>,
|
|
|
|
/// Names of all twelve months
|
|
|
|
pub months: HashMap<String, usize>,
|
|
|
|
/// Tokens to indicate a value is in units of hours, minutes, or seconds
|
|
|
|
pub hms: HashMap<String, usize>,
|
|
|
|
/// Tokens to indicate a value refers to AM or PM time
|
|
|
|
pub ampm: HashMap<String, usize>,
|
|
|
|
/// Tokens to indicate our timestamp is in the UTC timezone
|
|
|
|
pub utczone: HashMap<String, usize>,
|
|
|
|
/// Tokens to indicate values "belonging" to other tokens (e.g. 3rd *of* March)
|
|
|
|
pub pertain: HashMap<String, usize>,
|
|
|
|
/// Map of timezone names to their offset in seconds
|
|
|
|
pub tzoffset: HashMap<String, usize>,
|
|
|
|
/// For ambiguous year/month/day values, and `dayfirst` was not specified as
|
|
|
|
/// an argument to `Parser`, treat the first observed value as the day.
|
|
|
|
pub dayfirst: bool,
|
|
|
|
/// For ambiguous year/month/day values, and `dayfirst` was not specified as
|
|
|
|
/// an argument to `Parser`, treat the first observed value as the day.
|
|
|
|
/// Takes priority over `dayfirst`
|
|
|
|
pub yearfirst: bool,
|
|
|
|
/// The current year we are parsing values for
|
|
|
|
pub year: i32,
|
|
|
|
/// The current year we are parsing values for *modulo* 100
|
|
|
|
pub century: i32,
|
2018-05-17 22:56:46 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for ParserInfo {
|
2018-08-01 23:27:49 -04:00
|
|
|
/// Create a basic `ParserInfo` object suitable for parsing dates in English
|
2018-05-17 22:56:46 -04:00
|
|
|
fn default() -> Self {
|
|
|
|
let year = Local::now().year();
|
|
|
|
let century = year / 100 * 100;
|
|
|
|
|
|
|
|
ParserInfo {
|
2019-11-13 23:18:37 -05:00
|
|
|
jump: parse_info(vec![vec![
|
|
|
|
" ", ".", ",", ";", "-", "/", "'", "at", "on", "and", "ad", "m", "t", "of", "st",
|
|
|
|
"nd", "rd", "th",
|
|
|
|
]]),
|
2018-05-17 22:56:46 -04:00
|
|
|
weekday: parse_info(vec![
|
|
|
|
vec!["Mon", "Monday"],
|
|
|
|
vec!["Tue", "Tues", "Tuesday"],
|
|
|
|
vec!["Wed", "Wednesday"],
|
|
|
|
vec!["Thu", "Thurs", "Thursday"],
|
|
|
|
vec!["Fri", "Friday"],
|
|
|
|
vec!["Sat", "Saturday"],
|
|
|
|
vec!["Sun", "Sunday"],
|
|
|
|
]),
|
|
|
|
months: parse_info(vec![
|
|
|
|
vec!["Jan", "January"],
|
|
|
|
vec!["Feb", "February"],
|
|
|
|
vec!["Mar", "March"],
|
|
|
|
vec!["Apr", "April"],
|
|
|
|
vec!["May"],
|
|
|
|
vec!["Jun", "June"],
|
|
|
|
vec!["Jul", "July"],
|
|
|
|
vec!["Aug", "August"],
|
|
|
|
vec!["Sep", "Sept", "September"],
|
|
|
|
vec!["Oct", "October"],
|
|
|
|
vec!["Nov", "November"],
|
|
|
|
vec!["Dec", "December"],
|
|
|
|
]),
|
|
|
|
hms: parse_info(vec![
|
|
|
|
vec!["h", "hour", "hours"],
|
|
|
|
vec!["m", "minute", "minutes"],
|
|
|
|
vec!["s", "second", "seconds"],
|
|
|
|
]),
|
2018-05-18 23:50:53 -04:00
|
|
|
ampm: parse_info(vec![vec!["am", "a"], vec!["pm", "p"]]),
|
|
|
|
utczone: parse_info(vec![vec!["UTC", "GMT", "Z"]]),
|
2018-05-17 22:56:46 -04:00
|
|
|
pertain: parse_info(vec![vec!["of"]]),
|
|
|
|
tzoffset: parse_info(vec![vec![]]),
|
|
|
|
dayfirst: false,
|
|
|
|
yearfirst: false,
|
2018-08-10 23:24:02 -04:00
|
|
|
year,
|
|
|
|
century,
|
2018-05-17 22:56:46 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ParserInfo {
|
2018-08-03 23:40:54 -04:00
|
|
|
fn jump_index(&self, name: &str) -> bool {
|
2018-05-17 22:56:46 -04:00
|
|
|
self.jump.contains_key(&name.to_lowercase())
|
|
|
|
}
|
|
|
|
|
2018-08-03 23:40:54 -04:00
|
|
|
fn weekday_index(&self, name: &str) -> Option<usize> {
|
2018-08-10 23:24:02 -04:00
|
|
|
self.weekday.get(&name.to_lowercase()).cloned()
|
2018-05-17 22:56:46 -04:00
|
|
|
}
|
|
|
|
|
2018-08-03 23:40:54 -04:00
|
|
|
fn month_index(&self, name: &str) -> Option<usize> {
|
2018-05-17 22:56:46 -04:00
|
|
|
self.months.get(&name.to_lowercase()).map(|u| u + 1)
|
|
|
|
}
|
|
|
|
|
2018-08-03 23:40:54 -04:00
|
|
|
fn hms_index(&self, name: &str) -> Option<usize> {
|
2018-08-10 23:24:02 -04:00
|
|
|
self.hms.get(&name.to_lowercase()).cloned()
|
2018-05-17 22:56:46 -04:00
|
|
|
}
|
|
|
|
|
2018-08-03 23:40:54 -04:00
|
|
|
fn ampm_index(&self, name: &str) -> Option<bool> {
|
2018-05-26 22:40:32 -04:00
|
|
|
if let Some(v) = self.ampm.get(&name.to_lowercase()) {
|
2018-07-08 21:31:18 -04:00
|
|
|
// Python technically uses numbers here, but given that the numbers are
|
|
|
|
// only 0 and 1, it's easier to use booleans
|
|
|
|
Some(*v == 1)
|
2018-05-26 22:40:32 -04:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
2018-05-17 22:56:46 -04:00
|
|
|
}
|
|
|
|
|
2018-08-03 23:40:54 -04:00
|
|
|
fn pertain_index(&self, name: &str) -> bool {
|
2018-05-17 22:56:46 -04:00
|
|
|
self.pertain.contains_key(&name.to_lowercase())
|
|
|
|
}
|
|
|
|
|
2018-08-03 23:40:54 -04:00
|
|
|
fn utczone_index(&self, name: &str) -> bool {
|
2018-05-17 22:56:46 -04:00
|
|
|
self.utczone.contains_key(&name.to_lowercase())
|
|
|
|
}
|
|
|
|
|
2018-08-03 23:40:54 -04:00
|
|
|
fn tzoffset_index(&self, name: &str) -> Option<usize> {
|
2018-05-17 22:56:46 -04:00
|
|
|
if self.utczone.contains_key(&name.to_lowercase()) {
|
|
|
|
Some(0)
|
|
|
|
} else {
|
|
|
|
self.tzoffset.get(&name.to_lowercase()).cloned()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-25 00:00:15 -04:00
|
|
|
fn convertyear(&self, year: i32, century_specified: bool) -> i32 {
|
2018-05-17 22:56:46 -04:00
|
|
|
let mut year = year;
|
|
|
|
|
|
|
|
if year < 100 && !century_specified {
|
|
|
|
year += self.century;
|
|
|
|
if year >= self.year + 50 {
|
|
|
|
year -= 100;
|
|
|
|
} else if year < self.year - 50 {
|
|
|
|
year += 100
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
year
|
|
|
|
}
|
2018-05-25 00:00:15 -04:00
|
|
|
|
|
|
|
// TODO: Should this be moved elsewhere?
|
|
|
|
fn validate(&self, res: &mut ParsingResult) -> bool {
|
2018-05-26 20:14:30 -04:00
|
|
|
if let Some(y) = res.year {
|
|
|
|
res.year = Some(self.convertyear(y, res.century_specified))
|
|
|
|
};
|
|
|
|
|
2020-06-11 12:49:55 -04:00
|
|
|
if (res.tzoffset == Some(0) && res.tzname.is_none())
|
|
|
|
|| (res.tzname == Some("Z".to_owned()) || res.tzname == Some("z".to_owned()))
|
|
|
|
{
|
2018-05-25 00:00:15 -04:00
|
|
|
res.tzname = Some("UTC".to_owned());
|
2018-05-26 20:14:30 -04:00
|
|
|
res.tzoffset = Some(0);
|
2019-11-13 23:18:37 -05:00
|
|
|
} else if res.tzoffset != Some(0)
|
|
|
|
&& res.tzname.is_some()
|
2018-08-03 23:40:54 -04:00
|
|
|
&& self.utczone_index(res.tzname.as_ref().unwrap())
|
2018-05-26 20:14:30 -04:00
|
|
|
{
|
|
|
|
res.tzoffset = Some(0);
|
2018-05-25 00:00:15 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
true
|
|
|
|
}
|
2018-05-18 23:50:53 -04:00
|
|
|
}
|
|
|
|
|
2018-06-17 21:43:43 -04:00
|
|
|
fn days_in_month(year: i32, month: i32) -> Result<u32, ParseError> {
|
2018-05-18 23:50:53 -04:00
|
|
|
let leap_year = match year % 4 {
|
2018-06-17 21:43:43 -04:00
|
|
|
0 => year % 400 != 0,
|
2018-05-18 23:50:53 -04:00
|
|
|
_ => false,
|
|
|
|
};
|
|
|
|
|
|
|
|
match month {
|
2019-11-13 23:18:37 -05:00
|
|
|
2 => {
|
|
|
|
if leap_year {
|
|
|
|
Ok(29)
|
|
|
|
} else {
|
|
|
|
Ok(28)
|
|
|
|
}
|
|
|
|
}
|
2018-05-18 23:50:53 -04:00
|
|
|
1 | 3 | 5 | 7 | 8 | 10 | 12 => Ok(31),
|
|
|
|
4 | 6 | 9 | 11 => Ok(30),
|
2019-11-13 23:18:37 -05:00
|
|
|
_ => Err(ParseError::ImpossibleTimestamp("Invalid month")),
|
2018-05-18 23:50:53 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, Hash, PartialEq, Eq)]
|
2018-07-24 23:28:38 -04:00
|
|
|
enum YMDLabel {
|
2018-05-18 23:50:53 -04:00
|
|
|
Year,
|
|
|
|
Month,
|
|
|
|
Day,
|
|
|
|
}
|
|
|
|
|
2018-05-25 00:00:15 -04:00
|
|
|
#[derive(Debug, Default)]
|
2018-05-18 23:50:53 -04:00
|
|
|
struct YMD {
|
|
|
|
_ymd: Vec<i32>, // TODO: This seems like a super weird way to store things
|
|
|
|
century_specified: bool,
|
|
|
|
dstridx: Option<usize>,
|
|
|
|
mstridx: Option<usize>,
|
|
|
|
ystridx: Option<usize>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl YMD {
|
2018-05-26 20:14:30 -04:00
|
|
|
fn len(&self) -> usize {
|
|
|
|
self._ymd.len()
|
|
|
|
}
|
2018-05-25 00:00:15 -04:00
|
|
|
|
2018-05-26 20:14:30 -04:00
|
|
|
fn could_be_day(&self, val: i32) -> bool {
|
2018-05-18 23:50:53 -04:00
|
|
|
if self.dstridx.is_some() {
|
2018-05-26 20:14:30 -04:00
|
|
|
false
|
2018-05-18 23:50:53 -04:00
|
|
|
} else if self.mstridx.is_none() {
|
2018-05-26 20:14:30 -04:00
|
|
|
(1 <= val) && (val <= 31)
|
2018-05-18 23:50:53 -04:00
|
|
|
} else if self.ystridx.is_none() {
|
2018-06-25 22:16:34 -04:00
|
|
|
// UNWRAP: Earlier condition catches mstridx missing
|
2018-05-18 23:50:53 -04:00
|
|
|
let month = self._ymd[self.mstridx.unwrap()];
|
2018-06-17 21:43:43 -04:00
|
|
|
1 <= val && (val <= days_in_month(2000, month).unwrap() as i32)
|
2018-05-18 23:50:53 -04:00
|
|
|
} else {
|
2018-06-25 22:16:34 -04:00
|
|
|
// UNWRAP: Earlier conditions prevent us from unsafely unwrapping
|
2018-05-18 23:50:53 -04:00
|
|
|
let month = self._ymd[self.mstridx.unwrap()];
|
|
|
|
let year = self._ymd[self.ystridx.unwrap()];
|
2018-06-17 21:43:43 -04:00
|
|
|
1 <= val && (val <= days_in_month(year, month).unwrap() as i32)
|
2018-05-18 23:50:53 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-24 23:28:38 -04:00
|
|
|
fn append(&mut self, val: i32, token: &str, label: Option<YMDLabel>) -> ParseResult<()> {
|
2018-05-18 23:50:53 -04:00
|
|
|
let mut label = label;
|
|
|
|
|
2018-06-17 22:39:06 -04:00
|
|
|
// Python auto-detects strings using the '__len__' function here.
|
|
|
|
// We instead take in both and handle as necessary.
|
|
|
|
if Decimal::from_str(token).is_ok() && token.len() > 2 {
|
|
|
|
self.century_specified = true;
|
|
|
|
match label {
|
|
|
|
None | Some(YMDLabel::Year) => label = Some(YMDLabel::Year),
|
2018-07-24 23:28:38 -04:00
|
|
|
Some(YMDLabel::Month) => {
|
|
|
|
return Err(ParseError::ImpossibleTimestamp("Invalid month"))
|
|
|
|
}
|
2019-11-13 23:18:37 -05:00
|
|
|
Some(YMDLabel::Day) => return Err(ParseError::ImpossibleTimestamp("Invalid day")),
|
2018-06-17 22:39:06 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-18 23:50:53 -04:00
|
|
|
if val > 100 {
|
|
|
|
self.century_specified = true;
|
|
|
|
match label {
|
|
|
|
None => label = Some(YMDLabel::Year),
|
|
|
|
Some(YMDLabel::Year) => (),
|
2018-07-24 23:28:38 -04:00
|
|
|
Some(YMDLabel::Month) => {
|
|
|
|
return Err(ParseError::ImpossibleTimestamp("Invalid month"))
|
|
|
|
}
|
2019-11-13 23:18:37 -05:00
|
|
|
Some(YMDLabel::Day) => return Err(ParseError::ImpossibleTimestamp("Invalid day")),
|
2018-05-18 23:50:53 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-28 00:36:54 -04:00
|
|
|
self._ymd.push(val);
|
|
|
|
|
2018-05-18 23:50:53 -04:00
|
|
|
match label {
|
|
|
|
Some(YMDLabel::Month) => {
|
|
|
|
if self.mstridx.is_some() {
|
2018-07-24 23:28:38 -04:00
|
|
|
Err(ParseError::YearMonthDayError("Month already set"))
|
2018-05-18 23:50:53 -04:00
|
|
|
} else {
|
|
|
|
self.mstridx = Some(self._ymd.len() - 1);
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Some(YMDLabel::Day) => {
|
|
|
|
if self.dstridx.is_some() {
|
2018-07-24 23:28:38 -04:00
|
|
|
Err(ParseError::YearMonthDayError("Day already set"))
|
2018-05-18 23:50:53 -04:00
|
|
|
} else {
|
|
|
|
self.dstridx = Some(self._ymd.len() - 1);
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Some(YMDLabel::Year) => {
|
|
|
|
if self.ystridx.is_some() {
|
2018-07-24 23:28:38 -04:00
|
|
|
Err(ParseError::YearMonthDayError("Year already set"))
|
2018-05-18 23:50:53 -04:00
|
|
|
} else {
|
|
|
|
self.ystridx = Some(self._ymd.len() - 1);
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
2018-07-03 01:02:27 -04:00
|
|
|
None => Ok(()),
|
2018-05-18 23:50:53 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn resolve_from_stridxs(
|
|
|
|
&mut self,
|
|
|
|
strids: &mut HashMap<YMDLabel, usize>,
|
2018-07-24 23:28:38 -04:00
|
|
|
) -> ParseResult<(Option<i32>, Option<i32>, Option<i32>)> {
|
2018-05-28 12:28:49 -04:00
|
|
|
if self._ymd.len() == 3 && strids.len() == 2 {
|
2018-05-18 23:50:53 -04:00
|
|
|
let missing_key = if !strids.contains_key(&YMDLabel::Year) {
|
|
|
|
YMDLabel::Year
|
|
|
|
} else if !strids.contains_key(&YMDLabel::Month) {
|
|
|
|
YMDLabel::Month
|
|
|
|
} else {
|
|
|
|
YMDLabel::Day
|
|
|
|
};
|
|
|
|
|
2018-08-10 23:24:02 -04:00
|
|
|
let strids_vals: Vec<usize> = strids.values().cloned().collect();
|
2018-05-18 23:50:53 -04:00
|
|
|
let missing_val = if !strids_vals.contains(&0) {
|
|
|
|
0
|
|
|
|
} else if !strids_vals.contains(&1) {
|
|
|
|
1
|
|
|
|
} else {
|
|
|
|
2
|
|
|
|
};
|
|
|
|
|
|
|
|
strids.insert(missing_key, missing_val);
|
|
|
|
}
|
|
|
|
|
2018-05-28 12:28:49 -04:00
|
|
|
if self._ymd.len() != strids.len() {
|
2019-11-13 23:18:37 -05:00
|
|
|
return Err(ParseError::YearMonthDayError(
|
|
|
|
"Tried to resolve year, month, and day without enough information",
|
|
|
|
));
|
2018-05-18 23:50:53 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok((
|
2019-11-13 23:18:37 -05:00
|
|
|
strids.get(&YMDLabel::Year).map(|i| self._ymd[*i]),
|
|
|
|
strids.get(&YMDLabel::Month).map(|i| self._ymd[*i]),
|
|
|
|
strids.get(&YMDLabel::Day).map(|i| self._ymd[*i]),
|
2018-05-18 23:50:53 -04:00
|
|
|
))
|
|
|
|
}
|
|
|
|
|
2020-06-11 13:33:09 -04:00
|
|
|
#[allow(clippy::needless_return)]
|
2018-05-28 13:21:34 -04:00
|
|
|
fn resolve_ymd(
|
|
|
|
&mut self,
|
|
|
|
yearfirst: bool,
|
|
|
|
dayfirst: bool,
|
2018-07-24 23:28:38 -04:00
|
|
|
) -> ParseResult<(Option<i32>, Option<i32>, Option<i32>)> {
|
2018-05-18 23:50:53 -04:00
|
|
|
let len_ymd = self._ymd.len();
|
2018-06-25 13:12:08 -04:00
|
|
|
|
2018-05-18 23:50:53 -04:00
|
|
|
let mut strids: HashMap<YMDLabel, usize> = HashMap::new();
|
2019-11-13 23:18:37 -05:00
|
|
|
self.ystridx.map(|u| strids.insert(YMDLabel::Year, u));
|
|
|
|
self.mstridx.map(|u| strids.insert(YMDLabel::Month, u));
|
|
|
|
self.dstridx.map(|u| strids.insert(YMDLabel::Day, u));
|
2018-05-18 23:50:53 -04:00
|
|
|
|
|
|
|
// TODO: More Rustiomatic way of doing this?
|
2019-11-13 23:18:37 -05:00
|
|
|
if len_ymd == strids.len() && !strids.is_empty() || (len_ymd == 3 && strids.len() == 2) {
|
2018-05-28 00:36:54 -04:00
|
|
|
return self.resolve_from_stridxs(&mut strids);
|
2018-05-23 21:53:33 -04:00
|
|
|
};
|
2018-05-18 23:50:53 -04:00
|
|
|
|
2018-07-24 23:28:38 -04:00
|
|
|
// Received year, month, day, and ???
|
2018-05-18 23:50:53 -04:00
|
|
|
if len_ymd > 3 {
|
2019-11-13 23:18:37 -05:00
|
|
|
return Err(ParseError::YearMonthDayError(
|
|
|
|
"Received extra tokens in resolving year, month, and day",
|
|
|
|
));
|
2018-06-25 13:12:08 -04:00
|
|
|
}
|
2018-06-25 15:22:59 -04:00
|
|
|
|
2018-06-25 14:56:24 -04:00
|
|
|
match (len_ymd, self.mstridx) {
|
2019-11-13 23:18:37 -05:00
|
|
|
(1, Some(val)) | (2, Some(val)) => {
|
2018-06-25 14:56:24 -04:00
|
|
|
let other = if len_ymd == 1 {
|
|
|
|
self._ymd[0]
|
2018-05-28 13:21:34 -04:00
|
|
|
} else {
|
2018-06-25 14:56:24 -04:00
|
|
|
self._ymd[1 - val]
|
|
|
|
};
|
2018-06-25 13:49:30 -04:00
|
|
|
if other > 31 {
|
2018-06-25 15:22:59 -04:00
|
|
|
return Ok((Some(other), Some(self._ymd[val]), None));
|
2018-06-25 13:49:30 -04:00
|
|
|
}
|
2018-06-25 15:22:59 -04:00
|
|
|
return Ok((None, Some(self._ymd[val]), Some(other)));
|
2019-11-13 23:18:37 -05:00
|
|
|
}
|
2018-06-25 14:56:24 -04:00
|
|
|
(2, None) => {
|
2018-06-25 13:49:30 -04:00
|
|
|
if self._ymd[0] > 31 {
|
2018-06-25 15:22:59 -04:00
|
|
|
return Ok((Some(self._ymd[0]), Some(self._ymd[1]), None));
|
2018-06-25 14:56:24 -04:00
|
|
|
}
|
|
|
|
if self._ymd[1] > 31 {
|
2018-06-25 15:22:59 -04:00
|
|
|
return Ok((Some(self._ymd[1]), Some(self._ymd[0]), None));
|
2018-06-25 14:56:24 -04:00
|
|
|
}
|
|
|
|
if dayfirst && self._ymd[1] <= 12 {
|
2018-06-25 15:22:59 -04:00
|
|
|
return Ok((None, Some(self._ymd[1]), Some(self._ymd[0])));
|
2018-06-25 13:49:30 -04:00
|
|
|
}
|
2018-06-25 15:22:59 -04:00
|
|
|
return Ok((None, Some(self._ymd[0]), Some(self._ymd[1])));
|
2019-11-13 23:18:37 -05:00
|
|
|
}
|
2018-06-25 14:56:24 -04:00
|
|
|
(3, Some(0)) => {
|
2018-05-18 23:50:53 -04:00
|
|
|
if self._ymd[1] > 31 {
|
2018-06-25 15:22:59 -04:00
|
|
|
return Ok((Some(self._ymd[1]), Some(self._ymd[0]), Some(self._ymd[2])));
|
2018-05-18 23:50:53 -04:00
|
|
|
}
|
2018-06-25 15:22:59 -04:00
|
|
|
return Ok((Some(self._ymd[2]), Some(self._ymd[0]), Some(self._ymd[1])));
|
2019-11-13 23:18:37 -05:00
|
|
|
}
|
2018-06-25 14:56:24 -04:00
|
|
|
(3, Some(1)) => {
|
2018-05-18 23:50:53 -04:00
|
|
|
if self._ymd[0] > 31 || (yearfirst && self._ymd[2] <= 31) {
|
2018-06-25 15:22:59 -04:00
|
|
|
return Ok((Some(self._ymd[0]), Some(self._ymd[1]), Some(self._ymd[2])));
|
2018-05-18 23:50:53 -04:00
|
|
|
}
|
2018-06-25 15:22:59 -04:00
|
|
|
return Ok((Some(self._ymd[2]), Some(self._ymd[1]), Some(self._ymd[0])));
|
2019-11-13 23:18:37 -05:00
|
|
|
}
|
2018-06-25 14:56:24 -04:00
|
|
|
(3, Some(2)) => {
|
2018-05-18 23:50:53 -04:00
|
|
|
// It was in the original docs, so: WTF!?
|
|
|
|
if self._ymd[1] > 31 {
|
2018-06-25 15:22:59 -04:00
|
|
|
return Ok((Some(self._ymd[2]), Some(self._ymd[1]), Some(self._ymd[0])));
|
2018-05-18 23:50:53 -04:00
|
|
|
}
|
2018-06-25 15:22:59 -04:00
|
|
|
return Ok((Some(self._ymd[0]), Some(self._ymd[2]), Some(self._ymd[1])));
|
2019-11-13 23:18:37 -05:00
|
|
|
}
|
2018-06-25 14:56:24 -04:00
|
|
|
(3, None) => {
|
2019-11-13 23:18:37 -05:00
|
|
|
if self._ymd[0] > 31
|
|
|
|
|| self.ystridx == Some(0)
|
2018-05-23 21:53:33 -04:00
|
|
|
|| (yearfirst && self._ymd[1] <= 12 && self._ymd[2] <= 31)
|
|
|
|
{
|
2018-05-18 23:50:53 -04:00
|
|
|
if dayfirst && self._ymd[2] <= 12 {
|
2018-06-25 15:22:59 -04:00
|
|
|
return Ok((Some(self._ymd[0]), Some(self._ymd[2]), Some(self._ymd[1])));
|
2018-05-18 23:50:53 -04:00
|
|
|
}
|
2018-06-25 15:22:59 -04:00
|
|
|
return Ok((Some(self._ymd[0]), Some(self._ymd[1]), Some(self._ymd[2])));
|
|
|
|
} else if self._ymd[0] > 12 || (dayfirst && self._ymd[1] <= 12) {
|
|
|
|
return Ok((Some(self._ymd[2]), Some(self._ymd[1]), Some(self._ymd[0])));
|
2018-05-18 23:50:53 -04:00
|
|
|
}
|
2018-06-25 15:22:59 -04:00
|
|
|
return Ok((Some(self._ymd[2]), Some(self._ymd[0]), Some(self._ymd[1])));
|
2019-11-13 23:18:37 -05:00
|
|
|
}
|
|
|
|
(_, _) => {
|
|
|
|
return Ok((None, None, None));
|
|
|
|
}
|
2018-05-18 23:50:53 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-05-23 21:53:33 -04:00
|
|
|
|
2018-06-25 23:08:03 -04:00
|
|
|
#[derive(Default, Debug, PartialEq)]
|
2018-07-24 23:28:38 -04:00
|
|
|
struct ParsingResult {
|
2018-05-25 00:00:15 -04:00
|
|
|
year: Option<i32>,
|
|
|
|
month: Option<i32>,
|
|
|
|
day: Option<i32>,
|
2018-06-24 23:53:33 -04:00
|
|
|
weekday: Option<usize>,
|
2018-05-25 00:00:15 -04:00
|
|
|
hour: Option<i32>,
|
|
|
|
minute: Option<i32>,
|
|
|
|
second: Option<i32>,
|
2023-03-24 22:12:57 -04:00
|
|
|
nanosecond: Option<i64>,
|
2018-05-25 00:00:15 -04:00
|
|
|
tzname: Option<String>,
|
2018-05-26 20:14:30 -04:00
|
|
|
tzoffset: Option<i32>,
|
2018-05-26 22:40:32 -04:00
|
|
|
ampm: Option<bool>,
|
2018-05-25 00:00:15 -04:00
|
|
|
century_specified: bool,
|
2018-05-23 21:53:33 -04:00
|
|
|
any_unused_tokens: Vec<String>,
|
|
|
|
}
|
|
|
|
|
2020-06-11 15:00:37 -04:00
|
|
|
macro_rules! option_len {
|
|
|
|
($o:expr) => {{
|
|
|
|
if $o.is_some() {
|
|
|
|
1
|
|
|
|
} else {
|
|
|
|
0
|
|
|
|
}
|
|
|
|
}};
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ParsingResult {
|
|
|
|
fn len(&self) -> usize {
|
|
|
|
option_len!(self.year)
|
|
|
|
+ option_len!(self.month)
|
|
|
|
+ option_len!(self.day)
|
|
|
|
+ option_len!(self.weekday)
|
|
|
|
+ option_len!(self.hour)
|
|
|
|
+ option_len!(self.minute)
|
|
|
|
+ option_len!(self.second)
|
2023-03-24 22:12:57 -04:00
|
|
|
+ option_len!(self.nanosecond)
|
2020-06-11 15:00:37 -04:00
|
|
|
+ option_len!(self.tzname)
|
|
|
|
+ option_len!(self.ampm)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-01 23:27:49 -04:00
|
|
|
/// Parser is responsible for doing the actual work of understanding a time string.
|
|
|
|
/// The root level `parse` function is responsible for constructing a default `Parser`
|
|
|
|
/// and triggering its behavior.
|
2018-05-25 00:00:15 -04:00
|
|
|
#[derive(Default)]
|
2018-06-03 16:11:51 -04:00
|
|
|
pub struct Parser {
|
2018-05-23 21:53:33 -04:00
|
|
|
info: ParserInfo,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Parser {
|
2018-08-01 23:27:49 -04:00
|
|
|
/// Create a new `Parser` instance using the provided `ParserInfo`.
|
2019-11-13 23:18:37 -05:00
|
|
|
///
|
2018-08-01 23:27:49 -04:00
|
|
|
/// This method allows you to set up a parser to handle different
|
|
|
|
/// names for days of the week, months, etc., enabling customization
|
|
|
|
/// for different languages or extra values.
|
2018-06-03 16:11:51 -04:00
|
|
|
pub fn new(info: ParserInfo) -> Self {
|
|
|
|
Parser { info }
|
|
|
|
}
|
|
|
|
|
2018-08-01 23:27:49 -04:00
|
|
|
/// Main method to trigger parsing of a string using the previously-provided
|
|
|
|
/// parser information. Returns a naive timestamp along with timezone and
|
|
|
|
/// unused tokens if available.
|
2019-11-13 23:18:37 -05:00
|
|
|
///
|
2018-08-01 23:27:49 -04:00
|
|
|
/// `dayfirst` and `yearfirst` force parser behavior in the event of ambiguous
|
|
|
|
/// dates. Consider the following scenarios where we parse the string '01.02.03'
|
2019-11-13 23:18:37 -05:00
|
|
|
///
|
2018-08-01 23:27:49 -04:00
|
|
|
/// - `dayfirst=Some(true)`, `yearfirst=None`: Results in `February 2, 2003`
|
|
|
|
/// - `dayfirst=None`, `yearfirst=Some(true)`: Results in `February 3, 2001`
|
|
|
|
/// - `dayfirst=Some(true)`, `yearfirst=Some(true)`: Results in `March 2, 2001`
|
2019-11-13 23:18:37 -05:00
|
|
|
///
|
2018-08-01 23:27:49 -04:00
|
|
|
/// `fuzzy` enables fuzzy parsing mode, allowing the parser to skip tokens if
|
|
|
|
/// they are unrecognized. However, the unused tokens will not be returned
|
|
|
|
/// unless `fuzzy_with_tokens` is set as `true`.
|
2019-11-13 23:18:37 -05:00
|
|
|
///
|
2018-08-01 23:27:49 -04:00
|
|
|
/// `default` is the timestamp used to infer missing values, and is midnight
|
|
|
|
/// of the current day by default. For example, when parsing the text '2003',
|
|
|
|
/// we will use the current month and day as a default value, leading to a
|
|
|
|
/// result of 'March 3, 2003' if the function was run using a default of
|
|
|
|
/// March 3rd.
|
2019-11-13 23:18:37 -05:00
|
|
|
///
|
2018-08-01 23:27:49 -04:00
|
|
|
/// `ignoretz` forces the parser to ignore timezone information even if it
|
|
|
|
/// is recognized in the time string
|
2019-11-13 23:18:37 -05:00
|
|
|
///
|
2018-08-01 23:27:49 -04:00
|
|
|
/// `tzinfos` is a map of timezone names to the offset seconds. For example,
|
|
|
|
/// the parser would ignore the 'EST' part of the string in '10 AM EST'
|
|
|
|
/// unless you added a `tzinfos` map of `{"EST": "14400"}`. Please note that
|
|
|
|
/// timezone name support (i.e. "EST", "BRST") is not available by default
|
|
|
|
/// at the moment, they must be added through `tzinfos` at the moment in
|
|
|
|
/// order to be resolved.
|
2020-06-11 13:33:09 -04:00
|
|
|
#[allow(clippy::too_many_arguments)]
|
2018-05-23 21:53:33 -04:00
|
|
|
pub fn parse(
|
2018-09-17 22:19:30 -04:00
|
|
|
&self,
|
2018-05-27 22:26:30 -04:00
|
|
|
timestr: &str,
|
2018-06-03 16:11:51 -04:00
|
|
|
dayfirst: Option<bool>,
|
|
|
|
yearfirst: Option<bool>,
|
|
|
|
fuzzy: bool,
|
|
|
|
fuzzy_with_tokens: bool,
|
2018-05-28 12:28:49 -04:00
|
|
|
default: Option<&NaiveDateTime>,
|
2018-05-23 21:53:33 -04:00
|
|
|
ignoretz: bool,
|
2018-07-24 23:28:38 -04:00
|
|
|
tzinfos: &HashMap<String, i32>,
|
2018-06-17 22:55:48 -04:00
|
|
|
) -> ParseResult<(NaiveDateTime, Option<FixedOffset>, Option<Vec<String>>)> {
|
2018-05-28 12:28:49 -04:00
|
|
|
let default_date = default.unwrap_or(&Local::now().naive_local()).date();
|
2018-05-23 21:53:33 -04:00
|
|
|
|
2023-03-24 22:29:55 -04:00
|
|
|
let default_ts = NaiveDateTime::new(default_date, NaiveTime::from_hms_opt(0, 0, 0).unwrap());
|
2018-05-23 21:53:33 -04:00
|
|
|
|
2018-06-03 16:11:51 -04:00
|
|
|
let (res, tokens) =
|
|
|
|
self.parse_with_tokens(timestr, dayfirst, yearfirst, fuzzy, fuzzy_with_tokens)?;
|
2018-05-23 21:53:33 -04:00
|
|
|
|
2020-06-11 15:00:37 -04:00
|
|
|
if res.len() == 0 {
|
|
|
|
return Err(ParseError::NoDate);
|
|
|
|
}
|
|
|
|
|
2018-06-17 22:55:48 -04:00
|
|
|
let naive = self.build_naive(&res, &default_ts)?;
|
2018-05-26 20:14:30 -04:00
|
|
|
|
|
|
|
if !ignoretz {
|
2018-06-07 23:49:11 -04:00
|
|
|
let offset = self.build_tzaware(&naive, &res, tzinfos)?;
|
2018-06-03 23:48:56 -04:00
|
|
|
Ok((naive, offset, tokens))
|
2018-05-26 20:14:30 -04:00
|
|
|
} else {
|
|
|
|
Ok((naive, None, tokens))
|
|
|
|
}
|
2018-05-23 21:53:33 -04:00
|
|
|
}
|
|
|
|
|
2020-06-11 13:33:09 -04:00
|
|
|
#[allow(clippy::cognitive_complexity)] // Imitating Python API is priority
|
2018-05-23 23:01:00 -04:00
|
|
|
fn parse_with_tokens(
|
2018-09-17 22:19:30 -04:00
|
|
|
&self,
|
2018-05-27 22:26:30 -04:00
|
|
|
timestr: &str,
|
2018-05-25 00:00:15 -04:00
|
|
|
dayfirst: Option<bool>,
|
|
|
|
yearfirst: Option<bool>,
|
2018-05-23 23:01:00 -04:00
|
|
|
fuzzy: bool,
|
|
|
|
fuzzy_with_tokens: bool,
|
2018-05-26 20:14:30 -04:00
|
|
|
) -> Result<(ParsingResult, Option<Vec<String>>), ParseError> {
|
2018-05-25 00:00:15 -04:00
|
|
|
let fuzzy = if fuzzy_with_tokens { true } else { fuzzy };
|
|
|
|
// This is probably a stylistic abomination
|
2018-05-26 20:14:30 -04:00
|
|
|
let dayfirst = if let Some(dayfirst) = dayfirst {
|
|
|
|
dayfirst
|
|
|
|
} else {
|
|
|
|
self.info.dayfirst
|
|
|
|
};
|
|
|
|
let yearfirst = if let Some(yearfirst) = yearfirst {
|
|
|
|
yearfirst
|
|
|
|
} else {
|
|
|
|
self.info.yearfirst
|
|
|
|
};
|
2018-05-25 00:00:15 -04:00
|
|
|
|
|
|
|
let mut res = ParsingResult::default();
|
|
|
|
|
2018-05-26 20:14:30 -04:00
|
|
|
let mut l = tokenize(×tr);
|
|
|
|
let mut skipped_idxs: Vec<usize> = Vec::new();
|
|
|
|
|
|
|
|
let mut ymd = YMD::default();
|
2018-05-25 00:00:15 -04:00
|
|
|
|
|
|
|
let len_l = l.len();
|
|
|
|
let mut i = 0;
|
|
|
|
|
|
|
|
while i < len_l {
|
2018-05-26 20:14:30 -04:00
|
|
|
let value_repr = l[i].clone();
|
2018-05-25 00:00:15 -04:00
|
|
|
|
2018-07-03 01:02:27 -04:00
|
|
|
if let Ok(_v) = Decimal::from_str(&value_repr) {
|
2018-05-26 20:14:30 -04:00
|
|
|
i = self.parse_numeric_token(&l, i, &self.info, &mut ymd, &mut res, fuzzy)?;
|
2018-08-03 23:40:54 -04:00
|
|
|
} else if let Some(value) = self.info.weekday_index(&l[i]) {
|
2018-06-24 23:53:33 -04:00
|
|
|
res.weekday = Some(value);
|
2018-08-03 23:40:54 -04:00
|
|
|
} else if let Some(value) = self.info.month_index(&l[i]) {
|
2018-07-03 01:02:27 -04:00
|
|
|
ymd.append(value as i32, &l[i], Some(YMDLabel::Month))?;
|
2018-05-26 20:14:30 -04:00
|
|
|
|
|
|
|
if i + 1 < len_l {
|
|
|
|
if l[i + 1] == "-" || l[i + 1] == "/" {
|
|
|
|
// Jan-01[-99]
|
|
|
|
let sep = &l[i + 1];
|
|
|
|
// TODO: This seems like a very unsafe unwrap
|
2020-05-29 14:23:54 -04:00
|
|
|
ymd.append(l[i + 2].parse::<i32>()?, &l[i + 2], None)?;
|
2018-05-26 20:14:30 -04:00
|
|
|
|
|
|
|
if i + 3 < len_l && &l[i + 3] == sep {
|
|
|
|
// Jan-01-99
|
2020-05-29 14:23:54 -04:00
|
|
|
ymd.append(l[i + 4].parse::<i32>()?, &l[i + 4], None)?;
|
2018-05-26 20:14:30 -04:00
|
|
|
i += 2;
|
|
|
|
}
|
|
|
|
|
|
|
|
i += 2;
|
2019-11-13 23:18:37 -05:00
|
|
|
} else if i + 4 < len_l
|
|
|
|
&& l[i + 1] == l[i + 3]
|
|
|
|
&& l[i + 3] == " "
|
2018-08-03 23:40:54 -04:00
|
|
|
&& self.info.pertain_index(&l[i + 2])
|
2018-05-26 20:14:30 -04:00
|
|
|
{
|
|
|
|
// Jan of 01
|
2018-08-10 23:24:02 -04:00
|
|
|
if let Ok(value) = l[i + 4].parse::<i32>() {
|
2018-05-26 20:14:30 -04:00
|
|
|
let year = self.info.convertyear(value, false);
|
2018-07-03 01:02:27 -04:00
|
|
|
ymd.append(year, &l[i + 4], Some(YMDLabel::Year))?;
|
2018-05-26 20:14:30 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
i += 4;
|
|
|
|
}
|
|
|
|
}
|
2018-08-03 23:40:54 -04:00
|
|
|
} else if let Some(value) = self.info.ampm_index(&l[i]) {
|
2018-05-26 20:14:30 -04:00
|
|
|
let is_ampm = self.ampm_valid(res.hour, res.ampm, fuzzy);
|
|
|
|
|
2018-07-08 21:51:02 -04:00
|
|
|
if is_ampm == Ok(true) {
|
2018-07-08 21:31:18 -04:00
|
|
|
res.hour = res.hour.map(|h| self.adjust_ampm(h, value));
|
2018-05-26 20:14:30 -04:00
|
|
|
res.ampm = Some(value);
|
|
|
|
} else if fuzzy {
|
|
|
|
skipped_idxs.push(i);
|
|
|
|
}
|
2018-08-10 23:24:02 -04:00
|
|
|
} else if self.could_be_tzname(res.hour, &res.tzname, res.tzoffset, &l[i]) {
|
2018-05-26 20:14:30 -04:00
|
|
|
res.tzname = Some(l[i].clone());
|
|
|
|
|
|
|
|
let tzname = res.tzname.clone().unwrap();
|
2018-08-03 23:40:54 -04:00
|
|
|
res.tzoffset = self.info.tzoffset_index(&tzname).map(|t| t as i32);
|
2018-05-26 20:14:30 -04:00
|
|
|
|
|
|
|
if i + 1 < len_l && (l[i + 1] == "+" || l[i + 1] == "-") {
|
|
|
|
// GMT+3
|
|
|
|
// According to dateutil docs - reverse the size, as GMT+3 means
|
|
|
|
// "my time +3 is GMT" not "GMT +3 is my time"
|
|
|
|
|
|
|
|
// TODO: Is there a better way of in-place modifying a vector?
|
|
|
|
let item = if l[i + 1] == "+" {
|
|
|
|
"-".to_owned()
|
|
|
|
} else {
|
2018-08-10 23:24:02 -04:00
|
|
|
"+".to_owned()
|
2018-05-26 20:14:30 -04:00
|
|
|
};
|
2019-11-13 23:18:37 -05:00
|
|
|
l[i + 1] = item;
|
2018-05-26 20:14:30 -04:00
|
|
|
|
|
|
|
res.tzoffset = None;
|
|
|
|
|
2018-08-03 23:40:54 -04:00
|
|
|
if self.info.utczone_index(&tzname) {
|
2018-05-26 20:14:30 -04:00
|
|
|
res.tzname = None;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else if res.hour.is_some() && (l[i] == "+" || l[i] == "-") {
|
|
|
|
let signal = if l[i] == "+" { 1 } else { -1 };
|
|
|
|
let len_li = l[i].len();
|
|
|
|
|
|
|
|
let mut hour_offset: Option<i32> = None;
|
|
|
|
let mut min_offset: Option<i32> = None;
|
|
|
|
|
|
|
|
// TODO: check that l[i + 1] is integer?
|
|
|
|
if len_li == 4 {
|
|
|
|
// -0300
|
2020-05-29 14:23:54 -04:00
|
|
|
hour_offset = Some(l[i + 1][..2].parse::<i32>()?);
|
|
|
|
min_offset = Some(l[i + 1][2..4].parse::<i32>()?);
|
2018-05-26 20:14:30 -04:00
|
|
|
} else if i + 2 < len_l && l[i + 2] == ":" {
|
|
|
|
// -03:00
|
2020-05-29 14:23:54 -04:00
|
|
|
hour_offset = Some(l[i + 1].parse::<i32>()?);
|
|
|
|
min_offset = Some(l[i + 3].parse::<i32>()?);
|
2018-05-26 20:14:30 -04:00
|
|
|
i += 2;
|
|
|
|
} else if len_li <= 2 {
|
|
|
|
// -[0]3
|
2018-08-10 23:24:02 -04:00
|
|
|
let range_len = min(l[i + 1].len(), 2);
|
2020-05-29 14:23:54 -04:00
|
|
|
hour_offset = Some(l[i + 1][..range_len].parse::<i32>()?);
|
2018-05-26 20:14:30 -04:00
|
|
|
min_offset = Some(0);
|
|
|
|
}
|
|
|
|
|
|
|
|
res.tzoffset =
|
|
|
|
Some(signal * (hour_offset.unwrap() * 3600 + min_offset.unwrap() * 60));
|
|
|
|
|
|
|
|
let tzname = res.tzname.clone();
|
2019-11-13 23:18:37 -05:00
|
|
|
if i + 5 < len_l
|
|
|
|
&& self.info.jump_index(&l[i + 2])
|
|
|
|
&& l[i + 3] == "("
|
|
|
|
&& l[i + 5] == ")"
|
|
|
|
&& 3 <= l[i + 4].len()
|
2018-08-10 23:24:02 -04:00
|
|
|
&& self.could_be_tzname(res.hour, &tzname, None, &l[i + 4])
|
2018-05-26 20:14:30 -04:00
|
|
|
{
|
|
|
|
// (GMT)
|
|
|
|
res.tzname = Some(l[i + 4].clone());
|
|
|
|
i += 4;
|
|
|
|
}
|
|
|
|
|
|
|
|
i += 1;
|
2018-08-03 23:40:54 -04:00
|
|
|
} else if !(self.info.jump_index(&l[i]) || fuzzy) {
|
2018-05-26 20:14:30 -04:00
|
|
|
return Err(ParseError::UnrecognizedToken(l[i].clone()));
|
|
|
|
} else {
|
|
|
|
skipped_idxs.push(i);
|
2018-05-25 00:00:15 -04:00
|
|
|
}
|
2018-05-26 20:14:30 -04:00
|
|
|
|
|
|
|
i += 1;
|
2018-05-25 00:00:15 -04:00
|
|
|
}
|
|
|
|
|
2018-05-26 20:14:30 -04:00
|
|
|
let (year, month, day) = ymd.resolve_ymd(yearfirst, dayfirst)?;
|
|
|
|
|
|
|
|
res.century_specified = ymd.century_specified;
|
2018-05-28 12:28:49 -04:00
|
|
|
res.year = year;
|
|
|
|
res.month = month;
|
|
|
|
res.day = day;
|
2018-05-26 20:14:30 -04:00
|
|
|
|
|
|
|
if !self.info.validate(&mut res) {
|
2018-07-24 23:28:38 -04:00
|
|
|
Err(ParseError::UnrecognizedFormat)
|
2018-05-26 20:14:30 -04:00
|
|
|
} else if fuzzy_with_tokens {
|
2018-07-03 01:02:27 -04:00
|
|
|
let skipped_tokens = self.recombine_skipped(skipped_idxs, l);
|
2018-05-26 20:14:30 -04:00
|
|
|
Ok((res, Some(skipped_tokens)))
|
|
|
|
} else {
|
|
|
|
Ok((res, None))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn could_be_tzname(
|
|
|
|
&self,
|
|
|
|
hour: Option<i32>,
|
2018-08-10 23:24:02 -04:00
|
|
|
tzname: &Option<String>,
|
2018-05-26 20:14:30 -04:00
|
|
|
tzoffset: Option<i32>,
|
|
|
|
token: &str,
|
|
|
|
) -> bool {
|
2018-06-12 22:22:30 -04:00
|
|
|
let all_ascii_upper = token
|
|
|
|
.chars()
|
|
|
|
.all(|c| 65u8 as char <= c && c <= 90u8 as char);
|
2018-08-10 23:24:02 -04:00
|
|
|
|
2019-11-13 23:18:37 -05:00
|
|
|
hour.is_some()
|
|
|
|
&& tzname.is_none()
|
|
|
|
&& tzoffset.is_none()
|
|
|
|
&& token.len() <= 5
|
2020-06-11 12:49:55 -04:00
|
|
|
&& (all_ascii_upper || self.info.utczone.contains_key(token))
|
2018-05-26 20:14:30 -04:00
|
|
|
}
|
|
|
|
|
2020-06-11 13:33:09 -04:00
|
|
|
#[allow(clippy::unnecessary_unwrap)]
|
2018-05-26 22:40:32 -04:00
|
|
|
fn ampm_valid(&self, hour: Option<i32>, ampm: Option<bool>, fuzzy: bool) -> ParseResult<bool> {
|
2018-08-10 23:24:02 -04:00
|
|
|
let mut val_is_ampm = !(fuzzy && ampm.is_some());
|
2018-05-26 22:40:32 -04:00
|
|
|
|
|
|
|
if hour.is_none() {
|
|
|
|
if fuzzy {
|
2018-07-08 21:51:02 -04:00
|
|
|
val_is_ampm = false;
|
2018-05-26 22:40:32 -04:00
|
|
|
} else {
|
2018-07-08 21:51:02 -04:00
|
|
|
return Err(ParseError::AmPmWithoutHour);
|
2018-05-26 22:40:32 -04:00
|
|
|
}
|
|
|
|
} else if !(0 <= hour.unwrap() && hour.unwrap() <= 12) {
|
|
|
|
if fuzzy {
|
2018-07-08 21:51:02 -04:00
|
|
|
val_is_ampm = false;
|
2018-05-26 22:40:32 -04:00
|
|
|
} else {
|
2018-07-08 22:01:14 -04:00
|
|
|
return Err(ParseError::ImpossibleTimestamp("Invalid hour"));
|
2018-05-26 22:40:32 -04:00
|
|
|
}
|
|
|
|
}
|
2018-07-08 21:51:02 -04:00
|
|
|
|
|
|
|
Ok(val_is_ampm)
|
2018-05-23 21:53:33 -04:00
|
|
|
}
|
|
|
|
|
2019-11-13 23:18:37 -05:00
|
|
|
fn build_naive(
|
|
|
|
&self,
|
|
|
|
res: &ParsingResult,
|
|
|
|
default: &NaiveDateTime,
|
|
|
|
) -> ParseResult<NaiveDateTime> {
|
2018-08-10 23:24:02 -04:00
|
|
|
let y = res.year.unwrap_or_else(|| default.year());
|
|
|
|
let m = res.month.unwrap_or_else(|| default.month() as i32) as u32;
|
2018-06-17 21:43:43 -04:00
|
|
|
|
2018-06-24 23:53:33 -04:00
|
|
|
let d_offset = if res.weekday.is_some() && res.day.is_none() {
|
2020-10-04 19:17:44 -04:00
|
|
|
let dow = day_of_week(y as u32, m, default.day())?;
|
2018-06-24 23:53:33 -04:00
|
|
|
|
|
|
|
// UNWRAP: We've already check res.weekday() is some
|
|
|
|
let actual_weekday = (res.weekday.unwrap() + 1) % 7;
|
|
|
|
let other = DayOfWeek::from_numeral(actual_weekday as u32);
|
2018-08-10 23:24:02 -04:00
|
|
|
Duration::days(i64::from(dow.difference(&other)))
|
2018-06-24 23:53:33 -04:00
|
|
|
} else {
|
|
|
|
Duration::days(0)
|
|
|
|
};
|
|
|
|
|
2018-05-26 22:40:32 -04:00
|
|
|
// TODO: Change month/day to u32
|
2020-10-04 19:17:44 -04:00
|
|
|
let d = NaiveDate::from_ymd_opt(
|
2018-06-17 21:43:43 -04:00
|
|
|
y,
|
|
|
|
m,
|
2019-11-13 23:18:37 -05:00
|
|
|
min(
|
|
|
|
res.day.unwrap_or(default.day() as i32) as u32,
|
|
|
|
days_in_month(y, m as i32)?,
|
|
|
|
),
|
2020-10-04 19:17:44 -04:00
|
|
|
)
|
|
|
|
.ok_or_else(|| ParseError::ImpossibleTimestamp("Invalid date range given"))?;
|
2018-05-26 22:40:32 -04:00
|
|
|
|
2018-06-24 23:53:33 -04:00
|
|
|
let d = d + d_offset;
|
|
|
|
|
2018-07-02 01:56:48 -04:00
|
|
|
let hour = res.hour.unwrap_or(default.hour() as i32) as u32;
|
|
|
|
let minute = res.minute.unwrap_or(default.minute() as i32) as u32;
|
|
|
|
let second = res.second.unwrap_or(default.second() as i32) as u32;
|
2023-03-24 22:12:57 -04:00
|
|
|
let nanosecond = res
|
|
|
|
.nanosecond
|
|
|
|
.unwrap_or(default.timestamp_subsec_nanos() as i64) as u32;
|
2019-11-13 23:18:37 -05:00
|
|
|
let t =
|
2023-03-24 22:12:57 -04:00
|
|
|
NaiveTime::from_hms_nano_opt(hour, minute, second, nanosecond).ok_or_else(|| {
|
2019-11-13 23:18:37 -05:00
|
|
|
if hour >= 24 {
|
|
|
|
ParseError::ImpossibleTimestamp("Invalid hour")
|
|
|
|
} else if minute >= 60 {
|
|
|
|
ParseError::ImpossibleTimestamp("Invalid minute")
|
|
|
|
} else if second >= 60 {
|
|
|
|
ParseError::ImpossibleTimestamp("Invalid second")
|
2023-03-24 22:12:57 -04:00
|
|
|
} else if nanosecond >= 2_000_000_000 {
|
2019-11-13 23:18:37 -05:00
|
|
|
ParseError::ImpossibleTimestamp("Invalid microsecond")
|
|
|
|
} else {
|
|
|
|
unreachable!();
|
|
|
|
}
|
|
|
|
})?;
|
2018-05-26 22:40:32 -04:00
|
|
|
|
2018-06-17 22:55:48 -04:00
|
|
|
Ok(NaiveDateTime::new(d, t))
|
2018-05-23 21:53:33 -04:00
|
|
|
}
|
|
|
|
|
2018-05-23 23:01:00 -04:00
|
|
|
fn build_tzaware(
|
|
|
|
&self,
|
2019-11-29 18:19:13 -05:00
|
|
|
_dt: &NaiveDateTime,
|
2018-05-23 23:01:00 -04:00
|
|
|
res: &ParsingResult,
|
2018-07-24 23:28:38 -04:00
|
|
|
tzinfos: &HashMap<String, i32>,
|
2018-05-28 11:03:11 -04:00
|
|
|
) -> ParseResult<Option<FixedOffset>> {
|
2018-06-03 23:48:56 -04:00
|
|
|
if let Some(offset) = res.tzoffset {
|
2023-03-24 22:29:55 -04:00
|
|
|
Ok(FixedOffset::east_opt(offset))
|
2018-06-03 23:48:56 -04:00
|
|
|
} else if res.tzoffset == None
|
2019-11-13 23:18:37 -05:00
|
|
|
&& (res.tzname == Some(" ".to_owned())
|
|
|
|
|| res.tzname == Some(".".to_owned())
|
|
|
|
|| res.tzname == Some("-".to_owned())
|
|
|
|
|| res.tzname == None)
|
2018-05-29 23:41:40 -04:00
|
|
|
{
|
2018-05-28 11:03:11 -04:00
|
|
|
Ok(None)
|
2018-06-07 23:49:11 -04:00
|
|
|
} else if res.tzname.is_some() && tzinfos.contains_key(res.tzname.as_ref().unwrap()) {
|
2023-03-24 22:29:55 -04:00
|
|
|
Ok(FixedOffset::east_opt(
|
2018-08-10 23:24:02 -04:00
|
|
|
*tzinfos.get(res.tzname.as_ref().unwrap()).unwrap(),
|
2023-03-24 22:29:55 -04:00
|
|
|
))
|
2019-11-29 17:58:40 -05:00
|
|
|
} else if let Some(tzname) = res.tzname.as_ref() {
|
2019-11-29 16:49:29 -05:00
|
|
|
println!("tzname {} identified but not understood.", tzname);
|
|
|
|
Ok(None)
|
2018-05-26 22:40:32 -04:00
|
|
|
} else {
|
|
|
|
Err(ParseError::TimezoneUnsupported)
|
|
|
|
}
|
2018-05-23 21:53:33 -04:00
|
|
|
}
|
2018-05-25 00:00:15 -04:00
|
|
|
|
2020-06-11 13:33:09 -04:00
|
|
|
#[allow(clippy::unnecessary_unwrap)]
|
2018-05-26 20:14:30 -04:00
|
|
|
fn parse_numeric_token(
|
|
|
|
&self,
|
2018-08-10 23:24:02 -04:00
|
|
|
tokens: &[String],
|
2018-05-26 20:14:30 -04:00
|
|
|
idx: usize,
|
|
|
|
info: &ParserInfo,
|
|
|
|
ymd: &mut YMD,
|
|
|
|
res: &mut ParsingResult,
|
|
|
|
fuzzy: bool,
|
2018-07-24 23:28:38 -04:00
|
|
|
) -> ParseResult<usize> {
|
2018-05-26 20:14:30 -04:00
|
|
|
let mut idx = idx;
|
2018-05-25 00:00:15 -04:00
|
|
|
let value_repr = &tokens[idx];
|
2018-05-26 20:14:30 -04:00
|
|
|
let mut value = Decimal::from_str(&value_repr).unwrap();
|
2018-05-25 00:00:15 -04:00
|
|
|
|
|
|
|
let len_li = value_repr.len();
|
|
|
|
let len_l = tokens.len();
|
|
|
|
|
|
|
|
// TODO: I miss the `x in y` syntax
|
|
|
|
// TODO: Decompose this logic a bit
|
2019-11-13 23:18:37 -05:00
|
|
|
if ymd.len() == 3
|
|
|
|
&& (len_li == 2 || len_li == 4)
|
|
|
|
&& res.hour.is_none()
|
2018-05-26 20:14:30 -04:00
|
|
|
&& (idx + 1 >= len_l
|
2018-08-03 23:40:54 -04:00
|
|
|
|| (tokens[idx + 1] != ":" && info.hms_index(&tokens[idx + 1]).is_none()))
|
2018-05-26 20:14:30 -04:00
|
|
|
{
|
2018-05-25 00:00:15 -04:00
|
|
|
// 1990101T32[59]
|
2018-05-26 20:14:30 -04:00
|
|
|
let s = &tokens[idx];
|
|
|
|
res.hour = s[0..2].parse::<i32>().ok();
|
2018-05-25 00:00:15 -04:00
|
|
|
|
2018-05-26 20:14:30 -04:00
|
|
|
if len_li == 4 {
|
|
|
|
res.minute = Some(s[2..4].parse::<i32>()?)
|
|
|
|
}
|
2018-08-10 23:24:02 -04:00
|
|
|
} else if len_li == 6 || (len_li > 6 && tokens[idx].find('.') == Some(6)) {
|
2018-05-26 20:14:30 -04:00
|
|
|
// YYMMDD or HHMMSS[.ss]
|
|
|
|
let s = &tokens[idx];
|
|
|
|
|
2018-08-10 23:24:02 -04:00
|
|
|
if ymd.len() == 0 && tokens[idx].find('.') == None {
|
2020-05-29 14:23:54 -04:00
|
|
|
ymd.append(s[0..2].parse::<i32>()?, &s[0..2], None)?;
|
|
|
|
ymd.append(s[2..4].parse::<i32>()?, &s[2..4], None)?;
|
|
|
|
ymd.append(s[4..6].parse::<i32>()?, &s[4..6], None)?;
|
2018-05-26 20:14:30 -04:00
|
|
|
} else {
|
|
|
|
// 19990101T235959[.59]
|
|
|
|
res.hour = s[0..2].parse::<i32>().ok();
|
|
|
|
res.minute = s[2..4].parse::<i32>().ok();
|
|
|
|
|
|
|
|
let t = self.parsems(&s[4..])?;
|
|
|
|
res.second = Some(t.0);
|
2023-03-24 22:12:57 -04:00
|
|
|
res.nanosecond = Some(t.1);
|
2018-05-26 20:14:30 -04:00
|
|
|
}
|
|
|
|
} else if vec![8, 12, 14].contains(&len_li) {
|
|
|
|
// YYMMDD
|
|
|
|
let s = &tokens[idx];
|
2020-06-11 13:11:52 -04:00
|
|
|
ymd.append(s[..4].parse::<i32>()?, &s[..4], Some(YMDLabel::Year))?;
|
2020-05-29 14:23:54 -04:00
|
|
|
ymd.append(s[4..6].parse::<i32>()?, &s[4..6], None)?;
|
|
|
|
ymd.append(s[6..8].parse::<i32>()?, &s[6..8], None)?;
|
2018-05-26 20:14:30 -04:00
|
|
|
|
|
|
|
if len_li > 8 {
|
|
|
|
res.hour = Some(s[8..10].parse::<i32>()?);
|
|
|
|
res.minute = Some(s[10..12].parse::<i32>()?);
|
|
|
|
|
|
|
|
if len_li > 12 {
|
|
|
|
res.second = Some(s[12..].parse::<i32>()?);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else if let Some(hms_idx) = self.find_hms_index(idx, tokens, info, true) {
|
|
|
|
// HH[ ]h or MM[ ]m or SS[.ss][ ]s
|
2018-05-29 23:41:40 -04:00
|
|
|
let (new_idx, hms) = self.parse_hms(idx, tokens, info, Some(hms_idx));
|
2021-08-23 22:36:03 -04:00
|
|
|
if let Some(hms) = hms {
|
|
|
|
self.assign_hms(res, value_repr, hms)?;
|
2018-05-26 20:14:30 -04:00
|
|
|
}
|
2018-05-29 23:41:40 -04:00
|
|
|
idx = new_idx;
|
2018-05-26 20:14:30 -04:00
|
|
|
} else if idx + 2 < len_l && tokens[idx + 1] == ":" {
|
|
|
|
// HH:MM[:SS[.ss]]
|
|
|
|
// TODO: Better story around Decimal handling
|
|
|
|
res.hour = Some(value.floor().to_i64().unwrap() as i32);
|
|
|
|
// TODO: Rescope `value` here?
|
2021-08-23 22:36:03 -04:00
|
|
|
value = self.to_decimal(&tokens[idx + 2])?;
|
2018-05-26 20:14:30 -04:00
|
|
|
let min_sec = self.parse_min_sec(value);
|
|
|
|
res.minute = Some(min_sec.0);
|
|
|
|
res.second = min_sec.1;
|
|
|
|
|
|
|
|
if idx + 4 < len_l && tokens[idx + 3] == ":" {
|
|
|
|
// TODO: (x, y) = (a, b) syntax?
|
|
|
|
let ms = self.parsems(&tokens[idx + 4]).unwrap();
|
|
|
|
res.second = Some(ms.0);
|
2023-03-24 22:12:57 -04:00
|
|
|
res.nanosecond = Some(ms.1);
|
2018-05-26 20:14:30 -04:00
|
|
|
|
|
|
|
idx += 2;
|
|
|
|
}
|
|
|
|
idx += 2;
|
|
|
|
} else if idx + 1 < len_l
|
|
|
|
&& (tokens[idx + 1] == "-" || tokens[idx + 1] == "/" || tokens[idx + 1] == ".")
|
|
|
|
{
|
|
|
|
// TODO: There's got to be a better way of handling the condition above
|
|
|
|
let sep = &tokens[idx + 1];
|
2020-05-29 14:23:54 -04:00
|
|
|
ymd.append(value_repr.parse::<i32>()?, &value_repr, None)?;
|
2018-05-26 20:14:30 -04:00
|
|
|
|
2018-08-03 23:40:54 -04:00
|
|
|
if idx + 2 < len_l && !info.jump_index(&tokens[idx + 2]) {
|
2018-05-26 20:14:30 -04:00
|
|
|
if let Ok(val) = tokens[idx + 2].parse::<i32>() {
|
2018-07-03 01:02:27 -04:00
|
|
|
ymd.append(val, &tokens[idx + 2], None)?;
|
2018-08-03 23:40:54 -04:00
|
|
|
} else if let Some(val) = info.month_index(&tokens[idx + 2]) {
|
2018-07-03 01:02:27 -04:00
|
|
|
ymd.append(val as i32, &tokens[idx + 2], Some(YMDLabel::Month))?;
|
2018-05-26 20:14:30 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
if idx + 3 < len_l && &tokens[idx + 3] == sep {
|
2018-08-03 23:40:54 -04:00
|
|
|
if let Some(value) = info.month_index(&tokens[idx + 4]) {
|
2018-07-03 01:02:27 -04:00
|
|
|
ymd.append(value as i32, &tokens[idx + 4], Some(YMDLabel::Month))?;
|
2018-08-10 23:24:02 -04:00
|
|
|
} else if let Ok(val) = tokens[idx + 4].parse::<i32>() {
|
2019-11-13 23:18:37 -05:00
|
|
|
ymd.append(val, &tokens[idx + 4], None)?;
|
|
|
|
} else {
|
|
|
|
return Err(ParseError::UnrecognizedFormat);
|
|
|
|
}
|
2018-05-26 20:14:30 -04:00
|
|
|
|
|
|
|
idx += 2;
|
|
|
|
}
|
|
|
|
|
|
|
|
idx += 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
idx += 1
|
2018-08-03 23:40:54 -04:00
|
|
|
} else if idx + 1 >= len_l || info.jump_index(&tokens[idx + 1]) {
|
|
|
|
if idx + 2 < len_l && info.ampm_index(&tokens[idx + 2]).is_some() {
|
2018-05-26 20:14:30 -04:00
|
|
|
let hour = value.to_i64().unwrap() as i32;
|
2018-08-03 23:40:54 -04:00
|
|
|
let ampm = info.ampm_index(&tokens[idx + 2]).unwrap();
|
2018-05-26 20:14:30 -04:00
|
|
|
res.hour = Some(self.adjust_ampm(hour, ampm));
|
2018-07-08 15:11:29 -04:00
|
|
|
idx += 1;
|
2018-05-28 11:03:11 -04:00
|
|
|
} else {
|
2021-08-23 22:36:03 -04:00
|
|
|
//let value = value.floor().to_i32().ok_or(Err(ParseError::InvalidNumeric()))
|
|
|
|
let value = value.floor().to_i32().ok_or_else(|| ParseError::InvalidNumeric(value_repr.to_owned()))?;
|
|
|
|
ymd.append(value, &value_repr, None)?;
|
2018-05-26 20:14:30 -04:00
|
|
|
}
|
2018-07-08 15:11:29 -04:00
|
|
|
|
|
|
|
idx += 1;
|
2018-08-03 23:40:54 -04:00
|
|
|
} else if info.ampm_index(&tokens[idx + 1]).is_some()
|
2018-05-26 20:14:30 -04:00
|
|
|
&& (*ZERO <= value && value < *TWENTY_FOUR)
|
|
|
|
{
|
|
|
|
// 12am
|
|
|
|
let hour = value.to_i64().unwrap() as i32;
|
2018-08-03 23:40:54 -04:00
|
|
|
res.hour = Some(self.adjust_ampm(hour, info.ampm_index(&tokens[idx + 1]).unwrap()));
|
2018-05-26 20:14:30 -04:00
|
|
|
idx += 1;
|
|
|
|
} else if ymd.could_be_day(value.to_i64().unwrap() as i32) {
|
2018-07-03 01:02:27 -04:00
|
|
|
ymd.append(value.to_i64().unwrap() as i32, &value_repr, None)?;
|
2018-05-26 20:14:30 -04:00
|
|
|
} else if !fuzzy {
|
2018-07-24 23:28:38 -04:00
|
|
|
return Err(ParseError::UnrecognizedFormat);
|
2018-05-25 00:00:15 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok(idx)
|
|
|
|
}
|
2018-05-26 20:14:30 -04:00
|
|
|
|
2018-05-26 22:40:32 -04:00
|
|
|
fn adjust_ampm(&self, hour: i32, ampm: bool) -> i32 {
|
|
|
|
if hour < 12 && ampm {
|
2018-05-26 20:14:30 -04:00
|
|
|
hour + 12
|
2018-05-29 23:41:40 -04:00
|
|
|
} else if hour == 12 && !ampm {
|
2018-05-26 20:14:30 -04:00
|
|
|
0
|
|
|
|
} else {
|
|
|
|
hour
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-24 22:12:57 -04:00
|
|
|
fn parsems(&self, seconds_str: &str) -> ParseResult<(i32, i64)> {
|
2018-08-10 23:24:02 -04:00
|
|
|
if seconds_str.contains('.') {
|
|
|
|
let split: Vec<&str> = seconds_str.split('.').collect();
|
2018-05-26 20:14:30 -04:00
|
|
|
let (i, f): (&str, &str) = (split[0], split[1]);
|
|
|
|
|
|
|
|
let i_parse = i.parse::<i32>()?;
|
2023-03-24 22:12:57 -04:00
|
|
|
let f_parse = ljust(f, 9, '0').parse::<i64>()?;
|
2018-05-26 20:14:30 -04:00
|
|
|
Ok((i_parse, f_parse))
|
|
|
|
} else {
|
|
|
|
Ok((seconds_str.parse::<i32>()?, 0))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn find_hms_index(
|
|
|
|
&self,
|
|
|
|
idx: usize,
|
2018-08-10 23:24:02 -04:00
|
|
|
tokens: &[String],
|
2018-05-26 20:14:30 -04:00
|
|
|
info: &ParserInfo,
|
|
|
|
allow_jump: bool,
|
|
|
|
) -> Option<usize> {
|
|
|
|
let len_l = tokens.len();
|
|
|
|
let mut hms_idx = None;
|
|
|
|
|
2018-06-29 22:50:39 -04:00
|
|
|
// There's a super weird edge case that can happen
|
|
|
|
// because Python safely handles negative array indices,
|
|
|
|
// and Rust (because of usize) does not.
|
|
|
|
let idx_minus_two = if idx == 1 && len_l > 0 {
|
|
|
|
len_l - 1
|
|
|
|
} else if idx == 0 && len_l > 1 {
|
|
|
|
len_l - 2
|
|
|
|
} else if idx > 1 {
|
|
|
|
idx - 2
|
2019-11-13 23:18:37 -05:00
|
|
|
} else if len_l == 0 {
|
2018-06-29 22:50:39 -04:00
|
|
|
panic!("Attempting to find_hms_index() wih no tokens.");
|
|
|
|
} else {
|
|
|
|
0
|
|
|
|
};
|
|
|
|
|
2018-08-03 23:40:54 -04:00
|
|
|
if idx + 1 < len_l && info.hms_index(&tokens[idx + 1]).is_some() {
|
2018-05-26 20:14:30 -04:00
|
|
|
hms_idx = Some(idx + 1)
|
2019-11-13 23:18:37 -05:00
|
|
|
} else if allow_jump
|
|
|
|
&& idx + 2 < len_l
|
|
|
|
&& tokens[idx + 1] == " "
|
2018-08-03 23:40:54 -04:00
|
|
|
&& info.hms_index(&tokens[idx + 2]).is_some()
|
2018-05-26 20:14:30 -04:00
|
|
|
{
|
|
|
|
hms_idx = Some(idx + 2)
|
2018-08-03 23:40:54 -04:00
|
|
|
} else if idx > 0 && info.hms_index(&tokens[idx - 1]).is_some() {
|
2018-05-26 20:14:30 -04:00
|
|
|
hms_idx = Some(idx - 1)
|
2019-11-13 23:18:37 -05:00
|
|
|
} else if len_l > 0
|
|
|
|
&& idx > 0
|
|
|
|
&& idx == len_l - 1
|
|
|
|
&& tokens[idx - 1] == " "
|
2018-08-03 23:40:54 -04:00
|
|
|
&& info.hms_index(&tokens[idx_minus_two]).is_some()
|
2018-05-26 20:14:30 -04:00
|
|
|
{
|
|
|
|
hms_idx = Some(idx - 2)
|
|
|
|
}
|
|
|
|
|
|
|
|
hms_idx
|
|
|
|
}
|
|
|
|
|
2020-06-11 13:33:09 -04:00
|
|
|
#[allow(clippy::unnecessary_unwrap)]
|
2018-05-26 20:14:30 -04:00
|
|
|
fn parse_hms(
|
|
|
|
&self,
|
|
|
|
idx: usize,
|
2018-08-10 23:24:02 -04:00
|
|
|
tokens: &[String],
|
2018-05-26 20:14:30 -04:00
|
|
|
info: &ParserInfo,
|
|
|
|
hms_index: Option<usize>,
|
|
|
|
) -> (usize, Option<usize>) {
|
|
|
|
if hms_index.is_none() {
|
|
|
|
(idx, None)
|
|
|
|
} else if hms_index.unwrap() > idx {
|
|
|
|
(
|
|
|
|
hms_index.unwrap(),
|
2018-08-03 23:40:54 -04:00
|
|
|
info.hms_index(&tokens[hms_index.unwrap()]),
|
2018-05-26 20:14:30 -04:00
|
|
|
)
|
|
|
|
} else {
|
|
|
|
(
|
|
|
|
idx,
|
2018-08-03 23:40:54 -04:00
|
|
|
info.hms_index(&tokens[hms_index.unwrap()]).map(|u| u + 1),
|
2018-05-26 20:14:30 -04:00
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-23 22:36:03 -04:00
|
|
|
fn assign_hms(&self, res: &mut ParsingResult, value_repr: &str, hms: usize) -> ParseResult<()> {
|
|
|
|
let value = self.to_decimal(value_repr)?;
|
2018-05-26 20:14:30 -04:00
|
|
|
|
|
|
|
if hms == 0 {
|
2021-08-23 22:36:03 -04:00
|
|
|
res.hour = value.to_i32();
|
2018-05-29 23:41:40 -04:00
|
|
|
if !close_to_integer(&value) {
|
2018-05-26 20:14:30 -04:00
|
|
|
res.minute = Some((*SIXTY * (value % *ONE)).to_i64().unwrap() as i32);
|
|
|
|
}
|
|
|
|
} else if hms == 1 {
|
|
|
|
let (min, sec) = self.parse_min_sec(value);
|
2018-05-29 23:41:40 -04:00
|
|
|
res.minute = Some(min);
|
|
|
|
res.second = sec;
|
2018-05-26 20:14:30 -04:00
|
|
|
} else if hms == 2 {
|
|
|
|
let (sec, micro) = self.parsems(value_repr).unwrap();
|
2018-05-29 23:41:40 -04:00
|
|
|
res.second = Some(sec);
|
2023-03-24 22:12:57 -04:00
|
|
|
res.nanosecond = Some(micro);
|
2018-05-26 20:14:30 -04:00
|
|
|
}
|
2021-08-23 22:36:03 -04:00
|
|
|
|
|
|
|
Ok(())
|
2018-05-26 20:14:30 -04:00
|
|
|
}
|
|
|
|
|
2021-08-23 22:36:03 -04:00
|
|
|
fn to_decimal(&self, value: &str) -> ParseResult<Decimal> {
|
|
|
|
Decimal::from_str(value).or_else(|_| Err(ParseError::InvalidNumeric(value.to_owned())))
|
2018-05-26 20:14:30 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn parse_min_sec(&self, value: Decimal) -> (i32, Option<i32>) {
|
2018-07-08 21:16:43 -04:00
|
|
|
// UNWRAP: i64 guaranteed to be fine because of preceding floor
|
2018-05-26 20:14:30 -04:00
|
|
|
let minute = value.floor().to_i64().unwrap() as i32;
|
|
|
|
let mut second = None;
|
|
|
|
|
2018-06-08 00:06:37 -04:00
|
|
|
let sec_remainder = value - value.floor();
|
2018-05-26 20:14:30 -04:00
|
|
|
if sec_remainder != *ZERO {
|
|
|
|
second = Some((*SIXTY * sec_remainder).floor().to_i64().unwrap() as i32);
|
|
|
|
}
|
|
|
|
|
|
|
|
(minute, second)
|
|
|
|
}
|
2018-07-03 01:02:27 -04:00
|
|
|
|
|
|
|
fn recombine_skipped(&self, skipped_idxs: Vec<usize>, tokens: Vec<String>) -> Vec<String> {
|
|
|
|
let mut skipped_tokens: Vec<String> = vec![];
|
|
|
|
|
|
|
|
let mut sorted_idxs = skipped_idxs.clone();
|
|
|
|
sorted_idxs.sort();
|
|
|
|
|
|
|
|
for (i, idx) in sorted_idxs.iter().enumerate() {
|
|
|
|
if i > 0 && idx - 1 == skipped_idxs[i - 1] {
|
|
|
|
// UNWRAP: Having an initial value and unconditional push at end guarantees value
|
|
|
|
let mut t = skipped_tokens.pop().unwrap();
|
2018-08-10 23:24:02 -04:00
|
|
|
t.push_str(tokens[*idx].as_ref());
|
2018-07-03 01:02:27 -04:00
|
|
|
skipped_tokens.push(t);
|
|
|
|
} else {
|
2018-08-10 23:24:02 -04:00
|
|
|
skipped_tokens.push(tokens[*idx].to_owned());
|
2018-07-03 01:02:27 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
skipped_tokens
|
|
|
|
}
|
2018-05-23 21:53:33 -04:00
|
|
|
}
|
|
|
|
|
2018-05-26 20:14:30 -04:00
|
|
|
fn close_to_integer(value: &Decimal) -> bool {
|
|
|
|
value % *ONE == *ZERO
|
|
|
|
}
|
|
|
|
|
|
|
|
fn ljust(s: &str, chars: usize, replace: char) -> String {
|
|
|
|
if s.len() >= chars {
|
|
|
|
s[..chars].to_owned()
|
|
|
|
} else {
|
|
|
|
format!("{}{}", s, replace.to_string().repeat(chars - s.len()))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-01 23:27:49 -04:00
|
|
|
/// Main entry point for using `dtparse`. The parse function is responsible for
|
|
|
|
/// taking in a string representing some time value, and turning it into
|
|
|
|
/// a timestamp with optional timezone information if it can be identified.
|
2019-11-13 23:18:37 -05:00
|
|
|
///
|
2018-08-01 23:27:49 -04:00
|
|
|
/// The default implementation assumes English values for names of months,
|
|
|
|
/// days of the week, etc. It is equivalent to Python's `dateutil.parser.parse()`
|
2018-05-29 21:07:22 -04:00
|
|
|
pub fn parse(timestr: &str) -> ParseResult<(NaiveDateTime, Option<FixedOffset>)> {
|
2018-09-17 22:19:30 -04:00
|
|
|
let res = DEFAULT_PARSER.parse(
|
2018-06-12 22:22:30 -04:00
|
|
|
timestr,
|
|
|
|
None,
|
|
|
|
None,
|
|
|
|
false,
|
|
|
|
false,
|
|
|
|
None,
|
|
|
|
false,
|
2018-07-24 23:28:38 -04:00
|
|
|
&HashMap::new(),
|
2018-06-12 22:22:30 -04:00
|
|
|
)?;
|
2018-06-03 16:11:51 -04:00
|
|
|
|
|
|
|
Ok((res.0, res.1))
|
2018-05-23 23:01:00 -04:00
|
|
|
}
|