xtap-core-lib 0.5.2

星TAP实验室通用 Rust 基座:跨平台路径/IO/硬件/MCP HTTP 服务/egui 主题与字体(features 按需裁剪)
Documentation
/*
 * Copyright (c) 2026 星TAP实验室
 * Skill: 硬件资源管理大师 (Hardware Resource Master)
 */

use crate::error::Result;
use rayon::prelude::*;

/// 动态硬件识别与优化建议
pub struct HardwareMaster;

impl HardwareMaster {
    /// 获取 CPU 物理核心数
    pub fn logical_cpus() -> usize {
        num_cpus::get()
    }

    /// 获取物理核心数 (非超线程)
    pub fn physical_cpus() -> usize {
        num_cpus::get_physical()
    }

    /// 自动配置全局并行线程池 (基于 Rayon)
    /// 这能确保在高并发处理时不会打死系统
    pub fn init_global_pool(threads: Option<usize>) -> Result<()> {
        let t = threads.unwrap_or_else(Self::logical_cpus);
        rayon::ThreadPoolBuilder::new()
            .num_threads(t)
            .build_global()?;
        Ok(())
    }

    /// 并行加速处理模版(Master Skill:自动分配 CPU 线程)
    /// 示例:快速处理海量数据,自动分配 CPU 线程
    pub fn parallel_process<T, R, F>(items: Vec<T>, f: F) -> Vec<R>
    where
        T: Send,
        R: Send,
        F: Fn(T) -> R + Sync + Send,
    {
        items.into_par_iter().map(f).collect()
    }
}

/// GPU 加速感知 (如果开启了 gpu feature)
#[cfg(feature = "gpu")]
pub mod gpu {
    use wgpu;

    pub async fn check_gpu_status() {
        let instance = wgpu::Instance::default();
        let adapters = instance.enumerate_adapters(wgpu::Backends::all());
        for adapter in adapters {
            println!("检测到 GPU: {:?}", adapter.get_info().name);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn logical_cpus_positive() {
        assert!(HardwareMaster::logical_cpus() >= 1, "逻辑核心数应 ≥ 1");
    }

    #[test]
    fn physical_cpus_positive() {
        assert!(HardwareMaster::physical_cpus() >= 1, "物理核心数应 ≥ 1");
    }

    #[test]
    fn parallel_process_preserves_order_and_len() {
        let items: Vec<i32> = (0..100).collect();
        let doubled = HardwareMaster::parallel_process(items.clone(), |x| x * 2);
        assert_eq!(doubled.len(), 100);
        // rayon 并行 map 保持输入顺序
        assert_eq!(doubled, items.iter().map(|x| x * 2).collect::<Vec<_>>());
    }

    #[test]
    fn parallel_process_empty() {
        let out: Vec<i32> = HardwareMaster::parallel_process(Vec::new(), |x| x);
        assert!(out.is_empty());
    }
}