✨ feat(retention): enhance message age with parsing and validation
- add `TryFrom<&str>` implementation for `MessageAge` - allows creating `MessageAge` from string slices - returns `Error` for invalid formats - improve `MessageAge::new` to return a `Result` - changes error type to `Error` enum - add `Error::InvalidMessageAge` for specific message age errors - mark `MessageAge::parse` and other methods as `must_use` - use byte string literals for character matching in `parse` - update error messages to include the invalid input value - add `#[derive(Hash)]` to `MessageAge`
This commit is contained in:
committed by
Jeremiah Russell
parent
5c2124ead4
commit
051507856a
@@ -1,5 +1,7 @@
|
||||
use std::fmt::Display;
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Message age specification for retention policies.
|
||||
///
|
||||
/// Defines different time periods that can be used to specify how old messages
|
||||
@@ -19,7 +21,7 @@ use std::fmt::Display;
|
||||
/// // Use with retention policy
|
||||
/// println!("Messages older than {} will be processed", months);
|
||||
/// ```
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum MessageAge {
|
||||
/// Number of days to retain the message
|
||||
///
|
||||
@@ -71,7 +73,7 @@ impl Display for MessageAge {
|
||||
}
|
||||
|
||||
impl MessageAge {
|
||||
/// Create a new MessageAge from a period string and count.
|
||||
/// Create a new `MessageAge` from a period string and count.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
@@ -101,9 +103,11 @@ impl MessageAge {
|
||||
/// Returns an error if:
|
||||
/// - The period string is not recognized
|
||||
/// - The count is negative or zero
|
||||
pub fn new(period: &str, count: i64) -> Result<Self, String> {
|
||||
pub fn new(period: &str, count: i64) -> Result<Self> {
|
||||
if count <= 0 {
|
||||
return Err(format!("Count must be positive, got: {}", count));
|
||||
return Err(Error::InvalidMessageAge(format!(
|
||||
"Count must be positive, got: {count}"
|
||||
)));
|
||||
}
|
||||
|
||||
match period.to_lowercase().as_str() {
|
||||
@@ -111,11 +115,13 @@ impl MessageAge {
|
||||
"weeks" => Ok(MessageAge::Weeks(count)),
|
||||
"months" => Ok(MessageAge::Months(count)),
|
||||
"years" => Ok(MessageAge::Years(count)),
|
||||
_ => Err(format!("Unknown period '{}', expected one of: days, weeks, months, years", period)),
|
||||
_ => Err(Error::InvalidMessageAge(format!(
|
||||
"Unknown period '{period}', expected one of: days, weeks, months, years"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a MessageAge from a string representation (e.g., "d:30", "m:6").
|
||||
/// Parse a `MessageAge` from a string representation (e.g., "d:30", "m:6").
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
@@ -136,12 +142,14 @@ impl MessageAge {
|
||||
/// assert!(MessageAge::parse("invalid").is_none());
|
||||
/// assert!(MessageAge::parse("d").is_none());
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn parse(s: &str) -> Option<MessageAge> {
|
||||
if s.len() < 3 || s.chars().nth(1) != Some(':') {
|
||||
let bytes = s.as_bytes();
|
||||
if bytes.len() < 3 || bytes[1] != b':' {
|
||||
return None;
|
||||
}
|
||||
|
||||
let period = s.chars().nth(0)?;
|
||||
let period = bytes[0];
|
||||
let count_str = &s[2..];
|
||||
let count = count_str.parse::<i64>().ok()?;
|
||||
|
||||
@@ -150,10 +158,10 @@ impl MessageAge {
|
||||
}
|
||||
|
||||
match period {
|
||||
'd' => Some(MessageAge::Days(count)),
|
||||
'w' => Some(MessageAge::Weeks(count)),
|
||||
'm' => Some(MessageAge::Months(count)),
|
||||
'y' => Some(MessageAge::Years(count)),
|
||||
b'd' => Some(MessageAge::Days(count)),
|
||||
b'w' => Some(MessageAge::Weeks(count)),
|
||||
b'm' => Some(MessageAge::Months(count)),
|
||||
b'y' => Some(MessageAge::Years(count)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -174,6 +182,7 @@ impl MessageAge {
|
||||
/// let age = MessageAge::Years(1);
|
||||
/// assert_eq!(age.label(), "retention/1-years");
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn label(&self) -> String {
|
||||
match self {
|
||||
MessageAge::Days(v) => format!("retention/{v}-days"),
|
||||
@@ -196,9 +205,13 @@ impl MessageAge {
|
||||
/// let age = MessageAge::Years(2);
|
||||
/// assert_eq!(age.value(), 2);
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn value(&self) -> i64 {
|
||||
match self {
|
||||
MessageAge::Days(v) | MessageAge::Weeks(v) | MessageAge::Months(v) | MessageAge::Years(v) => *v,
|
||||
MessageAge::Days(v)
|
||||
| MessageAge::Weeks(v)
|
||||
| MessageAge::Months(v)
|
||||
| MessageAge::Years(v) => *v,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -215,6 +228,7 @@ impl MessageAge {
|
||||
/// let age = MessageAge::Years(2);
|
||||
/// assert_eq!(age.period_type(), "years");
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn period_type(&self) -> &'static str {
|
||||
match self {
|
||||
MessageAge::Days(_) => "days",
|
||||
@@ -225,6 +239,30 @@ impl MessageAge {
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&str> for MessageAge {
|
||||
type Error = Error;
|
||||
|
||||
/// Try to create a `MessageAge` from a string using the parse format.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use cull_gmail::MessageAge;
|
||||
/// use std::convert::TryFrom;
|
||||
///
|
||||
/// let age = MessageAge::try_from("d:30").unwrap();
|
||||
/// assert_eq!(age, MessageAge::Days(30));
|
||||
///
|
||||
/// let age = MessageAge::try_from("invalid");
|
||||
/// assert!(age.is_err());
|
||||
/// ```
|
||||
fn try_from(value: &str) -> Result<Self> {
|
||||
Self::parse(value).ok_or_else(|| {
|
||||
Error::InvalidMessageAge(format!("Failed to parse MessageAge from '{value}'"))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -251,7 +289,7 @@ mod tests {
|
||||
|
||||
// Check error messages
|
||||
let err = MessageAge::new("invalid", 1).unwrap_err();
|
||||
assert!(err.contains("Unknown period 'invalid'"));
|
||||
assert!(err.to_string().contains("Unknown period 'invalid'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -262,7 +300,7 @@ mod tests {
|
||||
|
||||
// Check error messages
|
||||
let err = MessageAge::new("days", -1).unwrap_err();
|
||||
assert!(err.contains("Count must be positive"));
|
||||
assert!(err.to_string().contains("Count must be positive"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -353,4 +391,17 @@ mod tests {
|
||||
let parsed = MessageAge::parse(&serialized).unwrap();
|
||||
assert_eq!(original, parsed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_try_from() {
|
||||
use std::convert::TryFrom;
|
||||
|
||||
assert_eq!(MessageAge::try_from("d:30").unwrap(), MessageAge::Days(30));
|
||||
assert_eq!(MessageAge::try_from("w:4").unwrap(), MessageAge::Weeks(4));
|
||||
assert_eq!(MessageAge::try_from("m:6").unwrap(), MessageAge::Months(6));
|
||||
assert_eq!(MessageAge::try_from("y:2").unwrap(), MessageAge::Years(2));
|
||||
|
||||
assert!(MessageAge::try_from("invalid").is_err());
|
||||
assert!(MessageAge::try_from("d:-1").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user