use std::{
borrow::Cow,
sync::OnceLock,
time::{SystemTime, UNIX_EPOCH},
};
use regex::Regex;
pub(super) fn translate_timestamp(st: SystemTime) -> f64 {
st.duration_since(UNIX_EPOCH)
.expect("EPOCH is earlier")
.as_secs_f64()
}
pub(super) fn sanitize_annotation_key(key: &str) -> Cow<'_, str> {
static REGEX: OnceLock<Regex> = OnceLock::new();
REGEX
.get_or_init(|| Regex::new(r"[^a-zA-Z0-9_]").expect("Invalid annotation key regex"))
.replace_all(key, "_")
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
#[test]
fn translate_timestamp() {
let timestamp = UNIX_EPOCH + Duration::from_secs(1577836800);
let result = super::translate_timestamp(timestamp);
assert_eq!(
result, 1577836800.0,
"Should convert SystemTime to epoch seconds"
);
let timestamp_with_nanos = UNIX_EPOCH + Duration::from_nanos(1_577_836_800_500_000_000);
let result = super::translate_timestamp(timestamp_with_nanos);
assert_eq!(result, 1577836800.5, "Should preserve fractional seconds");
let epoch = UNIX_EPOCH;
let result = super::translate_timestamp(epoch);
assert_eq!(result, 0.0, "UNIX_EPOCH should convert to 0.0");
}
#[test]
fn test_sanitize_annotation_key_valid() {
let result = sanitize_annotation_key("valid_key");
assert!(matches!(result, Cow::Borrowed(_)));
assert_eq!(result, "valid_key");
let result = sanitize_annotation_key("snake_case_name");
assert!(matches!(result, Cow::Borrowed(_)));
assert_eq!(result, "snake_case_name");
let result = sanitize_annotation_key("key123");
assert!(matches!(result, Cow::Borrowed(_)));
assert_eq!(result, "key123");
let result = sanitize_annotation_key("MixedCase_Key_123");
assert!(matches!(result, Cow::Borrowed(_)));
assert_eq!(result, "MixedCase_Key_123");
let result = sanitize_annotation_key("___");
assert!(matches!(result, Cow::Borrowed(_)));
assert_eq!(result, "___");
}
#[test]
fn test_sanitize_annotation_key_invalid() {
let result = sanitize_annotation_key("key with spaces");
assert!(matches!(result, Cow::Owned(_)));
assert_eq!(result, "key_with_spaces");
let result = sanitize_annotation_key("key-with-dashes");
assert!(matches!(result, Cow::Owned(_)));
assert_eq!(result, "key_with_dashes");
let result = sanitize_annotation_key("key.with@special#chars!");
assert!(matches!(result, Cow::Owned(_)));
assert_eq!(result, "key_with_special_chars_");
let result = sanitize_annotation_key("key_配");
assert!(matches!(result, Cow::Owned(_)));
assert_eq!(result, "key__");
let result = sanitize_annotation_key("");
assert!(matches!(result, Cow::Borrowed(_)));
assert_eq!(result, "");
}
}