//! Small helpers shared across modules. use std::path::{Path, PathBuf}; use chrono::Local; use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode}; /// Characters that are percent-encoded when a username is substituted into a URL. /// Everything except unreserved characters and `@` (used by fediverse handles). const ACCOUNT_ENCODE: &AsciiSet = &NON_ALPHANUMERIC .remove(b'-') .remove(b'.') .remove(b'_') .remove(b'~') .remove(b'@'); /// Timestamp usable inside a file name, e.g. `2026-09-13_16-58-01`. pub fn file_stamp() -> String { Local::now().format("%Y-%m-%d_%H-%M-%S").to_string() } /// ISO-8601 timestamp with local offset. pub fn iso_now() -> String { Local::now().to_rfc3339() } /// Reduce an arbitrary string to something safe as a file name component. pub fn sanitize_filename(s: &str) -> String { let mut out: String = s .chars() .map(|c| { if c.is_alphanumeric() || c == '-' || c == '_' || c == '.' { c } else { '_' } }) .collect(); while out.contains("__") { out = out.replace("__", "_"); } let trimmed = out.trim_matches(|c| c == '_' || c == '.'); if trimmed.is_empty() { "item".to_string() } else { trimmed.chars().take(120).collect() } } /// Truncate to at most `max` characters, appending an ellipsis when cut. pub fn truncate(s: &str, max: usize) -> String { let count = s.chars().count(); if count <= max { return s.to_string(); } let keep = max.saturating_sub(1); let mut out: String = s.chars().take(keep).collect(); out.push('…'); out } /// Collapse whitespace runs into single spaces and trim. pub fn squash_ws(s: &str) -> String { s.split_whitespace().collect::>().join(" ") } /// Host part of a URL (without port), lower-cased. Template placeholders are kept. pub fn host_of(url: &str) -> Option { let rest = url.split("://").nth(1).unwrap_or(url); let host = rest.split(['/', '?', '#']).next()?; let host = host.rsplit('@').next()?; // strip userinfo let host = host.split(':').next()?; if host.is_empty() { None } else { Some(host.to_ascii_lowercase()) } } /// Registrable-ish domain: strips a leading `www.` and any `{account}.` subdomain label. pub fn bare_host(url: &str) -> Option { let mut h = host_of(url)?; if let Some(stripped) = h.strip_prefix("www.") { h = stripped.to_string(); } if let Some(idx) = h.find("{account}.") { h = h[idx + "{account}.".len()..].to_string(); } Some(h) } /// Percent-encode an account string for use inside a URL path or query. pub fn percent_encode_account(s: &str) -> String { utf8_percent_encode(s, ACCOUNT_ENCODE).to_string() } /// Escape a string for insertion inside a JSON string literal (without quotes). pub fn json_escape(s: &str) -> String { let full = serde_json::to_string(s).unwrap_or_default(); full[1..full.len().saturating_sub(1)].to_string() } /// Escape for `application/x-www-form-urlencoded` bodies. pub fn form_encode(s: &str) -> String { utf8_percent_encode(s, NON_ALPHANUMERIC) .to_string() .replace("%20", "+") } /// HTML-escape text content and attribute values. pub fn html_escape(s: &str) -> String { let mut out = String::with_capacity(s.len() + 8); for c in s.chars() { match c { '&' => out.push_str("&"), '<' => out.push_str("<"), '>' => out.push_str(">"), '"' => out.push_str("""), '\'' => out.push_str("'"), _ => out.push(c), } } out } /// `1234` → `1.2k`, `1_500_000` → `1.5M`. pub fn humanize_count(n: u64) -> String { if n >= 1_000_000_000 { format!("{:.1}B", n as f64 / 1e9) } else if n >= 1_000_000 { format!("{:.1}M", n as f64 / 1e6) } else if n >= 10_000 { format!("{:.0}k", n as f64 / 1e3) } else if n >= 1_000 { format!("{:.1}k", n as f64 / 1e3) } else { n.to_string() } } /// Thousands separators: `1842` → `1,842`. pub fn group_digits(n: usize) -> String { let s = n.to_string(); let mut out = String::new(); for (i, c) in s.chars().enumerate() { if i > 0 && (s.len() - i) % 3 == 0 { out.push(','); } out.push(c); } out } /// Expand a leading `~` to the user's home directory. pub fn expand_tilde(p: &str) -> PathBuf { if let Some(rest) = p.strip_prefix("~/") { if let Some(home) = std::env::var_os("HOME") { return Path::new(&home).join(rest); } } else if p == "~" { if let Some(home) = std::env::var_os("HOME") { return PathBuf::from(home); } } PathBuf::from(p) } /// MD5 hex digest of a lower-cased, trimmed string (Gravatar style). pub fn md5_hex_normalized(s: &str) -> String { use md5::{Digest, Md5}; let normalized = s.trim().to_ascii_lowercase(); let digest = Md5::digest(normalized.as_bytes()); digest.iter().map(|b| format!("{b:02x}")).collect() } /// Random lower-case alphanumeric string that starts with a letter. pub fn random_handle(len: usize) -> String { use rand::Rng; const LETTERS: &[u8] = b"abcdefghijklmnopqrstuvwxyz"; const ALNUM: &[u8] = b"abcdefghijklmnopqrstuvwxyz0123456789"; let mut rng = rand::thread_rng(); let mut s = String::with_capacity(len); s.push(LETTERS[rng.gen_range(0..LETTERS.len())] as char); while s.len() < len { s.push(ALNUM[rng.gen_range(0..ALNUM.len())] as char); } s } /// Strip HTML tags and decode a handful of common entities. Good enough for /// descriptions that carry light markup. pub fn strip_tags(s: &str) -> String { let mut out = String::with_capacity(s.len()); let mut in_tag = false; for c in s.chars() { match c { '<' => in_tag = true, '>' if in_tag => in_tag = false, _ if !in_tag => out.push(c), _ => {} } } let decoded = out .replace("&", "&") .replace("<", "<") .replace(">", ">") .replace(""", "\"") .replace("'", "'") .replace("'", "'") .replace(" ", " "); squash_ws(&decoded) } #[cfg(test)] mod tests { use super::*; #[test] fn host_extraction() { assert_eq!( host_of("https://www.example.com/a/b?c=d").as_deref(), Some("www.example.com") ); assert_eq!( bare_host("https://www.example.com/a").as_deref(), Some("example.com") ); assert_eq!( bare_host("https://{account}.tumblr.com").as_deref(), Some("tumblr.com") ); assert_eq!(host_of("nonsense"), Some("nonsense".into())); } #[test] fn encoding_helpers() { assert_eq!(percent_encode_account("john doe"), "john%20doe"); assert_eq!(percent_encode_account("@john.doe_x"), "@john.doe_x"); assert_eq!(json_escape("a\"b\\c"), "a\\\"b\\\\c"); assert_eq!(form_encode("a b&c"), "a+b%26c"); assert_eq!( html_escape("&"), "<a href="x">&</a>" ); } #[test] fn misc() { assert_eq!(truncate("abcdef", 4), "abc…"); assert_eq!(truncate("abc", 4), "abc"); assert_eq!(humanize_count(999), "999"); assert_eq!(humanize_count(1_234), "1.2k"); assert_eq!(humanize_count(12_345), "12k"); assert_eq!(group_digits(1842), "1,842"); assert_eq!(group_digits(12), "12"); assert_eq!( md5_hex_normalized(" MyEmailAddress@example.com "), "0bc83cb571cd1c50ba6f3e8a78ef1346" ); assert_eq!(strip_tags("Hi & bye"), "Hi & bye"); assert_eq!( sanitize_filename("Mastodon-101010.pl"), "Mastodon-101010.pl" ); assert_eq!(sanitize_filename("a/b c"), "a_b_c"); let h = random_handle(12); assert_eq!(h.len(), 12); assert!(h.chars().next().unwrap().is_ascii_lowercase()); } }