From 55dccaf8ba51bfb6df00d7b5fac03ac1b7e8ec8d Mon Sep 17 00:00:00 2001 From: FrozenlemonTee <1115306170@qq.com> Date: Sun, 22 Mar 2026 18:22:26 +0800 Subject: [PATCH 01/17] chore: Update copyright year and owner in LICENSE file Signed-off-by: FrozenlemonTee <1115306170@qq.com> --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 261eeb9..d158f0b 100644 --- a/LICENSE +++ b/LICENSE @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + Copyright [2026] [mcpp-community] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. From d901dc4bdd04b32a315060c9c47beee9b92284b4 Mon Sep 17 00:00:00 2001 From: FrozenlemonTee <1115306170@qq.com> Date: Sun, 22 Mar 2026 18:42:35 +0800 Subject: [PATCH 02/17] refactor: Improve type negotiation and construction behavior descriptions in ex02_type_policy Signed-off-by: FrozenlemonTee <1115306170@qq.com> --- examples/ex02_type_policy.cpp | 35 ++++++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/examples/ex02_type_policy.cpp b/examples/ex02_type_policy.cpp index 9dcbf09..4217c67 100644 --- a/examples/ex02_type_policy.cpp +++ b/examples/ex02_type_policy.cpp @@ -2,13 +2,18 @@ * Example: ex02_type_policy * * Purpose: - * Compare type negotiation behavior between strict and compatible policies. + * Compare type negotiation and underlying-construction behavior between strict + * and compatible type policies. * * Expected results: * - strict policy rejects mixed reps (int + long long) at compile-time * negotiation, yielding common_rep=void. + * - strict policy also rejects cross-underlying construction + * (primitive from int). * - compatible policy accepts mixed arithmetic reps and negotiates * common_rep=long long. + * - compatible policy allows same-category cross-underlying construction + * (primitive from int). * - Program prints a success message and exits with code 0. */ @@ -20,8 +25,7 @@ import mcpplibs.primitives; using namespace mcpplibs::primitives; int main() { - // Point 2: Compare different type_policy behaviors. - // Case A: strict policy rejects mixed underlying reps at compile time. + // Point 2A: strict policy rejects mixed reps in dispatcher negotiation. using strict_i32 = primitive; using strict_i64 = primitive::allowed); - // Case B: compatible policy allows mixed arithmetic reps and negotiates a - // common type. + // Point 2B: strict policy also applies to underlying construction. + static_assert(std::is_constructible_v); + static_assert(!std::is_constructible_v); + + // Point 2C: compatible policy allows mixed arithmetic reps and negotiates a + // common representation type. + using compatible_i64 = + primitive; + using compatible_meta = operations::dispatcher_meta< operations::Addition, primitive, - primitive, + compatible_i64, policy::error::kind>; static_assert( std::is_same_v); + static_assert(std::is_constructible_v); + static_assert(!std::is_constructible_v); + + auto const from_underlying = compatible_i64{42}; + auto const rhs = compatible_i64{2LL}; + auto const compatible_sum = operations::add(from_underlying, rhs); + if (!compatible_sum.has_value() || compatible_sum->value() != 44LL) { + std::cerr << "compatible underlying construction should participate in add\n"; + return 1; + } std::cout << "type_policy demo passed\n"; return 0; From 53dac13a156a63266319c1cffd727f356f47a893 Mon Sep 17 00:00:00 2001 From: FrozenlemonTee <1115306170@qq.com> Date: Sun, 22 Mar 2026 18:42:42 +0800 Subject: [PATCH 03/17] refactor: Update value policy demonstration to include mixed primitive/underlying operations Signed-off-by: FrozenlemonTee <1115306170@qq.com> --- examples/ex03_value_policy.cpp | 60 ++++++++++++++++++++++------------ 1 file changed, 39 insertions(+), 21 deletions(-) diff --git a/examples/ex03_value_policy.cpp b/examples/ex03_value_policy.cpp index e420aa6..1374132 100644 --- a/examples/ex03_value_policy.cpp +++ b/examples/ex03_value_policy.cpp @@ -3,12 +3,14 @@ * * Purpose: * Show how checked, unchecked, and saturating value policies behave under - * the same overflow input. + * the same overflow input, including mixed primitive/underlying binary + * operations. * * Expected results: - * - checked: reports overflow as an error. - * - unchecked: wraps according to native arithmetic semantics. - * - saturating: clamps to the representable upper bound. + * - checked: reports overflow as an error in both primitive+primitive and + * primitive+underlying paths. + * - unchecked: wraps according to native arithmetic semantics in both paths. + * - saturating: clamps to the representable upper bound in both paths. * - Program prints observed values and exits with code 0. */ @@ -21,45 +23,61 @@ using namespace mcpplibs::primitives; int main() { // Point 3: Compare checked / unchecked / saturating value policies. + using rep_t = std::uint16_t; + using checked_t = - primitive; - using unchecked_t = primitive; + using unchecked_t = primitive; - using saturating_t = primitive; // Same overflow input for all three policies. - auto const lhs_checked = checked_t{static_cast(65530)}; - auto const rhs_checked = checked_t{static_cast(20)}; + auto const lhs_checked = checked_t{static_cast(65530)}; + auto const rhs_checked = checked_t{static_cast(20)}; auto const checked_result = operations::add(lhs_checked, rhs_checked); + auto const checked_mixed_result = + operations::add(lhs_checked, static_cast(20)); - auto const lhs_unchecked = unchecked_t{static_cast(65530)}; - auto const rhs_unchecked = unchecked_t{static_cast(20)}; + auto const lhs_unchecked = unchecked_t{static_cast(65530)}; + auto const rhs_unchecked = unchecked_t{static_cast(20)}; auto const unchecked_result = operations::add(lhs_unchecked, rhs_unchecked); + auto const unchecked_mixed_result = + operations::add(lhs_unchecked, static_cast(20)); - auto const lhs_saturating = saturating_t{static_cast(65530)}; - auto const rhs_saturating = saturating_t{static_cast(20)}; + auto const lhs_saturating = saturating_t{static_cast(65530)}; + auto const rhs_saturating = saturating_t{static_cast(20)}; auto const saturating_result = operations::add(lhs_saturating, rhs_saturating); + auto const saturating_mixed_result = + operations::add(lhs_saturating, static_cast(20)); // Expected outcomes: // checked -> error, unchecked -> wrap, saturating -> clamp. - if (checked_result.has_value()) { - std::cerr << "checked policy should report overflow\n"; + if (checked_result.has_value() || checked_mixed_result.has_value()) { + std::cerr << "checked policy should report overflow in both paths\n"; return 1; } if (!unchecked_result.has_value() || - unchecked_result->value() != static_cast(14)) { - std::cerr << "unchecked policy should wrap\n"; + unchecked_result->value() != static_cast(14) || + !unchecked_mixed_result.has_value() || + unchecked_mixed_result->value() != static_cast(14)) { + std::cerr << "unchecked policy should wrap in both paths\n"; return 1; } if (!saturating_result.has_value() || - saturating_result->value() != static_cast(65535)) { - std::cerr << "saturating policy should clamp\n"; + saturating_result->value() != static_cast(65535) || + !saturating_mixed_result.has_value() || + saturating_mixed_result->value() != static_cast(65535)) { + std::cerr << "saturating policy should clamp in both paths\n"; return 1; } - std::cout << "checked=overflow, unchecked=" << unchecked_result->value() - << ", saturating=" << saturating_result->value() << '\n'; + std::cout << "checked=overflow, checked_mixed=overflow" + << ", unchecked=" << unchecked_result->value() + << ", unchecked_mixed=" << unchecked_mixed_result->value() + << ", saturating=" << saturating_result->value() + << ", saturating_mixed=" << saturating_mixed_result->value() + << '\n'; return 0; } From 0d0aab9984d3145274c5464321b9ec1df1de0c02 Mon Sep 17 00:00:00 2001 From: FrozenlemonTee <1115306170@qq.com> Date: Sun, 22 Mar 2026 18:42:48 +0800 Subject: [PATCH 04/17] refactor: Enhance concurrency policy demonstration with mixed read/write workload Signed-off-by: FrozenlemonTee <1115306170@qq.com> --- examples/ex05_concurrency_policy.cpp | 121 ++++++++++++++++++++------- 1 file changed, 91 insertions(+), 30 deletions(-) diff --git a/examples/ex05_concurrency_policy.cpp b/examples/ex05_concurrency_policy.cpp index 27a6cc2..2d52058 100644 --- a/examples/ex05_concurrency_policy.cpp +++ b/examples/ex05_concurrency_policy.cpp @@ -2,13 +2,14 @@ * Example: ex05_concurrency_policy * * Purpose: - * Demonstrate the fenced concurrency policy path under multi-threaded - * repeated dispatch. + * Demonstrate a more representative read/write mixed workload under fenced + * concurrency policy. * * Expected results: - * - Concurrent add operations consistently produce value 42. - * - Primitive load/store/CAS APIs work under fenced policy. - * - mismatch_count remains zero after all worker threads join. + * - Writer threads continuously update shared operands via store(). + * - Reader threads concurrently run add/sub dispatch and write snapshots. + * - No dispatch error and no range violation are observed. + * - Primitive load/store/CAS APIs all work under fenced policy. * - Program prints a success message and exits with code 0. */ @@ -22,49 +23,109 @@ import mcpplibs.primitives; using namespace mcpplibs::primitives; int main() { - // Point 5: Use fenced concurrency policy and verify concurrent consistency. + // Point 5: Use fenced concurrency policy in a read/write mixed scenario. using fenced_t = primitive; - auto const lhs = fenced_t{12}; - auto const rhs = fenced_t{30}; + constexpr int kWriterThreads = 4; + constexpr int kReaderThreads = 6; + constexpr int kIterationsPerThread = 20000; + constexpr int kMaxOperand = 100000; - auto concurrent_value = fenced_t{1}; - concurrent_value.store(2); - auto expected = 2; - if (!concurrent_value.compare_exchange(expected, 3) || - concurrent_value.load() != 3) { - std::cerr << "fenced load/store/CAS mismatch\n"; - return 1; - } + auto lhs = fenced_t{0}; + auto rhs = fenced_t{0}; + auto sink = fenced_t{0}; + + std::atomic add_error_count{0}; + std::atomic sub_error_count{0}; + std::atomic range_violation_count{0}; + std::atomic start{false}; - std::atomic mismatch_count{0}; std::vector workers; - workers.reserve(4); - - // Run many concurrent dispatches. Any error or wrong value is counted. - for (int i = 0; i < 4; ++i) { - workers.emplace_back([&]() { - for (int n = 0; n < 10000; ++n) { - auto const out = operations::add(lhs, rhs); - if (!out.has_value() || out->value() != 42) { - mismatch_count.fetch_add(1, std::memory_order_relaxed); + workers.reserve(kWriterThreads + kReaderThreads); + + // Writers continuously publish operand updates. + for (int writer = 0; writer < kWriterThreads; ++writer) { + workers.emplace_back([&, writer]() { + while (!start.load(std::memory_order_acquire)) { + } + + for (int n = 0; n < kIterationsPerThread; ++n) { + auto const next_lhs = (writer + n) % (kMaxOperand + 1); + auto const next_rhs = (writer * 3 + n * 7) % (kMaxOperand + 1); + lhs.store(next_lhs); + rhs.store(next_rhs); + } + }); + } + + // Readers mix load + dispatch + store paths. + for (int reader = 0; reader < kReaderThreads; ++reader) { + workers.emplace_back([&, reader]() { + while (!start.load(std::memory_order_acquire)) { + } + + for (int n = 0; n < kIterationsPerThread; ++n) { + if (((reader + n) & 1) == 0) { + auto const out = operations::add(lhs, rhs); + if (!out.has_value()) { + add_error_count.fetch_add(1, std::memory_order_relaxed); + continue; + } + + auto const value = out->load(); + if (value < 0 || value > (kMaxOperand * 2)) { + range_violation_count.fetch_add(1, std::memory_order_relaxed); + } + + sink.store(value); + continue; + } + + auto const out = operations::sub(lhs, rhs); + if (!out.has_value()) { + sub_error_count.fetch_add(1, std::memory_order_relaxed); + continue; + } + + auto const value = out->load(); + if (value < -kMaxOperand || value > kMaxOperand) { + range_violation_count.fetch_add(1, std::memory_order_relaxed); } + + sink.store(value); } }); } + start.store(true, std::memory_order_release); + for (auto &worker : workers) { worker.join(); } - // A non-zero mismatch count indicates unexpected behavior under concurrency. - if (mismatch_count.load(std::memory_order_relaxed) != 0) { - std::cerr << "fenced policy path mismatch\n"; + auto expected = sink.load(); + auto const cas_ok = sink.compare_exchange(expected, expected + 1); + if (!cas_ok || sink.load() != expected + 1) { + std::cerr << "fenced CAS failed after mixed workload\n"; + return 1; + } + + if (add_error_count.load(std::memory_order_relaxed) != 0 || + sub_error_count.load(std::memory_order_relaxed) != 0 || + range_violation_count.load(std::memory_order_relaxed) != 0) { + std::cerr << "concurrency workload mismatch: add_err=" + << add_error_count.load(std::memory_order_relaxed) + << ", sub_err=" + << sub_error_count.load(std::memory_order_relaxed) + << ", range_violation=" + << range_violation_count.load(std::memory_order_relaxed) + << '\n'; return 1; } - std::cout << "concurrency_policy demo passed\n"; + std::cout << "concurrency_policy demo passed, final sink=" << sink.load() + << '\n'; return 0; } From db80e87870c5f8a2a2746993d04b8c499adc4938 Mon Sep 17 00:00:00 2001 From: FrozenlemonTee <1115306170@qq.com> Date: Sun, 22 Mar 2026 19:10:58 +0800 Subject: [PATCH 05/17] docs: Revise README to enhance clarity on primitive infrastructure and usage examples Signed-off-by: FrozenlemonTee <1115306170@qq.com> --- README.md | 117 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 67 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index 517f89e..ccc11b0 100644 --- a/README.md +++ b/README.md @@ -2,51 +2,56 @@ > C++23 模块化原语库 - `import mcpplibs.primitives;` -本仓库实现了底层强类型 primitive 基础设施(traits、policy、underlying 类型分类),供上层 `Integer`/`Floating`/`Boolean` 等封装使用。 +本仓库提供可配置的 `primitive` 基础设施(`underlying traits`、`policy`、`operations/dispatcher`),用于统一约束数值计算、错误处理与并发访问语义。 > [!WARNING] -> 目前项目还在开发中,API会随着后续演进而改变 +> 当前项目仍在快速演进中,API 可能发生变更。 ## 特性 - **C++23 模块** — `import mcpplibs.primitives;` - **双构建系统** — 同时支持 xmake 和 CMake -- **CI/CD** — GitHub Actions 多平台构建(Linux / macOS / Windows) -- **标准化结构** — 遵循 [mcpp-style-ref](https://github.com/mcpp-community/mcpp-style-ref) 编码规范 -- **开箱即用** — 包含示例、测试和架构文档 +- **策略驱动行为** — 值/类型/错误/并发策略可组合配置 +- **混合运算支持** — 支持 `primitive` 与 `underlying` 的混合二元运算 +- **并发访问接口** — `primitive::load/store/compare_exchange` ## Operators -该库在 `primitive` 类型上重载了常见的 C++ 算术、位运算和一元运算符。算术行为受策略(policy)控制: +该库为 `primitive` 提供了常见的一元、算术、位运算与比较操作。 +算术结果通过统一分发链路返回 `std::expected<..., policy::error::kind>`。 - 值策略(`policy::value::checked` / `policy::value::saturating` / `policy::value::unchecked`)决定溢出行为; -- 错误策略(`policy::error::throwing` / `policy::error::expected` / `policy::error::terminate`)决定在 `policy::value::checked` 且发生错误时的处理方式。 +- 错误策略(`policy::error::throwing` / `policy::error::expected` / `policy::error::terminate`)决定错误传播方式。 示例: ```cpp +import std; import mcpplibs.primitives; + using namespace mcpplibs::primitives; -using namespace mcpplibs::primitives::policy; +using namespace mcpplibs::primitives::operators; -primitive a{1}, b{2}; -auto c = a + b; // primitive +primitive a{1}; +primitive b{2}; +auto sum = a + b; // std::expected, policy::error::kind> -primitive x{std::numeric_limits::max()}; -primitive y{1}; -auto maybe = x + y; // std::expected, policy::error::kind> +using checked_t = + primitive; +auto maybe_overflow = + checked_t{std::numeric_limits::max()} + checked_t{1}; ``` ## Policy 协议命名空间 -自定义 policy 时,协议入口已按职责拆分到子命名空间: +自定义 policy 时,协议入口按职责拆分到子命名空间: - `policy::type::handler` / `policy::type::handler_available` - `policy::concurrency::handler` / `policy::concurrency::injection` - `policy::value::handler` / `policy::value::decision` - `policy::error::handler` / `policy::error::request` / `policy::error::kind` -预设 policy 标签也按类别归档: +预设 policy 标签: - `policy::value::{checked, unchecked, saturating}` - `policy::type::{strict, compatible, transparent}` @@ -56,22 +61,22 @@ auto maybe = x + y; // std::expected, po 并发策略说明: - `fenced*` 系列是操作级并发语义,通过策略注入内存序 fence; -- `primitive` 存储仍保持统一、零开销布局,不引入额外存储层抽象; -- `primitive::load/store/compare_exchange` 由并发策略的协议实现提供,若策略未实现该协议会在编译期报错。 +- `primitive` 存储仍保持统一、零额外存储抽象; +- `primitive::load/store/compare_exchange` 由并发策略协议提供,若策略未实现会在编译期报错。 示例(并发访问 API): ```cpp using shared_t = primitive; + policy::concurrency::fenced_acq_rel, + policy::error::expected>; shared_t v{1}; v.store(2); auto expected = 2; if (v.compare_exchange(expected, 3)) { - auto now = v.load(); - (void)now; + auto now = v.load(); + (void)now; } ``` @@ -82,26 +87,32 @@ if (v.compare_exchange(expected, 3)) { - `policy::defaults::error` - `policy::defaults::concurrency` +## 示例程序 + +- `ex01_default_arithmetic`: 默认策略下的基础算术运算示例。 +- `ex02_type_policy`: 展示 `strict/compatible` 的类型协商差异,并包含 `underlying` 构造路径对 type 策略的影响。 +- `ex03_value_policy`: 展示 `checked/unchecked/saturating`,并包含与 `underlying` 的混合二元运算行为。 +- `ex04_error_policy`: 展示不同 error 策略的处理方式。 +- `ex05_concurrency_policy`: 读写组合并发场景(writer `store` + reader `add/sub` + `CAS`)示例。 +- `ex06_custom_underlying`: 自定义 underlying traits、rep 校验与 common rep 扩展。 +- `ex07_custom_policy`: 自定义策略协议实现示例。 +- `ex08_custom_operation`: 自定义 operation 扩展示例。 ## 项目结构 ``` mcpplibs-primitives/ -├── src/ # 模块源码 -│ └── primitive.cppm # 主模块接口(导出 traits 与 primitive 聚合) -├── tests/ # 测试 -│ ├── main.cpp -│ └── xmake.lua -├── examples/ # 示例 -│ ├── basic.cpp -│ └── xmake.lua -├── docs/ # 文档 -│ └── architecture.md -├── .github/workflows/ # CI/CD -│ └── ci.yml -├── xmake.lua # xmake 构建配置 -├── CMakeLists.txt # CMake 构建配置 -└── config.xlings # xlings 工具链配置 +├── src/ # 模块源码 +│ ├── primitives.cppm # 顶层聚合模块 +│ ├── primitive/ # primitive 定义与 traits +│ ├── policy/ # policy 标签与协议实现 +│ ├── operations/ # operation tags / dispatcher / operators +│ └── underlying/ # underlying traits 与 common_rep +├── examples/ # ex01 ~ ex08 示例 +├── tests/ # 测试入口与 basic 测试集 +├── xmake.lua # xmake 构建脚本 +├── CMakeLists.txt # CMake 构建脚本 +└── .xlings.json # xlings 包描述文件 ``` ## 快速开始 @@ -111,8 +122,11 @@ import std; import mcpplibs.primitives; int main() { - static_assert(mcpplibs::primitives::std_integer); - return 0; + using namespace mcpplibs::primitives; + + using value_t = primitive; + auto const result = operations::add(value_t{40}, value_t{2}); + return (result.has_value() && result->value() == 42) ? 0 : 1; } ``` @@ -127,17 +141,20 @@ xlings install **使用 xmake** ```bash -xmake build # 构建库 -xmake run basic # 运行基础示例 -xmake run primitives_test # 运行测试 +xmake build mcpplibs-primitives +xmake run basic # 等价于 ex01_default_arithmetic +xmake run ex05_concurrency_policy +xmake run primitives_test ``` **使用 CMake** ```bash cmake -B build -G Ninja -cmake --build build -ctest --test-dir build +cmake --build build --target mcpplibs-primitives +cmake --build build --target ex01_default_arithmetic +cmake --build build --target basic_tests +ctest --test-dir build --output-on-failure ``` ## 集成到构建工具 @@ -147,20 +164,20 @@ ctest --test-dir build ```lua add_repositories("mcpplibs-index https://github.com/mcpplibs/mcpplibs-index.git") -add_requires("templates") +add_requires("primitives") target("myapp") set_kind("binary") set_languages("c++23") add_files("main.cpp") - add_packages("templates") + add_packages("primitives") set_policy("build.c++.modules", true) ``` ## 相关链接 -- [mcpp-style-ref | 现代C++编码/项目风格参考](https://github.com/mcpp-community/mcpp-style-ref) -- [mcpplibs/cmdline | 命令行解析库](https://github.com/mcpplibs/cmdline) -- [mcpp社区官网](https://mcpp.d2learn.org) -- [mcpp | 现代C++爱好者论坛](https://mcpp.d2learn.org/forum) -- [入门教程: 动手学现代C++](https://github.com/Sunrisepeak/mcpp-standard) +- [mcpp-style-ref | 现代 C++ 编码/项目风格参考](https://github.com/mcpp-community/mcpp-style-ref) +- [d2mystl | 从零实现一个迷你STL库](https://github.com/mcpp-community/d2mystl) +- [mcpp 社区官网](https://mcpp.d2learn.org) +- [mcpp | 现代 C++ 爱好者论坛](https://mcpp.d2learn.org/forum) +- [入门教程: 动手学现代 C++](https://github.com/Sunrisepeak/mcpp-standard) From f2f2b7f0833e5c1af16f340ddadb06dfc7b1d249 Mon Sep 17 00:00:00 2001 From: FrozenlemonTee <1115306170@qq.com> Date: Sun, 22 Mar 2026 19:15:28 +0800 Subject: [PATCH 06/17] docs: Update README to include badges and links for enhanced visibility and navigation Signed-off-by: FrozenlemonTee <1115306170@qq.com> --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index ccc11b0..2177899 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,14 @@ > C++23 模块化原语库 - `import mcpplibs.primitives;` +[![d2x](https://img.shields.io/badge/d2x-ok-green.svg)](https://github.com/d2learn/d2x) +[![Online-ebook](https://img.shields.io/badge/online-ebook-orange.svg)](https://github.com/d2learn/d2x) +[![License](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](LICENSE-CODE) + +| [中文](README.zh.md) - [English](README.md) | +| --- | +| [d2x Tool](https://github.com/d2learn/d2x) - [Docs](https://mcpp-community.github.io/d2mystl) - [Forum](https://mcpp.d2learn.org/forum) | + 本仓库提供可配置的 `primitive` 基础设施(`underlying traits`、`policy`、`operations/dispatcher`),用于统一约束数值计算、错误处理与并发访问语义。 > [!WARNING] From 8b8928b3dc98b96f5272dfc9be6e7366e2bc3740 Mon Sep 17 00:00:00 2001 From: FrozenlemonTee <1115306170@qq.com> Date: Sun, 22 Mar 2026 19:19:40 +0800 Subject: [PATCH 07/17] docs: Update README for improved clarity and add Chinese translation Signed-off-by: FrozenlemonTee <1115306170@qq.com> --- README.md | 112 +++++++++++++++--------------- README.zh.md | 191 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 247 insertions(+), 56 deletions(-) create mode 100644 README.zh.md diff --git a/README.md b/README.md index 2177899..5b46116 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # mcpplibs primitives -> C++23 模块化原语库 - `import mcpplibs.primitives;` +> C++23 modular primitives library - `import mcpplibs.primitives;` [![d2x](https://img.shields.io/badge/d2x-ok-green.svg)](https://github.com/d2learn/d2x) [![Online-ebook](https://img.shields.io/badge/online-ebook-orange.svg)](https://github.com/d2learn/d2x) @@ -10,28 +10,28 @@ | --- | | [d2x Tool](https://github.com/d2learn/d2x) - [Docs](https://mcpp-community.github.io/d2mystl) - [Forum](https://mcpp.d2learn.org/forum) | -本仓库提供可配置的 `primitive` 基础设施(`underlying traits`、`policy`、`operations/dispatcher`),用于统一约束数值计算、错误处理与并发访问语义。 +This repository provides configurable `primitive` infrastructure (`underlying traits`, `policy`, and `operations/dispatcher`) to unify numeric behavior, error handling, and concurrency access semantics. > [!WARNING] -> 当前项目仍在快速演进中,API 可能发生变更。 +> The project is still evolving quickly, and APIs may change. -## 特性 +## Features -- **C++23 模块** — `import mcpplibs.primitives;` -- **双构建系统** — 同时支持 xmake 和 CMake -- **策略驱动行为** — 值/类型/错误/并发策略可组合配置 -- **混合运算支持** — 支持 `primitive` 与 `underlying` 的混合二元运算 -- **并发访问接口** — `primitive::load/store/compare_exchange` +- **C++23 modules** — `import mcpplibs.primitives;` +- **Dual build systems** — both xmake and CMake are supported +- **Policy-driven behavior** — value/type/error/concurrency policies are composable +- **Mixed operations support** — binary operations between `primitive` and `underlying` are supported +- **Concurrency access APIs** — `primitive::load/store/compare_exchange` ## Operators -该库为 `primitive` 提供了常见的一元、算术、位运算与比较操作。 -算术结果通过统一分发链路返回 `std::expected<..., policy::error::kind>`。 +The library provides unary, arithmetic, bitwise, and comparison operations for `primitive`. +Arithmetic paths are dispatched through a unified pipeline and return `std::expected<..., policy::error::kind>`. -- 值策略(`policy::value::checked` / `policy::value::saturating` / `policy::value::unchecked`)决定溢出行为; -- 错误策略(`policy::error::throwing` / `policy::error::expected` / `policy::error::terminate`)决定错误传播方式。 +- Value policies (`policy::value::checked` / `policy::value::saturating` / `policy::value::unchecked`) define overflow behavior. +- Error policies (`policy::error::throwing` / `policy::error::expected` / `policy::error::terminate`) define how errors are propagated. -示例: +Example: ```cpp import std; @@ -50,29 +50,29 @@ auto maybe_overflow = checked_t{std::numeric_limits::max()} + checked_t{1}; ``` -## Policy 协议命名空间 +## Policy Protocol Namespaces -自定义 policy 时,协议入口按职责拆分到子命名空间: +When implementing custom policies, protocol entry points are split by responsibility: - `policy::type::handler` / `policy::type::handler_available` - `policy::concurrency::handler` / `policy::concurrency::injection` - `policy::value::handler` / `policy::value::decision` - `policy::error::handler` / `policy::error::request` / `policy::error::kind` -预设 policy 标签: +Built-in policy tags: - `policy::value::{checked, unchecked, saturating}` - `policy::type::{strict, compatible, transparent}` - `policy::error::{throwing, expected, terminate}` - `policy::concurrency::{none, fenced, fenced_relaxed, fenced_acq_rel, fenced_seq_cst}` -并发策略说明: +Concurrency notes: -- `fenced*` 系列是操作级并发语义,通过策略注入内存序 fence; -- `primitive` 存储仍保持统一、零额外存储抽象; -- `primitive::load/store/compare_exchange` 由并发策略协议提供,若策略未实现会在编译期报错。 +- `fenced*` policies provide operation-level concurrency semantics with injected memory-order fences. +- `primitive` storage keeps a uniform, zero-extra-storage abstraction. +- `primitive::load/store/compare_exchange` are provided by concurrency policy protocols and fail at compile time if unsupported. -示例(并发访问 API): +Example (concurrent access APIs): ```cpp using shared_t = primitive C++23 模块化原语库 - `import mcpplibs.primitives;` + +[![d2x](https://img.shields.io/badge/d2x-ok-green.svg)](https://github.com/d2learn/d2x) +[![Online-ebook](https://img.shields.io/badge/online-ebook-orange.svg)](https://github.com/d2learn/d2x) +[![License](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](LICENSE-CODE) + +| [中文](README.zh.md) - [English](README.md) | +| --- | +| [d2x Tool](https://github.com/d2learn/d2x) - [Docs](https://mcpp-community.github.io/d2mystl) - [Forum](https://mcpp.d2learn.org/forum) | + +本仓库提供可配置的 `primitive` 基础设施(`underlying traits`、`policy`、`operations/dispatcher`),用于统一约束数值计算、错误处理与并发访问语义。 + +> [!WARNING] +> 当前项目仍在快速演进中,API 可能发生变更。 + +## 特性 + +- **C++23 模块** — `import mcpplibs.primitives;` +- **双构建系统** — 同时支持 xmake 和 CMake +- **策略驱动行为** — 值/类型/错误/并发策略可组合配置 +- **混合运算支持** — 支持 `primitive` 与 `underlying` 的混合二元运算 +- **并发访问接口** — `primitive::load/store/compare_exchange` + +## Operators + +该库为 `primitive` 提供了常见的一元、算术、位运算与比较操作。 +算术结果通过统一分发链路返回 `std::expected<..., policy::error::kind>`。 + +- 值策略(`policy::value::checked` / `policy::value::saturating` / `policy::value::unchecked`)决定溢出行为; +- 错误策略(`policy::error::throwing` / `policy::error::expected` / `policy::error::terminate`)决定错误传播方式。 + +示例: + +```cpp +import std; +import mcpplibs.primitives; + +using namespace mcpplibs::primitives; +using namespace mcpplibs::primitives::operators; + +primitive a{1}; +primitive b{2}; +auto sum = a + b; // std::expected, policy::error::kind> + +using checked_t = + primitive; +auto maybe_overflow = + checked_t{std::numeric_limits::max()} + checked_t{1}; +``` + +## Policy 协议命名空间 + +自定义 policy 时,协议入口按职责拆分到子命名空间: + +- `policy::type::handler` / `policy::type::handler_available` +- `policy::concurrency::handler` / `policy::concurrency::injection` +- `policy::value::handler` / `policy::value::decision` +- `policy::error::handler` / `policy::error::request` / `policy::error::kind` + +预设 policy 标签: + +- `policy::value::{checked, unchecked, saturating}` +- `policy::type::{strict, compatible, transparent}` +- `policy::error::{throwing, expected, terminate}` +- `policy::concurrency::{none, fenced, fenced_relaxed, fenced_acq_rel, fenced_seq_cst}` + +并发策略说明: + +- `fenced*` 系列是操作级并发语义,通过策略注入内存序 fence; +- `primitive` 存储仍保持统一、零额外存储抽象; +- `primitive::load/store/compare_exchange` 由并发策略协议提供,若策略未实现会在编译期报错。 + +示例(并发访问 API): + +```cpp +using shared_t = primitive; + +shared_t v{1}; +v.store(2); +auto expected = 2; +if (v.compare_exchange(expected, 3)) { + auto now = v.load(); + (void)now; +} +``` + +默认策略位于 `policy::defaults`: + +- `policy::defaults::value` +- `policy::defaults::type` +- `policy::defaults::error` +- `policy::defaults::concurrency` + +## 示例程序 + +- `ex01_default_arithmetic`: 默认策略下的基础算术运算示例。 +- `ex02_type_policy`: 展示 `strict/compatible` 的类型协商差异,并包含 `underlying` 构造路径对 type 策略的影响。 +- `ex03_value_policy`: 展示 `checked/unchecked/saturating`,并包含与 `underlying` 的混合二元运算行为。 +- `ex04_error_policy`: 展示不同 error 策略的处理方式。 +- `ex05_concurrency_policy`: 读写组合并发场景(writer `store` + reader `add/sub` + `CAS`)示例。 +- `ex06_custom_underlying`: 自定义 underlying traits、rep 校验与 common rep 扩展。 +- `ex07_custom_policy`: 自定义策略协议实现示例。 +- `ex08_custom_operation`: 自定义 operation 扩展示例。 + +## 项目结构 + +``` +mcpplibs-primitives/ +├── src/ # 模块源码 +│ ├── primitives.cppm # 顶层聚合模块 +│ ├── primitive/ # primitive 定义与 traits +│ ├── policy/ # policy 标签与协议实现 +│ ├── operations/ # operation tags / dispatcher / operators +│ └── underlying/ # underlying traits 与 common_rep +├── examples/ # ex01 ~ ex08 示例 +├── tests/ # 测试入口与 basic 测试集 +├── xmake.lua # xmake 构建脚本 +├── CMakeLists.txt # CMake 构建脚本 +└── .xlings.json # xlings 包描述文件 +``` + +## 快速开始 + +```cpp +import std; +import mcpplibs.primitives; + +int main() { + using namespace mcpplibs::primitives; + + using value_t = primitive; + auto const result = operations::add(value_t{40}, value_t{2}); + return (result.has_value() && result->value() == 42) ? 0 : 1; +} +``` + +## 安装与配置 + +```bash +xlings install +``` + +## 构建与运行 + +**使用 xmake** + +```bash +xmake build mcpplibs-primitives +xmake run basic # 等价于 ex01_default_arithmetic +xmake run ex05_concurrency_policy +xmake run primitives_test +``` + +**使用 CMake** + +```bash +cmake -B build -G Ninja +cmake --build build --target mcpplibs-primitives +cmake --build build --target ex01_default_arithmetic +cmake --build build --target basic_tests +ctest --test-dir build --output-on-failure +``` + +## 集成到构建工具 + +### xmake + +```lua +add_repositories("mcpplibs-index https://github.com/mcpplibs/mcpplibs-index.git") + +add_requires("primitives") + +target("myapp") + set_kind("binary") + set_languages("c++23") + add_files("main.cpp") + add_packages("primitives") + set_policy("build.c++.modules", true) +``` + +## 相关链接 + +- [mcpp-style-ref | 现代 C++ 编码/项目风格参考](https://github.com/mcpp-community/mcpp-style-ref) +- [d2mystl | 从零实现一个迷你STL库](https://github.com/mcpp-community/d2mystl) +- [mcpp 社区官网](https://mcpp.d2learn.org) +- [mcpp | 现代 C++ 爱好者论坛](https://mcpp.d2learn.org/forum) +- [入门教程: 动手学现代 C++](https://github.com/Sunrisepeak/mcpp-standard) From 6addd3e3137e5433bf5e5dcfc38b7e85d0c310cf Mon Sep 17 00:00:00 2001 From: FrozenlemonTee <1115306170@qq.com> Date: Sun, 22 Mar 2026 20:51:03 +0800 Subject: [PATCH 08/17] bump: Update project version to 0.3.0 in CMakeLists.txt and xmake.lua Signed-off-by: FrozenlemonTee <1115306170@qq.com> --- CMakeLists.txt | 2 +- xmake.lua | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index afca2fc..3439b31 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,7 +6,7 @@ set(CMAKE_CXX_STANDARD 23) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) -project(mcpplibs-primitives VERSION 0.2.0 LANGUAGES CXX) +project(mcpplibs-primitives VERSION 0.3.0 LANGUAGES CXX) find_package(Threads REQUIRED) diff --git a/xmake.lua b/xmake.lua index 3b780dc..f51dd6b 100644 --- a/xmake.lua +++ b/xmake.lua @@ -1,3 +1,6 @@ +set_project("mcpplibs-primitives") +set_version("0.3.0") + add_rules("mode.release", "mode.debug") set_languages("c++23") From aac10d99f6e7186215749c4861c5a56aa62ce7da Mon Sep 17 00:00:00 2001 From: FrozenlemonTee <1115306170@qq.com> Date: Sun, 22 Mar 2026 20:55:28 +0800 Subject: [PATCH 09/17] docs: Add initial README file for project documentation Signed-off-by: FrozenlemonTee <1115306170@qq.com> --- docs/en/README.md | 0 docs/zh/README.md | 0 2 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 docs/en/README.md create mode 100644 docs/zh/README.md diff --git a/docs/en/README.md b/docs/en/README.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/zh/README.md b/docs/zh/README.md new file mode 100644 index 0000000..e69de29 From 968cbbfbfa0d94571d4a2e9346e07b28d2fab0a2 Mon Sep 17 00:00:00 2001 From: FrozenlemonTee <1115306170@qq.com> Date: Sun, 22 Mar 2026 20:55:34 +0800 Subject: [PATCH 10/17] docs: Update README files to enhance links and navigation for user documentation Signed-off-by: FrozenlemonTee <1115306170@qq.com> --- README.md | 6 +++--- README.zh.md | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 5b46116..7d2bfcb 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,9 @@ [![Online-ebook](https://img.shields.io/badge/online-ebook-orange.svg)](https://github.com/d2learn/d2x) [![License](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](LICENSE-CODE) -| [中文](README.zh.md) - [English](README.md) | -| --- | -| [d2x Tool](https://github.com/d2learn/d2x) - [Docs](https://mcpp-community.github.io/d2mystl) - [Forum](https://mcpp.d2learn.org/forum) | +| [中文](README.zh.md) - [English](README.md) | +|---------------------------------------------------------------------------------------------------------------------------------------| +| [中文用户文档](docs/zh/README.md) - [English User Documentation](docs/en/README.md) - [Forum](https://mcpp.d2learn.org/forum) | This repository provides configurable `primitive` infrastructure (`underlying traits`, `policy`, and `operations/dispatcher`) to unify numeric behavior, error handling, and concurrency access semantics. diff --git a/README.zh.md b/README.zh.md index 2177899..dc66260 100644 --- a/README.zh.md +++ b/README.zh.md @@ -6,9 +6,9 @@ [![Online-ebook](https://img.shields.io/badge/online-ebook-orange.svg)](https://github.com/d2learn/d2x) [![License](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](LICENSE-CODE) -| [中文](README.zh.md) - [English](README.md) | -| --- | -| [d2x Tool](https://github.com/d2learn/d2x) - [Docs](https://mcpp-community.github.io/d2mystl) - [Forum](https://mcpp.d2learn.org/forum) | +| [中文](README.zh.md) - [English](README.md) | +|----------------------------------------------------------------------------------------------------------------------| +| [中文用户文档](docs/zh/README.md) - [English User Documentation](docs/en/README.md) - [论坛](https://mcpp.d2learn.org/forum) | 本仓库提供可配置的 `primitive` 基础设施(`underlying traits`、`policy`、`operations/dispatcher`),用于统一约束数值计算、错误处理与并发访问语义。 From 2ce626a6aec77f8f6523edba94abc39d3862011f Mon Sep 17 00:00:00 2001 From: FrozenlemonTee <1115306170@qq.com> Date: Sun, 22 Mar 2026 21:08:09 +0800 Subject: [PATCH 11/17] docs: Update README files to improve navigation and add user and API documentation links Signed-off-by: FrozenlemonTee <1115306170@qq.com> --- README.md | 7 ++++--- README.zh.md | 7 ++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 7d2bfcb..efedd65 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,10 @@ [![Online-ebook](https://img.shields.io/badge/online-ebook-orange.svg)](https://github.com/d2learn/d2x) [![License](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](LICENSE-CODE) -| [中文](README.zh.md) - [English](README.md) | -|---------------------------------------------------------------------------------------------------------------------------------------| -| [中文用户文档](docs/zh/README.md) - [English User Documentation](docs/en/README.md) - [Forum](https://mcpp.d2learn.org/forum) | +| [中文](README.zh.md) - [English](README.md) - [Forum](https://mcpp.d2learn.org/forum) | +|---------------------------------------------------------------------------------| +| [用户文档](docs/guide/zh/README.md) - [User Documentation](docs/guide/en/README.md) | +| [API文档](docs/guide/api/README.md) - [API Documentation](docs/api/en/README.md) | This repository provides configurable `primitive` infrastructure (`underlying traits`, `policy`, and `operations/dispatcher`) to unify numeric behavior, error handling, and concurrency access semantics. diff --git a/README.zh.md b/README.zh.md index dc66260..1f10f6a 100644 --- a/README.zh.md +++ b/README.zh.md @@ -6,9 +6,10 @@ [![Online-ebook](https://img.shields.io/badge/online-ebook-orange.svg)](https://github.com/d2learn/d2x) [![License](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](LICENSE-CODE) -| [中文](README.zh.md) - [English](README.md) | -|----------------------------------------------------------------------------------------------------------------------| -| [中文用户文档](docs/zh/README.md) - [English User Documentation](docs/en/README.md) - [论坛](https://mcpp.d2learn.org/forum) | +| [中文](README.zh.md) - [English](README.md) - [论坛](https://mcpp.d2learn.org/forum) | +|----------------------------------------------------------------------------------| +| [用户文档](docs/guide/zh/README.md) - [User Documentation](docs/guide/en/README.md) | +| [API文档](docs/guide/api/README.md) - [API Documentation](docs/api/en/README.md) | 本仓库提供可配置的 `primitive` 基础设施(`underlying traits`、`policy`、`operations/dispatcher`),用于统一约束数值计算、错误处理与并发访问语义。 From 2ee202aab982776486731ef6d5ce867a456da00f Mon Sep 17 00:00:00 2001 From: FrozenlemonTee <1115306170@qq.com> Date: Sun, 22 Mar 2026 21:08:22 +0800 Subject: [PATCH 12/17] docs: Consolidate README files from language-specific directories into the root Signed-off-by: FrozenlemonTee <1115306170@qq.com> --- docs/{ => api}/en/README.md | 0 docs/{ => api}/zh/README.md | 0 docs/guide/en/README.md | 0 docs/guide/zh/README.md | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename docs/{ => api}/en/README.md (100%) rename docs/{ => api}/zh/README.md (100%) create mode 100644 docs/guide/en/README.md create mode 100644 docs/guide/zh/README.md diff --git a/docs/en/README.md b/docs/api/en/README.md similarity index 100% rename from docs/en/README.md rename to docs/api/en/README.md diff --git a/docs/zh/README.md b/docs/api/zh/README.md similarity index 100% rename from docs/zh/README.md rename to docs/api/zh/README.md diff --git a/docs/guide/en/README.md b/docs/guide/en/README.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/guide/zh/README.md b/docs/guide/zh/README.md new file mode 100644 index 0000000..e69de29 From 6020dbb66a6bec5c26a4725ef872e86c5645da4a Mon Sep 17 00:00:00 2001 From: FrozenlemonTee <1115306170@qq.com> Date: Sun, 22 Mar 2026 21:30:57 +0800 Subject: [PATCH 13/17] docs: Add API documentation for primitives module in English and Chinese Signed-off-by: FrozenlemonTee <1115306170@qq.com> --- docs/api/en/README.md | 246 ++++++++++++++++++++++++++++++++++++++++++ docs/api/zh/README.md | 246 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 492 insertions(+) diff --git a/docs/api/en/README.md b/docs/api/en/README.md index e69de29..345e74b 100644 --- a/docs/api/en/README.md +++ b/docs/api/en/README.md @@ -0,0 +1,246 @@ +# primitives API Documentation + +> Module entry: `import mcpplibs.primitives;` + +## Module Entry + +Top-level import: + +```cpp +import mcpplibs.primitives; +``` + +This module exports: + +- `mcpplibs.primitives.underlying` +- `mcpplibs.primitives.policy` +- `mcpplibs.primitives.primitive` +- `mcpplibs.primitives.operations` + +## Namespace Overview + +- `mcpplibs::primitives`: core types, concepts, and `primitive`. +- `mcpplibs::primitives::underlying`: underlying traits and categories. +- `mcpplibs::primitives::policy`: policy tags, defaults, and protocols. +- `mcpplibs::primitives::operations`: functional dispatch API. +- `mcpplibs::primitives::operators`: operator overload entry. +- `mcpplibs::primitives::meta`: primitive metadata traits. +- `mcpplibs::primitives::types`: convenience aliases for common underlying types. + +## Core Concepts and Metadata + +### underlying concepts + +- `underlying_type` +- `boolean_underlying_type` +- `character_underlying_type` +- `integer_underlying_type` +- `floating_underlying_type` +- `numeric_underlying_type` +- `has_common_rep` +- `common_rep_t` + +### policy concepts + +- `policy::policy_type

` +- `policy::value_policy

` +- `policy::type_policy

` +- `policy::error_policy

` +- `policy::concurrency_policy

` +- `policy::resolve_policy_t` + +### primitive metadata + +- `meta::traits>` + exposes `value_type / policies / value_policy / type_policy / error_policy / concurrency_policy` +- `meta::make_primitive_t` + +## `primitive` + +```cpp +template +class primitive; +``` + +### Member types + +- `value_type = T` +- `policies = std::tuple` + +### Construction and assignment + +- `explicit primitive(T)`: same-underlying construction. +- `explicit primitive(U)`: cross-underlying construction (subject to type policy). +- Copy/move construction and assignment are supported for the same policy set. +- Cross-underlying primitive construction/assignment is supported when allowed by type policy. + +### Value and concurrency access APIs + +- `value()` / `value() const` +- `explicit operator value_type() const` +- `load() -> value_type` +- `store(desired)` +- `compare_exchange(expected, desired) -> bool` + +Notes: + +- `store/compare_exchange` always support same-underlying types. +- Cross-underlying `store/compare_exchange` are available only when type policy allows. +- Access APIs are provided by `policy::concurrency::handler<..., void, ...>`. + +### Type policy impact on cross-underlying behavior + +- `policy::type::strict`: only identical types are allowed. +- `policy::type::compatible`: requires same underlying category and a valid `common_rep`. +- `policy::type::transparent`: only requires a valid `common_rep`. + +### Convenience aliases (`types`) + +- Integers: `U8/U16/U32/U64`, `I8/I16/I32/I64` +- Floating-point: `F32/F64/F80` +- Bool/chars: `Bool/UChar/Char8/Char16/Char32/WChar` + +Example: + +```cpp +using value_t = mcpplibs::primitives::types::I32< + mcpplibs::primitives::policy::value::checked, + mcpplibs::primitives::policy::error::expected>; +``` + +## `operations` API + +The `operations` namespace provides function-style APIs with unified `std::expected` results. + +### Common result aliases + +- `primitive_dispatch_result_t` +- `mixed_primitive_dispatch_result_t` +- `three_way_dispatch_result_t` + +### Unary operations + +- `increment` +- `decrement` +- `bit_not` +- `unary_plus` +- `unary_minus` + +### Binary arithmetic + +- `add` +- `sub` +- `mul` +- `div` +- `mod` + +### Binary bitwise + +- `shift_left` +- `shift_right` +- `bit_and` +- `bit_or` +- `bit_xor` + +### Comparisons + +- `equal` +- `not_equal` +- `three_way_compare` + +### Compound assignments + +- `add_assign/sub_assign/mul_assign/div_assign/mod_assign` +- `shift_left_assign/shift_right_assign` +- `bit_and_assign/bit_or_assign/bit_xor_assign` + +### Mixed operand support + +Most binary operations support: + +- `primitive op primitive` +- `primitive op underlying` +- `underlying op primitive` + +## `operators` overloads + +To use `+ - * / % ...` syntax, import: + +```cpp +using namespace mcpplibs::primitives::operators; +``` + +Operator results are still `std::expected<...>`, not raw values. + +## policy API + +### Built-in policy tags + +- Value: `policy::value::{checked, unchecked, saturating}` +- Type: `policy::type::{strict, compatible, transparent}` +- Error: `policy::error::{throwing, expected, terminate}` +- Concurrency: `policy::concurrency::{none, fenced, fenced_relaxed, fenced_acq_rel, fenced_seq_cst}` + +### Defaults + +- `policy::defaults::value = policy::value::checked` +- `policy::defaults::type = policy::type::strict` +- `policy::defaults::error = policy::error::throwing` +- `policy::defaults::concurrency = policy::concurrency::none` + +### Error kinds + +`policy::error::kind`: + +- `none` +- `invalid_type_combination` +- `overflow` +- `underflow` +- `divide_by_zero` +- `domain_error` +- `unspecified` + +## underlying Extension Points + +### 1) Register `underlying::traits` + +Required members: + +- `value_type` +- `rep_type` +- `enabled` +- `kind` +- `to_rep(value)` +- `from_rep(rep)` +- `is_valid_rep(rep)` + +### 2) Customize common-rep negotiation + +Specialize `underlying::common_rep_traits` to override the default `std::common_type_t` behavior. + +## Result and Error Model + +- Most operations/operators APIs return `std::expected<...>`. +- With `policy::error::expected`, failures are returned as `unexpected(policy::error::kind)`. +- With `policy::error::throwing`, runtime failures throw exceptions (while API signatures still use `std::expected`). + +## Minimal Example + +```cpp +import std; +import mcpplibs.primitives; + +using namespace mcpplibs::primitives; +using namespace mcpplibs::primitives::operators; + +int main() { + using value_t = + primitive; + + auto const out = value_t{40} + value_t{2}; + if (!out.has_value()) { + return 1; + } + return out->value() == 42 ? 0 : 1; +} +``` diff --git a/docs/api/zh/README.md b/docs/api/zh/README.md index e69de29..515b625 100644 --- a/docs/api/zh/README.md +++ b/docs/api/zh/README.md @@ -0,0 +1,246 @@ +# primitives API 文档 + +> 适用模块:`import mcpplibs.primitives;` + +## 模块入口 + +顶层模块: + +```cpp +import mcpplibs.primitives; +``` + +该模块导出以下子模块: + +- `mcpplibs.primitives.underlying` +- `mcpplibs.primitives.policy` +- `mcpplibs.primitives.primitive` +- `mcpplibs.primitives.operations` + +## 命名空间总览 + +- `mcpplibs::primitives`: 核心类型、概念与 `primitive`。 +- `mcpplibs::primitives::underlying`: underlying traits 与类别。 +- `mcpplibs::primitives::policy`: policy 标签、默认值与协议。 +- `mcpplibs::primitives::operations`: 分发函数 API。 +- `mcpplibs::primitives::operators`: 运算符重载入口。 +- `mcpplibs::primitives::meta`: primitive 元信息 traits。 +- `mcpplibs::primitives::types`: 常用 underlying 的 primitive 别名。 + +## 核心概念与元信息 + +### underlying 相关概念 + +- `underlying_type` +- `boolean_underlying_type` +- `character_underlying_type` +- `integer_underlying_type` +- `floating_underlying_type` +- `numeric_underlying_type` +- `has_common_rep` +- `common_rep_t` + +### policy 相关概念 + +- `policy::policy_type

` +- `policy::value_policy

` +- `policy::type_policy

` +- `policy::error_policy

` +- `policy::concurrency_policy

` +- `policy::resolve_policy_t` + +### primitive 元信息 + +- `meta::traits>` + 暴露 `value_type / policies / value_policy / type_policy / error_policy / concurrency_policy` +- `meta::make_primitive_t` + +## `primitive` + +```cpp +template +class primitive; +``` + +### 成员类型 + +- `value_type = T` +- `policies = std::tuple` + +### 主要构造与赋值 + +- `explicit primitive(T)`:同 underlying 构造。 +- `explicit primitive(U)`:跨 underlying 构造(是否允许由 type 策略决定)。 +- 支持同策略组下的拷贝/移动构造与赋值。 +- 支持同策略组、不同 underlying 的 primitive 互构造/赋值(受 type 策略约束)。 + +### 值访问与并发访问 API + +- `value()` / `value() const` +- `explicit operator value_type() const` +- `load() -> value_type` +- `store(desired)` +- `compare_exchange(expected, desired) -> bool` + +说明: + +- `store/compare_exchange` 支持同 underlying。 +- 在 type 策略允许时,`store/compare_exchange` 也支持跨 underlying 参数。 +- 并发访问能力由 `policy::concurrency::handler<..., void, ...>` 提供。 + +### type 策略对跨 underlying 行为的影响 + +- `policy::type::strict`:仅同类型允许,跨 underlying 构造/存储/CAS 不可用。 +- `policy::type::compatible`:要求同 underlying category 且可协商 `common_rep`。 +- `policy::type::transparent`:只要求可协商 `common_rep`。 + +### 预定义别名(`types`) + +- 整型:`U8/U16/U32/U64`、`I8/I16/I32/I64` +- 浮点:`F32/F64/F80` +- 布尔/字符:`Bool/UChar/Char8/Char16/Char32/WChar` + +用法示例: + +```cpp +using value_t = mcpplibs::primitives::types::I32< + mcpplibs::primitives::policy::value::checked, + mcpplibs::primitives::policy::error::expected>; +``` + +## `operations` API + +`operations` 命名空间提供函数式调用接口,统一返回 `std::expected`。 + +### 常用结果类型别名 + +- `primitive_dispatch_result_t` +- `mixed_primitive_dispatch_result_t` +- `three_way_dispatch_result_t` + +### 一元操作 + +- `increment` +- `decrement` +- `bit_not` +- `unary_plus` +- `unary_minus` + +### 二元算术 + +- `add` +- `sub` +- `mul` +- `div` +- `mod` + +### 二元位运算 + +- `shift_left` +- `shift_right` +- `bit_and` +- `bit_or` +- `bit_xor` + +### 比较 + +- `equal` +- `not_equal` +- `three_way_compare` + +### 复合赋值 + +- `add_assign/sub_assign/mul_assign/div_assign/mod_assign` +- `shift_left_assign/shift_right_assign` +- `bit_and_assign/bit_or_assign/bit_xor_assign` + +### 混合操作支持 + +对多数二元操作,支持以下三种形式: + +- `primitive op primitive` +- `primitive op underlying` +- `underlying op primitive` + +## `operators` 运算符重载 + +若需要 `+ - * / % ...` 运算符语法,请引入: + +```cpp +using namespace mcpplibs::primitives::operators; +``` + +重载结果同样是 `std::expected<...>`,不是裸值。 + +## policy API + +### 内置策略标签 + +- 值策略:`policy::value::{checked, unchecked, saturating}` +- 类型策略:`policy::type::{strict, compatible, transparent}` +- 错误策略:`policy::error::{throwing, expected, terminate}` +- 并发策略:`policy::concurrency::{none, fenced, fenced_relaxed, fenced_acq_rel, fenced_seq_cst}` + +### 默认策略 + +- `policy::defaults::value = policy::value::checked` +- `policy::defaults::type = policy::type::strict` +- `policy::defaults::error = policy::error::throwing` +- `policy::defaults::concurrency = policy::concurrency::none` + +### 错误码 + +`policy::error::kind`: + +- `none` +- `invalid_type_combination` +- `overflow` +- `underflow` +- `divide_by_zero` +- `domain_error` +- `unspecified` + +## underlying 扩展点 + +### 1) 注册 `underlying::traits` + +需要提供: + +- `value_type` +- `rep_type` +- `enabled` +- `kind` +- `to_rep(value)` +- `from_rep(rep)` +- `is_valid_rep(rep)` + +### 2) 自定义 common rep 协商 + +可特化 `underlying::common_rep_traits`,以覆盖默认 `std::common_type_t` 规则。 + +## 返回模型与错误处理模型 + +- 绝大多数 operations/operators API 返回 `std::expected<...>`。 +- 当错误策略为 `policy::error::expected` 时,错误通过 `unexpected(policy::error::kind)` 返回。 +- 当错误策略为 `policy::error::throwing` 时,运行期错误会抛出异常(签名仍保持 `std::expected`)。 + +## 最小示例 + +```cpp +import std; +import mcpplibs.primitives; + +using namespace mcpplibs::primitives; +using namespace mcpplibs::primitives::operators; + +int main() { + using value_t = + primitive; + + auto const out = value_t{40} + value_t{2}; + if (!out.has_value()) { + return 1; + } + return out->value() == 42 ? 0 : 1; +} +``` From 32b5300d7c9e8e9a208dace34c52c60e73374a4f Mon Sep 17 00:00:00 2001 From: FrozenlemonTee <1115306170@qq.com> Date: Sun, 22 Mar 2026 21:31:18 +0800 Subject: [PATCH 14/17] docs: Add user guide for primitives module in English and Chinese Signed-off-by: FrozenlemonTee <1115306170@qq.com> --- docs/guide/en/README.md | 15 +++++++++++++++ docs/guide/zh/README.md | 15 +++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/docs/guide/en/README.md b/docs/guide/en/README.md index e69de29..cad9506 100644 --- a/docs/guide/en/README.md +++ b/docs/guide/en/README.md @@ -0,0 +1,15 @@ +# primitives User Guide (English) + +This section is organized by workflow. Start with installation, then quick start. + +## Reading Order + +1. [Installation and Build](./installation-and-build.md) +2. [Quick Start](./quick-start.md) +3. [Concurrency Guide](./concurrency.md) +4. [Extension Guide](./extension.md) + +## Related Docs + +- API reference: [../../api/en/README.md](../../api/en/README.md) +- Docs root: [../../README.md](../../README.md) diff --git a/docs/guide/zh/README.md b/docs/guide/zh/README.md index e69de29..27b3d81 100644 --- a/docs/guide/zh/README.md +++ b/docs/guide/zh/README.md @@ -0,0 +1,15 @@ +# primitives 用户文档(中文) + +本节按使用流程组织。建议先看安装构建,再看快速上手。 + +## 阅读顺序 + +1. [安装与构建](./installation-and-build.md) +2. [快速上手](./quick-start.md) +3. [并发使用指南](./concurrency.md) +4. [扩展开发指南](./extension.md) + +## 相关文档 + +- API 参考: [../../api/zh/README.md](../../api/zh/README.md) +- 文档总入口: [../../README.md](../../README.md) From e3222e674cf361b6534faea6952a95a6be8b10f0 Mon Sep 17 00:00:00 2001 From: FrozenlemonTee <1115306170@qq.com> Date: Sun, 22 Mar 2026 21:31:41 +0800 Subject: [PATCH 15/17] docs: Add user and API documentation guides in English and Chinese Signed-off-by: FrozenlemonTee <1115306170@qq.com> --- docs/README.md | 12 ++++ docs/api/README.md | 5 ++ docs/guide/README.md | 5 ++ docs/guide/en/concurrency.md | 75 +++++++++++++++++++++ docs/guide/en/extension.md | 77 +++++++++++++++++++++ docs/guide/en/installation-and-build.md | 89 ++++++++++++++++++++++++ docs/guide/en/quick-start.md | 90 +++++++++++++++++++++++++ docs/guide/zh/concurrency.md | 75 +++++++++++++++++++++ docs/guide/zh/extension.md | 77 +++++++++++++++++++++ docs/guide/zh/installation-and-build.md | 89 ++++++++++++++++++++++++ docs/guide/zh/quick-start.md | 90 +++++++++++++++++++++++++ 11 files changed, 684 insertions(+) create mode 100644 docs/README.md create mode 100644 docs/api/README.md create mode 100644 docs/guide/README.md create mode 100644 docs/guide/en/concurrency.md create mode 100644 docs/guide/en/extension.md create mode 100644 docs/guide/en/installation-and-build.md create mode 100644 docs/guide/en/quick-start.md create mode 100644 docs/guide/zh/concurrency.md create mode 100644 docs/guide/zh/extension.md create mode 100644 docs/guide/zh/installation-and-build.md create mode 100644 docs/guide/zh/quick-start.md diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..77db821 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,12 @@ +# Documentation + +## Guide + +- [中文用户文档](./guide/zh/README.md) +- [English User Guide](./guide/en/README.md) + +## API + +- [中文 API 文档](./api/zh/README.md) +- [English API Documentation](./api/en/README.md) + diff --git a/docs/api/README.md b/docs/api/README.md new file mode 100644 index 0000000..9ba1de9 --- /dev/null +++ b/docs/api/README.md @@ -0,0 +1,5 @@ +# API Documentation + +- [中文 API 文档](./zh/README.md) +- [English API Documentation](./en/README.md) + diff --git a/docs/guide/README.md b/docs/guide/README.md new file mode 100644 index 0000000..c947c88 --- /dev/null +++ b/docs/guide/README.md @@ -0,0 +1,5 @@ +# User Guide + +- [中文用户文档](./zh/README.md) +- [English User Guide](./en/README.md) + diff --git a/docs/guide/en/concurrency.md b/docs/guide/en/concurrency.md new file mode 100644 index 0000000..f2d65b5 --- /dev/null +++ b/docs/guide/en/concurrency.md @@ -0,0 +1,75 @@ +# Concurrency Guide + +## Concurrency Policies + +Built-in concurrency policies: + +- `policy::concurrency::none` +- `policy::concurrency::fenced` +- `policy::concurrency::fenced_relaxed` +- `policy::concurrency::fenced_acq_rel` +- `policy::concurrency::fenced_seq_cst` + +General guidance: + +- Use `none` for single-threaded paths. +- Use `fenced` or `fenced_seq_cst` first for simple correctness. +- Use relaxed/acq_rel variants only when you have clear memory-order requirements. + +## Shared State with `primitive` + +```cpp +using shared_t = mcpplibs::primitives::primitive< + int, + mcpplibs::primitives::policy::value::checked, + mcpplibs::primitives::policy::concurrency::fenced, + mcpplibs::primitives::policy::error::expected>; + +shared_t counter{0}; +``` + +Use: + +- `counter.load()` +- `counter.store(v)` +- `counter.compare_exchange(expected, desired)` + +## CAS Loop Pattern + +```cpp +auto expected = counter.load(); +while (!counter.compare_exchange(expected, expected + 1)) { +} +``` + +This is the typical lock-free increment style used in multi-threaded updates. + +## Mixed Read/Write Workload + +For practical concurrent workloads, combine: + +- writer threads updating operands through `store` +- reader threads calling `operations::add` / `operations::sub` +- optional sink updates via `store` and checkpoint `compare_exchange` + +See `examples/ex05_concurrency_policy.cpp` for a representative end-to-end workload. + +## Pitfalls + +### 1) Atomic-ref compatibility + +Fenced access handlers require underlying representations to satisfy atomic-ref constraints (trivially copyable and alignment-compatible). + +### 2) Treating operations as implicit synchronization + +Operation dispatch consistency and concurrency fences are policy-driven. Do not assume synchronization semantics unless explicitly configured. + +### 3) Ignoring error paths + +Operation results are `std::expected<...>`. Always handle `has_value()`. + +## Next + +- Extension guide: [./extension.md](./extension.md) +- API concurrency details: [../../api/en/README.md](../../api/en/README.md) + diff --git a/docs/guide/en/extension.md b/docs/guide/en/extension.md new file mode 100644 index 0000000..2706bac --- /dev/null +++ b/docs/guide/en/extension.md @@ -0,0 +1,77 @@ +# Extension Guide + +This page covers extensibility paths used by advanced users. + +## 1) Custom Underlying Type + +Define a domain type and specialize `underlying::traits`. + +Required members: + +- `value_type` +- `rep_type` +- `static constexpr bool enabled` +- `static constexpr underlying::category kind` +- `to_rep(value)` +- `from_rep(rep)` +- `is_valid_rep(rep)` + +After registration, your type can be used as `primitive` if it satisfies `underlying_type`. + +Reference example: `examples/ex06_custom_underlying.cpp`. + +## 2) Custom Common Rep Negotiation + +If default `std::common_type_t` is not suitable, specialize: + +```cpp +template <> +struct mcpplibs::primitives::underlying::common_rep_traits { + using type = YourCommonRep; + static constexpr bool enabled = true; +}; +``` + +This affects mixed dispatch and type negotiation. + +## 3) Custom Policy Tags and Handlers + +Custom policies require: + +1. Registering tags via `policy::traits`. +2. Providing protocol specializations in the correct namespaces: + - `policy::type::handler` + - `policy::value::handler` + - `policy::error::handler` + - `policy::concurrency::handler` + +If your value policy needs operation runtime behavior, also provide `operations::runtime::op_binding` specializations. + +Reference example: `examples/ex07_custom_policy.cpp`. + +## 4) Custom Operation Tags + +To add new operation tags: + +1. Define operation tag type. +2. Specialize `operations::traits` with: + - `enabled = true` + - `arity` + - `capability_mask` +3. Provide `operations::runtime::op_binding`. +4. Invoke via `operations::apply(lhs, rhs)`. + +Reference example: `examples/ex08_custom_operation.cpp`. + +## Extension Checklist + +- Policy groups are consistent across operands. +- Operation capability metadata is valid. +- Value policy + operation binding exists for runtime dispatch. +- Error policy handler returns expected payload type. +- Concurrency access handler exists if you need `load/store/CAS`. + +## Next + +- API details for protocol contracts: [../../api/en/README.md](../../api/en/README.md) + diff --git a/docs/guide/en/installation-and-build.md b/docs/guide/en/installation-and-build.md new file mode 100644 index 0000000..a3090b9 --- /dev/null +++ b/docs/guide/en/installation-and-build.md @@ -0,0 +1,89 @@ +# Installation and Build + +## Prerequisites + +- C++23-capable compiler + - GCC >= 14 + - Clang >= 17 + - MSVC >= 19.34 (MSVC version >= 1934) +- Build tools + - xmake (recommended) + - or CMake + Ninja + +## Build with xmake + +Build the library: + +```bash +xmake build mcpplibs-primitives +``` + +Run an example: + +```bash +xmake run ex01_default_arithmetic +``` + +Run tests: + +```bash +xmake run primitives_test +``` + +Compatibility alias: + +```bash +xmake run basic +``` + +`basic` runs `ex01_default_arithmetic`. + +## Build with CMake + +Configure and build: + +```bash +cmake -B build -G Ninja +cmake --build build --target mcpplibs-primitives +``` + +Build an example and tests: + +```bash +cmake --build build --target ex01_default_arithmetic +cmake --build build --target basic_tests +ctest --test-dir build --output-on-failure +``` + +## Example Targets + +Examples are available as independent targets: + +- `ex01_default_arithmetic` +- `ex02_type_policy` +- `ex03_value_policy` +- `ex04_error_policy` +- `ex05_concurrency_policy` +- `ex06_custom_underlying` +- `ex07_custom_policy` +- `ex08_custom_operation` + +## Common Build Issues + +### 1) C++ standard or modules not enabled + +Ensure C++23 is enabled and your compiler supports C++ modules. + +### 2) Compiler version too old + +Use the minimum versions listed above. For GCC/Clang/MSVC, older versions can fail early at configuration or module compilation. + +### 3) Failing to find test dependencies + +The test target depends on GoogleTest. Use xmake package resolution or ensure CMake can fetch/access the configured repository. + +## Next + +- Continue with [Quick Start](./quick-start.md) +- API details: [../../api/en/README.md](../../api/en/README.md) + diff --git a/docs/guide/en/quick-start.md b/docs/guide/en/quick-start.md new file mode 100644 index 0000000..15dff70 --- /dev/null +++ b/docs/guide/en/quick-start.md @@ -0,0 +1,90 @@ +# Quick Start + +## Minimal Program + +```cpp +import std; +import mcpplibs.primitives; + +using namespace mcpplibs::primitives; +using namespace mcpplibs::primitives::operators; + +int main() { + using value_t = + primitive; + + auto const out = value_t{40} + value_t{2}; + if (!out.has_value()) { + return 1; + } + return out->value() == 42 ? 0 : 1; +} +``` + +Key point: arithmetic and operator APIs typically return `std::expected<...>`. + +## First Policy Setup + +Recommended starting combination: + +- `policy::value::checked` +- `policy::error::expected` +- default `type::strict` +- default `concurrency::none` + +This gives safe arithmetic and explicit error handling without requiring exceptions. + +## Learn by Examples + +Run examples in this order: + +1. `ex01_default_arithmetic` +2. `ex02_type_policy` +3. `ex03_value_policy` +4. `ex04_error_policy` +5. `ex05_concurrency_policy` +6. `ex06_custom_underlying` +7. `ex07_custom_policy` +8. `ex08_custom_operation` + +Command: + +```bash +xmake run ex03_value_policy +``` + +## Common Usage Snippets + +### Default primitive + +```cpp +using default_i32 = mcpplibs::primitives::primitive; +``` + +### Mixed primitive/underlying operation + +```cpp +using value_t = mcpplibs::primitives::primitive< + int, + mcpplibs::primitives::policy::type::compatible, + mcpplibs::primitives::policy::error::expected>; + +auto const lhs = value_t{40}; +short const rhs = 2; +auto const out = mcpplibs::primitives::operations::add(lhs, rhs); +``` + +### Operators namespace + +```cpp +using namespace mcpplibs::primitives::operators; +``` + +Without this namespace, call function APIs via `mcpplibs::primitives::operations`. + +## Next + +- Concurrency usage: [./concurrency.md](./concurrency.md) +- Extension guide: [./extension.md](./extension.md) +- API reference: [../../api/en/README.md](../../api/en/README.md) + diff --git a/docs/guide/zh/concurrency.md b/docs/guide/zh/concurrency.md new file mode 100644 index 0000000..e5e4589 --- /dev/null +++ b/docs/guide/zh/concurrency.md @@ -0,0 +1,75 @@ +# 并发使用指南 + +## 并发策略 + +内置并发策略: + +- `policy::concurrency::none` +- `policy::concurrency::fenced` +- `policy::concurrency::fenced_relaxed` +- `policy::concurrency::fenced_acq_rel` +- `policy::concurrency::fenced_seq_cst` + +选择建议: + +- 单线程路径使用 `none`。 +- 若优先正确性,先用 `fenced` 或 `fenced_seq_cst`。 +- 仅在明确内存序需求时使用 `relaxed/acq_rel` 变体。 + +## 使用 `primitive` 管理共享状态 + +```cpp +using shared_t = mcpplibs::primitives::primitive< + int, + mcpplibs::primitives::policy::value::checked, + mcpplibs::primitives::policy::concurrency::fenced, + mcpplibs::primitives::policy::error::expected>; + +shared_t counter{0}; +``` + +常用接口: + +- `counter.load()` +- `counter.store(v)` +- `counter.compare_exchange(expected, desired)` + +## CAS 循环模式 + +```cpp +auto expected = counter.load(); +while (!counter.compare_exchange(expected, expected + 1)) { +} +``` + +这是多线程下常见的无锁自增写法。 + +## 读写组合并发场景 + +建议组合使用: + +- writer 线程通过 `store` 更新操作数 +- reader 线程调用 `operations::add` / `operations::sub` +- 可选地将结果写入 sink,并用 `compare_exchange` 做检查点更新 + +可参考:`examples/ex05_concurrency_policy.cpp` + +## 常见问题 + +### 1) atomic_ref 约束不满足 + +fenced 访问路径依赖 atomic-ref,表示类型需要满足可平凡复制与对齐约束。 + +### 2) 误把运算调用当作隐式同步 + +分发一致性与并发内存序都由策略决定,未配置前不要假设有同步语义。 + +### 3) 忽略错误分支 + +运算结果是 `std::expected<...>`,请始终检查 `has_value()`。 + +## 下一步 + +- 扩展开发: [./extension.md](./extension.md) +- API 并发细节: [../../api/zh/README.md](../../api/zh/README.md) + diff --git a/docs/guide/zh/extension.md b/docs/guide/zh/extension.md new file mode 100644 index 0000000..3bbd723 --- /dev/null +++ b/docs/guide/zh/extension.md @@ -0,0 +1,77 @@ +# 扩展开发指南 + +本页面面向需要扩展库能力的用户。 + +## 1) 扩展 underlying 类型 + +定义业务类型后,特化 `underlying::traits`。 + +必需成员: + +- `value_type` +- `rep_type` +- `static constexpr bool enabled` +- `static constexpr underlying::category kind` +- `to_rep(value)` +- `from_rep(rep)` +- `is_valid_rep(rep)` + +完成后,只要满足 `underlying_type`,即可用于 `primitive`。 + +参考:`examples/ex06_custom_underlying.cpp` + +## 2) 自定义 common rep 协商 + +当默认 `std::common_type_t` 不满足需求时,可特化: + +```cpp +template <> +struct mcpplibs::primitives::underlying::common_rep_traits { + using type = YourCommonRep; + static constexpr bool enabled = true; +}; +``` + +这会影响 mixed dispatch 与 type negotiation。 + +## 3) 自定义 policy 标签与协议处理器 + +自定义 policy 需要: + +1. 通过 `policy::traits` 注册标签。 +2. 在对应命名空间提供协议特化: + - `policy::type::handler` + - `policy::value::handler` + - `policy::error::handler` + - `policy::concurrency::handler` + +如果 value policy 需要参与运行期运算逻辑,还要补充 `operations::runtime::op_binding` 特化。 + +参考:`examples/ex07_custom_policy.cpp` + +## 4) 自定义 operation 标签 + +新增 operation 的典型步骤: + +1. 定义 operation tag 类型。 +2. 特化 `operations::traits`,设置: + - `enabled = true` + - `arity` + - `capability_mask` +3. 提供 `operations::runtime::op_binding`。 +4. 通过 `operations::apply(lhs, rhs)` 调用。 + +参考:`examples/ex08_custom_operation.cpp` + +## 扩展检查清单 + +- 双操作数策略组是否一致。 +- operation capability 元信息是否正确。 +- value policy + operation binding 是否覆盖运行期分发路径。 +- error handler 返回类型是否匹配。 +- 若需要 `load/store/CAS`,并发 access handler 是否实现。 + +## 下一步 + +- 协议契约与模板细节: [../../api/zh/README.md](../../api/zh/README.md) + diff --git a/docs/guide/zh/installation-and-build.md b/docs/guide/zh/installation-and-build.md new file mode 100644 index 0000000..e660e4f --- /dev/null +++ b/docs/guide/zh/installation-and-build.md @@ -0,0 +1,89 @@ +# 安装与构建 + +## 环境要求 + +- 支持 C++23 的编译器 + - GCC >= 14 + - Clang >= 17 + - MSVC >= 19.34(MSVC 版本号 >= 1934) +- 构建工具 + - 推荐:xmake + - 或:CMake + Ninja + +## 使用 xmake 构建 + +构建库: + +```bash +xmake build mcpplibs-primitives +``` + +运行示例: + +```bash +xmake run ex01_default_arithmetic +``` + +运行测试: + +```bash +xmake run primitives_test +``` + +兼容别名: + +```bash +xmake run basic +``` + +`basic` 对应 `ex01_default_arithmetic`。 + +## 使用 CMake 构建 + +配置并构建: + +```bash +cmake -B build -G Ninja +cmake --build build --target mcpplibs-primitives +``` + +构建示例与测试: + +```bash +cmake --build build --target ex01_default_arithmetic +cmake --build build --target basic_tests +ctest --test-dir build --output-on-failure +``` + +## 示例目标 + +可独立构建/运行的示例目标: + +- `ex01_default_arithmetic` +- `ex02_type_policy` +- `ex03_value_policy` +- `ex04_error_policy` +- `ex05_concurrency_policy` +- `ex06_custom_underlying` +- `ex07_custom_policy` +- `ex08_custom_operation` + +## 常见构建问题 + +### 1) 未启用 C++23 / 模块能力 + +请确认工程使用 C++23,且编译器支持 C++ modules。 + +### 2) 编译器版本过低 + +请使用本文档列出的最低版本,否则可能在配置阶段或模块编译阶段失败。 + +### 3) 测试依赖获取失败 + +测试目标依赖 GoogleTest。请确保 xmake 包管理可用,或 CMake 侧可访问配置的拉取源。 + +## 下一步 + +- 继续阅读:[快速上手](./quick-start.md) +- API 细节: [../../api/zh/README.md](../../api/zh/README.md) + diff --git a/docs/guide/zh/quick-start.md b/docs/guide/zh/quick-start.md new file mode 100644 index 0000000..109e7ac --- /dev/null +++ b/docs/guide/zh/quick-start.md @@ -0,0 +1,90 @@ +# 快速上手 + +## 最小可运行示例 + +```cpp +import std; +import mcpplibs.primitives; + +using namespace mcpplibs::primitives; +using namespace mcpplibs::primitives::operators; + +int main() { + using value_t = + primitive; + + auto const out = value_t{40} + value_t{2}; + if (!out.has_value()) { + return 1; + } + return out->value() == 42 ? 0 : 1; +} +``` + +关键点:算术和运算符接口大多返回 `std::expected<...>`。 + +## 第一组推荐策略 + +建议起步组合: + +- `policy::value::checked` +- `policy::error::expected` +- 默认 `policy::type::strict` +- 默认 `policy::concurrency::none` + +这组配置通常具备较好的安全性与可诊断性。 + +## 通过示例学习 + +建议按以下顺序运行示例: + +1. `ex01_default_arithmetic` +2. `ex02_type_policy` +3. `ex03_value_policy` +4. `ex04_error_policy` +5. `ex05_concurrency_policy` +6. `ex06_custom_underlying` +7. `ex07_custom_policy` +8. `ex08_custom_operation` + +运行示例: + +```bash +xmake run ex03_value_policy +``` + +## 常用代码片段 + +### 默认 primitive + +```cpp +using default_i32 = mcpplibs::primitives::primitive; +``` + +### primitive 与 underlying 混合运算 + +```cpp +using value_t = mcpplibs::primitives::primitive< + int, + mcpplibs::primitives::policy::type::compatible, + mcpplibs::primitives::policy::error::expected>; + +auto const lhs = value_t{40}; +short const rhs = 2; +auto const out = mcpplibs::primitives::operations::add(lhs, rhs); +``` + +### 启用运算符重载命名空间 + +```cpp +using namespace mcpplibs::primitives::operators; +``` + +如果不引入该命名空间,请使用 `mcpplibs::primitives::operations` 下的函数式 API。 + +## 下一步 + +- 并发用法: [./concurrency.md](./concurrency.md) +- 扩展开发: [./extension.md](./extension.md) +- API 参考: [../../api/zh/README.md](../../api/zh/README.md) + From bcfe31e1f53410c28e07404e0fbf05a812e030ce Mon Sep 17 00:00:00 2001 From: FrozenlemonTee <1115306170@qq.com> Date: Sun, 22 Mar 2026 21:32:25 +0800 Subject: [PATCH 16/17] docs: Remove complete plan Markdown file Signed-off-by: FrozenlemonTee <1115306170@qq.com> --- .../plan-policyBehaviorProtocol.prompt.md | 66 ------------------- 1 file changed, 66 deletions(-) delete mode 100644 .github/prompts/plan-policyBehaviorProtocol.prompt.md diff --git a/.github/prompts/plan-policyBehaviorProtocol.prompt.md b/.github/prompts/plan-policyBehaviorProtocol.prompt.md deleted file mode 100644 index 37be9bc..0000000 --- a/.github/prompts/plan-policyBehaviorProtocol.prompt.md +++ /dev/null @@ -1,66 +0,0 @@ -## Plan: 策略组一致性 + Primitive/Underlying 混合操作(增量) - -本计划仅覆盖新增规则与新增重载,不重复已完成的分层协议与分发基建。 - -### A. 已确认规则(实现目标) -1. 单个 `primitive` 的策略组规则保持不变 - - 同类别策略标签重复时,编译期报错。 - -2. 两个 `primitive` 的策略组合并规则 - - 先按默认策略补全四类策略(`value/type/error/concurrency`)。 - - 补全后两边策略组必须完全一致(忽略声明顺序),否则编译期报错。 - -3. 两个 `primitive` 底层类型不同时的二元操作规则 - - 先满足规则 2。 - - `type::strict`:编译期拒绝。 - - `type::compatible`:两侧 `underlying category` 必须一致,且 `common_rep_traits` 可用且推导结果非 `void`。 - - `type::transparent`:忽略 `category`,但 `common_rep_traits` 必须可用且推导结果非 `void`。 - -4. 不新增策略标签 - - 维持 `compatible` / `transparent` 现有策略集合,不引入新 policy。 - -### B. 新增范围:Primitive 与 Underlying 混合作为二元操作数 -1. 在 `apply/operation` 层新增 `underlying` 参与重载 - - 支持 `(primitive, underlying)`。 - - 若是自由函数,必须同时支持 `(underlying, primitive)`(左右位置都可用)。 - -2. 返回类型约束 - - 算术类型操作结果始终返回 `primitive`(不返回裸 `underlying`)。 - -3. 策略选择约束 - - 混合操作中仅有一个 `primitive` 时,`type` 策略取该 `primitive` 的策略。 - - 其余策略(`value/error/concurrency`)同样取该 `primitive`,保持策略来源单一。 - -4. 底层类型推导约束 - - 混合操作的 `underlying` 推导与“两侧都是 primitive”的规则一致: - - 走相同的 `type` 协商路径,使用同一套 `common_rep_traits` 可用性与非 `void` 判定。 - -### C. 代码改动计划 -1. `src/operations/dispatcher.cppm` - - 增加“跨 primitive 策略组补全后一致”的编译期断言。 - - 增加 `compatible` 下 `category` 一致性判定(与 `common_rep` 可用性判定协同)。 - - 补齐 `common_rep` 非 `void` 的显式断言。 - -2. `src/operations/operators.cppm` - - 为自由函数 `apply/add/sub/mul/div/equal/not_equal/three_way_compare` 增加混合重载: - - `(primitive, underlying)` 与 `(underlying, primitive)`。 - - 保证非交换操作(如 `sub/div/<=>`)保留正确操作数顺序语义。 - -3. `src/primitive/impl.cppm`(如需) - - 若存在 primitive access 的自由函数入口,同步补齐混合重载的左右位置版本。 - - 成员函数形式的 access API 不做左右重载扩展。 - -4. `tests/basic/test_operations.cpp` - - 新增混合重载测试: - - `(primitive, underlying)` 与 `(underlying, primitive)` 都可编译并语义正确。 - - 算术结果类型恒为 `primitive`。 - - 策略组不一致时编译期失败。 - - `strict/compatible/transparent` 下的跨底层类型判定符合规则 A-3。 - -### D. 验收标准 -1. 所有新增约束均在编译期可判定,不引入运行期兜底分支。 -2. 混合操作重载完整覆盖左右操作数位置(自由函数)。 -3. 算术混合操作返回类型恒为 `primitive`。 -4. 混合操作的 `type` 策略来源唯一且可预测(取 primitive 操作数)。 -5. 与现有行为无回归,新增正反测试通过。 - From 65be873ab54568f95abcb65c822ba08894e7864e Mon Sep 17 00:00:00 2001 From: FrozenlemonTee <1115306170@qq.com> Date: Sun, 22 Mar 2026 21:49:55 +0800 Subject: [PATCH 17/17] fix: Improve concurrency control by adding wait and notify mechanisms Signed-off-by: FrozenlemonTee <1115306170@qq.com> --- examples/ex05_concurrency_policy.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/examples/ex05_concurrency_policy.cpp b/examples/ex05_concurrency_policy.cpp index 2d52058..e67cc3a 100644 --- a/examples/ex05_concurrency_policy.cpp +++ b/examples/ex05_concurrency_policy.cpp @@ -49,6 +49,7 @@ int main() { for (int writer = 0; writer < kWriterThreads; ++writer) { workers.emplace_back([&, writer]() { while (!start.load(std::memory_order_acquire)) { + start.wait(false, std::memory_order_relaxed); } for (int n = 0; n < kIterationsPerThread; ++n) { @@ -64,6 +65,7 @@ int main() { for (int reader = 0; reader < kReaderThreads; ++reader) { workers.emplace_back([&, reader]() { while (!start.load(std::memory_order_acquire)) { + start.wait(false, std::memory_order_relaxed); } for (int n = 0; n < kIterationsPerThread; ++n) { @@ -100,6 +102,7 @@ int main() { } start.store(true, std::memory_order_release); + start.notify_all(); for (auto &worker : workers) { worker.join();