| 1 | //! Utility functions for parsing rrule input. |
| 2 | use std::str::FromStr; |
| 3 | |
| 4 | /// Attempts to convert a comma separated `&str` to a `Vec<T>` of unique and sorted values. |
| 5 | /// The function accepts a closure which can be used to validate the values which are parsed. |
| 6 | pub(crate) fn parse_str_to_vec<T: FromStr + Ord + PartialEq + Copy, F: Fn(T) -> bool>( |
| 7 | val: &str, |
| 8 | accept: F, |
| 9 | ) -> Result<Vec<T>, String> { |
| 10 | if val.is_empty() { |
| 11 | return Ok(vec![]); |
| 12 | } |
| 13 | |
| 14 | let mut parsed_vals = vec![]; |
| 15 | for val in val.split(',') { |
| 16 | let parsed_val = val.parse().map_err(|_| val.to_string())?; |
| 17 | if accept(parsed_val) { |
| 18 | parsed_vals.push(parsed_val); |
| 19 | } else { |
| 20 | return Err(val.into()); |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | parsed_vals.sort(); |
| 25 | parsed_vals.dedup(); |
| 26 | |
| 27 | Ok(parsed_vals) |
| 28 | } |
| 29 | |
| 30 | #[cfg(test)] |
| 31 | mod tests { |
| 32 | use super::parse_str_to_vec; |
| 33 | |
| 34 | #[test] |
| 35 | fn parses_str_to_vec() { |
| 36 | const INVALID_VALUE: usize = 17; |
| 37 | let accept_fn = |val: usize| val != 17; |
| 38 | let tests = [ |
| 39 | ("", Ok(vec![])), |
| 40 | ("1,2,3", Ok(vec![1, 2, 3])), |
| 41 | ("3,2,1", Ok(vec![1, 2, 3])), |
| 42 | ("3,2,1,4", Ok(vec![1, 2, 3, 4])), |
| 43 | ("3,2,1,4,3,4,4,3,1", Ok(vec![1, 2, 3, 4])), |
| 44 | ( |
| 45 | &format!("14,15,16,{},18", INVALID_VALUE), |
| 46 | Err(format!("{}", INVALID_VALUE)), |
| 47 | ), |
| 48 | ]; |
| 49 | for (input, expected_output) in tests { |
| 50 | let output = parse_str_to_vec(input, accept_fn); |
| 51 | assert_eq!(output, expected_output); |
| 52 | } |
| 53 | } |
| 54 | } |