cache-lite 0.2.1

A cross-platform caching library for Rust with configurable storage, lifecycle, and file formatting
Documentation
/*
 * @filename: config.rs
 * @description: Configuration structures for cache-lite library
 * @author: TaimWay <taimway@gmail.com>
 * 
 * Copyright (C) 2026 TaimWay
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

use serde::{Deserialize, Serialize};
use crate::{CacheError, CacheResult};

/// Main configuration structure for cache behavior
/// 
/// # Fields
/// - `path`: Platform-specific storage paths (Windows/Linux)
/// - `format`: File naming format template
/// - `lifecycle`: Cache lifecycle policy
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]  
pub struct CacheConfig {
    pub path: CachePathConfig,
    pub format: CacheFormatConfig,
    pub max_size: u64,
    pub max_files: usize
}

/// Platform-specific path configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]  
pub struct CachePathConfig {
    pub windows: String,
    pub linux: String,
}

impl Default for CachePathConfig {
    fn default() -> Self {
        CachePathConfig {
            windows: "%temp%/Rust/Cache".to_string(),
            linux: "/tmp/Rust/Cache".to_string(),
        }
    }
}

/// File naming format configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]  
pub struct CacheFormatConfig {
    pub filename: String,
    pub time: String
}

impl Default for CacheFormatConfig {
    fn default() -> Self {
        CacheFormatConfig {
            filename: "r{name}.{time}.cache".to_string(),
            time: "%Y+%m+%d-%H+%M+%S".to_string()
        }
    }
}

impl Default for CacheConfig {
    fn default() -> Self {
        CacheConfig {
            path: CachePathConfig::default(),
            format: CacheFormatConfig::default(),
            max_size: 0,  // 0 means no limit
            max_files: 0, // 0 means no limit
        }
    }
}

impl CacheConfig {
    /// Creates a new CacheConfig from JSON string
    /// 
    /// # Parameters
    /// - `json_config: &str` - JSON configuration string
    /// 
    /// # Returns
    /// New CacheConfig instance or error if parsing fails
    pub fn new(json_config: &str) -> CacheResult<Self> {
        let json_config = json_config
            .trim()
            .replace('\\', "/") 
            .replace(r#"\""#, r#"""#); 
        
        serde_json::from_str(&json_config)
            .map_err(|e| CacheError::ConfigParse(format!("Failed to parse config: {}\nInput: {}", e, json_config)))
    }
    
    /// Creates a new CacheConfig from JSON string, falling back to default on error
    /// 
    /// # Parameters
    /// - `json_config: &str` - JSON configuration string
    /// 
    /// # Returns
    /// New CacheConfig instance (falls back to default on parse error)
    pub fn new_or_default(json_config: &str) -> Self {
        match Self::new(json_config) {
            Ok(config) => config,
            Err(_) => Self::default(),
        }
    }
}