From 530f8e673619006f65bd0f5fb585222e9365439d Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 4 Nov 2024 01:06:00 +0100 Subject: [PATCH] Adds a new entry function to parse Adds more badges and a benchmark --- Cargo.toml | 9 ++++ README.md | 2 +- TODO.md | 3 +- badge.svg | 23 --------- badges/release.svg | 1 + badges/test.svg | 1 + badges/test_cov.svg | 1 + benches/parser_benchmark.rs | 23 +++++++++ src/date/date_tools.rs | 98 ++++++++++++++++++++++++++++++++++--- src/date/mod.rs | 26 +++++++++- 10 files changed, 153 insertions(+), 34 deletions(-) delete mode 100644 badge.svg create mode 100644 badges/release.svg create mode 100644 badges/test.svg create mode 100644 badges/test_cov.svg create mode 100644 benches/parser_benchmark.rs diff --git a/Cargo.toml b/Cargo.toml index 11abbc0..e29711f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,7 @@ uuid = { version = "1.11.0", features = ["v4", "v7", "serde", "fast-rng"] } simplelog = { version = "0.12.2", features = ["paris"] } log = { version = "0.4.22", features = ["std"] } nom = "7.1.3" +criterion = "0.5" [profile.dev] debug = 0 @@ -38,3 +39,11 @@ path = "src/main.rs" [lib] name = "idlefox" path = "src/lib.rs" + + +[dev-dependencies] +criterion = { version = "0.5", features = ["html_reports"] } + +[[bench]] +name = "parser_benchmark" +harness = false diff --git a/README.md b/README.md index 0d457ef..982fec7 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # idlefox -![code coverage](badge.svg) +![code coverage](badges/test_cov.svg) ![version](badges/release.svg) ![code coverage](badges/test.svg) IdleFox is a feature-rich Discord bot designed to streamline the process of finding meeting dates, organizing events, and making decisions among multiple options. With its user-friendly commands and robust command system, IdleFox helps facilitate effective communication within server communities. diff --git a/TODO.md b/TODO.md index 6937c57..2547fcb 100644 --- a/TODO.md +++ b/TODO.md @@ -26,9 +26,10 @@ # Tasks ## Dan -* [ ] Finish testing to reach 100% coverage +* [x] Finish testing to reach 100% coverage * [ ] Implement Resilience & Recovery * [x] Parse date mini language +* [ ] Migrate the todo into gitea ## Vky * [x] Write documentation for all functions in IO.rs diff --git a/badge.svg b/badge.svg deleted file mode 100644 index 750f2df..0000000 --- a/badge.svg +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - coverage - coverage - 100 - 100 - - \ No newline at end of file diff --git a/badges/release.svg b/badges/release.svg new file mode 100644 index 0000000..99d9d9d --- /dev/null +++ b/badges/release.svg @@ -0,0 +1 @@ +release: v0.1.0releasev0.1.0 diff --git a/badges/test.svg b/badges/test.svg new file mode 100644 index 0000000..a34aaf8 --- /dev/null +++ b/badges/test.svg @@ -0,0 +1 @@ +build: passingbuildpassing diff --git a/badges/test_cov.svg b/badges/test_cov.svg new file mode 100644 index 0000000..f21e8b5 --- /dev/null +++ b/badges/test_cov.svg @@ -0,0 +1 @@ +test-coverage: 100%test-coverage100% diff --git a/benches/parser_benchmark.rs b/benches/parser_benchmark.rs new file mode 100644 index 0000000..c7aecd3 --- /dev/null +++ b/benches/parser_benchmark.rs @@ -0,0 +1,23 @@ +use chrono::NaiveDate; +use criterion::{criterion_group, criterion_main, Criterion}; +use idlefox::date::parse_date_list; +use std::hint::black_box; + +fn complex_date_parse(input: &str) -> usize { + let context = NaiveDate::from_ymd_opt(2023, 10, 1); + let list = parse_date_list(input, context).unwrap(); + list.len() +} + +fn criterion_benchmark(c: &mut Criterion) { + c.bench_function("complex_date_parse", |b| { + b.iter(|| { + complex_date_parse(black_box( + "Oct 5, Nov 15 - 18, sat, mon , tue-fri and some other text", + )) + }) + }); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/src/date/date_tools.rs b/src/date/date_tools.rs index e2f85ae..616e595 100644 --- a/src/date/date_tools.rs +++ b/src/date/date_tools.rs @@ -1,8 +1,12 @@ //! Utilities to handle date and relative date selection + use crate::error_handling::IdleError; use chrono::{Datelike, Duration, Local, Month, Months, NaiveDate, Weekday}; -use super::date_parse::{DateObject, DatePoint}; +use super::{ + date_parse::{DateObject, DatePoint}, + parse_str_into_date, +}; /// Returns the date corresponding to the implicit Weekday /// @@ -146,11 +150,19 @@ pub enum NaiveDateObject { /// A collection of [NaiveDateObject]s, allowing for sequential and random access to their start dates. /// -/// This struct can be used to iterate over a list of dates in order or access any date by its index. +/// This struct provides an abstraction over a list of date objects, enabling both sequential iteration +/// over the dates in order or direct access to any date by its index. The structure is designed to handle +/// different sources of date information, allowing for flexible data manipulation based on the provided dates. +/// +/// # Example +/// + #[cfg_attr(test, derive(PartialEq, Debug))] pub struct NaiveDateList { /// The inner vector inner: Vec, + /// The leftover, unparsed string + unparsed: Option, } impl DateObject { @@ -193,8 +205,11 @@ impl DateObject { impl NaiveDateList { /// Creates a new [NaiveDateList] from an existing vector of [NaiveDateObject]s. - pub fn new(inner: Vec) -> Self { - Self { inner } + pub fn new(inner: Vec, unparsed: Option<&str>) -> Self { + Self { + inner, + unparsed: unparsed.map(|v| v.to_string()), + } } /// Returns the number of dates in this [NaiveDateList]. @@ -230,29 +245,79 @@ impl NaiveDateList { /// month: Some(chrono::Month::January), /// }; /// let next_valid_date_object = DateObject::Single(date_point); - /// let list = NaiveDateList::from_context(vec![next_valid_date_object], Some(today)); + /// let list = NaiveDateList::from_context(vec![next_valid_date_object], Some(today), None); /// assert!(list.is_ok()); /// ``` pub fn from_context( inner: Vec, context: Option, + unparsed: Option<&str>, ) -> Result { let mut new = Vec::new(); for elem in inner { new.push(elem.to_naive_date_object(context)?); } - Ok(Self { inner: new }) + Ok(Self { + inner: new, + unparsed: unparsed.map(|v| v.to_owned()), + }) } } +// // TODO: If needed, make an iterator over all dates that this list of date encompasses // impl IntoIterator for NaiveDateList { -// type Item = NaiveDate; +// type Item = NaiveDateObject; // type IntoIter = std::vec::IntoIter; // fn into_iter(self) -> Self::IntoIter { // self.inner.into_iter() // } // } + +/// This function parses a given input string representing date information and returns a `NaiveDateList`, +/// which is a collection of sequential or random accessible date objects. If there are any unparsed parts +/// left after processing the input, they can be retrieved using the `unparsed` method on the returned `Result`. +/// +/// The function uses the context provided to resolve any relative dates within the input string. +/// +/// # Arguments +/// +/// * `input` - A string slice containing the date information to be parsed. This string may include various date formats, +/// single or range of dates, and possibly unparsed text. +/// * `context` - An optional NaiveDate that provides a context for resolving relative dates within the input. If no context +/// is provided, the function will attempt to use today's date as a fallback. +/// +/// # Returns +/// +/// A Result containing a `NaiveDateList` on success or an `IdleError` if parsing fails. The `Result` also includes any +/// unparsed text that was left over after processing the input string. +/// +/// # Examples +/// +/// ``` +/// # use idlefox::date::parse_date_list; +/// # use chrono::NaiveDate; +/// let input = "Oct 5, Nov 15 - 18, sat, mon , tue-fry and some other text"; +/// let context = NaiveDate::from_ymd_opt(2023, 10, 1); +/// let result = parse_date_list(input, context); +/// assert!(result.is_ok()); +/// match result { +/// Ok(date_list) => println!("Parsed dates: {}", date_list.len()), +/// Err(e) => eprintln!("Error parsing dates: {}", e), +/// } +/// ``` +pub fn parse_date_list( + input: &str, + context: Option, +) -> Result { + let (leftover, objects) = match parse_str_into_date(input)? { + ("", objects) => (None, objects), + (leftover, objects) => (Some(leftover), objects), + }; + + NaiveDateList::from_context(objects, context, leftover) +} + #[cfg(test)] pub(crate) mod tests { @@ -370,7 +435,7 @@ pub(crate) mod tests { } ); - let vec_obj = NaiveDateList::new(vec![date_obj.clone()]); + let vec_obj = NaiveDateList::new(vec![date_obj.clone()], None); assert_eq!(vec_obj.len(), 1); assert!(!vec_obj.is_empty()); assert_eq!(vec_obj.get(0).unwrap(), &date_obj); @@ -378,6 +443,7 @@ pub(crate) mod tests { assert!(!NaiveDateList::from_context( vec![DateObject::Single(date_a), DateObject::Single(date_a)], context, + None, ) .unwrap() .is_empty()); @@ -390,7 +456,23 @@ pub(crate) mod tests { DateObject::Single(date_a) ], context, + None, ) .is_err()); } + + #[test] + fn test_date_list() { + use chrono::NaiveDate; + let input = "Oct 5, Nov 15 - 18, sat, mon , tue-fri and some other text"; + let context = NaiveDate::from_ymd_opt(2023, 10, 1); + let list = parse_date_list(input, context).unwrap(); + assert_eq!(list.unparsed, Some("and some other text".to_string())); + assert_eq!(list.len(), 5); + + let input = "Oct 5, Nov 15"; + let list = parse_date_list(input, None).unwrap(); + assert_eq!(list.unparsed, None); + assert_eq!(list.len(), 2); + } } diff --git a/src/date/mod.rs b/src/date/mod.rs index 8326e3f..77062f2 100644 --- a/src/date/mod.rs +++ b/src/date/mod.rs @@ -8,6 +8,30 @@ //! - `date_tools`: This submodule offers utility functions for working with dates. //! It's main goal is do give a context for a subjective and incomplete date to transform it into a [chrono::NaiveDate] type from the chrono crate. //! +//! # Functions +//! +//! The following functions are re-exported from the `date_tools` submodule: +//! +//! - [parse_date_list]: This function parses a given input string representing date information and returns a `NaiveDateList`, +//! which is a collection of sequential or random accessible date objects. If there are any unparsed parts +//! left after processing the input, they can be retrieved using the `unparsed` method on the returned `Result`. +//! +//! The function uses the context provided to resolve any relative dates within the input string. +//! +//! # Examples +//! +//! ``` +//! # use idlefox::date::parse_date_list; +//! # use chrono::NaiveDate; +//! let input = "Oct 5, Nov 15 - 18, sat, mon , tue-fry and some other text"; +//! let context = NaiveDate::from_ymd_opt(2023, 10, 1); +//! let result = parse_date_list(input, context); +//! assert!(result.is_ok()); +//! match result { +//! Ok(date_list) => println!("Parsed dates: {}", date_list.len()), +//! Err(e) => eprintln!("Error parsing dates: {}", e), +//! } +//! ``` #![allow(dead_code)] // All structures @@ -29,6 +53,6 @@ pub mod date_tools; // Republishing important functions pub use date_parse::parse_str_into_date; -// TODO: Add these final user function +pub use date_tools::parse_date_list; // pub use date_tools::naivelistfromstr; // pub use date_tools::naivedayfromstr;