From 011cc78d3c787b18956c29da0f026a25d3ffd6f2 Mon Sep 17 00:00:00 2001 From: undali Date: Wed, 7 Jun 2023 16:17:52 +0400 Subject: [PATCH] Handle panic while converting to Duration --- src/lib.rs | 9 ++++++--- tests/simple.rs | 6 ++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 21a4b46..c1c4f43 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,6 +8,7 @@ use chrono::{Duration, Local, NaiveDate, Utc}; use regex::{Error as RegexError, Regex}; use std::error::Error; use std::fmt::{self, Display}; +use std::panic; #[derive(Debug, PartialEq)] pub enum ParseDurationError { @@ -157,7 +158,7 @@ pub fn from_str_at_date(date: NaiveDate, s: &str) -> Result Duration::days(value * 365), "months" | "month" => Duration::days(value * 30), "fortnights" | "fortnight" => Duration::weeks(value * 2), @@ -169,8 +170,10 @@ pub fn from_str_at_date(date: NaiveDate, s: &str) -> Result Duration::days(-1), "tomorrow" => Duration::days(1), "now" | "today" => Duration::zero(), - _ => return Err(ParseDurationError::InvalidInput), - }; + _ => panic!("Invalid Input"), + }) + .or(Err(ParseDurationError::InvalidInput))?; + let neg_duration = -duration; total_duration = match total_duration.checked_add(if is_ago { &neg_duration } else { &duration }) { diff --git a/tests/simple.rs b/tests/simple.rs index 366f318..247f2d7 100644 --- a/tests/simple.rs +++ b/tests/simple.rs @@ -146,3 +146,9 @@ fn test_invalid_input_at_date() { let result = from_str_at_date(today, "invalid 1r"); assert_eq!(result, Err(ParseDurationError::InvalidInput)); } + +#[test] +fn test_large_input() { + let result = humantime_to_duration::from_str("8888888888888h"); + assert_eq!(result, Err(ParseDurationError::InvalidInput)); +}