From b2de44db2b1037844d30ac9e25c1162113bbfa80 Mon Sep 17 00:00:00 2001 From: minelogy-dev <72928567+minelogy-dev@users.noreply.github.com> Date: Thu, 12 Nov 2026 04:18:14 -0800 Subject: [PATCH 1/2] docs: add bilingual documentation in docs/en_us and docs/zh_cn - add a complete English and Simplified Chinese manual: getting started, user guide, API reference for buffers/views and search/compare/split, regex guide, design & internals, build/test/package, contributing, CI - move the CI notes from docs/CI.md into both languages and update every link; add a docs hub at docs/README.md - correct root README statements about the layer that declares sx_split and about out-of-contract inputs - every public function is documented with its exact prototype; all complete examples compile and run under ASan/UBSan/LSan and the full 20-test suite passes --- README.md | 26 +- README.zh-CN.md | 24 +- docs/CI.md | 101 ----- docs/README.md | 27 ++ docs/en_us/README.md | 67 +++ docs/en_us/api-buffer.md | 793 ++++++++++++++++++++++++++++++++++ docs/en_us/api-search.md | 620 ++++++++++++++++++++++++++ docs/en_us/build-and-test.md | 359 +++++++++++++++ docs/en_us/ci.md | 140 ++++++ docs/en_us/contributing.md | 149 +++++++ docs/en_us/design.md | 750 ++++++++++++++++++++++++++++++++ docs/en_us/getting-started.md | 306 +++++++++++++ docs/en_us/guide.md | 462 ++++++++++++++++++++ docs/en_us/regex.md | 561 ++++++++++++++++++++++++ docs/zh_cn/README.md | 61 +++ docs/zh_cn/api-buffer.md | 722 +++++++++++++++++++++++++++++++ docs/zh_cn/api-search.md | 571 ++++++++++++++++++++++++ docs/zh_cn/build-and-test.md | 338 +++++++++++++++ docs/zh_cn/ci.md | 123 ++++++ docs/zh_cn/contributing.md | 131 ++++++ docs/zh_cn/design.md | 675 +++++++++++++++++++++++++++++ docs/zh_cn/getting-started.md | 300 +++++++++++++ docs/zh_cn/guide.md | 434 +++++++++++++++++++ docs/zh_cn/regex.md | 522 ++++++++++++++++++++++ 24 files changed, 8149 insertions(+), 113 deletions(-) delete mode 100644 docs/CI.md create mode 100644 docs/README.md create mode 100644 docs/en_us/README.md create mode 100644 docs/en_us/api-buffer.md create mode 100644 docs/en_us/api-search.md create mode 100644 docs/en_us/build-and-test.md create mode 100644 docs/en_us/ci.md create mode 100644 docs/en_us/contributing.md create mode 100644 docs/en_us/design.md create mode 100644 docs/en_us/getting-started.md create mode 100644 docs/en_us/guide.md create mode 100644 docs/en_us/regex.md create mode 100644 docs/zh_cn/README.md create mode 100644 docs/zh_cn/api-buffer.md create mode 100644 docs/zh_cn/api-search.md create mode 100644 docs/zh_cn/build-and-test.md create mode 100644 docs/zh_cn/ci.md create mode 100644 docs/zh_cn/contributing.md create mode 100644 docs/zh_cn/design.md create mode 100644 docs/zh_cn/getting-started.md create mode 100644 docs/zh_cn/guide.md create mode 100644 docs/zh_cn/regex.md diff --git a/README.md b/README.md index ad5567e..1020cf7 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,12 @@ To use it you only need: and link `-lstringx` — one header, one library. +**Documentation:** the full manual lives in [`docs/`](docs/README.md) — +[Getting started](docs/en_us/getting-started.md), [User guide](docs/en_us/guide.md), +[API reference](docs/en_us/api-buffer.md), [Regex](docs/en_us/regex.md), +[Design](docs/en_us/design.md), [Build & test](docs/en_us/build-and-test.md). +The Chinese edition is under [`docs/zh_cn/`](docs/zh_cn/README.md). + ## Design - **Buffer model.** Every `sx_t` owns a single NUL-terminated buffer: @@ -23,12 +29,13 @@ and link `-lstringx` — one header, one library. - **Views.** `sx_view_t {ref, offset, len}` aliases a slice of a buffer with **no copy and no modification** of the original. Many APIs return views (the `ref == NULL` sentinel marks "none"). -- **Layers.** `sx_core.h` provides the core buffer, view, search, compare - and split operations (reached through `sx.h`); the advanced layer adds - regex through **PCRE2** (`\d \w \b …` are ASCII in 8-bit non-UTF mode). +- **Layers.** `sx_core.h` provides the core buffer, view, search and + compare operations (reached through `sx.h`); the advanced layer adds + splitting (`sx_split`) and regex through **PCRE2** (`\d \w \b …` are + ASCII in 8-bit non-UTF mode). - **Deterministic contracts.** Every function documents its exact behavior - boundaries in `sx.h`; invalid inputs never crash — they return a - documented not-found/error value. + boundaries in `sx.h`: documented miss/error cases return sentinel values, + and anything outside those boundaries is out of contract. ## Requirements @@ -48,6 +55,9 @@ forge . # compile build.c into ./make (re-run whenever build.c changes) ./make test # build and run every test under tests/ (ASan + UBSan) ``` +See [Build, test & package](docs/en_us/build-and-test.md) for installation, +packaging and the test harness. + ## Quick start ```c @@ -116,10 +126,14 @@ Contract highlights (full detail in `sx.h`): | Split | `sx_split(sep)` | | Regex | `sx_reg_compile`, `sx_reg_free`, `sx_reg_is_match`, `sx_reg_match`, `sx_reg_match_all`, `sx_reg_replace`, `sx_reg_replace_first`, `sx_reg_split` | +This table is an index only: [API reference: buffers & views](docs/en_us/api-buffer.md) +and [API reference: search, compare & split](docs/en_us/api-search.md) document +every function's exact contract. + ## Tests Pull requests run compiler, sanitizer, static-analysis and secret checks. -See [Continuous integration](docs/CI.md) for coverage and merge-protection setup. +See [Continuous integration](docs/en_us/ci.md) for coverage and merge-protection setup. ```sh ./make test diff --git a/README.zh-CN.md b/README.zh-CN.md index 8331344..535cd2f 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -12,6 +12,12 @@ 并链接 `-lstringx` —— 一个头文件,一个库。 +**文档:** 完整手册位于 [`docs/`](docs/README.md) —— +[快速上手](docs/zh_cn/getting-started.md)、[用户指南](docs/zh_cn/guide.md)、 +[API 参考](docs/zh_cn/api-buffer.md)、[正则](docs/zh_cn/regex.md)、 +[设计](docs/zh_cn/design.md)、[构建与测试](docs/zh_cn/build-and-test.md)。 +英文版见 [`docs/en_us/`](docs/en_us/README.md)。 + ## 设计 - **缓冲区模型。** 每个 `sx_t` 拥有一个单 NUL 结尾的缓冲区: @@ -20,11 +26,11 @@ 内嵌 NUL 是普通数据(二进制安全)。 - **视图。** `sx_view_t {ref, offset, len}` 是缓冲区某一段的别名: **不拷贝、不修改**原串。多数 API 返回视图(`ref == NULL` 哨兵表示"无")。 -- **分层。** core 层(经 `sx.h` 可达)提供缓冲区、视图、查找、比较、 - split 等核心操作;adv 层基于 **PCRE2** 提供正则(8 位非 UTF 模式, - `\d \w \b …` 仅匹配 ASCII)。 -- **确定性契约。** 每个函数在 `sx.h` 里写明精确的行为边界;非法输入不会 - 崩溃——返回文档化的"未找到/出错"值。 +- **分层。** core 层(经 `sx.h` 可达)提供缓冲区、视图、查找、比较等 + 核心操作;adv 层提供分割(`sx_split`)与基于 **PCRE2** 的正则 + (8 位非 UTF 模式,`\d \w \b …` 仅匹配 ASCII)。 +- **确定性契约。** 每个函数在 `sx.h` 里写明精确的行为边界:文档化的 + "未找到/出错"情形返回哨兵值,超出文档边界的输入属于契约之外。 ## 依赖 @@ -43,6 +49,8 @@ forge . # 把 build.c 编译成 ./make(改动 build.c 后需重跑) ./make test # 编译并运行 tests/ 下每个测试(ASan + UBSan) ``` +安装、打包与测试框架的完整说明见[构建、测试与打包](docs/zh_cn/build-and-test.md)。 + ## 快速上手 ```c @@ -110,10 +118,14 @@ sx_reg_free(re); | 分隔 | `sx_split(sep)` | | 正则 | `sx_reg_compile`, `sx_reg_free`, `sx_reg_is_match`, `sx_reg_match`, `sx_reg_match_all`, `sx_reg_replace`, `sx_reg_replace_first`, `sx_reg_split` | +上表只是索引:[API 参考:缓冲区与视图](docs/zh_cn/api-buffer.md) 与 +[API 参考:查找、比较与分割](docs/zh_cn/api-search.md) 记录了每个函数 +精确的契约。 + ## 测试 PR 会自动执行编译、内存检查、静态分析和密钥扫描。 -检查范围与分支保护设置见[持续集成说明](docs/CI.md)。 +检查范围与分支保护设置见[持续集成说明](docs/zh_cn/ci.md)。 ```sh ./make test diff --git a/docs/CI.md b/docs/CI.md deleted file mode 100644 index 83e8606..0000000 --- a/docs/CI.md +++ /dev/null @@ -1,101 +0,0 @@ -# Continuous integration - -Changes to `main`, pull requests, and manual runs use GitHub Actions. -The workflows have read-only repository access, except for the CodeQL job's -permission to publish code-scanning results. Pull-request code never runs via -`pull_request_target`, and checkout credentials are not persisted. - -## Checks - -| Check | What it verifies | -| --- | --- | -| Build and test (gcc-14 / clang-19) | A real build on Ubuntu 24.04 with GCC 14 and Clang 19, the complete test suite, ASan, UBSan and leak detection | -| Compiler warnings | Every production C translation unit compiles with `-Wall -Wextra -Werror` | -| GCC static analysis | `-fanalyzer` checks production translation units; diagnostics fail the job | -| Workflow and secret checks | Actionlint, ShellCheck, whitespace errors and Gitleaks over the complete Git history, with redacted output | -| CodeQL (C/C++) | Manual build tracing with `security-and-quality` queries, findings in the Security tab and on pull requests | -| CI | A stable required check that fails if any build, analyzer or quality job fails or is cancelled | - -CodeQL also runs every Monday at 11:17 Asia/Shanghai (03:17 UTC). -Its successful job status means the analysis completed; it does **not** mean -there are no alerts. Use a code-scanning merge rule to enforce alert severity. - -GCC analysis uses `-O1 -fno-analyzer-state-merge`: GCC 14's default state merging -produces spurious allocation/cleanup diagnostics in this code. No diagnostic -categories are suppressed. An analyzer failure should be investigated, not -worked around with `continue-on-error`. - -All external Actions use immutable commit SHAs. Dependabot proposes weekly -GitHub Actions updates. The Actionlint and Gitleaks CLIs have pinned versions -and SHA-256 checksums in `.github/scripts/install-tools.sh`; update both values -together when upgrading them. - -## Enable merge protection - -After the first successful run, create a branch ruleset for `main`: - -1. Require pull requests and the `CI` and `CodeQL (C/C++)` status checks. -2. Require branches to be up to date before merging. -3. Add “Require code scanning results”, select CodeQL, and block high/critical - security alerts and error-level quality alerts. Tighten these thresholds - after triaging existing findings. -4. Use the checked-in advanced CodeQL workflow rather than enabling a duplicate - default-setup scan. - -Workflow files alone do not enable branch protection. These repository settings -require a one-time maintainer configuration. Changes to CI permissions, checks -and dependency pins still deserve human review. - -## Reproduce locally - -Install Linux build dependencies and a C23 compiler (GCC 14+ or Clang 19+). -Save local `build.conf` changes before running `configure.sh`: it updates the -compiler selection and enables Forge test instrumentation in that file. - -```sh -CC=gcc bash .github/scripts/configure.sh # or CC=clang -CC=gcc bash .github/scripts/check-c.sh -CC=gcc bash .github/scripts/check-c.sh analyze -``` - -Use GCC for `analyze`. Runtime checks set: - -```sh -export ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 -export UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 -``` - -The build dependency is Forge commit -`b6826ba762a1e9e337895e01ee604b943c682d23`, checked out under -`.ci-deps/forge` in CI and bootstrapped without installing system files. -Update this reviewed pin in **both** workflow files when changing Forge. -It is intentionally independent of Forge's moving `main` branch and is not -updated by Dependabot. PCRE2 comes from Ubuntu's `libpcre2-dev` package. - -With a bootstrapped Forge checkout available locally: - -```sh -export PATH="/path/to/forge/build/output:$PATH" -export CPATH="/path/to/forge/build/output/include" -forge . -./make -./make test -j 2 -``` - -Tests compile the library sources with sanitizers, including the exact-reserve -stress test. The build jobs also install into a temporary prefix, compile and -run the existing regex suite against the **installed shared library** using -`pkg-config`, and inspect the generated Debian package. This checks public -headers, exported symbols, package metadata and PCRE2 linkage in addition to -source-level behavior. - -## Review and failures - -Open the failed check for compiler diagnostics, sanitizer stack traces or -secret-scan locations. Build failures retain dependency and command metadata -for seven days; the Actions log contains the full build/test output. -CodeQL alerts include the affected lines and data flow where available. - -Automation covers mechanical regressions and many common memory-safety bugs. -Human review should concentrate on requirements, API contracts, ownership, -architecture and the findings reported by these tools. diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..67d15cc --- /dev/null +++ b/docs/README.md @@ -0,0 +1,27 @@ +# String X documentation + +String X is a small C string library with a single-header API (``) and a +byte-exact, zero-copy view model. This directory holds the complete +documentation for **v0.5**, in English and Simplified Chinese. + +Choose a language / 选择语言: + +- **[English documentation](en_us/README.md)** +- **[简体中文文档](zh_cn/README.md)** + +Both languages cover the same material with the same structure: + +| Topic | English | 中文 | +| --- | --- | --- | +| Getting started | [getting-started.md](en_us/getting-started.md) | [getting-started.md](zh_cn/getting-started.md) | +| User guide | [guide.md](en_us/guide.md) | [guide.md](zh_cn/guide.md) | +| API reference — buffers & views | [api-buffer.md](en_us/api-buffer.md) | [api-buffer.md](zh_cn/api-buffer.md) | +| API reference — search, compare, split | [api-search.md](en_us/api-search.md) | [api-search.md](zh_cn/api-search.md) | +| Regular expressions | [regex.md](en_us/regex.md) | [regex.md](zh_cn/regex.md) | +| Design & internals | [design.md](en_us/design.md) | [design.md](zh_cn/design.md) | +| Build, test & package | [build-and-test.md](en_us/build-and-test.md) | [build-and-test.md](zh_cn/build-and-test.md) | +| Contributing | [contributing.md](en_us/contributing.md) | [contributing.md](zh_cn/contributing.md) | +| Continuous integration | [ci.md](en_us/ci.md) | [ci.md](zh_cn/ci.md) | + +The project is MIT licensed; the regex layer uses PCRE2 (BSD-3-Clause). See +[LICENSE](../LICENSE) and [THIRD_PARTY_NOTICES.md](../THIRD_PARTY_NOTICES.md). diff --git a/docs/en_us/README.md b/docs/en_us/README.md new file mode 100644 index 0000000..4181b96 --- /dev/null +++ b/docs/en_us/README.md @@ -0,0 +1,67 @@ +# String X documentation (English) + +**Version v0.5** · [简体中文](../zh_cn/README.md) · +[Repository](https://github.com/minelogy-dev/StringX) + +String X is a small C string library built around one idea: every string is a +single NUL-terminated buffer, and every slice of it is a view that copies +nothing. The public surface is one header, ``, and one library, +`libstringx` (`-lstringx`); regular expressions are an optional advanced layer +backed by PCRE2. + +## Start here + +| If you want to… | Read | +| --- | --- | +| Install String X and write your first program | [Getting started](getting-started.md) | +| Understand the buffer/view/ownership model and see recipes | [User guide](guide.md) | +| Look up a buffer, view or mutation function | [API reference: buffers & views](api-buffer.md) | +| Look up a search, compare or split function | [API reference: search, compare & split](api-search.md) | +| Use the regular-expression layer | [Regular expressions](regex.md) | +| Understand how the library works inside | [Design & internals](design.md) | +| Build, test, install or package it | [Build, test & package](build-and-test.md) | +| Send a change | [Contributing](contributing.md) | +| Understand the CI gates | [Continuous integration](ci.md) | + +## All documents + +- [Getting started](getting-started.md) — requirements, build, install, first + program, ten-minute tour, documentation map. +- [User guide](guide.md) — mental model, ownership rules, binary safety, error + handling, task recipes, pitfalls, performance notes. +- [API reference: buffers & views](api-buffer.md) — creation and destruction, + capacity, accessors, mutation, substring, view navigation and trimming. +- [API reference: search, compare & split](api-search.md) — `sx_find*`, + `sx_rfind*`, `sx_find_all*`, `sx_cmp*`, `sx_starts_with*`, `sx_ends_with*`, + `sx_split`. +- [Regular expressions](regex.md) — the `sx_reg_*` families: match, replace and + split, with the full contract of each call. +- [Design & internals](design.md) — data layout, growth policy, search + algorithms, regex wrapper internals, portability limits, testing strategy. +- [Build, test & package](build-and-test.md) — Forge, `./make` targets, the + test harness, sanitizers, installation and Debian packaging. +- [Contributing](contributing.md) — workflow, contract-first documentation, + code style, tests, licensing. +- [Continuous integration](ci.md) — workflows, required checks, CodeQL, + merge protection, local reproduction. + +## Documentation conventions + +- The API reference covers the public headers only: `sx.h` and the + `sx_core.h` it includes. `sx_raw.h` is an internal allocation/debug API and + is not part of the supported public surface. +- Every behavior statement is derived from the public header contracts, the + implementation, and the behavior-boundary comments in `tests/*.c`. +- **Out of contract** means the call is outside the library's documented + guarantees and its behavior is not defined; the tests deliberately do not + exercise it, and your program must not rely on it. +- Code examples target C23 on Linux and link `-lstringx` (the regex examples + need no extra flags: the library links `pcre2-8` itself). +- The documentation describes **v0.5**; `build.conf` is the single source of + truth for the version. + +## License + +The library is MIT licensed — see [LICENSE](../../LICENSE) and the SPDX +headers in the sources. The regex layer depends on PCRE2 (BSD-3-Clause); see +[THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md). diff --git a/docs/en_us/api-buffer.md b/docs/en_us/api-buffer.md new file mode 100644 index 0000000..9e3cbd2 --- /dev/null +++ b/docs/en_us/api-buffer.md @@ -0,0 +1,793 @@ +English · [中文](../zh_cn/api-buffer.md) + +[Docs home](README.md) › API reference: buffers & views + +# Buffers and views + +The complete reference for the core buffer and view API declared in +`include/sx_core.h`: creating and releasing buffers, reading their +state, mutating content, taking substrings, and navigating and trimming +views. Search, comparison and splitting are documented in +[Search, compare and split](api-search.md). + +Every behavior statement below is derived from the public header +contract, the implementation, and the behavior-boundary comments in +`tests/*.c`. + +## Conventions + +**Headers and layers.** Include the one public header: + +```c +#include +``` + +`sx.h` includes `sx_core.h` (buffers, views, search, comparison) and +then declares `sx_split` and the `sx_reg_*` family. Link the library +with `-lstringx`. All functions on this page are declared in +`sx_core.h`. `sx_raw.h` is an internal allocation/debug API and is not +part of the supported public interface. + +**One allocation per buffer.** An `sx_t` handle owns exactly one +NUL-terminated byte array: `ptr[0 .. len-1]` are the content bytes, +`ptr[len]` is always `'\0'`, and `cap` is the allocation size, with +`cap >= len + 1`. `len` counts content bytes, so an embedded `'\0'` is +ordinary data, not a terminator — the model is binary-safe by +construction. + +**Ownership.** + +| Value | Owner | Released with | +| --- | --- | --- | +| buffer from `sx_new*`, `sx_dup`, `sx_substr` | caller | `sx_free` | +| `owned` argument of `sx_append`, `sx_write`, `sx_insert` | transferred to the library | nothing: the call frees it | +| buffer returned by an edit | the same handle as `self` | one `sx_free` for the original handle | +| `sx_view_t` | none: it aliases a buffer | nothing; views are never freed | +| array from `sx_find_all*` or `sx_split` | caller | `free` (see [api-search.md](api-search.md)) | + +Every edit returns `self`, so calls chain and the handle stays stable. +The backing array may move when the buffer grows: pointers returned by +`sx_buf_mut`/`sx_buf_view_mut` become stale after any call that can +reallocate and must be re-fetched. + +**NULL and out of contract.** Documented NULL handling on this page: +`sx_new_from_cstr(NULL)` and `sx_dup(NULL)` return `NULL`; the +`owned` forms of `sx_append`, `sx_write` and `sx_insert`, and all +`_cstr` forms, return `NULL` and leave `self` untouched when their +second argument is `NULL`. Everything else dereferences a buffer or +window: `sx_free`, `sx_len`, `sx_cap`, `sx_buf_mut`, `sx_view`, the +view navigation family, and the edit functions do not accept a NULL +handle, and `sx_new_from_view`, `sx_buf_view_mut` and `sx_view_*` do +not accept a view with `ref == NULL` (`sx_len_view` only reads the +stored length). A NULL handle or `v.ref`, a freed handle, a view whose +bounds exceed its backing buffer, a double free, use after a consuming +call, `self` passed as the `owned` argument, and indices that violate +what an entry states are all **out of contract**: undefined behavior, +not a documented error return. + +**Sentinels.** + +| Situation | Value | +| --- | --- | +| allocation failure | `NULL` | +| rejected NULL operand (where documented) | `NULL` | +| "no view" | `.ref == NULL` | +| not found / no match (search page) | `(size_t)-1` | +| no matches / refused split (search page) | `NULL` | + +**Sizes are `int`.** `sx_len`, `sx_len_view` and `sx_cap` return +`int`, while view fields and search offsets are `size_t`. Content +larger than `INT_MAX` bytes is outside the tested contract; cast with +`(size_t)` when mixing the two, for example +`fwrite(sx_buf_mut(h), 1, (size_t)sx_len(h), stdout)`. + +**Views are snapshots.** `sx_view_t {ref, offset, len}` denotes the +byte window `[offset, offset + len)` inside the buffer behind `ref`; it +copies nothing and modifies nothing. A valid window lies inside the +buffer (`offset + len <= len(ref)`). A later edit that reallocates or +changes the length invalidates the view's meaning: re-derive views +after such edits, and do not edit a buffer while views into it (such as +a `sx_split` array) are in use. `ref == NULL` marks "no view"; it is +not a usable buffer. + +**Capacity growth.** `sx_new` starts with capacity 32 bytes. Growth is +geometric (double, then `+0x10000` once the capacity is at least +64 KiB); a debug build with `-DSX_FORCE_EXACT_RESERVE` sizes every +allocation exactly to `need + 1`. Capacity never shrinks — +`sx_truncate` and `sx_clear` keep it — and no function promises spare +capacity beyond its stated guarantee. + +## Creation and destruction + +### sx_new + +```c +sx_t *sx_new(void); +``` + +Creates an empty buffer with initial capacity 32 bytes. + +- **Parameters:** none. +- **Returns:** a new buffer (`len == 0`, `cap == 32`, `ptr[0] == '\0'`), + or `NULL` on allocation failure. +- **Ownership:** caller-owned; release with `sx_free`. +- **Edge cases:** the exact initial capacity is an implementation + detail; only `cap >= 1` is guaranteed. + +### sx_new_from_cstr + +```c +sx_t *sx_new_from_cstr(const char *s); +``` + +Creates a buffer holding a copy of the C string `s`. + +- **Parameters:** `s` — NUL-terminated source string, read with + `strlen`. +- **Returns:** a new caller-owned buffer, or `NULL` when `s == NULL` or + on allocation failure. +- **Ownership:** caller-owned; release with `sx_free`. +- **Edge cases:** `strlen` semantics — an embedded `'\0'` truncates the + copy. Use `sx_new_from_view` for binary content. + +### sx_new_from_view + +```c +sx_t *sx_new_from_view(sx_view_t v); +``` + +Copies the bytes of a view into a new, independent buffer. + +- **Parameters:** `v` — source window; `v.len` bytes are read from + `v.ref->ptr + v.offset`. +- **Returns:** a new caller-owned buffer, or `NULL` on allocation + failure. +- **Ownership:** caller-owned; release with `sx_free`. +- **Edge cases:** byte-exact and binary-safe: embedded `'\0'` bytes are + copied. There is no aliasing — mutating either buffer never affects + the other. `v.ref == NULL` or an out-of-bounds window is out of + contract. + +### sx_new_with_cap + +```c +sx_t *sx_new_with_cap(size_t n); +``` + +Creates an empty buffer with exactly `n` allocated bytes. + +- **Parameters:** `n` — total allocation size in bytes. +- **Returns:** a new caller-owned buffer with `cap == n` for `n >= 1`, + or `NULL` on allocation failure. +- **Ownership:** caller-owned; release with `sx_free`. +- **Edge cases:** one byte is reserved for the terminator, so the buffer + can hold at most `n - 1` content bytes. `n == 0` still allocates one + byte (`cap == 1`), so the handle is always valid. + +```c +sx_t *buf = sx_new_with_cap(64); /* room for 63 content bytes */ +buf = sx_append_cstr(buf, "hello"); /* no reallocation */ +sx_free(buf); +``` + +### sx_dup + +```c +sx_t *sx_dup(const sx_t *src); +``` + +Creates a deep, independent copy of a buffer. + +- **Parameters:** `src` — source buffer. +- **Returns:** a new caller-owned buffer with the same content, or + `NULL` when `src == NULL` or on allocation failure. +- **Ownership:** caller-owned; the copy and the source are released + separately with `sx_free`. +- **Edge cases:** binary-safe. The copy's capacity is `len + 1` in + v0.5, not the source's capacity. + +```c +sx_t *src = sx_new_from_cstr("hello"); +sx_t *copy = sx_dup(src); /* independent: free both */ +sx_free(copy); +sx_free(src); +``` + +### sx_free + +```c +void sx_free(sx_t *h); +``` + +Releases a buffer: its content array and the handle. + +- **Parameters:** `h` — a live handle whose ownership the caller holds. +- **Returns:** nothing. +- **Ownership:** consumes `h`; every view and `sx_buf_mut` pointer into + the buffer becomes invalid. +- **Edge cases:** `h == NULL` is out of contract — the function + dereferences the handle (the regex layer's `sx_reg_free(NULL)` no-op + does not generalize here). Double free and use after free are out of + contract. + +## Accessors + +### sx_len + +```c +int sx_len(sx_t *h); +``` + +Returns the number of content bytes. + +- **Parameters:** `h` — buffer. +- **Returns:** `len`, counting embedded `'\0'` bytes; the terminator is + never counted. +- **Ownership:** none; the buffer is not modified. +- **Edge cases:** `h == NULL` is out of contract. The result is an + `int`; see the size note above. + +### sx_len_view + +```c +int sx_len_view(sx_view_t v); +``` + +Returns the view's stored length. + +- **Parameters:** `v` — the view whose length is wanted. +- **Returns:** `(int)v.len`; the backing buffer is not inspected and the + window bounds are not validated. +- **Ownership:** none. +- **Edge cases:** `v.len` above `INT_MAX` is outside the tested + contract. The "no view" sentinel (`ref == NULL`) carries `len == 0`. + +### sx_cap + +```c +int sx_cap(sx_t *h); +``` + +Returns the total number of bytes allocated for the content array. + +- **Parameters:** `h` — buffer. +- **Returns:** `cap`, which is always at least `len + 1` (the + single-NUL invariant). +- **Ownership:** none; the buffer is not modified. +- **Edge cases:** `h == NULL` is out of contract. Spare capacity beyond + `len + 1` depends on the growth policy and is not a contract. + +### sx_buf_mut + +```c +char *sx_buf_mut(sx_t *h); +``` + +Returns a mutable pointer to the content array. + +- **Parameters:** `h` — buffer. +- **Returns:** `ptr`; `ptr[len] == '\0'` at all times. +- **Ownership:** borrowed; the caller may rewrite bytes inside + `[0, len)` without changing `len`. +- **Edge cases:** the caller must not write at or beyond `len` without a + length-changing call, and must not store the pointer across any call + that can reallocate (`sx_append*`, `sx_write*`, `sx_insert*`, + `sx_reserve`, a growing `sx_truncate`). `h == NULL` is out of + contract. + +```c +char *p = sx_buf_mut(buf); +p[0] = 'H'; /* len unchanged; p[len] must stay '\0' */ +``` + +### sx_buf_view_mut + +```c +char *sx_buf_view_mut(sx_view_t v); +``` + +Returns a mutable pointer to the first byte of a view's window. + +- **Parameters:** `v` — view into a buffer. +- **Returns:** `v.ref->ptr + v.offset`. +- **Ownership:** borrowed; writes reach the backing buffer. +- **Edge cases:** the pointer carries no length information — pair it + with `sx_len_view(v)` and stay inside the window. `v.ref == NULL` or + an out-of-bounds window is out of contract, and the pointer is stale + after the backing buffer reallocates. + +```c +sx_view_t word = sx_view_range(sx_view(buf), 6, 5); +char *w = sx_buf_view_mut(word); /* == sx_buf_mut(buf) + 6 */ +w[0] = 'W'; +``` + +### sx_view + +```c +sx_view_t sx_view(const sx_t *h); +``` + +Returns the whole-buffer view. + +- **Parameters:** `h` — buffer. +- **Returns:** `{ref: h->ref, offset: 0, len: sx_len(h)}`. +- **Ownership:** none; the view aliases `h` and is never freed. +- **Edge cases:** zero-copy and read-only; `h == NULL` is out of + contract. + +## Capacity + +### sx_reserve + +```c +sx_t *sx_reserve(sx_t *self, size_t min_cap); +``` + +Ensures room for at least `min_cap` content bytes plus the terminator. + +- **Parameters:** `self` — buffer; `min_cap` — number of content bytes + that must fit without a later reallocation. +- **Returns:** `self` on success (including a no-op request), or `NULL` + on allocation failure. +- **Ownership:** `self` is returned and stays caller-owned; content and + length are preserved. +- **Edge cases:** on success `cap >= min_cap + 1`. A request the current + capacity already satisfies does not shrink or otherwise change it. + Capacity only grows; `sx_truncate` and `sx_clear` never release it. + The backing array may move, so all `sx_buf_mut` pointers must be + re-fetched afterwards. + +```c +buf = sx_reserve(buf, 4096); /* cap >= 4097 */ +``` + +## Appending + +### sx_append + +```c +sx_t *sx_append(sx_t *self, sx_t *owned); +``` + +Appends the content of another buffer, consuming that buffer. + +- **Parameters:** `self` — destination; `owned` — source whose content + is appended. +- **Returns:** `self`, or `NULL` when `owned == NULL` or on allocation + failure. +- **Ownership:** ownership transfer: the call reads `owned`'s content + and then frees `owned`. Do not use or free `owned` afterwards. +- **Edge cases:** byte-exact: the content length is used, so embedded + `'\0'` bytes are appended. On `owned == NULL` nothing changes. `self` + may reallocate. Passing `self` as `owned` is out of contract (it + would be freed while in use). + +### sx_append_cstr + +```c +sx_t *sx_append_cstr(sx_t *self, const char *s); +``` + +Appends a C string. + +- **Parameters:** `self` — destination; `s` — NUL-terminated source. +- **Returns:** `self`, or `NULL` when `s == NULL` or on allocation + failure. +- **Ownership:** none; `s` is only read. +- **Edge cases:** `strlen` semantics — an embedded `'\0'` truncates the + appended bytes. Appending `""` is a no-op that returns `self`. + +### sx_append_view + +```c +sx_t *sx_append_view(sx_t *self, sx_view_t v); +``` + +Appends the bytes of a view. + +- **Parameters:** `self` — destination; `v` — source window; `v.len` + bytes are read from `v.ref->ptr + v.offset`. +- **Returns:** `self`, or `NULL` on allocation failure. +- **Ownership:** none; `v` is only read. +- **Edge cases:** byte-exact and binary-safe. `v` may alias `self`, + including when the append grows the buffer: doubling a buffer in + place with `sx_append_view(h, sx_view(h))` is supported. `v.ref == + NULL` or an out-of-bounds window is out of contract. + +```c +buf = sx_append_view(buf, sx_view(buf)); /* doubles in place */ +``` + +## Writing + +### sx_write + +```c +sx_t *sx_write(sx_t *self, size_t idx, sx_t *owned); +``` + +Overwrites bytes starting at `idx`, growing the length if needed, and +consumes the source buffer. + +- **Parameters:** `self` — destination; `idx` — first byte to overwrite; + `owned` — source whose content is written. +- **Returns:** `self`, or `NULL` when `owned == NULL` or on allocation + failure. +- **Ownership:** ownership transfer: the call reads `owned`'s content + and then frees `owned`. Do not use or free it afterwards. +- **Edge cases:** after the call `len' = max(len, idx + owned.len)` — + writing never shrinks the buffer. `idx == len` behaves as an append; + `idx < len` overwrites in place; `idx > len` extends and the bytes in + `[len, idx)` are **unspecified**. Passing `self` as `owned`, or an + `idx + n` that overflows `size_t`, is out of contract. + +```c +buf = sx_new_from_cstr("abc"); +buf = sx_write_cstr(buf, 6, "XY"); /* len 8; bytes 3..5 unspecified */ +``` + +### sx_write_cstr + +```c +sx_t *sx_write_cstr(sx_t *self, size_t idx, const char *s); +``` + +Writes a C string at `idx`. + +- **Parameters:** `self` — destination; `idx` — first byte to write; + `s` — NUL-terminated source. +- **Returns:** `self`, or `NULL` when `s == NULL` or on allocation + failure. +- **Ownership:** none; `s` is only read. +- **Edge cases:** `strlen` semantics (an embedded `'\0'` truncates the + written bytes). On `s == NULL`, `self` is left untouched. Same + `idx`/padding rules as `sx_write`. + +### sx_write_view + +```c +sx_t *sx_write_view(sx_t *self, size_t idx, sx_view_t v); +``` + +Writes the bytes of a view at `idx`. + +- **Parameters:** `self` — destination; `idx` — first byte to write; + `v` — source window. +- **Returns:** `self`, or `NULL` on allocation failure. +- **Ownership:** none; `v` is only read. +- **Edge cases:** byte-exact and binary-safe. `v` may alias `self`, + including when the write must grow the buffer (the source bytes are + preserved across the reservation). Same `idx`/padding rules as + `sx_write`; an out-of-bounds window is out of contract. + +## Inserting + +### sx_insert + +```c +sx_t *sx_insert(sx_t *self, size_t idx, sx_t *owned); +``` + +Inserts the content of another buffer at `idx`, shifting the tail +right, and consumes that buffer. + +- **Parameters:** `self` — destination; `idx` — insertion point with + `0 <= idx <= len`; `owned` — source whose content is inserted. +- **Returns:** `self`, or `NULL` when `owned == NULL` or on allocation + failure. +- **Ownership:** ownership transfer: the call reads `owned`'s content + and then frees `owned`. Do not use or free it afterwards. +- **Edge cases:** the result is `[0, idx)` ++ inserted bytes ++ + `[idx, len)`, with `len' = len + n`. `idx == len` is append-like. + `idx > len` is out of contract (the tail shift underflows); passing + `self` as `owned` is out of contract. + +```c +buf = sx_insert_cstr(buf, 3, "-"); /* shift the tail right */ +``` + +### sx_insert_cstr + +```c +sx_t *sx_insert_cstr(sx_t *self, size_t idx, const char *s); +``` + +Inserts a C string at `idx`. + +- **Parameters:** `self` — destination; `idx` — insertion point with + `0 <= idx <= len`; `s` — NUL-terminated source. +- **Returns:** `self`, or `NULL` when `s == NULL` or on allocation + failure. +- **Ownership:** none; `s` is only read. +- **Edge cases:** `strlen` semantics; on `s == NULL`, `self` is left + untouched. `idx > len` is out of contract. + +### sx_insert_view + +```c +sx_t *sx_insert_view(sx_t *self, size_t idx, sx_view_t v); +``` + +Inserts the bytes of a view at `idx`. + +- **Parameters:** `self` — destination; `idx` — insertion point with + `0 <= idx <= len`; `v` — source window. +- **Returns:** `self`, or `NULL` on allocation failure. +- **Ownership:** none; `v` is only read. +- **Edge cases:** byte-exact and binary-safe. `v` may alias `self`, + including when the insert grows the buffer, as long as its window starts + at or before `idx` (the tested case: a slice taken at the insertion + point). A self-aliased window that starts after `idx` lies in the region + the tail shift overwrites and is **out of contract** — copy it first with + `sx_new_from_view`. `idx > len` and out-of-bounds views are out of + contract. + +## Truncating, erasing and clearing + +### sx_truncate + +```c +sx_t *sx_truncate(sx_t *self, size_t new_len); +``` + +Sets the content length to `new_len`. + +- **Parameters:** `self` — buffer; `new_len` — the new length in content + bytes. +- **Returns:** `self` on success, or `NULL` on allocation failure while + growing. +- **Ownership:** `self` is returned and stays caller-owned. +- **Edge cases:** a shorter `new_len` keeps the prefix and drops the + tail; the same `new_len` is a no-op. A longer `new_len` grows the + buffer: `len` becomes `new_len`, `ptr[new_len] == '\0'`, and the + bytes in `[old_len, new_len)` are **unspecified** — never read them + until they are overwritten. Capacity is not reduced by a shrink. + +### sx_erase + +```c +sx_t *sx_erase(sx_t *self, size_t idx, size_t n); +``` + +Removes `n` bytes starting at `idx`, shifting the tail left. + +- **Parameters:** `self` — buffer; `idx` — first byte to remove; `n` — + number of bytes to remove. +- **Returns:** `self`. +- **Ownership:** `self` is returned and stays caller-owned; `self` + itself must be valid. +- **Edge cases:** `idx + n == len` erases the suffix; `idx + n > len` is + a no-op that returns `self` unchanged; `n == 0` is a no-op. No + allocation happens, so the call does not fail. An `idx + n` that + overflows `size_t` is out of contract. + +```c +buf = sx_erase(buf, 2, 100); /* idx+n > len: no-op, returns self */ +``` + +### sx_clear + +```c +sx_t *sx_clear(sx_t *self); +``` + +Empties the buffer, keeping its capacity. + +- **Parameters:** `self` — buffer. +- **Returns:** `self`. +- **Ownership:** `self` is returned and stays caller-owned. +- **Edge cases:** sets `len = 0` and `ptr[0] = '\0'`; the allocation and + its capacity are kept, so the buffer is immediately reusable. + +```c +buf = sx_clear(buf); /* len 0, capacity kept */ +``` + +## Substrings + +### sx_substr + +```c +sx_t *sx_substr(const sx_t *h, size_t idx, size_t n); +``` + +Copies the byte range `[idx, idx + n)` into a new, independent buffer. + +- **Parameters:** `h` — source buffer; `idx` — start offset; `n` — + number of bytes, with the precondition `idx + n <= len(h)`. +- **Returns:** a new caller-owned buffer, or `NULL` on allocation + failure. (A NULL `h` or an out-of-bounds range is out of contract, + not an error value.) +- **Ownership:** caller-owned; release with `sx_free`. +- **Edge cases:** `n == 0` yields an empty buffer. Byte-exact and + binary-safe, including embedded `'\0'` bytes. Unlike view navigation, + this copies: mutations on either side never affect the other. + +```c +sx_t *word = sx_substr(buf, 6, 5); /* a copy, not a view */ +sx_free(word); +``` + +## View navigation + +All four functions re-derive the `(offset, len)` window over an existing +buffer. None of them copies bytes or modifies the buffer; they only +return a new view value. Inputs must be valid views (`ref != NULL`, the +window inside the buffer); invalid input is out of contract. + +### sx_view_advance + +```c +sx_view_t sx_view_advance(sx_view_t v, size_t n); +``` + +Moves the start of the window right by `n`. + +- **Parameters:** `v` — input view; `n` — bytes to advance. +- **Returns:** the adjusted view over the same buffer. +- **Ownership:** none. +- **Edge cases:** with `H = len(ref)`: + - if `offset + len + n < H`, the end is kept and `len` shrinks by + exactly `n`; + - otherwise, if `offset + n < H`, the start becomes `offset + n` and + the end clamps to the buffer end (`len = H - offset`); + - otherwise the result is the empty view `(H, 0)`. + Advancing never moves past the buffer end, even for a large `n`, and + advancing a sub-view beyond its own end widens it to the buffer end + (second case), as specified. + +```c +sx_view_t rest = sx_view_advance(sx_view(buf), 2); /* start +2 */ +``` + +### sx_view_retreat + +```c +sx_view_t sx_view_retreat(sx_view_t v, size_t n); +``` + +Moves the start of the window left by `n`, keeping the end fixed. + +- **Parameters:** `v` — input view; `n` — bytes to retreat. +- **Returns:** the adjusted view over the same buffer. +- **Ownership:** none. +- **Edge cases:** `len` grows by the same amount the offset shrinks; the + move saturates at offset 0 (`len` becomes the original + `offset + len`), so the window never starts before the buffer. + +### sx_view_shift + +```c +sx_view_t sx_view_shift(sx_view_t v, ptrdiff_t off); +``` + +Moves the window by a signed offset, preserving its length. + +- **Parameters:** `v` — input view; `off` — signed byte offset. +- **Returns:** the adjusted view over the same buffer. +- **Ownership:** none. +- **Edge cases:** `len` is preserved (unlike advance/retreat). A + positive `off` that would push the end past the buffer is clamped to + `offset = H - len` (the window ends at the buffer end); a negative + `off` saturates the start at 0. On an empty buffer the result is + `(0, 0)`. + +### sx_view_range + +```c +sx_view_t sx_view_range(sx_view_t v, size_t off, size_t len); +``` + +Re-anchors the window at absolute coordinates, ignoring the input +view's offset and length. + +- **Parameters:** `v` — supplies only the backing buffer; `off` — + absolute start offset, with the precondition `off <= H`; `len` — + requested length. +- **Returns:** the view `(off, min(len, H - off))`. +- **Ownership:** none. +- **Edge cases:** the length is clamped to the buffer end; `off == H` + gives `(H, 0)`; `off > H` is out of contract (`H - off` underflows). + +```c +sx_view_t slice = sx_view_range(sx_view(buf), 2, 3); /* absolute (2, 3) */ +``` + +## Trimming views + +The trim family removes ASCII whitespace from the edges of a view. The +whitespace set is exactly `{space, '\t', '\v', '\f', '\r', '\n'}`. No +buffer bytes are ever modified, and only bytes inside the window are +inspected. + +### sx_view_trim + +```c +sx_view_t sx_view_trim(sx_view_t v); +``` + +Trims both edges of the view. + +- **Parameters:** `v` — input view. +- **Returns:** the view with leading and trailing whitespace removed. +- **Ownership:** none. +- **Edge cases:** equivalent to `sx_view_trim_back(sx_view_trim_front(v))`. + A view with no edge whitespace is returned unchanged. A view whose + content is entirely whitespace becomes the empty view at the window's + end (offset `offset + len`, length 0) — `(H, 0)` for a whole-buffer + view. + +```c +sx_view_t field = sx_view_trim(sx_view(buf)); /* strip ASCII whitespace */ +``` + +### sx_view_trim_front + +```c +sx_view_t sx_view_trim_front(sx_view_t v); +``` + +Drops leading whitespace. + +- **Parameters:** `v` — input view. +- **Returns:** the view with leading whitespace removed. +- **Ownership:** none. +- **Edge cases:** the offset moves right and `len` shrinks by the same + amount, so the window end stays fixed. The scan is bounded by the + view's own length and never runs past the window's end, even when + whitespace continues in the buffer after it. + +### sx_view_trim_back + +```c +sx_view_t sx_view_trim_back(sx_view_t v); +``` + +Drops trailing whitespace. + +- **Parameters:** `v` — input view. +- **Returns:** the view with trailing whitespace removed. +- **Ownership:** none. +- **Edge cases:** only the window's last byte (`offset + len - 1`) is + inspected and `len` shrinks leftwards; the offset is unchanged, so an + all-whitespace window becomes `(offset, 0)`. Bytes outside the window + are never examined. + +## Complete example + +This program builds a string, trims a view of it, copies the trimmed +window into a new buffer, edits that buffer in place, and releases both +buffers. It compiles as written with the library sources and is also the +shape of a normal application: + +```c +#include +#include + +int main(void) { + sx_t *h = sx_new_from_cstr(" hello, world "); + + sx_view_t trimmed = sx_view_trim(sx_view(h)); /* (2, 12) */ + sx_t *clean = sx_new_from_view(trimmed); /* independent copy */ + + clean = sx_append_cstr(clean, "!"); + clean = sx_insert_cstr(clean, 0, "> "); + + printf("%s (%d bytes)\n", sx_buf_mut(clean), sx_len(clean)); + + sx_free(clean); + sx_free(h); + return 0; +} +``` + +Expected output: + +```text +> hello, world! (15 bytes) +``` + +--- + +[← Previous](guide.md) · [Docs home](README.md) · [Next →](api-search.md) diff --git a/docs/en_us/api-search.md b/docs/en_us/api-search.md new file mode 100644 index 0000000..bd4bd62 --- /dev/null +++ b/docs/en_us/api-search.md @@ -0,0 +1,620 @@ +English · [中文](../zh_cn/api-search.md) + +[Docs home](README.md) › API reference: search, compare & split + +# Search, compare and split + +The complete reference for the search family (`sx_find*`, `sx_rfind*`, +`sx_find_all*`), the comparison family (`sx_cmp*`, `sx_starts_with*`, +`sx_ends_with*`) and `sx_split`. All of them are byte-exact and work on +content lengths, so embedded NUL bytes are ordinary data. Buffer +creation, mutation and views are documented in +[Buffers and views](api-buffer.md). + +## Conventions + +**Needle forms.** Every search family has the same four needle shapes: + +| Suffix | Argument type | Bytes matched | NUL behavior | +| --- | --- | --- | --- | +| none | `const sx_t *` | the buffer's content bytes | embedded NUL is data | +| `_view` | `sx_view_t` | `v.len` bytes at `v.ref->ptr + v.offset` | embedded NUL is data | +| `_cstr` | `const char *` | `strlen(...)` bytes | the first NUL ends the needle | +| `_char` | `char` | exactly one byte | `'\0'` means a NUL content byte | + +The owned and view forms are binary-safe: they read exactly the +needle's length, so an embedded `'\0'` is matched as data. The `_cstr` +forms use `strlen`, so `sx_find_cstr(h, "a\0c")` actually searches for +`"a"`; use an owned or view needle to search binary patterns. An empty +needle (length 0) is never found. + +**Bounded regions.** With `H` = the haystack's content length and a needle of `m` bytes, a +match is a window `[p, p + m)` that must lie entirely inside the +searched region: + +| Function | Search region | Window requirement | +| --- | --- | --- | +| `sx_find*`, `sx_rfind*` (unbounded) | `[0, H)` | `p + m <= H` | +| `sx_find_view_b(h, needle, boundary)` | `[boundary, H)` | `p >= boundary` and `p + m <= H` | +| `sx_rfind_view_b(h, needle, boundary)` | `[0, min(boundary, H))` | `p + m <= min(boundary, H)` | + +The two bounded forms take a `size_t boundary` and differ in direction: +`sx_find_view_b` bounds the region on the left and excludes any window +that starts before `boundary`; `sx_rfind_view_b` bounds it on the right +and excludes any window that ends after the boundary. Concrete cases +from the tests, with `h = "ababa"` and needle `"ba"`: + +- `sx_find_view_b(h, nd, 2)` is 3 — the match at offset 1 starts before + the boundary and does not count; boundary 4 gives `(size_t)-1` + because the remaining region `"a"` is too small for one window. +- `sx_rfind_view_b(h, nd, 3)` is 1 — the match at 3 ends at 5, past the + boundary; boundary 2 gives `(size_t)-1`; with needle `"aba"` and + boundary 3 the window `[0, 3)` ends exactly at the boundary and the + result is 0. +- For `sx_find_view_b`, `boundary >= H` is an empty region and returns + `(size_t)-1`. For `sx_rfind_view_b`, a boundary at or above `H` + clamps to `H`, so it behaves like an unbounded rightmost search. + +**Binary safety.** The haystack is always searched by content length +(`H`), never as a C string: embedded `'\0'` bytes are ordinary bytes, +and the terminator at `ptr[H]` is outside the searched region. In +particular `sx_find_char(h, '\0')` reports only embedded NUL content +bytes, never the terminator. Owned and view needles are read by length +too; only `_cstr` needles stop at the first NUL. + +**Sentinels and NULL.** + +| Family | Missing result / rejected input | +| --- | --- | +| `sx_find*`, `sx_rfind*` | `(size_t)-1` | +| `sx_find_all*` | `NULL` | +| `sx_cmp*` | `0` when an operand is NULL | +| `sx_starts_with*`, `sx_ends_with*` | `0` | +| `sx_split` | `NULL` | + +The search functions check their pointer arguments: a NULL `h` or a +NULL needle argument returns the family sentinel instead of crashing. +For the view variants, `v.ref == NULL` is out of contract — the +pointer is formed before any length check, so always pass a view of a +live buffer. Allocation failure is reported with the same sentinel as +"no match" by `sx_find_all*` and `sx_split`; the two cases are +indistinguishable by contract. `(size_t)-1` cannot collide with a real +offset because offsets are below `INT_MAX` content bytes. + +**Search strategy.** One-byte needles use `memchr` (forward) or a +byte-wise backward scan, glibc's `memrchr` when available, and allocate +nothing. Longer needles use KMP: a temporary prefix table of `m` +`size_t` entries is allocated for the duration of the call, so one +search is O(n + m) worst case. `sx_find_all*` additionally returns a +malloc'ed result array. `sx_find_all*` reports every occurrence, +overlapping ones included. + +## Choosing the right call + +| You need | Call | +| --- | --- | +| leftmost occurrence in the whole string | `sx_find*` | +| rightmost occurrence in the whole string | `sx_rfind*` | +| every occurrence, overlaps included | `sx_find_all*` | +| leftmost occurrence at or after a boundary | `sx_find_view_b` | +| rightmost occurrence ending at or before a boundary | `sx_rfind_view_b` | +| equality or ordering | `sx_cmp*` | +| prefix or suffix test | `sx_starts_with*`, `sx_ends_with*` | +| split into tokens | `sx_split` | + +## Leftmost search: `sx_find*` + +### sx_find + +```c +size_t sx_find(const sx_t *h, const sx_t *needle); +``` + +Finds the leftmost occurrence of another buffer's content in `h`. + +- **Parameters:** `h` — haystack; `needle` — buffer whose content is + searched for. +- **Returns:** the byte offset of the leftmost match, or `(size_t)-1` + when there is none. +- **Ownership:** none; neither buffer is modified. A temporary KMP + prefix table is allocated and freed inside the call for needles longer + than one byte. +- **Edge cases:** NULL `h` or `needle` returns `(size_t)-1`; an empty + needle returns `(size_t)-1`; a needle longer than `h` never matches. + The match is byte-exact over content lengths, so embedded NULs match. + +### sx_find_view + +```c +size_t sx_find_view(const sx_t *h, sx_view_t needle); +``` + +Finds the leftmost occurrence of a view's bytes in the whole string. + +- **Parameters:** `h` — haystack; `needle` — window whose `needle.len` + bytes are searched for. +- **Returns:** the byte offset of the leftmost match, or `(size_t)-1`. +- **Ownership:** none; only reads. +- **Edge cases:** equivalent to `sx_find_view_b(h, needle, 0)`. An + empty view (`len == 0`) is never found. `needle.ref == NULL` or an + out-of-bounds window is out of contract. + +### sx_find_view_b + +```c +size_t sx_find_view_b(const sx_t *h, sx_view_t needle, size_t boundary); +``` + +Finds the leftmost occurrence of a view's bytes at or after `boundary`. + +- **Parameters:** `h` — haystack; `needle` — window to search for; + `boundary` — region start offset. +- **Returns:** the byte offset of the leftmost match inside + `[boundary, H)`, or `(size_t)-1`. +- **Ownership:** none; only reads. +- **Edge cases:** a match must start at or after `boundary` and end at + or before `H`; a window that straddles the boundary is not a match. + `boundary >= H`, a region too small for one window, and an empty + needle all return `(size_t)-1`. `needle.ref == NULL`, an + out-of-bounds window, or a `boundary + needle.len` that overflows + `size_t` is out of contract. + +```c +sx_t *h = sx_new_from_cstr("ababa"); +sx_t *ba = sx_new_from_cstr("ba"); +size_t at = sx_find_view_b(h, sx_view(ba), 2); /* 3, not 1 */ +sx_free(ba); +sx_free(h); +``` + +### sx_find_cstr + +```c +size_t sx_find_cstr(const sx_t *h, const char *needle); +``` + +Finds the leftmost occurrence of a C string in `h`. + +- **Parameters:** `h` — haystack; `needle` — NUL-terminated pattern, + read with `strlen`. +- **Returns:** the byte offset of the leftmost match, or `(size_t)-1`. +- **Ownership:** none; only reads. +- **Edge cases:** NULL `h` or `needle` returns `(size_t)-1`; an empty + needle returns `(size_t)-1`. The needle cannot contain a literal NUL; + use `sx_find_view` for binary patterns. The haystack may contain NULs. + +### sx_find_char + +```c +size_t sx_find_char(const sx_t *h, char c); +``` + +Finds the leftmost occurrence of a single byte. + +- **Parameters:** `h` — haystack; `c` — the byte to search for. +- **Returns:** the byte offset of the leftmost occurrence, or + `(size_t)-1`. +- **Ownership:** none; only reads. +- **Edge cases:** NULL `h` returns `(size_t)-1`. The search covers the + content only (`[0, H)`), so `c == '\0'` finds embedded NUL content + bytes but never the terminator. + +## Rightmost search: `sx_rfind*` + +### sx_rfind + +```c +size_t sx_rfind(const sx_t *h, const sx_t *needle); +``` + +Finds the rightmost occurrence of another buffer's content in `h`. + +- **Parameters:** `h` — haystack; `needle` — buffer whose content is + searched for. +- **Returns:** the byte offset of the rightmost match, or `(size_t)-1`. +- **Ownership:** none; neither buffer is modified. A temporary KMP + prefix table is allocated and freed inside the call for needles longer + than one byte. +- **Edge cases:** NULL `h` or `needle` returns `(size_t)-1`; an empty + needle returns `(size_t)-1`; a needle longer than `h` never matches. + Byte-exact and binary-safe. + +### sx_rfind_view + +```c +size_t sx_rfind_view(const sx_t *h, sx_view_t needle); +``` + +Finds the rightmost occurrence of a view's bytes in the whole string. + +- **Parameters:** `h` — haystack; `needle` — window whose + `needle.len` bytes are searched for. +- **Returns:** the byte offset of the rightmost match, or `(size_t)-1`. +- **Ownership:** none; only reads. +- **Edge cases:** equivalent to `sx_rfind_view_b(h, needle, H)`. An + empty view is never found. `needle.ref == NULL` or an out-of-bounds + window is out of contract. + +### sx_rfind_view_b + +```c +size_t sx_rfind_view_b(const sx_t *h, sx_view_t needle, size_t boundary); +``` + +Finds the rightmost occurrence of a view's bytes that ends at or before +`boundary`. + +- **Parameters:** `h` — haystack; `needle` — window to search for; + `boundary` — region end offset (exclusive). +- **Returns:** the byte offset of the rightmost match whose window ends + inside `[0, min(boundary, H))`, or `(size_t)-1`. +- **Ownership:** none; only reads. +- **Edge cases:** a match must end at or before `boundary`; one that + sticks out past the boundary is not a match. A boundary of 0, a + region too small for one window, and an empty needle all return + `(size_t)-1`. A boundary at or above `H` clamps to `H` and behaves + like an unbounded rightmost search. `needle.ref == NULL` and + out-of-bounds windows are out of contract. + +```c +sx_t *h = sx_new_from_cstr("ababa"); +sx_t *aba = sx_new_from_cstr("aba"); +size_t at = sx_rfind_view_b(h, sx_view(aba), 3); /* 0: ends exactly at 3 */ +sx_free(aba); +sx_free(h); +``` + +### sx_rfind_cstr + +```c +size_t sx_rfind_cstr(const sx_t *h, const char *needle); +``` + +Finds the rightmost occurrence of a C string in `h`. + +- **Parameters:** `h` — haystack; `needle` — NUL-terminated pattern, + read with `strlen`. +- **Returns:** the byte offset of the rightmost match, or `(size_t)-1`. +- **Ownership:** none; only reads. +- **Edge cases:** NULL `h` or `needle` returns `(size_t)-1`; an empty + needle returns `(size_t)-1`. The needle cannot contain a literal NUL. + +### sx_rfind_char + +```c +size_t sx_rfind_char(const sx_t *h, char c); +``` + +Finds the rightmost occurrence of a single byte. + +- **Parameters:** `h` — haystack; `c` — the byte to search for. +- **Returns:** the byte offset of the rightmost occurrence, or + `(size_t)-1`. +- **Ownership:** none; only reads. +- **Edge cases:** NULL `h` returns `(size_t)-1`. The search covers the + content only, so `c == '\0'` never matches the terminator. + +## All occurrences: `sx_find_all*` + +These functions return a malloc'ed `size_t` array in "count first" form: + +```text +r[0] number of matches +r[1 .. r[0]] ascending byte offsets of every match +``` + +Overlapping matches are all reported: `"aa"` inside `"aaaa"` is found at +offsets 0, 1 and 2. There is no end guard (unlike `sx_split` and +`sx_reg_match_all`); the count is authoritative. + +- **Returns:** `NULL` when there is no match — including an empty needle + — when an argument is NULL, or on allocation failure. The two failure + causes are indistinguishable by contract. +- **Ownership:** the caller owns the array and releases it with `free` + (not `sx_free`). Do not read past `r[0] + 1` entries. + +```c +sx_t *h = sx_new_from_cstr("ababab"); +size_t *hits = sx_find_all_cstr(h, "ab"); +/* hits[0] == 3; hits[1] == 0, hits[2] == 2, hits[3] == 4 */ +free(hits); +sx_free(h); +``` + +### sx_find_all + +```c +size_t *sx_find_all(const sx_t *h, const sx_t *needle); +``` + +Collects every occurrence of another buffer's content. + +- **Parameters:** `h` — haystack; `needle` — buffer whose content is + searched for. +- **Returns:** the count-first `size_t` array, or `NULL` (no match, + empty needle, NULL argument, allocation failure). +- **Ownership:** caller-owned; release with `free`. +- **Edge cases:** binary-safe; offsets are ascending and include + overlapping matches. + +### sx_find_all_view + +```c +size_t *sx_find_all_view(const sx_t *h, sx_view_t needle); +``` + +Collects every occurrence of a view's bytes. + +- **Parameters:** `h` — haystack; `needle` — window to search for. +- **Returns:** the count-first `size_t` array, or `NULL` (no match, + empty view, NULL argument, allocation failure). +- **Ownership:** caller-owned; release with `free`. +- **Edge cases:** `needle.ref == NULL` or an out-of-bounds window is out + of contract. + +### sx_find_all_cstr + +```c +size_t *sx_find_all_cstr(const sx_t *h, const char *needle); +``` + +Collects every occurrence of a C string. + +- **Parameters:** `h` — haystack; `needle` — NUL-terminated pattern, + read with `strlen`. +- **Returns:** the count-first `size_t` array, or `NULL` (no match, + empty needle, NULL argument, allocation failure). +- **Ownership:** caller-owned; release with `free`. +- **Edge cases:** the needle cannot contain a literal NUL; the haystack + can. + +### sx_find_all_char + +```c +size_t *sx_find_all_char(const sx_t *h, char c); +``` + +Collects every occurrence of a single byte. + +- **Parameters:** `h` — haystack; `c` — the byte to search for. +- **Returns:** the count-first `size_t` array, or `NULL` (no match, NULL + argument, allocation failure). +- **Ownership:** caller-owned; release with `free`. +- **Edge cases:** searches the content only, so a `'\0'` needle finds + embedded NUL content bytes, never the terminator. + +## Comparison: `sx_cmp*` + +### sx_cmp + +```c +int sx_cmp(const sx_t *h, const sx_t *other); +``` + +Compares two buffers lexicographically over their content bytes. + +- **Parameters:** `h` — left operand; `other` — right operand. +- **Returns:** a negative value if `h` sorts before `other`, 0 if they + are equal, a positive value if `h` sorts after. Only the sign is + meaningful. +- **Ownership:** none; neither buffer is modified. +- **Edge cases:** comparison is byte-wise in `memcmp` order (unsigned + byte values), so `"10" < "2"` and `"Z" < "中"`. A shorter string that + is a prefix of the other sorts first (`"abc" < "abcd"`). Embedded NUL + bytes compare as data. If either operand is NULL the result is 0 + (treated as equal) — never rely on that as a meaningful order. + +### sx_cmp_view + +```c +int sx_cmp_view(const sx_t *h, sx_view_t other); +``` + +Compares a buffer with a view's bytes. + +- **Parameters:** `h` — left operand; `other` — right operand window; + `other.len` bytes are compared. +- **Returns:** negative, 0 or positive as in `sx_cmp`. +- **Ownership:** none; only reads. +- **Edge cases:** NULL `h` returns 0. `other.ref == NULL` or an + out-of-bounds window is out of contract. + +### sx_cmp_cstr + +```c +int sx_cmp_cstr(const sx_t *h, const char *s); +``` + +Compares a buffer with a C string. + +- **Parameters:** `h` — left operand; `s` — NUL-terminated right + operand, read with `strlen`. +- **Returns:** negative, 0 or positive as in `sx_cmp`. +- **Ownership:** none; only reads. +- **Edge cases:** NULL `h` or `s` returns 0. An embedded NUL in `s` + shortens the compared range. + +## Prefix and suffix predicates + +### sx_starts_with + +```c +int sx_starts_with(const sx_t *h, const sx_t *prefix); +``` + +Tests whether `h` starts with another buffer's content. + +- **Parameters:** `h` — buffer; `prefix` — buffer whose content is the + prefix. +- **Returns:** 1 if the first `len(prefix)` content bytes of `h` equal + the prefix byte for byte, otherwise 0. +- **Ownership:** none; only reads. +- **Edge cases:** an empty prefix always matches; a prefix longer than + `h` never matches. Byte-exact and binary-safe. NULL `h` or `prefix` + returns 0. + +### sx_starts_with_view + +```c +int sx_starts_with_view(const sx_t *h, sx_view_t prefix); +``` + +Tests whether `h` starts with a view's bytes. + +- **Parameters:** `h` — buffer; `prefix` — window read by + `prefix.len` bytes. +- **Returns:** 1 on a match, otherwise 0. +- **Ownership:** none; only reads. +- **Edge cases:** an empty view always matches. NULL `h` returns 0; + `prefix.ref == NULL` or an out-of-bounds window is out of contract. + +### sx_starts_with_cstr + +```c +int sx_starts_with_cstr(const sx_t *h, const char *prefix); +``` + +Tests whether `h` starts with a C string. + +- **Parameters:** `h` — buffer; `prefix` — NUL-terminated prefix, read + with `strlen`. +- **Returns:** 1 on a match, otherwise 0. +- **Ownership:** none; only reads. +- **Edge cases:** the empty string always matches; NULL `h` or `prefix` + returns 0. + +### sx_ends_with + +```c +int sx_ends_with(const sx_t *h, const sx_t *suffix); +``` + +Tests whether `h` ends with another buffer's content. + +- **Parameters:** `h` — buffer; `suffix` — buffer whose content is the + suffix. +- **Returns:** 1 if the last `len(suffix)` content bytes of `h` equal + the suffix byte for byte, otherwise 0. +- **Ownership:** none; only reads. +- **Edge cases:** an empty suffix always matches; a suffix longer than + `h` never matches. Byte-exact and binary-safe. NULL `h` or `suffix` + returns 0. + +### sx_ends_with_view + +```c +int sx_ends_with_view(const sx_t *h, sx_view_t suffix); +``` + +Tests whether `h` ends with a view's bytes. + +- **Parameters:** `h` — buffer; `suffix` — window read by + `suffix.len` bytes. +- **Returns:** 1 on a match, otherwise 0. +- **Ownership:** none; only reads. +- **Edge cases:** an empty view always matches. NULL `h` returns 0; + `suffix.ref == NULL` or an out-of-bounds window is out of contract. + +### sx_ends_with_cstr + +```c +int sx_ends_with_cstr(const sx_t *h, const char *suffix); +``` + +Tests whether `h` ends with a C string. + +- **Parameters:** `h` — buffer; `suffix` — NUL-terminated suffix, read + with `strlen`. +- **Returns:** 1 on a match, otherwise 0. +- **Ownership:** none; only reads. +- **Edge cases:** the empty string always matches; NULL `h` or `suffix` + returns 0. + +## Splitting: sx_split + +### sx_split + +```c +sx_view_t *sx_split(const sx_t *h, const char *sep); +``` + +Splits a buffer on a C-string separator into an array of token views. +The declaration lives in `sx.h` (the advanced layer), not in +`sx_core.h`. + +- **Parameters:** `h` — buffer to split; `sep` — separator C string, + read with `strlen`. An empty separator is refused, not treated as + "every byte". +- **Returns:** a malloc'ed `sx_view_t` array with the classic `char **` + shape, or `NULL` for NULL `h`, NULL `sep`, an empty `sep`, or + allocation failure. +- **Ownership:** the caller owns the array and releases it with `free` + (not `sx_free`). The tokens are views into `h` and must never be + freed individually. +- **Contract notes:** + - The array has exactly `count + 1` elements: `arr[0] .. arr[count-1]` + are the tokens in order, and `arr[count]` is the end guard whose + `.ref == NULL`. Iterate with + `for (size_t i = 0; arr[i].ref != NULL; i++)`. + - `count == 1 + (number of separator occurrences)`. Separators are + matched left to right and are non-overlapping: after a hit the scan + resumes past it, so `"aaaa"` split on `"aa"` yields three empty + tokens, not two. + - Empty fields are kept at every edge and in the interior: `"a,,b"` + gives `"a"`, `""`, `"b"`; a leading or trailing separator produces + an empty first or last token; an empty `h` splits into the single + token `""`; a string equal to the separator splits into two empty + tokens. + - An empty token is not the end guard: it has `ref != NULL` and + `len == 0`, while the guard has `ref == NULL`. + - Tokens alias `h`'s content (`ref == h->ref`, `offset`, `len`): + copying nothing, modifying nothing, and reallocating nothing during + the call, so the content pointer is bitwise unchanged. Later edits + of `h` invalidate the tokens; do not edit `h` while they are in + use. + - Matching is byte-exact, so tokens may contain embedded NUL bytes + (the separator itself, being a C string, cannot). Print such a + token with `fwrite` or `"%.*s"` and its length, not with `"%s"`. + +The regex layer's `sx_reg_split` returns exactly this shape; see +[Regular expressions](regex.md). + +Full example — split, iterate to the end guard, then release the array +and the buffer: + +```c +#include +#include +#include + +int main(void) { + sx_t *csv = sx_new_from_cstr("alpha,beta,,gamma,"); + sx_view_t *fields = sx_split(csv, ","); + + if (!fields) + return 1; + + for (size_t i = 0; fields[i].ref != NULL; i++) + printf("field %zu: \"%.*s\" (offset %zu, len %zu)\n", i, + (int)fields[i].len, sx_buf_view_mut(fields[i]), + fields[i].offset, fields[i].len); + + free(fields); /* the array, not the tokens */ + sx_free(csv); + return 0; +} +``` + +Expected output (the trailing separator produces an empty last field): + +```text +field 0: "alpha" (offset 0, len 5) +field 1: "beta" (offset 6, len 4) +field 2: "" (offset 11, len 0) +field 3: "gamma" (offset 12, len 5) +field 4: "" (offset 18, len 0) +``` + +--- + +[← Previous](api-buffer.md) · [Docs home](README.md) · [Next →](regex.md) diff --git a/docs/en_us/build-and-test.md b/docs/en_us/build-and-test.md new file mode 100644 index 0000000..7c3cf8b --- /dev/null +++ b/docs/en_us/build-and-test.md @@ -0,0 +1,359 @@ +English · [中文](../zh_cn/build-and-test.md) + +[Docs home](README.md) › Build, test & package + +# Build, test & package + +String X builds with [Forge](https://github.com/minelogy-dev/forge), a build +system whose build script is a C program. This page covers the toolchain +requirements, every `./make` task, the test harness and sanitizers, +installation, pkg-config and Debian packaging. For the CI pipelines that run +these commands, see [Continuous integration](ci.md). + +## Prerequisites + +| Requirement | Notes | +| --- | --- | +| Linux | CI uses Ubuntu 24.04; other Linux distributions work. | +| C23 compiler | GCC 14+ or Clang 19+. | +| `libpcre2-dev` | PCRE2 10.46, 8-bit, for the regex layer and every test. At run time the library needs `libpcre2-8-0`. | +| `pkg-config` | Recommended for consumers; CI also uses it to link against the installed library. | +| Forge | The build tool; bootstrap it from source (next section). `./make` is generated, not checked in. | +| `tar` and `ar` | Only for `./make gen_deb`; `dpkg-deb` is only needed to inspect the result. | + +Run every command from the repository root: `build.c` and `build.conf` are read +relative to it. + +## Forge in one minute + +Forge compiles `build.c` into a local executable, `./make`. That generated file +is the build entry point: each task below is a function in `build.c`, invoked as +`./make `. It is not GNU make. Re-run `forge .` whenever `build.c` or +`build.conf` changes. + +Bootstrap Forge from source and put its artifacts on the search paths: + +```sh +git clone https://github.com/minelogy-dev/forge.git +cd forge +./bootstrap.sh --no-test +export PATH="$PWD/build/output:$PATH" +export CPATH="$PWD/build/output/include" +cd /path/to/StringX +forge . +``` + +CI pins Forge to commit +`b6826ba762a1e9e337895e01ee604b943c682d23`. To reproduce CI exactly, check out +that commit into `.ci-deps/forge` and bootstrap it without installing system +files: + +```sh +git clone https://github.com/minelogy-dev/forge.git .ci-deps/forge +git -C .ci-deps/forge checkout b6826ba762a1e9e337895e01ee604b943c682d23 +sh .ci-deps/forge/bootstrap.sh --no-test +export PATH="$PWD/.ci-deps/forge/build/output:$PATH" +export CPATH="$PWD/.ci-deps/forge/build/output/include" +forge . +``` + +Keep the pin identical in `.github/workflows/ci.yml` and +`.github/workflows/codeql.yml` when changing Forge. It is deliberately +independent of Forge's `main` branch and is not updated by Dependabot. + +With Forge on `PATH`, the everyday commands are the ones from the README: + +```sh +forge . # compile build.c into ./make (re-run whenever build.c changes) +./make # build -> build/output/libstringx.so (+ headers at build/output/include) +./make test # build and run every test under tests/ (ASan + UBSan) +``` + +## Targets and commands + +| Command | What it does | +| --- | --- | +| `forge .` | Compile `build.c` with the `build.conf` settings into a local `./make`. | +| `./make` | Default `build` task: compile `src/` into `build/output/libstringx.so` and sync `include/*.h` to `build/output/include/`. | +| `./make check` | Compile the library target with the warning flags and the GCC analyzer, without the header sync. | +| `./make test` | Build and run every file in `tests/` under ASan + UBSan + LSan. | +| `./make test -j 2` | The same, compiling the source files of each test in parallel (2-way here). | +| `./make install ` | Build, then install the library, headers, notices and `libstringx.pc`; the prefix defaults to `/usr/local`. | +| `./make gen_deb` | Build, then stage and produce `build/deb/libstringx__.deb`. | + +`-v` makes `./make test` and `./make check` print the full compile commands; +without it only `PASSED`/`FAILED` lines and the final summary are shown. `-j N` +parallelizes one target's compile pass. + +The artifacts land here: + +| Path | Produced by | Contents | +| --- | --- | --- | +| `build/output/libstringx.so` | `./make`, `./make check`, `./make install`, `./make gen_deb` | the shared library | +| `build/output/include/` | `./make`, `./make install`, `./make gen_deb` | synced copies of `sx.h`, `sx_core.h` and `sx_raw.h` | +| `build/exe-obj/` | `./make`, `./make check` | per-source object files with their `.d`/`.meta` incrementality files | +| `test/` | `./make test` | one executable per test file (`tests/new.c` → `test/new`) | +| `build/opt/` | `./make test` | test object files with their `.d`/`.meta` files | +| `build/deb/` | `./make gen_deb` | the Debian staging tree and the final `.deb` | + +`./make test` does not need `./make` first: every test compiles the library +sources directly. + +## build.conf + +`build.conf` is read when Forge generates `./make`; each `KEY=VALUE` line +becomes a `-DCONF_KEY=VALUE` macro for the build script. Lines starting with +`#` are comments. Re-run `forge .` after editing it. + +| Key | Value | Effect | +| --- | --- | --- | +| `compiler` | `GCC` or `CLANG` | Toolchain backend. `build.c` forwards `CONF_compiler` to `set_toolchain`, so this selects the compiler for the library and the tests. | +| `compiler_path` | an absolute path, e.g. `/usr/bin/gcc` | The compiler binary Forge uses to build the generated `./make`. | +| `version` | `v0.5` | The single source of truth for the project version. `build.c` stringifies it into `SX_VERSION`; install and packaging strip the leading `v`. | +| `sanitize` | `1` | Added by `.github/scripts/configure.sh` in CI. The sanitizer flags themselves are declared per test in the header DSL. | + +## Running the tests + +`./make test` scans `tests/` recursively, compiles each `tests/*.c` into +`test/` and runs it. A test prints `PASSED: ` on success, or +`FAILED: :: ` on the first failing assertion. The task +ends with a summary such as: + +```text +forge: 20 tests, 20 passed, 0 failed +``` + +The task exits non-zero if any test fails to compile or to run. + +Tests do not link `libstringx.so`: each one compiles the library sources +directly and declares its own flags, including `-fsanitize=address,undefined` +and `-fno-omit-frame-pointer`. LeakSanitizer runs together with ASan, so a test +that forgets to free a buffer or a returned array fails. + +Set the same sanitizer options CI uses: + +```sh +export ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 +export UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 +./make test -j 2 +``` + +To rerun one built test directly: + +```sh +./test/reserve_stress +``` + +### Exact-reserve stress test + +`tests/reserve_stress.c` is the dedicated configuration for +`-DSX_FORCE_EXACT_RESERVE`, declared as +`// Option -DSX_FORCE_EXACT_RESERVE` in its header. The switch remaps the +internal reserve helper in `src/sx_raw.c` from geometric growth to exact sizing +(`cap == need + 1`), so an allocation ends exactly at the terminator and any +access past `len` hits an ASan redzone immediately — slack capacity cannot hide +an off-by-one or a stale length. The test drives a deterministic LCG over three +live buffers and asserts full content on every edit; its models stay within +512 bytes. Every other test builds in the default geometric-growth mode. + +## Test files and the header DSL + +Each test is a self-contained program. Its leading consecutive `//` lines form a +header DSL that Forge's test runner reads; the first non-`//` line ends the +header. + +| Entry | Effect | +| --- | --- | +| `// Include ` | Add `-I`. Every test includes `include`, `src` and `/usr/lib/forge/include` — Forge's headers for ``; the last one is harmless when they are supplied through `CPATH` instead. | +| `// Source ` | Add a source file to the test executable. Tests add `src/sx_raw.c`, `src/sx_core.c` and `src/sx_adv.c`. | +| `// Link ` | Add `-l`. Only `tests/reg.c` adds `pcre2-8`; the other tests do not use the regex layer. | +| `// Library ` | Add `-L`. Tests add `/usr/local/lib`. | +| `// Option ` | Add a compiler, linker and assembler option. Tests use `-std=c23 -O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer`, plus test-specific defines such as `-DSX_FORCE_EXACT_RESERVE`. | + +A line without a keyword continues the current scope, which starts as `Source`; +the tests spell out every keyword for clarity. + +Because every test compiles `src/sx_adv.c`, `build.c` attaches `pcre2-8` to +every test target through its reserved `LANGUAGE` override; `tests/reg.c` also +declares `// Link pcre2-8` explicitly. + +The program itself includes the header under test (`"sx.h"`, or `"sx_core.h"` +for core-only tests) and `` for two test macros: + +| Macro | Purpose | +| --- | --- | +| `TEST(expr)` | On failure print `FAILED: :: ` and exit 1; on success print nothing and continue. | +| `PASS()` | Print `PASSED: `; call it at the end of `main`. | + +### Adding a test + +1. Create `tests/.c` — one behavior area per file. +2. Copy the header DSL block from an existing test and adjust `Source`, + `Link` and `Option` for the dependencies you need. +3. Document the behavior boundaries at the top: what the test locks in + (`In scope (contract)`) and what it deliberately does not exercise + (`Out of contract (not exercised)`). +4. Include the header under test, assert with `TEST`, free every buffer and + returned array, then finish with `PASS()`. +5. Run `./make test`. The new file is discovered automatically. + +```c +// Include include +// Include src +// Include /usr/lib/forge/include +// Source src/sx_raw.c +// Source src/sx_core.c +// Source src/sx_adv.c +// Option -std=c23 +// Option -O1 +// Option -g +// Option -fsanitize=address,undefined +// Option -fno-omit-frame-pointer +// Library /usr/local/lib +#include "sx.h" +#include + +/* + * Behavior boundaries — sx_erase (example) + * =================================================================== + * In scope (contract): + * · sx_erase(h, idx, n) removes the n bytes starting at idx, + * shifts the tail left, keeps ptr[len] == '\0', and returns h. + * n == 0 is a no-op; idx + n > len is a no-op returning h. + * Out of contract (not exercised): + * · h == NULL or freed; erase idx > len with n such that idx + n + * wraps; keeping sx_buf_mut pointers across edits. + */ + +int main(void) { + sx_t *h = sx_new_from_cstr("hello"); + TEST(h != NULL); + TEST(sx_erase(h, 1, 3) == h); + TEST(sx_cmp_cstr(h, "ho") == 0); + sx_free(h); + PASS(); + return 0; +} +``` + +## Installing + +`./make install` builds first (including the header sync), then copies: + +| Destination | Contents | +| --- | --- | +| `/lib/libstringx.so` | the shared library | +| `/include/sx.h` | the public API header | +| `/include/sx_core.h` | the core layer included by `sx.h` | +| `/include/sx_raw.h` | the internal allocation header; not part of the supported API | +| `/lib/pkgconfig/libstringx.pc` | pkg-config metadata | +| `/share/doc/libstringx/LICENSE` | the MIT license | +| `/share/doc/libstringx/THIRD_PARTY_NOTICES.md` | PCRE2 attribution and license | +| `/share/doc/libstringx/copyright` | a copy of `LICENSE` under Debian's conventional name | + +The default prefix is `/usr/local`. Pass a prefix you can write to without +root, for example: + +```sh +./make install "$HOME/.local" +``` + +The pkg-config file is generated at install time. Its `prefix=` is the install +prefix and its `Version` is the `build.conf` version without the leading `v` +(so `0.5`). + +## Consuming the installed library + +With pkg-config: + +```sh +cc -std=c23 hello.c $(pkg-config --cflags --libs libstringx) -o hello +./hello +``` + +Without pkg-config: + +```sh +cc -std=c23 hello.c -I/include -L/lib -lstringx -o hello +``` + +For a non-standard prefix, point pkg-config and the loader at it, or bake an +rpath: + +```sh +export PKG_CONFIG_PATH="/lib/pkgconfig" +cc -std=c23 hello.c $(pkg-config --cflags --libs libstringx) \ + -Wl,-rpath,"/lib" -o hello +``` + +The library links `pcre2-8` itself, so consumers do not need `-lpcre2-8`. A +complete program: + +```c +#include +#include + +int main(void) { + sx_t *h = sx_new_from_cstr("hello, world"); + if (h == NULL) + return 1; + printf("len=%d cap=%d: %.*s\n", sx_len(h), sx_cap(h), sx_len(h), + sx_buf_mut(h)); + sx_free(h); + return 0; +} +``` + +## Debian package + +`./make gen_deb` builds first, then stages and packages a Debian `.deb` with +`tar` and `ar` (no `dpkg-deb` dependency): + +| Path | Contents | +| --- | --- | +| `build/deb/data/usr/` | the package data tree at the FHS root: `lib/`, `include/` and `share/doc/libstringx/` | +| `build/deb/control-dir/control` | the package metadata | +| `build/deb/debian-binary`, `control.tar.gz`, `data.tar.gz` | the package parts | +| `build/deb/libstringx__.deb` | the finished package | + +The version comes from `build.conf` with the leading `v` stripped; the +architecture comes from `uname -m` (`x86_64` → `amd64`, `aarch64` → `arm64`, +anything else unchanged). The package installs under `/usr` and declares +`Depends: libc6, libpcre2-8-0`. The `libstringx.pc` inside the package bakes +`/usr` as its prefix; the staging path never leaks into it. + +Inspect and install it: + +```sh +dpkg-deb --info build/deb/libstringx_*.deb +dpkg-deb --contents build/deb/libstringx_*.deb +sudo apt install ./build/deb/libstringx_*.deb +``` + +## Troubleshooting + +| Symptom | Cause and fix | +| --- | --- | +| `forge: command not found` | Forge is not on `PATH`. Bootstrap it and export `PATH=/build/output`. | +| `build.h: No such file or directory` | Forge's build-script headers are not visible. Export `CPATH=/build/output/include` as CI does, or install Forge system-wide. `` exists only inside Forge builds. | +| `pcre2.h: No such file or directory` or `cannot find -lpcre2-8` | Install `libpcre2-dev` (Ubuntu: `sudo apt-get install libpcre2-dev`). | +| `./make: No such file or directory` after cloning | `./make` is generated and gitignored. Run `forge .` first. | +| Changes to `build.c` or `build.conf` have no effect | `./make` was generated from the old script. Re-run `forge .`. | +| Test link fails with Clang and `-flto` | The pinned Forge emits GCC-only `-flto=N` for parallel Clang links, so the test targets in `build.c` deliberately disable LTO; production targets keep it. Keep test LTO disabled when running the suite with Clang. | +| `install` reports a permission error | The prefix is not writable. Pass one you own, e.g. `./make install "$HOME/.local"`. | +| A test fails with a leak report | A buffer or an array is not freed. Free every `sx_t` with `sx_free` and every returned array with `free`. | +| A consumer binary cannot find `libstringx.so` | Set `LD_LIBRARY_PATH` to `/lib`, link with `-Wl,-rpath,/lib`, or install to a standard prefix. | + +Do not include `` in the library sources or in applications: it is +Forge's build-script DSL header, not part of the String X API. Applications +include `` only. + +## Continuous integration + +The workflows that run these commands on every push and pull request — the +build matrix, the analyzer, the quality checks, CodeQL and merge protection — +are described in [Continuous integration](ci.md). + +--- + +[← Previous](design.md) · [Docs home](README.md) · [Next →](contributing.md) diff --git a/docs/en_us/ci.md b/docs/en_us/ci.md new file mode 100644 index 0000000..fbb8b01 --- /dev/null +++ b/docs/en_us/ci.md @@ -0,0 +1,140 @@ +English · [中文](../zh_cn/ci.md) + +[Docs home](README.md) › Continuous integration + +# Continuous integration + +Changes to `main`, pull requests and manual runs use GitHub Actions. This page +covers what each workflow verifies, how to reproduce the checks locally, and how +merge protection ties them together. For the commands themselves — Forge +bootstrap, `./make` targets, the test harness — see +[Build, test & package](build-and-test.md). + +## Triggers + +| Event | Workflows | +| --- | --- | +| `push` to `main` | [ci.yml](../../.github/workflows/ci.yml) and [codeql.yml](../../.github/workflows/codeql.yml) | +| `pull_request` on any branch | `ci.yml` and `codeql.yml` | +| `workflow_dispatch` (manual run) | `ci.yml` and `codeql.yml` | +| `schedule` | `codeql.yml` only (weekly) | + +The workflows have read-only repository access, except for the CodeQL job's +permission to publish code-scanning results. Pull-request code never runs via +`pull_request_target`, and checkout credentials are not persisted. + +## Checks + +| Check | What it verifies | +| --- | --- | +| Build and test (gcc-14 / clang-19) | A real build on Ubuntu 24.04 with GCC 14 and Clang 19, the complete test suite, ASan, UBSan and leak detection | +| Compiler warnings | Every production C translation unit compiles with `-Wall -Wextra -Werror` | +| GCC static analysis | `-fanalyzer` checks production translation units; diagnostics fail the job | +| Workflow and secret checks | Actionlint, ShellCheck, whitespace errors and Gitleaks over the complete Git history, with redacted output | +| CodeQL (C/C++) | Manual build tracing with `security-and-quality` queries, findings in the Security tab and on pull requests | +| CI | A stable required check that fails if any build, analyzer or quality job fails or is cancelled | + +GCC analysis uses `-O1 -fno-analyzer-state-merge`: GCC 14's default state +merging produces spurious allocation/cleanup diagnostics in this code. No +diagnostic categories are suppressed. An analyzer failure should be +investigated, not worked around with `continue-on-error`. + +All external Actions use immutable commit SHAs. Dependabot proposes weekly +GitHub Actions updates. The Actionlint and Gitleaks CLIs have pinned versions +and SHA-256 checksums in +[.github/scripts/install-tools.sh](../../.github/scripts/install-tools.sh); +update both values together when upgrading them. + +## CodeQL + +CodeQL is configured for C/C++ with manual build tracing and the +`security-and-quality` query set. It analyzes the code built by the pinned Forge +toolchain, publishes findings to the Security tab, and reports them on pull +requests. + +CodeQL also runs every Monday at 11:17 Asia/Shanghai (03:17 UTC). A successful +job status means the analysis completed; it does **not** mean there are no +alerts. Use a code-scanning merge rule to enforce alert severity — see +[Enable merge protection](#enable-merge-protection). + +## Enable merge protection + +Workflow files alone do not enable branch protection; these repository settings +are a one-time maintainer configuration. After the first successful run, create +a branch ruleset for `main`: + +1. Require pull requests and the `CI` and `CodeQL (C/C++)` status checks. +2. Require branches to be up to date before merging. +3. Add "Require code scanning results", select CodeQL, and block high/critical + security alerts and error-level quality alerts. Tighten these thresholds + after triaging existing findings. +4. Use the checked-in advanced CodeQL workflow rather than enabling a duplicate + default-setup scan. + +Changes to CI permissions, checks and dependency pins still deserve human +review. + +## Reproduce locally + +Install Linux build dependencies and a C23 compiler (GCC 14+ or Clang 19+). +Save local `build.conf` changes before running `configure.sh`: it updates the +compiler selection and appends `sanitize=1` in that file. + +```sh +CC=gcc bash .github/scripts/configure.sh # or CC=clang +CC=gcc bash .github/scripts/check-c.sh +CC=gcc bash .github/scripts/check-c.sh analyze +``` + +Use GCC for `analyze`. Runtime checks set: + +```sh +export ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 +export UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 +``` + +The build dependency is Forge commit +`b6826ba762a1e9e337895e01ee604b943c682d23`, checked out under `.ci-deps/forge` +in CI and bootstrapped without installing system files. PCRE2 comes from +Ubuntu's `libpcre2-dev` package. + +With a bootstrapped Forge checkout available locally: + +```sh +export PATH="/path/to/forge/build/output:$PATH" +export CPATH="/path/to/forge/build/output/include" +forge . +./make +./make test -j 2 +``` + +CI additionally installs into a temporary prefix, compiles and runs the existing +regex suite against the **installed shared library** using `pkg-config`, and +inspects the generated Debian package. This checks public headers, exported +symbols, package metadata and PCRE2 linkage in addition to source-level +behavior. The corresponding commands are in `ci.yml`; the layout they exercise +is documented in [Build, test & package](build-and-test.md). + +## Pinned Forge commit + +Both workflow files check out Forge commit +`b6826ba762a1e9e337895e01ee604b943c682d23` under `.ci-deps/forge` and bootstrap +it with `sh .ci-deps/forge/bootstrap.sh --no-test`, without installing system +files. Update this reviewed pin in **both** workflow files when changing Forge. +It is intentionally independent of Forge's moving `main` branch and is not +updated by Dependabot. + +## Review and failures + +Open the failed check for compiler diagnostics, sanitizer stack traces or +secret-scan locations. Build failures retain dependency and command metadata for +seven days; the Actions log contains the full build/test output. CodeQL alerts +include the affected lines and data flow where available. + +Automation covers mechanical regressions and many common memory-safety bugs. +Human review should concentrate on requirements, API contracts, ownership, +architecture and the findings reported by these tools. + +--- + +[← Previous](contributing.md) · [Docs home](README.md) diff --git a/docs/en_us/contributing.md b/docs/en_us/contributing.md new file mode 100644 index 0000000..837541b --- /dev/null +++ b/docs/en_us/contributing.md @@ -0,0 +1,149 @@ +English · [中文](../zh_cn/contributing.md) + +[Docs home](README.md) › Contributing + +# Contributing + +String X is a small C23 library with a tightly documented contract, so changes +are easiest to review when they stay small, keep the tests and the documentation +in step, and pass the same checks CI runs. This page describes the workflow and +the conventions the project expects. + +## Workflow + +1. Fork the repository and create a branch from `main`. Name the branch for the + change (`fix/split-end-guard`, `docs/build-targets`). +2. Make the change, including tests for behavior and updates to the English and + Chinese documentation. +3. Run the local checks before opening the pull request: + + ```sh + ./make test -j 2 + bash .github/scripts/check-c.sh + bash .github/scripts/check-c.sh analyze # GCC only + ``` + +4. Open a pull request against `main` and describe the behavior change, the + tests that cover it, and the documentation pages you updated. +5. Wait for the required checks. Merge protection on `main` requires the `CI` + and `CodeQL (C/C++)` status checks and up-to-date branches. The checks are + described in [Continuous integration](ci.md). +6. Address review comments with additional commits; keep the pull request + focused on one change. + +`bash .github/scripts/configure.sh` reproduces CI's compiler selection, but it +rewrites `compiler=`, `compiler_path=` and `sanitize=` in `build.conf`, so save +any local changes to that file first. + +## Contract-first documentation + +Behavior boundaries live in two places: + +- the comments in the public headers, `include/sx.h` and `include/sx_core.h`; +- the `Behavior boundaries` comment at the top of every `tests/*.c`, with its + `In scope (contract)` and `Out of contract (not exercised)` lists. + +A change to observable behavior must update all of them together: + +1. the header comment for every affected function; +2. the test implementation and its behavior-boundaries comment; +3. the English and Chinese pages under `docs/en_us/` and `docs/zh_cn/`. + +Do not leave a behavior undocumented or documented as it used to be. When +sources disagree, the tests win for run-time behavior, the headers win for +signatures, and `build.c` wins for build and packaging behavior — report a real +contradiction instead of silently picking one. + +## Code style + +- C23; the library and tests build with `-std=c23`. +- Two-space indentation; opening braces stay on the same line. +- Follow the existing naming and layering: core functions in `src/sx_core.c`, + the advanced regex layer in `src/sx_adv.c`, internal allocation in + `src/sx_raw.c`. Do not add public functions outside `sx.h`/`sx_core.h`. +- Use `size_t` for offsets and lengths, and the existing sentinel conventions + (`(size_t)-1`, a view with `ref == NULL`, a NULL array). +- Treat warnings as errors. The `./make check` target compiles the library + with `-Wall -Wextra -Wpedantic -Werror` and, on GCC, `-fanalyzer`; the + direct compile check in CI uses + `-std=c23 -O1 -Wall -Wextra -Werror`. Do not suppress a diagnostic to make + a build pass; fix the code or explain the analyzer finding in review. + +## Tests + +Every behavior change needs a test. Tests are self-contained programs under +`tests/` that compile the library sources directly and declare their +dependencies in the header DSL (`// Include`, `// Source`, `// Link`, +`// Library`, `// Option`). See +[Build, test & package](build-and-test.md) for the DSL and a complete example. + +When adding or changing a test: + +- keep the `Behavior boundaries` comment accurate — it is the written contract + the test enforces, including the `Out of contract (not exercised)` list; +- assert observable results (exact bytes, lengths, offsets and sentinels), not + only that a call returned non-NULL; +- free every buffer with `sx_free` and every returned array with `free`; the + suite runs under AddressSanitizer, UBSan and LeakSanitizer, and a leak or an + out-of-bounds access fails the test; +- keep the sanitizer flags and `-fno-omit-frame-pointer` in the test header so + the test runs the same way locally and in CI; +- if you change allocation or growth, run the exact-reserve configuration in + `tests/reserve_stress.c` (`-DSX_FORCE_EXACT_RESERVE`), which exposes + off-by-one accesses that slack capacity can hide. + +Run the suite with the same environment CI uses: + +```sh +export ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 +export UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 +./make test -j 2 +``` + +## Commits and pull requests + +- Keep one logical change per commit and a focused diff; avoid unrelated + reformatting and drive-by changes. +- Write a short imperative subject line, then a body that explains why the + change is needed and which behavior boundaries or documentation it touches. + Reference the issue when one exists. +- Include tests and both language versions of the documentation in the same + pull request as the code. +- Leave build artifacts out of the diff: `build/`, `test/`, `./make` and + `.ci-deps/` are generated and gitignored. +- A pull request is ready to merge when the required checks pass and review + comments are resolved. + +## Licensing and attribution + +- The library and the project sources are MIT licensed. New C source and header + files should start with `// SPDX-License-Identifier: MIT`, as `include/sx.h`, + `src/sx_adv.c` and `tests/reg.c` do; keep existing SPDX headers intact. +- The build script and the Forge-derived `src/export.h` are covered by Forge's + build-script exception, identified as + `GPL-3.0-or-later WITH LicenseRef-Forge-BuildScript-Exception`. `build.conf` + and `src/export.h` already carry that identifier and `build.c` is covered by + the same exception; do not relicense this build tooling as MIT or remove the + headers. +- The regex layer uses PCRE2 (BSD-3-Clause). Its attribution and license text + live in [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md). If you add a + third-party dependency, add its notice and license there as well. +- The project license is reproduced in [LICENSE](../../LICENSE). + +## Where things live + +| Path | Contents | +| --- | --- | +| [include/](../../include) | public headers: `sx.h` (advanced layer and `sx_split`) and the `sx_core.h` it includes | +| [src/](../../src) | implementation: `sx_core.c`, `sx_adv.c`, `sx_raw.c`, plus the internal `_sx.h` and `export.h` | +| [tests/](../../tests) | the self-contained test suite | +| [build.c](../../build.c), [build.conf](../../build.conf) | the Forge build script and its configuration | +| [.github/workflows/](../../.github/workflows) | the CI and CodeQL workflows | +| [.github/scripts/](../../.github/scripts) | compiler, analyzer and tooling checks used by CI | +| [docs/](../) | this documentation, in English and Simplified Chinese | +| [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md) | third-party licenses and attribution | +| [README.md](../../README.md) | the project overview and quick start | + +--- + +[← Previous](build-and-test.md) · [Docs home](README.md) · [Next →](ci.md) diff --git a/docs/en_us/design.md b/docs/en_us/design.md new file mode 100644 index 0000000..c189f80 --- /dev/null +++ b/docs/en_us/design.md @@ -0,0 +1,750 @@ +English · [中文](../zh_cn/design.md) + +[Docs home](README.md) › Design & internals + +# Design and internals + +This page is for contributors and for readers who need to reason about the +library's guarantees or port it. It describes the data layout, the +algorithms, the ownership model and the deliberate trade-offs behind the +public contracts in ``. The contracts themselves are documented in the +[API reference](api-buffer.md), [search reference](api-search.md) and +[regular expressions](regex.md) pages. + +## Goals and non-goals + +The design follows from a short set of goals: + +- **Byte-exact contract.** Every operation is defined on bytes and its + behavior boundaries are written down. Search, comparison and regex work + by length, so embedded NUL bytes are ordinary data. +- **Zero-copy access.** Slices are `sx_view_t` values that alias a buffer; + inspecting or iterating over subslices copies nothing. +- **One stable handle per buffer.** An `sx_t *` identifies the buffer for + its whole life; edits return `self`, so calls compose into chains even + when the backing array is reallocated. +- **Predictable failure.** A documented invalid input produces a fixed + sentinel instead of crashing; inputs outside the documented boundaries are + out of contract. There are no exceptions, error codes or global error + state. +- **Small surface.** One public header ``, one library, one optional + advanced dependency (PCRE2) that the library links itself. + +Equally deliberate non-goals: + +- **No text encoding layer.** The library does not decode UTF-8, normalize + text, or provide character/grapheme operations. Strings are bytes; the + regex layer runs PCRE2 in 8-bit non-UTF mode. +- **No locale awareness.** Comparison, trimming and character classes are + defined on bytes and fixed ASCII sets, independent of `LC_*`. +- **No thread-safe buffers.** A compiled regex is immutable and shareable; + a mutable buffer is plain memory and needs external synchronization. +- **No custom allocator hooks, ropes/streaming, or lazy views.** Every + buffer is one contiguous allocation. +- **No regex engine of its own.** Pattern semantics are PCRE2's; the + library supplies only the lifecycle, scanning and substitution plumbing. + +## Layers and headers + +### Header map + +| Header | Layer | Contents | Audience | +| --- | --- | --- | --- | +| `include/sx_core.h` | core | `sx_t`, `sx_view_t`, buffer/view/edit/search/compare prototypes | public, included by `` | +| `include/sx.h` | advanced | includes `sx_core.h`; declares `sx_split` and `sx_reg_*` | public entry point | +| `include/sx_raw.h` | internal | opaque `_sx` plus the raw allocation helpers | not supported | +| `src/_sx.h` | internal | definition of `struct _sx` | library only | +| `src/export.h` | Forge-derived | `SYMBOL_PUBLIC` visibility macro (checked in) | library only | + +Consumers include ``. `sx_core.h` is public because `` includes +it, but it is not a second entry point: `sx_split` and the regex layer are +only declared in `sx.h`. + +The implementation mirrors the header split: + +| Translation unit | Implements | +| --- | --- | +| `src/sx_core.c` | buffer, view, mutation, search, compare | +| `src/sx_raw.c` | allocation primitives (`sx__new`, `sx__reserve`, ...) | +| `src/sx_adv.c` | `sx_split` and the PCRE2 wrapper | + +All three library translation units use the private `_sx` layout directly; +only `sx.h` and `sx_core.h` are consumed by client code. + +### Why sx_split lives in the advanced layer + +`sx_split` is declared in `sx.h`, after the include of `sx_core.h`, and is +implemented in `src/sx_adv.c`. That placement is intentional: + +- It returns a `malloc`'ed array of views with the iterator convention used + by `sx_reg_match_all` and `sx_reg_split`: tokens in order, then an end + guard whose `.ref == NULL`, and the caller frees the array with `free()`. + Grouping the array-returning view APIs keeps that ownership convention in + one place instead of adding an array-allocating API to the core. +- `sx_split`'s scan is self-contained. The core's search primitive is a + `static` KMP implementation inside `sx_core.c`; the advanced layer cannot + call it and does not need to, because a split scan is bounded by the + output size anyway. The source comment states the trade directly: the + `O(n*m)` byte-exact scan "is fine for the advanced layer and keeps this TU + independent". +- The split scan is not PCRE2-dependent: it is a plain separator search. + It lives in the advanced TU by API shape, not by dependency. + +### Why sx_raw.h is internal + +`include/sx_raw.h` exposes the private allocation layer: + +```c +typedef struct _sx _sx; + +_sx *sx__new(size_t cap); +_sx *sx__dup(const _sx *src); +int sx__reserve(_sx *s, size_t need); +void sx__free(_sx *s); +``` + +It is internal for three reasons: + +- it hands out `_sx`, the private buffer struct, which `sx_core.h` only + forward-declares; +- its functions are named with a reserved double-underscore prefix and + bypass the public error model (`sx__reserve` returns `int`, not a + sentinel `sx_t *`) — they serve the library's own TUs, not clients; +- it carries no stability promise. The installed header set includes it + because Forge copies every `include/*.h` (the build script syncs the + whole directory), but it is not part of the supported public API and + must not be used by client code. The four `sx__*` helpers are declared + `SYMBOL_PUBLIC`, so they do appear in the shared library's dynamic symbol + table; that export does not make them supported API. + +## Buffer layout and invariants + +A public `sx_t` is a one-field handle pointing at a private `_sx`: + +```text +sx_t (public handle) _sx (private) ++------------+ +------------+ +| ref | -------------> | ptr | ----> one allocation of cap bytes ++------------+ | len | [ H e l l o \0 ? ? ... ] + | cap | + +------------+ + +content: bytes [0, len) terminator: ptr[len] == '\0' +capacity: bytes [0, cap) invariant: len + 1 <= cap, cap >= 1 +``` + +A view is a value, not an allocation: + +```text +sx_view_t v = { ref = h->ref, offset = 2, len = 3 } + +buffer: a b c d e f \0 view covers c d e + ^ ^ + v.offset v.offset + v.len +``` + +The invariants that every function preserves: + +1. `ptr != NULL` and `cap >= 1` for every live buffer. +2. `len + 1 <= cap`: there is always room for the terminator. +3. `ptr[len] == '\0'` at all times. Content bytes may themselves be + `'\0'`; the terminator is the first NUL *after* the content. +4. `len` counts content bytes, not the terminator. `sx_len` returns it as + `int` (see [integer accessors](#integer-accessors-and-size_max)). +5. A returned view satisfies `ref = buffer.ref` and + `offset + len <= buffer len`. The API does not validate caller-built + views; a view whose bounds exceed its buffer is out of contract. +6. The `sx_t *` handle address is stable for the buffer's life. `ptr` + returned by `sx_buf_mut` is **not** stable across growth: `realloc` can + move it. +7. Bytes in `[len, cap)` are unspecified: they may hold stale content or + never-initialized memory. Only `ptr[len]` is part of the contract. + +The invariants are enforced structurally: every mutating function ends with +`ptr[len] = '\0'`, and `sx__reserve` is the only place that changes `cap` +or `ptr`. `sx_buf_mut` lets a caller rewrite `[0, len)` without changing +`len`; the invariant still holds because the terminator is outside that +range. + +## Allocation and growth + +### Initial capacities + +Every buffer is one allocation from `sx__new(cap)`, which allocates the +`_sx` header and a `cap`-byte array (rounded up to 1 so `ptr[0]` has a +home). The constructors choose `cap` as follows: + +| Constructor | Initial `cap` | Maximum content bytes | +| --- | --- | --- | +| `sx_new()` | 32 | 31 | +| `sx_new_with_cap(n)` | `n`, or 1 when `n == 0` | `n - 1` (0 when `n <= 1`) | +| `sx_new_from_cstr(s)` | `strlen(s) + 1` | `strlen(s)` | +| `sx_new_from_view(v)` | `v.len + 1` | `v.len` | +| `sx_dup(src)` | `src->len + 1` | `src->len` | +| `sx_substr(h, idx, n)` | `n + 1` | `n` | + +`sx_new()` goes through `sx_new_with_cap(32)`; the 32-byte start keeps the +first few appends allocation-free without wasting much memory. The +construction-from-content constructors allocate exactly `content + 1`, so +a freshly built or copied buffer is tight. + +### Growth policy + +All growth goes through `sx__reserve(_sx *s, size_t need)`, which treats +`need` as the number of **content bytes** the caller must be able to hold +afterwards. Internally it must produce `cap > need`, i.e. room for `need` +bytes plus the terminator. The decision: + +| Situation | New `cap` | +| --- | --- | +| `cap > need` | unchanged (no-op) | +| `need == SIZE_MAX` | rejected (integer overflow guard) | +| default, `cap < 0x10000` | `max(cap * 2, need + 1)` | +| default, `cap >= 0x10000` | `max(cap + 0x10000, need + 1)` | +| `-DSX_FORCE_EXACT_RESERVE` | `need + 1` | + +The default policy is geometric doubling while the allocation is below +64 KiB, then a fixed `+0x10000` step. Doubling gives amortized constant +cost per appended byte; the fixed step avoids doubling a large allocation +(say 8 MiB to 16 MiB) just to append a few bytes. The `max` with +`need + 1` covers the case where a single call needs more than the next +geometric step would provide. + +The public `sx_reserve(self, n)` forwards `n` unchanged, so it guarantees +`cap >= n + 1`: after the call the buffer can hold `n` content bytes in +total without another reallocation. `sx_append`, `sx_write` and `sx_insert` call +`sx__reserve(final_content_length)` before copying: + +- append: `need = len + appended`; +- write: `need = idx + written`; `len` afterwards is `max(len, idx + n)`; +- insert: `need = len + inserted`; the tail is shifted with `memmove`. + +Growth is monotonic. Shrinking operations never reallocate: +`sx_truncate` only reserves when the new length is larger, `sx_erase` +moves bytes inside the existing allocation, and `sx_clear` only rewrites +`ptr[0]`. The exact-reserve test asserts both properties +(`tests/reserve_stress.c`). + +### SX_FORCE_EXACT_RESERVE + +`-DSX_FORCE_EXACT_RESERVE` replaces the policy with `cap = need + 1` for +every growth. The allocation then ends exactly at the terminator, so any +access past `len` lands in the AddressSanitizer redzone immediately +instead of hiding behind slack capacity. The costs are a reallocation per +growth (a per-byte append workload becomes quadratic-ish in copies) and no +slack, so it is a debugging/testing mode, not a production mode. +`tests/reserve_stress.c` is the dedicated configuration: it starts every +buffer at `cap == 1`, drives 1500 pseudo-random edits from a fixed LCG +against a byte-exact model, and asserts `cap == len + 1` after every +reallocation plus "shrinking never reallocates". + +## Views and aliasing + +Views are the library's core abstraction: `sx_view_t` stores a buffer +reference plus an `(offset, len)` window. Returning a view never copies, +never allocates and never modifies the buffer. The same representation is +used for whole-buffer views (`sx_view`), navigation (`sx_view_advance`, +`sx_view_range`, ...), split tokens and regex match arrays. + +The rules a caller must respect: + +- **Views are snapshots.** An edit does not adjust captured views. If the + length changes, offsets and lengths captured earlier may no longer + describe the same bytes; re-derive the view afterwards. +- **Growth invalidates raw pointers.** `sx_buf_mut` and `sx_buf_view_mut` + borrow the array; a later edit that grows the buffer may `realloc` it. + The `sx_t *` handle is stable, the pointer is not. +- **A view must not outlive its buffer.** The `ref` is a raw `_sx *`; + freeing the buffer frees the referent. Returning an array of views does + not transfer ownership of the underlying buffer. +- **Do not edit while views are in use.** This is the same rule for + `sx_split` tokens, `sx_reg_match_all` arrays and user-held views. +- **A `NULL` view means "none".** `{ref = NULL, offset = 0, len = 0}` is + the sentinel; library-returned views otherwise point into a live buffer. + +Aliasing edits are the delicate part. When the source view refers to the +same buffer as the destination, `sx_append_view`, `sx_write_view` and +`sx_insert_view` copy with `memmove` instead of `memcpy`. For append and +write the copy is a plain overlap-safe move, so any contract-valid source +view works. `sx_insert_view` is narrower, and its order of operations is +why: + +1. reserve space for the **final** content length (this is what keeps the + source pointer valid: `realloc` updates `_sx.ptr` in place, so a pointer + taken afterwards sees the new allocation); +2. shift the tail right by `v.len`, writing `[idx + n, len + n)`; +3. write the inserted bytes at `idx` with `memmove`. + +The tail shift makes self-aliasing conditional: a source window that starts +at or before the insertion point (`v.offset <= idx`) ends at or before +`idx + n`, so the shift never overwrites it and the `memmove` at step 3 +handles the remaining overlap. The exercised case is `v.offset == idx`: +inserting the view `[2, 4)` (`"cd"`) into `"abcdef"` at index 2 gives +`"abcdcdef"`. A self-aliased window that starts **after** `idx` is +overwritten by the shift before it is read: inserting the view `[3, 5)` +(`"de"`) into `"abcdef"` at index 2 yields `"abdccdef"`, not +`"abdecdef"`; such a call is out of contract. The regression at the end of +`tests/reserve_stress.c` exercises the `v.offset == idx` case with growth +forced, which pins the reserve-before-pointer ordering. The owned variants +(`sx_append(self, self)` and friends) do not have this protection — they +free their argument and are out of contract for self-aliasing. + +## Ownership and error model + +Ownership is deliberately explicit and small: whoever receives an owning +pointer releases it. + +| Operation | Ownership | +| --- | --- | +| `sx_new*`, `sx_dup`, `sx_substr`, `sx_reg_replace*` | returns caller-owned `sx_t *`; release with `sx_free` | +| `sx_append`, `sx_write`, `sx_insert` (the `owned` argument) | consume the argument: the library frees it | +| `sx_split`, `sx_find_all*`, `sx_reg_match_all`, `sx_reg_split` | return `malloc`'ed arrays; release with `free` | +| match views, tokens, whole-buffer views | borrow; nothing to release | + +Details that matter: + +- **Consuming calls consume on failure too.** `sx_append`/`sx_write`/ + `sx_insert` attempt the edit, then free `owned` unconditionally. If the + edit itself fails (allocation failure), the call returns `NULL` and the + argument has still been consumed. A `NULL` argument returns `NULL` + without freeing anything. +- **Handle identity.** Every edit returns `self`, so successful edits chain: + `sx_append_cstr(sx_append_cstr(s, "a"), "b") == s`. The handle is stable + across growth; only the backing array moves. +- **Arrays do not own their elements' buffer.** Freeing the array returned + by `sx_split` or `sx_reg_match_all` is not freeing the subject; the + views simply become unreachable. + +The error model is sentinel-based, with no `errno`, no error object and no +error return code: + +| Situation | Sentinel | +| --- | --- | +| offset search (`sx_find*`, `sx_rfind*`) | `(size_t)-1` | +| "no occurrences" (`sx_find_all*`) | `NULL` array | +| "no match" view (`sx_reg_match`) | `{ref = NULL, offset = 0, len = 0}` | +| "no match" array (`sx_reg_match_all`) | `NULL` | +| invalid/empty separator, invalid regex, OOM in an array/string factory | `NULL` | +| boolean predicates and `sx_reg_is_match` | `0` | + +Two consequences are intentional and documented: + +- **"No result" and "out of memory" can be indistinguishable.** The + `find_all` family and the `sx_reg_*` array family return `NULL` for both, + because the contract gives them no third channel. The regex replace family + does distinguish them: "no match" returns an unchanged copy, `NULL` means + invalid input or failure. +- **NULL handle arguments are mostly out of contract.** Only the families + that explicitly check — `sx_new_from_cstr`, `sx_dup`, the cstr/owned + mutation arguments, `sx_find*`, `sx_rfind*`, `sx_find_all*`, the + `sx_cmp*`/`sx_starts_with*`/`sx_ends_with*` group, `sx_split` and the + `sx_reg_*` calls — have defined `NULL` behavior. Accessors + (`sx_len`, `sx_cap`, `sx_buf_mut`, `sx_view`, ...), view movers and + `sx_free` dereference their handle and do not accept `NULL`. The public + headers state the boundaries per function. + +Errors never leave a partially built buffer behind: a failed growth happens +before any byte is copied, so `self` keeps its previous content and the +single-NUL invariant. The one visible exception is the consumed `owned` +argument described above. + +## Search internals + +The whole search family is built on one `static` primitive in +`src/sx_core.c`: + +```c +static inline find_ret_t find(const sx_t *h, const char *needle, int len, + size_t boundary, int opt); +``` + +The return type is a position or a pointer to a result array, so the +implementation picks an integer type wide enough to round-trip a pointer: + +```c +#if SIZE_MAX > UINTPTR_MAX +typedef size_t find_ret_t; +#else +typedef uintptr_t find_ret_t; +#endif +``` + +### Region model + +`opt` selects the direction and the result shape: + +- bit 0: `1` = right search, `0` = left search; +- bit 1: `1` = first result (scalar), `0` = all results (array). + +The searched region is computed from the caller's boundary: + +```text +left search (sx_find*): region = [boundary, H) +right search (sx_rfind*): region = [0, min(boundary, H)) + +H = content length of h +a match window [p, p+m) counts only if p >= region_start and p+m <= region_end +``` + +The wrappers plug in the documented boundaries: `sx_find*` use +`boundary = 0`; `sx_rfind*` use `boundary = len(h)` with the right flag; +`sx_find_view_b` and `sx_rfind_view_b` pass the caller's boundary. +`len <= 0`, an empty region, or a region shorter than the needle is +reported as "not found" in the shape the mode requires — `(size_t)-1` for +the scalar wrappers, a count-0 array internally (converted to `NULL` by +`sx_find_all*`) for the array wrappers. + +`len` is the needle's content length (`sx_t` needle), `v.len` (view +needle), or `(int)strlen(s)` (cstr needle — note the narrowing cast, which +is one of the practical `int` limits). The needle bytes are read directly +from the view or buffer; the search is byte-exact, like `memcmp`. + +### One-byte needles: memchr and memrchr + +For `m == 1` the primitive uses the C library's vectorized scans: + +- **leftmost:** `memchr(t + l, c, er - l)`; +- **rightmost:** `memrchr(t, c, er)` on glibc. `memrchr` is a GNU + extension, not ISO C, so it is declared by hand in `sx_core.c` and used + only when `__GLIBC__` is defined and `SX_FORCE_NO_MEMRCHR` is not. The + fallback is a byte-wise backward loop that keeps the last (rightmost) + hit before reaching `l`. + +The rightmost fast path is allowed to search from `0` because a right +search always sets `l = 0`; `er` already carries the caller's boundary. +`SX_FORCE_NO_MEMRCHR` exists to build and test the portable path on glibc +systems. + +For `m == 1` in "all" mode, the implementation repeatedly calls `memchr` +starting at the previous hit + 1. That reports **overlapping** positions, +which is exactly what `sx_find_all*` promises (`"aa"` in `"aaaa"` reports +0, 1 and 2). + +### Longer needles: KMP + +For `m >= 2` the primitive computes a KMP prefix table (`pi`, one +`malloc(m * sizeof(size_t))`) and scans the region in `O(n + m)` time: + +- **leftmost-first and all mode** use forward KMP over + `[l, er)`. On a full match the first mode returns immediately; the all + mode records the start offset and resumes with `q = pi[m - 1]`, which is + what makes it report overlapping occurrences. +- **rightmost-first** uses reverse KMP: the same prefix table computed over + the *reversed* needle by index mapping (no copy of the needle), scanning + the text from `er - 1` down to `l`. When the matched suffix length + reaches `m`, the current text index is the window start. + +The all-mode result array starts at capacity 16 and doubles with an +overflow guard (`cap > SIZE_MAX / 2 / sizeof(*r)` aborts with `NULL`), then +shrinks once with `realloc` before returning. Its layout is +`{count, pos0, pos1, ...}`: `arr[0]` is the count, not a position. + +### Complexity + +| Case | Technique | Time | Extra memory | +| --- | --- | --- | --- | +| one-byte needle, first left | `memchr` | `O(n)` | none | +| one-byte needle, first right | `memrchr`, or backward scan | `O(n)` | none | +| needle length >= 2, first | KMP | `O(n + m)` | `O(m)` prefix table | +| `sx_find_all*`, one byte | repeated `memchr` | `O(n)` scan | `O(k)` result | +| `sx_find_all*`, longer needle | KMP | `O(n + m)` scan | `O(m) + O(k)` result | +| `sx_split` | two passes of `is_sep` | `O(H * m)` worst case | `O(tokens)` result | + +`n` is the region length, `m` the needle length and `k` the number of +matches. The array wrappers allocate the result only; `sx_find*` / +`sx_rfind*` return a scalar and allocate nothing (except the KMP table, +which is freed before returning). + +## Regex wrapper internals + +The advanced regex layer is intentionally thin. Its whole state is one +compiled PCRE2 code object: + +```c +typedef struct sx_reg_t { + pcre2_code *code; +} sx_reg_t; +``` + +### Compile and release + +`sx_reg_compile` calls PCRE2 with fixed arguments: +`pcre2_compile(pattern, PCRE2_ZERO_TERMINATED, 0, ...)`. The `0` is the +option word — no `CASELESS`, no `UTF`, nothing — and +`PCRE2_ZERO_TERMINATED` means the pattern is a C string. The PCRE2 error +code and error offset are captured only to satisfy the signature and are +discarded, which is why every compile failure collapses to `NULL`. +Compilation allocates the PCRE2 code object and the small `sx_reg_t` +wrapper; `sx_reg_free` frees both and accepts `NULL`. + +### Per-call match data and the scan rule + +PCRE2 separates the compiled pattern from per-call match data. The wrapper +creates match data per call with +`pcre2_match_data_create_from_pattern(r->code, NULL)` and frees it before +returning. That is what makes a compiled handle thread-shareable: no match +state lives in the handle. + +A single match step is `pcre2_match(code, subject, len, offset, 0, md, +NULL)`. Note the subject is passed with an explicit **length**, not as a C +string, and the last argument (match context) is `NULL`, so PCRE2's default +match limits apply. A negative return (no match, or a PCRE2 match-time +error such as a match limit) is treated as "no further match"; the wrapper +does not expose match-time error codes. + +The scan shared by `sx_reg_match_all` and `sx_reg_split` advances with: + +```c +static size_t reg_next_at(size_t start, size_t end) { + return end > start ? end : start + 1; +} +``` + +The next search starts at the match end, or one byte past the start for a +zero-length match, so the scan is guaranteed to advance. `pcre2_match` is +called with `offset` on every step; when `offset` passes the subject length +PCRE2 returns an error and the loop ends. This is why `a*` on `"bbb"` +reports empty matches at offsets 0, 1, 2 and 3, and why `$` on `"abc"` +reports a single empty match at offset 3. + +### Two-pass sizing for match_all and split + +Both array families run the scan twice: + +```text +pass 1: count matches -> cnt +malloc((cnt + 1) * sizeof view) -> exact size, no realloc +pass 2: repeat the same scan -> fill views, then arr[cnt] = {0} guard +``` + +The scan is deterministic (same pattern, same subject, same start offsets), +so both passes observe identical positions. `sx_reg_split` additionally +tracks the gap start `seg`: each token is `[seg, match_start)` and `seg` +moves to `match_end`; the final token is `[seg, len)`. This gives exactly +`matches + 1` tokens, including the empty edge tokens and the empty tokens +produced by adjacent or zero-length matches. + +### Substitution: two pcre2_substitute calls + +Replace is built from PCRE2's substitution routine, with two fixed flags: + +```c +options |= PCRE2_SUBSTITUTE_UNSET_EMPTY | PCRE2_SUBSTITUTE_UNKNOWN_UNSET; +``` + +`UNSET_EMPTY` makes a group that did not participate expand to nothing; +`UNKNOWN_UNSET` makes a group number that does not exist expand to nothing +instead of failing the whole substitution. `sx_reg_replace` adds +`PCRE2_SUBSTITUTE_GLOBAL`; `sx_reg_replace_first` does not. + +Because the output length is not known before substituting, the wrapper +calls `pcre2_substitute` twice: + +```text +call 1: output buffer NULL, PCRE2_SUBSTITUTE_OVERFLOW_LENGTH, &needed + -> PCRE2_ERROR_NOMEMORY, `needed` = required size including NUL +malloc(needed) (single temporary) +call 2: fill the buffer, &used = needed + -> rc >= 0, `used` = bytes written excluding NUL +sx_new_with_cap(used + 1) (new public buffer) +memcpy(ptr, buf, used); len = used; ptr[used] = '\0' +``` + +The temporary buffer is freed after the copy. A first call that does not +return `PCRE2_ERROR_NOMEMORY` means the template/replacement pair was +rejected; the wrapper returns `NULL` and never touches the subject. With no +match, PCRE2 substitutes nothing and the output is an unchanged copy of the +subject — a normal success, not an error. + +### Allocation summary + +| Call | Result allocations | Notes | +| --- | --- | --- | +| `sx_reg_compile` | PCRE2 code object + `sx_reg_t` | one-time cost | +| `sx_reg_free` | none | frees the two compile allocations | +| `sx_reg_is_match` | per-call match data | no result allocation | +| `sx_reg_match` | per-call match data | result is a view value | +| `sx_reg_match_all` | match data + exact `(cnt + 1)` array | two scan passes | +| `sx_reg_split` | match data + exact `(matches + 2)` array | two scan passes | +| `sx_reg_replace*` | PCRE2-internal match data + temporary buffer + `sx_t` | two substitute calls | + +The wrapper does not enable PCRE2 JIT (`pcre2_jit_compile` is never called) +and exposes no compile or match options. Pattern-level features such as +inline options still work because they are part of the pattern, not the +wrapper's policy. + +## Concurrency + +- **Compiled regex handles are immutable and shareable.** All per-call + state lives in caller-owned match data created inside the call; the + wrapper has no global variables. One `sx_reg_t *` may serve concurrent + calls from several threads. +- **Buffers are not synchronized.** They are ordinary heap memory. Two + threads reading the same buffer concurrently are fine as long as nobody + mutates it; a mutation needs external synchronization. Views make this + stricter: a view read concurrently with a length-changing edit is a data + race (out of contract). +- **Ownership must be coordinated.** A buffer with a single owner must not + be consumed by two threads; arrays are single-owner results. + +The library itself never mutates global state, so it is safe to use from +multi-threaded programs as long as each buffer's access is synchronized by +the caller. + +## Portability and limits + +### memrchr and SX_FORCE_NO_MEMRCHR + +The only non-ISO C API in the search path is `memrchr`, a glibc extension. +`sx_core.c` declares it manually rather than relying on a feature-test +macro, and compiles it in only when `__GLIBC__` is defined and the build +does not define `SX_FORCE_NO_MEMRCHR`. On other platforms (and with the +forced switch) the rightmost one-byte search falls back to a portable +single-byte backward loop. The in-tree test suite runs the default glibc +path; the switch exists so the fallback can be built and checked on glibc +as well. + +### Integer accessors and SIZE_MAX + +The public accessors return `int` while offsets and needles use `size_t`: + +| Function | Return type | +| --- | --- | +| `sx_len`, `sx_len_view` | `int` (content byte count) | +| `sx_cap` | `int` (total allocation) | +| offsets (`sx_find*`, view fields, regex views) | `size_t` | + +A buffer with more than `INT_MAX` content bytes is outside the tested +contract. This is a deliberate API simplification (the intended use case is +small-to-medium strings), not a bug; the practical ceiling is about 2 GiB +per buffer on common platforms. The same `int` narrowing appears where a +`strlen`-based needle length is cast to `int` in the search wrappers. + +`SIZE_MAX` guards appear where a size arithmetic could wrap: + +- `sx__reserve` rejects `need == SIZE_MAX` (it would not be able to add + the terminator); +- the `sx_find_all*` array growth checks `cap > SIZE_MAX / 2 / sizeof(*r)` + before doubling; +- there is no general overflow checking: extreme `n` or `off` arguments can + wrap unsigned size arithmetic, and such calls are outside the tested + contract. + +### Platform assumptions + +- The library is C23. The reference toolchains are GCC 14+ and Clang 19+ + on Linux (CI uses Ubuntu 24.04 with GCC 14 and Clang 19); the sources + avoid compiler-specific extensions apart from `SYMBOL_PUBLIC` and the + glibc `memrchr` fast path. +- `src/export.h` is a checked-in, Forge-derived header. It defines + `SYMBOL_PUBLIC` as `__attribute__((visibility("default")))` for + GCC/Clang and as `_declspec(dllexport)` for MSVC; the build uses hidden + default visibility, so exactly the `SYMBOL_PUBLIC` functions are exported + from `libstringx.so`. +- The regex layer needs PCRE2 10.46 (`pcre2-8`), 8-bit, non-UTF mode. The + build links it into `libstringx`, so consumers do not add PCRE2 flags, + but PCRE2 is a runtime dependency of the shared library. +- Install and Debian packaging targets are guarded by the `LINUX` macro in + `build.c`; the library itself compiles as ordinary C23. + +## Testing strategy + +Every file in `tests/` is a self-contained program. Its header comments +declare how to build it (`// Include`, `// Source`, `// Option`, `// Link`, +`// Library` lines consumed by the pinned Forge build system), and document +its **behavior boundaries**: an "In scope (contract)" list and an +"Out of contract (not exercised)" list. The header is part of the +contract: when behavior changes, the boundary lists change with it (see +[Contributing](contributing.md)). + +The suite (20 tests) maps one topic per file: + +| Test | Pins | +| --- | --- | +| `access.c` | `sx_len` / `sx_cap` / buffer accessors / whole-buffer view | +| `append.c` | append family, ownership transfer, aliased appends | +| `chain.c` | edit chaining, handle identity, zero-leak ownership | +| `cmp.c` | lexicographic byte comparison | +| `ends_with.c` | suffix predicate | +| `find.c` | leftmost search, bounded regions, `strlen` needles | +| `find_all.c` | all occurrences, overlapping positions included | +| `insert.c` | insertion, aliasing across growth | +| `new.c` | constructors, `sx_dup`, capacity edge cases | +| `reg.c` | regex families, binary-safe subjects, zero-length handling | +| `reserve.c` | `sx_reserve` monotonicity and no-shrink rules | +| `reserve_stress.c` | exact-reserve model-based stress (1500 random edits) | +| `rfind.c` | rightmost search and bounded regions | +| `shrink.c` | truncate / erase / clear edge cases | +| `split.c` | split shape, end guard, zero-copy tokens | +| `starts_with.c` | prefix predicate | +| `substr.c` | copy-out independence in both directions | +| `view_move.c` | advance / retreat / shift / range clamping | +| `view_trim.c` | whitespace trim set and empty-view clamp | +| `write.c` | overwrite, append-at-end and padding semantics | + +How the tests run: + +- Each test compiles the library **sources directly**, with the per-test + options from its header. Sanitizers are on: AddressSanitizer, UBSan and + (on Linux, through ASan) LeakSanitizer, so the leak sanitizer is the + witness for every ownership rule. CI sets + `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1` and + `UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1`. +- `tests/reserve_stress.c` is the only test built with + `-DSX_FORCE_EXACT_RESERVE`. It drives a deterministic LCG through append, + insert, erase, write, truncate and aliased-view edits against a byte-exact + model, and includes the aliased `insert_view` growth regression. +- CI additionally installs the built library into a temporary prefix, + links `tests/reg.c` against the **installed shared library** through + `pkg-config` (with an rpath), and runs it. That verifies the public + headers, exported symbols and the PCRE2 link in addition to source-level + behavior; it then inspects the generated Debian package. +- Fault-injection is absent, so allocation-failure branches are not + exercised by the suite (the reserve test comments note that such a test is + not expressible without fault injection). The documented OOM sentinels + are reasoned from the code, not observed in tests. +- The `./make check` target compiles production code with + `-Wall -Wextra -Wpedantic -Werror`; GCC builds also run `-fanalyzer` + (with `-O1 -fno-analyzer-state-merge` in CI), and CodeQL scans with + `security-and-quality` queries. +- Tests disable LTO (`set(TARGET_LTO, 1, DISABLE)` in `build.c`) because the + pinned Forge emits GCC-only `-flto=N` flags for parallel Clang links. + Production library targets keep LTO. + +## Design trade-offs + +| Choice | Benefit | Cost | +| --- | --- | --- | +| Single NUL-terminated allocation | cheap `cstr` interop, one `free`, contiguous content | one byte overhead; cstr variants truncate at embedded NUL | +| `sx_t` handle to a private `_sx` | stable handle across growth; private layout | one indirection and per-buffer allocation of the header | +| `(ref, offset, len)` views | zero-copy slices; uniform for split and regex results | lifetime rules; stale views after edits; raw pointers invalidated by growth | +| Geometric growth | amortized constant append cost | slack capacity; peak memory above `len` | +| Exact-reserve debug mode | redzone-tight allocations expose off-by-one bugs | slow; test-only | +| `int` length accessors | compact, simple API | ~2 GiB practical buffer ceiling; narrowing casts | +| Sentinel error model | no global state, no error plumbing, deterministic | "no result" vs OOM can be ambiguous; no diagnostics | +| Caller-frees arrays, library-frees handles | explicit, predictable ownership | two release functions (`free` vs `sx_free`) to know | +| KMP + `memchr`/`memrchr` | guaranteed `O(n + m)` worst case, simple code, vectorized one-byte case | prefix table allocation for `m >= 2`; average-case speed below optimized substring search | +| Overlapping results from `sx_find_all*` | complete position set; useful for byte scanning | callers must expect overlapping offsets | +| Non-overlapping regex scan | standard PCRE2 behavior; forward progress guaranteed | cannot report overlapping regex matches | +| Two-pass exact sizing | one allocation, no realloc growth, deterministic | roughly twice the matching work for array APIs | +| Thin PCRE2 wrapper, no options/JIT | tiny surface, full PCRE2 semantics, one dependency | no wrapper-level flags or tuning; PCRE2 linked at runtime | +| Explicit immutability of compiled regex, no internal locks | shareable handles without synchronization | buffers still need caller synchronization | +| Build-time configuration macros | zero runtime cost for growth/memrchr policy | a policy change requires a rebuild | + +These are trade-offs, not accidents. The tests pin the observable +consequences, and the header comments name the out-of-contract side of each +rule. + +## Licensing + +Project sources are MIT licensed (see [LICENSE](../../LICENSE) and the SPDX +headers in the sources). The Forge-derived build tooling follows the +build-script exception: `build.conf` and `src/export.h` carry the +`GPL-3.0-or-later WITH LicenseRef-Forge-BuildScript-Exception` SPDX +identifier, and `build.c` is covered by the same exception; the library +sources themselves remain MIT. The regex layer uses PCRE2 (BSD-3-Clause); see +[THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md). + +--- + +[← Previous](regex.md) · [Docs home](README.md) · [Next →](build-and-test.md) diff --git a/docs/en_us/getting-started.md b/docs/en_us/getting-started.md new file mode 100644 index 0000000..1496df2 --- /dev/null +++ b/docs/en_us/getting-started.md @@ -0,0 +1,306 @@ +English · [中文](../zh_cn/getting-started.md) + +[Docs home](README.md) › Getting started + +# Getting started + +String X is a small C23 string library that treats one string as a single +NUL-terminated buffer and every slice of it as a zero-copy view. Buffers are +handled by byte length, so embedded NUL bytes are ordinary data and nothing is +lost to C-string truncation. The public surface is one header, ``, and +one library, `libstringx` (`-lstringx`); an optional advanced layer adds +regular expressions through PCRE2. This page takes you from a fresh checkout +to a running program. It describes **v0.5**. + +## Requirements + +| Requirement | Notes | +| --- | --- | +| Linux | Tested platform; the build and tests target Linux | +| C23 compiler | GCC 14+ or Clang 19+; CI runs GCC 14 and Clang 19 on Ubuntu 24.04 | +| `forge` | `https://github.com/minelogy-dev/forge`; compiles `build.c` into a local `./make` executable | +| `libpcre2-dev` | PCRE2 10.46, 8-bit API; needed to build; the library links `pcre2-8` | +| `pkg-config` | Recommended for consumers; the installed package ships `libstringx.pc` | + +## Build from source + +```sh +forge . # compile build.c into ./make (re-run whenever build.c changes) +./make # build -> build/output/libstringx.so +./make test # build and run every test under tests/ (ASan + UBSan + LSan) +``` + +`./make` also syncs the public headers to `build/output/include`. `./make test` +runs each `tests/*.c` file as a self-contained program under AddressSanitizer, +UBSan and LeakSanitizer; use `./make test -j 2` to run tests in parallel. +`build.conf` selects the compiler and is the single source of truth for the +version. + +## Install + +```sh +./make install # default prefix: /usr/local (may need sudo) +./make install "$HOME/.local" # user-owned prefix +``` + +The install target builds first, then copies the artifacts: + +| Path under `` | Contents | +| --- | --- | +| `lib/libstringx.so` | the shared library | +| `include/sx.h` | the public header, plus `sx_core.h` and `sx_raw.h` | +| `lib/pkgconfig/libstringx.pc` | pkg-config metadata | +| `share/doc/libstringx/` | `LICENSE`, `THIRD_PARTY_NOTICES.md`, `copyright` | + +### Consuming the installed library + +```sh +cc app.c $(pkg-config --cflags --libs libstringx) -o app +``` + +For a prefix that is not in the default search path, point pkg-config at the +installed metadata and, for a non-system prefix, set the runtime library path: + +```sh +export PKG_CONFIG_PATH="$HOME/.local/lib/pkgconfig" +cc app.c $(pkg-config --cflags --libs libstringx) -o app +LD_LIBRARY_PATH="$HOME/.local/lib" ./app +``` + +Without pkg-config, the same build is: + +```sh +cc app.c -I/include -L/lib -lstringx -o app +``` + +You link only `-lstringx`: `libstringx` links `pcre2-8` itself, so no extra +library flags are needed. The shared library does need `libpcre2-8` present at +run time. + +### Debian package + +```sh +./make gen_deb +sudo apt install ./build/deb/libstringx_0.5_amd64.deb +``` + +`gen_deb` stages `build/deb/libstringx__.deb`; the version comes +from `build.conf` with the leading `v` stripped, and the architecture from +`uname -m` (`x86_64` becomes `amd64`, `aarch64` becomes `arm64`). The package +depends on `libc6` and `libpcre2-8-0`. + +## Hello, String X + +This is the quick-start program from the README. It copies a C string into an +owned buffer, finds the first comma, copies the text before it into a second +owned buffer, and prints that. Both buffers are released with `sx_free`. + +```c +#include +#include + +int main(void) { + sx_t *msg = sx_new_from_cstr("hello, world"); + size_t at = sx_find_cstr(msg, ", "); + sx_t *hi = sx_substr(msg, 0, at); + fwrite(sx_buf_mut(hi), 1, (size_t)sx_len(hi), stdout); + putchar('\n'); /* hello */ + sx_free(hi); + sx_free(msg); + return 0; +} +``` + +After installing as shown above, build and run it with: + +```sh +cc hello.c $(pkg-config --cflags --libs libstringx) -o hello +./hello +``` + +```text +hello +``` + +From the source tree, before installing, use the build output instead: + +```sh +cc hello.c -Ibuild/output/include -Lbuild/output -lstringx -o hello +LD_LIBRARY_PATH=build/output ./hello +``` + +## Ten-minute tour + +Five things users do with the library, one small program each. Every example +is complete and can be compiled the same way as `hello.c` above. + +### Create a buffer + +`sx_new` returns an empty buffer, `sx_new_from_cstr` copies a C string, and +`sx_dup` makes an independent deep copy. All results are caller-owned. + +```c +#include +#include + +int main(void) { + sx_t *empty = sx_new(); /* len 0 */ + sx_t *hello = sx_new_from_cstr("hello"); + sx_t *copy = sx_dup(hello); + printf("empty: len=%d cap=%d\n", sx_len(empty), sx_cap(empty)); + printf("hello: len=%d [%s]\n", sx_len(hello), sx_buf_mut(hello)); + printf("copy: len=%d [%s]\n", sx_len(copy), sx_buf_mut(copy)); + sx_free(empty); + sx_free(hello); + sx_free(copy); + return 0; +} +``` + +```text +empty: len=0 cap=32 +hello: len=5 [hello] +copy: len=5 [hello] +``` + +### Append and insert + +Every edit returns the buffer it was given, so edits chain and the handle +stays the same even when the backing array grows. + +```c +#include +#include + +int main(void) { + sx_t *s = sx_new_from_cstr("abc"); + s = sx_append_cstr(s, "def"); /* "abcdef" */ + s = sx_insert_cstr(s, 3, "-"); /* "abc-def" */ + s = sx_write_cstr(s, 0, "A"); /* "Abc-def" */ + printf("%s (len %d)\n", sx_buf_mut(s), sx_len(s)); + sx_free(s); + return 0; +} +``` + +```text +Abc-def (len 7) +``` + +### Find + +`sx_find*` returns the leftmost byte offset, `sx_rfind*` the rightmost; the +not-found sentinel is `(size_t)-1`. + +```c +#include +#include + +int main(void) { + sx_t *s = sx_new_from_cstr("one two one"); + size_t first = sx_find_cstr(s, "one"); + size_t last = sx_rfind_cstr(s, "one"); + printf("first=%zu last=%zu\n", first, last); + if (sx_find_cstr(s, "three") == (size_t)-1) + printf("three: not found\n"); + if (sx_starts_with_cstr(s, "one")) + printf("starts with one\n"); + sx_free(s); + return 0; +} +``` + +```text +first=0 last=8 +three: not found +starts with one +``` + +### Views and split + +A view is `{ref, offset, len}` and aliases the buffer without copying. +`sx_split` returns an array of such views, terminated by an end guard whose +`ref` is `NULL`; the array is freed with `free`. + +```c +#include +#include +#include + +int main(void) { + sx_t *csv = sx_new_from_cstr("id,name,email"); + sx_view_t head = sx_view_advance(sx_view(csv), 0); + head.len = 2; /* "id" - a view, no copy */ + printf("head: %.*s\n", sx_len_view(head), sx_buf_view_mut(head)); + + sx_view_t *fields = sx_split(csv, ","); + for (size_t i = 0; fields[i].ref != NULL; i++) + printf("field %zu: %.*s\n", i, (int)fields[i].len, + sx_buf_view_mut(fields[i])); + free(fields); /* the array, not the views */ + sx_free(csv); + return 0; +} +``` + +```text +head: id +field 0: id +field 1: name +field 2: email +``` + +### Regex + +The advanced layer wraps PCRE2. Compile a pattern once, run it against any +number of buffers, then free it. `sx_reg_replace` returns a new buffer and +never modifies its subject. + +```c +#include +#include + +int main(void) { + sx_reg_t *re = sx_reg_compile("(\\w+)@(\\w+\\.\\w+)"); + if (!re) + return 1; + sx_t *msg = sx_new_from_cstr("bob@example.com, alice@example.org"); + if (sx_reg_is_match(re, msg)) { + sx_view_t m = sx_reg_match(re, msg); + printf("first match: %.*s\n", (int)m.len, sx_buf_view_mut(m)); + } + sx_t *out = sx_reg_replace(re, msg, "$1 at $2"); + printf("replaced: %s\n", sx_buf_mut(out)); + sx_free(out); + sx_free(msg); + sx_reg_free(re); + return 0; +} +``` + +```text +first match: bob@example.com +replaced: bob at example.com, alice at example.org +``` + +Patterns are C strings and are matched in PCRE2's 8-bit non-UTF mode, so `\w` +and friends are ASCII. Subjects are matched by byte length and may contain any +byte, including NUL. + +## Documentation map + +| Document | What it covers | +| --- | --- | +| [Documentation home](README.md) | Language chooser and the full document index | +| [User guide](guide.md) | Mental model, ownership, binary safety, recipes, pitfalls | +| [API reference: buffers & views](api-buffer.md) | Creation, capacity, accessors, mutation, views | +| [API reference: search, compare & split](api-search.md) | `sx_find*`, `sx_rfind*`, `sx_cmp*`, `sx_split` | +| [Regular expressions](regex.md) | The `sx_reg_*` match, replace and split families | +| [Design & internals](design.md) | Data layout, growth policy, algorithms, limits | +| [Build, test & package](build-and-test.md) | Forge targets, test harness, installation | +| [Contributing](contributing.md) | Workflow, style, tests, licensing | +| [Continuous integration](ci.md) | Workflows, required checks, CodeQL | + +--- + +[Docs home](README.md) · [Next →](guide.md) diff --git a/docs/en_us/guide.md b/docs/en_us/guide.md new file mode 100644 index 0000000..930a19f --- /dev/null +++ b/docs/en_us/guide.md @@ -0,0 +1,462 @@ +English · [中文](../zh_cn/guide.md) + +[Docs home](README.md) › User guide + +# User guide + +This guide is for C programmers who can already build and link String X (see +[Getting started](getting-started.md)) and want the mental model plus working +recipes. Signatures and per-function details live in the API reference; this +page is about how the pieces fit together and which calls are out of contract. + +## Mental model + +### The buffer + +Every string is one `sx_t` handle pointing at one backing allocation: + +```text +sx_t* ──► _sx { ptr: [ h e l l o \0 . . . . ] , len: 5, cap: 32 } +``` + +- `ptr[0 .. len-1]` are content bytes; `ptr[len]` is always `'\0'`. +- `len` is a byte count, never a character count, and it does not stop at an + embedded NUL. +- `cap` is the allocation size in bytes and always satisfies `cap >= len + 1`. +- `sx_new()` starts with capacity 32; `sx_new_with_cap(n)` has exactly capacity + `n` for `n >= 1`, so it can hold at most `n - 1` content bytes (`n == 0` + still allocates one byte). + +The handle is stable: growth may move the backing array, never the `sx_t`. +Treat the handle as opaque, and do not copy the struct by value. + +### Views + +A view aliases a slice of a buffer without copying: + +```text +sx_view_t { ref: the same _sx, offset: 1, len: 3 } ──► "ell" +``` + +- `ref == NULL` means "no view": the sentinel for a failed match or for "none". +- Creating or moving a view allocates nothing, so a view is never freed. +- A view is a snapshot of `(offset, len)`: later edits never adjust it, and a + length change invalidates it. + +## Ownership + +Exactly one place owns a buffer at a time. The table says what each call +returns and how to release it. + +| Call | Result | Release with | +| --- | --- | --- | +| `sx_new`, `sx_new_from_cstr`, `sx_new_from_view`, `sx_new_with_cap`, `sx_dup` | new buffer | `sx_free` | +| `sx_substr` | new buffer | `sx_free` | +| `sx_reg_replace`, `sx_reg_replace_first` | new buffer | `sx_free` | +| `sx_append`, `sx_write`, `sx_insert` (the `sx_t *owned` forms) | `self`; the argument is consumed and freed | `sx_free` on `self` | +| `sx_find_all*`, `sx_split`, `sx_reg_match_all`, `sx_reg_split` | malloc'ed array | `free` | +| `sx_view`, `sx_view_*`, `sx_reg_match`, tokens inside the arrays above | view | nothing | +| `sx_reg_compile` | compiled pattern | `sx_reg_free` | + +Two consequences matter in practice: + +- Edits return `self`, so they chain: `sx_append_cstr(sx_append_cstr(s, "a"), + "b")` returns `s` itself, and the number of `sx_free` calls equals the number + of buffers created, not the number of edits. +- A consuming call ends the source's life. After `sx_append(s, part)`, `part` + must not be used or freed again: its content was copied into `s`, and even on + allocation failure the source is released. + +`sx_append_cstr`, `sx_append_view`, `sx_write_cstr`, `sx_write_view`, +`sx_insert_cstr` and `sx_insert_view` take a C string or a view and never +consume a buffer. + +## Binary safety and the cstr variants + +String X is binary-safe wherever an explicit length is carried: + +| Input form | Length rule | Embedded NUL | +| --- | --- | --- | +| `sx_*_cstr`, `sx_new_from_cstr`, `sx_split` separator, regex pattern | `strlen` | ends the input | +| `sx_view_t` forms, `sx_new_from_view`, owned `sx_t *` forms | explicit `len` | ordinary byte | +| regex subject (`sx_t *h`) | byte length of `h` | ordinary byte | + +So `sx_append_cstr` stops at a NUL, while `sx_append_view`, `sx_append` and +`sx_new_from_view` copy every content byte. To print a binary buffer, use the +length: `fwrite(sx_buf_mut(h), 1, (size_t)sx_len(h), stdout)` rather than +`printf("%s", ...)`. + +The same split applies to compare and search: the `_cstr` forms use `strlen`, +while the owned and view forms compare content bytes. Regular expressions match +subjects by byte length, but their patterns are C strings, so a pattern cannot +contain a literal NUL. + +## Invariants and stale pointers + +- After every public call, `ptr[len] == '\0'`, `cap >= len + 1`, and `len` + counts content bytes. Only a length-changing call moves those values. +- Any edit that grows the buffer may `realloc` the backing array. Every `char *` + obtained from `sx_buf_mut` or `sx_buf_view_mut` before that call is then + stale; re-fetch it after the edit. The `sx_t *` handle stays valid. +- Writes through `sx_buf_mut` must stay inside `[0, len)` unless a matching + length-changing call follows; `ptr[len]` is the terminator, not a spare byte. +- Views are snapshots. Do not edit a buffer while views into it (or arrays of + tokens from `sx_split` / `sx_reg_*`) are alive, and re-derive views after a + length change even when no reallocation happened. +- Accessors return `int` (`sx_len`, `sx_len_view`, `sx_cap`) while offsets are + `size_t`. Buffers with more than `INT_MAX` content bytes are outside the + tested contract. +- Capacity only grows: `sx_truncate`, `sx_erase` and `sx_clear` free no + capacity. + +## Errors and sentinels + +There are no exceptions and no error codes. Each family has a sentinel: + +| Situation | Result | +| --- | --- | +| `sx_find*` / `sx_rfind*`: no match | `(size_t)-1` | +| `sx_find_all*`: no match, empty needle, or allocation failure | `NULL` array | +| `sx_split`: NULL handle or separator, empty separator, allocation failure | `NULL` array | +| `sx_reg_match`: no match | view with `ref == NULL` | +| `sx_reg_match_all` / `sx_reg_split`: no match or allocation failure | `NULL` array | +| `sx_reg_replace*`: NULL argument or rejected template | `NULL` buffer | +| allocation failure | `NULL` | + +`NULL` means "no result"; for the array-returning calls, allocation failure is +indistinguishable from "no match". The documented NULL-argument handling is +narrow: + +- `sx_new_from_cstr(NULL)` and `sx_dup(NULL)` return `NULL`. +- The C-string and owned-buffer arguments of append/write/insert return `NULL` + and leave `self` unchanged. +- `sx_cmp*`, `sx_starts_with*` and `sx_ends_with*` return `0`. +- `sx_find*` / `sx_rfind*` return `(size_t)-1`; `sx_find_all*` return `NULL`. +- `sx_split` returns `NULL` for a NULL handle, NULL separator or empty + separator. +- `sx_reg_compile(NULL)` returns `NULL`; `sx_reg_free(NULL)` is a no-op; the + match, replace and split families return their not-found value for NULL + arguments. + +Everything else does not accept a NULL handle. `sx_len`, `sx_cap`, +`sx_buf_mut`, `sx_view`, `sx_free`, `sx_substr`, `sx_reserve`, `sx_erase` and +the rest dereference the handle; passing NULL is out of contract and may crash. +In particular, `sx_free(NULL)` is not a no-op, and a view with `ref == NULL` +cannot be passed to the view functions. + +## Recipes + +Each recipe is a complete C23 program. Build one with the command used for +`hello.c` in [Getting started](getting-started.md), or with: + +```sh +cc recipe.c $(pkg-config --cflags --libs libstringx) -o recipe +``` + +### Build a string from pieces + +Mix C strings, views and owned buffers; the owned buffer is consumed. + +```c +#include +#include + +int main(void) { + sx_t *path = sx_new(); + path = sx_append_cstr(path, "/usr"); + path = sx_append_cstr(path, "/local"); + sx_t *part = sx_new_from_cstr("/bin"); + path = sx_append(path, part); /* part is consumed */ + path = sx_insert_cstr(path, 0, "/opt:"); /* prefix */ + printf("%s (%d bytes)\n", sx_buf_mut(path), sx_len(path)); + sx_free(path); + return 0; +} +``` + +```text +/opt:/usr/local/bin (19 bytes) +``` + +### Search and extract a substring + +Check the `(size_t)-1` sentinel before using an offset. `sx_substr` copies, so +its result is independent of the source, and `sx_find_view_b` restricts the +search to a region starting at a boundary. + +```c +#include +#include + +int main(void) { + sx_t *line = sx_new_from_cstr("key=value;flag=on"); + size_t eq = sx_find_cstr(line, "="); + size_t semi = sx_find_cstr(line, ";"); + sx_t *nod = sx_new_from_cstr("="); + size_t later = sx_find_view_b(line, sx_view(nod), 10); /* region [10, 17) */ + + if (eq == (size_t)-1 || semi == (size_t)-1) + return 1; + sx_t *key = sx_substr(line, 0, eq); + sx_t *value = sx_substr(line, eq + 1, semi - eq - 1); + printf("first '='=%zu, next '=' from 10=%zu\n", eq, later); + printf("key=%s value=%s\n", sx_buf_mut(key), sx_buf_mut(value)); + sx_free(key); + sx_free(value); + sx_free(nod); + sx_free(line); + return 0; +} +``` + +```text +first '='=3, next '=' from 10=14 +key=key value=value +``` + +### Split and iterate + +`sx_split` returns a malloc'ed array of views terminated by an end guard whose +`ref` is `NULL`; empty fields are kept. Free the array with `free`, and keep the +buffer alive while you read the tokens. + +```c +#include +#include +#include + +int main(void) { + sx_t *csv = sx_new_from_cstr("id,,name,"); + sx_view_t *fields = sx_split(csv, ","); + if (!fields) + return 1; + for (size_t i = 0; fields[i].ref != NULL; i++) + printf("[%zu] \"%.*s\" (offset %zu, len %zu)\n", i, + (int)fields[i].len, sx_buf_view_mut(fields[i]), + fields[i].offset, fields[i].len); + free(fields); + sx_free(csv); + return 0; +} +``` + +```text +[0] "id" (offset 0, len 2) +[1] "" (offset 3, len 0) +[2] "name" (offset 4, len 4) +[3] "" (offset 9, len 0) +``` + +### Trim input + +`sx_view_trim` drops the ASCII whitespace set `{space, \t, \v, \f, \r, \n}` from +both edges without copying. Copy the trimmed view into an owned buffer when the +buffer may change later. + +```c +#include +#include + +int main(void) { + sx_t *raw = sx_new_from_cstr(" \t hello world \r\n"); + sx_view_t trimmed = sx_view_trim(sx_view(raw)); + printf("[%.*s]\n", sx_len_view(trimmed), sx_buf_view_mut(trimmed)); + + sx_t *copy = sx_new_from_view(trimmed); /* independent copy */ + printf("[%s] len=%d\n", sx_buf_mut(copy), sx_len(copy)); + sx_free(copy); + sx_free(raw); + return 0; +} +``` + +```text +[hello world] +[hello world] len=11 +``` + +A view that consists only of whitespace trims to an empty view at its slot's +end; for the whole-buffer view that is `(offset = len(h), len = 0)`. + +### In-place edits + +`sx_write` overwrites without shrinking, `sx_erase` removes a range, and +`sx_insert` shifts the tail. All of them return `self`. + +```c +#include +#include + +int main(void) { + sx_t *s = sx_new_from_cstr("the quick brown fox"); + s = sx_write_cstr(s, 10, "green"); /* same length: overwrite */ + s = sx_erase(s, 0, 4); /* remove "the " */ + s = sx_insert_cstr(s, 0, "red "); /* prepend */ + s = sx_truncate(s, (size_t)sx_len(s) - 4); /* drop " fox" */ + printf("%s (len %d)\n", sx_buf_mut(s), sx_len(s)); + s = sx_clear(s); /* len 0, capacity kept */ + printf("after clear: len=%d cap=%d\n", sx_len(s), sx_cap(s)); + sx_free(s); + return 0; +} +``` + +```text +red quick green (len 15) +after clear: len=0 cap=20 +``` + +`sx_erase` with `idx + n > len` is a no-op that returns `self`, as is `n == 0`. +`sx_insert` requires `0 <= idx <= len`; `idx > len` is out of contract. Growing +`sx_truncate` and out-of-range `sx_write` leave the gap bytes unspecified. + +### Regex extract, replace and split + +Compile once, reuse, free last. Match and token results are views into the +subject; replace returns a new buffer and never modifies the subject. + +```c +#include +#include +#include + +int main(void) { + sx_reg_t *re = sx_reg_compile("[a-z]+@[a-z.]+"); + if (!re) + return 1; + sx_t *msg = sx_new_from_cstr("bob@example.com;alice@example.org"); + + sx_view_t m = sx_reg_match(re, msg); /* leftmost match */ + if (m.ref != NULL) + printf("first: %.*s\n", (int)m.len, sx_buf_view_mut(m)); + + sx_view_t *hits = sx_reg_match_all(re, msg); /* non-overlapping */ + for (size_t i = 0; hits && hits[i].ref != NULL; i++) + printf("hit %zu: %.*s\n", i, (int)hits[i].len, sx_buf_view_mut(hits[i])); + free(hits); + + sx_t *out = sx_reg_replace(re, msg, "<$0>"); /* $0 = whole match */ + printf("replaced: %s\n", sx_buf_mut(out)); + sx_free(out); + + sx_view_t *tokens = sx_reg_split(re, msg); /* gaps between matches */ + for (size_t i = 0; tokens && tokens[i].ref != NULL; i++) + printf("token %zu: \"%.*s\"\n", i, (int)tokens[i].len, + sx_buf_view_mut(tokens[i])); + free(tokens); + + sx_free(msg); + sx_reg_free(re); + return 0; +} +``` + +```text +first: bob@example.com +hit 0: bob@example.com +hit 1: alice@example.org +replaced: ; +token 0: "" +token 1: ";" +token 2: "" +``` + +## Pitfalls + +These are the calls and habits the tests deliberately put out of contract, plus +documented edge cases that are easy to miss: + +- Using a buffer after handing it to a consuming call: `sx_append(s, part)`, + `sx_write(s, idx, part)` and `sx_insert(s, idx, part)` free `part`. +- Passing a buffer to itself through the owned forms: `sx_append(s, s)`, + `sx_write(s, idx, s)`, `sx_insert(s, idx, s)`. To double a buffer in place, + use `sx_append_view(s, sx_view(s))` and `sx_write_view`; they accept a view + into `s`. `sx_insert_view` also accepts one when the slice starts at or + before `idx` (the tested case); a self-aliased slice that starts after `idx` + is overwritten by the tail shift — copy it first. +- `sx_insert*` with `idx > len`: the tail shift underflows. The tested contract + is `0 <= idx <= len`. `sx_write*` is different: it pads and extends. +- Reading the unspecified bytes in `[old_len, n)` after a growing + `sx_truncate`, or in `[len, idx)` after `sx_write` beyond the end. Write over + the gap before reading it. +- Editing a buffer while views or arrays from `sx_split`, `sx_reg_match_all`, + `sx_reg_split` or `sx_find_all*` are alive, or keeping a view past a length + change. Views are not adjusted and may point into freed memory after growth. +- Interpreting a `sx_find_all*` array beyond `arr[0] + 1` entries; its shape is + `{count, positions...}`. +- Treating `sx_erase` with `idx + n > len` as an error. It is a documented no-op + that returns `self`. +- Passing NULL handles to functions that do not check for them (see + [Errors and sentinels](#errors-and-sentinels)). `sx_free(NULL)` and + `sx_len(NULL)` are out of contract. +- Forgetting the release call: `sx_free` for buffers, `free` for view arrays, + `sx_reg_free` for compiled patterns. A view needs no release. +- `sx_split` with an empty separator returns `NULL`; it does not split on every + byte. +- A regex pattern is a C string and cannot contain a literal NUL. Subjects can. +- `sx_new_from_cstr` and every `_cstr` parameter stop at the first NUL; use + views for binary content. +- `sx_substr` requires `idx + n <= len(h)`; `sx_view_range` requires + `off <= len(backing buffer)` (its `len` is clamped to the buffer end, `off` is + not). Neither call clamps the precondition itself. +- Sharing one `sx_t` between threads without synchronization. The library has no + internal locking; a compiled `sx_reg_t` is the only object documented as + immutable and shareable. + +## Performance notes + +- **Reserve before a known append loop.** `sx_reserve(self, n)` guarantees + `cap >= n + 1` without shrinking, so a buffer can reach `n` content bytes + without reallocating. Without it, growth is still amortized: the allocation + doubles, or grows by `0x10000` once the capacity is at least 64 KiB. +- **Views do not copy.** `sx_view`, `sx_view_advance` and the other view movers + are O(1) and allocate nothing. Prefer them for read-only slicing; use + `sx_substr` or `sx_new_from_view` only when you need an independent buffer. +- **Search is linear.** One-byte needles use `memchr` / `memrchr`; longer + needles use forward or reverse KMP, O(n + m). `sx_find_all*` reports + overlapping matches and sizes its array to the match count. +- **Split and regex scans are two-pass.** The token or match array is counted + first and allocated exactly once; the cost is two scans of the subject. +- **Compile a regex once.** `sx_reg_compile` is the expensive call; every match, + replace and split reuses the compiled pattern and allocates only its own match + data. `sx_reg_is_match` is the cheapest existence check. +- **Capacity is never returned.** `sx_truncate`, `sx_erase` and `sx_clear` keep + the allocation, which makes a cleared buffer reusable but means a peak stays + allocated until `sx_free`. + +## FAQ + +**Do I need PCRE2 to use buffers?** To build the library, yes: the source tree +links `pcre2-8`, and `./make` needs `libpcre2-dev`. To use an installed +`libstringx`, link only `-lstringx`; the shared library carries its own PCRE2 +dependency. + +**Is every function NULL-safe?** No. Only the cases listed in +[Errors and sentinels](#errors-and-sentinels) are defined; NULL handles are out +of contract everywhere else. + +**Is String X UTF-8 aware?** No. It is a byte library: lengths, comparisons and +searches are byte-exact, and the regex layer runs in PCRE2's 8-bit non-UTF mode, +so `\d`, `\w`, `\s` and `\b` match ASCII only. + +**How do I copy a view?** `sx_new_from_view(v)` returns an owned buffer with a +byte-exact copy of the view's `len` bytes. + +**How do I get a substring?** `sx_view_range` and `sx_view_advance` give a +zero-copy view; `sx_substr(h, idx, n)` gives an owned copy. + +**Why does `sx_len` return `int`?** That is the library's practical size limit: +content longer than `INT_MAX` bytes is outside the tested contract. Offsets are +`size_t`, so search and view positions stay full-width. + +**Can I share a compiled regex between threads?** Yes: a compiled `sx_reg_t` is +immutable and each call uses its own match data. Sharing an `sx_t` buffer +between threads is not supported. + +**What does a zero-length match look like?** `sx_reg_match` returns a view with +`ref != NULL` and `len == 0`; `sx_reg_match_all` and `sx_reg_split` report it +and continue the scan one byte to the right. + +--- + +[← Previous](getting-started.md) · [Docs home](README.md) · [Next →](api-buffer.md) diff --git a/docs/en_us/regex.md b/docs/en_us/regex.md new file mode 100644 index 0000000..b90a36d --- /dev/null +++ b/docs/en_us/regex.md @@ -0,0 +1,561 @@ +English · [中文](../zh_cn/regex.md) + +[Docs home](README.md) › Regular expressions + +# Regular expressions + +## Overview + +`` adds one advanced layer on top of the core buffer API: a thin, +fixed-configuration wrapper around the **PCRE2 8-bit library** (`pcre2-8`, +version 10.46). It exposes a compile/free pair and three families — match, +replace and split — and deliberately adds no policy of its own: everything +this page does not state is PCRE2's default behavior. + +The layer is designed around one lifecycle: + +1. compile a pattern into an opaque `sx_reg_t *` handle; +2. run any number of calls against any number of `sx_t` subjects; +3. release the handle once with `sx_reg_free`. + +A compiled handle is immutable and may be shared across threads; every call +uses its own match data. Subjects are matched by **byte length**, so an +embedded NUL is ordinary data (binary safe); patterns and replacement +templates are C strings and cannot contain a literal NUL. + +The layer is part of `libstringx`, which links `pcre2-8` itself: consumers +link `-lstringx` and pass no PCRE2 flags. PCRE2 is BSD-3-Clause; attribution +lives in [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md). For the +`$n` substitution rules see [Substitution templates](#substitution-templates); +for a task-oriented tour see the [user guide](guide.md). + +The families at a glance: + +| Family | Functions | Result | +| --- | --- | --- | +| Compile / release | `sx_reg_compile`, `sx_reg_free` | handle | +| Match | `sx_reg_is_match`, `sx_reg_match`, `sx_reg_match_all` | 0/1, one view, or an array | +| Replace | `sx_reg_replace`, `sx_reg_replace_first` | new `sx_t` | +| Split | `sx_reg_split` | array of views | + +## Lifecycle + +Compile the pattern once, before the loop that uses it, and keep the handle. +The pattern string itself is not retained, so it can be freed right after +compilation. When the handle is no longer needed, release it with +`sx_reg_free`. + +```c +#include +#include +#include + +static void show(const char *label, sx_view_t v) { + printf("%s: ", label); + if (v.ref == NULL) { + printf("\n"); + return; + } + fwrite(sx_buf_view_mut(v), 1, v.len, stdout); + putchar('\n'); +} + +int main(void) { + sx_t *h = sx_new_from_cstr("bob@example.com and alice@example.org"); + sx_reg_t *re = sx_reg_compile("(\\w+)@(\\w+\\.\\w+)"); + if (!h || !re) + return 1; + + printf("is_match: %d\n", sx_reg_is_match(re, h)); + show("first", sx_reg_match(re, h)); + + sx_view_t *all = sx_reg_match_all(re, h); + for (int i = 0; all && all[i].ref != NULL; i++) + printf("match %d: %zu bytes at offset %zu\n", i, all[i].len, + all[i].offset); + free(all); + + sx_t *out = sx_reg_replace(re, h, "[$2: $1]"); + if (out) { + printf("replaced: "); + fwrite(sx_buf_mut(out), 1, (size_t)sx_len(out), stdout); + putchar('\n'); + sx_free(out); + } + + sx_view_t *tok = sx_reg_split(re, h); + for (int i = 0; tok && tok[i].ref != NULL; i++) + printf("token %d: %zu bytes\n", i, tok[i].len); + free(tok); + + sx_reg_free(re); + sx_free(h); + return 0; +} +``` + +The three points that make the API safe to use in long-lived code are: + +- the handle is independent of the subjects: one compiled pattern serves any + number of buffers; +- results that alias a subject are views, so they stay valid only while that + subject lives and keeps its length; +- arrays returned by `sx_reg_match_all` and `sx_reg_split` are + caller-owned: release them with `free()`, not `sx_free`. + +### sx_reg_compile + +```c +sx_reg_t *sx_reg_compile(const char *pattern); +``` + +Compiles a pattern with PCRE2 and returns an opaque handle. + +| Parameter | Meaning | +| --- | --- | +| `pattern` | NUL-terminated PCRE2 pattern; not retained by the handle | + +Returns a new handle, or `NULL` when `pattern` is `NULL`, the pattern is +syntactically invalid, or allocation fails. The wrapper exposes no PCRE2 +error code or error offset, so these cases cannot be told apart: validate a +pattern during development and treat `NULL` as "do not use this handle". + +Notes: + +- The pattern string may be freed or modified immediately after the call. +- No compile options are passed to PCRE2. PCRE2 features selected inside the + pattern itself (an inline option such as `(?i)`) still apply. +- Compilation is the expensive step of the layer relative to a single match + call, so compile once and reuse the handle ([performance](#performance)). + +```c +sx_reg_t *re = sx_reg_compile("(\\w+)@(\\w+)"); /* NULL on bad input */ +/* re == NULL means: NULL pattern, invalid syntax, or out of memory */ +/* ... run match / replace / split calls ... */ +sx_reg_free(re); /* release the handle after its last use */ +``` + +### sx_reg_free + +```c +void sx_reg_free(sx_reg_t *r); +``` + +Releases a compiled handle. `NULL` is accepted and is a no-op. + +Notes: + +- Free a handle exactly once, after the last call that uses it. +- Data returned by earlier calls does not depend on the handle: match views + alias the subject, and arrays are caller-owned. +- Using a freed handle again is out of contract. + +```c +sx_reg_free(re); /* release the handle after its last use */ +``` + +## Match family + +All three calls scan the subject's content bytes from the left and follow +PCRE2's **leftmost-first** semantics: the match that starts earliest wins, +and among alternatives that start at the same byte PCRE2's preference order +decides. A zero-length match is a real match. Views alias the subject: no +bytes are copied and `h` is never modified. + +### sx_reg_is_match + +```c +int sx_reg_is_match(const sx_reg_t *r, const sx_t *h); +``` + +Answers "does the pattern match anywhere in `h`?". + +| Parameter | Meaning | +| --- | --- | +| `r` | compiled pattern | +| `h` | subject buffer | + +Returns `1` if some match exists anywhere in `h`, otherwise `0` — including +when `r` or `h` is `NULL`, or when an internal allocation fails. A +zero-length match counts as a match, so `a*` matches an empty subject. + +Notes: + +- The cheapest existence test: one PCRE2 match call and no result + allocation. Each call still creates and frees its own small PCRE2 + match-data block. +- The subject is searched by byte length; anchors refer to byte offsets. + +```c +sx_reg_t *re = sx_reg_compile("a*"); +sx_t *empty = sx_new(); +int yes = sx_reg_is_match(re, empty); /* 1: a zero-length match counts */ +sx_free(empty); +sx_reg_free(re); +``` + +### sx_reg_match + +```c +sx_view_t sx_reg_match(const sx_reg_t *r, const sx_t *h); +``` + +Returns the leftmost match as a view into `h`. + +| Parameter | Meaning | +| --- | --- | +| `r` | compiled pattern | +| `h` | subject buffer | + +On success the result is a view into `h`'s buffer: `.ref` points at the +subject, and `.offset` / `.len` select the matched bytes. No match, a `NULL` +argument, or allocation failure returns the null view +`{ref = NULL, offset = 0, len = 0}`. A zero-length match is still a match: +`.ref != NULL` with `.len == 0`. + +Notes: + +- Leftmost match, not "the longest match": alternatives prefer PCRE2's + order, so `b|bc` against `abc` matches `b` at offset 1. +- One PCRE2 match call; the view is not a copy. +- Anchors follow PCRE2's defaults: `^` matches at the subject start + (offset 0) and `$` at the subject end; by default `$` also matches before + a final newline. +- Using the view after `h` is freed, or after an edit changes `h`'s length, + is out of contract. + +```c +sx_reg_t *re = sx_reg_compile("bc"); +sx_t *h = sx_new_from_cstr("abc"); +sx_view_t v = sx_reg_match(re, h); /* v.offset == 1, v.len == 2 ("bc") */ +sx_free(h); +sx_reg_free(re); +``` + +### sx_reg_match_all + +```c +sx_view_t *sx_reg_match_all(const sx_reg_t *r, const sx_t *h); +``` + +Collects every match in one left-to-right pass. + +| Parameter | Meaning | +| --- | --- | +| `r` | compiled pattern | +| `h` | subject buffer | + +Returns a `malloc`'ed array of views with the same shape as `sx_split`: +`arr[0 .. count-1]` are the matches and `arr[count].ref == NULL` is the end +guard. Release the array with `free()`; the views alias `h` and stay valid +while `h` lives and keeps its length. + +Returns `NULL` when there is no match at all, when `r` or `h` is `NULL`, or +when allocation fails. These three cases are not distinguishable by this +API. + +Notes: + +- Matches do not overlap: after each match the scan resumes at the match end, + or one byte further right for a zero-length match + ([the scan rule](#the-scan-rule)). +- Counting and filling are two passes over the same deterministic scan, so + the array is allocated exactly once at its final size. +- `sx_find_all*` reports overlapping positions instead; `sx_reg_match_all` + reports regex matches, which cannot overlap. + +```c +sx_reg_t *re = sx_reg_compile("a*"); +sx_t *h = sx_new_from_cstr("bbb"); +sx_view_t *arr = sx_reg_match_all(re, h); +int n = 0; +while (arr[n].ref != NULL) + n++; /* n == 4: zero-length matches at offsets 0, 1, 2 and 3 */ +free(arr); +sx_free(h); +sx_reg_free(re); +``` + +## The scan rule + +`sx_reg_match_all` and `sx_reg_split` share one scan: + +- matches are taken left to right and never overlap; +- after a match the next search starts at the match's end; +- after a zero-length match the next search starts **one byte to the right** + of the match start, so a pattern that can match empty cannot stall the + scan; +- a match may end exactly at `len(h)` (for example `$`); the scan then + stops because PCRE2 rejects a start offset beyond the subject. + +| Pattern | Subject | Reported matches (offset, length) | +| --- | --- | --- | +| `aa\|aaa` | `aaaa` | (0,2), (2,2) — `aaa` never gets a chance | +| `a*` | `bbb` | (0,0), (1,0), (2,0), (3,0) | +| `$` | `abc` | (3,0) | +| `bc` | `abcb` | (1,2) | + +The same rule determines the token count of `sx_reg_split`: it is always +`number_of_matches + 1`. + +## Replace family + +Both replace calls substitute a C-string template into the match(es) and +return a **new** caller-owned `sx_t`; `h` is never modified. Free the result +with `sx_free`, like any other buffer. + +### sx_reg_replace + +```c +sx_t *sx_reg_replace(const sx_reg_t *r, const sx_t *h, const char *repl); +``` + +Replaces every match in `h` with `repl`. + +| Parameter | Meaning | +| --- | --- | +| `r` | compiled pattern | +| `h` | subject buffer; never modified | +| `repl` | NUL-terminated substitution template; not retained | + +Returns a new buffer, or `NULL` when `r`, `h` or `repl` is `NULL`, PCRE2 +rejects the template, or allocation fails. With valid arguments and no match +the result is an **unchanged copy** of `h`, never `NULL`. + +Notes: + +- The template expands `$0` / `$n`; see + [Substitution templates](#substitution-templates). +- Zero-length matches are substituted too: `a*` against `bbb` with the + template `-` yields `-b-b-b-`. +- An empty template deletes every match, so a pattern that matches the whole + subject produces an empty buffer. +- Byte-exact: embedded NULs in `h` are ordinary matching data and are copied + into the result. + +```c +sx_reg_t *re = sx_reg_compile("(\\w+) (\\w+)"); +sx_t *h = sx_new_from_cstr("hello world"); +sx_t *swapped = sx_reg_replace(re, h, "$2 $1"); /* "world hello" */ +sx_free(swapped); +sx_free(h); +sx_reg_free(re); +``` + +### sx_reg_replace_first + +```c +sx_t *sx_reg_replace_first(const sx_reg_t *r, const sx_t *h, + const char *repl); +``` + +Same contract as `sx_reg_replace`, except that only the **leftmost** match is +substituted; every other byte is copied unchanged. + +```c +sx_reg_t *re = sx_reg_compile("x"); +sx_t *h = sx_new_from_cstr("xax"); +sx_t *out = sx_reg_replace_first(re, h, "<$0>"); /* "ax" */ +sx_free(out); +sx_free(h); +sx_reg_free(re); +``` + +## Substitution templates + +Both replace calls interpret `repl` with PCRE2's substitution syntax, with +two options fixed by the wrapper that make missing captures harmless. + +| Template element | Expands to | +| --- | --- | +| `$0` | the whole match | +| `$n` (`n >= 1`) | capture group `n`, or the empty string if the group took no part or does not exist | +| any other text | copied; PCRE2's substitution syntax still defines how to write `$` and `\` literally | + +| Pattern | Subject | Template | Result | +| --- | --- | --- | --- | +| `(\w+) (\w+)` | `hello world` | `$2 $1` | `world hello` | +| `(a)(b)` | `ab` | `$1$3` | `a` | +| `a(b)?` | `a` | `[$1]` | `[]` | +| `abc` | `abc` | (empty template) | (empty buffer) | + +Notes: + +- The wrapper passes PCRE2's `PCRE2_SUBSTITUTE_UNSET_EMPTY` and + `PCRE2_SUBSTITUTE_UNKNOWN_UNSET`: a group that did not participate, and a + group number that does not exist, both expand to the empty string. A + template is therefore never rejected just because a capture is missing. +- `$n` refers to capture groups of each match as it is substituted; group 0 + is the whole match. +- `repl` is a C string, so a literal NUL cannot appear in it. Matched NUL + bytes still reach the result through `$0` / `$n`. +- The full substitution syntax is PCRE2's; see the + [PCRE2 documentation](https://www.pcre.org/). + +## Split family + +### sx_reg_split + +```c +sx_view_t *sx_reg_split(const sx_reg_t *r, const sx_t *h); +``` + +Splits `h` into the gaps between non-overlapping matches. + +| Parameter | Meaning | +| --- | --- | +| `r` | compiled pattern | +| `h` | subject buffer | + +Returns a `malloc`'ed array with exactly the `sx_split` shape: +`arr[0 .. count-1]` are the tokens in order, `arr[count].ref == NULL` is the +end guard, and `count == number_of_matches + 1`. Empty tokens are kept at +every edge and in the interior. The caller frees the array with `free()`; the +tokens are views into `h`. + +Returns `NULL` for a `NULL` argument or allocation failure. No match is not +an error: the array then contains the whole subject as its single token. + +Notes: + +- Zero-length matches split at every position: `a*` against `bbb` gives + `""`, `"b"`, `"b"`, `"b"`, `""` — five tokens. +- A match that covers the whole subject yields two empty tokens. +- Leading and trailing matches yield empty edge tokens; interior empty tokens + come from adjacent matches. +- Do not edit `h` while the tokens are in use (views are snapshots; see the + [user guide](guide.md)). + +```c +sx_reg_t *re = sx_reg_compile("[0-9]+"); +sx_t *h = sx_new_from_cstr("a1b22c"); +sx_view_t *tok = sx_reg_split(re, h); +/* 3 tokens: "a" (0,1), "b" (2,1), "c" (5,1) — "22" is one match */ +free(tok); +sx_free(h); +sx_reg_free(re); +``` + +## Binary safety + +| Direction | Rule | +| --- | --- | +| Subject `h` | matched by byte length; embedded NUL and every byte value are ordinary data | +| Pattern | a C string: NUL-terminated, so no literal NUL inside the pattern | +| Template `repl` | a C string: no literal NUL; captures can inject NUL bytes into the result | + +- PCRE2 runs in **8-bit non-UTF mode**: `\d`, `\w`, `\s`, `\b` and friends + match ASCII only. Bytes that form a non-ASCII character (for example the + UTF-8 bytes `C2 A5`) never match `\d`. +- In 8-bit non-UTF mode, `.` matches any byte except newline, including an + embedded NUL: the pattern `A.B` matches the three bytes `A\0B`. +- Replace is binary-safe in both directions: `a\0b` with the pattern `b` and + template `B` produces `a\0B`; `.` with template `X` over the same subject + produces `XXX`. +- Because the pattern is a C string, a NUL byte in the subject can only be + described with a PCRE2 escape; see the + [PCRE2 documentation](https://www.pcre.org/). + +## Error sentinels + +No documented call crashes on invalid input, a missing match or allocation +failure; each family reports it with a fixed sentinel. + +| Call | No match | `NULL` argument / invalid input | Allocation failure | +| --- | --- | --- | --- | +| `sx_reg_compile` | — | `NULL` (also for a syntax error) | `NULL` | +| `sx_reg_free` | — | `NULL` is a no-op | — | +| `sx_reg_is_match` | `0` | `0` | `0` | +| `sx_reg_match` | null view `{ref = NULL}` | null view | null view | +| `sx_reg_match_all` | `NULL` | `NULL` | `NULL` | +| `sx_reg_replace` | unchanged copy | `NULL` | `NULL` | +| `sx_reg_replace_first` | unchanged copy | `NULL` | `NULL` | +| `sx_reg_split` | one-token array (the whole subject) | `NULL` | `NULL` | + +Notes: + +- For `sx_reg_match_all` and `sx_reg_split`, "no match" and allocation + failure both yield `NULL`; the array family cannot distinguish them. +- For the replace family, "no match" is a normal success: you get an + unchanged copy of `h`. +- Arrays are `malloc`'ed and released with `free()`; buffers returned by the + replace family are `sx_t *` and released with `sx_free()`. + +## Thread safety + +- A compiled `sx_reg_t` is immutable after `sx_reg_compile`. It has no + mutable state and the wrapper keeps no global state, so one handle can be + used by several threads at the same time. +- Each match/split call creates its own PCRE2 match-data block + (`pcre2_match_data_create_from_pattern`) and frees it before returning; the + replace calls delegate to `pcre2_substitute`, which also uses per-call + match data. Two threads never share match state. +- A subject buffer is plain memory with no locking: concurrent readers are + fine, but any mutation requires external synchronization. +- Views and arrays are snapshots into a subject. Do not edit the subject + while a thread is still reading views from it, and do not free a handle + while another thread is using it. + +## Performance + +| Call | PCRE2 work | Wrapper allocation | Result | +| --- | --- | --- | --- | +| `sx_reg_compile` | one compile | code plus handle | handle | +| `sx_reg_is_match` | one match call | match data only | `0` / `1` | +| `sx_reg_match` | one match call | match data only | one view | +| `sx_reg_match_all` | two passes over the scan | match data plus one exact-size array | array | +| `sx_reg_split` | two passes over the scan | match data plus one exact-size array | array | +| `sx_reg_replace*` | two substitute calls | internal PCRE2 match data, one temporary buffer, one `sx_t` | new buffer | + +Notes: + +- Compile once: pattern compilation costs far more than a single match, so + compiling inside a loop is the one avoidable performance mistake. +- `sx_reg_is_match` is the cheapest existence test; `sx_reg_match` adds only + the returned view. +- `sx_reg_match_all` and `sx_reg_split` scan twice (count, then fill) so the + result array is allocated exactly once and never grows by `realloc`. +- The replace family probes the exact output length with a first + `pcre2_substitute` call, then fills a fitting buffer with a second call; + the buffer is copied once into the returned `sx_t`. +- Every call allocates and frees match data; no match data is cached between + calls, and the wrapper does not enable PCRE2 JIT or any compile option. +- The subject is never copied; only the replace family allocates a result + buffer. + +## Choose the right call + +| Requirement | Call | Returns | Ownership | +| --- | --- | --- | --- | +| Does anything match? | `sx_reg_is_match` | `int` 0/1 | none | +| The leftmost match | `sx_reg_match` | view into `h` | none; view is a snapshot | +| Every match | `sx_reg_match_all` | `malloc` array plus end guard | caller: `free()` | +| Replace every match | `sx_reg_replace` | new `sx_t` | caller: `sx_free()` | +| Replace the first match only | `sx_reg_replace_first` | new `sx_t` | caller: `sx_free()` | +| Split into fields | `sx_reg_split` | `malloc` array plus end guard | caller: `free()` | + +## PCRE2 semantics + +The wrapper fixes a small, deliberately plain configuration: + +- **8-bit, non-UTF**: the pattern and subject are bytes, character classes + are ASCII, and no UTF validation happens. In the default (no `DOTALL`) + mode `.` does not match newline. +- **No option flags**: the wrapper passes no compile options and no match + options, and no match context. PCRE2 features that are expressed inside + the pattern, such as inline options, still work; case-insensitive + matching, multiline matching and similar behavior are requested with + PCRE2's in-pattern syntax. +- **PCRE2 defaults govern**: leftmost-first alternation, greedy/lazy + quantifiers, anchors, backreferences and all other pattern semantics are + PCRE2's, not the wrapper's. +- The wrapper does not expose PCRE2 error codes or compile error offsets. + +Pattern syntax and semantics are documented by the PCRE2 project at +[pcre.org](https://www.pcre.org/); this library does not re-document them. +The bundled PCRE2 version is 10.46; the dependency is BSD-3-Clause, with +attribution in [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md). + +--- + +[← Previous](api-search.md) · [Docs home](README.md) · [Next →](design.md) diff --git a/docs/zh_cn/README.md b/docs/zh_cn/README.md new file mode 100644 index 0000000..01b4332 --- /dev/null +++ b/docs/zh_cn/README.md @@ -0,0 +1,61 @@ +# String X 文档(简体中文) + +**版本 v0.5** · [English](../en_us/README.md) · +[项目仓库](https://github.com/minelogy-dev/StringX) + +String X 是一个轻量的 C 字符串库,核心思路只有一个:每个字符串都是一段 +以单个 NUL 结尾的缓冲区,而它的每一段切片都是一个不拷贝任何数据的视图。 +公开接口只有一个头文件 `` 和一个库 `libstringx`(`-lstringx`); +正则表达式是由 PCRE2 支持的进阶层,可按需使用。 + +## 从这里开始 + +| 你想…… | 请阅读 | +| --- | --- | +| 安装 String X 并写第一个程序 | [快速上手](getting-started.md) | +| 理解缓冲区 / 视图 / 所有权模型并查找用法示例 | [用户指南](guide.md) | +| 查询缓冲区、视图与修改类函数 | [API 参考:缓冲区与视图](api-buffer.md) | +| 查询查找、比较与分割类函数 | [API 参考:查找、比较与分割](api-search.md) | +| 使用正则表达式层 | [正则表达式](regex.md) | +| 了解库的内部实现 | [设计与内部实现](design.md) | +| 构建、测试、安装或打包 | [构建、测试与打包](build-and-test.md) | +| 提交一处修改 | [贡献指南](contributing.md) | +| 了解 CI 检查 | [持续集成](ci.md) | + +## 全部文档 + +- [快速上手](getting-started.md) —— 环境要求、构建、安装、第一个程序、 + 十分钟概览、文档索引。 +- [用户指南](guide.md) —— 心智模型、所有权规则、二进制安全、错误处理、 + 常用任务示例、常见陷阱、性能说明。 +- [API 参考:缓冲区与视图](api-buffer.md) —— 创建与释放、容量、访问器、 + 修改、子串、视图移动与裁剪。 +- [API 参考:查找、比较与分割](api-search.md) —— `sx_find*`、`sx_rfind*`、 + `sx_find_all*`、`sx_cmp*`、`sx_starts_with*`、`sx_ends_with*`、`sx_split`。 +- [正则表达式](regex.md) —— `sx_reg_*` 三个家族:匹配、替换与分割,以及 + 每个调用的完整契约。 +- [设计与内部实现](design.md) —— 数据布局、扩容策略、查找算法、正则封装 + 的内部细节、可移植性限制、测试策略。 +- [构建、测试与打包](build-and-test.md) —— Forge、`./make` 各目标、测试 + 框架、内存检查器、安装与 Debian 打包。 +- [贡献指南](contributing.md) —— 工作流程、契约优先的文档规则、代码风格、 + 测试、许可。 +- [持续集成](ci.md) —— 工作流、必需检查、CodeQL、合并保护、本地复现。 + +## 文档约定 + +- API 参考只覆盖公开头文件:`sx.h` 以及它包含的 `sx_core.h`。`sx_raw.h` + 是内部的分配/调试接口,不属于受支持的公开接口。 +- 文档中的每一条行为描述都来自公开头文件中的契约、实现代码,以及 + `tests/*.c` 中的行为边界注释。 +- **契约之外(out of contract)**表示该调用不在库的文档化保证范围内, + 行为未定义;测试有意不覆盖这类调用,你的程序也不应依赖它。 +- 代码示例面向 Linux 上的 C23,并链接 `-lstringx`(正则示例无需额外 + 参数:库自身已链接 `pcre2-8`)。 +- 本文档描述 **v0.5**;版本号的唯一来源是 `build.conf`。 + +## 许可 + +库本身以 MIT 许可发布 —— 见 [LICENSE](../../LICENSE) 以及源文件中的 SPDX +标注。正则层依赖 PCRE2(BSD-3-Clause),详见 +[THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md)。 diff --git a/docs/zh_cn/api-buffer.md b/docs/zh_cn/api-buffer.md new file mode 100644 index 0000000..01f8c75 --- /dev/null +++ b/docs/zh_cn/api-buffer.md @@ -0,0 +1,722 @@ +[English](../en_us/api-buffer.md) · 中文 + +[文档首页](README.md) › API 参考:缓冲区与视图 + +# 缓冲区与视图 API 参考 + +本页是 `include/sx_core.h` 中核心缓冲区与视图 API 的完整参考:创建与释放 +缓冲区、读取状态、修改内容、截取子串,以及移动和裁剪视图。查找、比较与 +分割由[查找、比较与分割](api-search.md)一并说明。 + +下文每一条行为描述都来自公开头文件中的契约、实现代码,以及 +`tests/*.c` 中的行为边界注释。 + +## 约定 + +**头文件与分层。** 包含唯一的公开头文件: + +```c +#include +``` + +`sx.h` 包含 `sx_core.h`(缓冲区、视图、查找、比较),随后声明 `sx_split` +和 `sx_reg_*` 家族。链接库时使用 `-lstringx`。本页所有函数都声明在 +`sx_core.h` 中。`sx_raw.h` 是内部的分配/调试接口,不属于受支持的公开 +接口。 + +**每个缓冲区一次分配。** 一个 `sx_t` 句柄拥有恰好一段以 NUL 结尾的字节 +数组:`ptr[0 .. len-1]` 是内容字节,`ptr[len]` 恒为 `'\0'`,`cap` 是分配 +大小,且 `cap >= len + 1`。`len` 统计内容字节,因此内嵌的 `'\0'` 是普通 +数据而不是结尾符 —— 该模型天然二进制安全。 + +**所有权。** + +| 值 | 所有者 | 释放方式 | +| --- | --- | --- | +| `sx_new*`、`sx_dup`、`sx_substr` 返回的缓冲区 | 调用方 | `sx_free` | +| `sx_append`、`sx_write`、`sx_insert` 的 `owned` 参数 | 转移给库 | 无需操作:调用会释放它 | +| 修改类函数返回的缓冲区 | 与 `self` 是同一个句柄 | 对最初的句柄调用一次 `sx_free` | +| `sx_view_t` | 无:它仅别名一段缓冲区 | 无需释放;视图从不单独释放 | +| `sx_find_all*` 或 `sx_split` 返回的数组 | 调用方 | `free`(见 [api-search.md](api-search.md)) | + +每次修改都返回 `self`,因此调用可以链式书写,句柄保持稳定。缓冲区增长时 +底层数组可能搬移:`sx_buf_mut`/`sx_buf_view_mut` 返回的指针在任何可能 +重新分配的调用之后都会失效,必须重新获取。 + +**NULL 与契约之外。** 本页明确记录的 NULL 处理只有:`sx_new_from_cstr(NULL)` +和 `sx_dup(NULL)` 返回 `NULL`;`sx_append`、`sx_write`、`sx_insert` 的 +`owned` 形式以及所有 `_cstr` 形式在第二个参数为 `NULL` 时返回 `NULL` 且 +保持 `self` 不变。其余函数都会解引用缓冲区或窗口:`sx_free`、`sx_len`、 +`sx_cap`、`sx_buf_mut`、`sx_view`、视图移动家族以及修改类函数都不接受 +NULL 句柄;`sx_new_from_view`、`sx_buf_view_mut` 和 `sx_view_*` 也不接受 +`ref == NULL` 的视图(`sx_len_view` 只读取存储的长度)。NULL 句柄或 +`v.ref`、已释放的句柄、越出底层缓冲区的视图、重复释放、在消耗所有权的 +调用之后继续使用、把 `self` 作为 `owned` 参数传入,以及违反各条目所述 +条件的下标,全部属于**契约之外**:行为未定义,而不是有文档化的错误 +返回值。 + +**哨兵值。** + +| 情形 | 取值 | +| --- | --- | +| 分配失败 | `NULL` | +| 拒绝 NULL 操作数(有文档记录处) | `NULL` | +| “没有视图” | `.ref == NULL` | +| 未找到 / 无匹配(查找页) | `(size_t)-1` | +| 无匹配 / 拒绝分割(查找页) | `NULL` | + +**大小是 `int`。** `sx_len`、`sx_len_view` 和 `sx_cap` 返回 `int`,而视图 +字段和查找偏移是 `size_t`。内容超过 `INT_MAX` 字节的情况不在测试契约 +范围内;两者混用时请转换为 `(size_t)`,例如 +`fwrite(sx_buf_mut(h), 1, (size_t)sx_len(h), stdout)`。 + +**视图是快照。** `sx_view_t {ref, offset, len}` 表示 `ref` 所指缓冲区内的 +字节窗口 `[offset, offset + len)`;它不拷贝、也不修改任何东西。合法的窗口 +必须位于缓冲区内(`offset + len <= len(ref)`)。之后任何重新分配或改变 +长度的修改都会使视图失去意义:这类修改之后要重新推导视图;有视图(例如 +`sx_split` 数组)在使用时不要修改其底层缓冲区。`ref == NULL` 表示“没有 +视图”,它不是可用的缓冲区。 + +**容量增长。** `sx_new` 的初始容量是 32 字节。增长是几何式的(先翻倍, +容量达到 64 KiB 之后改为 `+0x10000`);使用 `-DSX_FORCE_EXACT_RESERVE` +的调试构建会把每次分配精确设为 `need + 1`。容量从不收缩 —— `sx_truncate` +和 `sx_clear` 都会保留容量 —— 任何函数也不会承诺其所述保证之外的空闲 +容量。 + +## 创建与释放 + +### sx_new + +```c +sx_t *sx_new(void); +``` + +创建一个初始容量为 32 字节的空缓冲区。 + +- **参数:** 无。 +- **返回:** 新缓冲区(`len == 0`、`cap == 32`、`ptr[0] == '\0'`), + 分配失败时返回 `NULL`。 +- **所有权:** 调用方所有;用 `sx_free` 释放。 +- **边界情况:** 确切的初始容量属于实现细节;只有 `cap >= 1` 有保证。 + +### sx_new_from_cstr + +```c +sx_t *sx_new_from_cstr(const char *s); +``` + +创建一个存放 C 字符串 `s` 副本的缓冲区。 + +- **参数:** `s` —— 以 NUL 结尾的源字符串,按 `strlen` 读取。 +- **返回:** 新的调用方所有的缓冲区;`s == NULL` 或分配失败时返回 + `NULL`。 +- **所有权:** 调用方所有;用 `sx_free` 释放。 +- **边界情况:** 采用 `strlen` 语义 —— 内嵌的 `'\0'` 会截断副本。二进制 + 内容请使用 `sx_new_from_view`。 + +### sx_new_from_view + +```c +sx_t *sx_new_from_view(sx_view_t v); +``` + +把视图中的字节拷贝成一个新的独立缓冲区。 + +- **参数:** `v` —— 源窗口;从 `v.ref->ptr + v.offset` 读取 `v.len` + 个字节。 +- **返回:** 新的调用方所有的缓冲区;分配失败时返回 `NULL`。 +- **所有权:** 调用方所有;用 `sx_free` 释放。 +- **边界情况:** 字节精确且二进制安全:内嵌的 `'\0'` 字节会被拷贝。两个 + 缓冲区之间不存在别名 —— 修改任一方永远不影响另一方。`v.ref == NULL` 或 + 越界窗口属于契约之外。 + +### sx_new_with_cap + +```c +sx_t *sx_new_with_cap(size_t n); +``` + +创建一个恰好分配 `n` 个字节的空缓冲区。 + +- **参数:** `n` —— 分配的总字节数。 +- **返回:** `n >= 1` 时 `cap == n` 的新缓冲区;分配失败时返回 `NULL`。 +- **所有权:** 调用方所有;用 `sx_free` 释放。 +- **边界情况:** 其中一个字节留给结尾符,因此最多容纳 `n - 1` 个内容 + 字节。`n == 0` 时仍会分配一个字节(`cap == 1`),句柄始终有效。 + +```c +sx_t *buf = sx_new_with_cap(64); /* room for 63 content bytes */ +buf = sx_append_cstr(buf, "hello"); /* no reallocation */ +sx_free(buf); +``` + +### sx_dup + +```c +sx_t *sx_dup(const sx_t *src); +``` + +创建缓冲区的深拷贝,副本完全独立。 + +- **参数:** `src` —— 源缓冲区。 +- **返回:** 内容相同的新缓冲区;`src == NULL` 或分配失败时返回 + `NULL`。 +- **所有权:** 调用方所有;副本与源分别用 `sx_free` 释放。 +- **边界情况:** 二进制安全。v0.5 中副本的容量是 `len + 1`,而不是源的 + 容量。 + +```c +sx_t *src = sx_new_from_cstr("hello"); +sx_t *copy = sx_dup(src); /* independent: free both */ +sx_free(copy); +sx_free(src); +``` + +### sx_free + +```c +void sx_free(sx_t *h); +``` + +释放缓冲区:内容数组和句柄本身。 + +- **参数:** `h` —— 调用方持有所有权的有效句柄。 +- **返回:** 无。 +- **所有权:** 消耗 `h`;所有指向该缓冲区的视图和 `sx_buf_mut` 指针都 + 随之失效。 +- **边界情况:** `h == NULL` 属于契约之外 —— 该函数会解引用句柄(正则层 + 的 `sx_reg_free(NULL)` 空操作不适用于这里)。重复释放和释放后使用同样 + 属于契约之外。 + +## 访问器 + +### sx_len + +```c +int sx_len(sx_t *h); +``` + +返回内容字节数。 + +- **参数:** `h` —— 缓冲区。 +- **返回:** `len`,内嵌的 `'\0'` 字节也计入;结尾符从不计入。 +- **所有权:** 无;不修改缓冲区。 +- **边界情况:** `h == NULL` 属于契约之外。返回值是 `int`;参见上文的 + 大小说明。 + +### sx_len_view + +```c +int sx_len_view(sx_view_t v); +``` + +返回视图中存储的长度。 + +- **参数:** `v` —— 要读取长度的视图。 +- **返回:** `(int)v.len`;不会查看底层缓冲区,也不会校验窗口边界。 +- **所有权:** 无。 +- **边界情况:** `v.len` 超过 `INT_MAX` 不在测试契约范围内。“没有视图” + 哨兵值(`ref == NULL`)的 `len` 为 0。 + +### sx_cap + +```c +int sx_cap(sx_t *h); +``` + +返回为内容数组分配的总字节数。 + +- **参数:** `h` —— 缓冲区。 +- **返回:** `cap`,它始终至少为 `len + 1`(单 NUL 结尾不变式)。 +- **所有权:** 无;不修改缓冲区。 +- **边界情况:** `h == NULL` 属于契约之外。`len + 1` 之外的空闲容量取决于 + 增长策略,不构成契约。 + +### sx_buf_mut + +```c +char *sx_buf_mut(sx_t *h); +``` + +返回指向内容数组的可写指针。 + +- **参数:** `h` —— 缓冲区。 +- **返回:** `ptr`;任何时刻都有 `ptr[len] == '\0'`。 +- **所有权:** 借用;调用方可以在 `[0, len)` 内改写字节而不改变 `len`。 +- **边界情况:** 没有改变长度的调用时,不得在 `len` 及其之后写入;也不得 + 跨过任何可能重新分配的调用保存该指针(`sx_append*`、`sx_write*`、 + `sx_insert*`、`sx_reserve`、会增长的 `sx_truncate`)。`h == NULL` 属于 + 契约之外。 + +```c +char *p = sx_buf_mut(buf); +p[0] = 'H'; /* len unchanged; p[len] must stay '\0' */ +``` + +### sx_buf_view_mut + +```c +char *sx_buf_view_mut(sx_view_t v); +``` + +返回指向视图窗口首字节的可写指针。 + +- **参数:** `v` —— 指向某个缓冲区的视图。 +- **返回:** `v.ref->ptr + v.offset`。 +- **所有权:** 借用;写入会落到底层缓冲区上。 +- **边界情况:** 该指针不携带长度信息 —— 请配合 `sx_len_view(v)` 使用并 + 停留在窗口内。`v.ref == NULL` 或越界窗口属于契约之外;底层缓冲区重新 + 分配后该指针失效。 + +```c +sx_view_t word = sx_view_range(sx_view(buf), 6, 5); +char *w = sx_buf_view_mut(word); /* == sx_buf_mut(buf) + 6 */ +w[0] = 'W'; +``` + +### sx_view + +```c +sx_view_t sx_view(const sx_t *h); +``` + +返回整个缓冲区的视图。 + +- **参数:** `h` —— 缓冲区。 +- **返回:** `{ref: h->ref, offset: 0, len: sx_len(h)}`。 +- **所有权:** 无;视图为 `h` 的别名,从不单独释放。 +- **边界情况:** 零拷贝且只读;`h == NULL` 属于契约之外。 + +## 容量 + +### sx_reserve + +```c +sx_t *sx_reserve(sx_t *self, size_t min_cap); +``` + +确保能容纳至少 `min_cap` 个内容字节外加结尾符。 + +- **参数:** `self` —— 缓冲区;`min_cap` —— 必须能在后续操作中直接容纳的 + 内容字节数。 +- **返回:** 成功时(包括无需操作的请求)返回 `self`;分配失败时返回 + `NULL`。 +- **所有权:** 返回的 `self` 仍归调用方所有;内容与长度保持不变。 +- **边界情况:** 成功后 `cap >= min_cap + 1`。当前容量已经满足的请求不会 + 缩小或改变容量。容量只增不减;`sx_truncate` 和 `sx_clear` 从不回收。 + 底层数组可能搬移,之后必须重新获取所有 `sx_buf_mut` 指针。 + +```c +buf = sx_reserve(buf, 4096); /* cap >= 4097 */ +``` + +## 追加 + +### sx_append + +```c +sx_t *sx_append(sx_t *self, sx_t *owned); +``` + +追加另一个缓冲区的内容,并消耗该缓冲区。 + +- **参数:** `self` —— 目标;`owned` —— 内容被追加的源。 +- **返回:** `self`;`owned == NULL` 或分配失败时返回 `NULL`。 +- **所有权:** 所有权转移:调用读取 `owned` 的内容后将其释放。此后不得 + 再使用或释放 `owned`。 +- **边界情况:** 字节精确:按内容长度处理,内嵌的 `'\0'` 字节也会被追加。 + `owned == NULL` 时不做任何修改。`self` 可能重新分配。把 `self` 作为 + `owned` 传入属于契约之外(它会在使用中被释放)。 + +### sx_append_cstr + +```c +sx_t *sx_append_cstr(sx_t *self, const char *s); +``` + +追加一个 C 字符串。 + +- **参数:** `self` —— 目标;`s` —— 以 NUL 结尾的源。 +- **返回:** `self`;`s == NULL` 或分配失败时返回 `NULL`。 +- **所有权:** 无;只读取 `s`。 +- **边界情况:** `strlen` 语义 —— 内嵌的 `'\0'` 会截断追加的字节。追加 + `""` 是空操作,返回 `self`。 + +### sx_append_view + +```c +sx_t *sx_append_view(sx_t *self, sx_view_t v); +``` + +追加视图中的字节。 + +- **参数:** `self` —— 目标;`v` —— 源窗口;从 `v.ref->ptr + v.offset` + 读取 `v.len` 个字节。 +- **返回:** `self`;分配失败时返回 `NULL`。 +- **所有权:** 无;只读取 `v`。 +- **边界情况:** 字节精确且二进制安全。`v` 可以是 `self` 的别名,追加导致 + 缓冲区增长时也一样:用 `sx_append_view(h, sx_view(h))` 原地翻倍是支持的。 + `v.ref == NULL` 或越界窗口属于契约之外。 + +```c +buf = sx_append_view(buf, sx_view(buf)); /* doubles in place */ +``` + +## 写入 + +### sx_write + +```c +sx_t *sx_write(sx_t *self, size_t idx, sx_t *owned); +``` + +从 `idx` 开始覆盖写入字节,必要时扩展长度,并消耗源缓冲区。 + +- **参数:** `self` —— 目标;`idx` —— 第一个被覆盖的字节;`owned` —— + 内容被写入的源。 +- **返回:** `self`;`owned == NULL` 或分配失败时返回 `NULL`。 +- **所有权:** 所有权转移:调用读取 `owned` 的内容后将其释放。此后不得 + 再使用或释放它。 +- **边界情况:** 调用后 `len' = max(len, idx + owned.len)` —— 写入从不 + 缩短缓冲区。`idx == len` 等价于追加;`idx < len` 原地覆盖;`idx > len` + 会扩展长度,且 `[len, idx)` 区间的字节是**未指定的**。把 `self` 作为 + `owned` 传入,或 `idx + n` 使 `size_t` 溢出,都属于契约之外。 + +```c +buf = sx_new_from_cstr("abc"); +buf = sx_write_cstr(buf, 6, "XY"); /* len 8; bytes 3..5 unspecified */ +``` + +### sx_write_cstr + +```c +sx_t *sx_write_cstr(sx_t *self, size_t idx, const char *s); +``` + +在 `idx` 处写入一个 C 字符串。 + +- **参数:** `self` —— 目标;`idx` —— 第一个写入位置;`s` —— 以 NUL + 结尾的源。 +- **返回:** `self`;`s == NULL` 或分配失败时返回 `NULL`。 +- **所有权:** 无;只读取 `s`。 +- **边界情况:** `strlen` 语义(内嵌的 `'\0'` 会截断写入的字节)。 + `s == NULL` 时 `self` 保持不变。`idx` 与填充规则同 `sx_write`。 + +### sx_write_view + +```c +sx_t *sx_write_view(sx_t *self, size_t idx, sx_view_t v); +``` + +在 `idx` 处写入视图中的字节。 + +- **参数:** `self` —— 目标;`idx` —— 第一个写入位置;`v` —— 源窗口。 +- **返回:** `self`;分配失败时返回 `NULL`。 +- **所有权:** 无;只读取 `v`。 +- **边界情况:** 字节精确且二进制安全。`v` 可以是 `self` 的别名,写入需要 + 增长缓冲区时也一样(源字节在预留空间的过程中保持有效)。`idx` 与填充 + 规则同 `sx_write`;越界窗口属于契约之外。 + +## 插入 + +### sx_insert + +```c +sx_t *sx_insert(sx_t *self, size_t idx, sx_t *owned); +``` + +在 `idx` 处插入另一个缓冲区的内容,尾部右移,并消耗该缓冲区。 + +- **参数:** `self` —— 目标;`idx` —— 插入点,要求 `0 <= idx <= len`; + `owned` —— 内容被插入的源。 +- **返回:** `self`;`owned == NULL` 或分配失败时返回 `NULL`。 +- **所有权:** 所有权转移:调用读取 `owned` 的内容后将其释放。此后不得 + 再使用或释放它。 +- **边界情况:** 结果为 `[0, idx)` ++ 插入字节 ++ `[idx, len)`, + 且 `len' = len + n`。`idx == len` 等价于追加。`idx > len` 属于契约之外 + (尾部移动会下溢);把 `self` 作为 `owned` 传入属于契约之外。 + +```c +buf = sx_insert_cstr(buf, 3, "-"); /* shift the tail right */ +``` + +### sx_insert_cstr + +```c +sx_t *sx_insert_cstr(sx_t *self, size_t idx, const char *s); +``` + +在 `idx` 处插入一个 C 字符串。 + +- **参数:** `self` —— 目标;`idx` —— 插入点,要求 `0 <= idx <= len`; + `s` —— 以 NUL 结尾的源。 +- **返回:** `self`;`s == NULL` 或分配失败时返回 `NULL`。 +- **所有权:** 无;只读取 `s`。 +- **边界情况:** `strlen` 语义;`s == NULL` 时 `self` 保持不变。`idx > len` + 属于契约之外。 + +### sx_insert_view + +```c +sx_t *sx_insert_view(sx_t *self, size_t idx, sx_view_t v); +``` + +在 `idx` 处插入视图中的字节。 + +- **参数:** `self` —— 目标;`idx` —— 插入点,要求 `0 <= idx <= len`; + `v` —— 源窗口。 +- **返回:** `self`;分配失败时返回 `NULL`。 +- **所有权:** 无;只读取 `v`。 +- **边界情况:** 字节精确且二进制安全。`v` 可以是 `self` 的别名,插入 + 导致缓冲区增长时也一样,但前提是视图窗口的起始偏移不大于 `idx`(测试 + 覆盖的即插入点处的切片);起始偏移大于 `idx` 的自别名窗口会被尾部右移 + 覆盖,属于**契约之外** —— 请先用 `sx_new_from_view` 复制该切片。 + `idx > len` 和越界视图属于契约之外。 + +## 截断、删除与清空 + +### sx_truncate + +```c +sx_t *sx_truncate(sx_t *self, size_t new_len); +``` + +把内容长度设为 `new_len`。 + +- **参数:** `self` —— 缓冲区;`new_len` —— 新的内容字节长度。 +- **返回:** 成功时返回 `self`;增长过程中分配失败时返回 `NULL`。 +- **所有权:** 返回的 `self` 仍归调用方所有。 +- **边界情况:** 更短的 `new_len` 保留前缀并丢弃尾部;相同的 `new_len` + 是空操作。更长的 `new_len` 会扩展缓冲区:`len` 变为 `new_len`, + `ptr[new_len] == '\0'`,而 `[old_len, new_len)` 区间的字节是**未指定的** + —— 在覆盖它们之前不要读取。收缩不会回收容量。 + +### sx_erase + +```c +sx_t *sx_erase(sx_t *self, size_t idx, size_t n); +``` + +删除从 `idx` 开始的 `n` 个字节,尾部左移。 + +- **参数:** `self` —— 缓冲区;`idx` —— 第一个被删除的字节;`n` —— 要 + 删除的字节数。 +- **返回:** `self`。 +- **所有权:** 返回的 `self` 仍归调用方所有;`self` 本身必须有效。 +- **边界情况:** `idx + n == len` 删除后缀;`idx + n > len` 是空操作,原样 + 返回 `self`;`n == 0` 是空操作。调用不进行分配,因此不会失败。 + `idx + n` 使 `size_t` 溢出属于契约之外。 + +```c +buf = sx_erase(buf, 2, 100); /* idx+n > len: no-op, returns self */ +``` + +### sx_clear + +```c +sx_t *sx_clear(sx_t *self); +``` + +清空缓冲区,保留容量。 + +- **参数:** `self` —— 缓冲区。 +- **返回:** `self`。 +- **所有权:** 返回的 `self` 仍归调用方所有。 +- **边界情况:** 设置 `len = 0` 和 `ptr[0] = '\0'`;分配及其容量保留, + 缓冲区可以立即复用。 + +```c +buf = sx_clear(buf); /* len 0, capacity kept */ +``` + +## 子串 + +### sx_substr + +```c +sx_t *sx_substr(const sx_t *h, size_t idx, size_t n); +``` + +把字节区间 `[idx, idx + n)` 拷贝到一个新的独立缓冲区。 + +- **参数:** `h` —— 源缓冲区;`idx` —— 起始偏移;`n` —— 字节数,前置 + 条件为 `idx + n <= len(h)`。 +- **返回:** 新的调用方所有的缓冲区;分配失败时返回 `NULL`。(`h` 为 + NULL 或区间越界属于契约之外,而不是错误返回值。) +- **所有权:** 调用方所有;用 `sx_free` 释放。 +- **边界情况:** `n == 0` 得到空缓冲区。字节精确且二进制安全,包括内嵌的 + `'\0'` 字节。与视图移动不同,这里是拷贝:任一侧的修改都不会影响另一侧。 + +```c +sx_t *word = sx_substr(buf, 6, 5); /* a copy, not a view */ +sx_free(word); +``` + +## 视图移动 + +这四个函数都在已有缓冲区上重新推导 `(offset, len)` 窗口。它们都不拷贝 +字节、不修改缓冲区,只返回新的视图值。输入必须是合法视图(`ref != NULL` +且窗口位于缓冲区内);非法输入属于契约之外。 + +### sx_view_advance + +```c +sx_view_t sx_view_advance(sx_view_t v, size_t n); +``` + +把窗口起点向右移动 `n`。 + +- **参数:** `v` —— 输入视图;`n` —— 前进的字节数。 +- **返回:** 同一缓冲区上调整后的视图。 +- **所有权:** 无。 +- **边界情况:** 设 `H = len(ref)`: + - 若 `offset + len + n < H`,保持终点不动,`len` 精确减少 `n`; + - 否则若 `offset + n < H`,起点变为 `offset + n`,终点夹紧到缓冲区 + 末尾(`len = H - offset`); + - 否则结果为空视图 `(H, 0)`。 + 即使 `n` 很大,前进也永远不会越过缓冲区末尾;而把子视图推进到其自身 + 终点之外时,会按第二种情况扩展到缓冲区末尾,这是契约规定的行为。 + +```c +sx_view_t rest = sx_view_advance(sx_view(buf), 2); /* start +2 */ +``` + +### sx_view_retreat + +```c +sx_view_t sx_view_retreat(sx_view_t v, size_t n); +``` + +把窗口起点向左移动 `n`,保持终点不动。 + +- **参数:** `v` —— 输入视图;`n` —— 后退的字节数。 +- **返回:** 同一缓冲区上调整后的视图。 +- **所有权:** 无。 +- **边界情况:** `len` 增加的量等于偏移减少的量;移动在偏移 0 处饱和 + (`len` 变为原来的 `offset + len`),因此窗口永远不会从缓冲区之前开始。 + +### sx_view_shift + +```c +sx_view_t sx_view_shift(sx_view_t v, ptrdiff_t off); +``` + +按有符号偏移移动窗口,保持长度不变。 + +- **参数:** `v` —— 输入视图;`off` —— 有符号字节偏移。 +- **返回:** 同一缓冲区上调整后的视图。 +- **所有权:** 无。 +- **边界情况:** 与 advance/retreat 不同,`len` 保持不变。正的 `off` 若会 + 把终点推过缓冲区,则夹紧为 `offset = H - len`(窗口停在缓冲区末尾); + 负的 `off` 使起点饱和在 0。空缓冲区上的结果是 `(0, 0)`。 + +### sx_view_range + +```c +sx_view_t sx_view_range(sx_view_t v, size_t off, size_t len); +``` + +按绝对坐标重新锚定窗口,忽略输入视图的偏移和长度。 + +- **参数:** `v` —— 只提供底层缓冲区;`off` —— 绝对起始偏移,前置条件为 + `off <= H`;`len` —— 请求的长度。 +- **返回:** 视图 `(off, min(len, H - off))`。 +- **所有权:** 无。 +- **边界情况:** 长度会夹紧到缓冲区末尾;`off == H` 得到 `(H, 0)`; + `off > H` 属于契约之外(`H - off` 下溢)。 + +```c +sx_view_t slice = sx_view_range(sx_view(buf), 2, 3); /* absolute (2, 3) */ +``` + +## 视图裁剪 + +裁剪家族从视图两端移除 ASCII 空白字符。空白集合恰为 +`{space, '\t', '\v', '\f', '\r', '\n'}`。不会修改任何缓冲区字节,也只 +检查窗口内部的字节。 + +### sx_view_trim + +```c +sx_view_t sx_view_trim(sx_view_t v); +``` + +裁剪视图的两端。 + +- **参数:** `v` —— 输入视图。 +- **返回:** 去掉首尾空白后的视图。 +- **所有权:** 无。 +- **边界情况:** 等价于 `sx_view_trim_back(sx_view_trim_front(v))`。两端都 + 没有空白的视图原样返回。内容全为空白的视图会变成窗口末尾处的空视图 + (偏移为 `offset + len`,长度为 0)—— 对整个缓冲区的视图而言就是 + `(H, 0)`。 + +```c +sx_view_t field = sx_view_trim(sx_view(buf)); /* strip ASCII whitespace */ +``` + +### sx_view_trim_front + +```c +sx_view_t sx_view_trim_front(sx_view_t v); +``` + +去掉前导空白。 + +- **参数:** `v` —— 输入视图。 +- **返回:** 去掉前导空白后的视图。 +- **所有权:** 无。 +- **边界情况:** 偏移右移,`len` 相应减少,因此窗口终点保持不动。扫描受 + 视图自身长度的限制,即使窗口之后缓冲区里仍有空白,也不会越过窗口末尾。 + +### sx_view_trim_back + +```c +sx_view_t sx_view_trim_back(sx_view_t v); +``` + +去掉尾部空白。 + +- **参数:** `v` —— 输入视图。 +- **返回:** 去掉尾部空白后的视图。 +- **所有权:** 无。 +- **边界情况:** 只检查窗口的最后一个字节(`offset + len - 1`),`len` + 向左收缩;偏移保持不变,因此全为空白的窗口会变成 `(offset, 0)`。窗口 + 之外的字节永远不会被检查。 + +## 完整示例 + +下面这个程序构造一个字符串,裁剪它的一个视图,把裁剪后的窗口拷贝到新 +缓冲区,原地修改该缓冲区,最后释放两个缓冲区。按原样与库源码一起即可 +编译,也是普通应用程序的典型写法: + +```c +#include +#include + +int main(void) { + sx_t *h = sx_new_from_cstr(" hello, world "); + + sx_view_t trimmed = sx_view_trim(sx_view(h)); /* (2, 12) */ + sx_t *clean = sx_new_from_view(trimmed); /* independent copy */ + + clean = sx_append_cstr(clean, "!"); + clean = sx_insert_cstr(clean, 0, "> "); + + printf("%s (%d bytes)\n", sx_buf_mut(clean), sx_len(clean)); + + sx_free(clean); + sx_free(h); + return 0; +} +``` + +预期输出: + +```text +> hello, world! (15 bytes) +``` + +--- + +[← 上一页](guide.md) · [文档首页](README.md) · [下一页 →](api-search.md) diff --git a/docs/zh_cn/api-search.md b/docs/zh_cn/api-search.md new file mode 100644 index 0000000..587ead1 --- /dev/null +++ b/docs/zh_cn/api-search.md @@ -0,0 +1,571 @@ +[English](../en_us/api-search.md) · 中文 + +[文档首页](README.md) › API 参考:查找、比较与分割 + +# 查找、比较与分割 + +本页是查找家族(`sx_find*`、`sx_rfind*`、`sx_find_all*`)、比较家族 +(`sx_cmp*`、`sx_starts_with*`、`sx_ends_with*`)以及 `sx_split` 的完整 +参考。它们全部字节精确,并按内容长度工作,因此内嵌的 NUL 字节是普通 +数据。缓冲区的创建、修改与视图见[缓冲区与视图](api-buffer.md)。 + +## 约定 + +**needle 的形式。** 每个查找家族都有同样的四种 needle 形态: + +| 后缀 | 参数类型 | 匹配的字节 | NUL 行为 | +| --- | --- | --- | --- | +| 无 | `const sx_t *` | 该缓冲区的内容字节 | 内嵌 NUL 是数据 | +| `_view` | `sx_view_t` | `v.ref->ptr + v.offset` 处的 `v.len` 个字节 | 内嵌 NUL 是数据 | +| `_cstr` | `const char *` | `strlen(...)` 个字节 | 第一个 NUL 结束 needle | +| `_char` | `char` | 恰好一个字节 | `'\0'` 表示一个 NUL 内容字节 | + +owned 形式和 view 形式是二进制安全的:它们精确读取 needle 的长度,因此 +内嵌的 `'\0'` 会作为数据参与匹配。`_cstr` 形式使用 `strlen`,所以 +`sx_find_cstr(h, "a\0c")` 实际查找的是 `"a"`;要查找二进制模式,请使用 +owned 或 view 形式的 needle。空的 needle(长度为 0)永远不会被找到。 + +**有界区域。** 设 `H` 为被查找缓冲区的内容长度,needle 长度为 `m`,一次匹配是窗口 +`[p, p + m)`,它必须完全位于被搜索的区域之内: + +| 函数 | 搜索区域 | 窗口条件 | +| --- | --- | --- | +| `sx_find*`、`sx_rfind*`(无界) | `[0, H)` | `p + m <= H` | +| `sx_find_view_b(h, needle, boundary)` | `[boundary, H)` | `p >= boundary` 且 `p + m <= H` | +| `sx_rfind_view_b(h, needle, boundary)` | `[0, min(boundary, H))` | `p + m <= min(boundary, H)` | + +两个有界形式都接收 `size_t boundary`,但方向相反:`sx_find_view_b` 从 +左侧限定区域,起点早于 `boundary` 的窗口不计入;`sx_rfind_view_b` 从右侧 +限定区域,终点晚于边界的窗口不计入。下面是测试中的具体用例,取 +`h = "ababa"`,needle 为 `"ba"`: + +- `sx_find_view_b(h, nd, 2)` 为 3 —— 偏移 1 处的匹配起点在边界之前,不计 + 入;boundary 为 4 时返回 `(size_t)-1`,因为剩余区域 `"a"` 放不下一个 + 窗口。 +- `sx_rfind_view_b(h, nd, 3)` 为 1 —— 偏移 3 处的匹配终止于 5,越过了 + 边界;boundary 为 2 时返回 `(size_t)-1`;若 needle 为 `"aba"` 且 + boundary 为 3,窗口 `[0, 3)` 恰好终止于边界,结果为 0。 +- 对 `sx_find_view_b` 而言,`boundary >= H` 是空区域,返回 `(size_t)-1`。 + 对 `sx_rfind_view_b` 而言,大于等于 `H` 的 boundary 会夹紧到 `H`, + 等价于无界的最右查找。 + +**二进制安全。** 被查找的缓冲区始终按内容长度(`H`)处理,而不是按 +C 字符串:内嵌的 `'\0'` 字节是普通字节,`ptr[H]` 处的结尾符不属于搜索 +区域。特别地,`sx_find_char(h, '\0')` 只报告内嵌的 NUL 内容字节,永远不会 +匹配结尾符。owned 和 view 形式的 needle 同样按长度读取;只有 `_cstr` +形式的 needle 会在第一个 NUL 处停止。 + +**哨兵值与 NULL。** + +| 家族 | 未找到 / 拒绝输入时的结果 | +| --- | --- | +| `sx_find*`、`sx_rfind*` | `(size_t)-1` | +| `sx_find_all*` | `NULL` | +| `sx_cmp*` | 任一操作数为 NULL 时返回 `0` | +| `sx_starts_with*`、`sx_ends_with*` | `0` | +| `sx_split` | `NULL` | + +查找函数会检查指针参数:`h` 为 NULL 或 needle 参数为 NULL 时返回该家族 +的哨兵值,而不是崩溃。对 view 形式而言,`v.ref == NULL` 属于契约之外 —— +指针在任何长度检查之前就已形成,因此务必传入指向有效缓冲区的视图。 +`sx_find_all*` 和 `sx_split` 用与“无匹配”相同的哨兵值报告分配失败;按 +契约这两者无法区分。`(size_t)-1` 不会与真实的偏移冲突,因为偏移都小于 +`INT_MAX` 个内容字节。 + +**查找策略。** 单字节 needle 使用 `memchr`(向前)或逐字节反向扫描(可用 +时使用 glibc 的 `memrchr`),不进行分配。更长的 needle 使用 KMP:调用 +期间会分配一张含 `m` 个 `size_t` 的临时前缀表,因此一次查找的最坏情况为 +O(n + m)。`sx_find_all*` 还会额外返回一个 malloc 分配的结果数组,并报告 +每一次出现,包括相互重叠的出现。 + +## 如何选择调用 + +| 你需要 | 使用 | +| --- | --- | +| 整串中最左的出现 | `sx_find*` | +| 整串中最右的出现 | `sx_rfind*` | +| 每一次出现,含重叠 | `sx_find_all*` | +| 边界处或之后最左的出现 | `sx_find_view_b` | +| 边界处或之前结束的最右出现 | `sx_rfind_view_b` | +| 相等或排序比较 | `sx_cmp*` | +| 前缀或后缀判定 | `sx_starts_with*`、`sx_ends_with*` | +| 分割为若干 token | `sx_split` | + +## 最左查找:`sx_find*` + +### sx_find + +```c +size_t sx_find(const sx_t *h, const sx_t *needle); +``` + +查找另一个缓冲区的内容在 `h` 中最左的出现。 + +- **参数:** `h` —— 被查找的缓冲区;`needle` —— 内容被查找的缓冲区。 +- **返回:** 最左匹配的字节偏移;没有匹配时返回 `(size_t)-1`。 +- **所有权:** 无;不修改任一缓冲区。needle 长于一个字节时,调用内部会 + 分配并释放一张临时的 KMP 前缀表。 +- **边界情况:** `h` 或 `needle` 为 NULL 时返回 `(size_t)-1`;空 + needle 返回 `(size_t)-1`;比 `h` 更长的 needle 永远不会匹配。匹配按 + 内容长度字节精确进行,内嵌 NUL 同样参与匹配。 + +### sx_find_view + +```c +size_t sx_find_view(const sx_t *h, sx_view_t needle); +``` + +查找视图中的字节在整串中最左的出现。 + +- **参数:** `h` —— 被查找的缓冲区;`needle` —— 其 `needle.len` 个 + 字节被查找的窗口。 +- **返回:** 最左匹配的字节偏移,或 `(size_t)-1`。 +- **所有权:** 无;只读取。 +- **边界情况:** 等价于 `sx_find_view_b(h, needle, 0)`。空视图 + (`len == 0`)永远不会被找到。`needle.ref == NULL` 或越界窗口属于 + 契约之外。 + +### sx_find_view_b + +```c +size_t sx_find_view_b(const sx_t *h, sx_view_t needle, size_t boundary); +``` + +查找视图中的字节在 `boundary` 处或之后最左的出现。 + +- **参数:** `h` —— 被查找的缓冲区;`needle` —— 要查找的窗口; + `boundary` —— 区域起始偏移。 +- **返回:** `[boundary, H)` 内最左匹配的字节偏移,或 `(size_t)-1`。 +- **所有权:** 无;只读取。 +- **边界情况:** 匹配必须起始于 `boundary` 处或之后,并终止于 `H` 处或 + 之前;跨过边界的窗口不算匹配。`boundary >= H`、区域放不下一个窗口、 + 以及空 needle 都返回 `(size_t)-1`。`needle.ref == NULL`、越界窗口,或 + `boundary + needle.len` 使 `size_t` 溢出,属于契约之外。 + +```c +sx_t *h = sx_new_from_cstr("ababa"); +sx_t *ba = sx_new_from_cstr("ba"); +size_t at = sx_find_view_b(h, sx_view(ba), 2); /* 3, not 1 */ +sx_free(ba); +sx_free(h); +``` + +### sx_find_cstr + +```c +size_t sx_find_cstr(const sx_t *h, const char *needle); +``` + +查找 C 字符串在 `h` 中最左的出现。 + +- **参数:** `h` —— 被查找的缓冲区;`needle` —— 以 NUL 结尾的模式,按 + `strlen` 读取。 +- **返回:** 最左匹配的字节偏移,或 `(size_t)-1`。 +- **所有权:** 无;只读取。 +- **边界情况:** `h` 或 `needle` 为 NULL 时返回 `(size_t)-1`;空 needle + 返回 `(size_t)-1`。needle 中不能包含字面 NUL;二进制模式请使用 + `sx_find_view`。被查找的缓冲区可以包含 NUL。 + +### sx_find_char + +```c +size_t sx_find_char(const sx_t *h, char c); +``` + +查找单个字节最左的出现。 + +- **参数:** `h` —— 被查找的缓冲区;`c` —— 要查找的字节。 +- **返回:** 最左出现的字节偏移,或 `(size_t)-1`。 +- **所有权:** 无;只读取。 +- **边界情况:** `h` 为 NULL 时返回 `(size_t)-1`。搜索只覆盖内容 + (`[0, H)`),因此 `c == '\0'` 会找到内嵌的 NUL 内容字节,但永远不会 + 匹配结尾符。 + +## 最右查找:`sx_rfind*` + +### sx_rfind + +```c +size_t sx_rfind(const sx_t *h, const sx_t *needle); +``` + +查找另一个缓冲区的内容在 `h` 中最右的出现。 + +- **参数:** `h` —— 被查找的缓冲区;`needle` —— 内容被查找的缓冲区。 +- **返回:** 最右匹配的字节偏移,或 `(size_t)-1`。 +- **所有权:** 无;不修改任一缓冲区。needle 长于一个字节时,调用内部会 + 分配并释放一张临时的 KMP 前缀表。 +- **边界情况:** `h` 或 `needle` 为 NULL 时返回 `(size_t)-1`;空 + needle 返回 `(size_t)-1`;比 `h` 更长的 needle 永远不会匹配。字节 + 精确且二进制安全。 + +### sx_rfind_view + +```c +size_t sx_rfind_view(const sx_t *h, sx_view_t needle); +``` + +查找视图中的字节在整串中最右的出现。 + +- **参数:** `h` —— 被查找的缓冲区;`needle` —— 其 `needle.len` 个 + 字节被查找的窗口。 +- **返回:** 最右匹配的字节偏移,或 `(size_t)-1`。 +- **所有权:** 无;只读取。 +- **边界情况:** 等价于 `sx_rfind_view_b(h, needle, H)`。空视图永远不会 + 被找到。`needle.ref == NULL` 或越界窗口属于契约之外。 + +### sx_rfind_view_b + +```c +size_t sx_rfind_view_b(const sx_t *h, sx_view_t needle, size_t boundary); +``` + +查找视图中的字节在 `boundary` 处或之前结束的最右出现。 + +- **参数:** `h` —— 被查找的缓冲区;`needle` —— 要查找的窗口; + `boundary` —— 区域终止偏移(不含)。 +- **返回:** 窗口终止于 `[0, min(boundary, H))` 之内的最右匹配的字节 + 偏移,或 `(size_t)-1`。 +- **所有权:** 无;只读取。 +- **边界情况:** 匹配必须终止于 `boundary` 处或之前;伸出边界之外的 + 窗口不算匹配。boundary 为 0、区域放不下一个窗口、以及空 needle 都返回 + `(size_t)-1`。大于等于 `H` 的 boundary 会夹紧到 `H`,等价于无界的最右 + 查找。`needle.ref == NULL` 和越界窗口属于契约之外。 + +```c +sx_t *h = sx_new_from_cstr("ababa"); +sx_t *aba = sx_new_from_cstr("aba"); +size_t at = sx_rfind_view_b(h, sx_view(aba), 3); /* 0: ends exactly at 3 */ +sx_free(aba); +sx_free(h); +``` + +### sx_rfind_cstr + +```c +size_t sx_rfind_cstr(const sx_t *h, const char *needle); +``` + +查找 C 字符串在 `h` 中最右的出现。 + +- **参数:** `h` —— 被查找的缓冲区;`needle` —— 以 NUL 结尾的模式,按 + `strlen` 读取。 +- **返回:** 最右匹配的字节偏移,或 `(size_t)-1`。 +- **所有权:** 无;只读取。 +- **边界情况:** `h` 或 `needle` 为 NULL 时返回 `(size_t)-1`;空 needle + 返回 `(size_t)-1`。needle 中不能包含字面 NUL。 + +### sx_rfind_char + +```c +size_t sx_rfind_char(const sx_t *h, char c); +``` + +查找单个字节最右的出现。 + +- **参数:** `h` —— 被查找的缓冲区;`c` —— 要查找的字节。 +- **返回:** 最右出现的字节偏移,或 `(size_t)-1`。 +- **所有权:** 无;只读取。 +- **边界情况:** `h` 为 NULL 时返回 `(size_t)-1`。搜索只覆盖内容, + 因此 `c == '\0'` 永远不会匹配结尾符。 + +## 全部出现:`sx_find_all*` + +这些函数返回一个 malloc 分配的 `size_t` 数组,采用“计数在前”的形式: + +```text +r[0] number of matches +r[1 .. r[0]] ascending byte offsets of every match +``` + +重叠的匹配会全部报告:`"aaaa"` 中的 `"aa"` 会在偏移 0、1、2 处各找到 +一次。这里没有结束哨兵(与 `sx_split` 和 `sx_reg_match_all` 不同), +以计数为准。 + +- **返回:** 没有匹配时返回 `NULL` —— 包括空 needle 的情况 —— 参数为 + NULL 或分配失败时同样返回 `NULL`。按契约这两种失败原因无法区分。 +- **所有权:** 调用方拥有数组,用 `free`(而不是 `sx_free`)释放。不要 + 读取超过 `r[0] + 1` 个元素。 + +```c +sx_t *h = sx_new_from_cstr("ababab"); +size_t *hits = sx_find_all_cstr(h, "ab"); +/* hits[0] == 3; hits[1] == 0, hits[2] == 2, hits[3] == 4 */ +free(hits); +sx_free(h); +``` + +### sx_find_all + +```c +size_t *sx_find_all(const sx_t *h, const sx_t *needle); +``` + +收集另一个缓冲区内容的所有出现。 + +- **参数:** `h` —— 被查找的缓冲区;`needle` —— 内容被查找的缓冲区。 +- **返回:** 计数在前的 `size_t` 数组;无匹配、空 needle、NULL 参数或 + 分配失败时返回 `NULL`。 +- **所有权:** 调用方所有;用 `free` 释放。 +- **边界情况:** 二进制安全;偏移按升序排列,并包含重叠的匹配。 + +### sx_find_all_view + +```c +size_t *sx_find_all_view(const sx_t *h, sx_view_t needle); +``` + +收集视图中字节的所有出现。 + +- **参数:** `h` —— 被查找的缓冲区;`needle` —— 要查找的窗口。 +- **返回:** 计数在前的 `size_t` 数组;无匹配、空视图、NULL 参数或分配 + 失败时返回 `NULL`。 +- **所有权:** 调用方所有;用 `free` 释放。 +- **边界情况:** `needle.ref == NULL` 或越界窗口属于契约之外。 + +### sx_find_all_cstr + +```c +size_t *sx_find_all_cstr(const sx_t *h, const char *needle); +``` + +收集 C 字符串的所有出现。 + +- **参数:** `h` —— 被查找的缓冲区;`needle` —— 以 NUL 结尾的模式,按 + `strlen` 读取。 +- **返回:** 计数在前的 `size_t` 数组;无匹配、空 needle、NULL 参数或 + 分配失败时返回 `NULL`。 +- **所有权:** 调用方所有;用 `free` 释放。 +- **边界情况:** needle 中不能包含字面 NUL;被查找的缓冲区可以包含。 + +### sx_find_all_char + +```c +size_t *sx_find_all_char(const sx_t *h, char c); +``` + +收集单个字节的所有出现。 + +- **参数:** `h` —— 被查找的缓冲区;`c` —— 要查找的字节。 +- **返回:** 计数在前的 `size_t` 数组;无匹配、NULL 参数或分配失败时 + 返回 `NULL`。 +- **所有权:** 调用方所有;用 `free` 释放。 +- **边界情况:** 只搜索内容,因此 `'\0'` needle 会找到内嵌的 NUL 内容 + 字节,永远不会匹配结尾符。 + +## 比较:`sx_cmp*` + +### sx_cmp + +```c +int sx_cmp(const sx_t *h, const sx_t *other); +``` + +按内容字节对两个缓冲区做字典序比较。 + +- **参数:** `h` —— 左操作数;`other` —— 右操作数。 +- **返回:** `h` 排在 `other` 之前时返回负数,相等返回 0,排在之后返回 + 正数。只有符号有意义。 +- **所有权:** 无;不修改任一缓冲区。 +- **边界情况:** 比较按 `memcmp` 顺序逐字节进行(无符号字节值),因此 + `"10" < "2"`、`"Z" < "中"`。若较短字符串是另一方的真前缀,则它排在 + 前面(`"abc" < "abcd"`)。内嵌 NUL 字节按数据参与比较。任一操作数为 + NULL 时结果为 0(视为相等)—— 不要把该结果当作有意义的排序依据。 + +### sx_cmp_view + +```c +int sx_cmp_view(const sx_t *h, sx_view_t other); +``` + +把一个缓冲区与视图中的字节比较。 + +- **参数:** `h` —— 左操作数;`other` —— 右操作数窗口,比较其 + `other.len` 个字节。 +- **返回:** 与 `sx_cmp` 相同的负值、0 或正值。 +- **所有权:** 无;只读取。 +- **边界情况:** `h` 为 NULL 时返回 0。`other.ref == NULL` 或越界窗口 + 属于契约之外。 + +### sx_cmp_cstr + +```c +int sx_cmp_cstr(const sx_t *h, const char *s); +``` + +把一个缓冲区与 C 字符串比较。 + +- **参数:** `h` —— 左操作数;`s` —— 以 NUL 结尾的右操作数,按 + `strlen` 读取。 +- **返回:** 与 `sx_cmp` 相同的负值、0 或正值。 +- **所有权:** 无;只读取。 +- **边界情况:** `h` 或 `s` 为 NULL 时返回 0。`s` 中的内嵌 NUL 会缩短 + 参与比较的范围。 + +## 前缀与后缀判定 + +### sx_starts_with + +```c +int sx_starts_with(const sx_t *h, const sx_t *prefix); +``` + +判断 `h` 是否以另一个缓冲区的内容开头。 + +- **参数:** `h` —— 缓冲区;`prefix` —— 内容作为前缀的缓冲区。 +- **返回:** `h` 的前 `len(prefix)` 个内容字节与 prefix 逐字节相等时返回 + 1,否则返回 0。 +- **所有权:** 无;只读取。 +- **边界情况:** 空前缀总是匹配;比 `h` 更长的 prefix 永远不匹配。字节 + 精确且二进制安全。`h` 或 `prefix` 为 NULL 时返回 0。 + +### sx_starts_with_view + +```c +int sx_starts_with_view(const sx_t *h, sx_view_t prefix); +``` + +判断 `h` 是否以视图中的字节开头。 + +- **参数:** `h` —— 缓冲区;`prefix` —— 按 `prefix.len` 个字节读取的 + 窗口。 +- **返回:** 匹配时返回 1,否则返回 0。 +- **所有权:** 无;只读取。 +- **边界情况:** 空视图总是匹配。`h` 为 NULL 时返回 0;`prefix.ref == + NULL` 或越界窗口属于契约之外。 + +### sx_starts_with_cstr + +```c +int sx_starts_with_cstr(const sx_t *h, const char *prefix); +``` + +判断 `h` 是否以 C 字符串开头。 + +- **参数:** `h` —— 缓冲区;`prefix` —— 以 NUL 结尾的前缀,按 `strlen` + 读取。 +- **返回:** 匹配时返回 1,否则返回 0。 +- **所有权:** 无;只读取。 +- **边界情况:** 空字符串总是匹配;`h` 或 `prefix` 为 NULL 时返回 0。 + +### sx_ends_with + +```c +int sx_ends_with(const sx_t *h, const sx_t *suffix); +``` + +判断 `h` 是否以另一个缓冲区的内容结尾。 + +- **参数:** `h` —— 缓冲区;`suffix` —— 内容作为后缀的缓冲区。 +- **返回:** `h` 的后 `len(suffix)` 个内容字节与 suffix 逐字节相等时返回 + 1,否则返回 0。 +- **所有权:** 无;只读取。 +- **边界情况:** 空后缀总是匹配;比 `h` 更长的 suffix 永远不匹配。字节 + 精确且二进制安全。`h` 或 `suffix` 为 NULL 时返回 0。 + +### sx_ends_with_view + +```c +int sx_ends_with_view(const sx_t *h, sx_view_t suffix); +``` + +判断 `h` 是否以视图中的字节结尾。 + +- **参数:** `h` —— 缓冲区;`suffix` —— 按 `suffix.len` 个字节读取的 + 窗口。 +- **返回:** 匹配时返回 1,否则返回 0。 +- **所有权:** 无;只读取。 +- **边界情况:** 空视图总是匹配。`h` 为 NULL 时返回 0;`suffix.ref == + NULL` 或越界窗口属于契约之外。 + +### sx_ends_with_cstr + +```c +int sx_ends_with_cstr(const sx_t *h, const char *suffix); +``` + +判断 `h` 是否以 C 字符串结尾。 + +- **参数:** `h` —— 缓冲区;`suffix` —— 以 NUL 结尾的后缀,按 `strlen` + 读取。 +- **返回:** 匹配时返回 1,否则返回 0。 +- **所有权:** 无;只读取。 +- **边界情况:** 空字符串总是匹配;`h` 或 `suffix` 为 NULL 时返回 0。 + +## 分割:sx_split + +### sx_split + +```c +sx_view_t *sx_split(const sx_t *h, const char *sep); +``` + +按 C 字符串分隔符把缓冲区分割成一组 token 视图。该声明位于 `sx.h` +(进阶层),不在 `sx_core.h` 中。 + +- **参数:** `h` —— 要分割的缓冲区;`sep` —— 以 NUL 结尾的分隔符,按 + `strlen` 读取。空分隔符会被拒绝,而不是按“每个字节”处理。 +- **返回:** 一个 malloc 分配的 `sx_view_t` 数组,采用经典的 `char **` + 形态;`h` 为 NULL、`sep` 为 NULL、`sep` 为空,或分配失败时返回 + `NULL`。 +- **所有权:** 调用方拥有数组,用 `free`(而不是 `sx_free`)释放。token + 是 `h` 上的视图,绝不能单独释放。 +- **契约说明:** + - 数组恰有 `count + 1` 个元素:`arr[0] .. arr[count-1]` 是按顺序排列 + 的 token,`arr[count]` 是 `.ref == NULL` 的结束哨兵。遍历方式为 + `for (size_t i = 0; arr[i].ref != NULL; i++)`。 + - `count == 1 + (分隔符出现次数)`。分隔符从左到右非重叠匹配:命中后 + 扫描越过该分隔符继续,因此用 `"aa"` 分割 `"aaaa"` 得到三个空 token, + 而不是两个。 + - 每个位置的空字段都会保留:`"a,,b"` 得到 `"a"`、`""`、`"b"`;开头或 + 结尾的分隔符会产生空的第一个或最后一个 token;空 `h` 分割为单个空 + token `""`;内容与分隔符完全相同的字符串分割为两个空 token。 + - 空 token 不是结束哨兵:它的 `ref != NULL` 且 `len == 0`,而哨兵的 + `ref == NULL`。 + - token 是 `h` 内容的别名(`ref == h->ref`,以及 `offset`、`len`): + 调用过程中不拷贝、不修改、也不重新分配,因此内容指针按位保持不变。 + 之后对 `h` 的修改会使 token 失效;token 在使用时不要修改 `h`。 + - 匹配是字节精确的,因此 token 中可能包含内嵌的 NUL 字节(分隔符本身 + 是 C 字符串,不能包含)。打印这类 token 请使用 `fwrite` 或带长度的 + `"%.*s"`,不要使用 `"%s"`。 + +正则层的 `sx_reg_split` 返回完全相同的形态,见[正则表达式](regex.md)。 + +完整示例 —— 分割、遍历到结束哨兵,然后释放数组和缓冲区: + +```c +#include +#include +#include + +int main(void) { + sx_t *csv = sx_new_from_cstr("alpha,beta,,gamma,"); + sx_view_t *fields = sx_split(csv, ","); + + if (!fields) + return 1; + + for (size_t i = 0; fields[i].ref != NULL; i++) + printf("field %zu: \"%.*s\" (offset %zu, len %zu)\n", i, + (int)fields[i].len, sx_buf_view_mut(fields[i]), + fields[i].offset, fields[i].len); + + free(fields); /* the array, not the tokens */ + sx_free(csv); + return 0; +} +``` + +预期输出(结尾的分隔符产生一个空的最后字段): + +```text +field 0: "alpha" (offset 0, len 5) +field 1: "beta" (offset 6, len 4) +field 2: "" (offset 11, len 0) +field 3: "gamma" (offset 12, len 5) +field 4: "" (offset 18, len 0) +``` + +--- + +[← 上一页](api-buffer.md) · [文档首页](README.md) · [下一页 →](regex.md) diff --git a/docs/zh_cn/build-and-test.md b/docs/zh_cn/build-and-test.md new file mode 100644 index 0000000..60d9b13 --- /dev/null +++ b/docs/zh_cn/build-and-test.md @@ -0,0 +1,338 @@ +[English](../en_us/build-and-test.md) · 中文 + +[文档首页](README.md) › 构建、测试与打包 + +# 构建、测试与打包 + +String X 使用 [Forge](https://github.com/minelogy-dev/forge) 构建,这是一个 +构建脚本本身就是 C 程序的构建系统。本页介绍工具链要求、每个 `./make` 任务、 +测试框架与内存检查器(sanitizer)、安装、pkg-config 以及 Debian 打包。运行这些 +命令的 CI 流水线见[持续集成](ci.md)。 + +## 环境要求 + +| 依赖 | 说明 | +| --- | --- | +| Linux | CI 使用 Ubuntu 24.04;其他 Linux 发行版同样可用。 | +| C23 编译器 | GCC 14+ 或 Clang 19+。 | +| `libpcre2-dev` | PCRE2 10.46,8 位,正则层与每个测试都需要。运行时库需要 `libpcre2-8-0`。 | +| `pkg-config` | 推荐使用者安装;CI 还用它链接已安装的库。 | +| Forge | 构建工具;从源码引导安装(见下一节)。`./make` 是生成物,不纳入版本库。 | +| `tar` 与 `ar` | 只有 `./make gen_deb` 需要;`dpkg-deb` 仅用于检查产物。 | + +所有命令都在仓库根目录执行:`build.c` 与 `build.conf` 都相对于该目录读取。 + +## Forge 一分钟上手 + +Forge 把 `build.c` 编译成本地可执行文件 `./make`。这个生成文件就是构建入口: +下文每个任务都是 `build.c` 里的一个函数,以 `./make <任务>` 调用。它不是 GNU +make。只要修改了 `build.c` 或 `build.conf`,就要重新运行 `forge .`。 + +从源码引导 Forge,并把它的产物加入搜索路径: + +```sh +git clone https://github.com/minelogy-dev/forge.git +cd forge +./bootstrap.sh --no-test +export PATH="$PWD/build/output:$PATH" +export CPATH="$PWD/build/output/include" +cd /path/to/StringX +forge . +``` + +CI 将 Forge 固定到提交 +`b6826ba762a1e9e337895e01ee604b943c682d23`。若要精确复现 CI,请把该提交 +检出到 `.ci-deps/forge`,并在不安装系统文件的情况下引导它: + +```sh +git clone https://github.com/minelogy-dev/forge.git .ci-deps/forge +git -C .ci-deps/forge checkout b6826ba762a1e9e337895e01ee604b943c682d23 +sh .ci-deps/forge/bootstrap.sh --no-test +export PATH="$PWD/.ci-deps/forge/build/output:$PATH" +export CPATH="$PWD/.ci-deps/forge/build/output/include" +forge . +``` + +更换 Forge 版本时,两个工作流文件 `.github/workflows/ci.yml` 与 +`.github/workflows/codeql.yml` 中的固定提交必须保持一致。该固定点有意独立于 +Forge 的 `main` 分支,也不会被 Dependabot 更新。 + +把 Forge 加入 `PATH` 后,日常命令与 README 一致: + +```sh +forge . # 把 build.c 编译成 ./make(改动 build.c 后需重跑) +./make # 构建 -> build/output/libstringx.so(头文件随附于 build/output/include) +./make test # 编译并运行 tests/ 下每个测试(ASan + UBSan) +``` + +## 目标与命令 + +| 命令 | 作用 | +| --- | --- | +| `forge .` | 按 `build.conf` 的设置把 `build.c` 编译成本地 `./make`。 | +| `./make` | 默认的 `build` 任务:把 `src/` 编译成 `build/output/libstringx.so`,并把 `include/*.h` 同步到 `build/output/include/`。 | +| `./make check` | 用警告选项和 GCC 分析器编译库目标,但不做头文件同步。 | +| `./make test` | 在 ASan + UBSan + LSan 下构建并运行 `tests/` 下的每个文件。 | +| `./make test -j 2` | 同上,并并行编译每个测试的源文件(这里是 2 路并行)。 | +| `./make install ` | 先构建,再安装库、头文件、声明文件和 `libstringx.pc`;前缀默认为 `/usr/local`。 | +| `./make gen_deb` | 先构建,再暂存并生成 `build/deb/libstringx_<版本>_<架构>.deb`。 | + +`-v` 会让 `./make test` 与 `./make check` 打印完整的编译命令;不加时只显示 +`PASSED`/`FAILED` 行和最终汇总。`-j N` 并行执行一个目标的编译阶段。 + +产物位置如下: + +| 路径 | 由谁生成 | 内容 | +| --- | --- | --- | +| `build/output/libstringx.so` | `./make`、`./make check`、`./make install`、`./make gen_deb` | 共享库 | +| `build/output/include/` | `./make`、`./make install`、`./make gen_deb` | `sx.h`、`sx_core.h`、`sx_raw.h` 的同步副本 | +| `build/exe-obj/` | `./make`、`./make check` | 各源文件的目标文件及其 `.d`/`.meta` 增量信息 | +| `test/<名称>` | `./make test` | 每个测试文件一个可执行文件(`tests/new.c` → `test/new`) | +| `build/opt/` | `./make test` | 测试目标文件及其 `.d`/`.meta` 文件 | +| `build/deb/` | `./make gen_deb` | Debian 暂存目录与最终 `.deb` | + +`./make test` 不需要先运行 `./make`:每个测试都直接编译库源码。 + +## build.conf + +`build.conf` 在 Forge 生成 `./make` 时读取;每个 `KEY=VALUE` 行都会变成构建脚本 +的 `-DCONF_KEY=VALUE` 宏。以 `#` 开头的行是注释。修改后需要重新运行 `forge .`。 + +| 键 | 取值 | 作用 | +| --- | --- | --- | +| `compiler` | `GCC` 或 `CLANG` | 工具链后端。`build.c` 把 `CONF_compiler` 传给 `set_toolchain`,因此它同时决定库与测试使用的编译器。 | +| `compiler_path` | 绝对路径,例如 `/usr/bin/gcc` | Forge 编译生成的 `./make` 时使用的编译器二进制文件。 | +| `version` | `v0.5` | 项目版本的唯一来源。`build.c` 把它字符串化为 `SX_VERSION`;安装与打包会去掉开头的 `v`。 | +| `sanitize` | `1` | CI 中由 `.github/scripts/configure.sh` 追加。内存检查器选项本身由每个测试在头部 DSL 中声明。 | + +## 运行测试 + +`./make test` 递归扫描 `tests/`,把每个 `tests/*.c` 编译成 `test/<名称>` 并 +运行。测试成功时打印 `PASSED: <文件>`,第一个断言失败时打印 +`FAILED: <文件>:<行号>: <表达式>`。任务结束时输出类似下面的汇总: + +```text +forge: 20 tests, 20 passed, 0 failed +``` + +只要有测试编译或运行失败,任务就以非零状态退出。 + +测试不链接 `libstringx.so`:每个测试直接编译库源码,并在自己的头部声明选项, +包括 `-fsanitize=address,undefined` 与 `-fno-omit-frame-pointer`。LeakSanitizer +与 ASan 一起运行,因此测试若忘记释放缓冲区或返回的数组就会失败。 + +请设置与 CI 相同的内存检查器选项: + +```sh +export ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 +export UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 +./make test -j 2 +``` + +单独重跑某个已构建的测试: + +```sh +./test/reserve_stress +``` + +### 精确预留压力测试 + +`tests/reserve_stress.c` 是 `-DSX_FORCE_EXACT_RESERVE` 的专用配置,该宏在其 +头部以 `// Option -DSX_FORCE_EXACT_RESERVE` 声明。这个开关把 +`src/sx_raw.c` 内部的预留辅助函数从几何增长改为精确分配 +(`cap == need + 1`),于是分配正好在结尾符处结束,任何越过 `len` 的访问都会 +立刻命中 ASan 的红区——多余的容量无法掩盖差一错误或过期的长度。测试用确定性 +的 LCG 驱动三个活动缓冲区,并在每次修改后断言完整内容;其模型不超过 512 字节。 +其余所有测试都在默认的几何增长模式下构建。 + +## 测试文件与头部 DSL + +每个测试都是自包含程序。文件开头连续若干行 `//` 构成 Forge 测试运行器读取的 +头部 DSL;遇到第一行非 `//` 的内容时头部结束。 + +| 条目 | 作用 | +| --- | --- | +| `// Include <目录>` | 添加 `-I<目录>`。每个测试都包含 `include`、`src` 和 `/usr/lib/forge/include` —— 最后一项是 `` 所需的 Forge 头文件;若通过 `CPATH` 提供,这一项也无害。 | +| `// Source <文件>` | 把一个源文件加入测试可执行文件。测试都会加入 `src/sx_raw.c`、`src/sx_core.c` 与 `src/sx_adv.c`。 | +| `// Link <库>` | 添加 `-l<库>`。只有 `tests/reg.c` 加入 `pcre2-8`;其他测试不使用正则层。 | +| `// Library <目录>` | 添加 `-L<目录>`。测试加入 `/usr/local/lib`。 | +| `// Option <选项>` | 添加编译器、链接器与汇编器选项。测试使用 `-std=c23 -O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer`,以及诸如 `-DSX_FORCE_EXACT_RESERVE` 的测试专用宏。 | + +不带关键字的行会延续当前作用域(初始为 `Source`);测试为了清晰都写出了每个 +关键字。 + +由于每个测试都会编译 `src/sx_adv.c`,`build.c` 通过其保留的 `LANGUAGE` +覆盖项为每个测试目标附加 `pcre2-8`;`tests/reg.c` 还显式声明了 +`// Link pcre2-8`。 + +程序本身包含被测头文件(`"sx.h"`,仅测核心层时用 `"sx_core.h"`)以及提供两个 +测试宏的 ``: + +| 宏 | 作用 | +| --- | --- | +| `TEST(表达式)` | 失败时打印 `FAILED: <文件>:<行号>: <表达式>` 并以 1 退出;成功时不输出并继续。 | +| `PASS()` | 打印 `PASSED: <文件>`;在 `main` 末尾调用。 | + +### 添加测试 + +1. 创建 `tests/<名称>.c` —— 每个文件只覆盖一个行为领域。 +2. 从现有测试复制头部 DSL 块,并按所需依赖调整 `Source`、`Link` 与 `Option`。 +3. 在文件顶部写明行为边界:测试锁定了什么(`In scope (contract)`),以及 + 有意不覆盖什么(`Out of contract (not exercised)`)。 +4. 包含被测头文件,用 `TEST` 断言,释放每个缓冲区与返回的数组,最后以 + `PASS()` 结束。 +5. 运行 `./make test`。新文件会被自动发现。 + +```c +// Include include +// Include src +// Include /usr/lib/forge/include +// Source src/sx_raw.c +// Source src/sx_core.c +// Source src/sx_adv.c +// Option -std=c23 +// Option -O1 +// Option -g +// Option -fsanitize=address,undefined +// Option -fno-omit-frame-pointer +// Library /usr/local/lib +#include "sx.h" +#include + +/* + * Behavior boundaries — sx_erase (example) + * =================================================================== + * In scope (contract): + * · sx_erase(h, idx, n) removes the n bytes starting at idx, + * shifts the tail left, keeps ptr[len] == '\0', and returns h. + * n == 0 is a no-op; idx + n > len is a no-op returning h. + * Out of contract (not exercised): + * · h == NULL or freed; erase idx > len with n such that idx + n + * wraps; keeping sx_buf_mut pointers across edits. + */ + +int main(void) { + sx_t *h = sx_new_from_cstr("hello"); + TEST(h != NULL); + TEST(sx_erase(h, 1, 3) == h); + TEST(sx_cmp_cstr(h, "ho") == 0); + sx_free(h); + PASS(); + return 0; +} +``` + +## 安装 + +`./make install` 会先构建(包括头文件同步),然后复制: + +| 目标位置 | 内容 | +| --- | --- | +| `/lib/libstringx.so` | 共享库 | +| `/include/sx.h` | 公开 API 头文件 | +| `/include/sx_core.h` | 被 `sx.h` 包含的核心层 | +| `/include/sx_raw.h` | 内部内存分配头文件;不属于受支持的 API | +| `/lib/pkgconfig/libstringx.pc` | pkg-config 元数据 | +| `/share/doc/libstringx/LICENSE` | MIT 许可全文 | +| `/share/doc/libstringx/THIRD_PARTY_NOTICES.md` | PCRE2 归属与许可全文 | +| `/share/doc/libstringx/copyright` | `LICENSE` 的副本,Debian 惯用文件名 | + +默认前缀为 `/usr/local`。可以传入一个无需 root 即可写入的前缀,例如: + +```sh +./make install "$HOME/.local" +``` + +pkg-config 文件在安装时生成。它的 `prefix=` 就是安装前缀,`Version` 是 +`build.conf` 版本去掉开头的 `v`(即 `0.5`)。 + +## 使用已安装的库 + +使用 pkg-config: + +```sh +cc -std=c23 hello.c $(pkg-config --cflags --libs libstringx) -o hello +./hello +``` + +不使用 pkg-config: + +```sh +cc -std=c23 hello.c -I/include -L/lib -lstringx -o hello +``` + +对于非标准前缀,让 pkg-config 与运行期加载器指向它,或者写入 rpath: + +```sh +export PKG_CONFIG_PATH="/lib/pkgconfig" +cc -std=c23 hello.c $(pkg-config --cflags --libs libstringx) \ + -Wl,-rpath,"/lib" -o hello +``` + +库自身已链接 `pcre2-8`,使用者无需 `-lpcre2-8`。完整程序如下: + +```c +#include +#include + +int main(void) { + sx_t *h = sx_new_from_cstr("hello, world"); + if (h == NULL) + return 1; + printf("len=%d cap=%d: %.*s\n", sx_len(h), sx_cap(h), sx_len(h), + sx_buf_mut(h)); + sx_free(h); + return 0; +} +``` + +## Debian 包 + +`./make gen_deb` 会先构建,然后用 `tar` 与 `ar` 暂存并打包出 Debian `.deb` +(不依赖 `dpkg-deb`): + +| 路径 | 内容 | +| --- | --- | +| `build/deb/data/usr/` | 位于 FHS 根下的包数据树:`lib/`、`include/` 与 `share/doc/libstringx/` | +| `build/deb/control-dir/control` | 包元数据 | +| `build/deb/debian-binary`、`control.tar.gz`、`data.tar.gz` | 包的各组成部分 | +| `build/deb/libstringx_<版本>_<架构>.deb` | 最终包 | + +版本取自 `build.conf` 并去掉开头的 `v`;架构取自 `uname -m` +(`x86_64` → `amd64`,`aarch64` → `arm64`,其他值保持不变)。包装到 `/usr` +下,并声明 `Depends: libc6, libpcre2-8-0`。包内的 `libstringx.pc` 以 `/usr` +作为前缀,暂存路径不会写进去。 + +检查并安装: + +```sh +dpkg-deb --info build/deb/libstringx_*.deb +dpkg-deb --contents build/deb/libstringx_*.deb +sudo apt install ./build/deb/libstringx_*.deb +``` + +## 故障排查 + +| 现象 | 原因与处理 | +| --- | --- | +| `forge: command not found` | Forge 不在 `PATH` 中。引导它并导出 `PATH=/build/output`。 | +| `build.h: No such file or directory` | Forge 的构建脚本头文件不可见。像 CI 那样导出 `CPATH=/build/output/include`,或系统级安装 Forge。`` 只存在于 Forge 构建环境中。 | +| `pcre2.h: No such file or directory` 或 `cannot find -lpcre2-8` | 安装 `libpcre2-dev`(Ubuntu:`sudo apt-get install libpcre2-dev`)。 | +| 克隆后出现 `./make: No such file or directory` | `./make` 是生成物且被 gitignore。先运行 `forge .`。 | +| 修改 `build.c` 或 `build.conf` 后没有生效 | `./make` 由旧脚本生成。重新运行 `forge .`。 | +| Clang 下测试链接因 `-flto` 失败 | 固定的 Forge 在并行 Clang 链接时会输出仅适用于 GCC 的 `-flto=N`,因此 `build.c` 中的测试目标特意关闭 LTO;生产目标保留 LTO。用 Clang 运行测试套件时请保持测试关闭 LTO。 | +| `install` 报告权限错误 | 前缀不可写。传入你有权限的前缀,例如 `./make install "$HOME/.local"`。 | +| 测试因泄漏报告失败 | 有缓冲区或数组未释放。每个 `sx_t` 都要用 `sx_free` 释放,每个返回的数组都要用 `free` 释放。 | +| 使用者程序找不到 `libstringx.so` | 把 `LD_LIBRARY_PATH` 设为 `/lib`,用 `-Wl,-rpath,/lib` 链接,或安装到标准前缀。 | + +不要在库源码或应用程序中包含 ``:它是 Forge 的构建脚本 DSL 头文件, +不属于 String X API。应用程序只包含 ``。 + +## 持续集成 + +在每次推送与拉取请求上运行这些命令的工作流——构建矩阵、分析器、质量检查、 +CodeQL 与合并保护——见[持续集成](ci.md)。 + +--- + +[← 上一页](design.md) · [文档首页](README.md) · [下一页 →](contributing.md) diff --git a/docs/zh_cn/ci.md b/docs/zh_cn/ci.md new file mode 100644 index 0000000..dc5e1fb --- /dev/null +++ b/docs/zh_cn/ci.md @@ -0,0 +1,123 @@ +[English](../en_us/ci.md) · 中文 + +[文档首页](README.md) › 持续集成 + +# 持续集成 + +对 `main` 的改动、拉取请求以及手动运行都使用 GitHub Actions。本页说明每个 +工作流验证什么、如何在本地复现这些检查,以及合并保护如何把它们串起来。命令本身 +——Forge 引导、`./make` 目标、测试框架——见[构建、测试与打包](build-and-test.md)。 + +## 触发条件 + +| 事件 | 工作流 | +| --- | --- | +| 推送到 `main` | [ci.yml](../../.github/workflows/ci.yml) 与 [codeql.yml](../../.github/workflows/codeql.yml) | +| 任意分支上的 `pull_request` | `ci.yml` 与 `codeql.yml` | +| `workflow_dispatch`(手动运行) | `ci.yml` 与 `codeql.yml` | +| `schedule` | 仅 `codeql.yml`(每周) | + +工作流对仓库只有只读访问权限,唯一例外是 CodeQL 任务发布代码扫描结果所需的权限。 +拉取请求中的代码绝不会通过 `pull_request_target` 运行,且不保留检出凭据。 + +## 检查项 + +| 检查 | 验证内容 | +| --- | --- | +| 构建与测试(gcc-14 / clang-19) | 在 Ubuntu 24.04 上用 GCC 14 与 Clang 19 做真实构建,运行完整测试套件、ASan、UBSan 与泄漏检测 | +| 编译器警告 | 每个生产 C 翻译单元都以 `-Wall -Wextra -Werror` 编译通过 | +| GCC 静态分析 | 用 `-fanalyzer` 检查生产翻译单元;出现诊断即令任务失败 | +| 工作流与密钥检查 | 对完整 Git 历史运行 Actionlint、ShellCheck、空白错误检查与 Gitleaks,输出中的密钥已脱敏 | +| CodeQL(C/C++) | 手动构建追踪,使用 `security-and-quality` 查询;发现显示在 Security 页与拉取请求中 | +| CI | 稳定的必需检查:任何构建、分析或质量任务失败或被取消时它都会失败 | + +GCC 分析使用 `-O1 -fno-analyzer-state-merge`:GCC 14 默认的状态合并会在这份 +代码上产生虚假的分配/清理诊断。没有屏蔽任何诊断类别。分析器失败应当被调查, +而不是用 `continue-on-error` 绕过。 + +所有外部 Action 都固定到不可变的提交 SHA。Dependabot 每周提出 GitHub Actions +更新。Actionlint 与 Gitleaks CLI 的版本和 SHA-256 校验和固定在 +[.github/scripts/install-tools.sh](../../.github/scripts/install-tools.sh) 中; +升级它们时要同时更新这两处值。 + +## CodeQL + +CodeQL 面向 C/C++ 配置,使用手动构建追踪与 `security-and-quality` 查询集。 +它分析由固定的 Forge 工具链构建出的代码,把发现发布到 Security 页,并在拉取 +请求中报告。 + +CodeQL 还会在每周一 11:17 Asia/Shanghai(03:17 UTC)运行。任务状态为成功只表示 +分析完成,**并不**表示没有告警。请用代码扫描合并规则来强制告警级别——见 +[启用合并保护](#启用合并保护)。 + +## 启用合并保护 + +仅靠工作流文件无法启用分支保护;这些仓库设置是维护者的一次性配置。首次成功 +运行后,为 `main` 创建分支规则集: + +1. 要求拉取请求,且 `CI` 与 `CodeQL (C/C++)` 状态检查通过。 +2. 要求分支在合并前保持最新。 +3. 添加“Require code scanning results”,选择 CodeQL,并阻止高危/严重安全告警 + 与错误级质量告警。在分诊现有发现后可以收紧这些阈值。 +4. 使用仓库中检入的高级 CodeQL 工作流,而不要启用重复的默认设置扫描。 + +CI 权限、检查项与依赖固定点的改动仍然值得人工评审。 + +## 本地复现 + +安装 Linux 构建依赖与 C23 编译器(GCC 14+ 或 Clang 19+)。运行 `configure.sh` +前请保存本地 `build.conf` 修改:它会更新编译器选择,并在该文件中追加 +`sanitize=1`。 + +```sh +CC=gcc bash .github/scripts/configure.sh # 或 CC=clang +CC=gcc bash .github/scripts/check-c.sh +CC=gcc bash .github/scripts/check-c.sh analyze +``` + +`analyze` 请使用 GCC。运行时检查需设置: + +```sh +export ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 +export UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 +``` + +构建依赖是 Forge 提交 +`b6826ba762a1e9e337895e01ee604b943c682d23`:CI 把它检出到 `.ci-deps/forge`, +并在不安装系统文件的情况下引导。PCRE2 来自 Ubuntu 的 `libpcre2-dev` 包。 + +本地有已引导的 Forge 检出时: + +```sh +export PATH="/path/to/forge/build/output:$PATH" +export CPATH="/path/to/forge/build/output/include" +forge . +./make +./make test -j 2 +``` + +CI 还会安装到临时前缀,用 `pkg-config` 把现有正则测试编译并链接到**已安装的 +共享库**后运行,并检查生成的 Debian 包。这样除源码级行为外,还验证了公开头文件、 +导出符号、包元数据与 PCRE2 链接。对应命令在 `ci.yml` 中;它们使用的布局记录在 +[构建、测试与打包](build-and-test.md)。 + +## 固定的 Forge 提交 + +两个工作流文件都把 Forge 固定到提交 +`b6826ba762a1e9e337895e01ee604b943c682d23`,检出到 `.ci-deps/forge`,并用 +`sh .ci-deps/forge/bootstrap.sh --no-test` 在不安装系统文件的情况下引导。更换 +Forge 版本时,必须在**两个**工作流文件中更新这个经过评审的固定点。它有意独立于 +Forge 不断变动的 `main` 分支,也不会被 Dependabot 更新。 + +## 评审与失败处理 + +打开失败的检查,查看编译器诊断、内存检查器堆栈或密钥扫描位置。构建失败会保留 +依赖与命令元数据七天;Actions 日志包含完整的构建/测试输出。CodeQL 告警会附带 +受影响的代码行,并在可用时给出数据流。 + +自动化覆盖机械性回归和许多常见的内存安全缺陷。人工评审应集中在需求、API 契约、 +所有权、架构以及这些工具报告的问题上。 + +--- + +[← 上一页](contributing.md) · [文档首页](README.md) diff --git a/docs/zh_cn/contributing.md b/docs/zh_cn/contributing.md new file mode 100644 index 0000000..b48a9f1 --- /dev/null +++ b/docs/zh_cn/contributing.md @@ -0,0 +1,131 @@ +[English](../en_us/contributing.md) · 中文 + +[文档首页](README.md) › 贡献指南 + +# 贡献指南 + +String X 是一个契约写得很细的小型 C23 库,因此改动越小、测试与文档越同步, +评审就越容易,也越容易通过 CI 运行的同一套检查。本页说明工作流程与项目约定。 + +## 工作流程 + +1. Fork 仓库,并从 `main` 创建分支。分支名应体现改动内容 + (`fix/split-end-guard`、`docs/build-targets`)。 +2. 完成改动,包括行为测试,以及英文和中文文档的更新。 +3. 提交拉取请求前先在本地运行检查: + + ```sh + ./make test -j 2 + bash .github/scripts/check-c.sh + bash .github/scripts/check-c.sh analyze # 仅 GCC + ``` + +4. 向 `main` 提交拉取请求,说明行为变化、覆盖它的测试,以及更新了哪些文档页。 +5. 等待必需检查通过。`main` 的合并保护要求 `CI` 与 `CodeQL (C/C++)` 状态检查 + 通过且分支保持最新。检查内容见[持续集成](ci.md)。 +6. 通过追加提交来回应评审意见;让拉取请求始终聚焦于一个改动。 + +`bash .github/scripts/configure.sh` 可以复现 CI 的编译器选择,但它会重写 +`build.conf` 中的 `compiler=`、`compiler_path=` 与 `sanitize=`,因此请先保存 +该文件的本地修改。 + +## 契约优先的文档规则 + +行为边界记录在两个地方: + +- 公开头文件 `include/sx.h` 与 `include/sx_core.h` 中的注释; +- 每个 `tests/*.c` 顶部的 `Behavior boundaries` 注释,其中列出 + `In scope (contract)` 与 `Out of contract (not exercised)`。 + +任何可观察行为的变化都必须同时更新: + +1. 受影响函数的头文件注释; +2. 测试实现及其行为边界注释; +3. `docs/en_us/` 与 `docs/zh_cn/` 下的英文和中文页面。 + +不要把行为留成未文档化,或仍按旧行为描述。若不同来源互相矛盾,运行时行为以 +测试为准,函数签名以头文件为准,构建与打包行为以 `build.c` 为准——遇到真正的 +矛盾应报告,而不是悄悄选择其中一个。 + +## 代码风格 + +- C23;库与测试都以 `-std=c23` 构建。 +- 两空格缩进;左花括号与语句同行。 +- 遵循现有命名与分层:核心函数放在 `src/sx_core.c`,正则进阶层放在 + `src/sx_adv.c`,内部内存分配放在 `src/sx_raw.c`。不要在 + `sx.h`/`sx_core.h` 之外新增公开函数。 +- 偏移与长度使用 `size_t`,并沿用现有的哨兵约定(`(size_t)-1`、`ref == NULL` + 的视图、NULL 数组)。 +- 把警告当作错误。`./make check` 目标使用 `-Wall -Wextra -Wpedantic -Werror` + 编译库,GCC 构建还会加上 `-fanalyzer`;CI 的直接编译检查使用 + `-std=c23 -O1 -Wall -Wextra -Werror`。不要为了让构建通过而屏蔽诊断信息; + 应修正代码,或在评审中解释分析器的发现。 + +## 测试 + +每个行为改动都需要测试。测试是 `tests/` 下自包含的程序,直接编译库源码,并在 +头部 DSL(`// Include`、`// Source`、`// Link`、`// Library`、`// Option`)中 +声明依赖。DSL 与完整示例见[构建、测试与打包](build-and-test.md)。 + +新增或修改测试时: + +- 保持 `Behavior boundaries` 注释准确——它是测试实际执行的书面契约,包括 + `Out of contract (not exercised)` 列表; +- 断言可观察的结果(精确字节、长度、偏移与哨兵),而不只是调用返回了非 NULL; +- 每个缓冲区都用 `sx_free` 释放,每个返回的数组都用 `free` 释放;测试套件在 + AddressSanitizer、UBSan 与 LeakSanitizer 下运行,泄漏或越界访问都会导致 + 测试失败; +- 在测试头部保留内存检查器选项与 `-fno-omit-frame-pointer`,使测试在本地与 + CI 中运行方式一致; +- 若改动了内存分配或扩容,请运行 `tests/reserve_stress.c` 的精确预留配置 + (`-DSX_FORCE_EXACT_RESERVE`),它能暴露被多余容量掩盖的越界访问。 + +用与 CI 相同的环境运行测试套件: + +```sh +export ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 +export UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 +./make test -j 2 +``` + +## 提交与拉取请求 + +- 每次提交只做一个逻辑改动,保持差异聚焦;避免无关的重新格式化与顺手修改。 +- 提交标题用简短祈使句,正文说明为什么需要该改动,以及它影响哪些行为边界或 + 文档。若有关联 issue 请注明。 +- 代码、测试与两种语言的文档放在同一个拉取请求中。 +- 不要把构建产物放进差异:`build/`、`test/`、`./make` 与 `.ci-deps/` 都是 + 生成物且被 gitignore。 +- 必需检查通过、评审意见全部解决后,拉取请求才可合并。 + +## 许可与归属 + +- 库与项目源码使用 MIT 许可。新增的 C 源码与头文件应以 + `// SPDX-License-Identifier: MIT` 开头,就像 `include/sx.h`、`src/sx_adv.c` + 与 `tests/reg.c` 那样;已有的 SPDX 标注请勿改动。 +- 构建脚本以及源自 Forge 的 `src/export.h` 适用 Forge 的构建脚本例外条款, + 标识为 `GPL-3.0-or-later WITH LicenseRef-Forge-BuildScript-Exception`。 + `build.conf` 与 `src/export.h` 已带有该标识,`build.c` 同样适用该例外; + 不要把这部分构建工具改为 MIT,也不要删除这些标注。 +- 正则层使用 PCRE2(BSD-3-Clause)。其归属与许可全文位于 + [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md)。若新增第三方依赖, + 也要在该文件中补充它的声明与许可。 +- 项目许可全文见 [LICENSE](../../LICENSE)。 + +## 目录结构 + +| 路径 | 内容 | +| --- | --- | +| [include/](../../include) | 公开头文件:`sx.h`(进阶层与 `sx_split`)以及它包含的 `sx_core.h` | +| [src/](../../src) | 实现:`sx_core.c`、`sx_adv.c`、`sx_raw.c`,以及内部 `_sx.h` 与 `export.h` | +| [tests/](../../tests) | 自包含的测试套件 | +| [build.c](../../build.c)、[build.conf](../../build.conf) | Forge 构建脚本及其配置 | +| [.github/workflows/](../../.github/workflows) | CI 与 CodeQL 工作流 | +| [.github/scripts/](../../.github/scripts) | CI 使用的编译、分析与工具检查脚本 | +| [docs/](../) | 本文档,含英文与简体中文 | +| [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md) | 第三方许可与归属 | +| [README.md](../../README.md) | 项目概览与快速上手 | + +--- + +[← 上一页](build-and-test.md) · [文档首页](README.md) · [下一页 →](ci.md) diff --git a/docs/zh_cn/design.md b/docs/zh_cn/design.md new file mode 100644 index 0000000..4eff00a --- /dev/null +++ b/docs/zh_cn/design.md @@ -0,0 +1,675 @@ +[English](../en_us/design.md) · 中文 + +[文档首页](README.md) › 设计与内部实现 + +# 设计与内部实现 + +本页面向贡献者,以及需要推敲库的保证或进行移植的读者。它描述数据布局、 +算法、所有权模型,以及 `` 公开契约背后的取舍。契约本身记录在 +[缓冲区与视图 API 参考](api-buffer.md)、[查找 API 参考](api-search.md) +和[正则表达式](regex.md)页面中。 + +## 目标与非目标 + +整个设计源自一组简短的目标: + +- **字节精确的契约。** 每个操作都定义在字节上,其行为边界都写明。查找、 + 比较和正则都按长度工作,因此内嵌 NUL 字节是普通数据。 +- **零拷贝访问。** 切片是别名到缓冲区的 `sx_view_t` 值;查看或遍历子切片 + 不拷贝任何东西。 +- **每个缓冲区一个稳定句柄。** 一个 `sx_t *` 在其整个生命周期内标识该 + 缓冲区;修改函数返回 `self`,因此即使底层数组被重新分配,调用也能串联 + 起来。 +- **可预测的失败。** 文档化的非法输入会产生固定哨兵,而不是崩溃;超出 + 文档边界的输入属于契约之外。没有异常、错误码或全局错误状态。 +- **小接口面。** 一个公开头文件 ``、一个库、一个可选的由库自身链接 + 的高级依赖(PCRE2)。 + +同样刻意设定的非目标: + +- **不提供文本编码层。** 库不解码 UTF-8、不做文本规范化,也不提供字符/ + 字素操作。字符串就是字节;正则层运行在 PCRE2 的 8 位非 UTF 模式。 +- **不感知 locale。** 比较、裁剪和字符类都定义在字节与固定 ASCII 集合上, + 与 `LC_*` 无关。 +- **缓冲区不是线程安全的。** 已编译正则是不可变且可共享的;可变缓冲区 + 就是普通内存,需要外部同步。 +- **不支持自定义分配器、rope/流式结构或惰性视图。** 每个缓冲区都是一块 + 连续分配。 +- **不自带正则引擎。** 模式语义属于 PCRE2;库只提供生命周期、扫描和替换 + 这些管线。 + +## 分层与头文件 + +### 头文件一览 + +| 头文件 | 层 | 内容 | 受众 | +| --- | --- | --- | --- | +| `include/sx_core.h` | 核心层 | `sx_t`、`sx_view_t`、缓冲区/视图/修改/查找/比较原型 | 公开;被 `` 包含 | +| `include/sx.h` | 高级层 | 包含 `sx_core.h`;声明 `sx_split` 和 `sx_reg_*` | 公开入口 | +| `include/sx_raw.h` | 内部 | 不透明 `_sx` 以及原始分配辅助函数 | 不受支持 | +| `src/_sx.h` | 内部 | `struct _sx` 的定义 | 仅库内部 | +| `src/export.h` | Forge 派生 | `SYMBOL_PUBLIC` 可见性宏(已入库) | 仅库内部 | + +使用者包含 ``。`sx_core.h` 之所以是公开的,是因为 `` 包含 +它,但它不是第二个入口:`sx_split` 和正则层只在 `sx.h` 中声明。 + +实现与头文件的分层相对应: + +| 翻译单元 | 实现内容 | +| --- | --- | +| `src/sx_core.c` | 缓冲区、视图、修改、查找、比较 | +| `src/sx_raw.c` | 分配原语(`sx__new`、`sx__reserve` 等) | +| `src/sx_adv.c` | `sx_split` 与 PCRE2 封装 | + +三个库翻译单元都直接使用私有的 `_sx` 布局;客户端代码只消费 `sx.h` 和 +`sx_core.h`。 + +### 为什么 sx_split 位于高级层 + +`sx_split` 在 `sx.h` 中、包含 `sx_core.h` 之后声明,并在 +`src/sx_adv.c` 中实现。这一位置是有意为之: + +- 它返回 `malloc` 分配的视图数组,迭代约定与 `sx_reg_match_all`、 + `sx_reg_split` 相同:token 按顺序排列,随后是一个 `.ref == NULL` 的 + 结束哨兵,调用方用 `free()` 释放数组。把返回数组的视图 API 放在一起, + 可以让这套所有权约定集中在一处,而不必给核心层增加一个分配数组的 API。 +- `sx_split` 的扫描是自包含的。核心的查找原语是 `sx_core.c` 内部 + `static` 的 KMP 实现;高级层无法调用它,也不需要调用,因为分割扫描 + 本来就被输出规模所约束。源码注释直接说明了这一取舍:`O(n*m)` 的 + 字节精确扫描"对高级层来说足够,并且让这个翻译单元保持独立"。 +- 分割扫描不依赖 PCRE2:它只是普通的分隔符查找。它位于高级层的翻译单元 + 中,是按 API 形态归类,而不是按依赖归类。 + +### 为什么 sx_raw.h 是内部头文件 + +`include/sx_raw.h` 暴露私有分配层: + +```c +typedef struct _sx _sx; + +_sx *sx__new(size_t cap); +_sx *sx__dup(const _sx *src); +int sx__reserve(_sx *s, size_t need); +void sx__free(_sx *s); +``` + +它属于内部有三个原因: + +- 它交出 `_sx`——私有缓冲区结构,而 `sx_core.h` 只对其做前置声明; +- 它的函数用保留的双下划线前缀命名,并绕开公开错误模型 + (`sx__reserve` 返回 `int`,而公开 API 返回哨兵 `sx_t *`)——它们服务 + 于库自己的翻译单元,而不是客户端; +- 它不提供稳定性承诺。安装后的头文件集合包含它,是因为 Forge 会复制 + 整个 `include/*.h`(构建脚本同步整个目录),但它不属于受支持的公开 + API,客户端代码不得使用。四个 `sx__*` 辅助函数声明为 `SYMBOL_PUBLIC`, + 因此确实会出现在共享库的动态符号表中;但这种导出并不代表它们属于受支持 + 的 API。 + +## 缓冲区布局与不变式 + +公开的 `sx_t` 是一个只有单个字段的句柄,指向私有的 `_sx`: + +```text +sx_t (public handle) _sx (private) ++------------+ +------------+ +| ref | -------------> | ptr | ----> one allocation of cap bytes ++------------+ | len | [ H e l l o \0 ? ? ... ] + | cap | + +------------+ + +content: bytes [0, len) terminator: ptr[len] == '\0' +capacity: bytes [0, cap) invariant: len + 1 <= cap, cap >= 1 +``` + +视图是一个值,而不是一次分配: + +```text +sx_view_t v = { ref = h->ref, offset = 2, len = 3 } + +buffer: a b c d e f \0 view covers c d e + ^ ^ + v.offset v.offset + v.len +``` + +每个函数都保持以下不变式: + +1. 对每个存活缓冲区都有 `ptr != NULL` 且 `cap >= 1`。 +2. `len + 1 <= cap`:始终留出结尾符的位置。 +3. 始终有 `ptr[len] == '\0'`。内容字节本身可以是 `'\0'`;结尾符是内容 + 之后的第一个 NUL。 +4. `len` 计的是内容字节数,不含结尾符。`sx_len` 以 `int` 返回它(见 + [整数访问器](#整数访问器与-size_max))。 +5. 库返回的视图满足 `ref = buffer.ref` 且 `offset + len <= buffer len`。 + API 不校验调用方自行构造的视图;边界超出所属缓冲区的视图属于契约之外。 +6. `sx_t *` 句柄地址在缓冲区生命期内稳定。`sx_buf_mut` 返回的 `ptr` + 在增长时**不**稳定:`realloc` 可能移动它。 +7. `[len, cap)` 区间的字节未指定:它们可能是陈旧内容,也可能是从未初始化 + 的内存。只有 `ptr[len]` 属于契约的一部分。 + +不变式是结构性保证的:每个修改函数结尾都会执行 `ptr[len] = '\0'`,而 +`sx__reserve` 是唯一改变 `cap` 或 `ptr` 的地方。`sx_buf_mut` 允许调用方 +重写 `[0, len)` 而不改变 `len`;由于结尾符位于该区间之外,不变式仍然 +成立。 + +## 分配与增长 + +### 初始容量 + +每个缓冲区都是 `sx__new(cap)` 的一次分配:它分配 `_sx` 头和 `cap` 字节 +的数组(最少按 1 处理,好让 `ptr[0]` 有落脚处)。各构造函数的 `cap` +选择如下: + +| 构造函数 | 初始 `cap` | 最大内容字节数 | +| --- | --- | --- | +| `sx_new()` | 32 | 31 | +| `sx_new_with_cap(n)` | `n`;`n == 0` 时为 1 | `n - 1`(`n <= 1` 时为 0) | +| `sx_new_from_cstr(s)` | `strlen(s) + 1` | `strlen(s)` | +| `sx_new_from_view(v)` | `v.len + 1` | `v.len` | +| `sx_dup(src)` | `src->len + 1` | `src->len` | +| `sx_substr(h, idx, n)` | `n + 1` | `n` | + +`sx_new()` 经由 `sx_new_with_cap(32)` 实现;32 字节的起点让最初几次追加 +不产生分配,同时不会浪费太多内存。从内容构造的构造函数精确分配 +`内容长度 + 1`,因此新建或拷贝出来的缓冲区容量是紧的。 + +### 增长策略 + +所有增长都经过 `sx__reserve(_sx *s, size_t need)`,它把 `need` 解释为 +调用方此后必须能够容纳的**内容字节数**。内部必须产生 `cap > need`, +即为 `need` 个字节加上结尾符留出空间。决策如下: + +| 情况 | 新的 `cap` | +| --- | --- | +| `cap > need` | 不变(空操作) | +| `need == SIZE_MAX` | 拒绝(整数溢出保护) | +| 默认,`cap < 0x10000` | `max(cap * 2, need + 1)` | +| 默认,`cap >= 0x10000` | `max(cap + 0x10000, need + 1)` | +| `-DSX_FORCE_EXACT_RESERVE` | `need + 1` | + +默认策略在分配小于 64 KiB 时按几何级数翻倍,此后改为固定的 +`+0x10000` 步进。翻倍使每个追加字节的代价摊还为常数;固定步进则避免 +仅仅为了追加几个字节就把大块分配(例如 8 MiB)翻倍到 16 MiB。与 +`need + 1` 取 `max` 覆盖了单次调用需要超过下一个几何步长的情况。 + +公开的 `sx_reserve(self, n)` 原样转发 `n`,因此保证 `cap >= n + 1`: +调用之后,缓冲区总共能容纳 `n` 个内容字节而无需再次重新分配。 +`sx_append`、`sx_write` 和 `sx_insert` 在拷贝前调用 +`sx__reserve(最终内容长度)`: + +- append:`need = len + 追加长度`; +- write:`need = idx + 写入长度`;此后的 `len` 为 `max(len, idx + n)`; +- insert:`need = len + 插入长度`;尾部用 `memmove` 后移。 + +增长是单调的。收缩操作从不重新分配:`sx_truncate` 只在新长度更大时才 +预留,`sx_erase` 在既有分配内部移动字节,`sx_clear` 只重写 `ptr[0]`。 +精确预留测试对这两个性质都有断言(`tests/reserve_stress.c`)。 + +### SX_FORCE_EXACT_RESERVE + +`-DSX_FORCE_EXACT_RESERVE` 用 `cap = need + 1` 取代增长策略。此时分配 +正好在结尾符处结束,因此任何越过 `len` 的访问都会立刻落入 +AddressSanitizer 的红区,而不是藏在多余的容量后面。代价是每次增长都 +重新分配(逐字节追加的工作负载在拷贝次数上接近平方级),并且没有余量, +所以它是调试/测试模式,而不是生产模式。`tests/reserve_stress.c` 是它的 +专用配置:每个缓冲区都从 `cap == 1` 开始,用固定 LCG 驱动 1500 次伪随机 +修改,并与字节精确模型对照;每次重新分配后断言 `cap == len + 1`,同时 +断言"收缩从不重新分配"。 + +## 视图与别名 + +视图是本库的核心抽象:`sx_view_t` 保存一个缓冲区引用加上一个 +`(offset, len)` 窗口。返回视图从不拷贝、从不分配,也从不修改缓冲区。 +同一套表示用于整缓冲区视图(`sx_view`)、视图移动 +(`sx_view_advance`、`sx_view_range` 等)、分割 token 和正则匹配数组。 + +调用方必须遵守的规则: + +- **视图是快照。** 修改不会调整已捕获的视图。若长度发生变化,先前捕获的 + 偏移和长度可能不再描述同样的字节;修改后应重新派生视图。 +- **增长会使裸指针失效。** `sx_buf_mut` 和 `sx_buf_view_mut` 借用底层 + 数组;之后使缓冲区增长的修改可能 `realloc` 它。`sx_t *` 句柄稳定, + 指针不稳定。 +- **视图不得比缓冲区活得更久。** `ref` 是裸 `_sx *`;释放缓冲区就释放 + 了被引用对象。返回视图数组不会转移底层缓冲区的所有权。 +- **视图使用期间不要修改。** 对 `sx_split` token、 + `sx_reg_match_all` 数组和用户持有的视图,规则相同。 +- **`NULL` 视图表示"无"。** `{ref = NULL, offset = 0, len = 0}` 是 + 哨兵值;除此之外,库返回的视图都指向存活缓冲区。 + +别名修改是最微妙的部分。当源视图与目标引用同一个缓冲区时, +`sx_append_view`、`sx_write_view` 和 `sx_insert_view` 用 `memmove` +而不是 `memcpy` 拷贝。对 append 和 write 来说,这只是普通的、能安全 +处理重叠的移动,因此任何契约内的源视图都可以使用。`sx_insert_view` +则更窄,原因在于它的操作顺序: + +1. 先为**最终**内容长度预留空间(这正是源指针保持有效的原因: + `realloc` 会原地更新 `_sx.ptr`,因此之后取得的指针看到的是新分配); +2. 把尾部向右移动 `v.len` 个字节,写入 `[idx + n, len + n)`; +3. 在 `idx` 处用 `memmove` 写入插入的字节。 + +尾部移动使自别名带有条件:起点在插入点之前或正好在插入点 +(`v.offset <= idx`)的源窗口结束于 `idx + n` 或更早,因此移动不会 +覆盖它,第 3 步的 `memmove` 再负责处理剩余的重叠。已被测试覆盖的情形是 +`v.offset == idx`:把视图 `[2, 4)`(`"cd"`)插入 `"abcdef"` 的索引 2, +得到 `"abcdcdef"`。起点**在 `idx` 之后**的自别名窗口会在被读取之前就被 +尾部移动覆盖:把视图 `[3, 5)`(`"de"`)插入 `"abcdef"` 的索引 2,得到 +`"abdccdef"` 而不是 `"abdecdef"`;这类调用属于契约之外。 +`tests/reserve_stress.c` 末尾的回归用例覆盖的正是强制增长下的 +`v.offset == idx` 情形,锁定"先预留、后取指针"的顺序。带 `owned` 参数的 +变体(`sx_append(self, self)` 等)没有这层保护——它们会释放自己的参数, +对自别名而言属于契约之外。 + +## 所有权与错误模型 + +所有权刻意保持显式且简单:谁收到拥有所有权的指针,谁负责释放。 + +| 操作 | 所有权 | +| --- | --- | +| `sx_new*`、`sx_dup`、`sx_substr`、`sx_reg_replace*` | 返回调用方拥有的 `sx_t *`;用 `sx_free` 释放 | +| `sx_append`、`sx_write`、`sx_insert`(`owned` 参数) | 消费该参数:由库释放 | +| `sx_split`、`sx_find_all*`、`sx_reg_match_all`、`sx_reg_split` | 返回 `malloc` 分配的数组;用 `free` 释放 | +| 匹配视图、token、整缓冲区视图 | 借用;无需释放 | + +需要注意的细节: + +- **消费型调用在失败时也会消费。** `sx_append`/`sx_write`/`sx_insert` + 先尝试修改,然后无条件释放 `owned`。如果修改本身失败(分配失败), + 调用返回 `NULL`,但参数仍已被消费。参数为 `NULL` 时返回 `NULL`, + 不释放任何东西。 +- **句柄同一性。** 每次修改都返回 `self`,因此成功的修改可以串联: + `sx_append_cstr(sx_append_cstr(s, "a"), "b") == s`。句柄在增长前后 + 稳定;只有底层数组会移动。 +- **数组不拥有元素所指的缓冲区。** 释放 `sx_split` 或 + `sx_reg_match_all` 返回的数组并不是释放主体;视图只是变得不可达。 + +错误模型基于哨兵值,没有 `errno`、没有错误对象,也没有错误返回码: + +| 情况 | 哨兵值 | +| --- | --- | +| 偏移查找(`sx_find*`、`sx_rfind*`) | `(size_t)-1` | +| "无出现"(`sx_find_all*`) | `NULL` 数组 | +| "无匹配"视图(`sx_reg_match`) | `{ref = NULL, offset = 0, len = 0}` | +| "无匹配"数组(`sx_reg_match_all`) | `NULL` | +| 非法/空分隔符、非法正则、数组/字符串工厂分配失败 | `NULL` | +| 布尔谓词与 `sx_reg_is_match` | `0` | + +两个后果是有意为之,并且都有文档: + +- **"无结果"与"内存不足"可能无法区分。** `find_all` 家族和 `sx_reg_*` + 数组家族对两者都返回 `NULL`,因为契约没有给它们第三条通道。正则替换 + 家族则能区分:无匹配返回原样拷贝,`NULL` 表示非法输入或失败。 +- **`NULL` 句柄参数大多属于契约之外。** 只有显式检查的那些家族有定义的 + `NULL` 行为——`sx_new_from_cstr`、`sx_dup`、cstr/owned 修改参数、 + `sx_find*`、`sx_rfind*`、`sx_find_all*`、 + `sx_cmp*`/`sx_starts_with*`/`sx_ends_with*` 组、`sx_split` 以及 + `sx_reg_*` 调用。访问器(`sx_len`、`sx_cap`、`sx_buf_mut`、`sx_view` + 等)、视图移动函数和 `sx_free` 会解引用句柄,不接受 `NULL`。公开头 + 文件按函数写明这些边界。 + +错误不会留下构建到一半的缓冲区:失败的预留发生在拷贝任何字节之前, +因此 `self` 保持原内容与单 NUL 结尾不变式。唯一可见的例外是上文所述的 +被消费的 `owned` 参数。 + +## 查找内部实现 + +整个查找家族建立在 `src/sx_core.c` 中唯一的 `static` 原语之上: + +```c +static inline find_ret_t find(const sx_t *h, const char *needle, int len, + size_t boundary, int opt); +``` + +返回类型既可能是位置,也可能是指向结果数组的指针,因此实现选择一种宽度 +足以往返指针的整数类型: + +```c +#if SIZE_MAX > UINTPTR_MAX +typedef size_t find_ret_t; +#else +typedef uintptr_t find_ret_t; +#endif +``` + +### 区域模型 + +`opt` 选择方向和结果形态: + +- 第 0 位:`1` = 向右查找,`0` = 向左查找; +- 第 1 位:`1` = 单个结果(标量),`0` = 全部结果(数组)。 + +查找区域由调用方的 boundary 计算: + +```text +left search (sx_find*): region = [boundary, H) +right search (sx_rfind*): region = [0, min(boundary, H)) + +H = content length of h +a match window [p, p+m) counts only if p >= region_start and p+m <= region_end +``` + +各封装填入文档化的边界:`sx_find*` 使用 `boundary = 0`;`sx_rfind*` 使用 +`boundary = len(h)` 并带向右标志;`sx_find_view_b` 和 +`sx_rfind_view_b` 传递调用方的 boundary。`len <= 0`、空区域或短于 +needle 的区域都按模式要求报告"未找到"——标量封装返回 `(size_t)-1`, +数组封装在内部返回计数为 0 的数组(再由 `sx_find_all*` 转成 `NULL`)。 + +`len` 是 needle 的内容长度(`sx_t` needle)、`v.len`(视图 needle), +或 `(int)strlen(s)`(cstr needle——注意这里的窄化转换,它属于 `int` +实际限制之一)。needle 字节直接从视图或缓冲区读取;查找是字节精确的, +类似 `memcmp`。 + +### 单字节 needle:memchr 与 memrchr + +当 `m == 1` 时,原语使用 C 库的向量化扫描: + +- **最左:** `memchr(t + l, c, er - l)`; +- **最右:** 在 glibc 上使用 `memrchr(t, c, er)`。`memrchr` 是 GNU + 扩展而非 ISO C 函数,因此 `sx_core.c` 手动声明它,并且只在定义了 + `__GLIBC__` 且未定义 `SX_FORCE_NO_MEMRCHR` 时使用。回退方案是逐字节 + 反向循环,在到达 `l` 之前保留最后一个(最右的)命中。 + +最右快路径可以从 `0` 开始搜索,因为向右查找总是设置 `l = 0`;`er` +已经携带了调用方的 boundary。`SX_FORCE_NO_MEMRCHR` 用于在 glibc 系统上 +构建并测试可移植路径。 + +对 `m == 1` 的"全部"模式,实现从上一个命中 + 1 处反复调用 `memchr`。 +这样会报告**重叠**位置,而这正是 `sx_find_all*` 承诺的行为 +(`"aa"` 在 `"aaaa"` 中报告 0、1 和 2)。 + +### 更长的 needle:KMP + +当 `m >= 2` 时,原语计算 KMP 前缀表(`pi`,一次 +`malloc(m * sizeof(size_t))`),并在 `O(n + m)` 时间内扫描区域: + +- **最左优先与全部模式**在 `[l, er)` 上使用正向 KMP。完整匹配时,单结果 + 模式立即返回;全部模式记录起始偏移,并以 `q = pi[m - 1]` 继续,这正 + 是它能报告重叠出现的原因。 +- **最右优先**使用反向 KMP:用索引映射在*反向* needle 上计算同一张前缀 + 表(不拷贝 needle),再从 `er - 1` 向下扫描到 `l`。当已匹配后缀长度 + 达到 `m` 时,当前文本索引就是窗口起点。 + +全部模式的结果数组从容量 16 开始,带溢出保护地翻倍 +(`cap > SIZE_MAX / 2 / sizeof(*r)` 时以 `NULL` 中止),返回前再用 +`realloc` 收缩一次。其布局为 `{count, pos0, pos1, ...}`:`arr[0]` 是 +计数,不是位置。 + +### 复杂度 + +| 情况 | 技术 | 时间 | 额外内存 | +| --- | --- | --- | --- | +| 单字节 needle,最左单结果 | `memchr` | `O(n)` | 无 | +| 单字节 needle,最右单结果 | `memrchr` 或反向扫描 | `O(n)` | 无 | +| needle 长度 >= 2,单结果 | KMP | `O(n + m)` | `O(m)` 前缀表 | +| `sx_find_all*`,单字节 | 反复 `memchr` | `O(n)` 扫描 | `O(k)` 结果 | +| `sx_find_all*`,更长 needle | KMP | `O(n + m)` 扫描 | `O(m) + O(k)` 结果 | +| `sx_split` | 两遍 `is_sep` | 最坏 `O(H * m)` | `O(tokens)` 结果 | + +`n` 是区域长度,`m` 是 needle 长度,`k` 是匹配数。数组封装只分配结果; +`sx_find*` / `sx_rfind*` 返回标量,不分配任何东西(除了 KMP 表,它在 +返回前释放)。 + +## 正则封装内部实现 + +高级正则层刻意保持很薄。它的全部状态就是一个已编译的 PCRE2 代码对象: + +```c +typedef struct sx_reg_t { + pcre2_code *code; +} sx_reg_t; +``` + +### 编译与释放 + +`sx_reg_compile` 用固定参数调用 PCRE2: +`pcre2_compile(pattern, PCRE2_ZERO_TERMINATED, 0, ...)`。这里的 `0` +是选项字——没有 `CASELESS`、没有 `UTF`、什么都没有——而 +`PCRE2_ZERO_TERMINATED` 表示模式是 C 字符串。PCRE2 的错误码和错误位置 +只是为了满足函数签名而接收,随后被丢弃,因此所有编译失败都归结为 +`NULL`。编译会分配 PCRE2 代码对象和小的 `sx_reg_t` 封装;`sx_reg_free` +释放两者,并接受 `NULL`。 + +### 每次调用的匹配数据与扫描规则 + +PCRE2 把已编译模式与每次调用的匹配数据分开。封装在每次调用时用 +`pcre2_match_data_create_from_pattern(r->code, NULL)` 创建匹配数据, +并在返回前释放。这正是已编译句柄可以跨线程共享的原因:句柄中不保存 +任何匹配状态。 + +单步匹配是 `pcre2_match(code, subject, len, offset, 0, md, NULL)`。注意 +主体以显式**长度**传入,而不是当作 C 字符串;最后一个参数(匹配上下文) +是 `NULL`,因此适用 PCRE2 的默认匹配限制。负返回值(无匹配,或诸如匹配 +限制之类的 PCRE2 匹配期错误)被当作"没有更多匹配";封装不暴露匹配期 +错误码。 + +`sx_reg_match_all` 和 `sx_reg_split` 共用的扫描推进逻辑是: + +```c +static size_t reg_next_at(size_t start, size_t end) { + return end > start ? end : start + 1; +} +``` + +下一次搜索从匹配结尾开始;对零长匹配则从起点后一个字节开始,因此扫描 +保证前进。每一步都用 `offset` 调用 `pcre2_match`;当 `offset` 越过主体 +长度时,PCRE2 返回错误,循环结束。这就是 `a*` 对 `"bbb"` 报告偏移 0、 +1、2、3 处的空匹配,以及 `$` 对 `"abc"` 报告偏移 3 处单个空匹配的原因。 + +### match_all 与 split 的两遍定长策略 + +两个数组家族都扫描两遍: + +```text +pass 1: count matches -> cnt +malloc((cnt + 1) * sizeof view) -> exact size, no realloc +pass 2: repeat the same scan -> fill views, then arr[cnt] = {0} guard +``` + +扫描是确定性的(相同模式、相同主体、相同起始偏移),因此两遍看到完全 +相同的位置。`sx_reg_split` 还额外跟踪空隙起点 `seg`:每个 token 是 +`[seg, match_start)`,随后 `seg` 移动到 `match_end`;最后一个 token 是 +`[seg, len)`。这样正好产生 `匹配数 + 1` 个 token,包括空的首尾 token, +以及相邻匹配或零长匹配产生的空 token。 + +### 替换:两次 pcre2_substitute 调用 + +替换由 PCRE2 的替换例程构建,并固定两个标志: + +```c +options |= PCRE2_SUBSTITUTE_UNSET_EMPTY | PCRE2_SUBSTITUTE_UNKNOWN_UNSET; +``` + +`UNSET_EMPTY` 让未参与匹配的组展开为空;`UNKNOWN_UNSET` 让不存在的组号 +展开为空,而不是让整个替换失败。`sx_reg_replace` 额外传入 +`PCRE2_SUBSTITUTE_GLOBAL`;`sx_reg_replace_first` 不传。 + +由于替换前不知道输出长度,封装调用两次 `pcre2_substitute`: + +```text +call 1: output buffer NULL, PCRE2_SUBSTITUTE_OVERFLOW_LENGTH, &needed + -> PCRE2_ERROR_NOMEMORY, `needed` = required size including NUL +malloc(needed) (single temporary) +call 2: fill the buffer, &used = needed + -> rc >= 0, `used` = bytes written excluding NUL +sx_new_with_cap(used + 1) (new public buffer) +memcpy(ptr, buf, used); len = used; ptr[used] = '\0' +``` + +拷贝完成后释放临时缓冲区。若第一次调用没有返回 `PCRE2_ERROR_NOMEMORY`, +说明模板/替换对被拒绝;封装返回 `NULL`,且从不改写主体。没有匹配时, +PCRE2 不替换任何内容,输出就是主体的原样拷贝——这是正常成功,不是错误。 + +### 分配一览 + +| 调用 | 结果分配 | 说明 | +| --- | --- | --- | +| `sx_reg_compile` | PCRE2 代码对象 + `sx_reg_t` | 一次性成本 | +| `sx_reg_free` | 无 | 释放编译时的两次分配 | +| `sx_reg_is_match` | 每次调用的匹配数据 | 不分配结果 | +| `sx_reg_match` | 每次调用的匹配数据 | 结果是视图值 | +| `sx_reg_match_all` | 匹配数据 + 精确的 `(cnt + 1)` 数组 | 两遍扫描 | +| `sx_reg_split` | 匹配数据 + 精确的 `(matches + 2)` 数组 | 两遍扫描 | +| `sx_reg_replace*` | PCRE2 内部匹配数据 + 临时缓冲区 + `sx_t` | 两次替换调用 | + +封装不启用 PCRE2 JIT(从不调用 `pcre2_jit_compile`),也不暴露编译或 +匹配选项。模式级特性(例如内联选项)仍然生效,因为它们是模式的一部分, +而不是封装层的策略。 + +## 并发 + +- **已编译正则句柄不可变且可共享。** 每次调用的状态都保存在调用内部 + 创建的、归调用方所有的匹配数据中;封装没有全局变量。一个 + `sx_reg_t *` 可以同时服务多个线程的调用。 +- **缓冲区没有同步。** 它们是普通堆内存。多个线程并发读取同一缓冲区没 + 问题,前提是无人修改;修改需要外部同步。视图让规则更严格:与改变长度 + 的修改并发读取视图构成数据竞争(契约之外)。 +- **所有权需要协调。** 只有一个所有者的缓冲区不能被两个线程同时消费; + 数组是单一所有者的结果。 + +库本身从不修改全局状态,因此只要调用方对每个缓冲区的访问做了同步,在多 +线程程序中使用它就是安全的。 + +## 可移植性与限制 + +### memrchr 与 SX_FORCE_NO_MEMRCHR + +查找路径中唯一的非 ISO C API 是 `memrchr`,一个 glibc 扩展。 +`sx_core.c` 手动声明它,而不依赖特性测试宏,并且只在定义了 +`__GLIBC__` 且构建未定义 `SX_FORCE_NO_MEMRCHR` 时编译进去。在其他平台 +(以及强制开关打开时),最右单字节查找回退到可移植的逐字节反向循环。 +仓库内的测试套件运行默认的 glibc 路径;该开关存在的目的,是让回退路径 +也能在 glibc 上构建并检查。 + +### 整数访问器与 SIZE_MAX + +公开访问器返回 `int`,而偏移和 needle 使用 `size_t`: + +| 函数 | 返回类型 | +| --- | --- | +| `sx_len`、`sx_len_view` | `int`(内容字节数) | +| `sx_cap` | `int`(总分配量) | +| 偏移(`sx_find*`、视图字段、正则视图) | `size_t` | + +内容字节数超过 `INT_MAX` 的缓冲区在测试契约之外。这是有意的 API 简化 +(目标场景是中小字符串),不是缺陷;常见平台上每个缓冲区的实际上限约为 +2 GiB。同样的 `int` 窄化还出现在查找封装把基于 `strlen` 的 needle 长度 +转换为 `int` 的地方。 + +`SIZE_MAX` 保护出现在尺寸运算可能回绕的地方: + +- `sx__reserve` 拒绝 `need == SIZE_MAX`(否则无法再加上结尾符); +- `sx_find_all*` 的数组增长在翻倍前检查 + `cap > SIZE_MAX / 2 / sizeof(*r)`; +- 没有通用的溢出检查:极端的 `n` 或 `off` 参数可能让无符号尺寸运算 + 回绕,这类调用在测试契约之外。 + +### 平台假设 + +- 库使用 C23。参考工具链是 Linux 上的 GCC 14+ 与 Clang 19+(CI 使用 + Ubuntu 24.04、GCC 14 和 Clang 19);除 `SYMBOL_PUBLIC` 和 glibc + `memrchr` 快路径外,源码不依赖编译器特定扩展。 +- `src/export.h` 是已入库的 Forge 派生头文件。它把 `SYMBOL_PUBLIC` + 定义为 GCC/Clang 的 `__attribute__((visibility("default")))`,以及 + MSVC 的 `_declspec(dllexport)`;构建采用隐藏的默认可见性,因此恰好是 + `SYMBOL_PUBLIC` 函数从 `libstringx.so` 导出。 +- 正则层需要 PCRE2 10.46(`pcre2-8`),8 位、非 UTF 模式。构建把它 + 链接进 `libstringx`,因此使用者无需添加 PCRE2 链接参数,但 PCRE2 是 + 共享库的运行时依赖。 +- 安装与 Debian 打包目标在 `build.c` 中由 `LINUX` 宏保护;库本身作为 + 普通 C23 代码编译。 + +## 测试策略 + +`tests/` 下的每个文件都是自包含程序。其文件头注释声明构建方式 +(由固定版本的 Forge 构建系统消费的 `// Include`、`// Source`、 +`// Option`、`// Link`、`// Library` 行),并记录它的**行为边界**: +一个"In scope (contract)"列表和一个"Out of contract (not exercised)" +列表。文件头本身也是契约的一部分:行为变化时,边界列表要随之修改 +(见[贡献指南](contributing.md))。 + +测试套件(20 个测试)按主题一文件: + +| 测试 | 锁定的内容 | +| --- | --- | +| `access.c` | `sx_len` / `sx_cap` / 缓冲区访问器 / 整缓冲区视图 | +| `append.c` | append 家族、所有权转移、别名追加 | +| `chain.c` | 修改串联、句柄同一性、零泄漏所有权 | +| `cmp.c` | 按字节的字典序比较 | +| `ends_with.c` | 后缀谓词 | +| `find.c` | 最左查找、有界区域、`strlen` needle | +| `find_all.c` | 全部出现,包含重叠位置 | +| `insert.c` | 插入、跨增长时的别名 | +| `new.c` | 构造函数、`sx_dup`、容量边界情况 | +| `reg.c` | 正则家族、二进制安全主体、零长匹配处理 | +| `reserve.c` | `sx_reserve` 的单调性与不收缩规则 | +| `reserve_stress.c` | 精确预留的模型化压力测试(1500 次随机修改) | +| `rfind.c` | 最右查找与有界区域 | +| `shrink.c` | truncate / erase / clear 边界情况 | +| `split.c` | 分割形态、结束哨兵、零拷贝 token | +| `starts_with.c` | 前缀谓词 | +| `substr.c` | 双向的拷贝独立性 | +| `view_move.c` | advance / retreat / shift / range 的钳制 | +| `view_trim.c` | 空白裁剪集合与空视图钳制 | +| `write.c` | 覆盖、尾部追加与填充语义 | + +测试如何运行: + +- 每个测试都**直接编译库源码**,并使用其文件头中的每测试选项。 + 内存检查器开启:AddressSanitizer、UBSan,以及在 Linux 上通过 ASan + 启用的 LeakSanitizer,因此泄漏检查器是所有所有权规则的见证者。CI 设置 + `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1` 和 + `UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1`。 +- `tests/reserve_stress.c` 是唯一用 `-DSX_FORCE_EXACT_RESERVE` 构建的 + 测试。它用确定性 LCG 驱动 append、insert、erase、write、truncate 和 + 别名视图修改,与字节精确模型对照,并包含别名 `insert_view` 增长的回归 + 用例。 +- CI 还会把构建好的库安装到临时前缀,通过 `pkg-config` 把 + `tests/reg.c` 链接到**安装后的共享库**(带 rpath)并运行。这样除了 + 源码级行为外,还验证了公开头文件、导出符号和 PCRE2 链接;随后检查生成 + 的 Debian 包。 +- 没有故障注入,因此测试套件不会覆盖分配失败分支(预留测试的注释指出, + 没有故障注入就无法表达这样的测试)。文档化的 OOM 哨兵是从代码推得, + 而不是在测试中观察到的。 +- `./make check` 目标用 `-Wall -Wextra -Wpedantic -Werror` 编译生产代码; + GCC 构建还运行 `-fanalyzer`(CI 中使用 + `-O1 -fno-analyzer-state-merge`),CodeQL 用 `security-and-quality` + 查询扫描。 +- 测试禁用 LTO(`build.c` 中的 `set(TARGET_LTO, 1, DISABLE)`),因为 + 固定版本的 Forge 为并行 Clang 链接发出仅 GCC 支持的 `-flto=N` 标志。 + 生产库目标保留 LTO。 + +## 设计取舍 + +| 选择 | 收益 | 代价 | +| --- | --- | --- | +| 单 NUL 结尾的单块分配 | `cstr` 互操作便宜,一次 `free`,内容连续 | 一个字节开销;cstr 变体在内嵌 NUL 处截断 | +| `sx_t` 句柄指向私有 `_sx` | 增长时句柄稳定;布局私有 | 多一层间接,并为每个缓冲区分配头结构 | +| `(ref, offset, len)` 视图 | 零拷贝切片;分割和正则结果统一表示 | 生命周期规则;修改后视图过时;增长使裸指针失效 | +| 几何增长 | 追加的摊还常数成本 | 多余容量;峰值内存高于 `len` | +| 精确预留调试模式 | 红区紧贴的分配能暴露差一错误 | 慢;仅供测试 | +| `int` 长度访问器 | 紧凑、简单的 API | 实际约 2 GiB 的缓冲区上限;窄化转换 | +| 哨兵错误模型 | 无全局状态、无错误传递、确定性 | "无结果"与 OOM 可能混淆;没有诊断信息 | +| 数组由调用方释放,句柄由库释放 | 所有权显式、可预测 | 需要知道两个释放函数(`free` 与 `sx_free`) | +| KMP + `memchr`/`memrchr` | 最坏 `O(n + m)` 有保证,代码简单,单字节路径向量化 | `m >= 2` 时需要前缀表分配;平均速度低于优化过的子串查找 | +| `sx_find_all*` 报告重叠结果 | 完整位置集合;对字节扫描有用 | 调用方必须预期偏移会重叠 | +| 正则非重叠扫描 | 标准 PCRE2 行为;保证前进 | 无法报告重叠的正则匹配 | +| 两遍精确定长 | 一次分配、不靠 realloc 增长、确定性 | 数组 API 的匹配工作量大约翻倍 | +| 薄 PCRE2 封装,无选项/JIT | 接口面极小、完整的 PCRE2 语义、单一依赖 | 没有封装层标志或调优;PCRE2 在运行时链接 | +| 已编译正则不可变且无内部锁 | 句柄可共享且无需同步 | 缓冲区仍需调用方同步 | +| 构建期配置宏 | 增长/memrchr 策略零运行时成本 | 改变策略需要重新构建 | + +这些是取舍,不是意外。测试锁定可观察的后果,头文件注释写明每条规则 +契约之外的那一面。 + +## 许可 + +项目源码采用 MIT 许可(见 [LICENSE](../../LICENSE) 以及源码中的 SPDX +标注)。Forge 派生的构建工具遵循构建脚本例外:`build.conf` 与 +`src/export.h` 带有 +GPL-3.0-or-later WITH LicenseRef-Forge-BuildScript-Exception 的 SPDX +标识,`build.c` 也由同一例外覆盖;库源码本身仍为 MIT。正则层使用 PCRE2 +(BSD-3-Clause);见 +[THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md)。 + +--- + +[← 上一页](regex.md) · [文档首页](README.md) · [下一页 →](build-and-test.md) diff --git a/docs/zh_cn/getting-started.md b/docs/zh_cn/getting-started.md new file mode 100644 index 0000000..ce70338 --- /dev/null +++ b/docs/zh_cn/getting-started.md @@ -0,0 +1,300 @@ +[English](../en_us/getting-started.md) · 中文 + +[文档首页](README.md) › 快速上手 + +# 快速上手 + +String X 是一个轻量的 C23 字符串库:它把每个字符串视为一段以单个 NUL +结尾的缓冲区,而它的每一段切片都是一个零拷贝视图。所有缓冲区都按字节长度 +处理,内嵌的 NUL 字节是普通数据,不会被 C 字符串规则截断。公开接口只有 +一个头文件 `` 和一个库 `libstringx`(`-lstringx`);可选的进阶 +层通过 PCRE2 提供正则表达式。本页带你从一份全新检出的代码走到一个可运行 +的程序。文档描述的是 **v0.5**。 + +## 环境要求 + +| 要求 | 说明 | +| --- | --- | +| Linux | 经过测试的平台;构建与测试均面向 Linux | +| C23 编译器 | GCC 14+ 或 Clang 19+;CI 在 Ubuntu 24.04 上使用 GCC 14 与 Clang 19 | +| `forge` | `https://github.com/minelogy-dev/forge`;把 `build.c` 编译成本地 `./make` 可执行文件 | +| `libpcre2-dev` | PCRE2 10.46,8 位 API;构建时需要;库自身会链接 `pcre2-8` | +| `pkg-config` | 推荐使用者使用;安装包自带 `libstringx.pc` | + +## 从源码构建 + +```sh +forge . # compile build.c into ./make (re-run whenever build.c changes) +./make # build -> build/output/libstringx.so +./make test # build and run every test under tests/ (ASan + UBSan + LSan) +``` + +`./make` 还会把公开头文件同步到 `build/output/include`。`./make test` 把每个 +`tests/*.c` 当作独立程序运行,全程开启 AddressSanitizer、UBSan 与 +LeakSanitizer(内存检查器);可以用 `./make test -j 2` 并行执行测试。 +`build.conf` 选择编译器,也是版本号的唯一来源。 + +## 安装 + +```sh +./make install # default prefix: /usr/local (may need sudo) +./make install "$HOME/.local" # user-owned prefix +``` + +install 目标会先构建,然后复制产物: + +| `` 下的路径 | 内容 | +| --- | --- | +| `lib/libstringx.so` | 共享库 | +| `include/sx.h` | 公开头文件,以及 `sx_core.h`、`sx_raw.h` | +| `lib/pkgconfig/libstringx.pc` | pkg-config 元数据 | +| `share/doc/libstringx/` | `LICENSE`、`THIRD_PARTY_NOTICES.md`、`copyright` | + +### 使用已安装的库 + +```sh +cc app.c $(pkg-config --cflags --libs libstringx) -o app +``` + +如果前缀不在默认搜索路径中,请让 pkg-config 找到已安装的元数据;对于非系统 +前缀,还要设置运行时库路径: + +```sh +export PKG_CONFIG_PATH="$HOME/.local/lib/pkgconfig" +cc app.c $(pkg-config --cflags --libs libstringx) -o app +LD_LIBRARY_PATH="$HOME/.local/lib" ./app +``` + +不使用 pkg-config 时,等价的构建命令是: + +```sh +cc app.c -I/include -L/lib -lstringx -o app +``` + +你只需要链接 `-lstringx`:`libstringx` 自身已链接 `pcre2-8`,因此无需额外的 +库参数。但共享库在运行时需要系统中存在 `libpcre2-8`。 + +### Debian 软件包 + +```sh +./make gen_deb +sudo apt install ./build/deb/libstringx_0.5_amd64.deb +``` + +`gen_deb` 会生成 `build/deb/libstringx__.deb`;版本号来自 +`build.conf`(去掉前缀 `v`),架构名来自 `uname -m`(`x86_64` 映射为 +`amd64`,`aarch64` 映射为 `arm64`)。软件包依赖 `libc6` 与 `libpcre2-8-0`。 + +## Hello, String X + +这是 README 中的快速上手程序。它把一个 C 字符串复制进自有缓冲区,找到第一个 +逗号,把它之前的文本复制到第二个自有缓冲区并打印出来。两个缓冲区都用 +`sx_free` 释放。 + +```c +#include +#include + +int main(void) { + sx_t *msg = sx_new_from_cstr("hello, world"); + size_t at = sx_find_cstr(msg, ", "); + sx_t *hi = sx_substr(msg, 0, at); + fwrite(sx_buf_mut(hi), 1, (size_t)sx_len(hi), stdout); + putchar('\n'); /* hello */ + sx_free(hi); + sx_free(msg); + return 0; +} +``` + +按上文完成安装后,用下面的命令构建并运行: + +```sh +cc hello.c $(pkg-config --cflags --libs libstringx) -o hello +./hello +``` + +```text +hello +``` + +在安装之前,也可以直接使用源码树的构建输出: + +```sh +cc hello.c -Ibuild/output/include -Lbuild/output -lstringx -o hello +LD_LIBRARY_PATH=build/output ./hello +``` + +## 十分钟概览 + +用户最常做的五件事,每个配一个小程序。所有示例都是完整程序,编译方式与上面的 +`hello.c` 相同。 + +### 创建缓冲区 + +`sx_new` 返回空缓冲区,`sx_new_from_cstr` 复制一个 C 字符串,`sx_dup` 生成 +一份独立的深拷贝。所有结果都归调用方所有。 + +```c +#include +#include + +int main(void) { + sx_t *empty = sx_new(); /* len 0 */ + sx_t *hello = sx_new_from_cstr("hello"); + sx_t *copy = sx_dup(hello); + printf("empty: len=%d cap=%d\n", sx_len(empty), sx_cap(empty)); + printf("hello: len=%d [%s]\n", sx_len(hello), sx_buf_mut(hello)); + printf("copy: len=%d [%s]\n", sx_len(copy), sx_buf_mut(copy)); + sx_free(empty); + sx_free(hello); + sx_free(copy); + return 0; +} +``` + +```text +empty: len=0 cap=32 +hello: len=5 [hello] +copy: len=5 [hello] +``` + +### 追加与插入 + +每次修改都返回传入的那个缓冲区,因此修改可以链式书写;即使底层数组重新分配, +句柄也保持不变。 + +```c +#include +#include + +int main(void) { + sx_t *s = sx_new_from_cstr("abc"); + s = sx_append_cstr(s, "def"); /* "abcdef" */ + s = sx_insert_cstr(s, 3, "-"); /* "abc-def" */ + s = sx_write_cstr(s, 0, "A"); /* "Abc-def" */ + printf("%s (len %d)\n", sx_buf_mut(s), sx_len(s)); + sx_free(s); + return 0; +} +``` + +```text +Abc-def (len 7) +``` + +### 查找 + +`sx_find*` 返回最左匹配的字节偏移,`sx_rfind*` 返回最右匹配;未找到的哨兵值 +是 `(size_t)-1`。 + +```c +#include +#include + +int main(void) { + sx_t *s = sx_new_from_cstr("one two one"); + size_t first = sx_find_cstr(s, "one"); + size_t last = sx_rfind_cstr(s, "one"); + printf("first=%zu last=%zu\n", first, last); + if (sx_find_cstr(s, "three") == (size_t)-1) + printf("three: not found\n"); + if (sx_starts_with_cstr(s, "one")) + printf("starts with one\n"); + sx_free(s); + return 0; +} +``` + +```text +first=0 last=8 +three: not found +starts with one +``` + +### 视图与分割 + +视图是 `{ref, offset, len}`,它别名一段缓冲区而不拷贝。`sx_split` 返回由这类 +视图组成的数组,数组末尾是一个 `ref` 为 `NULL` 的结束哨兵;数组本身用 +`free` 释放。 + +```c +#include +#include +#include + +int main(void) { + sx_t *csv = sx_new_from_cstr("id,name,email"); + sx_view_t head = sx_view_advance(sx_view(csv), 0); + head.len = 2; /* "id" - a view, no copy */ + printf("head: %.*s\n", sx_len_view(head), sx_buf_view_mut(head)); + + sx_view_t *fields = sx_split(csv, ","); + for (size_t i = 0; fields[i].ref != NULL; i++) + printf("field %zu: %.*s\n", i, (int)fields[i].len, + sx_buf_view_mut(fields[i])); + free(fields); /* the array, not the views */ + sx_free(csv); + return 0; +} +``` + +```text +head: id +field 0: id +field 1: name +field 2: email +``` + +### 正则 + +进阶层封装了 PCRE2。编译一次模式,对任意多个缓冲区执行,最后释放。 +`sx_reg_replace` 返回新缓冲区,永不修改原串。 + +```c +#include +#include + +int main(void) { + sx_reg_t *re = sx_reg_compile("(\\w+)@(\\w+\\.\\w+)"); + if (!re) + return 1; + sx_t *msg = sx_new_from_cstr("bob@example.com, alice@example.org"); + if (sx_reg_is_match(re, msg)) { + sx_view_t m = sx_reg_match(re, msg); + printf("first match: %.*s\n", (int)m.len, sx_buf_view_mut(m)); + } + sx_t *out = sx_reg_replace(re, msg, "$1 at $2"); + printf("replaced: %s\n", sx_buf_mut(out)); + sx_free(out); + sx_free(msg); + sx_reg_free(re); + return 0; +} +``` + +```text +first match: bob@example.com +replaced: bob at example.com, alice at example.org +``` + +模式是 C 字符串,按 PCRE2 的 8 位非 UTF 模式匹配,因此 `\w` 等字符类只 +匹配 ASCII。subject 按字节长度匹配,可以包含任意字节,包括 NUL。 + +## 文档索引 + +| 文档 | 内容 | +| --- | --- | +| [文档首页](README.md) | 语言选择与完整文档列表 | +| [用户指南](guide.md) | 心智模型、所有权、二进制安全、示例与陷阱 | +| [API 参考:缓冲区与视图](api-buffer.md) | 创建、容量、访问器、修改、视图 | +| [API 参考:查找、比较与分割](api-search.md) | `sx_find*`、`sx_rfind*`、`sx_cmp*`、`sx_split` | +| [正则表达式](regex.md) | `sx_reg_*` 的匹配、替换与分割家族 | +| [设计与内部实现](design.md) | 数据布局、扩容策略、算法与限制 | +| [构建、测试与打包](build-and-test.md) | Forge 目标、测试框架、安装 | +| [贡献指南](contributing.md) | 工作流程、代码风格、测试、许可 | +| [持续集成](ci.md) | 工作流、必需检查、CodeQL | + +--- + +[文档首页](README.md) · [下一页 →](guide.md) diff --git a/docs/zh_cn/guide.md b/docs/zh_cn/guide.md new file mode 100644 index 0000000..4cc306f --- /dev/null +++ b/docs/zh_cn/guide.md @@ -0,0 +1,434 @@ +[English](../en_us/guide.md) · 中文 + +[文档首页](README.md) › 用户指南 + +# 用户指南 + +本指南面向已经能够构建并链接 String X 的 C 程序员(见[快速上手](getting-started.md)), +讲解它的心智模型并给出可直接使用的示例。函数签名与逐函数细节在 API 参考中; +本页关注各部分如何配合,以及哪些调用属于契约之外。 + +## 心智模型 + +### 缓冲区 + +每个字符串都是一个 `sx_t` 句柄,指向一块底层分配: + +```text +sx_t* ──► _sx { ptr: [ h e l l o \0 . . . . ] , len: 5, cap: 32 } +``` + +- `ptr[0 .. len-1]` 是内容字节;`ptr[len]` 恒为 `'\0'`。 +- `len` 是字节数,永远不是字符数,也不会在内嵌 NUL 处停下。 +- `cap` 是分配的字节数,始终满足 `cap >= len + 1`。 +- `sx_new()` 的初始容量为 32;对于 `n >= 1`,`sx_new_with_cap(n)` 的容量 + 恰好是 `n`,因此最多容纳 `n - 1` 个内容字节(`n == 0` 时仍分配一个字节)。 + +句柄本身是稳定的:扩容可能移动底层数组,但绝不会更换 `sx_t`。请把句柄视为 +不透明对象,不要按值复制该结构体。 + +### 视图 + +视图别名缓冲区的一段,不进行拷贝: + +```text +sx_view_t { ref: the same _sx, offset: 1, len: 3 } ──► "ell" +``` + +- `ref == NULL` 表示"无视图":匹配失败或"没有"的哨兵值。 +- 创建或移动视图不分配内存,因此视图永远不需要释放。 +- 视图是 `(offset, len)` 的快照:之后的修改不会调整它,长度变化会使它失效。 + +## 所有权 + +同一时刻只有一个地方拥有缓冲区。下表说明每个调用返回什么、该如何释放。 + +| 调用 | 结果 | 释放方式 | +| --- | --- | --- | +| `sx_new`、`sx_new_from_cstr`、`sx_new_from_view`、`sx_new_with_cap`、`sx_dup` | 新缓冲区 | `sx_free` | +| `sx_substr` | 新缓冲区 | `sx_free` | +| `sx_reg_replace`、`sx_reg_replace_first` | 新缓冲区 | `sx_free` | +| `sx_append`、`sx_write`、`sx_insert`(`sx_t *owned` 形式) | `self`;实参被消费并释放 | 对 `self` 调用 `sx_free` | +| `sx_find_all*`、`sx_split`、`sx_reg_match_all`、`sx_reg_split` | malloc 分配的数组 | `free` | +| `sx_view`、`sx_view_*`、`sx_reg_match`、上述数组中的 token | 视图 | 无 | +| `sx_reg_compile` | 已编译模式 | `sx_reg_free` | + +有两条推论在实战中很重要: + +- 修改操作返回 `self`,因此可以链式书写: + `sx_append_cstr(sx_append_cstr(s, "a"), "b")` 返回的就是 `s` 本身; + `sx_free` 的调用次数等于创建的缓冲区数量,而不是修改次数。 +- 消费型调用会结束源缓冲区的生命周期。调用 `sx_append(s, part)` 之后, + 不得再使用或释放 `part`:它的内容已复制进 `s`,而且即使分配失败,源缓冲区 + 同样会被释放。 + +`sx_append_cstr`、`sx_append_view`、`sx_write_cstr`、`sx_write_view`、 +`sx_insert_cstr` 与 `sx_insert_view` 接收 C 字符串或视图,永远不会消费缓冲区。 + +## 二进制安全与 cstr 变体 + +凡是显式携带长度的接口都是二进制安全的: + +| 输入形式 | 长度规则 | 内嵌 NUL | +| --- | --- | --- | +| `sx_*_cstr`、`sx_new_from_cstr`、`sx_split` 分隔符、正则模式 | `strlen` | 终止输入 | +| `sx_view_t` 形式、`sx_new_from_view`、自有 `sx_t *` 形式 | 显式 `len` | 普通字节 | +| 正则 subject(`sx_t *h`) | `h` 的字节长度 | 普通字节 | + +因此 `sx_append_cstr` 会在 NUL 处停下,而 `sx_append_view`、`sx_append` 与 +`sx_new_from_view` 会复制每一个内容字节。要打印二进制缓冲区,请按长度输出: +用 `fwrite(sx_buf_mut(h), 1, (size_t)sx_len(h), stdout)` 而不是 +`printf("%s", ...)`。 + +比较与查找遵循同样的区分:`_cstr` 形式使用 `strlen`,自有形式与视图形式比较 +内容字节。正则表达式按字节长度匹配 subject,但模式本身是 C 字符串,因此模式中 +不能包含字面 NUL。 + +## 不变式与失效指针 + +- 每次公开调用之后都有 `ptr[len] == '\0'`、`cap >= len + 1`,且 `len` 统计 + 内容字节。只有会改变长度的调用才会改动这些值。 +- 任何使缓冲区变大的修改都可能 `realloc` 底层数组。此前从 `sx_buf_mut` 或 + `sx_buf_view_mut` 取得的 `char *` 全部失效;修改之后需要重新获取。 + `sx_t *` 句柄始终有效。 +- 通过 `sx_buf_mut` 写入必须保持在 `[0, len)` 内,除非随后有配套的改长度调用; + `ptr[len]` 是结尾符,不是备用字节。 +- 视图是快照。视图(或 `sx_split` / `sx_reg_*` 返回的数组)仍在使用时,不要 + 修改缓冲区;即使没有发生重新分配,长度变化之后也要重新派生视图。 +- 访问器返回 `int`(`sx_len`、`sx_len_view`、`sx_cap`),而偏移是 `size_t`。 + 内容超过 `INT_MAX` 字节的缓冲区不在受测契约之内。 +- 容量只增不减:`sx_truncate`、`sx_erase` 与 `sx_clear` 都不会释放容量。 + +## 错误与哨兵值 + +库中没有异常,也没有错误码。每个家族用一个哨兵值表示无结果: + +| 情况 | 结果 | +| --- | --- | +| `sx_find*` / `sx_rfind*`:未找到 | `(size_t)-1` | +| `sx_find_all*`:未找到、空 needle 或分配失败 | `NULL` 数组 | +| `sx_split`:句柄或分隔符为 NULL、空分隔符、分配失败 | `NULL` 数组 | +| `sx_reg_match`:无匹配 | `ref == NULL` 的视图 | +| `sx_reg_match_all` / `sx_reg_split`:无匹配或分配失败 | `NULL` 数组 | +| `sx_reg_replace*`:参数为 NULL 或模板被拒绝 | `NULL` 缓冲区 | +| 分配失败 | `NULL` | + +`NULL` 表示"没有结果";对返回数组的调用而言,分配失败与"无匹配"无法区分。 +文档化的 NULL 实参处理是有限的: + +- `sx_new_from_cstr(NULL)` 与 `sx_dup(NULL)` 返回 `NULL`。 +- append/write/insert 的 C 字符串实参与 owned 缓冲区实参返回 `NULL`,且 + `self` 保持不变。 +- `sx_cmp*`、`sx_starts_with*` 与 `sx_ends_with*` 返回 `0`。 +- `sx_find*` / `sx_rfind*` 返回 `(size_t)-1`;`sx_find_all*` 返回 `NULL`。 +- `sx_split` 在句柄为 NULL、分隔符为 NULL 或分隔符为空时返回 `NULL`。 +- `sx_reg_compile(NULL)` 返回 `NULL`;`sx_reg_free(NULL)` 是空操作; + match、replace 与 split 家族在参数为 NULL 时返回各自的未找到值。 + +其余接口都不接受 NULL 句柄。`sx_len`、`sx_cap`、`sx_buf_mut`、`sx_view`、 +`sx_free`、`sx_substr`、`sx_reserve`、`sx_erase` 以及其余函数都会解引用句柄; +传入 NULL 属于契约之外,可能直接崩溃。特别地,`sx_free(NULL)` 不是空操作, +`ref == NULL` 的视图也不能传给视图操作函数。 + +## 常用示例 + +每个示例都是完整的 C23 程序。构建方式与[快速上手](getting-started.md)中的 +`hello.c` 相同,或者使用: + +```sh +cc recipe.c $(pkg-config --cflags --libs libstringx) -o recipe +``` + +### 由片段构建字符串 + +混合使用 C 字符串、视图与自有缓冲区;自有缓冲区会被消费。 + +```c +#include +#include + +int main(void) { + sx_t *path = sx_new(); + path = sx_append_cstr(path, "/usr"); + path = sx_append_cstr(path, "/local"); + sx_t *part = sx_new_from_cstr("/bin"); + path = sx_append(path, part); /* part is consumed */ + path = sx_insert_cstr(path, 0, "/opt:"); /* prefix */ + printf("%s (%d bytes)\n", sx_buf_mut(path), sx_len(path)); + sx_free(path); + return 0; +} +``` + +```text +/opt:/usr/local/bin (19 bytes) +``` + +### 查找并提取子串 + +使用偏移之前先检查 `(size_t)-1` 哨兵值。`sx_substr` 会拷贝,因此结果独立于 +源缓冲区;`sx_find_view_b` 把查找限制在从某个边界开始的区域内。 + +```c +#include +#include + +int main(void) { + sx_t *line = sx_new_from_cstr("key=value;flag=on"); + size_t eq = sx_find_cstr(line, "="); + size_t semi = sx_find_cstr(line, ";"); + sx_t *nod = sx_new_from_cstr("="); + size_t later = sx_find_view_b(line, sx_view(nod), 10); /* region [10, 17) */ + + if (eq == (size_t)-1 || semi == (size_t)-1) + return 1; + sx_t *key = sx_substr(line, 0, eq); + sx_t *value = sx_substr(line, eq + 1, semi - eq - 1); + printf("first '='=%zu, next '=' from 10=%zu\n", eq, later); + printf("key=%s value=%s\n", sx_buf_mut(key), sx_buf_mut(value)); + sx_free(key); + sx_free(value); + sx_free(nod); + sx_free(line); + return 0; +} +``` + +```text +first '='=3, next '=' from 10=14 +key=key value=value +``` + +### 分割并遍历 + +`sx_split` 返回 malloc 分配的视图数组,末尾是以 `ref == NULL` 标记的结束 +哨兵;空字段会被保留。用 `free` 释放数组,读取 token 期间保持缓冲区存活。 + +```c +#include +#include +#include + +int main(void) { + sx_t *csv = sx_new_from_cstr("id,,name,"); + sx_view_t *fields = sx_split(csv, ","); + if (!fields) + return 1; + for (size_t i = 0; fields[i].ref != NULL; i++) + printf("[%zu] \"%.*s\" (offset %zu, len %zu)\n", i, + (int)fields[i].len, sx_buf_view_mut(fields[i]), + fields[i].offset, fields[i].len); + free(fields); + sx_free(csv); + return 0; +} +``` + +```text +[0] "id" (offset 0, len 2) +[1] "" (offset 3, len 0) +[2] "name" (offset 4, len 4) +[3] "" (offset 9, len 0) +``` + +### 裁剪输入 + +`sx_view_trim` 从两端去掉 ASCII 空白集合 `{space, \t, \v, \f, \r, \n}`, +不进行拷贝。若缓冲区之后可能变化,请把裁剪后的视图复制成自有缓冲区。 + +```c +#include +#include + +int main(void) { + sx_t *raw = sx_new_from_cstr(" \t hello world \r\n"); + sx_view_t trimmed = sx_view_trim(sx_view(raw)); + printf("[%.*s]\n", sx_len_view(trimmed), sx_buf_view_mut(trimmed)); + + sx_t *copy = sx_new_from_view(trimmed); /* independent copy */ + printf("[%s] len=%d\n", sx_buf_mut(copy), sx_len(copy)); + sx_free(copy); + sx_free(raw); + return 0; +} +``` + +```text +[hello world] +[hello world] len=11 +``` + +只由空白组成的视图会被裁剪成位于其槽位末尾的空视图;对于整缓冲区视图,就是 +`(offset = len(h), len = 0)`。 + +### 原地修改 + +`sx_write` 覆盖写入但不缩短,`sx_erase` 删除一段,`sx_insert` 右移尾部。 +三者都返回 `self`。 + +```c +#include +#include + +int main(void) { + sx_t *s = sx_new_from_cstr("the quick brown fox"); + s = sx_write_cstr(s, 10, "green"); /* same length: overwrite */ + s = sx_erase(s, 0, 4); /* remove "the " */ + s = sx_insert_cstr(s, 0, "red "); /* prepend */ + s = sx_truncate(s, (size_t)sx_len(s) - 4); /* drop " fox" */ + printf("%s (len %d)\n", sx_buf_mut(s), sx_len(s)); + s = sx_clear(s); /* len 0, capacity kept */ + printf("after clear: len=%d cap=%d\n", sx_len(s), sx_cap(s)); + sx_free(s); + return 0; +} +``` + +```text +red quick green (len 15) +after clear: len=0 cap=20 +``` + +`sx_erase` 在 `idx + n > len` 时是返回 `self` 的空操作,`n == 0` 同样如此。 +`sx_insert` 要求 `0 <= idx <= len`;`idx > len` 属于契约之外。增长的 +`sx_truncate` 与越界的 `sx_write` 会留下未指定的间隙字节。 + +### 正则提取、替换与分割 + +编译一次、复用、最后释放。匹配与 token 结果是指向 subject 的视图;替换返回 +新缓冲区,永不修改 subject。 + +```c +#include +#include +#include + +int main(void) { + sx_reg_t *re = sx_reg_compile("[a-z]+@[a-z.]+"); + if (!re) + return 1; + sx_t *msg = sx_new_from_cstr("bob@example.com;alice@example.org"); + + sx_view_t m = sx_reg_match(re, msg); /* leftmost match */ + if (m.ref != NULL) + printf("first: %.*s\n", (int)m.len, sx_buf_view_mut(m)); + + sx_view_t *hits = sx_reg_match_all(re, msg); /* non-overlapping */ + for (size_t i = 0; hits && hits[i].ref != NULL; i++) + printf("hit %zu: %.*s\n", i, (int)hits[i].len, sx_buf_view_mut(hits[i])); + free(hits); + + sx_t *out = sx_reg_replace(re, msg, "<$0>"); /* $0 = whole match */ + printf("replaced: %s\n", sx_buf_mut(out)); + sx_free(out); + + sx_view_t *tokens = sx_reg_split(re, msg); /* gaps between matches */ + for (size_t i = 0; tokens && tokens[i].ref != NULL; i++) + printf("token %zu: \"%.*s\"\n", i, (int)tokens[i].len, + sx_buf_view_mut(tokens[i])); + free(tokens); + + sx_free(msg); + sx_reg_free(re); + return 0; +} +``` + +```text +first: bob@example.com +hit 0: bob@example.com +hit 1: alice@example.org +replaced: ; +token 0: "" +token 1: ";" +token 2: "" +``` + +## 常见陷阱 + +以下是把测试有意列为契约之外的调用与习惯,以及已经写入文档、但容易忽略的边界 +情况: + +- 把缓冲区交给消费型调用之后继续使用:`sx_append(s, part)`、 + `sx_write(s, idx, part)` 与 `sx_insert(s, idx, part)` 都会释放 `part`。 +- 通过 owned 形式把缓冲区传给它自己:`sx_append(s, s)`、`sx_write(s, idx, s)`、 + `sx_insert(s, idx, s)`。要把缓冲区原地翻倍,请用 + `sx_append_view(s, sx_view(s))` 与 `sx_write_view`,它们接受指向 `s` 的视图。 + `sx_insert_view` 也接受这种视图,前提是切片起点不晚于 `idx`(测试覆盖的 + 情形);起点晚于 `idx` 的自别名切片会被尾部右移覆盖,请先复制该切片。 +- `sx_insert*` 的 `idx > len`:尾部右移会下溢。受测契约是 `0 <= idx <= len`。 + `sx_write*` 不同:它会填充并扩展。 +- 读取增长的 `sx_truncate` 之后 `[old_len, n)` 内的未指定字节,或 `sx_write` + 越界写入后 `[len, idx)` 内的字节。读取之前先把间隙写满。 +- 在 `sx_split`、`sx_reg_match_all`、`sx_reg_split` 或 `sx_find_all*` 返回的 + 视图/数组仍在使用时修改缓冲区,或在长度变化之后继续保留视图。视图不会被调整, + 扩容后可能指向已释放的内存。 +- 把 `sx_find_all*` 的结果读到 `arr[0] + 1` 项之外;它的形状是 + `{count, positions...}`。 +- 把 `sx_erase` 在 `idx + n > len` 时当成错误。它是有文档说明的空操作,返回 + `self`。 +- 向不检查 NULL 的函数传入 NULL 句柄(见[错误与哨兵值](#错误与哨兵值))。 + `sx_free(NULL)` 与 `sx_len(NULL)` 属于契约之外。 +- 忘记释放:缓冲区用 `sx_free`,视图数组用 `free`,已编译模式用 `sx_reg_free`。 + 视图不需要释放。 +- `sx_split` 的分隔符为空时返回 `NULL`;它不会按每个字节分割。 +- 正则模式是 C 字符串,不能包含字面 NUL。subject 可以包含。 +- `sx_new_from_cstr` 与所有 `_cstr` 实参都在第一个 NUL 处停下;二进制内容请用 + 视图。 +- `sx_substr` 要求 `idx + n <= len(h)`;`sx_view_range` 要求 + `off <= len(底层缓冲区)`(`len` 会被钳制到缓冲区末尾,`off` 不会)。两者都不会 + 钳制前置条件本身。 +- 在多线程间共享同一个 `sx_t` 且不加同步。库内部没有锁;唯一文档化为不可变、 + 可共享的对象是已编译的 `sx_reg_t`。 + +## 性能说明 + +- **已知追加量时先预留。** `sx_reserve(self, n)` 保证 `cap >= n + 1` 且不 + 缩小容量,因此缓冲区可以增长到 `n` 个内容字节而不重新分配。不预留时扩容仍是 + 摊还的:分配量翻倍;容量达到 64 KiB 后改为每次增加 `0x10000`。 +- **视图不拷贝。** `sx_view`、`sx_view_advance` 及其他视图移动函数都是 O(1), + 不分配内存。只读切片优先用它们;只有在需要独立缓冲区时才用 `sx_substr` 或 + `sx_new_from_view`。 +- **查找是线性的。** 单字节 needle 使用 `memchr` / `memrchr`;更长的 needle + 使用正向或反向 KMP,复杂度 O(n + m)。`sx_find_all*` 会报告重叠匹配,并按 + 匹配数精确分配数组。 +- **分割与正则扫描都是两遍。** 先统计 token 或匹配数量,再一次性精确分配数组; + 代价是对 subject 扫描两遍。 +- **正则只编译一次。** `sx_reg_compile` 是开销最大的调用;match、replace 与 + split 复用已编译模式,每次只分配自己的匹配数据。`sx_reg_is_match` 是最便宜的 + 存在性检查。 +- **容量不会归还。** `sx_truncate`、`sx_erase` 与 `sx_clear` 都保留分配, + 这使清空后的缓冲区可以复用,但也意味着峰值分配会一直保留到 `sx_free`。 + +## 常见问题 + +**使用缓冲区需要 PCRE2 吗?** 构建库时需要:源码树会链接 `pcre2-8`, +`./make` 需要 `libpcre2-dev`。使用已安装的 `libstringx` 时只需链接 +`-lstringx`;共享库自身带有 PCRE2 依赖。 + +**所有函数都支持 NULL 吗?** 不。只有[错误与哨兵值](#错误与哨兵值)中列出的 +情况有定义;其他情况下 NULL 句柄都属于契约之外。 + +**String X 感知 UTF-8 吗?** 不。它是字节库:长度、比较与查找都按字节精确 +处理,正则层运行在 PCRE2 的 8 位非 UTF 模式,因此 `\d`、`\w`、`\s` 与 `\b` +只匹配 ASCII。 + +**如何复制一个视图?** `sx_new_from_view(v)` 返回自有缓冲区,其中是视图 +`len` 个字节的精确副本。 + +**如何取得子串?** `sx_view_range` 与 `sx_view_advance` 给出零拷贝视图; +`sx_substr(h, idx, n)` 给出自有副本。 + +**为什么 `sx_len` 返回 `int`?** 这是库的实际大小上限:内容超过 `INT_MAX` +字节不在受测契约之内。偏移是 `size_t`,因此查找与视图位置仍是全宽度。 + +**已编译的正则可以在线程间共享吗?** 可以:已编译的 `sx_reg_t` 不可变,每次 +调用使用各自的匹配数据。在线程间共享 `sx_t` 缓冲区则不受支持。 + +**零长匹配是什么样子?** `sx_reg_match` 返回 `ref != NULL`、`len == 0` 的 +视图;`sx_reg_match_all` 与 `sx_reg_split` 会报告它,并把扫描继续推进一个 +字节。 + +--- + +[← 上一页](getting-started.md) · [文档首页](README.md) · [下一页 →](api-buffer.md) diff --git a/docs/zh_cn/regex.md b/docs/zh_cn/regex.md new file mode 100644 index 0000000..8dc7b4c --- /dev/null +++ b/docs/zh_cn/regex.md @@ -0,0 +1,522 @@ +[English](../en_us/regex.md) · 中文 + +[文档首页](README.md) › 正则表达式 + +# 正则表达式 + +## 概述 + +`` 在核心缓冲区 API 之上加入了一个高级层:对 **PCRE2 8 位库** +(`pcre2-8`,版本 10.46)的一层薄封装,配置固定。它提供编译/释放这一对 +函数,以及匹配、替换、分割三个家族,并且有意不自带任何策略:本页没有 +说明的行为,一律是 PCRE2 的默认行为。 + +这一层的使用方式围绕一个生命周期: + +1. 把一个模式编译成不透明的 `sx_reg_t *` 句柄; +2. 对任意多个 `sx_t` 主体(subject)执行任意多次调用; +3. 最后用 `sx_reg_free` 释放该句柄一次。 + +已编译的句柄不可变,可以跨线程共享;每次调用使用自己的匹配数据。主体按 +**字节长度**匹配,因此内嵌 NUL 是普通数据(二进制安全);模式和替换模板 +都是 C 字符串,不能包含字面 NUL。 + +该层属于 `libstringx`,由库自身链接 `pcre2-8`:使用者只需链接 +`-lstringx`,无需额外的 PCRE2 链接参数。PCRE2 采用 BSD-3-Clause 许可, +归属声明见 [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md)。 +`$n` 替换规则见[替换模板](#替换模板);按任务组织的用法示例见 +[用户指南](guide.md)。 + +各家族一览: + +| 家族 | 函数 | 结果 | +| --- | --- | --- | +| 编译 / 释放 | `sx_reg_compile`, `sx_reg_free` | 句柄 | +| 匹配 | `sx_reg_is_match`, `sx_reg_match`, `sx_reg_match_all` | 0/1、单个视图或数组 | +| 替换 | `sx_reg_replace`, `sx_reg_replace_first` | 新的 `sx_t` | +| 分割 | `sx_reg_split` | 视图数组 | + +## 生命周期 + +在使用它的循环之前把模式编译一次,并保留句柄。模式字符串本身不会被保留, +因此编译后可以立即释放。句柄不再需要时,用 `sx_reg_free` 释放。 + +```c +#include +#include +#include + +static void show(const char *label, sx_view_t v) { + printf("%s: ", label); + if (v.ref == NULL) { + printf("\n"); + return; + } + fwrite(sx_buf_view_mut(v), 1, v.len, stdout); + putchar('\n'); +} + +int main(void) { + sx_t *h = sx_new_from_cstr("bob@example.com and alice@example.org"); + sx_reg_t *re = sx_reg_compile("(\\w+)@(\\w+\\.\\w+)"); + if (!h || !re) + return 1; + + printf("is_match: %d\n", sx_reg_is_match(re, h)); + show("first", sx_reg_match(re, h)); + + sx_view_t *all = sx_reg_match_all(re, h); + for (int i = 0; all && all[i].ref != NULL; i++) + printf("match %d: %zu bytes at offset %zu\n", i, all[i].len, + all[i].offset); + free(all); + + sx_t *out = sx_reg_replace(re, h, "[$2: $1]"); + if (out) { + printf("replaced: "); + fwrite(sx_buf_mut(out), 1, (size_t)sx_len(out), stdout); + putchar('\n'); + sx_free(out); + } + + sx_view_t *tok = sx_reg_split(re, h); + for (int i = 0; tok && tok[i].ref != NULL; i++) + printf("token %d: %zu bytes\n", i, tok[i].len); + free(tok); + + sx_reg_free(re); + sx_free(h); + return 0; +} +``` + +让这套 API 可以安全地用于长期运行代码的,是下面三点: + +- 句柄独立于主体:一个已编译模式可以服务任意多个缓冲区; +- 别名到主体的结果是视图,因此只在该主体存活且长度不变期间有效; +- `sx_reg_match_all` 和 `sx_reg_split` 返回的数组归调用方所有:用 + `free()` 释放,而不是 `sx_free`。 + +### sx_reg_compile + +```c +sx_reg_t *sx_reg_compile(const char *pattern); +``` + +用 PCRE2 编译一个模式,返回不透明句柄。 + +| 参数 | 含义 | +| --- | --- | +| `pattern` | 以 NUL 结尾的 PCRE2 模式;句柄不会保留该字符串 | + +返回新句柄;当 `pattern` 为 `NULL`、模式语法无效或分配失败时返回 +`NULL`。封装层不暴露 PCRE2 的错误码和错误位置,因此这几种情况无法区分: +开发阶段请先校验模式,并把 `NULL` 一律当作"不要使用这个句柄"。 + +说明: + +- 模式字符串可以在调用后立即释放或修改。 +- 不会向 PCRE2 传递任何编译选项。模式内部选用的 PCRE2 特性(例如内联 + 选项 `(?i)`)仍然生效。 +- 相对于单次匹配调用,编译才是这一层里昂贵的一步,所以应当编译一次并 + 复用句柄([性能](#性能))。 + +```c +sx_reg_t *re = sx_reg_compile("(\\w+)@(\\w+)"); /* 输入非法时为 NULL */ +/* re == NULL 表示:pattern 为 NULL、语法无效,或内存不足 */ +/* ... 执行匹配 / 替换 / 分割调用 ... */ +sx_reg_free(re); /* 最后一次使用后释放句柄 */ +``` + +### sx_reg_free + +```c +void sx_reg_free(sx_reg_t *r); +``` + +释放已编译句柄。允许传入 `NULL`,此时为空操作。 + +说明: + +- 只释放一次,且要在最后一次使用它的调用之后。 +- 之前调用返回的数据不依赖该句柄:匹配视图别名到主体,数组归调用方所有。 +- 再次使用已释放的句柄属于契约之外。 + +```c +sx_reg_free(re); /* 最后一次使用后释放句柄 */ +``` + +## 匹配家族 + +三个调用都从左侧开始扫描主体的内容字节,遵循 PCRE2 的**最左优先** +(leftmost-first)语义:起始位置最早的匹配获胜;在同一字节起始的多个 +候选中,由 PCRE2 的偏好顺序决定。零长匹配也是真正的匹配。视图别名到 +主体:不拷贝任何字节,也从不修改 `h`。 + +### sx_reg_is_match + +```c +int sx_reg_is_match(const sx_reg_t *r, const sx_t *h); +``` + +回答"模式是否在 `h` 中任意位置匹配?"。 + +| 参数 | 含义 | +| --- | --- | +| `r` | 已编译模式 | +| `h` | 主体缓冲区 | + +若 `h` 中存在匹配返回 `1`,否则返回 `0`——包括 `r` 或 `h` 为 `NULL`、 +或内部分配失败的情况。零长匹配也算匹配,因此 `a*` 能匹配空主体。 + +说明: + +- 最便宜的存在性检查:一次 PCRE2 匹配调用,不分配结果。每次调用仍会创建 + 并释放自己的小型 PCRE2 匹配数据块。 +- 主体按字节长度搜索;锚点指向字节偏移。 + +```c +sx_reg_t *re = sx_reg_compile("a*"); +sx_t *empty = sx_new(); +int yes = sx_reg_is_match(re, empty); /* 1:零长匹配也算匹配 */ +sx_free(empty); +sx_reg_free(re); +``` + +### sx_reg_match + +```c +sx_view_t sx_reg_match(const sx_reg_t *r, const sx_t *h); +``` + +把最左匹配作为视图返回,指向 `h` 内部。 + +| 参数 | 含义 | +| --- | --- | +| `r` | 已编译模式 | +| `h` | 主体缓冲区 | + +成功时结果是 `h` 缓冲区上的视图:`.ref` 指向主体,`.offset` / `.len` +选出匹配到的字节。无匹配、参数为 `NULL` 或分配失败时返回空视图 +`{ref = NULL, offset = 0, len = 0}`。零长匹配仍是匹配: +`.ref != NULL` 且 `.len == 0`。 + +说明: + +- 最左匹配,而不是"最长匹配":候选之间的先后由 PCRE2 决定,例如 + `b|bc` 对 `abc` 会匹配偏移 1 处的 `b`。 +- 只做一次 PCRE2 匹配调用;返回的视图不是拷贝。 +- 锚点遵循 PCRE2 默认规则:`^` 匹配主体起点(偏移 0),`$` 匹配主体 + 结尾;默认情况下 `$` 也能匹配最后一个换行符之前的位置。 +- 在 `h` 被释放后,或在修改 `h` 长度之后使用该视图,属于契约之外。 + +```c +sx_reg_t *re = sx_reg_compile("bc"); +sx_t *h = sx_new_from_cstr("abc"); +sx_view_t v = sx_reg_match(re, h); /* v.offset == 1,v.len == 2("bc") */ +sx_free(h); +sx_reg_free(re); +``` + +### sx_reg_match_all + +```c +sx_view_t *sx_reg_match_all(const sx_reg_t *r, const sx_t *h); +``` + +从左到右扫描一遍,收集全部匹配。 + +| 参数 | 含义 | +| --- | --- | +| `r` | 已编译模式 | +| `h` | 主体缓冲区 | + +返回 `malloc` 分配的视图数组,形态与 `sx_split` 一致: +`arr[0 .. count-1]` 是各次匹配,`arr[count].ref == NULL` 是结束哨兵。 +调用方用 `free()` 释放数组;视图别名到 `h`,在 `h` 存活且长度不变期间 +有效。 + +完全没有匹配、`r` 或 `h` 为 `NULL`、或分配失败时返回 `NULL`。该 API +无法区分这三种情况。 + +说明: + +- 匹配之间不重叠:每次匹配后从匹配结尾继续扫描;零长匹配则再向右移动 + 一个字节([扫描规则](#扫描规则))。 +- 计数和填充是同一确定性扫描的两遍,因此数组只按最终大小分配一次。 +- `sx_find_all*` 报告的是可能重叠的位置;`sx_reg_match_all` 报告的是 + 正则匹配,它们不可能重叠。 + +```c +sx_reg_t *re = sx_reg_compile("a*"); +sx_t *h = sx_new_from_cstr("bbb"); +sx_view_t *arr = sx_reg_match_all(re, h); +int n = 0; +while (arr[n].ref != NULL) + n++; /* n == 4:偏移 0、1、2、3 处各有一个零长匹配 */ +free(arr); +sx_free(h); +sx_reg_free(re); +``` + +## 扫描规则 + +`sx_reg_match_all` 和 `sx_reg_split` 共用同一套扫描规则: + +- 匹配按从左到右的顺序取,且互不重叠; +- 一次匹配之后,下一次搜索从该匹配的结尾开始; +- 零长匹配之后,下一次搜索从匹配起点**向右一个字节**开始,因此能匹配 + 空串的模式不会让扫描停滞; +- 匹配可以正好结束于 `len(h)`(例如 `$`);随后扫描停止,因为 PCRE2 + 拒绝超出主体的起始偏移。 + +| 模式 | 主体 | 报告的匹配(偏移, 长度) | +| --- | --- | --- | +| `aa\|aaa` | `aaaa` | (0,2), (2,2) —— `aaa` 没有机会 | +| `a*` | `bbb` | (0,0), (1,0), (2,0), (3,0) | +| `$` | `abc` | (3,0) | +| `bc` | `abcb` | (1,2) | + +同一条规则决定了 `sx_reg_split` 的 token 数量:始终等于 +`匹配数 + 1`。 + +## 替换家族 + +两个替换调用都把 C 字符串模板代入匹配处,并返回**新的**、归调用方所有的 +`sx_t`;`h` 永远不会被修改。结果与其他缓冲区一样用 `sx_free` 释放。 + +### sx_reg_replace + +```c +sx_t *sx_reg_replace(const sx_reg_t *r, const sx_t *h, const char *repl); +``` + +用 `repl` 替换 `h` 中的每一处匹配。 + +| 参数 | 含义 | +| --- | --- | +| `r` | 已编译模式 | +| `h` | 主体缓冲区;不会被修改 | +| `repl` | 以 NUL 结尾的替换模板;不会被保留 | + +返回新缓冲区;当 `r`、`h` 或 `repl` 为 `NULL`、PCRE2 拒绝该模板、或 +分配失败时返回 `NULL`。参数合法但没有匹配时,结果是 `h` 的**原样拷贝**, +绝不会是 `NULL`。 + +说明: + +- 模板会展开 `$0` / `$n`;见[替换模板](#替换模板)。 +- 零长匹配也会被替换:`a*` 对 `bbb`、模板为 `-` 时得到 `-b-b-b-`。 +- 空模板会删除每一处匹配,因此模式匹配整个主体时结果为空缓冲区。 +- 字节精确:`h` 中的内嵌 NUL 是普通匹配数据,并会原样复制进结果。 + +```c +sx_reg_t *re = sx_reg_compile("(\\w+) (\\w+)"); +sx_t *h = sx_new_from_cstr("hello world"); +sx_t *swapped = sx_reg_replace(re, h, "$2 $1"); /* "world hello" */ +sx_free(swapped); +sx_free(h); +sx_reg_free(re); +``` + +### sx_reg_replace_first + +```c +sx_t *sx_reg_replace_first(const sx_reg_t *r, const sx_t *h, + const char *repl); +``` + +契约与 `sx_reg_replace` 相同,但只替换**最左**的一处匹配;其余字节原样 +拷贝。 + +```c +sx_reg_t *re = sx_reg_compile("x"); +sx_t *h = sx_new_from_cstr("xax"); +sx_t *out = sx_reg_replace_first(re, h, "<$0>"); /* "ax" */ +sx_free(out); +sx_free(h); +sx_reg_free(re); +``` + +## 替换模板 + +两个替换调用都按 PCRE2 的替换语法解释 `repl`,并固定设置两个选项,使缺失 +的捕获组不会造成问题。 + +| 模板元素 | 展开为 | +| --- | --- | +| `$0` | 整个匹配 | +| `$n`(`n >= 1`) | 第 `n` 个捕获组;该组未参与匹配或不存在时展开为空串 | +| 其他文本 | 原样拷贝;`$` 和 `\` 的字面写法仍由 PCRE2 替换语法定义 | + +| 模式 | 主体 | 模板 | 结果 | +| --- | --- | --- | --- | +| `(\w+) (\w+)` | `hello world` | `$2 $1` | `world hello` | +| `(a)(b)` | `ab` | `$1$3` | `a` | +| `a(b)?` | `a` | `[$1]` | `[]` | +| `abc` | `abc` | (空模板) | (空缓冲区) | + +说明: + +- 封装层传入 PCRE2 的 `PCRE2_SUBSTITUTE_UNSET_EMPTY` 和 + `PCRE2_SUBSTITUTE_UNKNOWN_UNSET`:未参与匹配的组和根本不存在的组都 + 展开为空串。因此模板不会仅仅因为缺少某个捕获组而被拒绝。 +- `$n` 指向每一次被替换的匹配自己的捕获组;第 0 组是整个匹配。 +- `repl` 是 C 字符串,因此其中不能出现字面 NUL。匹配到的 NUL 字节仍会 + 通过 `$0` / `$n` 进入结果。 +- 完整的替换语法属于 PCRE2;见 + [PCRE2 文档](https://www.pcre.org/)。 + +## 分割家族 + +### sx_reg_split + +```c +sx_view_t *sx_reg_split(const sx_reg_t *r, const sx_t *h); +``` + +把 `h` 分割为非重叠匹配之间的空隙。 + +| 参数 | 含义 | +| --- | --- | +| `r` | 已编译模式 | +| `h` | 主体缓冲区 | + +返回 `malloc` 分配的数组,形态与 `sx_split` 完全一致: +`arr[0 .. count-1]` 是按顺序排列的 token,`arr[count].ref == NULL` 是 +结束哨兵,且 `count == 匹配数 + 1`。各边界处以及内部产生的空 token 都会 +保留。调用方用 `free()` 释放数组;token 是 `h` 上的视图。 + +参数为 `NULL` 或分配失败时返回 `NULL`。没有匹配不是错误:此时数组中只有 +整个主体这一个 token。 + +说明: + +- 零长匹配会在每个位置分割:`a*` 对 `bbb` 得到 `""`、`"b"`、`"b"`、 + `"b"`、`""`,共五个 token。 +- 匹配覆盖整个主体时,产生两个空 token。 +- 开头和结尾的匹配会产生空的首尾 token;相邻匹配之间产生内部空 token。 +- token 使用期间不要修改 `h`(视图是快照;见[用户指南](guide.md))。 + +```c +sx_reg_t *re = sx_reg_compile("[0-9]+"); +sx_t *h = sx_new_from_cstr("a1b22c"); +sx_view_t *tok = sx_reg_split(re, h); +/* 3 个 token:"a" (0,1)、"b" (2,1)、"c" (5,1) —— "22" 是一处匹配 */ +free(tok); +sx_free(h); +sx_reg_free(re); +``` + +## 二进制安全 + +| 方向 | 规则 | +| --- | --- | +| 主体 `h` | 按字节长度匹配;内嵌 NUL 和任意字节值都是普通数据 | +| 模式 | 是 C 字符串:以 NUL 结尾,因此模式内部不能有字面 NUL | +| 模板 `repl` | 是 C 字符串:不能有字面 NUL;捕获组可以把 NUL 字节带入结果 | + +- PCRE2 运行在 **8 位非 UTF 模式**:`\d`、`\w`、`\s`、`\b` 等只匹配 + ASCII。组成非 ASCII 字符的字节(例如 UTF-8 字节 `C2 A5`)永远不会匹配 + `\d`。 +- 在 8 位非 UTF 模式下,`.` 匹配除换行以外的任意字节,包括内嵌 NUL: + 模式 `A.B` 能匹配三个字节 `A\0B`。 +- 替换在两个方向上都是二进制安全的:主体 `a\0b`、模式 `b`、模板 `B` + 得到 `a\0B`;对同一主体用 `.` 搭配模板 `X` 得到 `XXX`。 +- 由于模式是 C 字符串,主体中的 NUL 字节只能用 PCRE2 转义描述;见 + [PCRE2 文档](https://www.pcre.org/)。 + +## 错误哨兵 + +任何有文档的调用都不会因为非法输入、无匹配或分配失败而崩溃;每个家族用 +固定的哨兵值报告这些情况。 + +| 调用 | 无匹配 | `NULL` 参数 / 非法输入 | 分配失败 | +| --- | --- | --- | --- | +| `sx_reg_compile` | —— | `NULL`(语法错误也如此) | `NULL` | +| `sx_reg_free` | —— | `NULL` 为空操作 | —— | +| `sx_reg_is_match` | `0` | `0` | `0` | +| `sx_reg_match` | 空视图 `{ref = NULL}` | 空视图 | 空视图 | +| `sx_reg_match_all` | `NULL` | `NULL` | `NULL` | +| `sx_reg_replace` | 原样拷贝 | `NULL` | `NULL` | +| `sx_reg_replace_first` | 原样拷贝 | `NULL` | `NULL` | +| `sx_reg_split` | 单 token 数组(整个主体) | `NULL` | `NULL` | + +说明: + +- 对 `sx_reg_match_all` 和 `sx_reg_split`,"无匹配"和分配失败都返回 + `NULL`;数组家族无法区分二者。 +- 对替换家族,"无匹配"是正常成功:得到 `h` 的原样拷贝。 +- 数组由 `malloc` 分配,用 `free()` 释放;替换家族返回的缓冲区是 + `sx_t *`,用 `sx_free()` 释放。 + +## 线程安全 + +- 已编译的 `sx_reg_t` 在 `sx_reg_compile` 之后不可变。它没有可变状态, + 封装层也不保存全局状态,因此同一个句柄可以被多个线程同时使用。 +- 每个匹配/分割调用都会创建自己的 PCRE2 匹配数据块 + (`pcre2_match_data_create_from_pattern`)并在返回前释放;替换调用委托 + 给 `pcre2_substitute`,同样使用每次调用自己的匹配数据。两个线程不会 + 共享匹配状态。 +- 主体缓冲区是普通内存,没有加锁:并发只读没有问题,任何修改都需要外部 + 同步。 +- 视图和数组是主体的快照。某个线程仍在读取视图时不要修改主体;其他线程 + 仍在使用句柄时不要释放它。 + +## 性能 + +| 调用 | PCRE2 工作量 | 封装层分配 | 结果 | +| --- | --- | --- | --- | +| `sx_reg_compile` | 一次编译 | 代码加句柄 | 句柄 | +| `sx_reg_is_match` | 一次匹配调用 | 仅匹配数据 | `0` / `1` | +| `sx_reg_match` | 一次匹配调用 | 仅匹配数据 | 一个视图 | +| `sx_reg_match_all` | 扫描两遍 | 匹配数据加一个精确大小的数组 | 数组 | +| `sx_reg_split` | 扫描两遍 | 匹配数据加一个精确大小的数组 | 数组 | +| `sx_reg_replace*` | 两次替换调用 | PCRE2 内部匹配数据、一个临时缓冲区、一个 `sx_t` | 新缓冲区 | + +说明: + +- 编译一次:模式编译的成本远高于单次匹配,在循环里反复编译是唯一本可 + 避免的性能错误。 +- `sx_reg_is_match` 是最便宜的存在性检查;`sx_reg_match` 只多出一个返回 + 视图。 +- `sx_reg_match_all` 和 `sx_reg_split` 扫描两遍(先计数、再填充),因此 + 结果数组只分配一次,绝不通过 `realloc` 增长。 +- 替换家族先用第一次 `pcre2_substitute` 调用探测精确输出长度,再用第二次 + 调用填充合适大小的缓冲区;缓冲区随后一次性拷贝进返回的 `sx_t`。 +- 每次调用都会分配并释放匹配数据;调用之间不缓存匹配数据,封装层也不启用 + PCRE2 JIT 或任何编译选项。 +- 主体永远不会被拷贝;只有替换家族会分配结果缓冲区。 + +## 选择合适的调用 + +| 需求 | 调用 | 返回 | 所有权 | +| --- | --- | --- | --- | +| 是否有任意匹配? | `sx_reg_is_match` | `int` 0/1 | 无 | +| 最左匹配 | `sx_reg_match` | 指向 `h` 的视图 | 无;视图是快照 | +| 全部匹配 | `sx_reg_match_all` | `malloc` 数组加结束哨兵 | 调用方:`free()` | +| 替换全部匹配 | `sx_reg_replace` | 新的 `sx_t` | 调用方:`sx_free()` | +| 只替换第一处匹配 | `sx_reg_replace_first` | 新的 `sx_t` | 调用方:`sx_free()` | +| 分割成字段 | `sx_reg_split` | `malloc` 数组加结束哨兵 | 调用方:`free()` | + +## PCRE2 语义 + +封装层固定了一组简单、刻意的配置: + +- **8 位、非 UTF**:模式和主体都是字节,字符类是 ASCII,不做 UTF 校验。 + 在默认(未开启 `DOTALL`)模式下,`.` 不匹配换行。 +- **不暴露选项标志**:封装层不传编译选项、不传匹配选项,也不传匹配上下文。 + 写在模式内部的 PCRE2 特性(例如内联选项)仍然生效;大小写不敏感、多行 + 匹配等行为用 PCRE2 的模式内语法请求。 +- **以 PCRE2 默认行为为准**:最左优先的选择、贪婪/懒惰量词、锚点、反向 + 引用以及其他所有模式语义都属于 PCRE2,而不是封装层。 +- 封装层不暴露 PCRE2 错误码或编译错误位置。 + +模式语法与语义由 PCRE2 项目在 [pcre.org](https://www.pcre.org/) 记录; +本库不会重复记录它们。随附的 PCRE2 版本为 10.46;该依赖采用 +BSD-3-Clause 许可,归属声明见 +[THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md)。 + +--- + +[← 上一页](api-search.md) · [文档首页](README.md) · [下一页 →](design.md) From d9541228c62c10470d974a24813fd024d60a3851 Mon Sep 17 00:00:00 2001 From: minelogy-dev <72928567+minelogy-dev@users.noreply.github.com> Date: Thu, 12 Nov 2026 06:54:48 -0800 Subject: [PATCH 2/2] docs: polish bilingual manual and sync with latest behavior - tighten the prose to a concise, direct style; rewrite the quick-start example as a single chained expression that shows memory-safe ownership - replace Forge tutorials with a link and the commands users actually need - document the write-range overflow contract (NULL return, target unchanged, owned input still consumed) and the native memmem fast path for sx_find*, including the SX_FORCE_NO_MEMMEM fallback - sync with the 24-test suite and the new write-safety, search-performance and benchmark workflows - fold the upstream docs/WRITE_SAFETY.md into the bilingual manual and keep docs/ organized as docs/en_us + docs/zh_cn --- README.md | 25 +- README.zh-CN.md | 24 +- docs/WRITE_SAFETY.md | 42 --- docs/en_us/README.md | 4 +- docs/en_us/api-buffer.md | 491 +++++++++++------------- docs/en_us/api-search.md | 322 +++++++--------- docs/en_us/build-and-test.md | 199 ++++------ docs/en_us/ci.md | 109 +++--- docs/en_us/contributing.md | 156 ++++---- docs/en_us/design.md | 688 +++++++++++++++++----------------- docs/en_us/getting-started.md | 68 ++-- docs/en_us/guide.md | 152 ++++---- docs/en_us/regex.md | 313 +++++++--------- docs/zh_cn/README.md | 4 +- docs/zh_cn/api-buffer.md | 446 +++++++++++----------- docs/zh_cn/api-search.md | 359 ++++++++---------- docs/zh_cn/build-and-test.md | 169 ++++----- docs/zh_cn/ci.md | 87 +++-- docs/zh_cn/contributing.md | 114 +++--- docs/zh_cn/design.md | 584 +++++++++++++++-------------- docs/zh_cn/getting-started.md | 62 ++- docs/zh_cn/guide.md | 147 ++++---- docs/zh_cn/regex.md | 257 ++++++------- 23 files changed, 2241 insertions(+), 2581 deletions(-) delete mode 100644 docs/WRITE_SAFETY.md diff --git a/README.md b/README.md index 1020cf7..68d6cf2 100644 --- a/README.md +++ b/README.md @@ -40,8 +40,7 @@ The Chinese edition is under [`docs/zh_cn/`](docs/zh_cn/README.md). ## Requirements - A C23 compiler (GCC and Clang), Linux -- The `forge` build tool to build from source (https://github.com/minelogy-dev/forge — - a custom build system; the tool compiles `build.c` into a local `./make` entry) +- [Forge](https://github.com/minelogy-dev/forge) to build from source - `libpcre2-dev` (PCRE2 8-bit) — the regex layer's dependency; the shared library links `pcre2-8` itself, so consumers only need `-lstringx` - `pkg-config` (or `pkgconf`) recommended for consumers — the installed @@ -50,7 +49,7 @@ The Chinese edition is under [`docs/zh_cn/`](docs/zh_cn/README.md). ## Build ```sh -forge . # compile build.c into ./make (re-run whenever build.c changes) +forge . # generate ./make ./make # build -> build/output/libstringx.so (+ headers at build/output/include) ./make test # build and run every test under tests/ (ASan + UBSan) ``` @@ -60,22 +59,28 @@ packaging and the test harness. ## Quick start +Edits return the handle they were given, so the whole chain is one +expression: `sx_append` consumes its `sx_t *` argument, and one `sx_free` +releases everything. + ```c #include #include int main(void) { - sx_t *msg = sx_new_from_cstr("hello, world"); - size_t at = sx_find_cstr(msg, ", "); - sx_t *hi = sx_substr(msg, 0, at); - fwrite(sx_buf_mut(hi), 1, (size_t)sx_len(hi), stdout); - putchar('\n'); /* hello */ - sx_free(hi); - sx_free(msg); + /* One expression: every call returns the same handle, and the temporary + buffer is consumed by sx_append, so there is nothing else to free. */ + sx_t *msg = sx_append(sx_append_cstr(sx_new(), "Hello, "), + sx_new_from_cstr("String X!")); + + printf("%s (%d bytes)\n", sx_buf_mut(msg), sx_len(msg)); + sx_free(msg); /* one buffer, one free */ return 0; } ``` +It prints `Hello, String X! (16 bytes)`. + Compile with (manually, or via pkg-config): ```sh diff --git a/README.zh-CN.md b/README.zh-CN.md index 535cd2f..096f986 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -35,8 +35,7 @@ ## 依赖 - C23 编译器(GCC / Clang),Linux -- 构建需要 `forge` 构建工具(https://github.com/minelogy-dev/forge —— 自定义 - 构建系统:它会将 `build.c` 编译成本地 `./make` 入口) +- 从源码构建需要 [Forge](https://github.com/minelogy-dev/forge) - `libpcre2-dev`(PCRE2 8 位)——正则层的依赖;共享库自身已链接 `pcre2-8`,使用者只需 `-lstringx` - 推荐使用者安装 `pkg-config`(或 pkgconf)—— 安装包自带 `libstringx.pc` @@ -44,7 +43,7 @@ ## 构建 ```sh -forge . # 把 build.c 编译成 ./make(改动 build.c 后需重跑) +forge . # 生成 ./make ./make # 构建 -> build/output/libstringx.so(头文件随附于 build/output/include) ./make test # 编译并运行 tests/ 下每个测试(ASan + UBSan) ``` @@ -53,22 +52,27 @@ forge . # 把 build.c 编译成 ./make(改动 build.c 后需重跑) ## 快速上手 +每次修改都返回传入的句柄,因此整条链是一个表达式:`sx_append` 消费传入的 +`sx_t *`,最后只需一次 `sx_free`。 + ```c #include #include int main(void) { - sx_t *msg = sx_new_from_cstr("hello, world"); - size_t at = sx_find_cstr(msg, ", "); - sx_t *hi = sx_substr(msg, 0, at); - fwrite(sx_buf_mut(hi), 1, (size_t)sx_len(hi), stdout); - putchar('\n'); /* hello */ - sx_free(hi); - sx_free(msg); + /* One expression: every call returns the same handle, and the temporary + buffer is consumed by sx_append, so there is nothing else to free. */ + sx_t *msg = sx_append(sx_append_cstr(sx_new(), "Hello, "), + sx_new_from_cstr("String X!")); + + printf("%s (%d bytes)\n", sx_buf_mut(msg), sx_len(msg)); + sx_free(msg); /* one buffer, one free */ return 0; } ``` +输出为 `Hello, String X! (16 bytes)`。 + 编译(手动,或经 pkg-config): ```sh diff --git a/docs/WRITE_SAFETY.md b/docs/WRITE_SAFETY.md deleted file mode 100644 index 99ed351..0000000 --- a/docs/WRITE_SAFETY.md +++ /dev/null @@ -1,42 +0,0 @@ -# Write offset arithmetic - -The write APIs accept a size_t offset. The sum of that offset and the -input length must fit in size_t and leave room for the terminating NUL. -For example, sx_write_cstr(s, SIZE_MAX, "X") previously wrapped the -reserve request to zero, then formed an out-of-bounds destination pointer. - -The shared write helper rejects arithmetic overflow before computing a -destination. sx_write_view also checks before its alias-preserving -pre-reserve, so an invalid range cannot mutate the target capacity first. -The existing reserve helper rejects a total content length of SIZE_MAX, -which cannot include a terminator. Owned write inputs are still consumed -on failure. Valid writes, binary data and view aliases retain their semantics. - -Tests exercise all three write APIs near SIZE_MAX with real small input -buffers, unchanged target contents/capacity, borrowed views, owned failures, -binary writes and valid aliased growth. Both normal and exact-reserve -configurations run under the existing sanitizer suite. - -The Write safety and cost workflow compiles the same regression against -the immutable old implementation, requires a sanitizer failure there, and -requires both fixed configurations to pass with GCC 14 and Clang 19. - -The focused performance check reuses the pinned audited harness from -7f8a624af4809c9dc606c41533991acd1b51917d. It generates an overwrite-only -harness and saves that exact source in the artifact. Source/target lengths -are equal (8/64/4096/65536 bytes), buffers are preallocated, and binary -contents are compared in full outside timing. The APIs are sx_write_view, -sdscpylen and bassignblk, with raw memcpy using the same SDS buffer as a -control. This contract is an equal-length overwrite; it does not compare -their different truncation/extension semantics. - -Before/after StringX and peers run on the same pinned CPU, with three -fresh processes and seven samples per group. Separate translation units, -no LTO, verification-only call counters and release disassembly preserve -the audited call structure. Hot and CLFLUSH-based data conditions are -reported separately; flushing cost is excluded. No counting is enabled in -timed release adapters. This is a targeted write-cost check; it makes no -new claim about search or growth performance. - -Other mutator arithmetic (such as insert/erase/view ranges) remains a -separate audit target. This change is limited to write-range validation. diff --git a/docs/en_us/README.md b/docs/en_us/README.md index 4181b96..9591d7b 100644 --- a/docs/en_us/README.md +++ b/docs/en_us/README.md @@ -38,8 +38,8 @@ backed by PCRE2. split, with the full contract of each call. - [Design & internals](design.md) — data layout, growth policy, search algorithms, regex wrapper internals, portability limits, testing strategy. -- [Build, test & package](build-and-test.md) — Forge, `./make` targets, the - test harness, sanitizers, installation and Debian packaging. +- [Build, test & package](build-and-test.md) — `./make` targets, the test + harness, sanitizers, installation and Debian packaging. - [Contributing](contributing.md) — workflow, contract-first documentation, code style, tests, licensing. - [Continuous integration](ci.md) — workflows, required checks, CodeQL, diff --git a/docs/en_us/api-buffer.md b/docs/en_us/api-buffer.md index 9e3cbd2..9a636a7 100644 --- a/docs/en_us/api-buffer.md +++ b/docs/en_us/api-buffer.md @@ -4,15 +4,11 @@ English · [中文](../zh_cn/api-buffer.md) # Buffers and views -The complete reference for the core buffer and view API declared in -`include/sx_core.h`: creating and releasing buffers, reading their -state, mutating content, taking substrings, and navigating and trimming -views. Search, comparison and splitting are documented in -[Search, compare and split](api-search.md). - -Every behavior statement below is derived from the public header -contract, the implementation, and the behavior-boundary comments in -`tests/*.c`. +The core buffer and view API of `include/sx_core.h`: creation, state, +mutation, substrings, view navigation and trimming. Search, comparison and +splitting are in [Search, compare and split](api-search.md). Behavior +statements come from the public headers, the implementation and the +`tests/*.c` boundary comments. ## Conventions @@ -23,17 +19,15 @@ contract, the implementation, and the behavior-boundary comments in ``` `sx.h` includes `sx_core.h` (buffers, views, search, comparison) and -then declares `sx_split` and the `sx_reg_*` family. Link the library -with `-lstringx`. All functions on this page are declared in -`sx_core.h`. `sx_raw.h` is an internal allocation/debug API and is not -part of the supported public interface. - -**One allocation per buffer.** An `sx_t` handle owns exactly one -NUL-terminated byte array: `ptr[0 .. len-1]` are the content bytes, -`ptr[len]` is always `'\0'`, and `cap` is the allocation size, with -`cap >= len + 1`. `len` counts content bytes, so an embedded `'\0'` is -ordinary data, not a terminator — the model is binary-safe by -construction. +declares `sx_split` and `sx_reg_*`. Link with `-lstringx`. Every function +on this page is declared in `sx_core.h`; `sx_raw.h` is an internal +allocation/debug API, not part of the supported public interface. + +**One allocation per buffer.** An `sx_t` handle owns one NUL-terminated +byte array: `ptr[0 .. len-1]` are the content bytes, `ptr[len]` is always +`'\0'`, `cap` is the allocation size and `cap >= len + 1`. `len` counts +content bytes, so an embedded `'\0'` is data, not a terminator — the +model is binary-safe by construction. **Ownership.** @@ -45,25 +39,24 @@ construction. | `sx_view_t` | none: it aliases a buffer | nothing; views are never freed | | array from `sx_find_all*` or `sx_split` | caller | `free` (see [api-search.md](api-search.md)) | -Every edit returns `self`, so calls chain and the handle stays stable. -The backing array may move when the buffer grows: pointers returned by -`sx_buf_mut`/`sx_buf_view_mut` become stale after any call that can -reallocate and must be re-fetched. - -**NULL and out of contract.** Documented NULL handling on this page: -`sx_new_from_cstr(NULL)` and `sx_dup(NULL)` return `NULL`; the -`owned` forms of `sx_append`, `sx_write` and `sx_insert`, and all -`_cstr` forms, return `NULL` and leave `self` untouched when their -second argument is `NULL`. Everything else dereferences a buffer or -window: `sx_free`, `sx_len`, `sx_cap`, `sx_buf_mut`, `sx_view`, the -view navigation family, and the edit functions do not accept a NULL -handle, and `sx_new_from_view`, `sx_buf_view_mut` and `sx_view_*` do -not accept a view with `ref == NULL` (`sx_len_view` only reads the -stored length). A NULL handle or `v.ref`, a freed handle, a view whose -bounds exceed its backing buffer, a double free, use after a consuming -call, `self` passed as the `owned` argument, and indices that violate -what an entry states are all **out of contract**: undefined behavior, -not a documented error return. +Every edit returns `self`, so calls chain and the handle stays stable. The +backing array may move on growth: `sx_buf_mut`/`sx_buf_view_mut` pointers +become stale after any call that can reallocate and must be re-fetched. The +`owned` argument is consumed even when the edit itself fails: the call returns +`NULL`, frees the argument, and leaves `self` unchanged. + +**NULL and out of contract.** Documented NULL handling: +`sx_new_from_cstr(NULL)` and `sx_dup(NULL)` return `NULL`; the `owned` +forms of `sx_append`, `sx_write`, `sx_insert` and all `_cstr` forms return +`NULL` and leave `self` untouched when their second argument is `NULL`. +Everything else dereferences its buffer or window: `sx_free`, `sx_len`, +`sx_cap`, `sx_buf_mut`, `sx_view`, the view navigation family and the edit +functions reject NULL handles, and `sx_new_from_view`, `sx_buf_view_mut` +and `sx_view_*` reject `ref == NULL` (`sx_len_view` only reads the stored +length). **Out of contract** — undefined behavior, not an error return: +a NULL handle or `v.ref`, a freed handle, an out-of-bounds view, a double +free, use after a consuming call, `self` as `owned`, and indices that +violate an entry below. **Sentinels.** @@ -75,27 +68,24 @@ not a documented error return. | not found / no match (search page) | `(size_t)-1` | | no matches / refused split (search page) | `NULL` | -**Sizes are `int`.** `sx_len`, `sx_len_view` and `sx_cap` return -`int`, while view fields and search offsets are `size_t`. Content -larger than `INT_MAX` bytes is outside the tested contract; cast with -`(size_t)` when mixing the two, for example +**Sizes are `int`.** `sx_len`, `sx_len_view` and `sx_cap` return `int`; +view fields and search offsets are `size_t`. Content over `INT_MAX` bytes +is outside the tested contract; cast to `(size_t)` when mixing, e.g. `fwrite(sx_buf_mut(h), 1, (size_t)sx_len(h), stdout)`. -**Views are snapshots.** `sx_view_t {ref, offset, len}` denotes the -byte window `[offset, offset + len)` inside the buffer behind `ref`; it -copies nothing and modifies nothing. A valid window lies inside the -buffer (`offset + len <= len(ref)`). A later edit that reallocates or -changes the length invalidates the view's meaning: re-derive views -after such edits, and do not edit a buffer while views into it (such as -a `sx_split` array) are in use. `ref == NULL` marks "no view"; it is -not a usable buffer. - -**Capacity growth.** `sx_new` starts with capacity 32 bytes. Growth is -geometric (double, then `+0x10000` once the capacity is at least -64 KiB); a debug build with `-DSX_FORCE_EXACT_RESERVE` sizes every -allocation exactly to `need + 1`. Capacity never shrinks — -`sx_truncate` and `sx_clear` keep it — and no function promises spare -capacity beyond its stated guarantee. +**Views are snapshots.** `sx_view_t {ref, offset, len}` is the byte window +`[offset, offset + len)` inside the buffer behind `ref`; it copies nothing +and modifies nothing, and a valid window satisfies +`offset + len <= len(ref)`. A later edit that reallocates or changes the +length invalidates it: re-derive views afterwards, and do not edit a +buffer while views into it (such as a `sx_split` array) are in use. +`ref == NULL` means "no view", not a usable buffer. + +**Capacity growth.** `sx_new` starts at capacity 32; growth is geometric +(double, then `+0x10000` at 64 KiB and above), and a debug build with +`-DSX_FORCE_EXACT_RESERVE` sizes every allocation exactly to `need + 1`. +Capacity never shrinks (`sx_truncate` and `sx_clear` keep it), and no +function promises spare capacity beyond its stated guarantee. ## Creation and destruction @@ -105,14 +95,14 @@ capacity beyond its stated guarantee. sx_t *sx_new(void); ``` -Creates an empty buffer with initial capacity 32 bytes. +Creates an empty buffer of capacity 32 bytes. - **Parameters:** none. -- **Returns:** a new buffer (`len == 0`, `cap == 32`, `ptr[0] == '\0'`), - or `NULL` on allocation failure. +- **Returns:** a new buffer (`len == 0`, `cap == 32`, `ptr[0] == '\0'`), or + `NULL` on allocation failure. - **Ownership:** caller-owned; release with `sx_free`. -- **Edge cases:** the exact initial capacity is an implementation - detail; only `cap >= 1` is guaranteed. +- **Edge cases:** only `cap >= 1` is guaranteed; the exact 32-byte start is + an implementation detail. ### sx_new_from_cstr @@ -122,13 +112,12 @@ sx_t *sx_new_from_cstr(const char *s); Creates a buffer holding a copy of the C string `s`. -- **Parameters:** `s` — NUL-terminated source string, read with - `strlen`. -- **Returns:** a new caller-owned buffer, or `NULL` when `s == NULL` or - on allocation failure. +- **Parameters:** `s` — NUL-terminated string, read with `strlen`. +- **Returns:** a new caller-owned buffer, or `NULL` when `s == NULL` or on + allocation failure. - **Ownership:** caller-owned; release with `sx_free`. - **Edge cases:** `strlen` semantics — an embedded `'\0'` truncates the - copy. Use `sx_new_from_view` for binary content. + copy; use `sx_new_from_view` for binary content. ### sx_new_from_view @@ -136,17 +125,15 @@ Creates a buffer holding a copy of the C string `s`. sx_t *sx_new_from_view(sx_view_t v); ``` -Copies the bytes of a view into a new, independent buffer. +Copies a view's bytes into a new, independent buffer. -- **Parameters:** `v` — source window; `v.len` bytes are read from +- **Parameters:** `v` — source window; `v.len` bytes at `v.ref->ptr + v.offset`. -- **Returns:** a new caller-owned buffer, or `NULL` on allocation - failure. +- **Returns:** a new caller-owned buffer, or `NULL` on allocation failure. - **Ownership:** caller-owned; release with `sx_free`. -- **Edge cases:** byte-exact and binary-safe: embedded `'\0'` bytes are - copied. There is no aliasing — mutating either buffer never affects - the other. `v.ref == NULL` or an out-of-bounds window is out of - contract. +- **Edge cases:** byte-exact and binary-safe (embedded `'\0'` bytes are + copied); no aliasing — mutating either buffer never affects the other. + `v.ref == NULL` or an out-of-bounds window is out of contract. ### sx_new_with_cap @@ -157,12 +144,12 @@ sx_t *sx_new_with_cap(size_t n); Creates an empty buffer with exactly `n` allocated bytes. - **Parameters:** `n` — total allocation size in bytes. -- **Returns:** a new caller-owned buffer with `cap == n` for `n >= 1`, - or `NULL` on allocation failure. +- **Returns:** a new caller-owned buffer with `cap == n` for `n >= 1`, or + `NULL` on allocation failure. - **Ownership:** caller-owned; release with `sx_free`. -- **Edge cases:** one byte is reserved for the terminator, so the buffer - can hold at most `n - 1` content bytes. `n == 0` still allocates one - byte (`cap == 1`), so the handle is always valid. +- **Edge cases:** one byte is reserved for the terminator, so at most + `n - 1` content bytes fit; `n == 0` still allocates one byte + (`cap == 1`), so the handle is always valid. ```c sx_t *buf = sx_new_with_cap(64); /* room for 63 content bytes */ @@ -179,12 +166,12 @@ sx_t *sx_dup(const sx_t *src); Creates a deep, independent copy of a buffer. - **Parameters:** `src` — source buffer. -- **Returns:** a new caller-owned buffer with the same content, or - `NULL` when `src == NULL` or on allocation failure. -- **Ownership:** caller-owned; the copy and the source are released - separately with `sx_free`. -- **Edge cases:** binary-safe. The copy's capacity is `len + 1` in - v0.5, not the source's capacity. +- **Returns:** a new caller-owned buffer with the same content, or `NULL` + when `src == NULL` or on allocation failure. +- **Ownership:** caller-owned; copy and source are freed separately with + `sx_free`. +- **Edge cases:** binary-safe; in v0.5 the copy's capacity is `len + 1`, + not the source's capacity. ```c sx_t *src = sx_new_from_cstr("hello"); @@ -199,16 +186,15 @@ sx_free(src); void sx_free(sx_t *h); ``` -Releases a buffer: its content array and the handle. +Releases a buffer: the content array and the handle. -- **Parameters:** `h` — a live handle whose ownership the caller holds. +- **Parameters:** `h` — a live handle owned by the caller. - **Returns:** nothing. -- **Ownership:** consumes `h`; every view and `sx_buf_mut` pointer into - the buffer becomes invalid. -- **Edge cases:** `h == NULL` is out of contract — the function - dereferences the handle (the regex layer's `sx_reg_free(NULL)` no-op - does not generalize here). Double free and use after free are out of - contract. +- **Ownership:** consumes `h`; every view and `sx_buf_mut` pointer into it + becomes invalid. +- **Edge cases:** `h == NULL` is out of contract — the handle is + dereferenced (the regex layer's `sx_reg_free(NULL)` no-op does not + generalize). Double free and use after free are out of contract. ## Accessors @@ -222,10 +208,9 @@ Returns the number of content bytes. - **Parameters:** `h` — buffer. - **Returns:** `len`, counting embedded `'\0'` bytes; the terminator is - never counted. -- **Ownership:** none; the buffer is not modified. -- **Edge cases:** `h == NULL` is out of contract. The result is an - `int`; see the size note above. + never counted; the buffer is not modified. +- **Edge cases:** `h == NULL` is out of contract; the result is an `int` + (see the size note above). ### sx_len_view @@ -237,10 +222,9 @@ Returns the view's stored length. - **Parameters:** `v` — the view whose length is wanted. - **Returns:** `(int)v.len`; the backing buffer is not inspected and the - window bounds are not validated. -- **Ownership:** none. -- **Edge cases:** `v.len` above `INT_MAX` is outside the tested - contract. The "no view" sentinel (`ref == NULL`) carries `len == 0`. + window is not validated. +- **Edge cases:** `v.len` above `INT_MAX` is outside the tested contract; + the "no view" sentinel (`ref == NULL`) has `len == 0`. ### sx_cap @@ -248,13 +232,12 @@ Returns the view's stored length. int sx_cap(sx_t *h); ``` -Returns the total number of bytes allocated for the content array. +Returns the total bytes allocated for the content array. - **Parameters:** `h` — buffer. -- **Returns:** `cap`, which is always at least `len + 1` (the - single-NUL invariant). -- **Ownership:** none; the buffer is not modified. -- **Edge cases:** `h == NULL` is out of contract. Spare capacity beyond +- **Returns:** `cap`, always at least `len + 1` (the single-NUL invariant); + the buffer is not modified. +- **Edge cases:** `h == NULL` is out of contract; spare capacity beyond `len + 1` depends on the growth policy and is not a contract. ### sx_buf_mut @@ -267,13 +250,12 @@ Returns a mutable pointer to the content array. - **Parameters:** `h` — buffer. - **Returns:** `ptr`; `ptr[len] == '\0'` at all times. -- **Ownership:** borrowed; the caller may rewrite bytes inside - `[0, len)` without changing `len`. -- **Edge cases:** the caller must not write at or beyond `len` without a - length-changing call, and must not store the pointer across any call - that can reallocate (`sx_append*`, `sx_write*`, `sx_insert*`, - `sx_reserve`, a growing `sx_truncate`). `h == NULL` is out of - contract. +- **Ownership:** borrowed; bytes inside `[0, len)` may be rewritten without + changing `len`. +- **Edge cases:** do not write at or beyond `len` without a + length-changing call, and do not keep the pointer across any call that + can reallocate (`sx_append*`, `sx_write*`, `sx_insert*`, `sx_reserve`, + a growing `sx_truncate`). `h == NULL` is out of contract. ```c char *p = sx_buf_mut(buf); @@ -291,10 +273,10 @@ Returns a mutable pointer to the first byte of a view's window. - **Parameters:** `v` — view into a buffer. - **Returns:** `v.ref->ptr + v.offset`. - **Ownership:** borrowed; writes reach the backing buffer. -- **Edge cases:** the pointer carries no length information — pair it - with `sx_len_view(v)` and stay inside the window. `v.ref == NULL` or - an out-of-bounds window is out of contract, and the pointer is stale - after the backing buffer reallocates. +- **Edge cases:** the pointer carries no length — pair it with + `sx_len_view(v)` and stay inside the window. `v.ref == NULL` or an + out-of-bounds window is out of contract; the pointer is stale after the + backing buffer reallocates. ```c sx_view_t word = sx_view_range(sx_view(buf), 6, 5); @@ -311,10 +293,9 @@ sx_view_t sx_view(const sx_t *h); Returns the whole-buffer view. - **Parameters:** `h` — buffer. -- **Returns:** `{ref: h->ref, offset: 0, len: sx_len(h)}`. -- **Ownership:** none; the view aliases `h` and is never freed. -- **Edge cases:** zero-copy and read-only; `h == NULL` is out of - contract. +- **Returns:** `{ref: h->ref, offset: 0, len: sx_len(h)}`; the view aliases + `h` and is never freed. +- **Edge cases:** zero-copy and read-only; `h == NULL` is out of contract. ## Capacity @@ -326,17 +307,16 @@ sx_t *sx_reserve(sx_t *self, size_t min_cap); Ensures room for at least `min_cap` content bytes plus the terminator. -- **Parameters:** `self` — buffer; `min_cap` — number of content bytes - that must fit without a later reallocation. -- **Returns:** `self` on success (including a no-op request), or `NULL` - on allocation failure. +- **Parameters:** `self` — buffer; `min_cap` — content bytes that must fit + without a later reallocation. +- **Returns:** `self` on success (including a no-op request), or `NULL` on + allocation failure. - **Ownership:** `self` is returned and stays caller-owned; content and length are preserved. -- **Edge cases:** on success `cap >= min_cap + 1`. A request the current - capacity already satisfies does not shrink or otherwise change it. - Capacity only grows; `sx_truncate` and `sx_clear` never release it. - The backing array may move, so all `sx_buf_mut` pointers must be - re-fetched afterwards. +- **Edge cases:** on success `cap >= min_cap + 1`; a request the current + capacity already satisfies does not shrink it. Capacity only grows — + `sx_truncate` and `sx_clear` never release it — and the backing array may + move, so re-fetch all `sx_buf_mut` pointers. ```c buf = sx_reserve(buf, 4096); /* cap >= 4097 */ @@ -350,18 +330,16 @@ buf = sx_reserve(buf, 4096); /* cap >= 4097 */ sx_t *sx_append(sx_t *self, sx_t *owned); ``` -Appends the content of another buffer, consuming that buffer. +Appends another buffer's content, consuming that buffer. -- **Parameters:** `self` — destination; `owned` — source whose content - is appended. +- **Parameters:** `self` — destination; `owned` — source buffer. - **Returns:** `self`, or `NULL` when `owned == NULL` or on allocation failure. -- **Ownership:** ownership transfer: the call reads `owned`'s content - and then frees `owned`. Do not use or free `owned` afterwards. -- **Edge cases:** byte-exact: the content length is used, so embedded - `'\0'` bytes are appended. On `owned == NULL` nothing changes. `self` - may reallocate. Passing `self` as `owned` is out of contract (it - would be freed while in use). +- **Ownership:** ownership transfer — the call copies `owned`'s content + and frees `owned`; do not use or free it afterwards. +- **Edge cases:** byte-exact by content length, so embedded `'\0'` bytes + are appended; `owned == NULL` changes nothing; `self` may reallocate; + passing `self` as `owned` is out of contract (it would be freed in use). ### sx_append_cstr @@ -372,11 +350,10 @@ sx_t *sx_append_cstr(sx_t *self, const char *s); Appends a C string. - **Parameters:** `self` — destination; `s` — NUL-terminated source. -- **Returns:** `self`, or `NULL` when `s == NULL` or on allocation - failure. +- **Returns:** `self`, or `NULL` when `s == NULL` or on allocation failure. - **Ownership:** none; `s` is only read. - **Edge cases:** `strlen` semantics — an embedded `'\0'` truncates the - appended bytes. Appending `""` is a no-op that returns `self`. + appended bytes; appending `""` is a no-op returning `self`. ### sx_append_view @@ -384,16 +361,16 @@ Appends a C string. sx_t *sx_append_view(sx_t *self, sx_view_t v); ``` -Appends the bytes of a view. +Appends a view's bytes. -- **Parameters:** `self` — destination; `v` — source window; `v.len` - bytes are read from `v.ref->ptr + v.offset`. +- **Parameters:** `self` — destination; `v` — source window; `v.len` bytes + at `v.ref->ptr + v.offset`. - **Returns:** `self`, or `NULL` on allocation failure. - **Ownership:** none; `v` is only read. -- **Edge cases:** byte-exact and binary-safe. `v` may alias `self`, - including when the append grows the buffer: doubling a buffer in - place with `sx_append_view(h, sx_view(h))` is supported. `v.ref == - NULL` or an out-of-bounds window is out of contract. +- **Edge cases:** byte-exact and binary-safe; `v` may alias `self`, + including when the append grows the buffer — in-place doubling with + `sx_append_view(h, sx_view(h))` is supported. `v.ref == NULL` or an + out-of-bounds window is out of contract. ```c buf = sx_append_view(buf, sx_view(buf)); /* doubles in place */ @@ -407,20 +384,23 @@ buf = sx_append_view(buf, sx_view(buf)); /* doubles in place */ sx_t *sx_write(sx_t *self, size_t idx, sx_t *owned); ``` -Overwrites bytes starting at `idx`, growing the length if needed, and -consumes the source buffer. +Overwrites bytes at `idx`, growing the length if needed, and consumes the +source buffer. - **Parameters:** `self` — destination; `idx` — first byte to overwrite; - `owned` — source whose content is written. -- **Returns:** `self`, or `NULL` when `owned == NULL` or on allocation - failure. -- **Ownership:** ownership transfer: the call reads `owned`'s content - and then frees `owned`. Do not use or free it afterwards. -- **Edge cases:** after the call `len' = max(len, idx + owned.len)` — - writing never shrinks the buffer. `idx == len` behaves as an append; - `idx < len` overwrites in place; `idx > len` extends and the bytes in - `[len, idx)` are **unspecified**. Passing `self` as `owned`, or an - `idx + n` that overflows `size_t`, is out of contract. + `owned` — source buffer. +- **Returns:** `self`; `NULL` when `owned == NULL`, when the write range + cannot be reserved, or on allocation failure. +- **Ownership:** ownership transfer — the content is copied and `owned` is + freed; do not use or free it afterwards. `owned` is freed even if the + write fails. +- **Edge cases:** `len' = max(len, idx + owned.len)` — a write never shrinks + the buffer. `idx == len` is an append; `idx < len` overwrites in place; + `idx > len` extends and `[len, idx)` is **unspecified**. If `idx + n` + overflows `size_t`, or the resulting end cannot be reserved (a total + content length of `SIZE_MAX` cannot include a terminator), the call returns + `NULL` before copying and leaves `self` unchanged. Passing `self` as + `owned` is out of contract. ```c buf = sx_new_from_cstr("abc"); @@ -435,14 +415,14 @@ sx_t *sx_write_cstr(sx_t *self, size_t idx, const char *s); Writes a C string at `idx`. -- **Parameters:** `self` — destination; `idx` — first byte to write; - `s` — NUL-terminated source. -- **Returns:** `self`, or `NULL` when `s == NULL` or on allocation - failure. +- **Parameters:** `self` — destination; `idx` — first byte to write; `s` — + NUL-terminated source. +- **Returns:** `self`; `NULL` when `s == NULL`, when the write range cannot + be reserved, or on allocation failure. - **Ownership:** none; `s` is only read. - **Edge cases:** `strlen` semantics (an embedded `'\0'` truncates the - written bytes). On `s == NULL`, `self` is left untouched. Same - `idx`/padding rules as `sx_write`. + written bytes); on `s == NULL`, `self` is untouched. The same range + validation, padding and `idx` rules as `sx_write` apply. ### sx_write_view @@ -450,16 +430,19 @@ Writes a C string at `idx`. sx_t *sx_write_view(sx_t *self, size_t idx, sx_view_t v); ``` -Writes the bytes of a view at `idx`. +Writes a view's bytes at `idx`. -- **Parameters:** `self` — destination; `idx` — first byte to write; - `v` — source window. -- **Returns:** `self`, or `NULL` on allocation failure. +- **Parameters:** `self` — destination; `idx` — first byte to write; `v` — + source window. +- **Returns:** `self`; `NULL` when the write range cannot be reserved or on + allocation failure. - **Ownership:** none; `v` is only read. -- **Edge cases:** byte-exact and binary-safe. `v` may alias `self`, - including when the write must grow the buffer (the source bytes are - preserved across the reservation). Same `idx`/padding rules as - `sx_write`; an out-of-bounds window is out of contract. +- **Edge cases:** byte-exact and binary-safe; `v` may alias `self`, + including when the write must grow the buffer (the source bytes survive + the reservation). The overflow check runs before the alias-preserving + pre-reserve, so a rejected range cannot change the target's capacity. Same + `idx`/padding rules as `sx_write`; an out-of-bounds window is out of + contract. ## Inserting @@ -469,18 +452,18 @@ Writes the bytes of a view at `idx`. sx_t *sx_insert(sx_t *self, size_t idx, sx_t *owned); ``` -Inserts the content of another buffer at `idx`, shifting the tail -right, and consumes that buffer. +Inserts another buffer's content at `idx`, shifting the tail right, and +consumes that buffer. - **Parameters:** `self` — destination; `idx` — insertion point with - `0 <= idx <= len`; `owned` — source whose content is inserted. + `0 <= idx <= len`; `owned` — source buffer. - **Returns:** `self`, or `NULL` when `owned == NULL` or on allocation failure. -- **Ownership:** ownership transfer: the call reads `owned`'s content - and then frees `owned`. Do not use or free it afterwards. +- **Ownership:** ownership transfer — the content is copied and `owned` is + freed; do not use or free it afterwards. - **Edge cases:** the result is `[0, idx)` ++ inserted bytes ++ - `[idx, len)`, with `len' = len + n`. `idx == len` is append-like. - `idx > len` is out of contract (the tail shift underflows); passing + `[idx, len)`, with `len' = len + n`; `idx == len` is append-like. + `idx > len` is out of contract (the tail shift underflows), and passing `self` as `owned` is out of contract. ```c @@ -497,11 +480,10 @@ Inserts a C string at `idx`. - **Parameters:** `self` — destination; `idx` — insertion point with `0 <= idx <= len`; `s` — NUL-terminated source. -- **Returns:** `self`, or `NULL` when `s == NULL` or on allocation - failure. +- **Returns:** `self`, or `NULL` when `s == NULL` or on allocation failure. - **Ownership:** none; `s` is only read. -- **Edge cases:** `strlen` semantics; on `s == NULL`, `self` is left - untouched. `idx > len` is out of contract. +- **Edge cases:** `strlen` semantics; on `s == NULL`, `self` is untouched. + `idx > len` is out of contract. ### sx_insert_view @@ -509,17 +491,17 @@ Inserts a C string at `idx`. sx_t *sx_insert_view(sx_t *self, size_t idx, sx_view_t v); ``` -Inserts the bytes of a view at `idx`. +Inserts a view's bytes at `idx`. - **Parameters:** `self` — destination; `idx` — insertion point with `0 <= idx <= len`; `v` — source window. - **Returns:** `self`, or `NULL` on allocation failure. - **Ownership:** none; `v` is only read. -- **Edge cases:** byte-exact and binary-safe. `v` may alias `self`, +- **Edge cases:** byte-exact and binary-safe; `v` may alias `self`, including when the insert grows the buffer, as long as its window starts at or before `idx` (the tested case: a slice taken at the insertion - point). A self-aliased window that starts after `idx` lies in the region - the tail shift overwrites and is **out of contract** — copy it first with + point). A self-aliased window starting after `idx` lies in the region the + tail shift overwrites and is **out of contract** — copy it first with `sx_new_from_view`. `idx > len` and out-of-bounds views are out of contract. @@ -535,14 +517,13 @@ Sets the content length to `new_len`. - **Parameters:** `self` — buffer; `new_len` — the new length in content bytes. -- **Returns:** `self` on success, or `NULL` on allocation failure while +- **Returns:** `self` on success; `NULL` on allocation failure while growing. -- **Ownership:** `self` is returned and stays caller-owned. -- **Edge cases:** a shorter `new_len` keeps the prefix and drops the - tail; the same `new_len` is a no-op. A longer `new_len` grows the - buffer: `len` becomes `new_len`, `ptr[new_len] == '\0'`, and the - bytes in `[old_len, new_len)` are **unspecified** — never read them - until they are overwritten. Capacity is not reduced by a shrink. +- **Edge cases:** a shorter `new_len` keeps the prefix and drops the tail; + the same `new_len` is a no-op. A longer `new_len` grows the buffer: `len` + becomes `new_len`, `ptr[new_len] == '\0'`, and `[old_len, new_len)` is + **unspecified** — do not read it until overwritten. A shrink does not + reduce capacity. ### sx_erase @@ -550,17 +531,15 @@ Sets the content length to `new_len`. sx_t *sx_erase(sx_t *self, size_t idx, size_t n); ``` -Removes `n` bytes starting at `idx`, shifting the tail left. +Removes `n` bytes at `idx`, shifting the tail left. - **Parameters:** `self` — buffer; `idx` — first byte to remove; `n` — number of bytes to remove. -- **Returns:** `self`. -- **Ownership:** `self` is returned and stays caller-owned; `self` - itself must be valid. -- **Edge cases:** `idx + n == len` erases the suffix; `idx + n > len` is - a no-op that returns `self` unchanged; `n == 0` is a no-op. No - allocation happens, so the call does not fail. An `idx + n` that - overflows `size_t` is out of contract. +- **Returns:** `self`; `self` itself must be valid. +- **Edge cases:** `idx + n == len` erases the suffix; `idx + n > len` is a + no-op returning `self` unchanged; `n == 0` is a no-op. No allocation + happens, so the call cannot fail. An `idx + n` overflowing `size_t` is + out of contract. ```c buf = sx_erase(buf, 2, 100); /* idx+n > len: no-op, returns self */ @@ -575,8 +554,7 @@ sx_t *sx_clear(sx_t *self); Empties the buffer, keeping its capacity. - **Parameters:** `self` — buffer. -- **Returns:** `self`. -- **Ownership:** `self` is returned and stays caller-owned. +- **Returns:** `self` (still caller-owned). - **Edge cases:** sets `len = 0` and `ptr[0] = '\0'`; the allocation and its capacity are kept, so the buffer is immediately reusable. @@ -592,15 +570,15 @@ buf = sx_clear(buf); /* len 0, capacity kept */ sx_t *sx_substr(const sx_t *h, size_t idx, size_t n); ``` -Copies the byte range `[idx, idx + n)` into a new, independent buffer. +Copies `[idx, idx + n)` into a new, independent buffer. -- **Parameters:** `h` — source buffer; `idx` — start offset; `n` — - number of bytes, with the precondition `idx + n <= len(h)`. -- **Returns:** a new caller-owned buffer, or `NULL` on allocation - failure. (A NULL `h` or an out-of-bounds range is out of contract, - not an error value.) +- **Parameters:** `h` — source buffer; `idx` — start offset; `n` — number + of bytes, with the precondition `idx + n <= len(h)`. +- **Returns:** a new caller-owned buffer, or `NULL` on allocation failure. + (A NULL `h` or out-of-bounds range is out of contract, not an error + value.) - **Ownership:** caller-owned; release with `sx_free`. -- **Edge cases:** `n == 0` yields an empty buffer. Byte-exact and +- **Edge cases:** `n == 0` yields an empty buffer; byte-exact and binary-safe, including embedded `'\0'` bytes. Unlike view navigation, this copies: mutations on either side never affect the other. @@ -612,9 +590,9 @@ sx_free(word); ## View navigation All four functions re-derive the `(offset, len)` window over an existing -buffer. None of them copies bytes or modifies the buffer; they only -return a new view value. Inputs must be valid views (`ref != NULL`, the -window inside the buffer); invalid input is out of contract. +buffer. None copies, modifies or transfers ownership; each returns a new +view value. Inputs must be valid views (`ref != NULL`, window inside +the buffer); invalid input is out of contract. ### sx_view_advance @@ -622,20 +600,17 @@ window inside the buffer); invalid input is out of contract. sx_view_t sx_view_advance(sx_view_t v, size_t n); ``` -Moves the start of the window right by `n`. +Moves the window start right by `n`. - **Parameters:** `v` — input view; `n` — bytes to advance. - **Returns:** the adjusted view over the same buffer. -- **Ownership:** none. - **Edge cases:** with `H = len(ref)`: - - if `offset + len + n < H`, the end is kept and `len` shrinks by - exactly `n`; - - otherwise, if `offset + n < H`, the start becomes `offset + n` and - the end clamps to the buffer end (`len = H - offset`); + - if `offset + len + n < H`, the end is kept and `len` shrinks by `n`; + - otherwise, if `offset + n < H`, the start becomes `offset + n` and the + end clamps to the buffer end (`len = H - offset`); - otherwise the result is the empty view `(H, 0)`. - Advancing never moves past the buffer end, even for a large `n`, and - advancing a sub-view beyond its own end widens it to the buffer end - (second case), as specified. + It never moves past the buffer end, even for a large `n`; advancing a + sub-view beyond its own end widens it to the buffer end (second case). ```c sx_view_t rest = sx_view_advance(sx_view(buf), 2); /* start +2 */ @@ -647,14 +622,13 @@ sx_view_t rest = sx_view_advance(sx_view(buf), 2); /* start +2 */ sx_view_t sx_view_retreat(sx_view_t v, size_t n); ``` -Moves the start of the window left by `n`, keeping the end fixed. +Moves the window start left by `n`, keeping the end fixed. - **Parameters:** `v` — input view; `n` — bytes to retreat. - **Returns:** the adjusted view over the same buffer. -- **Ownership:** none. -- **Edge cases:** `len` grows by the same amount the offset shrinks; the - move saturates at offset 0 (`len` becomes the original - `offset + len`), so the window never starts before the buffer. +- **Edge cases:** `len` grows by the amount the offset shrinks; the move + saturates at offset 0 (`len` becomes the original `offset + len`), so the + window never starts before the buffer. ### sx_view_shift @@ -666,12 +640,10 @@ Moves the window by a signed offset, preserving its length. - **Parameters:** `v` — input view; `off` — signed byte offset. - **Returns:** the adjusted view over the same buffer. -- **Ownership:** none. -- **Edge cases:** `len` is preserved (unlike advance/retreat). A - positive `off` that would push the end past the buffer is clamped to - `offset = H - len` (the window ends at the buffer end); a negative - `off` saturates the start at 0. On an empty buffer the result is - `(0, 0)`. +- **Edge cases:** `len` is preserved (unlike advance/retreat). A positive + `off` that would push the end past the buffer clamps to + `offset = H - len` (the window ends at the buffer end); a negative `off` + saturates the start at 0. On an empty buffer the result is `(0, 0)`. ### sx_view_range @@ -679,16 +651,15 @@ Moves the window by a signed offset, preserving its length. sx_view_t sx_view_range(sx_view_t v, size_t off, size_t len); ``` -Re-anchors the window at absolute coordinates, ignoring the input -view's offset and length. +Re-anchors the window at absolute coordinates, ignoring the input view's +offset and length. - **Parameters:** `v` — supplies only the backing buffer; `off` — absolute start offset, with the precondition `off <= H`; `len` — requested length. - **Returns:** the view `(off, min(len, H - off))`. -- **Ownership:** none. -- **Edge cases:** the length is clamped to the buffer end; `off == H` - gives `(H, 0)`; `off > H` is out of contract (`H - off` underflows). +- **Edge cases:** the length clamps to the buffer end; `off == H` gives + `(H, 0)`; `off > H` is out of contract (`H - off` underflows). ```c sx_view_t slice = sx_view_range(sx_view(buf), 2, 3); /* absolute (2, 3) */ @@ -696,9 +667,9 @@ sx_view_t slice = sx_view_range(sx_view(buf), 2, 3); /* absolute (2, 3) */ ## Trimming views -The trim family removes ASCII whitespace from the edges of a view. The -whitespace set is exactly `{space, '\t', '\v', '\f', '\r', '\n'}`. No -buffer bytes are ever modified, and only bytes inside the window are +The trim family removes ASCII whitespace from a view's edges. The set is +exactly `{space, '\t', '\v', '\f', '\r', '\n'}`. No bytes are modified, +no ownership is transferred, and only bytes inside the window are inspected. ### sx_view_trim @@ -711,12 +682,11 @@ Trims both edges of the view. - **Parameters:** `v` — input view. - **Returns:** the view with leading and trailing whitespace removed. -- **Ownership:** none. -- **Edge cases:** equivalent to `sx_view_trim_back(sx_view_trim_front(v))`. - A view with no edge whitespace is returned unchanged. A view whose - content is entirely whitespace becomes the empty view at the window's - end (offset `offset + len`, length 0) — `(H, 0)` for a whole-buffer - view. +- **Edge cases:** equivalent to + `sx_view_trim_back(sx_view_trim_front(v))`. A view with no edge + whitespace is returned unchanged. An all-whitespace view becomes the + empty view at the window's end (offset `offset + len`, length 0) — + `(H, 0)` for a whole-buffer view. ```c sx_view_t field = sx_view_trim(sx_view(buf)); /* strip ASCII whitespace */ @@ -732,11 +702,10 @@ Drops leading whitespace. - **Parameters:** `v` — input view. - **Returns:** the view with leading whitespace removed. -- **Ownership:** none. - **Edge cases:** the offset moves right and `len` shrinks by the same - amount, so the window end stays fixed. The scan is bounded by the - view's own length and never runs past the window's end, even when - whitespace continues in the buffer after it. + amount, so the window end stays fixed. The scan is bounded by the view's + own length and never runs past the window's end, even when whitespace + continues in the buffer after it. ### sx_view_trim_back @@ -748,18 +717,16 @@ Drops trailing whitespace. - **Parameters:** `v` — input view. - **Returns:** the view with trailing whitespace removed. -- **Ownership:** none. - **Edge cases:** only the window's last byte (`offset + len - 1`) is inspected and `len` shrinks leftwards; the offset is unchanged, so an - all-whitespace window becomes `(offset, 0)`. Bytes outside the window - are never examined. + all-whitespace window becomes `(offset, 0)`. Bytes outside the window are + never examined. ## Complete example This program builds a string, trims a view of it, copies the trimmed window into a new buffer, edits that buffer in place, and releases both -buffers. It compiles as written with the library sources and is also the -shape of a normal application: +buffers: ```c #include diff --git a/docs/en_us/api-search.md b/docs/en_us/api-search.md index bd4bd62..305553f 100644 --- a/docs/en_us/api-search.md +++ b/docs/en_us/api-search.md @@ -4,12 +4,10 @@ English · [中文](../zh_cn/api-search.md) # Search, compare and split -The complete reference for the search family (`sx_find*`, `sx_rfind*`, -`sx_find_all*`), the comparison family (`sx_cmp*`, `sx_starts_with*`, -`sx_ends_with*`) and `sx_split`. All of them are byte-exact and work on -content lengths, so embedded NUL bytes are ordinary data. Buffer -creation, mutation and views are documented in -[Buffers and views](api-buffer.md). +This page covers the search (`sx_find*`, `sx_rfind*`, `sx_find_all*`), +comparison (`sx_cmp*`, `sx_starts_with*`, `sx_ends_with*`) and `sx_split` +APIs. All are byte-exact and length-based, so embedded NUL bytes are data; +buffers, mutation and views are in [Buffers and views](api-buffer.md). ## Conventions @@ -22,15 +20,14 @@ creation, mutation and views are documented in | `_cstr` | `const char *` | `strlen(...)` bytes | the first NUL ends the needle | | `_char` | `char` | exactly one byte | `'\0'` means a NUL content byte | -The owned and view forms are binary-safe: they read exactly the -needle's length, so an embedded `'\0'` is matched as data. The `_cstr` -forms use `strlen`, so `sx_find_cstr(h, "a\0c")` actually searches for -`"a"`; use an owned or view needle to search binary patterns. An empty -needle (length 0) is never found. +Owned and view needles are binary-safe: exactly the needle's length is +read, so an embedded `'\0'` matches as data. `_cstr` needles use `strlen`, +so `sx_find_cstr(h, "a\0c")` searches for `"a"`; use an owned/view needle +for binary patterns. A needle of length 0 is never found. -**Bounded regions.** With `H` = the haystack's content length and a needle of `m` bytes, a -match is a window `[p, p + m)` that must lie entirely inside the -searched region: +**Bounded regions.** With `H` = the haystack's content length and a needle +of `m` bytes, a match is a window `[p, p + m)` that must lie entirely +inside the searched region: | Function | Search region | Window requirement | | --- | --- | --- | @@ -38,28 +35,26 @@ searched region: | `sx_find_view_b(h, needle, boundary)` | `[boundary, H)` | `p >= boundary` and `p + m <= H` | | `sx_rfind_view_b(h, needle, boundary)` | `[0, min(boundary, H))` | `p + m <= min(boundary, H)` | -The two bounded forms take a `size_t boundary` and differ in direction: -`sx_find_view_b` bounds the region on the left and excludes any window -that starts before `boundary`; `sx_rfind_view_b` bounds it on the right -and excludes any window that ends after the boundary. Concrete cases -from the tests, with `h = "ababa"` and needle `"ba"`: - -- `sx_find_view_b(h, nd, 2)` is 3 — the match at offset 1 starts before - the boundary and does not count; boundary 4 gives `(size_t)-1` - because the remaining region `"a"` is too small for one window. -- `sx_rfind_view_b(h, nd, 3)` is 1 — the match at 3 ends at 5, past the - boundary; boundary 2 gives `(size_t)-1`; with needle `"aba"` and - boundary 3 the window `[0, 3)` ends exactly at the boundary and the - result is 0. -- For `sx_find_view_b`, `boundary >= H` is an empty region and returns - `(size_t)-1`. For `sx_rfind_view_b`, a boundary at or above `H` - clamps to `H`, so it behaves like an unbounded rightmost search. - -**Binary safety.** The haystack is always searched by content length -(`H`), never as a C string: embedded `'\0'` bytes are ordinary bytes, -and the terminator at `ptr[H]` is outside the searched region. In -particular `sx_find_char(h, '\0')` reports only embedded NUL content -bytes, never the terminator. Owned and view needles are read by length +The bounded forms take a `size_t boundary` and differ in direction: +`sx_find_view_b` bounds the region on the left (windows starting before +`boundary` are excluded); `sx_rfind_view_b` bounds it on the right +(windows ending after the boundary are excluded). Test cases with +`h = "ababa"` and needle `"ba"`: + +- `sx_find_view_b(h, nd, 2)` is 3 (the match at offset 1 starts before the + boundary); boundary 4 gives `(size_t)-1` — only `"a"` remains, too small + for a window. +- `sx_rfind_view_b(h, nd, 3)` is 1 (the match at 3 ends at 5, past the + boundary); boundary 2 gives `(size_t)-1`; needle `"aba"` at boundary 3 + gives 0 — its window `[0, 3)` ends exactly at the boundary. +- For `sx_find_view_b`, `boundary >= H` is an empty region returning + `(size_t)-1`. For `sx_rfind_view_b`, a boundary at or above `H` clamps to + `H`, so it behaves like an unbounded rightmost search. + +**Binary safety.** The haystack is searched by content length (`H`), never +as a C string: embedded `'\0'` bytes are ordinary bytes and the terminator +at `ptr[H]` is outside the region. `sx_find_char(h, '\0')` therefore finds +only embedded NUL content bytes. Owned and view needles are read by length too; only `_cstr` needles stop at the first NUL. **Sentinels and NULL.** @@ -72,22 +67,27 @@ too; only `_cstr` needles stop at the first NUL. | `sx_starts_with*`, `sx_ends_with*` | `0` | | `sx_split` | `NULL` | -The search functions check their pointer arguments: a NULL `h` or a -NULL needle argument returns the family sentinel instead of crashing. -For the view variants, `v.ref == NULL` is out of contract — the -pointer is formed before any length check, so always pass a view of a -live buffer. Allocation failure is reported with the same sentinel as -"no match" by `sx_find_all*` and `sx_split`; the two cases are -indistinguishable by contract. `(size_t)-1` cannot collide with a real +The search functions check pointer arguments: a NULL `h` or NULL needle +returns the family sentinel instead of crashing. For view variants, +`v.ref == NULL` is out of contract — the pointer is formed before any +length check, so pass a view of a live buffer. All calls treat their +inputs as read-only and transfer no ownership; only the arrays from +`sx_find_all*` and `sx_split` are caller-owned. Those two also report +allocation failure with the same sentinel as "no match", and the two cases +are indistinguishable by contract. `(size_t)-1` cannot collide with a real offset because offsets are below `INT_MAX` content bytes. **Search strategy.** One-byte needles use `memchr` (forward) or a -byte-wise backward scan, glibc's `memrchr` when available, and allocate -nothing. Longer needles use KMP: a temporary prefix table of `m` -`size_t` entries is allocated for the duration of the call, so one -search is O(n + m) worst case. `sx_find_all*` additionally returns a -malloc'ed result array. `sx_find_all*` reports every occurrence, -overlapping ones included. +byte-wise backward scan (glibc's `memrchr` when available), with no +allocation. Leftmost first-match calls (`sx_find*`) with `m >= 2` use a +native glibc fast path — a front compare, first-byte and last-byte `memchr` +filters, then `memmem` for needles up to 32 bytes — and allocate nothing when +it succeeds. Otherwise (longer needles, non-glibc, or +`-DSX_FORCE_NO_MEMMEM`) the call falls back to KMP, which allocates a +temporary prefix table of `m` `size_t` entries for the duration of the call; +one search is O(n + m) worst case. `sx_rfind*` uses the KMP path for +`m >= 2` (one-byte rightmost searches use `memrchr`), and `sx_find_all*` +reports every occurrence, overlaps included, plus its result array. ## Choosing the right call @@ -114,14 +114,10 @@ Finds the leftmost occurrence of another buffer's content in `h`. - **Parameters:** `h` — haystack; `needle` — buffer whose content is searched for. -- **Returns:** the byte offset of the leftmost match, or `(size_t)-1` - when there is none. -- **Ownership:** none; neither buffer is modified. A temporary KMP - prefix table is allocated and freed inside the call for needles longer - than one byte. +- **Returns:** the leftmost match's byte offset, or `(size_t)-1`. - **Edge cases:** NULL `h` or `needle` returns `(size_t)-1`; an empty needle returns `(size_t)-1`; a needle longer than `h` never matches. - The match is byte-exact over content lengths, so embedded NULs match. + Byte-exact over content lengths, so embedded NULs match. ### sx_find_view @@ -133,10 +129,9 @@ Finds the leftmost occurrence of a view's bytes in the whole string. - **Parameters:** `h` — haystack; `needle` — window whose `needle.len` bytes are searched for. -- **Returns:** the byte offset of the leftmost match, or `(size_t)-1`. -- **Ownership:** none; only reads. -- **Edge cases:** equivalent to `sx_find_view_b(h, needle, 0)`. An - empty view (`len == 0`) is never found. `needle.ref == NULL` or an +- **Returns:** the leftmost match's byte offset, or `(size_t)-1`. +- **Edge cases:** equivalent to `sx_find_view_b(h, needle, 0)`. An empty + view (`len == 0`) is never found. `needle.ref == NULL` or an out-of-bounds window is out of contract. ### sx_find_view_b @@ -149,15 +144,13 @@ Finds the leftmost occurrence of a view's bytes at or after `boundary`. - **Parameters:** `h` — haystack; `needle` — window to search for; `boundary` — region start offset. -- **Returns:** the byte offset of the leftmost match inside - `[boundary, H)`, or `(size_t)-1`. -- **Ownership:** none; only reads. -- **Edge cases:** a match must start at or after `boundary` and end at - or before `H`; a window that straddles the boundary is not a match. - `boundary >= H`, a region too small for one window, and an empty - needle all return `(size_t)-1`. `needle.ref == NULL`, an - out-of-bounds window, or a `boundary + needle.len` that overflows - `size_t` is out of contract. +- **Returns:** the leftmost match's byte offset inside `[boundary, H)`, or + `(size_t)-1`. +- **Edge cases:** a match must start at or after `boundary` and end at or + before `H`; a window straddling the boundary is not a match. + `boundary >= H`, a region too small for one window, and an empty needle + all return `(size_t)-1`. `needle.ref == NULL`, an out-of-bounds window, + or `boundary + needle.len` overflowing `size_t` is out of contract. ```c sx_t *h = sx_new_from_cstr("ababa"); @@ -175,10 +168,9 @@ size_t sx_find_cstr(const sx_t *h, const char *needle); Finds the leftmost occurrence of a C string in `h`. -- **Parameters:** `h` — haystack; `needle` — NUL-terminated pattern, - read with `strlen`. -- **Returns:** the byte offset of the leftmost match, or `(size_t)-1`. -- **Ownership:** none; only reads. +- **Parameters:** `h` — haystack; `needle` — NUL-terminated pattern, read + with `strlen`. +- **Returns:** the leftmost match's byte offset, or `(size_t)-1`. - **Edge cases:** NULL `h` or `needle` returns `(size_t)-1`; an empty needle returns `(size_t)-1`. The needle cannot contain a literal NUL; use `sx_find_view` for binary patterns. The haystack may contain NULs. @@ -192,12 +184,10 @@ size_t sx_find_char(const sx_t *h, char c); Finds the leftmost occurrence of a single byte. - **Parameters:** `h` — haystack; `c` — the byte to search for. -- **Returns:** the byte offset of the leftmost occurrence, or - `(size_t)-1`. -- **Ownership:** none; only reads. -- **Edge cases:** NULL `h` returns `(size_t)-1`. The search covers the - content only (`[0, H)`), so `c == '\0'` finds embedded NUL content - bytes but never the terminator. +- **Returns:** the leftmost occurrence's byte offset, or `(size_t)-1`. +- **Edge cases:** NULL `h` returns `(size_t)-1`. Only content (`[0, H)`) is + searched, so `c == '\0'` finds embedded NUL content bytes, never the + terminator. ## Rightmost search: `sx_rfind*` @@ -211,10 +201,7 @@ Finds the rightmost occurrence of another buffer's content in `h`. - **Parameters:** `h` — haystack; `needle` — buffer whose content is searched for. -- **Returns:** the byte offset of the rightmost match, or `(size_t)-1`. -- **Ownership:** none; neither buffer is modified. A temporary KMP - prefix table is allocated and freed inside the call for needles longer - than one byte. +- **Returns:** the rightmost match's byte offset, or `(size_t)-1`. - **Edge cases:** NULL `h` or `needle` returns `(size_t)-1`; an empty needle returns `(size_t)-1`; a needle longer than `h` never matches. Byte-exact and binary-safe. @@ -227,13 +214,12 @@ size_t sx_rfind_view(const sx_t *h, sx_view_t needle); Finds the rightmost occurrence of a view's bytes in the whole string. -- **Parameters:** `h` — haystack; `needle` — window whose - `needle.len` bytes are searched for. -- **Returns:** the byte offset of the rightmost match, or `(size_t)-1`. -- **Ownership:** none; only reads. -- **Edge cases:** equivalent to `sx_rfind_view_b(h, needle, H)`. An - empty view is never found. `needle.ref == NULL` or an out-of-bounds - window is out of contract. +- **Parameters:** `h` — haystack; `needle` — window whose `needle.len` + bytes are searched for. +- **Returns:** the rightmost match's byte offset, or `(size_t)-1`. +- **Edge cases:** equivalent to `sx_rfind_view_b(h, needle, H)`. An empty + view is never found. `needle.ref == NULL` or an out-of-bounds window is + out of contract. ### sx_rfind_view_b @@ -246,15 +232,14 @@ Finds the rightmost occurrence of a view's bytes that ends at or before - **Parameters:** `h` — haystack; `needle` — window to search for; `boundary` — region end offset (exclusive). -- **Returns:** the byte offset of the rightmost match whose window ends - inside `[0, min(boundary, H))`, or `(size_t)-1`. -- **Ownership:** none; only reads. -- **Edge cases:** a match must end at or before `boundary`; one that - sticks out past the boundary is not a match. A boundary of 0, a - region too small for one window, and an empty needle all return - `(size_t)-1`. A boundary at or above `H` clamps to `H` and behaves - like an unbounded rightmost search. `needle.ref == NULL` and - out-of-bounds windows are out of contract. +- **Returns:** the rightmost match's byte offset whose window ends inside + `[0, min(boundary, H))`, or `(size_t)-1`. +- **Edge cases:** a match must end at or before `boundary`; one sticking + out past the boundary is not a match. A boundary of 0, a region too + small for one window, and an empty needle all return `(size_t)-1`. A + boundary at or above `H` clamps to `H` and behaves like an unbounded + rightmost search. `needle.ref == NULL` and out-of-bounds windows are out + of contract. ```c sx_t *h = sx_new_from_cstr("ababa"); @@ -272,10 +257,9 @@ size_t sx_rfind_cstr(const sx_t *h, const char *needle); Finds the rightmost occurrence of a C string in `h`. -- **Parameters:** `h` — haystack; `needle` — NUL-terminated pattern, - read with `strlen`. -- **Returns:** the byte offset of the rightmost match, or `(size_t)-1`. -- **Ownership:** none; only reads. +- **Parameters:** `h` — haystack; `needle` — NUL-terminated pattern, read + with `strlen`. +- **Returns:** the rightmost match's byte offset, or `(size_t)-1`. - **Edge cases:** NULL `h` or `needle` returns `(size_t)-1`; an empty needle returns `(size_t)-1`. The needle cannot contain a literal NUL. @@ -288,11 +272,9 @@ size_t sx_rfind_char(const sx_t *h, char c); Finds the rightmost occurrence of a single byte. - **Parameters:** `h` — haystack; `c` — the byte to search for. -- **Returns:** the byte offset of the rightmost occurrence, or - `(size_t)-1`. -- **Ownership:** none; only reads. -- **Edge cases:** NULL `h` returns `(size_t)-1`. The search covers the - content only, so `c == '\0'` never matches the terminator. +- **Returns:** the rightmost occurrence's byte offset, or `(size_t)-1`. +- **Edge cases:** NULL `h` returns `(size_t)-1`. Only content is searched, + so `c == '\0'` never matches the terminator. ## All occurrences: `sx_find_all*` @@ -307,9 +289,9 @@ Overlapping matches are all reported: `"aa"` inside `"aaaa"` is found at offsets 0, 1 and 2. There is no end guard (unlike `sx_split` and `sx_reg_match_all`); the count is authoritative. -- **Returns:** `NULL` when there is no match — including an empty needle - — when an argument is NULL, or on allocation failure. The two failure - causes are indistinguishable by contract. +- **Returns:** `NULL` when there is no match — including an empty needle — + when an argument is NULL, or on allocation failure; no match and + allocation failure are indistinguishable by contract. - **Ownership:** the caller owns the array and releases it with `free` (not `sx_free`). Do not read past `r[0] + 1` entries. @@ -331,11 +313,9 @@ Collects every occurrence of another buffer's content. - **Parameters:** `h` — haystack; `needle` — buffer whose content is searched for. -- **Returns:** the count-first `size_t` array, or `NULL` (no match, - empty needle, NULL argument, allocation failure). -- **Ownership:** caller-owned; release with `free`. -- **Edge cases:** binary-safe; offsets are ascending and include - overlapping matches. +- **Returns:** the count-first `size_t` array, or `NULL` (no match, empty + needle, NULL argument, allocation failure). +- **Edge cases:** binary-safe; offsets ascend and include overlaps. ### sx_find_all_view @@ -346,11 +326,10 @@ size_t *sx_find_all_view(const sx_t *h, sx_view_t needle); Collects every occurrence of a view's bytes. - **Parameters:** `h` — haystack; `needle` — window to search for. -- **Returns:** the count-first `size_t` array, or `NULL` (no match, - empty view, NULL argument, allocation failure). -- **Ownership:** caller-owned; release with `free`. -- **Edge cases:** `needle.ref == NULL` or an out-of-bounds window is out - of contract. +- **Returns:** the count-first `size_t` array, or `NULL` (no match, empty + view, NULL argument, allocation failure). +- **Edge cases:** `needle.ref == NULL` or an out-of-bounds window is out of + contract. ### sx_find_all_cstr @@ -360,11 +339,10 @@ size_t *sx_find_all_cstr(const sx_t *h, const char *needle); Collects every occurrence of a C string. -- **Parameters:** `h` — haystack; `needle` — NUL-terminated pattern, - read with `strlen`. -- **Returns:** the count-first `size_t` array, or `NULL` (no match, - empty needle, NULL argument, allocation failure). -- **Ownership:** caller-owned; release with `free`. +- **Parameters:** `h` — haystack; `needle` — NUL-terminated pattern, read + with `strlen`. +- **Returns:** the count-first `size_t` array, or `NULL` (no match, empty + needle, NULL argument, allocation failure). - **Edge cases:** the needle cannot contain a literal NUL; the haystack can. @@ -379,8 +357,7 @@ Collects every occurrence of a single byte. - **Parameters:** `h` — haystack; `c` — the byte to search for. - **Returns:** the count-first `size_t` array, or `NULL` (no match, NULL argument, allocation failure). -- **Ownership:** caller-owned; release with `free`. -- **Edge cases:** searches the content only, so a `'\0'` needle finds +- **Edge cases:** only content is searched, so a `'\0'` needle finds embedded NUL content bytes, never the terminator. ## Comparison: `sx_cmp*` @@ -394,15 +371,13 @@ int sx_cmp(const sx_t *h, const sx_t *other); Compares two buffers lexicographically over their content bytes. - **Parameters:** `h` — left operand; `other` — right operand. -- **Returns:** a negative value if `h` sorts before `other`, 0 if they - are equal, a positive value if `h` sorts after. Only the sign is - meaningful. -- **Ownership:** none; neither buffer is modified. -- **Edge cases:** comparison is byte-wise in `memcmp` order (unsigned - byte values), so `"10" < "2"` and `"Z" < "中"`. A shorter string that - is a prefix of the other sorts first (`"abc" < "abcd"`). Embedded NUL - bytes compare as data. If either operand is NULL the result is 0 - (treated as equal) — never rely on that as a meaningful order. +- **Returns:** a negative value if `h` sorts before `other`, 0 if equal, a + positive value if it sorts after. Only the sign is meaningful. +- **Edge cases:** comparison is byte-wise in `memcmp` order (unsigned byte + values), so `"10" < "2"` and `"Z" < "中"`. A shorter string that is a + prefix of the other sorts first (`"abc" < "abcd"`). Embedded NUL bytes + compare as data. If either operand is NULL the result is 0 (treated as + equal) — never rely on that as a meaningful order. ### sx_cmp_view @@ -415,7 +390,6 @@ Compares a buffer with a view's bytes. - **Parameters:** `h` — left operand; `other` — right operand window; `other.len` bytes are compared. - **Returns:** negative, 0 or positive as in `sx_cmp`. -- **Ownership:** none; only reads. - **Edge cases:** NULL `h` returns 0. `other.ref == NULL` or an out-of-bounds window is out of contract. @@ -427,10 +401,9 @@ int sx_cmp_cstr(const sx_t *h, const char *s); Compares a buffer with a C string. -- **Parameters:** `h` — left operand; `s` — NUL-terminated right - operand, read with `strlen`. +- **Parameters:** `h` — left operand; `s` — NUL-terminated right operand, + read with `strlen`. - **Returns:** negative, 0 or positive as in `sx_cmp`. -- **Ownership:** none; only reads. - **Edge cases:** NULL `h` or `s` returns 0. An embedded NUL in `s` shortens the compared range. @@ -448,10 +421,9 @@ Tests whether `h` starts with another buffer's content. prefix. - **Returns:** 1 if the first `len(prefix)` content bytes of `h` equal the prefix byte for byte, otherwise 0. -- **Ownership:** none; only reads. -- **Edge cases:** an empty prefix always matches; a prefix longer than - `h` never matches. Byte-exact and binary-safe. NULL `h` or `prefix` - returns 0. +- **Edge cases:** an empty prefix always matches; a prefix longer than `h` + never matches. Byte-exact and binary-safe. NULL `h` or `prefix` returns + 0. ### sx_starts_with_view @@ -461,10 +433,9 @@ int sx_starts_with_view(const sx_t *h, sx_view_t prefix); Tests whether `h` starts with a view's bytes. -- **Parameters:** `h` — buffer; `prefix` — window read by - `prefix.len` bytes. +- **Parameters:** `h` — buffer; `prefix` — window read by `prefix.len` + bytes. - **Returns:** 1 on a match, otherwise 0. -- **Ownership:** none; only reads. - **Edge cases:** an empty view always matches. NULL `h` returns 0; `prefix.ref == NULL` or an out-of-bounds window is out of contract. @@ -479,7 +450,6 @@ Tests whether `h` starts with a C string. - **Parameters:** `h` — buffer; `prefix` — NUL-terminated prefix, read with `strlen`. - **Returns:** 1 on a match, otherwise 0. -- **Ownership:** none; only reads. - **Edge cases:** the empty string always matches; NULL `h` or `prefix` returns 0. @@ -493,12 +463,11 @@ Tests whether `h` ends with another buffer's content. - **Parameters:** `h` — buffer; `suffix` — buffer whose content is the suffix. -- **Returns:** 1 if the last `len(suffix)` content bytes of `h` equal - the suffix byte for byte, otherwise 0. -- **Ownership:** none; only reads. -- **Edge cases:** an empty suffix always matches; a suffix longer than - `h` never matches. Byte-exact and binary-safe. NULL `h` or `suffix` - returns 0. +- **Returns:** 1 if the last `len(suffix)` content bytes of `h` equal the + suffix byte for byte, otherwise 0. +- **Edge cases:** an empty suffix always matches; a suffix longer than `h` + never matches. Byte-exact and binary-safe. NULL `h` or `suffix` returns + 0. ### sx_ends_with_view @@ -508,10 +477,9 @@ int sx_ends_with_view(const sx_t *h, sx_view_t suffix); Tests whether `h` ends with a view's bytes. -- **Parameters:** `h` — buffer; `suffix` — window read by - `suffix.len` bytes. +- **Parameters:** `h` — buffer; `suffix` — window read by `suffix.len` + bytes. - **Returns:** 1 on a match, otherwise 0. -- **Ownership:** none; only reads. - **Edge cases:** an empty view always matches. NULL `h` returns 0; `suffix.ref == NULL` or an out-of-bounds window is out of contract. @@ -526,7 +494,6 @@ Tests whether `h` ends with a C string. - **Parameters:** `h` — buffer; `suffix` — NUL-terminated suffix, read with `strlen`. - **Returns:** 1 on a match, otherwise 0. -- **Ownership:** none; only reads. - **Edge cases:** the empty string always matches; NULL `h` or `suffix` returns 0. @@ -538,19 +505,18 @@ Tests whether `h` ends with a C string. sx_view_t *sx_split(const sx_t *h, const char *sep); ``` -Splits a buffer on a C-string separator into an array of token views. -The declaration lives in `sx.h` (the advanced layer), not in -`sx_core.h`. +Splits a buffer on a C-string separator into an array of token views. The +declaration lives in `sx.h` (the advanced layer), not in `sx_core.h`. -- **Parameters:** `h` — buffer to split; `sep` — separator C string, - read with `strlen`. An empty separator is refused, not treated as - "every byte". +- **Parameters:** `h` — buffer to split; `sep` — separator C string, read + with `strlen`. An empty separator is refused, not treated as "every + byte". - **Returns:** a malloc'ed `sx_view_t` array with the classic `char **` - shape, or `NULL` for NULL `h`, NULL `sep`, an empty `sep`, or - allocation failure. + shape, or `NULL` for NULL `h`, NULL `sep`, an empty `sep`, or allocation + failure. - **Ownership:** the caller owns the array and releases it with `free` - (not `sx_free`). The tokens are views into `h` and must never be - freed individually. + (not `sx_free`). The tokens are views into `h` and must never be freed + individually. - **Contract notes:** - The array has exactly `count + 1` elements: `arr[0] .. arr[count-1]` are the tokens in order, and `arr[count]` is the end guard whose @@ -561,20 +527,18 @@ The declaration lives in `sx.h` (the advanced layer), not in resumes past it, so `"aaaa"` split on `"aa"` yields three empty tokens, not two. - Empty fields are kept at every edge and in the interior: `"a,,b"` - gives `"a"`, `""`, `"b"`; a leading or trailing separator produces - an empty first or last token; an empty `h` splits into the single - token `""`; a string equal to the separator splits into two empty - tokens. + gives `"a"`, `""`, `"b"`; a leading or trailing separator produces an + empty first or last token; an empty `h` splits into the single token + `""`; a string equal to the separator splits into two empty tokens. - An empty token is not the end guard: it has `ref != NULL` and `len == 0`, while the guard has `ref == NULL`. - Tokens alias `h`'s content (`ref == h->ref`, `offset`, `len`): - copying nothing, modifying nothing, and reallocating nothing during - the call, so the content pointer is bitwise unchanged. Later edits - of `h` invalidate the tokens; do not edit `h` while they are in - use. - - Matching is byte-exact, so tokens may contain embedded NUL bytes - (the separator itself, being a C string, cannot). Print such a - token with `fwrite` or `"%.*s"` and its length, not with `"%s"`. + nothing is copied, modified or reallocated, so the content pointer is + bitwise unchanged. Later edits of `h` invalidate the tokens; do not + edit `h` while they are in use. + - Matching is byte-exact, so tokens may contain embedded NUL bytes (the + separator itself, being a C string, cannot). Print such a token with + `fwrite` or `"%.*s"` and its length, not with `"%s"`. The regex layer's `sx_reg_split` returns exactly this shape; see [Regular expressions](regex.md). diff --git a/docs/en_us/build-and-test.md b/docs/en_us/build-and-test.md index 7c3cf8b..bea88f0 100644 --- a/docs/en_us/build-and-test.md +++ b/docs/en_us/build-and-test.md @@ -4,11 +4,10 @@ English · [中文](../zh_cn/build-and-test.md) # Build, test & package -String X builds with [Forge](https://github.com/minelogy-dev/forge), a build -system whose build script is a C program. This page covers the toolchain -requirements, every `./make` task, the test harness and sanitizers, -installation, pkg-config and Debian packaging. For the CI pipelines that run -these commands, see [Continuous integration](ci.md). +String X builds with [Forge](https://github.com/minelogy-dev/forge). This page +covers prerequisites, `./make` tasks, the test harness and sanitizers, +installation, pkg-config and Debian packaging. CI is described in +[Continuous integration](ci.md). ## Prerequisites @@ -18,62 +17,31 @@ these commands, see [Continuous integration](ci.md). | C23 compiler | GCC 14+ or Clang 19+. | | `libpcre2-dev` | PCRE2 10.46, 8-bit, for the regex layer and every test. At run time the library needs `libpcre2-8-0`. | | `pkg-config` | Recommended for consumers; CI also uses it to link against the installed library. | -| Forge | The build tool; bootstrap it from source (next section). `./make` is generated, not checked in. | +| Forge | [github.com/minelogy-dev/forge](https://github.com/minelogy-dev/forge); `./make` is generated, not checked in. | | `tar` and `ar` | Only for `./make gen_deb`; `dpkg-deb` is only needed to inspect the result. | -Run every command from the repository root: `build.c` and `build.conf` are read +Run commands from the repository root; `build.c` and `build.conf` are read relative to it. -## Forge in one minute +## Build tool -Forge compiles `build.c` into a local executable, `./make`. That generated file -is the build entry point: each task below is a function in `build.c`, invoked as -`./make `. It is not GNU make. Re-run `forge .` whenever `build.c` or -`build.conf` changes. - -Bootstrap Forge from source and put its artifacts on the search paths: - -```sh -git clone https://github.com/minelogy-dev/forge.git -cd forge -./bootstrap.sh --no-test -export PATH="$PWD/build/output:$PATH" -export CPATH="$PWD/build/output/include" -cd /path/to/StringX -forge . -``` - -CI pins Forge to commit -`b6826ba762a1e9e337895e01ee604b943c682d23`. To reproduce CI exactly, check out -that commit into `.ci-deps/forge` and bootstrap it without installing system -files: +Install [Forge](https://github.com/minelogy-dev/forge) from its repository. Once +`forge .` has generated `./make`, the everyday commands are: ```sh -git clone https://github.com/minelogy-dev/forge.git .ci-deps/forge -git -C .ci-deps/forge checkout b6826ba762a1e9e337895e01ee604b943c682d23 -sh .ci-deps/forge/bootstrap.sh --no-test -export PATH="$PWD/.ci-deps/forge/build/output:$PATH" -export CPATH="$PWD/.ci-deps/forge/build/output/include" -forge . -``` - -Keep the pin identical in `.github/workflows/ci.yml` and -`.github/workflows/codeql.yml` when changing Forge. It is deliberately -independent of Forge's `main` branch and is not updated by Dependabot. - -With Forge on `PATH`, the everyday commands are the ones from the README: - -```sh -forge . # compile build.c into ./make (re-run whenever build.c changes) +forge . # generate ./make ./make # build -> build/output/libstringx.so (+ headers at build/output/include) ./make test # build and run every test under tests/ (ASan + UBSan) ``` +`./make` is generated and gitignored; re-run `forge .` after editing `build.c` +or `build.conf`. + ## Targets and commands | Command | What it does | | --- | --- | -| `forge .` | Compile `build.c` with the `build.conf` settings into a local `./make`. | +| `forge .` | Generate `./make` from `build.c` and `build.conf`. | | `./make` | Default `build` task: compile `src/` into `build/output/libstringx.so` and sync `include/*.h` to `build/output/include/`. | | `./make check` | Compile the library target with the warning flags and the GCC analyzer, without the header sync. | | `./make test` | Build and run every file in `tests/` under ASan + UBSan + LSan. | @@ -81,11 +49,11 @@ forge . # compile build.c into ./make (re-run whenever build.c changes) | `./make install ` | Build, then install the library, headers, notices and `libstringx.pc`; the prefix defaults to `/usr/local`. | | `./make gen_deb` | Build, then stage and produce `build/deb/libstringx__.deb`. | -`-v` makes `./make test` and `./make check` print the full compile commands; -without it only `PASSED`/`FAILED` lines and the final summary are shown. `-j N` +`-v` prints the full compile commands for `./make test` and `./make check`; +without it only `PASSED`/`FAILED` lines and the summary appear. `-j N` parallelizes one target's compile pass. -The artifacts land here: +Artifacts: | Path | Produced by | Contents | | --- | --- | --- | @@ -96,41 +64,43 @@ The artifacts land here: | `build/opt/` | `./make test` | test object files with their `.d`/`.meta` files | | `build/deb/` | `./make gen_deb` | the Debian staging tree and the final `.deb` | -`./make test` does not need `./make` first: every test compiles the library -sources directly. +`./make test` needs no prior `./make`: every test compiles the library sources +directly. ## build.conf -`build.conf` is read when Forge generates `./make`; each `KEY=VALUE` line -becomes a `-DCONF_KEY=VALUE` macro for the build script. Lines starting with -`#` are comments. Re-run `forge .` after editing it. +`build.conf` is read when `./make` is generated; each `KEY=VALUE` line becomes a +`-DCONF_KEY=VALUE` macro, and `#` starts a comment. Re-run `forge .` after +editing it. | Key | Value | Effect | | --- | --- | --- | | `compiler` | `GCC` or `CLANG` | Toolchain backend. `build.c` forwards `CONF_compiler` to `set_toolchain`, so this selects the compiler for the library and the tests. | -| `compiler_path` | an absolute path, e.g. `/usr/bin/gcc` | The compiler binary Forge uses to build the generated `./make`. | +| `compiler_path` | an absolute path, e.g. `/usr/bin/gcc` | Compiler binary used when generating `./make`. | | `version` | `v0.5` | The single source of truth for the project version. `build.c` stringifies it into `SX_VERSION`; install and packaging strip the leading `v`. | | `sanitize` | `1` | Added by `.github/scripts/configure.sh` in CI. The sanitizer flags themselves are declared per test in the header DSL. | ## Running the tests `./make test` scans `tests/` recursively, compiles each `tests/*.c` into -`test/` and runs it. A test prints `PASSED: ` on success, or -`FAILED: :: ` on the first failing assertion. The task -ends with a summary such as: +`test/` and runs it. Success prints `PASSED: `; the first failed +assertion prints `FAILED: :: `. The summary looks +like: ```text -forge: 20 tests, 20 passed, 0 failed +forge: 24 tests, 24 passed, 0 failed ``` -The task exits non-zero if any test fails to compile or to run. +The task exits non-zero if a test fails to compile or run. -Tests do not link `libstringx.so`: each one compiles the library sources -directly and declares its own flags, including `-fsanitize=address,undefined` -and `-fno-omit-frame-pointer`. LeakSanitizer runs together with ASan, so a test -that forgets to free a buffer or a returned array fails. +Tests do not link `libstringx.so`: each compiles the library sources directly +and declares its own flags, including `-fsanitize=address,undefined` and +`-fno-omit-frame-pointer`. LeakSanitizer runs with ASan, so an unfreed buffer +or array fails the test. A few tests share a local case header +(`find_differential.h`, `write_overflow_cases.h`) between the normal and a +forced-configuration sibling; each `.c` remains its own target. -Set the same sanitizer options CI uses: +Set CI's sanitizer options: ```sh export ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 @@ -138,7 +108,7 @@ export UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 ./make test -j 2 ``` -To rerun one built test directly: +Rerun one built test directly: ```sh ./test/reserve_stress @@ -146,39 +116,39 @@ To rerun one built test directly: ### Exact-reserve stress test -`tests/reserve_stress.c` is the dedicated configuration for -`-DSX_FORCE_EXACT_RESERVE`, declared as -`// Option -DSX_FORCE_EXACT_RESERVE` in its header. The switch remaps the -internal reserve helper in `src/sx_raw.c` from geometric growth to exact sizing -(`cap == need + 1`), so an allocation ends exactly at the terminator and any -access past `len` hits an ASan redzone immediately — slack capacity cannot hide -an off-by-one or a stale length. The test drives a deterministic LCG over three -live buffers and asserts full content on every edit; its models stay within -512 bytes. Every other test builds in the default geometric-growth mode. +`tests/reserve_stress.c` and `tests/write_overflow_exact.c` run with +`-DSX_FORCE_EXACT_RESERVE`, declared as `// Option -DSX_FORCE_EXACT_RESERVE` in +their headers. The switch remaps the internal reserve helper in `src/sx_raw.c` +from geometric growth to exact sizing (`cap == need + 1`): the allocation ends +exactly at the terminator, so any access past `len` hits an ASan redzone and +slack capacity cannot hide an off-by-one or a stale length. The stress test +drives three live buffers with a deterministic LCG and asserts full content on +every edit (models stay within 512 bytes); the write-overflow test repeats its +`SIZE_MAX` range cases under exact allocations. Every other test builds with +geometric growth. ## Test files and the header DSL -Each test is a self-contained program. Its leading consecutive `//` lines form a -header DSL that Forge's test runner reads; the first non-`//` line ends the -header. +Each test is a self-contained program. Its leading consecutive `//` lines are a +header DSL read by the test runner; the first non-`//` line ends it. | Entry | Effect | | --- | --- | -| `// Include ` | Add `-I`. Every test includes `include`, `src` and `/usr/lib/forge/include` — Forge's headers for ``; the last one is harmless when they are supplied through `CPATH` instead. | +| `// Include ` | Add `-I`. Every test includes `include`, `src` and `/usr/lib/forge/include`; the last one supplies `` when it is not on `CPATH`. | | `// Source ` | Add a source file to the test executable. Tests add `src/sx_raw.c`, `src/sx_core.c` and `src/sx_adv.c`. | | `// Link ` | Add `-l`. Only `tests/reg.c` adds `pcre2-8`; the other tests do not use the regex layer. | | `// Library ` | Add `-L`. Tests add `/usr/local/lib`. | | `// Option ` | Add a compiler, linker and assembler option. Tests use `-std=c23 -O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer`, plus test-specific defines such as `-DSX_FORCE_EXACT_RESERVE`. | -A line without a keyword continues the current scope, which starts as `Source`; -the tests spell out every keyword for clarity. +A line without a keyword continues the current scope (initially `Source`); the +tests spell out every keyword. -Because every test compiles `src/sx_adv.c`, `build.c` attaches `pcre2-8` to -every test target through its reserved `LANGUAGE` override; `tests/reg.c` also -declares `// Link pcre2-8` explicitly. +Every test compiles `src/sx_adv.c`, so `build.c` attaches `pcre2-8` to every +test target through its reserved `LANGUAGE` override; `tests/reg.c` also +declares `// Link pcre2-8`. -The program itself includes the header under test (`"sx.h"`, or `"sx_core.h"` -for core-only tests) and `` for two test macros: +The program includes the header under test (`"sx.h"`, or `"sx_core.h"` for +core-only tests) and `` for two macros: | Macro | Purpose | | --- | --- | @@ -188,14 +158,14 @@ for core-only tests) and `` for two test macros: ### Adding a test 1. Create `tests/.c` — one behavior area per file. -2. Copy the header DSL block from an existing test and adjust `Source`, - `Link` and `Option` for the dependencies you need. -3. Document the behavior boundaries at the top: what the test locks in - (`In scope (contract)`) and what it deliberately does not exercise +2. Copy a header DSL block from an existing test; adjust `Source`, `Link` and + `Option` as needed. +3. Document the behavior boundaries: what the test locks in + (`In scope (contract)`) and what it does not exercise (`Out of contract (not exercised)`). 4. Include the header under test, assert with `TEST`, free every buffer and returned array, then finish with `PASS()`. -5. Run `./make test`. The new file is discovered automatically. +5. Run `./make test`; the new file is discovered automatically. ```c // Include include @@ -238,7 +208,7 @@ int main(void) { ## Installing -`./make install` builds first (including the header sync), then copies: +`./make install` builds first (with the header sync), then copies: | Destination | Contents | | --- | --- | @@ -251,16 +221,15 @@ int main(void) { | `/share/doc/libstringx/THIRD_PARTY_NOTICES.md` | PCRE2 attribution and license | | `/share/doc/libstringx/copyright` | a copy of `LICENSE` under Debian's conventional name | -The default prefix is `/usr/local`. Pass a prefix you can write to without -root, for example: +The default prefix is `/usr/local`; pass a writable prefix, for example: ```sh ./make install "$HOME/.local" ``` -The pkg-config file is generated at install time. Its `prefix=` is the install -prefix and its `Version` is the `build.conf` version without the leading `v` -(so `0.5`). +The pkg-config file is generated at install time: `prefix=` is the install +prefix, and `Version` is the `build.conf` version without the leading `v` +(`0.5`). ## Consuming the installed library @@ -286,8 +255,8 @@ cc -std=c23 hello.c $(pkg-config --cflags --libs libstringx) \ -Wl,-rpath,"/lib" -o hello ``` -The library links `pcre2-8` itself, so consumers do not need `-lpcre2-8`. A -complete program: +The library links `pcre2-8`, so consumers need no `-lpcre2-8`. A complete +program: ```c #include @@ -306,8 +275,8 @@ int main(void) { ## Debian package -`./make gen_deb` builds first, then stages and packages a Debian `.deb` with -`tar` and `ar` (no `dpkg-deb` dependency): +`./make gen_deb` builds first, then stages a Debian `.deb` with `tar` and `ar` +(no `dpkg-deb` dependency): | Path | Contents | | --- | --- | @@ -316,13 +285,12 @@ int main(void) { | `build/deb/debian-binary`, `control.tar.gz`, `data.tar.gz` | the package parts | | `build/deb/libstringx__.deb` | the finished package | -The version comes from `build.conf` with the leading `v` stripped; the -architecture comes from `uname -m` (`x86_64` → `amd64`, `aarch64` → `arm64`, -anything else unchanged). The package installs under `/usr` and declares -`Depends: libc6, libpcre2-8-0`. The `libstringx.pc` inside the package bakes -`/usr` as its prefix; the staging path never leaks into it. +Version comes from `build.conf` without the leading `v`; architecture from +`uname -m` (`x86_64` → `amd64`, `aarch64` → `arm64`, otherwise unchanged). The +package installs under `/usr`, declares `Depends: libc6, libpcre2-8-0`, and +bakes `/usr` into its `libstringx.pc` — the staging path never leaks in. -Inspect and install it: +Inspect and install: ```sh dpkg-deb --info build/deb/libstringx_*.deb @@ -334,25 +302,24 @@ sudo apt install ./build/deb/libstringx_*.deb | Symptom | Cause and fix | | --- | --- | -| `forge: command not found` | Forge is not on `PATH`. Bootstrap it and export `PATH=/build/output`. | -| `build.h: No such file or directory` | Forge's build-script headers are not visible. Export `CPATH=/build/output/include` as CI does, or install Forge system-wide. `` exists only inside Forge builds. | +| `forge: command not found` | Forge is not on `PATH`; follow its repository's installation instructions. | | `pcre2.h: No such file or directory` or `cannot find -lpcre2-8` | Install `libpcre2-dev` (Ubuntu: `sudo apt-get install libpcre2-dev`). | | `./make: No such file or directory` after cloning | `./make` is generated and gitignored. Run `forge .` first. | | Changes to `build.c` or `build.conf` have no effect | `./make` was generated from the old script. Re-run `forge .`. | -| Test link fails with Clang and `-flto` | The pinned Forge emits GCC-only `-flto=N` for parallel Clang links, so the test targets in `build.c` deliberately disable LTO; production targets keep it. Keep test LTO disabled when running the suite with Clang. | +| Test link fails with Clang and `-flto` | The pinned build tool emits GCC-only `-flto=N` for parallel Clang links, so test targets in `build.c` disable LTO; production targets keep it. | | `install` reports a permission error | The prefix is not writable. Pass one you own, e.g. `./make install "$HOME/.local"`. | | A test fails with a leak report | A buffer or an array is not freed. Free every `sx_t` with `sx_free` and every returned array with `free`. | | A consumer binary cannot find `libstringx.so` | Set `LD_LIBRARY_PATH` to `/lib`, link with `-Wl,-rpath,/lib`, or install to a standard prefix. | -Do not include `` in the library sources or in applications: it is -Forge's build-script DSL header, not part of the String X API. Applications -include `` only. +Do not include `` in library sources or applications: it is the +build-script DSL header, not part of the String X API. Applications include +`` only. ## Continuous integration -The workflows that run these commands on every push and pull request — the -build matrix, the analyzer, the quality checks, CodeQL and merge protection — -are described in [Continuous integration](ci.md). +The workflows that run these commands on every push and pull request — build +matrix, analyzer, quality checks, CodeQL and merge protection — are in +[Continuous integration](ci.md). --- diff --git a/docs/en_us/ci.md b/docs/en_us/ci.md index fbb8b01..e5e7128 100644 --- a/docs/en_us/ci.md +++ b/docs/en_us/ci.md @@ -5,9 +5,8 @@ English · [中文](../zh_cn/ci.md) # Continuous integration Changes to `main`, pull requests and manual runs use GitHub Actions. This page -covers what each workflow verifies, how to reproduce the checks locally, and how -merge protection ties them together. For the commands themselves — Forge -bootstrap, `./make` targets, the test harness — see +covers the workflows, local reproduction and merge protection; for build +commands, `./make` targets and the test harness see [Build, test & package](build-and-test.md). ## Triggers @@ -16,11 +15,12 @@ bootstrap, `./make` targets, the test harness — see | --- | --- | | `push` to `main` | [ci.yml](../../.github/workflows/ci.yml) and [codeql.yml](../../.github/workflows/codeql.yml) | | `pull_request` on any branch | `ci.yml` and `codeql.yml` | -| `workflow_dispatch` (manual run) | `ci.yml` and `codeql.yml` | +| `pull_request`, path-filtered | [write-safety.yml](../../.github/workflows/write-safety.yml) (`src/sx_core.c`, `tests/write_overflow*`, its script), [search-performance.yml](../../.github/workflows/search-performance.yml) (`src/sx_core.c`, its script), [benchmarks.yml](../../.github/workflows/benchmarks.yml) (`benchmarks/**`), [benchmark-report.yml](../../.github/workflows/benchmark-report.yml) (its workflow file only) | +| `workflow_dispatch` (manual run) | `ci.yml`, `codeql.yml`, `write-safety.yml`, `search-performance.yml`, `benchmarks.yml`, `benchmark-report.yml` | | `schedule` | `codeql.yml` only (weekly) | -The workflows have read-only repository access, except for the CodeQL job's -permission to publish code-scanning results. Pull-request code never runs via +Workflows have read-only repository access, except CodeQL's permission to +publish code-scanning results. Pull-request code never runs via `pull_request_target`, and checkout credentials are not persisted. ## Checks @@ -32,42 +32,48 @@ permission to publish code-scanning results. Pull-request code never runs via | GCC static analysis | `-fanalyzer` checks production translation units; diagnostics fail the job | | Workflow and secret checks | Actionlint, ShellCheck, whitespace errors and Gitleaks over the complete Git history, with redacted output | | CodeQL (C/C++) | Manual build tracing with `security-and-quality` queries, findings in the Security tab and on pull requests | +| Write safety and cost | Re-runs the write-overflow regression against the immutable old implementation (a sanitizer failure is required there), runs both fixed configurations with GCC 14 and Clang 19, and compares equal-length write cost with SDS and bstrlib | +| Search performance | Before/after search benchmark with GCC and Clang for `src/sx_core.c` changes | +| Audited benchmarks | Reruns the pinned StringX / SDS / bstrlib harness when `benchmarks/` changes | +| Benchmark results report | Renders a saved benchmark artifact as a report (manual) | | CI | A stable required check that fails if any build, analyzer or quality job fails or is cancelled | +The four audit/benchmark workflows are path-filtered and independent of the +aggregate `CI` check; they gate merges only if branch protection requires them. + GCC analysis uses `-O1 -fno-analyzer-state-merge`: GCC 14's default state -merging produces spurious allocation/cleanup diagnostics in this code. No -diagnostic categories are suppressed. An analyzer failure should be -investigated, not worked around with `continue-on-error`. +merging produces spurious allocation/cleanup diagnostics here. No categories +are suppressed; investigate analyzer failures instead of using +`continue-on-error`. -All external Actions use immutable commit SHAs. Dependabot proposes weekly -GitHub Actions updates. The Actionlint and Gitleaks CLIs have pinned versions -and SHA-256 checksums in +External Actions are pinned to immutable commit SHAs; Dependabot proposes +weekly updates. The Actionlint and Gitleaks CLIs have pinned versions and +SHA-256 checksums in [.github/scripts/install-tools.sh](../../.github/scripts/install-tools.sh); -update both values together when upgrading them. +update both together when upgrading. ## CodeQL -CodeQL is configured for C/C++ with manual build tracing and the -`security-and-quality` query set. It analyzes the code built by the pinned Forge -toolchain, publishes findings to the Security tab, and reports them on pull -requests. +CodeQL covers C/C++ with manual build tracing and `security-and-quality` +queries. It analyzes code built by the pinned toolchain, publishes +findings to the Security tab and on pull requests. -CodeQL also runs every Monday at 11:17 Asia/Shanghai (03:17 UTC). A successful -job status means the analysis completed; it does **not** mean there are no -alerts. Use a code-scanning merge rule to enforce alert severity — see +CodeQL also runs every Monday at 11:17 Asia/Shanghai (03:17 UTC). Success means +the analysis completed, not that there are no alerts; enforce severity with a +code-scanning merge rule — see [Enable merge protection](#enable-merge-protection). ## Enable merge protection -Workflow files alone do not enable branch protection; these repository settings -are a one-time maintainer configuration. After the first successful run, create -a branch ruleset for `main`: +Workflow files alone do not enable branch protection; these are one-time +maintainer settings. After the first successful run, create a branch ruleset +for `main`: 1. Require pull requests and the `CI` and `CodeQL (C/C++)` status checks. 2. Require branches to be up to date before merging. 3. Add "Require code scanning results", select CodeQL, and block high/critical - security alerts and error-level quality alerts. Tighten these thresholds - after triaging existing findings. + security alerts and error-level quality alerts; tighten thresholds after + triaging existing findings. 4. Use the checked-in advanced CodeQL workflow rather than enabling a duplicate default-setup scan. @@ -77,8 +83,8 @@ review. ## Reproduce locally Install Linux build dependencies and a C23 compiler (GCC 14+ or Clang 19+). -Save local `build.conf` changes before running `configure.sh`: it updates the -compiler selection and appends `sanitize=1` in that file. +Save local `build.conf` changes before `configure.sh`: it updates the compiler +selection and appends `sanitize=1`. ```sh CC=gcc bash .github/scripts/configure.sh # or CC=clang @@ -86,54 +92,43 @@ CC=gcc bash .github/scripts/check-c.sh CC=gcc bash .github/scripts/check-c.sh analyze ``` -Use GCC for `analyze`. Runtime checks set: +Use GCC for `analyze`; runtime checks set: ```sh export ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 export UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 ``` -The build dependency is Forge commit -`b6826ba762a1e9e337895e01ee604b943c682d23`, checked out under `.ci-deps/forge` -in CI and bootstrapped without installing system files. PCRE2 comes from -Ubuntu's `libpcre2-dev` package. - -With a bootstrapped Forge checkout available locally: +CI pins Forge to a reviewed commit (checked out under `.ci-deps/forge`); both +workflow files contain the exact pin and setup commands, and the pin must +be updated in both together. PCRE2 comes from Ubuntu's `libpcre2-dev` package. +With Forge installed: ```sh -export PATH="/path/to/forge/build/output:$PATH" -export CPATH="/path/to/forge/build/output/include" forge . ./make ./make test -j 2 ``` -CI additionally installs into a temporary prefix, compiles and runs the existing -regex suite against the **installed shared library** using `pkg-config`, and -inspects the generated Debian package. This checks public headers, exported -symbols, package metadata and PCRE2 linkage in addition to source-level -behavior. The corresponding commands are in `ci.yml`; the layout they exercise -is documented in [Build, test & package](build-and-test.md). - -## Pinned Forge commit +The focused audit scripts live in `.github/scripts/` (`check-write-safety.py`, +`compare-search.py`); `benchmarks/` documents its own harness and rerun steps. -Both workflow files check out Forge commit -`b6826ba762a1e9e337895e01ee604b943c682d23` under `.ci-deps/forge` and bootstrap -it with `sh .ci-deps/forge/bootstrap.sh --no-test`, without installing system -files. Update this reviewed pin in **both** workflow files when changing Forge. -It is intentionally independent of Forge's moving `main` branch and is not -updated by Dependabot. +CI also installs into a temporary prefix, compiles and runs the existing regex +suite against the **installed shared library** via `pkg-config`, and inspects +the generated Debian `.deb`. This checks public headers, exported symbols, +package metadata and PCRE2 linkage beyond source-level behavior. Commands are +in `ci.yml`; the layout is in [Build, test & package](build-and-test.md). ## Review and failures -Open the failed check for compiler diagnostics, sanitizer stack traces or -secret-scan locations. Build failures retain dependency and command metadata for -seven days; the Actions log contains the full build/test output. CodeQL alerts -include the affected lines and data flow where available. +Open the failed check for compiler diagnostics, sanitizer traces or secret-scan +locations. Build failures keep dependency and command metadata for seven days; +the Actions log has the full output. CodeQL alerts include affected lines and +data flow where available. -Automation covers mechanical regressions and many common memory-safety bugs. -Human review should concentrate on requirements, API contracts, ownership, -architecture and the findings reported by these tools. +Automation covers mechanical regressions and many memory-safety bugs; human +review should focus on requirements, API contracts, ownership, architecture and +tool findings. --- diff --git a/docs/en_us/contributing.md b/docs/en_us/contributing.md index 837541b..4570d8f 100644 --- a/docs/en_us/contributing.md +++ b/docs/en_us/contributing.md @@ -4,18 +4,17 @@ English · [中文](../zh_cn/contributing.md) # Contributing -String X is a small C23 library with a tightly documented contract, so changes -are easiest to review when they stay small, keep the tests and the documentation -in step, and pass the same checks CI runs. This page describes the workflow and -the conventions the project expects. +String X is a small C23 library with a detailed contract. Keep documentation, +tests and changes in sync. This page covers the workflow and project +conventions. ## Workflow -1. Fork the repository and create a branch from `main`. Name the branch for the - change (`fix/split-end-guard`, `docs/build-targets`). -2. Make the change, including tests for behavior and updates to the English and - Chinese documentation. -3. Run the local checks before opening the pull request: +1. Fork the repository and branch from `main`; name it for the change + (`fix/split-end-guard`, `docs/build-targets`). +2. Make the change, with behavior tests and English/Chinese documentation + updates. +3. Run the local checks before opening a pull request: ```sh ./make test -j 2 @@ -23,76 +22,74 @@ the conventions the project expects. bash .github/scripts/check-c.sh analyze # GCC only ``` -4. Open a pull request against `main` and describe the behavior change, the - tests that cover it, and the documentation pages you updated. -5. Wait for the required checks. Merge protection on `main` requires the `CI` - and `CodeQL (C/C++)` status checks and up-to-date branches. The checks are - described in [Continuous integration](ci.md). +4. Open a pull request against `main` describing the behavior change, its tests + and updated documentation pages. +5. Wait for the required checks: merge protection on `main` requires `CI` and + `CodeQL (C/C++)` and up-to-date branches — see + [Continuous integration](ci.md). Path-filtered write-safety, + search-performance and benchmark workflows also run for matching changes. 6. Address review comments with additional commits; keep the pull request - focused on one change. + focused. -`bash .github/scripts/configure.sh` reproduces CI's compiler selection, but it -rewrites `compiler=`, `compiler_path=` and `sanitize=` in `build.conf`, so save -any local changes to that file first. +`bash .github/scripts/configure.sh` reproduces CI's compiler selection but +rewrites `compiler=`, `compiler_path=` and `sanitize=` in `build.conf`; save +local changes first. ## Contract-first documentation Behavior boundaries live in two places: -- the comments in the public headers, `include/sx.h` and `include/sx_core.h`; -- the `Behavior boundaries` comment at the top of every `tests/*.c`, with its +- the comments in the public headers `include/sx.h` and `include/sx_core.h`; +- the `Behavior boundaries` comment atop every `tests/*.c`, with its `In scope (contract)` and `Out of contract (not exercised)` lists. -A change to observable behavior must update all of them together: +A behavior change updates all of them together: -1. the header comment for every affected function; +1. the header comment of every affected function; 2. the test implementation and its behavior-boundaries comment; 3. the English and Chinese pages under `docs/en_us/` and `docs/zh_cn/`. -Do not leave a behavior undocumented or documented as it used to be. When -sources disagree, the tests win for run-time behavior, the headers win for -signatures, and `build.c` wins for build and packaging behavior — report a real -contradiction instead of silently picking one. +Never leave a behavior undocumented or stale. When sources disagree, tests win +for run-time behavior, headers for signatures, and `build.c` for build and +packaging — report a real contradiction instead of picking one silently. ## Code style - C23; the library and tests build with `-std=c23`. -- Two-space indentation; opening braces stay on the same line. -- Follow the existing naming and layering: core functions in `src/sx_core.c`, - the advanced regex layer in `src/sx_adv.c`, internal allocation in - `src/sx_raw.c`. Do not add public functions outside `sx.h`/`sx_core.h`. -- Use `size_t` for offsets and lengths, and the existing sentinel conventions +- Two-space indent; opening braces on the same line. +- Follow existing naming and layering: core in `src/sx_core.c`, regex in + `src/sx_adv.c`, allocation in `src/sx_raw.c`. Do not add public functions + outside `sx.h`/`sx_core.h`. +- Use `size_t` for offsets and lengths and the existing sentinel conventions (`(size_t)-1`, a view with `ref == NULL`, a NULL array). -- Treat warnings as errors. The `./make check` target compiles the library - with `-Wall -Wextra -Wpedantic -Werror` and, on GCC, `-fanalyzer`; the - direct compile check in CI uses - `-std=c23 -O1 -Wall -Wextra -Werror`. Do not suppress a diagnostic to make - a build pass; fix the code or explain the analyzer finding in review. +- Treat warnings as errors: `./make check` uses + `-Wall -Wextra -Wpedantic -Werror` and, on GCC, `-fanalyzer`; CI's direct + compile check uses `-std=c23 -O1 -Wall -Wextra -Werror`. Do not suppress a + diagnostic; fix the code or explain the analyzer finding in review. ## Tests -Every behavior change needs a test. Tests are self-contained programs under -`tests/` that compile the library sources directly and declare their -dependencies in the header DSL (`// Include`, `// Source`, `// Link`, -`// Library`, `// Option`). See -[Build, test & package](build-and-test.md) for the DSL and a complete example. - -When adding or changing a test: - -- keep the `Behavior boundaries` comment accurate — it is the written contract - the test enforces, including the `Out of contract (not exercised)` list; -- assert observable results (exact bytes, lengths, offsets and sentinels), not - only that a call returned non-NULL; -- free every buffer with `sx_free` and every returned array with `free`; the - suite runs under AddressSanitizer, UBSan and LeakSanitizer, and a leak or an - out-of-bounds access fails the test; -- keep the sanitizer flags and `-fno-omit-frame-pointer` in the test header so - the test runs the same way locally and in CI; -- if you change allocation or growth, run the exact-reserve configuration in +Every behavior change needs a test. Tests under `tests/` are self-contained +programs that compile the library sources and declare dependencies in the +header DSL (`// Include`, `// Source`, `// Link`, `// Library`, `// Option`); +see [Build, test & package](build-and-test.md) for the DSL and an example. + +When adding or changing one: + +- keep the `Behavior boundaries` comment accurate — it is the contract the test + enforces, including `Out of contract (not exercised)`; +- assert observable results (bytes, lengths, offsets, sentinels), not just + non-NULL; +- free every buffer with `sx_free` and every array with `free`; the suite runs + under AddressSanitizer, UBSan and LeakSanitizer, so a leak or out-of-bounds + access fails; +- keep sanitizer flags and `-fno-omit-frame-pointer` in the test header so local + and CI runs match; +- if you change allocation or growth, run the exact-reserve config in `tests/reserve_stress.c` (`-DSX_FORCE_EXACT_RESERVE`), which exposes - off-by-one accesses that slack capacity can hide. + off-by-one accesses slack capacity can hide. -Run the suite with the same environment CI uses: +Run the suite with CI's environment: ```sh export ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 @@ -103,32 +100,30 @@ export UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 ## Commits and pull requests - Keep one logical change per commit and a focused diff; avoid unrelated - reformatting and drive-by changes. -- Write a short imperative subject line, then a body that explains why the - change is needed and which behavior boundaries or documentation it touches. - Reference the issue when one exists. -- Include tests and both language versions of the documentation in the same - pull request as the code. -- Leave build artifacts out of the diff: `build/`, `test/`, `./make` and - `.ci-deps/` are generated and gitignored. -- A pull request is ready to merge when the required checks pass and review - comments are resolved. + reformatting. +- Use a short imperative subject; the body explains why and which boundaries or + docs change. Reference the issue when one exists. +- Put tests and both language versions of the docs in the same pull request. +- Leave build artifacts out: `build/`, `test/`, `./make` and `.ci-deps/` are + generated and gitignored. +- A pull request is ready when required checks pass and review comments are + resolved. ## Licensing and attribution -- The library and the project sources are MIT licensed. New C source and header - files should start with `// SPDX-License-Identifier: MIT`, as `include/sx.h`, - `src/sx_adv.c` and `tests/reg.c` do; keep existing SPDX headers intact. -- The build script and the Forge-derived `src/export.h` are covered by Forge's - build-script exception, identified as - `GPL-3.0-or-later WITH LicenseRef-Forge-BuildScript-Exception`. `build.conf` - and `src/export.h` already carry that identifier and `build.c` is covered by - the same exception; do not relicense this build tooling as MIT or remove the - headers. -- The regex layer uses PCRE2 (BSD-3-Clause). Its attribution and license text - live in [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md). If you add a - third-party dependency, add its notice and license there as well. -- The project license is reproduced in [LICENSE](../../LICENSE). +- The library and project sources are MIT licensed. New C source and header + files start with `// SPDX-License-Identifier: MIT`, as `include/sx.h`, + `src/sx_adv.c` and `tests/reg.c` do; keep existing SPDX headers. +- The build script and Forge-derived `src/export.h` fall under Forge's + build-script exception, + `GPL-3.0-or-later WITH LicenseRef-Forge-BuildScript-Exception`. + `build.conf` and `src/export.h` carry that identifier and `build.c` is + covered by the same exception; do not relicense this build tooling as MIT or + remove the headers. +- The regex layer uses PCRE2 (BSD-3-Clause), attributed in + [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md). Add new third-party + dependencies and their licenses there too. +- The project license is in [LICENSE](../../LICENSE). ## Where things live @@ -137,7 +132,8 @@ export UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 | [include/](../../include) | public headers: `sx.h` (advanced layer and `sx_split`) and the `sx_core.h` it includes | | [src/](../../src) | implementation: `sx_core.c`, `sx_adv.c`, `sx_raw.c`, plus the internal `_sx.h` and `export.h` | | [tests/](../../tests) | the self-contained test suite | -| [build.c](../../build.c), [build.conf](../../build.conf) | the Forge build script and its configuration | +| [benchmarks/](../../benchmarks) | audited StringX / SDS / bstrlib benchmarks and rerun tooling | +| [build.c](../../build.c), [build.conf](../../build.conf) | the build script and its configuration | | [.github/workflows/](../../.github/workflows) | the CI and CodeQL workflows | | [.github/scripts/](../../.github/scripts) | compiler, analyzer and tooling checks used by CI | | [docs/](../) | this documentation, in English and Simplified Chinese | diff --git a/docs/en_us/design.md b/docs/en_us/design.md index c189f80..3aee985 100644 --- a/docs/en_us/design.md +++ b/docs/en_us/design.md @@ -4,10 +4,9 @@ English · [中文](../zh_cn/design.md) # Design and internals -This page is for contributors and for readers who need to reason about the -library's guarantees or port it. It describes the data layout, the -algorithms, the ownership model and the deliberate trade-offs behind the -public contracts in ``. The contracts themselves are documented in the +This page is for contributors who need to reason about the library's +guarantees or port it: the data layout, algorithms, ownership model and +trade-offs behind the `` contracts. The contracts themselves are in the [API reference](api-buffer.md), [search reference](api-search.md) and [regular expressions](regex.md) pages. @@ -15,34 +14,32 @@ public contracts in ``. The contracts themselves are documented in the The design follows from a short set of goals: -- **Byte-exact contract.** Every operation is defined on bytes and its - behavior boundaries are written down. Search, comparison and regex work - by length, so embedded NUL bytes are ordinary data. -- **Zero-copy access.** Slices are `sx_view_t` values that alias a buffer; - inspecting or iterating over subslices copies nothing. -- **One stable handle per buffer.** An `sx_t *` identifies the buffer for - its whole life; edits return `self`, so calls compose into chains even - when the backing array is reallocated. -- **Predictable failure.** A documented invalid input produces a fixed - sentinel instead of crashing; inputs outside the documented boundaries are - out of contract. There are no exceptions, error codes or global error - state. -- **Small surface.** One public header ``, one library, one optional - advanced dependency (PCRE2) that the library links itself. +- **Byte-exact contract.** Operations are defined on bytes and their + boundaries written down. Search, comparison and regex work by length, so + embedded NULs are ordinary data. +- **Zero-copy access.** Slices are `sx_view_t` values aliasing a buffer; + inspecting subslices copies nothing. +- **One stable handle per buffer.** An `sx_t *` identifies its buffer for + life; edits return `self`, so calls chain even when the array is reallocated. +- **Predictable failure.** Documented invalid input yields a fixed sentinel + instead of crashing; other inputs are out of contract. No exceptions, error + codes or global error state. +- **Small surface.** One header ``, one library, one advanced dependency + (PCRE2) that the library links itself. Equally deliberate non-goals: -- **No text encoding layer.** The library does not decode UTF-8, normalize - text, or provide character/grapheme operations. Strings are bytes; the - regex layer runs PCRE2 in 8-bit non-UTF mode. +- **No text encoding layer.** No UTF-8 decoding, normalization or character + and grapheme operations. Strings are bytes; the regex layer runs PCRE2 in + 8-bit non-UTF mode. - **No locale awareness.** Comparison, trimming and character classes are - defined on bytes and fixed ASCII sets, independent of `LC_*`. -- **No thread-safe buffers.** A compiled regex is immutable and shareable; - a mutable buffer is plain memory and needs external synchronization. -- **No custom allocator hooks, ropes/streaming, or lazy views.** Every - buffer is one contiguous allocation. -- **No regex engine of its own.** Pattern semantics are PCRE2's; the - library supplies only the lifecycle, scanning and substitution plumbing. + byte- and ASCII-defined, independent of `LC_*`. +- **No thread-safe buffers.** Compiled regexes are immutable and shareable; + mutable buffers are plain memory needing external synchronization. +- **No custom allocators, ropes/streaming or lazy views.** Every buffer is one + contiguous allocation. +- **No regex engine of its own.** Pattern semantics are PCRE2's; the library + supplies only lifecycle, scanning and substitution plumbing. ## Layers and headers @@ -56,9 +53,8 @@ Equally deliberate non-goals: | `src/_sx.h` | internal | definition of `struct _sx` | library only | | `src/export.h` | Forge-derived | `SYMBOL_PUBLIC` visibility macro (checked in) | library only | -Consumers include ``. `sx_core.h` is public because `` includes -it, but it is not a second entry point: `sx_split` and the regex layer are -only declared in `sx.h`. +Consumers include ``; `sx_core.h` is public only because `` +includes it. `sx_split` and the regex layer are declared only in `sx.h`. The implementation mirrors the header split: @@ -68,27 +64,26 @@ The implementation mirrors the header split: | `src/sx_raw.c` | allocation primitives (`sx__new`, `sx__reserve`, ...) | | `src/sx_adv.c` | `sx_split` and the PCRE2 wrapper | -All three library translation units use the private `_sx` layout directly; -only `sx.h` and `sx_core.h` are consumed by client code. +All three library TUs use the private `_sx` layout directly; client code +consumes only `sx.h` and `sx_core.h`. ### Why sx_split lives in the advanced layer -`sx_split` is declared in `sx.h`, after the include of `sx_core.h`, and is -implemented in `src/sx_adv.c`. That placement is intentional: - -- It returns a `malloc`'ed array of views with the iterator convention used - by `sx_reg_match_all` and `sx_reg_split`: tokens in order, then an end - guard whose `.ref == NULL`, and the caller frees the array with `free()`. - Grouping the array-returning view APIs keeps that ownership convention in - one place instead of adding an array-allocating API to the core. -- `sx_split`'s scan is self-contained. The core's search primitive is a - `static` KMP implementation inside `sx_core.c`; the advanced layer cannot - call it and does not need to, because a split scan is bounded by the - output size anyway. The source comment states the trade directly: the +`sx_split` is declared in `sx.h` after `sx_core.h` and implemented in +`src/sx_adv.c`; the placement is intentional: + +- It returns a `malloc`'ed array of views using the same iterator convention + as `sx_reg_match_all`/`sx_reg_split` (tokens in order, `.ref == NULL` end + guard, caller frees). Grouping the array-returning view APIs keeps that + ownership convention in one place instead of adding an array-allocating API + to the core. +- Its scan is self-contained: the core's KMP primitive is `static` in + `sx_core.c` and unavailable to the advanced layer, and a split scan is + bounded by the output size anyway. The source comment states the trade: the `O(n*m)` byte-exact scan "is fine for the advanced layer and keeps this TU independent". -- The split scan is not PCRE2-dependent: it is a plain separator search. - It lives in the advanced TU by API shape, not by dependency. +- It has no PCRE2 dependency: it is a plain separator search that lives in the + advanced TU by API shape, not dependency. ### Why sx_raw.h is internal @@ -105,16 +100,15 @@ void sx__free(_sx *s); It is internal for three reasons: -- it hands out `_sx`, the private buffer struct, which `sx_core.h` only +- it hands out `_sx`, the private buffer struct that `sx_core.h` only forward-declares; -- its functions are named with a reserved double-underscore prefix and - bypass the public error model (`sx__reserve` returns `int`, not a - sentinel `sx_t *`) — they serve the library's own TUs, not clients; +- its functions use a reserved double-underscore prefix and bypass the public + error model (`sx__reserve` returns `int`, not a sentinel `sx_t *`); they + serve the library's TUs, not clients; - it carries no stability promise. The installed header set includes it - because Forge copies every `include/*.h` (the build script syncs the - whole directory), but it is not part of the supported public API and + because the build copies every `include/*.h`, but it is not supported API and must not be used by client code. The four `sx__*` helpers are declared - `SYMBOL_PUBLIC`, so they do appear in the shared library's dynamic symbol + `SYMBOL_PUBLIC`, so they appear in the shared library's dynamic symbol table; that export does not make them supported API. ## Buffer layout and invariants @@ -146,33 +140,31 @@ buffer: a b c d e f \0 view covers c d e The invariants that every function preserves: 1. `ptr != NULL` and `cap >= 1` for every live buffer. -2. `len + 1 <= cap`: there is always room for the terminator. -3. `ptr[len] == '\0'` at all times. Content bytes may themselves be - `'\0'`; the terminator is the first NUL *after* the content. -4. `len` counts content bytes, not the terminator. `sx_len` returns it as +2. `len + 1 <= cap`: room for the terminator. +3. `ptr[len] == '\0'` always. Content may contain `'\0'`; the terminator is + the first NUL *after* the content. +4. `len` counts content bytes, not the terminator; `sx_len` returns it as `int` (see [integer accessors](#integer-accessors-and-size_max)). 5. A returned view satisfies `ref = buffer.ref` and - `offset + len <= buffer len`. The API does not validate caller-built - views; a view whose bounds exceed its buffer is out of contract. -6. The `sx_t *` handle address is stable for the buffer's life. `ptr` - returned by `sx_buf_mut` is **not** stable across growth: `realloc` can - move it. -7. Bytes in `[len, cap)` are unspecified: they may hold stale content or - never-initialized memory. Only `ptr[len]` is part of the contract. + `offset + len <= buffer len`. Caller-built views are not validated; one + exceeding its buffer is out of contract. +6. The `sx_t *` handle address is stable for the buffer's life; `ptr` from + `sx_buf_mut` is **not** stable across growth because `realloc` can move it. +7. Bytes in `[len, cap)` are unspecified (stale or uninitialized); only + `ptr[len]` is contractual. The invariants are enforced structurally: every mutating function ends with -`ptr[len] = '\0'`, and `sx__reserve` is the only place that changes `cap` -or `ptr`. `sx_buf_mut` lets a caller rewrite `[0, len)` without changing -`len`; the invariant still holds because the terminator is outside that -range. +`ptr[len] = '\0'`, and `sx__reserve` is the only place that changes `cap` or +`ptr`. `sx_buf_mut` may rewrite `[0, len)` without changing `len`; the +terminator lies outside that range, so the invariant holds. ## Allocation and growth ### Initial capacities -Every buffer is one allocation from `sx__new(cap)`, which allocates the -`_sx` header and a `cap`-byte array (rounded up to 1 so `ptr[0]` has a -home). The constructors choose `cap` as follows: +Every buffer is one allocation from `sx__new(cap)`: the `_sx` header plus a +`cap`-byte array (minimum 1, so `ptr[0]` has a home). Constructor +capacities: | Constructor | Initial `cap` | Maximum content bytes | | --- | --- | --- | @@ -183,17 +175,15 @@ home). The constructors choose `cap` as follows: | `sx_dup(src)` | `src->len + 1` | `src->len` | | `sx_substr(h, idx, n)` | `n + 1` | `n` | -`sx_new()` goes through `sx_new_with_cap(32)`; the 32-byte start keeps the -first few appends allocation-free without wasting much memory. The -construction-from-content constructors allocate exactly `content + 1`, so -a freshly built or copied buffer is tight. +`sx_new()` goes through `sx_new_with_cap(32)`: the 32-byte start covers the +first few appends without wasting much memory. Content constructors allocate +exactly `content + 1`, so a fresh or copied buffer is tight. ### Growth policy -All growth goes through `sx__reserve(_sx *s, size_t need)`, which treats -`need` as the number of **content bytes** the caller must be able to hold -afterwards. Internally it must produce `cap > need`, i.e. room for `need` -bytes plus the terminator. The decision: +All growth goes through `sx__reserve(_sx *s, size_t need)`, where `need` is +the number of **content bytes** required afterwards. It must produce +`cap > need` — room for `need` bytes plus the terminator: | Situation | New `cap` | | --- | --- | @@ -203,91 +193,85 @@ bytes plus the terminator. The decision: | default, `cap >= 0x10000` | `max(cap + 0x10000, need + 1)` | | `-DSX_FORCE_EXACT_RESERVE` | `need + 1` | -The default policy is geometric doubling while the allocation is below -64 KiB, then a fixed `+0x10000` step. Doubling gives amortized constant -cost per appended byte; the fixed step avoids doubling a large allocation -(say 8 MiB to 16 MiB) just to append a few bytes. The `max` with -`need + 1` covers the case where a single call needs more than the next -geometric step would provide. +Default growth doubles while the allocation is below 64 KiB, then adds a +fixed `+0x10000`. Doubling gives amortized constant cost per byte; the fixed +step avoids doubling a large allocation (say 8 MiB to 16 MiB) just to append a +few bytes. The `max` with `need + 1` covers a single call needing more than the +next geometric step. -The public `sx_reserve(self, n)` forwards `n` unchanged, so it guarantees -`cap >= n + 1`: after the call the buffer can hold `n` content bytes in -total without another reallocation. `sx_append`, `sx_write` and `sx_insert` call +The public `sx_reserve(self, n)` forwards `n` unchanged, guaranteeing +`cap >= n + 1`: after the call the buffer holds `n` content bytes total +without another reallocation. `sx_append`, `sx_write` and `sx_insert` call `sx__reserve(final_content_length)` before copying: - append: `need = len + appended`; - write: `need = idx + written`; `len` afterwards is `max(len, idx + n)`; - insert: `need = len + inserted`; the tail is shifted with `memmove`. -Growth is monotonic. Shrinking operations never reallocate: -`sx_truncate` only reserves when the new length is larger, `sx_erase` -moves bytes inside the existing allocation, and `sx_clear` only rewrites +Growth is monotonic; shrinking never reallocates: `sx_truncate` reserves only +when growing, `sx_erase` moves bytes in place, and `sx_clear` rewrites `ptr[0]`. The exact-reserve test asserts both properties (`tests/reserve_stress.c`). ### SX_FORCE_EXACT_RESERVE -`-DSX_FORCE_EXACT_RESERVE` replaces the policy with `cap = need + 1` for -every growth. The allocation then ends exactly at the terminator, so any -access past `len` lands in the AddressSanitizer redzone immediately -instead of hiding behind slack capacity. The costs are a reallocation per -growth (a per-byte append workload becomes quadratic-ish in copies) and no -slack, so it is a debugging/testing mode, not a production mode. -`tests/reserve_stress.c` is the dedicated configuration: it starts every -buffer at `cap == 1`, drives 1500 pseudo-random edits from a fixed LCG -against a byte-exact model, and asserts `cap == len + 1` after every -reallocation plus "shrinking never reallocates". +`-DSX_FORCE_EXACT_RESERVE` replaces the policy with `cap = need + 1` on +every growth. The allocation ends exactly at the terminator, so an access past +`len` lands in the AddressSanitizer redzone instead of hiding behind slack +capacity. The cost is a reallocation per growth (per-byte appends become +quadratic-ish in copies) and no slack, so it is a debugging/testing mode. +`tests/reserve_stress.c` is its dedicated configuration: every buffer starts at +`cap == 1`; a fixed LCG drives 1500 pseudo-random edits against a byte-exact +model; it asserts `cap == len + 1` after every reallocation and that shrinking +never reallocates. ## Views and aliasing -Views are the library's core abstraction: `sx_view_t` stores a buffer -reference plus an `(offset, len)` window. Returning a view never copies, -never allocates and never modifies the buffer. The same representation is -used for whole-buffer views (`sx_view`), navigation (`sx_view_advance`, -`sx_view_range`, ...), split tokens and regex match arrays. +Views are the core abstraction: `sx_view_t` stores a buffer reference plus an +`(offset, len)` window. Returning a view never copies, allocates or modifies +the buffer. The same representation serves whole-buffer views (`sx_view`), +navigation (`sx_view_advance`, `sx_view_range`, ...), split tokens and regex +match arrays. The rules a caller must respect: -- **Views are snapshots.** An edit does not adjust captured views. If the - length changes, offsets and lengths captured earlier may no longer - describe the same bytes; re-derive the view afterwards. -- **Growth invalidates raw pointers.** `sx_buf_mut` and `sx_buf_view_mut` - borrow the array; a later edit that grows the buffer may `realloc` it. - The `sx_t *` handle is stable, the pointer is not. -- **A view must not outlive its buffer.** The `ref` is a raw `_sx *`; - freeing the buffer frees the referent. Returning an array of views does - not transfer ownership of the underlying buffer. -- **Do not edit while views are in use.** This is the same rule for - `sx_split` tokens, `sx_reg_match_all` arrays and user-held views. -- **A `NULL` view means "none".** `{ref = NULL, offset = 0, len = 0}` is - the sentinel; library-returned views otherwise point into a live buffer. - -Aliasing edits are the delicate part. When the source view refers to the -same buffer as the destination, `sx_append_view`, `sx_write_view` and -`sx_insert_view` copy with `memmove` instead of `memcpy`. For append and -write the copy is a plain overlap-safe move, so any contract-valid source -view works. `sx_insert_view` is narrower, and its order of operations is -why: - -1. reserve space for the **final** content length (this is what keeps the - source pointer valid: `realloc` updates `_sx.ptr` in place, so a pointer - taken afterwards sees the new allocation); +- **Views are snapshots.** Edits do not adjust captured views; after a length + change, re-derive them. +- **Growth invalidates raw pointers.** `sx_buf_mut`/`sx_buf_view_mut` borrow + the array, and a later growing edit may `realloc` it. The `sx_t *` handle is + stable, the pointer is not. +- **A view must not outlive its buffer.** `ref` is a raw `_sx *`; freeing the + buffer frees the referent. Returning a view array does not transfer ownership + of the buffer. +- **Do not edit while views are in use** — for `sx_split` tokens, + `sx_reg_match_all` arrays and user-held views alike. +- **A `NULL` view means "none".** `{ref = NULL, offset = 0, len = 0}` is the + sentinel; other library-returned views point into a live buffer. + +Aliasing edits need care. When the source view refers to the same buffer as +the destination, `sx_append_view`, `sx_write_view` and `sx_insert_view` copy +with `memmove` rather than `memcpy`. Append and write are plain overlap-safe +moves, so any contract-valid source view works. `sx_insert_view` is +narrower: + +1. reserve space for the **final** content length (keeps the source pointer + valid: `realloc` updates `_sx.ptr` in place, so a pointer taken afterwards + sees the new allocation); 2. shift the tail right by `v.len`, writing `[idx + n, len + n)`; 3. write the inserted bytes at `idx` with `memmove`. -The tail shift makes self-aliasing conditional: a source window that starts -at or before the insertion point (`v.offset <= idx`) ends at or before -`idx + n`, so the shift never overwrites it and the `memmove` at step 3 -handles the remaining overlap. The exercised case is `v.offset == idx`: -inserting the view `[2, 4)` (`"cd"`) into `"abcdef"` at index 2 gives -`"abcdcdef"`. A self-aliased window that starts **after** `idx` is -overwritten by the shift before it is read: inserting the view `[3, 5)` -(`"de"`) into `"abcdef"` at index 2 yields `"abdccdef"`, not -`"abdecdef"`; such a call is out of contract. The regression at the end of -`tests/reserve_stress.c` exercises the `v.offset == idx` case with growth -forced, which pins the reserve-before-pointer ordering. The owned variants -(`sx_append(self, self)` and friends) do not have this protection — they -free their argument and are out of contract for self-aliasing. +The tail shift makes self-aliasing conditional: a source window starting at +or before the insertion point (`v.offset <= idx`) ends at or before `idx + n`, +so the shift cannot overwrite it and step 3's `memmove` handles the remaining +overlap. The exercised case is `v.offset == idx`: inserting view `[2, 4)` +(`"cd"`) into `"abcdef"` at index 2 gives `"abcdcdef"`. A window starting +**after** `idx` is overwritten before it is read: inserting `[3, 5)` (`"de"`) +into `"abcdef"` at index 2 yields `"abdccdef"`, not `"abdecdef"`; that call is +out of contract. The regression at the end of `tests/reserve_stress.c` covers +the `v.offset == idx` case with forced growth, pinning the +reserve-before-pointer ordering. The owned variants (`sx_append(self, self)` +and friends) free their argument, so self-aliasing is out of contract for +them. ## Ownership and error model @@ -304,19 +288,24 @@ pointer releases it. Details that matter: - **Consuming calls consume on failure too.** `sx_append`/`sx_write`/ - `sx_insert` attempt the edit, then free `owned` unconditionally. If the - edit itself fails (allocation failure), the call returns `NULL` and the - argument has still been consumed. A `NULL` argument returns `NULL` - without freeing anything. + `sx_insert` attempt the edit, then free `owned` unconditionally; if the edit + fails, the call returns `NULL` but the argument is still consumed. A `NULL` + argument returns `NULL` and frees nothing. +- **Write-range rejection is documented.** If `idx + n` overflows `size_t`, + or the resulting end cannot be reserved (`SIZE_MAX` content cannot include + a terminator), `sx_write*` returns `NULL` before copying and leaves `self` + unchanged. `sx_write_view` checks before its alias-preserving pre-reserve, + so a rejected range cannot change capacity. `tests/write_overflow.c` and + its exact-reserve sibling pin this contract. - **Handle identity.** Every edit returns `self`, so successful edits chain: `sx_append_cstr(sx_append_cstr(s, "a"), "b") == s`. The handle is stable - across growth; only the backing array moves. -- **Arrays do not own their elements' buffer.** Freeing the array returned - by `sx_split` or `sx_reg_match_all` is not freeing the subject; the - views simply become unreachable. + across growth; only the array moves. +- **Arrays do not own their elements' buffer.** Freeing a `sx_split` or + `sx_reg_match_all` array does not free the subject; the views merely become + unreachable. -The error model is sentinel-based, with no `errno`, no error object and no -error return code: +The error model is sentinel-based: no `errno`, error object or error return +code. | Situation | Sentinel | | --- | --- | @@ -325,28 +314,26 @@ error return code: | "no match" view (`sx_reg_match`) | `{ref = NULL, offset = 0, len = 0}` | | "no match" array (`sx_reg_match_all`) | `NULL` | | invalid/empty separator, invalid regex, OOM in an array/string factory | `NULL` | +| write range overflow or unreservable end | `NULL`; `self` unchanged (owned input consumed) | | boolean predicates and `sx_reg_is_match` | `0` | Two consequences are intentional and documented: - **"No result" and "out of memory" can be indistinguishable.** The - `find_all` family and the `sx_reg_*` array family return `NULL` for both, - because the contract gives them no third channel. The regex replace family - does distinguish them: "no match" returns an unchanged copy, `NULL` means - invalid input or failure. -- **NULL handle arguments are mostly out of contract.** Only the families - that explicitly check — `sx_new_from_cstr`, `sx_dup`, the cstr/owned - mutation arguments, `sx_find*`, `sx_rfind*`, `sx_find_all*`, the - `sx_cmp*`/`sx_starts_with*`/`sx_ends_with*` group, `sx_split` and the - `sx_reg_*` calls — have defined `NULL` behavior. Accessors - (`sx_len`, `sx_cap`, `sx_buf_mut`, `sx_view`, ...), view movers and - `sx_free` dereference their handle and do not accept `NULL`. The public - headers state the boundaries per function. - -Errors never leave a partially built buffer behind: a failed growth happens -before any byte is copied, so `self` keeps its previous content and the -single-NUL invariant. The one visible exception is the consumed `owned` -argument described above. + `find_all` and `sx_reg_*` array families return `NULL` for both, having no + third channel. Replace distinguishes them: no match returns an unchanged + copy; `NULL` means invalid input or failure. +- **NULL handle arguments are mostly out of contract.** The explicitly + checking families — `sx_new_from_cstr`, `sx_dup`, cstr/owned mutation + arguments, `sx_find*`, `sx_rfind*`, `sx_find_all*`, + `sx_cmp*`/`sx_starts_with*`/`sx_ends_with*`, `sx_split` and `sx_reg_*` — + have defined `NULL` behavior. Accessors (`sx_len`, `sx_cap`, `sx_buf_mut`, + `sx_view`, ...), view movers and `sx_free` dereference their handle and + reject `NULL`; headers state the boundaries per function. + +Errors never leave a partially built buffer: a failed growth happens before +any copy, so `self` keeps its content and the single-NUL invariant. The one +exception is the consumed `owned` argument. ## Search internals @@ -359,7 +346,7 @@ static inline find_ret_t find(const sx_t *h, const char *needle, int len, ``` The return type is a position or a pointer to a result array, so the -implementation picks an integer type wide enough to round-trip a pointer: +implementation uses an integer type wide enough to round-trip a pointer: ```c #if SIZE_MAX > UINTPTR_MAX @@ -387,57 +374,73 @@ a match window [p, p+m) counts only if p >= region_start and p+m <= region_end ``` The wrappers plug in the documented boundaries: `sx_find*` use -`boundary = 0`; `sx_rfind*` use `boundary = len(h)` with the right flag; -`sx_find_view_b` and `sx_rfind_view_b` pass the caller's boundary. -`len <= 0`, an empty region, or a region shorter than the needle is -reported as "not found" in the shape the mode requires — `(size_t)-1` for -the scalar wrappers, a count-0 array internally (converted to `NULL` by -`sx_find_all*`) for the array wrappers. - -`len` is the needle's content length (`sx_t` needle), `v.len` (view -needle), or `(int)strlen(s)` (cstr needle — note the narrowing cast, which -is one of the practical `int` limits). The needle bytes are read directly -from the view or buffer; the search is byte-exact, like `memcmp`. +`boundary = 0`, `sx_rfind*` use `boundary = len(h)` with the right flag, and +`sx_find_view_b`/`sx_rfind_view_b` pass the caller's boundary. `len <= 0`, an +empty region or a region shorter than the needle is "not found" — +`(size_t)-1` for scalar wrappers, a count-0 array internally (converted to +`NULL` by `sx_find_all*`) for array wrappers. + +`len` is the needle content length (`sx_t` needle), `v.len` (view needle) or +`(int)strlen(s)` (cstr needle — the narrowing cast is one practical `int` +limit). Needle bytes are read directly from the view or buffer; search is +byte-exact like `memcmp`. ### One-byte needles: memchr and memrchr For `m == 1` the primitive uses the C library's vectorized scans: - **leftmost:** `memchr(t + l, c, er - l)`; -- **rightmost:** `memrchr(t, c, er)` on glibc. `memrchr` is a GNU - extension, not ISO C, so it is declared by hand in `sx_core.c` and used - only when `__GLIBC__` is defined and `SX_FORCE_NO_MEMRCHR` is not. The - fallback is a byte-wise backward loop that keeps the last (rightmost) - hit before reaching `l`. - -The rightmost fast path is allowed to search from `0` because a right -search always sets `l = 0`; `er` already carries the caller's boundary. -`SX_FORCE_NO_MEMRCHR` exists to build and test the portable path on glibc -systems. - -For `m == 1` in "all" mode, the implementation repeatedly calls `memchr` +- **rightmost:** `memrchr(t, c, er)` on glibc. `memrchr` is a GNU extension, + not ISO C, so `sx_core.c` declares it by hand and uses it only when + `__GLIBC__` is defined and `SX_FORCE_NO_MEMRCHR` is not. The fallback is a + byte-wise backward loop keeping the last (rightmost) hit before `l`. + +The rightmost fast path may search from `0` because a right search always +sets `l = 0`; `er` already carries the boundary. `SX_FORCE_NO_MEMRCHR` exists +to build and test the portable path on glibc. + +For `m == 1` in "all" mode the implementation calls `memchr` repeatedly, starting at the previous hit + 1. That reports **overlapping** positions, -which is exactly what `sx_find_all*` promises (`"aa"` in `"aaaa"` reports -0, 1 and 2). +which is exactly what `sx_find_all*` promises (`"aa"` in `"aaaa"` reports 0, 1 +and 2). + +### Native forward fast path + +Leftmost first-match calls (`sx_find`, `sx_find_view`, `sx_find_view_b`, +`sx_find_cstr`) go through `find_first()`; on glibc it may take a native path +before the portable KMP implementation. `try_native_find_first` is +`noinline`, so its branches do not alter the fallback's optimization: + +1. reject an empty/negative needle or a region too short for one window; +2. `m == 1`: one `memchr`; +3. compare the window at the region start (front hits need no preprocessing); +4. `memchr` for the needle's first byte from the next offset, then `memchr` + for its last byte, narrowing the candidate start to where a window can end; +5. for `m <= 32`, `memmem` over the remaining region; otherwise decline. + +A decline falls back to KMP. The native path allocates nothing; only the +fallback's prefix table does. It is compiled out on non-glibc targets and with +`-DSX_FORCE_NO_MEMMEM`; `tests/find_differential_fallback.c` runs the same +differential cases through the forced-portable build. ### Longer needles: KMP -For `m >= 2` the primitive computes a KMP prefix table (`pi`, one +For `m >= 2` the fallback (and the primitive used by `sx_rfind*` and +`sx_find_all*`) computes a KMP prefix table (`pi`, one `malloc(m * sizeof(size_t))`) and scans the region in `O(n + m)` time: -- **leftmost-first and all mode** use forward KMP over - `[l, er)`. On a full match the first mode returns immediately; the all - mode records the start offset and resumes with `q = pi[m - 1]`, which is - what makes it report overlapping occurrences. -- **rightmost-first** uses reverse KMP: the same prefix table computed over - the *reversed* needle by index mapping (no copy of the needle), scanning - the text from `er - 1` down to `l`. When the matched suffix length - reaches `m`, the current text index is the window start. +- **leftmost-first and all mode** use forward KMP over `[l, er)`. On a full + match, first mode returns; all mode records the start and resumes with + `q = pi[m - 1]`, which reports overlapping occurrences. +- **rightmost-first** uses reverse KMP: the same prefix table over the + *reversed* needle by index mapping (no copy), scanning from `er - 1` down to + `l`. When the matched suffix reaches `m`, the current index is the window + start. -The all-mode result array starts at capacity 16 and doubles with an -overflow guard (`cap > SIZE_MAX / 2 / sizeof(*r)` aborts with `NULL`), then -shrinks once with `realloc` before returning. Its layout is -`{count, pos0, pos1, ...}`: `arr[0]` is the count, not a position. +The all-mode array starts at capacity 16, doubles with an overflow guard +(`cap > SIZE_MAX / 2 / sizeof(*r)` aborts with `NULL`), then shrinks once with +`realloc`. Layout: `{count, pos0, pos1, ...}` — `arr[0]` is the count, not a +position. ### Complexity @@ -445,15 +448,17 @@ shrinks once with `realloc` before returning. Its layout is | --- | --- | --- | --- | | one-byte needle, first left | `memchr` | `O(n)` | none | | one-byte needle, first right | `memrchr`, or backward scan | `O(n)` | none | -| needle length >= 2, first | KMP | `O(n + m)` | `O(m)` prefix table | +| needle length >= 2, first left (native) | byte checks + `memmem` (`m <= 32`) | `O(n + m)` typical | none | +| needle length >= 2, first left (fallback) | KMP | `O(n + m)` | `O(m)` prefix table | +| needle length >= 2, first right | reverse KMP | `O(n + m)` | `O(m)` prefix table | | `sx_find_all*`, one byte | repeated `memchr` | `O(n)` scan | `O(k)` result | | `sx_find_all*`, longer needle | KMP | `O(n + m)` scan | `O(m) + O(k)` result | | `sx_split` | two passes of `is_sep` | `O(H * m)` worst case | `O(tokens)` result | -`n` is the region length, `m` the needle length and `k` the number of -matches. The array wrappers allocate the result only; `sx_find*` / -`sx_rfind*` return a scalar and allocate nothing (except the KMP table, -which is freed before returning). +`n` is the region length, `m` the needle length, `k` the number of matches. +Array wrappers allocate only the result. `sx_find*` allocate nothing on the +native path; the KMP fallback (and every multi-byte `sx_rfind*`) allocates a +temporary prefix table, freed before returning. ## Regex wrapper internals @@ -468,29 +473,26 @@ typedef struct sx_reg_t { ### Compile and release -`sx_reg_compile` calls PCRE2 with fixed arguments: +`sx_reg_compile` calls `pcre2_compile(pattern, PCRE2_ZERO_TERMINATED, 0, ...)`. The `0` is the -option word — no `CASELESS`, no `UTF`, nothing — and -`PCRE2_ZERO_TERMINATED` means the pattern is a C string. The PCRE2 error -code and error offset are captured only to satisfy the signature and are -discarded, which is why every compile failure collapses to `NULL`. -Compilation allocates the PCRE2 code object and the small `sx_reg_t` -wrapper; `sx_reg_free` frees both and accepts `NULL`. +option word (no `CASELESS`, no `UTF`, nothing) and `PCRE2_ZERO_TERMINATED` +means a C-string pattern. The PCRE2 error code and offset are captured only +for the signature and discarded, so every compile failure collapses to +`NULL`. Compilation allocates the code object and the small `sx_reg_t`; +`sx_reg_free` frees both and accepts `NULL`. ### Per-call match data and the scan rule PCRE2 separates the compiled pattern from per-call match data. The wrapper -creates match data per call with -`pcre2_match_data_create_from_pattern(r->code, NULL)` and frees it before -returning. That is what makes a compiled handle thread-shareable: no match -state lives in the handle. - -A single match step is `pcre2_match(code, subject, len, offset, 0, md, -NULL)`. Note the subject is passed with an explicit **length**, not as a C -string, and the last argument (match context) is `NULL`, so PCRE2's default -match limits apply. A negative return (no match, or a PCRE2 match-time -error such as a match limit) is treated as "no further match"; the wrapper -does not expose match-time error codes. +creates match data with `pcre2_match_data_create_from_pattern(r->code, NULL)` +and frees it before returning, so no match state lives in the handle — hence a +compiled handle is thread-shareable. + +A match step is `pcre2_match(code, subject, len, offset, 0, md, NULL)`: the +subject is passed with an explicit **length**, not as a C string, and the +`NULL` match context means PCRE2's default match limits apply. A negative +return (no match or a match-time error such as a match limit) means "no further +match"; match-time error codes are not exposed. The scan shared by `sx_reg_match_all` and `sx_reg_split` advances with: @@ -501,11 +503,10 @@ static size_t reg_next_at(size_t start, size_t end) { ``` The next search starts at the match end, or one byte past the start for a -zero-length match, so the scan is guaranteed to advance. `pcre2_match` is -called with `offset` on every step; when `offset` passes the subject length -PCRE2 returns an error and the loop ends. This is why `a*` on `"bbb"` -reports empty matches at offsets 0, 1, 2 and 3, and why `$` on `"abc"` -reports a single empty match at offset 3. +zero-length match, so the scan always advances. `pcre2_match` gets `offset` on +every step; once it passes the subject length PCRE2 errors and the loop ends. +Hence `a*` on `"bbb"` reports empty matches at offsets 0–3, and `$` on `"abc"` +one empty match at offset 3. ### Two-pass sizing for match_all and split @@ -517,12 +518,11 @@ malloc((cnt + 1) * sizeof view) -> exact size, no realloc pass 2: repeat the same scan -> fill views, then arr[cnt] = {0} guard ``` -The scan is deterministic (same pattern, same subject, same start offsets), -so both passes observe identical positions. `sx_reg_split` additionally -tracks the gap start `seg`: each token is `[seg, match_start)` and `seg` -moves to `match_end`; the final token is `[seg, len)`. This gives exactly -`matches + 1` tokens, including the empty edge tokens and the empty tokens -produced by adjacent or zero-length matches. +The scan is deterministic (same pattern, subject and start offsets), so both +passes see identical positions. `sx_reg_split` also tracks the gap start +`seg`: each token is `[seg, match_start)` and `seg` moves to `match_end`; the +final token is `[seg, len)`. That gives exactly `matches + 1` tokens, including +empty edge tokens and empty tokens from adjacent or zero-length matches. ### Substitution: two pcre2_substitute calls @@ -532,13 +532,13 @@ Replace is built from PCRE2's substitution routine, with two fixed flags: options |= PCRE2_SUBSTITUTE_UNSET_EMPTY | PCRE2_SUBSTITUTE_UNKNOWN_UNSET; ``` -`UNSET_EMPTY` makes a group that did not participate expand to nothing; -`UNKNOWN_UNSET` makes a group number that does not exist expand to nothing -instead of failing the whole substitution. `sx_reg_replace` adds -`PCRE2_SUBSTITUTE_GLOBAL`; `sx_reg_replace_first` does not. +`UNSET_EMPTY` expands a group that did not participate to nothing; +`UNKNOWN_UNSET` expands a non-existent group number to nothing instead of +failing. `sx_reg_replace` adds `PCRE2_SUBSTITUTE_GLOBAL`; +`sx_reg_replace_first` does not. -Because the output length is not known before substituting, the wrapper -calls `pcre2_substitute` twice: +Because output length is unknown beforehand, the wrapper substitutes +twice: ```text call 1: output buffer NULL, PCRE2_SUBSTITUTE_OVERFLOW_LENGTH, &needed @@ -550,11 +550,11 @@ sx_new_with_cap(used + 1) (new public buffer) memcpy(ptr, buf, used); len = used; ptr[used] = '\0' ``` -The temporary buffer is freed after the copy. A first call that does not -return `PCRE2_ERROR_NOMEMORY` means the template/replacement pair was -rejected; the wrapper returns `NULL` and never touches the subject. With no -match, PCRE2 substitutes nothing and the output is an unchanged copy of the -subject — a normal success, not an error. +The temporary buffer is freed after the copy. A first call not returning +`PCRE2_ERROR_NOMEMORY` means the template/replacement pair was rejected: the +wrapper returns `NULL` without touching the subject. With no match, PCRE2 +substitutes nothing and the output is an unchanged copy — normal success, not +an error. ### Allocation summary @@ -568,41 +568,36 @@ subject — a normal success, not an error. | `sx_reg_split` | match data + exact `(matches + 2)` array | two scan passes | | `sx_reg_replace*` | PCRE2-internal match data + temporary buffer + `sx_t` | two substitute calls | -The wrapper does not enable PCRE2 JIT (`pcre2_jit_compile` is never called) -and exposes no compile or match options. Pattern-level features such as -inline options still work because they are part of the pattern, not the -wrapper's policy. +The wrapper enables no PCRE2 JIT (`pcre2_jit_compile` is never called) and +exposes no compile or match options; pattern-level features such as inline +options still work because they belong to the pattern, not the wrapper's +policy. ## Concurrency -- **Compiled regex handles are immutable and shareable.** All per-call - state lives in caller-owned match data created inside the call; the - wrapper has no global variables. One `sx_reg_t *` may serve concurrent - calls from several threads. -- **Buffers are not synchronized.** They are ordinary heap memory. Two - threads reading the same buffer concurrently are fine as long as nobody - mutates it; a mutation needs external synchronization. Views make this - stricter: a view read concurrently with a length-changing edit is a data - race (out of contract). -- **Ownership must be coordinated.** A buffer with a single owner must not - be consumed by two threads; arrays are single-owner results. - -The library itself never mutates global state, so it is safe to use from -multi-threaded programs as long as each buffer's access is synchronized by -the caller. +- **Compiled regex handles are immutable and shareable.** Per-call state + lives in caller-owned match data created inside the call, and the wrapper has + no globals; one `sx_reg_t *` may serve concurrent threads. +- **Buffers are not synchronized.** They are ordinary heap memory: concurrent + reads are fine while nobody mutates; mutation needs external synchronization. + Views make this stricter — a view read concurrent with a length-changing edit + is a data race (out of contract). +- **Ownership must be coordinated.** A single-owner buffer must not be consumed + by two threads; arrays are single-owner results. + +The library never mutates global state, so it is safe in multithreaded +programs provided the caller synchronizes each buffer's access. ## Portability and limits -### memrchr and SX_FORCE_NO_MEMRCHR +### memrchr, memmem and the portable switches -The only non-ISO C API in the search path is `memrchr`, a glibc extension. -`sx_core.c` declares it manually rather than relying on a feature-test -macro, and compiles it in only when `__GLIBC__` is defined and the build -does not define `SX_FORCE_NO_MEMRCHR`. On other platforms (and with the -forced switch) the rightmost one-byte search falls back to a portable -single-byte backward loop. The in-tree test suite runs the default glibc -path; the switch exists so the fallback can be built and checked on glibc -as well. +The search path uses two glibc extensions: `memrchr` (rightmost one-byte scan) +and `memmem` (native forward fast path). `sx_core.c` declares both by hand and +compiles them in only when `__GLIBC__` is defined. `-DSX_FORCE_NO_MEMRCHR` and +`-DSX_FORCE_NO_MEMMEM` force the portable paths; the in-tree suite runs the +glibc path plus a forced-portable differential search test, so both fallbacks +are built and checked on glibc too. ### Integer accessors and SIZE_MAX @@ -614,36 +609,31 @@ The public accessors return `int` while offsets and needles use `size_t`: | `sx_cap` | `int` (total allocation) | | offsets (`sx_find*`, view fields, regex views) | `size_t` | -A buffer with more than `INT_MAX` content bytes is outside the tested -contract. This is a deliberate API simplification (the intended use case is -small-to-medium strings), not a bug; the practical ceiling is about 2 GiB -per buffer on common platforms. The same `int` narrowing appears where a -`strlen`-based needle length is cast to `int` in the search wrappers. +A buffer over `INT_MAX` content bytes is outside the tested contract. This is +a deliberate simplification for small-to-medium strings, not a bug; the +practical ceiling is ~2 GiB per buffer. The same `int` narrowing appears where +`strlen`-based needle lengths are cast to `int` in search wrappers. `SIZE_MAX` guards appear where a size arithmetic could wrap: -- `sx__reserve` rejects `need == SIZE_MAX` (it would not be able to add - the terminator); -- the `sx_find_all*` array growth checks `cap > SIZE_MAX / 2 / sizeof(*r)` - before doubling; -- there is no general overflow checking: extreme `n` or `off` arguments can - wrap unsigned size arithmetic, and such calls are outside the tested - contract. +- `sx__reserve` rejects `need == SIZE_MAX` (it could not add the terminator); +- `sx_find_all*` growth checks `cap > SIZE_MAX / 2 / sizeof(*r)` before + doubling; +- there is no general overflow checking: extreme `n` or `off` can wrap unsigned + arithmetic, which is outside the tested contract. ### Platform assumptions -- The library is C23. The reference toolchains are GCC 14+ and Clang 19+ - on Linux (CI uses Ubuntu 24.04 with GCC 14 and Clang 19); the sources - avoid compiler-specific extensions apart from `SYMBOL_PUBLIC` and the - glibc `memrchr` fast path. -- `src/export.h` is a checked-in, Forge-derived header. It defines - `SYMBOL_PUBLIC` as `__attribute__((visibility("default")))` for - GCC/Clang and as `_declspec(dllexport)` for MSVC; the build uses hidden - default visibility, so exactly the `SYMBOL_PUBLIC` functions are exported - from `libstringx.so`. -- The regex layer needs PCRE2 10.46 (`pcre2-8`), 8-bit, non-UTF mode. The - build links it into `libstringx`, so consumers do not add PCRE2 flags, - but PCRE2 is a runtime dependency of the shared library. +- The library is C23, with GCC 14+ and Clang 19+ on Linux as reference + toolchains (CI: Ubuntu 24.04, GCC 14, Clang 19). Sources avoid + compiler-specific extensions apart from `SYMBOL_PUBLIC` and glibc `memrchr`. +- `src/export.h` is a checked-in, Forge-derived header defining + `SYMBOL_PUBLIC` as `__attribute__((visibility("default")))` for GCC/Clang and + `_declspec(dllexport)` for MSVC. The build uses hidden default visibility, so + exactly the `SYMBOL_PUBLIC` functions are exported from `libstringx.so`. +- The regex layer needs PCRE2 10.46 (`pcre2-8`, 8-bit, non-UTF). The build + links it into `libstringx`, so consumers add no PCRE2 flags, but it remains a + runtime dependency. - Install and Debian packaging targets are guarded by the `LINUX` macro in `build.c`; the library itself compiles as ordinary C23. @@ -651,13 +641,12 @@ per buffer on common platforms. The same `int` narrowing appears where a Every file in `tests/` is a self-contained program. Its header comments declare how to build it (`// Include`, `// Source`, `// Option`, `// Link`, -`// Library` lines consumed by the pinned Forge build system), and document -its **behavior boundaries**: an "In scope (contract)" list and an -"Out of contract (not exercised)" list. The header is part of the -contract: when behavior changes, the boundary lists change with it (see -[Contributing](contributing.md)). +`// Library` lines consumed by the build system) and document its +**behavior boundaries**: an "In scope (contract)" list and an "Out of contract +(not exercised)" list. The header is part of the contract — behavior changes +must update the boundary lists (see [Contributing](contributing.md)). -The suite (20 tests) maps one topic per file: +The suite (24 tests) maps one topic per file: | Test | Pins | | --- | --- | @@ -668,6 +657,8 @@ The suite (20 tests) maps one topic per file: | `ends_with.c` | suffix predicate | | `find.c` | leftmost search, bounded regions, `strlen` needles | | `find_all.c` | all occurrences, overlapping positions included | +| `find_differential.c` | leftmost search against an independent window oracle (native path) | +| `find_differential_fallback.c` | the same cases with `-DSX_FORCE_NO_MEMMEM` (portable KMP path) | | `insert.c` | insertion, aliasing across growth | | `new.c` | constructors, `sx_dup`, capacity edge cases | | `reg.c` | regex families, binary-safe subjects, zero-length handling | @@ -681,35 +672,43 @@ The suite (20 tests) maps one topic per file: | `view_move.c` | advance / retreat / shift / range clamping | | `view_trim.c` | whitespace trim set and empty-view clamp | | `write.c` | overwrite, append-at-end and padding semantics | +| `write_overflow.c` | `SIZE_MAX` write ranges return `NULL`, leave `self` unchanged, consume owned input | +| `write_overflow_exact.c` | the same cases under `-DSX_FORCE_EXACT_RESERVE` | + +Some tests share a local case header between the normal and forced +configuration (`find_differential.h`, `write_overflow_cases.h`); each `.c` is +still its own target. -How the tests run: +How tests run: -- Each test compiles the library **sources directly**, with the per-test - options from its header. Sanitizers are on: AddressSanitizer, UBSan and - (on Linux, through ASan) LeakSanitizer, so the leak sanitizer is the - witness for every ownership rule. CI sets - `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1` and +- Each test compiles the library **sources directly** with its header + options. Sanitizers are on: AddressSanitizer, UBSan and (on Linux, through + ASan) LeakSanitizer — the leak sanitizer witnesses every ownership rule. CI + sets `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1` and `UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1`. -- `tests/reserve_stress.c` is the only test built with - `-DSX_FORCE_EXACT_RESERVE`. It drives a deterministic LCG through append, - insert, erase, write, truncate and aliased-view edits against a byte-exact - model, and includes the aliased `insert_view` growth regression. -- CI additionally installs the built library into a temporary prefix, - links `tests/reg.c` against the **installed shared library** through - `pkg-config` (with an rpath), and runs it. That verifies the public - headers, exported symbols and the PCRE2 link in addition to source-level - behavior; it then inspects the generated Debian package. -- Fault-injection is absent, so allocation-failure branches are not - exercised by the suite (the reserve test comments note that such a test is - not expressible without fault injection). The documented OOM sentinels - are reasoned from the code, not observed in tests. +- `tests/reserve_stress.c` and `tests/write_overflow_exact.c` are built with + `-DSX_FORCE_EXACT_RESERVE`. The first drives a deterministic LCG through + append, insert, erase, write, truncate and aliased-view edits against a + byte-exact model, including the aliased `insert_view` growth regression; the + second repeats the overflow cases with exact-size allocations. +- Dedicated audit workflows also run: Write safety reproduces the overflow + against the immutable old implementation and compares write cost; Search + performance compares the baseline; benchmarks rerun the audited + StringX/SDS/bstrlib harness (see [ci.md](ci.md)). +- CI also installs the library into a temporary prefix, links `tests/reg.c` + against the **installed shared library** via `pkg-config` (with rpath), runs + it, and inspects the generated Debian package — verifying public headers, + exported symbols and the PCRE2 link. +- Fault injection is absent, so allocation-failure branches are not exercised; + the reserve test notes such a test is not expressible without it. Documented + OOM sentinels are reasoned from code, not observed. - The `./make check` target compiles production code with - `-Wall -Wextra -Wpedantic -Werror`; GCC builds also run `-fanalyzer` - (with `-O1 -fno-analyzer-state-merge` in CI), and CodeQL scans with + `-Wall -Wextra -Wpedantic -Werror`; GCC builds also run `-fanalyzer` (with + `-O1 -fno-analyzer-state-merge` in CI), and CodeQL scans with `security-and-quality` queries. - Tests disable LTO (`set(TARGET_LTO, 1, DISABLE)` in `build.c`) because the - pinned Forge emits GCC-only `-flto=N` flags for parallel Clang links. - Production library targets keep LTO. + pinned build tool emits GCC-only `-flto=N` for parallel Clang links; + production library targets keep LTO. ## Design trade-offs @@ -723,6 +722,8 @@ How the tests run: | `int` length accessors | compact, simple API | ~2 GiB practical buffer ceiling; narrowing casts | | Sentinel error model | no global state, no error plumbing, deterministic | "no result" vs OOM can be ambiguous; no diagnostics | | Caller-frees arrays, library-frees handles | explicit, predictable ownership | two release functions (`free` vs `sx_free`) to know | +| Native first-match fast path | faster common-case search on glibc, allocation-free for `m <= 32` | extra libc-specific code and a forced-portable test | +| Checked write-range arithmetic | arithmetic overflow returns a documented `NULL` instead of corrupting memory | one branch per write; owned input is still consumed | | KMP + `memchr`/`memrchr` | guaranteed `O(n + m)` worst case, simple code, vectorized one-byte case | prefix table allocation for `m >= 2`; average-case speed below optimized substring search | | Overlapping results from `sx_find_all*` | complete position set; useful for byte scanning | callers must expect overlapping offsets | | Non-overlapping regex scan | standard PCRE2 behavior; forward progress guaranteed | cannot report overlapping regex matches | @@ -731,18 +732,17 @@ How the tests run: | Explicit immutability of compiled regex, no internal locks | shareable handles without synchronization | buffers still need caller synchronization | | Build-time configuration macros | zero runtime cost for growth/memrchr policy | a policy change requires a rebuild | -These are trade-offs, not accidents. The tests pin the observable -consequences, and the header comments name the out-of-contract side of each -rule. +These are trade-offs, not accidents: the tests pin the observable +consequences and the header comments name each rule's out-of-contract side. ## Licensing -Project sources are MIT licensed (see [LICENSE](../../LICENSE) and the SPDX -headers in the sources). The Forge-derived build tooling follows the -build-script exception: `build.conf` and `src/export.h` carry the +Project sources are MIT (see [LICENSE](../../LICENSE) and SPDX headers). The +Forge-derived build tooling follows the build-script exception: `build.conf`, +`build.c` and `src/export.h` carry the `GPL-3.0-or-later WITH LicenseRef-Forge-BuildScript-Exception` SPDX -identifier, and `build.c` is covered by the same exception; the library -sources themselves remain MIT. The regex layer uses PCRE2 (BSD-3-Clause); see +identifier; the library sources remain MIT. The regex layer uses PCRE2 +(BSD-3-Clause); see [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md). --- diff --git a/docs/en_us/getting-started.md b/docs/en_us/getting-started.md index 1496df2..7ed87df 100644 --- a/docs/en_us/getting-started.md +++ b/docs/en_us/getting-started.md @@ -4,13 +4,10 @@ English · [中文](../zh_cn/getting-started.md) # Getting started -String X is a small C23 string library that treats one string as a single -NUL-terminated buffer and every slice of it as a zero-copy view. Buffers are -handled by byte length, so embedded NUL bytes are ordinary data and nothing is -lost to C-string truncation. The public surface is one header, ``, and -one library, `libstringx` (`-lstringx`); an optional advanced layer adds -regular expressions through PCRE2. This page takes you from a fresh checkout -to a running program. It describes **v0.5**. +String X is a small C23 string library: one NUL-terminated buffer per string, +zero-copy views as slices, byte-length handling (embedded NULs are ordinary +data). One header ``, one library `libstringx` (`-lstringx`); an optional +PCRE2 layer adds regexes. Version: **v0.5**. ## Requirements @@ -18,23 +15,22 @@ to a running program. It describes **v0.5**. | --- | --- | | Linux | Tested platform; the build and tests target Linux | | C23 compiler | GCC 14+ or Clang 19+; CI runs GCC 14 and Clang 19 on Ubuntu 24.04 | -| `forge` | `https://github.com/minelogy-dev/forge`; compiles `build.c` into a local `./make` executable | +| `forge` | [github.com/minelogy-dev/forge](https://github.com/minelogy-dev/forge) | | `libpcre2-dev` | PCRE2 10.46, 8-bit API; needed to build; the library links `pcre2-8` | | `pkg-config` | Recommended for consumers; the installed package ships `libstringx.pc` | ## Build from source ```sh -forge . # compile build.c into ./make (re-run whenever build.c changes) +forge . # generate ./make ./make # build -> build/output/libstringx.so ./make test # build and run every test under tests/ (ASan + UBSan + LSan) ``` -`./make` also syncs the public headers to `build/output/include`. `./make test` -runs each `tests/*.c` file as a self-contained program under AddressSanitizer, -UBSan and LeakSanitizer; use `./make test -j 2` to run tests in parallel. -`build.conf` selects the compiler and is the single source of truth for the -version. +`./make` syncs the public headers to `build/output/include`; `./make test` runs +every `tests/*.c` as a self-contained program under AddressSanitizer, UBSan and +LeakSanitizer (`-j 2` parallelizes). `build.conf` selects the compiler and is +the single source of truth for the version. ## Install @@ -58,8 +54,8 @@ The install target builds first, then copies the artifacts: cc app.c $(pkg-config --cflags --libs libstringx) -o app ``` -For a prefix that is not in the default search path, point pkg-config at the -installed metadata and, for a non-system prefix, set the runtime library path: +For a non-default prefix, point pkg-config at the installed metadata and set the +runtime library path: ```sh export PKG_CONFIG_PATH="$HOME/.local/lib/pkgconfig" @@ -73,9 +69,8 @@ Without pkg-config, the same build is: cc app.c -I/include -L/lib -lstringx -o app ``` -You link only `-lstringx`: `libstringx` links `pcre2-8` itself, so no extra -library flags are needed. The shared library does need `libpcre2-8` present at -run time. +Link only `-lstringx`: `libstringx` links `pcre2-8` itself, so no extra library +flags are needed; the shared library still needs `libpcre2-8` at run time. ### Debian package @@ -84,29 +79,29 @@ run time. sudo apt install ./build/deb/libstringx_0.5_amd64.deb ``` -`gen_deb` stages `build/deb/libstringx__.deb`; the version comes -from `build.conf` with the leading `v` stripped, and the architecture from -`uname -m` (`x86_64` becomes `amd64`, `aarch64` becomes `arm64`). The package -depends on `libc6` and `libpcre2-8-0`. +`gen_deb` stages `build/deb/libstringx__.deb`: version from +`build.conf` without the leading `v`, architecture from `uname -m` (`x86_64` → +`amd64`, `aarch64` → `arm64`); it depends on `libc6` and `libpcre2-8-0`. ## Hello, String X -This is the quick-start program from the README. It copies a C string into an -owned buffer, finds the first comma, copies the text before it into a second -owned buffer, and prints that. Both buffers are released with `sx_free`. +The README quick start. Every edit returns the same handle, so the whole +chain is one expression; `sx_append` consumes the temporary buffer, and the +result needs one `sx_free`. The handle survives growth, and the buffer is +NUL-terminated after every call. ```c #include #include int main(void) { - sx_t *msg = sx_new_from_cstr("hello, world"); - size_t at = sx_find_cstr(msg, ", "); - sx_t *hi = sx_substr(msg, 0, at); - fwrite(sx_buf_mut(hi), 1, (size_t)sx_len(hi), stdout); - putchar('\n'); /* hello */ - sx_free(hi); - sx_free(msg); + /* One expression: every call returns the same handle, and the temporary + buffer is consumed by sx_append, so there is nothing else to free. */ + sx_t *msg = sx_append(sx_append_cstr(sx_new(), "Hello, "), + sx_new_from_cstr("String X!")); + + printf("%s (%d bytes)\n", sx_buf_mut(msg), sx_len(msg)); + sx_free(msg); /* one buffer, one free */ return 0; } ``` @@ -119,7 +114,7 @@ cc hello.c $(pkg-config --cflags --libs libstringx) -o hello ``` ```text -hello +Hello, String X! (16 bytes) ``` From the source tree, before installing, use the build output instead: @@ -131,8 +126,7 @@ LD_LIBRARY_PATH=build/output ./hello ## Ten-minute tour -Five things users do with the library, one small program each. Every example -is complete and can be compiled the same way as `hello.c` above. +Five common tasks, one complete program each, compiled like `hello.c`. ### Create a buffer @@ -297,7 +291,7 @@ byte, including NUL. | [API reference: search, compare & split](api-search.md) | `sx_find*`, `sx_rfind*`, `sx_cmp*`, `sx_split` | | [Regular expressions](regex.md) | The `sx_reg_*` match, replace and split families | | [Design & internals](design.md) | Data layout, growth policy, algorithms, limits | -| [Build, test & package](build-and-test.md) | Forge targets, test harness, installation | +| [Build, test & package](build-and-test.md) | build targets, test harness, installation | | [Contributing](contributing.md) | Workflow, style, tests, licensing | | [Continuous integration](ci.md) | Workflows, required checks, CodeQL | diff --git a/docs/en_us/guide.md b/docs/en_us/guide.md index 930a19f..c81c3d6 100644 --- a/docs/en_us/guide.md +++ b/docs/en_us/guide.md @@ -4,10 +4,9 @@ English · [中文](../zh_cn/guide.md) # User guide -This guide is for C programmers who can already build and link String X (see -[Getting started](getting-started.md)) and want the mental model plus working -recipes. Signatures and per-function details live in the API reference; this -page is about how the pieces fit together and which calls are out of contract. +For C programmers who can build and link String X (see +[Getting started](getting-started.md)). Signatures and details are in the API +reference; this page covers the model, recipes, and out-of-contract calls. ## Mental model @@ -20,12 +19,10 @@ sx_t* ──► _sx { ptr: [ h e l l o \0 . . . . ] , len: 5, cap: 32 } ``` - `ptr[0 .. len-1]` are content bytes; `ptr[len]` is always `'\0'`. -- `len` is a byte count, never a character count, and it does not stop at an - embedded NUL. +- `len` counts bytes, not characters, and does not stop at an embedded NUL. - `cap` is the allocation size in bytes and always satisfies `cap >= len + 1`. - `sx_new()` starts with capacity 32; `sx_new_with_cap(n)` has exactly capacity - `n` for `n >= 1`, so it can hold at most `n - 1` content bytes (`n == 0` - still allocates one byte). + `n` for `n >= 1` (`n - 1` content bytes max; `n == 0` still allocates one). The handle is stable: growth may move the backing array, never the `sx_t`. Treat the handle as opaque, and do not copy the struct by value. @@ -45,8 +42,7 @@ sx_view_t { ref: the same _sx, offset: 1, len: 3 } ──► "ell" ## Ownership -Exactly one place owns a buffer at a time. The table says what each call -returns and how to release it. +One place owns a buffer at a time; per-call result and release: | Call | Result | Release with | | --- | --- | --- | @@ -58,18 +54,13 @@ returns and how to release it. | `sx_view`, `sx_view_*`, `sx_reg_match`, tokens inside the arrays above | view | nothing | | `sx_reg_compile` | compiled pattern | `sx_reg_free` | -Two consequences matter in practice: - -- Edits return `self`, so they chain: `sx_append_cstr(sx_append_cstr(s, "a"), - "b")` returns `s` itself, and the number of `sx_free` calls equals the number - of buffers created, not the number of edits. -- A consuming call ends the source's life. After `sx_append(s, part)`, `part` - must not be used or freed again: its content was copied into `s`, and even on - allocation failure the source is released. +- Edits return `self` and chain: `sx_append_cstr(sx_append_cstr(s, "a"), "b")` + returns `s`; `sx_free` calls equal buffers created, not edits. +- A consuming call ends the source: after `sx_append(s, part)`, `part` must not + be used or freed again (content copied; released even on allocation failure). `sx_append_cstr`, `sx_append_view`, `sx_write_cstr`, `sx_write_view`, -`sx_insert_cstr` and `sx_insert_view` take a C string or a view and never -consume a buffer. +`sx_insert_cstr`, `sx_insert_view` take a string or view, never a buffer. ## Binary safety and the cstr variants @@ -81,33 +72,29 @@ String X is binary-safe wherever an explicit length is carried: | `sx_view_t` forms, `sx_new_from_view`, owned `sx_t *` forms | explicit `len` | ordinary byte | | regex subject (`sx_t *h`) | byte length of `h` | ordinary byte | -So `sx_append_cstr` stops at a NUL, while `sx_append_view`, `sx_append` and -`sx_new_from_view` copy every content byte. To print a binary buffer, use the -length: `fwrite(sx_buf_mut(h), 1, (size_t)sx_len(h), stdout)` rather than -`printf("%s", ...)`. +`sx_append_cstr` stops at a NUL; `sx_append_view`, `sx_append` and +`sx_new_from_view` copy every content byte. Print a binary buffer by length: +`fwrite(sx_buf_mut(h), 1, (size_t)sx_len(h), stdout)`, not `printf("%s", ...)`. -The same split applies to compare and search: the `_cstr` forms use `strlen`, -while the owned and view forms compare content bytes. Regular expressions match -subjects by byte length, but their patterns are C strings, so a pattern cannot -contain a literal NUL. +The same split applies to compare and search: `_cstr` forms use `strlen`, owned +and view forms compare content bytes. Regex subjects match by byte length; +patterns are C strings, so a pattern cannot contain a literal NUL. ## Invariants and stale pointers - After every public call, `ptr[len] == '\0'`, `cap >= len + 1`, and `len` counts content bytes. Only a length-changing call moves those values. -- Any edit that grows the buffer may `realloc` the backing array. Every `char *` - obtained from `sx_buf_mut` or `sx_buf_view_mut` before that call is then - stale; re-fetch it after the edit. The `sx_t *` handle stays valid. +- Any growing edit may `realloc` the backing array; every `char *` from + `sx_buf_mut`/`sx_buf_view_mut` is then stale — re-fetch it. The `sx_t *` + handle stays valid. - Writes through `sx_buf_mut` must stay inside `[0, len)` unless a matching length-changing call follows; `ptr[len]` is the terminator, not a spare byte. -- Views are snapshots. Do not edit a buffer while views into it (or arrays of - tokens from `sx_split` / `sx_reg_*`) are alive, and re-derive views after a - length change even when no reallocation happened. +- Views are snapshots: do not edit a buffer while its views (or `sx_split` / + `sx_reg_*` arrays) are alive; re-derive views after any length change. - Accessors return `int` (`sx_len`, `sx_len_view`, `sx_cap`) while offsets are `size_t`. Buffers with more than `INT_MAX` content bytes are outside the tested contract. -- Capacity only grows: `sx_truncate`, `sx_erase` and `sx_clear` free no - capacity. +- Capacity only grows: `sx_truncate`, `sx_erase`, `sx_clear` free nothing. ## Errors and sentinels @@ -121,6 +108,7 @@ There are no exceptions and no error codes. Each family has a sentinel: | `sx_reg_match`: no match | view with `ref == NULL` | | `sx_reg_match_all` / `sx_reg_split`: no match or allocation failure | `NULL` array | | `sx_reg_replace*`: NULL argument or rejected template | `NULL` buffer | +| `sx_write*`: range end overflows `size_t` or cannot be reserved | `NULL`; `self` unchanged (owned input consumed) | | allocation failure | `NULL` | `NULL` means "no result"; for the array-returning calls, allocation failure is @@ -130,24 +118,25 @@ narrow: - `sx_new_from_cstr(NULL)` and `sx_dup(NULL)` return `NULL`. - The C-string and owned-buffer arguments of append/write/insert return `NULL` and leave `self` unchanged. +- `sx_write*` returns `NULL` when `idx + len` overflows `size_t` or the end + cannot be reserved; `self` keeps its content and an owned argument is still + freed. - `sx_cmp*`, `sx_starts_with*` and `sx_ends_with*` return `0`. - `sx_find*` / `sx_rfind*` return `(size_t)-1`; `sx_find_all*` return `NULL`. -- `sx_split` returns `NULL` for a NULL handle, NULL separator or empty - separator. +- `sx_split` returns `NULL` for a NULL handle/separator or an empty separator. - `sx_reg_compile(NULL)` returns `NULL`; `sx_reg_free(NULL)` is a no-op; the match, replace and split families return their not-found value for NULL arguments. -Everything else does not accept a NULL handle. `sx_len`, `sx_cap`, -`sx_buf_mut`, `sx_view`, `sx_free`, `sx_substr`, `sx_reserve`, `sx_erase` and -the rest dereference the handle; passing NULL is out of contract and may crash. -In particular, `sx_free(NULL)` is not a no-op, and a view with `ref == NULL` -cannot be passed to the view functions. +Everything else rejects NULL handles: `sx_len`, `sx_cap`, `sx_buf_mut`, +`sx_view`, `sx_free`, `sx_substr`, `sx_reserve`, `sx_erase` and the rest +dereference it, so NULL is out of contract and may crash. `sx_free(NULL)` +is not a no-op, and a `ref == NULL` view cannot be passed to view functions. ## Recipes -Each recipe is a complete C23 program. Build one with the command used for -`hello.c` in [Getting started](getting-started.md), or with: +Each recipe is a complete C23 program; build it like `hello.c` in +[Getting started](getting-started.md), or with: ```sh cc recipe.c $(pkg-config --cflags --libs libstringx) -o recipe @@ -180,9 +169,8 @@ int main(void) { ### Search and extract a substring -Check the `(size_t)-1` sentinel before using an offset. `sx_substr` copies, so -its result is independent of the source, and `sx_find_view_b` restricts the -search to a region starting at a boundary. +Check the `(size_t)-1` sentinel before using an offset. `sx_substr` copies +(independent result); `sx_find_view_b` searches only the region from a boundary. ```c #include @@ -216,9 +204,9 @@ key=key value=value ### Split and iterate -`sx_split` returns a malloc'ed array of views terminated by an end guard whose -`ref` is `NULL`; empty fields are kept. Free the array with `free`, and keep the -buffer alive while you read the tokens. +`sx_split` returns a malloc'ed view array whose end guard has `ref == NULL`; +empty fields are kept. `free` the array; keep the buffer alive while reading +tokens. ```c #include @@ -368,17 +356,19 @@ documented edge cases that are easy to miss: - Using a buffer after handing it to a consuming call: `sx_append(s, part)`, `sx_write(s, idx, part)` and `sx_insert(s, idx, part)` free `part`. -- Passing a buffer to itself through the owned forms: `sx_append(s, s)`, - `sx_write(s, idx, s)`, `sx_insert(s, idx, s)`. To double a buffer in place, - use `sx_append_view(s, sx_view(s))` and `sx_write_view`; they accept a view - into `s`. `sx_insert_view` also accepts one when the slice starts at or - before `idx` (the tested case); a self-aliased slice that starts after `idx` - is overwritten by the tail shift — copy it first. +- Passing a buffer to itself via the owned forms (`sx_append(s, s)`, + `sx_write(s, idx, s)`, `sx_insert(s, idx, s)`) is out of contract, and + doubling in place uses `sx_append_view(s, sx_view(s))` or `sx_write_view`; + `sx_insert_view` accepts a view into `s` only when the slice starts at or + before `idx` (the tested case); a slice starting after `idx` is clobbered by + the tail shift — copy it first. - `sx_insert*` with `idx > len`: the tail shift underflows. The tested contract is `0 <= idx <= len`. `sx_write*` is different: it pads and extends. -- Reading the unspecified bytes in `[old_len, n)` after a growing - `sx_truncate`, or in `[len, idx)` after `sx_write` beyond the end. Write over - the gap before reading it. +- Reading unspecified bytes in `[old_len, n)` after a growing `sx_truncate` + or `[len, idx)` after an out-of-range `sx_write`; write the gap first. +- Calling `sx_write*` with an `idx + len` near `SIZE_MAX` and assuming the + write happened: arithmetic overflow is rejected with `NULL` and `self` stays + unchanged. Check the return value. - Editing a buffer while views or arrays from `sx_split`, `sx_reg_match_all`, `sx_reg_split` or `sx_find_all*` are alive, or keeping a view past a length change. Views are not adjusted and may point into freed memory after growth. @@ -386,32 +376,29 @@ documented edge cases that are easy to miss: `{count, positions...}`. - Treating `sx_erase` with `idx + n > len` as an error. It is a documented no-op that returns `self`. -- Passing NULL handles to functions that do not check for them (see - [Errors and sentinels](#errors-and-sentinels)). `sx_free(NULL)` and - `sx_len(NULL)` are out of contract. +- Passing NULL handles to functions that do not check for them: `sx_free(NULL)` + and `sx_len(NULL)` are out of contract — see + [Errors and sentinels](#errors-and-sentinels). - Forgetting the release call: `sx_free` for buffers, `free` for view arrays, `sx_reg_free` for compiled patterns. A view needs no release. -- `sx_split` with an empty separator returns `NULL`; it does not split on every - byte. +- `sx_split` with an empty separator returns `NULL`, not one token per byte. - A regex pattern is a C string and cannot contain a literal NUL. Subjects can. - `sx_new_from_cstr` and every `_cstr` parameter stop at the first NUL; use views for binary content. - `sx_substr` requires `idx + n <= len(h)`; `sx_view_range` requires `off <= len(backing buffer)` (its `len` is clamped to the buffer end, `off` is not). Neither call clamps the precondition itself. -- Sharing one `sx_t` between threads without synchronization. The library has no - internal locking; a compiled `sx_reg_t` is the only object documented as - immutable and shareable. +- Sharing one `sx_t` across threads without synchronization: no internal + locking; only a compiled `sx_reg_t` is documented as immutable and shareable. ## Performance notes -- **Reserve before a known append loop.** `sx_reserve(self, n)` guarantees - `cap >= n + 1` without shrinking, so a buffer can reach `n` content bytes - without reallocating. Without it, growth is still amortized: the allocation - doubles, or grows by `0x10000` once the capacity is at least 64 KiB. +- **Reserve for known append loops.** `sx_reserve(self, n)` guarantees + `cap >= n + 1` without shrinking, so `n` content bytes fit without realloc; + otherwise growth is amortized — doubling, then `+0x10000` at 64 KiB and up. - **Views do not copy.** `sx_view`, `sx_view_advance` and the other view movers - are O(1) and allocate nothing. Prefer them for read-only slicing; use - `sx_substr` or `sx_new_from_view` only when you need an independent buffer. + are O(1) and allocate nothing; use `sx_substr`/`sx_new_from_view` only for an + independent buffer. - **Search is linear.** One-byte needles use `memchr` / `memrchr`; longer needles use forward or reverse KMP, O(n + m). `sx_find_all*` reports overlapping matches and sizes its array to the match count. @@ -421,15 +408,14 @@ documented edge cases that are easy to miss: replace and split reuses the compiled pattern and allocates only its own match data. `sx_reg_is_match` is the cheapest existence check. - **Capacity is never returned.** `sx_truncate`, `sx_erase` and `sx_clear` keep - the allocation, which makes a cleared buffer reusable but means a peak stays - allocated until `sx_free`. + the allocation: a cleared buffer is reusable, but a peak stays allocated until + `sx_free`. ## FAQ -**Do I need PCRE2 to use buffers?** To build the library, yes: the source tree -links `pcre2-8`, and `./make` needs `libpcre2-dev`. To use an installed -`libstringx`, link only `-lstringx`; the shared library carries its own PCRE2 -dependency. +**Do I need PCRE2 to use buffers?** To build, yes: the source tree links +`pcre2-8` and `./make` needs `libpcre2-dev`. An installed `libstringx` needs +only `-lstringx`; the shared library carries the PCRE2 dependency. **Is every function NULL-safe?** No. Only the cases listed in [Errors and sentinels](#errors-and-sentinels) are defined; NULL handles are out @@ -442,8 +428,8 @@ so `\d`, `\w`, `\s` and `\b` match ASCII only. **How do I copy a view?** `sx_new_from_view(v)` returns an owned buffer with a byte-exact copy of the view's `len` bytes. -**How do I get a substring?** `sx_view_range` and `sx_view_advance` give a -zero-copy view; `sx_substr(h, idx, n)` gives an owned copy. +**How do I get a substring?** `sx_view_range`/`sx_view_advance` give a zero-copy +view; `sx_substr(h, idx, n)` gives an owned copy. **Why does `sx_len` return `int`?** That is the library's practical size limit: content longer than `INT_MAX` bytes is outside the tested contract. Offsets are @@ -455,7 +441,7 @@ between threads is not supported. **What does a zero-length match look like?** `sx_reg_match` returns a view with `ref != NULL` and `len == 0`; `sx_reg_match_all` and `sx_reg_split` report it -and continue the scan one byte to the right. +and scan one byte on. --- diff --git a/docs/en_us/regex.md b/docs/en_us/regex.md index b90a36d..6e2ef85 100644 --- a/docs/en_us/regex.md +++ b/docs/en_us/regex.md @@ -6,28 +6,27 @@ English · [中文](../zh_cn/regex.md) ## Overview -`` adds one advanced layer on top of the core buffer API: a thin, -fixed-configuration wrapper around the **PCRE2 8-bit library** (`pcre2-8`, -version 10.46). It exposes a compile/free pair and three families — match, -replace and split — and deliberately adds no policy of its own: everything -this page does not state is PCRE2's default behavior. +`` adds an advanced layer: a thin, fixed-configuration wrapper around +the **PCRE2 8-bit library** (`pcre2-8`, version 10.46). It provides a +compile/free pair and three families — match, replace and split — and adds no +policy: anything not stated here is PCRE2's default. -The layer is designed around one lifecycle: +The lifecycle: 1. compile a pattern into an opaque `sx_reg_t *` handle; 2. run any number of calls against any number of `sx_t` subjects; 3. release the handle once with `sx_reg_free`. -A compiled handle is immutable and may be shared across threads; every call -uses its own match data. Subjects are matched by **byte length**, so an -embedded NUL is ordinary data (binary safe); patterns and replacement -templates are C strings and cannot contain a literal NUL. +A compiled handle is immutable and shareable across threads; each call uses +its own match data. Subjects are matched by **byte length**, so an embedded NUL +is ordinary data (binary safe); patterns and replacement templates are C +strings and cannot contain a literal NUL. -The layer is part of `libstringx`, which links `pcre2-8` itself: consumers -link `-lstringx` and pass no PCRE2 flags. PCRE2 is BSD-3-Clause; attribution -lives in [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md). For the -`$n` substitution rules see [Substitution templates](#substitution-templates); -for a task-oriented tour see the [user guide](guide.md). +The layer is part of `libstringx`, which links `pcre2-8`: consumers link +`-lstringx` and pass no PCRE2 flags. PCRE2 is BSD-3-Clause; see +[THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md). For `$n` substitution +see [Substitution templates](#substitution-templates); for task recipes see the +[user guide](guide.md). The families at a glance: @@ -40,10 +39,9 @@ The families at a glance: ## Lifecycle -Compile the pattern once, before the loop that uses it, and keep the handle. -The pattern string itself is not retained, so it can be freed right after -compilation. When the handle is no longer needed, release it with -`sx_reg_free`. +Compile the pattern once before the loop that uses it. The pattern string is +not retained, so free it after compilation; release the handle with +`sx_reg_free` when done. ```c #include @@ -94,14 +92,14 @@ int main(void) { } ``` -The three points that make the API safe to use in long-lived code are: +Three properties keep it safe in long-lived code: -- the handle is independent of the subjects: one compiled pattern serves any - number of buffers; -- results that alias a subject are views, so they stay valid only while that - subject lives and keeps its length; -- arrays returned by `sx_reg_match_all` and `sx_reg_split` are - caller-owned: release them with `free()`, not `sx_free`. +- The handle is independent of subjects: one compiled pattern serves any + number of buffers. +- Results that alias a subject are views, valid only while that subject lives + and keeps its length. +- Arrays from `sx_reg_match_all` and `sx_reg_split` are caller-owned: release + them with `free()`, not `sx_free`. ### sx_reg_compile @@ -115,18 +113,16 @@ Compiles a pattern with PCRE2 and returns an opaque handle. | --- | --- | | `pattern` | NUL-terminated PCRE2 pattern; not retained by the handle | -Returns a new handle, or `NULL` when `pattern` is `NULL`, the pattern is -syntactically invalid, or allocation fails. The wrapper exposes no PCRE2 -error code or error offset, so these cases cannot be told apart: validate a -pattern during development and treat `NULL` as "do not use this handle". +Returns a new handle, or `NULL` for a `NULL` pattern, invalid syntax or +allocation failure. The wrapper exposes no PCRE2 error code or offset, so these +cases are indistinguishable: validate patterns during development and treat +`NULL` as unusable. -Notes: - -- The pattern string may be freed or modified immediately after the call. -- No compile options are passed to PCRE2. PCRE2 features selected inside the - pattern itself (an inline option such as `(?i)`) still apply. -- Compilation is the expensive step of the layer relative to a single match - call, so compile once and reuse the handle ([performance](#performance)). +- The pattern string can be freed or modified immediately after the call. +- No compile options are passed. Features selected inside the pattern, such as + inline `(?i)`, still apply. +- Compilation is the expensive step, so compile once and reuse the handle + ([performance](#performance)). ```c sx_reg_t *re = sx_reg_compile("(\\w+)@(\\w+)"); /* NULL on bad input */ @@ -143,12 +139,10 @@ void sx_reg_free(sx_reg_t *r); Releases a compiled handle. `NULL` is accepted and is a no-op. -Notes: - -- Free a handle exactly once, after the last call that uses it. -- Data returned by earlier calls does not depend on the handle: match views - alias the subject, and arrays are caller-owned. -- Using a freed handle again is out of contract. +- Free a handle exactly once, after its last use. +- Earlier results do not depend on the handle: match views alias the subject + and arrays are caller-owned. +- Reusing a freed handle is out of contract. ```c sx_reg_free(re); /* release the handle after its last use */ @@ -156,11 +150,10 @@ sx_reg_free(re); /* release the handle after its last use */ ## Match family -All three calls scan the subject's content bytes from the left and follow -PCRE2's **leftmost-first** semantics: the match that starts earliest wins, -and among alternatives that start at the same byte PCRE2's preference order -decides. A zero-length match is a real match. Views alias the subject: no -bytes are copied and `h` is never modified. +All three calls scan content bytes from the left with PCRE2's +**leftmost-first** semantics: the earliest start wins; same-start alternatives +follow PCRE2's order. A zero-length match is a real match. Views alias the +subject and `h` is never modified. ### sx_reg_is_match @@ -175,15 +168,12 @@ Answers "does the pattern match anywhere in `h`?". | `r` | compiled pattern | | `h` | subject buffer | -Returns `1` if some match exists anywhere in `h`, otherwise `0` — including -when `r` or `h` is `NULL`, or when an internal allocation fails. A -zero-length match counts as a match, so `a*` matches an empty subject. +Returns `1` if a match exists anywhere in `h`, otherwise `0` — including for +`NULL` `r`/`h` or internal allocation failure. A zero-length match counts, so +`a*` matches an empty subject. -Notes: - -- The cheapest existence test: one PCRE2 match call and no result - allocation. Each call still creates and frees its own small PCRE2 - match-data block. +- The cheapest existence test: one PCRE2 match call and no result allocation; + each call still creates and frees a small PCRE2 match-data block. - The subject is searched by byte length; anchors refer to byte offsets. ```c @@ -207,22 +197,19 @@ Returns the leftmost match as a view into `h`. | `r` | compiled pattern | | `h` | subject buffer | -On success the result is a view into `h`'s buffer: `.ref` points at the -subject, and `.offset` / `.len` select the matched bytes. No match, a `NULL` -argument, or allocation failure returns the null view -`{ref = NULL, offset = 0, len = 0}`. A zero-length match is still a match: -`.ref != NULL` with `.len == 0`. - -Notes: +On success the result is a view into `h`: `.ref`, `.offset` and `.len` select +the matched bytes. No match, a `NULL` argument or allocation failure returns the +null view `{ref = NULL, offset = 0, len = 0}`; a zero-length match still has +`.ref != NULL` and `.len == 0`. -- Leftmost match, not "the longest match": alternatives prefer PCRE2's - order, so `b|bc` against `abc` matches `b` at offset 1. +- Leftmost, not longest: alternatives follow PCRE2's order, so `b|bc` against + `abc` matches `b` at offset 1. - One PCRE2 match call; the view is not a copy. - Anchors follow PCRE2's defaults: `^` matches at the subject start (offset 0) and `$` at the subject end; by default `$` also matches before a final newline. -- Using the view after `h` is freed, or after an edit changes `h`'s length, - is out of contract. +- Using the view after `h` is freed or its length changes is out of + contract. ```c sx_reg_t *re = sx_reg_compile("bc"); @@ -245,24 +232,18 @@ Collects every match in one left-to-right pass. | `r` | compiled pattern | | `h` | subject buffer | -Returns a `malloc`'ed array of views with the same shape as `sx_split`: -`arr[0 .. count-1]` are the matches and `arr[count].ref == NULL` is the end -guard. Release the array with `free()`; the views alias `h` and stay valid -while `h` lives and keeps its length. +Returns a `malloc`'ed array with the `sx_split` shape: `arr[0 .. count-1]` +are matches and `arr[count].ref == NULL` is the end guard. Release it with +`free()`; views alias `h` while `h` lives and keeps its length. No match, a +`NULL` argument or allocation failure returns `NULL` — indistinguishable by +this API. -Returns `NULL` when there is no match at all, when `r` or `h` is `NULL`, or -when allocation fails. These three cases are not distinguishable by this -API. - -Notes: - -- Matches do not overlap: after each match the scan resumes at the match end, - or one byte further right for a zero-length match - ([the scan rule](#the-scan-rule)). -- Counting and filling are two passes over the same deterministic scan, so - the array is allocated exactly once at its final size. -- `sx_find_all*` reports overlapping positions instead; `sx_reg_match_all` - reports regex matches, which cannot overlap. +- Matches do not overlap: after each match the scan resumes at its end, or one + byte right for a zero-length match ([the scan rule](#the-scan-rule)). +- Counting and filling are two passes over the same deterministic scan, so the + array is allocated once at final size. +- `sx_find_all*` reports overlapping positions instead; regex matches cannot + overlap. ```c sx_reg_t *re = sx_reg_compile("a*"); @@ -283,8 +264,7 @@ sx_reg_free(re); - matches are taken left to right and never overlap; - after a match the next search starts at the match's end; - after a zero-length match the next search starts **one byte to the right** - of the match start, so a pattern that can match empty cannot stall the - scan; + of the match start, so an empty-matching pattern cannot stall the scan; - a match may end exactly at `len(h)` (for example `$`); the scan then stops because PCRE2 rejects a start offset beyond the subject. @@ -295,14 +275,14 @@ sx_reg_free(re); | `$` | `abc` | (3,0) | | `bc` | `abcb` | (1,2) | -The same rule determines the token count of `sx_reg_split`: it is always +The same rule fixes the `sx_reg_split` token count: always `number_of_matches + 1`. ## Replace family -Both replace calls substitute a C-string template into the match(es) and -return a **new** caller-owned `sx_t`; `h` is never modified. Free the result -with `sx_free`, like any other buffer. +Both replace calls substitute a C-string template into matches and return a +**new** caller-owned `sx_t`; `h` is never modified. Free the result with +`sx_free` like any other buffer. ### sx_reg_replace @@ -318,18 +298,16 @@ Replaces every match in `h` with `repl`. | `h` | subject buffer; never modified | | `repl` | NUL-terminated substitution template; not retained | -Returns a new buffer, or `NULL` when `r`, `h` or `repl` is `NULL`, PCRE2 -rejects the template, or allocation fails. With valid arguments and no match -the result is an **unchanged copy** of `h`, never `NULL`. - -Notes: +Returns a new buffer, or `NULL` for a `NULL` argument, a template PCRE2 +rejects, or allocation failure. With valid arguments and no match, the result +is an **unchanged copy** of `h`, never `NULL`. - The template expands `$0` / `$n`; see [Substitution templates](#substitution-templates). - Zero-length matches are substituted too: `a*` against `bbb` with the template `-` yields `-b-b-b-`. -- An empty template deletes every match, so a pattern that matches the whole - subject produces an empty buffer. +- An empty template deletes every match; a whole-subject match therefore + yields an empty buffer. - Byte-exact: embedded NULs in `h` are ordinary matching data and are copied into the result. @@ -349,8 +327,8 @@ sx_t *sx_reg_replace_first(const sx_reg_t *r, const sx_t *h, const char *repl); ``` -Same contract as `sx_reg_replace`, except that only the **leftmost** match is -substituted; every other byte is copied unchanged. +Same contract as `sx_reg_replace`, but only the **leftmost** match is +substituted; all other bytes are copied unchanged. ```c sx_reg_t *re = sx_reg_compile("x"); @@ -363,8 +341,8 @@ sx_reg_free(re); ## Substitution templates -Both replace calls interpret `repl` with PCRE2's substitution syntax, with -two options fixed by the wrapper that make missing captures harmless. +Both replace calls use PCRE2's substitution syntax for `repl`, with two +wrapper-fixed options that make missing captures harmless. | Template element | Expands to | | --- | --- | @@ -379,17 +357,15 @@ two options fixed by the wrapper that make missing captures harmless. | `a(b)?` | `a` | `[$1]` | `[]` | | `abc` | `abc` | (empty template) | (empty buffer) | -Notes: - -- The wrapper passes PCRE2's `PCRE2_SUBSTITUTE_UNSET_EMPTY` and - `PCRE2_SUBSTITUTE_UNKNOWN_UNSET`: a group that did not participate, and a - group number that does not exist, both expand to the empty string. A - template is therefore never rejected just because a capture is missing. -- `$n` refers to capture groups of each match as it is substituted; group 0 - is the whole match. -- `repl` is a C string, so a literal NUL cannot appear in it. Matched NUL +- The wrapper sets `PCRE2_SUBSTITUTE_UNSET_EMPTY` and + `PCRE2_SUBSTITUTE_UNKNOWN_UNSET`: a group that did not participate and a + non-existent group number both expand to empty, so a template is never + rejected merely for a missing capture. +- `$n` refers to each match's own capture groups; group 0 is the whole + match. +- `repl` is a C string, so a literal NUL cannot appear in it; matched NUL bytes still reach the result through `$0` / `$n`. -- The full substitution syntax is PCRE2's; see the +- The full syntax is PCRE2's; see the [PCRE2 documentation](https://www.pcre.org/). ## Split family @@ -407,22 +383,18 @@ Splits `h` into the gaps between non-overlapping matches. | `r` | compiled pattern | | `h` | subject buffer | -Returns a `malloc`'ed array with exactly the `sx_split` shape: -`arr[0 .. count-1]` are the tokens in order, `arr[count].ref == NULL` is the -end guard, and `count == number_of_matches + 1`. Empty tokens are kept at -every edge and in the interior. The caller frees the array with `free()`; the -tokens are views into `h`. - -Returns `NULL` for a `NULL` argument or allocation failure. No match is not -an error: the array then contains the whole subject as its single token. - -Notes: - -- Zero-length matches split at every position: `a*` against `bbb` gives - `""`, `"b"`, `"b"`, `"b"`, `""` — five tokens. -- A match that covers the whole subject yields two empty tokens. -- Leading and trailing matches yield empty edge tokens; interior empty tokens - come from adjacent matches. +Returns a `malloc`'ed array with the `sx_split` shape: tokens in order at +`arr[0 .. count-1]`, end guard `arr[count].ref == NULL`, and +`count == number_of_matches + 1`. Empty tokens are kept at every edge and in +the interior; free the array with `free()`; tokens are views into `h`. `NULL` +on a `NULL` argument or allocation failure. No match is not an error: the whole +subject is the single token. + +- Zero-length matches split at every position: `a*` against `bbb` gives `""`, + `"b"`, `"b"`, `"b"`, `""` — five tokens. +- A whole-subject match yields two empty tokens. +- Leading and trailing matches yield empty edge tokens; adjacent matches yield + interior empty tokens. - Do not edit `h` while the tokens are in use (views are snapshots; see the [user guide](guide.md)). @@ -445,8 +417,8 @@ sx_reg_free(re); | Template `repl` | a C string: no literal NUL; captures can inject NUL bytes into the result | - PCRE2 runs in **8-bit non-UTF mode**: `\d`, `\w`, `\s`, `\b` and friends - match ASCII only. Bytes that form a non-ASCII character (for example the - UTF-8 bytes `C2 A5`) never match `\d`. + match ASCII only; bytes forming a non-ASCII character (e.g. UTF-8 `C2 A5`) + never match `\d`. - In 8-bit non-UTF mode, `.` matches any byte except newline, including an embedded NUL: the pattern `A.B` matches the three bytes `A\0B`. - Replace is binary-safe in both directions: `a\0b` with the pattern `b` and @@ -459,7 +431,7 @@ sx_reg_free(re); ## Error sentinels No documented call crashes on invalid input, a missing match or allocation -failure; each family reports it with a fixed sentinel. +failure; each family reports a fixed sentinel. | Call | No match | `NULL` argument / invalid input | Allocation failure | | --- | --- | --- | --- | @@ -472,29 +444,24 @@ failure; each family reports it with a fixed sentinel. | `sx_reg_replace_first` | unchanged copy | `NULL` | `NULL` | | `sx_reg_split` | one-token array (the whole subject) | `NULL` | `NULL` | -Notes: - -- For `sx_reg_match_all` and `sx_reg_split`, "no match" and allocation - failure both yield `NULL`; the array family cannot distinguish them. -- For the replace family, "no match" is a normal success: you get an - unchanged copy of `h`. -- Arrays are `malloc`'ed and released with `free()`; buffers returned by the - replace family are `sx_t *` and released with `sx_free()`. +- For `sx_reg_match_all` and `sx_reg_split`, no match and allocation failure + both yield `NULL`; the array family cannot distinguish them. +- For replace, no match is normal success: an unchanged copy of `h`. +- Arrays are `malloc`'ed and freed with `free()`; replace results are + `sx_t *` freed with `sx_free()`. ## Thread safety -- A compiled `sx_reg_t` is immutable after `sx_reg_compile`. It has no - mutable state and the wrapper keeps no global state, so one handle can be - used by several threads at the same time. -- Each match/split call creates its own PCRE2 match-data block - (`pcre2_match_data_create_from_pattern`) and frees it before returning; the - replace calls delegate to `pcre2_substitute`, which also uses per-call - match data. Two threads never share match state. +- A compiled `sx_reg_t` is immutable after `sx_reg_compile`, has no mutable + state, and the wrapper keeps no global state, so one handle can serve several + threads. +- Each match/split call creates and frees its own PCRE2 match-data block; + replace delegates to `pcre2_substitute`, which also uses per-call match data. + No match state is shared. - A subject buffer is plain memory with no locking: concurrent readers are - fine, but any mutation requires external synchronization. -- Views and arrays are snapshots into a subject. Do not edit the subject - while a thread is still reading views from it, and do not free a handle - while another thread is using it. + fine; mutation needs external synchronization. +- Views and arrays are snapshots: do not edit a subject while another thread + reads its views, and do not free a handle while another thread uses it. ## Performance @@ -507,19 +474,17 @@ Notes: | `sx_reg_split` | two passes over the scan | match data plus one exact-size array | array | | `sx_reg_replace*` | two substitute calls | internal PCRE2 match data, one temporary buffer, one `sx_t` | new buffer | -Notes: - -- Compile once: pattern compilation costs far more than a single match, so - compiling inside a loop is the one avoidable performance mistake. +- Compile once: compilation costs far more than a single match, so compiling + inside a loop is the one avoidable performance mistake. - `sx_reg_is_match` is the cheapest existence test; `sx_reg_match` adds only the returned view. -- `sx_reg_match_all` and `sx_reg_split` scan twice (count, then fill) so the - result array is allocated exactly once and never grows by `realloc`. -- The replace family probes the exact output length with a first - `pcre2_substitute` call, then fills a fitting buffer with a second call; - the buffer is copied once into the returned `sx_t`. -- Every call allocates and frees match data; no match data is cached between - calls, and the wrapper does not enable PCRE2 JIT or any compile option. +- `sx_reg_match_all` and `sx_reg_split` scan twice (count, then fill), so the + result array is allocated once at final size without `realloc` growth. +- Replace probes the exact output length with a first `pcre2_substitute` + call, then fills a fitting buffer with a second; the buffer is copied once + into the returned `sx_t`. +- Every call allocates and frees match data; nothing is cached, and the wrapper + enables neither PCRE2 JIT nor compile options. - The subject is never copied; only the replace family allocates a result buffer. @@ -538,23 +503,21 @@ Notes: The wrapper fixes a small, deliberately plain configuration: -- **8-bit, non-UTF**: the pattern and subject are bytes, character classes - are ASCII, and no UTF validation happens. In the default (no `DOTALL`) - mode `.` does not match newline. -- **No option flags**: the wrapper passes no compile options and no match - options, and no match context. PCRE2 features that are expressed inside - the pattern, such as inline options, still work; case-insensitive - matching, multiline matching and similar behavior are requested with - PCRE2's in-pattern syntax. -- **PCRE2 defaults govern**: leftmost-first alternation, greedy/lazy - quantifiers, anchors, backreferences and all other pattern semantics are - PCRE2's, not the wrapper's. +- **8-bit, non-UTF**: pattern and subject are bytes, character classes are + ASCII, and no UTF validation happens. In the default (no `DOTALL`) mode `.` + does not match newline. +- **No option flags**: no compile options, match options or match context are + passed. In-pattern features such as inline options still work, so + case-insensitive and multiline matching use PCRE2's own syntax. +- **PCRE2 defaults govern**: alternation preference, greedy/lazy quantifiers, + anchors, backreferences and all other pattern semantics are PCRE2's, not the + wrapper's. - The wrapper does not expose PCRE2 error codes or compile error offsets. -Pattern syntax and semantics are documented by the PCRE2 project at -[pcre.org](https://www.pcre.org/); this library does not re-document them. -The bundled PCRE2 version is 10.46; the dependency is BSD-3-Clause, with -attribution in [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md). +Pattern syntax and semantics are documented by PCRE2 at +[pcre.org](https://www.pcre.org/); this library does not re-document them. The +bundled PCRE2 version is 10.46; the dependency is BSD-3-Clause, attributed in +[THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md). --- diff --git a/docs/zh_cn/README.md b/docs/zh_cn/README.md index 01b4332..225bcbd 100644 --- a/docs/zh_cn/README.md +++ b/docs/zh_cn/README.md @@ -36,8 +36,8 @@ String X 是一个轻量的 C 字符串库,核心思路只有一个:每个 每个调用的完整契约。 - [设计与内部实现](design.md) —— 数据布局、扩容策略、查找算法、正则封装 的内部细节、可移植性限制、测试策略。 -- [构建、测试与打包](build-and-test.md) —— Forge、`./make` 各目标、测试 - 框架、内存检查器、安装与 Debian 打包。 +- [构建、测试与打包](build-and-test.md) —— `./make` 各目标、测试框架、 + 内存检查器、安装与 Debian 打包。 - [贡献指南](contributing.md) —— 工作流程、契约优先的文档规则、代码风格、 测试、许可。 - [持续集成](ci.md) —— 工作流、必需检查、CodeQL、合并保护、本地复现。 diff --git a/docs/zh_cn/api-buffer.md b/docs/zh_cn/api-buffer.md index 01f8c75..ea4262a 100644 --- a/docs/zh_cn/api-buffer.md +++ b/docs/zh_cn/api-buffer.md @@ -4,12 +4,9 @@ # 缓冲区与视图 API 参考 -本页是 `include/sx_core.h` 中核心缓冲区与视图 API 的完整参考:创建与释放 -缓冲区、读取状态、修改内容、截取子串,以及移动和裁剪视图。查找、比较与 -分割由[查找、比较与分割](api-search.md)一并说明。 - -下文每一条行为描述都来自公开头文件中的契约、实现代码,以及 -`tests/*.c` 中的行为边界注释。 +`include/sx_core.h` 的核心缓冲区与视图 API:创建、状态、修改、子串、 +视图移动与裁剪。查找、比较与分割见[查找、比较与分割](api-search.md)。 +行为描述来自公开头文件、实现代码与 `tests/*.c` 的边界注释。 ## 约定 @@ -19,15 +16,14 @@ #include ``` -`sx.h` 包含 `sx_core.h`(缓冲区、视图、查找、比较),随后声明 `sx_split` -和 `sx_reg_*` 家族。链接库时使用 `-lstringx`。本页所有函数都声明在 -`sx_core.h` 中。`sx_raw.h` 是内部的分配/调试接口,不属于受支持的公开 -接口。 +`sx.h` 包含 `sx_core.h`(缓冲区、视图、查找、比较),并声明 `sx_split` +和 `sx_reg_*`;链接用 `-lstringx`。本页函数都声明在 `sx_core.h` 中。 +`sx_raw.h` 是内部调试接口,不属于公开接口。 -**每个缓冲区一次分配。** 一个 `sx_t` 句柄拥有恰好一段以 NUL 结尾的字节 -数组:`ptr[0 .. len-1]` 是内容字节,`ptr[len]` 恒为 `'\0'`,`cap` 是分配 -大小,且 `cap >= len + 1`。`len` 统计内容字节,因此内嵌的 `'\0'` 是普通 -数据而不是结尾符 —— 该模型天然二进制安全。 +**每个缓冲区一次分配。** `sx_t` 拥有一段 NUL 结尾的字节数组: +`ptr[0 .. len-1]` 是内容,`ptr[len]` 恒为 `'\0'`,`cap` 是分配大小, +`cap >= len + 1`。`len` 统计内容字节,内嵌 `'\0'` 是数据而非结尾符, +天然二进制安全。 **所有权。** @@ -39,21 +35,20 @@ | `sx_view_t` | 无:它仅别名一段缓冲区 | 无需释放;视图从不单独释放 | | `sx_find_all*` 或 `sx_split` 返回的数组 | 调用方 | `free`(见 [api-search.md](api-search.md)) | -每次修改都返回 `self`,因此调用可以链式书写,句柄保持稳定。缓冲区增长时 -底层数组可能搬移:`sx_buf_mut`/`sx_buf_view_mut` 返回的指针在任何可能 -重新分配的调用之后都会失效,必须重新获取。 - -**NULL 与契约之外。** 本页明确记录的 NULL 处理只有:`sx_new_from_cstr(NULL)` -和 `sx_dup(NULL)` 返回 `NULL`;`sx_append`、`sx_write`、`sx_insert` 的 -`owned` 形式以及所有 `_cstr` 形式在第二个参数为 `NULL` 时返回 `NULL` 且 -保持 `self` 不变。其余函数都会解引用缓冲区或窗口:`sx_free`、`sx_len`、 -`sx_cap`、`sx_buf_mut`、`sx_view`、视图移动家族以及修改类函数都不接受 -NULL 句柄;`sx_new_from_view`、`sx_buf_view_mut` 和 `sx_view_*` 也不接受 -`ref == NULL` 的视图(`sx_len_view` 只读取存储的长度)。NULL 句柄或 -`v.ref`、已释放的句柄、越出底层缓冲区的视图、重复释放、在消耗所有权的 -调用之后继续使用、把 `self` 作为 `owned` 参数传入,以及违反各条目所述 -条件的下标,全部属于**契约之外**:行为未定义,而不是有文档化的错误 -返回值。 +每次修改都返回 `self`,调用可以链式书写,句柄保持稳定。增长可能搬移底层 +数组:`sx_buf_mut`/`sx_buf_view_mut` 的指针在任何可能重新分配的调用后 +失效,必须重新获取。修改失败时 `owned` 参数同样会被消耗:调用返回 +`NULL`、释放该参数,`self` 保持不变。 + +**NULL 与契约之外。** 文档化的 NULL 处理:`sx_new_from_cstr(NULL)` 和 +`sx_dup(NULL)` 返回 `NULL`;`sx_append`、`sx_write`、`sx_insert` 的 +`owned` 形式及所有 `_cstr` 形式在第二个参数为 `NULL` 时返回 `NULL` 且 +`self` 不变。其余函数解引用缓冲区或窗口:`sx_free`、`sx_len`、`sx_cap`、 +`sx_buf_mut`、`sx_view`、视图移动家族和修改类函数不接受 NULL 句柄, +`sx_new_from_view`、`sx_buf_view_mut`、`sx_view_*` 不接受 `ref == NULL` +的视图(`sx_len_view` 只读存储的长度)。**契约之外**(行为未定义,而非 +错误返回值):NULL 句柄或 `v.ref`、已释放句柄、越界视图、重复释放、 +消耗后继续使用、把 `self` 作为 `owned`,以及违反条目条件的下标。 **哨兵值。** @@ -65,23 +60,21 @@ NULL 句柄;`sx_new_from_view`、`sx_buf_view_mut` 和 `sx_view_*` 也不接 | 未找到 / 无匹配(查找页) | `(size_t)-1` | | 无匹配 / 拒绝分割(查找页) | `NULL` | -**大小是 `int`。** `sx_len`、`sx_len_view` 和 `sx_cap` 返回 `int`,而视图 -字段和查找偏移是 `size_t`。内容超过 `INT_MAX` 字节的情况不在测试契约 -范围内;两者混用时请转换为 `(size_t)`,例如 +**大小是 `int`。** `sx_len`、`sx_len_view`、`sx_cap` 返回 `int`;视图字段 +和查找偏移是 `size_t`。超过 `INT_MAX` 字节不在测试契约内;混用时转换为 +`(size_t)`,例如 `fwrite(sx_buf_mut(h), 1, (size_t)sx_len(h), stdout)`。 -**视图是快照。** `sx_view_t {ref, offset, len}` 表示 `ref` 所指缓冲区内的 -字节窗口 `[offset, offset + len)`;它不拷贝、也不修改任何东西。合法的窗口 -必须位于缓冲区内(`offset + len <= len(ref)`)。之后任何重新分配或改变 -长度的修改都会使视图失去意义:这类修改之后要重新推导视图;有视图(例如 -`sx_split` 数组)在使用时不要修改其底层缓冲区。`ref == NULL` 表示“没有 -视图”,它不是可用的缓冲区。 +**视图是快照。** `sx_view_t {ref, offset, len}` 是 `ref` 所指缓冲区内的 +窗口 `[offset, offset + len)`;不拷贝、不修改,合法窗口满足 +`offset + len <= len(ref)`。之后任何重新分配或改变长度的修改都会使其 +失效:重新推导视图;有视图(如 `sx_split` 数组)使用时不要修改底层 +缓冲区。`ref == NULL` 表示“没有视图”,不是可用缓冲区。 -**容量增长。** `sx_new` 的初始容量是 32 字节。增长是几何式的(先翻倍, -容量达到 64 KiB 之后改为 `+0x10000`);使用 `-DSX_FORCE_EXACT_RESERVE` -的调试构建会把每次分配精确设为 `need + 1`。容量从不收缩 —— `sx_truncate` -和 `sx_clear` 都会保留容量 —— 任何函数也不会承诺其所述保证之外的空闲 -容量。 +**容量增长。** `sx_new` 初始容量 32 字节;增长为几何式(先翻倍,达到 +64 KiB 后改为 `+0x10000`),`-DSX_FORCE_EXACT_RESERVE` 调试构建则把 +每次分配精确设为 `need + 1`。容量从不收缩(`sx_truncate`、`sx_clear` +保留容量),也没有函数承诺所述保证之外的空闲容量。 ## 创建与释放 @@ -91,13 +84,13 @@ NULL 句柄;`sx_new_from_view`、`sx_buf_view_mut` 和 `sx_view_*` 也不接 sx_t *sx_new(void); ``` -创建一个初始容量为 32 字节的空缓冲区。 +创建容量为 32 字节的空缓冲区。 - **参数:** 无。 -- **返回:** 新缓冲区(`len == 0`、`cap == 32`、`ptr[0] == '\0'`), - 分配失败时返回 `NULL`。 -- **所有权:** 调用方所有;用 `sx_free` 释放。 -- **边界情况:** 确切的初始容量属于实现细节;只有 `cap >= 1` 有保证。 +- **返回:** 新缓冲区(`len == 0`、`cap == 32`、`ptr[0] == '\0'`); + 分配失败返回 `NULL`。 +- **所有权:** 调用方所有;`sx_free` 释放。 +- **边界情况:** 只有 `cap >= 1` 有保证;初始 32 字节属于实现细节。 ### sx_new_from_cstr @@ -105,14 +98,13 @@ sx_t *sx_new(void); sx_t *sx_new_from_cstr(const char *s); ``` -创建一个存放 C 字符串 `s` 副本的缓冲区。 +创建存放 C 字符串 `s` 副本的缓冲区。 -- **参数:** `s` —— 以 NUL 结尾的源字符串,按 `strlen` 读取。 -- **返回:** 新的调用方所有的缓冲区;`s == NULL` 或分配失败时返回 - `NULL`。 -- **所有权:** 调用方所有;用 `sx_free` 释放。 -- **边界情况:** 采用 `strlen` 语义 —— 内嵌的 `'\0'` 会截断副本。二进制 - 内容请使用 `sx_new_from_view`。 +- **参数:** `s` —— NUL 结尾字符串,按 `strlen` 读取。 +- **返回:** 新缓冲区;`s == NULL` 或分配失败返回 `NULL`。 +- **所有权:** 调用方所有;`sx_free` 释放。 +- **边界情况:** `strlen` 语义,内嵌 `'\0'` 截断副本;二进制内容用 + `sx_new_from_view`。 ### sx_new_from_view @@ -120,15 +112,15 @@ sx_t *sx_new_from_cstr(const char *s); sx_t *sx_new_from_view(sx_view_t v); ``` -把视图中的字节拷贝成一个新的独立缓冲区。 +把视图中的字节拷贝成新的独立缓冲区。 - **参数:** `v` —— 源窗口;从 `v.ref->ptr + v.offset` 读取 `v.len` 个字节。 -- **返回:** 新的调用方所有的缓冲区;分配失败时返回 `NULL`。 -- **所有权:** 调用方所有;用 `sx_free` 释放。 -- **边界情况:** 字节精确且二进制安全:内嵌的 `'\0'` 字节会被拷贝。两个 - 缓冲区之间不存在别名 —— 修改任一方永远不影响另一方。`v.ref == NULL` 或 - 越界窗口属于契约之外。 +- **返回:** 新缓冲区;分配失败返回 `NULL`。 +- **所有权:** 调用方所有;`sx_free` 释放。 +- **边界情况:** 字节精确且二进制安全(内嵌 `'\0'` 会拷贝);两个缓冲区 + 无别名,修改任一方不影响另一方。`v.ref == NULL` 或越界窗口属于契约 + 之外。 ### sx_new_with_cap @@ -136,13 +128,13 @@ sx_t *sx_new_from_view(sx_view_t v); sx_t *sx_new_with_cap(size_t n); ``` -创建一个恰好分配 `n` 个字节的空缓冲区。 +创建恰好分配 `n` 个字节的空缓冲区。 - **参数:** `n` —— 分配的总字节数。 -- **返回:** `n >= 1` 时 `cap == n` 的新缓冲区;分配失败时返回 `NULL`。 -- **所有权:** 调用方所有;用 `sx_free` 释放。 -- **边界情况:** 其中一个字节留给结尾符,因此最多容纳 `n - 1` 个内容 - 字节。`n == 0` 时仍会分配一个字节(`cap == 1`),句柄始终有效。 +- **返回:** `n >= 1` 时 `cap == n` 的新缓冲区;分配失败返回 `NULL`。 +- **所有权:** 调用方所有;`sx_free` 释放。 +- **边界情况:** 一个字节留给结尾符,最多容纳 `n - 1` 个内容字节; + `n == 0` 仍分配一个字节(`cap == 1`),句柄始终有效。 ```c sx_t *buf = sx_new_with_cap(64); /* room for 63 content bytes */ @@ -156,14 +148,12 @@ sx_free(buf); sx_t *sx_dup(const sx_t *src); ``` -创建缓冲区的深拷贝,副本完全独立。 +创建完全独立的深拷贝。 - **参数:** `src` —— 源缓冲区。 -- **返回:** 内容相同的新缓冲区;`src == NULL` 或分配失败时返回 - `NULL`。 +- **返回:** 内容相同的新缓冲区;`src == NULL` 或分配失败返回 `NULL`。 - **所有权:** 调用方所有;副本与源分别用 `sx_free` 释放。 -- **边界情况:** 二进制安全。v0.5 中副本的容量是 `len + 1`,而不是源的 - 容量。 +- **边界情况:** 二进制安全;v0.5 中副本容量是 `len + 1`,而非源的容量。 ```c sx_t *src = sx_new_from_cstr("hello"); @@ -178,15 +168,14 @@ sx_free(src); void sx_free(sx_t *h); ``` -释放缓冲区:内容数组和句柄本身。 +释放缓冲区:内容数组和句柄。 -- **参数:** `h` —— 调用方持有所有权的有效句柄。 +- **参数:** `h` —— 调用方持有的有效句柄。 - **返回:** 无。 -- **所有权:** 消耗 `h`;所有指向该缓冲区的视图和 `sx_buf_mut` 指针都 - 随之失效。 -- **边界情况:** `h == NULL` 属于契约之外 —— 该函数会解引用句柄(正则层 - 的 `sx_reg_free(NULL)` 空操作不适用于这里)。重复释放和释放后使用同样 - 属于契约之外。 +- **所有权:** 消耗 `h`;指向它的视图和 `sx_buf_mut` 指针全部失效。 +- **边界情况:** `h == NULL` 属于契约之外 —— 函数会解引用句柄(正则层 + `sx_reg_free(NULL)` 的空操作不适用于此)。重复释放、释放后使用也属于 + 契约之外。 ## 访问器 @@ -199,10 +188,8 @@ int sx_len(sx_t *h); 返回内容字节数。 - **参数:** `h` —— 缓冲区。 -- **返回:** `len`,内嵌的 `'\0'` 字节也计入;结尾符从不计入。 -- **所有权:** 无;不修改缓冲区。 -- **边界情况:** `h == NULL` 属于契约之外。返回值是 `int`;参见上文的 - 大小说明。 +- **返回:** `len`,内嵌 `'\0'` 也计入;结尾符从不计入;不修改缓冲区。 +- **边界情况:** `h == NULL` 属于契约之外;返回值是 `int`(见大小说明)。 ### sx_len_view @@ -210,13 +197,12 @@ int sx_len(sx_t *h); int sx_len_view(sx_view_t v); ``` -返回视图中存储的长度。 +返回视图存储的长度。 - **参数:** `v` —— 要读取长度的视图。 -- **返回:** `(int)v.len`;不会查看底层缓冲区,也不会校验窗口边界。 -- **所有权:** 无。 -- **边界情况:** `v.len` 超过 `INT_MAX` 不在测试契约范围内。“没有视图” - 哨兵值(`ref == NULL`)的 `len` 为 0。 +- **返回:** `(int)v.len`;不查看底层缓冲区,也不校验窗口边界。 +- **边界情况:** `v.len` 超过 `INT_MAX` 不在测试契约内;“没有视图”哨兵值 + (`ref == NULL`)的 `len` 为 0。 ### sx_cap @@ -224,12 +210,12 @@ int sx_len_view(sx_view_t v); int sx_cap(sx_t *h); ``` -返回为内容数组分配的总字节数。 +返回内容数组的总分配字节数。 - **参数:** `h` —— 缓冲区。 -- **返回:** `cap`,它始终至少为 `len + 1`(单 NUL 结尾不变式)。 -- **所有权:** 无;不修改缓冲区。 -- **边界情况:** `h == NULL` 属于契约之外。`len + 1` 之外的空闲容量取决于 +- **返回:** `cap`,始终至少为 `len + 1`(单 NUL 结尾不变式);不修改 + 缓冲区。 +- **边界情况:** `h == NULL` 属于契约之外;`len + 1` 之外的空闲容量取决于 增长策略,不构成契约。 ### sx_buf_mut @@ -238,15 +224,14 @@ int sx_cap(sx_t *h); char *sx_buf_mut(sx_t *h); ``` -返回指向内容数组的可写指针。 +返回内容数组的可写指针。 - **参数:** `h` —— 缓冲区。 -- **返回:** `ptr`;任何时刻都有 `ptr[len] == '\0'`。 -- **所有权:** 借用;调用方可以在 `[0, len)` 内改写字节而不改变 `len`。 -- **边界情况:** 没有改变长度的调用时,不得在 `len` 及其之后写入;也不得 - 跨过任何可能重新分配的调用保存该指针(`sx_append*`、`sx_write*`、 - `sx_insert*`、`sx_reserve`、会增长的 `sx_truncate`)。`h == NULL` 属于 - 契约之外。 +- **返回:** `ptr`;任何时刻 `ptr[len] == '\0'`。 +- **所有权:** 借用;可在 `[0, len)` 内改写字节而不改变 `len`。 +- **边界情况:** 无长度变更时不得在 `len` 及之后写入;也不得跨过可能 + 重新分配的调用保存指针(`sx_append*`、`sx_write*`、`sx_insert*`、 + `sx_reserve`、会增长的 `sx_truncate`)。`h == NULL` 属于契约之外。 ```c char *p = sx_buf_mut(buf); @@ -259,14 +244,13 @@ p[0] = 'H'; /* len unchanged; p[len] must stay '\0' */ char *sx_buf_view_mut(sx_view_t v); ``` -返回指向视图窗口首字节的可写指针。 +返回视图窗口首字节的可写指针。 -- **参数:** `v` —— 指向某个缓冲区的视图。 +- **参数:** `v` —— 指向缓冲区的视图。 - **返回:** `v.ref->ptr + v.offset`。 -- **所有权:** 借用;写入会落到底层缓冲区上。 -- **边界情况:** 该指针不携带长度信息 —— 请配合 `sx_len_view(v)` 使用并 - 停留在窗口内。`v.ref == NULL` 或越界窗口属于契约之外;底层缓冲区重新 - 分配后该指针失效。 +- **所有权:** 借用;写入落到底层缓冲区。 +- **边界情况:** 指针不携带长度 —— 配合 `sx_len_view(v)` 停留在窗口内。 + `v.ref == NULL` 或越界窗口属于契约之外;底层缓冲区重新分配后指针失效。 ```c sx_view_t word = sx_view_range(sx_view(buf), 6, 5); @@ -283,8 +267,8 @@ sx_view_t sx_view(const sx_t *h); 返回整个缓冲区的视图。 - **参数:** `h` —— 缓冲区。 -- **返回:** `{ref: h->ref, offset: 0, len: sx_len(h)}`。 -- **所有权:** 无;视图为 `h` 的别名,从不单独释放。 +- **返回:** `{ref: h->ref, offset: 0, len: sx_len(h)}`;视图别名 `h`, + 从不单独释放。 - **边界情况:** 零拷贝且只读;`h == NULL` 属于契约之外。 ## 容量 @@ -295,16 +279,15 @@ sx_view_t sx_view(const sx_t *h); sx_t *sx_reserve(sx_t *self, size_t min_cap); ``` -确保能容纳至少 `min_cap` 个内容字节外加结尾符。 +确保容纳至少 `min_cap` 个内容字节外加结尾符。 -- **参数:** `self` —— 缓冲区;`min_cap` —— 必须能在后续操作中直接容纳的 - 内容字节数。 -- **返回:** 成功时(包括无需操作的请求)返回 `self`;分配失败时返回 - `NULL`。 -- **所有权:** 返回的 `self` 仍归调用方所有;内容与长度保持不变。 -- **边界情况:** 成功后 `cap >= min_cap + 1`。当前容量已经满足的请求不会 - 缩小或改变容量。容量只增不减;`sx_truncate` 和 `sx_clear` 从不回收。 - 底层数组可能搬移,之后必须重新获取所有 `sx_buf_mut` 指针。 +- **参数:** `self` —— 缓冲区;`min_cap` —— 后续操作中必须直接容纳的内容 + 字节数。 +- **返回:** 成功时(含无需操作的请求)返回 `self`;分配失败返回 `NULL`。 +- **所有权:** `self` 仍归调用方所有;内容与长度不变。 +- **边界情况:** 成功后 `cap >= min_cap + 1`;当前容量已满足的请求不会 + 缩小容量。容量只增不减(`sx_truncate`、`sx_clear` 从不回收),且底层 + 数组可能搬移,之后必须重新获取 `sx_buf_mut` 指针。 ```c buf = sx_reserve(buf, 4096); /* cap >= 4097 */ @@ -318,15 +301,15 @@ buf = sx_reserve(buf, 4096); /* cap >= 4097 */ sx_t *sx_append(sx_t *self, sx_t *owned); ``` -追加另一个缓冲区的内容,并消耗该缓冲区。 +追加另一缓冲区的内容并消耗该缓冲区。 - **参数:** `self` —— 目标;`owned` —— 内容被追加的源。 -- **返回:** `self`;`owned == NULL` 或分配失败时返回 `NULL`。 -- **所有权:** 所有权转移:调用读取 `owned` 的内容后将其释放。此后不得 - 再使用或释放 `owned`。 -- **边界情况:** 字节精确:按内容长度处理,内嵌的 `'\0'` 字节也会被追加。 - `owned == NULL` 时不做任何修改。`self` 可能重新分配。把 `self` 作为 - `owned` 传入属于契约之外(它会在使用中被释放)。 +- **返回:** `self`;`owned == NULL` 或分配失败返回 `NULL`。 +- **所有权:** 所有权转移 —— 复制 `owned` 的内容后将其释放;此后不得使用 + 或释放 `owned`。 +- **边界情况:** 按内容长度字节精确处理,内嵌 `'\0'` 也会追加; + `owned == NULL` 时不做修改;`self` 可能重新分配;把 `self` 作为 + `owned` 传入属于契约之外(会在使用中被释放)。 ### sx_append_cstr @@ -334,13 +317,13 @@ sx_t *sx_append(sx_t *self, sx_t *owned); sx_t *sx_append_cstr(sx_t *self, const char *s); ``` -追加一个 C 字符串。 +追加 C 字符串。 -- **参数:** `self` —— 目标;`s` —— 以 NUL 结尾的源。 -- **返回:** `self`;`s == NULL` 或分配失败时返回 `NULL`。 +- **参数:** `self` —— 目标;`s` —— NUL 结尾的源。 +- **返回:** `self`;`s == NULL` 或分配失败返回 `NULL`。 - **所有权:** 无;只读取 `s`。 -- **边界情况:** `strlen` 语义 —— 内嵌的 `'\0'` 会截断追加的字节。追加 - `""` 是空操作,返回 `self`。 +- **边界情况:** `strlen` 语义,内嵌 `'\0'` 截断追加字节;追加 `""` 是 + 空操作,返回 `self`。 ### sx_append_view @@ -350,12 +333,12 @@ sx_t *sx_append_view(sx_t *self, sx_view_t v); 追加视图中的字节。 -- **参数:** `self` —— 目标;`v` —— 源窗口;从 `v.ref->ptr + v.offset` - 读取 `v.len` 个字节。 -- **返回:** `self`;分配失败时返回 `NULL`。 +- **参数:** `self` —— 目标;`v` —— 源窗口;从 + `v.ref->ptr + v.offset` 读取 `v.len` 个字节。 +- **返回:** `self`;分配失败返回 `NULL`。 - **所有权:** 无;只读取 `v`。 -- **边界情况:** 字节精确且二进制安全。`v` 可以是 `self` 的别名,追加导致 - 缓冲区增长时也一样:用 `sx_append_view(h, sx_view(h))` 原地翻倍是支持的。 +- **边界情况:** 字节精确且二进制安全;`v` 可为 `self` 的别名,增长时 + 也一样 —— `sx_append_view(h, sx_view(h))` 原地翻倍受支持。 `v.ref == NULL` 或越界窗口属于契约之外。 ```c @@ -370,17 +353,19 @@ buf = sx_append_view(buf, sx_view(buf)); /* doubles in place */ sx_t *sx_write(sx_t *self, size_t idx, sx_t *owned); ``` -从 `idx` 开始覆盖写入字节,必要时扩展长度,并消耗源缓冲区。 +从 `idx` 起覆盖写入,必要时扩展长度,并消耗源缓冲区。 -- **参数:** `self` —— 目标;`idx` —— 第一个被覆盖的字节;`owned` —— - 内容被写入的源。 -- **返回:** `self`;`owned == NULL` 或分配失败时返回 `NULL`。 -- **所有权:** 所有权转移:调用读取 `owned` 的内容后将其释放。此后不得 - 再使用或释放它。 -- **边界情况:** 调用后 `len' = max(len, idx + owned.len)` —— 写入从不 - 缩短缓冲区。`idx == len` 等价于追加;`idx < len` 原地覆盖;`idx > len` - 会扩展长度,且 `[len, idx)` 区间的字节是**未指定的**。把 `self` 作为 - `owned` 传入,或 `idx + n` 使 `size_t` 溢出,都属于契约之外。 +- **参数:** `self` —— 目标;`idx` —— 首个被覆盖字节;`owned` —— 内容 + 被写入的源。 +- **返回:** `self`;`owned == NULL`、写入范围无法预留或分配失败时返回 + `NULL`。 +- **所有权:** 所有权转移 —— 复制内容后释放 `owned`;此后不得使用或 + 释放它。即使写入失败,`owned` 也会被释放。 +- **边界情况:** `len' = max(len, idx + owned.len)`,写入从不缩短缓冲区。 + `idx == len` 等价追加;`idx < len` 原地覆盖;`idx > len` 会扩展,且 + `[len, idx)` 为**未指定**。若 `idx + n` 使 `size_t` 溢出,或结果末端 + 无法预留(总内容长度为 `SIZE_MAX` 时放不下结尾符),调用在拷贝前返回 + `NULL`,`self` 保持不变。把 `self` 作为 `owned` 传入属于契约之外。 ```c buf = sx_new_from_cstr("abc"); @@ -393,14 +378,15 @@ buf = sx_write_cstr(buf, 6, "XY"); /* len 8; bytes 3..5 unspecified */ sx_t *sx_write_cstr(sx_t *self, size_t idx, const char *s); ``` -在 `idx` 处写入一个 C 字符串。 +在 `idx` 处写入 C 字符串。 -- **参数:** `self` —— 目标;`idx` —— 第一个写入位置;`s` —— 以 NUL - 结尾的源。 -- **返回:** `self`;`s == NULL` 或分配失败时返回 `NULL`。 +- **参数:** `self` —— 目标;`idx` —— 首个写入位置;`s` —— NUL 结尾的 + 源。 +- **返回:** `self`;`s == NULL`、写入范围无法预留或分配失败时返回 + `NULL`。 - **所有权:** 无;只读取 `s`。 -- **边界情况:** `strlen` 语义(内嵌的 `'\0'` 会截断写入的字节)。 - `s == NULL` 时 `self` 保持不变。`idx` 与填充规则同 `sx_write`。 +- **边界情况:** `strlen` 语义(内嵌 `'\0'` 截断写入字节);`s == NULL` + 时 `self` 不变。范围校验、`idx` 与填充规则同 `sx_write`。 ### sx_write_view @@ -410,12 +396,13 @@ sx_t *sx_write_view(sx_t *self, size_t idx, sx_view_t v); 在 `idx` 处写入视图中的字节。 -- **参数:** `self` —— 目标;`idx` —— 第一个写入位置;`v` —— 源窗口。 -- **返回:** `self`;分配失败时返回 `NULL`。 +- **参数:** `self` —— 目标;`idx` —— 首个写入位置;`v` —— 源窗口。 +- **返回:** `self`;写入范围无法预留或分配失败时返回 `NULL`。 - **所有权:** 无;只读取 `v`。 -- **边界情况:** 字节精确且二进制安全。`v` 可以是 `self` 的别名,写入需要 - 增长缓冲区时也一样(源字节在预留空间的过程中保持有效)。`idx` 与填充 - 规则同 `sx_write`;越界窗口属于契约之外。 +- **边界情况:** 字节精确且二进制安全;`v` 可为 `self` 的别名,写入需要 + 增长时也一样(源字节在预留空间后仍有效)。溢出检查先于保留别名的预 + 预留执行,因此被拒绝的范围不会改变目标容量。`idx` 与填充规则同 + `sx_write`;越界窗口属于契约之外。 ## 插入 @@ -425,16 +412,16 @@ sx_t *sx_write_view(sx_t *self, size_t idx, sx_view_t v); sx_t *sx_insert(sx_t *self, size_t idx, sx_t *owned); ``` -在 `idx` 处插入另一个缓冲区的内容,尾部右移,并消耗该缓冲区。 +在 `idx` 处插入另一缓冲区的内容,尾部右移,并消耗该缓冲区。 - **参数:** `self` —— 目标;`idx` —— 插入点,要求 `0 <= idx <= len`; `owned` —— 内容被插入的源。 -- **返回:** `self`;`owned == NULL` 或分配失败时返回 `NULL`。 -- **所有权:** 所有权转移:调用读取 `owned` 的内容后将其释放。此后不得 - 再使用或释放它。 +- **返回:** `self`;`owned == NULL` 或分配失败返回 `NULL`。 +- **所有权:** 所有权转移 —— 复制内容后释放 `owned`;此后不得使用或 + 释放它。 - **边界情况:** 结果为 `[0, idx)` ++ 插入字节 ++ `[idx, len)`, - 且 `len' = len + n`。`idx == len` 等价于追加。`idx > len` 属于契约之外 - (尾部移动会下溢);把 `self` 作为 `owned` 传入属于契约之外。 + `len' = len + n`;`idx == len` 等价追加。`idx > len` 属于契约之外 + (尾部移动会下溢);把 `self` 作为 `owned` 传入也属于契约之外。 ```c buf = sx_insert_cstr(buf, 3, "-"); /* shift the tail right */ @@ -446,13 +433,13 @@ buf = sx_insert_cstr(buf, 3, "-"); /* shift the tail right */ sx_t *sx_insert_cstr(sx_t *self, size_t idx, const char *s); ``` -在 `idx` 处插入一个 C 字符串。 +在 `idx` 处插入 C 字符串。 - **参数:** `self` —— 目标;`idx` —— 插入点,要求 `0 <= idx <= len`; - `s` —— 以 NUL 结尾的源。 -- **返回:** `self`;`s == NULL` 或分配失败时返回 `NULL`。 + `s` —— NUL 结尾的源。 +- **返回:** `self`;`s == NULL` 或分配失败返回 `NULL`。 - **所有权:** 无;只读取 `s`。 -- **边界情况:** `strlen` 语义;`s == NULL` 时 `self` 保持不变。`idx > len` +- **边界情况:** `strlen` 语义;`s == NULL` 时 `self` 不变。`idx > len` 属于契约之外。 ### sx_insert_view @@ -465,13 +452,13 @@ sx_t *sx_insert_view(sx_t *self, size_t idx, sx_view_t v); - **参数:** `self` —— 目标;`idx` —— 插入点,要求 `0 <= idx <= len`; `v` —— 源窗口。 -- **返回:** `self`;分配失败时返回 `NULL`。 +- **返回:** `self`;分配失败返回 `NULL`。 - **所有权:** 无;只读取 `v`。 -- **边界情况:** 字节精确且二进制安全。`v` 可以是 `self` 的别名,插入 - 导致缓冲区增长时也一样,但前提是视图窗口的起始偏移不大于 `idx`(测试 - 覆盖的即插入点处的切片);起始偏移大于 `idx` 的自别名窗口会被尾部右移 - 覆盖,属于**契约之外** —— 请先用 `sx_new_from_view` 复制该切片。 - `idx > len` 和越界视图属于契约之外。 +- **边界情况:** 字节精确且二进制安全;`v` 可为 `self` 的别名,插入增长 + 时也一样,但窗口起始偏移不得大于 `idx`(测试覆盖插入点处的切片)。 + 起始偏移大于 `idx` 的自别名窗口会被尾部右移覆盖,属于**契约之外** —— + 先用 `sx_new_from_view` 复制该切片。`idx > len` 和越界视图属于契约 + 之外。 ## 截断、删除与清空 @@ -484,12 +471,11 @@ sx_t *sx_truncate(sx_t *self, size_t new_len); 把内容长度设为 `new_len`。 - **参数:** `self` —— 缓冲区;`new_len` —— 新的内容字节长度。 -- **返回:** 成功时返回 `self`;增长过程中分配失败时返回 `NULL`。 -- **所有权:** 返回的 `self` 仍归调用方所有。 -- **边界情况:** 更短的 `new_len` 保留前缀并丢弃尾部;相同的 `new_len` - 是空操作。更长的 `new_len` 会扩展缓冲区:`len` 变为 `new_len`, - `ptr[new_len] == '\0'`,而 `[old_len, new_len)` 区间的字节是**未指定的** - —— 在覆盖它们之前不要读取。收缩不会回收容量。 +- **返回:** `self`;增长中分配失败返回 `NULL`。 +- **边界情况:** 更短的 `new_len` 保留前缀、丢弃尾部;相同值无操作。 + 更长的 `new_len` 会扩展:`len` 变为 `new_len`,`ptr[new_len] == '\0'`, + 且 `[old_len, new_len)` 为**未指定** —— 覆盖前不要读取。收缩不回收 + 容量。 ### sx_erase @@ -499,12 +485,11 @@ sx_t *sx_erase(sx_t *self, size_t idx, size_t n); 删除从 `idx` 开始的 `n` 个字节,尾部左移。 -- **参数:** `self` —— 缓冲区;`idx` —— 第一个被删除的字节;`n` —— 要 - 删除的字节数。 -- **返回:** `self`。 -- **所有权:** 返回的 `self` 仍归调用方所有;`self` 本身必须有效。 +- **参数:** `self` —— 缓冲区;`idx` —— 首个被删除字节;`n` —— 删除 + 字节数。 +- **返回:** `self`;`self` 本身必须有效。 - **边界情况:** `idx + n == len` 删除后缀;`idx + n > len` 是空操作,原样 - 返回 `self`;`n == 0` 是空操作。调用不进行分配,因此不会失败。 + 返回 `self`;`n == 0` 是空操作。调用不分配,因此不会失败。 `idx + n` 使 `size_t` 溢出属于契约之外。 ```c @@ -520,10 +505,9 @@ sx_t *sx_clear(sx_t *self); 清空缓冲区,保留容量。 - **参数:** `self` —— 缓冲区。 -- **返回:** `self`。 -- **所有权:** 返回的 `self` 仍归调用方所有。 -- **边界情况:** 设置 `len = 0` 和 `ptr[0] = '\0'`;分配及其容量保留, - 缓冲区可以立即复用。 +- **返回:** `self`(仍归调用方所有)。 +- **边界情况:** 设置 `len = 0`、`ptr[0] = '\0'`;分配与容量保留,缓冲区 + 可立即复用。 ```c buf = sx_clear(buf); /* len 0, capacity kept */ @@ -537,15 +521,15 @@ buf = sx_clear(buf); /* len 0, capacity kept */ sx_t *sx_substr(const sx_t *h, size_t idx, size_t n); ``` -把字节区间 `[idx, idx + n)` 拷贝到一个新的独立缓冲区。 +把 `[idx, idx + n)` 拷贝为新的独立缓冲区。 - **参数:** `h` —— 源缓冲区;`idx` —— 起始偏移;`n` —— 字节数,前置 - 条件为 `idx + n <= len(h)`。 -- **返回:** 新的调用方所有的缓冲区;分配失败时返回 `NULL`。(`h` 为 - NULL 或区间越界属于契约之外,而不是错误返回值。) -- **所有权:** 调用方所有;用 `sx_free` 释放。 -- **边界情况:** `n == 0` 得到空缓冲区。字节精确且二进制安全,包括内嵌的 - `'\0'` 字节。与视图移动不同,这里是拷贝:任一侧的修改都不会影响另一侧。 + 条件 `idx + n <= len(h)`。 +- **返回:** 新缓冲区;分配失败返回 `NULL`。(`h` 为 NULL 或区间越界 + 属于契约之外,而非错误返回值。) +- **所有权:** 调用方所有;`sx_free` 释放。 +- **边界情况:** `n == 0` 得到空缓冲区;字节精确且二进制安全(含内嵌 + `'\0'`)。与视图移动不同,这里是拷贝:任一侧修改都不影响另一侧。 ```c sx_t *word = sx_substr(buf, 6, 5); /* a copy, not a view */ @@ -554,9 +538,9 @@ sx_free(word); ## 视图移动 -这四个函数都在已有缓冲区上重新推导 `(offset, len)` 窗口。它们都不拷贝 -字节、不修改缓冲区,只返回新的视图值。输入必须是合法视图(`ref != NULL` -且窗口位于缓冲区内);非法输入属于契约之外。 +四个函数都在已有缓冲区上重新推导 `(offset, len)` 窗口;不拷贝、不修改、 +不转移所有权,只返回新视图值。输入必须是合法视图(`ref != NULL` 且窗口 +在缓冲区内),否则属于契约之外。 ### sx_view_advance @@ -564,18 +548,17 @@ sx_free(word); sx_view_t sx_view_advance(sx_view_t v, size_t n); ``` -把窗口起点向右移动 `n`。 +把窗口起点右移 `n`。 -- **参数:** `v` —— 输入视图;`n` —— 前进的字节数。 +- **参数:** `v` —— 输入视图;`n` —— 前进字节数。 - **返回:** 同一缓冲区上调整后的视图。 -- **所有权:** 无。 - **边界情况:** 设 `H = len(ref)`: - - 若 `offset + len + n < H`,保持终点不动,`len` 精确减少 `n`; + - 若 `offset + len + n < H`,终点不动,`len` 减少 `n`; - 否则若 `offset + n < H`,起点变为 `offset + n`,终点夹紧到缓冲区 末尾(`len = H - offset`); - 否则结果为空视图 `(H, 0)`。 - 即使 `n` 很大,前进也永远不会越过缓冲区末尾;而把子视图推进到其自身 - 终点之外时,会按第二种情况扩展到缓冲区末尾,这是契约规定的行为。 + `n` 再大也不会越过缓冲区末尾;把子视图推进到自身终点之外时,会按 + 第二种情况扩展到缓冲区末尾。 ```c sx_view_t rest = sx_view_advance(sx_view(buf), 2); /* start +2 */ @@ -587,13 +570,12 @@ sx_view_t rest = sx_view_advance(sx_view(buf), 2); /* start +2 */ sx_view_t sx_view_retreat(sx_view_t v, size_t n); ``` -把窗口起点向左移动 `n`,保持终点不动。 +把窗口起点左移 `n`,终点不动。 -- **参数:** `v` —— 输入视图;`n` —— 后退的字节数。 +- **参数:** `v` —— 输入视图;`n` —— 后退字节数。 - **返回:** 同一缓冲区上调整后的视图。 -- **所有权:** 无。 -- **边界情况:** `len` 增加的量等于偏移减少的量;移动在偏移 0 处饱和 - (`len` 变为原来的 `offset + len`),因此窗口永远不会从缓冲区之前开始。 +- **边界情况:** `len` 增加量等于偏移减少量;移动在偏移 0 处饱和 + (`len` 变为原 `offset + len`),窗口不会从缓冲区之前开始。 ### sx_view_shift @@ -601,14 +583,13 @@ sx_view_t sx_view_retreat(sx_view_t v, size_t n); sx_view_t sx_view_shift(sx_view_t v, ptrdiff_t off); ``` -按有符号偏移移动窗口,保持长度不变。 +按有符号偏移移动窗口,保持长度。 - **参数:** `v` —— 输入视图;`off` —— 有符号字节偏移。 - **返回:** 同一缓冲区上调整后的视图。 -- **所有权:** 无。 -- **边界情况:** 与 advance/retreat 不同,`len` 保持不变。正的 `off` 若会 - 把终点推过缓冲区,则夹紧为 `offset = H - len`(窗口停在缓冲区末尾); - 负的 `off` 使起点饱和在 0。空缓冲区上的结果是 `(0, 0)`。 +- **边界情况:** `len` 不变(不同于 advance/retreat)。正 `off` 若把终点 + 推过缓冲区,则夹紧为 `offset = H - len`(停在缓冲区末尾);负 `off` + 使起点饱和在 0。空缓冲区上结果为 `(0, 0)`。 ### sx_view_range @@ -618,11 +599,10 @@ sx_view_t sx_view_range(sx_view_t v, size_t off, size_t len); 按绝对坐标重新锚定窗口,忽略输入视图的偏移和长度。 -- **参数:** `v` —— 只提供底层缓冲区;`off` —— 绝对起始偏移,前置条件为 - `off <= H`;`len` —— 请求的长度。 +- **参数:** `v` —— 只提供底层缓冲区;`off` —— 绝对起始偏移,前置条件 + `off <= H`;`len` —— 请求长度。 - **返回:** 视图 `(off, min(len, H - off))`。 -- **所有权:** 无。 -- **边界情况:** 长度会夹紧到缓冲区末尾;`off == H` 得到 `(H, 0)`; +- **边界情况:** 长度夹紧到缓冲区末尾;`off == H` 得 `(H, 0)`; `off > H` 属于契约之外(`H - off` 下溢)。 ```c @@ -631,9 +611,9 @@ sx_view_t slice = sx_view_range(sx_view(buf), 2, 3); /* absolute (2, 3) */ ## 视图裁剪 -裁剪家族从视图两端移除 ASCII 空白字符。空白集合恰为 -`{space, '\t', '\v', '\f', '\r', '\n'}`。不会修改任何缓冲区字节,也只 -检查窗口内部的字节。 +裁剪家族移除视图两端的 ASCII 空白。空白集合恰为 +`{space, '\t', '\v', '\f', '\r', '\n'}`。不修改缓冲区、不涉及所有权, +只检查窗口内字节。 ### sx_view_trim @@ -641,15 +621,13 @@ sx_view_t slice = sx_view_range(sx_view(buf), 2, 3); /* absolute (2, 3) */ sx_view_t sx_view_trim(sx_view_t v); ``` -裁剪视图的两端。 +裁剪视图两端。 - **参数:** `v` —— 输入视图。 -- **返回:** 去掉首尾空白后的视图。 -- **所有权:** 无。 -- **边界情况:** 等价于 `sx_view_trim_back(sx_view_trim_front(v))`。两端都 - 没有空白的视图原样返回。内容全为空白的视图会变成窗口末尾处的空视图 - (偏移为 `offset + len`,长度为 0)—— 对整个缓冲区的视图而言就是 - `(H, 0)`。 +- **返回:** 去掉首尾空白的视图。 +- **边界情况:** 等价于 `sx_view_trim_back(sx_view_trim_front(v))`。两端 + 无空白的视图原样返回。全空白视图变为窗口末尾处的空视图(偏移 + `offset + len`,长度 0)—— 整缓冲区视图即 `(H, 0)`。 ```c sx_view_t field = sx_view_trim(sx_view(buf)); /* strip ASCII whitespace */ @@ -664,10 +642,9 @@ sx_view_t sx_view_trim_front(sx_view_t v); 去掉前导空白。 - **参数:** `v` —— 输入视图。 -- **返回:** 去掉前导空白后的视图。 -- **所有权:** 无。 -- **边界情况:** 偏移右移,`len` 相应减少,因此窗口终点保持不动。扫描受 - 视图自身长度的限制,即使窗口之后缓冲区里仍有空白,也不会越过窗口末尾。 +- **返回:** 去掉前导空白的视图。 +- **边界情况:** 偏移右移、`len` 相应减少,窗口终点不动。扫描受视图自身 + 长度限制,即使窗口之后缓冲区仍有空白,也不会越过窗口末尾。 ### sx_view_trim_back @@ -678,17 +655,14 @@ sx_view_t sx_view_trim_back(sx_view_t v); 去掉尾部空白。 - **参数:** `v` —— 输入视图。 -- **返回:** 去掉尾部空白后的视图。 -- **所有权:** 无。 -- **边界情况:** 只检查窗口的最后一个字节(`offset + len - 1`),`len` - 向左收缩;偏移保持不变,因此全为空白的窗口会变成 `(offset, 0)`。窗口 - 之外的字节永远不会被检查。 +- **返回:** 去掉尾部空白的视图。 +- **边界情况:** 只检查窗口最后一个字节(`offset + len - 1`),`len` 向左 + 收缩;偏移不变,全空白窗口变为 `(offset, 0)`。窗口之外的字节永不检查。 ## 完整示例 -下面这个程序构造一个字符串,裁剪它的一个视图,把裁剪后的窗口拷贝到新 -缓冲区,原地修改该缓冲区,最后释放两个缓冲区。按原样与库源码一起即可 -编译,也是普通应用程序的典型写法: +下面程序构造字符串、裁剪其视图、把裁剪窗口拷贝为新缓冲区、原地修改并 +释放两个缓冲区: ```c #include diff --git a/docs/zh_cn/api-search.md b/docs/zh_cn/api-search.md index 587ead1..d5c8cbc 100644 --- a/docs/zh_cn/api-search.md +++ b/docs/zh_cn/api-search.md @@ -4,10 +4,10 @@ # 查找、比较与分割 -本页是查找家族(`sx_find*`、`sx_rfind*`、`sx_find_all*`)、比较家族 -(`sx_cmp*`、`sx_starts_with*`、`sx_ends_with*`)以及 `sx_split` 的完整 -参考。它们全部字节精确,并按内容长度工作,因此内嵌的 NUL 字节是普通 -数据。缓冲区的创建、修改与视图见[缓冲区与视图](api-buffer.md)。 +本页涵盖查找(`sx_find*`、`sx_rfind*`、`sx_find_all*`)、比较 +(`sx_cmp*`、`sx_starts_with*`、`sx_ends_with*`)与 `sx_split` API。全部 +字节精确并按内容长度工作,内嵌 NUL 字节是普通数据;缓冲区、修改与视图 +见[缓冲区与视图](api-buffer.md)。 ## 约定 @@ -20,13 +20,13 @@ | `_cstr` | `const char *` | `strlen(...)` 个字节 | 第一个 NUL 结束 needle | | `_char` | `char` | 恰好一个字节 | `'\0'` 表示一个 NUL 内容字节 | -owned 形式和 view 形式是二进制安全的:它们精确读取 needle 的长度,因此 -内嵌的 `'\0'` 会作为数据参与匹配。`_cstr` 形式使用 `strlen`,所以 -`sx_find_cstr(h, "a\0c")` 实际查找的是 `"a"`;要查找二进制模式,请使用 -owned 或 view 形式的 needle。空的 needle(长度为 0)永远不会被找到。 +owned 与 view 形式二进制安全:精确读取 needle 长度,内嵌 `'\0'` 作为 +数据参与匹配。`_cstr` 形式使用 `strlen`,所以 +`sx_find_cstr(h, "a\0c")` 实际查找 `"a"`;二进制模式请用 owned/view +needle。长度为 0 的 needle 永远不会被找到。 -**有界区域。** 设 `H` 为被查找缓冲区的内容长度,needle 长度为 `m`,一次匹配是窗口 -`[p, p + m)`,它必须完全位于被搜索的区域之内: +**有界区域。** 设 `H` 为被查找缓冲区的内容长度、needle 长度为 `m`,一次 +匹配是窗口 `[p, p + m)`,必须完全位于被搜索区域之内: | 函数 | 搜索区域 | 窗口条件 | | --- | --- | --- | @@ -34,26 +34,24 @@ owned 或 view 形式的 needle。空的 needle(长度为 0)永远不会被 | `sx_find_view_b(h, needle, boundary)` | `[boundary, H)` | `p >= boundary` 且 `p + m <= H` | | `sx_rfind_view_b(h, needle, boundary)` | `[0, min(boundary, H))` | `p + m <= min(boundary, H)` | -两个有界形式都接收 `size_t boundary`,但方向相反:`sx_find_view_b` 从 -左侧限定区域,起点早于 `boundary` 的窗口不计入;`sx_rfind_view_b` 从右侧 -限定区域,终点晚于边界的窗口不计入。下面是测试中的具体用例,取 -`h = "ababa"`,needle 为 `"ba"`: - -- `sx_find_view_b(h, nd, 2)` 为 3 —— 偏移 1 处的匹配起点在边界之前,不计 - 入;boundary 为 4 时返回 `(size_t)-1`,因为剩余区域 `"a"` 放不下一个 - 窗口。 -- `sx_rfind_view_b(h, nd, 3)` 为 1 —— 偏移 3 处的匹配终止于 5,越过了 - 边界;boundary 为 2 时返回 `(size_t)-1`;若 needle 为 `"aba"` 且 - boundary 为 3,窗口 `[0, 3)` 恰好终止于边界,结果为 0。 -- 对 `sx_find_view_b` 而言,`boundary >= H` 是空区域,返回 `(size_t)-1`。 - 对 `sx_rfind_view_b` 而言,大于等于 `H` 的 boundary 会夹紧到 `H`, - 等价于无界的最右查找。 - -**二进制安全。** 被查找的缓冲区始终按内容长度(`H`)处理,而不是按 -C 字符串:内嵌的 `'\0'` 字节是普通字节,`ptr[H]` 处的结尾符不属于搜索 -区域。特别地,`sx_find_char(h, '\0')` 只报告内嵌的 NUL 内容字节,永远不会 -匹配结尾符。owned 和 view 形式的 needle 同样按长度读取;只有 `_cstr` -形式的 needle 会在第一个 NUL 处停止。 +两个有界形式都接收 `size_t boundary`,方向相反:`sx_find_view_b` 从左侧 +限定区域(起点早于 `boundary` 的窗口不计入);`sx_rfind_view_b` 从右侧 +限定区域(终点晚于边界的窗口不计入)。测试用例取 `h = "ababa"`、needle +为 `"ba"`: + +- `sx_find_view_b(h, nd, 2)` 为 3(偏移 1 处的匹配起点在边界之前); + boundary 为 4 时返回 `(size_t)-1` —— 只剩 `"a"`,放不下一个窗口。 +- `sx_rfind_view_b(h, nd, 3)` 为 1(偏移 3 处的匹配终止于 5,越过边界); + boundary 为 2 时返回 `(size_t)-1`;needle 为 `"aba"`、boundary 为 3 时 + 结果为 0 —— 窗口 `[0, 3)` 恰好终止于边界。 +- 对 `sx_find_view_b`,`boundary >= H` 是空区域,返回 `(size_t)-1`;对 + `sx_rfind_view_b`,大于等于 `H` 的 boundary 夹紧到 `H`,等价于无界 + 最右查找。 + +**二进制安全。** 被查找缓冲区始终按内容长度(`H`)处理而非 C 字符串: +内嵌 `'\0'` 是普通字节,`ptr[H]` 处的结尾符不属于搜索区域。因此 +`sx_find_char(h, '\0')` 只找到内嵌 NUL 内容字节。owned/view needle 也按 +长度读取;只有 `_cstr` needle 在第一个 NUL 处停止。 **哨兵值与 NULL。** @@ -65,18 +63,17 @@ C 字符串:内嵌的 `'\0'` 字节是普通字节,`ptr[H]` 处的结尾符 | `sx_starts_with*`、`sx_ends_with*` | `0` | | `sx_split` | `NULL` | -查找函数会检查指针参数:`h` 为 NULL 或 needle 参数为 NULL 时返回该家族 -的哨兵值,而不是崩溃。对 view 形式而言,`v.ref == NULL` 属于契约之外 —— -指针在任何长度检查之前就已形成,因此务必传入指向有效缓冲区的视图。 -`sx_find_all*` 和 `sx_split` 用与“无匹配”相同的哨兵值报告分配失败;按 -契约这两者无法区分。`(size_t)-1` 不会与真实的偏移冲突,因为偏移都小于 -`INT_MAX` 个内容字节。 +查找函数检查指针参数:`h` 或 needle 参数为 NULL 时返回家族哨兵值,而不是 +崩溃。对 view 形式,`v.ref == NULL` 属于契约之外 —— 指针在任何长度检查 +之前已形成,务必传入指向有效缓冲区的视图。所有调用只读取输入、不转移 +所有权;只有 `sx_find_all*` 和 `sx_split` 的数组归调用方所有。这两个函数 +也用与“无匹配”相同的哨兵值报告分配失败,按契约两者无法区分。 +`(size_t)-1` 不会与真实偏移冲突,因为偏移都小于 `INT_MAX` 个内容字节。 **查找策略。** 单字节 needle 使用 `memchr`(向前)或逐字节反向扫描(可用 -时使用 glibc 的 `memrchr`),不进行分配。更长的 needle 使用 KMP:调用 -期间会分配一张含 `m` 个 `size_t` 的临时前缀表,因此一次查找的最坏情况为 -O(n + m)。`sx_find_all*` 还会额外返回一个 malloc 分配的结果数组,并报告 -每一次出现,包括相互重叠的出现。 +时用 glibc 的 `memrchr`),不分配内存。更长的 needle 使用 KMP:调用期间 +分配一张含 `m` 个 `size_t` 的临时前缀表并在返回前释放,一次查找最坏为 +O(n + m)。`sx_find_all*` 还额外分配结果数组,并报告每一次出现(含重叠)。 ## 如何选择调用 @@ -99,15 +96,13 @@ O(n + m)。`sx_find_all*` 还会额外返回一个 malloc 分配的结果数组 size_t sx_find(const sx_t *h, const sx_t *needle); ``` -查找另一个缓冲区的内容在 `h` 中最左的出现。 +查找另一缓冲区的内容在 `h` 中最左的出现。 -- **参数:** `h` —— 被查找的缓冲区;`needle` —— 内容被查找的缓冲区。 -- **返回:** 最左匹配的字节偏移;没有匹配时返回 `(size_t)-1`。 -- **所有权:** 无;不修改任一缓冲区。needle 长于一个字节时,调用内部会 - 分配并释放一张临时的 KMP 前缀表。 -- **边界情况:** `h` 或 `needle` 为 NULL 时返回 `(size_t)-1`;空 - needle 返回 `(size_t)-1`;比 `h` 更长的 needle 永远不会匹配。匹配按 - 内容长度字节精确进行,内嵌 NUL 同样参与匹配。 +- **参数:** `h` —— 被查找缓冲区;`needle` —— 内容被查找的缓冲区。 +- **返回:** 最左匹配的字节偏移,或 `(size_t)-1`。 +- **边界情况:** `h` 或 `needle` 为 NULL 返回 `(size_t)-1`;空 needle + 返回 `(size_t)-1`;比 `h` 更长的 needle 永不匹配。按内容长度字节精确 + 匹配,内嵌 NUL 也参与。 ### sx_find_view @@ -115,15 +110,14 @@ size_t sx_find(const sx_t *h, const sx_t *needle); size_t sx_find_view(const sx_t *h, sx_view_t needle); ``` -查找视图中的字节在整串中最左的出现。 +查找视图字节在整串中最左的出现。 -- **参数:** `h` —— 被查找的缓冲区;`needle` —— 其 `needle.len` 个 - 字节被查找的窗口。 +- **参数:** `h` —— 被查找缓冲区;`needle` —— 其 `needle.len` 个字节被 + 查找的窗口。 - **返回:** 最左匹配的字节偏移,或 `(size_t)-1`。 -- **所有权:** 无;只读取。 - **边界情况:** 等价于 `sx_find_view_b(h, needle, 0)`。空视图 - (`len == 0`)永远不会被找到。`needle.ref == NULL` 或越界窗口属于 - 契约之外。 + (`len == 0`)永不被找到。`needle.ref == NULL` 或越界窗口属于契约 + 之外。 ### sx_find_view_b @@ -131,15 +125,14 @@ size_t sx_find_view(const sx_t *h, sx_view_t needle); size_t sx_find_view_b(const sx_t *h, sx_view_t needle, size_t boundary); ``` -查找视图中的字节在 `boundary` 处或之后最左的出现。 +查找视图字节在 `boundary` 处或之后最左的出现。 -- **参数:** `h` —— 被查找的缓冲区;`needle` —— 要查找的窗口; +- **参数:** `h` —— 被查找缓冲区;`needle` —— 要查找的窗口; `boundary` —— 区域起始偏移。 - **返回:** `[boundary, H)` 内最左匹配的字节偏移,或 `(size_t)-1`。 -- **所有权:** 无;只读取。 -- **边界情况:** 匹配必须起始于 `boundary` 处或之后,并终止于 `H` 处或 - 之前;跨过边界的窗口不算匹配。`boundary >= H`、区域放不下一个窗口、 - 以及空 needle 都返回 `(size_t)-1`。`needle.ref == NULL`、越界窗口,或 +- **边界情况:** 匹配必须起始于 `boundary` 处或之后、终止于 `H` 处或 + 之前;跨边界的窗口不算。`boundary >= H`、区域放不下一个窗口、空 + needle 都返回 `(size_t)-1`。`needle.ref == NULL`、越界窗口,或 `boundary + needle.len` 使 `size_t` 溢出,属于契约之外。 ```c @@ -158,13 +151,12 @@ size_t sx_find_cstr(const sx_t *h, const char *needle); 查找 C 字符串在 `h` 中最左的出现。 -- **参数:** `h` —— 被查找的缓冲区;`needle` —— 以 NUL 结尾的模式,按 +- **参数:** `h` —— 被查找缓冲区;`needle` —— NUL 结尾的模式,按 `strlen` 读取。 - **返回:** 最左匹配的字节偏移,或 `(size_t)-1`。 -- **所有权:** 无;只读取。 -- **边界情况:** `h` 或 `needle` 为 NULL 时返回 `(size_t)-1`;空 needle - 返回 `(size_t)-1`。needle 中不能包含字面 NUL;二进制模式请使用 - `sx_find_view`。被查找的缓冲区可以包含 NUL。 +- **边界情况:** `h` 或 `needle` 为 NULL 返回 `(size_t)-1`;空 needle + 返回 `(size_t)-1`。needle 不能含字面 NUL,二进制模式用 + `sx_find_view`;被查找缓冲区可以含 NUL。 ### sx_find_char @@ -174,12 +166,10 @@ size_t sx_find_char(const sx_t *h, char c); 查找单个字节最左的出现。 -- **参数:** `h` —— 被查找的缓冲区;`c` —— 要查找的字节。 +- **参数:** `h` —— 被查找缓冲区;`c` —— 要查找的字节。 - **返回:** 最左出现的字节偏移,或 `(size_t)-1`。 -- **所有权:** 无;只读取。 -- **边界情况:** `h` 为 NULL 时返回 `(size_t)-1`。搜索只覆盖内容 - (`[0, H)`),因此 `c == '\0'` 会找到内嵌的 NUL 内容字节,但永远不会 - 匹配结尾符。 +- **边界情况:** `h` 为 NULL 返回 `(size_t)-1`。只搜索内容(`[0, H)`), + 因此 `c == '\0'` 找到内嵌 NUL 内容字节,永不匹配结尾符。 ## 最右查找:`sx_rfind*` @@ -189,15 +179,13 @@ size_t sx_find_char(const sx_t *h, char c); size_t sx_rfind(const sx_t *h, const sx_t *needle); ``` -查找另一个缓冲区的内容在 `h` 中最右的出现。 +查找另一缓冲区的内容在 `h` 中最右的出现。 -- **参数:** `h` —— 被查找的缓冲区;`needle` —— 内容被查找的缓冲区。 +- **参数:** `h` —— 被查找缓冲区;`needle` —— 内容被查找的缓冲区。 - **返回:** 最右匹配的字节偏移,或 `(size_t)-1`。 -- **所有权:** 无;不修改任一缓冲区。needle 长于一个字节时,调用内部会 - 分配并释放一张临时的 KMP 前缀表。 -- **边界情况:** `h` 或 `needle` 为 NULL 时返回 `(size_t)-1`;空 - needle 返回 `(size_t)-1`;比 `h` 更长的 needle 永远不会匹配。字节 - 精确且二进制安全。 +- **边界情况:** `h` 或 `needle` 为 NULL 返回 `(size_t)-1`;空 needle + 返回 `(size_t)-1`;比 `h` 更长的 needle 永不匹配。字节精确且二进制 + 安全。 ### sx_rfind_view @@ -205,14 +193,13 @@ size_t sx_rfind(const sx_t *h, const sx_t *needle); size_t sx_rfind_view(const sx_t *h, sx_view_t needle); ``` -查找视图中的字节在整串中最右的出现。 +查找视图字节在整串中最右的出现。 -- **参数:** `h` —— 被查找的缓冲区;`needle` —— 其 `needle.len` 个 - 字节被查找的窗口。 +- **参数:** `h` —— 被查找缓冲区;`needle` —— 其 `needle.len` 个字节被 + 查找的窗口。 - **返回:** 最右匹配的字节偏移,或 `(size_t)-1`。 -- **所有权:** 无;只读取。 -- **边界情况:** 等价于 `sx_rfind_view_b(h, needle, H)`。空视图永远不会 - 被找到。`needle.ref == NULL` 或越界窗口属于契约之外。 +- **边界情况:** 等价于 `sx_rfind_view_b(h, needle, H)`。空视图永不被 + 找到。`needle.ref == NULL` 或越界窗口属于契约之外。 ### sx_rfind_view_b @@ -220,16 +207,15 @@ size_t sx_rfind_view(const sx_t *h, sx_view_t needle); size_t sx_rfind_view_b(const sx_t *h, sx_view_t needle, size_t boundary); ``` -查找视图中的字节在 `boundary` 处或之前结束的最右出现。 +查找视图字节在 `boundary` 处或之前结束的最右出现。 -- **参数:** `h` —— 被查找的缓冲区;`needle` —— 要查找的窗口; +- **参数:** `h` —— 被查找缓冲区;`needle` —— 要查找的窗口; `boundary` —— 区域终止偏移(不含)。 -- **返回:** 窗口终止于 `[0, min(boundary, H))` 之内的最右匹配的字节 - 偏移,或 `(size_t)-1`。 -- **所有权:** 无;只读取。 -- **边界情况:** 匹配必须终止于 `boundary` 处或之前;伸出边界之外的 - 窗口不算匹配。boundary 为 0、区域放不下一个窗口、以及空 needle 都返回 - `(size_t)-1`。大于等于 `H` 的 boundary 会夹紧到 `H`,等价于无界的最右 +- **返回:** 窗口终止于 `[0, min(boundary, H))` 内的最右匹配的字节偏移, + 或 `(size_t)-1`。 +- **边界情况:** 匹配必须终止于 `boundary` 处或之前;伸出边界的窗口不 + 算。boundary 为 0、区域放不下一个窗口、空 needle 都返回 + `(size_t)-1`;大于等于 `H` 的 boundary 夹紧到 `H`,等价于无界最右 查找。`needle.ref == NULL` 和越界窗口属于契约之外。 ```c @@ -248,12 +234,11 @@ size_t sx_rfind_cstr(const sx_t *h, const char *needle); 查找 C 字符串在 `h` 中最右的出现。 -- **参数:** `h` —— 被查找的缓冲区;`needle` —— 以 NUL 结尾的模式,按 +- **参数:** `h` —— 被查找缓冲区;`needle` —— NUL 结尾的模式,按 `strlen` 读取。 - **返回:** 最右匹配的字节偏移,或 `(size_t)-1`。 -- **所有权:** 无;只读取。 -- **边界情况:** `h` 或 `needle` 为 NULL 时返回 `(size_t)-1`;空 needle - 返回 `(size_t)-1`。needle 中不能包含字面 NUL。 +- **边界情况:** `h` 或 `needle` 为 NULL 返回 `(size_t)-1`;空 needle + 返回 `(size_t)-1`。needle 不能含字面 NUL。 ### sx_rfind_char @@ -263,29 +248,27 @@ size_t sx_rfind_char(const sx_t *h, char c); 查找单个字节最右的出现。 -- **参数:** `h` —— 被查找的缓冲区;`c` —— 要查找的字节。 +- **参数:** `h` —— 被查找缓冲区;`c` —— 要查找的字节。 - **返回:** 最右出现的字节偏移,或 `(size_t)-1`。 -- **所有权:** 无;只读取。 -- **边界情况:** `h` 为 NULL 时返回 `(size_t)-1`。搜索只覆盖内容, - 因此 `c == '\0'` 永远不会匹配结尾符。 +- **边界情况:** `h` 为 NULL 返回 `(size_t)-1`。只搜索内容,因此 + `c == '\0'` 永不匹配结尾符。 ## 全部出现:`sx_find_all*` -这些函数返回一个 malloc 分配的 `size_t` 数组,采用“计数在前”的形式: +这些函数返回 malloc 分配的 `size_t` 数组,采用“计数在前”形式: ```text r[0] number of matches r[1 .. r[0]] ascending byte offsets of every match ``` -重叠的匹配会全部报告:`"aaaa"` 中的 `"aa"` 会在偏移 0、1、2 处各找到 -一次。这里没有结束哨兵(与 `sx_split` 和 `sx_reg_match_all` 不同), -以计数为准。 +重叠匹配全部报告:`"aaaa"` 中的 `"aa"` 在偏移 0、1、2 处各找到一次。 +这里没有结束哨兵(与 `sx_split`、`sx_reg_match_all` 不同),以计数为准。 -- **返回:** 没有匹配时返回 `NULL` —— 包括空 needle 的情况 —— 参数为 - NULL 或分配失败时同样返回 `NULL`。按契约这两种失败原因无法区分。 -- **所有权:** 调用方拥有数组,用 `free`(而不是 `sx_free`)释放。不要 - 读取超过 `r[0] + 1` 个元素。 +- **返回:** 无匹配时返回 `NULL`(含空 needle)、参数为 NULL 或分配失败 + 时同样返回 `NULL`;无匹配与分配失败按契约无法区分。 +- **所有权:** 调用方拥有数组,用 `free`(而非 `sx_free`)释放;不要读取 + 超过 `r[0] + 1` 个元素。 ```c sx_t *h = sx_new_from_cstr("ababab"); @@ -301,13 +284,12 @@ sx_free(h); size_t *sx_find_all(const sx_t *h, const sx_t *needle); ``` -收集另一个缓冲区内容的所有出现。 +收集另一缓冲区内容的所有出现。 -- **参数:** `h` —— 被查找的缓冲区;`needle` —— 内容被查找的缓冲区。 +- **参数:** `h` —— 被查找缓冲区;`needle` —— 内容被查找的缓冲区。 - **返回:** 计数在前的 `size_t` 数组;无匹配、空 needle、NULL 参数或 - 分配失败时返回 `NULL`。 -- **所有权:** 调用方所有;用 `free` 释放。 -- **边界情况:** 二进制安全;偏移按升序排列,并包含重叠的匹配。 + 分配失败返回 `NULL`。 +- **边界情况:** 二进制安全;偏移升序且包含重叠匹配。 ### sx_find_all_view @@ -315,12 +297,11 @@ size_t *sx_find_all(const sx_t *h, const sx_t *needle); size_t *sx_find_all_view(const sx_t *h, sx_view_t needle); ``` -收集视图中字节的所有出现。 +收集视图字节的所有出现。 -- **参数:** `h` —— 被查找的缓冲区;`needle` —— 要查找的窗口。 +- **参数:** `h` —— 被查找缓冲区;`needle` —— 要查找的窗口。 - **返回:** 计数在前的 `size_t` 数组;无匹配、空视图、NULL 参数或分配 - 失败时返回 `NULL`。 -- **所有权:** 调用方所有;用 `free` 释放。 + 失败返回 `NULL`。 - **边界情况:** `needle.ref == NULL` 或越界窗口属于契约之外。 ### sx_find_all_cstr @@ -331,12 +312,11 @@ size_t *sx_find_all_cstr(const sx_t *h, const char *needle); 收集 C 字符串的所有出现。 -- **参数:** `h` —— 被查找的缓冲区;`needle` —— 以 NUL 结尾的模式,按 +- **参数:** `h` —— 被查找缓冲区;`needle` —— NUL 结尾的模式,按 `strlen` 读取。 - **返回:** 计数在前的 `size_t` 数组;无匹配、空 needle、NULL 参数或 - 分配失败时返回 `NULL`。 -- **所有权:** 调用方所有;用 `free` 释放。 -- **边界情况:** needle 中不能包含字面 NUL;被查找的缓冲区可以包含。 + 分配失败返回 `NULL`。 +- **边界情况:** needle 不能含字面 NUL;被查找缓冲区可以含。 ### sx_find_all_char @@ -346,12 +326,11 @@ size_t *sx_find_all_char(const sx_t *h, char c); 收集单个字节的所有出现。 -- **参数:** `h` —— 被查找的缓冲区;`c` —— 要查找的字节。 -- **返回:** 计数在前的 `size_t` 数组;无匹配、NULL 参数或分配失败时 - 返回 `NULL`。 -- **所有权:** 调用方所有;用 `free` 释放。 -- **边界情况:** 只搜索内容,因此 `'\0'` needle 会找到内嵌的 NUL 内容 - 字节,永远不会匹配结尾符。 +- **参数:** `h` —— 被查找缓冲区;`c` —— 要查找的字节。 +- **返回:** 计数在前的 `size_t` 数组;无匹配、NULL 参数或分配失败返回 + `NULL`。 +- **边界情况:** 只搜索内容,因此 `'\0'` needle 找到内嵌 NUL 内容字节, + 永不匹配结尾符。 ## 比较:`sx_cmp*` @@ -364,13 +343,12 @@ int sx_cmp(const sx_t *h, const sx_t *other); 按内容字节对两个缓冲区做字典序比较。 - **参数:** `h` —— 左操作数;`other` —— 右操作数。 -- **返回:** `h` 排在 `other` 之前时返回负数,相等返回 0,排在之后返回 - 正数。只有符号有意义。 -- **所有权:** 无;不修改任一缓冲区。 -- **边界情况:** 比较按 `memcmp` 顺序逐字节进行(无符号字节值),因此 - `"10" < "2"`、`"Z" < "中"`。若较短字符串是另一方的真前缀,则它排在 - 前面(`"abc" < "abcd"`)。内嵌 NUL 字节按数据参与比较。任一操作数为 - NULL 时结果为 0(视为相等)—— 不要把该结果当作有意义的排序依据。 +- **返回:** `h` 排在 `other` 之前返回负数,相等返回 0,之后返回正数; + 只有符号有意义。 +- **边界情况:** 按 `memcmp` 顺序逐字节比较(无符号字节值),因此 + `"10" < "2"`、`"Z" < "中"`。较短字符串若是另一方的真前缀则排在前 + (`"abc" < "abcd"`)。内嵌 NUL 按数据比较。任一操作数为 NULL 时结果 + 为 0(视为相等)—— 不要当作有意义的排序依据。 ### sx_cmp_view @@ -378,14 +356,13 @@ int sx_cmp(const sx_t *h, const sx_t *other); int sx_cmp_view(const sx_t *h, sx_view_t other); ``` -把一个缓冲区与视图中的字节比较。 +把缓冲区与视图字节比较。 - **参数:** `h` —— 左操作数;`other` —— 右操作数窗口,比较其 `other.len` 个字节。 - **返回:** 与 `sx_cmp` 相同的负值、0 或正值。 -- **所有权:** 无;只读取。 -- **边界情况:** `h` 为 NULL 时返回 0。`other.ref == NULL` 或越界窗口 - 属于契约之外。 +- **边界情况:** `h` 为 NULL 返回 0。`other.ref == NULL` 或越界窗口属于 + 契约之外。 ### sx_cmp_cstr @@ -393,14 +370,13 @@ int sx_cmp_view(const sx_t *h, sx_view_t other); int sx_cmp_cstr(const sx_t *h, const char *s); ``` -把一个缓冲区与 C 字符串比较。 +把缓冲区与 C 字符串比较。 -- **参数:** `h` —— 左操作数;`s` —— 以 NUL 结尾的右操作数,按 - `strlen` 读取。 +- **参数:** `h` —— 左操作数;`s` —— NUL 结尾的右操作数,按 `strlen` + 读取。 - **返回:** 与 `sx_cmp` 相同的负值、0 或正值。 -- **所有权:** 无;只读取。 -- **边界情况:** `h` 或 `s` 为 NULL 时返回 0。`s` 中的内嵌 NUL 会缩短 - 参与比较的范围。 +- **边界情况:** `h` 或 `s` 为 NULL 返回 0。`s` 中的内嵌 NUL 缩短参与 + 比较的范围。 ## 前缀与后缀判定 @@ -410,14 +386,13 @@ int sx_cmp_cstr(const sx_t *h, const char *s); int sx_starts_with(const sx_t *h, const sx_t *prefix); ``` -判断 `h` 是否以另一个缓冲区的内容开头。 +判断 `h` 是否以另一缓冲区的内容开头。 - **参数:** `h` —— 缓冲区;`prefix` —— 内容作为前缀的缓冲区。 -- **返回:** `h` 的前 `len(prefix)` 个内容字节与 prefix 逐字节相等时返回 +- **返回:** `h` 的前 `len(prefix)` 个内容字节逐字节等于 prefix 时返回 1,否则返回 0。 -- **所有权:** 无;只读取。 -- **边界情况:** 空前缀总是匹配;比 `h` 更长的 prefix 永远不匹配。字节 - 精确且二进制安全。`h` 或 `prefix` 为 NULL 时返回 0。 +- **边界情况:** 空前缀总匹配;比 `h` 更长的 prefix 永不匹配。字节精确 + 且二进制安全。`h` 或 `prefix` 为 NULL 返回 0。 ### sx_starts_with_view @@ -425,14 +400,13 @@ int sx_starts_with(const sx_t *h, const sx_t *prefix); int sx_starts_with_view(const sx_t *h, sx_view_t prefix); ``` -判断 `h` 是否以视图中的字节开头。 +判断 `h` 是否以视图字节开头。 - **参数:** `h` —— 缓冲区;`prefix` —— 按 `prefix.len` 个字节读取的 窗口。 -- **返回:** 匹配时返回 1,否则返回 0。 -- **所有权:** 无;只读取。 -- **边界情况:** 空视图总是匹配。`h` 为 NULL 时返回 0;`prefix.ref == - NULL` 或越界窗口属于契约之外。 +- **返回:** 匹配返回 1,否则返回 0。 +- **边界情况:** 空视图总匹配。`h` 为 NULL 返回 0;`prefix.ref == NULL` + 或越界窗口属于契约之外。 ### sx_starts_with_cstr @@ -442,11 +416,10 @@ int sx_starts_with_cstr(const sx_t *h, const char *prefix); 判断 `h` 是否以 C 字符串开头。 -- **参数:** `h` —— 缓冲区;`prefix` —— 以 NUL 结尾的前缀,按 `strlen` +- **参数:** `h` —— 缓冲区;`prefix` —— NUL 结尾的前缀,按 `strlen` 读取。 -- **返回:** 匹配时返回 1,否则返回 0。 -- **所有权:** 无;只读取。 -- **边界情况:** 空字符串总是匹配;`h` 或 `prefix` 为 NULL 时返回 0。 +- **返回:** 匹配返回 1,否则返回 0。 +- **边界情况:** 空字符串总匹配;`h` 或 `prefix` 为 NULL 返回 0。 ### sx_ends_with @@ -454,14 +427,13 @@ int sx_starts_with_cstr(const sx_t *h, const char *prefix); int sx_ends_with(const sx_t *h, const sx_t *suffix); ``` -判断 `h` 是否以另一个缓冲区的内容结尾。 +判断 `h` 是否以另一缓冲区的内容结尾。 - **参数:** `h` —— 缓冲区;`suffix` —— 内容作为后缀的缓冲区。 -- **返回:** `h` 的后 `len(suffix)` 个内容字节与 suffix 逐字节相等时返回 +- **返回:** `h` 的后 `len(suffix)` 个内容字节逐字节等于 suffix 时返回 1,否则返回 0。 -- **所有权:** 无;只读取。 -- **边界情况:** 空后缀总是匹配;比 `h` 更长的 suffix 永远不匹配。字节 - 精确且二进制安全。`h` 或 `suffix` 为 NULL 时返回 0。 +- **边界情况:** 空后缀总匹配;比 `h` 更长的 suffix 永不匹配。字节精确 + 且二进制安全。`h` 或 `suffix` 为 NULL 返回 0。 ### sx_ends_with_view @@ -469,14 +441,13 @@ int sx_ends_with(const sx_t *h, const sx_t *suffix); int sx_ends_with_view(const sx_t *h, sx_view_t suffix); ``` -判断 `h` 是否以视图中的字节结尾。 +判断 `h` 是否以视图字节结尾。 - **参数:** `h` —— 缓冲区;`suffix` —— 按 `suffix.len` 个字节读取的 窗口。 -- **返回:** 匹配时返回 1,否则返回 0。 -- **所有权:** 无;只读取。 -- **边界情况:** 空视图总是匹配。`h` 为 NULL 时返回 0;`suffix.ref == - NULL` 或越界窗口属于契约之外。 +- **返回:** 匹配返回 1,否则返回 0。 +- **边界情况:** 空视图总匹配。`h` 为 NULL 返回 0;`suffix.ref == NULL` + 或越界窗口属于契约之外。 ### sx_ends_with_cstr @@ -486,11 +457,10 @@ int sx_ends_with_cstr(const sx_t *h, const char *suffix); 判断 `h` 是否以 C 字符串结尾。 -- **参数:** `h` —— 缓冲区;`suffix` —— 以 NUL 结尾的后缀,按 `strlen` +- **参数:** `h` —— 缓冲区;`suffix` —— NUL 结尾的后缀,按 `strlen` 读取。 -- **返回:** 匹配时返回 1,否则返回 0。 -- **所有权:** 无;只读取。 -- **边界情况:** 空字符串总是匹配;`h` 或 `suffix` 为 NULL 时返回 0。 +- **返回:** 匹配返回 1,否则返回 0。 +- **边界情况:** 空字符串总匹配;`h` 或 `suffix` 为 NULL 返回 0。 ## 分割:sx_split @@ -500,38 +470,37 @@ int sx_ends_with_cstr(const sx_t *h, const char *suffix); sx_view_t *sx_split(const sx_t *h, const char *sep); ``` -按 C 字符串分隔符把缓冲区分割成一组 token 视图。该声明位于 `sx.h` -(进阶层),不在 `sx_core.h` 中。 +按 C 字符串分隔符把缓冲区分割成 token 视图数组。声明位于 `sx.h` +(进阶层),不在 `sx_core.h`。 -- **参数:** `h` —— 要分割的缓冲区;`sep` —— 以 NUL 结尾的分隔符,按 - `strlen` 读取。空分隔符会被拒绝,而不是按“每个字节”处理。 -- **返回:** 一个 malloc 分配的 `sx_view_t` 数组,采用经典的 `char **` - 形态;`h` 为 NULL、`sep` 为 NULL、`sep` 为空,或分配失败时返回 - `NULL`。 -- **所有权:** 调用方拥有数组,用 `free`(而不是 `sx_free`)释放。token - 是 `h` 上的视图,绝不能单独释放。 +- **参数:** `h` —— 要分割的缓冲区;`sep` —— NUL 结尾的分隔符,按 + `strlen` 读取。空分隔符会被拒绝,而非按“每个字节”处理。 +- **返回:** malloc 分配的 `sx_view_t` 数组(经典 `char **` 形态); + `h` 为 NULL、`sep` 为 NULL、`sep` 为空或分配失败时返回 `NULL`。 +- **所有权:** 调用方拥有数组,用 `free`(而非 `sx_free`)释放;token 是 + `h` 上的视图,绝不能单独释放。 - **契约说明:** - - 数组恰有 `count + 1` 个元素:`arr[0] .. arr[count-1]` 是按顺序排列 - 的 token,`arr[count]` 是 `.ref == NULL` 的结束哨兵。遍历方式为 + - 数组恰有 `count + 1` 个元素:`arr[0] .. arr[count-1]` 为按序 token, + `arr[count]` 是 `.ref == NULL` 的结束哨兵。遍历方式为 `for (size_t i = 0; arr[i].ref != NULL; i++)`。 - `count == 1 + (分隔符出现次数)`。分隔符从左到右非重叠匹配:命中后 - 扫描越过该分隔符继续,因此用 `"aa"` 分割 `"aaaa"` 得到三个空 token, - 而不是两个。 - - 每个位置的空字段都会保留:`"a,,b"` 得到 `"a"`、`""`、`"b"`;开头或 - 结尾的分隔符会产生空的第一个或最后一个 token;空 `h` 分割为单个空 - token `""`;内容与分隔符完全相同的字符串分割为两个空 token。 - - 空 token 不是结束哨兵:它的 `ref != NULL` 且 `len == 0`,而哨兵的 + 扫描越过它继续,因此用 `"aa"` 分割 `"aaaa"` 得到三个空 token 而非 + 两个。 + - 每个位置的空字段都保留:`"a,,b"` 得到 `"a"`、`""`、`"b"`;开头或 + 结尾分隔符产生空的第一个或最后一个 token;空 `h` 分割为单个空 token + `""`;与分隔符完全相同的字符串分割为两个空 token。 + - 空 token 不是结束哨兵:其 `ref != NULL` 且 `len == 0`,哨兵则是 `ref == NULL`。 - token 是 `h` 内容的别名(`ref == h->ref`,以及 `offset`、`len`): - 调用过程中不拷贝、不修改、也不重新分配,因此内容指针按位保持不变。 - 之后对 `h` 的修改会使 token 失效;token 在使用时不要修改 `h`。 - - 匹配是字节精确的,因此 token 中可能包含内嵌的 NUL 字节(分隔符本身 - 是 C 字符串,不能包含)。打印这类 token 请使用 `fwrite` 或带长度的 - `"%.*s"`,不要使用 `"%s"`。 + 不拷贝、不修改、不重新分配,内容指针按位不变。之后对 `h` 的修改会使 + token 失效;使用期间不要修改 `h`。 + - 匹配字节精确,token 中可能含内嵌 NUL 字节(分隔符本身是 C 字符串, + 不能含)。打印这类 token 用 `fwrite` 或带长度的 `"%.*s"`,不要用 + `"%s"`。 正则层的 `sx_reg_split` 返回完全相同的形态,见[正则表达式](regex.md)。 -完整示例 —— 分割、遍历到结束哨兵,然后释放数组和缓冲区: +完整示例 —— 分割、遍历到结束哨兵,再释放数组和缓冲区: ```c #include @@ -556,7 +525,7 @@ int main(void) { } ``` -预期输出(结尾的分隔符产生一个空的最后字段): +预期输出(结尾分隔符产生空的最后字段): ```text field 0: "alpha" (offset 0, len 5) diff --git a/docs/zh_cn/build-and-test.md b/docs/zh_cn/build-and-test.md index 60d9b13..76899bb 100644 --- a/docs/zh_cn/build-and-test.md +++ b/docs/zh_cn/build-and-test.md @@ -4,10 +4,9 @@ # 构建、测试与打包 -String X 使用 [Forge](https://github.com/minelogy-dev/forge) 构建,这是一个 -构建脚本本身就是 C 程序的构建系统。本页介绍工具链要求、每个 `./make` 任务、 -测试框架与内存检查器(sanitizer)、安装、pkg-config 以及 Debian 打包。运行这些 -命令的 CI 流水线见[持续集成](ci.md)。 +String X 使用 [Forge](https://github.com/minelogy-dev/forge) 构建。本页介绍 +环境要求、`./make` 任务、测试框架与内存检查器(sanitizer)、安装、pkg-config +与 Debian 打包。CI 见[持续集成](ci.md)。 ## 环境要求 @@ -17,59 +16,30 @@ String X 使用 [Forge](https://github.com/minelogy-dev/forge) 构建,这是 | C23 编译器 | GCC 14+ 或 Clang 19+。 | | `libpcre2-dev` | PCRE2 10.46,8 位,正则层与每个测试都需要。运行时库需要 `libpcre2-8-0`。 | | `pkg-config` | 推荐使用者安装;CI 还用它链接已安装的库。 | -| Forge | 构建工具;从源码引导安装(见下一节)。`./make` 是生成物,不纳入版本库。 | +| Forge | [github.com/minelogy-dev/forge](https://github.com/minelogy-dev/forge);`./make` 是生成物,不纳入版本库。 | | `tar` 与 `ar` | 只有 `./make gen_deb` 需要;`dpkg-deb` 仅用于检查产物。 | -所有命令都在仓库根目录执行:`build.c` 与 `build.conf` 都相对于该目录读取。 +命令在仓库根目录执行;`build.c`、`build.conf` 相对该目录读取。 -## Forge 一分钟上手 +## 构建工具 -Forge 把 `build.c` 编译成本地可执行文件 `./make`。这个生成文件就是构建入口: -下文每个任务都是 `build.c` 里的一个函数,以 `./make <任务>` 调用。它不是 GNU -make。只要修改了 `build.c` 或 `build.conf`,就要重新运行 `forge .`。 - -从源码引导 Forge,并把它的产物加入搜索路径: - -```sh -git clone https://github.com/minelogy-dev/forge.git -cd forge -./bootstrap.sh --no-test -export PATH="$PWD/build/output:$PATH" -export CPATH="$PWD/build/output/include" -cd /path/to/StringX -forge . -``` - -CI 将 Forge 固定到提交 -`b6826ba762a1e9e337895e01ee604b943c682d23`。若要精确复现 CI,请把该提交 -检出到 `.ci-deps/forge`,并在不安装系统文件的情况下引导它: +从 [Forge](https://github.com/minelogy-dev/forge) 仓库安装 Forge。运行一次 +`forge .` 生成 `./make` 后,日常命令为: ```sh -git clone https://github.com/minelogy-dev/forge.git .ci-deps/forge -git -C .ci-deps/forge checkout b6826ba762a1e9e337895e01ee604b943c682d23 -sh .ci-deps/forge/bootstrap.sh --no-test -export PATH="$PWD/.ci-deps/forge/build/output:$PATH" -export CPATH="$PWD/.ci-deps/forge/build/output/include" -forge . -``` - -更换 Forge 版本时,两个工作流文件 `.github/workflows/ci.yml` 与 -`.github/workflows/codeql.yml` 中的固定提交必须保持一致。该固定点有意独立于 -Forge 的 `main` 分支,也不会被 Dependabot 更新。 - -把 Forge 加入 `PATH` 后,日常命令与 README 一致: - -```sh -forge . # 把 build.c 编译成 ./make(改动 build.c 后需重跑) +forge . # 生成 ./make ./make # 构建 -> build/output/libstringx.so(头文件随附于 build/output/include) ./make test # 编译并运行 tests/ 下每个测试(ASan + UBSan) ``` +`./make` 是生成物且被 gitignore;修改 `build.c` 或 `build.conf` 后重跑 +`forge .`。 + ## 目标与命令 | 命令 | 作用 | | --- | --- | -| `forge .` | 按 `build.conf` 的设置把 `build.c` 编译成本地 `./make`。 | +| `forge .` | 由 `build.c` 与 `build.conf` 生成 `./make`。 | | `./make` | 默认的 `build` 任务:把 `src/` 编译成 `build/output/libstringx.so`,并把 `include/*.h` 同步到 `build/output/include/`。 | | `./make check` | 用警告选项和 GCC 分析器编译库目标,但不做头文件同步。 | | `./make test` | 在 ASan + UBSan + LSan 下构建并运行 `tests/` 下的每个文件。 | @@ -77,10 +47,10 @@ forge . # 把 build.c 编译成 ./make(改动 build.c 后需重跑) | `./make install ` | 先构建,再安装库、头文件、声明文件和 `libstringx.pc`;前缀默认为 `/usr/local`。 | | `./make gen_deb` | 先构建,再暂存并生成 `build/deb/libstringx_<版本>_<架构>.deb`。 | -`-v` 会让 `./make test` 与 `./make check` 打印完整的编译命令;不加时只显示 -`PASSED`/`FAILED` 行和最终汇总。`-j N` 并行执行一个目标的编译阶段。 +`-v` 让 `./make test` 与 `./make check` 打印完整编译命令;不加时只显示 +`PASSED`/`FAILED` 行与汇总。`-j N` 并行执行一个目标的编译阶段。 -产物位置如下: +产物: | 路径 | 由谁生成 | 内容 | | --- | --- | --- | @@ -91,37 +61,39 @@ forge . # 把 build.c 编译成 ./make(改动 build.c 后需重跑) | `build/opt/` | `./make test` | 测试目标文件及其 `.d`/`.meta` 文件 | | `build/deb/` | `./make gen_deb` | Debian 暂存目录与最终 `.deb` | -`./make test` 不需要先运行 `./make`:每个测试都直接编译库源码。 +`./make test` 无需先运行 `./make`:每个测试直接编译库源码。 ## build.conf -`build.conf` 在 Forge 生成 `./make` 时读取;每个 `KEY=VALUE` 行都会变成构建脚本 -的 `-DCONF_KEY=VALUE` 宏。以 `#` 开头的行是注释。修改后需要重新运行 `forge .`。 +`build.conf` 在生成 `./make` 时读取;每个 `KEY=VALUE` 行变成 +`-DCONF_KEY=VALUE` 宏,`#` 开头为注释。修改后重跑 `forge .`。 | 键 | 取值 | 作用 | | --- | --- | --- | | `compiler` | `GCC` 或 `CLANG` | 工具链后端。`build.c` 把 `CONF_compiler` 传给 `set_toolchain`,因此它同时决定库与测试使用的编译器。 | -| `compiler_path` | 绝对路径,例如 `/usr/bin/gcc` | Forge 编译生成的 `./make` 时使用的编译器二进制文件。 | +| `compiler_path` | 绝对路径,例如 `/usr/bin/gcc` | 生成 `./make` 时使用的编译器二进制文件。 | | `version` | `v0.5` | 项目版本的唯一来源。`build.c` 把它字符串化为 `SX_VERSION`;安装与打包会去掉开头的 `v`。 | | `sanitize` | `1` | CI 中由 `.github/scripts/configure.sh` 追加。内存检查器选项本身由每个测试在头部 DSL 中声明。 | ## 运行测试 `./make test` 递归扫描 `tests/`,把每个 `tests/*.c` 编译成 `test/<名称>` 并 -运行。测试成功时打印 `PASSED: <文件>`,第一个断言失败时打印 -`FAILED: <文件>:<行号>: <表达式>`。任务结束时输出类似下面的汇总: +运行。成功打印 `PASSED: <文件>`,首个断言失败打印 +`FAILED: <文件>:<行号>: <表达式>`。汇总形如: ```text -forge: 20 tests, 20 passed, 0 failed +forge: 24 tests, 24 passed, 0 failed ``` -只要有测试编译或运行失败,任务就以非零状态退出。 +测试编译或运行失败时,任务以非零状态退出。 -测试不链接 `libstringx.so`:每个测试直接编译库源码,并在自己的头部声明选项, -包括 `-fsanitize=address,undefined` 与 `-fno-omit-frame-pointer`。LeakSanitizer -与 ASan 一起运行,因此测试若忘记释放缓冲区或返回的数组就会失败。 +测试不链接 `libstringx.so`:各自直接编译库源码,并在头部声明选项,包括 +`-fsanitize=address,undefined` 与 `-fno-omit-frame-pointer`。LeakSanitizer 与 +ASan 一起运行,忘记释放缓冲区或数组的测试会失败。少数测试在普通配置与强制 +配置的兄弟目标间共享本地用例头(`find_differential.h`、 +`write_overflow_cases.h`);每个 `.c` 仍是独立目标。 -请设置与 CI 相同的内存检查器选项: +设置 CI 的内存检查器选项: ```sh export ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 @@ -129,7 +101,7 @@ export UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 ./make test -j 2 ``` -单独重跑某个已构建的测试: +单独重跑已构建的测试: ```sh ./test/reserve_stress @@ -137,36 +109,35 @@ export UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 ### 精确预留压力测试 -`tests/reserve_stress.c` 是 `-DSX_FORCE_EXACT_RESERVE` 的专用配置,该宏在其 -头部以 `// Option -DSX_FORCE_EXACT_RESERVE` 声明。这个开关把 -`src/sx_raw.c` 内部的预留辅助函数从几何增长改为精确分配 -(`cap == need + 1`),于是分配正好在结尾符处结束,任何越过 `len` 的访问都会 -立刻命中 ASan 的红区——多余的容量无法掩盖差一错误或过期的长度。测试用确定性 -的 LCG 驱动三个活动缓冲区,并在每次修改后断言完整内容;其模型不超过 512 字节。 -其余所有测试都在默认的几何增长模式下构建。 +`tests/reserve_stress.c` 与 `tests/write_overflow_exact.c` 使用 +`-DSX_FORCE_EXACT_RESERVE` 构建,头部以 +`// Option -DSX_FORCE_EXACT_RESERVE` 声明。该开关把 `src/sx_raw.c` 的预留助手 +从几何增长改为精确分配(`cap == need + 1`):分配正好止于结尾符,越过 `len` +的访问立刻命中 ASan 红区,多余的容量无法掩盖差一错误或过期长度。压力测试用 +确定性 LCG 驱动三个活动缓冲区,每次修改都断言完整内容(模型不超过 512 字节); +写入溢出测试在精确分配下重跑其 `SIZE_MAX` 范围用例。其余测试使用几何增长。 ## 测试文件与头部 DSL -每个测试都是自包含程序。文件开头连续若干行 `//` 构成 Forge 测试运行器读取的 -头部 DSL;遇到第一行非 `//` 的内容时头部结束。 +每个测试都是自包含程序。开头连续的 `//` 行是测试运行器读取的头部 +DSL,第一行非 `//` 内容结束。 | 条目 | 作用 | | --- | --- | -| `// Include <目录>` | 添加 `-I<目录>`。每个测试都包含 `include`、`src` 和 `/usr/lib/forge/include` —— 最后一项是 `` 所需的 Forge 头文件;若通过 `CPATH` 提供,这一项也无害。 | +| `// Include <目录>` | 添加 `-I<目录>`。每个测试都包含 `include`、`src` 和 `/usr/lib/forge/include`;最后一项在 `CPATH` 未提供时用于找到 ``。 | | `// Source <文件>` | 把一个源文件加入测试可执行文件。测试都会加入 `src/sx_raw.c`、`src/sx_core.c` 与 `src/sx_adv.c`。 | | `// Link <库>` | 添加 `-l<库>`。只有 `tests/reg.c` 加入 `pcre2-8`;其他测试不使用正则层。 | | `// Library <目录>` | 添加 `-L<目录>`。测试加入 `/usr/local/lib`。 | | `// Option <选项>` | 添加编译器、链接器与汇编器选项。测试使用 `-std=c23 -O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer`,以及诸如 `-DSX_FORCE_EXACT_RESERVE` 的测试专用宏。 | -不带关键字的行会延续当前作用域(初始为 `Source`);测试为了清晰都写出了每个 +不带关键字的行延续当前作用域(初始为 `Source`);测试为清晰起见写出了每个 关键字。 -由于每个测试都会编译 `src/sx_adv.c`,`build.c` 通过其保留的 `LANGUAGE` -覆盖项为每个测试目标附加 `pcre2-8`;`tests/reg.c` 还显式声明了 -`// Link pcre2-8`。 +每个测试都编译 `src/sx_adv.c`,因此 `build.c` 通过保留的 `LANGUAGE` 覆盖项 +为测试目标附加 `pcre2-8`;`tests/reg.c` 还声明了 `// Link pcre2-8`。 -程序本身包含被测头文件(`"sx.h"`,仅测核心层时用 `"sx_core.h"`)以及提供两个 -测试宏的 ``: +程序包含被测头文件(`"sx.h"`,仅核心层用 `"sx_core.h"`)与提供两个测试宏的 +``: | 宏 | 作用 | | --- | --- | @@ -176,12 +147,11 @@ export UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 ### 添加测试 1. 创建 `tests/<名称>.c` —— 每个文件只覆盖一个行为领域。 -2. 从现有测试复制头部 DSL 块,并按所需依赖调整 `Source`、`Link` 与 `Option`。 -3. 在文件顶部写明行为边界:测试锁定了什么(`In scope (contract)`),以及 - 有意不覆盖什么(`Out of contract (not exercised)`)。 -4. 包含被测头文件,用 `TEST` 断言,释放每个缓冲区与返回的数组,最后以 - `PASS()` 结束。 -5. 运行 `./make test`。新文件会被自动发现。 +2. 从现有测试复制头部 DSL 块,按需调整 `Source`、`Link` 与 `Option`。 +3. 写明行为边界:锁定什么(`In scope (contract)`),不覆盖什么 + (`Out of contract (not exercised)`)。 +4. 包含被测头文件,用 `TEST` 断言,释放每个缓冲区与数组,最后调用 `PASS()`。 +5. 运行 `./make test`;新文件会被自动发现。 ```c // Include include @@ -224,7 +194,7 @@ int main(void) { ## 安装 -`./make install` 会先构建(包括头文件同步),然后复制: +`./make install` 先构建(含头文件同步),再复制: | 目标位置 | 内容 | | --- | --- | @@ -237,14 +207,14 @@ int main(void) { | `/share/doc/libstringx/THIRD_PARTY_NOTICES.md` | PCRE2 归属与许可全文 | | `/share/doc/libstringx/copyright` | `LICENSE` 的副本,Debian 惯用文件名 | -默认前缀为 `/usr/local`。可以传入一个无需 root 即可写入的前缀,例如: +默认前缀 `/usr/local`;可传入无需 root 即可写入的前缀,例如: ```sh ./make install "$HOME/.local" ``` -pkg-config 文件在安装时生成。它的 `prefix=` 就是安装前缀,`Version` 是 -`build.conf` 版本去掉开头的 `v`(即 `0.5`)。 +pkg-config 文件在安装时生成:`prefix=` 为安装前缀,`Version` 为 `build.conf` +版本去掉开头 `v`(即 `0.5`)。 ## 使用已安装的库 @@ -261,7 +231,7 @@ cc -std=c23 hello.c $(pkg-config --cflags --libs libstringx) -o hello cc -std=c23 hello.c -I/include -L/lib -lstringx -o hello ``` -对于非标准前缀,让 pkg-config 与运行期加载器指向它,或者写入 rpath: +非标准前缀时,让 pkg-config 与运行期加载器指向它,或写入 rpath: ```sh export PKG_CONFIG_PATH="/lib/pkgconfig" @@ -269,7 +239,7 @@ cc -std=c23 hello.c $(pkg-config --cflags --libs libstringx) \ -Wl,-rpath,"/lib" -o hello ``` -库自身已链接 `pcre2-8`,使用者无需 `-lpcre2-8`。完整程序如下: +库自身已链接 `pcre2-8`,使用者无需 `-lpcre2-8`。完整程序: ```c #include @@ -288,7 +258,7 @@ int main(void) { ## Debian 包 -`./make gen_deb` 会先构建,然后用 `tar` 与 `ar` 暂存并打包出 Debian `.deb` +`./make gen_deb` 先构建,再用 `tar` 与 `ar` 暂存并打包 Debian `.deb` (不依赖 `dpkg-deb`): | 路径 | 内容 | @@ -298,12 +268,12 @@ int main(void) { | `build/deb/debian-binary`、`control.tar.gz`、`data.tar.gz` | 包的各组成部分 | | `build/deb/libstringx_<版本>_<架构>.deb` | 最终包 | -版本取自 `build.conf` 并去掉开头的 `v`;架构取自 `uname -m` -(`x86_64` → `amd64`,`aarch64` → `arm64`,其他值保持不变)。包装到 `/usr` -下,并声明 `Depends: libc6, libpcre2-8-0`。包内的 `libstringx.pc` 以 `/usr` -作为前缀,暂存路径不会写进去。 +版本取自 `build.conf` 去掉开头 `v`;架构取自 `uname -m`(`x86_64` → +`amd64`,`aarch64` → `arm64`,其他值不变)。包装到 `/usr` 下,声明 +`Depends: libc6, libpcre2-8-0`,包内 `libstringx.pc` 以 `/usr` 为前缀,暂存 +路径不会写入。 -检查并安装: +检查安装: ```sh dpkg-deb --info build/deb/libstringx_*.deb @@ -315,23 +285,22 @@ sudo apt install ./build/deb/libstringx_*.deb | 现象 | 原因与处理 | | --- | --- | -| `forge: command not found` | Forge 不在 `PATH` 中。引导它并导出 `PATH=/build/output`。 | -| `build.h: No such file or directory` | Forge 的构建脚本头文件不可见。像 CI 那样导出 `CPATH=/build/output/include`,或系统级安装 Forge。`` 只存在于 Forge 构建环境中。 | +| `forge: command not found` | Forge 不在 `PATH` 中;按 Forge 仓库的安装说明配置。 | | `pcre2.h: No such file or directory` 或 `cannot find -lpcre2-8` | 安装 `libpcre2-dev`(Ubuntu:`sudo apt-get install libpcre2-dev`)。 | | 克隆后出现 `./make: No such file or directory` | `./make` 是生成物且被 gitignore。先运行 `forge .`。 | | 修改 `build.c` 或 `build.conf` 后没有生效 | `./make` 由旧脚本生成。重新运行 `forge .`。 | -| Clang 下测试链接因 `-flto` 失败 | 固定的 Forge 在并行 Clang 链接时会输出仅适用于 GCC 的 `-flto=N`,因此 `build.c` 中的测试目标特意关闭 LTO;生产目标保留 LTO。用 Clang 运行测试套件时请保持测试关闭 LTO。 | +| Clang 下测试链接因 `-flto` 失败 | 固定版本的构建工具在并行 Clang 链接时会输出仅适用于 GCC 的 `-flto=N`,因此 `build.c` 中的测试目标关闭 LTO;生产目标保留 LTO。 | | `install` 报告权限错误 | 前缀不可写。传入你有权限的前缀,例如 `./make install "$HOME/.local"`。 | | 测试因泄漏报告失败 | 有缓冲区或数组未释放。每个 `sx_t` 都要用 `sx_free` 释放,每个返回的数组都要用 `free` 释放。 | | 使用者程序找不到 `libstringx.so` | 把 `LD_LIBRARY_PATH` 设为 `/lib`,用 `-Wl,-rpath,/lib` 链接,或安装到标准前缀。 | -不要在库源码或应用程序中包含 ``:它是 Forge 的构建脚本 DSL 头文件, -不属于 String X API。应用程序只包含 ``。 +不要在库源码或程序中包含 ``:它是构建脚本的 DSL 头文件,非 +String X API。程序只包含 ``。 ## 持续集成 -在每次推送与拉取请求上运行这些命令的工作流——构建矩阵、分析器、质量检查、 -CodeQL 与合并保护——见[持续集成](ci.md)。 +运行这些命令的工作流(推送与拉取请求)——构建矩阵、分析器、质量检查、CodeQL +与合并保护——见[持续集成](ci.md)。 --- diff --git a/docs/zh_cn/ci.md b/docs/zh_cn/ci.md index dc5e1fb..466f970 100644 --- a/docs/zh_cn/ci.md +++ b/docs/zh_cn/ci.md @@ -4,9 +4,9 @@ # 持续集成 -对 `main` 的改动、拉取请求以及手动运行都使用 GitHub Actions。本页说明每个 -工作流验证什么、如何在本地复现这些检查,以及合并保护如何把它们串起来。命令本身 -——Forge 引导、`./make` 目标、测试框架——见[构建、测试与打包](build-and-test.md)。 +对 `main` 的改动、拉取请求与手动运行都使用 GitHub Actions。本页介绍工作流、 +本地复现与合并保护;构建命令、`./make` 目标与测试框架见 +[构建、测试与打包](build-and-test.md)。 ## 触发条件 @@ -14,11 +14,12 @@ | --- | --- | | 推送到 `main` | [ci.yml](../../.github/workflows/ci.yml) 与 [codeql.yml](../../.github/workflows/codeql.yml) | | 任意分支上的 `pull_request` | `ci.yml` 与 `codeql.yml` | -| `workflow_dispatch`(手动运行) | `ci.yml` 与 `codeql.yml` | +| 按路径过滤的 `pull_request` | [write-safety.yml](../../.github/workflows/write-safety.yml)(`src/sx_core.c`、`tests/write_overflow*`、其脚本)、[search-performance.yml](../../.github/workflows/search-performance.yml)(`src/sx_core.c`、其脚本)、[benchmarks.yml](../../.github/workflows/benchmarks.yml)(`benchmarks/**`)、[benchmark-report.yml](../../.github/workflows/benchmark-report.yml)(仅其工作流文件) | +| `workflow_dispatch`(手动运行) | `ci.yml`、`codeql.yml`、`write-safety.yml`、`search-performance.yml`、`benchmarks.yml`、`benchmark-report.yml` | | `schedule` | 仅 `codeql.yml`(每周) | -工作流对仓库只有只读访问权限,唯一例外是 CodeQL 任务发布代码扫描结果所需的权限。 -拉取请求中的代码绝不会通过 `pull_request_target` 运行,且不保留检出凭据。 +工作流对仓库只有只读权限,唯一例外是 CodeQL 发布代码扫描结果所需的权限。 +拉取请求代码绝不会通过 `pull_request_target` 运行,且不保留检出凭据。 ## 检查项 @@ -29,36 +30,42 @@ | GCC 静态分析 | 用 `-fanalyzer` 检查生产翻译单元;出现诊断即令任务失败 | | 工作流与密钥检查 | 对完整 Git 历史运行 Actionlint、ShellCheck、空白错误检查与 Gitleaks,输出中的密钥已脱敏 | | CodeQL(C/C++) | 手动构建追踪,使用 `security-and-quality` 查询;发现显示在 Security 页与拉取请求中 | +| Write safety 与成本 | 在不可变旧实现上复现写入溢出回归(该实现必须出现 sanitizer 失败),用 GCC 14 与 Clang 19 运行两种修复配置,并与 SDS、bstrlib 比较等长写入成本 | +| Search performance | 针对 `src/sx_core.c` 改动,用 GCC 与 Clang 做改动前后查找基准 | +| 经审计的基准 | 当 `benchmarks/` 变化时重跑固定版本的 StringX / SDS / bstrlib 基准 | +| 基准结果报告 | 把手动保存的基准产物渲染成报告 | | CI | 稳定的必需检查:任何构建、分析或质量任务失败或被取消时它都会失败 | +四个审计/基准工作流按路径过滤,独立于聚合的 `CI` 检查;只有分支保护显式要求 +时它们才参与合并门禁。 + GCC 分析使用 `-O1 -fno-analyzer-state-merge`:GCC 14 默认的状态合并会在这份 -代码上产生虚假的分配/清理诊断。没有屏蔽任何诊断类别。分析器失败应当被调查, -而不是用 `continue-on-error` 绕过。 +代码上产生虚假的分配/清理诊断。未屏蔽任何诊断类别;分析器失败应调查,而不是 +用 `continue-on-error` 绕过。 -所有外部 Action 都固定到不可变的提交 SHA。Dependabot 每周提出 GitHub Actions -更新。Actionlint 与 Gitleaks CLI 的版本和 SHA-256 校验和固定在 +外部 Action 固定到不可变的提交 SHA;Dependabot 每周提出更新。Actionlint 与 +Gitleaks CLI 的版本和 SHA-256 校验和固定在 [.github/scripts/install-tools.sh](../../.github/scripts/install-tools.sh) 中; -升级它们时要同时更新这两处值。 +升级时两处值要同时更新。 ## CodeQL -CodeQL 面向 C/C++ 配置,使用手动构建追踪与 `security-and-quality` 查询集。 -它分析由固定的 Forge 工具链构建出的代码,把发现发布到 Security 页,并在拉取 -请求中报告。 +CodeQL 面向 C/C++,使用手动构建追踪与 `security-and-quality` 查询。它分析由 +固定工具链构建的代码,把发现发布到 Security 页与拉取请求。 -CodeQL 还会在每周一 11:17 Asia/Shanghai(03:17 UTC)运行。任务状态为成功只表示 -分析完成,**并不**表示没有告警。请用代码扫描合并规则来强制告警级别——见 +CodeQL 还在每周一 11:17 Asia/Shanghai(03:17 UTC)运行。成功只表示分析完成, +**并不**表示没有告警;用代码扫描合并规则强制告警级别——见 [启用合并保护](#启用合并保护)。 ## 启用合并保护 -仅靠工作流文件无法启用分支保护;这些仓库设置是维护者的一次性配置。首次成功 -运行后,为 `main` 创建分支规则集: +仅靠工作流文件无法启用分支保护;这些是维护者的一次性设置。首次成功运行后, +为 `main` 创建分支规则集: 1. 要求拉取请求,且 `CI` 与 `CodeQL (C/C++)` 状态检查通过。 2. 要求分支在合并前保持最新。 -3. 添加“Require code scanning results”,选择 CodeQL,并阻止高危/严重安全告警 - 与错误级质量告警。在分诊现有发现后可以收紧这些阈值。 +3. 添加“Require code scanning results”,选择 CodeQL,阻止高危/严重安全告警 + 与错误级质量告警;分诊现有发现后可收紧阈值。 4. 使用仓库中检入的高级 CodeQL 工作流,而不要启用重复的默认设置扫描。 CI 权限、检查项与依赖固定点的改动仍然值得人工评审。 @@ -66,8 +73,7 @@ CI 权限、检查项与依赖固定点的改动仍然值得人工评审。 ## 本地复现 安装 Linux 构建依赖与 C23 编译器(GCC 14+ 或 Clang 19+)。运行 `configure.sh` -前请保存本地 `build.conf` 修改:它会更新编译器选择,并在该文件中追加 -`sanitize=1`。 +前保存本地 `build.conf` 修改:它会更新编译器选择并追加 `sanitize=1`。 ```sh CC=gcc bash .github/scripts/configure.sh # 或 CC=clang @@ -75,48 +81,39 @@ CC=gcc bash .github/scripts/check-c.sh CC=gcc bash .github/scripts/check-c.sh analyze ``` -`analyze` 请使用 GCC。运行时检查需设置: +`analyze` 用 GCC;运行时检查设置: ```sh export ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 export UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 ``` -构建依赖是 Forge 提交 -`b6826ba762a1e9e337895e01ee604b943c682d23`:CI 把它检出到 `.ci-deps/forge`, -并在不安装系统文件的情况下引导。PCRE2 来自 Ubuntu 的 `libpcre2-dev` 包。 - -本地有已引导的 Forge 检出时: +CI 将 Forge 固定到经过评审的提交(检出到 `.ci-deps/forge`);两个工作流文件 +包含该固定点与相关命令,更换时须同步更新。PCRE2 来自 Ubuntu 的 +`libpcre2-dev` 包。已安装 Forge 时: ```sh -export PATH="/path/to/forge/build/output:$PATH" -export CPATH="/path/to/forge/build/output/include" forge . ./make ./make test -j 2 ``` +专项审计脚本位于 `.github/scripts/`(`check-write-safety.py`、 +`compare-search.py`);`benchmarks/` 自带基准框架与复跑说明。 + CI 还会安装到临时前缀,用 `pkg-config` 把现有正则测试编译并链接到**已安装的 -共享库**后运行,并检查生成的 Debian 包。这样除源码级行为外,还验证了公开头文件、 -导出符号、包元数据与 PCRE2 链接。对应命令在 `ci.yml` 中;它们使用的布局记录在 +共享库**后运行,并检查生成的 Debian `.deb`。这样除源码级行为外,还验证公开头文件、 +导出符号、包元数据与 PCRE2 链接。命令在 `ci.yml` 中,布局见 [构建、测试与打包](build-and-test.md)。 -## 固定的 Forge 提交 - -两个工作流文件都把 Forge 固定到提交 -`b6826ba762a1e9e337895e01ee604b943c682d23`,检出到 `.ci-deps/forge`,并用 -`sh .ci-deps/forge/bootstrap.sh --no-test` 在不安装系统文件的情况下引导。更换 -Forge 版本时,必须在**两个**工作流文件中更新这个经过评审的固定点。它有意独立于 -Forge 不断变动的 `main` 分支,也不会被 Dependabot 更新。 - ## 评审与失败处理 -打开失败的检查,查看编译器诊断、内存检查器堆栈或密钥扫描位置。构建失败会保留 -依赖与命令元数据七天;Actions 日志包含完整的构建/测试输出。CodeQL 告警会附带 -受影响的代码行,并在可用时给出数据流。 +打开失败的检查,查看编译器诊断、内存检查器堆栈或密钥扫描位置。构建失败保留依赖 +与命令元数据七天;Actions 日志包含完整输出。CodeQL 告警附带受影响的代码行, +并在可用时给出数据流。 -自动化覆盖机械性回归和许多常见的内存安全缺陷。人工评审应集中在需求、API 契约、 -所有权、架构以及这些工具报告的问题上。 +自动化覆盖机械性回归与许多内存安全缺陷;人工评审应聚焦需求、API 契约、所有权、 +架构以及工具报告的问题。 --- diff --git a/docs/zh_cn/contributing.md b/docs/zh_cn/contributing.md index b48a9f1..e1b6426 100644 --- a/docs/zh_cn/contributing.md +++ b/docs/zh_cn/contributing.md @@ -4,15 +4,15 @@ # 贡献指南 -String X 是一个契约写得很细的小型 C23 库,因此改动越小、测试与文档越同步, -评审就越容易,也越容易通过 CI 运行的同一套检查。本页说明工作流程与项目约定。 +String X 是一个契约详细的小型 C23 库,请保证文档、测试、改动的同步。本页说明 +工作流程与项目约定。 ## 工作流程 -1. Fork 仓库,并从 `main` 创建分支。分支名应体现改动内容 +1. Fork 仓库并从 `main` 创建分支,分支名体现改动内容 (`fix/split-end-guard`、`docs/build-targets`)。 -2. 完成改动,包括行为测试,以及英文和中文文档的更新。 -3. 提交拉取请求前先在本地运行检查: +2. 完成改动,包括行为测试与中英文文档更新。 +3. 提交拉取请求前先运行本地检查: ```sh ./make test -j 2 @@ -20,67 +20,65 @@ String X 是一个契约写得很细的小型 C23 库,因此改动越小、测 bash .github/scripts/check-c.sh analyze # 仅 GCC ``` -4. 向 `main` 提交拉取请求,说明行为变化、覆盖它的测试,以及更新了哪些文档页。 -5. 等待必需检查通过。`main` 的合并保护要求 `CI` 与 `CodeQL (C/C++)` 状态检查 - 通过且分支保持最新。检查内容见[持续集成](ci.md)。 -6. 通过追加提交来回应评审意见;让拉取请求始终聚焦于一个改动。 +4. 向 `main` 提交拉取请求,说明行为变化、对应测试与更新的文档页。 +5. 等待必需检查:`main` 的合并保护要求 `CI` 与 `CodeQL (C/C++)` 通过且分支 + 保持最新,见[持续集成](ci.md)。按路径过滤的 write-safety、 + search-performance 与 benchmark 工作流也会在匹配的改动上运行。 +6. 用追加提交回应评审意见;让拉取请求保持聚焦。 -`bash .github/scripts/configure.sh` 可以复现 CI 的编译器选择,但它会重写 -`build.conf` 中的 `compiler=`、`compiler_path=` 与 `sanitize=`,因此请先保存 -该文件的本地修改。 +`bash .github/scripts/configure.sh` 可以复现 CI 的编译器选择,但会重写 +`build.conf` 中的 `compiler=`、`compiler_path=` 与 `sanitize=`;请先保存本地 +修改。 ## 契约优先的文档规则 -行为边界记录在两个地方: +行为边界记录在两处: -- 公开头文件 `include/sx.h` 与 `include/sx_core.h` 中的注释; -- 每个 `tests/*.c` 顶部的 `Behavior boundaries` 注释,其中列出 - `In scope (contract)` 与 `Out of contract (not exercised)`。 +- 公开头文件 `include/sx.h` 与 `include/sx_core.h` 的注释; +- 每个 `tests/*.c` 顶部的 `Behavior boundaries` 注释,含 + `In scope (contract)` 与 `Out of contract (not exercised)` 列表。 -任何可观察行为的变化都必须同时更新: +行为变化要同时更新: 1. 受影响函数的头文件注释; 2. 测试实现及其行为边界注释; -3. `docs/en_us/` 与 `docs/zh_cn/` 下的英文和中文页面。 +3. `docs/en_us/` 与 `docs/zh_cn/` 的中英文页面。 -不要把行为留成未文档化,或仍按旧行为描述。若不同来源互相矛盾,运行时行为以 -测试为准,函数签名以头文件为准,构建与打包行为以 `build.c` 为准——遇到真正的 -矛盾应报告,而不是悄悄选择其中一个。 +不要让行为未文档化或停留在旧描述。若来源矛盾,运行时以测试为准,签名以头文件 +为准,构建与打包以 `build.c` 为准——应报告真正的矛盾,而非悄悄取舍。 ## 代码风格 - C23;库与测试都以 `-std=c23` 构建。 - 两空格缩进;左花括号与语句同行。 -- 遵循现有命名与分层:核心函数放在 `src/sx_core.c`,正则进阶层放在 - `src/sx_adv.c`,内部内存分配放在 `src/sx_raw.c`。不要在 - `sx.h`/`sx_core.h` 之外新增公开函数。 -- 偏移与长度使用 `size_t`,并沿用现有的哨兵约定(`(size_t)-1`、`ref == NULL` - 的视图、NULL 数组)。 -- 把警告当作错误。`./make check` 目标使用 `-Wall -Wextra -Wpedantic -Werror` - 编译库,GCC 构建还会加上 `-fanalyzer`;CI 的直接编译检查使用 - `-std=c23 -O1 -Wall -Wextra -Werror`。不要为了让构建通过而屏蔽诊断信息; - 应修正代码,或在评审中解释分析器的发现。 +- 遵循现有命名与分层:核心在 `src/sx_core.c`,正则在 `src/sx_adv.c`,分配在 + `src/sx_raw.c`。不要在 `sx.h`/`sx_core.h` 之外新增公开函数。 +- 偏移与长度用 `size_t`,沿用现有哨兵约定(`(size_t)-1`、`ref == NULL` 的 + 视图、NULL 数组)。 +- 把警告当作错误:`./make check` 使用 `-Wall -Wextra -Wpedantic -Werror`, + GCC 还加 `-fanalyzer`;CI 的直接编译检查使用 + `-std=c23 -O1 -Wall -Wextra -Werror`。不要屏蔽诊断;修正代码或在评审中 + 解释分析器的发现。 ## 测试 -每个行为改动都需要测试。测试是 `tests/` 下自包含的程序,直接编译库源码,并在 +每个行为改动都需要测试。`tests/` 下的测试是自包含程序,直接编译库源码,并在 头部 DSL(`// Include`、`// Source`、`// Link`、`// Library`、`// Option`)中 -声明依赖。DSL 与完整示例见[构建、测试与打包](build-and-test.md)。 +声明依赖;DSL 与示例见[构建、测试与打包](build-and-test.md)。 新增或修改测试时: -- 保持 `Behavior boundaries` 注释准确——它是测试实际执行的书面契约,包括 - `Out of contract (not exercised)` 列表; -- 断言可观察的结果(精确字节、长度、偏移与哨兵),而不只是调用返回了非 NULL; -- 每个缓冲区都用 `sx_free` 释放,每个返回的数组都用 `free` 释放;测试套件在 - AddressSanitizer、UBSan 与 LeakSanitizer 下运行,泄漏或越界访问都会导致 - 测试失败; -- 在测试头部保留内存检查器选项与 `-fno-omit-frame-pointer`,使测试在本地与 - CI 中运行方式一致; -- 若改动了内存分配或扩容,请运行 `tests/reserve_stress.c` 的精确预留配置 +- 保持 `Behavior boundaries` 注释准确——它是测试执行的契约,包括 + `Out of contract (not exercised)`; +- 断言可观察结果(字节、长度、偏移、哨兵),而不只是非 NULL; +- 每个缓冲区用 `sx_free`、每个返回数组用 `free` 释放;测试套件在 + AddressSanitizer、UBSan 与 LeakSanitizer 下运行,泄漏或越界都会失败; +- 在测试头部保留内存检查器选项与 `-fno-omit-frame-pointer`,使本地与 CI + 运行一致; +- 若改动内存分配或扩容,请运行 `tests/reserve_stress.c` 的精确预留配置 (`-DSX_FORCE_EXACT_RESERVE`),它能暴露被多余容量掩盖的越界访问。 -用与 CI 相同的环境运行测试套件: +用 CI 的环境运行测试套件: ```sh export ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 @@ -90,26 +88,25 @@ export UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 ## 提交与拉取请求 -- 每次提交只做一个逻辑改动,保持差异聚焦;避免无关的重新格式化与顺手修改。 -- 提交标题用简短祈使句,正文说明为什么需要该改动,以及它影响哪些行为边界或 - 文档。若有关联 issue 请注明。 +- 每次提交只做一个逻辑改动,保持差异聚焦;避免无关的重新格式化。 +- 标题用简短祈使句,正文说明原因与受影响的行为边界或文档;有关联 issue 请注明。 - 代码、测试与两种语言的文档放在同一个拉取请求中。 -- 不要把构建产物放进差异:`build/`、`test/`、`./make` 与 `.ci-deps/` 都是 - 生成物且被 gitignore。 +- 不要把构建产物放进差异:`build/`、`test/`、`./make` 与 `.ci-deps/` 均被 + gitignore。 - 必需检查通过、评审意见全部解决后,拉取请求才可合并。 ## 许可与归属 -- 库与项目源码使用 MIT 许可。新增的 C 源码与头文件应以 - `// SPDX-License-Identifier: MIT` 开头,就像 `include/sx.h`、`src/sx_adv.c` - 与 `tests/reg.c` 那样;已有的 SPDX 标注请勿改动。 -- 构建脚本以及源自 Forge 的 `src/export.h` 适用 Forge 的构建脚本例外条款, - 标识为 `GPL-3.0-or-later WITH LicenseRef-Forge-BuildScript-Exception`。 - `build.conf` 与 `src/export.h` 已带有该标识,`build.c` 同样适用该例外; - 不要把这部分构建工具改为 MIT,也不要删除这些标注。 -- 正则层使用 PCRE2(BSD-3-Clause)。其归属与许可全文位于 - [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md)。若新增第三方依赖, - 也要在该文件中补充它的声明与许可。 +- 库与项目源码使用 MIT 许可。新增 C 源码与头文件以 + `// SPDX-License-Identifier: MIT` 开头(如 `include/sx.h`、`src/sx_adv.c` + 与 `tests/reg.c`);已有 SPDX 标注请勿改动。 +- 构建脚本与源自 Forge 的 `src/export.h` 适用 Forge 构建脚本例外条款 + `GPL-3.0-or-later WITH LicenseRef-Forge-BuildScript-Exception`。 + `build.conf` 与 `src/export.h` 带有该标识,`build.c` 同样适用;不要把这 + 部分构建工具改为 MIT 或删除标注。 +- 正则层使用 PCRE2(BSD-3-Clause),归属见 + [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md);新增第三方依赖也 + 要在其中补充声明与许可。 - 项目许可全文见 [LICENSE](../../LICENSE)。 ## 目录结构 @@ -119,7 +116,8 @@ export UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 | [include/](../../include) | 公开头文件:`sx.h`(进阶层与 `sx_split`)以及它包含的 `sx_core.h` | | [src/](../../src) | 实现:`sx_core.c`、`sx_adv.c`、`sx_raw.c`,以及内部 `_sx.h` 与 `export.h` | | [tests/](../../tests) | 自包含的测试套件 | -| [build.c](../../build.c)、[build.conf](../../build.conf) | Forge 构建脚本及其配置 | +| [benchmarks/](../../benchmarks) | 经审计的 StringX / SDS / bstrlib 基准与复跑工具 | +| [build.c](../../build.c)、[build.conf](../../build.conf) | 构建脚本及其配置 | | [.github/workflows/](../../.github/workflows) | CI 与 CodeQL 工作流 | | [.github/scripts/](../../.github/scripts) | CI 使用的编译、分析与工具检查脚本 | | [docs/](../) | 本文档,含英文与简体中文 | diff --git a/docs/zh_cn/design.md b/docs/zh_cn/design.md index 4eff00a..8616730 100644 --- a/docs/zh_cn/design.md +++ b/docs/zh_cn/design.md @@ -4,39 +4,37 @@ # 设计与内部实现 -本页面向贡献者,以及需要推敲库的保证或进行移植的读者。它描述数据布局、 -算法、所有权模型,以及 `` 公开契约背后的取舍。契约本身记录在 -[缓冲区与视图 API 参考](api-buffer.md)、[查找 API 参考](api-search.md) -和[正则表达式](regex.md)页面中。 +本页面向需要推敲库的保证或进行移植的贡献者:数据布局、算法、所有权模型 +以及 `` 契约背后的取舍。契约本身见 +[缓冲区与视图 API 参考](api-buffer.md)、[查找 API 参考](api-search.md) 和 +[正则表达式](regex.md)。 ## 目标与非目标 -整个设计源自一组简短的目标: +设计源自一组简短目标: -- **字节精确的契约。** 每个操作都定义在字节上,其行为边界都写明。查找、 - 比较和正则都按长度工作,因此内嵌 NUL 字节是普通数据。 -- **零拷贝访问。** 切片是别名到缓冲区的 `sx_view_t` 值;查看或遍历子切片 - 不拷贝任何东西。 -- **每个缓冲区一个稳定句柄。** 一个 `sx_t *` 在其整个生命周期内标识该 - 缓冲区;修改函数返回 `self`,因此即使底层数组被重新分配,调用也能串联 - 起来。 -- **可预测的失败。** 文档化的非法输入会产生固定哨兵,而不是崩溃;超出 - 文档边界的输入属于契约之外。没有异常、错误码或全局错误状态。 -- **小接口面。** 一个公开头文件 ``、一个库、一个可选的由库自身链接 - 的高级依赖(PCRE2)。 +- **字节精确的契约。** 操作定义在字节上,边界都写明。查找、比较和正则 + 按长度工作,内嵌 NUL 是普通数据。 +- **零拷贝访问。** 切片是别名到缓冲区的 `sx_view_t` 值;查看子切片不拷贝。 +- **每个缓冲区一个稳定句柄。** `sx_t *` 在生命期内标识缓冲区;修改返回 + `self`,即使数组重新分配,调用也能串联。 +- **可预测的失败。** 文档化的非法输入产生固定哨兵而非崩溃;其余输入属于 + 契约之外。没有异常、错误码或全局错误状态。 +- **小接口面。** 一个头文件 ``、一个库、一个由库自身链接的高级依赖 + (PCRE2)。 同样刻意设定的非目标: -- **不提供文本编码层。** 库不解码 UTF-8、不做文本规范化,也不提供字符/ - 字素操作。字符串就是字节;正则层运行在 PCRE2 的 8 位非 UTF 模式。 -- **不感知 locale。** 比较、裁剪和字符类都定义在字节与固定 ASCII 集合上, +- **不提供文本编码层。** 不解码 UTF-8、不做规范化,也不提供字符或字素 + 操作。字符串就是字节;正则层运行在 PCRE2 的 8 位非 UTF 模式。 +- **不感知 locale。** 比较、裁剪和字符类都按字节与固定 ASCII 集合定义, 与 `LC_*` 无关。 -- **缓冲区不是线程安全的。** 已编译正则是不可变且可共享的;可变缓冲区 - 就是普通内存,需要外部同步。 +- **缓冲区不是线程安全的。** 已编译正则不可变且可共享;可变缓冲区是普通 + 内存,需要外部同步。 - **不支持自定义分配器、rope/流式结构或惰性视图。** 每个缓冲区都是一块 连续分配。 - **不自带正则引擎。** 模式语义属于 PCRE2;库只提供生命周期、扫描和替换 - 这些管线。 + 管线。 ## 分层与头文件 @@ -50,8 +48,8 @@ | `src/_sx.h` | 内部 | `struct _sx` 的定义 | 仅库内部 | | `src/export.h` | Forge 派生 | `SYMBOL_PUBLIC` 可见性宏(已入库) | 仅库内部 | -使用者包含 ``。`sx_core.h` 之所以是公开的,是因为 `` 包含 -它,但它不是第二个入口:`sx_split` 和正则层只在 `sx.h` 中声明。 +使用者包含 ``;`sx_core.h` 公开只是因为 `` 包含它。 +`sx_split` 和正则层只在 `sx.h` 中声明。 实现与头文件的分层相对应: @@ -61,24 +59,23 @@ | `src/sx_raw.c` | 分配原语(`sx__new`、`sx__reserve` 等) | | `src/sx_adv.c` | `sx_split` 与 PCRE2 封装 | -三个库翻译单元都直接使用私有的 `_sx` 布局;客户端代码只消费 `sx.h` 和 +三个库翻译单元都直接使用私有 `_sx` 布局;客户端代码只消费 `sx.h` 和 `sx_core.h`。 ### 为什么 sx_split 位于高级层 -`sx_split` 在 `sx.h` 中、包含 `sx_core.h` 之后声明,并在 -`src/sx_adv.c` 中实现。这一位置是有意为之: +`sx_split` 在 `sx.h` 中、包含 `sx_core.h` 之后声明,实现在 +`src/sx_adv.c`;位置是刻意的: -- 它返回 `malloc` 分配的视图数组,迭代约定与 `sx_reg_match_all`、 - `sx_reg_split` 相同:token 按顺序排列,随后是一个 `.ref == NULL` 的 - 结束哨兵,调用方用 `free()` 释放数组。把返回数组的视图 API 放在一起, - 可以让这套所有权约定集中在一处,而不必给核心层增加一个分配数组的 API。 -- `sx_split` 的扫描是自包含的。核心的查找原语是 `sx_core.c` 内部 - `static` 的 KMP 实现;高级层无法调用它,也不需要调用,因为分割扫描 - 本来就被输出规模所约束。源码注释直接说明了这一取舍:`O(n*m)` 的 - 字节精确扫描"对高级层来说足够,并且让这个翻译单元保持独立"。 -- 分割扫描不依赖 PCRE2:它只是普通的分隔符查找。它位于高级层的翻译单元 - 中,是按 API 形态归类,而不是按依赖归类。 +- 它返回 `malloc` 分配的视图数组,迭代约定与 `sx_reg_match_all`/ + `sx_reg_split` 相同(token 按序、`.ref == NULL` 结束哨兵、调用方 + `free`)。把返回数组的视图 API 放在一起,让所有权约定集中一处,而不必 + 给核心层增加分配数组的 API。 +- 扫描自包含:核心的 KMP 原语是 `sx_core.c` 内的 `static` 实现,高级层 + 无法调用;分割扫描本来也被输出规模约束。源码注释直说这一取舍: + `O(n*m)` 字节精确扫描"对高级层足够,并让该翻译单元保持独立"。 +- 它不依赖 PCRE2:只是普通分隔符查找,按 API 形态(而非依赖)归入高级 + 翻译单元。 ### 为什么 sx_raw.h 是内部头文件 @@ -93,17 +90,15 @@ int sx__reserve(_sx *s, size_t need); void sx__free(_sx *s); ``` -它属于内部有三个原因: +内部原因有三: -- 它交出 `_sx`——私有缓冲区结构,而 `sx_core.h` 只对其做前置声明; -- 它的函数用保留的双下划线前缀命名,并绕开公开错误模型 - (`sx__reserve` 返回 `int`,而公开 API 返回哨兵 `sx_t *`)——它们服务 - 于库自己的翻译单元,而不是客户端; -- 它不提供稳定性承诺。安装后的头文件集合包含它,是因为 Forge 会复制 - 整个 `include/*.h`(构建脚本同步整个目录),但它不属于受支持的公开 - API,客户端代码不得使用。四个 `sx__*` 辅助函数声明为 `SYMBOL_PUBLIC`, - 因此确实会出现在共享库的动态符号表中;但这种导出并不代表它们属于受支持 - 的 API。 +- 它交出 `_sx`——`sx_core.h` 只做前置声明的私有缓冲区结构; +- 函数使用保留的双下划线前缀,并绕开公开错误模型(`sx__reserve` 返回 + `int`,而非哨兵 `sx_t *`);它们服务于库自身翻译单元,不是客户端; +- 它不提供稳定性承诺。安装后的头文件集合包含它,是因为构建会复制整个 + `include/*.h`,但它不属于受支持 API,客户端不得使用。四个 `sx__*` + 辅助函数声明为 `SYMBOL_PUBLIC`,因此会出现在共享库动态符号表中;导出 + 不代表受支持。 ## 缓冲区布局与不变式 @@ -134,30 +129,28 @@ buffer: a b c d e f \0 view covers c d e 每个函数都保持以下不变式: 1. 对每个存活缓冲区都有 `ptr != NULL` 且 `cap >= 1`。 -2. `len + 1 <= cap`:始终留出结尾符的位置。 -3. 始终有 `ptr[len] == '\0'`。内容字节本身可以是 `'\0'`;结尾符是内容 - 之后的第一个 NUL。 -4. `len` 计的是内容字节数,不含结尾符。`sx_len` 以 `int` 返回它(见 +2. `len + 1 <= cap`:留出结尾符位置。 +3. 始终有 `ptr[len] == '\0'`。内容可含 `'\0'`;结尾符是内容之后的第一个 + NUL。 +4. `len` 计内容字节数,不含结尾符;`sx_len` 以 `int` 返回(见 [整数访问器](#整数访问器与-size_max))。 5. 库返回的视图满足 `ref = buffer.ref` 且 `offset + len <= buffer len`。 - API 不校验调用方自行构造的视图;边界超出所属缓冲区的视图属于契约之外。 -6. `sx_t *` 句柄地址在缓冲区生命期内稳定。`sx_buf_mut` 返回的 `ptr` - 在增长时**不**稳定:`realloc` 可能移动它。 -7. `[len, cap)` 区间的字节未指定:它们可能是陈旧内容,也可能是从未初始化 - 的内存。只有 `ptr[len]` 属于契约的一部分。 + API 不校验调用方构造的视图;越出缓冲区的视图属于契约之外。 +6. `sx_t *` 句柄地址在生命期内稳定;`sx_buf_mut` 返回的 `ptr` 在增长时 + **不**稳定,因为 `realloc` 可能移动它。 +7. `[len, cap)` 的字节未指定(陈旧或未初始化);只有 `ptr[len]` 属于 + 契约。 -不变式是结构性保证的:每个修改函数结尾都会执行 `ptr[len] = '\0'`,而 -`sx__reserve` 是唯一改变 `cap` 或 `ptr` 的地方。`sx_buf_mut` 允许调用方 -重写 `[0, len)` 而不改变 `len`;由于结尾符位于该区间之外,不变式仍然 -成立。 +不变式由结构保证:每个修改函数结尾都执行 `ptr[len] = '\0'`, +`sx__reserve` 是唯一改变 `cap` 或 `ptr` 的地方。`sx_buf_mut` 可重写 +`[0, len)` 而不改变 `len`;结尾符在该区间之外,不变式仍成立。 ## 分配与增长 ### 初始容量 -每个缓冲区都是 `sx__new(cap)` 的一次分配:它分配 `_sx` 头和 `cap` 字节 -的数组(最少按 1 处理,好让 `ptr[0]` 有落脚处)。各构造函数的 `cap` -选择如下: +每个缓冲区都是 `sx__new(cap)` 的一次分配:`_sx` 头加 `cap` 字节数组 +(最少 1,让 `ptr[0]` 有落脚处)。各构造函数的 `cap`: | 构造函数 | 初始 `cap` | 最大内容字节数 | | --- | --- | --- | @@ -168,15 +161,15 @@ buffer: a b c d e f \0 view covers c d e | `sx_dup(src)` | `src->len + 1` | `src->len` | | `sx_substr(h, idx, n)` | `n + 1` | `n` | -`sx_new()` 经由 `sx_new_with_cap(32)` 实现;32 字节的起点让最初几次追加 -不产生分配,同时不会浪费太多内存。从内容构造的构造函数精确分配 -`内容长度 + 1`,因此新建或拷贝出来的缓冲区容量是紧的。 +`sx_new()` 经 `sx_new_with_cap(32)` 实现:32 字节起点让最初几次追加不 +分配,也不浪费太多内存。从内容构造的构造函数精确分配 `内容长度 + 1`, +新建或拷贝的缓冲区容量是紧的。 ### 增长策略 -所有增长都经过 `sx__reserve(_sx *s, size_t need)`,它把 `need` 解释为 -调用方此后必须能够容纳的**内容字节数**。内部必须产生 `cap > need`, -即为 `need` 个字节加上结尾符留出空间。决策如下: +所有增长都经过 `sx__reserve(_sx *s, size_t need)`,`need` 是此后必须 +容纳的**内容字节数**。内部必须得到 `cap > need`,即为 `need` 字节加结尾符 +留空间: | 情况 | 新的 `cap` | | --- | --- | @@ -186,82 +179,75 @@ buffer: a b c d e f \0 view covers c d e | 默认,`cap >= 0x10000` | `max(cap + 0x10000, need + 1)` | | `-DSX_FORCE_EXACT_RESERVE` | `need + 1` | -默认策略在分配小于 64 KiB 时按几何级数翻倍,此后改为固定的 -`+0x10000` 步进。翻倍使每个追加字节的代价摊还为常数;固定步进则避免 -仅仅为了追加几个字节就把大块分配(例如 8 MiB)翻倍到 16 MiB。与 -`need + 1` 取 `max` 覆盖了单次调用需要超过下一个几何步长的情况。 +默认策略在分配小于 64 KiB 时翻倍,此后固定加 `+0x10000`。翻倍让每个 +追加字节的代价摊还为常数;固定步进避免仅为追加几个字节就把大块分配 +(例如 8 MiB)翻到 16 MiB。与 `need + 1` 取 `max` 覆盖单次调用超过下一个 +几何步长的情况。 -公开的 `sx_reserve(self, n)` 原样转发 `n`,因此保证 `cap >= n + 1`: -调用之后,缓冲区总共能容纳 `n` 个内容字节而无需再次重新分配。 -`sx_append`、`sx_write` 和 `sx_insert` 在拷贝前调用 -`sx__reserve(最终内容长度)`: +公开的 `sx_reserve(self, n)` 原样转发 `n`,保证 `cap >= n + 1`:调用后 +缓冲区总共可容纳 `n` 个内容字节,无需再次重新分配。`sx_append`、 +`sx_write`、`sx_insert` 在拷贝前调用 `sx__reserve(最终内容长度)`: - append:`need = len + 追加长度`; - write:`need = idx + 写入长度`;此后的 `len` 为 `max(len, idx + n)`; - insert:`need = len + 插入长度`;尾部用 `memmove` 后移。 -增长是单调的。收缩操作从不重新分配:`sx_truncate` 只在新长度更大时才 -预留,`sx_erase` 在既有分配内部移动字节,`sx_clear` 只重写 `ptr[0]`。 -精确预留测试对这两个性质都有断言(`tests/reserve_stress.c`)。 +增长单调;收缩从不重新分配:`sx_truncate` 只在上调时预留,`sx_erase` +原地移动字节,`sx_clear` 只重写 `ptr[0]`。精确预留测试对这两个性质都有 +断言(`tests/reserve_stress.c`)。 ### SX_FORCE_EXACT_RESERVE -`-DSX_FORCE_EXACT_RESERVE` 用 `cap = need + 1` 取代增长策略。此时分配 -正好在结尾符处结束,因此任何越过 `len` 的访问都会立刻落入 -AddressSanitizer 的红区,而不是藏在多余的容量后面。代价是每次增长都 -重新分配(逐字节追加的工作负载在拷贝次数上接近平方级),并且没有余量, -所以它是调试/测试模式,而不是生产模式。`tests/reserve_stress.c` 是它的 -专用配置:每个缓冲区都从 `cap == 1` 开始,用固定 LCG 驱动 1500 次伪随机 -修改,并与字节精确模型对照;每次重新分配后断言 `cap == len + 1`,同时 -断言"收缩从不重新分配"。 +`-DSX_FORCE_EXACT_RESERVE` 用 `cap = need + 1` 取代增长策略。分配正好 +结束在结尾符处,越过 `len` 的访问会立刻落入 AddressSanitizer 红区,而非 +藏在多余容量后。代价是每次增长都重新分配(逐字节追加在拷贝次数上接近 +平方级)且没有余量,因此是调试/测试模式。`tests/reserve_stress.c` 是 +专用配置:每个缓冲区从 `cap == 1` 开始,固定 LCG 驱动 1500 次伪随机修改, +与字节精确模型对照,并在每次重新分配后断言 `cap == len + 1`、收缩从不 +重新分配。 ## 视图与别名 -视图是本库的核心抽象:`sx_view_t` 保存一个缓冲区引用加上一个 -`(offset, len)` 窗口。返回视图从不拷贝、从不分配,也从不修改缓冲区。 -同一套表示用于整缓冲区视图(`sx_view`)、视图移动 -(`sx_view_advance`、`sx_view_range` 等)、分割 token 和正则匹配数组。 +视图是核心抽象:`sx_view_t` 保存缓冲区引用加 `(offset, len)` 窗口。返回 +视图从不拷贝、分配或修改缓冲区。同一表示服务于整缓冲区视图(`sx_view`)、 +视图移动(`sx_view_advance`、`sx_view_range` 等)、分割 token 和正则 +匹配数组。 调用方必须遵守的规则: -- **视图是快照。** 修改不会调整已捕获的视图。若长度发生变化,先前捕获的 - 偏移和长度可能不再描述同样的字节;修改后应重新派生视图。 -- **增长会使裸指针失效。** `sx_buf_mut` 和 `sx_buf_view_mut` 借用底层 - 数组;之后使缓冲区增长的修改可能 `realloc` 它。`sx_t *` 句柄稳定, - 指针不稳定。 -- **视图不得比缓冲区活得更久。** `ref` 是裸 `_sx *`;释放缓冲区就释放 - 了被引用对象。返回视图数组不会转移底层缓冲区的所有权。 -- **视图使用期间不要修改。** 对 `sx_split` token、 - `sx_reg_match_all` 数组和用户持有的视图,规则相同。 -- **`NULL` 视图表示"无"。** `{ref = NULL, offset = 0, len = 0}` 是 - 哨兵值;除此之外,库返回的视图都指向存活缓冲区。 - -别名修改是最微妙的部分。当源视图与目标引用同一个缓冲区时, -`sx_append_view`、`sx_write_view` 和 `sx_insert_view` 用 `memmove` -而不是 `memcpy` 拷贝。对 append 和 write 来说,这只是普通的、能安全 -处理重叠的移动,因此任何契约内的源视图都可以使用。`sx_insert_view` -则更窄,原因在于它的操作顺序: - -1. 先为**最终**内容长度预留空间(这正是源指针保持有效的原因: - `realloc` 会原地更新 `_sx.ptr`,因此之后取得的指针看到的是新分配); -2. 把尾部向右移动 `v.len` 个字节,写入 `[idx + n, len + n)`; -3. 在 `idx` 处用 `memmove` 写入插入的字节。 - -尾部移动使自别名带有条件:起点在插入点之前或正好在插入点 -(`v.offset <= idx`)的源窗口结束于 `idx + n` 或更早,因此移动不会 -覆盖它,第 3 步的 `memmove` 再负责处理剩余的重叠。已被测试覆盖的情形是 -`v.offset == idx`:把视图 `[2, 4)`(`"cd"`)插入 `"abcdef"` 的索引 2, -得到 `"abcdcdef"`。起点**在 `idx` 之后**的自别名窗口会在被读取之前就被 -尾部移动覆盖:把视图 `[3, 5)`(`"de"`)插入 `"abcdef"` 的索引 2,得到 -`"abdccdef"` 而不是 `"abdecdef"`;这类调用属于契约之外。 -`tests/reserve_stress.c` 末尾的回归用例覆盖的正是强制增长下的 -`v.offset == idx` 情形,锁定"先预留、后取指针"的顺序。带 `owned` 参数的 -变体(`sx_append(self, self)` 等)没有这层保护——它们会释放自己的参数, -对自别名而言属于契约之外。 +- **视图是快照。** 修改不调整已捕获视图;长度变化后应重新派生。 +- **增长使裸指针失效。** `sx_buf_mut`/`sx_buf_view_mut` 借用数组,之后 + 使缓冲区增长的修改可能 `realloc` 它。`sx_t *` 句柄稳定,指针不稳定。 +- **视图不得比缓冲区活得久。** `ref` 是裸 `_sx *`;释放缓冲区即释放 + 被引用对象。返回视图数组不转移缓冲区所有权。 +- **视图使用期间不要修改**——`sx_split` token、`sx_reg_match_all` 数组 + 和用户视图同理。 +- **`NULL` 视图表示"无"。** `{ref = NULL, offset = 0, len = 0}` 是哨兵; + 其他库返回视图指向存活缓冲区。 + +别名修改需小心。源视图与目标指向同一缓冲区时,`sx_append_view`、 +`sx_write_view` 和 `sx_insert_view` 用 `memmove` 而非 `memcpy`。 +append/write 是普通重叠安全移动,任何契约内源视图都可用。`sx_insert_view` +更窄: + +1. 先为**最终**内容长度预留空间(保持源指针有效:`realloc` 原地更新 + `_sx.ptr`,之后取得的指针看到新分配); +2. 尾部右移 `v.len` 字节,写入 `[idx + n, len + n)`; +3. 在 `idx` 处用 `memmove` 写入插入字节。 + +尾部移动使自别名有条件:起点在插入点或之前的源窗口 +(`v.offset <= idx`)结束于 `idx + n` 或更早,移动不会覆盖它,第 3 步的 +`memmove` 处理剩余重叠。被测试覆盖的是 `v.offset == idx`:把视图 +`[2, 4)`(`"cd"`)插入 `"abcdef"` 的索引 2,得到 `"abcdcdef"`。起点 +**在 `idx` 之后**的窗口在被读取前就被覆盖:把 `[3, 5)`(`"de"`)插入 +`"abcdef"` 的索引 2,得到 `"abdccdef"` 而非 `"abdecdef"`;该调用属于 +契约之外。`tests/reserve_stress.c` 末尾的回归用例覆盖强制增长下的 +`v.offset == idx`,锁定"先预留、后取指针"的顺序。带 `owned` 参数的变体 +(`sx_append(self, self)` 等)会释放自己的参数,自别名属于契约之外。 ## 所有权与错误模型 -所有权刻意保持显式且简单:谁收到拥有所有权的指针,谁负责释放。 +所有权刻意保持显式且小:谁收到拥有所有权的指针,谁负责释放。 | 操作 | 所有权 | | --- | --- | @@ -273,16 +259,20 @@ AddressSanitizer 的红区,而不是藏在多余的容量后面。代价是每 需要注意的细节: - **消费型调用在失败时也会消费。** `sx_append`/`sx_write`/`sx_insert` - 先尝试修改,然后无条件释放 `owned`。如果修改本身失败(分配失败), - 调用返回 `NULL`,但参数仍已被消费。参数为 `NULL` 时返回 `NULL`, - 不释放任何东西。 -- **句柄同一性。** 每次修改都返回 `self`,因此成功的修改可以串联: - `sx_append_cstr(sx_append_cstr(s, "a"), "b") == s`。句柄在增长前后 - 稳定;只有底层数组会移动。 -- **数组不拥有元素所指的缓冲区。** 释放 `sx_split` 或 - `sx_reg_match_all` 返回的数组并不是释放主体;视图只是变得不可达。 - -错误模型基于哨兵值,没有 `errno`、没有错误对象,也没有错误返回码: + 先尝试修改,再无条件释放 `owned`;修改失败时调用返回 `NULL`,但参数 + 仍被消费。参数为 `NULL` 时返回 `NULL`,不释放任何东西。 +- **写入范围拒绝是文档化行为。** 若 `idx + n` 使 `size_t` 溢出,或结果 + 末端无法预留(内容为 `SIZE_MAX` 时放不下结尾符),`sx_write*` 在拷贝前 + 返回 `NULL`,`self` 保持不变。`sx_write_view` 在保留别名的预预留之前 + 检查,因此被拒绝的范围不会改变容量。`tests/write_overflow.c` 与其精确 + 预留兄弟测试锁定该契约。 +- **句柄同一性。** 每次修改都返回 `self`,成功修改可以串联: + `sx_append_cstr(sx_append_cstr(s, "a"), "b") == s`。句柄在增长前后稳定; + 只有数组移动。 +- **数组不拥有元素所指的缓冲区。** 释放 `sx_split`/`sx_reg_match_all` + 数组不会释放主体;视图只是变得不可达。 + +错误模型基于哨兵值:没有 `errno`、错误对象或错误返回码。 | 情况 | 哨兵值 | | --- | --- | @@ -291,24 +281,23 @@ AddressSanitizer 的红区,而不是藏在多余的容量后面。代价是每 | "无匹配"视图(`sx_reg_match`) | `{ref = NULL, offset = 0, len = 0}` | | "无匹配"数组(`sx_reg_match_all`) | `NULL` | | 非法/空分隔符、非法正则、数组/字符串工厂分配失败 | `NULL` | +| 写入范围溢出或末端无法预留 | `NULL`;`self` 不变(`owned` 输入被消耗) | | 布尔谓词与 `sx_reg_is_match` | `0` | 两个后果是有意为之,并且都有文档: -- **"无结果"与"内存不足"可能无法区分。** `find_all` 家族和 `sx_reg_*` - 数组家族对两者都返回 `NULL`,因为契约没有给它们第三条通道。正则替换 - 家族则能区分:无匹配返回原样拷贝,`NULL` 表示非法输入或失败。 -- **`NULL` 句柄参数大多属于契约之外。** 只有显式检查的那些家族有定义的 - `NULL` 行为——`sx_new_from_cstr`、`sx_dup`、cstr/owned 修改参数、 - `sx_find*`、`sx_rfind*`、`sx_find_all*`、 - `sx_cmp*`/`sx_starts_with*`/`sx_ends_with*` 组、`sx_split` 以及 - `sx_reg_*` 调用。访问器(`sx_len`、`sx_cap`、`sx_buf_mut`、`sx_view` - 等)、视图移动函数和 `sx_free` 会解引用句柄,不接受 `NULL`。公开头 - 文件按函数写明这些边界。 - -错误不会留下构建到一半的缓冲区:失败的预留发生在拷贝任何字节之前, -因此 `self` 保持原内容与单 NUL 结尾不变式。唯一可见的例外是上文所述的 -被消费的 `owned` 参数。 +- **"无结果"与"内存不足"可能无法区分。** `find_all` 和 `sx_reg_*` + 数组家族对两者都返回 `NULL`,因为没有第三条通道。替换能区分:无匹配 + 返回原样拷贝,`NULL` 表示非法输入或失败。 +- **`NULL` 句柄参数大多属于契约之外。** 显式检查的家族——`sx_new_from_cstr`、 + `sx_dup`、cstr/owned 修改参数、`sx_find*`、`sx_rfind*`、 + `sx_find_all*`、`sx_cmp*`/`sx_starts_with*`/`sx_ends_with*`、 + `sx_split`、`sx_reg_*`——有定义的 `NULL` 行为。访问器(`sx_len`、 + `sx_cap`、`sx_buf_mut`、`sx_view` 等)、视图移动函数和 `sx_free` 会 + 解引用句柄、不接受 `NULL`;头文件按函数写明边界。 + +错误不会留下半成品缓冲区:失败的预留在任何拷贝前发生,`self` 保持原内容 +与单 NUL 不变式。唯一例外是上述被消费的 `owned` 参数。 ## 查找内部实现 @@ -319,8 +308,8 @@ static inline find_ret_t find(const sx_t *h, const char *needle, int len, size_t boundary, int opt); ``` -返回类型既可能是位置,也可能是指向结果数组的指针,因此实现选择一种宽度 -足以往返指针的整数类型: +返回类型可能是位置或指向结果数组的指针,因此实现选择宽度足以往返指针的 +整数类型: ```c #if SIZE_MAX > UINTPTR_MAX @@ -347,51 +336,66 @@ H = content length of h a match window [p, p+m) counts only if p >= region_start and p+m <= region_end ``` -各封装填入文档化的边界:`sx_find*` 使用 `boundary = 0`;`sx_rfind*` 使用 -`boundary = len(h)` 并带向右标志;`sx_find_view_b` 和 -`sx_rfind_view_b` 传递调用方的 boundary。`len <= 0`、空区域或短于 -needle 的区域都按模式要求报告"未找到"——标量封装返回 `(size_t)-1`, -数组封装在内部返回计数为 0 的数组(再由 `sx_find_all*` 转成 `NULL`)。 +各封装填入文档化边界:`sx_find*` 用 `boundary = 0`,`sx_rfind*` 用 +`boundary = len(h)` 并带向右标志,有界变体 `sx_find_view_b`/ +`sx_rfind_view_b` 传调用方 boundary。`len <= 0`、空区域或短于 needle 的 +区域报告"未找到"——标量封装返回 `(size_t)-1`,数组封装在内部返回计数 0 +的数组(再由 `sx_find_all*` 转成 `NULL`)。 -`len` 是 needle 的内容长度(`sx_t` needle)、`v.len`(视图 needle), -或 `(int)strlen(s)`(cstr needle——注意这里的窄化转换,它属于 `int` -实际限制之一)。needle 字节直接从视图或缓冲区读取;查找是字节精确的, -类似 `memcmp`。 +`len` 是 needle 内容长度(`sx_t` needle)、`v.len`(视图 needle)或 +`(int)strlen(s)`(cstr needle——窄化转换是一个实际 `int` 限制)。 +needle 字节直接从视图或缓冲区读取;查找是字节精确的,类似 `memcmp`。 ### 单字节 needle:memchr 与 memrchr 当 `m == 1` 时,原语使用 C 库的向量化扫描: - **最左:** `memchr(t + l, c, er - l)`; -- **最右:** 在 glibc 上使用 `memrchr(t, c, er)`。`memrchr` 是 GNU - 扩展而非 ISO C 函数,因此 `sx_core.c` 手动声明它,并且只在定义了 - `__GLIBC__` 且未定义 `SX_FORCE_NO_MEMRCHR` 时使用。回退方案是逐字节 - 反向循环,在到达 `l` 之前保留最后一个(最右的)命中。 +- **最右:** glibc 上用 `memrchr(t, c, er)`。它是 GNU 扩展而非 ISO C, + 因此 `sx_core.c` 手动声明,并只在定义了 `__GLIBC__` 且未定义 + `SX_FORCE_NO_MEMRCHR` 时使用。回退是逐字节反向循环,在到达 `l` 前保留 + 最后一个(最右)命中。 + +最右快路径可从 `0` 搜索,因为向右查找总设置 `l = 0`;`er` 已携带 +boundary。`SX_FORCE_NO_MEMRCHR` 用于在 glibc 上构建并测试可移植路径。 + +`m == 1` 的"全部"模式从上一个命中 + 1 处反复调用 `memchr`,因此报告 +**重叠**位置,正是 `sx_find_all*` 承诺的行为(`"aa"` 在 `"aaaa"` 中报告 +0、1、2)。 -最右快路径可以从 `0` 开始搜索,因为向右查找总是设置 `l = 0`;`er` -已经携带了调用方的 boundary。`SX_FORCE_NO_MEMRCHR` 用于在 glibc 系统上 -构建并测试可移植路径。 +### 最左原生快路径 -对 `m == 1` 的"全部"模式,实现从上一个命中 + 1 处反复调用 `memchr`。 -这样会报告**重叠**位置,而这正是 `sx_find_all*` 承诺的行为 -(`"aa"` 在 `"aaaa"` 中报告 0、1 和 2)。 +最左单结果调用(`sx_find`、`sx_find_view`、`sx_find_view_b`、 +`sx_find_cstr`)经过 `find_first()`;在 glibc 上它可能先走原生路径,而不 +进入可移植的 KMP 实现。`try_native_find_first` 标记为 `noinline`,其分支 +不会改变回退实现的优化: + +1. 拒绝空/负长度 needle 或放不下一个窗口的区域; +2. `m == 1`:一次 `memchr`; +3. 先比较区域起点处的窗口(首段命中无需预处理); +4. 从下一个偏移用 `memchr` 找 needle 首字节,再用 `memchr` 找末字节, + 把候选起点收窄到窗口可能结束的位置; +5. 对 `m <= 32` 的 needle 在剩余区域调用 `memmem`;否则放弃。 + +放弃时回退到 KMP。原生路径不分配内存,只有回退的前缀表会分配。非 glibc +目标或定义 `-DSX_FORCE_NO_MEMMEM` 时该路径不编译;`tests/find_differential_fallback.c` +让相同差分用例走强制可移植构建。 ### 更长的 needle:KMP -当 `m >= 2` 时,原语计算 KMP 前缀表(`pi`,一次 -`malloc(m * sizeof(size_t))`),并在 `O(n + m)` 时间内扫描区域: +当 `m >= 2` 时,回退路径(以及 `sx_rfind*` 与 `sx_find_all*` 使用的 +原语)计算 KMP 前缀表(`pi`,一次 `malloc(m * sizeof(size_t))`),并在 +`O(n + m)` 时间内扫描区域: -- **最左优先与全部模式**在 `[l, er)` 上使用正向 KMP。完整匹配时,单结果 - 模式立即返回;全部模式记录起始偏移,并以 `q = pi[m - 1]` 继续,这正 - 是它能报告重叠出现的原因。 -- **最右优先**使用反向 KMP:用索引映射在*反向* needle 上计算同一张前缀 - 表(不拷贝 needle),再从 `er - 1` 向下扫描到 `l`。当已匹配后缀长度 - 达到 `m` 时,当前文本索引就是窗口起点。 +- **最左优先与全部模式**在 `[l, er)` 上正向 KMP。完整匹配时单结果模式 + 立即返回;全部模式记录起点并以 `q = pi[m - 1]` 继续,因此报告重叠出现。 +- **最右优先**用反向 KMP:以索引映射在*反向* needle 上计算同一前缀表 + (不拷贝),从 `er - 1` 向下扫描到 `l`。已匹配后缀达到 `m` 时,当前 + 索引就是窗口起点。 -全部模式的结果数组从容量 16 开始,带溢出保护地翻倍 -(`cap > SIZE_MAX / 2 / sizeof(*r)` 时以 `NULL` 中止),返回前再用 -`realloc` 收缩一次。其布局为 `{count, pos0, pos1, ...}`:`arr[0]` 是 -计数,不是位置。 +全部模式数组从容量 16 开始,带溢出保护翻倍(`cap > SIZE_MAX / 2 / +sizeof(*r)` 时以 `NULL` 中止),返回前用 `realloc` 收缩一次。布局为 +`{count, pos0, pos1, ...}`:`arr[0]` 是计数,不是位置。 ### 复杂度 @@ -399,14 +403,16 @@ needle 的区域都按模式要求报告"未找到"——标量封装返回 `(si | --- | --- | --- | --- | | 单字节 needle,最左单结果 | `memchr` | `O(n)` | 无 | | 单字节 needle,最右单结果 | `memrchr` 或反向扫描 | `O(n)` | 无 | -| needle 长度 >= 2,单结果 | KMP | `O(n + m)` | `O(m)` 前缀表 | +| needle 长度 >= 2,最左单结果(原生路径) | 字节检查 + `memmem`(`m <= 32`) | 典型 `O(n + m)` | 无 | +| needle 长度 >= 2,最左单结果(回退) | KMP | `O(n + m)` | `O(m)` 前缀表 | +| needle 长度 >= 2,最右单结果 | 反向 KMP | `O(n + m)` | `O(m)` 前缀表 | | `sx_find_all*`,单字节 | 反复 `memchr` | `O(n)` 扫描 | `O(k)` 结果 | | `sx_find_all*`,更长 needle | KMP | `O(n + m)` 扫描 | `O(m) + O(k)` 结果 | | `sx_split` | 两遍 `is_sep` | 最坏 `O(H * m)` | `O(tokens)` 结果 | -`n` 是区域长度,`m` 是 needle 长度,`k` 是匹配数。数组封装只分配结果; -`sx_find*` / `sx_rfind*` 返回标量,不分配任何东西(除了 KMP 表,它在 -返回前释放)。 +`n` 是区域长度,`m` 是 needle 长度,`k` 是匹配数。数组封装只分配结果。 +`sx_find*` 在原生路径上不分配;KMP 回退(以及所有多字节 `sx_rfind*`) +会分配一张临时前缀表,并在返回前释放。 ## 正则封装内部实现 @@ -420,26 +426,23 @@ typedef struct sx_reg_t { ### 编译与释放 -`sx_reg_compile` 用固定参数调用 PCRE2: -`pcre2_compile(pattern, PCRE2_ZERO_TERMINATED, 0, ...)`。这里的 `0` -是选项字——没有 `CASELESS`、没有 `UTF`、什么都没有——而 -`PCRE2_ZERO_TERMINATED` 表示模式是 C 字符串。PCRE2 的错误码和错误位置 -只是为了满足函数签名而接收,随后被丢弃,因此所有编译失败都归结为 -`NULL`。编译会分配 PCRE2 代码对象和小的 `sx_reg_t` 封装;`sx_reg_free` -释放两者,并接受 `NULL`。 +`sx_reg_compile` 调用 +`pcre2_compile(pattern, PCRE2_ZERO_TERMINATED, 0, ...)`。`0` 是选项字 +(没有 `CASELESS`、没有 `UTF`),`PCRE2_ZERO_TERMINATED` 表示 C 字符串 +模式。PCRE2 错误码和位置只为满足签名而接收并丢弃,因此所有编译失败都 +归结为 `NULL`。编译分配代码对象和小 `sx_reg_t`;`sx_reg_free` 释放两者, +接受 `NULL`。 ### 每次调用的匹配数据与扫描规则 -PCRE2 把已编译模式与每次调用的匹配数据分开。封装在每次调用时用 -`pcre2_match_data_create_from_pattern(r->code, NULL)` 创建匹配数据, -并在返回前释放。这正是已编译句柄可以跨线程共享的原因:句柄中不保存 -任何匹配状态。 +PCRE2 把已编译模式与每次调用的匹配数据分开。封装用 +`pcre2_match_data_create_from_pattern(r->code, NULL)` 创建匹配数据并在 +返回前释放,句柄不保存匹配状态,因此可跨线程共享。 -单步匹配是 `pcre2_match(code, subject, len, offset, 0, md, NULL)`。注意 -主体以显式**长度**传入,而不是当作 C 字符串;最后一个参数(匹配上下文) -是 `NULL`,因此适用 PCRE2 的默认匹配限制。负返回值(无匹配,或诸如匹配 -限制之类的 PCRE2 匹配期错误)被当作"没有更多匹配";封装不暴露匹配期 -错误码。 +单步匹配是 `pcre2_match(code, subject, len, offset, 0, md, NULL)`:主体 +以显式**长度**传入而非 C 字符串,`NULL` 匹配上下文意味适用 PCRE2 默认 +匹配限制。负返回值(无匹配,或匹配限制之类匹配期错误)表示"没有更多 +匹配";不暴露匹配期错误码。 `sx_reg_match_all` 和 `sx_reg_split` 共用的扫描推进逻辑是: @@ -449,10 +452,10 @@ static size_t reg_next_at(size_t start, size_t end) { } ``` -下一次搜索从匹配结尾开始;对零长匹配则从起点后一个字节开始,因此扫描 -保证前进。每一步都用 `offset` 调用 `pcre2_match`;当 `offset` 越过主体 -长度时,PCRE2 返回错误,循环结束。这就是 `a*` 对 `"bbb"` 报告偏移 0、 -1、2、3 处的空匹配,以及 `$` 对 `"abc"` 报告偏移 3 处单个空匹配的原因。 +下一次搜索从匹配结尾开始;零长匹配则从起点后一字节开始,因此扫描保证 +前进。每步用 `offset` 调用 `pcre2_match`;越过主体长度时 PCRE2 报错、 +循环结束。因此 `a*` 对 `"bbb"` 报告偏移 0–3 的空匹配,`$` 对 `"abc"` +报告偏移 3 的一个空匹配。 ### match_all 与 split 的两遍定长策略 @@ -464,11 +467,10 @@ malloc((cnt + 1) * sizeof view) -> exact size, no realloc pass 2: repeat the same scan -> fill views, then arr[cnt] = {0} guard ``` -扫描是确定性的(相同模式、相同主体、相同起始偏移),因此两遍看到完全 -相同的位置。`sx_reg_split` 还额外跟踪空隙起点 `seg`:每个 token 是 -`[seg, match_start)`,随后 `seg` 移动到 `match_end`;最后一个 token 是 -`[seg, len)`。这样正好产生 `匹配数 + 1` 个 token,包括空的首尾 token, -以及相邻匹配或零长匹配产生的空 token。 +扫描是确定性的(相同模式、主体和起始偏移),两遍看到相同位置。 +`sx_reg_split` 还跟踪空隙起点 `seg`:每个 token 是 `[seg, match_start)`, +`seg` 移到 `match_end`;最后一个 token 是 `[seg, len)`。这正好产生 +`匹配数 + 1` 个 token,包括空的首尾 token 和相邻或零长匹配产生的空 token。 ### 替换:两次 pcre2_substitute 调用 @@ -479,10 +481,10 @@ options |= PCRE2_SUBSTITUTE_UNSET_EMPTY | PCRE2_SUBSTITUTE_UNKNOWN_UNSET; ``` `UNSET_EMPTY` 让未参与匹配的组展开为空;`UNKNOWN_UNSET` 让不存在的组号 -展开为空,而不是让整个替换失败。`sx_reg_replace` 额外传入 +展开为空,而不是让替换失败。`sx_reg_replace` 额外传 `PCRE2_SUBSTITUTE_GLOBAL`;`sx_reg_replace_first` 不传。 -由于替换前不知道输出长度,封装调用两次 `pcre2_substitute`: +由于事先不知道输出长度,封装替换两次: ```text call 1: output buffer NULL, PCRE2_SUBSTITUTE_OVERFLOW_LENGTH, &needed @@ -494,9 +496,9 @@ sx_new_with_cap(used + 1) (new public buffer) memcpy(ptr, buf, used); len = used; ptr[used] = '\0' ``` -拷贝完成后释放临时缓冲区。若第一次调用没有返回 `PCRE2_ERROR_NOMEMORY`, -说明模板/替换对被拒绝;封装返回 `NULL`,且从不改写主体。没有匹配时, -PCRE2 不替换任何内容,输出就是主体的原样拷贝——这是正常成功,不是错误。 +拷贝后释放临时缓冲区。第一次调用未返回 `PCRE2_ERROR_NOMEMORY` 说明 +模板/替换对被拒绝;封装返回 `NULL` 且不改写主体。无匹配时 PCRE2 不替换 +任何内容,输出是主体的原样拷贝——正常成功,不是错误。 ### 分配一览 @@ -511,33 +513,32 @@ PCRE2 不替换任何内容,输出就是主体的原样拷贝——这是正 | `sx_reg_replace*` | PCRE2 内部匹配数据 + 临时缓冲区 + `sx_t` | 两次替换调用 | 封装不启用 PCRE2 JIT(从不调用 `pcre2_jit_compile`),也不暴露编译或 -匹配选项。模式级特性(例如内联选项)仍然生效,因为它们是模式的一部分, -而不是封装层的策略。 +匹配选项;模式级特性(例如内联选项)仍生效,因为它们属于模式而非封装 +策略。 ## 并发 -- **已编译正则句柄不可变且可共享。** 每次调用的状态都保存在调用内部 - 创建的、归调用方所有的匹配数据中;封装没有全局变量。一个 - `sx_reg_t *` 可以同时服务多个线程的调用。 -- **缓冲区没有同步。** 它们是普通堆内存。多个线程并发读取同一缓冲区没 - 问题,前提是无人修改;修改需要外部同步。视图让规则更严格:与改变长度 - 的修改并发读取视图构成数据竞争(契约之外)。 -- **所有权需要协调。** 只有一个所有者的缓冲区不能被两个线程同时消费; - 数组是单一所有者的结果。 +- **已编译正则句柄不可变且可共享。** 每次调用的状态在调用内部创建、归 + 调用方所有的匹配数据中;封装没有全局变量,一个 `sx_reg_t *` 可服务多个 + 线程。 +- **缓冲区没有同步。** 它们是普通堆内存:无人修改时并发读安全;修改需要 + 外部同步。视图更严格——与改变长度的修改并发读视图是数据竞争 + (契约之外)。 +- **所有权需要协调。** 单一所有者的缓冲区不能被两个线程同时消费;数组是 + 单一所有者的结果。 -库本身从不修改全局状态,因此只要调用方对每个缓冲区的访问做了同步,在多 -线程程序中使用它就是安全的。 +库从不修改全局状态,因此只要调用方同步每个缓冲区的访问,多线程程序中 +使用就是安全的。 ## 可移植性与限制 -### memrchr 与 SX_FORCE_NO_MEMRCHR +### memrchr、memmem 与可移植开关 -查找路径中唯一的非 ISO C API 是 `memrchr`,一个 glibc 扩展。 -`sx_core.c` 手动声明它,而不依赖特性测试宏,并且只在定义了 -`__GLIBC__` 且构建未定义 `SX_FORCE_NO_MEMRCHR` 时编译进去。在其他平台 -(以及强制开关打开时),最右单字节查找回退到可移植的逐字节反向循环。 -仓库内的测试套件运行默认的 glibc 路径;该开关存在的目的,是让回退路径 -也能在 glibc 上构建并检查。 +查找路径使用两个 glibc 扩展:`memrchr`(最右单字节扫描)和 `memmem` +(最左原生快路径)。`sx_core.c` 手动声明两者,并只在定义了 `__GLIBC__` +时编译进去。`-DSX_FORCE_NO_MEMRCHR` 与 `-DSX_FORCE_NO_MEMMEM` 强制使用 +可移植路径;仓库测试除 glibc 路径外,还运行强制可移植的差分查找测试, +因此两条回退路径都能在 glibc 上构建并检查。 ### 整数访问器与 SIZE_MAX @@ -549,44 +550,41 @@ PCRE2 不替换任何内容,输出就是主体的原样拷贝——这是正 | `sx_cap` | `int`(总分配量) | | 偏移(`sx_find*`、视图字段、正则视图) | `size_t` | -内容字节数超过 `INT_MAX` 的缓冲区在测试契约之外。这是有意的 API 简化 -(目标场景是中小字符串),不是缺陷;常见平台上每个缓冲区的实际上限约为 -2 GiB。同样的 `int` 窄化还出现在查找封装把基于 `strlen` 的 needle 长度 -转换为 `int` 的地方。 +内容字节数超过 `INT_MAX` 的缓冲区在测试契约之外。这是面向中小字符串的 +有意简化,不是缺陷;实际上限约 2 GiB。同样的 `int` 窄化出现在查找封装把 +基于 `strlen` 的 needle 长度转换为 `int` 的地方。 `SIZE_MAX` 保护出现在尺寸运算可能回绕的地方: -- `sx__reserve` 拒绝 `need == SIZE_MAX`(否则无法再加上结尾符); -- `sx_find_all*` 的数组增长在翻倍前检查 - `cap > SIZE_MAX / 2 / sizeof(*r)`; -- 没有通用的溢出检查:极端的 `n` 或 `off` 参数可能让无符号尺寸运算 - 回绕,这类调用在测试契约之外。 +- `sx__reserve` 拒绝 `need == SIZE_MAX`(否则无法再加结尾符); +- `sx_find_all*` 数组增长在翻倍前检查 `cap > SIZE_MAX / 2 / sizeof(*r)`; +- 没有通用溢出检查:极端 `n` 或 `off` 可能让无符号尺寸运算回绕,这类 + 调用在测试契约之外。 ### 平台假设 -- 库使用 C23。参考工具链是 Linux 上的 GCC 14+ 与 Clang 19+(CI 使用 - Ubuntu 24.04、GCC 14 和 Clang 19);除 `SYMBOL_PUBLIC` 和 glibc - `memrchr` 快路径外,源码不依赖编译器特定扩展。 -- `src/export.h` 是已入库的 Forge 派生头文件。它把 `SYMBOL_PUBLIC` - 定义为 GCC/Clang 的 `__attribute__((visibility("default")))`,以及 - MSVC 的 `_declspec(dllexport)`;构建采用隐藏的默认可见性,因此恰好是 +- 库使用 C23,参考工具链为 Linux 上的 GCC 14+ 与 Clang 19+(CI: + Ubuntu 24.04、GCC 14、Clang 19)。除 `SYMBOL_PUBLIC` 和 glibc + `memrchr` 外,源码不依赖编译器特定扩展。 +- `src/export.h` 是已入库的 Forge 派生头文件,把 `SYMBOL_PUBLIC` 定义为 + GCC/Clang 的 `__attribute__((visibility("default")))` 与 MSVC 的 + `_declspec(dllexport)`。构建使用隐藏默认可见性,因此恰好 `SYMBOL_PUBLIC` 函数从 `libstringx.so` 导出。 -- 正则层需要 PCRE2 10.46(`pcre2-8`),8 位、非 UTF 模式。构建把它 - 链接进 `libstringx`,因此使用者无需添加 PCRE2 链接参数,但 PCRE2 是 - 共享库的运行时依赖。 -- 安装与 Debian 打包目标在 `build.c` 中由 `LINUX` 宏保护;库本身作为 - 普通 C23 代码编译。 +- 正则层需要 PCRE2 10.46(`pcre2-8`,8 位、非 UTF)。构建把它链接进 + `libstringx`,使用者无需添加 PCRE2 链接参数,但它仍是共享库的运行时 + 依赖。 +- 安装与 Debian 打包目标由 `build.c` 中的 `LINUX` 宏保护;库本身按普通 + C23 编译。 ## 测试策略 -`tests/` 下的每个文件都是自包含程序。其文件头注释声明构建方式 -(由固定版本的 Forge 构建系统消费的 `// Include`、`// Source`、 -`// Option`、`// Link`、`// Library` 行),并记录它的**行为边界**: -一个"In scope (contract)"列表和一个"Out of contract (not exercised)" -列表。文件头本身也是契约的一部分:行为变化时,边界列表要随之修改 -(见[贡献指南](contributing.md))。 +`tests/` 下每个文件都是自包含程序。文件头注释声明构建方式(由固定版本 +构建系统消费的 `// Include`、`// Source`、`// Option`、`// Link`、 +`// Library` 行),并记录**行为边界**:"In scope (contract)"列表和 +"Out of contract (not exercised)"列表。文件头也是契约的一部分:行为变化 +必须同步更新边界列表(见[贡献指南](contributing.md))。 -测试套件(20 个测试)按主题一文件: +测试套件(24 个)按主题一文件: | 测试 | 锁定的内容 | | --- | --- | @@ -597,6 +595,8 @@ PCRE2 不替换任何内容,输出就是主体的原样拷贝——这是正 | `ends_with.c` | 后缀谓词 | | `find.c` | 最左查找、有界区域、`strlen` needle | | `find_all.c` | 全部出现,包含重叠位置 | +| `find_differential.c` | 最左查找对照独立窗口 oracle(原生路径) | +| `find_differential_fallback.c` | 相同用例,使用 `-DSX_FORCE_NO_MEMMEM`(可移植 KMP 路径) | | `insert.c` | 插入、跨增长时的别名 | | `new.c` | 构造函数、`sx_dup`、容量边界情况 | | `reg.c` | 正则家族、二进制安全主体、零长匹配处理 | @@ -610,32 +610,38 @@ PCRE2 不替换任何内容,输出就是主体的原样拷贝——这是正 | `view_move.c` | advance / retreat / shift / range 的钳制 | | `view_trim.c` | 空白裁剪集合与空视图钳制 | | `write.c` | 覆盖、尾部追加与填充语义 | +| `write_overflow.c` | `SIZE_MAX` 写入范围返回 `NULL`、`self` 不变、消耗 `owned` 输入 | +| `write_overflow_exact.c` | 相同用例,使用 `-DSX_FORCE_EXACT_RESERVE` | + +部分测试在普通配置与强制配置之间共享本地用例头(`find_differential.h`、 +`write_overflow_cases.h`);每个 `.c` 仍然是独立目标。 测试如何运行: -- 每个测试都**直接编译库源码**,并使用其文件头中的每测试选项。 - 内存检查器开启:AddressSanitizer、UBSan,以及在 Linux 上通过 ASan - 启用的 LeakSanitizer,因此泄漏检查器是所有所有权规则的见证者。CI 设置 +- 每个测试用其文件头选项**直接编译库源码**。内存检查器开启: + AddressSanitizer、UBSan,以及在 Linux 上通过 ASan 启用的 + LeakSanitizer——泄漏检查器是所有所有权规则的见证。CI 设置 `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1` 和 `UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1`。 -- `tests/reserve_stress.c` 是唯一用 `-DSX_FORCE_EXACT_RESERVE` 构建的 - 测试。它用确定性 LCG 驱动 append、insert、erase、write、truncate 和 - 别名视图修改,与字节精确模型对照,并包含别名 `insert_view` 增长的回归 - 用例。 -- CI 还会把构建好的库安装到临时前缀,通过 `pkg-config` 把 - `tests/reg.c` 链接到**安装后的共享库**(带 rpath)并运行。这样除了 - 源码级行为外,还验证了公开头文件、导出符号和 PCRE2 链接;随后检查生成 - 的 Debian 包。 -- 没有故障注入,因此测试套件不会覆盖分配失败分支(预留测试的注释指出, - 没有故障注入就无法表达这样的测试)。文档化的 OOM 哨兵是从代码推得, - 而不是在测试中观察到的。 +- `tests/reserve_stress.c` 与 `tests/write_overflow_exact.c` 使用 + `-DSX_FORCE_EXACT_RESERVE` 构建:前者用确定性 LCG 驱动 append、insert、 + erase、write、truncate 和别名视图修改,与字节精确模型对照,包含别名 + `insert_view` 增长回归;后者以精确大小分配重跑溢出用例。 +- CI 还运行专项审计工作流:Write safety 在不可变旧实现上复现溢出并比较 + 写入成本;Search performance 对比基线;benchmarks 重跑经审计的 + StringX/SDS/bstrlib 基准(见 [ci.md](ci.md))。 +- CI 还把库安装到临时前缀,通过 `pkg-config` 把 `tests/reg.c` 链接到 + **安装后的共享库**(带 rpath)运行,并检查生成的 Debian 包——验证公开 + 头文件、导出符号和 PCRE2 链接。 +- 没有故障注入,因此不覆盖分配失败分支;预留测试注释指出没有故障注入 + 无法表达这种测试。文档化的 OOM 哨兵由代码推得,未在测试中观察。 - `./make check` 目标用 `-Wall -Wextra -Wpedantic -Werror` 编译生产代码; - GCC 构建还运行 `-fanalyzer`(CI 中使用 + GCC 构建还运行 `-fanalyzer`(CI 中用 `-O1 -fno-analyzer-state-merge`),CodeQL 用 `security-and-quality` 查询扫描。 -- 测试禁用 LTO(`build.c` 中的 `set(TARGET_LTO, 1, DISABLE)`),因为 - 固定版本的 Forge 为并行 Clang 链接发出仅 GCC 支持的 `-flto=N` 标志。 - 生产库目标保留 LTO。 +- 测试禁用 LTO(`build.c` 中 `set(TARGET_LTO, 1, DISABLE)`),因为 + 固定版本的构建工具为并行 Clang 链接发出仅 GCC 支持的 `-flto=N`;生产 + 库目标保留 LTO。 ## 设计取舍 @@ -649,6 +655,8 @@ PCRE2 不替换任何内容,输出就是主体的原样拷贝——这是正 | `int` 长度访问器 | 紧凑、简单的 API | 实际约 2 GiB 的缓冲区上限;窄化转换 | | 哨兵错误模型 | 无全局状态、无错误传递、确定性 | "无结果"与 OOM 可能混淆;没有诊断信息 | | 数组由调用方释放,句柄由库释放 | 所有权显式、可预测 | 需要知道两个释放函数(`free` 与 `sx_free`) | +| 最左原生快路径 | glibc 上常见查找更快,`m <= 32` 时不分配内存 | 额外的 libc 特定代码,需要强制可移植测试 | +| 受检的写入范围算术 | 算术溢出返回文档化的 `NULL`,而不是破坏内存 | 每次写入多一个分支;`owned` 输入仍被消耗 | | KMP + `memchr`/`memrchr` | 最坏 `O(n + m)` 有保证,代码简单,单字节路径向量化 | `m >= 2` 时需要前缀表分配;平均速度低于优化过的子串查找 | | `sx_find_all*` 报告重叠结果 | 完整位置集合;对字节扫描有用 | 调用方必须预期偏移会重叠 | | 正则非重叠扫描 | 标准 PCRE2 行为;保证前进 | 无法报告重叠的正则匹配 | @@ -657,17 +665,15 @@ PCRE2 不替换任何内容,输出就是主体的原样拷贝——这是正 | 已编译正则不可变且无内部锁 | 句柄可共享且无需同步 | 缓冲区仍需调用方同步 | | 构建期配置宏 | 增长/memrchr 策略零运行时成本 | 改变策略需要重新构建 | -这些是取舍,不是意外。测试锁定可观察的后果,头文件注释写明每条规则 -契约之外的那一面。 +这些是取舍,不是意外:测试锁定可观察后果,头文件注释写明契约之外的一面。 ## 许可 -项目源码采用 MIT 许可(见 [LICENSE](../../LICENSE) 以及源码中的 SPDX -标注)。Forge 派生的构建工具遵循构建脚本例外:`build.conf` 与 +项目源码采用 MIT 许可(见 [LICENSE](../../LICENSE) 与源码 SPDX 标注)。 +Forge 派生的构建工具遵循构建脚本例外:`build.conf`、`build.c` 与 `src/export.h` 带有 -GPL-3.0-or-later WITH LicenseRef-Forge-BuildScript-Exception 的 SPDX -标识,`build.c` 也由同一例外覆盖;库源码本身仍为 MIT。正则层使用 PCRE2 -(BSD-3-Clause);见 +`GPL-3.0-or-later WITH LicenseRef-Forge-BuildScript-Exception` SPDX +标识;库源码本身仍为 MIT。正则层使用 PCRE2(BSD-3-Clause);见 [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md)。 --- diff --git a/docs/zh_cn/getting-started.md b/docs/zh_cn/getting-started.md index ce70338..19fa015 100644 --- a/docs/zh_cn/getting-started.md +++ b/docs/zh_cn/getting-started.md @@ -4,12 +4,10 @@ # 快速上手 -String X 是一个轻量的 C23 字符串库:它把每个字符串视为一段以单个 NUL -结尾的缓冲区,而它的每一段切片都是一个零拷贝视图。所有缓冲区都按字节长度 -处理,内嵌的 NUL 字节是普通数据,不会被 C 字符串规则截断。公开接口只有 -一个头文件 `` 和一个库 `libstringx`(`-lstringx`);可选的进阶 -层通过 PCRE2 提供正则表达式。本页带你从一份全新检出的代码走到一个可运行 -的程序。文档描述的是 **v0.5**。 +String X 是一个轻量的 C23 字符串库:每个字符串是一段 NUL 结尾的缓冲区, +切片是零拷贝视图,全部按字节长度处理(内嵌 NUL 是普通数据)。公开接口只有 +一个头文件 `` 和一个库 `libstringx`(`-lstringx`);可选的 PCRE2 进阶层 +提供正则表达式。版本:**v0.5**。 ## 环境要求 @@ -17,22 +15,21 @@ String X 是一个轻量的 C23 字符串库:它把每个字符串视为一段 | --- | --- | | Linux | 经过测试的平台;构建与测试均面向 Linux | | C23 编译器 | GCC 14+ 或 Clang 19+;CI 在 Ubuntu 24.04 上使用 GCC 14 与 Clang 19 | -| `forge` | `https://github.com/minelogy-dev/forge`;把 `build.c` 编译成本地 `./make` 可执行文件 | +| `forge` | [github.com/minelogy-dev/forge](https://github.com/minelogy-dev/forge) | | `libpcre2-dev` | PCRE2 10.46,8 位 API;构建时需要;库自身会链接 `pcre2-8` | | `pkg-config` | 推荐使用者使用;安装包自带 `libstringx.pc` | ## 从源码构建 ```sh -forge . # compile build.c into ./make (re-run whenever build.c changes) +forge . # generate ./make ./make # build -> build/output/libstringx.so ./make test # build and run every test under tests/ (ASan + UBSan + LSan) ``` -`./make` 还会把公开头文件同步到 `build/output/include`。`./make test` 把每个 -`tests/*.c` 当作独立程序运行,全程开启 AddressSanitizer、UBSan 与 -LeakSanitizer(内存检查器);可以用 `./make test -j 2` 并行执行测试。 -`build.conf` 选择编译器,也是版本号的唯一来源。 +`./make` 会把公开头文件同步到 `build/output/include`;`./make test` 把每个 +`tests/*.c` 当作独立程序在 AddressSanitizer、UBSan 与 LeakSanitizer 下运行 +(`-j 2` 并行)。`build.conf` 选择编译器,也是版本号的唯一来源。 ## 安装 @@ -56,8 +53,8 @@ install 目标会先构建,然后复制产物: cc app.c $(pkg-config --cflags --libs libstringx) -o app ``` -如果前缀不在默认搜索路径中,请让 pkg-config 找到已安装的元数据;对于非系统 -前缀,还要设置运行时库路径: +前缀不在默认搜索路径时,设置 `PKG_CONFIG_PATH` 让 pkg-config 找到元数据, +并设置运行时库路径: ```sh export PKG_CONFIG_PATH="$HOME/.local/lib/pkgconfig" @@ -71,8 +68,8 @@ LD_LIBRARY_PATH="$HOME/.local/lib" ./app cc app.c -I/include -L/lib -lstringx -o app ``` -你只需要链接 `-lstringx`:`libstringx` 自身已链接 `pcre2-8`,因此无需额外的 -库参数。但共享库在运行时需要系统中存在 `libpcre2-8`。 +只需链接 `-lstringx`:`libstringx` 已链接 `pcre2-8`,无需额外库参数,但运行时 +需要 `libpcre2-8`。 ### Debian 软件包 @@ -81,28 +78,28 @@ cc app.c -I/include -L/lib -lstringx -o app sudo apt install ./build/deb/libstringx_0.5_amd64.deb ``` -`gen_deb` 会生成 `build/deb/libstringx__.deb`;版本号来自 -`build.conf`(去掉前缀 `v`),架构名来自 `uname -m`(`x86_64` 映射为 -`amd64`,`aarch64` 映射为 `arm64`)。软件包依赖 `libc6` 与 `libpcre2-8-0`。 +`gen_deb` 生成 `build/deb/libstringx__.deb`:版本号取自 +`build.conf` 并去掉前缀 `v`,架构名取自 `uname -m`(`x86_64` → `amd64`, +`aarch64` → `arm64`);依赖 `libc6` 与 `libpcre2-8-0`。 ## Hello, String X -这是 README 中的快速上手程序。它把一个 C 字符串复制进自有缓冲区,找到第一个 -逗号,把它之前的文本复制到第二个自有缓冲区并打印出来。两个缓冲区都用 -`sx_free` 释放。 +README 中的快速上手程序:每次修改都返回同一句柄,因此整条链是一个表达式; +`sx_append` 消费临时缓冲区,结果只需一次 `sx_free`。扩容后句柄仍然有效, +且每次调用后缓冲区都以 NUL 结尾。 ```c #include #include int main(void) { - sx_t *msg = sx_new_from_cstr("hello, world"); - size_t at = sx_find_cstr(msg, ", "); - sx_t *hi = sx_substr(msg, 0, at); - fwrite(sx_buf_mut(hi), 1, (size_t)sx_len(hi), stdout); - putchar('\n'); /* hello */ - sx_free(hi); - sx_free(msg); + /* One expression: every call returns the same handle, and the temporary + buffer is consumed by sx_append, so there is nothing else to free. */ + sx_t *msg = sx_append(sx_append_cstr(sx_new(), "Hello, "), + sx_new_from_cstr("String X!")); + + printf("%s (%d bytes)\n", sx_buf_mut(msg), sx_len(msg)); + sx_free(msg); /* one buffer, one free */ return 0; } ``` @@ -115,7 +112,7 @@ cc hello.c $(pkg-config --cflags --libs libstringx) -o hello ``` ```text -hello +Hello, String X! (16 bytes) ``` 在安装之前,也可以直接使用源码树的构建输出: @@ -127,8 +124,7 @@ LD_LIBRARY_PATH=build/output ./hello ## 十分钟概览 -用户最常做的五件事,每个配一个小程序。所有示例都是完整程序,编译方式与上面的 -`hello.c` 相同。 +用户最常做的五件事,每个一个完整程序,编译方式同 `hello.c`。 ### 创建缓冲区 @@ -291,7 +287,7 @@ replaced: bob at example.com, alice at example.org | [API 参考:查找、比较与分割](api-search.md) | `sx_find*`、`sx_rfind*`、`sx_cmp*`、`sx_split` | | [正则表达式](regex.md) | `sx_reg_*` 的匹配、替换与分割家族 | | [设计与内部实现](design.md) | 数据布局、扩容策略、算法与限制 | -| [构建、测试与打包](build-and-test.md) | Forge 目标、测试框架、安装 | +| [构建、测试与打包](build-and-test.md) | 构建目标、测试框架、安装 | | [贡献指南](contributing.md) | 工作流程、代码风格、测试、许可 | | [持续集成](ci.md) | 工作流、必需检查、CodeQL | diff --git a/docs/zh_cn/guide.md b/docs/zh_cn/guide.md index 4cc306f..0248477 100644 --- a/docs/zh_cn/guide.md +++ b/docs/zh_cn/guide.md @@ -4,9 +4,8 @@ # 用户指南 -本指南面向已经能够构建并链接 String X 的 C 程序员(见[快速上手](getting-started.md)), -讲解它的心智模型并给出可直接使用的示例。函数签名与逐函数细节在 API 参考中; -本页关注各部分如何配合,以及哪些调用属于契约之外。 +面向能够构建并链接 String X 的 C 程序员(见[快速上手](getting-started.md))。 +函数签名与细节见 API 参考;本页讲心智模型、示例与契约之外的调用。 ## 心智模型 @@ -41,7 +40,7 @@ sx_view_t { ref: the same _sx, offset: 1, len: 3 } ──► "ell" ## 所有权 -同一时刻只有一个地方拥有缓冲区。下表说明每个调用返回什么、该如何释放。 +同一时刻只有一个地方拥有缓冲区;各调用的结果与释放方式如下: | 调用 | 结果 | 释放方式 | | --- | --- | --- | @@ -53,17 +52,13 @@ sx_view_t { ref: the same _sx, offset: 1, len: 3 } ──► "ell" | `sx_view`、`sx_view_*`、`sx_reg_match`、上述数组中的 token | 视图 | 无 | | `sx_reg_compile` | 已编译模式 | `sx_reg_free` | -有两条推论在实战中很重要: - -- 修改操作返回 `self`,因此可以链式书写: - `sx_append_cstr(sx_append_cstr(s, "a"), "b")` 返回的就是 `s` 本身; - `sx_free` 的调用次数等于创建的缓冲区数量,而不是修改次数。 -- 消费型调用会结束源缓冲区的生命周期。调用 `sx_append(s, part)` 之后, - 不得再使用或释放 `part`:它的内容已复制进 `s`,而且即使分配失败,源缓冲区 - 同样会被释放。 +- 修改返回 `self`,可链式书写:`sx_append_cstr(sx_append_cstr(s, "a"), "b")` + 返回 `s`;`sx_free` 次数等于创建的缓冲区数,而不是修改次数。 +- 消费型调用结束源的生命周期:`sx_append(s, part)` 之后不得再使用或释放 + `part`——内容已复制进 `s`,即使分配失败它也会被释放。 `sx_append_cstr`、`sx_append_view`、`sx_write_cstr`、`sx_write_view`、 -`sx_insert_cstr` 与 `sx_insert_view` 接收 C 字符串或视图,永远不会消费缓冲区。 +`sx_insert_cstr`、`sx_insert_view` 接收字符串或视图,永不消费缓冲区。 ## 二进制安全与 cstr 变体 @@ -75,29 +70,26 @@ sx_view_t { ref: the same _sx, offset: 1, len: 3 } ──► "ell" | `sx_view_t` 形式、`sx_new_from_view`、自有 `sx_t *` 形式 | 显式 `len` | 普通字节 | | 正则 subject(`sx_t *h`) | `h` 的字节长度 | 普通字节 | -因此 `sx_append_cstr` 会在 NUL 处停下,而 `sx_append_view`、`sx_append` 与 -`sx_new_from_view` 会复制每一个内容字节。要打印二进制缓冲区,请按长度输出: -用 `fwrite(sx_buf_mut(h), 1, (size_t)sx_len(h), stdout)` 而不是 -`printf("%s", ...)`。 +`sx_append_cstr` 遇 NUL 即停;`sx_append_view`、`sx_append`、`sx_new_from_view` +复制每个内容字节。二进制缓冲区按长度打印,不要用 `printf("%s", ...)`: +`fwrite(sx_buf_mut(h), 1, (size_t)sx_len(h), stdout)`。 -比较与查找遵循同样的区分:`_cstr` 形式使用 `strlen`,自有形式与视图形式比较 -内容字节。正则表达式按字节长度匹配 subject,但模式本身是 C 字符串,因此模式中 -不能包含字面 NUL。 +比较与查找同理:`_cstr` 形式用 `strlen`,自有与视图形式比较内容字节。正则按 +字节长度匹配 subject,模式是 C 字符串,不能包含字面 NUL。 ## 不变式与失效指针 - 每次公开调用之后都有 `ptr[len] == '\0'`、`cap >= len + 1`,且 `len` 统计 内容字节。只有会改变长度的调用才会改动这些值。 -- 任何使缓冲区变大的修改都可能 `realloc` 底层数组。此前从 `sx_buf_mut` 或 - `sx_buf_view_mut` 取得的 `char *` 全部失效;修改之后需要重新获取。 - `sx_t *` 句柄始终有效。 +- 任何增长修改都可能 `realloc` 底层数组;此前从 `sx_buf_mut` / + `sx_buf_view_mut` 取得的 `char *` 全部失效,需重新获取;`sx_t *` 句柄仍有效。 - 通过 `sx_buf_mut` 写入必须保持在 `[0, len)` 内,除非随后有配套的改长度调用; `ptr[len]` 是结尾符,不是备用字节。 -- 视图是快照。视图(或 `sx_split` / `sx_reg_*` 返回的数组)仍在使用时,不要 - 修改缓冲区;即使没有发生重新分配,长度变化之后也要重新派生视图。 +- 视图是快照:视图(或 `sx_split` / `sx_reg_*` 数组)仍在使用时不要修改缓冲区; + 任何长度变化之后都需重新派生视图。 - 访问器返回 `int`(`sx_len`、`sx_len_view`、`sx_cap`),而偏移是 `size_t`。 内容超过 `INT_MAX` 字节的缓冲区不在受测契约之内。 -- 容量只增不减:`sx_truncate`、`sx_erase` 与 `sx_clear` 都不会释放容量。 +- 容量只增:`sx_truncate`、`sx_erase`、`sx_clear` 都不释放容量。 ## 错误与哨兵值 @@ -111,29 +103,31 @@ sx_view_t { ref: the same _sx, offset: 1, len: 3 } ──► "ell" | `sx_reg_match`:无匹配 | `ref == NULL` 的视图 | | `sx_reg_match_all` / `sx_reg_split`:无匹配或分配失败 | `NULL` 数组 | | `sx_reg_replace*`:参数为 NULL 或模板被拒绝 | `NULL` 缓冲区 | +| `sx_write*`:范围末端使 `size_t` 溢出或无法预留 | `NULL`;`self` 不变(`owned` 输入被消耗) | | 分配失败 | `NULL` | `NULL` 表示"没有结果";对返回数组的调用而言,分配失败与"无匹配"无法区分。 文档化的 NULL 实参处理是有限的: - `sx_new_from_cstr(NULL)` 与 `sx_dup(NULL)` 返回 `NULL`。 -- append/write/insert 的 C 字符串实参与 owned 缓冲区实参返回 `NULL`,且 - `self` 保持不变。 +- append/write/insert 的字符串/owned 实参返回 `NULL`,`self` 不变。 +- `sx_write*` 在 `idx + len` 使 `size_t` 溢出、或末端无法预留时返回 + `NULL`;`self` 保持原内容,`owned` 实参仍被释放。 - `sx_cmp*`、`sx_starts_with*` 与 `sx_ends_with*` 返回 `0`。 - `sx_find*` / `sx_rfind*` 返回 `(size_t)-1`;`sx_find_all*` 返回 `NULL`。 -- `sx_split` 在句柄为 NULL、分隔符为 NULL 或分隔符为空时返回 `NULL`。 +- `sx_split` 在句柄/分隔符为 NULL 或分隔符为空时返回 `NULL`。 - `sx_reg_compile(NULL)` 返回 `NULL`;`sx_reg_free(NULL)` 是空操作; match、replace 与 split 家族在参数为 NULL 时返回各自的未找到值。 -其余接口都不接受 NULL 句柄。`sx_len`、`sx_cap`、`sx_buf_mut`、`sx_view`、 -`sx_free`、`sx_substr`、`sx_reserve`、`sx_erase` 以及其余函数都会解引用句柄; -传入 NULL 属于契约之外,可能直接崩溃。特别地,`sx_free(NULL)` 不是空操作, -`ref == NULL` 的视图也不能传给视图操作函数。 +其余接口都不接受 NULL 句柄:`sx_len`、`sx_cap`、`sx_buf_mut`、`sx_view`、 +`sx_free`、`sx_substr`、`sx_reserve`、`sx_erase` 等都会解引用句柄,传 NULL +属于契约之外,可能崩溃。`sx_free(NULL)` 不是空操作,`ref == NULL` 的视图 +也不能传给视图操作函数。 ## 常用示例 -每个示例都是完整的 C23 程序。构建方式与[快速上手](getting-started.md)中的 -`hello.c` 相同,或者使用: +每个示例都是完整 C23 程序,按[快速上手](getting-started.md)中 `hello.c` 的 +方式构建,或使用: ```sh cc recipe.c $(pkg-config --cflags --libs libstringx) -o recipe @@ -166,8 +160,8 @@ int main(void) { ### 查找并提取子串 -使用偏移之前先检查 `(size_t)-1` 哨兵值。`sx_substr` 会拷贝,因此结果独立于 -源缓冲区;`sx_find_view_b` 把查找限制在从某个边界开始的区域内。 +使用偏移前先检查 `(size_t)-1` 哨兵值;`sx_substr` 会拷贝(结果独立于源), +`sx_find_view_b` 只查从边界开始的区域。 ```c #include @@ -201,8 +195,8 @@ key=key value=value ### 分割并遍历 -`sx_split` 返回 malloc 分配的视图数组,末尾是以 `ref == NULL` 标记的结束 -哨兵;空字段会被保留。用 `free` 释放数组,读取 token 期间保持缓冲区存活。 +`sx_split` 返回 malloc 分配的视图数组,以 `ref == NULL` 结束哨兵收尾,空字段 +保留;用 `free` 释放数组,读取 token 期间保持缓冲区存活。 ```c #include @@ -258,7 +252,7 @@ int main(void) { [hello world] len=11 ``` -只由空白组成的视图会被裁剪成位于其槽位末尾的空视图;对于整缓冲区视图,就是 +只含空白的视图裁剪成其槽位末尾的空视图;整缓冲区视图即 `(offset = len(h), len = 0)`。 ### 原地修改 @@ -346,78 +340,74 @@ token 2: "" ## 常见陷阱 -以下是把测试有意列为契约之外的调用与习惯,以及已经写入文档、但容易忽略的边界 -情况: +测试有意列为契约之外的调用与习惯,以及容易忽略的边界情况: - 把缓冲区交给消费型调用之后继续使用:`sx_append(s, part)`、 `sx_write(s, idx, part)` 与 `sx_insert(s, idx, part)` 都会释放 `part`。 -- 通过 owned 形式把缓冲区传给它自己:`sx_append(s, s)`、`sx_write(s, idx, s)`、 - `sx_insert(s, idx, s)`。要把缓冲区原地翻倍,请用 - `sx_append_view(s, sx_view(s))` 与 `sx_write_view`,它们接受指向 `s` 的视图。 - `sx_insert_view` 也接受这种视图,前提是切片起点不晚于 `idx`(测试覆盖的 - 情形);起点晚于 `idx` 的自别名切片会被尾部右移覆盖,请先复制该切片。 +- 通过 owned 形式把缓冲区传给它自己(`sx_append(s, s)`、`sx_write(s, idx, s)`、 + `sx_insert(s, idx, s)`)属于契约之外。原地翻倍请用 + `sx_append_view(s, sx_view(s))` 或 `sx_write_view`;`sx_insert_view` 仅当 + 切片起点不晚于 `idx`(测试覆盖的情形)才可用,起点晚于 `idx` 的自别名切片 + 会被尾部右移覆盖,请先复制。 - `sx_insert*` 的 `idx > len`:尾部右移会下溢。受测契约是 `0 <= idx <= len`。 `sx_write*` 不同:它会填充并扩展。 -- 读取增长的 `sx_truncate` 之后 `[old_len, n)` 内的未指定字节,或 `sx_write` - 越界写入后 `[len, idx)` 内的字节。读取之前先把间隙写满。 +- 读取增长 `sx_truncate` 后 `[old_len, n)` 内的未指定字节,或越界 `sx_write` + 后 `[len, idx)` 内的字节;读取前先把间隙写满。 +- 在 `idx + len` 接近 `SIZE_MAX` 时调用 `sx_write*` 却假定写入已发生: + 算术溢出会被拒绝,返回 `NULL` 且 `self` 不变。请检查返回值。 - 在 `sx_split`、`sx_reg_match_all`、`sx_reg_split` 或 `sx_find_all*` 返回的 视图/数组仍在使用时修改缓冲区,或在长度变化之后继续保留视图。视图不会被调整, 扩容后可能指向已释放的内存。 - 把 `sx_find_all*` 的结果读到 `arr[0] + 1` 项之外;它的形状是 `{count, positions...}`。 -- 把 `sx_erase` 在 `idx + n > len` 时当成错误。它是有文档说明的空操作,返回 - `self`。 -- 向不检查 NULL 的函数传入 NULL 句柄(见[错误与哨兵值](#错误与哨兵值))。 - `sx_free(NULL)` 与 `sx_len(NULL)` 属于契约之外。 +- 把 `sx_erase` 在 `idx + n > len` 时当成错误:它是有文档说明的空操作。 +- 向不检查 NULL 的函数传 NULL 句柄:`sx_free(NULL)`、`sx_len(NULL)` 属于 + 契约之外(见[错误与哨兵值](#错误与哨兵值))。 - 忘记释放:缓冲区用 `sx_free`,视图数组用 `free`,已编译模式用 `sx_reg_free`。 视图不需要释放。 -- `sx_split` 的分隔符为空时返回 `NULL`;它不会按每个字节分割。 +- `sx_split` 分隔符为空时返回 `NULL`,不会每个字节都分割。 - 正则模式是 C 字符串,不能包含字面 NUL。subject 可以包含。 - `sx_new_from_cstr` 与所有 `_cstr` 实参都在第一个 NUL 处停下;二进制内容请用 视图。 - `sx_substr` 要求 `idx + n <= len(h)`;`sx_view_range` 要求 `off <= len(底层缓冲区)`(`len` 会被钳制到缓冲区末尾,`off` 不会)。两者都不会 钳制前置条件本身。 -- 在多线程间共享同一个 `sx_t` 且不加同步。库内部没有锁;唯一文档化为不可变、 - 可共享的对象是已编译的 `sx_reg_t`。 +- 多线程共享同一个 `sx_t` 且不加同步:库内部没有锁,只有已编译的 `sx_reg_t` + 文档化为不可变、可共享。 ## 性能说明 -- **已知追加量时先预留。** `sx_reserve(self, n)` 保证 `cap >= n + 1` 且不 - 缩小容量,因此缓冲区可以增长到 `n` 个内容字节而不重新分配。不预留时扩容仍是 - 摊还的:分配量翻倍;容量达到 64 KiB 后改为每次增加 `0x10000`。 -- **视图不拷贝。** `sx_view`、`sx_view_advance` 及其他视图移动函数都是 O(1), - 不分配内存。只读切片优先用它们;只有在需要独立缓冲区时才用 `sx_substr` 或 - `sx_new_from_view`。 +- **已知追加量时先预留。** `sx_reserve(self, n)` 保证 `cap >= n + 1` 且不缩小 + 容量,`n` 个内容字节无需重新分配即可容纳;否则扩容仍摊还:翻倍,达到 + 64 KiB 后改为每次增加 `0x10000`。 +- **视图不拷贝。** `sx_view`、`sx_view_advance` 等视图移动函数都是 O(1) 且不 + 分配;只在需要独立缓冲区时才用 `sx_substr` / `sx_new_from_view`。 - **查找是线性的。** 单字节 needle 使用 `memchr` / `memrchr`;更长的 needle 使用正向或反向 KMP,复杂度 O(n + m)。`sx_find_all*` 会报告重叠匹配,并按 匹配数精确分配数组。 -- **分割与正则扫描都是两遍。** 先统计 token 或匹配数量,再一次性精确分配数组; - 代价是对 subject 扫描两遍。 -- **正则只编译一次。** `sx_reg_compile` 是开销最大的调用;match、replace 与 - split 复用已编译模式,每次只分配自己的匹配数据。`sx_reg_is_match` 是最便宜的 - 存在性检查。 +- **分割与正则扫描都是两遍。** 先统计 token/匹配数,再一次性精确分配; + 对 subject 扫描两遍。 +- **正则只编译一次。** `sx_reg_compile` 是开销最大的调用;match、replace、split + 复用已编译模式,每次只分配自己的匹配数据;`sx_reg_is_match` 最便宜。 - **容量不会归还。** `sx_truncate`、`sx_erase` 与 `sx_clear` 都保留分配, 这使清空后的缓冲区可以复用,但也意味着峰值分配会一直保留到 `sx_free`。 ## 常见问题 -**使用缓冲区需要 PCRE2 吗?** 构建库时需要:源码树会链接 `pcre2-8`, -`./make` 需要 `libpcre2-dev`。使用已安装的 `libstringx` 时只需链接 -`-lstringx`;共享库自身带有 PCRE2 依赖。 +**使用缓冲区需要 PCRE2 吗?** 构建时需要:源码树链接 `pcre2-8`,`./make` 需要 +`libpcre2-dev`;已安装的 `libstringx` 只需 `-lstringx`,共享库自带 PCRE2 依赖。 **所有函数都支持 NULL 吗?** 不。只有[错误与哨兵值](#错误与哨兵值)中列出的 情况有定义;其他情况下 NULL 句柄都属于契约之外。 -**String X 感知 UTF-8 吗?** 不。它是字节库:长度、比较与查找都按字节精确 -处理,正则层运行在 PCRE2 的 8 位非 UTF 模式,因此 `\d`、`\w`、`\s` 与 `\b` -只匹配 ASCII。 +**String X 感知 UTF-8 吗?** 不:它是字节库,长度、比较与查找都按字节精确处理。 +正则运行于 PCRE2 8 位非 UTF 模式,`\d`、`\w`、`\s`、`\b` 仅匹配 ASCII。 -**如何复制一个视图?** `sx_new_from_view(v)` 返回自有缓冲区,其中是视图 -`len` 个字节的精确副本。 +**如何复制一个视图?** `sx_new_from_view(v)` 返回自有缓冲区,含视图 `len` 字节的 +精确副本。 -**如何取得子串?** `sx_view_range` 与 `sx_view_advance` 给出零拷贝视图; -`sx_substr(h, idx, n)` 给出自有副本。 +**如何取得子串?** `sx_view_range`/`sx_view_advance` 给零拷贝视图; +`sx_substr(h, idx, n)` 给自有副本。 **为什么 `sx_len` 返回 `int`?** 这是库的实际大小上限:内容超过 `INT_MAX` 字节不在受测契约之内。偏移是 `size_t`,因此查找与视图位置仍是全宽度。 @@ -426,8 +416,7 @@ token 2: "" 调用使用各自的匹配数据。在线程间共享 `sx_t` 缓冲区则不受支持。 **零长匹配是什么样子?** `sx_reg_match` 返回 `ref != NULL`、`len == 0` 的 -视图;`sx_reg_match_all` 与 `sx_reg_split` 会报告它,并把扫描继续推进一个 -字节。 +视图;`sx_reg_match_all` 与 `sx_reg_split` 照常报告,并把扫描推进一个字节。 --- diff --git a/docs/zh_cn/regex.md b/docs/zh_cn/regex.md index 8dc7b4c..3962f3e 100644 --- a/docs/zh_cn/regex.md +++ b/docs/zh_cn/regex.md @@ -6,25 +6,25 @@ ## 概述 -`` 在核心缓冲区 API 之上加入了一个高级层:对 **PCRE2 8 位库** -(`pcre2-8`,版本 10.46)的一层薄封装,配置固定。它提供编译/释放这一对 -函数,以及匹配、替换、分割三个家族,并且有意不自带任何策略:本页没有 -说明的行为,一律是 PCRE2 的默认行为。 +`` 在核心缓冲区 API 之上增加了一个高级层:对 **PCRE2 8 位库** +(`pcre2-8`,版本 10.46)的薄封装,配置固定。它提供编译/释放函数,以及 +匹配、替换、分割三个家族,不自带策略:本页未说明的行为一律是 PCRE2 默认 +行为。 -这一层的使用方式围绕一个生命周期: +生命周期: 1. 把一个模式编译成不透明的 `sx_reg_t *` 句柄; 2. 对任意多个 `sx_t` 主体(subject)执行任意多次调用; 3. 最后用 `sx_reg_free` 释放该句柄一次。 -已编译的句柄不可变,可以跨线程共享;每次调用使用自己的匹配数据。主体按 +已编译句柄不可变,可跨线程共享;每次调用使用自己的匹配数据。主体按 **字节长度**匹配,因此内嵌 NUL 是普通数据(二进制安全);模式和替换模板 都是 C 字符串,不能包含字面 NUL。 -该层属于 `libstringx`,由库自身链接 `pcre2-8`:使用者只需链接 -`-lstringx`,无需额外的 PCRE2 链接参数。PCRE2 采用 BSD-3-Clause 许可, -归属声明见 [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md)。 -`$n` 替换规则见[替换模板](#替换模板);按任务组织的用法示例见 +该层属于 `libstringx`,库自身链接 `pcre2-8`:使用者只需链接 `-lstringx`, +无需额外 PCRE2 参数。PCRE2 采用 BSD-3-Clause 许可,归属见 +[THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md)。`$n` 替换规则见 +[替换模板](#替换模板);按任务的用法示例见 [用户指南](guide.md)。 各家族一览: @@ -38,8 +38,8 @@ ## 生命周期 -在使用它的循环之前把模式编译一次,并保留句柄。模式字符串本身不会被保留, -因此编译后可以立即释放。句柄不再需要时,用 `sx_reg_free` 释放。 +在循环之前把模式编译一次。模式字符串不会被保留,编译后可立即释放;句柄 +不再需要时用 `sx_reg_free` 释放。 ```c #include @@ -90,12 +90,12 @@ int main(void) { } ``` -让这套 API 可以安全地用于长期运行代码的,是下面三点: +三点特性让这套 API 可安全用于长期代码: -- 句柄独立于主体:一个已编译模式可以服务任意多个缓冲区; -- 别名到主体的结果是视图,因此只在该主体存活且长度不变期间有效; -- `sx_reg_match_all` 和 `sx_reg_split` 返回的数组归调用方所有:用 - `free()` 释放,而不是 `sx_free`。 +- 句柄独立于主体:一个已编译模式可服务任意多个缓冲区。 +- 别名到主体的结果是视图,仅在该主体存活且长度不变时有效。 +- `sx_reg_match_all` 和 `sx_reg_split` 返回的数组归调用方所有:用 `free()` + 释放,而不是 `sx_free`。 ### sx_reg_compile @@ -109,17 +109,14 @@ sx_reg_t *sx_reg_compile(const char *pattern); | --- | --- | | `pattern` | 以 NUL 结尾的 PCRE2 模式;句柄不会保留该字符串 | -返回新句柄;当 `pattern` 为 `NULL`、模式语法无效或分配失败时返回 -`NULL`。封装层不暴露 PCRE2 的错误码和错误位置,因此这几种情况无法区分: -开发阶段请先校验模式,并把 `NULL` 一律当作"不要使用这个句柄"。 +返回新句柄;`pattern` 为 `NULL`、语法无效或分配失败时返回 `NULL`。封装层 +不暴露 PCRE2 错误码和位置,这几种情况无法区分:开发时先校验模式,把 +`NULL` 一律视为不可用。 -说明: - -- 模式字符串可以在调用后立即释放或修改。 -- 不会向 PCRE2 传递任何编译选项。模式内部选用的 PCRE2 特性(例如内联 - 选项 `(?i)`)仍然生效。 -- 相对于单次匹配调用,编译才是这一层里昂贵的一步,所以应当编译一次并 - 复用句柄([性能](#性能))。 +- 模式字符串可在调用后立即释放或修改。 +- 不向 PCRE2 传递编译选项;模式内部选用的特性(如内联选项 `(?i)`)仍 + 生效。 +- 编译是这一层昂贵的一步,应编译一次并复用句柄([性能](#性能))。 ```c sx_reg_t *re = sx_reg_compile("(\\w+)@(\\w+)"); /* 输入非法时为 NULL */ @@ -134,13 +131,11 @@ sx_reg_free(re); /* 最后一次使用后释放句柄 */ void sx_reg_free(sx_reg_t *r); ``` -释放已编译句柄。允许传入 `NULL`,此时为空操作。 - -说明: +释放已编译句柄;`NULL` 为空操作。 -- 只释放一次,且要在最后一次使用它的调用之后。 -- 之前调用返回的数据不依赖该句柄:匹配视图别名到主体,数组归调用方所有。 -- 再次使用已释放的句柄属于契约之外。 +- 只释放一次,且在最后一次使用之后。 +- 先前结果不依赖该句柄:匹配视图别名到主体,数组归调用方所有。 +- 再次使用已释放句柄属于契约之外。 ```c sx_reg_free(re); /* 最后一次使用后释放句柄 */ @@ -148,10 +143,9 @@ sx_reg_free(re); /* 最后一次使用后释放句柄 */ ## 匹配家族 -三个调用都从左侧开始扫描主体的内容字节,遵循 PCRE2 的**最左优先** -(leftmost-first)语义:起始位置最早的匹配获胜;在同一字节起始的多个 -候选中,由 PCRE2 的偏好顺序决定。零长匹配也是真正的匹配。视图别名到 -主体:不拷贝任何字节,也从不修改 `h`。 +三个调用都从左侧扫描内容字节,遵循 PCRE2 的**最左优先** +(leftmost-first)语义:起点最早者获胜;同一起点的候选按 PCRE2 的偏好顺序 +决定。零长匹配也是真正的匹配。视图别名到主体,`h` 从不被修改。 ### sx_reg_is_match @@ -159,20 +153,18 @@ sx_reg_free(re); /* 最后一次使用后释放句柄 */ int sx_reg_is_match(const sx_reg_t *r, const sx_t *h); ``` -回答"模式是否在 `h` 中任意位置匹配?"。 +回答"模式是否匹配 `h` 的任意位置?"。 | 参数 | 含义 | | --- | --- | | `r` | 已编译模式 | | `h` | 主体缓冲区 | -若 `h` 中存在匹配返回 `1`,否则返回 `0`——包括 `r` 或 `h` 为 `NULL`、 -或内部分配失败的情况。零长匹配也算匹配,因此 `a*` 能匹配空主体。 +若 `h` 中任意位置存在匹配返回 `1`,否则返回 `0`——包括 `r`/`h` 为 `NULL` +或内部分配失败。零长匹配也算匹配,因此 `a*` 能匹配空主体。 -说明: - -- 最便宜的存在性检查:一次 PCRE2 匹配调用,不分配结果。每次调用仍会创建 - 并释放自己的小型 PCRE2 匹配数据块。 +- 最便宜的存在性检查:一次 PCRE2 匹配调用、不分配结果;每次调用仍会创建 + 并释放小型 PCRE2 匹配数据块。 - 主体按字节长度搜索;锚点指向字节偏移。 ```c @@ -189,26 +181,24 @@ sx_reg_free(re); sx_view_t sx_reg_match(const sx_reg_t *r, const sx_t *h); ``` -把最左匹配作为视图返回,指向 `h` 内部。 +把最左匹配作为指向 `h` 内部的视图返回。 | 参数 | 含义 | | --- | --- | | `r` | 已编译模式 | | `h` | 主体缓冲区 | -成功时结果是 `h` 缓冲区上的视图:`.ref` 指向主体,`.offset` / `.len` -选出匹配到的字节。无匹配、参数为 `NULL` 或分配失败时返回空视图 -`{ref = NULL, offset = 0, len = 0}`。零长匹配仍是匹配: -`.ref != NULL` 且 `.len == 0`。 - -说明: +成功时结果是 `h` 上的视图:`.ref`、`.offset`、`.len` 选出匹配到的字节。 +无匹配、参数为 `NULL` 或分配失败时返回空视图 +`{ref = NULL, offset = 0, len = 0}`;零长匹配仍有 `.ref != NULL` 且 +`.len == 0`。 -- 最左匹配,而不是"最长匹配":候选之间的先后由 PCRE2 决定,例如 - `b|bc` 对 `abc` 会匹配偏移 1 处的 `b`。 +- 最左而非最长:候选先后由 PCRE2 决定,例如 `b|bc` 对 `abc` 匹配偏移 1 + 处的 `b`。 - 只做一次 PCRE2 匹配调用;返回的视图不是拷贝。 - 锚点遵循 PCRE2 默认规则:`^` 匹配主体起点(偏移 0),`$` 匹配主体 结尾;默认情况下 `$` 也能匹配最后一个换行符之前的位置。 -- 在 `h` 被释放后,或在修改 `h` 长度之后使用该视图,属于契约之外。 +- 在 `h` 被释放或长度改变后使用该视图属于契约之外。 ```c sx_reg_t *re = sx_reg_compile("bc"); @@ -231,18 +221,12 @@ sx_view_t *sx_reg_match_all(const sx_reg_t *r, const sx_t *h); | `r` | 已编译模式 | | `h` | 主体缓冲区 | -返回 `malloc` 分配的视图数组,形态与 `sx_split` 一致: -`arr[0 .. count-1]` 是各次匹配,`arr[count].ref == NULL` 是结束哨兵。 -调用方用 `free()` 释放数组;视图别名到 `h`,在 `h` 存活且长度不变期间 -有效。 +返回 `malloc` 分配的数组,形态与 `sx_split` 一致:`arr[0 .. count-1]` 是 +各次匹配,`arr[count].ref == NULL` 是结束哨兵。用 `free()` 释放;视图在 +`h` 存活且长度不变期间别名到 `h`。无匹配、参数为 `NULL` 或分配失败时返回 +`NULL`——该 API 无法区分。 -完全没有匹配、`r` 或 `h` 为 `NULL`、或分配失败时返回 `NULL`。该 API -无法区分这三种情况。 - -说明: - -- 匹配之间不重叠:每次匹配后从匹配结尾继续扫描;零长匹配则再向右移动 - 一个字节([扫描规则](#扫描规则))。 +- 匹配不重叠:每次匹配后从结尾继续扫描;零长匹配则右移一个字节([扫描规则](#扫描规则))。 - 计数和填充是同一确定性扫描的两遍,因此数组只按最终大小分配一次。 - `sx_find_all*` 报告的是可能重叠的位置;`sx_reg_match_all` 报告的是 正则匹配,它们不可能重叠。 @@ -263,12 +247,12 @@ sx_reg_free(re); `sx_reg_match_all` 和 `sx_reg_split` 共用同一套扫描规则: -- 匹配按从左到右的顺序取,且互不重叠; -- 一次匹配之后,下一次搜索从该匹配的结尾开始; -- 零长匹配之后,下一次搜索从匹配起点**向右一个字节**开始,因此能匹配 - 空串的模式不会让扫描停滞; -- 匹配可以正好结束于 `len(h)`(例如 `$`);随后扫描停止,因为 PCRE2 - 拒绝超出主体的起始偏移。 +- 匹配从左到右取,互不重叠; +- 一次匹配后,下一次搜索从匹配结尾开始; +- 零长匹配后,下一次搜索从匹配起点**向右一个字节**开始,能匹配空串的模式 + 不会让扫描停滞; +- 匹配可正好结束于 `len(h)`(例如 `$`),随后扫描停止,因为 PCRE2 拒绝 + 超出主体的起始偏移。 | 模式 | 主体 | 报告的匹配(偏移, 长度) | | --- | --- | --- | @@ -277,13 +261,12 @@ sx_reg_free(re); | `$` | `abc` | (3,0) | | `bc` | `abcb` | (1,2) | -同一条规则决定了 `sx_reg_split` 的 token 数量:始终等于 -`匹配数 + 1`。 +同一条规则决定 `sx_reg_split` 的 token 数:始终为 `匹配数 + 1`。 ## 替换家族 -两个替换调用都把 C 字符串模板代入匹配处,并返回**新的**、归调用方所有的 -`sx_t`;`h` 永远不会被修改。结果与其他缓冲区一样用 `sx_free` 释放。 +两个替换调用把 C 字符串模板代入匹配处,返回**新的**、归调用方所有的 +`sx_t`;`h` 永不修改。结果用 `sx_free` 释放。 ### sx_reg_replace @@ -299,15 +282,12 @@ sx_t *sx_reg_replace(const sx_reg_t *r, const sx_t *h, const char *repl); | `h` | 主体缓冲区;不会被修改 | | `repl` | 以 NUL 结尾的替换模板;不会被保留 | -返回新缓冲区;当 `r`、`h` 或 `repl` 为 `NULL`、PCRE2 拒绝该模板、或 -分配失败时返回 `NULL`。参数合法但没有匹配时,结果是 `h` 的**原样拷贝**, -绝不会是 `NULL`。 - -说明: +返回新缓冲区;参数为 `NULL`、PCRE2 拒绝模板或分配失败时返回 `NULL`。 +参数合法但无匹配时,结果是 `h` 的**原样拷贝**,绝不是 `NULL`。 - 模板会展开 `$0` / `$n`;见[替换模板](#替换模板)。 - 零长匹配也会被替换:`a*` 对 `bbb`、模板为 `-` 时得到 `-b-b-b-`。 -- 空模板会删除每一处匹配,因此模式匹配整个主体时结果为空缓冲区。 +- 空模板删除每一处匹配;因此模式匹配整个主体时结果为空缓冲区。 - 字节精确:`h` 中的内嵌 NUL 是普通匹配数据,并会原样复制进结果。 ```c @@ -326,7 +306,7 @@ sx_t *sx_reg_replace_first(const sx_reg_t *r, const sx_t *h, const char *repl); ``` -契约与 `sx_reg_replace` 相同,但只替换**最左**的一处匹配;其余字节原样 +契约与 `sx_reg_replace` 相同,但只替换**最左**一处匹配,其余字节原样 拷贝。 ```c @@ -340,8 +320,8 @@ sx_reg_free(re); ## 替换模板 -两个替换调用都按 PCRE2 的替换语法解释 `repl`,并固定设置两个选项,使缺失 -的捕获组不会造成问题。 +两个替换调用都按 PCRE2 的替换语法解释 `repl`,并固定设置两个使缺失捕获组 +无害的选项。 | 模板元素 | 展开为 | | --- | --- | @@ -356,16 +336,13 @@ sx_reg_free(re); | `a(b)?` | `a` | `[$1]` | `[]` | | `abc` | `abc` | (空模板) | (空缓冲区) | -说明: - -- 封装层传入 PCRE2 的 `PCRE2_SUBSTITUTE_UNSET_EMPTY` 和 - `PCRE2_SUBSTITUTE_UNKNOWN_UNSET`:未参与匹配的组和根本不存在的组都 - 展开为空串。因此模板不会仅仅因为缺少某个捕获组而被拒绝。 +- 封装层设置 `PCRE2_SUBSTITUTE_UNSET_EMPTY` 和 + `PCRE2_SUBSTITUTE_UNKNOWN_UNSET`:未参与匹配的组和不存在的组号都展开为 + 空,因此模板不会仅因缺少捕获组而被拒绝。 - `$n` 指向每一次被替换的匹配自己的捕获组;第 0 组是整个匹配。 -- `repl` 是 C 字符串,因此其中不能出现字面 NUL。匹配到的 NUL 字节仍会 - 通过 `$0` / `$n` 进入结果。 -- 完整的替换语法属于 PCRE2;见 - [PCRE2 文档](https://www.pcre.org/)。 +- `repl` 是 C 字符串,不能含字面 NUL;匹配到的 NUL 字节仍通过 `$0`/`$n` + 进入结果。 +- 完整语法属于 PCRE2;见 [PCRE2 文档](https://www.pcre.org/)。 ## 分割家族 @@ -382,20 +359,16 @@ sx_view_t *sx_reg_split(const sx_reg_t *r, const sx_t *h); | `r` | 已编译模式 | | `h` | 主体缓冲区 | -返回 `malloc` 分配的数组,形态与 `sx_split` 完全一致: -`arr[0 .. count-1]` 是按顺序排列的 token,`arr[count].ref == NULL` 是 -结束哨兵,且 `count == 匹配数 + 1`。各边界处以及内部产生的空 token 都会 -保留。调用方用 `free()` 释放数组;token 是 `h` 上的视图。 - -参数为 `NULL` 或分配失败时返回 `NULL`。没有匹配不是错误:此时数组中只有 -整个主体这一个 token。 +返回 `malloc` 分配的数组,形态与 `sx_split` 完全一致:token 按顺序位于 +`arr[0 .. count-1]`,`arr[count].ref == NULL` 是结束哨兵,且 +`count == 匹配数 + 1`。各边界和内部空 token 都保留;用 `free()` 释放数组; +token 是 `h` 上的视图。参数为 `NULL` 或分配失败时返回 `NULL`;没有匹配不是 +错误:整个主体就是单个 token。 -说明: - -- 零长匹配会在每个位置分割:`a*` 对 `bbb` 得到 `""`、`"b"`、`"b"`、 - `"b"`、`""`,共五个 token。 -- 匹配覆盖整个主体时,产生两个空 token。 -- 开头和结尾的匹配会产生空的首尾 token;相邻匹配之间产生内部空 token。 +- 零长匹配在每个位置分割:`a*` 对 `bbb` 得到 `""`、`"b"`、`"b"`、`"b"`、 + `""`,共五个 token。 +- 匹配覆盖整个主体时产生两个空 token。 +- 首尾匹配产生空的首尾 token;相邻匹配之间产生内部空 token。 - token 使用期间不要修改 `h`(视图是快照;见[用户指南](guide.md))。 ```c @@ -417,8 +390,7 @@ sx_reg_free(re); | 模板 `repl` | 是 C 字符串:不能有字面 NUL;捕获组可以把 NUL 字节带入结果 | - PCRE2 运行在 **8 位非 UTF 模式**:`\d`、`\w`、`\s`、`\b` 等只匹配 - ASCII。组成非 ASCII 字符的字节(例如 UTF-8 字节 `C2 A5`)永远不会匹配 - `\d`。 + ASCII;组成非 ASCII 字符的字节(例如 UTF-8 `C2 A5`)永远不匹配 `\d`。 - 在 8 位非 UTF 模式下,`.` 匹配除换行以外的任意字节,包括内嵌 NUL: 模式 `A.B` 能匹配三个字节 `A\0B`。 - 替换在两个方向上都是二进制安全的:主体 `a\0b`、模式 `b`、模板 `B` @@ -428,8 +400,8 @@ sx_reg_free(re); ## 错误哨兵 -任何有文档的调用都不会因为非法输入、无匹配或分配失败而崩溃;每个家族用 -固定的哨兵值报告这些情况。 +有文档的调用不会因非法输入、无匹配或分配失败而崩溃;每个家族用固定哨兵 +报告。 | 调用 | 无匹配 | `NULL` 参数 / 非法输入 | 分配失败 | | --- | --- | --- | --- | @@ -442,26 +414,21 @@ sx_reg_free(re); | `sx_reg_replace_first` | 原样拷贝 | `NULL` | `NULL` | | `sx_reg_split` | 单 token 数组(整个主体) | `NULL` | `NULL` | -说明: - -- 对 `sx_reg_match_all` 和 `sx_reg_split`,"无匹配"和分配失败都返回 - `NULL`;数组家族无法区分二者。 -- 对替换家族,"无匹配"是正常成功:得到 `h` 的原样拷贝。 -- 数组由 `malloc` 分配,用 `free()` 释放;替换家族返回的缓冲区是 - `sx_t *`,用 `sx_free()` 释放。 +- 对 `sx_reg_match_all` 和 `sx_reg_split`,无匹配和分配失败都返回 `NULL`; + 数组家族无法区分。 +- 对替换家族,无匹配是正常成功:`h` 的原样拷贝。 +- 数组由 `malloc` 分配并用 `free()` 释放;替换结果是 `sx_t *`,用 + `sx_free()` 释放。 ## 线程安全 -- 已编译的 `sx_reg_t` 在 `sx_reg_compile` 之后不可变。它没有可变状态, - 封装层也不保存全局状态,因此同一个句柄可以被多个线程同时使用。 -- 每个匹配/分割调用都会创建自己的 PCRE2 匹配数据块 - (`pcre2_match_data_create_from_pattern`)并在返回前释放;替换调用委托 - 给 `pcre2_substitute`,同样使用每次调用自己的匹配数据。两个线程不会 - 共享匹配状态。 -- 主体缓冲区是普通内存,没有加锁:并发只读没有问题,任何修改都需要外部 - 同步。 -- 视图和数组是主体的快照。某个线程仍在读取视图时不要修改主体;其他线程 - 仍在使用句柄时不要释放它。 +- 已编译的 `sx_reg_t` 在 `sx_reg_compile` 后不可变,没有可变状态,封装层也 + 不保存全局状态,因此同一句柄可被多个线程同时使用。 +- 每个匹配/分割调用创建并释放自己的 PCRE2 匹配数据块;替换委托给 + `pcre2_substitute`,同样使用每次调用自己的匹配数据。线程之间不共享匹配状态。 +- 主体缓冲区是普通内存、无加锁:并发只读安全,任何修改需要外部同步。 +- 视图和数组是快照:某线程仍在读取视图时不要修改主体;其他线程仍在使用 + 句柄时不要释放它。 ## 性能 @@ -474,19 +441,17 @@ sx_reg_free(re); | `sx_reg_split` | 扫描两遍 | 匹配数据加一个精确大小的数组 | 数组 | | `sx_reg_replace*` | 两次替换调用 | PCRE2 内部匹配数据、一个临时缓冲区、一个 `sx_t` | 新缓冲区 | -说明: - -- 编译一次:模式编译的成本远高于单次匹配,在循环里反复编译是唯一本可 - 避免的性能错误。 +- 编译一次:编译成本远高于单次匹配,在循环里反复编译是唯一可避免的性能 + 错误。 - `sx_reg_is_match` 是最便宜的存在性检查;`sx_reg_match` 只多出一个返回 视图。 -- `sx_reg_match_all` 和 `sx_reg_split` 扫描两遍(先计数、再填充),因此 - 结果数组只分配一次,绝不通过 `realloc` 增长。 -- 替换家族先用第一次 `pcre2_substitute` 调用探测精确输出长度,再用第二次 - 调用填充合适大小的缓冲区;缓冲区随后一次性拷贝进返回的 `sx_t`。 -- 每次调用都会分配并释放匹配数据;调用之间不缓存匹配数据,封装层也不启用 - PCRE2 JIT 或任何编译选项。 -- 主体永远不会被拷贝;只有替换家族会分配结果缓冲区。 +- `sx_reg_match_all` 和 `sx_reg_split` 扫描两遍(先计数、再填充),结果数 + 组只按最终大小分配一次,不靠 `realloc` 增长。 +- 替换先用第一次 `pcre2_substitute` 探测精确输出长度,再用第二次填充合适 + 缓冲区;随后一次性拷贝进返回的 `sx_t`。 +- 每次调用都分配并释放匹配数据;调用之间不缓存,封装层不启用 PCRE2 JIT 或 + 编译选项。 +- 主体从不拷贝;只有替换家族分配结果缓冲区。 ## 选择合适的调用 @@ -504,17 +469,15 @@ sx_reg_free(re); 封装层固定了一组简单、刻意的配置: - **8 位、非 UTF**:模式和主体都是字节,字符类是 ASCII,不做 UTF 校验。 - 在默认(未开启 `DOTALL`)模式下,`.` 不匹配换行。 -- **不暴露选项标志**:封装层不传编译选项、不传匹配选项,也不传匹配上下文。 - 写在模式内部的 PCRE2 特性(例如内联选项)仍然生效;大小写不敏感、多行 - 匹配等行为用 PCRE2 的模式内语法请求。 -- **以 PCRE2 默认行为为准**:最左优先的选择、贪婪/懒惰量词、锚点、反向 - 引用以及其他所有模式语义都属于 PCRE2,而不是封装层。 + 默认(未开启 `DOTALL`)下 `.` 不匹配换行。 +- **不暴露选项标志**:不传编译选项、匹配选项或匹配上下文。模式内部的内联 + 选项等特性仍然生效,因此大小写不敏感、多行匹配等使用 PCRE2 自己的语法。 +- **以 PCRE2 默认行为为准**:候选顺序、贪婪/懒惰量词、锚点、反向引用及其 + 他模式语义都属于 PCRE2,而非封装层。 - 封装层不暴露 PCRE2 错误码或编译错误位置。 -模式语法与语义由 PCRE2 项目在 [pcre.org](https://www.pcre.org/) 记录; -本库不会重复记录它们。随附的 PCRE2 版本为 10.46;该依赖采用 -BSD-3-Clause 许可,归属声明见 +模式语法与语义由 PCRE2 项目在 [pcre.org](https://www.pcre.org/) 记录,本库 +不重复记录。随附的 PCRE2 版本为 10.46;依赖采用 BSD-3-Clause 许可,归属见 [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md)。 ---