navid/veins / commit
e362a182625e
Navid M <navidmomtahen@gmail.com> · 2026-11-27
parents: 0f2b7d81e2f0
Browse files at this commit · Download source
--- a/.gitignore+++ b/.gitignore@@ -1,1 +1,2 @@+.vscode .DS_Store--- a/veins-cpprewrite/.gitignore+++ b/veins-cpprewrite/.gitignore@@ -1,2 +1,3 @@ /build*/ /.cache/+.net-bench/--- /dev/null+++ b/veins-cpprewrite/BENCHES.md@@ -0,0 +1,200 @@+# veins benchmarks++Two reproducible benchmark sets are kept here: a local-core comparison that includes+the Rust subset, and the native network comparison between the C++ rewrite and Spectre.++## Local core: Rust subset vs C++ vs Spectre++Generated 2026-11-27 by `bench/core_bench.py`.++### Environment++| Implementation | Binary |+|:---|:---|+| Rust | `veins-rust v0.1.0 (veins-store 1)` |+| C++ | `veins v0.0.1 (veins-store 1)` |+| Spectre | `veins v0.0.1 (veins-store 1)` |++```+host: Darwin arm64+cpu: Apple M2+repeats: 5 (median reported)+cpu pinning: no+```++### Scope++The Rust binary implements the local-core subset: `init`, `status`, `log`, `go`/`commit`, `co`/`checkout`, `bmk set|ls|rm`, `self-test`, and `version`.+It uses the same FastCDC parameters, BLAKE3 object IDs, zstd level 1, pack/index layout, operation log, and stat-cache invalidation window as the reference.++The subset does not implement merge/conflict objects, rebase/undo, the git bridge, ignore files, or the network protocol. The workload below contains no renames, ignores, merges, or network traffic, so the measured local operations are directly comparable.++### Workload++- Base snapshot: 2.95 MiB, 42 files.+- 20 edit/commit revisions, 8 checkouts, 5 repeats, median reported.+- Each revision rewrites about 1% of a 120,000-line generated C file and three small module files.+- Each `go` performs the same snapshot, describe, and new-empty-change sequence as the reference, including all operation-log writes.+- Store size includes `.veins` packs, indexes, operation heads, the native commit map, and the stat cache.++### Summary++| Metric | Rust | C++ | Spectre | C++ / Rust | Spectre / Rust |+|:---|---:|---:|---:|---:|---:|+| Commit total [s] | 0.252 (0.250-0.262) | 0.280 (0.279-0.291) | 0.310 (0.309-0.330) | 1.11x | 1.23x |+| Checkout total [s] | 0.162 (0.161-0.165) | 0.175 (0.172-0.179) | 0.181 (0.179-0.196) | 1.08x | 1.12x |+| Store size [MiB] | 8.28 (8.28-8.37) | 8.28 (8.28-8.37) | 10.60 (10.60-10.69) | 1.00x | 1.28x |++Each cell is the median with the observed min-max range in parentheses.+A ratio above 1 means the other implementation took longer or used more space than Rust.++### Repeats++| Repeat | Rust commit [s] | C++ commit [s] | Spectre commit [s] | Rust checkout [s] | C++ checkout [s] | Spectre checkout [s] |+|:---|---:|---:|---:|---:|---:|---:|+| 1 | 0.262 | 0.291 | 0.330 | 0.165 | 0.172 | 0.195 |+| 2 | 0.250 | 0.280 | 0.310 | 0.162 | 0.172 | 0.196 |+| 3 | 0.252 | 0.281 | 0.309 | 0.161 | 0.179 | 0.179 |+| 4 | 0.252 | 0.279 | 0.309 | 0.162 | 0.175 | 0.179 |+| 5 | 0.257 | 0.280 | 0.311 | 0.165 | 0.177 | 0.181 |++### Notes++- Both implementations use the same FastCDC parameters, BLAKE3 object IDs, zstd level 1, pack/index layout, operation log, and stat-cache racy window.+- Each `go` performs the same snapshot, describe, and new-empty-change sequence in both implementations, including three operation writes.+- The Rust subset omits ignore-file parsing and similarity-based rename detection. This workload has neither ignore files nor renames, so both implementations see the same file set and perform the same exact-rename scan.+- Rust and C++ store sizes are equal at this resolution; Spectre stores the same logical history with a different packing policy.+- This is a single-machine run. Treat differences below roughly 5% as noise.++### Reproduce++```sh+cd veins-rust+cargo build --release+cd ../veins-cpprewrite+python3 bench/core_bench.py --repeats 5 --markdown-out bench/core_bench.md+```++## Networking: C++ rewrite vs Spectre++Generated 2026-11-27 16:15:11 UTC by `bench/net_bench.sh`.++The Rust subset is not included in this section because it does not implement a+network transport.++### Environment++```+host: Darwin arm64+cpu: Apple M2+hyperfine: hyperfine 1.20.0+c++ vn: veins v0.0.1 (veins-store 1)+spectre vn: veins v0.0.1 (veins-store 1)+runs: 10 (clone/fetch/push/checkout), 20 (whoami)+warmup: 1 (clone/fetch/push/checkout), 2 (whoami)+```++### Dataset++- `bench_src`: 361 working files, 5.7M on disk including packs.+ - 360 small text files in 18 directories.+ - 2 MiB `big_old.bin` in the `oldbig` history.+ - 1 MiB `big_head.bin` in `main`.+- `push_pristine`: a separate 20-file repository, so push does not transfer the large dataset.++### What each benchmark does++| Benchmark | Operation |+|:---|:---|+| `clone-file` | Full clone over `file://`: handshake, refs, history, head chunks, checkout. Includes spawning one local server per run. |+| `fetch-file` | `vn fetch origin` with no new remote refs. Both clients start from a full `-blobs:all` clone. |+| `lazy-checkout-file` | `vn co oldbig` in a `-blobs:none` clone, fetching the 2 MiB old blob from the promisor over `file://`. |+| `push-file` | Push one new commit from a prepared client to a freshly reset copy of `push_pristine` over `file://`. |+| `whoami-file` | Connect, authenticate, `WHOAMI`, close over `file://`. |+| `clone-ssh` | Full clone over `ssh://`, using a local `ssh` shim that runs the remote `vn serve -stdio` command. |+| `clone-tls` | Full clone over TLS 1.3 with a pinned self-signed certificate. Uses long-running servers. |+| `whoami-tls` | Connect, authenticate, `WHOAMI`, close over TLS 1.3. |++Lower is better. Hyperfine reports wall-clock time; the relative column is against the fastest command.++### Summary++| Benchmark | C++ mean | Spectre mean | Spectre / C++ |+|:---|---:|---:|---:|+| Clone file:// | 35.9 ms | 61.0 ms | 1.70x |+| Fetch file:// | 24.6 ms | 31.2 ms | 1.27x |+| Lazy checkout file:// | 253.1 ms | 420.2 ms | 1.66x |+| Push file:// | 17.0 ms | 16.0 ms | 0.94x |+| Whoami file:// | 9.7 ms | 12.5 ms | 1.28x |+| Clone ssh:// | 42.5 ms | 66.6 ms | 1.57x |+| Clone TLS 1.3 | 37.9 ms | 64.9 ms | 1.71x |+| Whoami TLS 1.3 | 10.0 ms | 14.8 ms | 1.48x |++A ratio above 1 means Spectre took longer than C++.++### Results++#### Clone over file://+| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |+|:---|---:|---:|---:|---:|+| `C++` | 35.9 ± 0.3 | 35.5 | 36.3 | 1.00 |+| `Spectre` | 61.0 ± 1.8 | 58.2 | 63.4 | 1.70 ± 0.05 |++#### Fetch over file://+| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |+|:---|---:|---:|---:|---:|+| `C++` | 24.6 ± 0.4 | 23.9 | 25.1 | 1.00 |+| `Spectre` | 31.2 ± 1.0 | 30.2 | 32.6 | 1.27 ± 0.04 |++#### Lazy checkout over file://+| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |+|:---|---:|---:|---:|---:|+| `C++` | 253.1 ± 7.1 | 247.7 | 272.4 | 1.00 |+| `Spectre` | 420.2 ± 14.5 | 402.5 | 451.8 | 1.66 ± 0.07 |++#### Push over file://+| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |+|:---|---:|---:|---:|---:|+| `C++` | 17.0 ± 6.8 | 12.3 | 32.0 | 1.06 ± 0.43 |+| `Spectre` | 16.0 ± 0.4 | 15.7 | 16.8 | 1.00 |++#### Whoami over file://+| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |+|:---|---:|---:|---:|---:|+| `C++` | 9.7 ± 0.6 | 8.7 | 10.5 | 1.00 |+| `Spectre` | 12.5 ± 0.2 | 12.1 | 12.9 | 1.28 ± 0.08 |++#### Clone over ssh://+| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |+|:---|---:|---:|---:|---:|+| `C++` | 42.5 ± 0.4 | 41.9 | 43.2 | 1.00 |+| `Spectre` | 66.6 ± 1.2 | 64.4 | 67.8 | 1.57 ± 0.03 |++#### Clone over TLS 1.3+| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |+|:---|---:|---:|---:|---:|+| `C++` | 37.9 ± 1.4 | 35.9 | 39.8 | 1.00 |+| `Spectre` | 64.9 ± 1.6 | 62.0 | 67.7 | 1.71 ± 0.07 |++#### Whoami over TLS 1.3+| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |+|:---|---:|---:|---:|---:|+| `C++` | 10.0 ± 0.2 | 9.4 | 10.4 | 1.00 |+| `Spectre` | 14.8 ± 0.3 | 14.0 | 15.2 | 1.48 ± 0.04 |++### Notes++- Spectre clone destinations are absolute paths on macOS. The reference checkout hardcodes Linux's `AT_FDCWD` value (`-100`); with a relative destination it cannot open the working directory on macOS.+- `file://` and `ssh://` include server process startup. `clone-tls` and `whoami-tls` use long-running servers, so they isolate protocol and TLS cost more closely.+- These runs reproduce the reference's transfer behavior: fetch `haves` are operation heads (so metadata is re-sent), and push sends all objects reachable from the bookmark rather than using `HAVE_QUERY`.+- Lazy checkout fetches one missing chunk per promisor connection in both implementations, so it is intentionally a worst-case/read-ahead-free measurement.+- `push-file` is only a few milliseconds of real work; process startup noise can dominate. Read the min/max columns alongside the mean.+- Treat differences below roughly 10 ms as noise; this is a single-machine run, not a controlled lab measurement.++### Reproduce++```sh+cd veins-cpprewrite+cmake -S . -B build && cmake --build build -j+./bench/net_bench.sh+```--- /dev/null+++ b/veins-cpprewrite/bench/core_bench.md@@ -0,0 +1,69 @@+Generated 2026-11-27 by `bench/core_bench.py`.++### Environment++| Implementation | Binary |+|:---|:---|+| Rust | `veins-rust v0.1.0 (veins-store 1)` |+| C++ | `veins v0.0.1 (veins-store 1)` |+| Spectre | `veins v0.0.1 (veins-store 1)` |++```+host: Darwin arm64+cpu: Apple M2+repeats: 5 (median reported)+cpu pinning: no+```++### Scope++The Rust binary implements the local-core subset: `init`, `status`, `log`, `go`/`commit`, `co`/`checkout`, `bmk set|ls|rm`, `self-test`, and `version`.+It uses the same FastCDC parameters, BLAKE3 object IDs, zstd level 1, pack/index layout, operation log, and stat-cache invalidation window as the reference.++The subset does not implement merge/conflict objects, rebase/undo, the git bridge, ignore files, or the network protocol. The workload below contains no renames, ignores, merges, or network traffic, so the measured local operations are directly comparable.++### Workload++- Base snapshot: 2.95 MiB, 42 files.+- 20 edit/commit revisions, 8 checkouts, 5 repeats, median reported.+- Each revision rewrites about 1% of a 120,000-line generated C file and three small module files.+- Each `go` performs the same snapshot, describe, and new-empty-change sequence as the reference, including all operation-log writes.+- Store size includes `.veins` packs, indexes, operation heads, the native commit map, and the stat cache.++### Summary++| Metric | Rust | C++ | Spectre | C++ / Rust | Spectre / Rust |+|:---|---:|---:|---:|---:|---:|+| Commit total [s] | 0.252 (0.250-0.262) | 0.280 (0.279-0.291) | 0.310 (0.309-0.330) | 1.11x | 1.23x |+| Checkout total [s] | 0.162 (0.161-0.165) | 0.175 (0.172-0.179) | 0.181 (0.179-0.196) | 1.08x | 1.12x |+| Store size [MiB] | 8.28 (8.28-8.37) | 8.28 (8.28-8.37) | 10.60 (10.60-10.69) | 1.00x | 1.28x |++Each cell is the median with the observed min-max range in parentheses.+A ratio above 1 means the other implementation took longer or used more space than Rust.++### Repeats++| Repeat | Rust commit [s] | C++ commit [s] | Spectre commit [s] | Rust checkout [s] | C++ checkout [s] | Spectre checkout [s] |+|:---|---:|---:|---:|---:|---:|---:|+| 1 | 0.262 | 0.291 | 0.330 | 0.165 | 0.172 | 0.195 |+| 2 | 0.250 | 0.280 | 0.310 | 0.162 | 0.172 | 0.196 |+| 3 | 0.252 | 0.281 | 0.309 | 0.161 | 0.179 | 0.179 |+| 4 | 0.252 | 0.279 | 0.309 | 0.162 | 0.175 | 0.179 |+| 5 | 0.257 | 0.280 | 0.311 | 0.165 | 0.177 | 0.181 |++### Notes++- Both implementations use the same FastCDC parameters, BLAKE3 object IDs, zstd level 1, pack/index layout, operation log, and stat-cache racy window.+- Each `go` performs the same snapshot, describe, and new-empty-change sequence in both implementations, including three operation writes.+- The Rust subset omits ignore-file parsing and similarity-based rename detection. This workload has neither ignore files nor renames, so both implementations see the same file set and perform the same exact-rename scan.+- Rust and C++ store sizes are equal at this resolution; Spectre stores the same logical history with a different packing policy.+- This is a single-machine run. Treat differences below roughly 5% as noise.++### Reproduce++```sh+cd veins-rust+cargo build --release+cd ../veins-cpprewrite+python3 bench/core_bench.py --repeats 5 --markdown-out bench/core_bench.md+```--- /dev/null+++ b/veins-cpprewrite/bench/core_bench.py@@ -0,0 +1,334 @@+#!/usr/bin/env python3++from __future__ import annotations++import argparse+import os+import platform+import random+import re+import shutil+import statistics+import subprocess+import sys+import tempfile+import time+from datetime import datetime, timezone+from pathlib import Path++HEX12 = re.compile(r"\b[0-9a-f]{12}\b")+++def command_prefix() -> list[str]:+ try:+ subprocess.run(+ ["taskset", "-c", "0", "true"],+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ check=True,+ )+ return ["taskset", "-c", "0"]+ except Exception:+ return []+++PREFIX: list[str] = []+++def run(cmd: list[str], cwd: Path) -> str:+ env = os.environ.copy()+ env["LC_ALL"] = "C"+ env["NO_COLOR"] = "1"+ result = subprocess.run(+ [str(part) for part in PREFIX + cmd],+ cwd=str(cwd),+ env=env,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ check=True,+ text=True,+ )+ return result.stdout+++def timed(cmd: list[str], cwd: Path) -> float:+ start = time.perf_counter()+ run(cmd, cwd)+ return time.perf_counter() - start+++def make_base(root: Path, lines: int, small_files: int) -> None:+ root.mkdir(parents=True)+ (root / "generated.c").write_text(+ "".join(f"int value_{i} = {i * 3 + 7};\n" for i in range(lines)),+ encoding="utf-8",+ )+ for i in range(small_files):+ (root / f"module_{i:03d}.c").write_text(+ f"// module {i}\nint module_{i}(void) {{ return {i}; }}\n", encoding="utf-8"+ )+ (root / "sub").mkdir()+ (root / "sub" / "nested.txt").write_text("nested\n" * 200, encoding="utf-8")+++def mutate(root: Path, revision: int) -> None:+ path = root / "generated.c"+ lines = path.read_text(encoding="utf-8").splitlines(keepends=True)+ rng = random.Random(revision)+ for _ in range(max(1, len(lines) // 100)):+ index = rng.randrange(len(lines))+ lines[index] = f"int changed_{revision}_{index} = {revision};\n"+ path.write_text("".join(lines), encoding="utf-8")+ for i in range(3):+ (root / f"module_{i:03d}.c").write_text(+ f"// module {i}, revision {revision}\n"+ f"int module_{i}(void) {{ return {revision * 1000 + i}; }}\n",+ encoding="utf-8",+ )+++def tree_bytes(root: Path) -> int:+ return sum(path.stat().st_size for path in root.rglob("*") if path.is_file())+++def bench_one(+ binary: Path, work: Path, label: str, revisions: int, checkouts: int+) -> tuple[float, float, int]:+ repo = work / label+ shutil.copytree(work / "base", repo)+ run([str(binary), "init"], repo)+ (repo / ".veins" / "config").write_text(+ "user.name = Bench\nuser.email = bench@example.com\n", encoding="utf-8"+ )+ mutate(repo, 0)+ run([str(binary), "go", "-m", "warmup"], repo)++ commit_time = 0.0+ for revision in range(1, revisions + 1):+ mutate(repo, revision)+ commit_time += timed([str(binary), "go", "-m", f"revision {revision}"], repo)++ log_lines = run([str(binary), "log", "-no-col-titles"], repo).splitlines()+ ids = [match.group(0) for line in log_lines if (match := HEX12.search(line))]+ targets = ids[: max(1, checkouts)]+ checkout_time = 0.0+ for i in range(checkouts):+ target = targets[min(i, len(targets) - 1)]+ checkout_time += timed([str(binary), "co", target], repo)+ return commit_time, checkout_time, tree_bytes(repo / ".veins")+++def environment(binary: Path) -> str:+ try:+ return run([str(binary), "version"], Path.cwd()).strip()+ except Exception:+ return "unknown"+++def cpu_name() -> str:+ try:+ return subprocess.run(+ ["sysctl", "-n", "machdep.cpu.brand_string"],+ stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL,+ check=True,+ text=True,+ ).stdout.strip()+ except Exception:+ return platform.processor() or platform.machine()+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ root = Path(__file__).resolve().parents[2]+ parser.add_argument("--spectre", type=Path, default=root / "veins" / "vn")+ parser.add_argument("--cpp", type=Path, default=root / "veins-cpprewrite" / "build" / "vn")+ parser.add_argument(+ "--rust", type=Path, default=root / "veins-rust" / "target" / "release" / "vn"+ )+ parser.add_argument("--revisions", type=int, default=20)+ parser.add_argument("--checkouts", type=int, default=8)+ parser.add_argument("--repeats", type=int, default=3)+ parser.add_argument("--large-lines", type=int, default=120000)+ parser.add_argument("--small-files", type=int, default=40)+ parser.add_argument("--no-pin", action="store_true")+ parser.add_argument("--markdown-out", type=Path)+ args = parser.parse_args()++ global PREFIX+ PREFIX = [] if args.no_pin else command_prefix()++ binaries = {+ "rust": args.rust,+ "cpp": args.cpp,+ "spectre": args.spectre,+ }+ for label, binary in binaries.items():+ if not binary.exists():+ print(f"missing {label} binary: {binary}", file=sys.stderr)+ return 2++ work = Path(tempfile.mkdtemp(prefix="veins-core-bench-"))+ try:+ make_base(work / "base", args.large_lines, args.small_files)+ size = tree_bytes(work / "base")+ print(+ f"workload: {size / (1024 * 1024):.2f} MiB, "+ f"{args.revisions} revisions, {args.checkouts} checkouts, "+ f"{args.repeats} repeats, cpu pinning={'yes' if PREFIX else 'no'}"+ )+ rows: dict[str, list[tuple[float, float, int]]] = {+ "rust": [],+ "cpp": [],+ "spectre": [],+ }+ for repeat in range(args.repeats):+ print(f"repeat {repeat + 1}/{args.repeats}")+ for label, binary in binaries.items():+ commit, checkout, store = bench_one(+ binary, work, f"{label}-{repeat}", args.revisions, args.checkouts+ )+ rows[label].append((commit, checkout, store))+ print(+ f" {label}: commit {commit:.3f}s checkout {checkout:.3f}s "+ f"store {store / (1024 * 1024):.2f} MiB"+ )++ def median(label: str, index: int) -> float:+ return statistics.median(row[index] for row in rows[label])++ def spread(label: str, index: int) -> str:+ values = [row[index] for row in rows[label]]+ return f"{statistics.median(values):.3f} ({min(values):.3f}-{max(values):.3f})"++ def spread_mib(label: str) -> str:+ values = [row[2] / (1024 * 1024) for row in rows[label]]+ return f"{statistics.median(values):.2f} ({min(values):.2f}-{max(values):.2f})"++ values = {+ label: (median(label, 0), median(label, 1), median(label, 2))+ for label in rows+ }+ rust_commit, rust_checkout, rust_store = values["rust"]+ cpp_commit, cpp_checkout, cpp_store = values["cpp"]+ sx_commit, sx_checkout, sx_store = values["spectre"]++ print()+ print(f"commit C++/Rust: {cpp_commit / rust_commit:.2f}x")+ print(f"commit Spectre/Rust: {sx_commit / rust_commit:.2f}x")+ print(f"checkout C++/Rust: {cpp_checkout / rust_checkout:.2f}x")+ print(f"checkout Spectre/Rust: {sx_checkout / rust_checkout:.2f}x")+ print(f"store C++/Rust: {cpp_store / rust_store:.2f}x")+ print(f"store Spectre/Rust: {sx_store / rust_store:.2f}x")++ if args.markdown_out:+ lines = [+ f"Generated {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')} by `bench/core_bench.py`.",+ "",+ "### Environment",+ "",+ "| Implementation | Binary |",+ "|:---|:---|",+ f"| Rust | `{environment(args.rust)}` |",+ f"| C++ | `{environment(args.cpp)}` |",+ f"| Spectre | `{environment(args.spectre)}` |",+ "",+ "```",+ f"host: {platform.system()} {platform.machine()}",+ f"cpu: {cpu_name()}",+ f"repeats: {args.repeats} (median reported)",+ f"cpu pinning: {'yes' if PREFIX else 'no'}",+ "```",+ "",+ "### Scope",+ "",+ "The Rust binary implements the local-core subset: `init`, `status`, `log`, "+ "`go`/`commit`, `co`/`checkout`, `bmk set|ls|rm`, `self-test`, and `version`.",+ "It uses the same FastCDC parameters, BLAKE3 object IDs, zstd level 1, "+ "pack/index layout, operation log, and stat-cache invalidation window as "+ "the reference.",+ "",+ "The subset does not implement merge/conflict objects, rebase/undo, the git "+ "bridge, ignore files, or the network protocol. The workload below contains "+ "no renames, ignores, merges, or network traffic, so the measured local "+ "operations are directly comparable.",+ "",+ "### Workload",+ "",+ f"- Base snapshot: {size / (1024 * 1024):.2f} MiB, "+ f"{args.small_files + 2} files.",+ f"- {args.revisions} edit/commit revisions, {args.checkouts} checkouts, "+ f"{args.repeats} repeats, median reported.",+ "- Each revision rewrites about 1% of a 120,000-line generated C file "+ "and three small module files.",+ "- Each `go` performs the same snapshot, describe, and new-empty-change "+ "sequence as the reference, including all operation-log writes.",+ "- Store size includes `.veins` packs, indexes, operation heads, the native "+ "commit map, and the stat cache.",+ "",+ "### Summary",+ "",+ "| Metric | Rust | C++ | Spectre | C++ / Rust | Spectre / Rust |",+ "|:---|---:|---:|---:|---:|---:|",+ f"| Commit total [s] | {spread('rust', 0)} | {spread('cpp', 0)} | "+ f"{spread('spectre', 0)} | {cpp_commit / rust_commit:.2f}x | "+ f"{sx_commit / rust_commit:.2f}x |",+ f"| Checkout total [s] | {spread('rust', 1)} | {spread('cpp', 1)} | "+ f"{spread('spectre', 1)} | {cpp_checkout / rust_checkout:.2f}x | "+ f"{sx_checkout / rust_checkout:.2f}x |",+ f"| Store size [MiB] | {spread_mib('rust')} | {spread_mib('cpp')} | "+ f"{spread_mib('spectre')} | {cpp_store / rust_store:.2f}x | "+ f"{sx_store / rust_store:.2f}x |",+ "",+ "Each cell is the median with the observed min-max range in parentheses.",+ "A ratio above 1 means the other implementation took longer or used "+ "more space than Rust.",+ "",+ "### Repeats",+ "",+ "| Repeat | Rust commit [s] | C++ commit [s] | Spectre commit [s] | "+ "Rust checkout [s] | C++ checkout [s] | Spectre checkout [s] |",+ "|:---|---:|---:|---:|---:|---:|---:|",+ ]+ for index in range(args.repeats):+ lines.append(+ f"| {index + 1} | {rows['rust'][index][0]:.3f} | "+ f"{rows['cpp'][index][0]:.3f} | {rows['spectre'][index][0]:.3f} | "+ f"{rows['rust'][index][1]:.3f} | {rows['cpp'][index][1]:.3f} | "+ f"{rows['spectre'][index][1]:.3f} |"+ )+ lines.extend(+ [+ "",+ "### Notes",+ "",+ "- Both implementations use the same FastCDC parameters, BLAKE3 object IDs, "+ "zstd level 1, pack/index layout, operation log, and stat-cache racy window.",+ "- Each `go` performs the same snapshot, describe, and new-empty-change "+ "sequence in both implementations, including three operation writes.",+ "- The Rust subset omits ignore-file parsing and similarity-based rename "+ "detection. This workload has neither ignore files nor renames, so both "+ "implementations see the same file set and perform the same exact-rename scan.",+ "- Rust and C++ store sizes are equal at this resolution; Spectre stores the "+ "same logical history with a different packing policy.",+ "- This is a single-machine run. Treat differences below roughly 5% as noise.",+ "",+ "### Reproduce",+ "",+ "```sh",+ "cd veins-rust",+ "cargo build --release",+ "cd ../veins-cpprewrite",+ "python3 bench/core_bench.py --repeats 5 --markdown-out bench/core_bench.md",+ "```",+ "",+ ]+ )+ args.markdown_out.write_text("\n".join(lines), encoding="utf-8")+ return 0+ finally:+ shutil.rmtree(work, ignore_errors=True)+++if __name__ == "__main__":+ raise SystemExit(main())--- /dev/null+++ b/veins-cpprewrite/bench/net_bench.sh@@ -0,0 +1,510 @@+#!/bin/sh+# Compare the C++ rewrite with the Spectre reference over the native protocol.+#+# Requirements: hyperfine, python3, openssl, a built C++ vn, and the Spectre vn+# in ../veins/vn. The script creates a throwaway dataset under bench/.net-bench,+# runs hyperfine, and writes BENCHES.md.+set -eu++SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)+ROOT=$(CDPATH= cd -- "$SCRIPT_DIR/.." && pwd)+REPO=$(CDPATH= cd -- "$ROOT/.." && pwd)++VN_CPP=${VN_CPP:-$ROOT/build/vn}+VN_SPECTRE=${VN_SPECTRE:-$REPO/veins/vn}+HYPERFINE=${HYPERFINE:-hyperfine}+WORK=${WORK:-$ROOT/bench/.net-bench}+OUT=${OUT:-$ROOT/BENCHES.md}+RUNS=${RUNS:-10}+WHOAMI_RUNS=${WHOAMI_RUNS:-20}++SYS_PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"++case "$WORK" in+ ""|"/"|".") echo "refusing to use WORK='$WORK'" >&2; exit 1 ;;+esac++CPP_DIR=$(CDPATH= cd -- "$(dirname -- "$VN_CPP")" && pwd)+SX_DIR=$(CDPATH= cd -- "$(dirname -- "$VN_SPECTRE")" && pwd)+VN_CPP="$CPP_DIR/$(basename -- "$VN_CPP")"+VN_SPECTRE="$SX_DIR/$(basename -- "$VN_SPECTRE")"++for tool in "$VN_CPP" "$VN_SPECTRE"; do+ if [ ! -x "$tool" ]; then+ echo "missing executable: $tool" >&2+ echo "build the C++ rewrite first: cmake --build $ROOT/build" >&2+ exit 1+ fi+done+for tool in "$HYPERFINE" python3 openssl; do+ if ! command -v "$tool" >/dev/null 2>&1; then+ echo "required tool not found: $tool" >&2+ exit 1+ fi+done++rm -rf "$WORK"+mkdir -p "$WORK/config" "$WORK/bench_src" "$WORK/push_pristine" "$WORK/fakebin"++XDG_CONFIG_HOME="$WORK/config"+export XDG_CONFIG_HOME++CPP_RUN="env XDG_CONFIG_HOME='$XDG_CONFIG_HOME' PATH='$CPP_DIR:$SYS_PATH' '$VN_CPP'"+SX_RUN="env XDG_CONFIG_HOME='$XDG_CONFIG_HOME' PATH='$SX_DIR:$SYS_PATH' '$VN_SPECTRE'"+CPP_SSH_RUN="env XDG_CONFIG_HOME='$XDG_CONFIG_HOME' PATH='$WORK/fakebin:$CPP_DIR:$SYS_PATH' '$VN_CPP'"+SX_SSH_RUN="env XDG_CONFIG_HOME='$XDG_CONFIG_HOME' PATH='$WORK/fakebin:$SX_DIR:$SYS_PATH' '$VN_SPECTRE'"++run_cpp() {+ env XDG_CONFIG_HOME="$XDG_CONFIG_HOME" PATH="$CPP_DIR:$SYS_PATH" "$VN_CPP" "$@"+}+run_sx() {+ env XDG_CONFIG_HOME="$XDG_CONFIG_HOME" PATH="$SX_DIR:$SYS_PATH" "$VN_SPECTRE" "$@"+}++wait_port() {+ python3 - "$1" <<'PY'+import socket, sys, time+port = int(sys.argv[1])+for _ in range(100):+ sock = socket.socket()+ sock.settimeout(0.1)+ try:+ sock.connect(("127.0.0.1", port))+ sock.close()+ sys.exit(0)+ except OSError:+ sock.close()+ time.sleep(0.1)+sys.exit(1)+PY+}++generate_small_files() {+ python3 - "$1" "$2" "$3" <<'PY'+import os, sys+root, start, stop = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])+body = ("abcdefghijklmnopqrstuvwxyz" * 70)[:1800]+for d in range(start, stop):+ folder = os.path.join(root, "d%02d" % d)+ os.makedirs(folder, exist_ok=True)+ for f in range(20):+ path = os.path.join(folder, "f%02d.txt" % f)+ with open(path, "w", encoding="utf-8") as handle:+ handle.write("file %d-%d\n" % (d, f))+ handle.write(body)+ handle.write("\n")+PY+}++# ---------------------------------------------------------------------------+# Keys and access+# ---------------------------------------------------------------------------++run_cpp key generate benchkey > "$WORK/key.txt"+PUB=$(awk '/public key:/ {print $3}' "$WORK/key.txt")+if [ -z "$PUB" ]; then+ echo "could not generate the benchmark key" >&2+ exit 1+fi+run_cpp auth use benchkey >/dev/null++grant_access() {+ ( cd "$1" && run_cpp access anonymous on && \+ run_cpp access add -role write -key "$PUB" -name bench >/dev/null )+}++# ---------------------------------------------------------------------------+# Dataset: 360 small files, a 2 MiB old blob, and a 1 MiB head blob.+# ---------------------------------------------------------------------------++(+ cd "$WORK/bench_src"+ run_sx init . >/dev/null+ generate_small_files . 0 12+ python3 - <<'PY'+import os+with open("big_old.bin", "wb") as handle:+ handle.write(os.urandom(2 * 1024 * 1024))+PY+ run_sx go -m "base commit" >/dev/null+ # Point oldbig at the real base commit, not the movable working-copy commit.+ BASE_CHANGE=$(run_sx log | awk '/base commit/ {print $2}' | tail -1)+ if [ -z "$BASE_CHANGE" ]; then+ echo "could not resolve the base commit" >&2+ exit 1+ fi+ run_sx bmk set oldbig -rev "$BASE_CHANGE" >/dev/null+ rm -f big_old.bin+ generate_small_files . 12 18+ python3 - <<'PY'+import os+with open("big_head.bin", "wb") as handle:+ handle.write(os.urandom(1 * 1024 * 1024))+PY+ run_sx go -m "head commit" >/dev/null+ run_sx bmk set main >/dev/null+)+grant_access "$WORK/bench_src"++# A separate small repository for push, so a push does not transfer the large+# dataset. The reference pushes all reachable objects, as does the rewrite.+(+ cd "$WORK/push_pristine"+ run_sx init . >/dev/null+ generate_small_files . 0 1+ run_sx go -m "push base" >/dev/null+ run_sx bmk set main >/dev/null+)+grant_access "$WORK/push_pristine"++# ---------------------------------------------------------------------------+# Prepared client/server repositories+# ---------------------------------------------------------------------------++run_cpp clone "file://$WORK/bench_src" "$WORK/fetch_pristine_cpp" -blobs:all >/dev/null+run_sx clone "file://$WORK/bench_src" "$WORK/fetch_pristine_sx" -blobs:all >/dev/null+run_cpp clone "file://$WORK/bench_src" "$WORK/lazy_pristine_cpp" -blobs:none >/dev/null+run_sx clone "file://$WORK/bench_src" "$WORK/lazy_pristine_sx" -blobs:none >/dev/null++run_cpp clone "file://$WORK/push_pristine" "$WORK/push_client_cpp" >/dev/null+run_sx clone "file://$WORK/push_pristine" "$WORK/push_client_sx" >/dev/null+(+ cd "$WORK/push_client_cpp"+ printf 'bench push\n' > push.txt+ run_cpp go -m "bench push" >/dev/null+ run_cpp bmk set main >/dev/null+ run_cpp remote set-url origin "file://$WORK/push_srv_cpp"+)+(+ cd "$WORK/push_client_sx"+ printf 'bench push\n' > push.txt+ run_sx go -m "bench push" >/dev/null+ run_sx bmk set main >/dev/null+ run_sx remote set-url origin "file://$WORK/push_srv_sx"+)++# ---------------------------------------------------------------------------+# ssh shim: execute the remote `vn serve -stdio ...` command locally.+# ---------------------------------------------------------------------------++cat > "$WORK/fakebin/ssh" <<'SH'+#!/bin/sh+while [ $# -gt 0 ]; do+ case "$1" in+ -p|-l) shift 2 ;;+ -*) shift ;;+ *) break ;;+ esac+done+host=$1+shift+exec /bin/sh -c "$*"+SH+chmod +x "$WORK/fakebin/ssh"++# ---------------------------------------------------------------------------+# TLS certificate and servers+# ---------------------------------------------------------------------------++cat > "$WORK/openssl.cnf" <<EOF+[req]+distinguished_name = dn+x509_extensions = v3_req+prompt = no+[dn]+CN = localhost+[v3_req]+subjectAltName = @alt+[alt]+DNS.1 = localhost+IP.1 = 127.0.0.1+EOF+openssl req -x509 -newkey rsa:2048 -nodes \+ -keyout "$WORK/key.pem" -out "$WORK/cert.pem" \+ -days 2 -config "$WORK/openssl.cnf" >/dev/null 2>&1+PIN=$(openssl x509 -in "$WORK/cert.pem" -noout -fingerprint -sha256 \+ | sed 's/.*=//;s/://g' | tr 'A-F' 'a-f')++free_port() {+ python3 - <<'PY'+import socket+sock = socket.socket()+sock.bind(("127.0.0.1", 0))+print(sock.getsockname()[1])+sock.close()+PY+}+PORT_CPP=$(free_port)+PORT_SX=$(free_port)+while [ "$PORT_SX" = "$PORT_CPP" ]; do PORT_SX=$(free_port); done++CPP_PID=""+SX_PID=""+cleanup() {+ if [ -n "$CPP_PID" ]; then kill "$CPP_PID" 2>/dev/null || true; fi+ if [ -n "$SX_PID" ]; then kill "$SX_PID" 2>/dev/null || true; fi+ if [ -n "$CPP_PID" ]; then wait "$CPP_PID" 2>/dev/null || true; fi+ if [ -n "$SX_PID" ]; then wait "$SX_PID" 2>/dev/null || true; fi+}+trap cleanup EXIT INT TERM++"$VN_CPP" serve -listen "127.0.0.1:$PORT_CPP" -root "$WORK" \+ -tls-cert "$WORK/cert.pem" -tls-key "$WORK/key.pem" \+ >"$WORK/cpp-server.log" 2>&1 &+CPP_PID=$!+"$VN_SPECTRE" serve -listen "127.0.0.1:$PORT_SX" -root "$WORK" \+ -tls-cert "$WORK/cert.pem" -tls-key "$WORK/key.pem" \+ >"$WORK/sx-server.log" 2>&1 &+SX_PID=$!+wait_port "$PORT_CPP"+wait_port "$PORT_SX"++# A tiny repository used only for whoami over TLS.+mkdir -p "$WORK/whoami_repo"+(+ cd "$WORK/whoami_repo"+ run_cpp init . >/dev/null+ run_cpp remote add tls_cpp "veins://localhost:$PORT_CPP/bench_src" \+ -key:benchkey -tls-pin:"$PIN" >/dev/null+ run_cpp remote add tls_sx "veins://localhost:$PORT_SX/bench_src" \+ -key:benchkey -tls-pin:"$PIN" >/dev/null+)++# ---------------------------------------------------------------------------+# Hyperfine prepare scripts+# ---------------------------------------------------------------------------++write_prepare() {+ path="$WORK/$1"+ shift+ {+ echo '#!/bin/sh'+ printf '%s\n' "$@"+ } > "$path"+ chmod +x "$path"+}++write_prepare prepare_clone.sh \+ "rm -rf '$WORK/clone_cpp' '$WORK/clone_sx'"+write_prepare prepare_fetch.sh \+ "rm -rf '$WORK/fetch_cpp' '$WORK/fetch_sx'" \+ "cp -R '$WORK/fetch_pristine_cpp' '$WORK/fetch_cpp'" \+ "cp -R '$WORK/fetch_pristine_sx' '$WORK/fetch_sx'"+write_prepare prepare_lazy.sh \+ "rm -rf '$WORK/lazy_cpp' '$WORK/lazy_sx'" \+ "cp -R '$WORK/lazy_pristine_cpp' '$WORK/lazy_cpp'" \+ "cp -R '$WORK/lazy_pristine_sx' '$WORK/lazy_sx'"+write_prepare prepare_push.sh \+ "rm -rf '$WORK/push_srv_cpp' '$WORK/push_srv_sx'" \+ "cp -R '$WORK/push_pristine' '$WORK/push_srv_cpp'" \+ "cp -R '$WORK/push_pristine' '$WORK/push_srv_sx'"+write_prepare prepare_ssh.sh \+ "rm -rf '$WORK/clone_ssh_cpp' '$WORK/clone_ssh_sx'"+write_prepare prepare_tls.sh \+ "rm -rf '$WORK/clone_tls_cpp' '$WORK/clone_tls_sx'"+write_prepare prepare_noop.sh \+ "exit 0"++# ---------------------------------------------------------------------------+# Run hyperfine+# ---------------------------------------------------------------------------++run_pair() {+ name=$1+ prepare=$2+ runs=$3+ warmup=$4+ cpp_cmd=$5+ sx_cmd=$6+ echo+ echo "== $name =="+ "$HYPERFINE" --style basic --warmup "$warmup" --runs "$runs" \+ --prepare "$prepare" \+ --export-markdown "$WORK/$name.md" \+ --export-json "$WORK/$name.json" \+ -n "C++" "$cpp_cmd" \+ -n "Spectre" "$sx_cmd"+}++SSH_URL="ssh://localhost/$WORK/bench_src"+TLS_CPP_URL="veins://localhost:$PORT_CPP/bench_src"+TLS_SX_URL="veins://localhost:$PORT_SX/bench_src"++run_pair clone-file "$WORK/prepare_clone.sh" "$RUNS" 1 \+ "cd '$WORK' && $CPP_RUN clone 'file://$WORK/bench_src' '$WORK/clone_cpp'" \+ "cd '$WORK' && $SX_RUN clone 'file://$WORK/bench_src' '$WORK/clone_sx'"++run_pair fetch-file "$WORK/prepare_fetch.sh" "$RUNS" 1 \+ "cd '$WORK/fetch_cpp' && $CPP_RUN fetch origin" \+ "cd '$WORK/fetch_sx' && $SX_RUN fetch origin"++run_pair lazy-checkout-file "$WORK/prepare_lazy.sh" "$RUNS" 1 \+ "cd '$WORK/lazy_cpp' && $CPP_RUN co oldbig" \+ "cd '$WORK/lazy_sx' && $SX_RUN co oldbig"++run_pair push-file "$WORK/prepare_push.sh" "$RUNS" 1 \+ "cd '$WORK/push_client_cpp' && $CPP_RUN push origin main" \+ "cd '$WORK/push_client_sx' && $SX_RUN push origin main"++run_pair whoami-file "$WORK/prepare_noop.sh" "$WHOAMI_RUNS" 2 \+ "cd '$WORK' && $CPP_RUN whoami 'file://$WORK/bench_src'" \+ "cd '$WORK' && $SX_RUN whoami 'file://$WORK/bench_src'"++run_pair clone-ssh "$WORK/prepare_ssh.sh" "$RUNS" 1 \+ "cd '$WORK' && $CPP_SSH_RUN clone '$SSH_URL' '$WORK/clone_ssh_cpp'" \+ "cd '$WORK' && $SX_SSH_RUN clone '$SSH_URL' '$WORK/clone_ssh_sx'"++run_pair clone-tls "$WORK/prepare_tls.sh" "$RUNS" 1 \+ "cd '$WORK' && $CPP_RUN clone '$TLS_CPP_URL' '$WORK/clone_tls_cpp' -pin:'$PIN'" \+ "cd '$WORK' && $SX_RUN clone '$TLS_SX_URL' '$WORK/clone_tls_sx' -pin:'$PIN'"++run_pair whoami-tls "$WORK/prepare_noop.sh" "$WHOAMI_RUNS" 2 \+ "cd '$WORK/whoami_repo' && $CPP_RUN whoami tls_cpp" \+ "cd '$WORK/whoami_repo' && $SX_RUN whoami tls_sx"++cleanup+trap - 0 2 15++# ---------------------------------------------------------------------------+# BENCHES.md+# ---------------------------------------------------------------------------++python3 - "$WORK" > "$WORK/summary.md" <<'PY'+import json, os, sys+work = sys.argv[1]+names = [+ ("clone-file", "Clone file://"),+ ("fetch-file", "Fetch file://"),+ ("lazy-checkout-file", "Lazy checkout file://"),+ ("push-file", "Push file://"),+ ("whoami-file", "Whoami file://"),+ ("clone-ssh", "Clone ssh://"),+ ("clone-tls", "Clone TLS 1.3"),+ ("whoami-tls", "Whoami TLS 1.3"),+]+print("| Benchmark | C++ mean | Spectre mean | Spectre / C++ |")+print("|:---|---:|---:|---:|")+for key, label in names:+ with open(os.path.join(work, key + ".json"), encoding="utf-8") as handle:+ data = json.load(handle)+ means = {r["command"]: r["mean"] for r in data["results"]}+ cpp = means["C++"] * 1000.0+ sx = means["Spectre"] * 1000.0+ ratio = sx / cpp if cpp else float("nan")+ print(f"| {label} | {cpp:.1f} ms | {sx:.1f} ms | {ratio:.2f}x |")+PY++FILE_COUNT=$(find "$WORK/bench_src" -type f -not -path '*/.veins/*' | wc -l | tr -d ' ')+DISK_SIZE=$(du -sh "$WORK/bench_src" | awk '{print $1}')+HOST_TEXT=$(uname -sm)+CPU_TEXT=$(sysctl -n machdep.cpu.brand_string 2>/dev/null || uname -m)+HYPERFINE_VERSION=$("$HYPERFINE" --version)+CPP_VERSION=$("$VN_CPP" version)+SX_VERSION=$("$VN_SPECTRE" version)++{+ echo "# veins benchmarks"+ echo+ echo "Two reproducible benchmark sets are kept here: a local-core comparison that includes"+ echo "the Rust subset, and the native network comparison between the C++ rewrite and Spectre."+ echo+ if [ -f "$ROOT/bench/core_bench.md" ]; then+ echo "## Local core: Rust subset vs C++ vs Spectre"+ echo+ cat "$ROOT/bench/core_bench.md"+ echo+ fi+ echo "## Networking: C++ rewrite vs Spectre"+ echo+ echo "Generated $(date -u '+%Y-%m-%d %H:%M:%S UTC') by \`bench/net_bench.sh\`."+ echo+ echo "The Rust subset is not included in this section because it does not implement a"+ echo "network transport."+ echo+ echo "### Environment"+ echo+ echo '```'+ echo "host: $HOST_TEXT"+ echo "cpu: $CPU_TEXT"+ echo "hyperfine: $HYPERFINE_VERSION"+ echo "c++ vn: $CPP_VERSION"+ echo "spectre vn: $SX_VERSION"+ echo "runs: $RUNS (clone/fetch/push/checkout), $WHOAMI_RUNS (whoami)"+ echo "warmup: 1 (clone/fetch/push/checkout), 2 (whoami)"+ echo '```'+ echo+ echo "### Dataset"+ echo+ echo "- \`bench_src\`: $FILE_COUNT working files, $DISK_SIZE on disk including packs."+ echo " - 360 small text files in 18 directories."+ echo " - 2 MiB \`big_old.bin\` in the \`oldbig\` history."+ echo " - 1 MiB \`big_head.bin\` in \`main\`."+ echo "- \`push_pristine\`: a separate 20-file repository, so push does not transfer the large dataset."+ echo+ echo "### What each benchmark does"+ echo+ echo "| Benchmark | Operation |"+ echo "|:---|:---|"+ echo "| \`clone-file\` | Full clone over \`file://\`: handshake, refs, history, head chunks, checkout. Includes spawning one local server per run. |"+ echo "| \`fetch-file\` | \`vn fetch origin\` with no new remote refs. Both clients start from a full \`-blobs:all\` clone. |"+ echo "| \`lazy-checkout-file\` | \`vn co oldbig\` in a \`-blobs:none\` clone, fetching the 2 MiB old blob from the promisor over \`file://\`. |"+ echo "| \`push-file\` | Push one new commit from a prepared client to a freshly reset copy of \`push_pristine\` over \`file://\`. |"+ echo "| \`whoami-file\` | Connect, authenticate, \`WHOAMI\`, close over \`file://\`. |"+ echo "| \`clone-ssh\` | Full clone over \`ssh://\`, using a local \`ssh\` shim that runs the remote \`vn serve -stdio\` command. |"+ echo "| \`clone-tls\` | Full clone over TLS 1.3 with a pinned self-signed certificate. Uses long-running servers. |"+ echo "| \`whoami-tls\` | Connect, authenticate, \`WHOAMI\`, close over TLS 1.3. |"+ echo+ echo "Lower is better. Hyperfine reports wall-clock time; the relative column is against the fastest command."+ echo+ echo "### Summary"+ echo+ cat "$WORK/summary.md"+ echo+ echo "A ratio above 1 means Spectre took longer than C++."+ echo+ echo "### Results"+ echo+ echo "#### Clone over file://"+ cat "$WORK/clone-file.md"+ echo+ echo "#### Fetch over file://"+ cat "$WORK/fetch-file.md"+ echo+ echo "#### Lazy checkout over file://"+ cat "$WORK/lazy-checkout-file.md"+ echo+ echo "#### Push over file://"+ cat "$WORK/push-file.md"+ echo+ echo "#### Whoami over file://"+ cat "$WORK/whoami-file.md"+ echo+ echo "#### Clone over ssh://"+ cat "$WORK/clone-ssh.md"+ echo+ echo "#### Clone over TLS 1.3"+ cat "$WORK/clone-tls.md"+ echo+ echo "#### Whoami over TLS 1.3"+ cat "$WORK/whoami-tls.md"+ echo+ echo "### Notes"+ echo+ echo "- Spectre clone destinations are absolute paths on macOS. The reference checkout hardcodes Linux's \`AT_FDCWD\` value (\`-100\`); with a relative destination it cannot open the working directory on macOS."+ echo "- \`file://\` and \`ssh://\` include server process startup. \`clone-tls\` and \`whoami-tls\` use long-running servers, so they isolate protocol and TLS cost more closely."+ echo "- These runs reproduce the reference's transfer behavior: fetch \`haves\` are operation heads (so metadata is re-sent), and push sends all objects reachable from the bookmark rather than using \`HAVE_QUERY\`."+ echo "- Lazy checkout fetches one missing chunk per promisor connection in both implementations, so it is intentionally a worst-case/read-ahead-free measurement."+ echo "- \`push-file\` is only a few milliseconds of real work; process startup noise can dominate. Read the min/max columns alongside the mean."+ echo "- Treat differences below roughly 10 ms as noise; this is a single-machine run, not a controlled lab measurement."+ echo+ echo "### Reproduce"+ echo+ echo '```sh'+ echo "cd veins-cpprewrite"+ echo "cmake -S . -B build && cmake --build build -j"+ echo "./bench/net_bench.sh"+ echo '```'+} > "$OUT"++echo+echo "wrote $OUT"--- /dev/null+++ b/veins-rust/.gitignore@@ -0,0 +1,1 @@+/target/--- /dev/null+++ b/veins-rust/Cargo.lock@@ -0,0 +1,204 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "arrayvec"+version = "0.7.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"++[[package]]+name = "blake3"+version = "1.8.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "64c0e36294adc8db531500e3f2b8ec75c4af9177271e9c6d33f93609d56e57cd"+dependencies = [+ "arrayvec",+ "cc",+ "cfg-if",+ "constant_time_eq",+ "cpufeatures",+]++[[package]]+name = "cc"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66"+dependencies = [+ "find-msvc-tools",+ "jobserver",+ "libc",+ "shlex",+]++[[package]]+name = "cfg-if"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"++[[package]]+name = "constant_time_eq"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7"+dependencies = [+ "rustversion",+]++[[package]]+name = "cpufeatures"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"+dependencies = [+ "libc",+]++[[package]]+name = "crossbeam-deque"+version = "0.8.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"+dependencies = [+ "crossbeam-epoch",+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-epoch"+version = "0.9.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-utils"+version = "0.8.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"++[[package]]+name = "either"+version = "1.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"++[[package]]+name = "find-msvc-tools"+version = "0.1.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8"++[[package]]+name = "getrandom"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi",+]++[[package]]+name = "jobserver"+version = "0.1.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"+dependencies = [+ "getrandom",+ "libc",+]++[[package]]+name = "libc"+version = "0.2.191"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"++[[package]]+name = "pkg-config"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"++[[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"++[[package]]+name = "rayon"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"+dependencies = [+ "either",+ "rayon-core",+]++[[package]]+name = "rayon-core"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"+dependencies = [+ "crossbeam-deque",+ "crossbeam-utils",+]++[[package]]+name = "rustversion"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "veins-rust"+version = "0.1.0"+dependencies = [+ "blake3",+ "libc",+ "rayon",+ "zstd",+]++[[package]]+name = "zstd"+version = "0.13.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b04655dc7bf4abd8ebe23dac6bef20fceea52a29ad19e37a4101b3951d7e8b45"+dependencies = [+ "zstd-safe",+]++[[package]]+name = "zstd-safe"+version = "7.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df2575690b2a3eccad509fe7898cdde32a5afca06a06449ff4dcfb318c7b7281"+dependencies = [+ "zstd-sys",+]++[[package]]+name = "zstd-sys"+version = "2.2.0+zstd.1.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3f4089cda6dda4dc43c43dd9f8964140064fd2f752f3da46c3a483c3c175160"+dependencies = [+ "cc",+ "pkg-config",+]--- /dev/null+++ b/veins-rust/Cargo.toml@@ -0,0 +1,20 @@+[package]+name = "veins-rust"+version = "0.1.0"+edition = "2024"+license = "MIT"++[[bin]]+name = "vn"+path = "src/main.rs"++[dependencies]+blake3 = "1.8"+libc = "0.2"+rayon = "1.12"+zstd = "0.13"++[profile.release]+opt-level = 3+lto = false+codegen-units = 16--- /dev/null+++ b/veins-rust/src/cli/args.rs@@ -0,0 +1,40 @@+use crate::error::{Error, Result};++pub fn is_flag(argument: &str) -> bool {+ argument.starts_with('-') && argument != "-"+}++pub fn join(parts: &[String]) -> String {+ parts.join(" ")+}++pub fn message_is_blank(parts: &[String]) -> bool {+ parts+ .iter()+ .flat_map(|part| part.bytes())+ .all(|byte| matches!(byte, b' ' | b'\t' | b'\n' | b'\r'))+}++pub fn parse_message(args: &[String], start: usize) -> Result<Vec<String>> {+ let mut parts = Vec::new();+ let mut end_flags = false;+ let mut index = start;+ while index < args.len() {+ let argument = &args[index];+ if !end_flags && argument == "--" {+ end_flags = true;+ } else if !end_flags && (argument == "-m" || argument == "-message") {+ index += 1;+ if index >= args.len() {+ return Err(Error::new(format!("{argument} requires a message")));+ }+ parts.push(args[index].clone());+ } else if !end_flags && is_flag(argument) {+ return Err(Error::new(format!("unknown flag: {argument}")));+ } else {+ parts.push(argument.clone());+ }+ index += 1;+ }+ Ok(parts)+}--- /dev/null+++ b/veins-rust/src/cli/commands/bookmark.rs@@ -0,0 +1,221 @@+use std::path::Path;++use crate::cli::args;+use crate::error::{Error, Result};+use crate::object::view::Bookmark;+use crate::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::store::Txn;+use crate::worktree::snapshot;++pub fn run(arguments: &[String]) -> Result<u8> {+ let Some(subcommand) = arguments.first() else {+ return Err(Error::new("bmk requires a subcommand"));+ };+ let rest = &arguments[1..];+ match subcommand.as_str() {+ "set" | "mv" => set(rest),+ "ls" => list(rest),+ "rm" => remove(rest),+ _ => Err(Error::new(format!("unknown bmk subcommand: {subcommand}"))),+ }+}++fn valid_bookmark_name(name: &str) -> bool {+ if name.is_empty() {+ return false;+ }+ let bytes = name.as_bytes();+ if bytes[0] == b'-' || bytes[0] == b'/' || bytes[0] == b'.' {+ return false;+ }+ if bytes[bytes.len() - 1] == b'/' || bytes[bytes.len() - 1] == b'.' {+ return false;+ }+ for byte in bytes {+ if *byte == 0 || *byte == b' ' || *byte < 32 || *byte == 127 {+ return false;+ }+ if matches!(+ *byte,+ b'~' | b'^' | b':' | b'?' | b'*' | b'[' | b'\\'+ ) {+ return false;+ }+ }+ if name.contains("..") || name.contains("@{") || name.contains("//") {+ return false;+ }+ if name == "@" || name.ends_with(".lock") {+ return false;+ }+ true+}++fn set(arguments: &[String]) -> Result<u8> {+ let mut name = String::new();+ let mut revision = String::new();+ let mut end_flags = false;+ let mut index = 0;+ while index < arguments.len() {+ let argument = &arguments[index];+ if !end_flags && argument == "--" {+ end_flags = true;+ } else if !end_flags && (argument == "-r" || argument == "-rev") {+ index += 1;+ if index >= arguments.len() {+ return Err(Error::new(format!("{argument} requires a revision")));+ }+ revision = arguments[index].clone();+ } else if !end_flags && args::is_flag(argument) {+ return Err(Error::new(format!("unknown flag: {argument}")));+ } else if name.is_empty() {+ name = argument.clone();+ } else if revision.is_empty() {+ revision = argument.clone();+ } else {+ return Err(Error::new("bmk set accepts a name and one revision"));+ }+ index += 1;+ }+ if name.is_empty() {+ return Err(Error::new("bmk set requires a name"));+ }+ if !valid_bookmark_name(&name) {+ return Err(Error::new(format!("invalid bookmark name: {name}")));+ }++ let root = layout::discover(Path::new("."))?;+ let mut store = Store::open(&root)?;+ snapshot::run_with(&root, &mut store)?;+ let mut txn = Txn::begin(&root, &mut store)?;+ let target = graph::resolve_revision(&mut store, txn.view(), &revision)?+ .ok_or_else(|| Error::new(format!("unknown revision: {revision}")))?;++ let mut changed = true;+ match ops::find_bookmark(txn.view(), name.as_bytes()) {+ Some(existing) => {+ let bookmark = &mut txn.view_mut().bookmarks[existing];+ if ops::bookmark_points_at(bookmark, target) {+ changed = false;+ } else {+ bookmark.targets.adds = vec![Some(target)];+ bookmark.targets.removes.clear();+ }+ }+ None => {+ txn.view_mut().bookmarks.push(Bookmark {+ name: name.as_bytes().to_vec(),+ targets: crate::object::view::TargetSet {+ adds: vec![Some(target)],+ removes: Vec::new(),+ },+ });+ }+ }++ if !changed {+ println!("info: bookmark {name} is already at {}", target.short());+ return Ok(0);+ }+ ops::rebuild_heads(txn.view_mut());+ txn.finish(&format!("bookmark set {name}"))?;+ println!("info: bookmark {name} set to {}", target.short());+ Ok(0)+}++fn list(arguments: &[String]) -> Result<u8> {+ let mut column_titles = true;+ let mut end_flags = false;+ for argument in arguments {+ if !end_flags && argument == "--" {+ end_flags = true;+ } else if !end_flags && argument == "-no-col-titles" {+ column_titles = false;+ } else if !end_flags && args::is_flag(argument) {+ return Err(Error::new(format!("unknown flag: {argument}")));+ } else {+ return Err(Error::new("bmk ls takes no operands"));+ }+ }++ let root = layout::discover(Path::new("."))?;+ let mut store = Store::open(&root)?;+ let view = ops::current_view(&root, &mut store)?+ .ok_or_else(|| Error::new("no operation state"))?;+ let working_copy = ops::working_copy_id(&view);+ let mut name_width = 8;+ for bookmark in &view.bookmarks {+ name_width = name_width.max(bookmark.name.len());+ }+ if column_titles {+ println!(+ "{:<name_width$} {:<12} {:<8} Target",+ "Bookmark",+ "Commit",+ "Change",+ name_width = name_width+ );+ }+ for bookmark in &view.bookmarks {+ let name = String::from_utf8_lossy(&bookmark.name);+ let Some(target) = bookmark.targets.adds.first().copied().flatten() else {+ println!(+ "{:<name_width$} {:<12} {:<8} (missing)",+ name,+ "<missing>",+ "",+ name_width = name_width+ );+ continue;+ };+ let change = match graph::load_commit(&mut store, target)? {+ Some(commit) => graph::base32_encode(commit.change_id)[..8].to_string(),+ None => String::new(),+ };+ let marker = if working_copy == Some(target) { "@" } else { "" };+ println!(+ "{:<name_width$} {:<12} {:<8} {marker}",+ name,+ target.short(),+ change,+ name_width = name_width+ );+ }+ if view.bookmarks.is_empty() {+ println!("info: no bookmarks");+ }+ Ok(0)+}++fn remove(arguments: &[String]) -> Result<u8> {+ let mut name = String::new();+ let mut end_flags = false;+ for argument in arguments {+ if !end_flags && argument == "--" {+ end_flags = true;+ } else if !end_flags && args::is_flag(argument) {+ return Err(Error::new(format!("unknown flag: {argument}")));+ } else if !name.is_empty() {+ return Err(Error::new("bmk rm accepts exactly one name"));+ } else {+ name = argument.clone();+ }+ }+ if name.is_empty() {+ return Err(Error::new("bmk rm requires a name"));+ }+ let root = layout::discover(Path::new("."))?;+ let mut store = Store::open(&root)?;+ let mut txn = Txn::begin(&root, &mut store)?;+ let Some(existing) = ops::find_bookmark(txn.view(), name.as_bytes()) else {+ return Err(Error::new(format!("no such bookmark: {name}")));+ };+ txn.view_mut().bookmarks.remove(existing);+ ops::rebuild_heads(txn.view_mut());+ txn.finish(&format!("bookmark delete {name}"))?;+ println!("info: deleted bookmark {name}");+ Ok(0)+}--- /dev/null+++ b/veins-rust/src/cli/commands/checkout.rs@@ -0,0 +1,23 @@+use std::path::Path;++use crate::cli::args;+use crate::error::Result;+use crate::store::layout;+use crate::worktree::checkout;++pub fn run(arguments: &[String]) -> Result<u8> {+ let mut revision = String::new();+ let mut end_flags = false;+ for argument in arguments {+ if !end_flags && argument == "--" {+ end_flags = true;+ } else if !end_flags && args::is_flag(argument) {+ return Err(crate::Error::new(format!("unknown flag: {argument}")));+ } else if revision.is_empty() {+ revision = argument.clone();+ }+ }+ let root = layout::discover(Path::new("."))?;+ checkout::run(&root, &revision)?;+ Ok(0)+}--- /dev/null+++ b/veins-rust/src/cli/commands/commit.rs@@ -0,0 +1,104 @@+use std::path::Path;++use crate::cli::args;+use crate::error::{Error, Result};+use crate::identity;+use crate::object::commit::{self, Commit};+use crate::object::id::Id;+use crate::object::TYPE_COMMIT;+use crate::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::store::Txn;+use crate::worktree::snapshot;++enum Outcome {+ Nothing,+ Described,+}++pub fn run(arguments: &[String]) -> Result<u8> {+ let parts = args::parse_message(arguments, 0)?;+ if args::message_is_blank(&parts) {+ return Err(Error::new("commit requires a non-empty message (-message)"));+ }+ let message = args::join(&parts);+ let root = layout::discover(Path::new("."))?;+ let mut store = Store::open(&root)?;++ if matches!(+ describe(&root, &mut store, &message, true)?,+ Outcome::Nothing+ ) {+ return Ok(0);+ }+ create_empty(&root, &mut store)?;+ Ok(0)+}++fn describe(root: &Path, store: &mut Store, message: &str, require_changes: bool) -> Result<Outcome> {+ snapshot::run_with(root, store)?;+ let mut txn = Txn::begin(root, store)?;+ let working_copy =+ ops::working_copy_id(txn.view()).ok_or_else(|| Error::new("no working-copy commit"))?;+ let loaded = graph::load_commit(store, working_copy)?+ .ok_or_else(|| Error::new("cannot read working-copy commit"))?;+ let changed = graph::has_changes(store, &loaded)?;+ let same_message = loaded.message == message.as_bytes();+ if !changed && (require_changes || same_message) {+ if require_changes {+ println!("info: nothing to commit, working copy clean");+ }+ return Ok(Outcome::Nothing);+ }++ let signature = identity::signature(root);+ let mut updated = loaded;+ updated.committer = signature;+ updated.message = message.as_bytes().to_vec();+ let encoded = commit::encode(&updated);+ let new_id = txn.add_object(TYPE_COMMIT, encoded);+ ops::remove_head(txn.view_mut(), working_copy);+ ops::move_bookmarks(txn.view_mut(), working_copy, new_id);+ ops::set_workspace(txn.view_mut(), new_id);+ ops::rebuild_heads(txn.view_mut());+ txn.finish("describe")?;+ store.refresh()?;+ mark_native(root, new_id)?;+ Ok(Outcome::Described)+}++fn create_empty(root: &Path, store: &mut Store) -> Result<()> {+ let mut txn = Txn::begin(root, store)?;+ let working_copy =+ ops::working_copy_id(txn.view()).ok_or_else(|| Error::new("no working-copy commit"))?;+ let loaded = graph::load_commit(store, working_copy)?+ .ok_or_else(|| Error::new("cannot read working-copy commit"))?;+ let signature = identity::signature(root);+ let new_commit = Commit {+ version: 1,+ parents: vec![working_copy],+ root_tree: loaded.root_tree,+ change_id: identity::random_change_id(),+ author: signature.clone(),+ committer: signature,+ message: Vec::new(),+ renames_state: commit::RENAMES_RECORDED,+ renames: Vec::new(),+ extra: Vec::new(),+ };+ let encoded = commit::encode(&new_commit);+ let new_id = txn.add_object(TYPE_COMMIT, encoded);+ ops::remove_head(txn.view_mut(), working_copy);+ ops::set_workspace(txn.view_mut(), new_id);+ ops::rebuild_heads(txn.view_mut());+ txn.finish("new")?;+ mark_native(root, new_id)?;+ Ok(())+}++fn mark_native(root: &Path, id: Id) -> Result<()> {+ let path = layout::git_map_dir(root).join("native");+ layout::append_file(&path, format!("{}\n", id.to_hex()).as_bytes())+}--- /dev/null+++ b/veins-rust/src/cli/commands/init.rs@@ -0,0 +1,22 @@+use std::path::Path;++use crate::cli::args;+use crate::error::Result;+use crate::store::layout;++pub fn run(arguments: &[String]) -> Result<u8> {+ let mut path = ".";+ let mut end_flags = false;+ for argument in arguments {+ if !end_flags && argument == "--" {+ end_flags = true;+ } else if !end_flags && args::is_flag(argument) {+ return Err(crate::Error::new(format!("unknown flag: {argument}")));+ } else {+ path = argument;+ }+ }+ let root = layout::init(Path::new(path))?;+ println!("info: initialized veins repository at {}", root.display());+ Ok(0)+}--- /dev/null+++ b/veins-rust/src/cli/commands/log.rs@@ -0,0 +1,142 @@+use std::path::Path;++use crate::cli::args;+use crate::error::Result;+use crate::object::id::Id;+use crate::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::time;+use crate::worktree::snapshot;++struct Record {+ id: Id,+ change: String,+ seconds: i64,+ message: Vec<u8>,+ author: Vec<u8>,+}++pub fn run(arguments: &[String]) -> Result<u8> {+ let mut revision = String::new();+ let mut column_titles = true;+ let mut end_flags = false;+ let mut index = 0;+ while index < arguments.len() {+ let argument = &arguments[index];+ if !end_flags && argument == "--" {+ end_flags = true;+ } else if !end_flags && (argument == "-r" || argument == "-rev") {+ index += 1;+ if index >= arguments.len() {+ return Err(crate::Error::new(format!("{argument} requires a revision")));+ }+ revision = arguments[index].clone();+ } else if !end_flags && argument == "-no-col-titles" {+ column_titles = false;+ } else if !end_flags && args::is_flag(argument) {+ return Err(crate::Error::new(format!("unknown flag: {argument}")));+ } else {+ revision = argument.clone();+ }+ index += 1;+ }++ let root = layout::discover(Path::new("."))?;+ let mut store = Store::open(&root)?;+ snapshot::run_with(&root, &mut store)?;+ let view = ops::current_view(&root, &mut store)?+ .ok_or_else(|| crate::Error::new("no operation state"))?;+ let working_copy = ops::working_copy_id(&view);++ let ids = if revision.is_empty() || revision == "all()" {+ let roots = graph::view_roots(&view);+ graph::collect_commits(&mut store, &roots)?+ } else if let Some(target) = graph::resolve_revision(&mut store, &view, &revision)? {+ graph::collect_commits(&mut store, &[target])?+ } else {+ Vec::new()+ };++ let mut records = Vec::new();+ for id in ids {+ let Some(commit) = graph::load_commit(&mut store, id)? else {+ continue;+ };+ records.push(Record {+ id,+ change: graph::base32_encode(commit.change_id),+ seconds: commit.committer.seconds,+ message: commit.message,+ author: commit.author.name,+ });+ }+ records.sort_by(|left, right| right.seconds.cmp(&left.seconds));++ let change_ids: Vec<String> = records+ .iter()+ .map(|record| record.change.clone())+ .collect();+ let mut change_width = 6;+ let mut author_width = 6;+ for (index, record) in records.iter().enumerate() {+ change_width = change_width.max(graph::short_change_id(&change_ids, index).len());+ author_width = author_width.max(record.author.len());+ }++ if column_titles {+ println!(+ " {:<12} {:<change_width$} {:<19} {:<author_width$} Message",+ "Commit",+ "Change",+ "Date",+ "Author",+ change_width = change_width,+ author_width = author_width,+ );+ }++ for (index, record) in records.iter().enumerate() {+ let marker = if working_copy == Some(record.id) {+ "@"+ } else {+ " "+ };+ let change = graph::short_change_id(&change_ids, index);+ let date = time::format_utc(record.seconds);+ let message = first_line(&record.message);+ print!(+ "{marker} {:<12} {:<change_width$} {:<19} {:<author_width$} {}",+ record.id.short(),+ change,+ date,+ String::from_utf8_lossy(&record.author),+ String::from_utf8_lossy(message),+ change_width = change_width,+ author_width = author_width,+ );+ for name in ops::bookmark_names(&view, record.id) {+ print!(" [{}]", String::from_utf8_lossy(&name));+ }+ for name in ops::tag_names(&view, record.id) {+ print!(" <{}>", String::from_utf8_lossy(&name));+ }+ if change_ids+ .iter()+ .enumerate()+ .any(|(other, value)| other != index && *value == record.change)+ {+ print!(" (divergent)");+ }+ println!();+ }+ Ok(0)+}++fn first_line(message: &[u8]) -> &[u8] {+ match message.iter().position(|byte| *byte == b'\n') {+ Some(position) => &message[..position],+ None => message,+ }+}--- /dev/null+++ b/veins-rust/src/cli/commands/mod.rs@@ -0,0 +1,8 @@+pub mod bookmark;+pub mod checkout;+pub mod commit;+pub mod init;+pub mod log;+pub mod selftest;+pub mod status;+pub mod version;--- /dev/null+++ b/veins-rust/src/cli/commands/selftest.rs@@ -0,0 +1,176 @@+use crate::error::{Error, Result};+use crate::object::blob::{self, BlobForm};+use crate::object::chunker::{gear_table, next_chunk};+use crate::object::commit::{self, Commit, Sig};+use crate::object::id::{hash_bytes, object_id, Id};+use crate::object::tree;+use crate::object::view::{self, Bookmark, Operation, TargetSet, TimeMs, View, WorkspaceRef};+use crate::object::{RawObject, TYPE_BLOB, TYPE_CHUNK, TYPE_TREE};+use crate::store::pack;++pub fn run() -> Result<u8> {+ let empty_hash = hex(&hash_bytes(b""));+ expect(+ empty_hash == "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262",+ "blake3 vector",+ )?;++ let gear = gear_table();+ expect(gear[0] == 0xf8447b379cdadcd5, "gear table entry 0")?;+ expect(gear[1] == 0xbe63d125aec8ca6d, "gear table entry 1")?;++ let mut chunk_input = vec![0u8; 300_000];+ for (index, byte) in chunk_input.iter_mut().enumerate() {+ *byte = ((index * 31 + 2 * 17) % 251) as u8;+ }+ let first = next_chunk(&chunk_input);+ let second = next_chunk(&chunk_input[first..]);+ expect(first == 262_144 && second == 37_856, "chunk boundaries")?;+ expect(+ object_id(TYPE_CHUNK, &chunk_input[..first]).to_hex()+ == "c83c67617ae4445631508cc4edba83ba58d9e996cea40c980ec69a8b6da86458",+ "first chunk id",+ )?;+ expect(+ object_id(TYPE_CHUNK, &chunk_input[first..]).to_hex()+ == "0c91665d423fd704baae9454d24697460c4898fbf16cc6ad498d3f750d073a4b",+ "second chunk id",+ )?;+ let build = blob::build(&chunk_input);+ expect(+ build.root.to_hex() == "937fe1a8d674aa28cb9fa074a76ea84cdc1d6c61e209f47bbdebbe4361b698cf",+ "manifest blob id",+ )?;+ let manifest = blob::decode(&build.objects.last().unwrap().body)?;+ expect(manifest.form == BlobForm::Leaf, "manifest form")?;++ let empty_tree_body = vec![0u8];+ let empty_tree_id = object_id(TYPE_TREE, &empty_tree_body);+ expect(+ empty_tree_id.to_hex() == "8be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb",+ "empty tree id",+ )?;+ expect(tree::decode(&empty_tree_body)?.entries.is_empty(), "empty tree decode")?;++ let inline = blob::encode_inline(b"hello");+ expect(+ object_id(TYPE_BLOB, &inline).to_hex()+ == "f04a7f7324bbb7279471b5c656c893ee51b62ed9f9bad4c8cb8a289101f68240",+ "inline blob id",+ )?;++ let change_id: [u8; 16] = [+ 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,+ 0x19, 0x1a,+ ];+ let signature = Sig {+ name: b"Alice".to_vec(),+ email: b"alice@example.com".to_vec(),+ seconds: 1_700_000_000,+ tz_min: 0,+ };+ let commit = Commit {+ version: 1,+ parents: Vec::new(),+ root_tree: empty_tree_id,+ change_id,+ author: signature.clone(),+ committer: signature,+ message: b"initial commit".to_vec(),+ renames_state: commit::RENAMES_RECORDED,+ renames: Vec::new(),+ extra: Vec::new(),+ };+ let commit_body = commit::encode(&commit);+ let commit_id = object_id(crate::object::TYPE_COMMIT, &commit_body);+ expect(+ commit_id.to_hex() == "7f648b3621402df01985d121888c89c37107274fb8bb54661f12deca6cc72299",+ "commit id",+ )?;+ expect(+ commit_id+ == Id::from_hex("7f648b3621402df01985d121888c89c37107274fb8bb54661f12deca6cc72299")?,+ "commit round trip",+ )?;++ let view = View {+ heads: vec![commit_id],+ bookmarks: vec![Bookmark {+ name: b"main".to_vec(),+ targets: TargetSet {+ adds: vec![Some(commit_id)],+ removes: Vec::new(),+ },+ }],+ tags: Vec::new(),+ remote_refs: Vec::new(),+ working_copies: vec![WorkspaceRef {+ workspace: b"default".to_vec(),+ target: commit_id,+ }],+ };+ let view_body = view::encode_view(&view);+ let view_id = object_id(crate::object::TYPE_VIEW, &view_body);+ expect(+ view_id.to_hex() == "a2e19569bb3b5c28775bc8503c45c4edce6d51f55303e39bc02eec529324cd11",+ "view id",+ )?;++ let operation = Operation {+ parents: Vec::new(),+ view: view_id,+ start: TimeMs {+ millis: 1_700_000_000_000,+ tz_min: 0,+ },+ end: TimeMs {+ millis: 1_700_000_000_000,+ tz_min: 0,+ },+ hostname: b"host".to_vec(),+ username: b"alice".to_vec(),+ description: b"selftest operation".to_vec(),+ tags: Vec::new(),+ };+ let operation_body = view::encode_operation(&operation);+ expect(+ object_id(crate::object::TYPE_OPERATION, &operation_body).to_hex()+ == "0a5494529353fb5886870a128139e07d95f40afcd831afc423617808f31dc426",+ "operation id",+ )?;++ let output = pack::encode(&[RawObject::known(TYPE_TREE, empty_tree_id, vec![0])]);+ expect(+ hex(&output.pack)+ == "56504b310100000001000000000000008be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb030001010072c385a83448a5e16853735a79a212f0377d0e40be777d121271758525dbc911",+ "pack bytes",+ )?;+ expect(output.index.len() == 1136, "index length")?;+ expect(+ hex(&hash_bytes(&output.index))+ == "d5dfb7b2ce4235f87856c12ff2e0b65d817dc29dfedad62ba34e71d74dca0cfc",+ "index checksum",+ )?;+ pack::decode(output.pack)?;++ println!("self-test: ok");+ Ok(0)+}++fn expect(condition: bool, message: &str) -> Result<()> {+ if condition {+ Ok(())+ } else {+ Err(Error::new(format!("self-test failed: {message}")))+ }+}++fn hex(bytes: &[u8]) -> String {+ const DIGITS: &[u8; 16] = b"0123456789abcdef";+ let mut text = String::with_capacity(bytes.len() * 2);+ for byte in bytes {+ text.push(DIGITS[(byte >> 4) as usize] as char);+ text.push(DIGITS[(byte & 0x0f) as usize] as char);+ }+ text+}--- /dev/null+++ b/veins-rust/src/cli/commands/status.rs@@ -0,0 +1,50 @@+use std::path::Path;++use crate::error::{Error, Result};+use crate::object::tree::{KIND_CONFLICT, KIND_MISSING};+use crate::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::worktree::snapshot;++pub fn run() -> Result<u8> {+ let root = layout::discover(Path::new("."))?;+ let mut store = Store::open(&root)?;+ snapshot::run_with(&root, &mut store)?;+ let view = ops::current_view(&root, &mut store)?+ .ok_or_else(|| Error::new("no operation state"))?;+ let Some(working_copy) = ops::working_copy_id(&view) else {+ println!("info: working copy clean");+ return Ok(0);+ };+ let commit = graph::load_commit(&mut store, working_copy)?+ .ok_or_else(|| Error::new("no operation state"))?;+ let old_tree = match commit.parents.first() {+ Some(parent) => graph::load_commit(&mut store, *parent)?.map(|parent| parent.root_tree),+ None => None,+ };+ let changes = graph::compare_trees(&mut store, old_tree, Some(commit.root_tree))?;+ let empty = changes.is_empty();+ let mut conflicts = 0usize;+ for change in changes {+ let path = String::from_utf8_lossy(&change.path);+ if change.old_kind == KIND_MISSING {+ println!("A {path}");+ } else if change.new_kind == KIND_MISSING {+ println!("D {path}");+ } else if change.new_kind == KIND_CONFLICT {+ println!("C {path}");+ conflicts += 1;+ } else {+ println!("M {path}");+ }+ }+ if empty {+ println!("info: working copy clean");+ }+ if conflicts > 0 {+ println!("{conflicts} conflict(s)");+ }+ Ok(0)+}--- /dev/null+++ b/veins-rust/src/cli/commands/version.rs@@ -0,0 +1,6 @@+use crate::error::Result;++pub fn run() -> Result<u8> {+ println!("veins-rust v0.1.0 (veins-store 1)");+ Ok(0)+}--- /dev/null+++ b/veins-rust/src/cli/mod.rs@@ -0,0 +1,51 @@+pub mod args;+pub mod commands;++use crate::Result;++pub fn run(arguments: &[String]) -> u8 {+ match dispatch(arguments) {+ Ok(code) => code,+ Err(error) => {+ eprintln!("error: {error}");+ 1+ }+ }+}++fn dispatch(arguments: &[String]) -> Result<u8> {+ let Some(command) = arguments.first() else {+ usage();+ return Ok(1);+ };+ let rest = &arguments[1..];+ match command.as_str() {+ "init" => commands::init::run(rest),+ "status" | "stat" => commands::status::run(),+ "log" => commands::log::run(rest),+ "go" | "commit" => commands::commit::run(rest),+ "co" | "checkout" => commands::checkout::run(rest),+ "bmk" => commands::bookmark::run(rest),+ "self-test" => commands::selftest::run(),+ "version" | "-version" => commands::version::run(),+ "help" | "-help" | "-h" => {+ usage();+ Ok(0)+ }+ _ => Err(crate::Error::new(format!("unknown command: {command}"))),+ }+}++fn usage() {+ println!("usage: vn <command> [options]");+ println!();+ println!("commands:");+ println!(" init [path] create a repository");+ println!(" status show working-copy changes");+ println!(" log [-rev <rev>] show history");+ println!(" go -message <message> commit the working copy");+ println!(" co [rev] check out a revision");+ println!(" bmk set|ls|rm manage bookmarks");+ println!(" self-test run format self-tests");+ println!(" version print version information");+}--- /dev/null+++ b/veins-rust/src/encoding/mod.rs@@ -0,0 +1,5 @@+pub mod reader;+pub mod writer;++pub use reader::Reader;+pub use writer::Writer;--- /dev/null+++ b/veins-rust/src/encoding/reader.rs@@ -0,0 +1,114 @@+use crate::error::{Error, Result};+use crate::object::id::Id;++pub struct Reader<'a> {+ data: &'a [u8],+ position: usize,+}++impl<'a> Reader<'a> {+ pub fn new(data: &'a [u8]) -> Self {+ Self { data, position: 0 }+ }++ pub fn offset(&self) -> usize {+ self.position+ }++ pub fn remaining(&self) -> usize {+ self.data.len().saturating_sub(self.position)+ }++ fn take(&mut self, length: usize) -> Result<&'a [u8]> {+ if length > self.remaining() {+ return Err(Error::new("unexpected end of input"));+ }+ let start = self.position;+ self.position += length;+ Ok(&self.data[start..start + length])+ }++ pub fn u8(&mut self) -> Result<u8> {+ Ok(self.take(1)?[0])+ }++ pub fn u16le(&mut self) -> Result<u16> {+ let bytes = self.take(2)?;+ Ok(u16::from_le_bytes([bytes[0], bytes[1]]))+ }++ pub fn u32le(&mut self) -> Result<u32> {+ let bytes = self.take(4)?;+ Ok(u32::from_le_bytes([+ bytes[0], bytes[1], bytes[2], bytes[3],+ ]))+ }++ pub fn u64le(&mut self) -> Result<u64> {+ let bytes = self.take(8)?;+ let mut value = [0u8; 8];+ value.copy_from_slice(bytes);+ Ok(u64::from_le_bytes(value))+ }++ pub fn i16le(&mut self) -> Result<i16> {+ Ok(self.u16le()? as i16)+ }++ pub fn i64le(&mut self) -> Result<i64> {+ Ok(self.u64le()? as i64)+ }++ pub fn varint(&mut self) -> Result<u64> {+ let mut value = 0u64;+ for index in 0..10 {+ let byte = self.u8()?;+ if index == 9 && byte > 1 {+ return Err(Error::new("varint overflow"));+ }+ value |= u64::from(byte & 0x7f) << (index * 7);+ if byte & 0x80 == 0 {+ if index > 0 && byte == 0 {+ return Err(Error::new("non-minimal varint"));+ }+ return Ok(value);+ }+ }+ Err(Error::new("varint too long"))+ }++ pub fn bytes(&mut self, maximum: usize) -> Result<&'a [u8]> {+ let length = self.varint()?;+ let length = usize::try_from(length).map_err(|_| Error::new("length overflow"))?;+ if length > maximum {+ return Err(Error::new("length limit exceeded"));+ }+ self.take(length)+ }++ pub fn raw(&mut self, length: usize) -> Result<&'a [u8]> {+ self.take(length)+ }++ pub fn id(&mut self) -> Result<Id> {+ let mut value = [0u8; 32];+ value.copy_from_slice(self.take(32)?);+ Ok(Id(value))+ }++ pub fn opt_id(&mut self) -> Result<Option<Id>> {+ match self.u8()? {+ 0 => Ok(None),+ 1 => Ok(Some(self.id()?)),+ _ => Err(Error::new("invalid optional value")),+ }+ }++ pub fn finish(&self) -> Result<()> {+ if self.position == self.data.len() {+ Ok(())+ } else {+ Err(Error::new("trailing bytes"))+ }+ }+}--- /dev/null+++ b/veins-rust/src/encoding/writer.rs@@ -0,0 +1,93 @@+use crate::object::id::Id;++#[derive(Default)]+pub struct Writer {+ data: Vec<u8>,+}++impl Writer {+ pub fn new() -> Self {+ Self::default()+ }++ pub fn with_capacity(capacity: usize) -> Self {+ Self {+ data: Vec::with_capacity(capacity),+ }+ }++ pub fn len(&self) -> usize {+ self.data.len()+ }++ pub fn is_empty(&self) -> bool {+ self.data.is_empty()+ }++ pub fn u8(&mut self, value: u8) {+ self.data.push(value);+ }++ pub fn u16le(&mut self, value: u16) {+ self.data.extend_from_slice(&value.to_le_bytes());+ }++ pub fn u32le(&mut self, value: u32) {+ self.data.extend_from_slice(&value.to_le_bytes());+ }++ pub fn u64le(&mut self, value: u64) {+ self.data.extend_from_slice(&value.to_le_bytes());+ }++ pub fn i16le(&mut self, value: i16) {+ self.u16le(value as u16);+ }++ pub fn i64le(&mut self, value: i64) {+ self.u64le(value as u64);+ }++ pub fn varint(&mut self, mut value: u64) {+ loop {+ let byte = (value & 0x7f) as u8;+ value >>= 7;+ if value == 0 {+ self.data.push(byte);+ return;+ }+ self.data.push(byte | 0x80);+ }+ }++ pub fn raw(&mut self, bytes: &[u8]) {+ self.data.extend_from_slice(bytes);+ }++ pub fn bytes(&mut self, bytes: &[u8]) {+ self.varint(bytes.len() as u64);+ self.data.extend_from_slice(bytes);+ }++ pub fn id(&mut self, id: Id) {+ self.data.extend_from_slice(&id.0);+ }++ pub fn opt_id(&mut self, id: Option<Id>) {+ match id {+ Some(value) => {+ self.u8(1);+ self.id(value);+ }+ None => self.u8(0),+ }+ }++ pub fn into_vec(self) -> Vec<u8> {+ self.data+ }++ pub fn as_slice(&self) -> &[u8] {+ &self.data+ }+}--- /dev/null+++ b/veins-rust/src/error.rs@@ -0,0 +1,57 @@+use std::fmt;+use std::io;++pub type Result<T> = std::result::Result<T, Error>;++#[derive(Debug)]+pub struct Error {+ message: String,+}++impl Error {+ pub fn new(message: impl Into<String>) -> Self {+ Self {+ message: message.into(),+ }+ }++ pub fn context(self, context: impl AsRef<str>) -> Self {+ Self::new(format!("{}: {}", context.as_ref(), self.message))+ }+}++impl fmt::Display for Error {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter.write_str(&self.message)+ }+}++impl std::error::Error for Error {}++impl From<io::Error> for Error {+ fn from(error: io::Error) -> Self {+ Self::new(error.to_string())+ }+}++impl From<String> for Error {+ fn from(message: String) -> Self {+ Self::new(message)+ }+}++impl From<&str> for Error {+ fn from(message: &str) -> Self {+ Self::new(message)+ }+}++pub trait OptionExt<T> {+ fn or_error(self, message: impl Into<String>) -> Result<T>;+}++impl<T> OptionExt<T> for Option<T> {+ fn or_error(self, message: impl Into<String>) -> Result<T> {+ self.ok_or_else(|| Error::new(message))+ }+}--- /dev/null+++ b/veins-rust/src/identity.rs@@ -0,0 +1,112 @@+use std::env;+use std::fs;+use std::path::Path;++use crate::object::commit::Sig;+use crate::store::layout;+use crate::time;++struct Config {+ entries: Vec<(String, String)>,+}++impl Config {+ fn load(root: &Path) -> Self {+ let mut entries = Vec::new();+ let mut section = String::new();+ if let Ok(text) = fs::read_to_string(layout::config_path(root)) {+ for raw in text.lines() {+ let line = raw.trim();+ if line.is_empty() || line.starts_with('#') {+ continue;+ }+ if line.starts_with('[') && line.ends_with(']') {+ section = line[1..line.len() - 1].trim().to_string();+ continue;+ }+ let Some((key, value)) = line.split_once('=') else {+ continue;+ };+ let key = key.trim();+ let full_key = if section.is_empty() {+ key.to_string()+ } else {+ format!("{section}.{key}")+ };+ entries.push((full_key, unquote(strip_comment(value))));+ }+ }+ Self { entries }+ }++ fn get(&self, key: &str) -> Option<&str> {+ self.entries+ .iter()+ .find(|(name, _)| name == key)+ .map(|(_, value)| value.as_str())+ }+}++fn strip_comment(value: &str) -> &str {+ let mut quoted = false;+ for (index, byte) in value.bytes().enumerate() {+ match byte {+ b'"' => quoted = !quoted,+ b'#' if !quoted => return value[..index].trim(),+ _ => {}+ }+ }+ value.trim()+}++fn unquote(value: &str) -> String {+ if value.len() >= 2 && value.starts_with('"') && value.ends_with('"') {+ value[1..value.len() - 1].to_string()+ } else {+ value.to_string()+ }+}++fn first_config(root: &Path, key: &str, environment: &[&str], fallback: &str) -> String {+ let config = Config::load(root);+ if let Some(value) = config.get(key)+ && !value.is_empty()+ {+ return value.to_string();+ }+ for name in environment {+ if let Ok(value) = env::var(name)+ && !value.is_empty()+ {+ return value;+ }+ }+ fallback.to_string()+}++pub fn signature(root: &Path) -> Sig {+ Sig {+ name: first_config(root, "user.name", &["GIT_AUTHOR_NAME", "USER"], "unknown").into_bytes(),+ email: first_config(root, "user.email", &["GIT_AUTHOR_EMAIL", "EMAIL"], "unknown")+ .into_bytes(),+ seconds: time::now_seconds(),+ tz_min: 0,+ }+}++pub fn random_change_id() -> [u8; 16] {+ use std::io::Read;++ let mut value = [0u8; 16];+ if let Ok(mut file) = fs::File::open("/dev/urandom")+ && file.read_exact(&mut value).is_ok()+ {+ return value;+ }+ let mut hasher = blake3::Hasher::new();+ hasher.update(&time::now_millis().to_le_bytes());+ hasher.update(&std::process::id().to_le_bytes());+ hasher.update(format!("{:?}", std::time::Instant::now()).as_bytes());+ value.copy_from_slice(&hasher.finalize().as_bytes()[..16]);+ value+}--- /dev/null+++ b/veins-rust/src/lib.rs@@ -0,0 +1,10 @@+pub mod cli;+pub mod encoding;+pub mod error;+pub mod identity;+pub mod object;+pub mod store;+pub mod time;+pub mod worktree;++pub use error::{Error, Result};--- /dev/null+++ b/veins-rust/src/main.rs@@ -0,0 +1,6 @@+use std::process::ExitCode;++fn main() -> ExitCode {+ let args: Vec<String> = std::env::args().skip(1).collect();+ ExitCode::from(veins_rust::cli::run(&args))+}--- /dev/null+++ b/veins-rust/src/object/blob.rs@@ -0,0 +1,155 @@+use crate::encoding::{Reader, Writer};+use crate::error::{Error, Result};+use crate::object::chunker::next_chunk;+use crate::object::id::{object_id, Id};+use crate::object::{+ RawObject, INLINE_THRESHOLD, MAX_CHUNK_LEN, MAX_MANIFEST_ENTRIES, TYPE_BLOB, TYPE_CHUNK,+};++#[derive(Clone, Copy, PartialEq, Eq)]+pub enum BlobForm {+ Inline,+ Leaf,+ Interior,+}++#[derive(Clone)]+pub struct BlobEntry {+ pub id: Id,+ pub length: u64,+}++#[derive(Clone)]+pub struct Blob {+ pub form: BlobForm,+ pub data: Vec<u8>,+ pub entries: Vec<BlobEntry>,+}++pub struct BlobBuild {+ pub root: Id,+ pub objects: Vec<RawObject>,+}++pub fn encode_inline(data: &[u8]) -> Vec<u8> {+ let mut writer = Writer::with_capacity(data.len() + 8);+ writer.u8(0);+ writer.bytes(data);+ writer.into_vec()+}++pub fn decode(body: &[u8]) -> Result<Blob> {+ let mut reader = Reader::new(body);+ let form = match reader.u8()? {+ 0 => BlobForm::Inline,+ 1 => BlobForm::Leaf,+ 2 => BlobForm::Interior,+ _ => return Err(Error::new("invalid blob form")),+ };+ if form == BlobForm::Inline {+ let data = reader.bytes(INLINE_THRESHOLD)?.to_vec();+ reader.finish()?;+ return Ok(Blob {+ form,+ data,+ entries: Vec::new(),+ });+ }+ let count = reader.varint()?;+ let count = usize::try_from(count).map_err(|_| Error::new("manifest too large"))?;+ if count == 0 || count > MAX_MANIFEST_ENTRIES {+ return Err(Error::new("invalid manifest entry count"));+ }+ let mut entries = Vec::with_capacity(count);+ for _ in 0..count {+ let id = reader.id()?;+ let length = reader.varint()?;+ if length == 0 {+ return Err(Error::new("invalid manifest entry length"));+ }+ if form == BlobForm::Leaf && length > MAX_CHUNK_LEN as u64 {+ return Err(Error::new("chunk exceeds maximum size"));+ }+ entries.push(BlobEntry { id, length });+ }+ reader.finish()?;+ Ok(Blob {+ form,+ data: Vec::new(),+ entries,+ })+}++fn cut_after(id: Id, current_length: usize) -> bool {+ current_length >= MAX_MANIFEST_ENTRIES || (current_length >= 16 && id.0[0] == 0)+}++struct NodeRef {+ id: Id,+ length: u64,+}++pub fn build(data: &[u8]) -> BlobBuild {+ if data.len() <= INLINE_THRESHOLD {+ let body = encode_inline(data);+ let root = object_id(TYPE_BLOB, &body);+ return BlobBuild {+ root,+ objects: vec![RawObject::known(TYPE_BLOB, root, body)],+ };+ }++ let mut objects = Vec::new();+ let mut level = Vec::new();+ let mut offset = 0;+ while offset < data.len() {+ let length = next_chunk(&data[offset..]);+ let chunk = &data[offset..offset + length];+ let id = object_id(TYPE_CHUNK, chunk);+ objects.push(RawObject::known(TYPE_CHUNK, id, chunk.to_vec()));+ level.push(NodeRef {+ id,+ length: length as u64,+ });+ offset += length;+ }++ let mut leaf_level = true;+ let root = loop {+ let mut groups = Vec::new();+ let mut start = 0;+ for index in 0..level.len() {+ let current = index - start + 1;+ if cut_after(level[index].id, current) || index + 1 == level.len() {+ groups.push((start, current));+ start = index + 1;+ }+ }++ let mut next = Vec::with_capacity(groups.len());+ for (start, count) in groups {+ let mut writer = Writer::with_capacity(count * 40 + 8);+ writer.u8(if leaf_level { 1 } else { 2 });+ writer.varint(count as u64);+ let mut total = 0u64;+ for index in 0..count {+ let node = &level[start + index];+ writer.id(node.id);+ writer.varint(node.length);+ total += node.length;+ }+ let body = writer.into_vec();+ let id = object_id(TYPE_BLOB, &body);+ objects.push(RawObject::known(TYPE_BLOB, id, body));+ next.push(NodeRef { id, length: total });+ }++ if next.len() == 1 {+ break next[0].id;+ }+ level = next;+ leaf_level = false;+ };++ BlobBuild { root, objects }+}--- /dev/null+++ b/veins-rust/src/object/chunker.rs@@ -0,0 +1,58 @@+use std::sync::OnceLock;++static GEAR: OnceLock<[u64; 256]> = OnceLock::new();++fn build_gear() -> [u64; 256] {+ let mut table = [0u64; 256];+ for (index, slot) in table.iter_mut().enumerate() {+ let mut hasher = blake3::Hasher::new();+ hasher.update(b"veins/fastcdc/gear/v1");+ hasher.update(&[index as u8]);+ let digest = hasher.finalize();+ let mut value = [0u8; 8];+ value.copy_from_slice(&digest.as_bytes()[..8]);+ *slot = u64::from_le_bytes(value);+ }+ table+}++pub fn gear_table() -> &'static [u64; 256] {+ GEAR.get_or_init(build_gear)+}++pub fn next_chunk(data: &[u8]) -> usize {+ const MIN_SIZE: usize = 16 * 1024;+ const AVG_SIZE: usize = 64 * 1024;+ const MAX_SIZE: usize = 256 * 1024;+ const MASK_SMALL: u64 = 0x3ffff;+ const MASK_LARGE: u64 = 0x3fff;++ let length = data.len();+ if length <= MIN_SIZE {+ return length;+ }+ let limit = length.min(MAX_SIZE);+ let normal = AVG_SIZE.min(limit);+ let gear = gear_table();+ let mut fingerprint = 0u64;+ let mut index = MIN_SIZE;+ unsafe {+ while index < normal {+ let byte = *data.get_unchecked(index);+ fingerprint = (fingerprint >> 1).wrapping_add(gear[byte as usize]);+ if fingerprint & MASK_SMALL == 0 {+ return index + 1;+ }+ index += 1;+ }+ while index < limit {+ let byte = *data.get_unchecked(index);+ fingerprint = (fingerprint >> 1).wrapping_add(gear[byte as usize]);+ if fingerprint & MASK_LARGE == 0 {+ return index + 1;+ }+ index += 1;+ }+ }+ limit+}--- /dev/null+++ b/veins-rust/src/object/commit.rs@@ -0,0 +1,176 @@+use crate::encoding::{Reader, Writer};+use crate::error::{Error, Result};+use crate::object::id::Id;+use crate::object::{MAX_MESSAGE_LEN, MAX_NAME_LEN};++pub const RENAMES_UNKNOWN: u8 = 0;+pub const RENAMES_RECORDED: u8 = 1;++#[derive(Clone, Default)]+pub struct Sig {+ pub name: Vec<u8>,+ pub email: Vec<u8>,+ pub seconds: i64,+ pub tz_min: i16,+}++#[derive(Clone)]+pub struct Rename {+ pub parent_index: u64,+ pub kind: u8,+ pub from_path: Vec<u8>,+ pub to_path: Vec<u8>,+}++#[derive(Clone)]+pub struct Commit {+ pub version: u8,+ pub parents: Vec<Id>,+ pub root_tree: Id,+ pub change_id: [u8; 16],+ pub author: Sig,+ pub committer: Sig,+ pub message: Vec<u8>,+ pub renames_state: u8,+ pub renames: Vec<Rename>,+ pub extra: Vec<(Vec<u8>, Vec<u8>)>,+}++impl Commit {+ pub fn empty(change_id: [u8; 16], root_tree: Id, sig: Sig) -> Self {+ Self {+ version: 1,+ parents: Vec::new(),+ root_tree,+ change_id,+ author: sig.clone(),+ committer: sig,+ message: Vec::new(),+ renames_state: RENAMES_RECORDED,+ renames: Vec::new(),+ extra: Vec::new(),+ }+ }+}++fn write_sig(writer: &mut Writer, sig: &Sig) {+ writer.bytes(&sig.name);+ writer.bytes(&sig.email);+ writer.i64le(sig.seconds);+ writer.i16le(sig.tz_min);+}++fn read_sig(reader: &mut Reader<'_>) -> Result<Sig> {+ Ok(Sig {+ name: reader.bytes(MAX_NAME_LEN)?.to_vec(),+ email: reader.bytes(MAX_NAME_LEN)?.to_vec(),+ seconds: reader.i64le()?,+ tz_min: reader.i16le()?,+ })+}++pub fn encode(commit: &Commit) -> Vec<u8> {+ let mut writer = Writer::with_capacity(256);+ writer.u8(commit.version);+ writer.varint(commit.parents.len() as u64);+ for parent in &commit.parents {+ writer.id(*parent);+ }+ writer.id(commit.root_tree);+ writer.raw(&commit.change_id);+ write_sig(&mut writer, &commit.author);+ write_sig(&mut writer, &commit.committer);+ writer.bytes(&commit.message);+ writer.u8(commit.renames_state);+ writer.varint(commit.renames.len() as u64);+ for rename in &commit.renames {+ writer.varint(rename.parent_index);+ writer.u8(rename.kind);+ writer.bytes(&rename.from_path);+ writer.bytes(&rename.to_path);+ }+ writer.varint(commit.extra.len() as u64);+ for (key, value) in &commit.extra {+ writer.bytes(key);+ writer.bytes(value);+ }+ writer.into_vec()+}++pub fn decode(body: &[u8]) -> Result<Commit> {+ let mut reader = Reader::new(body);+ let version = reader.u8()?;+ if version != 1 {+ return Err(Error::new("unsupported commit version"));+ }+ let parent_count = reader.varint()?;+ let parent_count = usize::try_from(parent_count).map_err(|_| Error::new("too many parents"))?;+ if parent_count > 1024 {+ return Err(Error::new("too many parents"));+ }+ let mut parents = Vec::with_capacity(parent_count);+ for _ in 0..parent_count {+ parents.push(reader.id()?);+ }+ let root_tree = reader.id()?;+ let mut change_id = [0u8; 16];+ change_id.copy_from_slice(reader.raw(16)?);+ let author = read_sig(&mut reader)?;+ let committer = read_sig(&mut reader)?;+ let message = reader.bytes(MAX_MESSAGE_LEN)?.to_vec();+ let renames_state = reader.u8()?;+ if renames_state > 1 {+ return Err(Error::new("invalid rename state"));+ }+ let rename_count = reader.varint()?;+ let rename_count = usize::try_from(rename_count).map_err(|_| Error::new("too many renames"))?;+ if renames_state == RENAMES_UNKNOWN && rename_count != 0 {+ return Err(Error::new("unknown rename state carries renames"));+ }+ let mut renames = Vec::with_capacity(rename_count);+ for _ in 0..rename_count {+ let parent_index = reader.varint()?;+ if parent_index >= parent_count as u64 {+ return Err(Error::new("rename parent index out of range"));+ }+ let kind = reader.u8()?;+ if kind > 1 {+ return Err(Error::new("invalid rename kind"));+ }+ let from_path = reader.bytes(crate::object::MAX_PATH_LEN)?.to_vec();+ let to_path = reader.bytes(crate::object::MAX_PATH_LEN)?.to_vec();+ renames.push(Rename {+ parent_index,+ kind,+ from_path,+ to_path,+ });+ }+ let extra_count = reader.varint()?;+ let extra_count = usize::try_from(extra_count).map_err(|_| Error::new("too many extra headers"))?;+ if extra_count > 1024 {+ return Err(Error::new("too many extra headers"));+ }+ let mut extra = Vec::with_capacity(extra_count);+ for _ in 0..extra_count {+ let key = reader.bytes(MAX_NAME_LEN)?.to_vec();+ let value = reader.bytes(MAX_MESSAGE_LEN)?.to_vec();+ if key.is_empty() {+ return Err(Error::new("empty extra header key"));+ }+ extra.push((key, value));+ }+ reader.finish()?;+ Ok(Commit {+ version,+ parents,+ root_tree,+ change_id,+ author,+ committer,+ message,+ renames_state,+ renames,+ extra,+ })+}--- /dev/null+++ b/veins-rust/src/object/id.rs@@ -0,0 +1,76 @@+use crate::error::{Error, Result};++#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub struct Id(pub [u8; 32]);++const HEX: &[u8; 16] = b"0123456789abcdef";++impl Id {+ pub fn to_hex(self) -> String {+ let mut text = String::with_capacity(64);+ for byte in self.0 {+ text.push(HEX[(byte >> 4) as usize] as char);+ text.push(HEX[(byte & 0x0f) as usize] as char);+ }+ text+ }++ pub fn short(self) -> String {+ self.to_hex()[..12].to_string()+ }++ pub fn from_hex(text: &str) -> Result<Self> {+ if text.len() != 64 {+ return Err(Error::new("object id must contain 64 hex digits"));+ }+ let bytes = text.as_bytes();+ let mut value = [0u8; 32];+ for index in 0..32 {+ let high = hex_value(bytes[index * 2])?;+ let low = hex_value(bytes[index * 2 + 1])?;+ value[index] = (high << 4) | low;+ }+ Ok(Self(value))+ }+}++impl std::fmt::Debug for Id {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter.write_str(&self.to_hex())+ }+}++fn hex_value(byte: u8) -> Result<u8> {+ match byte {+ b'0'..=b'9' => Ok(byte - b'0'),+ b'a'..=b'f' => Ok(byte - b'a' + 10),+ b'A'..=b'F' => Ok(byte - b'A' + 10),+ _ => Err(Error::new("invalid hex digit")),+ }+}++pub fn hash_bytes(data: &[u8]) -> [u8; 32] {+ *blake3::hash(data).as_bytes()+}++pub fn object_id(kind: u8, body: &[u8]) -> Id {+ let mut hasher = blake3::Hasher::new();+ hasher.update(b"veins/1\0");+ hasher.update(&[kind]);+ hasher.update(body);+ Id(*hasher.finalize().as_bytes())+}++pub fn prefix_matches(full: &str, prefix: &str) -> bool {+ if prefix.is_empty() || prefix.len() > full.len() {+ return false;+ }+ full.as_bytes()+ .iter()+ .zip(prefix.as_bytes())+ .all(|(left, right)| left.eq_ignore_ascii_case(right))+}++pub fn is_hex_prefix(text: &str) -> bool {+ (4..=64).contains(&text.len()) && text.bytes().all(|byte| byte.is_ascii_hexdigit())+}--- /dev/null+++ b/veins-rust/src/object/mod.rs@@ -0,0 +1,48 @@+pub mod blob;+pub mod chunker;+pub mod commit;+pub mod id;+pub mod path;+pub mod tree;+pub mod view;++use id::Id;++pub const TYPE_CHUNK: u8 = 1;+pub const TYPE_BLOB: u8 = 2;+pub const TYPE_TREE: u8 = 3;+pub const TYPE_COMMIT: u8 = 4;+pub const TYPE_CONFLICT: u8 = 5;+pub const TYPE_OPERATION: u8 = 6;+pub const TYPE_VIEW: u8 = 7;++pub const INLINE_THRESHOLD: usize = 16 * 1024;+pub const MAX_CHUNK_LEN: usize = 256 * 1024;+pub const MAX_MANIFEST_ENTRIES: usize = 1024;+pub const MAX_TREE_ENTRIES: usize = 1_000_000;+pub const MAX_NAME_LEN: usize = 4096;+pub const MAX_PATH_LEN: usize = 65_536;+pub const MAX_MESSAGE_LEN: usize = 16 * 1024 * 1024;+pub const MAX_OBJECT_BODY: usize = 64 * 1024 * 1024;++#[derive(Clone)]+pub struct RawObject {+ pub kind: u8,+ pub body: Vec<u8>,+ pub id: Id,+}++impl RawObject {+ pub fn new(kind: u8, body: Vec<u8>) -> Self {+ let id = id::object_id(kind, &body);+ Self { kind, body, id }+ }++ pub fn known(kind: u8, id: Id, body: Vec<u8>) -> Self {+ Self { kind, body, id }+ }+}++pub fn type_valid(kind: u8) -> bool {+ (TYPE_CHUNK..=TYPE_VIEW).contains(&kind)+}--- /dev/null+++ b/veins-rust/src/object/path.rs@@ -0,0 +1,47 @@+use crate::object::MAX_NAME_LEN;++pub fn valid_component(component: &[u8]) -> bool {+ if component.is_empty() || component.len() > MAX_NAME_LEN {+ return false;+ }+ if component == b"." || component == b".." {+ return false;+ }+ component+ .iter()+ .all(|byte| *byte != 0 && *byte != b'/')+}++pub fn valid_name(name: &[u8]) -> bool {+ valid_component(name) && !name.eq_ignore_ascii_case(b".veins")+}++pub fn valid_path(path: &[u8]) -> bool {+ if path.is_empty() {+ return false;+ }+ if path[0] == b'/' {+ return false;+ }+ path.split(|byte| *byte == b'/').all(valid_component)+}++pub fn valid_checkout_path(path: &[u8]) -> bool {+ if !valid_path(path) {+ return false;+ }+ path.split(|byte| *byte == b'/').all(|component| {+ valid_name(component) && !component.eq_ignore_ascii_case(b".git")+ })+}++pub fn join(base: &[u8], name: &[u8]) -> Vec<u8> {+ if base.is_empty() {+ return name.to_vec();+ }+ let mut path = Vec::with_capacity(base.len() + 1 + name.len());+ path.extend_from_slice(base);+ path.push(b'/');+ path.extend_from_slice(name);+ path+}--- /dev/null+++ b/veins-rust/src/object/tree.rs@@ -0,0 +1,144 @@+use crate::encoding::{Reader, Writer};+use crate::error::{Error, Result};+use crate::object::id::Id;+use crate::object::path::valid_name;+use crate::object::{MAX_NAME_LEN, MAX_TREE_ENTRIES, TYPE_TREE};+use crate::store::reader::Store;++pub const KIND_FILE: u8 = 1;+pub const KIND_EXECUTABLE: u8 = 2;+pub const KIND_SYMLINK: u8 = 3;+pub const KIND_SUBTREE: u8 = 4;+pub const KIND_SUBMODULE: u8 = 5;+pub const KIND_CONFLICT: u8 = 6;+pub const KIND_MISSING: u8 = 0;++#[derive(Clone)]+pub struct TreeEntry {+ pub name: Vec<u8>,+ pub kind: u8,+ pub target: Id,+}++#[derive(Clone)]+pub struct Tree {+ pub entries: Vec<TreeEntry>,+}++#[derive(Clone)]+pub struct FlatEntry {+ pub path: Vec<u8>,+ pub kind: u8,+ pub target: Id,+}++fn valid_kind(kind: u8) -> bool {+ (KIND_FILE..=KIND_CONFLICT).contains(&kind)+}++pub fn encode(entries: &[TreeEntry]) -> Result<Vec<u8>> {+ let mut writer = Writer::with_capacity(entries.len() * 48 + 8);+ writer.varint(entries.len() as u64);+ let mut previous: Option<&[u8]> = None;+ for entry in entries {+ if !valid_name(&entry.name) {+ return Err(Error::new("invalid tree entry name"));+ }+ if previous.is_some_and(|name| name >= entry.name.as_slice()) {+ return Err(Error::new("tree entries are not sorted"));+ }+ if !valid_kind(entry.kind) {+ return Err(Error::new("invalid tree entry kind"));+ }+ writer.bytes(&entry.name);+ writer.u8(entry.kind);+ writer.id(entry.target);+ previous = Some(&entry.name);+ }+ Ok(writer.into_vec())+}++pub fn decode(body: &[u8]) -> Result<Tree> {+ let mut reader = Reader::new(body);+ let count = reader.varint()?;+ let count = usize::try_from(count).map_err(|_| Error::new("tree too large"))?;+ if count > MAX_TREE_ENTRIES {+ return Err(Error::new("tree entry limit exceeded"));+ }+ let mut entries = Vec::with_capacity(count);+ let mut previous: Option<Vec<u8>> = None;+ for _ in 0..count {+ let name = reader.bytes(MAX_NAME_LEN)?.to_vec();+ if !valid_name(&name) {+ return Err(Error::new("invalid tree entry name"));+ }+ if previous.as_ref().is_some_and(|value| value >= &name) {+ return Err(Error::new("tree entries are not sorted"));+ }+ let kind = reader.u8()?;+ if !valid_kind(kind) {+ return Err(Error::new("invalid tree entry kind"));+ }+ let target = reader.id()?;+ entries.push(TreeEntry { name, kind, target });+ previous = Some(entries.last().unwrap().name.clone());+ }+ reader.finish()?;+ Ok(Tree { entries })+}++fn flatten_into(+ store: &mut Store,+ tree_id: Id,+ prefix: &mut Vec<u8>,+ output: &mut Vec<FlatEntry>,+ depth: usize,+) -> Result<()> {+ if depth > 4096 {+ return Err(Error::new("tree nesting too deep"));+ }+ let body = store+ .body(tree_id, TYPE_TREE)?+ .ok_or_else(|| Error::new(format!("missing tree {}", tree_id.to_hex())))?;+ let tree = decode(&body)?;+ for entry in tree.entries {+ let old_length = prefix.len();+ if !prefix.is_empty() {+ prefix.push(b'/');+ }+ prefix.extend_from_slice(&entry.name);+ if entry.kind == KIND_SUBTREE {+ flatten_into(store, entry.target, prefix, output, depth + 1)?;+ } else {+ output.push(FlatEntry {+ path: prefix.clone(),+ kind: entry.kind,+ target: entry.target,+ });+ }+ prefix.truncate(old_length);+ }+ Ok(())+}++pub fn flatten(store: &mut Store, tree_id: Id) -> Result<Vec<FlatEntry>> {+ let mut output = Vec::new();+ let mut prefix = Vec::new();+ flatten_into(store, tree_id, &mut prefix, &mut output, 0)?;+ output.sort_by(|left, right| left.path.cmp(&right.path));+ Ok(output)+}++pub fn find_flat<'a>(entries: &'a [FlatEntry], path: &[u8]) -> Option<&'a FlatEntry> {+ entries+ .binary_search_by(|entry| entry.path.as_slice().cmp(path))+ .ok()+ .map(|index| &entries[index])+}++pub fn find_entry(tree: &Tree, name: &[u8]) -> Option<usize> {+ tree.entries+ .binary_search_by(|entry| entry.name.as_slice().cmp(name))+ .ok()+}+--- /dev/null+++ b/veins-rust/src/object/view.rs@@ -0,0 +1,320 @@+use crate::encoding::{Reader, Writer};+use crate::error::{Error, Result};+use crate::object::id::Id;+use crate::object::{MAX_MESSAGE_LEN, MAX_NAME_LEN};++#[derive(Clone, Default)]+pub struct TargetSet {+ pub adds: Vec<Option<Id>>,+ pub removes: Vec<Option<Id>>,+}++#[derive(Clone, Default)]+pub struct Bookmark {+ pub name: Vec<u8>,+ pub targets: TargetSet,+}++#[derive(Clone, Default)]+pub struct TagRef {+ pub name: Vec<u8>,+ pub target: Id,+}++#[derive(Clone, Default)]+pub struct RemoteRef {+ pub remote: Vec<u8>,+ pub name: Vec<u8>,+ pub target: Id,+}++#[derive(Clone, Default)]+pub struct WorkspaceRef {+ pub workspace: Vec<u8>,+ pub target: Id,+}++#[derive(Clone, Default)]+pub struct View {+ pub heads: Vec<Id>,+ pub bookmarks: Vec<Bookmark>,+ pub tags: Vec<TagRef>,+ pub remote_refs: Vec<RemoteRef>,+ pub working_copies: Vec<WorkspaceRef>,+}++#[derive(Clone, Default)]+pub struct TimeMs {+ pub millis: i64,+ pub tz_min: i16,+}++#[derive(Clone, Default)]+pub struct Operation {+ pub parents: Vec<Id>,+ pub view: Id,+ pub start: TimeMs,+ pub end: TimeMs,+ pub hostname: Vec<u8>,+ pub username: Vec<u8>,+ pub description: Vec<u8>,+ pub tags: Vec<(Vec<u8>, Vec<u8>)>,+}++fn read_opt_ids(reader: &mut Reader<'_>, maximum: usize) -> Result<Vec<Option<Id>>> {+ let count = reader.varint()?;+ let count = usize::try_from(count).map_err(|_| Error::new("list too large"))?;+ if count > maximum {+ return Err(Error::new("list limit exceeded"));+ }+ let mut ids = Vec::with_capacity(count);+ for _ in 0..count {+ ids.push(reader.opt_id()?);+ }+ Ok(ids)+}++fn write_opt_ids(writer: &mut Writer, ids: &[Option<Id>]) {+ writer.varint(ids.len() as u64);+ for id in ids {+ writer.opt_id(*id);+ }+}++fn read_target_set(reader: &mut Reader<'_>) -> Result<TargetSet> {+ let adds = read_opt_ids(reader, 64)?;+ let removes = read_opt_ids(reader, 64)?;+ if adds.is_empty() {+ return Err(Error::new("bookmark target set has no adds"));+ }+ if adds.len() != removes.len() + 1 {+ return Err(Error::new("bookmark target set is unbalanced"));+ }+ for add in &adds {+ if removes.contains(add) {+ return Err(Error::new("bookmark target set is not simplified"));+ }+ }+ if adds.len() > 1 && adds.iter().all(|id| id == &adds[0]) {+ return Err(Error::new("bookmark target set has duplicate adds"));+ }+ Ok(TargetSet { adds, removes })+}++fn write_target_set(writer: &mut Writer, targets: &TargetSet) {+ write_opt_ids(writer, &targets.adds);+ write_opt_ids(writer, &targets.removes);+}++fn read_name(reader: &mut Reader<'_>) -> Result<Vec<u8>> {+ let name = reader.bytes(MAX_NAME_LEN)?.to_vec();+ if name.is_empty() || name.contains(&0) {+ return Err(Error::new("invalid view name"));+ }+ Ok(name)+}++pub fn encode_view(view: &View) -> Vec<u8> {+ let mut writer = Writer::with_capacity(256);+ writer.varint(view.heads.len() as u64);+ for head in &view.heads {+ writer.id(*head);+ }+ writer.varint(view.bookmarks.len() as u64);+ for bookmark in &view.bookmarks {+ writer.bytes(&bookmark.name);+ write_target_set(&mut writer, &bookmark.targets);+ }+ writer.varint(view.tags.len() as u64);+ for tag in &view.tags {+ writer.bytes(&tag.name);+ writer.id(tag.target);+ }+ writer.varint(view.remote_refs.len() as u64);+ for reference in &view.remote_refs {+ writer.bytes(&reference.remote);+ writer.bytes(&reference.name);+ writer.id(reference.target);+ }+ writer.varint(view.working_copies.len() as u64);+ for workspace in &view.working_copies {+ writer.bytes(&workspace.workspace);+ writer.id(workspace.target);+ }+ writer.into_vec()+}++pub fn decode_view(body: &[u8]) -> Result<View> {+ let mut reader = Reader::new(body);+ let head_count = reader.varint()?;+ let head_count = usize::try_from(head_count).map_err(|_| Error::new("too many heads"))?;+ if head_count > 1_000_000 {+ return Err(Error::new("head limit exceeded"));+ }+ let mut heads = Vec::with_capacity(head_count);+ let mut previous: Option<Id> = None;+ for _ in 0..head_count {+ let id = reader.id()?;+ if previous.is_some_and(|value| value >= id) {+ return Err(Error::new("heads are not sorted"));+ }+ heads.push(id);+ previous = Some(id);+ }++ let bookmark_count = reader.varint()?;+ let bookmark_count =+ usize::try_from(bookmark_count).map_err(|_| Error::new("too many bookmarks"))?;+ if bookmark_count > 1_000_000 {+ return Err(Error::new("bookmark limit exceeded"));+ }+ let mut bookmarks = Vec::with_capacity(bookmark_count);+ let mut previous_name: Option<Vec<u8>> = None;+ for _ in 0..bookmark_count {+ let name = read_name(&mut reader)?;+ if previous_name.as_ref().is_some_and(|value| value >= &name) {+ return Err(Error::new("bookmarks are not sorted"));+ }+ let targets = read_target_set(&mut reader)?;+ bookmarks.push(Bookmark { name: name.clone(), targets });+ previous_name = Some(name);+ }++ let tag_count = reader.varint()?;+ let tag_count = usize::try_from(tag_count).map_err(|_| Error::new("too many tags"))?;+ if tag_count > 1_000_000 {+ return Err(Error::new("tag limit exceeded"));+ }+ let mut tags = Vec::with_capacity(tag_count);+ let mut previous_name: Option<Vec<u8>> = None;+ for _ in 0..tag_count {+ let name = read_name(&mut reader)?;+ if previous_name.as_ref().is_some_and(|value| value >= &name) {+ return Err(Error::new("tags are not sorted"));+ }+ let target = reader.id()?;+ tags.push(TagRef { name: name.clone(), target });+ previous_name = Some(name);+ }++ let remote_count = reader.varint()?;+ let remote_count = usize::try_from(remote_count).map_err(|_| Error::new("too many remote refs"))?;+ if remote_count > 1_000_000 {+ return Err(Error::new("remote ref limit exceeded"));+ }+ let mut remote_refs = Vec::with_capacity(remote_count);+ let mut previous_pair: Option<(Vec<u8>, Vec<u8>)> = None;+ for _ in 0..remote_count {+ let remote = read_name(&mut reader)?;+ let name = read_name(&mut reader)?;+ let key = (remote.clone(), name.clone());+ if previous_pair.as_ref().is_some_and(|value| value >= &key) {+ return Err(Error::new("remote refs are not sorted"));+ }+ let target = reader.id()?;+ remote_refs.push(RemoteRef { remote, name, target });+ previous_pair = Some(key);+ }++ let workspace_count = reader.varint()?;+ let workspace_count =+ usize::try_from(workspace_count).map_err(|_| Error::new("too many workspaces"))?;+ if workspace_count > 1_000_000 {+ return Err(Error::new("workspace limit exceeded"));+ }+ let mut working_copies = Vec::with_capacity(workspace_count);+ let mut previous_name: Option<Vec<u8>> = None;+ for _ in 0..workspace_count {+ let workspace = read_name(&mut reader)?;+ if previous_name.as_ref().is_some_and(|value| value >= &workspace) {+ return Err(Error::new("workspaces are not sorted"));+ }+ let target = reader.id()?;+ working_copies.push(WorkspaceRef {+ workspace: workspace.clone(),+ target,+ });+ previous_name = Some(workspace);+ }++ reader.finish()?;+ Ok(View {+ heads,+ bookmarks,+ tags,+ remote_refs,+ working_copies,+ })+}++pub fn encode_operation(operation: &Operation) -> Vec<u8> {+ let mut writer = Writer::with_capacity(256);+ writer.varint(operation.parents.len() as u64);+ for parent in &operation.parents {+ writer.id(*parent);+ }+ writer.id(operation.view);+ writer.i64le(operation.start.millis);+ writer.i16le(operation.start.tz_min);+ writer.i64le(operation.end.millis);+ writer.i16le(operation.end.tz_min);+ writer.bytes(&operation.hostname);+ writer.bytes(&operation.username);+ writer.bytes(&operation.description);+ writer.varint(operation.tags.len() as u64);+ for (key, value) in &operation.tags {+ writer.bytes(key);+ writer.bytes(value);+ }+ writer.into_vec()+}++pub fn decode_operation(body: &[u8]) -> Result<Operation> {+ let mut reader = Reader::new(body);+ let parent_count = reader.varint()?;+ let parent_count = usize::try_from(parent_count).map_err(|_| Error::new("too many parents"))?;+ if parent_count > 1024 {+ return Err(Error::new("parent limit exceeded"));+ }+ let mut parents = Vec::with_capacity(parent_count);+ for _ in 0..parent_count {+ parents.push(reader.id()?);+ }+ let view = reader.id()?;+ let start = TimeMs {+ millis: reader.i64le()?,+ tz_min: reader.i16le()?,+ };+ let end = TimeMs {+ millis: reader.i64le()?,+ tz_min: reader.i16le()?,+ };+ let hostname = reader.bytes(MAX_NAME_LEN)?.to_vec();+ let username = reader.bytes(MAX_NAME_LEN)?.to_vec();+ let description = reader.bytes(MAX_MESSAGE_LEN)?.to_vec();+ let tag_count = reader.varint()?;+ let tag_count = usize::try_from(tag_count).map_err(|_| Error::new("too many tags"))?;+ if tag_count > 1024 {+ return Err(Error::new("tag limit exceeded"));+ }+ let mut tags = Vec::with_capacity(tag_count);+ for _ in 0..tag_count {+ let key = reader.bytes(MAX_NAME_LEN)?.to_vec();+ if key.is_empty() {+ return Err(Error::new("empty operation tag key"));+ }+ let value = reader.bytes(MAX_MESSAGE_LEN)?.to_vec();+ tags.push((key, value));+ }+ reader.finish()?;+ Ok(Operation {+ parents,+ view,+ start,+ end,+ hostname,+ username,+ description,+ tags,+ })+}--- /dev/null+++ b/veins-rust/src/store/graph.rs@@ -0,0 +1,314 @@+use std::collections::HashSet;++use crate::error::{Error, Result};+use crate::object::blob::{self, BlobForm};+use crate::object::commit::{self, Commit};+use crate::object::id::{is_hex_prefix, prefix_matches, Id};+use crate::object::tree::{self, FlatEntry, KIND_MISSING};+use crate::object::view::View;+use crate::object::{TYPE_BLOB, TYPE_CHUNK, TYPE_COMMIT};+use crate::store::ops;+use crate::store::reader::Store;++pub fn load_commit(store: &mut Store, id: Id) -> Result<Option<Commit>> {+ let Some(body) = store.body(id, TYPE_COMMIT)? else {+ return Ok(None);+ };+ Ok(Some(commit::decode(&body)?))+}++pub fn has_changes(store: &mut Store, commit: &Commit) -> Result<bool> {+ if let Some(parent) = commit.parents.first() {+ let Some(parent) = load_commit(store, *parent)? else {+ return Ok(true);+ };+ return Ok(parent.root_tree != commit.root_tree);+ }+ Ok(!tree::flatten(store, commit.root_tree)?.is_empty())+}++pub fn collect_commits(store: &mut Store, start: &[Id]) -> Result<Vec<Id>> {+ let mut output = Vec::new();+ let mut stack = Vec::new();+ let mut seen = HashSet::new();+ for id in start {+ if seen.insert(*id) {+ stack.push(*id);+ }+ }+ while let Some(id) = stack.pop() {+ output.push(id);+ if let Some(commit) = load_commit(store, id)? {+ for parent in commit.parents {+ if seen.insert(parent) {+ stack.push(parent);+ }+ }+ }+ }+ Ok(output)+}++pub fn view_roots(view: &View) -> Vec<Id> {+ let mut roots = Vec::new();+ let mut add = |id: Id| {+ if !roots.contains(&id) {+ roots.push(id);+ }+ };+ for head in &view.heads {+ add(*head);+ }+ for bookmark in &view.bookmarks {+ for id in bookmark.targets.adds.iter().flatten() {+ add(*id);+ }+ }+ for tag in &view.tags {+ add(tag.target);+ }+ for workspace in &view.working_copies {+ add(workspace.target);+ }+ roots+}++pub fn all_commits(store: &mut Store, view: &View) -> Result<Vec<Id>> {+ collect_commits(store, &view_roots(view))+}++pub fn bookmark_target(view: &View, name: &[u8]) -> Option<Id> {+ view.bookmarks.iter().find_map(|bookmark| {+ if bookmark.name == name+ && bookmark.targets.adds.len() == 1+ && bookmark.targets.adds[0].is_some()+ {+ bookmark.targets.adds[0]+ } else {+ None+ }+ })+}++pub fn resolve_revision(store: &mut Store, view: &View, revision: &str) -> Result<Option<Id>> {+ if revision.is_empty() || revision == "@" {+ return Ok(ops::working_copy_id(view));+ }+ if let Some(id) = bookmark_target(view, revision.as_bytes()) {+ return Ok(Some(id));+ }+ if let Some(id) = view+ .tags+ .iter()+ .find(|tag| tag.name == revision.as_bytes())+ .map(|tag| tag.target)+ {+ return Ok(Some(id));+ }+ if let Some(id) = view.remote_refs.iter().find_map(|reference| {+ let mut joined = reference.remote.clone();+ joined.push(b'/');+ joined.extend_from_slice(&reference.name);+ (joined == revision.as_bytes()).then_some(reference.target)+ }) {+ return Ok(Some(id));+ }++ let ids = all_commits(store, view)?;+ let mut matches = Vec::new();+ if is_hex_prefix(revision) {+ for id in &ids {+ if prefix_matches(&id.to_hex(), revision) {+ matches.push(*id);+ }+ }+ }+ if matches.is_empty() {+ for id in &ids {+ if let Some(commit) = load_commit(store, *id)? {+ let encoded = base32_encode(commit.change_id);+ if prefix_matches(&encoded, revision) {+ matches.push(*id);+ }+ }+ }+ }+ if matches.len() == 1 {+ Ok(Some(matches[0]))+ } else {+ Ok(None)+ }+}++pub fn base32_encode(value: [u8; 16]) -> String {+ const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";+ let mut output = String::with_capacity(26);+ let mut buffer = 0u64;+ let mut bits = 0usize;+ for byte in value {+ buffer = (buffer << 8) | u64::from(byte);+ bits += 8;+ while bits >= 5 {+ let shift = bits - 5;+ let index = ((buffer >> shift) & 31) as usize;+ output.push(ALPHABET[index] as char);+ bits = shift;+ }+ if bits == 0 {+ buffer = 0;+ } else {+ buffer &= (1u64 << bits) - 1;+ }+ }+ if bits > 0 {+ output.push(ALPHABET[((buffer << (5 - bits)) & 31) as usize] as char);+ }+ output+}++pub fn short_change_id(ids: &[String], index: usize) -> String {+ let target = &ids[index];+ let mut length = 4.min(target.len());+ while length < target.len() {+ let prefix = &target[..length];+ let unique = ids.iter().enumerate().all(|(other_index, other)| {+ other_index == index || other == target || !other.starts_with(prefix)+ });+ if unique {+ break;+ }+ length += 1;+ }+ target[..length].to_string()+}++fn append_blob(store: &Store, id: Id, output: &mut Vec<u8>, depth: usize) -> Result<bool> {+ if depth > 64 {+ return Err(Error::new("blob nesting too deep"));+ }+ let Some(body) = store.body_loaded(id, TYPE_BLOB)? else {+ return Ok(false);+ };+ let blob = blob::decode(&body)?;+ match blob.form {+ BlobForm::Inline => {+ output.extend_from_slice(&blob.data);+ }+ BlobForm::Leaf => {+ for entry in blob.entries {+ let Some(chunk) = store.body_loaded(entry.id, TYPE_CHUNK)? else {+ return Ok(false);+ };+ output.extend_from_slice(&chunk);+ }+ }+ BlobForm::Interior => {+ for entry in blob.entries {+ if !append_blob(store, entry.id, output, depth + 1)? {+ return Ok(false);+ }+ }+ }+ }+ Ok(true)+}++pub fn read_blob_loaded(store: &Store, id: Id) -> Result<Option<Vec<u8>>> {+ let mut output = Vec::new();+ if append_blob(store, id, &mut output, 0)? {+ Ok(Some(output))+ } else {+ Ok(None)+ }+}++pub fn read_blob(store: &mut Store, id: Id) -> Result<Option<Vec<u8>>> {+ store.preload()?;+ read_blob_loaded(store, id)+}++#[derive(Clone)]+pub struct TreeChange {+ pub path: Vec<u8>,+ pub old_kind: u8,+ pub new_kind: u8,+ pub old_id: Option<Id>,+ pub new_id: Option<Id>,+}++pub fn compare_trees(+ store: &mut Store,+ old_tree: Option<Id>,+ new_tree: Option<Id>,+) -> Result<Vec<TreeChange>> {+ let old_entries = match old_tree {+ Some(id) => tree::flatten(store, id)?,+ None => Vec::new(),+ };+ let new_entries = match new_tree {+ Some(id) => tree::flatten(store, id)?,+ None => Vec::new(),+ };+ let mut changes = Vec::new();+ let mut old_index = 0;+ let mut new_index = 0;+ while old_index < old_entries.len() || new_index < new_entries.len() {+ let ordering = if old_index >= old_entries.len() {+ std::cmp::Ordering::Greater+ } else if new_index >= new_entries.len() {+ std::cmp::Ordering::Less+ } else {+ old_entries[old_index]+ .path+ .cmp(&new_entries[new_index].path)+ };+ match ordering {+ std::cmp::Ordering::Less => {+ let entry = &old_entries[old_index];+ changes.push(TreeChange {+ path: entry.path.clone(),+ old_kind: entry.kind,+ new_kind: KIND_MISSING,+ old_id: Some(entry.target),+ new_id: None,+ });+ old_index += 1;+ }+ std::cmp::Ordering::Greater => {+ let entry = &new_entries[new_index];+ changes.push(TreeChange {+ path: entry.path.clone(),+ old_kind: KIND_MISSING,+ new_kind: entry.kind,+ old_id: None,+ new_id: Some(entry.target),+ });+ new_index += 1;+ }+ std::cmp::Ordering::Equal => {+ let old = &old_entries[old_index];+ let new = &new_entries[new_index];+ if old.kind != new.kind || old.target != new.target {+ changes.push(TreeChange {+ path: old.path.clone(),+ old_kind: old.kind,+ new_kind: new.kind,+ old_id: Some(old.target),+ new_id: Some(new.target),+ });+ }+ old_index += 1;+ new_index += 1;+ }+ }+ }+ Ok(changes)+}++pub fn flatten(store: &mut Store, tree_id: Id) -> Result<Vec<FlatEntry>> {+ tree::flatten(store, tree_id)+}++pub fn tree_conflicted(_store: &mut Store, _tree_id: Id) -> bool {+ false+}--- /dev/null+++ b/veins-rust/src/store/index.rs@@ -0,0 +1,120 @@+use crate::encoding::Reader;+use crate::error::{Error, Result};+use crate::object::id::{hash_bytes, Id};++#[derive(Clone)]+pub struct IndexEntry {+ pub id: Id,+ pub offset: u64,+}++#[derive(Clone)]+pub struct Index {+ pub entries: Vec<IndexEntry>,+ pub pack_trailer: [u8; 32],+}++impl Index {+ pub fn find(&self, id: Id) -> Option<usize> {+ self.entries+ .binary_search_by(|entry| entry.id.0.cmp(&id.0))+ .ok()+ }+}++pub fn decode(data: &[u8], expected_pack_trailer: Option<[u8; 32]>) -> Result<Index> {+ const BASE: usize = 1032 + 64;+ if data.len() < BASE {+ return Err(Error::new("index is truncated"));+ }+ if &data[..4] != b"VIX1" {+ return Err(Error::new("invalid index magic"));+ }+ let mut reader = Reader::new(data);+ reader.raw(4)?;+ let version = reader.u32le()?;+ if version != 1 {+ return Err(Error::new("unsupported index version"));+ }+ let mut fanout = [0u32; 256];+ let mut previous = 0u32;+ for slot in &mut fanout {+ let value = reader.u32le()?;+ if value < previous {+ return Err(Error::new("index fanout is not sorted"));+ }+ previous = value;+ *slot = value;+ }+ let body = data.len() - BASE;+ if !body.is_multiple_of(40) {+ return Err(Error::new("index body has an invalid length"));+ }+ let count = body / 40;+ if count != fanout[255] as usize {+ return Err(Error::new("index fanout does not match entry count"));+ }+ let mut entries: Vec<IndexEntry> = Vec::with_capacity(count);+ for index in 0..count {+ let id = reader.id()?;+ if index > 0 && entries[index - 1].id.0 >= id.0 {+ return Err(Error::new("index ids are not sorted"));+ }+ entries.push(IndexEntry { id, offset: 0 });+ }+ for entry in &mut entries {+ entry.offset = reader.u64le()?;+ }+ let mut pack_trailer = [0u8; 32];+ pack_trailer.copy_from_slice(reader.raw(32)?);+ let trailer_offset = data.len() - 32;+ if hash_bytes(&data[..trailer_offset])[..] != data[trailer_offset..] {+ return Err(Error::new("index checksum mismatch"));+ }+ if expected_pack_trailer.is_some_and(|value| value != pack_trailer) {+ return Err(Error::new("index pack trailer mismatch"));+ }+ let mut counts = [0u32; 256];+ for entry in &entries {+ counts[entry.id.0[0] as usize] += 1;+ }+ let mut running = 0u32;+ for index in 0..256 {+ running += counts[index];+ if running != fanout[index] {+ return Err(Error::new("index fanout is inconsistent"));+ }+ }+ Ok(Index {+ entries,+ pack_trailer,+ })+}++pub fn encode(entries: &[IndexEntry], pack_trailer: [u8; 32]) -> Vec<u8> {+ use crate::encoding::Writer;++ let mut counts = [0u32; 256];+ for entry in entries {+ counts[entry.id.0[0] as usize] += 1;+ }+ let mut writer = Writer::with_capacity(entries.len() * 40 + 128);+ writer.raw(b"VIX1");+ writer.u32le(1);+ let mut running = 0u32;+ for count in counts {+ running += count;+ writer.u32le(running);+ }+ for entry in entries {+ writer.id(entry.id);+ }+ for entry in entries {+ writer.u64le(entry.offset);+ }+ writer.raw(&pack_trailer);+ let mut data = writer.into_vec();+ let digest = hash_bytes(&data);+ data.extend_from_slice(&digest);+ data+}--- /dev/null+++ b/veins-rust/src/store/layout.rs@@ -0,0 +1,165 @@+use std::fs::{self, File};+use std::io::Write;+use std::os::unix::io::AsRawFd;+use std::path::{Path, PathBuf};++use crate::error::{Error, Result};++pub fn veins_dir(root: &Path) -> PathBuf {+ root.join(".veins")+}++pub fn packs_dir(root: &Path) -> PathBuf {+ veins_dir(root).join("store").join("packs")+}++pub fn tmp_dir(root: &Path) -> PathBuf {+ veins_dir(root).join("store").join("tmp")+}++pub fn op_heads_dir(root: &Path) -> PathBuf {+ veins_dir(root).join("op-heads")+}++pub fn git_map_dir(root: &Path) -> PathBuf {+ veins_dir(root).join("git-map")+}++pub fn working_copy_dir(root: &Path) -> PathBuf {+ veins_dir(root).join("working-copy")+}++pub fn resolutions_dir(root: &Path) -> PathBuf {+ veins_dir(root).join("resolutions")+}++pub fn config_path(root: &Path) -> PathBuf {+ veins_dir(root).join("config")+}++pub fn format_path(root: &Path) -> PathBuf {+ veins_dir(root).join("format")+}++pub fn discover(start: &Path) -> Result<PathBuf> {+ let mut current = fs::canonicalize(start)?;+ loop {+ if format_path(¤t).is_file() {+ return Ok(current);+ }+ match current.parent() {+ Some(parent) => current = parent.to_path_buf(),+ None => return Err(Error::new("not a veins repository")),+ }+ }+}++pub fn init(path: &Path) -> Result<PathBuf> {+ let root = if path.as_os_str().is_empty() {+ PathBuf::from(".")+ } else {+ path.to_path_buf()+ };+ fs::create_dir_all(&root)?;+ let format = format_path(&root);+ let expected = b"veins-store 1";+ if format.exists() {+ let data = fs::read(&format)?;+ if data != expected {+ return Err(Error::new("unsupported repository format"));+ }+ }+ ensure_layout(&root)?;+ if !format.exists() {+ fs::write(&format, expected)?;+ }+ if !config_path(&root).exists() {+ fs::write(config_path(&root), [])?;+ }+ Ok(root)+}++fn ensure_layout(root: &Path) -> Result<()> {+ let directories = [+ veins_dir(root),+ veins_dir(root).join("store"),+ packs_dir(root),+ tmp_dir(root),+ op_heads_dir(root),+ git_map_dir(root),+ git_map_dir(root).join("raw"),+ working_copy_dir(root),+ resolutions_dir(root),+ ];+ for directory in directories {+ fs::create_dir_all(directory)?;+ }+ Ok(())+}++pub fn write_atomic(final_path: &Path, data: &[u8]) -> Result<()> {+ if let Some(parent) = final_path.parent() {+ fs::create_dir_all(parent)?;+ }+ let parent = final_path+ .parent()+ .ok_or_else(|| Error::new("path has no parent"))?;+ let name = final_path+ .file_name()+ .ok_or_else(|| Error::new("path has no file name"))?+ .to_string_lossy();+ let temporary = parent.join(format!(".{name}.tmp"));+ {+ let mut file = File::create(&temporary)?;+ file.write_all(data)?;+ }+ sync_file(&temporary)?;+ fs::rename(&temporary, final_path)?;+ sync_directory(parent);+ Ok(())+}++fn sync_file(path: &Path) -> Result<()> {+ let file = File::open(path)?;+ if unsafe { libc::fsync(file.as_raw_fd()) } != 0 {+ return Err(std::io::Error::last_os_error().into());+ }+ Ok(())+}++fn sync_directory(path: &Path) {+ if let Ok(directory) = File::open(path) {+ unsafe {+ libc::fsync(directory.as_raw_fd());+ }+ }+}++pub fn read_directory(path: &Path) -> Result<Vec<Vec<u8>>> {+ use std::os::unix::ffi::OsStringExt;++ let mut names = Vec::new();+ for entry in fs::read_dir(path)? {+ let entry = entry?;+ names.push(entry.file_name().into_vec());+ }+ names.sort();+ Ok(names)+}++pub fn os_string(bytes: &[u8]) -> std::ffi::OsString {+ use std::os::unix::ffi::OsStringExt;+ std::ffi::OsString::from_vec(bytes.to_vec())+}++pub fn append_file(path: &Path, data: &[u8]) -> Result<()> {+ if let Some(parent) = path.parent() {+ fs::create_dir_all(parent)?;+ }+ let mut file = fs::OpenOptions::new()+ .create(true)+ .append(true)+ .open(path)?;+ file.write_all(data)?;+ Ok(())+}--- /dev/null+++ b/veins-rust/src/store/mod.rs@@ -0,0 +1,11 @@+pub mod graph;+pub mod index;+pub mod layout;+pub mod ops;+pub mod pack;+pub mod reader;+pub mod transaction;+pub mod writer;++pub use reader::Store;+pub use transaction::Txn;--- /dev/null+++ b/veins-rust/src/store/ops.rs@@ -0,0 +1,163 @@+use std::fs;+use std::path::Path;++use crate::error::{Error, Result};+use crate::object::id::Id;+use crate::object::view::{Bookmark, View, WorkspaceRef};+use crate::store::layout;+use crate::store::reader::Store;++pub fn read_heads(root: &Path) -> Result<Vec<Id>> {+ let directory = layout::op_heads_dir(root);+ let mut heads = Vec::new();+ if let Ok(entries) = fs::read_dir(&directory) {+ for entry in entries.flatten() {+ let name = entry.file_name();+ let text = name.to_string_lossy();+ if text.len() == 64+ && let Ok(id) = Id::from_hex(&text)+ {+ heads.push(id);+ }+ }+ }+ heads.sort_by(|left, right| left.0.cmp(&right.0));+ Ok(heads)+}++pub fn write_head(root: &Path, id: Id) -> Result<()> {+ let path = layout::op_heads_dir(root).join(id.to_hex());+ layout::write_atomic(&path, &[])+}++pub fn delete_head(root: &Path, id: Id) -> Result<()> {+ let path = layout::op_heads_dir(root).join(id.to_hex());+ match fs::remove_file(path) {+ Ok(()) => Ok(()),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),+ Err(error) => Err(error.into()),+ }+}++pub fn empty_view() -> View {+ View::default()+}++pub fn current_view(root: &Path, store: &mut Store) -> Result<Option<View>> {+ let heads = read_heads(root)?;+ let Some(head) = heads.first() else {+ return Ok(None);+ };+ let operation = store+ .operation(*head)?+ .ok_or_else(|| Error::new("missing operation state"))?;+ store.view(operation.view)+}++pub fn working_copy_id(view: &View) -> Option<Id> {+ view.working_copies+ .iter()+ .find(|workspace| workspace.workspace == b"default")+ .map(|workspace| workspace.target)+}++pub fn sort_ids(ids: &mut [Id]) {+ ids.sort_by(|left, right| left.0.cmp(&right.0));+}++pub fn sort_view(view: &mut View) {+ view.heads.sort_by(|left, right| left.0.cmp(&right.0));+ view.bookmarks+ .sort_by(|left, right| left.name.cmp(&right.name));+ view.tags.sort_by(|left, right| left.name.cmp(&right.name));+ view.remote_refs.sort_by(|left, right| {+ left.remote+ .cmp(&right.remote)+ .then_with(|| left.name.cmp(&right.name))+ });+ view.working_copies+ .sort_by(|left, right| left.workspace.cmp(&right.workspace));+}++pub fn add_unique_head(view: &mut View, id: Id) {+ if !view.heads.contains(&id) {+ view.heads.push(id);+ }+}++pub fn rebuild_heads(view: &mut View) {+ view.heads.clear();+ let mut ids = Vec::new();+ for bookmark in &view.bookmarks {+ for id in bookmark.targets.adds.iter().flatten() {+ ids.push(*id);+ }+ }+ for tag in &view.tags {+ ids.push(tag.target);+ }+ for workspace in &view.working_copies {+ ids.push(workspace.target);+ }+ for id in ids {+ add_unique_head(view, id);+ }+ sort_ids(&mut view.heads);+}++pub fn set_workspace(view: &mut View, id: Id) {+ for workspace in &mut view.working_copies {+ if workspace.workspace == b"default" {+ workspace.target = id;+ return;+ }+ }+ view.working_copies.push(WorkspaceRef {+ workspace: b"default".to_vec(),+ target: id,+ });+ view.working_copies+ .sort_by(|left, right| left.workspace.cmp(&right.workspace));+}++pub fn remove_head(view: &mut View, id: Id) {+ view.heads.retain(|head| *head != id);+}++pub fn move_bookmarks(view: &mut View, old_id: Id, new_id: Id) {+ if old_id == new_id {+ return;+ }+ for bookmark in &mut view.bookmarks {+ if bookmark.targets.adds.contains(&Some(old_id)) {+ bookmark.targets.adds = vec![Some(new_id)];+ bookmark.targets.removes.clear();+ }+ }+}++pub fn find_bookmark(view: &View, name: &[u8]) -> Option<usize> {+ view.bookmarks+ .iter()+ .position(|bookmark| bookmark.name == name)+}++pub fn bookmark_points_at(bookmark: &Bookmark, target: Id) -> bool {+ bookmark.targets.adds.len() == 1 && bookmark.targets.adds[0] == Some(target)+}++pub fn tag_names(view: &View, id: Id) -> Vec<Vec<u8>> {+ view.tags+ .iter()+ .filter(|tag| tag.target == id)+ .map(|tag| tag.name.clone())+ .collect()+}++pub fn bookmark_names(view: &View, id: Id) -> Vec<Vec<u8>> {+ view.bookmarks+ .iter()+ .filter(|bookmark| bookmark.targets.adds.contains(&Some(id)))+ .map(|bookmark| bookmark.name.clone())+ .collect()+}--- /dev/null+++ b/veins-rust/src/store/pack.rs@@ -0,0 +1,213 @@+use std::collections::HashSet;++use rayon::prelude::*;++use crate::encoding::Reader;+use crate::error::{Error, Result};+use crate::object::id::{hash_bytes, Id};+use crate::object::{+ type_valid, RawObject, MAX_CHUNK_LEN, MAX_OBJECT_BODY, TYPE_CHUNK,+};+use crate::store::index::{self, IndexEntry};++#[derive(Clone)]+pub struct PackRecord {+ pub id: Id,+ pub kind: u8,+ pub compression: u8,+ pub raw_len: u64,+ pub stored_len: u64,+ pub data_offset: usize,+ pub record_offset: usize,+}++pub struct Pack {+ pub data: Vec<u8>,+ pub records: Vec<PackRecord>,+ pub trailer: [u8; 32],+}++impl Pack {+ pub fn find_by_offset(&self, offset: u64) -> Option<usize> {+ self.records+ .binary_search_by(|record| record.record_offset.cmp(&(offset as usize)))+ .ok()+ }++ pub fn get(&self, index: usize) -> Result<Vec<u8>> {+ let record = self+ .records+ .get(index)+ .ok_or_else(|| Error::new("pack record out of range"))?;+ if record.raw_len == 0 {+ return Ok(Vec::new());+ }+ let raw_len = usize::try_from(record.raw_len).map_err(|_| Error::new("raw length overflow"))?;+ let stored_len =+ usize::try_from(record.stored_len).map_err(|_| Error::new("stored length overflow"))?;+ let end = record+ .data_offset+ .checked_add(stored_len)+ .ok_or_else(|| Error::new("pack offset overflow"))?;+ if end > self.data.len() {+ return Err(Error::new("pack record exceeds file"));+ }+ let stored = &self.data[record.data_offset..end];+ if record.compression == 0 {+ return Ok(stored.to_vec());+ }+ zstd::bulk::decompress(stored, raw_len).map_err(|error| Error::new(error.to_string()))+ }+}++fn record_limit(kind: u8) -> usize {+ if kind == TYPE_CHUNK {+ MAX_CHUNK_LEN+ } else {+ MAX_OBJECT_BODY+ }+}++pub fn decode(data: Vec<u8>) -> Result<Pack> {+ const HEADER: usize = 16;+ const RECORD_MIN: usize = 36;+ if data.len() < HEADER + 32 {+ return Err(Error::new("pack is truncated"));+ }+ if &data[..4] != b"VPK1" {+ return Err(Error::new("invalid pack magic"));+ }+ let mut header = Reader::new(&data[..HEADER]);+ header.raw(4)?;+ let version = header.u32le()?;+ if version != 1 {+ return Err(Error::new("unsupported pack version"));+ }+ let count = header.u64le()?;+ let body_end = data.len() - 32;+ if hash_bytes(&data[..body_end])[..] != data[body_end..] {+ return Err(Error::new("pack checksum mismatch"));+ }+ if count > (body_end / RECORD_MIN) as u64 {+ return Err(Error::new("pack record count is impossible"));+ }+ let count = usize::try_from(count).map_err(|_| Error::new("pack record count overflow"))?;+ let mut records = Vec::with_capacity(count);+ {+ let mut reader = Reader::new(&data[..body_end]);+ reader.raw(HEADER)?;+ for _ in 0..count {+ let record_offset = reader.offset();+ let id = reader.id()?;+ let kind = reader.u8()?;+ if !type_valid(kind) {+ return Err(Error::new("invalid pack object type"));+ }+ let compression = reader.u8()?;+ if compression > 1 {+ return Err(Error::new("invalid pack compression"));+ }+ let raw_len = reader.varint()?;+ let stored_len = reader.varint()?;+ if raw_len == 0 || raw_len > record_limit(kind) as u64 {+ return Err(Error::new("invalid pack record length"));+ }+ if compression == 0 && raw_len != stored_len {+ return Err(Error::new("uncompressed pack record length mismatch"));+ }+ if stored_len > reader.remaining() as u64 {+ return Err(Error::new("pack record exceeds body"));+ }+ let data_offset = reader.offset();+ reader.raw(stored_len as usize)?;+ records.push(PackRecord {+ id,+ kind,+ compression,+ raw_len,+ stored_len,+ data_offset,+ record_offset,+ });+ }+ if reader.offset() != body_end {+ return Err(Error::new("pack has trailing bytes"));+ }+ }+ let mut trailer = [0u8; 32];+ trailer.copy_from_slice(&data[body_end..]);+ Ok(Pack {+ data,+ records,+ trailer,+ })+}++pub struct PackOutput {+ pub pack: Vec<u8>,+ pub index: Vec<u8>,+ pub name: String,+ pub count: usize,+}++fn compress_object(body: &[u8]) -> (u8, Vec<u8>) {+ if body.len() < 64 {+ return (0, body.to_vec());+ }+ match zstd::bulk::compress(body, 1) {+ Ok(compressed) if compressed.len() < body.len() => (1, compressed),+ _ => (0, body.to_vec()),+ }+}++pub fn encode(objects: &[RawObject]) -> PackOutput {+ let mut seen = HashSet::new();+ let mut unique = Vec::new();+ for object in objects {+ if seen.insert(object.id) {+ unique.push(object);+ }+ }+ let stored: Vec<(u8, Vec<u8>)> = unique+ .par_iter()+ .map(|object| compress_object(&object.body))+ .collect();++ let estimate = unique+ .iter()+ .map(|object| object.body.len() + 64)+ .sum::<usize>()+ + 16;+ let mut writer = crate::encoding::Writer::with_capacity(estimate);+ writer.raw(b"VPK1");+ writer.u32le(1);+ writer.u64le(0);+ let mut metas = Vec::with_capacity(unique.len());+ for (object, (compression, data)) in unique.iter().zip(stored.iter()) {+ let offset = writer.len() as u64;+ writer.id(object.id);+ writer.u8(object.kind);+ writer.u8(*compression);+ writer.varint(object.body.len() as u64);+ writer.varint(data.len() as u64);+ writer.raw(data);+ metas.push(IndexEntry {+ id: object.id,+ offset,+ });+ }+ let mut pack = writer.into_vec();+ pack[8..16].copy_from_slice(&(metas.len() as u64).to_le_bytes());+ let digest = hash_bytes(&pack);+ pack.extend_from_slice(&digest);+ let mut by_id = metas;+ by_id.sort_by(|left, right| left.id.0.cmp(&right.id.0));+ let index = index::encode(&by_id, digest);+ let name = Id(digest).to_hex();+ PackOutput {+ pack,+ index,+ name,+ count: unique.len(),+ }+}--- /dev/null+++ b/veins-rust/src/store/reader.rs@@ -0,0 +1,215 @@+use std::fs;+use std::path::{Path, PathBuf};+use std::time::UNIX_EPOCH;++use crate::error::{Error, Result};+use crate::object::id::object_id;+use crate::object::id::Id;+use crate::object::view::{self, Operation, View};+use crate::store::index::{self, Index};+use crate::store::layout;+use crate::store::pack::{self, Pack};++#[derive(Clone, Copy)]+pub struct Location {+ pub pack: usize,+ pub record: usize,+ pub kind: u8,+}++struct PackFile {+ path: PathBuf,+ mtime: u128,+ index: Option<Index>,+ pack: Option<Pack>,+}++pub struct Store {+ root: PathBuf,+ packs: Vec<PackFile>,+}++impl Store {+ pub fn open(root: &Path) -> Result<Self> {+ let mut store = Self {+ root: root.to_path_buf(),+ packs: Vec::new(),+ };+ store.refresh()?;+ Ok(store)+ }++ pub fn root(&self) -> &Path {+ &self.root+ }++ pub fn refresh(&mut self) -> Result<()> {+ let directory = layout::packs_dir(&self.root);+ let mut known = std::collections::HashSet::new();+ for pack in &self.packs {+ known.insert(pack.path.clone());+ }+ if let Ok(entries) = fs::read_dir(&directory) {+ for entry in entries.flatten() {+ let path = entry.path();+ if path.extension().and_then(|value| value.to_str()) != Some("vpack") {+ continue;+ }+ if known.contains(&path) {+ continue;+ }+ let mtime = fs::metadata(&path)+ .and_then(|metadata| metadata.modified())+ .ok()+ .and_then(|time| time.duration_since(UNIX_EPOCH).ok())+ .map(|duration| duration.as_nanos())+ .unwrap_or(0);+ self.packs.push(PackFile {+ path,+ mtime,+ index: None,+ pack: None,+ });+ }+ }+ self.packs.sort_by(|left, right| right.mtime.cmp(&left.mtime));+ Ok(())+ }++ fn ensure_index(&mut self, pack_index: usize) -> Result<()> {+ if self.packs[pack_index].index.is_some() {+ return Ok(());+ }+ let path = self.packs[pack_index].path.clone();+ let stem = path+ .file_stem()+ .ok_or_else(|| Error::new("pack path has no stem"))?+ .to_string_lossy()+ .to_string();+ let index_path = path.with_file_name(format!("{stem}.vidx"));+ let data = fs::read(&index_path)?;+ let decoded = index::decode(&data, None)?;+ if stem != Id(decoded.pack_trailer).to_hex() {+ return Err(Error::new("index name does not match pack trailer"));+ }+ self.packs[pack_index].index = Some(decoded);+ Ok(())+ }++ fn ensure_pack(&mut self, pack_index: usize) -> Result<()> {+ if self.packs[pack_index].pack.is_some() {+ return Ok(());+ }+ self.ensure_index(pack_index)?;+ let path = self.packs[pack_index].path.clone();+ let data = fs::read(&path)?;+ let decoded = pack::decode(data)?;+ let expected = self.packs[pack_index]+ .index+ .as_ref()+ .ok_or_else(|| Error::new("missing index"))?+ .pack_trailer;+ if decoded.trailer != expected {+ return Err(Error::new("pack trailer does not match index"));+ }+ self.packs[pack_index].pack = Some(decoded);+ Ok(())+ }++ pub fn find(&mut self, id: Id) -> Result<Option<Location>> {+ for pack_index in 0..self.packs.len() {+ self.ensure_index(pack_index)?;+ let found = {+ let index = self.packs[pack_index]+ .index+ .as_ref()+ .ok_or_else(|| Error::new("missing index"))?;+ index.find(id).map(|position| index.entries[position].offset)+ };+ let Some(offset) = found else {+ continue;+ };+ self.ensure_pack(pack_index)?;+ let pack = self.packs[pack_index]+ .pack+ .as_ref()+ .ok_or_else(|| Error::new("missing pack"))?;+ let Some(record) = pack.find_by_offset(offset) else {+ continue;+ };+ return Ok(Some(Location {+ pack: pack_index,+ record,+ kind: pack.records[record].kind,+ }));+ }+ Ok(None)+ }++ pub fn body(&mut self, id: Id, expected: u8) -> Result<Option<Vec<u8>>> {+ let Some(location) = self.find(id)? else {+ return Ok(None);+ };+ if location.kind != expected {+ return Ok(None);+ }+ let pack = self.packs[location.pack]+ .pack+ .as_ref()+ .ok_or_else(|| Error::new("missing pack"))?;+ let data = pack.get(location.record)?;+ if object_id(expected, &data) != id {+ return Err(Error::new(format!("object checksum mismatch: {}", id.to_hex())));+ }+ Ok(Some(data))+ }++ pub fn preload(&mut self) -> Result<()> {+ for pack_index in 0..self.packs.len() {+ self.ensure_index(pack_index)?;+ self.ensure_pack(pack_index)?;+ }+ Ok(())+ }++ pub fn body_loaded(&self, id: Id, expected: u8) -> Result<Option<Vec<u8>>> {+ for file in &self.packs {+ let Some(index) = file.index.as_ref() else {+ continue;+ };+ let Some(position) = index.find(id) else {+ continue;+ };+ let offset = index.entries[position].offset;+ let Some(pack) = file.pack.as_ref() else {+ continue;+ };+ let Some(record) = pack.find_by_offset(offset) else {+ continue;+ };+ if pack.records[record].kind != expected {+ continue;+ }+ let data = pack.get(record)?;+ if object_id(expected, &data) != id {+ return Err(Error::new(format!("object checksum mismatch: {}", id.to_hex())));+ }+ return Ok(Some(data));+ }+ Ok(None)+ }++ pub fn view(&mut self, id: Id) -> Result<Option<View>> {+ let Some(body) = self.body(id, crate::object::TYPE_VIEW)? else {+ return Ok(None);+ };+ Ok(Some(view::decode_view(&body)?))+ }++ pub fn operation(&mut self, id: Id) -> Result<Option<Operation>> {+ let Some(body) = self.body(id, crate::object::TYPE_OPERATION)? else {+ return Ok(None);+ };+ Ok(Some(view::decode_operation(&body)?))+ }+}--- /dev/null+++ b/veins-rust/src/store/transaction.rs@@ -0,0 +1,158 @@+use std::path::{Path, PathBuf};++use crate::error::{Error, Result};+use crate::object::id::Id;+use crate::object::view::{+ encode_operation, encode_view, Operation, TimeMs, View,+};+use crate::object::{TYPE_OPERATION, TYPE_VIEW};+use crate::store::ops;+use crate::store::reader::Store;+use crate::store::writer::Writer;+use crate::time;++pub struct Txn {+ root: PathBuf,+ view: View,+ parents: Vec<Id>,+ start_ms: i64,+ writer: Writer,+}++impl Txn {+ pub fn begin(root: &Path, store: &mut Store) -> Result<Self> {+ let heads = ops::read_heads(root)?;+ let view = if heads.is_empty() {+ ops::empty_view()+ } else if heads.len() == 1 {+ load_view(store, heads[0])?+ } else {+ let mut merged = load_view(store, heads[0])?;+ for head in &heads[1..] {+ let extra = load_view(store, *head)?;+ merge_view_into(&mut merged, &extra);+ }+ ops::add_unique_head(&mut merged, heads[0]);+ merged+ };+ let mut view = view;+ ops::sort_view(&mut view);+ Ok(Self {+ root: root.to_path_buf(),+ view,+ parents: heads,+ start_ms: time::now_millis(),+ writer: Writer::default(),+ })+ }++ pub fn view(&self) -> &View {+ &self.view+ }++ pub fn view_mut(&mut self) -> &mut View {+ &mut self.view+ }++ pub fn writer(&mut self) -> &mut Writer {+ &mut self.writer+ }++ pub fn add_object(&mut self, kind: u8, body: Vec<u8>) -> Id {+ self.writer.add(kind, body)+ }++ pub fn add_known(&mut self, kind: u8, id: Id, body: Vec<u8>) -> Id {+ self.writer.add_known(kind, id, body)+ }++ pub fn finish(&mut self, description: &str) -> Result<Id> {+ ops::sort_view(&mut self.view);+ let view_body = encode_view(&self.view);+ let view_id = self.writer.add(TYPE_VIEW, view_body);+ let now = time::now_millis();+ let operation = Operation {+ parents: self.parents.clone(),+ view: view_id,+ start: TimeMs {+ millis: self.start_ms,+ tz_min: 0,+ },+ end: TimeMs {+ millis: now,+ tz_min: 0,+ },+ hostname: host_name(),+ username: user_name(),+ description: description.as_bytes().to_vec(),+ tags: vec![(b"command".to_vec(), description.as_bytes().to_vec())],+ };+ let operation_body = encode_operation(&operation);+ let operation_id = self.writer.add(TYPE_OPERATION, operation_body);+ self.writer.finish(&self.root)?;+ ops::write_head(&self.root, operation_id)?;+ for parent in &self.parents {+ ops::delete_head(&self.root, *parent)?;+ }+ Ok(operation_id)+ }+}++fn load_view(store: &mut Store, head: Id) -> Result<View> {+ let operation = store+ .operation(head)?+ .ok_or_else(|| Error::new("cannot load operation state"))?;+ store+ .view(operation.view)?+ .ok_or_else(|| Error::new("cannot load view state"))+}++fn merge_view_into(target: &mut View, source: &View) {+ for head in &source.heads {+ ops::add_unique_head(target, *head);+ }+ for bookmark in &source.bookmarks {+ match ops::find_bookmark(target, &bookmark.name) {+ None => target.bookmarks.push(bookmark.clone()),+ Some(index) => {+ let existing = &mut target.bookmarks[index];+ let left = existing.targets.adds.first().copied().flatten();+ let right = bookmark.targets.adds.first().copied().flatten();+ if left != right || existing.targets.adds.len() != bookmark.targets.adds.len() {+ existing.targets.adds = vec![left, right];+ existing.targets.removes = vec![None];+ }+ }+ }+ }+ for tag in &source.tags {+ if !target.tags.iter().any(|value| value.name == tag.name) {+ target.tags.push(tag.clone());+ }+ }+ for workspace in &source.working_copies {+ if !target+ .working_copies+ .iter()+ .any(|value| value.workspace == workspace.workspace)+ {+ target.working_copies.push(workspace.clone());+ }+ }+}++fn host_name() -> Vec<u8> {+ std::env::var("HOSTNAME")+ .ok()+ .filter(|value| !value.is_empty())+ .unwrap_or_else(|| "localhost".to_string())+ .into_bytes()+}++fn user_name() -> Vec<u8> {+ std::env::var("USER")+ .ok()+ .filter(|value| !value.is_empty())+ .unwrap_or_else(|| "unknown".to_string())+ .into_bytes()+}--- /dev/null+++ b/veins-rust/src/store/writer.rs@@ -0,0 +1,55 @@+use std::collections::HashSet;+use std::fs;+use std::path::Path;++use crate::error::Result;+use crate::object::id::Id;+use crate::object::RawObject;+use crate::store::layout;+use crate::store::pack;++#[derive(Default)]+pub struct Writer {+ objects: Vec<RawObject>,+ seen: HashSet<Id>,+}++impl Writer {+ pub fn add(&mut self, kind: u8, body: Vec<u8>) -> Id {+ let object = RawObject::new(kind, body);+ let id = object.id;+ if self.seen.insert(id) {+ self.objects.push(object);+ }+ id+ }++ pub fn add_known(&mut self, kind: u8, id: Id, body: Vec<u8>) -> Id {+ if self.seen.insert(id) {+ self.objects.push(RawObject::known(kind, id, body));+ }+ id+ }++ pub fn find_cached(&self, id: Id) -> Option<&[u8]> {+ self.objects+ .iter()+ .find(|object| object.id == id)+ .map(|object| object.body.as_slice())+ }++ pub fn finish(&self, root: &Path) -> Result<()> {+ let output = pack::encode(&self.objects);+ if output.count == 0 {+ return Ok(());+ }+ let pack_path = layout::packs_dir(root).join(format!("{}.vpack", output.name));+ let index_path = layout::packs_dir(root).join(format!("{}.vidx", output.name));+ layout::write_atomic(&pack_path, &output.pack)?;+ if let Err(error) = layout::write_atomic(&index_path, &output.index) {+ let _ = fs::remove_file(&pack_path);+ return Err(error);+ }+ Ok(())+ }+}--- /dev/null+++ b/veins-rust/src/time.rs@@ -0,0 +1,47 @@+use std::time::{SystemTime, UNIX_EPOCH};++pub fn now_millis() -> i64 {+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|duration| duration.as_millis() as i64)+ .unwrap_or(0)+}++pub fn now_seconds() -> i64 {+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|duration| duration.as_secs() as i64)+ .unwrap_or(0)+}++fn floor_div(value: i64, divisor: i64) -> i64 {+ let quotient = value / divisor;+ let remainder = value % divisor;+ if remainder != 0 && (remainder < 0) != (divisor < 0) {+ quotient - 1+ } else {+ quotient+ }+}++pub fn format_utc(seconds: i64) -> String {+ let days = floor_div(seconds, 86_400);+ let remainder = seconds - days * 86_400;+ let hour = remainder / 3_600;+ let minute = (remainder % 3_600) / 60;+ let second = remainder % 60;++ let z = days + 719_468;+ let era = floor_div(z, 146_097);+ let doe = z - era * 146_097;+ let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;+ let y0 = yoe + era * 400;+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);+ let mp = (5 * doy + 2) / 153;+ let day = doy - (153 * mp + 2) / 5 + 1;+ let month0 = mp + 3;+ let month = if mp >= 10 { mp - 9 } else { month0 };+ let year = if month <= 2 { y0 + 1 } else { y0 };++ format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}")+}--- /dev/null+++ b/veins-rust/src/worktree/checkout.rs@@ -0,0 +1,216 @@+use std::fs;+use std::os::unix::fs::PermissionsExt;+use std::path::{Path, PathBuf};++use rayon::prelude::*;++use crate::error::{Error, Result};+use crate::object::id::Id;+use crate::object::path::valid_checkout_path;+use crate::object::tree::{self, FlatEntry};+use crate::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::store::Txn;+use crate::worktree::snapshot;++pub fn run(root: &Path, revision: &str) -> Result<()> {+ snapshot::run(root)?;++ let mut store = Store::open(root)?;+ let view = ops::current_view(root, &mut store)?+ .ok_or_else(|| Error::new("no operation state"))?;+ let target = graph::resolve_revision(&mut store, &view, revision)?+ .ok_or_else(|| Error::new(format!("unknown revision: {revision}")))?;+ let target_commit = graph::load_commit(&mut store, target)?+ .ok_or_else(|| Error::new("cannot read commit"))?;++ let working_copy = ops::working_copy_id(&view);+ let old_root = match working_copy {+ Some(id) => graph::load_commit(&mut store, id)?.map(|commit| commit.root_tree),+ None => None,+ };++ if old_root != Some(target_commit.root_tree) {+ materialize(+ root,+ &mut store,+ old_root,+ target_commit.root_tree,+ )?;+ }++ if working_copy != Some(target) {+ let mut txn = Txn::begin(root, &mut store)?;+ if let Some(old_id) = working_copy {+ ops::remove_head(txn.view_mut(), old_id);+ }+ ops::set_workspace(txn.view_mut(), target);+ ops::rebuild_heads(txn.view_mut());+ txn.finish("checkout")?;+ }+ Ok(())+}++fn materialize(+ root: &Path,+ store: &mut Store,+ old_root: Option<Id>,+ new_root: Id,+) -> Result<()> {+ let old_entries = match old_root {+ Some(id) => tree::flatten(store, id)?,+ None => Vec::new(),+ };+ let new_entries = tree::flatten(store, new_root)?;++ let mut directories: Vec<Vec<u8>> = Vec::new();+ let mut files = Vec::new();+ for entry in &new_entries {+ if !valid_checkout_path(&entry.path) {+ return Err(Error::new(format!(+ "invalid path in checkout tree: {}",+ String::from_utf8_lossy(&entry.path)+ )));+ }+ let mut cursor = 0;+ while let Some(position) = entry.path[cursor..].iter().position(|byte| *byte == b'/') {+ let end = cursor + position;+ directories.push(entry.path[..end].to_vec());+ cursor = end + 1;+ }+ files.push(entry.clone());+ }++ delete_stale(root, &old_entries, &new_entries)?;++ for directory in &directories {+ ensure_safe_dirs(root, directory)?;+ }+ ensure_safe_dirs(root, b"")?;++ store.preload()?;+ files.par_iter().try_for_each(|entry| write_entry(store, root, entry))?;++ clear_stat_cache(root)?;+ println!("info: checked out {} files", files.len());+ Ok(())+}++fn write_entry(store: &Store, root: &Path, entry: &FlatEntry) -> Result<()> {+ let data = graph::read_blob_loaded(store, entry.target)?+ .ok_or_else(|| Error::new("missing blob"))?;+ write_content(root, &entry.path, &data, entry.kind == tree::KIND_EXECUTABLE)+}++fn write_content(root: &Path, relative: &[u8], data: &[u8], executable: bool) -> Result<()> {+ if !valid_checkout_path(relative) {+ return Err(Error::new("invalid checkout path"));+ }+ ensure_safe_dirs(root, relative)?;+ let final_path = root.join(path_buf(relative));+ if let Ok(metadata) = fs::symlink_metadata(&final_path) {+ if metadata.is_dir() && !metadata.file_type().is_symlink() {+ return Err(Error::new("checkout path collides with a directory"));+ }+ if metadata.file_type().is_symlink() {+ fs::remove_file(&final_path)?;+ }+ }+ fs::write(&final_path, data)?;+ let mode = if executable { 0o755 } else { 0o644 };+ fs::set_permissions(&final_path, fs::Permissions::from_mode(mode))?;+ Ok(())+}++fn ensure_safe_dirs(root: &Path, relative: &[u8]) -> Result<()> {+ if relative.is_empty() {+ return Ok(());+ }+ let mut current = root.to_path_buf();+ let mut start = 0;+ for index in 0..=relative.len() {+ let at_end = index == relative.len();+ if !at_end && relative[index] != b'/' {+ continue;+ }+ if at_end {+ break;+ }+ let component = &relative[start..index];+ if component.is_empty() {+ return Err(Error::new("empty path component"));+ }+ current = current.join(path_buf(component));+ match fs::symlink_metadata(¤t) {+ Ok(metadata) => {+ if metadata.file_type().is_symlink() || !metadata.is_dir() {+ return Err(Error::new("unsafe path component"));+ }+ }+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ fs::create_dir(¤t)?;+ }+ Err(error) => return Err(error.into()),+ }+ start = index + 1;+ }+ Ok(())+}++fn delete_stale(root: &Path, old_entries: &[FlatEntry], new_entries: &[FlatEntry]) -> Result<()> {+ for entry in old_entries {+ if entry.kind == tree::KIND_SUBMODULE {+ continue;+ }+ if tree::find_flat(new_entries, &entry.path).is_some() {+ continue;+ }+ let path = root.join(path_buf(&entry.path));+ if fs::symlink_metadata(&path).is_ok() {+ remove_any(&path)?;+ prune_empty_parents(root, &entry.path)?;+ }+ }+ Ok(())+}++fn remove_any(path: &Path) -> Result<()> {+ let metadata = fs::symlink_metadata(path)?;+ if metadata.is_dir() && !metadata.file_type().is_symlink() {+ fs::remove_dir_all(path)?;+ } else {+ fs::remove_file(path)?;+ }+ Ok(())+}++fn prune_empty_parents(root: &Path, relative: &[u8]) -> Result<()> {+ let mut end = relative.len();+ while end > 0 {+ let Some(position) = relative[..end].iter().rposition(|byte| *byte == b'/') else {+ break;+ };+ let parent = &relative[..position];+ let path = root.join(path_buf(parent));+ if fs::remove_dir(&path).is_err() {+ break;+ }+ end = position;+ }+ Ok(())+}++fn clear_stat_cache(root: &Path) -> Result<()> {+ let path = layout::working_copy_dir(root).join("stat-cache");+ match fs::remove_file(path) {+ Ok(()) => Ok(()),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),+ Err(error) => Err(error.into()),+ }+}++fn path_buf(bytes: &[u8]) -> PathBuf {+ PathBuf::from(layout::os_string(bytes))+}--- /dev/null+++ b/veins-rust/src/worktree/mod.rs@@ -0,0 +1,3 @@+pub mod checkout;+pub mod snapshot;+pub mod stat_cache;--- /dev/null+++ b/veins-rust/src/worktree/snapshot.rs@@ -0,0 +1,350 @@+use std::fs;+use std::os::unix::ffi::OsStrExt;+use std::os::unix::fs::MetadataExt;+use std::path::{Path, PathBuf};++use crate::error::{Error, Result};+use crate::identity;+use crate::object::blob;+use crate::object::commit::{self, Commit, Rename};+use crate::object::id::Id;+use crate::object::path;+use crate::object::tree::{self, FlatEntry, TreeEntry};+use crate::object::{TYPE_COMMIT, TYPE_TREE};+use crate::store::graph;+use crate::store::ops;+use crate::store::reader::Store;+use crate::store::writer::Writer;+use crate::store::Txn;+use crate::time;+use crate::worktree::stat_cache::{self, Cache, CacheEntry};++pub fn run(root: &Path) -> Result<bool> {+ let mut store = Store::open(root)?;+ run_with(root, &mut store)+}++pub fn run_with(root: &Path, store: &mut Store) -> Result<bool> {+ let mut txn = Txn::begin(root, store)?;+ let working_copy = ops::working_copy_id(txn.view());+ let old_commit = match working_copy {+ Some(id) => Some(+ graph::load_commit(store, id)?+ .ok_or_else(|| Error::new("missing working-copy commit"))?,+ ),+ None => None,+ };+ let old_tree = old_commit.as_ref().map(|commit| commit.root_tree);++ let cache = stat_cache::load(root);+ let now_ms = time::now_millis();+ let mut new_cache = Vec::new();+ let built = build_directory(+ &mut txn,+ store,+ root,+ b"",+ old_tree,+ &cache,+ &mut new_cache,+ now_ms,+ 0,+ )?;+ let new_root = match built {+ Some(id) => id,+ None => txn.add_object(TYPE_TREE, tree::encode(&[])?),+ };++ if old_tree == Some(new_root) {+ stat_cache::save(root, &mut new_cache, now_ms)?;+ return Ok(false);+ }++ let committer = identity::signature(root);+ let (parents, change_id, message, author, extra) = match &old_commit {+ Some(commit) => (+ commit.parents.clone(),+ commit.change_id,+ commit.message.clone(),+ commit.author.clone(),+ commit.extra.clone(),+ ),+ None => (+ Vec::new(),+ identity::random_change_id(),+ Vec::new(),+ committer.clone(),+ Vec::new(),+ ),+ };++ let renames = match old_tree {+ Some(old) => {+ let mut renames = old_commit+ .as_ref()+ .map(|commit| commit.renames.clone())+ .unwrap_or_default();+ let mut detected = detect_exact_renames(store, txn.writer(), old, new_root)?;+ renames.append(&mut detected);+ renames.sort_by(|left, right| {+ left.parent_index+ .cmp(&right.parent_index)+ .then_with(|| left.to_path.cmp(&right.to_path))+ });+ renames+ }+ None => Vec::new(),+ };++ let new_commit = Commit {+ version: 1,+ parents,+ root_tree: new_root,+ change_id,+ author,+ committer,+ message,+ renames_state: commit::RENAMES_RECORDED,+ renames,+ extra,+ };+ let encoded = commit::encode(&new_commit);+ let commit_id = txn.add_object(TYPE_COMMIT, encoded);++ if let Some(old_id) = working_copy {+ ops::remove_head(txn.view_mut(), old_id);+ ops::move_bookmarks(txn.view_mut(), old_id, commit_id);+ }+ ops::set_workspace(txn.view_mut(), commit_id);+ ops::rebuild_heads(txn.view_mut());+ txn.finish("snapshot")?;+ store.refresh()?;+ mark_native(root, commit_id)?;+ stat_cache::save(root, &mut new_cache, now_ms)?;+ Ok(true)+}++fn add_blob(txn: &mut Txn, data: &[u8]) -> Id {+ let build = blob::build(data);+ for object in build.objects {+ txn.add_known(object.kind, object.id, object.body);+ }+ build.root+}++#[allow(clippy::too_many_arguments)]+fn build_directory(+ txn: &mut Txn,+ store: &mut Store,+ root: &Path,+ base: &[u8],+ old_tree_id: Option<Id>,+ cache: &Cache,+ new_cache: &mut Vec<CacheEntry>,+ now_ms: i64,+ depth: usize,+) -> Result<Option<Id>> {+ if depth > 4096 {+ return Err(Error::new("directory nesting too deep"));+ }+ let old_tree = match old_tree_id {+ Some(id) => {+ let body = store+ .body(id, TYPE_TREE)?+ .ok_or_else(|| Error::new("missing tree"))?;+ Some(tree::decode(&body)?)+ }+ None => None,+ };+ let directory = if base.is_empty() {+ root.to_path_buf()+ } else {+ root.join(path_to_os_string(base))+ };+ let names = crate::store::layout::read_directory(&directory)?;+ let mut entries = Vec::new();+ for name in names {+ if name == b".veins" || name == b".git" {+ continue;+ }+ let relative = path::join(base, &name);+ let file_path = directory.join(path_to_os_string(&name));+ let Ok(metadata) = fs::symlink_metadata(&file_path) else {+ continue;+ };+ let old_index = old_tree+ .as_ref()+ .and_then(|tree| tree::find_entry(tree, &name));+ if metadata.is_dir() {+ let child_old = old_index.and_then(|index| {+ let entry = &old_tree.as_ref().unwrap().entries[index];+ (entry.kind == tree::KIND_SUBTREE).then_some(entry.target)+ });+ if let Some(child) = build_directory(+ txn,+ store,+ root,+ &relative,+ child_old,+ cache,+ new_cache,+ now_ms,+ depth + 1,+ )? {+ entries.push(TreeEntry {+ name,+ kind: tree::KIND_SUBTREE,+ target: child,+ });+ }+ } else if metadata.file_type().is_symlink() {+ let target = fs::read_link(&file_path)?;+ let blob_id = add_blob(txn, target.as_os_str().as_bytes());+ new_cache.push(CacheEntry {+ path: relative,+ size: metadata.size(),+ mtime_ns: stat_cache::mtime_ns(&metadata),+ inode: metadata.ino(),+ kind: stat_cache::file_kind(&metadata),+ executable: false,+ target: blob_id,+ });+ entries.push(TreeEntry {+ name,+ kind: tree::KIND_SYMLINK,+ target: blob_id,+ });+ } else if metadata.is_file() {+ let executable = stat_cache::executable(&metadata);+ let target = match stat_cache::lookup(cache, &relative) {+ Some(entry)+ if stat_cache::matches(entry, &metadata, executable, now_ms, cache.written_ms) =>+ {+ entry.target+ }+ _ => {+ let data = fs::read(&file_path)?;+ add_blob(txn, &data)+ }+ };+ new_cache.push(CacheEntry {+ path: relative,+ size: metadata.size(),+ mtime_ns: stat_cache::mtime_ns(&metadata),+ inode: metadata.ino(),+ kind: stat_cache::file_kind(&metadata),+ executable,+ target,+ });+ entries.push(TreeEntry {+ name,+ kind: if executable {+ tree::KIND_EXECUTABLE+ } else {+ tree::KIND_FILE+ },+ target,+ });+ }+ }+ if entries.is_empty() {+ return Ok(None);+ }+ entries.sort_by(|left, right| left.name.cmp(&right.name));+ Ok(Some(txn.add_object(TYPE_TREE, tree::encode(&entries)?)))+}++fn path_to_os_string(bytes: &[u8]) -> PathBuf {+ PathBuf::from(crate::store::layout::os_string(bytes))+}++fn flatten_any(+ store: &mut Store,+ writer: &Writer,+ tree_id: Id,+ prefix: &mut Vec<u8>,+ output: &mut Vec<FlatEntry>,+ depth: usize,+) -> Result<()> {+ if depth > 4096 {+ return Err(Error::new("tree nesting too deep"));+ }+ let body = match writer.find_cached(tree_id) {+ Some(body) => body.to_vec(),+ None => store+ .body(tree_id, TYPE_TREE)?+ .ok_or_else(|| Error::new("missing tree"))?,+ };+ let tree = tree::decode(&body)?;+ for entry in tree.entries {+ let old_length = prefix.len();+ if !prefix.is_empty() {+ prefix.push(b'/');+ }+ prefix.extend_from_slice(&entry.name);+ if entry.kind == tree::KIND_SUBTREE {+ flatten_any(store, writer, entry.target, prefix, output, depth + 1)?;+ } else {+ output.push(FlatEntry {+ path: prefix.clone(),+ kind: entry.kind,+ target: entry.target,+ });+ }+ prefix.truncate(old_length);+ }+ Ok(())+}++fn detect_exact_renames(+ store: &mut Store,+ writer: &Writer,+ old_tree: Id,+ new_tree: Id,+) -> Result<Vec<Rename>> {+ let mut old_entries = Vec::new();+ flatten_any(store, writer, old_tree, &mut Vec::new(), &mut old_entries, 0)?;+ let mut new_entries = Vec::new();+ flatten_any(store, writer, new_tree, &mut Vec::new(), &mut new_entries, 0)?;+ old_entries.sort_by(|left, right| left.path.cmp(&right.path));+ new_entries.sort_by(|left, right| left.path.cmp(&right.path));++ let deleted: Vec<&FlatEntry> = old_entries+ .iter()+ .filter(|entry| tree::find_flat(&new_entries, &entry.path).is_none())+ .collect();+ let added: Vec<&FlatEntry> = new_entries+ .iter()+ .filter(|entry| tree::find_flat(&old_entries, &entry.path).is_none())+ .collect();+ let mut used_old = vec![false; deleted.len()];+ let mut used_new = vec![false; added.len()];+ let mut renames = Vec::new();+ for (old_index, old) in deleted.iter().enumerate() {+ if used_old[old_index] {+ continue;+ }+ for (new_index, new) in added.iter().enumerate() {+ if used_new[new_index] {+ continue;+ }+ if old.target == new.target {+ renames.push(Rename {+ parent_index: 0,+ kind: 0,+ from_path: old.path.clone(),+ to_path: new.path.clone(),+ });+ used_old[old_index] = true;+ used_new[new_index] = true;+ break;+ }+ }+ }+ Ok(renames)+}++fn mark_native(root: &Path, id: Id) -> Result<()> {+ let path = crate::store::layout::git_map_dir(root).join("native");+ crate::store::layout::append_file(&path, format!("{}\n", id.to_hex()).as_bytes())+}--- /dev/null+++ b/veins-rust/src/worktree/stat_cache.rs@@ -0,0 +1,158 @@+use std::fs;+use std::os::unix::fs::MetadataExt;+use std::path::Path;++use crate::encoding::{Reader, Writer};+use crate::error::Result;+use crate::object::id::Id;+use crate::store::layout;++#[derive(Clone)]+pub struct CacheEntry {+ pub path: Vec<u8>,+ pub size: u64,+ pub mtime_ns: u64,+ pub inode: u64,+ pub kind: u8,+ pub executable: bool,+ pub target: Id,+}++pub struct Cache {+ pub entries: Vec<CacheEntry>,+ pub written_ms: i64,+}++pub fn load(root: &Path) -> Cache {+ let mut cache = Cache {+ entries: Vec::new(),+ written_ms: 0,+ };+ let Ok(data) = fs::read(layout::working_copy_dir(root).join("stat-cache")) else {+ return cache;+ };+ if data.len() < 13 || &data[..4] != b"VST1" {+ return cache;+ }+ let mut reader = Reader::new(&data[4..]);+ let Ok(version) = reader.u8() else {+ return cache;+ };+ if version != 49 {+ return cache;+ }+ let Ok(written) = reader.u64le() else {+ return cache;+ };+ cache.written_ms = written as i64;+ let Ok(count) = reader.varint() else {+ return cache;+ };+ for _ in 0..count {+ let Ok(path) = reader.bytes(65_536) else {+ break;+ };+ let path = path.to_vec();+ let (Ok(size), Ok(mtime), Ok(inode), Ok(kind), Ok(executable), Ok(target)) = (+ reader.u64le(),+ reader.u64le(),+ reader.u64le(),+ reader.u8(),+ reader.u8(),+ reader.id(),+ ) else {+ break;+ };+ cache.entries.push(CacheEntry {+ path,+ size,+ mtime_ns: mtime,+ inode,+ kind,+ executable: executable != 0,+ target,+ });+ }+ cache.entries.sort_by(|left, right| left.path.cmp(&right.path));+ cache+}++pub fn save(root: &Path, entries: &mut Vec<CacheEntry>, written_ms: i64) -> Result<()> {+ entries.sort_by(|left, right| left.path.cmp(&right.path));+ let mut writer = Writer::with_capacity(4096);+ writer.raw(b"VST1");+ writer.u8(49);+ writer.u64le(written_ms as u64);+ writer.varint(entries.len() as u64);+ for entry in entries {+ writer.bytes(&entry.path);+ writer.u64le(entry.size);+ writer.u64le(entry.mtime_ns);+ writer.u64le(entry.inode);+ writer.u8(entry.kind);+ writer.u8(u8::from(entry.executable));+ writer.id(entry.target);+ }+ let path = layout::working_copy_dir(root).join("stat-cache");+ layout::write_atomic(&path, &writer.into_vec())+}++pub fn lookup<'a>(cache: &'a Cache, path: &[u8]) -> Option<&'a CacheEntry> {+ cache+ .entries+ .binary_search_by(|entry| entry.path.as_slice().cmp(path))+ .ok()+ .map(|index| &cache.entries[index])+}++pub fn matches(+ entry: &CacheEntry,+ metadata: &fs::Metadata,+ executable: bool,+ now_ms: i64,+ written_ms: i64,+) -> bool {+ let kind = file_kind(metadata);+ let mtime_ns = mtime_ns(metadata);+ if entry.size != metadata.size()+ || entry.mtime_ns != mtime_ns+ || entry.inode != metadata.ino()+ || entry.executable != executable+ || entry.kind != kind+ {+ return false;+ }+ let now_ns = now_ms.saturating_mul(1_000_000);+ let written_ns = written_ms.saturating_mul(1_000_000);+ const WINDOW: i64 = 2_000_000_000;+ if mtime_ns as i64 >= written_ns - WINDOW {+ return false;+ }+ if now_ns - (mtime_ns as i64) < WINDOW {+ return false;+ }+ true+}++pub fn mtime_ns(metadata: &fs::Metadata) -> u64 {+ let seconds = metadata.mtime();+ let nanoseconds = metadata.mtime_nsec();+ (seconds as u64)+ .wrapping_mul(1_000_000_000)+ .wrapping_add(nanoseconds as u64)+}++pub fn file_kind(metadata: &fs::Metadata) -> u8 {+ let file_type = metadata.file_type();+ if file_type.is_symlink() {+ 3+ } else if file_type.is_dir() {+ 2+ } else {+ 1+ }+}++pub fn executable(metadata: &fs::Metadata) -> bool {+ metadata.mode() & 0o100 != 0+}--- /dev/null+++ b/veins-rust/tests/end_to_end.rs@@ -0,0 +1,85 @@+use std::fs;+use std::path::{Path, PathBuf};+use std::process::{Command, Output};+use std::time::{SystemTime, UNIX_EPOCH};++struct TempDirectory(PathBuf);++impl TempDirectory {+ fn new() -> Self {+ let stamp = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_nanos();+ let path = std::env::temp_dir().join(format!("veins-rust-test-{}-{stamp}", std::process::id()));+ fs::create_dir_all(&path).unwrap();+ Self(path)+ }++ fn path(&self) -> &Path {+ &self.0+ }+}++impl Drop for TempDirectory {+ fn drop(&mut self) {+ let _ = fs::remove_dir_all(&self.0);+ }+}++fn vn(directory: &Path, arguments: &[&str]) -> Output {+ Command::new(env!("CARGO_BIN_EXE_vn"))+ .args(arguments)+ .current_dir(directory)+ .env("NO_COLOR", "1")+ .output()+ .unwrap()+}++fn ok(directory: &Path, arguments: &[&str]) -> String {+ let output = vn(directory, arguments);+ assert!(+ output.status.success(),+ "command {:?} failed: {}",+ arguments,+ String::from_utf8_lossy(&output.stderr)+ );+ String::from_utf8(output.stdout).unwrap()+}++#[test]+fn commit_log_checkout_and_bookmarks() {+ let temporary = TempDirectory::new();+ let root = temporary.path();+ ok(root, &["init", "."]);+ fs::write(+ root.join(".veins/config"),+ "user.name = Bench\nuser.email = bench@example.com\n",+ )+ .unwrap();+ fs::write(root.join("a.txt"), "hello\n").unwrap();+ fs::create_dir(root.join("src")).unwrap();+ fs::write(root.join("src/b.txt"), "world\n").unwrap();+ ok(root, &["go", "-m", "first"]);++ fs::write(root.join("a.txt"), "hello again\n").unwrap();+ ok(root, &["go", "-m", "second"]);++ let log = ok(root, &["log", "-no-col-titles"]);+ let first = log+ .lines()+ .find(|line| line.contains("first"))+ .and_then(|line| {+ line.split_whitespace()+ .find(|token| token.len() == 12 && token.bytes().all(|byte| byte.is_ascii_hexdigit()))+ })+ .expect("first commit id");+ ok(root, &["co", first]);+ assert_eq!(fs::read_to_string(root.join("a.txt")).unwrap(), "hello\n");++ ok(root, &["status"]);+ ok(root, &["bmk", "set", "main"]);+ let bookmarks = ok(root, &["bmk", "ls"]);+ assert!(bookmarks.contains("main"));+ ok(root, &["self-test"]);+}--- /dev/null+++ b/veins-rust/tests/format_vectors.rs@@ -0,0 +1,150 @@+use veins_rust::object::blob;+use veins_rust::object::chunker::{gear_table, next_chunk};+use veins_rust::object::commit::{self, Commit, Sig};+use veins_rust::object::id::{hash_bytes, object_id, Id};+use veins_rust::object::tree;+use veins_rust::object::view::{self, Bookmark, Operation, TargetSet, TimeMs, View, WorkspaceRef};+use veins_rust::object::{RawObject, TYPE_BLOB, TYPE_CHUNK, TYPE_TREE};+use veins_rust::store::pack;++fn hex(bytes: &[u8]) -> String {+ bytes.iter().map(|byte| format!("{byte:02x}")).collect()+}++#[test]+fn published_vectors_match() {+ assert_eq!(+ hex(&hash_bytes(b"")),+ "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262"+ );+ assert_eq!(gear_table()[0], 0xf8447b379cdadcd5);+ assert_eq!(gear_table()[1], 0xbe63d125aec8ca6d);++ let mut input = vec![0u8; 300_000];+ for (index, byte) in input.iter_mut().enumerate() {+ *byte = ((index * 31 + 34) % 251) as u8;+ }+ let first = next_chunk(&input);+ assert_eq!(first, 262_144);+ assert_eq!(next_chunk(&input[first..]), 37_856);+ assert_eq!(+ object_id(TYPE_CHUNK, &input[..first]).to_hex(),+ "c83c67617ae4445631508cc4edba83ba58d9e996cea40c980ec69a8b6da86458"+ );+ assert_eq!(+ object_id(TYPE_CHUNK, &input[first..]).to_hex(),+ "0c91665d423fd704baae9454d24697460c4898fbf16cc6ad498d3f750d073a4b"+ );+ assert_eq!(+ blob::build(&input).root.to_hex(),+ "937fe1a8d674aa28cb9fa074a76ea84cdc1d6c61e209f47bbdebbe4361b698cf"+ );++ let empty_tree = vec![0u8];+ let empty_tree_id = object_id(TYPE_TREE, &empty_tree);+ assert_eq!(+ empty_tree_id.to_hex(),+ "8be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb"+ );+ assert!(tree::decode(&empty_tree).unwrap().entries.is_empty());++ assert_eq!(+ object_id(TYPE_BLOB, &blob::encode_inline(b"hello")).to_hex(),+ "f04a7f7324bbb7279471b5c656c893ee51b62ed9f9bad4c8cb8a289101f68240"+ );+}++#[test]+fn objects_round_trip_and_pack_is_canonical() {+ let change_id = [+ 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,+ 0x19, 0x1a,+ ];+ let signature = Sig {+ name: b"Alice".to_vec(),+ email: b"alice@example.com".to_vec(),+ seconds: 1_700_000_000,+ tz_min: 0,+ };+ let empty_tree_id = Id::from_hex(+ "8be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb",+ )+ .unwrap();+ let commit = Commit {+ version: 1,+ parents: Vec::new(),+ root_tree: empty_tree_id,+ change_id,+ author: signature.clone(),+ committer: signature,+ message: b"initial commit".to_vec(),+ renames_state: commit::RENAMES_RECORDED,+ renames: Vec::new(),+ extra: Vec::new(),+ };+ let commit_body = commit::encode(&commit);+ let commit_id = object_id(veins_rust::object::TYPE_COMMIT, &commit_body);+ assert_eq!(+ commit_id.to_hex(),+ "7f648b3621402df01985d121888c89c37107274fb8bb54661f12deca6cc72299"+ );+ assert_eq!(commit::decode(&commit_body).unwrap().message, b"initial commit");++ let view = View {+ heads: vec![commit_id],+ bookmarks: vec![Bookmark {+ name: b"main".to_vec(),+ targets: TargetSet {+ adds: vec![Some(commit_id)],+ removes: Vec::new(),+ },+ }],+ tags: Vec::new(),+ remote_refs: Vec::new(),+ working_copies: vec![WorkspaceRef {+ workspace: b"default".to_vec(),+ target: commit_id,+ }],+ };+ let view_body = view::encode_view(&view);+ let view_id = object_id(veins_rust::object::TYPE_VIEW, &view_body);+ assert_eq!(+ view_id.to_hex(),+ "a2e19569bb3b5c28775bc8503c45c4edce6d51f55303e39bc02eec529324cd11"+ );+ assert_eq!(view::decode_view(&view_body).unwrap().heads, vec![commit_id]);++ let operation = Operation {+ parents: Vec::new(),+ view: view_id,+ start: TimeMs {+ millis: 1_700_000_000_000,+ tz_min: 0,+ },+ end: TimeMs {+ millis: 1_700_000_000_000,+ tz_min: 0,+ },+ hostname: b"host".to_vec(),+ username: b"alice".to_vec(),+ description: b"selftest operation".to_vec(),+ tags: Vec::new(),+ };+ let operation_body = view::encode_operation(&operation);+ assert_eq!(+ object_id(veins_rust::object::TYPE_OPERATION, &operation_body).to_hex(),+ "0a5494529353fb5886870a128139e07d95f40afcd831afc423617808f31dc426"+ );++ let output = pack::encode(&[RawObject::known(TYPE_TREE, empty_tree_id, vec![0])]);+ assert_eq!(+ hex(&output.pack),+ "56504b310100000001000000000000008be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb030001010072c385a83448a5e16853735a79a212f0377d0e40be777d121271758525dbc911"+ );+ assert_eq!(output.index.len(), 1136);+ assert_eq!(+ hex(&hash_bytes(&output.index)),+ "d5dfb7b2ce4235f87856c12ff2e0b65d817dc29dfedad62ba34e71d74dca0cfc"+ );+ pack::decode(output.pack).unwrap();+}