1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
//! Text utilities — slug generation, HTML escaping, truncation.
//!
//! Small zero-dep helpers for the common bits of text-handling boilerplate
//! every web app needs.
// ------------------------------------------------------------------ slugify
/// Convert a string into a URL-safe slug.
///
/// - Lowercases ASCII letters
/// - Replaces non-alphanumeric runs with a single `-`
/// - Strips leading and trailing `-`
/// - Drops non-ASCII characters (use [`slugify_unicode`] for transliteration support)
///
/// # Examples
///
/// ```
/// use rustango::text::slugify;
/// assert_eq!(slugify("Hello, World!"), "hello-world");
/// assert_eq!(slugify("Rust & Django"), "rust-django");
/// assert_eq!(slugify(" --leading-- "), "leading");
/// ```
#[must_use]
pub fn slugify(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut last_was_dash = false;
for c in s.chars() {
if c.is_ascii_alphanumeric() {
out.push(c.to_ascii_lowercase());
last_was_dash = false;
} else if !out.is_empty() && !last_was_dash {
out.push('-');
last_was_dash = true;
}
}
let trimmed = out.trim_end_matches('-');
trimmed.to_owned()
}
/// Like [`slugify`] but preserves Unicode letters/digits (lowercased).
/// Useful when your URL infrastructure handles UTF-8 paths.
#[must_use]
pub fn slugify_unicode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut last_was_dash = false;
for c in s.chars() {
if c.is_alphanumeric() {
for lower in c.to_lowercase() {
out.push(lower);
}
last_was_dash = false;
} else if !out.is_empty() && !last_was_dash {
out.push('-');
last_was_dash = true;
}
}
out.trim_end_matches('-').to_owned()
}
/// Generate a unique slug by appending `-2`, `-3`, ... until `is_taken`
/// returns false. Useful for URL slugs where the natural `slugify(title)`
/// might collide with an existing row.
///
/// `is_taken` is a closure called once per candidate; it should return
/// `true` if the slug already exists in your DB.
///
/// # Examples
///
/// ```
/// use rustango::text::unique_slug;
///
/// let mut existing = std::collections::HashSet::new();
/// existing.insert("hello-world".to_owned());
/// existing.insert("hello-world-2".to_owned());
///
/// let slug = unique_slug("Hello, World!", |s| existing.contains(s));
/// assert_eq!(slug, "hello-world-3");
/// ```
///
/// For DB-backed checks, wrap your async lookup:
///
/// ```ignore
/// let slug = unique_slug_async(&title, |candidate| async {
/// Post::objects().where_(Post::slug.eq(candidate.to_owned())).count(&pool).await? > 0
/// }).await?;
/// ```
#[must_use]
pub fn unique_slug<F>(input: &str, mut is_taken: F) -> String
where
F: FnMut(&str) -> bool,
{
let base = slugify(input);
if !is_taken(&base) {
return base;
}
for i in 2..u32::MAX {
let candidate = format!("{base}-{i}");
if !is_taken(&candidate) {
return candidate;
}
}
base // pathological — fall back to base
}
/// Async variant of [`unique_slug`] for DB-backed uniqueness checks.
pub async fn unique_slug_async<F, Fut>(input: &str, mut is_taken: F) -> String
where
F: FnMut(String) -> Fut,
Fut: std::future::Future<Output = bool>,
{
let base = slugify(input);
if !is_taken(base.clone()).await {
return base;
}
for i in 2..u32::MAX {
let candidate = format!("{base}-{i}");
if !is_taken(candidate.clone()).await {
return candidate;
}
}
base
}
// ------------------------------------------------------------------ HTML escape
/// Escape a string for safe insertion into HTML element content or
/// double-quoted HTML attributes.
///
/// Replaces `&`, `<`, `>`, `"`, `'` with their HTML entities.
///
/// # Example
///
/// ```
/// use rustango::text::html_escape;
/// assert_eq!(html_escape("<script>"), "<script>");
/// assert_eq!(html_escape("a & b"), "a & b");
/// ```
#[must_use]
pub fn html_escape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
other => out.push(other),
}
}
out
}
// ------------------------------------------------------------------ truncate
/// Truncate `s` to at most `max_chars` characters. If truncation happens,
/// append `suffix` (typically `"…"` or `"..."`).
///
/// Counts CHARACTERS, not bytes — never breaks UTF-8 boundaries.
///
/// # Example
///
/// ```
/// use rustango::text::truncate;
/// assert_eq!(truncate("hello world", 5, "…"), "hello…");
/// assert_eq!(truncate("short", 10, "…"), "short");
/// ```
#[must_use]
pub fn truncate(s: &str, max_chars: usize, suffix: &str) -> String {
if s.chars().count() <= max_chars {
return s.to_owned();
}
let mut out: String = s.chars().take(max_chars).collect();
out.push_str(suffix);
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn slugify_basic() {
assert_eq!(slugify("Hello World"), "hello-world");
}
#[test]
fn slugify_strips_punctuation() {
assert_eq!(slugify("Hello, World!"), "hello-world");
assert_eq!(slugify("Rust & Django"), "rust-django");
}
#[test]
fn slugify_collapses_whitespace_runs() {
assert_eq!(slugify("foo bar"), "foo-bar");
assert_eq!(slugify("foo--bar"), "foo-bar");
}
#[test]
fn slugify_trims_dashes() {
assert_eq!(slugify("---foo---"), "foo");
assert_eq!(slugify(" hi "), "hi");
}
#[test]
fn slugify_drops_non_ascii() {
assert_eq!(slugify("Café"), "caf");
assert_eq!(slugify("日本語"), "");
}
#[test]
fn slugify_empty_input() {
assert_eq!(slugify(""), "");
assert_eq!(slugify(" "), "");
}
#[test]
fn slugify_unicode_keeps_letters() {
assert_eq!(slugify_unicode("Café"), "café");
assert_eq!(slugify_unicode("Hello, 世界!"), "hello-世界");
}
#[test]
fn html_escape_special_chars() {
assert_eq!(
html_escape("<a>&\"'</a>"),
"<a>&"'</a>"
);
}
#[test]
fn html_escape_passes_safe_chars() {
assert_eq!(html_escape("hello world 123"), "hello world 123");
}
#[test]
fn html_escape_xss_attack_examples() {
// Common XSS attempts — after escape, none should produce executable HTML
let evil = r#"<script>alert("xss")</script>"#;
let safe = html_escape(evil);
assert!(!safe.contains("<script>"));
assert!(!safe.contains("</script>"));
}
#[test]
fn truncate_short_unchanged() {
assert_eq!(truncate("hi", 10, "…"), "hi");
}
#[test]
fn truncate_long_appends_suffix() {
assert_eq!(truncate("hello world", 5, "…"), "hello…");
assert_eq!(truncate("hello world", 5, "..."), "hello...");
}
#[test]
fn truncate_at_exact_boundary_unchanged() {
assert_eq!(truncate("hello", 5, "…"), "hello");
}
#[test]
fn truncate_counts_chars_not_bytes() {
// "café" is 4 chars but 5 bytes in UTF-8 — must respect char boundary
assert_eq!(truncate("café au lait", 4, "…"), "café…");
}
// -------------------------------------------------------------- unique_slug
#[test]
fn unique_slug_returns_base_when_free() {
let result = unique_slug("Hello World", |_| false);
assert_eq!(result, "hello-world");
}
#[test]
fn unique_slug_appends_2_when_base_taken() {
let mut existing = std::collections::HashSet::new();
existing.insert("hello-world".to_owned());
let result = unique_slug("Hello World", |s| existing.contains(s));
assert_eq!(result, "hello-world-2");
}
#[test]
fn unique_slug_keeps_incrementing_until_free() {
let mut existing = std::collections::HashSet::new();
for i in 1..=5 {
let s = if i == 1 {
"hello".to_owned()
} else {
format!("hello-{i}")
};
existing.insert(s);
}
let result = unique_slug("Hello", |s| existing.contains(s));
assert_eq!(result, "hello-6");
}
#[tokio::test]
async fn unique_slug_async_works() {
let mut existing = std::collections::HashSet::new();
existing.insert("foo".to_owned());
existing.insert("foo-2".to_owned());
let result = unique_slug_async("foo", |candidate| {
let existing = existing.clone();
async move { existing.contains(&candidate) }
})
.await;
assert_eq!(result, "foo-3");
}
}