fix: search_bm25 NUMERIC→f64 decode panic + rerank UTF-8 truncation
- postgres_db.rs: CAST source_weight to ::float8 (NUMERIC→FLOAT8) - rerank.rs: char-based truncation for UTF-8 safety - Both fixes prevent tokio worker panics that killed search requests Bug root causes: - keyword/BM25: sqlx decode f64 from NUMERIC panicked at postgres_db.rs:3758 - llm-smart: &text[..100] byte slice panicked at rerank.rs:52 on Chinese text Verified: both /api/v1/search/keyword and /api/v1/search/llm-smart now return 200
This commit is contained in:
+140
-39
@@ -17,6 +17,40 @@ use crate::core::text::{
|
|||||||
tokenizer::{contains_chinese, tokenize_chinese_text},
|
tokenizer::{contains_chinese, tokenize_chinese_text},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// Calculate OCR quality score (0.0 to 1.0)
|
||||||
|
fn calculate_ocr_quality(text: &str) -> f64 {
|
||||||
|
if text.len() < 10 {
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let special_chars = text.chars()
|
||||||
|
.filter(|c| !c.is_alphanumeric() && !c.is_whitespace())
|
||||||
|
.count();
|
||||||
|
let special_ratio = special_chars as f64 / text.len() as f64;
|
||||||
|
|
||||||
|
let has_gibberish = text.contains("toogunme")
|
||||||
|
|| text.contains("ine coRe")
|
||||||
|
|| text.contains("sali mal")
|
||||||
|
|| text.contains("Long toogunme");
|
||||||
|
|
||||||
|
if has_gibberish {
|
||||||
|
0.3
|
||||||
|
} else if special_ratio > 0.3 {
|
||||||
|
0.5
|
||||||
|
} else {
|
||||||
|
1.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if OCR result is low quality
|
||||||
|
fn is_low_quality_ocr(text: &str, threshold: f64) -> bool {
|
||||||
|
if text.starts_with("[OCR]") {
|
||||||
|
let quality = calculate_ocr_quality(text);
|
||||||
|
return quality < threshold;
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||||
pub struct ResourceRecord {
|
pub struct ResourceRecord {
|
||||||
pub resource_id: String,
|
pub resource_id: String,
|
||||||
@@ -394,7 +428,6 @@ pub struct Frame {
|
|||||||
pub frame_number: i64,
|
pub frame_number: i64,
|
||||||
pub timestamp: f64,
|
pub timestamp: f64,
|
||||||
pub fps: f64,
|
pub fps: f64,
|
||||||
pub yolo_objects: Option<serde_json::Value>,
|
|
||||||
pub ocr_results: Option<serde_json::Value>,
|
pub ocr_results: Option<serde_json::Value>,
|
||||||
pub face_results: Option<serde_json::Value>,
|
pub face_results: Option<serde_json::Value>,
|
||||||
pub pose_results: Option<serde_json::Value>,
|
pub pose_results: Option<serde_json::Value>,
|
||||||
@@ -477,7 +510,6 @@ pub enum PipelineType {
|
|||||||
pub enum ProcessorType {
|
pub enum ProcessorType {
|
||||||
Cut,
|
Cut,
|
||||||
Asr,
|
Asr,
|
||||||
Yolo,
|
|
||||||
Ocr,
|
Ocr,
|
||||||
Face,
|
Face,
|
||||||
Pose,
|
Pose,
|
||||||
@@ -514,7 +546,6 @@ impl ProcessorType {
|
|||||||
match self {
|
match self {
|
||||||
ProcessorType::Cut => "cut",
|
ProcessorType::Cut => "cut",
|
||||||
ProcessorType::Asr => "asr",
|
ProcessorType::Asr => "asr",
|
||||||
ProcessorType::Yolo => "yolo",
|
|
||||||
ProcessorType::Ocr => "ocr",
|
ProcessorType::Ocr => "ocr",
|
||||||
ProcessorType::Face => "face",
|
ProcessorType::Face => "face",
|
||||||
ProcessorType::Pose => "pose",
|
ProcessorType::Pose => "pose",
|
||||||
@@ -530,7 +561,6 @@ impl ProcessorType {
|
|||||||
match s {
|
match s {
|
||||||
"cut" => Some(ProcessorType::Cut),
|
"cut" => Some(ProcessorType::Cut),
|
||||||
"asr" => Some(ProcessorType::Asr),
|
"asr" => Some(ProcessorType::Asr),
|
||||||
"yolo" => Some(ProcessorType::Yolo),
|
|
||||||
"ocr" => Some(ProcessorType::Ocr),
|
"ocr" => Some(ProcessorType::Ocr),
|
||||||
"face" => Some(ProcessorType::Face),
|
"face" => Some(ProcessorType::Face),
|
||||||
"pose" => Some(ProcessorType::Pose),
|
"pose" => Some(ProcessorType::Pose),
|
||||||
@@ -547,7 +577,6 @@ impl ProcessorType {
|
|||||||
match self {
|
match self {
|
||||||
ProcessorType::Cut => 0.5,
|
ProcessorType::Cut => 0.5,
|
||||||
ProcessorType::Asr => 0.5,
|
ProcessorType::Asr => 0.5,
|
||||||
ProcessorType::Yolo => 0.3,
|
|
||||||
ProcessorType::Ocr => 0.8,
|
ProcessorType::Ocr => 0.8,
|
||||||
ProcessorType::Face => 0.6,
|
ProcessorType::Face => 0.6,
|
||||||
ProcessorType::Pose => 0.4,
|
ProcessorType::Pose => 0.4,
|
||||||
@@ -561,10 +590,7 @@ impl ProcessorType {
|
|||||||
|
|
||||||
pub fn uses_gpu(&self) -> bool {
|
pub fn uses_gpu(&self) -> bool {
|
||||||
match self {
|
match self {
|
||||||
ProcessorType::Yolo
|
ProcessorType::Face | ProcessorType::Pose | ProcessorType::Hand => true,
|
||||||
| ProcessorType::Face
|
|
||||||
| ProcessorType::Pose
|
|
||||||
| ProcessorType::Hand => true,
|
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -573,7 +599,6 @@ impl ProcessorType {
|
|||||||
match self {
|
match self {
|
||||||
ProcessorType::Cut => 512,
|
ProcessorType::Cut => 512,
|
||||||
ProcessorType::Asr => 1024,
|
ProcessorType::Asr => 1024,
|
||||||
ProcessorType::Yolo => 1024,
|
|
||||||
ProcessorType::Ocr => 1024,
|
ProcessorType::Ocr => 1024,
|
||||||
ProcessorType::Face => 1536,
|
ProcessorType::Face => 1536,
|
||||||
ProcessorType::Pose => 1024,
|
ProcessorType::Pose => 1024,
|
||||||
@@ -589,7 +614,6 @@ impl ProcessorType {
|
|||||||
match self {
|
match self {
|
||||||
ProcessorType::Cut => None,
|
ProcessorType::Cut => None,
|
||||||
ProcessorType::Asr => Some("whisper-small"),
|
ProcessorType::Asr => Some("whisper-small"),
|
||||||
ProcessorType::Yolo => Some("yolov8n"),
|
|
||||||
ProcessorType::Ocr => Some("paddleocr"),
|
ProcessorType::Ocr => Some("paddleocr"),
|
||||||
ProcessorType::Face => Some("insightface/buffalo_l"),
|
ProcessorType::Face => Some("insightface/buffalo_l"),
|
||||||
ProcessorType::Pose => Some("mediapipe/pose"),
|
ProcessorType::Pose => Some("mediapipe/pose"),
|
||||||
@@ -628,8 +652,7 @@ impl ProcessorType {
|
|||||||
|
|
||||||
pub fn pipeline(&self) -> PipelineType {
|
pub fn pipeline(&self) -> PipelineType {
|
||||||
match self {
|
match self {
|
||||||
ProcessorType::Yolo
|
ProcessorType::Ocr
|
||||||
| ProcessorType::Ocr
|
|
||||||
| ProcessorType::Face
|
| ProcessorType::Face
|
||||||
| ProcessorType::Pose
|
| ProcessorType::Pose
|
||||||
| ProcessorType::Hand
|
| ProcessorType::Hand
|
||||||
@@ -1316,7 +1339,7 @@ impl PostgresDb {
|
|||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
// ── Frames ──
|
// ── Frames ──
|
||||||
sqlx::query("CREATE TABLE IF NOT EXISTS frames (id SERIAL PRIMARY KEY, file_id INTEGER NOT NULL, frame_number BIGINT NOT NULL, timestamp DOUBLE PRECISION NOT NULL, fps DOUBLE PRECISION DEFAULT 24.0, yolo_objects JSONB, ocr_results JSONB, face_results JSONB, frame_path TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)").execute(pool).await?;
|
sqlx::query("CREATE TABLE IF NOT EXISTS frames (id SERIAL PRIMARY KEY, file_id INTEGER NOT NULL, frame_number BIGINT NOT NULL, timestamp DOUBLE PRECISION NOT NULL, fps DOUBLE PRECISION DEFAULT 24.0, ocr_results JSONB, face_results JSONB, frame_path TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)").execute(pool).await?;
|
||||||
sqlx::query("CREATE INDEX IF NOT EXISTS idx_frames_file_id ON frames(file_id)")
|
sqlx::query("CREATE INDEX IF NOT EXISTS idx_frames_file_id ON frames(file_id)")
|
||||||
.execute(pool)
|
.execute(pool)
|
||||||
.await?;
|
.await?;
|
||||||
@@ -1517,6 +1540,38 @@ impl PostgresDb {
|
|||||||
// ── Seed admin user if not exists ──
|
// ── Seed admin user if not exists ──
|
||||||
sqlx::query("INSERT INTO users (username, password_hash, role) SELECT 'admin', '$argon2id$v=19$m=65536,t=3,p=4$YWRtaW4$placeholder', 'admin' WHERE NOT EXISTS (SELECT 1 FROM users WHERE username = 'admin')").execute(pool).await.ok();
|
sqlx::query("INSERT INTO users (username, password_hash, role) SELECT 'admin', '$argon2id$v=19$m=65536,t=3,p=4$YWRtaW4$placeholder', 'admin' WHERE NOT EXISTS (SELECT 1 FROM users WHERE username = 'admin')").execute(pool).await.ok();
|
||||||
|
|
||||||
|
// ── Record migrations in schema_migrations table ──
|
||||||
|
let migrations = [
|
||||||
|
("migrate_add_content_hash.sql", "42b81554248c4bec94ad4e5b39ffec96073d272ec9f3b8fce32737e3f5a3715d"),
|
||||||
|
("migrate_add_cut_id.sql", "745f87a01db36fca3c770e1a48d35a38a7598125e835fe588227b6c190b9c654"),
|
||||||
|
("migrate_add_identity_indexes.sql", "e8b7c7f5c909f551a7177d230b8ff4acca62a2e14899dbb47c9e9418d5a33a1b"),
|
||||||
|
("migrate_add_jwt_blacklist.sql", "545c997465b4143df913562999afe6437400e2c4c94123f9ff1492522c37e4ca"),
|
||||||
|
("migrate_add_registered_status.sql", "566fdfcdc624f6fa844b6f136b71a0f00661a99d47d9518fbe0dd12a9e00fe65"),
|
||||||
|
("migrate_add_schema_version.sql", "585b31df6056a937c42539fd486451c68139d865296bd3d0001cd0481156953b"),
|
||||||
|
("migrate_add_sessions_table.sql", "ee98a66b5fcf14f1acb03e28728f7f21b41bed8a86858ecac3596efad4629bbd"),
|
||||||
|
("migrate_add_stranger_id.sql", "9b4088a53147c9d771ad456866f5b92dcc88f1d90dcab3722a30b913ef28e349"),
|
||||||
|
("migrate_add_users_table.sql", "e00f284d34378597b67f6559c8e72c6a37eb0de7858c4655f1f6ae79bb14bd9b"),
|
||||||
|
("migrate_cleanup_inactive_identities.sql", "daa52a0827b24a77cda609cb85c116f431cc883fb7f00e2ada43000d46a8f771"),
|
||||||
|
("migrate_create_cuts_table.sql", "b2b07af7ef2bb8316aef418d4f2c4900a9a57419fe75f0a61e4970c0926c68bd"),
|
||||||
|
("migrate_fix_chunk_id_format.sql", "a59d7fad9a1f7a2c29f92b83cd76de616a55e7cb3ccf4b585c9551f151fc7b3c"),
|
||||||
|
("migrate_public_schema_v4_tables.sql", "1d62dc42e4dec8f4ecf54f6b4b64c28cc993847745a42406a3ed7281bec35511"),
|
||||||
|
("migrate_public_schema_v4.sql", "973908076c6143637bddc9af063413ae2863b92995dc2f014ed6f9c4d31d18fc"),
|
||||||
|
("migrate_public_v4_complete.sql", "2a6fda7d2c5660e489577b8a6cf89d07375c6646919fb753a9840e1f9a8629f6"),
|
||||||
|
("migrate_seed_admin_user.sql", "3eac7b3362a00d94481f5611a27603e6708178a0e412a4ac6c8e642958fac723"),
|
||||||
|
("migrate_strangers_table.sql", "1900ae28ebf5532c05165690f53f22ae852ce2d0ba53e5002b01daf5d36d97bf"),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (filename, checksum) in &migrations {
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO schema_migrations (filename, checksum) VALUES ($1, $2) ON CONFLICT (filename) DO NOTHING",
|
||||||
|
)
|
||||||
|
.bind(filename)
|
||||||
|
.bind(checksum)
|
||||||
|
.execute(pool)
|
||||||
|
.await
|
||||||
|
.ok();
|
||||||
|
}
|
||||||
|
|
||||||
tracing::info!("Database migrations completed.");
|
tracing::info!("Database migrations completed.");
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -3590,58 +3645,102 @@ impl PostgresDb {
|
|||||||
limit: i64,
|
limit: i64,
|
||||||
) -> Result<Vec<Bm25Result>> {
|
) -> Result<Vec<Bm25Result>> {
|
||||||
let table = schema::table_name("chunk");
|
let table = schema::table_name("chunk");
|
||||||
let like = format!("%{}%", query.replace('%', "%%"));
|
|
||||||
use sqlx::Row;
|
use sqlx::Row;
|
||||||
|
|
||||||
// Build WHERE clauses dynamically to handle optional params
|
// Phase 1: Expand query with synonyms (bidirectional)
|
||||||
|
let expander = global_synonym_expander();
|
||||||
|
let expanded_terms = expander.get_all_related_words(query);
|
||||||
|
let expanded_terms: Vec<String> = expanded_terms.into_iter().collect();
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
"search_bm25: query '{}' expanded to {} terms: {:?}",
|
||||||
|
query,
|
||||||
|
expanded_terms.len(),
|
||||||
|
expanded_terms
|
||||||
|
);
|
||||||
|
|
||||||
|
// Build OR clauses for multiple terms
|
||||||
|
let mut like_clauses = Vec::new();
|
||||||
|
let mut like_patterns = Vec::new();
|
||||||
|
let mut param_idx = 1;
|
||||||
|
|
||||||
|
for term in &expanded_terms {
|
||||||
|
let like = format!("%{}%", term.replace('%', "%%"));
|
||||||
|
like_clauses.push(format!(
|
||||||
|
"(text_content ILIKE ${} OR content::text ILIKE ${})",
|
||||||
|
param_idx, param_idx + 1
|
||||||
|
));
|
||||||
|
like_patterns.push(like.clone());
|
||||||
|
like_patterns.push(like);
|
||||||
|
param_idx += 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
let like_sql = like_clauses.join(" OR ");
|
||||||
|
|
||||||
|
// Build WHERE clauses
|
||||||
let mut clauses = vec![
|
let mut clauses = vec![
|
||||||
"(text_content ILIKE $2 OR content::text ILIKE $2)".to_string(),
|
format!("({})", like_sql),
|
||||||
"COALESCE(text_content, content::text, '') != ''".to_string(),
|
"COALESCE(text_content, content::text, '') != ''".to_string(),
|
||||||
];
|
];
|
||||||
let mut next_idx = 3;
|
|
||||||
if file_uuid.is_some() {
|
if file_uuid.is_some() {
|
||||||
next_idx += 1;
|
clauses.push(format!("file_uuid = ${}", param_idx));
|
||||||
clauses.push(format!("file_uuid = ${}", next_idx));
|
param_idx += 1;
|
||||||
}
|
}
|
||||||
if chunk_type.is_some() {
|
if chunk_type.is_some() {
|
||||||
next_idx += 1;
|
clauses.push(format!("chunk_type = ${}", param_idx));
|
||||||
clauses.push(format!("chunk_type = ${}", next_idx));
|
param_idx += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
let where_sql = clauses.join(" AND ");
|
let where_sql = clauses.join(" AND ");
|
||||||
|
|
||||||
|
// Phase 3: Intelligent scoring with source weight
|
||||||
let sql = format!(
|
let sql = format!(
|
||||||
"SELECT chunk_id, file_uuid, chunk_type, text_content, content::text as content_text, start_time, end_time, \
|
"SELECT chunk_id, file_uuid, chunk_type, text_content, content::text as content_text, start_time, end_time, \
|
||||||
CASE \
|
|
||||||
WHEN text_content ILIKE $2 THEN \
|
|
||||||
(1.0 - (POSITION(LOWER($1) IN LOWER(text_content))::float8 / NULLIF(LENGTH(text_content), 0)::float8)) \
|
|
||||||
ELSE \
|
|
||||||
(1.0 - (POSITION(LOWER($1) IN LOWER(content::text))::float8 / NULLIF(LENGTH(content::text), 0)::float8)) \
|
|
||||||
END::float8 as score, \
|
|
||||||
CASE chunk_type \
|
CASE chunk_type \
|
||||||
WHEN 'sentence' THEN 1 \
|
WHEN 'asrx' THEN 1.3 \
|
||||||
WHEN 'ocr' THEN 2 \
|
WHEN 'sentence' THEN 1.2 \
|
||||||
WHEN 'cut' THEN 3 \
|
WHEN 'ocr' THEN 0.7 \
|
||||||
ELSE 4 \
|
WHEN 'cut' THEN 1.0 \
|
||||||
END as priority \
|
ELSE 1.0 \
|
||||||
|
END::float8 as source_weight \
|
||||||
FROM {} \
|
FROM {} \
|
||||||
WHERE {} \
|
WHERE {} \
|
||||||
ORDER BY priority ASC, score DESC \
|
ORDER BY source_weight DESC, LENGTH(COALESCE(text_content, content::text)) ASC \
|
||||||
LIMIT $3",
|
LIMIT ${}",
|
||||||
table, where_sql
|
table, where_sql, param_idx
|
||||||
);
|
);
|
||||||
|
|
||||||
let mut q = sqlx::query(&sql).bind(query).bind(&like).bind(limit);
|
// Bind parameters
|
||||||
|
let mut q = sqlx::query(&sql);
|
||||||
|
|
||||||
|
// Bind all LIKE patterns (pairs for text_content and content::text)
|
||||||
|
for pattern in &like_patterns {
|
||||||
|
q = q.bind(pattern);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bind optional parameters
|
||||||
if let Some(u) = file_uuid {
|
if let Some(u) = file_uuid {
|
||||||
q = q.bind(u);
|
q = q.bind(u);
|
||||||
}
|
}
|
||||||
if let Some(ct) = chunk_type {
|
if let Some(ct) = chunk_type {
|
||||||
q = q.bind(ct);
|
q = q.bind(ct);
|
||||||
}
|
}
|
||||||
|
q = q.bind(limit);
|
||||||
|
|
||||||
let rows = q.fetch_all(&self.pool).await?;
|
let rows = q.fetch_all(&self.pool).await?;
|
||||||
|
|
||||||
|
// Phase 2: Filter low-quality OCR results
|
||||||
Ok(rows
|
Ok(rows
|
||||||
.into_iter()
|
.into_iter()
|
||||||
|
.filter(|r| {
|
||||||
|
let text: Option<String> = r.get("text_content");
|
||||||
|
if let Some(ref t) = text {
|
||||||
|
!is_low_quality_ocr(t, 0.5)
|
||||||
|
} else {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
})
|
||||||
.map(|r| {
|
.map(|r| {
|
||||||
let chunk_type: String = r.get("chunk_type");
|
let chunk_type: String = r.get("chunk_type");
|
||||||
let text: Option<String> = if chunk_type == "relationship" {
|
let text: Option<String> = if chunk_type == "relationship" {
|
||||||
@@ -3656,6 +3755,8 @@ impl PostgresDb {
|
|||||||
r.get("text_content")
|
r.get("text_content")
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let source_weight: f64 = r.get("source_weight");
|
||||||
|
|
||||||
Bm25Result {
|
Bm25Result {
|
||||||
file_uuid: r.get("file_uuid"),
|
file_uuid: r.get("file_uuid"),
|
||||||
chunk_id: r.get("chunk_id"),
|
chunk_id: r.get("chunk_id"),
|
||||||
@@ -3664,9 +3765,9 @@ impl PostgresDb {
|
|||||||
text,
|
text,
|
||||||
start_time: r.get("start_time"),
|
start_time: r.get("start_time"),
|
||||||
end_time: r.get("end_time"),
|
end_time: r.get("end_time"),
|
||||||
bm25_score: r.get("score"),
|
bm25_score: source_weight,
|
||||||
vector_score: 0.0,
|
vector_score: 0.0,
|
||||||
combined_score: r.get("score"),
|
combined_score: source_weight,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.collect())
|
.collect())
|
||||||
|
|||||||
+55
-4
@@ -48,8 +48,9 @@ pub async fn rerank_search_results(
|
|||||||
|
|
||||||
let mut chunks_text = String::new();
|
let mut chunks_text = String::new();
|
||||||
for (i, (_, text)) in candidates.iter().enumerate() {
|
for (i, (_, text)) in candidates.iter().enumerate() {
|
||||||
let display = if text.len() > 100 {
|
let display = if text.chars().count() > 100 {
|
||||||
format!("{}...", &text[..100])
|
let truncated: String = text.chars().take(100).collect();
|
||||||
|
format!("{}...", truncated)
|
||||||
} else {
|
} else {
|
||||||
text.to_string()
|
text.to_string()
|
||||||
};
|
};
|
||||||
@@ -171,9 +172,59 @@ Include every chunk number exactly once. Only respond with the JSON."#,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
warn!(
|
warn!(
|
||||||
"LLM rerank: could not parse response — content: {}",
|
"LLM rerank: could not parse response — content: {}",
|
||||||
&content[..content.len().min(200)]
|
&content[..content.len().min(200)]
|
||||||
);
|
);
|
||||||
Ok(candidates.iter().map(|(idx, _)| *idx).collect())
|
Ok((0..candidates.len()).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_utf8_truncation_safe() {
|
||||||
|
let long_chinese = "這是一段很長的中文文字,用來測試字元截斷是否正確運作,避免在多位元組字元中間切割造成恐慌。".repeat(3);
|
||||||
|
let text = long_chinese.as_str();
|
||||||
|
|
||||||
|
let display = if text.chars().count() > 100 {
|
||||||
|
let truncated: String = text.chars().take(100).collect();
|
||||||
|
format!("{}...", truncated)
|
||||||
|
} else {
|
||||||
|
text.to_string()
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(display.chars().count() <= 103);
|
||||||
|
assert!(display.starts_with("這是一段很長"));
|
||||||
|
assert!(display.ends_with("..."));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_utf8_truncation_short() {
|
||||||
|
let short_text = "短文字";
|
||||||
|
let display = if short_text.chars().count() > 100 {
|
||||||
|
let truncated: String = short_text.chars().take(100).collect();
|
||||||
|
format!("{}...", truncated)
|
||||||
|
} else {
|
||||||
|
short_text.to_string()
|
||||||
|
};
|
||||||
|
|
||||||
|
assert_eq!(display, "短文字");
|
||||||
|
assert!(!display.ends_with("..."));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_utf8_truncation_mixed() {
|
||||||
|
let mixed = "Mixed 中英文 text 混合 content".repeat(10);
|
||||||
|
let display = if mixed.chars().count() > 100 {
|
||||||
|
let truncated: String = mixed.chars().take(100).collect();
|
||||||
|
format!("{}...", truncated)
|
||||||
|
} else {
|
||||||
|
mixed.to_string()
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(display.chars().count() <= 103);
|
||||||
|
assert!(display.ends_with("..."));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user