config_rw 2.1.0

配置文件读取与写入
Documentation
# Config RW


**Thread-safe Configuration Management Library with Read/Write and Auto Hot-Reload**  
**线程安全的配置管理库,支持读写操作及自动热重载**

## 🚀 Features | 特性


*   **Read & Write Config** | **配置读写**  
    Type-safe access (String, Integer, Float, Bool, JSON) with auto-save capability.  
    类型安全的访问(支持字符串、整数、浮点、布尔、JSON),更改会自动保存到文件。

*   **Auto Callback on External Change** | **外部变更自动回调**  
    Register callbacks that are automatically triggered when the file is modified externally.  
    注册回调函数,当文件被外部进程修改时会自动触发,无需手动轮询。

*   **Thread Safety** | **线程安全**  
    Safe for concurrent access using `Arc` and `RwLock`.  
    基于 `Arc``RwLock` 保证并发访问安全。

## 📦 Installation | 安装


Add to `Cargo.toml` | 添加到 `Cargo.toml`:

```toml
[dependencies]
config_rw = "2.1.0"
```

## 💡 Usage Example | 使用示例


```rust
use std::sync::LazyLock;
use config_rw::ConfigState;

// Initialize global config instance
// 初始化全局配置实例
static CONFIG: LazyLock<ConfigState> = LazyLock::new(|| {
    ConfigState::init_config("config.toml")
});

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 1. Register Auto-Callback for External Changes
    //    Triggered automatically when file is modified externally
    // 1. 注册外部变更自动回调
    //    当文件被外部进程修改时自动触发
    CONFIG.add_change_callback(|| {
        let new_val = CONFIG.get_string("app.name").unwrap_or_default();
        println!("📝 Config auto-reloaded! app.name: {}", new_val);
    });

    // 2. Write Configuration (Thread-safe & Auto-saved)
    //    Internal writes do NOT trigger the callback
    // 2. 写入配置(线程安全且自动保存)
    //    程序内部写入不会触发回调
    CONFIG.set_string("app.name", "MyApplication".to_string())?;
    CONFIG.set_i64("server.port", 8080)?;

    // 3. Read Configuration
    // 3. 读取配置
    let app_name = CONFIG.get_string("app.name").unwrap_or_default();
    println!("📖 App Name: {}", app_name);

    // Keep running - callbacks fire automatically on file changes
    // 保持运行 - 文件变化时回调会自动触发
    loop {
        std::thread::sleep(std::time::Duration::from_secs(1));
    }
}
```

## 📚 API Overview | API 概览


### Reading | 读取

*   `get_string("key")``Option<String>`
*   `get_i64("key")``Option<i64>`
*   `get_bool("key")``Option<bool>`
*   `get_value("key")``Value` (serde_json)

### Writing | 写入

*   `set_string("key", val)``Result<()>`
*   `set_i64("key", val)``Result<()>`
*   `set_bool("key", val)``Result<()>`

### Lifecycle | 生命周期

*   `init_config("path")` → Initialize / 初始化
*   `add_change_callback(Fn())` → Auto-triggered on external file changes / 外部文件变更时自动触发

## 📄 License | 许可证


MIT / Apache-2.0