diff --git a/README.md b/README.md index ad5567e..68d6cf2 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,18 +29,18 @@ 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 - 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 @@ -43,29 +49,38 @@ and link `-lstringx` — one header, one library. ## 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) ``` +See [Build, test & package](docs/en_us/build-and-test.md) for installation, +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 @@ -116,10 +131,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..096f986 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,17 +26,16 @@ 内嵌 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` 里写明精确的行为边界:文档化的 + "未找到/出错"情形返回哨兵值,超出文档边界的输入属于契约之外。 ## 依赖 - 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` @@ -38,29 +43,36 @@ ## 构建 ```sh -forge . # 把 build.c 编译成 ./make(改动 build.c 后需重跑) +forge . # 生成 ./make ./make # 构建 -> build/output/libstringx.so(头文件随附于 build/output/include) ./make test # 编译并运行 tests/ 下每个测试(ASan + UBSan) ``` +安装、打包与测试框架的完整说明见[构建、测试与打包](docs/zh_cn/build-and-test.md)。 + ## 快速上手 +每次修改都返回传入的句柄,因此整条链是一个表达式:`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 @@ -110,10 +122,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/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 new file mode 100644 index 0000000..9591d7b --- /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) — `./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..9a636a7 --- /dev/null +++ b/docs/en_us/api-buffer.md @@ -0,0 +1,760 @@ +English · [中文](../zh_cn/api-buffer.md) + +[Docs home](README.md) › API reference: buffers & views + +# Buffers and views + +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 + +**Headers and layers.** Include the one public header: + +```c +#include +``` + +`sx.h` includes `sx_core.h` (buffers, views, search, comparison) and +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.** + +| 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 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.** + +| 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`; +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}` 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 + +### sx_new + +```c +sx_t *sx_new(void); +``` + +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. +- **Ownership:** caller-owned; release with `sx_free`. +- **Edge cases:** only `cap >= 1` is guaranteed; the exact 32-byte start is + an implementation detail. + +### 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 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 a view's bytes into a new, independent buffer. + +- **Parameters:** `v` — source window; `v.len` bytes at + `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); 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 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 */ +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; 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"); +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: the content array and the handle. + +- **Parameters:** `h` — a live handle owned by the caller. +- **Returns:** nothing. +- **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 + +### 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; 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 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 + +```c +int sx_cap(sx_t *h); +``` + +Returns the total bytes allocated for the content array. + +- **Parameters:** `h` — buffer. +- **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 + +```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; 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); +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 — 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); +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)}`; 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` — 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 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 */ +``` + +## Appending + +### sx_append + +```c +sx_t *sx_append(sx_t *self, sx_t *owned); +``` + +Appends another buffer's content, consuming that buffer. + +- **Parameters:** `self` — destination; `owned` — source buffer. +- **Returns:** `self`, or `NULL` when `owned == NULL` or on allocation + failure. +- **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 + +```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 returning `self`. + +### sx_append_view + +```c +sx_t *sx_append_view(sx_t *self, sx_view_t v); +``` + +Appends a view's bytes. + +- **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 — 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 */ +``` + +## Writing + +### sx_write + +```c +sx_t *sx_write(sx_t *self, size_t idx, sx_t *owned); +``` + +Overwrites bytes at `idx`, growing the length if needed, and consumes the +source buffer. + +- **Parameters:** `self` — destination; `idx` — first byte to overwrite; + `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"); +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`; `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 untouched. The same range + validation, padding and `idx` rules as `sx_write` apply. + +### sx_write_view + +```c +sx_t *sx_write_view(sx_t *self, size_t idx, sx_view_t v); +``` + +Writes a view's bytes at `idx`. + +- **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 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 + +### sx_insert + +```c +sx_t *sx_insert(sx_t *self, size_t idx, sx_t *owned); +``` + +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 buffer. +- **Returns:** `self`, or `NULL` when `owned == NULL` or on allocation + failure. +- **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), and 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 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 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`, + 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 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. + +## 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; `NULL` on allocation failure while + growing. +- **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 + +```c +sx_t *sx_erase(sx_t *self, size_t idx, size_t n); +``` + +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`; `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 */ +``` + +### sx_clear + +```c +sx_t *sx_clear(sx_t *self); +``` + +Empties the buffer, keeping its capacity. + +- **Parameters:** `self` — buffer. +- **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. + +```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 `[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 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 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 + +```c +sx_view_t sx_view_advance(sx_view_t v, size_t n); +``` + +Moves the window start right by `n`. + +- **Parameters:** `v` — input view; `n` — bytes to advance. +- **Returns:** the adjusted view over the same buffer. +- **Edge cases:** with `H = len(ref)`: + - 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)`. + 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 */ +``` + +### sx_view_retreat + +```c +sx_view_t sx_view_retreat(sx_view_t v, size_t n); +``` + +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. +- **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 + +```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. +- **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 + +```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))`. +- **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) */ +``` + +## Trimming views + +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 + +```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. +- **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 */ +``` + +### 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. +- **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. +- **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: + +```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..305553f --- /dev/null +++ b/docs/en_us/api-search.md @@ -0,0 +1,584 @@ +English · [中文](../zh_cn/api-search.md) + +[Docs home](README.md) › API reference: search, compare & split + +# Search, compare and split + +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 + +**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 | + +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: + +| 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 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.** + +| 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 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), 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 + +| 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 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. + 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 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 + +```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 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"); +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 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. + +### 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 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*` + +### 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 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. + +### 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 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 + +```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 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"); +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 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. + +### 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 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*` + +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; 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. + +```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). +- **Edge cases:** binary-safe; offsets ascend and include overlaps. + +### 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). +- **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). +- **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). +- **Edge cases:** only content is searched, 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 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 + +```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`. +- **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`. +- **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. +- **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. +- **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. +- **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. +- **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. +- **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. +- **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`): + 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). + +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..bea88f0 --- /dev/null +++ b/docs/en_us/build-and-test.md @@ -0,0 +1,326 @@ +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). 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 + +| 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 | [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 commands from the repository root; `build.c` and `build.conf` are read +relative to it. + +## Build tool + +Install [Forge](https://github.com/minelogy-dev/forge) from its repository. Once +`forge .` has generated `./make`, the everyday commands are: + +```sh +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 .` | 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. | +| `./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` 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. + +Artifacts: + +| 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` needs no prior `./make`: every test compiles the library sources +directly. + +## build.conf + +`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` | 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. Success prints `PASSED: `; the first failed +assertion prints `FAILED: :: `. The summary looks +like: + +```text +forge: 24 tests, 24 passed, 0 failed +``` + +The task exits non-zero if a test fails to compile or run. + +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 CI's sanitizer options: + +```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 +``` + +Rerun one built test directly: + +```sh +./test/reserve_stress +``` + +### Exact-reserve stress test + +`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 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`; 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 (initially `Source`); the +tests spell out every keyword. + +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 includes the header under test (`"sx.h"`, or `"sx_core.h"` for +core-only tests) and `` for two 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 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. + +```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 (with 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 writable prefix, for example: + +```sh +./make install "$HOME/.local" +``` + +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 + +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`, so consumers need no `-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 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 | + +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: + +```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`; 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 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 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 — build +matrix, analyzer, quality checks, CodeQL and merge protection — are 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..e5e7128 --- /dev/null +++ b/docs/en_us/ci.md @@ -0,0 +1,135 @@ +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 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 + +| 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` | +| `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) | + +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 + +| 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 | +| 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 here. No categories +are suppressed; investigate analyzer failures instead of using +`continue-on-error`. + +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 together when upgrading. + +## CodeQL + +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). 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 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 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 `configure.sh`: it updates the compiler +selection and appends `sanitize=1`. + +```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 +``` + +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 +forge . +./make +./make test -j 2 +``` + +The focused audit scripts live in `.github/scripts/` (`check-write-safety.py`, +`compare-search.py`); `benchmarks/` documents its own harness and rerun steps. + +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 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 memory-safety bugs; human +review should focus on requirements, API contracts, ownership, architecture and +tool findings. + +--- + +[← 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..4570d8f --- /dev/null +++ b/docs/en_us/contributing.md @@ -0,0 +1,145 @@ +English · [中文](../zh_cn/contributing.md) + +[Docs home](README.md) › Contributing + +# Contributing + +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 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 + bash .github/scripts/check-c.sh + bash .github/scripts/check-c.sh analyze # GCC only + ``` + +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. + +`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 atop every `tests/*.c`, with its + `In scope (contract)` and `Out of contract (not exercised)` lists. + +A behavior change updates all of them together: + +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/`. + +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 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: `./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 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 slack capacity can hide. + +Run the suite with CI's environment: + +```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. +- 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 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 + +| 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 | +| [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 | +| [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..3aee985 --- /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 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. + +## Goals and non-goals + +The design follows from a short set of goals: + +- **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.** 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 + 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 + +### 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 only because `` +includes it. `sx_split` and the regex layer are declared only 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 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 `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". +- 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 + +`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 that `sx_core.h` only + forward-declares; +- 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 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 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`: 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`. 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` 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)`: the `_sx` header plus a +`cap`-byte array (minimum 1, so `ptr[0]` has a home). Constructor +capacities: + +| 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 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)`, 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` | +| --- | --- | +| `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` | + +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, 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 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` 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 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.** 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 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 + +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 + 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 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: no `errno`, error object or 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` | +| 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` 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 + +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 uses 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, 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 `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). + +### 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 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, 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 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 + +| 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 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, `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 + +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_compile(pattern, PCRE2_ZERO_TERMINATED, 0, ...)`. The `0` is the +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 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: + +```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 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 + +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, 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 + +Replace is built from PCRE2's substitution routine, with two fixed flags: + +```c +options |= PCRE2_SUBSTITUTE_UNSET_EMPTY | PCRE2_SUBSTITUTE_UNKNOWN_UNSET; +``` + +`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 output length is unknown beforehand, the wrapper substitutes +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 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 + +| 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 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.** 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, memmem and the portable switches + +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 + +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 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 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, 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. + +## 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 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 (24 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 | +| `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 | +| `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 | +| `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 tests run: + +- 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` 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 + `security-and-quality` queries. +- Tests disable LTO (`set(TARGET_LTO, 1, DISABLE)` in `build.c`) because the + pinned build tool emits GCC-only `-flto=N` 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 | +| 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 | +| 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 each rule's out-of-contract side. + +## Licensing + +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; the library sources 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..7ed87df --- /dev/null +++ b/docs/en_us/getting-started.md @@ -0,0 +1,300 @@ +English · [中文](../zh_cn/getting-started.md) + +[Docs home](README.md) › Getting started + +# Getting started + +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 + +| 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` | [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 . # generate ./make +./make # build -> build/output/libstringx.so +./make test # build and run every test under tests/ (ASan + UBSan + LSan) +``` + +`./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 + +```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 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" +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 +``` + +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 + +```sh +./make gen_deb +sudo apt install ./build/deb/libstringx_0.5_amd64.deb +``` + +`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 + +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) { + /* 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; +} +``` + +After installing as shown above, build and run it with: + +```sh +cc hello.c $(pkg-config --cflags --libs libstringx) -o hello +./hello +``` + +```text +Hello, String X! (16 bytes) +``` + +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 common tasks, one complete program each, compiled like `hello.c`. + +### 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) | build 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..c81c3d6 --- /dev/null +++ b/docs/en_us/guide.md @@ -0,0 +1,448 @@ +English · [中文](../zh_cn/guide.md) + +[Docs home](README.md) › User guide + +# User guide + +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 + +### 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` 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` (`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. + +### 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 + +One place owns a buffer at a time; per-call result and release: + +| 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` | + +- 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`, `sx_insert_view` take a string or view, never 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 | + +`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: `_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 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 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`, `sx_clear` free nothing. + +## 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 | +| `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 +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_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/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 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 it like `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 +(independent result); `sx_find_view_b` searches only the region from 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 view array whose end guard has `ref == NULL`; +empty fields are kept. `free` the array; keep the buffer alive while reading +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 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 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. +- 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: `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`, 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` across threads without synchronization: no internal + locking; only a compiled `sx_reg_t` is documented as immutable and shareable. + +## Performance notes + +- **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; 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. +- **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: a cleared buffer is reusable, but a peak stays allocated until + `sx_free`. + +## FAQ + +**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 +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`/`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 scan one byte on. + +--- + +[← 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..6e2ef85 --- /dev/null +++ b/docs/en_us/regex.md @@ -0,0 +1,524 @@ +English · [中文](../zh_cn/regex.md) + +[Docs home](README.md) › Regular expressions + +# Regular expressions + +## Overview + +`` 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 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 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`: 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: + +| 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. The pattern string is +not retained, so free it after compilation; release the handle with +`sx_reg_free` when done. + +```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; +} +``` + +Three properties keep it safe in long-lived code: + +- 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 + +```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` 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. + +- 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 */ +/* 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. + +- 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 */ +``` + +## Match family + +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 + +```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 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. + +- 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 +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`: `.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, 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 its length changes 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 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. + +- 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*"); +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 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. + +| 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 fixes the `sx_reg_split` token count: always +`number_of_matches + 1`. + +## Replace family + +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 + +```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` 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; 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. + +```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`, but only the **leftmost** match is +substituted; all other bytes are 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 use PCRE2's substitution syntax for `repl`, with two +wrapper-fixed options 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) | + +- 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 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 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)). + +```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 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 + 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 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` | + +- 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`, 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; 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 + +| 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 | + +- 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 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. + +## 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**: 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 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). + +--- + +[← 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..225bcbd --- /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) —— `./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..ea4262a --- /dev/null +++ b/docs/zh_cn/api-buffer.md @@ -0,0 +1,696 @@ +[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` 的指针在任何可能重新分配的调用后 +失效,必须重新获取。修改失败时 `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`,以及违反条目条件的下标。 + +**哨兵值。** + +| 情形 | 取值 | +| --- | --- | +| 分配失败 | `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` 有保证;初始 32 字节属于实现细节。 + +### 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`;此后不得使用或 + 释放它。即使写入失败,`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"); +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`。 +- **边界情况:** 更短的 `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` 本身必须有效。 +- **边界情况:** `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`(仍归调用方所有)。 +- **边界情况:** 设置 `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` —— 有符号字节偏移。 +- **返回:** 同一缓冲区上调整后的视图。 +- **边界情况:** `len` 不变(不同于 advance/retreat)。正 `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..d5c8cbc --- /dev/null +++ b/docs/zh_cn/api-search.md @@ -0,0 +1,540 @@ +[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` API。全部 +字节精确并按内容长度工作,内嵌 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。长度为 0 的 needle 永远不会被找到。 + +**有界区域。** 设 `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 —— 窗口 `[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。** + +| 家族 | 未找到 / 拒绝输入时的结果 | +| --- | --- | +| `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` 或 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*` 还额外分配结果数组,并报告每一次出现(含重叠)。 + +## 如何选择调用 + +| 你需要 | 使用 | +| --- | --- | +| 整串中最左的出现 | `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`。 +- **边界情况:** `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`。 +- **边界情况:** `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`。 +- **边界情况:** 二进制安全;偏移升序且包含重叠匹配。 + +### 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`。 +- **边界情况:** `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`。 +- **边界情况:** 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`。 +- **边界情况:** 只搜索内容,因此 `'\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 失效;使用期间不要修改 `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..76899bb --- /dev/null +++ b/docs/zh_cn/build-and-test.md @@ -0,0 +1,307 @@ +[English](../en_us/build-and-test.md) · 中文 + +[文档首页](README.md) › 构建、测试与打包 + +# 构建、测试与打包 + +String X 使用 [Forge](https://github.com/minelogy-dev/forge) 构建。本页介绍 +环境要求、`./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 | [github.com/minelogy-dev/forge](https://github.com/minelogy-dev/forge);`./make` 是生成物,不纳入版本库。 | +| `tar` 与 `ar` | 只有 `./make gen_deb` 需要;`dpkg-deb` 仅用于检查产物。 | + +命令在仓库根目录执行;`build.c`、`build.conf` 相对该目录读取。 + +## 构建工具 + +从 [Forge](https://github.com/minelogy-dev/forge) 仓库安装 Forge。运行一次 +`forge .` 生成 `./make` 后,日常命令为: + +```sh +forge . # 生成 ./make +./make # 构建 -> build/output/libstringx.so(头文件随附于 build/output/include) +./make test # 编译并运行 tests/ 下每个测试(ASan + UBSan) +``` + +`./make` 是生成物且被 gitignore;修改 `build.c` 或 `build.conf` 后重跑 +`forge .`。 + +## 目标与命令 + +| 命令 | 作用 | +| --- | --- | +| `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/` 下的每个文件。 | +| `./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` 在生成 `./make` 时读取;每个 `KEY=VALUE` 行变成 +`-DCONF_KEY=VALUE` 宏,`#` 开头为注释。修改后重跑 `forge .`。 + +| 键 | 取值 | 作用 | +| --- | --- | --- | +| `compiler` | `GCC` 或 `CLANG` | 工具链后端。`build.c` 把 `CONF_compiler` 传给 `set_toolchain`,因此它同时决定库与测试使用的编译器。 | +| `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: <文件>:<行号>: <表达式>`。汇总形如: + +```text +forge: 24 tests, 24 passed, 0 failed +``` + +测试编译或运行失败时,任务以非零状态退出。 + +测试不链接 `libstringx.so`:各自直接编译库源码,并在头部声明选项,包括 +`-fsanitize=address,undefined` 与 `-fno-omit-frame-pointer`。LeakSanitizer 与 +ASan 一起运行,忘记释放缓冲区或数组的测试会失败。少数测试在普通配置与强制 +配置的兄弟目标间共享本地用例头(`find_differential.h`、 +`write_overflow_cases.h`);每个 `.c` 仍是独立目标。 + +设置 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` 与 `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 + +每个测试都是自包含程序。开头连续的 `//` 行是测试运行器读取的头部 +DSL,第一行非 `//` 内容结束。 + +| 条目 | 作用 | +| --- | --- | +| `// 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`);测试为清晰起见写出了每个 +关键字。 + +每个测试都编译 `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` 中;按 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` 失败 | 固定版本的构建工具在并行 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` 链接,或安装到标准前缀。 | + +不要在库源码或程序中包含 ``:它是构建脚本的 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..466f970 --- /dev/null +++ b/docs/zh_cn/ci.md @@ -0,0 +1,120 @@ +[English](../en_us/ci.md) · 中文 + +[文档首页](README.md) › 持续集成 + +# 持续集成 + +对 `main` 的改动、拉取请求与手动运行都使用 GitHub Actions。本页介绍工作流、 +本地复现与合并保护;构建命令、`./make` 目标与测试框架见 +[构建、测试与打包](build-and-test.md)。 + +## 触发条件 + +| 事件 | 工作流 | +| --- | --- | +| 推送到 `main` | [ci.yml](../../.github/workflows/ci.yml) 与 [codeql.yml](../../.github/workflows/codeql.yml) | +| 任意分支上的 `pull_request` | `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` 运行,且不保留检出凭据。 + +## 检查项 + +| 检查 | 验证内容 | +| --- | --- | +| 构建与测试(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 页与拉取请求中 | +| 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` 绕过。 + +外部 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` 查询。它分析由 +固定工具链构建的代码,把发现发布到 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 +``` + +CI 将 Forge 固定到经过评审的提交(检出到 `.ci-deps/forge`);两个工作流文件 +包含该固定点与相关命令,更换时须同步更新。PCRE2 来自 Ubuntu 的 +`libpcre2-dev` 包。已安装 Forge 时: + +```sh +forge . +./make +./make test -j 2 +``` + +专项审计脚本位于 `.github/scripts/`(`check-write-safety.py`、 +`compare-search.py`);`benchmarks/` 自带基准框架与复跑说明。 + +CI 还会安装到临时前缀,用 `pkg-config` 把现有正则测试编译并链接到**已安装的 +共享库**后运行,并检查生成的 Debian `.deb`。这样除源码级行为外,还验证公开头文件、 +导出符号、包元数据与 PCRE2 链接。命令在 `ci.yml` 中,布局见 +[构建、测试与打包](build-and-test.md)。 + +## 评审与失败处理 + +打开失败的检查,查看编译器诊断、内存检查器堆栈或密钥扫描位置。构建失败保留依赖 +与命令元数据七天;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..e1b6426 --- /dev/null +++ b/docs/zh_cn/contributing.md @@ -0,0 +1,129 @@ +[English](../en_us/contributing.md) · 中文 + +[文档首页](README.md) › 贡献指南 + +# 贡献指南 + +String X 是一个契约详细的小型 C23 库,请保证文档、测试、改动的同步。本页说明 +工作流程与项目约定。 + +## 工作流程 + +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)。按路径过滤的 write-safety、 + search-performance 与 benchmark 工作流也会在匹配的改动上运行。 +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) | 自包含的测试套件 | +| [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/](../) | 本文档,含英文与简体中文 | +| [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..8616730 --- /dev/null +++ b/docs/zh_cn/design.md @@ -0,0 +1,681 @@ +[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。 +- 扫描自包含:核心的 KMP 原语是 `sx_core.c` 内的 `static` 实现,高级层 + 无法调用;分割扫描本来也被输出规模约束。源码注释直说这一取舍: + `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`,而非哨兵 `sx_t *`);它们服务于库自身翻译单元,不是客户端; +- 它不提供稳定性承诺。安装后的头文件集合包含它,是因为构建会复制整个 + `include/*.h`,但它不属于受支持 API,客户端不得使用。四个 `sx__*` + 辅助函数声明为 `SYMBOL_PUBLIC`,因此会出现在共享库动态符号表中;导出 + 不代表受支持。 + +## 缓冲区布局与不变式 + +公开的 `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`,不释放任何东西。 +- **写入范围拒绝是文档化行为。** 若 `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`、错误对象或错误返回码。 + +| 情况 | 哨兵值 | +| --- | --- | +| 偏移查找(`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` | +| 写入范围溢出或末端无法预留 | `NULL`;`self` 不变(`owned` 输入被消耗) | +| 布尔谓词与 `sx_reg_is_match` | `0` | + +两个后果是有意为之,并且都有文档: + +- **"无结果"与"内存不足"可能无法区分。** `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` 参数。 + +## 查找内部实现 + +整个查找家族建立在 `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)`。它是 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)。 + +### 最左原生快路径 + +最左单结果调用(`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` 时,回退路径(以及 `sx_rfind*` 与 `sx_find_all*` 使用的 +原语)计算 KMP 前缀表(`pi`,一次 `malloc(m * sizeof(size_t))`),并在 +`O(n + 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]` 是计数,不是位置。 + +### 复杂度 + +| 情况 | 技术 | 时间 | 额外内存 | +| --- | --- | --- | --- | +| 单字节 needle,最左单结果 | `memchr` | `O(n)` | 无 | +| 单字节 needle,最右单结果 | `memrchr` 或反向扫描 | `O(n)` | 无 | +| 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*` 在原生路径上不分配;KMP 回退(以及所有多字节 `sx_rfind*`) +会分配一张临时前缀表,并在返回前释放。 + +## 正则封装内部实现 + +高级正则层刻意保持很薄。它的全部状态就是一个已编译的 PCRE2 代码对象: + +```c +typedef struct sx_reg_t { + pcre2_code *code; +} sx_reg_t; +``` + +### 编译与释放 + +`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_match(code, subject, len, offset, 0, md, NULL)`:主体 +以显式**长度**传入而非 C 字符串,`NULL` 匹配上下文意味适用 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`;越过主体长度时 PCRE2 报错、 +循环结束。因此 `a*` 对 `"bbb"` 报告偏移 0–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` 不传。 + +由于事先不知道输出长度,封装替换两次: + +```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、memmem 与可移植开关 + +查找路径使用两个 glibc 扩展:`memrchr`(最右单字节扫描)和 `memmem` +(最左原生快路径)。`sx_core.c` 手动声明两者,并只在定义了 `__GLIBC__` +时编译进去。`-DSX_FORCE_NO_MEMRCHR` 与 `-DSX_FORCE_NO_MEMMEM` 强制使用 +可移植路径;仓库测试除 glibc 路径外,还运行强制可移植的差分查找测试, +因此两条回退路径都能在 glibc 上构建并检查。 + +### 整数访问器与 SIZE_MAX + +公开访问器返回 `int`,而偏移和 needle 使用 `size_t`: + +| 函数 | 返回类型 | +| --- | --- | +| `sx_len`、`sx_len_view` | `int`(内容字节数) | +| `sx_cap` | `int`(总分配量) | +| 偏移(`sx_find*`、视图字段、正则视图) | `size_t` | + +内容字节数超过 `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` 可能让无符号尺寸运算回绕,这类 + 调用在测试契约之外。 + +### 平台假设 + +- 库使用 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 链接参数,但它仍是共享库的运行时 + 依赖。 +- 安装与 Debian 打包目标由 `build.c` 中的 `LINUX` 宏保护;库本身按普通 + C23 编译。 + +## 测试策略 + +`tests/` 下每个文件都是自包含程序。文件头注释声明构建方式(由固定版本 +构建系统消费的 `// Include`、`// Source`、`// Option`、`// Link`、 +`// Library` 行),并记录**行为边界**:"In scope (contract)"列表和 +"Out of contract (not exercised)"列表。文件头也是契约的一部分:行为变化 +必须同步更新边界列表(见[贡献指南](contributing.md))。 + +测试套件(24 个)按主题一文件: + +| 测试 | 锁定的内容 | +| --- | --- | +| `access.c` | `sx_len` / `sx_cap` / 缓冲区访问器 / 整缓冲区视图 | +| `append.c` | append 家族、所有权转移、别名追加 | +| `chain.c` | 修改串联、句柄同一性、零泄漏所有权 | +| `cmp.c` | 按字节的字典序比较 | +| `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` | 正则家族、二进制安全主体、零长匹配处理 | +| `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` | 覆盖、尾部追加与填充语义 | +| `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 设置 + `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1` 和 + `UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1`。 +- `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 中用 + `-O1 -fno-analyzer-state-merge`),CodeQL 用 `security-and-quality` + 查询扫描。 +- 测试禁用 LTO(`build.c` 中 `set(TARGET_LTO, 1, DISABLE)`),因为 + 固定版本的构建工具为并行 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`) | +| 最左原生快路径 | glibc 上常见查找更快,`m <= 32` 时不分配内存 | 额外的 libc 特定代码,需要强制可移植测试 | +| 受检的写入范围算术 | 算术溢出返回文档化的 `NULL`,而不是破坏内存 | 每次写入多一个分支;`owned` 输入仍被消耗 | +| 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`、`build.c` 与 +`src/export.h` 带有 +`GPL-3.0-or-later WITH LicenseRef-Forge-BuildScript-Exception` SPDX +标识;库源码本身仍为 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..19fa015 --- /dev/null +++ b/docs/zh_cn/getting-started.md @@ -0,0 +1,296 @@ +[English](../en_us/getting-started.md) · 中文 + +[文档首页](README.md) › 快速上手 + +# 快速上手 + +String X 是一个轻量的 C23 字符串库:每个字符串是一段 NUL 结尾的缓冲区, +切片是零拷贝视图,全部按字节长度处理(内嵌 NUL 是普通数据)。公开接口只有 +一个头文件 `` 和一个库 `libstringx`(`-lstringx`);可选的 PCRE2 进阶层 +提供正则表达式。版本:**v0.5**。 + +## 环境要求 + +| 要求 | 说明 | +| --- | --- | +| Linux | 经过测试的平台;构建与测试均面向 Linux | +| C23 编译器 | GCC 14+ 或 Clang 19+;CI 在 Ubuntu 24.04 上使用 GCC 14 与 Clang 19 | +| `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 . # 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 下运行 +(`-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_PATH` 让 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 中的快速上手程序:每次修改都返回同一句柄,因此整条链是一个表达式; +`sx_append` 消费临时缓冲区,结果只需一次 `sx_free`。扩容后句柄仍然有效, +且每次调用后缓冲区都以 NUL 结尾。 + +```c +#include +#include + +int main(void) { + /* 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; +} +``` + +按上文完成安装后,用下面的命令构建并运行: + +```sh +cc hello.c $(pkg-config --cflags --libs libstringx) -o hello +./hello +``` + +```text +Hello, String X! (16 bytes) +``` + +在安装之前,也可以直接使用源码树的构建输出: + +```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) | 构建目标、测试框架、安装 | +| [贡献指南](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..0248477 --- /dev/null +++ b/docs/zh_cn/guide.md @@ -0,0 +1,423 @@ +[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` 接收字符串或视图,永不消费缓冲区。 + +## 二进制安全与 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` +复制每个内容字节。二进制缓冲区按长度打印,不要用 `printf("%s", ...)`: +`fwrite(sx_buf_mut(h), 1, (size_t)sx_len(h), stdout)`。 + +比较与查找同理:`_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` 缓冲区 | +| `sx_write*`:范围末端使 `size_t` 溢出或无法预留 | `NULL`;`self` 不变(`owned` 输入被消耗) | +| 分配失败 | `NULL` | + +`NULL` 表示"没有结果";对返回数组的调用而言,分配失败与"无匹配"无法区分。 +文档化的 NULL 实参处理是有限的: + +- `sx_new_from_cstr(NULL)` 与 `sx_dup(NULL)` 返回 `NULL`。 +- 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`。 +- `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`;`sx_insert_view` 仅当 + 切片起点不晚于 `idx`(测试覆盖的情形)才可用,起点晚于 `idx` 的自别名切片 + 会被尾部右移覆盖,请先复制。 +- `sx_insert*` 的 `idx > len`:尾部右移会下溢。受测契约是 `0 <= idx <= len`。 + `sx_write*` 不同:它会填充并扩展。 +- 读取增长 `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` 时当成错误:它是有文档说明的空操作。 +- 向不检查 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..3962f3e --- /dev/null +++ b/docs/zh_cn/regex.md @@ -0,0 +1,485 @@ +[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 传递编译选项;模式内部选用的特性(如内联选项 `(?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` 被释放或长度改变后使用该视图属于契约之外。 + +```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`。无匹配、参数为 `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 结尾的替换模板;不会被保留 | + +返回新缓冲区;参数为 `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_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` 完全一致: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。 +- 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_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 项目在 [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)