translation-lib 0.1.1

A simple and efficient translation library for Rust
Documentation
//! 类型定义模块
//!
//! 定义翻译库中使用的简化数据结构和类型。

use serde::{Deserialize, Serialize};

/// 文本类型枚举
///
/// 用于标识不同类型的文本内容,以便进行相应的处理。
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TextType {
    /// 普通文本内容
    Content,
    /// 代码片段
    Code,
    /// URL链接
    Url,
    /// 邮箱地址
    Email,
    /// 空文本
    Empty,
    /// 标题
    Title,
    /// 按钮文本
    Button,
    /// 链接文本
    Link,
}

/// 文本分析结果
///
/// 包含对文本进行语言检测和类型分析的结果。
#[derive(Debug, Clone)]
pub struct TextAnalysis {
    /// 是否可翻译
    pub is_translatable: bool,
    /// 检测到的语言
    pub detected_lang: Option<String>,
    /// 检测置信度 (0.0 - 1.0)
    pub confidence: f32,
    /// 文本类型
    pub text_type: TextType,
}

/// 翻译请求
///
/// 发送到翻译API的请求结构。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TranslationRequest {
    /// 要翻译的文本
    pub text: String,
    /// 源语言代码
    pub source_lang: String,
    /// 目标语言代码
    pub target_lang: String,
}

/// 翻译响应
///
/// 从翻译API返回的响应结构。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TranslationResponse {
    /// 翻译后的文本
    pub translated_text: String,
    /// 检测到的源语言
    pub detected_source_lang: Option<String>,
}

/// 缓存条目
///
/// 缓存中存储的翻译结果条目。
#[derive(Debug, Clone)]
pub struct CacheEntry {
    /// 翻译结果
    pub translated_text: String,
    /// 创建时间戳
    pub created_at: std::time::Instant,
    /// 访问次数
    pub access_count: usize,
}

impl CacheEntry {
    /// 创建新的缓存条目
    pub fn new(translated_text: String) -> Self {
        Self {
            translated_text,
            created_at: std::time::Instant::now(),
            access_count: 1,
        }
    }

    /// 标记访问
    pub fn access(&mut self) {
        self.access_count += 1;
    }

    /// 检查是否过期
    pub fn is_expired(&self, ttl: std::time::Duration) -> bool {
        self.created_at.elapsed() > ttl
    }
}

/// HTML元素信息
///
/// 在HTML翻译过程中使用的元素信息。
#[cfg(feature = "html-support")]
#[derive(Debug, Clone)]
pub struct ElementInfo {
    /// 元素标签名
    pub tag_name: String,
    /// 属性名(如果是属性翻译)
    pub attr_name: Option<String>,
    /// 文本类型
    pub text_type: TextType,
    /// 优先级
    pub priority: u8,
}

#[cfg(feature = "html-support")]
impl ElementInfo {
    /// 创建新的元素信息
    pub fn new(tag_name: String, attr_name: Option<String>) -> Self {
        let text_type = match tag_name.as_str() {
            "title" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => TextType::Title,
            "a" => TextType::Link,
            "button" | "input" => TextType::Button,
            "code" | "pre" => TextType::Code,
            _ => TextType::Content,
        };

        let priority = match text_type {
            TextType::Title => 3,
            TextType::Button | TextType::Link => 2,
            TextType::Content => 1,
            _ => 0,
        };

        Self {
            tag_name,
            attr_name,
            text_type,
            priority,
        }
    }
}