Metadata-Version: 2.4
Name: crossplatform
Version: 0.2.0
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Rust
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: MacOS
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Hardware
Classifier: Topic :: System :: Systems Administration
Summary: Cross-platform common utilities: path adaptation, env handling, memory monitoring, parallel processing, GPU (CUDA/Metal) — Rust-powered, Python-friendly
Keywords: cross-platform,path,memory,gpu,cuda,metal,parallel,pyo3,rust,utilities
Author-email: StarTAP Lab <cscb603@gmail.com>
License: MIT OR Apache-2.0
Requires-Python: >=3.8
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Homepage, https://github.com/cscb603/crossplatform
Project-URL: Repository, https://github.com/cscb603/crossplatform

# crossplatform

跨平台（Windows / macOS / Linux）通用底座：路径适配、环境处理、内存监控、并行计算、GPU（CUDA / Metal / CPU 兜底）。**Rust 真源，Python 薄封装**——同一份 Rust 代码同时服务两端，性能与一致性兼得。

Cross-platform common library (Windows / macOS / Linux): path adaptation, env handling, memory monitoring, parallel processing, GPU (CUDA / Metal / CPU fallback). **Rust core, thin Python wrapper** — one source, both languages.

[English](#english) · [中文](#中文)

---

## 快速上手 / Quick start

### Python

```bash
pip install crossplatform            # Windows 默认带 CUDA 支持
```

```python
import crossplatform as cp

# ① 平台检测
print(cp.current_platform())         # "windows" | "macos" | "linux"

# ② 路径适配（自动处理 / 与 \）
pa = cp.PathAdapter()
print(pa.normalize("~/data/x.txt"))  # 展开 ~、统一分隔符
print(pa.app_dir("myapp", "config")) # 系统规范配置目录 + 应用名

# ③ 内存监控
mm = cp.MemoryMonitor()
total, used, free, avail = mm.system()   # 单位：字节
print(f"可用 {avail // 1048576} MB, 压力 {mm.pressure()}")

# ④ 并行计算
pool = cp.ParallelPool(4)            # 4 线程
print(pool.map([1, 2, 3, 4], lambda x: x * 10))   # [10, 20, 30, 40]

# ⑤ GPU（自动降级：CUDA → Metal → CPU）
g = cp.GpuContext.auto()
print(g.backend(), g.device_name())           # "cuda NVIDIA GeForce GTX 1660"
print(g.memory_info())                        # (total, free, used) 字节
print(g.device_list())                        # 设备枚举 [(index, name, total, free)]

# ⑥ 显存分配
buf = g.allocate(1024)                        # 分配 1024 字节设备显存
print(buf.to_host())                          # 下载回主机
```

### Rust

```toml
[dependencies]
crossplatform = "0.2"
# Windows + CUDA：features = ["cuda"]
# macOS + Metal： features = ["metal"]
```

```rust
use crossplatform::prelude::*;

let pa = PathAdapter::new();
let cfg = pa.app_dir("myapp", AppDirKind::Config)?;   // 系统配置目录

let mut mm = MemoryMonitor::new();
println!("{:?}", mm.system());                        // 字节单位

let pool = ParallelPool::new(Some(4))?;               // 4 线程
let out = pool.map(vec![1, 2, 3], |x| x * 2)?;        // worker panic 不会崩进程

let gpu = GpuContext::auto()?;                        // ⚠️ 线程绑定：同一线程创建并使用
println!("{}: {} MB", gpu.device_name(), gpu.memory_bytes() / 1024 / 1024);
```

---

## 模块总览 / Modules

| 模块 | 说明 | 典型 API |
|------|------|----------|
| `platform` | 平台检测 / 分隔符 / 换行符 | `Platform::current()`, `line_ending()` |
| `path` | 路径归一化 / ~ 展开 / 系统目录 | `PathAdapter::normalize`, `app_dir` |
| `env` | 换行转换 / 环境变量 / 命令执行 | `to_platform_newlines`, `run_command` |
| `memory` | 系统/进程内存快照 / 压力分级 | `MemoryMonitor::system`, `pressure` |
| `parallel` | rayon 线程池 / panic 安全 | `ParallelPool::map`, `reduce` |
| `gpu` | CUDA / Metal / CPU 统一接口 | `GpuContext::auto`, `memory_info`, `allocate` |

详细 API 参考与异常场景：见 [docs/API_CN.md](docs/API_CN.md) / [docs/API_EN.md](docs/API_EN.md)。

## 异常场景说明 / Error scenarios

> 所有 API 失败都返回统一错误（Python 抛出对应异常，见下表），**不会静默吞错**。

| 场景 | Rust 错误 | Python 异常 | 处理建议 |
|------|-----------|-------------|----------|
| 路径规范化失败（用户目录无法解析） | `Error::Path` | `ValueError` | 检查 `dirs` 可用性，或改用绝对路径 |
| 内存查询失败（sysinfo 不支持平台） | `Error::Memory` | `ValueError` | 罕见；确认平台受支持 |
| 并行 worker panic | `Error::Parallel` | `RuntimeError` | 检查回调闭包是否可能 panic；pool 本身不 abort |
| `run_command` 程序不存在 / 退出码非 0 | `Error::Io` | `OSError` | 程序路径先 `which`/`where` 验证 |
| `run_shell` 未启用 `shell` feature | 编译期不存在该函数 | 无此函数 | 需要时 `--features shell`，且只传受信任脚本 |
| CUDA 不可用（无 NVIDIA 驱动/非 Windows） | `Error::Gpu` | `RuntimeError` | 用 `GpuContext::auto()` 自动降级，别用 `with_backend` 强求 |
| Metal 不可用（无 Metal 设备） | `Error::Gpu` | `RuntimeError` | 同上，`auto()` 会降级到 CPU |
| `GpuDeviceBuffer::write` 长度不匹配 | `Error::Gpu` | `RuntimeError` | 写入长度必须等于分配长度 |
| GPU 线程绑定违规（跨线程用 GpuContext） | 未定义行为（文档约束） | 运行时错误 | **同一线程创建并使用 GpuContext**，勿入 rayon |

## 相关项目 / Related projects

- **xtap-core-lib**（[GitHub](https://github.com/cscb603/xTap-core-lib) / [crates.io](https://crates.io/crates/xtap-core-lib)）— 星TAP Rust 工具基座：MCP HTTP 服务器 / egui 界面 / 文件 IO。crossplatform 管双系统底座 + Python 复用，xtap-core-lib 管 Rust 工具链，二者互补不冲突。

