Skip to content

obs-util: dstr FFI appends edit the C buffer in place (#1297) - #1393

Merged
zackees merged 3 commits into
masterfrom
perf/1297-dstr-ffi-in-place
Oct 18, 2026
Merged

zackees merged 3 commits into
masterfrom
perf/1297-dstr-ffi-in-place

Conversation

@zackees

@zackees zackees commented Oct 18, 2026 •

Copy link
Copy Markdown
Member

Fixes #1297. #1296's dstr/safe_printf is now within the 1.10 bound too, so #1296 can close.

Cause

rust/obs-util/src/ffi/dstr.rs ran every shim through with(): read() copied the whole C string into an owned Dstr (slice::from_raw_parts(..).to_vec()), and write() copied it back into a new bmalloc buffer. So an 8-byte dstr_ncat copied the existing 128 or 4096 bytes twice and made a Rust heap allocation. dstr_safe_printf went through the same round trip once per step (copy plus up to four replaces).

Design

  • ensure_capacity is a direct port of dstr_ensure_capacity from dstr.h: same grow_capacity rule and the same brealloc call, so capacity and the allocator traffic match C.
  • write_at(d, at, src, n) grows the buffer to at + n + 1, memmoves the bytes and sets len and the NUL. It backs dstr_ncat, dstr_cat_dstr, dstr_cat_strref (through dstr_ncat), dstr_ncat_dstr and dstr_copy.
  • dstr_replace and dstr_safe_printf edit the buffer in place. New safe core helpers in src/dstr.rs: replace_plan finds the first match and the grown length, replace_in_place handles same-length and shrinking replaces, and replace_grow grows once, moves the tail to the end and rebuilds front to back. Dstr::replace uses the same helpers, so Tier 1 covers them.
  • find_from now finds the first byte with SIMD memchr (new direct dependency memchr = "2", already in Cargo.lock). cstr uses it too. The replace value is measured once instead of at each step. I tried memmem::Finder first, but building the searcher cost more than the search for these short needles.
  • The rarer paths (insert, remove, left, mid, right, depad, ncopy) still go through with().

SAFETY reasoning

  • Every new unsafe block has a SAFETY comment. Pointers come only from the caller's dstr/strref contract, and the buffer only ever comes from the bmalloc family.
  • Aliasing: before a grow, write_at checks whether src points into d's own buffer ([array, array + capacity)). If it does, it re-derives src from the possibly moved buffer at the same offset after brealloc. brealloc keeps the old contents, and the copy is a memmove, so dstr_cat_dstr(d, d), dstr_ncat_dstr(d, d, n) and dstr_ncat(d, d->array + k, n) are all defined. In C the last one is a use-after-free when it reallocs.
  • dstr_cat_dstr and dstr_ncat_dstr read src's array and len before touching dst, because src may be dst.
  • The replace slices are built from array/len with no other live reference. A grow re-reads array after ensure_capacity.
  • No #[cfg]/libc additions (platform boundary unchanged).

Intentional difference from C (listed in the dstr_parity.rs header and rust/README.md)

A source that points into the destination's own buffer is undefined behavior in C. This covers dstr_ncat and dstr_cat_strref with a pointer into dst->array, dstr_cat_dstr(d, d), and dstr_copy from inside dst->array. C breallocs and then memcpys from the freed pointer, or copies overlapping ranges. Rust takes the offset before the grow, finds the source again in the new buffer and memmoves it. The result is the source bytes as they were before the call. The parity test never sends this case to the C oracle: Rust gets the aliasing pointer, and C gets a private copy of the same bytes. Both sides are then compared on bytes, terminator, len and capacity. dstr_ncat_dstr(d, d, n) is defined in C, so both sides get the aliasing pointer there.

New direct dependency: memchr = "2"

obs-util now depends on memchr directly. It was already in Cargo.lock as a transitive dependency (2.8.3), so no new crate enters the build. It provides the SIMD first-byte scan in find_from and cstr. C uses libc strstr/strlen, and the scalar Rust scan was the remaining safe_printf gap: a byte loop over the 4 KiB value. I tried memmem::Finder first, but building the searcher cost more than the search for these short needles.

Parity coverage (Tier 3, tests/strings/dstr_parity.rs)

New ops are compared against the C oracle after every step. The comparison covers bytes, terminator, len and capacity:

  • CatSelf: dstr_cat_dstr(d, d). Only Rust gets the aliasing pointer.
  • NcatDstrSelf: dstr_ncat_dstr(d, d, len)
  • NcatFromOwn: dstr_ncat(d, d->array + start, len), including lengths that make the buffer move. Only Rust gets the aliasing pointer.
  • CopyFromOwn: dstr_copy(d, d->array + start). Only Rust gets the aliasing pointer.

Existing ops already cover a NULL dstr, a NULL or empty source, and embedded NULs. The suite also passed with PROPTEST_CASES=20000.

RED/GREEN evidence

  • RED (e61ace233, tests only): tests/strings/dstr_alloc.rs::ffi_in_place needs zero Rust-side allocations. On master the tests fail:

    • ncat_onto_4096_with_spare_capacity_does_not_allocate: left 2, right 0
    • appends_that_grow_do_not_allocate_rust_side: left 13, right 0
    • safe_printf_does_not_allocate_rust_side: left 3, right 0

    The C-side bmalloc/brealloc is not counted; it stays what C does.

  • GREEN (aa6647cd6): soldr cargo test -p obs-util passes and ./lint gives rc=0.

Benchmarks

soldr cargo bench -p obs-c-oracle --bench port_comparison -- 'dstr/(cat|safe_printf)/', criterion medians, same machine.

bench before Rust before C ratio after Rust after C ratio
dstr/cat/128 114.98 ns 53.14 ns 2.16 52.65 ns 52.59 ns 1.00
dstr/cat/4096 242.43 ns 115.70 ns 2.10 141.53 ns 136.85 ns 1.03
dstr/safe_printf/128 241.80 ns 142.47 ns 1.70 159.07 ns 148.64 ns 1.07
dstr/safe_printf/4096 1.964 µs 331.27 ns 5.93 339.68 ns 335.79 ns 1.01

On an earlier after-run, dstr/replace was 918 ns (Rust) vs 1188 ns (C) at 128 and 32.4 µs vs 86.4 µs at 4096, so Rust is still faster there. The machine was shared (load average around 10 to 17), and the C medians moved by up to ±15% between runs.

…Rust side (#1297)

The C ABI shims copy the whole C string into an owned Dstr and back for
every append, so an 8-byte dstr_ncat onto a 4096-byte string allocates.
New deterministic allocation-counting tests (as in #1389) require zero
Rust-side allocations for dstr_ncat/cat_dstr/cat_strref/ncat_dstr and
dstr_safe_printf; they fail now (2, 13 and 3 allocations).

Tier 3 parity gains the aliasing cases: cat_dstr(d, d), ncat_dstr(d, d),
ncat from inside d's own buffer and copy from inside it, with capacity
compared after every step.
dstr_copy, dstr_ncat, dstr_cat_dstr, dstr_cat_strref, dstr_ncat_dstr,
dstr_replace and dstr_safe_printf no longer copy the whole string into an
owned Dstr and back. They grow the C buffer with dstr_ensure_capacity's
rule and the same brealloc call, then memmove the new bytes and write len
and the terminator. A source inside the destination buffer (cat_dstr(d, d),
a pointer into d->array) is re-derived after a moving brealloc.

dstr_replace runs on the buffer in place: same-length and shrinking
replaces compact in place, a growing one grows the buffer once and
rebuilds front to back. find_from uses a SIMD memchr for the first byte,
and the replace value is measured once instead of per step.

Medians (Rust/C): dstr/cat/128 114.98/53.14 -> 52.65/52.59 ns,
dstr/cat/4096 242.43/115.70 -> 141.53/136.85 ns, dstr/safe_printf/128
241.80/142.47 -> 159.07/148.64 ns, dstr/safe_printf/4096 1963.8/331.27 ->
339.68/335.79 ns.
@zackees
zackees enabled auto-merge October 18, 2026 04:35
@zackees
zackees disabled auto-merge October 18, 2026 04:36
…acle off C UB (#1297)

A source that points into the destination buffer (dstr_ncat/cat_strref
with a pointer into dst->array, dstr_cat_dstr(d, d), dstr_copy from inside
dst->array) is UB in C (memcpy from the freed pointer after brealloc, or
overlapping memcpy). Rust finds the source again after the grow and
memmoves it. Listed in the parity header and in rust/README.md. The parity
ops now give only Rust the aliasing pointer, and C a private copy of the
same bytes, so the oracle is never fed the UB case. NcatFromOwn now also
covers the growing (moving) case on the Rust side.
@zackees
zackees enabled auto-merge October 18, 2026 04:39
@zackees
zackees added this pull request to the merge queue Oct 18, 2026
Merged via the queue into master with commit 3fa2833 Oct 18, 2026
23 checks passed
@zackees
zackees deleted the perf/1297-dstr-ffi-in-place branch October 26, 2026 15:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

bug: dstr: concatenation copies the entire buffer through an owned model

1 participant