fix: truncate article titles to safe UTF-8 budget

This commit is contained in:
Longtail committed 2026-10-31 18:38:41 +08:00
1 parent 24a73b19c0
commit 7ab0bc3485
7 files changed
+115 -15

No files matched your search

+7 -4
View File
@@ -56,15 +56,18 @@ def validate_images(body, directory):
raise ValueError('配图为空或达到 20 MiB:' + target)
def short_title(title, budget=80):
# Conservative UTF-16 budget: do not split astral characters / surrogate pairs.
if len(title.encode('utf-16-le')) // 2 <= budget:
def short_title(title, budget=75):
"""Keep a UTF-8 prefix within budget, adding three ASCII dots if shortened."""
if len(title.encode('utf-8')) <= budget or (title.endswith('...') and len(title.encode('utf-8')) <= budget + 3):
return title
out = ''
used = 0
for ch in title:
if len((out + ch).encode('utf-16-le')) // 2 > budget - 3:
size = len(ch.encode('utf-8'))
if used + size > budget:
break
out += ch
used += size
return out + '...'