Skip to main content

yggdrasil/api/
slug.rs

1//! 文章 slug 生成与唯一性校验。
2//!
3//! 将标题转换为小写、仅含字母数字与连字符/下划线的 URL 友好形式,
4//! 并检测数据库中是否已存在,必要时追加数字后缀。
5//! 仅在 `feature = "server"` 时访问数据库。
6
7#![allow(clippy::unused_unit, deprecated)]
8
9#[cfg(feature = "server")]
10use pinyin::ToPinyin;
11
12#[cfg(feature = "server")]
13/// 将标题转换为 URL 友好的 slug。
14///
15/// 汉字转为无声调拼音(每字独立成词,用 `-` 分隔,如 `你好` → `ni-hao`);
16/// ASCII 字母数字与 `-`/`_` 保留;其余字符替换为 `-`,连续 `-` 合并。
17/// 结果截断至 100 字符;若全部被过滤则回退为当前时间戳。
18///
19/// 多音字取默认读音(不处理歧义),博客 slug 场景足够。
20///
21/// 单遍状态机实现:旧实现 `to_lowercase` 分配一次 String + `split.collect::<Vec>` +
22/// `join` 再分配 + `take.collect` 第三次分配,共 4 次堆分配、3 遍扫描。
23/// 现用 `prev_dash` 状态在单遍内合并连续 `-` 并按需截断,1 次分配、1 遍扫描。
24pub fn slugify(title: &str) -> String {
25    let mut out = String::with_capacity(title.len());
26    // prev_dash = true 表示当前不应再输出 `-`(处于开头,或上一输出字符已是 `-`)。
27    // 等价于旧实现字符流 + split('-').filter(!empty).join('-') 的合并/去首尾效果。
28    let mut prev_dash = true;
29    let mut len = 0usize;
30
31    /// 输出一个字符,截断到 100。返回 false 表示已达上限应停止。
32    fn push_char(out: &mut String, len: &mut usize, c: char) -> bool {
33        if *len >= 100 {
34            return false;
35        }
36        out.push(c);
37        *len += 1;
38        true
39    }
40
41    for c in title.chars() {
42        // 汉字优先转拼音:to_pinyin() 对非汉字(含 ascii)返回 None。
43        if let Some(py) = c.to_pinyin() {
44            // 拼音内部不含 `-`;连续字母直接拼接,与旧实现 push_str 行为一致。
45            for pc in py.plain().chars() {
46                if !push_char(&mut out, &mut len, pc) {
47                    break;
48                }
49            }
50            // 汉字成词,后接 `-`(合并连续、去除尾部由末尾清理负责)。
51            // 拼音后必然接 `-`,所以 prev_dash 在此无条件置 true,中间无读。
52            if !push_char(&mut out, &mut len, '-') {
53                break;
54            }
55            prev_dash = true;
56        } else {
57            // ASCII 小写化避免对整串 to_lowercase 的全量分配。
58            let lc = c.to_ascii_lowercase();
59            if lc.is_ascii_alphanumeric() {
60                if !push_char(&mut out, &mut len, lc) {
61                    break;
62                }
63                prev_dash = false;
64            } else if lc == '_' {
65                // 下划线保留原样(split('-') 不把它当分隔符,行为一致)。
66                if !push_char(&mut out, &mut len, '_') {
67                    break;
68                }
69                prev_dash = false;
70            } else {
71                // `-` 或其他字符(空格/标点):仅当前面非分隔符时输出一个 `-`,
72                // 连续分隔符合并为一个;首尾的 `-` 由 prev_dash 初值和末尾清理负责。
73                if !prev_dash {
74                    if !push_char(&mut out, &mut len, '-') {
75                        break;
76                    }
77                    prev_dash = true;
78                }
79            }
80        }
81    }
82
83    // 去除尾部 `-`(开头已被 prev_dash 初值 true 挡住)。
84    while out.ends_with('-') {
85        out.pop();
86    }
87
88    if out.is_empty() {
89        return chrono::Utc::now().timestamp().to_string();
90    }
91
92    out
93}
94
95#[cfg(feature = "server")]
96/// 校验 slug 是否为空且仅含合法字符、长度不超过 200。
97pub fn is_valid_slug(slug: &str) -> bool {
98    if slug.is_empty() || slug.len() > 200 {
99        return false;
100    }
101    slug.chars()
102        .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
103}
104
105#[cfg(feature = "server")]
106/// 确保生成的 slug 在数据库中唯一。
107///
108/// 若 `exclude_id` 不为空,则排除该文章自身;
109/// 当冲突时依次尝试 `base-2`、`base-3` …… 直到生成唯一值。
110///
111/// 该函数应在事务内调用,确保与后续 INSERT/UPDATE 的 slug 唯一性检查
112/// 在同一个事务中完成,避免并发竞态。
113pub async fn ensure_unique_slug(
114    tx: &deadpool_postgres::Transaction<'_>,
115    base: &str,
116    exclude_id: Option<i32>,
117) -> Result<String, crate::api::error::AppError> {
118    use crate::api::error::AppError;
119
120    let mut candidate = base.to_string();
121    let mut suffix = 2;
122
123    loop {
124        // 查询当前候选 slug 是否已存在(排除指定文章 ID)。
125        let exists = if let Some(exclude) = exclude_id {
126            tx.query_opt(
127                "SELECT 1 FROM posts WHERE slug = $1 AND deleted_at IS NULL AND id != $2",
128                &[&candidate, &exclude],
129            )
130            .await
131            .map_err(AppError::query)?
132            .is_some()
133        } else {
134            tx.query_opt(
135                "SELECT 1 FROM posts WHERE slug = $1 AND deleted_at IS NULL",
136                &[&candidate],
137            )
138            .await
139            .map_err(AppError::query)?
140            .is_some()
141        };
142
143        if !exists {
144            return Ok(candidate);
145        }
146
147        candidate = format!("{}-{}", base, suffix);
148        suffix += 1;
149
150        // 防止无限循环:slug 总长度超过 200 时直接报错。
151        if candidate.len() > 200 {
152            return Err(AppError::Internal("无法生成唯一 slug"));
153        }
154    }
155}
156
157#[cfg(all(test, feature = "server"))]
158mod tests {
159    use super::*;
160
161    #[test]
162    fn slugify_ascii_title() {
163        assert_eq!(slugify("Hello World"), "hello-world");
164    }
165
166    #[test]
167    fn slugify_special_characters() {
168        assert_eq!(slugify("Hello, World! (2024)"), "hello-world-2024");
169    }
170
171    #[test]
172    fn slugify_chinese_characters() {
173        // 汉字逐字转拼音,用 `-` 分隔;混入的 ascii 自然衔接到末尾。
174        assert_eq!(slugify("你好世界"), "ni-hao-shi-jie");
175        assert_eq!(slugify("你好世界 hello"), "ni-hao-shi-jie-hello");
176    }
177
178    #[test]
179    fn slugify_mixed_chinese_ascii() {
180        // Rust 入门指南 → rust + ru-men-zhi-nan
181        assert_eq!(slugify("Rust 入门指南"), "rust-ru-men-zhi-nan");
182    }
183
184    #[test]
185    fn slugify_chinese_with_punctuation() {
186        // 标点替换为 `-`,随后与拼音分隔符合并。
187        assert_eq!(slugify("你好,世界!"), "ni-hao-shi-jie");
188    }
189
190    #[test]
191    fn slugify_collapses_dashes() {
192        assert_eq!(slugify("a---b"), "a-b");
193    }
194
195    #[test]
196    fn slugify_empty_returns_timestamp() {
197        let slug = slugify("");
198        let _: i64 = slug.parse().expect("should be a valid timestamp");
199    }
200
201    #[test]
202    fn slugify_truncates_at_100_chars() {
203        let long_title = "a".repeat(200);
204        assert!(slugify(&long_title).len() <= 100);
205    }
206
207    #[test]
208    fn slugify_preserves_underscores() {
209        assert_eq!(slugify("hello_world"), "hello_world");
210    }
211
212    #[test]
213    fn is_valid_slug_normal() {
214        assert!(is_valid_slug("hello-world_123"));
215    }
216
217    #[test]
218    fn is_valid_slug_rejects_empty() {
219        assert!(!is_valid_slug(""));
220    }
221
222    #[test]
223    fn is_valid_slug_rejects_too_long() {
224        let long_slug = "a".repeat(201);
225        assert!(!is_valid_slug(&long_slug));
226    }
227
228    #[test]
229    fn is_valid_slug_accepts_max_length() {
230        let slug = "a".repeat(200);
231        assert!(is_valid_slug(&slug));
232    }
233
234    #[test]
235    fn is_valid_slug_rejects_special_chars() {
236        assert!(!is_valid_slug("hello world"));
237        assert!(!is_valid_slug("hello.world"));
238        assert!(!is_valid_slug("hello!world"));
239    }
240
241    #[test]
242    fn is_valid_slug_accepts_chinese() {
243        assert!(is_valid_slug("你好-world"));
244    }
245
246    #[test]
247    fn slugify_all_special_characters_returns_timestamp() {
248        let slug = slugify("!@#$%^&*()+=[]{}|\\;:'\",.<>/?`~");
249        let _: i64 = slug.parse().expect("should be a valid timestamp");
250    }
251
252    #[test]
253    fn slugify_only_whitespace_returns_timestamp() {
254        let slug = slugify("   \t\n  ");
255        let _: i64 = slug.parse().expect("should be a valid timestamp");
256    }
257
258    #[test]
259    fn slugify_leading_and_trailing_dashes() {
260        assert_eq!(slugify("-hello-world-"), "hello-world");
261        assert_eq!(slugify("---hello---world---"), "hello-world");
262    }
263
264    #[test]
265    fn is_valid_slug_mixed_chinese_and_digits() {
266        assert!(is_valid_slug("你好123"));
267        assert!(is_valid_slug("123你好456"));
268    }
269
270    #[test]
271    fn is_valid_slug_exact_200_char_boundary() {
272        let slug = "a".repeat(200);
273        assert!(is_valid_slug(&slug));
274        let slug = "a".repeat(201);
275        assert!(!is_valid_slug(&slug));
276    }
277}